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