Open History to see the last commit
1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { assert, it } from "@effect/vitest";
3import {
4 type ApplicationStoredEvent,
5 CommandId,
6 MessageId,
7 type ModelSelection,
8 ProjectId,
9 ProviderDriverKind,
10 ProviderInstanceId,
11 ThreadId,
12} from "@t3tools/contracts";
13import * as Effect from "effect/Effect";
14import * as Layer from "effect/Layer";
15import * as Queue from "effect/Queue";
16import * as Stream from "effect/Stream";
17import * as SqlClient from "effect/unstable/sql/SqlClient";
18
19import * as CheckpointStore from "../checkpointing/CheckpointStore.ts";
20import { ServerConfig } from "../config.ts";
21import { OrchestrationEngineService } from "../orchestration/Services/OrchestrationEngine.ts";
22import { ProjectionSnapshotQuery } from "../orchestration/Services/ProjectionSnapshotQuery.ts";
23import { OrchestrationLayerLive } from "../orchestration/runtimeLayer.ts";
24import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts";
25import { OrchestrationEventStore } from "../persistence/Services/OrchestrationEventStore.ts";
26import { ProjectEnrichmentService } from "../project/ProjectEnrichmentService.ts";
27import { ServerSettingsService } from "../serverSettings.ts";
28import { layer as mcpSessionRegistryTestLayer } from "../mcp/McpSessionRegistry.testkit.ts";
29import { ProviderInstanceRegistry } from "../provider/Services/ProviderInstanceRegistry.ts";
30import type { ProviderInstance } from "../provider/ProviderDriver.ts";
31import * as VcsDriverRegistry from "../vcs/VcsDriverRegistry.ts";
32import * as VcsProcess from "../vcs/VcsProcess.ts";
33import { OrchestratorV2 } from "./Orchestrator.ts";
34import { OrchestrationEffectWorkerV2 } from "./EffectWorker.ts";
35import type { ProviderAdapterV2Shape } from "./ProviderAdapter.ts";
36import { OrchestrationV2LayerLive } from "./runtimeLayer.ts";
37import { shellStreamItemFromSnapshot } from "./ShellStream.ts";
38import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts";
39import { ThreadManagementService } from "./ThreadManagementService.ts";
40
41const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
42 prefix: "t3-orchestration-v2-runtime-layer-",
43});
44
45const modelSelection = {
46 instanceId: ProviderInstanceId.make("codex"),
47 model: "gpt-5.4",
48} satisfies ModelSelection;
49
50const VcsDriverRegistryTestLayer = VcsDriverRegistry.layer.pipe(
51 Layer.provide(VcsProcess.layer),
52 Layer.provide(ServerConfigLayer),
53 Layer.provide(NodeServices.layer),
54);
55
56const CheckpointStoreTestLayer = CheckpointStore.layer.pipe(
57 Layer.provide(VcsDriverRegistryTestLayer),
58);
59
60const driver = ProviderDriverKind.make("codex");
61const orchestrationAdapter = {
62 instanceId: modelSelection.instanceId,
63 driver,
64 getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2),
65 planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" }),
66 openSession: () => Effect.die("sessions are not used by lifecycle tests"),
67} as ProviderAdapterV2Shape;
68const providerInstance = {
69 instanceId: modelSelection.instanceId,
70 driverKind: driver,
71 continuationIdentity: {
72 driverKind: driver,
73 continuationKey: "codex:test",
74 },
75 displayName: "Codex test",
76 enabled: true,
77 snapshot: {} as ProviderInstance["snapshot"],
78 orchestrationAdapter,
79 textGeneration: {} as ProviderInstance["textGeneration"],
80} satisfies ProviderInstance;
81
82const TestProviderInstanceRegistry = Layer.succeed(ProviderInstanceRegistry, {
83 getInstance: (instanceId) =>
84 Effect.succeed(instanceId === providerInstance.instanceId ? providerInstance : undefined),
85 listInstances: Effect.succeed([providerInstance]),
86 listUnavailable: Effect.succeed([]),
87 streamChanges: Stream.empty,
88 subscribeChanges: Effect.never,
89});
90
91const TestLayer = OrchestrationV2LayerLive.pipe(
92 Layer.provide(mcpSessionRegistryTestLayer),
93 Layer.provide(SqlitePersistenceMemory),
94 Layer.provide(CheckpointStoreTestLayer),
95 Layer.provide(ServerConfigLayer),
96 Layer.provide(ServerSettingsService.layerTest()),
97 Layer.provide(TestProviderInstanceRegistry),
98 Layer.provide(NodeServices.layer),
99);
100
101const SharedApplicationDataPlaneTestLayer = Layer.merge(
102 OrchestrationLayerLive,
103 OrchestrationV2LayerLive,
104).pipe(
105 Layer.provide(
106 Layer.succeed(ProjectEnrichmentService, {
107 peek: () => Effect.succeed({ repositoryIdentity: null, faviconPath: null }),
108 request: () => Effect.void,
109 getAvailable: () => Effect.succeed({ repositoryIdentity: null, faviconPath: null }),
110 invalidate: () => Effect.void,
111 subscribeChanges: Effect.never,
112 }),
113 ),
114 Layer.provide(mcpSessionRegistryTestLayer),
115 Layer.provideMerge(SqlitePersistenceMemory),
116 Layer.provide(CheckpointStoreTestLayer),
117 Layer.provide(ServerConfigLayer),
118 Layer.provide(ServerSettingsService.layerTest()),
119 Layer.provide(TestProviderInstanceRegistry),
120 Layer.provide(NodeServices.layer),
121);
122
123it.layer(TestLayer)("OrchestrationV2LayerLive", (it) => {
124 it.effect("creates and reads a thread through the production V2 composition", () =>
125 Effect.gen(function* () {
126 const orchestrator = yield* OrchestratorV2;
127 const threadId = ThreadId.make("runtime-layer-thread");
128 const projectId = ProjectId.make("runtime-layer-project");
129
130 const result = yield* orchestrator.dispatch({
131 type: "thread.create",
132 createdBy: "user",
133 creationSource: "web",
134 commandId: CommandId.make("runtime-layer-create"),
135 threadId,
136 projectId,
137 title: "Runtime layer thread",
138 modelSelection: modelSelection,
139 runtimeMode: "full-access",
140 interactionMode: "default",
141 branch: null,
142 worktreePath: null,
143 });
144
145 const projection = yield* orchestrator.getThreadProjection(threadId);
146
147 assert.equal(result.sequence, 1);
148 assert.equal(projection.thread.id, threadId);
149 assert.equal(projection.thread.projectId, projectId);
150 assert.equal(projection.thread.providerInstanceId, "codex");
151 assert.deepEqual(projection.runs, []);
152 }),
153 );
154
155 it.effect("applies lifecycle commands idempotently and emits archive/removal shell deltas", () =>
156 Effect.gen(function* () {
157 const orchestrator = yield* OrchestratorV2;
158 const threadId = ThreadId.make("runtime-layer-lifecycle-thread");
159 const create = {
160 type: "thread.create" as const,
161 createdBy: "user" as const,
162 creationSource: "web" as const,
163 commandId: CommandId.make("runtime-layer-lifecycle-create"),
164 threadId,
165 projectId: ProjectId.make("runtime-layer-lifecycle-project"),
166 title: "Lifecycle thread",
167 modelSelection,
168 runtimeMode: "full-access" as const,
169 interactionMode: "default" as const,
170 branch: null,
171 worktreePath: null,
172 };
173
174 const firstCreate = yield* orchestrator.dispatch(create);
175 const retriedCreate = yield* orchestrator.dispatch(create);
176 assert.equal(retriedCreate.sequence, firstCreate.sequence);
177 assert.lengthOf(retriedCreate.storedEvents, 1);
178
179 yield* orchestrator.dispatch({
180 type: "thread.metadata.update",
181 commandId: CommandId.make("runtime-layer-lifecycle-metadata"),
182 threadId,
183 title: "Renamed lifecycle thread",
184 branch: "feature/v2",
185 worktreePath: "/tmp/t3-v2-worktree",
186 });
187 yield* orchestrator.dispatch({
188 type: "thread.runtime-mode.set",
189 commandId: CommandId.make("runtime-layer-lifecycle-runtime"),
190 threadId,
191 runtimeMode: "approval-required",
192 });
193 yield* orchestrator.dispatch({
194 type: "thread.interaction-mode.set",
195 commandId: CommandId.make("runtime-layer-lifecycle-interaction"),
196 threadId,
197 interactionMode: "plan",
198 });
199 yield* orchestrator.dispatch({
200 type: "thread.model-selection.set",
201 commandId: CommandId.make("runtime-layer-lifecycle-model"),
202 threadId,
203 modelSelection: { ...modelSelection, model: "gpt-5.5" },
204 });
205
206 const archive = yield* orchestrator.dispatch({
207 type: "thread.archive",
208 commandId: CommandId.make("runtime-layer-lifecycle-archive"),
209 threadId,
210 });
211 const archivedShell = yield* orchestrator.getShellSnapshot();
212 assert.notInclude(
213 archivedShell.threads.map((thread) => thread.id),
214 threadId,
215 );
216 assert.include(
217 archivedShell.archivedThreads.map((thread) => thread.id),
218 threadId,
219 );
220 assert.deepEqual(
221 shellStreamItemFromSnapshot({
222 stored: archive.storedEvents[0]!,
223 snapshot: archivedShell,
224 }),
225 {
226 kind: "thread.updated",
227 sequence: archive.sequence,
228 location: "archive",
229 thread: archivedShell.archivedThreads[0]!,
230 },
231 );
232
233 const remove = yield* orchestrator.dispatch({
234 type: "thread.delete",
235 commandId: CommandId.make("runtime-layer-lifecycle-delete"),
236 threadId,
237 });
238 const deletedShell = yield* orchestrator.getShellSnapshot();
239 assert.notInclude(
240 deletedShell.threads.map((thread) => thread.id),
241 threadId,
242 );
243 assert.notInclude(
244 deletedShell.archivedThreads.map((thread) => thread.id),
245 threadId,
246 );
247 assert.deepEqual(
248 shellStreamItemFromSnapshot({ stored: remove.storedEvents[0]!, snapshot: deletedShell }),
249 {
250 kind: "thread.removed",
251 sequence: remove.sequence,
252 location: "archive",
253 threadId,
254 },
255 );
256
257 const projection = yield* orchestrator.getThreadProjection(threadId);
258 assert.equal(projection.thread.title, "Renamed lifecycle thread");
259 assert.equal(projection.thread.branch, "feature/v2");
260 assert.equal(projection.thread.worktreePath, "/tmp/t3-v2-worktree");
261 assert.equal(projection.thread.runtimeMode, "approval-required");
262 assert.equal(projection.thread.interactionMode, "plan");
263 assert.equal(projection.thread.modelSelection.model, "gpt-5.5");
264 assert.isNotNull(projection.thread.archivedAt);
265 assert.isNotNull(projection.thread.deletedAt);
266 }),
267 );
268
269 it.effect("persists rejected command receipts across retries", () =>
270 Effect.gen(function* () {
271 const orchestrator = yield* OrchestratorV2;
272 const command = {
273 type: "thread.archive" as const,
274 commandId: CommandId.make("runtime-layer-rejected-command"),
275 threadId: ThreadId.make("runtime-layer-missing-thread"),
276 };
277
278 const first = yield* orchestrator.dispatch(command).pipe(Effect.flip);
279 const retry = yield* orchestrator.dispatch(command).pipe(Effect.flip);
280
281 assert.equal(first._tag, "OrchestratorProjectionError");
282 assert.equal(retry._tag, "OrchestratorCommandPreviouslyRejectedError");
283 }),
284 );
285});
286
287it.layer(SharedApplicationDataPlaneTestLayer)("pending provider interruption", (it) => {
288 it.effect("interrupts a pending provider start without launching provider work", () =>
289 Effect.gen(function* () {
290 const applicationEngine = yield* OrchestrationEngineService;
291 const orchestrator = yield* OrchestratorV2;
292 const threadManagement = yield* ThreadManagementService;
293 const effectWorker = yield* OrchestrationEffectWorkerV2;
294 const projectId = ProjectId.make("runtime-layer-pending-interrupt-project");
295 const threadId = ThreadId.make("runtime-layer-pending-interrupt-thread");
296
297 yield* applicationEngine.dispatch({
298 type: "project.create",
299 commandId: CommandId.make("runtime-layer-pending-interrupt-project-create"),
300 projectId,
301 title: "Pending interrupt project",
302 workspaceRoot: "/tmp/runtime-layer-pending-interrupt-project",
303 defaultModelSelection: modelSelection,
304 scripts: [],
305 createdAt: "2026-06-22T00:00:00.000Z",
306 });
307 yield* orchestrator.dispatch({
308 type: "thread.create",
309 createdBy: "user",
310 creationSource: "web",
311 commandId: CommandId.make("runtime-layer-pending-interrupt-create"),
312 threadId,
313 projectId,
314 title: "Pending interrupt",
315 modelSelection,
316 runtimeMode: "full-access",
317 interactionMode: "default",
318 branch: null,
319 worktreePath: null,
320 });
321 yield* orchestrator.dispatch({
322 type: "message.dispatch",
323 createdBy: "user",
324 creationSource: "web",
325 commandId: CommandId.make("runtime-layer-pending-interrupt-message"),
326 threadId,
327 messageId: MessageId.make("runtime-layer-pending-interrupt-message"),
328 text: "Do not reach the provider.",
329 attachments: [],
330 modelSelection,
331 dispatchMode: { type: "start_immediately" },
332 });
333
334 const starting = yield* orchestrator.getThreadProjection(threadId);
335 const run = starting.runs[0];
336 assert.isDefined(run);
337 assert.equal(run.status, "starting");
338
339 const interrupt = yield* threadManagement.interruptThread({
340 projectId,
341 commandId: CommandId.make("runtime-layer-pending-interrupt-command"),
342 threadId,
343 runId: run.id,
344 reason: "Cancelled before provider start",
345 });
346 assert.equal(interrupt.type, "interrupt_requested");
347
348 const interrupted = yield* orchestrator.getThreadProjection(threadId);
349 assert.equal(interrupted.runs[0]?.status, "interrupted");
350 assert.equal(interrupted.attempts[0]?.status, "interrupted");
351 assert.equal(
352 interrupted.nodes.find((node) => node.kind === "root_turn")?.status,
353 "interrupted",
354 );
355 assert.deepEqual(
356 interrupted.turnItems.filter((item) => item.runId === run.id).map((item) => item.type),
357 ["user_message", "run_interrupt_request", "run_interrupt_result"],
358 );
359 assert.deepEqual(interrupted.providerTurns, []);
360 assert.isFalse(yield* effectWorker.runOnce);
361 }),
362 );
363});
364
365it.layer(SharedApplicationDataPlaneTestLayer)("shared application data plane", (it) => {
366 it.effect("orders retained project transactions and V2 thread transactions in one source", () =>
367 Effect.gen(function* () {
368 const applicationEngine = yield* OrchestrationEngineService;
369 const applicationEvents = yield* OrchestrationEventStore;
370 const orchestrator = yield* OrchestratorV2;
371 const projectionSnapshot = yield* ProjectionSnapshotQuery;
372 const sql = yield* SqlClient.SqlClient;
373 const projectId = ProjectId.make("runtime-layer-shared-project");
374 const threadId = ThreadId.make("runtime-layer-shared-thread");
375 const projectCommand = {
376 type: "project.create" as const,
377 commandId: CommandId.make("runtime-layer-shared-project-create"),
378 projectId,
379 title: "Shared application source",
380 workspaceRoot: "/tmp/runtime-layer-shared-project",
381 defaultModelSelection: modelSelection,
382 scripts: [],
383 createdAt: "2026-06-20T00:00:00.000Z",
384 };
385
386 const projectResult = yield* applicationEngine.dispatch(projectCommand);
387 const projectRetry = yield* applicationEngine.dispatch(projectCommand);
388 assert.equal(projectRetry.sequence, projectResult.sequence);
389
390 const delivered = yield* Queue.unbounded<ApplicationStoredEvent>();
391 yield* applicationEvents.streamApplicationEvents().pipe(
392 Stream.take(2),
393 Stream.runForEach((event) => Queue.offer(delivered, event)),
394 Effect.forkScoped,
395 );
396
397 const projectEvent = yield* Queue.take(delivered);
398 assert.equal(projectEvent.sequence, projectResult.sequence);
399
400 const threadResult = yield* orchestrator.dispatch({
401 type: "thread.create",
402 createdBy: "user",
403 creationSource: "web",
404 commandId: CommandId.make("runtime-layer-shared-thread-create"),
405 threadId,
406 projectId,
407 title: "Shared thread",
408 modelSelection,
409 runtimeMode: "full-access",
410 interactionMode: "default",
411 branch: null,
412 worktreePath: null,
413 });
414 const threadEvent = yield* Queue.take(delivered);
415
416 assert.equal(threadEvent.sequence, threadResult.sequence);
417 assert.isAbove(threadEvent.sequence, projectEvent.sequence);
418 assert.isTrue("aggregateKind" in projectEvent);
419 assert.isTrue("event" in threadEvent);
420 assert.equal((yield* projectionSnapshot.getProjectShellById(projectId))._tag, "Some");
421
422 const retainedReceipts = yield* sql<{
423 readonly aggregate_kind: string;
424 readonly aggregate_id: string;
425 }>`
426 SELECT aggregate_kind, aggregate_id
427 FROM orchestration_command_receipts
428 ORDER BY result_sequence ASC
429 `;
430 assert.deepEqual(retainedReceipts, [
431 { aggregate_kind: "project", aggregate_id: projectId },
432 { aggregate_kind: "thread", aggregate_id: threadId },
433 ]);
434
435 const retiredWrites = yield* sql<{ readonly count: number }>`
436 SELECT
437 (SELECT COUNT(*) FROM orchestration_v2_events) +
438 (SELECT COUNT(*) FROM orchestration_v2_command_receipts) AS count
439 `;
440 assert.equal(retiredWrites[0]?.count, 0);
441 }),
442 );
443});