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

ThreadManagementService.test.ts

875 lines34.7 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 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, followUp: "none", settles: true },
563 { status: "failed" as const, followUp: "none", settles: false },
564 { status: "interrupted" as const, followUp: "none", settles: false },
565 { status: "completed" as const, followUp: "notification", settles: true },
566 { status: "completed" as const, followUp: "replayed-notification", settles: true },
567 { status: "completed" as const, followUp: "delegated", settles: true },
568 { status: "completed" as const, followUp: "failed-notification", settles: false },
569 { status: "completed" as const, followUp: "held-notification", settles: true },
570 { status: "completed" as const, followUp: "user", settles: false },
571 { status: "completed" as const, followUp: "steered-notification", settles: false },
572])("settleAfterRun handles $status with $followUp follow-up", ({ status, followUp, settles }) =>
573 Effect.gen(function* () {
574 const projectId = ProjectId.make("project:thread-management:settle-after-run");
575 const threadId = ThreadId.make("thread:thread-management:settle-after-run");
576 const runId = RunId.make("run:thread-management:settle-after-run");
577 const followUpId = RunId.make(`${runId}:follow-up`);
578 const subscribed = yield* Deferred.make<void>();
579 const events = yield* Queue.unbounded<OrchestrationV2StoredEvent>();
580 const replayRejected = yield* Deferred.make<void>();
581 let sequence = 0;
582 let sequenceReads = 0;
583 let rejectedCommandId: CommandId | undefined;
584 const runs = [{ id: runId, ordinal: 1, status, userMessageId: MessageId.make("original") }];
585 const nextRun = {
586 id: followUpId,
587 ordinal: 2,
588 status: "running" as OrchestrationV2Run["status"],
589 userMessageId: MessageId.make("follow-up"),
590 };
591 const dispatched: Array<string> = [];
592 // The notification starts after the completed run was observed, before settlement commits.
593 let raced = false;
594 const layerTest = ThreadManagementService.layer.pipe(
595 Layer.provide(Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({})),
596 Layer.provide(
597 Layer.mock(Orchestrator.OrchestratorV2)({
598 getThreadEventSequence: () =>
599 Effect.sync(() => {
600 if (followUp === "replayed-notification" && sequenceReads++ === 2) sequence = 1;
601 return sequence;
602 }),
603 restartContinuationPending: () => Effect.succeed(false),
604 streamStoredEventsFrom: () =>
605 Stream.fromEffect(Deferred.succeed(subscribed, undefined)).pipe(
606 Stream.drain,
607 Stream.concat(Stream.fromQueue(events)),
608 ),
609 getThreadRecords: (_threadId, _fields, filter) =>
610 Effect.sync(
611 () =>
612 ({
613 thread: { id: threadId, projectId, deletedAt: null },
614 runs: raced ? [...runs, nextRun] : runs,
615 messages: [
616 { id: MessageId.make("original"), runId, role: "user" as const },
617 {
618 id: nextRun.userMessageId,
619 runId: followUpId,
620 role: "user" as const,
621 ...(followUp.endsWith("notification") ? { notification: {} } : {}),
622 ...(followUp === "delegated" ? { delegatedCompletion: {} } : {}),
623 },
624 { id: MessageId.make("reply"), runId: followUpId, role: "assistant" as const },
625 ...(followUp === "steered-notification"
626 ? [
627 {
628 id: MessageId.make("user-steer"),
629 runId: followUpId,
630 role: "user" as const,
631 },
632 ]
633 : []),
634 ].filter(
635 (message) =>
636 (filter?.messageIds === undefined ||
637 filter.messageIds.includes(message.id)) &&
638 (filter?.messageRunIds === undefined ||
639 filter.messageRunIds.includes(message.runId)) &&
640 (filter?.messageRoles === undefined ||
641 filter.messageRoles.includes(message.role)),
642 ),
643 }) as unknown as OrchestrationV2ThreadProjection,
644 ),
645 dispatch: (command) =>
646 Effect.gen(function* () {
647 if (followUp !== "none" && !raced) {
648 raced = true;
649 rejectedCommandId = command.commandId;
650 return yield* new Orchestrator.OrchestratorDispatchError({
651 commandId: command.commandId,
652 commandType: command.type,
653 cause: "Thread is still running",
654 });
655 }
656 if (followUp === "replayed-notification" && command.commandId === rejectedCommandId) {
657 yield* Deferred.succeed(replayRejected, undefined);
658 return yield* new Orchestrator.OrchestratorCommandPreviouslyRejectedError({
659 commandId: command.commandId,
660 commandType: command.type,
661 detail: "Thread is still running",
662 });
663 }
664 dispatched.push(command.type);
665 return { sequence: 1, storedEvents: [] } as never;
666 }),
667 }),
668 ),
669 Layer.provide(ServerSettings.layerTest()),
670 Layer.provide(layerReceiptsTest),
671 );
672 const service = yield* ThreadManagementService.ThreadManagementService.pipe(
673 Effect.provide(layerTest),
674 );
675 const fiber = yield* service
676 .settleAfterRun({ projectId, threadId, runId })
677 .pipe(Effect.forkChild);
678 if (followUp !== "none") {
679 yield* Deferred.await(subscribed);
680 expect(dispatched).toEqual([]);
681 nextRun.status =
682 followUp === "failed-notification"
683 ? "failed"
684 : followUp === "held-notification"
685 ? "queued"
686 : "completed";
687 yield* Queue.offer(events, {
688 sequence: 1,
689 event: { type: "run.updated", threadId, payload: nextRun },
690 } as unknown as OrchestrationV2StoredEvent);
691 }
692 if (followUp === "replayed-notification") {
693 yield* Deferred.await(replayRejected);
694 expect(dispatched).toEqual([]);
695 sequence = 2;
696 yield* Queue.offer(events, {
697 sequence,
698 event: { type: "run.updated", threadId, payload: nextRun },
699 } as unknown as OrchestrationV2StoredEvent);
700 }
701 yield* Fiber.join(fiber);
702 expect(dispatched).toEqual(settles ? ["thread.settle"] : []);
703 }),
704);
705​
706it.effect.each([
707 {
708 name: "kills the thread's own agent and ends its turn",
709 others: [] as ReadonlyArray<string>,
710 killed: true,
711 expected: { outcome: "killed", sharedWithThreadIds: [] },
712 teardown: ["release"],
713 },
714 {
715 name: "keeps a process another working thread shares and only ends this turn",
716 others: ["thread:thread-management:force-stop:other"],
717 killed: false,
718 expected: {
719 outcome: "shared",
720 sharedWithThreadIds: ["thread:thread-management:force-stop:other"],
721 },
722 teardown: ["detach"],
723 },
724 {
725 name: "still settles a finished run's background work in a shared process",
726 others: ["thread:thread-management:force-stop:other"],
727 killed: false,
728 settledRun: true,
729 expected: {
730 outcome: "shared",
731 sharedWithThreadIds: ["thread:thread-management:force-stop:other"],
732 },
733 teardown: ["detach"],
734 },
735 {
736 name: "detaches when a sibling starts a turn just before the session is released",
737 others: [] as ReadonlyArray<string>,
738 killed: false,
739 siblingBusy: true,
740 expected: { outcome: "shared", sharedWithThreadIds: [] },
741 teardown: ["release", "detach"],
742 },
743 {
744 name: "reports a teardown that has not finished in time as still releasing",
745 others: [] as ReadonlyArray<string>,
746 killed: false,
747 releaseHangs: true,
748 expected: { outcome: "releasing", sharedWithThreadIds: [] },
749 teardown: ["release"],
750 },
751])("Force stop $name", ({ others, killed, expected, teardown, ...row }) =>
752 Effect.gen(function* () {
753 const threadId = ThreadId.make("thread:thread-management:force-stop");
754 const providerSessionId = ProviderSessionId.make("provider-session:force-stop");
755 const providerThreadId = ProviderThreadId.make("provider-thread:force-stop");
756 const runId = RunId.make("run:thread-management:force-stop");
757 const dispatched: Array<OrchestrationV2Command | { readonly type: string }> = [];
758 const teardowns: Array<string> = [];
759 const tornDown = yield* Deferred.make<void>();
760 const layerTest = ThreadManagementService.layer.pipe(
761 Layer.provide(
762 Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({
763 isLive: () => Effect.succeed(true),
764 otherWorkingThreads: () => Effect.succeed(others.map((id) => ThreadId.make(id))),
765 releaseUnlessBusy: () =>
766 Effect.sync(() => teardowns.push("release")).pipe(
767 Effect.andThen(
768 "releaseHangs" in row ? Effect.never : Effect.succeed(!("siblingBusy" in row)),
769 ),
770 ),
771 detach: () =>
772 Effect.sync(() => teardowns.push("detach")).pipe(
773 Effect.andThen(Deferred.succeed(tornDown, undefined)),
774 Effect.asVoid,
775 ),
776 }),
777 ),
778 Layer.provide(
779 Layer.mock(Orchestrator.OrchestratorV2)({
780 getThreadRecords: () =>
781 Effect.succeed({
782 thread: { id: threadId, deletedAt: null },
783 runs: [
784 {
785 id: runId,
786 ordinal: 1,
787 status: "settledRun" in row ? "completed" : "running",
788 activeAttemptId: "attempt",
789 },
790 // A queued follow-up neither supersedes the request nor becomes the target.
791 { id: RunId.make("run:queued-follow-up"), ordinal: 2, status: "queued" },
792 ],
793 providerThreads: [{ id: providerThreadId, appThreadId: threadId, providerSessionId }],
794 providerTurns: [
795 {
796 id: "provider-turn:force-stop",
797 providerThreadId,
798 runAttemptId: "attempt",
799 status: "settledRun" in row ? "completed" : "running",
800 },
801 ],
802 } as unknown as OrchestrationV2ThreadProjection),
803 dispatch: (command) =>
804 Effect.sync(() => {
805 dispatched.push(command);
806 return { sequence: 1, storedEvents: [] } as never;
807 }),
808 }),
809 ),
810 Layer.provide(
811 Layer.succeed(AgentScope, {
812 ...AgentScope.defaultValue(),
813 kill: () => Effect.succeed(killed),
814 }),
815 ),
816 Layer.provide(ServerSettings.layerTest()),
817 Layer.provide(layerReceiptsTest),
818 );
819 yield* Effect.gen(function* () {
820 const service = yield* ThreadManagementService.ThreadManagementService;
821 const stopping = yield* service.forceStopThread({ threadId, runId }).pipe(Effect.forkChild);
822 yield* TestClock.adjust("10 seconds");
823 expect(yield* Fiber.join(stopping)).toEqual(expected);
824 expect(dispatched).toMatchObject([
825 {
826 type: "thread.background-work.settle",
827 providerThreadId,
828 reason: "Force stopped by user",
829 },
830 ]);
831 if (teardown.at(-1) === "detach") yield* Deferred.await(tornDown);
832 expect(teardowns).toEqual(teardown);
833 }).pipe(Effect.provide(layerTest));
834 }),
835);
836​
837it.effect("Force stop refuses once a newer run has started, before killing anything", () =>
838 Effect.gen(function* () {
839 const threadId = ThreadId.make("thread:thread-management:force-stop-superseded");
840 let killed = false;
841 const layerTest = ThreadManagementService.layer.pipe(
842 Layer.provide(Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({})),
843 Layer.provide(
844 Layer.mock(Orchestrator.OrchestratorV2)({
845 getThreadRecords: () =>
846 Effect.succeed({
847 thread: { id: threadId, deletedAt: null },
848 runs: [
849 { id: RunId.make("run:stopped"), ordinal: 1, status: "running" },
850 { id: RunId.make("run:newer"), ordinal: 2, status: "running" },
851 ],
852 providerThreads: [],
853 providerTurns: [],
854 } as unknown as OrchestrationV2ThreadProjection),
855 }),
856 ),
857 Layer.provide(
858 Layer.succeed(AgentScope, {
859 ...AgentScope.defaultValue(),
860 kill: () => Effect.sync(() => (killed = true)),
861 }),
862 ),
863 Layer.provide(ServerSettings.layerTest()),
864 Layer.provide(layerReceiptsTest),
865 );
866 const error = yield* Effect.gen(function* () {
867 const service = yield* ThreadManagementService.ThreadManagementService;
868 return yield* Effect.flip(
869 service.forceStopThread({ threadId, runId: RunId.make("run:stopped") }),
870 );
871 }).pipe(Effect.provide(layerTest));
872 expect(error.reason).toBe("superseded");
873 expect(killed).toBe(false);
874 }),
875);