Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

ThreadManagementService.test.ts

1,079 lines41.0 KB

1import { expect, it } from "@effect/vitest";
2import {
3 CommandId,
4 MessageId,
5 NodeId,
6 type OrchestrationV2Command,
7 type OrchestrationV2Run,
8 type OrchestrationV2Subagent,
9 type OrchestrationV2ProviderThread,
10 ProviderThreadId,
11 ProviderDriverKind,
12 ProviderSessionId,
13 type OrchestrationV2StoredEvent,
14 type OrchestrationV2ThreadProjection,
15 type OrchestrationV2ThreadShell,
16 ProjectId,
17 ProviderInstanceId,
18 RunId,
19 ThreadId,
20} from "@t3tools/contracts";
21import * as Deferred from "effect/Deferred";
22import * as DateTime from "effect/DateTime";
23import * as Option from "effect/Option";
24import * as Duration from "effect/Duration";
25import * as Effect from "effect/Effect";
26import * as Fiber from "effect/Fiber";
27import * as Layer from "effect/Layer";
28import * as Queue from "effect/Queue";
29import * as Ref from "effect/Ref";
30import * as Stream from "effect/Stream";
31import * as TestClock from "effect/testing/TestClock";
32​
33import * as LegacyV1ThreadImporter from "./legacy/LegacyV1ThreadImporter.ts";
34import * as ServerSettings from "../serverSettings.ts";
35import * as SqlitePersistence from "../persistence/Sqlite.ts";
36import * as CommandReceiptStore from "./CommandReceiptStore.ts";
37import * as Orchestrator from "./Orchestrator.ts";
38import * as ProviderSessionManager from "./ProviderSessionManager.ts";
39import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
40import * as ThreadManagementService from "./ThreadManagementService.ts";
41import * as ThreadCommandExecutor from "./ThreadCommandExecutor.ts";
42import { DispatchModeLimit, type DispatchModeRefusal } from "./DispatchModeLimit.ts";
43​
44it("stamps authoritative provenance on commands that create threads or messages", () => {
45 const command: OrchestrationV2Command = {
46 type: "thread.create",
47 createdBy: "agent",
48 creationSource: "mcp",
49 commandId: CommandId.make("command:thread-management:create"),
50 threadId: ThreadId.make("thread:thread-management:create"),
51 projectId: ProjectId.make("project:thread-management"),
52 title: "Thread management",
53 modelSelection: {
54 instanceId: ProviderInstanceId.make("codex"),
55 model: "gpt-5-codex",
56 },
57 runtimeMode: "full-access",
58 interactionMode: "default",
59 branch: null,
60 worktreePath: null,
61 };
62​
63 expect(
64 ThreadManagementService.withCreationProvenance(command, {
65 createdBy: "user",
66 creationSource: "web",
67 }),
68 ).toMatchObject({
69 createdBy: "user",
70 creationSource: "web",
71 });
72});
73​
74it("leaves commands that do not create durable authored content unchanged", () => {
75 const command: OrchestrationV2Command = {
76 type: "run.interrupt",
77 commandId: CommandId.make("command:thread-management:interrupt"),
78 threadId: ThreadId.make("thread:thread-management:interrupt"),
79 runId: RunId.make("run:thread-management:interrupt"),
80 };
81​
82 expect(
83 ThreadManagementService.withCreationProvenance(command, {
84 createdBy: "user",
85 creationSource: "web",
86 }),
87 ).toBe(command);
88});
89​
90it("identifies every existing thread that must be hydrated before dispatch", () => {
91 const sourceThreadId = ThreadId.make("thread:thread-management:source");
92 const targetThreadId = ThreadId.make("thread:thread-management:target");
93 const parentThreadId = ThreadId.make("thread:thread-management:parent");
94​
95 expect(
96 ThreadManagementService.existingThreadIdsForCommand({
97 type: "thread.create",
98 createdBy: "user",
99 creationSource: "web",
100 commandId: CommandId.make("command:thread-management:create"),
101 threadId: targetThreadId,
102 projectId: ProjectId.make("project:thread-management"),
103 title: "Created thread",
104 modelSelection: {
105 instanceId: ProviderInstanceId.make("codex"),
106 model: "gpt-5-codex",
107 },
108 runtimeMode: "full-access",
109 interactionMode: "default",
110 branch: null,
111 worktreePath: null,
112 }),
113 ).toEqual([]);
114​
115 expect(
116 ThreadManagementService.existingThreadIdsForCommand({
117 type: "thread.archive",
118 commandId: CommandId.make("command:thread-management:archive"),
119 threadId: targetThreadId,
120 }),
121 ).toEqual([targetThreadId]);
122​
123 expect(
124 ThreadManagementService.existingThreadIdsForCommand({
125 type: "thread.visit",
126 commandId: CommandId.make("command:thread-management:visit"),
127 threadId: targetThreadId,
128 visitedAt: "2026-07-30T00:00:00.000Z",
129 }),
130 ).toEqual([]);
131​
132 expect(
133 ThreadManagementService.existingThreadIdsForCommand({
134 type: "thread.mark-unread",
135 commandId: CommandId.make("command:thread-management:mark-unread"),
136 threadId: targetThreadId,
137 }),
138 ).toEqual([]);
139​
140 expect(
141 ThreadManagementService.existingThreadIdsForCommand({
142 type: "thread.fork",
143 createdBy: "user",
144 creationSource: "web",
145 commandId: CommandId.make("command:thread-management:fork"),
146 sourceThreadId,
147 targetThreadId,
148 sourcePoint: {
149 type: "run",
150 runId: RunId.make("run:thread-management:source"),
151 },
152 }),
153 ).toEqual([sourceThreadId]);
154​
155 expect(
156 ThreadManagementService.existingThreadIdsForCommand({
157 type: "thread.merge_back",
158 createdBy: "user",
159 creationSource: "web",
160 commandId: CommandId.make("command:thread-management:merge"),
161 sourceThreadId,
162 targetThreadId,
163 sourcePoint: {
164 type: "run",
165 runId: RunId.make("run:thread-management:source"),
166 },
167 }),
168 ).toEqual([sourceThreadId, targetThreadId]);
169​
170 expect(
171 ThreadManagementService.existingThreadIdsForCommand({
172 type: "delegated_task.request",
173 createdBy: "agent",
174 creationSource: "provider",
175 commandId: CommandId.make("command:thread-management:delegate"),
176 parentThreadId,
177 parentRunId: RunId.make("run:thread-management:parent"),
178 parentNodeId: NodeId.make("node:thread-management:parent"),
179 task: "Inspect the migration",
180 modelSelection: {
181 instanceId: ProviderInstanceId.make("codex"),
182 model: "gpt-5-codex",
183 },
184 runtimeMode: "full-access",
185 interactionMode: "default",
186 }),
187 ).toEqual([parentThreadId]);
188​
189 expect(
190 ThreadManagementService.existingThreadIdsForCommand({
191 type: "delegated_task.wake-policy",
192 commandId: CommandId.make("command:thread-management:wake-policy"),
193 parentThreadId,
194 taskId: NodeId.make("node:thread-management:delegated"),
195 completionWake: "always",
196 }),
197 ).toEqual([parentThreadId]);
198​
199 expect(
200 ThreadManagementService.existingThreadIdsForCommand({
201 type: "thread.created.record",
202 commandId: CommandId.make("command:thread-management:record"),
203 parentThreadId,
204 parentRunId: RunId.make("run:thread-management:parent"),
205 parentNodeId: NodeId.make("node:thread-management:parent"),
206 targetThreadId,
207 targetRunId: null,
208 }),
209 ).toEqual([parentThreadId, targetThreadId]);
210});
211​
212it("derives thread management messages from structural error attributes", () => {
213 const projectId = ProjectId.make("project:thread-management:errors");
214 const threadId = ThreadId.make("thread:thread-management:errors");
215 const runId = RunId.make("run:thread-management:errors");
216 const messageId = MessageId.make("message:thread-management:errors");
217 const infrastructureCause = new Error("private sqlite detail");
218​
219 const threadNotFound = new ThreadManagementService.ThreadManagementThreadNotFoundError({
220 projectId,
221 threadId,
222 });
223 expect(threadNotFound).toMatchObject({ projectId, threadId });
224 expect(threadNotFound.message).toBe(`Thread ${threadId} was not found in project ${projectId}.`);
225​
226 const runNotFound = new ThreadManagementService.ThreadManagementRunNotFoundError({
227 threadId,
228 runId,
229 });
230 expect(runNotFound).toMatchObject({ threadId, runId });
231 expect(runNotFound.message).toBe(`Run ${runId} does not belong to thread ${threadId}.`);
232​
233 const archived = new ThreadManagementService.ThreadManagementThreadArchivedError({
234 threadId,
235 });
236 expect(archived).toMatchObject({ threadId });
237 expect(archived.message).toBe(`Thread ${threadId} is archived and cannot receive messages.`);
238​
239 const notSteerable = new ThreadManagementService.ThreadManagementNoSteerableRunError({
240 threadId,
241 mode: "restart",
242 });
243 expect(notSteerable).toMatchObject({
244 threadId,
245 mode: "restart",
246 });
247 expect(notSteerable.message).toBe(
248 `Thread ${threadId} has no running turn that can be restarted.`,
249 );
250​
251 const notInterruptible = new ThreadManagementService.ThreadManagementThreadNotInterruptibleError({
252 threadId,
253 runId,
254 });
255 expect(notInterruptible).toMatchObject({ threadId, runId });
256 expect(notInterruptible.message).toBe(`Run ${runId} is not currently interruptible.`);
257​
258 const listFailure = new ThreadManagementService.ThreadManagementProjectThreadsListError({
259 projectId,
260 cause: infrastructureCause,
261 });
262 expect(listFailure).toMatchObject({ projectId, cause: infrastructureCause });
263 expect(listFailure.message).toBe(`Unable to list threads in project ${projectId}.`);
264 expect(listFailure.message).not.toContain(infrastructureCause.message);
265​
266 const durableProjectionFailure =
267 new ThreadManagementService.ThreadManagementDurableRunProjectionError({
268 threadId,
269 messageId,
270 });
271 expect(durableProjectionFailure).toMatchObject({ threadId, messageId });
272 expect(durableProjectionFailure.message).toBe(
273 `Message ${messageId} was accepted on thread ${threadId} without a durable run projection.`,
274 );
275});
276​
277const layerReceiptsTest = CommandReceiptStore.layer.pipe(
278 Layer.provide(SqlitePersistence.layerMemory),
279);
280​
281const layerThreadManagementTest = (settingsLayer: ReturnType<typeof ServerSettings.layerTest>) =>
282 ThreadManagementService.layer.pipe(
283 Layer.provide(Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({})),
284 Layer.provide(Layer.mock(Orchestrator.OrchestratorV2)({})),
285 Layer.provide(settingsLayer),
286 Layer.provide(layerReceiptsTest),
287 );
288​
289it.effect("refuses a new turn when the project effectively disables the instance", () => {
290 const projectId = ProjectId.make("project:thread-management:gate-disabled");
291 const instanceId = ProviderInstanceId.make("codex_work");
292 const commandId = CommandId.make("command:thread-management:gate-disabled");
293 const layerTest = layerThreadManagementTest(
294 ServerSettings.layerTest({
295 providerInstances: { [instanceId]: { driver: "codex", enabled: true } },
296 projectSettingsOverrides: {
297 [projectId]: { providerInstances: { [instanceId]: { enabled: false } } },
298 },
299 }),
300 );
301​
302 return Effect.gen(function* () {
303 const threads = yield* ThreadManagementService.ThreadManagementService;
304 const error = yield* Effect.flip(
305 threads.assertProviderInstanceEnabled({ projectId, commandId, instanceId }),
306 );
307​
308 expect(error).toBeInstanceOf(
309 ThreadManagementService.ThreadManagementProviderInstanceDisabledError,
310 );
311 expect(error).toMatchObject({ projectId, instanceId });
312 expect(error.message).toBe(
313 `Provider instance "${instanceId}" is disabled for project ${projectId}.`,
314 );
315 }).pipe(Effect.provide(layerTest));
316});
317​
318it.effect("allows a new turn when the project enables an instance the machine disabled", () => {
319 const projectId = ProjectId.make("project:thread-management:gate-enabled");
320 const instanceId = ProviderInstanceId.make("codex_work");
321 const commandId = CommandId.make("command:thread-management:gate-enabled");
322 const layerTest = layerThreadManagementTest(
323 ServerSettings.layerTest({
324 providerInstances: { [instanceId]: { driver: "codex", enabled: false } },
325 projectSettingsOverrides: {
326 [projectId]: { providerInstances: { [instanceId]: { enabled: true } } },
327 },
328 }),
329 );
330​
331 return Effect.gen(function* () {
332 const threads = yield* ThreadManagementService.ThreadManagementService;
333 yield* threads.assertProviderInstanceEnabled({ projectId, commandId, instanceId });
334 }).pipe(Effect.provide(layerTest));
335});
336​
337it.effect("inherits the machine value when the project has no override", () => {
338 const projectId = ProjectId.make("project:thread-management:gate-inherit");
339 const instanceId = ProviderInstanceId.make("codex_work");
340 const commandId = CommandId.make("command:thread-management:gate-inherit");
341 const layerTest = layerThreadManagementTest(
342 ServerSettings.layerTest({
343 providerInstances: { [instanceId]: { driver: "codex", enabled: false } },
344 }),
345 );
346​
347 return Effect.gen(function* () {
348 const threads = yield* ThreadManagementService.ThreadManagementService;
349 const error = yield* Effect.flip(
350 threads.assertProviderInstanceEnabled({ projectId, commandId, instanceId }),
351 );
352​
353 expect(error).toBeInstanceOf(
354 ThreadManagementService.ThreadManagementProviderInstanceDisabledError,
355 );
356 }).pipe(Effect.provide(layerTest));
357});
358​
359const layerDispatchChokepointTest =
360 (settingsLayer: ReturnType<typeof ServerSettings.layerTest>) => (dispatched: Array<string>) =>
361 ThreadManagementService.layer.pipe(
362 Layer.provide(Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({})),
363 Layer.provide(
364 Layer.mock(Orchestrator.OrchestratorV2)({
365 getThreadRecords: () =>
366 Effect.succeed({
367 thread: {
368 id: ThreadId.make("thread:thread-management:chokepoint"),
369 projectId: ProjectId.make("project:thread-management:chokepoint"),
370 deletedAt: null,
371 modelSelection: {
372 instanceId: ProviderInstanceId.make("codex_work"),
373 model: "test",
374 },
375 },
376 } as unknown as OrchestrationV2ThreadProjection),
377 dispatch: (command) =>
378 Effect.sync(() => {
379 dispatched.push(command.type);
380 return { sequence: 1, storedEvents: [] } as never;
381 }),
382 }),
383 ),
384 Layer.provide(settingsLayer),
385 Layer.provideMerge(layerReceiptsTest),
386 );
387​
388it.effect(
389 "the dispatch chokepoint refuses a continuation message.dispatch on a project-disabled instance before reaching the orchestrator",
390 () => {
391 const projectId = ProjectId.make("project:thread-management:chokepoint");
392 const threadId = ThreadId.make("thread:thread-management:chokepoint");
393 const instanceId = ProviderInstanceId.make("codex_work");
394 const commandId = CommandId.make("command:thread-management:chokepoint-disabled");
395 const dispatched: Array<string> = [];
396 const layerTest = layerDispatchChokepointTest(
397 ServerSettings.layerTest({
398 providerInstances: { [instanceId]: { driver: "codex", enabled: true } },
399 projectSettingsOverrides: {
400 [projectId]: { providerInstances: { [instanceId]: { enabled: false } } },
401 },
402 }),
403 )(dispatched);
404​
405 return Effect.gen(function* () {
406 const threads = yield* ThreadManagementService.ThreadManagementService;
407 const error = yield* Effect.flip(
408 threads.dispatch({
409 type: "message.dispatch",
410 commandId,
411 threadId,
412 messageId: MessageId.make("message:thread-management:chokepoint-disabled"),
413 text: "Background task completed.",
414 attachments: [],
415 dispatchMode: { type: "queue_after_active" },
416 createdBy: "agent",
417 creationSource: "server",
418 }),
419 );
420​
421 expect(error).toBeInstanceOf(
422 ThreadManagementService.ThreadManagementProviderInstanceDisabledError,
423 );
424 expect(error).toMatchObject({ projectId, instanceId });
425 expect(dispatched).toEqual([]);
426 }).pipe(Effect.provide(layerTest));
427 },
428);
429​
430it.effect(
431 "a replay of an already-accepted command id dispatches despite the instance now being disabled",
432 () => {
433 const projectId = ProjectId.make("project:thread-management:chokepoint");
434 const threadId = ThreadId.make("thread:thread-management:chokepoint");
435 const instanceId = ProviderInstanceId.make("codex_work");
436 const commandId = CommandId.make("command:thread-management:chokepoint-replay");
437 const dispatched: Array<string> = [];
438 const layerTest = layerDispatchChokepointTest(
439 ServerSettings.layerTest({
440 providerInstances: { [instanceId]: { driver: "codex", enabled: true } },
441 projectSettingsOverrides: {
442 [projectId]: { providerInstances: { [instanceId]: { enabled: false } } },
443 },
444 }),
445 )(dispatched);
446​
447 return Effect.gen(function* () {
448 const receipts = yield* CommandReceiptStore.CommandReceiptStoreV2;
449 yield* receipts.insertIfAbsent({
450 commandId,
451 threadId,
452 commandType: "message.dispatch",
453 acceptedAt: yield* DateTime.now,
454 resultSequence: 1,
455 status: "accepted",
456 error: null,
457 });
458​
459 const threads = yield* ThreadManagementService.ThreadManagementService;
460 yield* threads.dispatch({
461 type: "message.dispatch",
462 commandId,
463 threadId,
464 messageId: MessageId.make("message:thread-management:chokepoint-replay"),
465 text: "Background task completed.",
466 attachments: [],
467 dispatchMode: { type: "queue_after_active" },
468 createdBy: "agent",
469 creationSource: "server",
470 });
471​
472 expect(dispatched).toEqual(["message.dispatch"]);
473 }).pipe(Effect.provide(layerTest));
474 },
475);
476​
477it.effect("classifies projection infrastructure failures separately from a missing thread", () => {
478 const projectId = ProjectId.make("project:thread-management:projection-failure");
479 const threadId = ThreadId.make("thread:thread-management:projection-failure");
480 const infrastructureCause = new Error("sqlite read failed");
481 const projectionError = new Orchestrator.OrchestratorProjectionError({
482 threadId,
483 cause: infrastructureCause,
484 });
485 const layerTest = ThreadManagementService.layer.pipe(
486 Layer.provide(Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({})),
487 Layer.provide(
488 Layer.mock(Orchestrator.OrchestratorV2)({
489 getThreadProjection: () => Effect.fail(projectionError),
490 }),
491 ),
492 Layer.provide(ServerSettings.layerTest()),
493 Layer.provide(layerReceiptsTest),
494 );
495​
496 return Effect.gen(function* () {
497 const service = yield* ThreadManagementService.ThreadManagementService;
498 const error = yield* Effect.flip(service.getProjectThread({ projectId, threadId }));
499​
500 expect(error).toBeInstanceOf(ThreadManagementService.ThreadManagementProjectionLoadError);
501 expect(error).toMatchObject({
502 projectId,
503 threadId,
504 cause: projectionError,
505 });
506 expect(error.message).toBe(`Unable to load thread ${threadId} in project ${projectId}.`);
507 }).pipe(Effect.provide(layerTest));
508});
509​
510it.effect("uses thread-not-found only after a projection loads outside the project", () => {
511 const projectId = ProjectId.make("project:thread-management:requested");
512 const otherProjectId = ProjectId.make("project:thread-management:other");
513 const threadId = ThreadId.make("thread:thread-management:wrong-project");
514 const projection = {
515 thread: {
516 id: threadId,
517 projectId: otherProjectId,
518 deletedAt: null,
519 },
520 } as OrchestrationV2ThreadProjection;
521 const layerTest = ThreadManagementService.layer.pipe(
522 Layer.provide(Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({})),
523 Layer.provide(
524 Layer.mock(Orchestrator.OrchestratorV2)({
525 getThreadProjection: () => Effect.succeed(projection),
526 }),
527 ),
528 Layer.provide(ServerSettings.layerTest()),
529 Layer.provide(layerReceiptsTest),
530 );
531​
532 return Effect.gen(function* () {
533 const service = yield* ThreadManagementService.ThreadManagementService;
534 const error = yield* Effect.flip(service.getProjectThread({ projectId, threadId }));
535​
536 expect(error).toBeInstanceOf(ThreadManagementService.ThreadManagementThreadNotFoundError);
537 expect(error).toMatchObject({ projectId, threadId });
538 expect("cause" in error).toBe(false);
539 }).pipe(Effect.provide(layerTest));
540});
541​
542it.effect("preserves failed legacy materialization when reading checkpoint context", () => {
543 const threadId = ThreadId.make("thread:thread-management:checkpoint-import-failure");
544 const importError = new LegacyV1ThreadImporter.LegacyV1ThreadImportError({
545 threadId,
546 operation: "hydrate transcript for",
547 cause: new Error("checkpoint import failed"),
548 });
549 const layerTest = ThreadManagementService.layerWithLegacyImporter.pipe(
550 Layer.provide(Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({})),
551 Layer.provide(
552 Layer.mergeAll(
553 Layer.mock(Orchestrator.OrchestratorV2)({
554 getCheckpointContext: () =>
555 Effect.succeed({ runs: [], checkpointScopes: [], checkpoints: [] }),
556 }),
557 Layer.mock(LegacyV1ThreadImporter.LegacyV1ThreadImporter)({
558 ensureTranscript: () => Effect.fail(importError),
559 }),
560 ),
561 ),
562 Layer.provide(ServerSettings.layerTest()),
563 Layer.provide(layerReceiptsTest),
564 );
565 return Effect.gen(function* () {
566 const service = yield* ThreadManagementService.ThreadManagementService;
567 const error = yield* service.getCheckpointContext(threadId).pipe(Effect.flip);
568 expect(error).toBeInstanceOf(Orchestrator.OrchestratorProjectionError);
569 expect(error).toMatchObject({ threadId, cause: importError });
570 }).pipe(Effect.provide(layerTest));
571});
572​
573it.effect.each([
574 { finalStatus: "completed" as const, timedOut: false },
575 { finalStatus: "failed" as const, timedOut: false },
576 { finalStatus: "cancelled" as const, timedOut: false },
577 { finalStatus: "interrupted" as const, timedOut: false },
578 { finalStatus: "rolled_back" as const, timedOut: false },
579 { finalStatus: "running" as const, timedOut: true },
580 { finalStatus: "missing" as const },
581])("waitForThread timeout final read when selected run is $finalStatus", (scenario) =>
582 Effect.gen(function* () {
583 const projectId = ProjectId.make("project:thread-management:wait-timeout");
584 const threadId = ThreadId.make("thread:thread-management:wait-timeout");
585 const runId = RunId.make("run:thread-management:wait-timeout");
586 const subscribed = yield* Deferred.make<void>();
587 let reads = 0;
588 const projection = (status: OrchestrationV2Run["status"] | "missing") =>
589 ({
590 thread: { id: threadId, projectId, deletedAt: null },
591 runs: status === "missing" ? [] : [{ id: runId, status }],
592 }) as unknown as OrchestrationV2ThreadProjection;
593 const layerTest = ThreadManagementService.layer.pipe(
594 Layer.provide(Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({})),
595 Layer.provide(
596 Layer.mock(Orchestrator.OrchestratorV2)({
597 getThreadEventSequence: () => Effect.succeed(0),
598 restartContinuationPending: () => Effect.succeed(false),
599 streamStoredEventsFrom: () =>
600 Stream.fromEffect(Deferred.succeed(subscribed, undefined)).pipe(
601 Stream.drain,
602 Stream.concat(Stream.never),
603 ),
604 getThreadRecords: () =>
605 Effect.sync(() => {
606 reads += 1;
607 return projection(reads === 1 ? "running" : scenario.finalStatus);
608 }),
609 }),
610 ),
611 Layer.provide(ServerSettings.layerTest()),
612 Layer.provide(layerReceiptsTest),
613 );
614 const service = yield* ThreadManagementService.ThreadManagementService.pipe(
615 Effect.provide(layerTest),
616 );
617 const fiber = yield* service
618 .waitForThread({
619 projectId,
620 threadId,
621 runId,
622 timeoutMs: 1,
623 })
624 .pipe(Effect.result, Effect.forkChild);
625 yield* Deferred.await(subscribed);
626 yield* TestClock.adjust(Duration.millis(1));
627 const result = yield* Fiber.join(fiber);
628​
629 if (scenario.finalStatus === "missing") {
630 expect(result._tag).toBe("Failure");
631 expect(result).toMatchObject({
632 failure: expect.any(ThreadManagementService.ThreadManagementRunNotFoundError),
633 });
634 expect(result).toMatchObject({
635 failure: { threadId, runId },
636 });
637 } else {
638 expect(result._tag).toBe("Success");
639 expect(result).toMatchObject({
640 success: {
641 threadId,
642 timedOut: scenario.timedOut,
643 run: { id: runId, status: scenario.finalStatus },
644 },
645 });
646 }
647 }),
648);
649​
650it.effect("waitForThread reads the run again only when the run updates", () =>
651 Effect.gen(function* () {
652 const projectId = ProjectId.make("project:thread-management:wait-event");
653 const threadId = ThreadId.make("thread:thread-management:wait-event");
654 const runId = RunId.make("run:thread-management:wait-event");
655 const subscribed = yield* Deferred.make<void>();
656 const events = yield* Queue.unbounded<OrchestrationV2StoredEvent>();
657 let status: OrchestrationV2Run["status"] = "running";
658 let reads = 0;
659 const stored = (sequence: number, event: object) =>
660 ({ sequence, event: { threadId, ...event } }) as unknown as OrchestrationV2StoredEvent;
661 const layerTest = ThreadManagementService.layer.pipe(
662 Layer.provide(Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({})),
663 Layer.provide(
664 Layer.mock(Orchestrator.OrchestratorV2)({
665 getThreadEventSequence: () => Effect.succeed(0),
666 restartContinuationPending: () => Effect.succeed(false),
667 streamStoredEventsFrom: (input) =>
668 input?.eventType === "run.updated"
669 ? Stream.fromEffect(Deferred.succeed(subscribed, undefined)).pipe(
670 Stream.drain,
671 Stream.concat(Stream.fromQueue(events)),
672 )
673 : Stream.never,
674 getThreadRecords: () =>
675 Effect.sync(() => {
676 reads += 1;
677 return {
678 thread: { id: threadId, projectId, deletedAt: null },
679 runs: [{ id: runId, status }],
680 } as unknown as OrchestrationV2ThreadProjection;
681 }),
682 }),
683 ),
684 Layer.provide(ServerSettings.layerTest()),
685 Layer.provide(layerReceiptsTest),
686 );
687 const service = yield* ThreadManagementService.ThreadManagementService.pipe(
688 Effect.provide(layerTest),
689 );
690 const fiber = yield* service
691 .waitForThread({ projectId, threadId, runId, timeoutMs: 60 * 60 * 1_000 })
692 .pipe(Effect.forkChild);
693 yield* Deferred.await(subscribed);
694 status = "completed";
695 yield* Queue.offer(events, stored(1, { type: "run.updated", payload: { id: "other-run" } }));
696 yield* Queue.offer(events, stored(2, { type: "run.updated", payload: { id: runId, status } }));
697 const result = yield* Fiber.join(fiber);
698​
699 expect(result).toMatchObject({ timedOut: false, run: { id: runId, status: "completed" } });
700 expect(reads).toBe(2);
701 }),
702);
703​
704it.effect("waitForThread follows a restart continuation instead of the cut run", () =>
705 Effect.gen(function* () {
706 const projectId = ProjectId.make("project:thread-management:wait-restart");
707 const threadId = ThreadId.make("thread:thread-management:wait-restart");
708 const runId = RunId.make("run:thread-management:wait-restart");
709 const continuationId = RunId.make("run:thread-management:wait-restart:2");
710 const subscribed = yield* Deferred.make<void>();
711 const events = yield* Queue.unbounded<OrchestrationV2StoredEvent>();
712 let runs: Array<{
713 id: RunId;
714 status: OrchestrationV2Run["status"];
715 restartContinuationOfRunId?: RunId;
716 }> = [{ id: runId, status: "cancelled" }];
717 let pending = true;
718 const stored = (sequence: number, event: object) =>
719 ({ sequence, event: { threadId, ...event } }) as unknown as OrchestrationV2StoredEvent;
720 const layerTest = ThreadManagementService.layer.pipe(
721 Layer.provide(Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({})),
722 Layer.provide(
723 Layer.mock(Orchestrator.OrchestratorV2)({
724 getThreadEventSequence: () => Effect.succeed(0),
725 restartContinuationPending: (run) => Effect.succeed(pending && run.id === runId),
726 awaitRestartContinuation: () => Effect.never,
727 streamStoredEventsFrom: (input) =>
728 input?.eventType === "run.updated"
729 ? Stream.fromEffect(Deferred.succeed(subscribed, undefined)).pipe(
730 Stream.drain,
731 Stream.concat(Stream.fromQueue(events)),
732 )
733 : Stream.never,
734 getThreadRecords: () =>
735 Effect.sync(
736 () =>
737 ({
738 thread: { id: threadId, projectId, deletedAt: null },
739 runs,
740 }) as unknown as OrchestrationV2ThreadProjection,
741 ),
742 }),
743 ),
744 Layer.provide(ServerSettings.layerTest()),
745 Layer.provide(layerReceiptsTest),
746 );
747 const service = yield* ThreadManagementService.ThreadManagementService.pipe(
748 Effect.provide(layerTest),
749 );
750 const fiber = yield* service
751 .waitForThread({ projectId, threadId, runId, timeoutMs: 60 * 60 * 1_000 })
752 .pipe(Effect.forkChild);
753 yield* Deferred.await(subscribed);
754 const continuation = { id: continuationId, restartContinuationOfRunId: runId };
755 runs = [...runs, { ...continuation, status: "running" }];
756 pending = false;
757 yield* Queue.offer(
758 events,
759 stored(1, { type: "run.updated", payload: { ...continuation, status: "running" } }),
760 );
761 runs = [runs[0]!, { ...continuation, status: "completed" }];
762 yield* Queue.offer(
763 events,
764 stored(2, { type: "run.updated", payload: { ...continuation, status: "completed" } }),
765 );
766 const result = yield* Fiber.join(fiber);
767​
768 expect(result).toMatchObject({
769 timedOut: false,
770 run: { id: continuationId, status: "completed" },
771 });
772 }),
773);
774​
775it.effect("waitForThread returns the cut run once its continuation is declined", () =>
776 Effect.gen(function* () {
777 const projectId = ProjectId.make("project:thread-management:wait-declined");
778 const threadId = ThreadId.make("thread:thread-management:wait-declined");
779 const runId = RunId.make("run:thread-management:wait-declined");
780 const subscribed = yield* Deferred.make<void>();
781 const declined = yield* Deferred.make<void>();
782 let pending = true;
783 const layerTest = ThreadManagementService.layer.pipe(
784 Layer.provide(Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({})),
785 Layer.provide(
786 Layer.mock(Orchestrator.OrchestratorV2)({
787 getThreadEventSequence: () => Effect.succeed(0),
788 restartContinuationPending: () => Effect.succeed(pending),
789 awaitRestartContinuation: () => Deferred.await(declined),
790 streamStoredEventsFrom: (input) =>
791 input?.eventType === "run.updated"
792 ? Stream.fromEffect(Deferred.succeed(subscribed, undefined)).pipe(
793 Stream.drain,
794 Stream.concat(Stream.never),
795 )
796 : Stream.never,
797 getThreadRecords: () =>
798 Effect.succeed({
799 thread: { id: threadId, projectId, deletedAt: null },
800 runs: [{ id: runId, status: "cancelled" }],
801 } as unknown as OrchestrationV2ThreadProjection),
802 }),
803 ),
804 Layer.provide(ServerSettings.layerTest()),
805 Layer.provide(layerReceiptsTest),
806 );
807 const service = yield* ThreadManagementService.ThreadManagementService.pipe(
808 Effect.provide(layerTest),
809 );
810 const fiber = yield* service
811 .waitForThread({ projectId, threadId, runId, timeoutMs: 60 * 60 * 1_000 })
812 .pipe(Effect.forkChild);
813 yield* Deferred.await(subscribed);
814 pending = false;
815 yield* Deferred.succeed(declined, undefined);
816 const result = yield* Fiber.join(fiber);
817​
818 expect(result).toMatchObject({ timedOut: false, run: { id: runId, status: "cancelled" } });
819 }),
820);
821​
822it.effect.each([
823 "running",
824 "missing",
825 "completed",
826 "unsupported",
827 "missing-native-id",
828 "wrong-thread",
829 "no-session",
830 "unsupported-runtime",
831 "provider-failed",
832 "provider-timeout",
833 "within-limit",
834 "runtime-raised",
835 "interaction-raised",
836] as const)("stops a persisted workflow with state %s", (state) =>
837 Effect.gen(function* () {
838 const threadId = ThreadId.make("thread:workflow-stop");
839 const subagentId = NodeId.make("node:workflow-stop");
840 const runId = RunId.make("run:workflow-stop");
841 const providerThreadId = ProviderThreadId.make("provider-thread:workflow-stop");
842 const providerSessionId = ProviderSessionId.make("provider-session:workflow-stop");
843 const driver = ProviderDriverKind.make("claudeAgent");
844 const instanceId = ProviderInstanceId.make("claudeAgent");
845 const now = yield* DateTime.now;
846 let targetModes: Pick<OrchestrationV2ThreadShell, "runtimeMode" | "interactionMode"> = {
847 runtimeMode: "approval-required",
848 interactionMode: "plan",
849 };
850 const task: OrchestrationV2Subagent = {
851 id: subagentId,
852 threadId,
853 runId,
854 parentNodeId: NodeId.make("node:workflow-parent"),
855 origin: "provider_native",
856 createdBy: "agent",
857 driver,
858 providerInstanceId: instanceId,
859 providerThreadId: null,
860 childThreadId: null,
861 nativeTaskRef:
862 state === "missing-native-id"
863 ? null
864 : {
865 driver,
866 nativeId: "native-workflow-id",
867 strength: "strong",
868 },
869 workflow: { phases: [], agents: [] },
870 prompt: "Run the workflow",
871 title: null,
872 model: null,
873 status: state === "completed" ? "completed" : "running",
874 result: null,
875 startedAt: now,
876 completedAt: null,
877 updatedAt: now,
878 ...(state === "unsupported" ? { driver: ProviderDriverKind.make("codex") } : {}),
879 };
880 const providerThread: OrchestrationV2ProviderThread = {
881 id: providerThreadId,
882 driver,
883 providerInstanceId: instanceId,
884 providerSessionId,
885 appThreadId: state === "wrong-thread" ? ThreadId.make("other-thread") : threadId,
886 ownerNodeId: null,
887 nativeThreadRef: { driver, nativeId: "native-thread", strength: "strong" },
888 nativeConversationHeadRef: null,
889 status: "idle",
890 firstRunOrdinal: 1,
891 lastRunOrdinal: 1,
892 handoffIds: [],
893 forkedFrom: null,
894 pendingBackgroundTasks: [],
895 contextUsage: null,
896 nativeMetadata: null,
897 createdAt: now,
898 updatedAt: now,
899 };
900 const calls: Array<{ taskId: string; providerThread: OrchestrationV2ProviderThread }> = [];
901 const stopStarted = yield* Deferred.make<void>();
902 const runtime = {
903 driver,
904 providerSessionId,
905 instanceId,
906 ...(state === "unsupported-runtime"
907 ? {}
908 : {
909 stopTask: (input: (typeof calls)[number]) =>
910 state === "provider-failed"
911 ? Effect.fail(
912 new ProviderAdapter.ProviderAdapterProtocolError({
913 driver,
914 detail: "private provider detail",
915 }),
916 )
917 : state === "provider-timeout"
918 ? Deferred.succeed(stopStarted, undefined).pipe(Effect.andThen(Effect.never))
919 : Effect.sync(() => {
920 calls.push(input);
921 }),
922 }),
923 } as unknown as ProviderAdapter.ProviderAdapterV2SessionRuntime;
924 const layerTest = ThreadManagementService.layer.pipe(
925 Layer.provide(
926 Layer.mergeAll(
927 Layer.mock(Orchestrator.OrchestratorV2)({
928 getThreadRecords: () =>
929 Effect.sync(
930 () =>
931 ({
932 thread: { id: threadId, deletedAt: null, ...targetModes },
933 subagents: state === "missing" ? [] : [task],
934 runs: [{ id: runId, providerThreadId }],
935 providerThreads: [providerThread],
936 }) as unknown as OrchestrationV2ThreadProjection,
937 ),
938 }),
939 Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({
940 get: (id) => {
941 expect(id).toBe(providerSessionId);
942 return Effect.succeed(state === "no-session" ? Option.none() : Option.some(runtime));
943 },
944 }),
945 ),
946 ),
947 Layer.provide(ServerSettings.layerTest()),
948 Layer.provide(layerReceiptsTest),
949 );
950 yield* Effect.gen(function* () {
951 const service = yield* ThreadManagementService.ThreadManagementService;
952 const refused = yield* Ref.make<DispatchModeRefusal | undefined>(undefined);
953 const stop = service
954 .stopWorkflow({ threadId, subagentId })
955 .pipe(
956 Effect.provideService(
957 DispatchModeLimit,
958 state === "within-limit" || state === "runtime-raised" || state === "interaction-raised"
959 ? { runtimeMode: "approval-required", interactionMode: "plan", refused }
960 : undefined,
961 ),
962 Effect.result,
963 );
964 const executor = yield* ThreadCommandExecutor.ThreadCommandExecutor;
965 const result =
966 state === "runtime-raised" || state === "interaction-raised"
967 ? yield* Effect.gen(function* () {
968 const started = yield* Deferred.make<void>();
969 const pending = yield* executor.withLock(
970 threadId,
971 Effect.gen(function* () {
972 const fiber = yield* Deferred.succeed(started, undefined).pipe(
973 Effect.andThen(stop),
974 Effect.forkChild,
975 );
976 yield* Deferred.await(started);
977 targetModes =
978 state === "runtime-raised"
979 ? { ...targetModes, runtimeMode: "full-access" }
980 : { ...targetModes, interactionMode: "default" };
981 return fiber;
982 }),
983 );
984 return yield* Fiber.join(pending);
985 })
986 : state === "provider-timeout"
987 ? yield* Effect.gen(function* () {
988 const finished = yield* Ref.make(false);
989 const pending = yield* stop.pipe(
990 Effect.tap(() => Ref.set(finished, true)),
991 Effect.forkChild,
992 );
993 yield* Deferred.await(stopStarted);
994 yield* TestClock.adjust("15 seconds");
995 expect(yield* Ref.get(finished)).toBe(true);
996 const result = yield* Fiber.join(pending);
997 expect(yield* executor.withLock(threadId, Effect.succeed("lock-released"))).toBe(
998 "lock-released",
999 );
1000 return result;
1001 })
1002 : yield* stop;
1003 if (state === "running" || state === "within-limit") {
1004 expect(result).toMatchObject({ _tag: "Success" });
1005 expect(calls).toEqual([{ taskId: "native-workflow-id", providerThread }]);
1006 expect(task.status).toBe("running");
1007 } else {
1008 expect(result).toMatchObject({
1009 _tag: "Failure",
1010 failure: {
1011 _tag: "OrchestrationV2StopWorkflowError",
1012 threadId,
1013 subagentId,
1014 reason:
1015 state === "missing" || state === "completed"
1016 ? "not-running"
1017 : state === "unsupported" || state === "unsupported-runtime"
1018 ? "unsupported"
1019 : state === "provider-failed" || state === "provider-timeout"
1020 ? "stop-failed"
1021 : "unavailable",
1022 },
1023 });
1024 expect(calls).toEqual([]);
1025 if (state === "provider-timeout") {
1026 expect(result).toMatchObject({ failure: { cause: { _tag: "TimeoutError" } } });
1028 if (state === "runtime-raised" || state === "interaction-raised") {
1029 expect(yield* Ref.get(refused)).toEqual({
1030 threadId,
1031 ...targetModes,
1032 mode: state === "runtime-raised" ? "runtime" : "interaction",
1033 });
1036 }).pipe(Effect.provide(Layer.merge(layerTest, ThreadCommandExecutor.layer)));
1037 }),
1039​
1040it.effect.each([
1041 { status: "completed" as const, settles: true },
1042 { status: "failed" as const, settles: false },
1043 { status: "interrupted" as const, settles: false },
1044])("settleAfterRun settles only when the run $status", ({ status, settles }) =>
1045 Effect.gen(function* () {
1046 const projectId = ProjectId.make("project:thread-management:settle-after-run");
1047 const threadId = ThreadId.make("thread:thread-management:settle-after-run");
1048 const runId = RunId.make("run:thread-management:settle-after-run");
1049 const dispatched: Array<string> = [];
1050 const layerTest = ThreadManagementService.layer.pipe(
1051 Layer.provide(Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({})),
1052 Layer.provide(
1053 Layer.mock(Orchestrator.OrchestratorV2)({
1054 getThreadEventSequence: () => Effect.succeed(0),
1055 restartContinuationPending: () => Effect.succeed(false),
1056 getThreadRecords: () =>
1057 Effect.succeed({
1058 thread: { id: threadId, projectId, deletedAt: null },
1059 runs: [{ id: runId, status }],
1060 } as unknown as OrchestrationV2ThreadProjection),
1061 dispatch: (command) =>
1062 Effect.sync(() => {
1063 dispatched.push(command.type);
1064 return { sequence: 1, storedEvents: [] } as never;
1065 }),
1066 }),
1067 ),
1068 Layer.provide(ServerSettings.layerTest()),
1069 Layer.provide(layerReceiptsTest),
1070 );
1071 const service = yield* ThreadManagementService.ThreadManagementService.pipe(
1072 Effect.provide(layerTest),
1073 );
1074​
1075 yield* service.settleAfterRun({ projectId, threadId, runId });
1076​
1077 expect(dispatched).toEqual(settles ? ["thread.settle"] : []);
1078 }),