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

ThreadManagementService.test.ts

1,245 lines50.2 KB

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