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

ThreadManagementService.test.ts

1,130 lines45.0 KB

1import { expect, it } from "@effect/vitest";
2import {
3 CommandId,
4 EnvironmentId,
5 MessageId,
6 type OrchestrationV2Command,
7 type OrchestrationV2Run,
8 type OrchestrationV2ProviderThread,
9 ProviderThreadId,
10 ProviderDriverKind,
11 ProviderSessionId,
12 type OrchestrationV2StoredEvent,
13 type OrchestrationV2ThreadProjection,
14 ProjectId,
15 ProviderInstanceId,
16 RunId,
17 ThreadId,
18} from "@t3tools/contracts";
19import * as Deferred from "effect/Deferred";
20import * as DateTime from "effect/DateTime";
21import * as Duration from "effect/Duration";
22import * as Option from "effect/Option";
23import * as Effect from "effect/Effect";
24import * as Fiber from "effect/Fiber";
25import * as Layer from "effect/Layer";
26import * as Queue from "effect/Queue";
27import * as Stream from "effect/Stream";
28import * as TestClock from "effect/testing/TestClock";
29​
30import { AgentScope } from "@t3tools/shared/AgentScope";
31​
32import * as ServerEnvironment from "../environment/ServerEnvironment.ts";
33import * as ServerSettings from "../serverSettings.ts";
34import * as SqlitePersistence from "../persistence/Sqlite.ts";
35import * as CommandReceiptStore from "./CommandReceiptStore.ts";
36import * as Orchestrator from "./Orchestrator.ts";
37import * as ProviderSessionManager from "./ProviderSessionManager.ts";
38import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
39import * as ThreadManagementService from "./ThreadManagementService.ts";
40import * as ThreadCommandExecutor from "./ThreadCommandExecutor.ts";
41import * as LegacyV1ThreadImporter from "./legacy/LegacyV1ThreadImporter.ts";
42import {
43 ThreadWorktreeRestore,
44 WorktreeRecreateError,
45} from "../workspace/restoreMissingWorktree.ts";
46​
47it("stamps authoritative provenance on commands that create threads or messages", () => {
48 const command: OrchestrationV2Command = {
49 type: "thread.create",
50 createdBy: "agent",
51 creationSource: "mcp",
52 commandId: CommandId.make("command:thread-management:create"),
53 threadId: ThreadId.make("thread:thread-management:create"),
54 projectId: ProjectId.make("project:thread-management"),
55 title: "Thread management",
56 modelSelection: {
57 instanceId: ProviderInstanceId.make("codex"),
58 model: "gpt-5-codex",
59 },
60 runtimeMode: "full-access",
61 interactionMode: "default",
62 branch: null,
63 worktreePath: null,
64 // A client cannot claim a linked environment's origin, or a parent there.
65 linkOrigin: { sessionId: "forged", label: "Somewhere else" },
66 delegatedFrom: {
67 environmentId: EnvironmentId.make("environment:elsewhere"),
68 threadId: ThreadId.make("thread:elsewhere"),
69 title: "Somewhere else",
70 },
71 // A client's message goes through intake; only the server folds one into the creation.
72 initialMessage: {
73 messageId: MessageId.make("message:thread-management:forged"),
74 text: "Forged",
75 attachments: [],
76 },
77 };
78​
79 const stamped = ThreadManagementService.withCreationProvenance(command, {
80 createdBy: "user",
81 creationSource: "web",
82 });
83 expect(stamped).toMatchObject({
84 createdBy: "user",
85 creationSource: "web",
86 });
87 expect(stamped).not.toHaveProperty("linkOrigin");
88 expect(stamped).not.toHaveProperty("delegatedFrom");
89 expect(stamped).not.toHaveProperty("initialMessage");
90});
91​
92const layerReceiptsTest = CommandReceiptStore.layer.pipe(
93 Layer.provide(SqlitePersistence.layerMemory),
94);
95​
96const layerDispatchChokepointTest =
97 (settingsLayer: ReturnType<typeof ServerSettings.layerTest>) => (dispatched: Array<string>) =>
98 ThreadManagementService.layer.pipe(
99 Layer.provide(Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({})),
100 Layer.provide(
101 Layer.mock(Orchestrator.OrchestratorV2)({
102 getThreadRecords: () =>
103 Effect.succeed({
104 thread: {
105 id: ThreadId.make("thread:thread-management:chokepoint"),
106 projectId: ProjectId.make("project:thread-management:chokepoint"),
107 deletedAt: null,
108 modelSelection: {
109 instanceId: ProviderInstanceId.make("codex_work"),
110 model: "test",
111 },
112 },
113 } as unknown as OrchestrationV2ThreadProjection),
114 dispatch: (command) =>
115 Effect.sync(() => {
116 dispatched.push(command.type);
117 return { sequence: 1, storedEvents: [] } as never;
118 }),
119 }),
120 ),
121 Layer.provide(settingsLayer),
122 Layer.provideMerge(layerReceiptsTest),
123 );
124​
125it.effect(
126 "the dispatch chokepoint refuses a continuation message.dispatch on a project-disabled instance before reaching the orchestrator",
127 () => {
128 const projectId = ProjectId.make("project:thread-management:chokepoint");
129 const threadId = ThreadId.make("thread:thread-management:chokepoint");
130 const instanceId = ProviderInstanceId.make("codex_work");
131 const commandId = CommandId.make("command:thread-management:chokepoint-disabled");
132 const dispatched: Array<string> = [];
133 const layerTest = layerDispatchChokepointTest(
134 ServerSettings.layerTest({
135 providerInstances: { [instanceId]: { driver: "codex", enabled: true } },
136 projectSettingsOverrides: {
137 [projectId]: { providerInstances: { [instanceId]: { enabled: false } } },
138 },
139 }),
140 )(dispatched);
141​
142 return Effect.gen(function* () {
143 const threads = yield* ThreadManagementService.ThreadManagementService;
144 const error = yield* Effect.flip(
145 threads.dispatch({
146 type: "message.dispatch",
147 commandId,
148 threadId,
149 messageId: MessageId.make("message:thread-management:chokepoint-disabled"),
150 text: "Background task completed.",
151 attachments: [],
152 dispatchMode: { type: "queue_after_active" },
153 createdBy: "agent",
154 creationSource: "server",
155 }),
156 );
157​
158 expect(error).toBeInstanceOf(
159 ThreadManagementService.ThreadManagementProviderInstanceDisabledError,
160 );
161 expect(error).toMatchObject({ projectId, instanceId });
162 expect(dispatched).toEqual([]);
163 }).pipe(Effect.provide(layerTest));
164 },
165);
166​
167it.effect(
168 "a replay of an already-accepted command id dispatches despite the instance now being disabled",
169 () => {
170 const projectId = ProjectId.make("project:thread-management:chokepoint");
171 const threadId = ThreadId.make("thread:thread-management:chokepoint");
172 const instanceId = ProviderInstanceId.make("codex_work");
173 const commandId = CommandId.make("command:thread-management:chokepoint-replay");
174 const dispatched: Array<string> = [];
175 const layerTest = layerDispatchChokepointTest(
176 ServerSettings.layerTest({
177 providerInstances: { [instanceId]: { driver: "codex", enabled: true } },
178 projectSettingsOverrides: {
179 [projectId]: { providerInstances: { [instanceId]: { enabled: false } } },
180 },
181 }),
182 )(dispatched);
183​
184 return Effect.gen(function* () {
185 const receipts = yield* CommandReceiptStore.CommandReceiptStoreV2;
186 yield* receipts.insertIfAbsent({
187 commandId,
188 threadId,
189 commandType: "message.dispatch",
190 acceptedAt: yield* DateTime.now,
191 resultSequence: 1,
192 status: "accepted",
193 error: null,
194 });
195​
196 const threads = yield* ThreadManagementService.ThreadManagementService;
197 yield* threads.dispatch({
198 type: "message.dispatch",
199 commandId,
200 threadId,
201 messageId: MessageId.make("message:thread-management:chokepoint-replay"),
202 text: "Background task completed.",
203 attachments: [],
204 dispatchMode: { type: "queue_after_active" },
205 createdBy: "agent",
206 creationSource: "server",
207 });
208​
209 expect(dispatched).toEqual(["message.dispatch"]);
210 }).pipe(Effect.provide(layerTest));
211 },
212);
213​
214it.effect.each([
215 { label: "fails a send that starts a turn", running: false },
216 { label: "still steers a running turn", running: true },
217])("sendToThread with a missing worktree that cannot be recreated $label", ({ running }) => {
218 const projectId = ProjectId.make("project:thread-management:worktree-gone");
219 const threadId = ThreadId.make("thread:thread-management:worktree-gone");
220 const dispatched: Array<string> = [];
221 const layerTest = ThreadManagementService.layerWithLegacyImporter.pipe(
222 Layer.provide(
223 Layer.succeed(ThreadWorktreeRestore, {
224 restore: () =>
225 Effect.fail(
226 new WorktreeRecreateError({
227 worktreePath: "/worktrees/gone",
228 branch: "t3/gone",
229 cause: new Error("branch_checked_out_in_worktree"),
230 }),
231 ),
232 }),
233 ),
234 Layer.provide(
235 Layer.mock(LegacyV1ThreadImporter.LegacyV1ThreadImporter)({
236 ensureTranscript: () => Effect.succeed({ importedThreadCount: 0, importedMessageCount: 0 }),
237 }),
238 ),
239 Layer.provide(Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({})),
240 Layer.provide(
241 Layer.mock(Orchestrator.OrchestratorV2)({
242 getThreadRecords: () =>
243 Effect.succeed({
244 thread: {
245 id: threadId,
246 projectId,
247 deletedAt: null,
248 archivedAt: null,
249 worktreePath: "/worktrees/gone",
250 branch: "t3/gone",
251 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "test" },
252 },
253 runs: running
254 ? [
255 {
256 id: RunId.make("run:thread-management:worktree-gone"),
257 status: "running",
258 activeAttemptId: "attempt:thread-management:worktree-gone",
259 },
260 ]
261 : [],
262 providerTurns: running
263 ? [
264 {
265 runAttemptId: "attempt:thread-management:worktree-gone",
266 status: "running",
267 },
268 ]
269 : [],
270 messages: [],
271 turnItems: [],
272 } as unknown as OrchestrationV2ThreadProjection),
273 dispatch: (command) =>
274 Effect.sync(() => {
275 dispatched.push(command.type);
276 return { sequence: 1, storedEvents: [] } as never;
277 }),
278 }),
279 ),
280 Layer.provide(ServerSettings.layerTest()),
281 Layer.provideMerge(layerReceiptsTest),
282 );
283​
284 return Effect.gen(function* () {
285 const threads = yield* ThreadManagementService.ThreadManagementService;
286 const error = yield* Effect.flip(
287 threads.sendToThread({
288 projectId,
289 threadId,
290 commandId: CommandId.make("command:thread-management:worktree-gone"),
291 messageId: MessageId.make("message:thread-management:worktree-gone"),
292 text: "Reply with ok.",
293 attachments: [],
294 mode: "auto",
295 createdBy: "agent",
296 creationSource: "mcp",
297 }),
298 );
299 // The mock records no message, so a dispatched send ends in the projection read.
300 expect(error._tag).toBe(
301 running
302 ? "ThreadManagementDurableRunProjectionError"
303 : "ThreadManagementWorktreeRestoreError",
304 );
305 expect(dispatched).toEqual(running ? ["message.dispatch"] : []);
306 }).pipe(Effect.provide(layerTest));
307});
308​
309it.effect("waitForThread follows a restart continuation instead of the cut run", () =>
310 Effect.gen(function* () {
311 const projectId = ProjectId.make("project:thread-management:wait-restart");
312 const threadId = ThreadId.make("thread:thread-management:wait-restart");
313 const runId = RunId.make("run:thread-management:wait-restart");
314 const continuationId = RunId.make("run:thread-management:wait-restart:2");
315 const subscribed = yield* Deferred.make<void>();
316 const events = yield* Queue.unbounded<OrchestrationV2StoredEvent>();
317 let runs: Array<{
318 id: RunId;
319 status: OrchestrationV2Run["status"];
320 restartContinuationOfRunId?: RunId;
321 }> = [{ id: runId, status: "cancelled" }];
322 let pending = true;
323 const stored = (sequence: number, event: object) =>
324 ({ sequence, event: { threadId, ...event } }) as unknown as OrchestrationV2StoredEvent;
325 const layerTest = ThreadManagementService.layer.pipe(
326 Layer.provide(Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({})),
327 Layer.provide(
328 Layer.mock(Orchestrator.OrchestratorV2)({
329 getThreadEventSequence: () => Effect.succeed(0),
330 restartContinuationPending: (run) => Effect.succeed(pending && run.id === runId),
331 awaitRestartContinuation: () => Effect.never,
332 streamStoredEventsFrom: (input) =>
333 input?.eventType === "run.updated"
334 ? Stream.fromEffect(Deferred.succeed(subscribed, undefined)).pipe(
335 Stream.drain,
336 Stream.concat(Stream.fromQueue(events)),
337 )
338 : Stream.never,
339 getThreadRecords: () =>
340 Effect.sync(
341 () =>
342 ({
343 thread: { id: threadId, projectId, deletedAt: null },
344 runs,
345 }) as unknown as OrchestrationV2ThreadProjection,
346 ),
347 }),
348 ),
349 Layer.provide(ServerSettings.layerTest()),
350 Layer.provide(layerReceiptsTest),
351 );
352 const service = yield* ThreadManagementService.ThreadManagementService.pipe(
353 Effect.provide(layerTest),
354 );
355 const fiber = yield* service
356 .waitForThread({ projectId, threadId, runId, timeoutMs: 60 * 60 * 1_000 })
357 .pipe(Effect.forkChild);
358 yield* Deferred.await(subscribed);
359 const continuation = { id: continuationId, restartContinuationOfRunId: runId };
360 runs = [...runs, { ...continuation, status: "running" }];
361 pending = false;
362 yield* Queue.offer(
363 events,
364 stored(1, { type: "run.updated", payload: { ...continuation, status: "running" } }),
365 );
366 runs = [runs[0]!, { ...continuation, status: "completed" }];
367 yield* Queue.offer(
368 events,
369 stored(2, { type: "run.updated", payload: { ...continuation, status: "completed" } }),
370 );
371 const result = yield* Fiber.join(fiber);
372​
373 expect(result).toMatchObject({
374 timedOut: false,
375 run: { id: continuationId, status: "completed" },
376 });
377 }),
378);
379​
380it.effect("waitForThread can wait past an ended run for the thread's delegated work", () =>
381 Effect.gen(function* () {
382 const projectId = ProjectId.make("project:thread-management:wait-delegated");
383 const threadId = ThreadId.make("thread:thread-management:wait-delegated");
384 const runId = RunId.make("run:thread-management:wait-delegated");
385 const wakeRunId = RunId.make("run:thread-management:wait-delegated:wake");
386 const subscribed = yield* Deferred.make<void>();
387 const events = yield* Queue.unbounded<OrchestrationV2StoredEvent>();
388 const at = (seconds: number) => DateTime.makeUnsafe(seconds * 1_000);
389 const run = (id: RunId, ordinal: number, status: OrchestrationV2Run["status"], end: number) =>
390 ({
391 id,
392 ordinal,
393 status,
394 startedAt: at(end - 1),
395 completedAt: status === "running" ? null : at(end),
396 }) as unknown as OrchestrationV2Run;
397 // The run ended, but a task it delegated still runs and will wake the thread.
398 let runs = [run(runId, 1, "completed", 1)];
399 let subagents = [{ status: "running" }];
400 const stored = (sequence: number, event: object) =>
401 ({ sequence, event: { threadId, ...event } }) as unknown as OrchestrationV2StoredEvent;
402 const layerTest = ThreadManagementService.layer.pipe(
403 Layer.provide(Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({})),
404 Layer.provide(
405 Layer.mock(Orchestrator.OrchestratorV2)({
406 getThreadEventSequence: () => Effect.succeed(0),
407 restartContinuationPending: () => Effect.succeed(false),
408 delegatedTaskResultPending: () => Effect.succeed(false),
409 streamStoredEventsFrom: (input) =>
410 input?.eventType === "subagent.updated"
411 ? Stream.fromEffect(Deferred.succeed(subscribed, undefined)).pipe(
412 Stream.drain,
413 Stream.concat(Stream.fromQueue(events)),
414 )
415 : Stream.never,
416 getThreadRecords: () =>
417 Effect.sync(
418 () =>
419 ({
420 thread: { id: threadId, projectId, deletedAt: null },
421 runs,
422 messages: [],
423 subagents,
424 providerThreads: [],
425 }) as unknown as OrchestrationV2ThreadProjection,
426 ),
427 }),
428 ),
429 Layer.provide(ServerSettings.layerTest()),
430 Layer.provide(layerReceiptsTest),
431 );
432 const service = yield* ThreadManagementService.ThreadManagementService.pipe(
433 Effect.provide(layerTest),
434 );
435 // Without the option, the ended run is the answer, as before.
436 expect(
437 yield* service.waitForThread({ projectId, threadId, runId, timeoutMs: 60 * 60 * 1_000 }),
438 ).toMatchObject({ timedOut: false, run: { id: runId } });
439 expect(
440 yield* service.waitForThread({ projectId, threadId, runId, timeoutMs: 60 * 60 * 1_000 }),
441 ).not.toHaveProperty("resultRun");
442​
443 const fiber = yield* service
444 .waitForThread({
445 projectId,
446 threadId,
447 runId,
448 timeoutMs: 60 * 60 * 1_000,
449 untilDelegatedWorkSettled: true,
450 })
451 .pipe(Effect.forkChild);
452 // A wait that returns early fails below instead of hanging here.
453 yield* Effect.raceFirst(Deferred.await(subscribed), Fiber.await(fiber));
454 // The task finishes; its delivery wakes the thread, whose next run answers.
455 subagents = [{ status: "completed" }];
456 runs = [...runs, run(wakeRunId, 2, "completed", 3)];
457 yield* Queue.offer(events, stored(1, { type: "subagent.updated", payload: {} }));
458 const result = yield* Fiber.join(fiber);
459​
460 expect(result).toMatchObject({
461 timedOut: false,
462 run: { id: runId, status: "completed" },
463 resultRun: { id: wakeRunId, status: "completed" },
464 });
465 }),
466);
467​
468it.effect("waitForThread settles delegated work on a thread rolled back past its only run", () =>
469 Effect.gen(function* () {
470 const projectId = ProjectId.make("project:thread-management:wait-rolled-back");
471 const threadId = ThreadId.make("thread:thread-management:wait-rolled-back");
472 const runId = RunId.make("run:thread-management:wait-rolled-back");
473 const rolledBack = {
474 id: runId,
475 ordinal: 1,
476 status: "rolled_back",
477 startedAt: DateTime.makeUnsafe(0),
478 completedAt: DateTime.makeUnsafe(1_000),
479 } as unknown as OrchestrationV2Run;
480 const layerTest = ThreadManagementService.layer.pipe(
481 Layer.provide(Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({})),
482 Layer.provide(
483 Layer.mock(Orchestrator.OrchestratorV2)({
484 getThreadEventSequence: () => Effect.succeed(0),
485 restartContinuationPending: () => Effect.succeed(false),
486 delegatedTaskResultPending: () => Effect.succeed(false),
487 streamStoredEventsFrom: () => Stream.never,
488 getThreadRecords: () =>
489 Effect.succeed({
490 thread: { id: threadId, projectId, deletedAt: null },
491 runs: [rolledBack],
492 messages: [],
493 subagents: [],
494 providerThreads: [],
495 } as unknown as OrchestrationV2ThreadProjection),
496 }),
497 ),
498 Layer.provide(ServerSettings.layerTest()),
499 Layer.provide(layerReceiptsTest),
500 );
501 const service = yield* ThreadManagementService.ThreadManagementService.pipe(
502 Effect.provide(layerTest),
503 );
504 const fiber = yield* service
505 .waitForThread({
506 projectId,
507 threadId,
508 runId,
509 timeoutMs: 60_000,
510 untilDelegatedWorkSettled: true,
511 })
512 .pipe(Effect.forkChild);
513 // Nothing will ever run there again, so a wait still open runs out here.
514 yield* TestClock.adjust(Duration.millis(60_000));
515 const result = yield* Fiber.join(fiber);
516​
517 expect(result).toMatchObject({
518 timedOut: false,
519 run: { id: runId, status: "rolled_back" },
520 resultRun: { id: runId, status: "rolled_back" },
521 });
522 }),
523);
524​
525it.effect("waitForThread waits for output only from a run that was asked for one", () =>
526 Effect.gen(function* () {
527 const projectId = ProjectId.make("project:thread-management:wait-output");
528 const threadId = ThreadId.make("thread:thread-management:wait-output");
529 const askedRunId = RunId.make("run:thread-management:wait-output:asked");
530 const plainRunId = RunId.make("run:thread-management:wait-output:plain");
531 const layerTest = ThreadManagementService.layer.pipe(
532 Layer.provide(Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({})),
533 Layer.provide(
534 Layer.mock(Orchestrator.OrchestratorV2)({
535 getThreadEventSequence: () => Effect.succeed(0),
536 restartContinuationPending: () => Effect.succeed(false),
537 streamStoredEventsFrom: () => Stream.never,
538 getThreadRecords: () =>
539 Effect.succeed({
540 thread: { id: threadId, projectId, deletedAt: null },
541 runs: [
542 { id: askedRunId, status: "completed", outputSchema: { type: "object" } },
543 { id: plainRunId, status: "completed" },
544 ],
545 } as unknown as OrchestrationV2ThreadProjection),
546 }),
547 ),
548 Layer.provide(ServerSettings.layerTest()),
549 Layer.provide(layerReceiptsTest),
550 );
551 const service = yield* ThreadManagementService.ThreadManagementService.pipe(
552 Effect.provide(layerTest),
553 );
554 const wait = (runId: RunId) =>
555 service
556 .waitForThread({ projectId, threadId, runId, timeoutMs: 60_000, untilOutput: true })
557 .pipe(Effect.forkChild);
558 const asked = yield* wait(askedRunId);
559 const plain = yield* wait(plainRunId);
560 yield* TestClock.adjust(Duration.millis(60_000));
561​
562 // A later turn may still submit the result the first run owes.
563 expect(yield* Fiber.join(asked)).toMatchObject({ timedOut: true, run: { id: askedRunId } });
564 // Nothing can submit one for a run that never asked, so its end is the answer.
565 expect(yield* Fiber.join(plain)).toMatchObject({
566 timedOut: false,
567 run: { id: plainRunId, status: "completed" },
568 });
569 }),
570);
571​
572it.effect("waitForThread returns the cut run once its continuation is declined", () =>
573 Effect.gen(function* () {
574 const projectId = ProjectId.make("project:thread-management:wait-declined");
575 const threadId = ThreadId.make("thread:thread-management:wait-declined");
576 const runId = RunId.make("run:thread-management:wait-declined");
577 const subscribed = yield* Deferred.make<void>();
578 const declined = yield* Deferred.make<void>();
579 let pending = true;
580 const layerTest = ThreadManagementService.layer.pipe(
581 Layer.provide(Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({})),
582 Layer.provide(
583 Layer.mock(Orchestrator.OrchestratorV2)({
584 getThreadEventSequence: () => Effect.succeed(0),
585 restartContinuationPending: () => Effect.succeed(pending),
586 awaitRestartContinuation: () => Deferred.await(declined),
587 streamStoredEventsFrom: (input) =>
588 input?.eventType === "run.updated"
589 ? Stream.fromEffect(Deferred.succeed(subscribed, undefined)).pipe(
590 Stream.drain,
591 Stream.concat(Stream.never),
592 )
593 : Stream.never,
594 getThreadRecords: () =>
595 Effect.succeed({
596 thread: { id: threadId, projectId, deletedAt: null },
597 runs: [{ id: runId, status: "cancelled" }],
598 } as unknown as OrchestrationV2ThreadProjection),
599 }),
600 ),
601 Layer.provide(ServerSettings.layerTest()),
602 Layer.provide(layerReceiptsTest),
603 );
604 const service = yield* ThreadManagementService.ThreadManagementService.pipe(
605 Effect.provide(layerTest),
606 );
607 const fiber = yield* service
608 .waitForThread({ projectId, threadId, runId, timeoutMs: 60 * 60 * 1_000 })
609 .pipe(Effect.forkChild);
610 yield* Deferred.await(subscribed);
611 pending = false;
612 yield* Deferred.succeed(declined, undefined);
613 const result = yield* Fiber.join(fiber);
614​
615 expect(result).toMatchObject({ timedOut: false, run: { id: runId, status: "cancelled" } });
616 }),
617);
618​
619it.effect.each([
620 "live",
621 "no-match",
622 "no-match-clear",
623 "no-session",
624 "unsupported-runtime",
625] as const)(
626 "marks background work awaited on the thread's active provider thread with state %s",
627 (state) =>
628 Effect.gen(function* () {
629 const threadId = ThreadId.make("thread:background-wait");
630 const providerThreadId = ProviderThreadId.make("provider-thread:background-wait");
631 const providerSessionId = ProviderSessionId.make("provider-session:background-wait");
632 const driver = ProviderDriverKind.make("claudeAgent");
633 const now = yield* DateTime.now;
634 const providerThread: OrchestrationV2ProviderThread = {
635 id: providerThreadId,
636 driver,
637 providerInstanceId: ProviderInstanceId.make("claudeAgent"),
638 providerSessionId,
639 appThreadId: threadId,
640 ownerNodeId: null,
641 nativeThreadRef: { driver, nativeId: "native-thread", strength: "strong" },
642 nativeConversationHeadRef: null,
643 status: "idle",
644 firstRunOrdinal: 1,
645 lastRunOrdinal: 1,
646 handoffIds: [],
647 forkedFrom: null,
648 pendingBackgroundTasks: [{ taskId: "tests", kind: "command" }],
649 contextUsage: null,
650 nativeMetadata: null,
651 createdAt: now,
652 updatedAt: now,
653 };
654 const calls: Array<{ providerThreadId: ProviderThreadId; awaited: boolean }> = [];
655 const runtime = {
656 driver,
657 providerSessionId,
658 ...(state === "unsupported-runtime"
659 ? {}
660 : {
661 awaitBackgroundTasks: (input: {
662 readonly providerThread: OrchestrationV2ProviderThread;
663 readonly taskIds: ReadonlyArray<string>;
664 readonly awaited: boolean;
665 }) =>
666 Effect.sync(() => {
667 calls.push({
668 providerThreadId: input.providerThread.id,
669 awaited: input.awaited,
670 });
671 return { matched: input.taskIds.filter((taskId) => taskId === "tests") };
672 }),
673 }),
674 } as unknown as ProviderAdapter.ProviderAdapterV2SessionRuntime;
675 const layerTest = ThreadManagementService.layer.pipe(
676 Layer.provide(
677 Layer.mergeAll(
678 Layer.mock(Orchestrator.OrchestratorV2)({
679 getThreadRecords: () =>
680 Effect.succeed({
681 thread: {
682 id: threadId,
683 deletedAt: null,
684 activeProviderThreadId: providerThreadId,
685 },
686 providerThreads: [providerThread],
687 } as unknown as OrchestrationV2ThreadProjection),
688 }),
689 Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({
690 get: () =>
691 Effect.succeed(state === "no-session" ? Option.none() : Option.some(runtime)),
692 }),
693 ),
694 ),
695 Layer.provide(ServerSettings.layerTest()),
696 Layer.provide(layerReceiptsTest),
697 );
698 const result = yield* Effect.gen(function* () {
699 const service = yield* ThreadManagementService.ThreadManagementService;
700 return yield* service
701 .awaitBackgroundTasks({
702 threadId,
703 taskIds: state.startsWith("no-match") ? ["finished"] : ["tests", "finished"],
704 awaited: state !== "no-match-clear",
705 })
706 .pipe(Effect.result);
707 }).pipe(Effect.provide(Layer.merge(layerTest, ThreadCommandExecutor.layer)));
708​
709 if (state === "live") {
710 expect(result).toMatchObject({
711 success: { matched: ["tests"], unmatched: ["finished"] },
712 });
713 expect(calls).toEqual([{ providerThreadId, awaited: true }]);
714 } else if (state === "no-match") {
715 expect(result).toMatchObject({
716 failure: { _tag: "ThreadManagementBackgroundWaitError", reason: "unmatched" },
717 });
718 expect(calls).toEqual([{ providerThreadId, awaited: true }]);
719 } else if (state === "no-match-clear") {
720 expect(result).toMatchObject({ success: { matched: [], unmatched: ["finished"] } });
721 expect(calls).toEqual([{ providerThreadId, awaited: false }]);
722 } else {
723 expect(result).toMatchObject({
724 failure: {
725 _tag: "ThreadManagementBackgroundWaitError",
726 reason: state === "no-session" ? "unavailable" : "unsupported",
727 },
728 });
729 expect(calls).toEqual([]);
730 }
731 }),
732);
733​
734it.effect.each([
735 { status: "completed" as const, followUp: "none", settles: true },
736 { status: "failed" as const, followUp: "none", settles: false },
737 { status: "interrupted" as const, followUp: "none", settles: false },
738 { status: "completed" as const, followUp: "notification", settles: true },
739 { status: "completed" as const, followUp: "replayed-notification", settles: true },
740 { status: "completed" as const, followUp: "delegated", settles: true },
741 { status: "completed" as const, followUp: "failed-notification", settles: false },
742 { status: "completed" as const, followUp: "held-notification", settles: true },
743 { status: "completed" as const, followUp: "user", settles: false },
744 { status: "completed" as const, followUp: "steered-notification", settles: false },
745 // Send now cancels the queued run; its message joins the run that asked to settle.
746 { status: "completed" as const, followUp: "promoted-to-steer", settles: true },
747 // A delegated-completion wake cancelled unstarted because the turn already took the result.
748 { status: "completed" as const, followUp: "cancelled-delegated", settles: true },
749 { status: "completed" as const, followUp: "stopped-delegated", settles: false },
750])("settleAfterRun handles $status with $followUp follow-up", ({ status, followUp, settles }) =>
751 Effect.gen(function* () {
752 const projectId = ProjectId.make("project:thread-management:settle-after-run");
753 const threadId = ThreadId.make("thread:thread-management:settle-after-run");
754 const runId = RunId.make("run:thread-management:settle-after-run");
755 const followUpId = RunId.make(`${runId}:follow-up`);
756 const subscribed = yield* Deferred.make<void>();
757 const events = yield* Queue.unbounded<OrchestrationV2StoredEvent>();
758 const replayRejected = yield* Deferred.make<void>();
759 let sequence = 0;
760 let sequenceReads = 0;
761 let rejectedCommandId: CommandId | undefined;
762 const runs = [{ id: runId, ordinal: 1, status, userMessageId: MessageId.make("original") }];
763 const nextRun = {
764 id: followUpId,
765 ordinal: 2,
766 status: "running" as OrchestrationV2Run["status"],
767 userMessageId: MessageId.make("follow-up"),
768 startedAt: followUp === "stopped-delegated" ? "2026-01-01T00:00:00.000Z" : null,
769 };
770 const dispatched: Array<string> = [];
771 // The notification starts after the completed run was observed, before settlement commits.
772 let raced = false;
773 const layerTest = ThreadManagementService.layer.pipe(
774 Layer.provide(Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({})),
775 Layer.provide(
776 Layer.mock(Orchestrator.OrchestratorV2)({
777 getThreadEventSequence: () =>
778 Effect.sync(() => {
779 if (followUp === "replayed-notification" && sequenceReads++ === 2) sequence = 1;
780 return sequence;
781 }),
782 restartContinuationPending: () => Effect.succeed(false),
783 streamStoredEventsFrom: () =>
784 Stream.fromEffect(Deferred.succeed(subscribed, undefined)).pipe(
785 Stream.drain,
786 Stream.concat(Stream.fromQueue(events)),
787 ),
788 getThreadRecords: (_threadId, _fields, filter) =>
789 Effect.sync(
790 () =>
791 ({
792 thread: { id: threadId, projectId, deletedAt: null },
793 runs: raced ? [...runs, nextRun] : runs,
794 messages: [
795 { id: MessageId.make("original"), runId, role: "user" as const },
796 {
797 id: nextRun.userMessageId,
798 runId: followUp === "promoted-to-steer" ? runId : followUpId,
799 role: "user" as const,
800 ...(followUp.endsWith("notification") ? { notification: {} } : {}),
801 ...(followUp.endsWith("delegated") ? { delegatedCompletion: {} } : {}),
802 },
803 { id: MessageId.make("reply"), runId: followUpId, role: "assistant" as const },
804 ...(followUp === "steered-notification"
805 ? [
806 {
807 id: MessageId.make("user-steer"),
808 runId: followUpId,
809 role: "user" as const,
810 },
811 ]
812 : []),
813 ].filter(
814 (message) =>
815 (filter?.messageIds === undefined ||
816 filter.messageIds.includes(message.id)) &&
817 (filter?.messageRunIds === undefined ||
818 filter.messageRunIds.includes(message.runId)) &&
819 (filter?.messageRoles === undefined ||
820 filter.messageRoles.includes(message.role)),
821 ),
822 }) as unknown as OrchestrationV2ThreadProjection,
823 ),
824 dispatch: (command) =>
825 Effect.gen(function* () {
826 if (followUp !== "none" && !raced) {
827 raced = true;
828 rejectedCommandId = command.commandId;
829 return yield* new Orchestrator.OrchestratorDispatchError({
830 commandId: command.commandId,
831 commandType: command.type,
832 cause: "Thread is still running",
833 });
834 }
835 if (followUp === "replayed-notification" && command.commandId === rejectedCommandId) {
836 yield* Deferred.succeed(replayRejected, undefined);
837 return yield* new Orchestrator.OrchestratorCommandPreviouslyRejectedError({
838 commandId: command.commandId,
839 commandType: command.type,
840 detail: "Thread is still running",
841 });
842 }
843 dispatched.push(command.type);
844 return { sequence: 1, storedEvents: [] } as never;
845 }),
846 }),
847 ),
848 Layer.provide(ServerSettings.layerTest()),
849 Layer.provide(layerReceiptsTest),
850 );
851 const service = yield* ThreadManagementService.ThreadManagementService.pipe(
852 Effect.provide(layerTest),
853 );
854 const fiber = yield* service
855 .settleAfterRun({ projectId, threadId, runId })
856 .pipe(Effect.forkChild);
857 if (followUp !== "none") {
858 yield* Deferred.await(subscribed);
859 expect(dispatched).toEqual([]);
860 nextRun.status =
861 followUp === "failed-notification"
862 ? "failed"
863 : followUp === "held-notification"
864 ? "queued"
865 : followUp === "promoted-to-steer" || followUp.endsWith("ed-delegated")
866 ? "cancelled"
867 : "completed";
868 yield* Queue.offer(events, {
869 sequence: 1,
870 event: { type: "run.updated", threadId, payload: nextRun },
871 } as unknown as OrchestrationV2StoredEvent);
872 }
873 if (followUp === "replayed-notification") {
874 yield* Deferred.await(replayRejected);
875 expect(dispatched).toEqual([]);
876 sequence = 2;
877 yield* Queue.offer(events, {
878 sequence,
879 event: { type: "run.updated", threadId, payload: nextRun },
880 } as unknown as OrchestrationV2StoredEvent);
881 }
882 yield* Fiber.join(fiber);
883 expect(dispatched).toEqual(settles ? ["thread.settle"] : []);
884 }),
885);
886​
887it.effect.each([
888 {
889 name: "kills the thread's own agent and ends its turn",
890 others: [] as ReadonlyArray<string>,
891 killed: true,
892 expected: { outcome: "killed", sharedWithThreadIds: [] },
893 teardown: ["release"],
894 },
895 {
896 name: "keeps a process another working thread shares and only ends this turn",
897 others: ["thread:thread-management:force-stop:other"],
898 killed: false,
899 expected: {
900 outcome: "shared",
901 sharedWithThreadIds: ["thread:thread-management:force-stop:other"],
902 },
903 teardown: ["detach"],
904 },
905 {
906 name: "still settles a finished run's background work in a shared process",
907 others: ["thread:thread-management:force-stop:other"],
908 killed: false,
909 settledRun: true,
910 expected: {
911 outcome: "shared",
912 sharedWithThreadIds: ["thread:thread-management:force-stop:other"],
913 },
914 teardown: ["detach"],
915 },
916 {
917 name: "detaches when a sibling starts a turn just before the session is released",
918 others: [] as ReadonlyArray<string>,
919 killed: false,
920 siblingBusy: true,
921 expected: { outcome: "shared", sharedWithThreadIds: [] },
922 teardown: ["release", "detach"],
923 },
924 {
925 name: "reports a teardown that has not finished in time as still releasing",
926 others: [] as ReadonlyArray<string>,
927 killed: false,
928 releaseHangs: true,
929 expected: { outcome: "releasing", sharedWithThreadIds: [] },
930 teardown: ["release"],
931 },
932])("Force stop $name", ({ others, killed, expected, teardown, ...row }) =>
933 Effect.gen(function* () {
934 const threadId = ThreadId.make("thread:thread-management:force-stop");
935 const providerSessionId = ProviderSessionId.make("provider-session:force-stop");
936 const providerThreadId = ProviderThreadId.make("provider-thread:force-stop");
937 const runId = RunId.make("run:thread-management:force-stop");
938 const dispatched: Array<OrchestrationV2Command | { readonly type: string }> = [];
939 const teardowns: Array<string> = [];
940 const tornDown = yield* Deferred.make<void>();
941 const layerTest = ThreadManagementService.layer.pipe(
942 Layer.provide(
943 Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({
944 isLive: () => Effect.succeed(true),
945 otherWorkingThreads: () => Effect.succeed(others.map((id) => ThreadId.make(id))),
946 releaseUnlessBusy: () =>
947 Effect.sync(() => teardowns.push("release")).pipe(
948 Effect.andThen(
949 "releaseHangs" in row ? Effect.never : Effect.succeed(!("siblingBusy" in row)),
950 ),
951 ),
952 detach: () =>
953 Effect.sync(() => teardowns.push("detach")).pipe(
954 Effect.andThen(Deferred.succeed(tornDown, undefined)),
955 Effect.asVoid,
956 ),
957 }),
958 ),
959 Layer.provide(
960 Layer.mock(Orchestrator.OrchestratorV2)({
961 getThreadRecords: () =>
962 Effect.succeed({
963 thread: { id: threadId, deletedAt: null },
964 runs: [
965 {
966 id: runId,
967 ordinal: 1,
968 status: "settledRun" in row ? "completed" : "running",
969 activeAttemptId: "attempt",
970 },
971 // A queued follow-up neither supersedes the request nor becomes the target.
972 { id: RunId.make("run:queued-follow-up"), ordinal: 2, status: "queued" },
973 ],
974 providerThreads: [{ id: providerThreadId, appThreadId: threadId, providerSessionId }],
975 providerTurns: [
976 {
977 id: "provider-turn:force-stop",
978 providerThreadId,
979 runAttemptId: "attempt",
980 status: "settledRun" in row ? "completed" : "running",
981 },
982 ],
983 } as unknown as OrchestrationV2ThreadProjection),
984 dispatch: (command) =>
985 Effect.sync(() => {
986 dispatched.push(command);
987 return { sequence: 1, storedEvents: [] } as never;
988 }),
989 }),
990 ),
991 Layer.provide(
992 Layer.succeed(AgentScope, {
993 ...AgentScope.defaultValue(),
994 kill: () => Effect.succeed(killed),
995 }),
996 ),
997 Layer.provide(ServerSettings.layerTest()),
998 Layer.provide(layerReceiptsTest),
999 );
1000 yield* Effect.gen(function* () {
1001 const service = yield* ThreadManagementService.ThreadManagementService;
1002 const stopping = yield* service.forceStopThread({ threadId, runId }).pipe(Effect.forkChild);
1003 yield* TestClock.adjust("10 seconds");
1004 expect(yield* Fiber.join(stopping)).toEqual(expected);
1005 expect(dispatched).toMatchObject([
1007 type: "thread.background-work.settle",
1008 providerThreadId,
1009 reason: "Force stopped by user",
1010 },
1011 ]);
1012 if (teardown.at(-1) === "detach") yield* Deferred.await(tornDown);
1013 expect(teardowns).toEqual(teardown);
1014 }).pipe(Effect.provide(layerTest));
1015 }),
1017​
1018it.effect("Force stop refuses once a newer run has started, before killing anything", () =>
1019 Effect.gen(function* () {
1020 const threadId = ThreadId.make("thread:thread-management:force-stop-superseded");
1021 let killed = false;
1022 const layerTest = ThreadManagementService.layer.pipe(
1023 Layer.provide(Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({})),
1024 Layer.provide(
1025 Layer.mock(Orchestrator.OrchestratorV2)({
1026 getThreadRecords: () =>
1027 Effect.succeed({
1028 thread: { id: threadId, deletedAt: null },
1029 runs: [
1030 { id: RunId.make("run:stopped"), ordinal: 1, status: "running" },
1031 { id: RunId.make("run:newer"), ordinal: 2, status: "running" },
1032 ],
1033 providerThreads: [],
1034 providerTurns: [],
1035 } as unknown as OrchestrationV2ThreadProjection),
1036 }),
1037 ),
1038 Layer.provide(
1039 Layer.succeed(AgentScope, {
1040 ...AgentScope.defaultValue(),
1041 kill: () => Effect.sync(() => (killed = true)),
1042 }),
1043 ),
1044 Layer.provide(ServerSettings.layerTest()),
1045 Layer.provide(layerReceiptsTest),
1046 );
1047 const error = yield* Effect.gen(function* () {
1048 const service = yield* ThreadManagementService.ThreadManagementService;
1049 return yield* Effect.flip(
1050 service.forceStopThread({ threadId, runId: RunId.make("run:stopped") }),
1051 );
1052 }).pipe(Effect.provide(layerTest));
1053 expect(error.reason).toBe("superseded");
1054 expect(killed).toBe(false);
1055 }),
1057​
1058it.effect(
1059 "admits two transcript exports at a time and frees a slot on failure or interruption",
1060 () =>
1061 Effect.gen(function* () {
1062 const started = yield* Queue.unbounded<string>();
1063 const gates = new Map(
1064 ["a", "b", "c", "d", "e", "f"].map((id) => [
1065 id,
1066 Deferred.makeUnsafe<void, Orchestrator.OrchestratorV2Error>(),
1067 ]),
1068 );
1069 const layerTest = ThreadManagementService.layer.pipe(
1070 Layer.provide(Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({})),
1071 Layer.provide(
1072 Layer.mock(Orchestrator.OrchestratorV2)({
1073 getTranscriptByteFloor: () => Effect.succeed(0),
1074 getThreadSnapshot: (threadId) =>
1075 Queue.offer(started, threadId).pipe(
1076 Effect.andThen(Deferred.await(gates.get(threadId)!)),
1077 Effect.as({
1078 schemaVersion: 1,
1079 snapshotSequence: 1,
1080 projection: {
1081 thread: { id: threadId, title: threadId },
1082 updatedAt: DateTime.makeUnsafe(0),
1083 visibleTurnItems: [],
1084 } as unknown as OrchestrationV2ThreadProjection,
1085 }),
1086 ),
1087 }),
1088 ),
1089 Layer.provide(ServerSettings.layerTest()),
1090 Layer.provide(layerReceiptsTest),
1091 );
1092​
1093 yield* Effect.gen(function* () {
1094 const threads = yield* ThreadManagementService.ThreadManagementService;
1095 const exportThread = (id: string) =>
1096 threads.getThreadTranscript(ThreadId.make(id)).pipe(
1097 Effect.provideService(ServerEnvironment.ServerEnvironmentIdentity, {
1098 getEnvironmentId: Effect.succeed(EnvironmentId.make("environment:export")),
1099 }),
1100 Effect.forkChild({ startImmediately: true }),
1101 );
1102 const a = yield* exportThread("a");
1103 const b = yield* exportThread("b");
1104 const c = yield* exportThread("c");
1105 const d = yield* exportThread("d");
1106 const e = yield* exportThread("e");
1107 const f = yield* exportThread("f");
1108 expect(yield* Queue.takeAll(started)).toEqual(["a", "b"]);
1109​
1110 yield* Fiber.interrupt(c);
1111 yield* Deferred.fail(
1112 gates.get("a")!,
1113 new Orchestrator.OrchestratorProjectionError({ threadId: ThreadId.make("a"), cause: "" }),
1114 );
1115 expect(yield* Queue.take(started)).toBe("d");
1116 yield* Fiber.interrupt(b);
1117 expect(yield* Queue.take(started)).toBe("e");
1118 yield* Deferred.succeed(gates.get("d")!, undefined);
1119 expect(yield* Queue.take(started)).toBe("f");
1120 yield* Deferred.succeed(gates.get("e")!, undefined);
1121 yield* Deferred.succeed(gates.get("f")!, undefined);
1122​
1123 expect((yield* Fiber.await(a))._tag).toBe("Failure");
1124 expect((yield* Fiber.join(d)).threadId).toBe("d");
1125 expect((yield* Fiber.join(e)).threadId).toBe("e");
1126 expect((yield* Fiber.join(f)).threadId).toBe("f");
1127 expect(yield* Queue.size(started)).toBe(0);
1128 }).pipe(Effect.provide(layerTest));
1129 }),