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

ThreadManagementService.test.ts

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