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