Open History to see the last commit
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 // Nor a workflow run it is a step of.
78 workflowRun: {
79 environmentId: EnvironmentId.make("environment:elsewhere"),
80 runId: "run-1",
81 workflow: "fix",
82 step: "write",
83 },
84 };
85
86 const stamped = ThreadManagementService.withCreationProvenance(command, {
87 createdBy: "user",
88 creationSource: "web",
89 });
90 expect(stamped).toMatchObject({
91 createdBy: "user",
92 creationSource: "web",
93 });
94 expect(stamped).not.toHaveProperty("linkOrigin");
95 expect(stamped).not.toHaveProperty("delegatedFrom");
96 expect(stamped).not.toHaveProperty("initialMessage");
97 expect(stamped).not.toHaveProperty("workflowRun");
98});
99
100const layerReceiptsTest = CommandReceiptStore.layer.pipe(
101 Layer.provide(SqlitePersistence.layerMemory),
102);
103
104const layerDispatchChokepointTest =
105 (settingsLayer: ReturnType<typeof ServerSettings.layerTest>) => (dispatched: Array<string>) =>
106 ThreadManagementService.layer.pipe(
107 Layer.provide(Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({})),
108 Layer.provide(
109 Layer.mock(Orchestrator.OrchestratorV2)({
110 getThreadRecords: () =>
111 Effect.succeed({
112 thread: {
113 id: ThreadId.make("thread:thread-management:chokepoint"),
114 projectId: ProjectId.make("project:thread-management:chokepoint"),
115 deletedAt: null,
116 modelSelection: {
117 instanceId: ProviderInstanceId.make("codex_work"),
118 model: "test",
119 },
120 },
121 } as unknown as OrchestrationV2ThreadProjection),
122 dispatch: (command) =>
123 Effect.sync(() => {
124 dispatched.push(command.type);
125 return { sequence: 1, storedEvents: [] } as never;
126 }),
127 }),
128 ),
129 Layer.provide(settingsLayer),
130 Layer.provideMerge(layerReceiptsTest),
131 );
132
133it.effect(
134 "the dispatch chokepoint refuses a continuation message.dispatch on a project-disabled instance before reaching the orchestrator",
135 () => {
136 const projectId = ProjectId.make("project:thread-management:chokepoint");
137 const threadId = ThreadId.make("thread:thread-management:chokepoint");
138 const instanceId = ProviderInstanceId.make("codex_work");
139 const commandId = CommandId.make("command:thread-management:chokepoint-disabled");
140 const dispatched: Array<string> = [];
141 const layerTest = layerDispatchChokepointTest(
142 ServerSettings.layerTest({
143 providerInstances: { [instanceId]: { driver: "codex", enabled: true } },
144 projectSettingsOverrides: {
145 [projectId]: { providerInstances: { [instanceId]: { enabled: false } } },
146 },
147 }),
148 )(dispatched);
149
150 return Effect.gen(function* () {
151 const threads = yield* ThreadManagementService.ThreadManagementService;
152 const error = yield* Effect.flip(
153 threads.dispatch({
154 type: "message.dispatch",
155 commandId,
156 threadId,
157 messageId: MessageId.make("message:thread-management:chokepoint-disabled"),
158 text: "Background task completed.",
159 attachments: [],
160 dispatchMode: { type: "queue_after_active" },
161 createdBy: "agent",
162 creationSource: "server",
163 }),
164 );
165
166 expect(error).toBeInstanceOf(
167 ThreadManagementService.ThreadManagementProviderInstanceDisabledError,
168 );
169 expect(error).toMatchObject({ projectId, instanceId });
170 expect(dispatched).toEqual([]);
171 }).pipe(Effect.provide(layerTest));
172 },
173);
174
175it.effect(
176 "a replay of an already-accepted command id dispatches despite the instance now being disabled",
177 () => {
178 const projectId = ProjectId.make("project:thread-management:chokepoint");
179 const threadId = ThreadId.make("thread:thread-management:chokepoint");
180 const instanceId = ProviderInstanceId.make("codex_work");
181 const commandId = CommandId.make("command:thread-management:chokepoint-replay");
182 const dispatched: Array<string> = [];
183 const layerTest = layerDispatchChokepointTest(
184 ServerSettings.layerTest({
185 providerInstances: { [instanceId]: { driver: "codex", enabled: true } },
186 projectSettingsOverrides: {
187 [projectId]: { providerInstances: { [instanceId]: { enabled: false } } },
188 },
189 }),
190 )(dispatched);
191
192 return Effect.gen(function* () {
193 const receipts = yield* CommandReceiptStore.CommandReceiptStoreV2;
194 yield* receipts.insertIfAbsent({
195 commandId,
196 threadId,
197 commandType: "message.dispatch",
198 acceptedAt: yield* DateTime.now,
199 resultSequence: 1,
200 status: "accepted",
201 error: null,
202 });
203
204 const threads = yield* ThreadManagementService.ThreadManagementService;
205 yield* threads.dispatch({
206 type: "message.dispatch",
207 commandId,
208 threadId,
209 messageId: MessageId.make("message:thread-management:chokepoint-replay"),
210 text: "Background task completed.",
211 attachments: [],
212 dispatchMode: { type: "queue_after_active" },
213 createdBy: "agent",
214 creationSource: "server",
215 });
216
217 expect(dispatched).toEqual(["message.dispatch"]);
218 }).pipe(Effect.provide(layerTest));
219 },
220);
221
222it.effect.each([
223 { label: "fails a send that starts a turn", running: false },
224 { label: "still steers a running turn", running: true },
225])("sendToThread with a missing worktree that cannot be recreated $label", ({ running }) => {
226 const projectId = ProjectId.make("project:thread-management:worktree-gone");
227 const threadId = ThreadId.make("thread:thread-management:worktree-gone");
228 const dispatched: Array<string> = [];
229 const layerTest = ThreadManagementService.layerWithLegacyImporter.pipe(
230 Layer.provide(
231 Layer.succeed(ThreadWorktreeRestore, {
232 takeRecreated: () => Effect.undefined,
233 restore: () =>
234 Effect.fail(
235 new WorktreeRecreateError({
236 worktreePath: "/worktrees/gone",
237 branch: "t3/gone",
238 cause: new Error("branch_checked_out_in_worktree"),
239 }),
240 ),
241 }),
242 ),
243 Layer.provide(
244 Layer.mock(LegacyV1ThreadImporter.LegacyV1ThreadImporter)({
245 ensureTranscript: () => Effect.succeed({ importedThreadCount: 0, importedMessageCount: 0 }),
246 }),
247 ),
248 Layer.provide(Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({})),
249 Layer.provide(
250 Layer.mock(Orchestrator.OrchestratorV2)({
251 getThreadRecords: () =>
252 Effect.succeed({
253 thread: {
254 id: threadId,
255 projectId,
256 deletedAt: null,
257 archivedAt: null,
258 worktreePath: "/worktrees/gone",
259 branch: "t3/gone",
260 modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "test" },
261 },
262 runs: running
263 ? [
264 {
265 id: RunId.make("run:thread-management:worktree-gone"),
266 status: "running",
267 activeAttemptId: "attempt:thread-management:worktree-gone",
268 },
269 ]
270 : [],
271 providerTurns: running
272 ? [
273 {
274 runAttemptId: "attempt:thread-management:worktree-gone",
275 status: "running",
276 },
277 ]
278 : [],
279 messages: [],
280 turnItems: [],
281 } as unknown as OrchestrationV2ThreadProjection),
282 dispatch: (command) =>
283 Effect.sync(() => {
284 dispatched.push(command.type);
285 return { sequence: 1, storedEvents: [] } as never;
286 }),
287 }),
288 ),
289 Layer.provide(ServerSettings.layerTest()),
290 Layer.provideMerge(layerReceiptsTest),
291 );
292
293 return Effect.gen(function* () {
294 const threads = yield* ThreadManagementService.ThreadManagementService;
295 const error = yield* Effect.flip(
296 threads.sendToThread({
297 projectId,
298 threadId,
299 commandId: CommandId.make("command:thread-management:worktree-gone"),
300 messageId: MessageId.make("message:thread-management:worktree-gone"),
301 text: "Reply with ok.",
302 attachments: [],
303 mode: "auto",
304 createdBy: "agent",
305 creationSource: "mcp",
306 }),
307 );
308 // The mock records no message, so a dispatched send ends in the projection read.
309 expect(error._tag).toBe(
310 running
311 ? "ThreadManagementDurableRunProjectionError"
312 : "ThreadManagementWorktreeRestoreError",
313 );
314 expect(dispatched).toEqual(running ? ["message.dispatch"] : []);
315 }).pipe(Effect.provide(layerTest));
316});
317
318it.effect("waitForThread follows a restart continuation instead of the cut run", () =>
319 Effect.gen(function* () {
320 const projectId = ProjectId.make("project:thread-management:wait-restart");
321 const threadId = ThreadId.make("thread:thread-management:wait-restart");
322 const runId = RunId.make("run:thread-management:wait-restart");
323 const continuationId = RunId.make("run:thread-management:wait-restart:2");
324 const subscribed = yield* Deferred.make<void>();
325 const events = yield* Queue.unbounded<OrchestrationV2StoredEvent>();
326 let runs: Array<{
327 id: RunId;
328 status: OrchestrationV2Run["status"];
329 restartContinuationOfRunId?: RunId;
330 }> = [{ id: runId, status: "cancelled" }];
331 let pending = true;
332 const stored = (sequence: number, event: object) =>
333 ({ sequence, event: { threadId, ...event } }) as unknown as OrchestrationV2StoredEvent;
334 const layerTest = ThreadManagementService.layer.pipe(
335 Layer.provide(Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({})),
336 Layer.provide(
337 Layer.mock(Orchestrator.OrchestratorV2)({
338 getThreadEventSequence: () => Effect.succeed(0),
339 restartContinuationPending: (run) => Effect.succeed(pending && run.id === runId),
340 awaitRestartContinuation: () => Effect.never,
341 streamStoredEventsFrom: (input) =>
342 input?.eventType === "run.updated"
343 ? Stream.fromEffect(Deferred.succeed(subscribed, undefined)).pipe(
344 Stream.drain,
345 Stream.concat(Stream.fromQueue(events)),
346 )
347 : Stream.never,
348 getThreadRecords: () =>
349 Effect.sync(
350 () =>
351 ({
352 thread: { id: threadId, projectId, deletedAt: null },
353 runs,
354 }) as unknown as OrchestrationV2ThreadProjection,
355 ),
356 }),
357 ),
358 Layer.provide(ServerSettings.layerTest()),
359 Layer.provide(layerReceiptsTest),
360 );
361 const service = yield* ThreadManagementService.ThreadManagementService.pipe(
362 Effect.provide(layerTest),
363 );
364 const fiber = yield* service
365 .waitForThread({ projectId, threadId, runId, timeoutMs: 60 * 60 * 1_000 })
366 .pipe(Effect.forkChild);
367 yield* Deferred.await(subscribed);
368 const continuation = { id: continuationId, restartContinuationOfRunId: runId };
369 runs = [...runs, { ...continuation, status: "running" }];
370 pending = false;
371 yield* Queue.offer(
372 events,
373 stored(1, { type: "run.updated", payload: { ...continuation, status: "running" } }),
374 );
375 runs = [runs[0]!, { ...continuation, status: "completed" }];
376 yield* Queue.offer(
377 events,
378 stored(2, { type: "run.updated", payload: { ...continuation, status: "completed" } }),
379 );
380 const result = yield* Fiber.join(fiber);
381
382 expect(result).toMatchObject({
383 timedOut: false,
384 run: { id: continuationId, status: "completed" },
385 });
386 }),
387);
388
389it.effect(
390 "waitForThread without runId skips a queued run cancelled while an earlier run is active",
391 () =>
392 Effect.gen(function* () {
393 const projectId = ProjectId.make("project:thread-management:wait-cancelled-queued");
394 const threadId = ThreadId.make("thread:thread-management:wait-cancelled-queued");
395 const activeRunId = RunId.make("run:thread-management:wait-cancelled-queued:1");
396 const cancelledRunId = RunId.make("run:thread-management:wait-cancelled-queued:2");
397 let subscribed = yield* Deferred.make<void>();
398 const cancellationRead = yield* Deferred.make<void>();
399 const events = yield* Queue.unbounded<OrchestrationV2StoredEvent>();
400 const at = (seconds: number) => DateTime.makeUnsafe(seconds * 1_000);
401 let runs = [
402 {
403 id: activeRunId,
404 ordinal: 1,
405 status: "running" as OrchestrationV2Run["status"],
406 startedAt: at(0),
407 completedAt: null as DateTime.Utc | null,
408 },
409 {
410 id: cancelledRunId,
411 ordinal: 2,
412 status: "queued" as OrchestrationV2Run["status"],
413 startedAt: null,
414 completedAt: null as DateTime.Utc | null,
415 },
416 ];
417 const layerTest = ThreadManagementService.layer.pipe(
418 Layer.provide(Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({})),
419 Layer.provide(
420 Layer.mock(Orchestrator.OrchestratorV2)({
421 getThreadEventSequence: () => Effect.succeed(0),
422 restartContinuationPending: () => Effect.succeed(false),
423 awaitRestartContinuation: () => Effect.never,
424 streamStoredEventsFrom: (input) =>
425 input?.eventType === "run.updated"
426 ? Stream.fromEffect(Deferred.succeed(subscribed, undefined)).pipe(
427 Stream.drain,
428 Stream.concat(Stream.fromQueue(events)),
429 )
430 : Stream.never,
431 getThreadRecords: () =>
432 Effect.gen(function* () {
433 const snapshot = runs;
434 if (snapshot[1]?.status === "cancelled" && snapshot[0]?.status === "running") {
435 yield* Deferred.succeed(cancellationRead, undefined);
436 }
437 return {
438 thread: { id: threadId, projectId, deletedAt: null },
439 runs: snapshot,
440 } as unknown as OrchestrationV2ThreadProjection;
441 }),
442 }),
443 ),
444 Layer.provide(ServerSettings.layerTest()),
445 Layer.provide(layerReceiptsTest),
446 );
447 const service = yield* ThreadManagementService.ThreadManagementService.pipe(
448 Effect.provide(layerTest),
449 );
450
451 const whileQueued = yield* service
452 .waitForThread({ projectId, threadId, timeoutMs: 60 * 60 * 1_000 })
453 .pipe(Effect.forkChild);
454 yield* Deferred.await(subscribed);
455 runs = [runs[0]!, { ...runs[1]!, status: "cancelled", completedAt: at(1) }];
456 yield* Queue.offer(events, {
457 sequence: 1,
458 event: { type: "run.updated", threadId, payload: runs[1] },
459 } as unknown as OrchestrationV2StoredEvent);
460 yield* Deferred.await(cancellationRead);
461 runs = [{ ...runs[0]!, status: "completed", completedAt: at(2) }, runs[1]!];
462 yield* Queue.offer(events, {
463 sequence: 2,
464 event: { type: "run.updated", threadId, payload: runs[0] },
465 } as unknown as OrchestrationV2StoredEvent);
466 expect(yield* Fiber.join(whileQueued)).toMatchObject({
467 timedOut: false,
468 run: { id: activeRunId, status: "completed" },
469 });
470
471 subscribed = yield* Deferred.make<void>();
472 runs = [{ ...runs[0]!, status: "running", completedAt: null }, runs[1]!];
473 const afterCancel = yield* service
474 .waitForThread({ projectId, threadId, timeoutMs: 60 * 60 * 1_000 })
475 .pipe(Effect.forkChild);
476 yield* Effect.race(Deferred.await(subscribed), Fiber.await(afterCancel));
477 expect(yield* Deferred.isDone(subscribed)).toBe(true);
478 runs = [{ ...runs[0]!, status: "completed", completedAt: at(2) }, runs[1]!];
479 yield* Queue.offer(events, {
480 sequence: 3,
481 event: { type: "run.updated", threadId, payload: runs[0] },
482 } as unknown as OrchestrationV2StoredEvent);
483 expect(yield* Fiber.join(afterCancel)).toMatchObject({
484 timedOut: false,
485 run: { id: activeRunId, status: "completed" },
486 });
487
488 const afterCompleted = yield* service.waitForThread({
489 projectId,
490 threadId,
491 timeoutMs: 60 * 60 * 1_000,
492 });
493 expect(afterCompleted).toMatchObject({
494 timedOut: false,
495 run: { id: activeRunId, status: "completed" },
496 });
497 }),
498);
499
500it.effect("waitForThread can wait past an ended run for the thread's delegated work", () =>
501 Effect.gen(function* () {
502 const projectId = ProjectId.make("project:thread-management:wait-delegated");
503 const threadId = ThreadId.make("thread:thread-management:wait-delegated");
504 const runId = RunId.make("run:thread-management:wait-delegated");
505 const wakeRunId = RunId.make("run:thread-management:wait-delegated:wake");
506 const subscribed = yield* Deferred.make<void>();
507 const events = yield* Queue.unbounded<OrchestrationV2StoredEvent>();
508 const at = (seconds: number) => DateTime.makeUnsafe(seconds * 1_000);
509 const run = (id: RunId, ordinal: number, status: OrchestrationV2Run["status"], end: number) =>
510 ({
511 id,
512 ordinal,
513 status,
514 startedAt: at(end - 1),
515 completedAt: status === "running" ? null : at(end),
516 }) as unknown as OrchestrationV2Run;
517 // The run ended, but a task it delegated still runs and will wake the thread.
518 let runs = [run(runId, 1, "completed", 1)];
519 let subagents = [{ status: "running" }];
520 const stored = (sequence: number, event: object) =>
521 ({ sequence, event: { threadId, ...event } }) as unknown as OrchestrationV2StoredEvent;
522 const layerTest = ThreadManagementService.layer.pipe(
523 Layer.provide(Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({})),
524 Layer.provide(
525 Layer.mock(Orchestrator.OrchestratorV2)({
526 getThreadEventSequence: () => Effect.succeed(0),
527 restartContinuationPending: () => Effect.succeed(false),
528 delegatedTaskResultPending: () => Effect.succeed(false),
529 streamStoredEventsFrom: (input) =>
530 input?.eventType === "subagent.updated"
531 ? Stream.fromEffect(Deferred.succeed(subscribed, undefined)).pipe(
532 Stream.drain,
533 Stream.concat(Stream.fromQueue(events)),
534 )
535 : Stream.never,
536 getThreadRecords: () =>
537 Effect.sync(
538 () =>
539 ({
540 thread: { id: threadId, projectId, deletedAt: null },
541 runs,
542 messages: [],
543 subagents,
544 providerThreads: [],
545 }) as unknown as OrchestrationV2ThreadProjection,
546 ),
547 }),
548 ),
549 Layer.provide(ServerSettings.layerTest()),
550 Layer.provide(layerReceiptsTest),
551 );
552 const service = yield* ThreadManagementService.ThreadManagementService.pipe(
553 Effect.provide(layerTest),
554 );
555 // Without the option, the ended run is the answer, as before.
556 expect(
557 yield* service.waitForThread({ projectId, threadId, runId, timeoutMs: 60 * 60 * 1_000 }),
558 ).toMatchObject({ timedOut: false, run: { id: runId } });
559 expect(
560 yield* service.waitForThread({ projectId, threadId, runId, timeoutMs: 60 * 60 * 1_000 }),
561 ).not.toHaveProperty("resultRun");
562
563 const fiber = yield* service
564 .waitForThread({
565 projectId,
566 threadId,
567 runId,
568 timeoutMs: 60 * 60 * 1_000,
569 untilDelegatedWorkSettled: true,
570 })
571 .pipe(Effect.forkChild);
572 // A wait that returns early fails below instead of hanging here.
573 yield* Effect.raceFirst(Deferred.await(subscribed), Fiber.await(fiber));
574 // The task finishes; its delivery wakes the thread, whose next run answers.
575 subagents = [{ status: "completed" }];
576 runs = [...runs, run(wakeRunId, 2, "completed", 3)];
577 yield* Queue.offer(events, stored(1, { type: "subagent.updated", payload: {} }));
578 const result = yield* Fiber.join(fiber);
579
580 expect(result).toMatchObject({
581 timedOut: false,
582 run: { id: runId, status: "completed" },
583 resultRun: { id: wakeRunId, status: "completed" },
584 });
585 }),
586);
587
588it.effect(
589 "a turn that ended without its result is waited past, and a later turn answers for it",
590 () =>
591 Effect.gen(function* () {
592 const projectId = ProjectId.make("project:thread-management:owed");
593 const threadId = ThreadId.make("thread:thread-management:owed");
594 const runId = RunId.make("run:thread-management:owed");
595 const wakeRunId = RunId.make("run:thread-management:owed:wake");
596 const subscribed = yield* Deferred.make<void>();
597 const events = yield* Queue.unbounded<OrchestrationV2StoredEvent>();
598 const outputSchema = { type: "object", required: ["head"] };
599 const run = (id: RunId, ordinal: number, fields: object) =>
600 ({ id, ordinal, ...fields }) as unknown as OrchestrationV2Run;
601 // The agent ended its turn to wait for something, without the result it was asked for.
602 let runs = [run(runId, 1, { status: "completed", outputSchema })];
603 const submitted: Array<unknown> = [];
604 const stored = (sequence: number, event: object) =>
605 ({ sequence, event: { threadId, ...event } }) as unknown as OrchestrationV2StoredEvent;
606 const layerTest = ThreadManagementService.layer.pipe(
607 Layer.provide(Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({})),
608 Layer.provide(
609 Layer.mock(Orchestrator.OrchestratorV2)({
610 getThreadEventSequence: () => Effect.succeed(0),
611 restartContinuationPending: () => Effect.succeed(false),
612 streamStoredEventsFrom: (input) =>
613 input?.eventType === "run.output-submitted"
614 ? Stream.fromEffect(Deferred.succeed(subscribed, undefined)).pipe(
615 Stream.drain,
616 Stream.concat(Stream.fromQueue(events)),
617 )
618 : Stream.never,
619 getThreadRecords: () =>
620 Effect.sync(
621 () =>
622 ({
623 thread: { id: threadId, projectId, deletedAt: null },
624 runs,
625 }) as unknown as OrchestrationV2ThreadProjection,
626 ),
627 dispatch: (command) =>
628 Effect.sync(() => {
629 submitted.push(command);
630 return { sequence: 1 } as never;
631 }),
632 }),
633 ),
634 Layer.provide(ServerSettings.layerTest()),
635 Layer.provide(layerReceiptsTest),
636 );
637 const service = yield* ThreadManagementService.ThreadManagementService.pipe(
638 Effect.provide(layerTest),
639 );
640 const wait = { projectId, threadId, runId, timeoutMs: 60 * 60 * 1_000 };
641 // Without the option the ended turn is the answer, as before.
642 expect(yield* service.waitForThread(wait)).toMatchObject({ timedOut: false });
643 // A turn asked for nothing owes nothing, so the option does not hold it.
644 const plainRunId = RunId.make("run:thread-management:owed:plain");
645 runs = [run(plainRunId, 0, { status: "completed" }), ...runs];
646 expect(
647 yield* Effect.raceFirst(
648 service.waitForThread({ ...wait, runId: plainRunId, untilOutput: true }),
649 Effect.as(Deferred.await(subscribed), "waited for a result"),
650 ),
651 ).toMatchObject({ timedOut: false, run: { id: plainRunId } });
652 runs = runs.slice(1);
653
654 const fiber = yield* service
655 .waitForThread({ ...wait, untilOutput: true })
656 .pipe(Effect.forkChild);
657 yield* Effect.raceFirst(Deferred.await(subscribed), Fiber.await(fiber));
658 // Something wakes the thread. The turn it starts was asked for nothing, and submits anyway.
659 // A request queued behind it asks for a result of its own, and is not the one owed.
660 const queuedRunId = RunId.make("run:thread-management:owed:queued");
661 runs = [
662 ...runs,
663 run(wakeRunId, 2, { status: "running" }),
664 run(queuedRunId, 3, { status: "queued", outputSchema }),
665 ];
666 const accepted = yield* service.submitRunOutput({
667 threadId,
668 commandId: CommandId.make("command:thread-management:owed"),
669 json: '{"head":"abc"}',
670 });
671 expect(accepted.runId).toBe(runId);
672 expect(submitted).toMatchObject([
673 { type: "run.output.submit", runId, value: { head: "abc" } },
674 ]);
675 const output = { value: { head: "abc" }, submittedAt: "2026-01-01T00:00:00.000Z" };
676 runs = [run(runId, 1, { status: "completed", outputSchema, output }), runs[1]!, runs[2]!];
677 yield* Queue.offer(events, stored(1, { type: "run.output-submitted", payload: {} }));
678 expect(yield* Fiber.join(fiber)).toMatchObject({
679 timedOut: false,
680 run: { id: runId, output },
681 });
682
683 // The result is given once: a later plain turn has nothing to submit to.
684 const again = yield* service
685 .submitRunOutput({
686 threadId,
687 commandId: CommandId.make("command:thread-management:owed:again"),
688 json: '{"head":"def"}',
689 })
690 .pipe(Effect.flip);
691 expect(again.message).toContain("not asked for a result");
692 }),
693);
694
695it.effect("waitForThread settles delegated work on a thread rolled back past its only run", () =>
696 Effect.gen(function* () {
697 const projectId = ProjectId.make("project:thread-management:wait-rolled-back");
698 const threadId = ThreadId.make("thread:thread-management:wait-rolled-back");
699 const runId = RunId.make("run:thread-management:wait-rolled-back");
700 const rolledBack = {
701 id: runId,
702 ordinal: 1,
703 status: "rolled_back",
704 startedAt: DateTime.makeUnsafe(0),
705 completedAt: DateTime.makeUnsafe(1_000),
706 } as unknown as OrchestrationV2Run;
707 const layerTest = ThreadManagementService.layer.pipe(
708 Layer.provide(Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({})),
709 Layer.provide(
710 Layer.mock(Orchestrator.OrchestratorV2)({
711 getThreadEventSequence: () => Effect.succeed(0),
712 restartContinuationPending: () => Effect.succeed(false),
713 delegatedTaskResultPending: () => Effect.succeed(false),
714 streamStoredEventsFrom: () => Stream.never,
715 getThreadRecords: () =>
716 Effect.succeed({
717 thread: { id: threadId, projectId, deletedAt: null },
718 runs: [rolledBack],
719 messages: [],
720 subagents: [],
721 providerThreads: [],
722 } as unknown as OrchestrationV2ThreadProjection),
723 }),
724 ),
725 Layer.provide(ServerSettings.layerTest()),
726 Layer.provide(layerReceiptsTest),
727 );
728 const service = yield* ThreadManagementService.ThreadManagementService.pipe(
729 Effect.provide(layerTest),
730 );
731 const fiber = yield* service
732 .waitForThread({
733 projectId,
734 threadId,
735 runId,
736 timeoutMs: 60_000,
737 untilDelegatedWorkSettled: true,
738 })
739 .pipe(Effect.forkChild);
740 // Nothing will ever run there again, so a wait still open runs out here.
741 yield* TestClock.adjust(Duration.millis(60_000));
742 const result = yield* Fiber.join(fiber);
743
744 expect(result).toMatchObject({
745 timedOut: false,
746 run: { id: runId, status: "rolled_back" },
747 resultRun: { id: runId, status: "rolled_back" },
748 });
749 }),
750);
751
752it.effect("waitForThread waits for output only from a run that was asked for one", () =>
753 Effect.gen(function* () {
754 const projectId = ProjectId.make("project:thread-management:wait-output");
755 const threadId = ThreadId.make("thread:thread-management:wait-output");
756 const askedRunId = RunId.make("run:thread-management:wait-output:asked");
757 const plainRunId = RunId.make("run:thread-management:wait-output:plain");
758 const layerTest = ThreadManagementService.layer.pipe(
759 Layer.provide(Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({})),
760 Layer.provide(
761 Layer.mock(Orchestrator.OrchestratorV2)({
762 getThreadEventSequence: () => Effect.succeed(0),
763 restartContinuationPending: () => Effect.succeed(false),
764 streamStoredEventsFrom: () => Stream.never,
765 getThreadRecords: () =>
766 Effect.succeed({
767 thread: { id: threadId, projectId, deletedAt: null },
768 runs: [
769 { id: askedRunId, status: "completed", outputSchema: { type: "object" } },
770 { id: plainRunId, status: "completed" },
771 ],
772 } as unknown as OrchestrationV2ThreadProjection),
773 }),
774 ),
775 Layer.provide(ServerSettings.layerTest()),
776 Layer.provide(layerReceiptsTest),
777 );
778 const service = yield* ThreadManagementService.ThreadManagementService.pipe(
779 Effect.provide(layerTest),
780 );
781 const wait = (runId: RunId) =>
782 service
783 .waitForThread({ projectId, threadId, runId, timeoutMs: 60_000, untilOutput: true })
784 .pipe(Effect.forkChild);
785 const asked = yield* wait(askedRunId);
786 const plain = yield* wait(plainRunId);
787 yield* TestClock.adjust(Duration.millis(60_000));
788
789 // A later turn may still submit the result the first run owes.
790 expect(yield* Fiber.join(asked)).toMatchObject({ timedOut: true, run: { id: askedRunId } });
791 // Nothing can submit one for a run that never asked, so its end is the answer.
792 expect(yield* Fiber.join(plain)).toMatchObject({
793 timedOut: false,
794 run: { id: plainRunId, status: "completed" },
795 });
796 }),
797);
798
799it.effect("waitForThread returns the cut run once its continuation is declined", () =>
800 Effect.gen(function* () {
801 const projectId = ProjectId.make("project:thread-management:wait-declined");
802 const threadId = ThreadId.make("thread:thread-management:wait-declined");
803 const runId = RunId.make("run:thread-management:wait-declined");
804 const subscribed = yield* Deferred.make<void>();
805 const declined = yield* Deferred.make<void>();
806 let pending = true;
807 const layerTest = ThreadManagementService.layer.pipe(
808 Layer.provide(Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({})),
809 Layer.provide(
810 Layer.mock(Orchestrator.OrchestratorV2)({
811 getThreadEventSequence: () => Effect.succeed(0),
812 restartContinuationPending: () => Effect.succeed(pending),
813 awaitRestartContinuation: () => Deferred.await(declined),
814 streamStoredEventsFrom: (input) =>
815 input?.eventType === "run.updated"
816 ? Stream.fromEffect(Deferred.succeed(subscribed, undefined)).pipe(
817 Stream.drain,
818 Stream.concat(Stream.never),
819 )
820 : Stream.never,
821 getThreadRecords: () =>
822 Effect.succeed({
823 thread: { id: threadId, projectId, deletedAt: null },
824 runs: [{ id: runId, status: "cancelled" }],
825 } as unknown as OrchestrationV2ThreadProjection),
826 }),
827 ),
828 Layer.provide(ServerSettings.layerTest()),
829 Layer.provide(layerReceiptsTest),
830 );
831 const service = yield* ThreadManagementService.ThreadManagementService.pipe(
832 Effect.provide(layerTest),
833 );
834 const fiber = yield* service
835 .waitForThread({ projectId, threadId, runId, timeoutMs: 60 * 60 * 1_000 })
836 .pipe(Effect.forkChild);
837 yield* Deferred.await(subscribed);
838 pending = false;
839 yield* Deferred.succeed(declined, undefined);
840 const result = yield* Fiber.join(fiber);
841
842 expect(result).toMatchObject({ timedOut: false, run: { id: runId, status: "cancelled" } });
843 }),
844);
845
846it.effect.each([
847 "live",
848 "no-match",
849 "no-match-clear",
850 "no-session",
851 "unsupported-runtime",
852] as const)(
853 "marks background work awaited on the thread's active provider thread with state %s",
854 (state) =>
855 Effect.gen(function* () {
856 const threadId = ThreadId.make("thread:background-wait");
857 const providerThreadId = ProviderThreadId.make("provider-thread:background-wait");
858 const providerSessionId = ProviderSessionId.make("provider-session:background-wait");
859 const driver = ProviderDriverKind.make("claudeAgent");
860 const now = yield* DateTime.now;
861 const providerThread: OrchestrationV2ProviderThread = {
862 id: providerThreadId,
863 driver,
864 providerInstanceId: ProviderInstanceId.make("claudeAgent"),
865 providerSessionId,
866 appThreadId: threadId,
867 ownerNodeId: null,
868 nativeThreadRef: { driver, nativeId: "native-thread", strength: "strong" },
869 nativeConversationHeadRef: null,
870 status: "idle",
871 firstRunOrdinal: 1,
872 lastRunOrdinal: 1,
873 handoffIds: [],
874 forkedFrom: null,
875 pendingBackgroundTasks: [{ taskId: "tests", kind: "command" }],
876 contextUsage: null,
877 nativeMetadata: null,
878 createdAt: now,
879 updatedAt: now,
880 };
881 const calls: Array<{ providerThreadId: ProviderThreadId; awaited: boolean }> = [];
882 const runtime = {
883 driver,
884 providerSessionId,
885 ...(state === "unsupported-runtime"
886 ? {}
887 : {
888 awaitBackgroundTasks: (input: {
889 readonly providerThread: OrchestrationV2ProviderThread;
890 readonly taskIds: ReadonlyArray<string>;
891 readonly awaited: boolean;
892 }) =>
893 Effect.sync(() => {
894 calls.push({
895 providerThreadId: input.providerThread.id,
896 awaited: input.awaited,
897 });
898 return { matched: input.taskIds.filter((taskId) => taskId === "tests") };
899 }),
900 }),
901 } as unknown as ProviderAdapter.ProviderAdapterV2SessionRuntime;
902 const layerTest = ThreadManagementService.layer.pipe(
903 Layer.provide(
904 Layer.mergeAll(
905 Layer.mock(Orchestrator.OrchestratorV2)({
906 getThreadRecords: () =>
907 Effect.succeed({
908 thread: {
909 id: threadId,
910 deletedAt: null,
911 activeProviderThreadId: providerThreadId,
912 },
913 providerThreads: [providerThread],
914 } as unknown as OrchestrationV2ThreadProjection),
915 }),
916 Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({
917 get: () =>
918 Effect.succeed(state === "no-session" ? Option.none() : Option.some(runtime)),
919 }),
920 ),
921 ),
922 Layer.provide(ServerSettings.layerTest()),
923 Layer.provide(layerReceiptsTest),
924 );
925 const result = yield* Effect.gen(function* () {
926 const service = yield* ThreadManagementService.ThreadManagementService;
927 return yield* service
928 .awaitBackgroundTasks({
929 threadId,
930 taskIds: state.startsWith("no-match") ? ["finished"] : ["tests", "finished"],
931 awaited: state !== "no-match-clear",
932 })
933 .pipe(Effect.result);
934 }).pipe(Effect.provide(Layer.merge(layerTest, ThreadCommandExecutor.layer)));
935
936 if (state === "live") {
937 expect(result).toMatchObject({
938 success: { matched: ["tests"], unmatched: ["finished"] },
939 });
940 expect(calls).toEqual([{ providerThreadId, awaited: true }]);
941 } else if (state === "no-match") {
942 expect(result).toMatchObject({
943 failure: { _tag: "ThreadManagementBackgroundWaitError", reason: "unmatched" },
944 });
945 expect(calls).toEqual([{ providerThreadId, awaited: true }]);
946 } else if (state === "no-match-clear") {
947 expect(result).toMatchObject({ success: { matched: [], unmatched: ["finished"] } });
948 expect(calls).toEqual([{ providerThreadId, awaited: false }]);
949 } else {
950 expect(result).toMatchObject({
951 failure: {
952 _tag: "ThreadManagementBackgroundWaitError",
953 reason: state === "no-session" ? "unavailable" : "unsupported",
954 },
955 });
956 expect(calls).toEqual([]);
957 }
958 }),
959);
960
961it("an unmatched background wait says Workflow IDs already keep the thread working", () => {
962 const error = new ThreadManagementService.ThreadManagementBackgroundWaitError({
963 threadId: ThreadId.make("thread:thread-management:background-wait"),
964 reason: "unmatched",
965 });
966 expect(error.message).toContain("Workflow");
967});
968
969it.effect.each([
970 { status: "completed" as const, followUp: "none", settles: true },
971 { status: "failed" as const, followUp: "none", settles: false },
972 { status: "interrupted" as const, followUp: "none", settles: false },
973 { status: "completed" as const, followUp: "notification", settles: true },
974 { status: "completed" as const, followUp: "replayed-notification", settles: true },
975 { status: "completed" as const, followUp: "delegated", settles: true },
976 { status: "completed" as const, followUp: "failed-notification", settles: false },
977 { status: "completed" as const, followUp: "held-notification", settles: true },
978 { status: "completed" as const, followUp: "user", settles: false },
979 { status: "completed" as const, followUp: "steered-notification", settles: false },
980 // Send now cancels the queued run; its message joins the run that asked to settle.
981 { status: "completed" as const, followUp: "promoted-to-steer", settles: true },
982 // A delegated-completion wake cancelled unstarted because the turn already took the result.
983 { status: "completed" as const, followUp: "cancelled-delegated", settles: true },
984 { status: "completed" as const, followUp: "stopped-delegated", settles: false },
985])("settleAfterRun handles $status with $followUp follow-up", ({ status, followUp, settles }) =>
986 Effect.gen(function* () {
987 const projectId = ProjectId.make("project:thread-management:settle-after-run");
988 const threadId = ThreadId.make("thread:thread-management:settle-after-run");
989 const runId = RunId.make("run:thread-management:settle-after-run");
990 const followUpId = RunId.make(`${runId}:follow-up`);
991 const subscribed = yield* Deferred.make<void>();
992 const events = yield* Queue.unbounded<OrchestrationV2StoredEvent>();
993 const replayRejected = yield* Deferred.make<void>();
994 let sequence = 0;
995 let sequenceReads = 0;
996 let rejectedCommandId: CommandId | undefined;
997 const runs = [{ id: runId, ordinal: 1, status, userMessageId: MessageId.make("original") }];
998 const nextRun = {
999 id: followUpId,
1000 ordinal: 2,
1001 status: "running" as OrchestrationV2Run["status"],
1002 userMessageId: MessageId.make("follow-up"),
1003 startedAt: followUp === "stopped-delegated" ? "2026-01-01T00:00:00.000Z" : null,
1004 };
1005 const dispatched: Array<string> = [];
1006 // The notification starts after the completed run was observed, before settlement commits.
1007 let raced = false;
1008 const layerTest = ThreadManagementService.layer.pipe(
1009 Layer.provide(Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({})),
1010 Layer.provide(
1011 Layer.mock(Orchestrator.OrchestratorV2)({
1012 getThreadEventSequence: () =>
1013 Effect.sync(() => {
1014 if (followUp === "replayed-notification" && sequenceReads++ === 2) sequence = 1;
1015 return sequence;
1016 }),
1017 restartContinuationPending: () => Effect.succeed(false),
1018 streamStoredEventsFrom: () =>
1019 Stream.fromEffect(Deferred.succeed(subscribed, undefined)).pipe(
1020 Stream.drain,
1021 Stream.concat(Stream.fromQueue(events)),
1022 ),
1023 getThreadRecords: (_threadId, _fields, filter) =>
1024 Effect.sync(
1025 () =>
1026 ({
1027 thread: { id: threadId, projectId, deletedAt: null },
1028 runs: raced ? [...runs, nextRun] : runs,
1029 turnItems: [],
1030 messages: [
1031 { id: MessageId.make("original"), runId, role: "user" as const },
1032 {
1033 id: nextRun.userMessageId,
1034 runId: followUp === "promoted-to-steer" ? runId : followUpId,
1035 role: "user" as const,
1036 ...(followUp.endsWith("notification") ? { notification: {} } : {}),
1037 ...(followUp.endsWith("delegated") ? { delegatedCompletion: {} } : {}),
1038 },
1039 { id: MessageId.make("reply"), runId: followUpId, role: "assistant" as const },
1040 ...(followUp === "steered-notification"
1041 ? [
1042 {
1043 id: MessageId.make("user-steer"),
1044 runId: followUpId,
1045 role: "user" as const,
1046 },
1047 ]
1048 : []),
1049 ].filter(
1050 (message) =>
1051 (filter?.messageIds === undefined ||
1052 filter.messageIds.includes(message.id)) &&
1053 (filter?.messageRunIds === undefined ||
1054 filter.messageRunIds.includes(message.runId)) &&
1055 (filter?.messageRoles === undefined ||
1056 filter.messageRoles.includes(message.role)),
1057 ),
1058 }) as unknown as OrchestrationV2ThreadProjection,
1059 ),
1060 dispatch: (command) =>
1061 Effect.gen(function* () {
1062 if (followUp !== "none" && !raced) {
1063 raced = true;
1064 rejectedCommandId = command.commandId;
1065 return yield* new Orchestrator.OrchestratorDispatchError({
1066 commandId: command.commandId,
1067 commandType: command.type,
1068 cause: "Thread is still running",
1069 });
1070 }
1071 if (followUp === "replayed-notification" && command.commandId === rejectedCommandId) {
1072 yield* Deferred.succeed(replayRejected, undefined);
1073 return yield* new Orchestrator.OrchestratorCommandPreviouslyRejectedError({
1074 commandId: command.commandId,
1075 commandType: command.type,
1076 detail: "Thread is still running",
1077 });
1078 }
1079 dispatched.push(command.type);
1080 return { sequence: 1, storedEvents: [] } as never;
1081 }),
1082 }),
1083 ),
1084 Layer.provide(ServerSettings.layerTest()),
1085 Layer.provide(layerReceiptsTest),
1086 );
1087 const service = yield* ThreadManagementService.ThreadManagementService.pipe(
1088 Effect.provide(layerTest),
1089 );
1090 const fiber = yield* service
1091 .settleAfterRun({ projectId, threadId, runId })
1092 .pipe(Effect.forkChild);
1093 if (followUp !== "none") {
1094 yield* Deferred.await(subscribed);
1095 expect(dispatched).toEqual([]);
1096 nextRun.status =
1097 followUp === "failed-notification"
1098 ? "failed"
1099 : followUp === "held-notification"
1100 ? "queued"
1101 : followUp === "promoted-to-steer" || followUp.endsWith("ed-delegated")
1102 ? "cancelled"
1103 : "completed";
1104 yield* Queue.offer(events, {
1105 sequence: 1,
1106 event: { type: "run.updated", threadId, payload: nextRun },
1107 } as unknown as OrchestrationV2StoredEvent);
1108 }
1109 if (followUp === "replayed-notification") {
1110 yield* Deferred.await(replayRejected);
1111 expect(dispatched).toEqual([]);
1112 sequence = 2;
1113 yield* Queue.offer(events, {
1114 sequence,
1115 event: { type: "run.updated", threadId, payload: nextRun },
1116 } as unknown as OrchestrationV2StoredEvent);
1117 }
1118 yield* Fiber.join(fiber);
1119 expect(dispatched).toEqual(settles ? ["thread.settle"] : []);
1120 }),
1121);
1122
1123// The agent reads a message steered in after it asked to settle and ends on a question.
1124it.effect.each(["steer", "promoted_queued_to_steer"] as const)(
1125 "settleAfterRun keeps the thread open after a %s read once the settle was requested",
1126 (inputIntent) =>
1127 Effect.gen(function* () {
1128 const projectId = ProjectId.make("project:thread-management:settle-after-steer");
1129 const threadId = ThreadId.make("thread:thread-management:settle-after-steer");
1130 const runId = RunId.make("run:thread-management:settle-after-steer");
1131 yield* TestClock.adjust(Duration.millis(60_000));
1132 const dispatched: Array<string> = [];
1133 const layerTest = ThreadManagementService.layer.pipe(
1134 Layer.provide(Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({})),
1135 Layer.provide(
1136 Layer.mock(Orchestrator.OrchestratorV2)({
1137 getThreadEventSequence: () => Effect.succeed(0),
1138 restartContinuationPending: () => Effect.succeed(false),
1139 streamStoredEventsFrom: () => Stream.empty,
1140 getThreadRecords: () =>
1141 Effect.succeed({
1142 thread: { id: threadId, projectId, deletedAt: null },
1143 runs: [{ id: runId, ordinal: 1, status: "completed", userMessageId: "original" }],
1144 messages: [
1145 { id: "original", runId, role: "user" },
1146 { id: "steered", runId, role: "user" },
1147 ],
1148 turnItems: [
1149 {
1150 runId,
1151 type: "user_message",
1152 inputIntent,
1153 status: "completed",
1154 createdAt: "1970-01-01T00:01:30.000Z",
1155 completedAt: "1970-01-01T00:01:30.000Z",
1156 },
1157 ],
1158 } as unknown as OrchestrationV2ThreadProjection),
1159 dispatch: (command) =>
1160 Effect.sync(() => {
1161 dispatched.push(command.type);
1162 return { sequence: 1, storedEvents: [] } as never;
1163 }),
1164 }),
1165 ),
1166 Layer.provide(ServerSettings.layerTest()),
1167 Layer.provide(layerReceiptsTest),
1168 );
1169 const service = yield* ThreadManagementService.ThreadManagementService.pipe(
1170 Effect.provide(layerTest),
1171 );
1172 yield* service.settleAfterRun({ projectId, threadId, runId });
1173 expect(dispatched).toEqual([]);
1174 }),
1175);
1176
1177it.effect.each([
1178 {
1179 name: "kills the thread's own agent and ends its turn",
1180 others: [] as ReadonlyArray<string>,
1181 killed: true,
1182 expected: { outcome: "killed", sharedWithThreadIds: [] },
1183 teardown: ["release"],
1184 },
1185 {
1186 name: "keeps a process another working thread shares and only ends this turn",
1187 others: ["thread:thread-management:force-stop:other"],
1188 killed: false,
1189 expected: {
1190 outcome: "shared",
1191 sharedWithThreadIds: ["thread:thread-management:force-stop:other"],
1192 },
1193 teardown: ["detach"],
1194 },
1195 {
1196 name: "still settles a finished run's background work in a shared process",
1197 others: ["thread:thread-management:force-stop:other"],
1198 killed: false,
1199 settledRun: true,
1200 expected: {
1201 outcome: "shared",
1202 sharedWithThreadIds: ["thread:thread-management:force-stop:other"],
1203 },
1204 teardown: ["detach"],
1205 },
1206 {
1207 name: "detaches when a sibling starts a turn just before the session is released",
1208 others: [] as ReadonlyArray<string>,
1209 killed: false,
1210 siblingBusy: true,
1211 expected: { outcome: "shared", sharedWithThreadIds: [] },
1212 teardown: ["release", "detach"],
1213 },
1214 {
1215 name: "reports a teardown that has not finished in time as still releasing",
1216 others: [] as ReadonlyArray<string>,
1217 killed: false,
1218 releaseHangs: true,
1219 expected: { outcome: "releasing", sharedWithThreadIds: [] },
1220 teardown: ["release"],
1221 },
1222])("Force stop $name", ({ others, killed, expected, teardown, ...row }) =>
1223 Effect.gen(function* () {
1224 const threadId = ThreadId.make("thread:thread-management:force-stop");
1225 const providerSessionId = ProviderSessionId.make("provider-session:force-stop");
1226 const providerThreadId = ProviderThreadId.make("provider-thread:force-stop");
1227 const runId = RunId.make("run:thread-management:force-stop");
1228 const dispatched: Array<OrchestrationV2Command | { readonly type: string }> = [];
1229 const teardowns: Array<string> = [];
1230 const tornDown = yield* Deferred.make<void>();
1231 const layerTest = ThreadManagementService.layer.pipe(
1232 Layer.provide(
1233 Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({
1234 isLive: () => Effect.succeed(true),
1235 otherWorkingThreads: () => Effect.succeed(others.map((id) => ThreadId.make(id))),
1236 releaseUnlessBusy: () =>
1237 Effect.sync(() => teardowns.push("release")).pipe(
1238 Effect.andThen(
1239 "releaseHangs" in row ? Effect.never : Effect.succeed(!("siblingBusy" in row)),
1240 ),
1241 ),
1242 detach: () =>
1243 Effect.sync(() => teardowns.push("detach")).pipe(
1244 Effect.andThen(Deferred.succeed(tornDown, undefined)),
1245 Effect.asVoid,
1246 ),
1247 }),
1248 ),
1249 Layer.provide(
1250 Layer.mock(Orchestrator.OrchestratorV2)({
1251 getThreadRecords: () =>
1252 Effect.succeed({
1253 thread: { id: threadId, deletedAt: null },
1254 runs: [
1255 {
1256 id: runId,
1257 ordinal: 1,
1258 status: "settledRun" in row ? "completed" : "running",
1259 activeAttemptId: "attempt",
1260 },
1261 // A queued follow-up neither supersedes the request nor becomes the target.
1262 { id: RunId.make("run:queued-follow-up"), ordinal: 2, status: "queued" },
1263 ],
1264 providerThreads: [{ id: providerThreadId, appThreadId: threadId, providerSessionId }],
1265 providerTurns: [
1266 {
1267 id: "provider-turn:force-stop",
1268 providerThreadId,
1269 runAttemptId: "attempt",
1270 status: "settledRun" in row ? "completed" : "running",
1271 },
1272 ],
1273 } as unknown as OrchestrationV2ThreadProjection),
1274 dispatch: (command) =>
1275 Effect.sync(() => {
1276 dispatched.push(command);
1277 return { sequence: 1, storedEvents: [] } as never;
1278 }),
1279 }),
1280 ),
1281 Layer.provide(
1282 Layer.succeed(AgentScope, {
1283 ...AgentScope.defaultValue(),
1284 kill: () => Effect.succeed(killed),
1285 }),
1286 ),
1287 Layer.provide(ServerSettings.layerTest()),
1288 Layer.provide(layerReceiptsTest),
1289 );
1290 yield* Effect.gen(function* () {
1291 const service = yield* ThreadManagementService.ThreadManagementService;
1292 const stopping = yield* service.forceStopThread({ threadId, runId }).pipe(Effect.forkChild);
1293 yield* TestClock.adjust("10 seconds");
1294 expect(yield* Fiber.join(stopping)).toEqual(expected);
1295 expect(dispatched).toMatchObject([
1296 {
1297 type: "thread.background-work.settle",
1298 providerThreadId,
1299 reason: "Force stopped by user",
1300 },
1301 ]);
1302 if (teardown.at(-1) === "detach") yield* Deferred.await(tornDown);
1303 expect(teardowns).toEqual(teardown);
1304 }).pipe(Effect.provide(layerTest));
1305 }),
1306);
1307
1308it.effect("Force stop refuses once a newer run has started, before killing anything", () =>
1309 Effect.gen(function* () {
1310 const threadId = ThreadId.make("thread:thread-management:force-stop-superseded");
1311 let killed = false;
1312 const layerTest = ThreadManagementService.layer.pipe(
1313 Layer.provide(Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({})),
1314 Layer.provide(
1315 Layer.mock(Orchestrator.OrchestratorV2)({
1316 getThreadRecords: () =>
1317 Effect.succeed({
1318 thread: { id: threadId, deletedAt: null },
1319 runs: [
1320 { id: RunId.make("run:stopped"), ordinal: 1, status: "running" },
1321 { id: RunId.make("run:newer"), ordinal: 2, status: "running" },
1322 ],
1323 providerThreads: [],
1324 providerTurns: [],
1325 } as unknown as OrchestrationV2ThreadProjection),
1326 }),
1327 ),
1328 Layer.provide(
1329 Layer.succeed(AgentScope, {
1330 ...AgentScope.defaultValue(),
1331 kill: () => Effect.sync(() => (killed = true)),
1332 }),
1333 ),
1334 Layer.provide(ServerSettings.layerTest()),
1335 Layer.provide(layerReceiptsTest),
1336 );
1337 const error = yield* Effect.gen(function* () {
1338 const service = yield* ThreadManagementService.ThreadManagementService;
1339 return yield* Effect.flip(
1340 service.forceStopThread({ threadId, runId: RunId.make("run:stopped") }),
1341 );
1342 }).pipe(Effect.provide(layerTest));
1343 expect(error.reason).toBe("superseded");
1344 expect(killed).toBe(false);
1345 }),
1346);
1347
1348it.effect(
1349 "admits two transcript exports at a time and frees a slot on failure or interruption",
1350 () =>
1351 Effect.gen(function* () {
1352 const started = yield* Queue.unbounded<string>();
1353 const gates = new Map(
1354 ["a", "b", "c", "d", "e", "f"].map((id) => [
1355 id,
1356 Deferred.makeUnsafe<void, Orchestrator.OrchestratorV2Error>(),
1357 ]),
1358 );
1359 const layerTest = ThreadManagementService.layer.pipe(
1360 Layer.provide(Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({})),
1361 Layer.provide(
1362 Layer.mock(Orchestrator.OrchestratorV2)({
1363 getTranscriptByteFloor: () => Effect.succeed(0),
1364 getThreadSnapshot: (threadId) =>
1365 Queue.offer(started, threadId).pipe(
1366 Effect.andThen(Deferred.await(gates.get(threadId)!)),
1367 Effect.as({
1368 schemaVersion: 1,
1369 snapshotSequence: 1,
1370 projection: {
1371 thread: { id: threadId, title: threadId },
1372 updatedAt: DateTime.makeUnsafe(0),
1373 visibleTurnItems: [],
1374 } as unknown as OrchestrationV2ThreadProjection,
1375 }),
1376 ),
1377 }),
1378 ),
1379 Layer.provide(ServerSettings.layerTest()),
1380 Layer.provide(layerReceiptsTest),
1381 );
1382
1383 yield* Effect.gen(function* () {
1384 const threads = yield* ThreadManagementService.ThreadManagementService;
1385 const exportThread = (id: string) =>
1386 threads.getThreadTranscript(ThreadId.make(id)).pipe(
1387 Effect.provideService(ServerEnvironment.ServerEnvironmentIdentity, {
1388 getEnvironmentId: Effect.succeed(EnvironmentId.make("environment:export")),
1389 }),
1390 Effect.forkChild({ startImmediately: true }),
1391 );
1392 const a = yield* exportThread("a");
1393 const b = yield* exportThread("b");
1394 const c = yield* exportThread("c");
1395 const d = yield* exportThread("d");
1396 const e = yield* exportThread("e");
1397 const f = yield* exportThread("f");
1398 expect(yield* Queue.takeAll(started)).toEqual(["a", "b"]);
1399
1400 yield* Fiber.interrupt(c);
1401 yield* Deferred.fail(
1402 gates.get("a")!,
1403 new Orchestrator.OrchestratorProjectionError({ threadId: ThreadId.make("a"), cause: "" }),
1404 );
1405 expect(yield* Queue.take(started)).toBe("d");
1406 yield* Fiber.interrupt(b);
1407 expect(yield* Queue.take(started)).toBe("e");
1408 yield* Deferred.succeed(gates.get("d")!, undefined);
1409 expect(yield* Queue.take(started)).toBe("f");
1410 yield* Deferred.succeed(gates.get("e")!, undefined);
1411 yield* Deferred.succeed(gates.get("f")!, undefined);
1412
1413 expect((yield* Fiber.await(a))._tag).toBe("Failure");
1414 expect((yield* Fiber.join(d)).threadId).toBe("d");
1415 expect((yield* Fiber.join(e)).threadId).toBe("e");
1416 expect((yield* Fiber.join(f)).threadId).toBe("f");
1417 expect(yield* Queue.size(started)).toBe(0);
1418 }).pipe(Effect.provide(layerTest));
1419 }),
1420);