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 ServerSettings from "../serverSettings.ts";
33import * as SqlitePersistence from "../persistence/Sqlite.ts";
34import * as CommandReceiptStore from "./CommandReceiptStore.ts";
35import * as Orchestrator from "./Orchestrator.ts";
36import * as ProviderSessionManager from "./ProviderSessionManager.ts";
37import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
38import * as ThreadManagementService from "./ThreadManagementService.ts";
39import * as ThreadCommandExecutor from "./ThreadCommandExecutor.ts";
40
41it("stamps authoritative provenance on commands that create threads or messages", () => {
42 const command: OrchestrationV2Command = {
43 type: "thread.create",
44 createdBy: "agent",
45 creationSource: "mcp",
46 commandId: CommandId.make("command:thread-management:create"),
47 threadId: ThreadId.make("thread:thread-management:create"),
48 projectId: ProjectId.make("project:thread-management"),
49 title: "Thread management",
50 modelSelection: {
51 instanceId: ProviderInstanceId.make("codex"),
52 model: "gpt-5-codex",
53 },
54 runtimeMode: "full-access",
55 interactionMode: "default",
56 branch: null,
57 worktreePath: null,
58 // A client cannot claim a linked environment's origin, or a parent there.
59 linkOrigin: { sessionId: "forged", label: "Somewhere else" },
60 delegatedFrom: {
61 environmentId: EnvironmentId.make("environment:elsewhere"),
62 threadId: ThreadId.make("thread:elsewhere"),
63 title: "Somewhere else",
64 },
65 };
66
67 const stamped = ThreadManagementService.withCreationProvenance(command, {
68 createdBy: "user",
69 creationSource: "web",
70 });
71 expect(stamped).toMatchObject({
72 createdBy: "user",
73 creationSource: "web",
74 });
75 expect(stamped).not.toHaveProperty("linkOrigin");
76 expect(stamped).not.toHaveProperty("delegatedFrom");
77});
78
79const layerReceiptsTest = CommandReceiptStore.layer.pipe(
80 Layer.provide(SqlitePersistence.layerMemory),
81);
82
83const layerDispatchChokepointTest =
84 (settingsLayer: ReturnType<typeof ServerSettings.layerTest>) => (dispatched: Array<string>) =>
85 ThreadManagementService.layer.pipe(
86 Layer.provide(Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({})),
87 Layer.provide(
88 Layer.mock(Orchestrator.OrchestratorV2)({
89 getThreadRecords: () =>
90 Effect.succeed({
91 thread: {
92 id: ThreadId.make("thread:thread-management:chokepoint"),
93 projectId: ProjectId.make("project:thread-management:chokepoint"),
94 deletedAt: null,
95 modelSelection: {
96 instanceId: ProviderInstanceId.make("codex_work"),
97 model: "test",
98 },
99 },
100 } as unknown as OrchestrationV2ThreadProjection),
101 dispatch: (command) =>
102 Effect.sync(() => {
103 dispatched.push(command.type);
104 return { sequence: 1, storedEvents: [] } as never;
105 }),
106 }),
107 ),
108 Layer.provide(settingsLayer),
109 Layer.provideMerge(layerReceiptsTest),
110 );
111
112it.effect(
113 "the dispatch chokepoint refuses a continuation message.dispatch on a project-disabled instance before reaching the orchestrator",
114 () => {
115 const projectId = ProjectId.make("project:thread-management:chokepoint");
116 const threadId = ThreadId.make("thread:thread-management:chokepoint");
117 const instanceId = ProviderInstanceId.make("codex_work");
118 const commandId = CommandId.make("command:thread-management:chokepoint-disabled");
119 const dispatched: Array<string> = [];
120 const layerTest = layerDispatchChokepointTest(
121 ServerSettings.layerTest({
122 providerInstances: { [instanceId]: { driver: "codex", enabled: true } },
123 projectSettingsOverrides: {
124 [projectId]: { providerInstances: { [instanceId]: { enabled: false } } },
125 },
126 }),
127 )(dispatched);
128
129 return Effect.gen(function* () {
130 const threads = yield* ThreadManagementService.ThreadManagementService;
131 const error = yield* Effect.flip(
132 threads.dispatch({
133 type: "message.dispatch",
134 commandId,
135 threadId,
136 messageId: MessageId.make("message:thread-management:chokepoint-disabled"),
137 text: "Background task completed.",
138 attachments: [],
139 dispatchMode: { type: "queue_after_active" },
140 createdBy: "agent",
141 creationSource: "server",
142 }),
143 );
144
145 expect(error).toBeInstanceOf(
146 ThreadManagementService.ThreadManagementProviderInstanceDisabledError,
147 );
148 expect(error).toMatchObject({ projectId, instanceId });
149 expect(dispatched).toEqual([]);
150 }).pipe(Effect.provide(layerTest));
151 },
152);
153
154it.effect(
155 "a replay of an already-accepted command id dispatches despite the instance now being disabled",
156 () => {
157 const projectId = ProjectId.make("project:thread-management:chokepoint");
158 const threadId = ThreadId.make("thread:thread-management:chokepoint");
159 const instanceId = ProviderInstanceId.make("codex_work");
160 const commandId = CommandId.make("command:thread-management:chokepoint-replay");
161 const dispatched: Array<string> = [];
162 const layerTest = layerDispatchChokepointTest(
163 ServerSettings.layerTest({
164 providerInstances: { [instanceId]: { driver: "codex", enabled: true } },
165 projectSettingsOverrides: {
166 [projectId]: { providerInstances: { [instanceId]: { enabled: false } } },
167 },
168 }),
169 )(dispatched);
170
171 return Effect.gen(function* () {
172 const receipts = yield* CommandReceiptStore.CommandReceiptStoreV2;
173 yield* receipts.insertIfAbsent({
174 commandId,
175 threadId,
176 commandType: "message.dispatch",
177 acceptedAt: yield* DateTime.now,
178 resultSequence: 1,
179 status: "accepted",
180 error: null,
181 });
182
183 const threads = yield* ThreadManagementService.ThreadManagementService;
184 yield* threads.dispatch({
185 type: "message.dispatch",
186 commandId,
187 threadId,
188 messageId: MessageId.make("message:thread-management:chokepoint-replay"),
189 text: "Background task completed.",
190 attachments: [],
191 dispatchMode: { type: "queue_after_active" },
192 createdBy: "agent",
193 creationSource: "server",
194 });
195
196 expect(dispatched).toEqual(["message.dispatch"]);
197 }).pipe(Effect.provide(layerTest));
198 },
199);
200
201it.effect("waitForThread follows a restart continuation instead of the cut run", () =>
202 Effect.gen(function* () {
203 const projectId = ProjectId.make("project:thread-management:wait-restart");
204 const threadId = ThreadId.make("thread:thread-management:wait-restart");
205 const runId = RunId.make("run:thread-management:wait-restart");
206 const continuationId = RunId.make("run:thread-management:wait-restart:2");
207 const subscribed = yield* Deferred.make<void>();
208 const events = yield* Queue.unbounded<OrchestrationV2StoredEvent>();
209 let runs: Array<{
210 id: RunId;
211 status: OrchestrationV2Run["status"];
212 restartContinuationOfRunId?: RunId;
213 }> = [{ id: runId, status: "cancelled" }];
214 let pending = true;
215 const stored = (sequence: number, event: object) =>
216 ({ sequence, event: { threadId, ...event } }) as unknown as OrchestrationV2StoredEvent;
217 const layerTest = ThreadManagementService.layer.pipe(
218 Layer.provide(Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({})),
219 Layer.provide(
220 Layer.mock(Orchestrator.OrchestratorV2)({
221 getThreadEventSequence: () => Effect.succeed(0),
222 restartContinuationPending: (run) => Effect.succeed(pending && run.id === runId),
223 awaitRestartContinuation: () => Effect.never,
224 streamStoredEventsFrom: (input) =>
225 input?.eventType === "run.updated"
226 ? Stream.fromEffect(Deferred.succeed(subscribed, undefined)).pipe(
227 Stream.drain,
228 Stream.concat(Stream.fromQueue(events)),
229 )
230 : Stream.never,
231 getThreadRecords: () =>
232 Effect.sync(
233 () =>
234 ({
235 thread: { id: threadId, projectId, deletedAt: null },
236 runs,
237 }) as unknown as OrchestrationV2ThreadProjection,
238 ),
239 }),
240 ),
241 Layer.provide(ServerSettings.layerTest()),
242 Layer.provide(layerReceiptsTest),
243 );
244 const service = yield* ThreadManagementService.ThreadManagementService.pipe(
245 Effect.provide(layerTest),
246 );
247 const fiber = yield* service
248 .waitForThread({ projectId, threadId, runId, timeoutMs: 60 * 60 * 1_000 })
249 .pipe(Effect.forkChild);
250 yield* Deferred.await(subscribed);
251 const continuation = { id: continuationId, restartContinuationOfRunId: runId };
252 runs = [...runs, { ...continuation, status: "running" }];
253 pending = false;
254 yield* Queue.offer(
255 events,
256 stored(1, { type: "run.updated", payload: { ...continuation, status: "running" } }),
257 );
258 runs = [runs[0]!, { ...continuation, status: "completed" }];
259 yield* Queue.offer(
260 events,
261 stored(2, { type: "run.updated", payload: { ...continuation, status: "completed" } }),
262 );
263 const result = yield* Fiber.join(fiber);
264
265 expect(result).toMatchObject({
266 timedOut: false,
267 run: { id: continuationId, status: "completed" },
268 });
269 }),
270);
271
272it.effect("waitForThread can wait past an ended run for the thread's delegated work", () =>
273 Effect.gen(function* () {
274 const projectId = ProjectId.make("project:thread-management:wait-delegated");
275 const threadId = ThreadId.make("thread:thread-management:wait-delegated");
276 const runId = RunId.make("run:thread-management:wait-delegated");
277 const wakeRunId = RunId.make("run:thread-management:wait-delegated:wake");
278 const subscribed = yield* Deferred.make<void>();
279 const events = yield* Queue.unbounded<OrchestrationV2StoredEvent>();
280 const at = (seconds: number) => DateTime.makeUnsafe(seconds * 1_000);
281 const run = (id: RunId, ordinal: number, status: OrchestrationV2Run["status"], end: number) =>
282 ({
283 id,
284 ordinal,
285 status,
286 startedAt: at(end - 1),
287 completedAt: status === "running" ? null : at(end),
288 }) as unknown as OrchestrationV2Run;
289 // The run ended, but a task it delegated still runs and will wake the thread.
290 let runs = [run(runId, 1, "completed", 1)];
291 let subagents = [{ status: "running" }];
292 const stored = (sequence: number, event: object) =>
293 ({ sequence, event: { threadId, ...event } }) as unknown as OrchestrationV2StoredEvent;
294 const layerTest = ThreadManagementService.layer.pipe(
295 Layer.provide(Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({})),
296 Layer.provide(
297 Layer.mock(Orchestrator.OrchestratorV2)({
298 getThreadEventSequence: () => Effect.succeed(0),
299 restartContinuationPending: () => Effect.succeed(false),
300 delegatedTaskResultPending: () => Effect.succeed(false),
301 streamStoredEventsFrom: (input) =>
302 input?.eventType === "subagent.updated"
303 ? Stream.fromEffect(Deferred.succeed(subscribed, undefined)).pipe(
304 Stream.drain,
305 Stream.concat(Stream.fromQueue(events)),
306 )
307 : Stream.never,
308 getThreadRecords: () =>
309 Effect.sync(
310 () =>
311 ({
312 thread: { id: threadId, projectId, deletedAt: null },
313 runs,
314 messages: [],
315 subagents,
316 providerThreads: [],
317 }) as unknown as OrchestrationV2ThreadProjection,
318 ),
319 }),
320 ),
321 Layer.provide(ServerSettings.layerTest()),
322 Layer.provide(layerReceiptsTest),
323 );
324 const service = yield* ThreadManagementService.ThreadManagementService.pipe(
325 Effect.provide(layerTest),
326 );
327 // Without the option, the ended run is the answer, as before.
328 expect(
329 yield* service.waitForThread({ projectId, threadId, runId, timeoutMs: 60 * 60 * 1_000 }),
330 ).toMatchObject({ timedOut: false, run: { id: runId } });
331 expect(
332 yield* service.waitForThread({ projectId, threadId, runId, timeoutMs: 60 * 60 * 1_000 }),
333 ).not.toHaveProperty("resultRun");
334
335 const fiber = yield* service
336 .waitForThread({
337 projectId,
338 threadId,
339 runId,
340 timeoutMs: 60 * 60 * 1_000,
341 untilDelegatedWorkSettled: true,
342 })
343 .pipe(Effect.forkChild);
344 // A wait that returns early fails below instead of hanging here.
345 yield* Effect.raceFirst(Deferred.await(subscribed), Fiber.await(fiber));
346 // The task finishes; its delivery wakes the thread, whose next run answers.
347 subagents = [{ status: "completed" }];
348 runs = [...runs, run(wakeRunId, 2, "completed", 3)];
349 yield* Queue.offer(events, stored(1, { type: "subagent.updated", payload: {} }));
350 const result = yield* Fiber.join(fiber);
351
352 expect(result).toMatchObject({
353 timedOut: false,
354 run: { id: runId, status: "completed" },
355 resultRun: { id: wakeRunId, status: "completed" },
356 });
357 }),
358);
359
360it.effect("waitForThread settles delegated work on a thread rolled back past its only run", () =>
361 Effect.gen(function* () {
362 const projectId = ProjectId.make("project:thread-management:wait-rolled-back");
363 const threadId = ThreadId.make("thread:thread-management:wait-rolled-back");
364 const runId = RunId.make("run:thread-management:wait-rolled-back");
365 const rolledBack = {
366 id: runId,
367 ordinal: 1,
368 status: "rolled_back",
369 startedAt: DateTime.makeUnsafe(0),
370 completedAt: DateTime.makeUnsafe(1_000),
371 } as unknown as OrchestrationV2Run;
372 const layerTest = ThreadManagementService.layer.pipe(
373 Layer.provide(Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({})),
374 Layer.provide(
375 Layer.mock(Orchestrator.OrchestratorV2)({
376 getThreadEventSequence: () => Effect.succeed(0),
377 restartContinuationPending: () => Effect.succeed(false),
378 delegatedTaskResultPending: () => Effect.succeed(false),
379 streamStoredEventsFrom: () => Stream.never,
380 getThreadRecords: () =>
381 Effect.succeed({
382 thread: { id: threadId, projectId, deletedAt: null },
383 runs: [rolledBack],
384 messages: [],
385 subagents: [],
386 providerThreads: [],
387 } as unknown as OrchestrationV2ThreadProjection),
388 }),
389 ),
390 Layer.provide(ServerSettings.layerTest()),
391 Layer.provide(layerReceiptsTest),
392 );
393 const service = yield* ThreadManagementService.ThreadManagementService.pipe(
394 Effect.provide(layerTest),
395 );
396 const fiber = yield* service
397 .waitForThread({
398 projectId,
399 threadId,
400 runId,
401 timeoutMs: 60_000,
402 untilDelegatedWorkSettled: true,
403 })
404 .pipe(Effect.forkChild);
405 // Nothing will ever run there again, so a wait still open runs out here.
406 yield* TestClock.adjust(Duration.millis(60_000));
407 const result = yield* Fiber.join(fiber);
408
409 expect(result).toMatchObject({
410 timedOut: false,
411 run: { id: runId, status: "rolled_back" },
412 resultRun: { id: runId, status: "rolled_back" },
413 });
414 }),
415);
416
417it.effect("waitForThread returns the cut run once its continuation is declined", () =>
418 Effect.gen(function* () {
419 const projectId = ProjectId.make("project:thread-management:wait-declined");
420 const threadId = ThreadId.make("thread:thread-management:wait-declined");
421 const runId = RunId.make("run:thread-management:wait-declined");
422 const subscribed = yield* Deferred.make<void>();
423 const declined = yield* Deferred.make<void>();
424 let pending = true;
425 const layerTest = ThreadManagementService.layer.pipe(
426 Layer.provide(Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({})),
427 Layer.provide(
428 Layer.mock(Orchestrator.OrchestratorV2)({
429 getThreadEventSequence: () => Effect.succeed(0),
430 restartContinuationPending: () => Effect.succeed(pending),
431 awaitRestartContinuation: () => Deferred.await(declined),
432 streamStoredEventsFrom: (input) =>
433 input?.eventType === "run.updated"
434 ? Stream.fromEffect(Deferred.succeed(subscribed, undefined)).pipe(
435 Stream.drain,
436 Stream.concat(Stream.never),
437 )
438 : Stream.never,
439 getThreadRecords: () =>
440 Effect.succeed({
441 thread: { id: threadId, projectId, deletedAt: null },
442 runs: [{ id: runId, status: "cancelled" }],
443 } as unknown as OrchestrationV2ThreadProjection),
444 }),
445 ),
446 Layer.provide(ServerSettings.layerTest()),
447 Layer.provide(layerReceiptsTest),
448 );
449 const service = yield* ThreadManagementService.ThreadManagementService.pipe(
450 Effect.provide(layerTest),
451 );
452 const fiber = yield* service
453 .waitForThread({ projectId, threadId, runId, timeoutMs: 60 * 60 * 1_000 })
454 .pipe(Effect.forkChild);
455 yield* Deferred.await(subscribed);
456 pending = false;
457 yield* Deferred.succeed(declined, undefined);
458 const result = yield* Fiber.join(fiber);
459
460 expect(result).toMatchObject({ timedOut: false, run: { id: runId, status: "cancelled" } });
461 }),
462);
463
464it.effect.each(["live", "no-session", "unsupported-runtime"] as const)(
465 "marks background work awaited on the thread's active provider thread with state %s",
466 (state) =>
467 Effect.gen(function* () {
468 const threadId = ThreadId.make("thread:background-wait");
469 const providerThreadId = ProviderThreadId.make("provider-thread:background-wait");
470 const providerSessionId = ProviderSessionId.make("provider-session:background-wait");
471 const driver = ProviderDriverKind.make("claudeAgent");
472 const now = yield* DateTime.now;
473 const providerThread: OrchestrationV2ProviderThread = {
474 id: providerThreadId,
475 driver,
476 providerInstanceId: ProviderInstanceId.make("claudeAgent"),
477 providerSessionId,
478 appThreadId: threadId,
479 ownerNodeId: null,
480 nativeThreadRef: { driver, nativeId: "native-thread", strength: "strong" },
481 nativeConversationHeadRef: null,
482 status: "idle",
483 firstRunOrdinal: 1,
484 lastRunOrdinal: 1,
485 handoffIds: [],
486 forkedFrom: null,
487 pendingBackgroundTasks: [{ taskId: "tests", kind: "command" }],
488 contextUsage: null,
489 nativeMetadata: null,
490 createdAt: now,
491 updatedAt: now,
492 };
493 const calls: Array<{ providerThreadId: ProviderThreadId; awaited: boolean }> = [];
494 const runtime = {
495 driver,
496 providerSessionId,
497 ...(state === "unsupported-runtime"
498 ? {}
499 : {
500 awaitBackgroundTasks: (input: {
501 readonly providerThread: OrchestrationV2ProviderThread;
502 readonly taskIds: ReadonlyArray<string>;
503 readonly awaited: boolean;
504 }) =>
505 Effect.sync(() => {
506 calls.push({
507 providerThreadId: input.providerThread.id,
508 awaited: input.awaited,
509 });
510 return { matched: input.taskIds.filter((taskId) => taskId === "tests") };
511 }),
512 }),
513 } as unknown as ProviderAdapter.ProviderAdapterV2SessionRuntime;
514 const layerTest = ThreadManagementService.layer.pipe(
515 Layer.provide(
516 Layer.mergeAll(
517 Layer.mock(Orchestrator.OrchestratorV2)({
518 getThreadRecords: () =>
519 Effect.succeed({
520 thread: {
521 id: threadId,
522 deletedAt: null,
523 activeProviderThreadId: providerThreadId,
524 },
525 providerThreads: [providerThread],
526 } as unknown as OrchestrationV2ThreadProjection),
527 }),
528 Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({
529 get: () =>
530 Effect.succeed(state === "no-session" ? Option.none() : Option.some(runtime)),
531 }),
532 ),
533 ),
534 Layer.provide(ServerSettings.layerTest()),
535 Layer.provide(layerReceiptsTest),
536 );
537 const result = yield* Effect.gen(function* () {
538 const service = yield* ThreadManagementService.ThreadManagementService;
539 return yield* service
540 .awaitBackgroundTasks({ threadId, taskIds: ["tests", "finished"], awaited: true })
541 .pipe(Effect.result);
542 }).pipe(Effect.provide(Layer.merge(layerTest, ThreadCommandExecutor.layer)));
543
544 if (state === "live") {
545 expect(result).toMatchObject({
546 success: { matched: ["tests"], unmatched: ["finished"] },
547 });
548 expect(calls).toEqual([{ providerThreadId, awaited: true }]);
549 } else {
550 expect(result).toMatchObject({
551 failure: {
552 _tag: "ThreadManagementBackgroundWaitError",
553 reason: state === "no-session" ? "unavailable" : "unsupported",
554 },
555 });
556 expect(calls).toEqual([]);
557 }
558 }),
559);
560
561it.effect.each([
562 { status: "completed" as const, settles: true },
563 { status: "failed" as const, settles: false },
564 { status: "interrupted" as const, settles: false },
565])("settleAfterRun settles only when the run $status", ({ status, settles }) =>
566 Effect.gen(function* () {
567 const projectId = ProjectId.make("project:thread-management:settle-after-run");
568 const threadId = ThreadId.make("thread:thread-management:settle-after-run");
569 const runId = RunId.make("run:thread-management:settle-after-run");
570 const dispatched: Array<string> = [];
571 const layerTest = ThreadManagementService.layer.pipe(
572 Layer.provide(Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({})),
573 Layer.provide(
574 Layer.mock(Orchestrator.OrchestratorV2)({
575 getThreadEventSequence: () => Effect.succeed(0),
576 restartContinuationPending: () => Effect.succeed(false),
577 getThreadRecords: () =>
578 Effect.succeed({
579 thread: { id: threadId, projectId, deletedAt: null },
580 runs: [{ id: runId, status }],
581 } as unknown as OrchestrationV2ThreadProjection),
582 dispatch: (command) =>
583 Effect.sync(() => {
584 dispatched.push(command.type);
585 return { sequence: 1, storedEvents: [] } as never;
586 }),
587 }),
588 ),
589 Layer.provide(ServerSettings.layerTest()),
590 Layer.provide(layerReceiptsTest),
591 );
592 const service = yield* ThreadManagementService.ThreadManagementService.pipe(
593 Effect.provide(layerTest),
594 );
595
596 yield* service.settleAfterRun({ projectId, threadId, runId });
597
598 expect(dispatched).toEqual(settles ? ["thread.settle"] : []);
599 }),
600);
601
602it.effect.each([
603 {
604 name: "kills the thread's own agent and ends its turn",
605 others: [] as ReadonlyArray<string>,
606 killed: true,
607 expected: { outcome: "killed", sharedWithThreadIds: [] },
608 teardown: ["release"],
609 },
610 {
611 name: "keeps a process another working thread shares and only ends this turn",
612 others: ["thread:thread-management:force-stop:other"],
613 killed: false,
614 expected: {
615 outcome: "shared",
616 sharedWithThreadIds: ["thread:thread-management:force-stop:other"],
617 },
618 teardown: ["detach"],
619 },
620 {
621 name: "still settles a finished run's background work in a shared process",
622 others: ["thread:thread-management:force-stop:other"],
623 killed: false,
624 settledRun: true,
625 expected: {
626 outcome: "shared",
627 sharedWithThreadIds: ["thread:thread-management:force-stop:other"],
628 },
629 teardown: ["detach"],
630 },
631 {
632 name: "detaches when a sibling starts a turn just before the session is released",
633 others: [] as ReadonlyArray<string>,
634 killed: false,
635 siblingBusy: true,
636 expected: { outcome: "shared", sharedWithThreadIds: [] },
637 teardown: ["release", "detach"],
638 },
639 {
640 name: "reports a teardown that has not finished in time as still releasing",
641 others: [] as ReadonlyArray<string>,
642 killed: false,
643 releaseHangs: true,
644 expected: { outcome: "releasing", sharedWithThreadIds: [] },
645 teardown: ["release"],
646 },
647])("Force stop $name", ({ others, killed, expected, teardown, ...row }) =>
648 Effect.gen(function* () {
649 const threadId = ThreadId.make("thread:thread-management:force-stop");
650 const providerSessionId = ProviderSessionId.make("provider-session:force-stop");
651 const providerThreadId = ProviderThreadId.make("provider-thread:force-stop");
652 const runId = RunId.make("run:thread-management:force-stop");
653 const dispatched: Array<OrchestrationV2Command | { readonly type: string }> = [];
654 const teardowns: Array<string> = [];
655 const tornDown = yield* Deferred.make<void>();
656 const layerTest = ThreadManagementService.layer.pipe(
657 Layer.provide(
658 Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({
659 isLive: () => Effect.succeed(true),
660 otherWorkingThreads: () => Effect.succeed(others.map((id) => ThreadId.make(id))),
661 releaseUnlessBusy: () =>
662 Effect.sync(() => teardowns.push("release")).pipe(
663 Effect.andThen(
664 "releaseHangs" in row ? Effect.never : Effect.succeed(!("siblingBusy" in row)),
665 ),
666 ),
667 detach: () =>
668 Effect.sync(() => teardowns.push("detach")).pipe(
669 Effect.andThen(Deferred.succeed(tornDown, undefined)),
670 Effect.asVoid,
671 ),
672 }),
673 ),
674 Layer.provide(
675 Layer.mock(Orchestrator.OrchestratorV2)({
676 getThreadRecords: () =>
677 Effect.succeed({
678 thread: { id: threadId, deletedAt: null },
679 runs: [
680 {
681 id: runId,
682 ordinal: 1,
683 status: "settledRun" in row ? "completed" : "running",
684 activeAttemptId: "attempt",
685 },
686 // A queued follow-up neither supersedes the request nor becomes the target.
687 { id: RunId.make("run:queued-follow-up"), ordinal: 2, status: "queued" },
688 ],
689 providerThreads: [{ id: providerThreadId, appThreadId: threadId, providerSessionId }],
690 providerTurns: [
691 {
692 id: "provider-turn:force-stop",
693 providerThreadId,
694 runAttemptId: "attempt",
695 status: "settledRun" in row ? "completed" : "running",
696 },
697 ],
698 } as unknown as OrchestrationV2ThreadProjection),
699 dispatch: (command) =>
700 Effect.sync(() => {
701 dispatched.push(command);
702 return { sequence: 1, storedEvents: [] } as never;
703 }),
704 }),
705 ),
706 Layer.provide(
707 Layer.succeed(AgentScope, {
708 ...AgentScope.defaultValue(),
709 kill: () => Effect.succeed(killed),
710 }),
711 ),
712 Layer.provide(ServerSettings.layerTest()),
713 Layer.provide(layerReceiptsTest),
714 );
715 yield* Effect.gen(function* () {
716 const service = yield* ThreadManagementService.ThreadManagementService;
717 const stopping = yield* service.forceStopThread({ threadId, runId }).pipe(Effect.forkChild);
718 yield* TestClock.adjust("10 seconds");
719 expect(yield* Fiber.join(stopping)).toEqual(expected);
720 expect(dispatched).toMatchObject([
721 {
722 type: "thread.background-work.settle",
723 providerThreadId,
724 reason: "Force stopped by user",
725 },
726 ]);
727 if (teardown.at(-1) === "detach") yield* Deferred.await(tornDown);
728 expect(teardowns).toEqual(teardown);
729 }).pipe(Effect.provide(layerTest));
730 }),
731);
732
733it.effect("Force stop refuses once a newer run has started, before killing anything", () =>
734 Effect.gen(function* () {
735 const threadId = ThreadId.make("thread:thread-management:force-stop-superseded");
736 let killed = false;
737 const layerTest = ThreadManagementService.layer.pipe(
738 Layer.provide(Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({})),
739 Layer.provide(
740 Layer.mock(Orchestrator.OrchestratorV2)({
741 getThreadRecords: () =>
742 Effect.succeed({
743 thread: { id: threadId, deletedAt: null },
744 runs: [
745 { id: RunId.make("run:stopped"), ordinal: 1, status: "running" },
746 { id: RunId.make("run:newer"), ordinal: 2, status: "running" },
747 ],
748 providerThreads: [],
749 providerTurns: [],
750 } as unknown as OrchestrationV2ThreadProjection),
751 }),
752 ),
753 Layer.provide(
754 Layer.succeed(AgentScope, {
755 ...AgentScope.defaultValue(),
756 kill: () => Effect.sync(() => (killed = true)),
757 }),
758 ),
759 Layer.provide(ServerSettings.layerTest()),
760 Layer.provide(layerReceiptsTest),
761 );
762 const error = yield* Effect.gen(function* () {
763 const service = yield* ThreadManagementService.ThreadManagementService;
764 return yield* Effect.flip(
765 service.forceStopThread({ threadId, runId: RunId.make("run:stopped") }),
766 );
767 }).pipe(Effect.provide(layerTest));
768 expect(error.reason).toBe("superseded");
769 expect(killed).toBe(false);
770 }),
771);