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