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

ThreadStop.test.ts

1,473 lines55.7 KB

1import { assert, it } from "@effect/vitest";
2import {
3 CommandId,
4 ContextTransferId,
5 EventId,
6 MessageId,
7 NodeId,
8 type OrchestrationV2DomainEvent,
9 ProjectId,
10 ProviderDriverKind,
11 ProviderInstanceId,
12 ProviderSessionId,
13 ProviderThreadId,
14 ProviderTurnId,
15 RuntimeRequestId,
16 ScheduledTaskId,
17 ThreadId,
18 TurnItemId,
19} from "@t3tools/contracts";
20import * as DateTime from "effect/DateTime";
21import * as Effect from "effect/Effect";
22import * as Exit from "effect/Exit";
23import * as Layer from "effect/Layer";
24import * as Schema from "effect/Schema";
25import * as SqlClient from "effect/sql/SqlClient";
26import * as Stream from "effect/Stream";
27import * as EventStore from "./EventStore.ts";
28import * as TestClock from "effect/testing/TestClock";
29​
30import * as SqlitePersistence from "../persistence/Sqlite.ts";
31import * as ServerSettings from "../serverSettings.ts";
32import { CLAUDE_PROVIDER } from "./Adapters/ClaudeAdapterV2.ts";
33import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts";
34import * as CommandReceiptStore from "./CommandReceiptStore.ts";
35import { OrchestrationEffectRequestV2 } from "./EffectOutbox.ts";
36import * as Orchestrator from "./Orchestrator.ts";
37import * as EffectWorker from "./EffectWorker.ts";
38import * as EffectOutbox from "./EffectOutbox.ts";
39import * as ProjectionStore from "./ProjectionStore.ts";
40import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts";
41import * as ThreadManagementService from "./ThreadManagementService.ts";
42import * as ProviderReplayHarness from "./testkit/ProviderReplayHarness.ts";
43import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
44​
45const instanceId = ProviderInstanceId.make("codex");
46const modelSelection = { instanceId, model: "gpt-5.1-codex" };
47const adapter = {
48 instanceId,
49 driver: ProviderDriverKind.make("codex"),
50 getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2),
51 planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" as const }),
52 openSession: () => Effect.die("Runs here never reach a provider"),
53} as ProviderAdapter.ProviderAdapterV2["Service"];
54const layerDatabase = SqlitePersistence.layerMemory;
55const layerTest = ThreadManagementService.layer.pipe(
56 Layer.provideMerge(
57 Layer.mergeAll(
58 layerDatabase,
59 ProjectionStore.layer.pipe(Layer.provide(layerDatabase)),
60 EventStore.layer.pipe(Layer.provide(layerDatabase)),
61 EffectOutbox.layer.pipe(Layer.provide(layerDatabase)),
62 ProviderReplayHarness.layerWithRegistry(
63 { name: "thread-stop" },
64 ProviderAdapterRegistry.layerFromAdapters([adapter]),
65 { databaseLayer: layerDatabase, runEffectWorker: false },
66 ),
67 ),
68 ),
69 Layer.provideMerge(ServerSettings.layerTest()),
70 Layer.provideMerge(CommandReceiptStore.layer.pipe(Layer.provide(layerDatabase))),
71);
72​
73const encodeEffectRequest = Schema.encodeSync(Schema.fromJsonString(OrchestrationEffectRequestV2));
74​
75const pullRequest = (number: number) => ({
76 host: "github.com",
77 repository: "pingdotgg/t3code",
78 number,
79});
80​
81const createWatchingThread = (threadId: ThreadId, number: number) =>
82 Effect.gen(function* () {
83 const orchestrator = yield* Orchestrator.OrchestratorV2;
84 yield* orchestrator.dispatch({
85 type: "thread.create",
86 commandId: CommandId.make(`create:${threadId}`),
87 threadId,
88 projectId: ProjectId.make("project:thread-stop"),
89 title: threadId,
90 modelSelection,
91 runtimeMode: "full-access",
92 interactionMode: "default",
93 branch: null,
94 worktreePath: null,
95 createdBy: "user",
96 creationSource: "web",
97 });
98 yield* watch(threadId, number);
99 });
100​
101const watch = (threadId: ThreadId, number: number) =>
102 Effect.gen(function* () {
103 const orchestrator = yield* Orchestrator.OrchestratorV2;
104 yield* orchestrator.dispatch({
105 type: "thread.pull-request.watch",
106 commandId: CommandId.make(`watch:${threadId}:${number}`),
107 threadId,
108 ...pullRequest(number),
109 watching: true,
110 link: { url: `https://github.com/pingdotgg/t3code/pull/${number}`, source: "agent" },
111 });
112 });
113​
114const send = (threadId: ThreadId, text: string, type: "start_immediately" | "queue_after_active") =>
115 Effect.gen(function* () {
116 const orchestrator = yield* Orchestrator.OrchestratorV2;
117 yield* orchestrator.dispatch({
118 type: "message.dispatch",
119 commandId: CommandId.make(`send:${threadId}:${text}`),
120 threadId,
121 messageId: MessageId.make(`message:${threadId}:${text}`),
122 text,
123 attachments: [],
124 dispatchMode: { type },
125 createdBy: "user",
126 creationSource: "web",
127 });
128 });
129​
130const delegate = (parentThreadId: ThreadId, task: string) =>
131 Effect.gen(function* () {
132 const orchestrator = yield* Orchestrator.OrchestratorV2;
133 const parentRun = (yield* orchestrator.getThreadProjection(parentThreadId)).runs.at(-1)!;
134 yield* orchestrator.dispatch({
135 type: "delegated_task.request",
136 commandId: CommandId.make(`delegate:${task}`),
137 parentThreadId,
138 parentRunId: parentRun.id,
139 parentNodeId: parentRun.rootNodeId!,
140 task,
141 modelSelection,
142 runtimeMode: "full-access",
143 interactionMode: "default",
144 completionWake: "always",
145 createdBy: "agent",
146 creationSource: "mcp",
147 });
148 const projection = yield* orchestrator.getThreadProjection(parentThreadId);
149 return projection.subagents.find((candidate) => candidate.prompt === task)!.childThreadId!;
150 });
151​
152const threadState = (threadId: ThreadId) =>
153 Effect.gen(function* () {
154 const orchestrator = yield* Orchestrator.OrchestratorV2;
155 const projection = yield* orchestrator.getThreadProjection(threadId);
156 return {
157 runs: projection.runs.map((run) => `${run.status}${run.queueHeld === true ? ":held" : ""}`),
158 watched: (projection.thread.pullRequests ?? [])
159 .filter((link) => link.watch !== undefined)
160 .map((link) => link.number),
161 };
162 });
163​
164it.effect.each([
165 ["idle", "thread.stop"],
166 ["idle", "run.interrupt"],
167 ["idle", "subagent.stop"],
168 ["running", "subagent.stop"],
169 ["bound", "subagent.stop"],
170 ["correlated", "subagent.stop"],
171 ["archived", "thread.stop"],
172 ["missing", "thread.stop"],
173 ["running", "thread.stop"],
174 ["queued", "thread.stop"],
175 ["waiting", "thread.stop"],
176 ["correlated", "thread.stop"],
177 ["provider-active", "thread.stop"],
178 ["roster", "thread.stop"],
179 ["background", "thread.stop"],
180 ["question", "thread.stop"],
181 ["restart", "thread.stop"],
182] as const)(
183 "Stop clears an orphaned follow-up when its child is finished; its own Stop does unless a run is bound (%s via %s)",
184 ([childState, type]) =>
185 Effect.gen(function* () {
186 const orchestrator = yield* Orchestrator.OrchestratorV2;
187 const projections = yield* ProjectionStore.ProjectionStoreV2;
188 const parentThreadId = ThreadId.make(`thread:orphan-parent:${childState}`);
189 yield* createWatchingThread(parentThreadId, 1);
190 yield* send(parentThreadId, "parent", "start_immediately");
191 const childThreadId = yield* delegate(parentThreadId, "original task");
192 const parent = yield* orchestrator.getThreadProjection(parentThreadId);
193 const child = yield* orchestrator.getThreadProjection(childThreadId);
194 const original = parent.subagents[0]!;
195 const originalItem = parent.turnItems.find((item) => item.type === "subagent")!;
196 const originalNode = parent.nodes.find((node) => node.id === original.id)!;
197 const taskId = NodeId.make(`node:orphan-followup:${childState}`);
198 const itemId = TurnItemId.make(`item:orphan-followup:${childState}`);
199 const followupChildThreadId =
200 childState === "missing" ? ThreadId.make("thread:missing-child") : childThreadId;
201 const now = yield* DateTime.now;
202 let sequence = 0;
203 const apply = (event: Omit<OrchestrationV2DomainEvent, "id">) =>
204 projections.apply({
205 ...event,
206 id: EventId.make(`event:orphan:${childState}:${sequence++}`),
207 } as OrchestrationV2DomainEvent);
208 yield* apply({
209 type: "subagent.updated",
210 threadId: parentThreadId,
211 occurredAt: now,
212 payload: {
213 ...original,
214 status: "completed",
215 result: "Original result",
216 completedAt: now,
217 completionDelivery: { state: "acknowledged", observedByRunId: null },
218 },
219 });
220 yield* apply({
221 type: "context-transfer.created",
222 threadId: parentThreadId,
223 occurredAt: now,
224 payload: {
225 ...child.contextTransfers[0]!,
226 id: ContextTransferId.make(`transfer:original-result:${childState}`),
227 type: "subagent_result",
228 sourceThreadId: childThreadId,
229 targetThreadId: parentThreadId,
230 sourcePoint: { threadId: childThreadId, runId: child.runs[0]!.id },
231 targetRunId: parent.runs[0]!.id,
232 },
233 });
234 yield* apply({
235 type: "node.updated",
236 threadId: parentThreadId,
237 occurredAt: now,
238 payload: { ...originalNode, status: "completed", completedAt: now },
239 });
240 yield* apply({
241 type: "turn-item.updated",
242 threadId: parentThreadId,
243 occurredAt: now,
244 payload: { ...originalItem, status: "completed", completedAt: now },
245 });
246 yield* apply({
247 type: "subagent.updated",
248 threadId: parentThreadId,
249 occurredAt: now,
250 payload: {
251 ...original,
252 id: taskId,
253 childThreadId: followupChildThreadId,
254 status: "running",
255 result: null,
256 completedAt: null,
257 },
258 });
259 yield* apply({
260 type: "node.updated",
261 threadId: parentThreadId,
262 occurredAt: now,
263 payload: { ...originalNode, id: taskId, status: "running" },
264 });
265 assert.equal(originalItem.type, "subagent");
266 if (originalItem.type !== "subagent") return;
267 yield* apply({
268 type: "turn-item.updated",
269 threadId: parentThreadId,
270 occurredAt: now,
271 payload: {
272 ...originalItem,
273 id: itemId,
274 nodeId: taskId,
275 subagentId: taskId,
276 childThreadId: followupChildThreadId,
277 status: "running",
278 },
279 });
280 const runAtStart = child.runs[0]!;
281 const childRunStatus =
282 childState === "running" || childState === "queued" || childState === "waiting"
283 ? childState
284 : childState === "bound"
285 ? "running"
286 : "completed";
287 yield* apply({
288 type: "run.updated",
289 threadId: childThreadId,
290 occurredAt: now,
291 payload: { ...runAtStart, status: "running", delegatedTaskId: taskId },
292 });
293 assert.equal(
294 (yield* orchestrator.getThreadProjection(childThreadId)).runs[0]?.delegatedTaskId,
295 taskId,
296 );
297 // A terminal write based on the attempt's start snapshot loses a later steer binding.
298 yield* apply({
299 type: "run.updated",
300 threadId: childThreadId,
301 occurredAt: now,
302 payload: {
303 ...runAtStart,
304 status: childRunStatus,
305 completedAt: childRunStatus === "completed" ? now : null,
306 ...(childState === "correlated" || childState === "bound"
307 ? { delegatedTaskId: taskId }
308 : {}),
309 },
310 });
311 assert.equal(
312 (yield* orchestrator.getThreadProjection(childThreadId)).runs[0]?.delegatedTaskId,
313 childState === "correlated" || childState === "bound" ? taskId : undefined,
314 );
315 if (childState === "provider-active" || childState === "roster") {
316 yield* apply({
317 type: "provider-thread.updated",
318 threadId: childThreadId,
319 occurredAt: now,
320 payload: {
321 ...child.providerThreads[0]!,
322 status: childState === "provider-active" ? "active" : "idle",
323 pendingBackgroundTasks:
324 childState === "roster" ? [{ taskId: "background-task", kind: "command" }] : [],
325 },
326 });
327 }
328 if (childState === "background") {
329 yield* apply({
330 type: "turn-item.updated",
331 threadId: childThreadId,
332 occurredAt: now,
333 payload: {
334 ...originalItem,
335 id: TurnItemId.make("item:child-background"),
336 threadId: childThreadId,
337 runId: runAtStart.id,
338 nodeId: runAtStart.rootNodeId,
339 type: "command_execution",
340 status: "running",
341 input: "test background work",
342 },
343 });
344 }
345 if (childState === "question") {
346 yield* apply({
347 type: "runtime-request.updated",
348 threadId: childThreadId,
349 occurredAt: now,
350 payload: {
351 id: RuntimeRequestId.make("request:child-question"),
352 nodeId: runAtStart.rootNodeId!,
353 providerTurnId: null,
354 nativeRequestRef: null,
355 kind: "user_input",
356 status: "pending",
357 responseCapability: { type: "message" },
358 createdAt: now,
359 resolvedAt: null,
360 },
361 });
362 }
363 if (childState === "restart") {
364 const outbox = yield* EffectOutbox.EffectOutboxV2;
365 yield* outbox.enqueue([
366 {
367 id: `effect:restart-continuation:${runAtStart.id}`,
368 commandId: CommandId.make("command:child-restart"),
369 threadId: childThreadId,
370 request: { type: "provider-runtime.continue", sourceRunId: runAtStart.id },
371 },
372 ]);
373 }
374 yield* apply({
375 type: "run.updated",
376 threadId: parentThreadId,
377 occurredAt: now,
378 payload: { ...parent.runs[0]!, status: "completed", completedAt: now },
379 });
380 if (type === "run.interrupt") {
381 const run = parent.runs[0]!;
382 yield* apply({
383 type: "provider-turn.updated",
384 threadId: parentThreadId,
385 occurredAt: now,
386 payload: {
387 id: ProviderTurnId.make("provider-turn:orphan-parent"),
388 providerThreadId: run.providerThreadId!,
389 nodeId: run.rootNodeId!,
390 runAttemptId: run.activeAttemptId!,
391 nativeTurnRef: null,
392 ordinal: 1,
393 status: "completed",
394 startedAt: now,
395 completedAt: now,
396 },
397 });
398 yield* apply({
399 type: "run-attempt.updated",
400 threadId: parentThreadId,
401 occurredAt: now,
402 payload: { ...parent.attempts[0]!, status: "completed", completedAt: now },
403 });
404 yield* apply({
405 type: "node.updated",
406 threadId: parentThreadId,
407 occurredAt: now,
408 payload: {
409 ...parent.nodes.find((node) => node.id === run.rootNodeId)!,
410 status: "completed",
411 completedAt: now,
412 },
413 });
414 }
415 if (childState === "archived") {
416 yield* apply({
417 type: "thread.archived",
418 threadId: childThreadId,
419 occurredAt: now,
420 payload: { ...child.thread, archivedAt: now },
421 });
422 }
423 const childBeforeStop = yield* orchestrator.getThreadProjection(childThreadId);
424 assert.lengthOf(
425 ((yield* orchestrator.getThreadShell(parentThreadId))?.pendingBackgroundTasks ?? []).filter(
426 (task) => task.kind === "subagent",
427 ),
428 1,
429 );
430 const stop = {
431 commandId: CommandId.make(`stop-orphan:${childState}`),
432 threadId: parentThreadId,
433 };
434 yield* orchestrator.dispatch(
435 type === "run.interrupt"
436 ? { ...stop, type, runId: parent.runs.at(-1)!.id, holdQueue: true }
437 : type === "subagent.stop"
438 ? { ...stop, type, runId: original.runId!, subagentId: taskId }
439 : { ...stop, type },
440 );
441 const after = yield* orchestrator.getThreadProjection(parentThreadId);
442 // The Lineage stop of one subagent leaves the parent's watches alone.
443 assert.lengthOf(
444 (after.thread.pullRequests ?? []).filter((link) => link.watch !== undefined),
445 type === "subagent.stop" ? 1 : 0,
446 );
447 // A task with a bound run, live or ended, keeps its settlement path.
448 const expected =
449 childState === "bound" || childState === "correlated"
450 ? "running"
451 : type === "subagent.stop" || childState === "idle" || childState === "archived"
452 ? "cancelled"
453 : "running";
454 assert.equal(after.subagents.find((task) => task.id === taskId)?.status, expected);
455 assert.equal(after.nodes.find((node) => node.id === taskId)?.status, expected);
456 assert.equal(after.turnItems.find((item) => item.id === itemId)?.status, expected);
457 assert.equal(
458 after.subagents.find((task) => task.id === taskId)?.completionDelivery?.state,
459 type === "subagent.stop" && expected === "running" ? undefined : "disposed",
460 );
461 assert.equal(
462 after.subagents.find((task) => task.id === original.id)?.result,
463 "Original result",
464 );
465 assert.deepEqual(yield* orchestrator.getThreadProjection(childThreadId), childBeforeStop);
466 if (expected === "cancelled") {
467 assert.lengthOf(
468 (
469 (yield* orchestrator.getThreadShell(parentThreadId))?.pendingBackgroundTasks ?? []
470 ).filter((task) => task.kind === "subagent"),
471 0,
472 );
473 yield* orchestrator.recoverDelegatedTasks;
474 yield* orchestrator.dispatch({
475 type: "thread.stop",
476 commandId: CommandId.make(`stop-orphan-again:${childState}`),
477 threadId: parentThreadId,
478 });
479 const repeated = yield* orchestrator.getThreadProjection(parentThreadId);
480 assert.equal(repeated.subagents.find((task) => task.id === taskId)?.status, "cancelled");
481 assert.deepEqual(repeated.messages, after.messages);
482 assert.deepEqual(repeated.contextTransfers, after.contextTransfers);
483 if (type === "subagent.stop") {
484 // A client that missed the cancel, such as one resumed from an older cache, still
485 // shows the task as running. Its Stop gets the ended task back.
486 const eventStore = yield* EventStore.EventStoreV2;
487 const afterSequence = yield* eventStore.latestSequence({ threadId: parentThreadId });
488 yield* orchestrator.dispatch({
489 ...stop,
490 commandId: CommandId.make(`stop-orphan-stale-client:${childState}`),
491 type,
492 runId: original.runId!,
493 subagentId: taskId,
494 });
495 const resent = yield* eventStore
496 .read({ threadId: parentThreadId, afterSequence })
497 .pipe(Stream.runCollect);
498 assert.deepEqual(
499 resent.flatMap(({ event }) =>
500 event.type === "subagent.updated" ? [event.payload.status] : [],
501 ),
502 ["cancelled"],
503 );
504 }
505 }
506 }).pipe(Effect.provide(layerTest)),
507);
508​
509it.effect("Stop still stops the thread when a delegated child cannot be read", () =>
510 Effect.gen(function* () {
511 const orchestrator = yield* Orchestrator.OrchestratorV2;
512 const sql = yield* SqlClient.SqlClient;
513 const parentThreadId = ThreadId.make("thread:unreadable-child-parent");
514 yield* createWatchingThread(parentThreadId, 1);
515 yield* send(parentThreadId, "parent", "start_immediately");
516 const childThreadId = yield* delegate(parentThreadId, "unreadable child");
517 yield* sql`
518 UPDATE orchestration_v2_projection_runs
519 SET payload_json = '{"obsolete":true}'
520 WHERE thread_id = ${childThreadId}
521 `;
522 yield* orchestrator.dispatch({
523 type: "run.interrupt",
524 commandId: CommandId.make("stop:unreadable-child"),
525 threadId: parentThreadId,
526 runId: (yield* orchestrator.getThreadProjection(parentThreadId)).runs.at(-1)!.id,
527 holdQueue: true,
528 });
529 assert.deepEqual(yield* threadState(parentThreadId), { runs: ["interrupted"], watched: [] });
530 }).pipe(Effect.provide(layerTest)),
531);
532​
533it.effect("Stop ends watches, holds queues, and stops the delegated tasks under the thread", () =>
534 Effect.gen(function* () {
535 const orchestrator = yield* Orchestrator.OrchestratorV2;
536 const projections = yield* ProjectionStore.ProjectionStoreV2;
537 const threads = yield* ThreadManagementService.ThreadManagementService;
538 const sql = yield* SqlClient.SqlClient;
539 const parentThreadId = ThreadId.make("thread:stop-parent");
540 yield* createWatchingThread(parentThreadId, 1);
541 yield* send(parentThreadId, "first", "start_immediately");
542 const childThreadId = yield* delegate(parentThreadId, "child task");
543 assert.isTrue(Exit.isFailure(yield* Effect.exit(watch(childThreadId, 2))));
544 const grandchildThreadId = yield* delegate(childThreadId, "grandchild task");
545 yield* send(childThreadId, "child follow-up", "queue_after_active");
546​
547 const now = yield* DateTime.now;
548 const firstRun = (yield* orchestrator.getThreadProjection(parentThreadId)).runs[0]!;
549 yield* projections.apply({
550 id: EventId.make("event:stop-parent:first-run-completed"),
551 type: "run.updated",
552 threadId: parentThreadId,
553 runId: firstRun.id,
554 occurredAt: now,
555 payload: { ...firstRun, status: "completed", completedAt: now },
556 });
557 yield* send(parentThreadId, "second", "start_immediately");
558 const secondRun = (yield* orchestrator.getThreadProjection(parentThreadId)).runs.at(-1)!;
559​
560 const stopCommandId = CommandId.make("stop-parent");
561 yield* orchestrator.dispatch({
562 type: "run.interrupt",
563 commandId: stopCommandId,
564 threadId: parentThreadId,
565 runId: secondRun.id,
566 holdQueue: true,
567 });
568​
569 assert.deepEqual(yield* threadState(parentThreadId), {
570 runs: ["completed", "interrupted"],
571 watched: [],
572 });
573 const parent = yield* orchestrator.getThreadProjection(parentThreadId);
574 assert.equal(parent.subagents[0]?.completionDelivery?.state, "disposed");
575 const effects = yield* sql<{ readonly effect_type: string }>`
576 SELECT effect_type FROM orchestration_v2_effect_outbox WHERE command_id = ${stopCommandId}
577 `;
578 assert.include(
579 effects.map((row) => row.effect_type),
580 "delegated-tasks.stop",
581 );
582​
583 yield* threads.stopDelegatedTasks({ threadId: parentThreadId, commandId: stopCommandId });
584 assert.deepEqual(yield* threadState(childThreadId), {
585 runs: ["interrupted", "queued:held"],
586 watched: [],
587 });
588 assert.deepEqual((yield* threadState(grandchildThreadId)).runs, ["interrupted"]);
589​
590 yield* threads.stopDelegatedTasks({ threadId: parentThreadId, commandId: stopCommandId });
591 assert.deepEqual((yield* threadState(childThreadId)).runs, ["interrupted", "queued:held"]);
592 }).pipe(Effect.provide(layerTest)),
593);
594​
595it.effect.each(["thread.stop", "run.interrupt"] as const)(
596 "%s cancels buffered wakes and preserves durable queued messages",
597 (type) =>
598 Effect.gen(function* () {
599 const orchestrator = yield* Orchestrator.OrchestratorV2;
600 const threadId = ThreadId.make(`thread:stop-buffered:${type}`);
601 yield* createWatchingThread(threadId, 5);
602 yield* send(threadId, "active", "start_immediately");
603 yield* send(threadId, "user follow-up", "queue_after_active");
604 for (const creationSource of ["provider", "server"] as const) {
605 yield* orchestrator.dispatch({
606 type: "message.dispatch",
607 commandId: CommandId.make(`notification:${type}:${creationSource}`),
608 threadId,
609 messageId: MessageId.make(`notification:${type}:${creationSource}`),
610 text: "Background activity updated",
611 attachments: [],
612 createdBy: "agent",
613 creationSource,
614 notification: {
615 source: { kind: "background_task" },
616 outcome: "updated",
617 summary: "Background activity updated",
618 },
619 dispatchMode: { type: "queue_after_active" },
620 });
621 }
622 const before = yield* orchestrator.getThreadProjection(threadId);
623 const buffered = before.runs.find((run) =>
624 before.messages.some(
625 (message) => message.id === run.userMessageId && message.creationSource === "provider",
626 ),
627 )!;
628 const stop = { commandId: CommandId.make(`stop:${type}`), threadId };
629 yield* orchestrator.dispatch(
630 type === "run.interrupt"
631 ? { ...stop, type, runId: before.runs[0]!.id, holdQueue: true }
632 : { ...stop, type },
633 );
634 const stopped = yield* orchestrator.getThreadProjection(threadId);
635 assert.equal(stopped.runs.find((run) => run.id === buffered.id)?.status, "cancelled");
636 assert.equal(
637 stopped.attempts.find((attempt) => attempt.runId === buffered.id)?.status,
638 "cancelled",
639 );
640 assert.equal(
641 stopped.nodes.find((node) => node.id === buffered.rootNodeId)?.status,
642 "cancelled",
643 );
644 assert.deepEqual(
645 stopped.runs.filter((run) => run.status === "queued").map((run) => run.queueHeld),
646 [true, true],
647 );
648 }).pipe(Effect.provide(layerTest)),
649);
650​
651it.effect("a message the user sends after Stop releases the held queue; an agent's does not", () =>
652 Effect.gen(function* () {
653 const orchestrator = yield* Orchestrator.OrchestratorV2;
654 const projections = yield* ProjectionStore.ProjectionStoreV2;
655 const threadId = ThreadId.make("thread:stop-release");
656 const agentSend = (text: string) =>
657 orchestrator.dispatch({
658 type: "message.dispatch",
659 commandId: CommandId.make(`agent-send:${text}`),
660 threadId,
661 messageId: MessageId.make(`message:${threadId}:${text}`),
662 text,
663 attachments: [],
664 dispatchMode: { type: "queue_after_active" },
665 createdBy: "agent",
666 creationSource: "mcp",
667 });
668 yield* createWatchingThread(threadId, 6);
669 yield* send(threadId, "active", "start_immediately");
670 yield* send(threadId, "queued before the stop", "queue_after_active");
671 yield* orchestrator.dispatch({
672 type: "thread.stop",
673 commandId: CommandId.make("stop-release"),
674 threadId,
675 });
676 assert.deepEqual((yield* threadState(threadId)).runs, ["interrupted", "queued:held"]);
677​
678 // An agent's message starts on the idle thread, but the hold is the user's.
679 yield* agentSend("agent nudge");
680 assert.deepEqual((yield* threadState(threadId)).runs, [
681 "interrupted",
682 "queued:held",
683 "starting",
684 ]);
685 const nudge = (yield* orchestrator.getThreadProjection(threadId)).runs.at(-1)!;
686 const now = yield* DateTime.now;
687 yield* projections.apply({
688 id: EventId.make("event:stop-release:nudge-completed"),
689 type: "run.updated",
690 threadId,
691 runId: nudge.id,
692 occurredAt: now,
693 payload: { ...nudge, status: "completed", completedAt: now },
694 });
695​
696 // A scheduled task the user created is not the user coming back.
697 yield* orchestrator.dispatch({
698 type: "message.dispatch",
699 commandId: CommandId.make("scheduled-send"),
700 threadId,
701 messageId: MessageId.make(`message:${threadId}:scheduled`),
702 text: "Nightly check",
703 attachments: [],
704 dispatchMode: { type: "queue_after_active" },
705 createdBy: "user",
706 creationSource: "web",
707 scheduledTaskId: ScheduledTaskId.make("scheduled:nightly"),
708 });
709 const scheduled = (yield* orchestrator.getThreadProjection(threadId)).runs.at(-1)!;
710 assert.deepEqual((yield* threadState(threadId)).runs, [
711 "interrupted",
712 "queued:held",
713 "completed",
714 "starting",
715 ]);
716 yield* projections.apply({
717 id: EventId.make("event:stop-release:scheduled-completed"),
718 type: "run.updated",
719 threadId,
720 runId: scheduled.id,
721 occurredAt: now,
722 payload: { ...scheduled, status: "completed", completedAt: now },
723 });
724​
725 // The user is back: the held message follows their run, and a wake that
726 // queues behind it is not held by the old Stop.
727 yield* send(threadId, "back", "start_immediately");
728 yield* agentSend("task finished");
729 assert.deepEqual((yield* threadState(threadId)).runs, [
730 "interrupted",
731 "queued",
732 "completed",
733 "completed",
734 "starting",
735 "queued",
736 ]);
737 }).pipe(Effect.provide(layerTest)),
738);
739​
740it.effect(
741 "thread.stop ends an idle thread's watches and accepts a thread with nothing to stop",
742 () =>
743 Effect.gen(function* () {
744 const orchestrator = yield* Orchestrator.OrchestratorV2;
745 const threadId = ThreadId.make("thread:stop-idle");
746 yield* createWatchingThread(threadId, 3);
747​
748 yield* orchestrator.dispatch({
749 type: "thread.stop",
750 commandId: CommandId.make("stop-idle"),
751 threadId,
752 });
753 assert.deepEqual(yield* threadState(threadId), { runs: [], watched: [] });
754​
755 const again = yield* orchestrator.dispatch({
756 type: "thread.stop",
757 commandId: CommandId.make("stop-idle-again"),
758 threadId,
759 });
760 assert.lengthOf(again.storedEvents, 0);
761 }).pipe(Effect.provide(layerTest)),
762);
763​
764it.effect.each([false, true])(
765 "a completed watch records whether it ended through Stop (%s)",
766 (stopped) =>
767 Effect.gen(function* () {
768 const orchestrator = yield* Orchestrator.OrchestratorV2;
769 const projections = yield* ProjectionStore.ProjectionStoreV2;
770 const threadId = ThreadId.make(`thread:watch-completion:${stopped}`);
771 yield* createWatchingThread(threadId, 7);
772 yield* send(threadId, "watch", "start_immediately");
773 const run = (yield* orchestrator.getThreadProjection(threadId)).runs[0]!;
774 const now = yield* DateTime.now;
775 const completedRun = {
776 ...run,
777 providerThreadId: run.providerThreadId ?? ProviderThreadId.make("provider-thread:watch"),
778 status: "completed" as const,
779 startedAt: now,
780 completedAt: now,
781 };
782 yield* projections.apply({
783 id: EventId.make("event:watch-completed"),
784 type: "run.updated",
785 threadId,
786 occurredAt: now,
787 payload: completedRun,
788 });
789 assert.isFalse((yield* projections.getThreadShell(threadId))?.latestRunStopRequested);
790​
791 yield* orchestrator.dispatch(
792 stopped
793 ? { type: "thread.stop", commandId: CommandId.make("stop-watch"), threadId }
794 : {
795 type: "thread.pull-request.watch",
796 commandId: CommandId.make("finish-watch"),
797 threadId,
798 ...pullRequest(7),
799 watching: false,
800 },
801 );
802 const shell = yield* projections.getThreadShell(threadId);
803 const snapshot = (yield* projections.getShellSnapshot()).threads.find(
804 (thread) => thread.id === threadId,
805 );
806 const memoryShell = ProjectionStore.threadShellFromProjection(
807 yield* orchestrator.getThreadProjection(threadId),
808 );
809 for (const result of [shell, snapshot, memoryShell]) {
810 assert.equal(result?.status, "completed");
811 assert.isEmpty(result?.pendingBackgroundTasks ?? []);
812 assert.equal(result?.latestRunStopRequested, stopped);
813 }
814​
815 yield* send(threadId, "next", "start_immediately");
816 assert.isFalse((yield* projections.getThreadShell(threadId))?.latestRunStopRequested);
817 }).pipe(Effect.provide(layerTest)),
818);
819​
820it.effect("a run Stop reached cannot delegate or start a watch, even after it ends", () =>
821 Effect.gen(function* () {
822 const orchestrator = yield* Orchestrator.OrchestratorV2;
823 const projections = yield* ProjectionStore.ProjectionStoreV2;
824 const threadId = ThreadId.make("thread:stop-barrier");
825 yield* createWatchingThread(threadId, 4);
826 yield* send(threadId, "work", "start_immediately");
827 const now = yield* DateTime.now;
828 const run = { ...(yield* orchestrator.getThreadProjection(threadId)).runs[0]!, startedAt: now };
829 yield* projections.apply({
830 id: EventId.make("event:stop-barrier:running"),
831 type: "run.updated",
832 threadId,
833 runId: run.id,
834 occurredAt: now,
835 payload: { ...run, status: "running" },
836 });
837 yield* send(threadId, "queued", "queue_after_active");
838 const queued = (yield* orchestrator.getThreadProjection(threadId)).runs.at(-1)!;
839 yield* orchestrator.dispatch({
840 type: "queued-run.cancel",
841 commandId: CommandId.make("cancel-queued"),
842 threadId,
843 runId: queued.id,
844 });
845 yield* projections.apply({
846 id: EventId.make("event:stop-barrier:interrupt-request"),
847 type: "turn-item.updated",
848 threadId,
849 runId: run.id,
850 occurredAt: now,
851 payload: {
852 id: TurnItemId.make("turn-item:stop-barrier:interrupt-request"),
853 threadId,
854 runId: run.id,
855 nodeId: run.rootNodeId!,
856 providerThreadId: run.providerThreadId!,
857 providerTurnId: null,
858 nativeItemRef: null,
859 parentItemId: null,
860 ordinal: 1_000,
861 status: "completed",
862 title: "Interrupt requested",
863 startedAt: now,
864 completedAt: now,
865 updatedAt: now,
866 type: "run_interrupt_request",
867 message: "Stop",
868 },
869 });
870​
871 assert.isTrue(Exit.isFailure(yield* Effect.exit(delegate(threadId, "late task"))));
872 assert.isTrue(Exit.isFailure(yield* Effect.exit(watch(threadId, 5))));
873​
874 yield* projections.apply({
875 id: EventId.make("event:stop-barrier:interrupted"),
876 type: "run.updated",
877 threadId,
878 runId: run.id,
879 occurredAt: now,
880 payload: { ...run, status: "interrupted", completedAt: now },
881 });
882 assert.isTrue(Exit.isFailure(yield* Effect.exit(watch(threadId, 5))));
883 assert.deepEqual(yield* threadState(threadId), {
884 runs: ["interrupted", "cancelled"],
885 watched: [4],
886 });
887​
888 for (const watching of [false, true]) {
889 yield* orchestrator.dispatch({
890 type: "thread.pull-request.watch",
891 commandId: CommandId.make(`manual-watch:${watching}`),
892 threadId,
893 ...pullRequest(4),
894 watching,
895 });
896 }
897 assert.deepEqual((yield* threadState(threadId)).watched, [4]);
898 }).pipe(Effect.provide(layerTest)),
899);
900​
901it.effect("thread.stop keeps a restart continuation of the stopped run from starting", () =>
902 Effect.gen(function* () {
903 const orchestrator = yield* Orchestrator.OrchestratorV2;
904 const projections = yield* ProjectionStore.ProjectionStoreV2;
905 const sql = yield* SqlClient.SqlClient;
906 const threadId = ThreadId.make("thread:stop-restart");
907 yield* createWatchingThread(threadId, 8);
908 yield* send(threadId, "work", "start_immediately");
909 const now = yield* DateTime.now;
910 const run = (yield* orchestrator.getThreadProjection(threadId)).runs[0]!;
911 yield* projections.apply({
912 id: EventId.make("event:stop-restart:cancelled"),
913 type: "run.updated",
914 threadId,
915 runId: run.id,
916 occurredAt: now,
917 payload: { ...run, status: "cancelled", startedAt: null, completedAt: now },
918 });
919 const at = DateTime.formatIso(now);
920 yield* sql`
921 INSERT INTO orchestration_v2_effect_outbox (
922 effect_id, command_id, thread_id, effect_type, payload_json, status,
923 attempt_count, available_at, created_at, updated_at
924 ) VALUES (
925 ${`effect:restart-continuation:${run.id}`}, 'command:restart', ${threadId},
926 'provider-runtime.continue',
927 ${encodeEffectRequest({ type: "provider-runtime.continue", sourceRunId: run.id })},
928 'pending', 0, ${at}, ${at}, ${at}
929 )
930 `;
931​
932 yield* orchestrator.dispatch({
933 type: "thread.stop",
934 commandId: CommandId.make("stop-restart"),
935 threadId,
936 });
937 yield* orchestrator.dispatch({
938 type: "message.dispatch",
939 commandId: CommandId.make("restart-continuation"),
940 threadId,
941 messageId: MessageId.make("message:restart-continuation"),
942 text: "Continue.",
943 attachments: [],
944 dispatchMode: { type: "start_immediately" },
945 createdBy: "agent",
946 creationSource: "server",
947 restartContinuationOfRunId: run.id,
948 });
949 assert.deepEqual(yield* threadState(threadId), { runs: ["cancelled"], watched: [] });
950 }).pipe(Effect.provide(layerTest)),
951);
952​
953it.effect.each(["thread.stop", "run.interrupt"] as const)(
954 "a successful %s blocks a newer restart continuation when completion timestamps tie",
955 (stopType) =>
956 Effect.gen(function* () {
957 const orchestrator = yield* Orchestrator.OrchestratorV2;
958 const projections = yield* ProjectionStore.ProjectionStoreV2;
959 const sql = yield* SqlClient.SqlClient;
960 const threadId = ThreadId.make("thread:stop-resumed-queue");
961 yield* createWatchingThread(threadId, 12);
962 yield* send(threadId, "first", "start_immediately");
963 yield* send(threadId, "queued", "queue_after_active");
964 const now = yield* DateTime.now;
965 const [first, queued] = (yield* orchestrator.getThreadProjection(threadId)).runs;
966 assert.isDefined(first);
967 assert.isDefined(queued);
968 for (const run of [first!, queued!]) {
969 yield* projections.apply({
970 id: EventId.make(`event:stop-resumed-queue:hold:${run.id}`),
971 type: "run.updated",
972 threadId,
973 runId: run.id,
974 occurredAt: now,
975 payload:
976 run.id === first!.id
977 ? { ...run, status: "completed", completedAt: now }
978 : { ...run, queueHeld: true },
979 });
980 }
981 yield* send(threadId, "restart source", "start_immediately");
982 const source = (yield* orchestrator.getThreadProjection(threadId)).runs.at(-1)!;
983 yield* projections.apply({
984 id: EventId.make("event:stop-resumed-queue:restart-cancelled"),
985 type: "run.updated",
986 threadId,
987 runId: source.id,
988 occurredAt: now,
989 payload: { ...source, status: "cancelled", startedAt: now, completedAt: now },
990 });
991 const at = DateTime.formatIso(now);
992 yield* sql`
993 INSERT INTO orchestration_v2_effect_outbox (
994 effect_id, command_id, thread_id, effect_type, payload_json, status,
995 attempt_count, available_at, created_at, updated_at
996 ) VALUES (
997 ${`effect:restart-continuation:${source.id}`}, 'command:restart', ${threadId},
998 'provider-runtime.continue',
999 ${encodeEffectRequest({ type: "provider-runtime.continue", sourceRunId: source.id })},
1000 'pending', 0, ${at}, ${at}, ${at}
1002 `;
1003 yield* orchestrator.dispatch({
1004 type: "queue.resume",
1005 commandId: CommandId.make("resume-older-queue"),
1006 threadId,
1007 });
1008 assert.equal(
1009 (yield* orchestrator.getThreadProjection(threadId)).runs.find(
1010 (run) => run.id === queued!.id,
1011 )?.status,
1012 "starting",
1013 );
1014 yield* orchestrator.dispatch(
1015 stopType === "thread.stop"
1016 ? { type: "thread.stop", commandId: CommandId.make("stop-resumed-queue"), threadId }
1017 : {
1018 type: "run.interrupt",
1019 commandId: CommandId.make("stop-resumed-queue"),
1020 threadId,
1021 runId: queued!.id,
1022 holdQueue: true,
1023 },
1024 );
1025 const stopped = yield* orchestrator.getThreadProjection(threadId);
1026 const interrupted = stopped.runs.find((run) => run.id === queued!.id)!;
1027 assert.equal(interrupted.status, "interrupted");
1028 assert.equal(DateTime.toEpochMillis(interrupted.completedAt!), DateTime.toEpochMillis(now));
1029 yield* orchestrator.dispatch({
1030 type: "message.dispatch",
1031 commandId: CommandId.make("restart-after-stop"),
1032 threadId,
1033 messageId: MessageId.make("message:restart-after-stop"),
1034 text: "Continue.",
1035 attachments: [],
1036 dispatchMode: { type: "start_immediately" },
1037 createdBy: "agent",
1038 creationSource: "server",
1039 restartContinuationOfRunId: source.id,
1040 });
1041 // The held run resumed after the cancelled source ran, so it sorts after it.
1042 assert.deepEqual(yield* threadState(threadId), {
1043 runs: ["completed", "cancelled", "interrupted"],
1044 watched: [],
1045 });
1046 }).pipe(Effect.provide(layerTest.pipe(Layer.provideMerge(TestClock.layer())))),
1048​
1049it.effect.each([
1050 { ending: "cancelled", question: "resolved" },
1051 { ending: "interrupted", question: "resolved" },
1052 { ending: "completed", question: "pending" },
1053 { ending: "failed", question: "pending" },
1054] as const)(
1055 "a $ending delegated task leaves its async question $question",
1056 ({ ending, question }) =>
1057 Effect.gen(function* () {
1058 const orchestrator = yield* Orchestrator.OrchestratorV2;
1059 const projections = yield* ProjectionStore.ProjectionStoreV2;
1060 const parentThreadId = ThreadId.make(`thread:stop-question-parent:${ending}`);
1061 yield* createWatchingThread(parentThreadId, 20);
1062 yield* send(parentThreadId, "first", "start_immediately");
1063 const childThreadId = yield* delegate(parentThreadId, `question task ${ending}`);
1064 const childRun = (yield* orchestrator.getThreadProjection(childThreadId)).runs[0]!;
1065 assert.equal(
1066 (yield* orchestrator.getThreadProjection(childThreadId)).nodes.find(
1067 (node) => node.id === childRun.rootNodeId,
1068 )?.runId,
1069 childRun.id,
1070 );
1071 const now = yield* DateTime.now;
1072 yield* projections.apply({
1073 id: EventId.make("event:stop-question:request"),
1074 type: "runtime-request.updated",
1075 threadId: childThreadId,
1076 runId: childRun.id,
1077 occurredAt: now,
1078 payload: {
1079 id: RuntimeRequestId.make("request:stop-question"),
1080 nodeId: childRun.rootNodeId!,
1081 providerTurnId: null,
1082 nativeRequestRef: null,
1083 kind: "user_input",
1084 status: "pending",
1085 responseCapability: { type: "message" },
1086 createdAt: now,
1087 resolvedAt: null,
1088 },
1089 });
1090 const request = Effect.map(
1091 orchestrator.getThreadProjection(childThreadId),
1092 (projection) => projection.runtimeRequests[0],
1093 );
1094​
1095 yield* orchestrator.recoverDelegatedTask(childThreadId, childRun.id);
1096 assert.equal((yield* request)?.status, "pending");
1097 if (ending === "interrupted") {
1098 yield* orchestrator.dispatch({
1099 type: "thread.stop",
1100 commandId: CommandId.make("stop-question-child"),
1101 threadId: childThreadId,
1102 });
1103 } else {
1104 yield* projections.apply({
1105 id: EventId.make(`event:stop-question:${ending}`),
1106 type: "run.updated",
1107 threadId: childThreadId,
1108 runId: childRun.id,
1109 occurredAt: now,
1110 payload: { ...childRun, status: ending, startedAt: now, completedAt: now },
1111 });
1113 yield* orchestrator.recoverDelegatedTask(childThreadId, childRun.id);
1114 assert.equal((yield* request)?.status, question);
1115 assert.equal((yield* request)?.decision, question === "resolved" ? "cancel" : undefined);
1116 }).pipe(Effect.provide(layerTest)),
1118​
1119it.effect("a delegated task that cannot be stopped fails the walk after its siblings stop", () =>
1120 Effect.gen(function* () {
1121 const orchestrator = yield* Orchestrator.OrchestratorV2;
1122 const projections = yield* ProjectionStore.ProjectionStoreV2;
1123 const threads = yield* ThreadManagementService.ThreadManagementService;
1124 const parentThreadId = ThreadId.make("thread:stop-partial");
1125 yield* createWatchingThread(parentThreadId, 6);
1126 yield* send(parentThreadId, "work", "start_immediately");
1127 const childThreadId = yield* delegate(parentThreadId, "stoppable task");
1128 const task = (yield* orchestrator.getThreadProjection(parentThreadId)).subagents[0]!;
1129 yield* projections.apply({
1130 id: EventId.make("event:stop-partial:missing-task"),
1131 type: "subagent.updated",
1132 threadId: parentThreadId,
1133 runId: task.runId!,
1134 nodeId: NodeId.make("node:stop-partial:missing"),
1135 providerInstanceId: instanceId,
1136 occurredAt: yield* DateTime.now,
1137 payload: {
1138 ...task,
1139 id: NodeId.make("node:stop-partial:missing"),
1140 childThreadId: ThreadId.make("thread:stop-partial:missing"),
1141 startedAt: DateTime.subtract(task.startedAt!, { hours: 1 }),
1142 },
1143 });
1144​
1145 const walked = yield* Effect.exit(
1146 threads.stopDelegatedTasks({
1147 threadId: parentThreadId,
1148 commandId: CommandId.make("stop-partial"),
1149 }),
1150 );
1151 assert.isTrue(Exit.isFailure(walked));
1152 assert.deepEqual((yield* threadState(childThreadId)).runs, ["interrupted"]);
1153 }).pipe(Effect.provide(layerTest)),
1155​
1156it.effect("thread.stop marks a turn it cannot interrupt so a late agent watch is refused", () =>
1157 Effect.gen(function* () {
1158 const orchestrator = yield* Orchestrator.OrchestratorV2;
1159 const projections = yield* ProjectionStore.ProjectionStoreV2;
1160 const threadId = ThreadId.make("thread:stop-lost-session");
1161 yield* createWatchingThread(threadId, 11);
1162 yield* send(threadId, "work", "start_immediately");
1163 const now = yield* DateTime.now;
1164 const run = (yield* orchestrator.getThreadProjection(threadId)).runs[0]!;
1165 yield* projections.apply({
1166 id: EventId.make("event:stop-lost-session:running"),
1167 type: "run.updated",
1168 threadId,
1169 runId: run.id,
1170 occurredAt: now,
1171 payload: { ...run, status: "running", startedAt: now },
1172 });
1173 yield* projections.apply({
1174 id: EventId.make("event:stop-lost-session:turn"),
1175 type: "provider-turn.updated",
1176 threadId,
1177 occurredAt: now,
1178 payload: {
1179 id: ProviderTurnId.make("provider-turn:stop-lost-session"),
1180 providerThreadId: run.providerThreadId!,
1181 nodeId: run.rootNodeId!,
1182 runAttemptId: run.activeAttemptId!,
1183 nativeTurnRef: null,
1184 ordinal: 1,
1185 status: "running",
1186 startedAt: now,
1187 completedAt: null,
1188 },
1189 });
1190​
1191 yield* orchestrator.dispatch({
1192 type: "thread.stop",
1193 commandId: CommandId.make("stop-lost-session"),
1194 threadId,
1195 });
1196 assert.isTrue(Exit.isFailure(yield* Effect.exit(watch(threadId, 12))));
1197 assert.deepEqual(yield* threadState(threadId), { runs: ["running"], watched: [] });
1198 }).pipe(Effect.provide(layerTest)),
1200​
1201it.effect.each(["missing session", "completed", "failed", "cancelled"] as const)(
1202 "a native child Stop only settles a confirmed %s outcome and preserves its owner and sibling",
1203 (providerState) =>
1204 Effect.gen(function* () {
1205 const orchestrator = yield* Orchestrator.OrchestratorV2;
1206 const projections = yield* ProjectionStore.ProjectionStoreV2;
1207 const sql = yield* SqlClient.SqlClient;
1208 const threadId = ThreadId.make("thread:native-child-stop");
1209 yield* createWatchingThread(threadId, 20);
1210 yield* send(threadId, "owner", "start_immediately");
1211 yield* delegate(threadId, "native-child-fixture");
1212 const before = yield* orchestrator.getThreadProjection(threadId);
1213 const run = before.runs[0]!;
1214 const now = yield* DateTime.now;
1215 const subagent = {
1216 ...before.subagents[0]!,
1217 origin: "provider_native" as const,
1218 driver: CLAUDE_PROVIDER,
1219 providerInstanceId: ProviderInstanceId.make("claudeAgent"),
1220 nativeTaskRef: {
1221 driver: CLAUDE_PROVIDER,
1222 nativeId: "claude-task",
1223 strength: "strong" as const,
1224 },
1225 status: "running" as const,
1226 startedAt: now,
1227 };
1228 yield* projections.apply({
1229 id: EventId.make("event:native-child-stop:agent"),
1230 type: "subagent.updated",
1231 threadId,
1232 runId: run.id,
1233 nodeId: subagent.id,
1234 occurredAt: now,
1235 payload: subagent,
1236 });
1237 const sibling = {
1238 ...subagent,
1239 id: NodeId.make("node:native-stop-sibling"),
1240 childThreadId: null,
1241 };
1242 yield* projections.apply({
1243 id: EventId.make("event:native-child-stop:sibling"),
1244 type: "subagent.updated",
1245 threadId,
1246 runId: run.id,
1247 nodeId: sibling.id,
1248 occurredAt: now,
1249 payload: sibling,
1250 });
1251 const item = before.turnItems.find(
1252 (item) => item.type === "subagent" && item.subagentId === subagent.id,
1253 )!;
1254 yield* projections.apply({
1255 id: EventId.make("event:native-child-stop:item"),
1256 type: "turn-item.updated",
1257 threadId,
1258 runId: run.id,
1259 occurredAt: now,
1260 payload: { ...item, status: "running", completedAt: null },
1261 });
1262 const childRoot = {
1263 ...before.nodes.find((node) => node.id === run.rootNodeId)!,
1264 id: NodeId.make("node:native-stop-child-root"),
1265 threadId: subagent.childThreadId!,
1266 runId: null,
1267 parentNodeId: null,
1268 status: "running" as const,
1269 countsForRun: false,
1270 completedAt: null,
1271 };
1272 yield* projections.apply({
1273 id: EventId.make("event:native-child-stop:child-root"),
1274 type: "node.updated",
1275 threadId: childRoot.threadId,
1276 nodeId: childRoot.id,
1277 occurredAt: now,
1278 payload: childRoot,
1279 });
1280 const providerThread = before.providerThreads.find(
1281 (thread) => thread.id === run.providerThreadId,
1282 )!;
1283 yield* projections.apply({
1284 id: EventId.make("event:native-child-stop:provider-thread"),
1285 type: "provider-thread.updated",
1286 threadId,
1287 occurredAt: now,
1288 payload: {
1289 ...providerThread,
1290 driver: CLAUDE_PROVIDER,
1291 providerInstanceId: ProviderInstanceId.make("claudeAgent"),
1292 providerSessionId: ProviderSessionId.make("session:native-child-stop"),
1293 },
1294 });
1295 const providerTurnId = ProviderTurnId.make("turn:native-child-stop");
1296 yield* projections.apply({
1297 id: EventId.make("event:native-child-stop:provider-turn"),
1298 type: "provider-turn.updated",
1299 threadId,
1300 occurredAt: now,
1301 payload: {
1302 id: providerTurnId,
1303 providerThreadId: providerThread.id,
1304 nodeId: run.rootNodeId!,
1305 runAttemptId: run.activeAttemptId!,
1306 nativeTurnRef: null,
1307 ordinal: 1,
1308 status: "completed",
1309 startedAt: now,
1310 completedAt: now,
1311 },
1312 });
1313 yield* projections.apply({
1314 id: EventId.make("event:native-child-stop:owner-completed"),
1315 type: "run.updated",
1316 threadId,
1317 runId: run.id,
1318 occurredAt: now,
1319 payload: { ...run, status: "completed", startedAt: now, completedAt: now },
1320 });
1321 yield* send(threadId, "queued", "queue_after_active");
1322 const stateBefore = yield* threadState(threadId);
1323 const eventStore = yield* EventStore.EventStoreV2;
1324 const afterSequence = yield* eventStore.latestSequence({ threadId });
1325 const confirmedStatus =
1326 providerState === "completed" || providerState === "failed" || providerState === "cancelled"
1327 ? providerState
1328 : null;
1329 const confirmedOutcome =
1330 confirmedStatus === null
1331 ? undefined
1332 : { status: confirmedStatus, completedAt: now, result: "Actual provider outcome" };
1333 const commandId = CommandId.make("stop-native-child");
1334 yield* orchestrator.dispatch({
1335 type: "subagent.stop",
1336 commandId,
1337 threadId,
1338 runId: run.id,
1339 subagentId: subagent.id,
1340 });
1341 assert.deepEqual(yield* threadState(threadId), stateBefore);
1342 const effects = yield* sql<{ payload_json: string }>`
1343 SELECT payload_json FROM orchestration_v2_effect_outbox WHERE command_id = ${commandId}
1344 `;
1345 assert.equal(effects.length, 1);
1346 assert.deepEqual(JSON.parse(effects[0]!.payload_json), {
1347 type: "provider-turn.interrupt",
1348 providerSessionId: "session:native-child-stop",
1349 providerThreadId: providerThread.id,
1350 providerTurnId,
1351 subagent: { id: subagent.id, nativeTaskId: "claude-task" },
1352 });
1353 assert.equal(
1354 (yield* orchestrator.getThreadProjection(threadId)).subagents[0]?.status,
1355 "running",
1356 );
1357 const unrelated = yield* Effect.exit(
1358 orchestrator.dispatch({
1359 type: "subagent.stop",
1360 commandId: CommandId.make("stop-unknown-child"),
1361 threadId,
1362 runId: run.id,
1363 subagentId: NodeId.make("unknown-child"),
1364 }),
1365 );
1366 assert.isTrue(Exit.isFailure(unrelated));
1367 yield* TestClock.adjust("1 second");
1368 yield* sql`DELETE FROM orchestration_v2_effect_outbox WHERE command_id != ${commandId}`;
1369 if (providerState === "missing session") {
1370 const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
1371 yield* worker.drain();
1372 } else {
1373 yield* orchestrator.dispatch({
1374 type: "thread.background-work.settle",
1375 commandId: CommandId.make("repair-native-child"),
1376 threadId,
1377 providerThreadId: providerThread.id,
1378 providerTurnId,
1379 subagent: { id: subagent.id, stoppedAt: now, outcome: confirmedOutcome! },
1380 });
1382 const settled = yield* orchestrator.getThreadProjection(threadId);
1383 const cancelled = settled.subagents.find((task) => task.id === subagent.id)!;
1384 if (confirmedOutcome === undefined) {
1385 const events = yield* eventStore.read({ threadId, afterSequence }).pipe(Stream.runCollect);
1386 assert.isFalse(
1387 events.some(
1388 ({ event }) =>
1389 (event.type === "subagent.updated" ||
1390 event.type === "node.updated" ||
1391 event.type === "turn-item.updated") &&
1392 ["completed", "failed", "cancelled", "interrupted"].includes(event.payload.status),
1393 ),
1394 );
1395 assert.equal(cancelled.status, "running");
1396 assert.equal(
1397 (yield* orchestrator.getThreadProjection(childRoot.threadId)).nodes.find(
1398 (node) => node.id === childRoot.id,
1399 )?.status,
1400 "running",
1401 );
1402 assert.deepEqual(yield* threadState(threadId), stateBefore);
1403 return;
1405​
1406 const repaired = yield* eventStore.read({ threadId, afterSequence }).pipe(Stream.runCollect);
1407 const terminal = repaired.flatMap(({ event }) =>
1408 (event.type === "subagent.updated" ||
1409 event.type === "node.updated" ||
1410 event.type === "turn-item.updated") &&
1411 event.payload.status === confirmedStatus
1412 ? [event]
1413 : [],
1414 );
1415 assert.deepEqual(terminal.map((event) => event.type).sort(), [
1416 "node.updated",
1417 "subagent.updated",
1418 "turn-item.updated",
1419 ]);
1420 for (const event of terminal) {
1421 assert.equal(event.nodeId, subagent.id);
1422 assert.equal(
1423 DateTime.toEpochMillis(event.payload.completedAt!),
1424 DateTime.toEpochMillis(confirmedOutcome!.completedAt),
1425 );
1426 if (event.type === "subagent.updated" || event.type === "turn-item.updated") {
1427 assert.isDefined(event.payload.updatedAt);
1430​
1431 assert.equal(cancelled.status, confirmedStatus);
1432 assert.isNotNull(cancelled.completedAt);
1433 assert.equal(
1434 DateTime.toEpochMillis(cancelled.completedAt!),
1435 DateTime.toEpochMillis(confirmedOutcome!.completedAt),
1436 );
1437 assert.equal(cancelled.result, confirmedOutcome!.result);
1438 assert.equal(
1439 settled.turnItems.find((candidate) => candidate.id === item.id)?.status,
1440 confirmedStatus,
1441 );
1442 const child = yield* orchestrator.getThreadProjection(childRoot.threadId);
1443 assert.equal(child.nodes.find((node) => node.id === childRoot.id)?.status, confirmedStatus);
1444 assert.isNotNull(child.nodes.find((node) => node.id === childRoot.id)?.completedAt);
1445 assert.equal(settled.subagents.find((task) => task.id === sibling.id)?.status, "running");
1446 assert.deepEqual(yield* threadState(threadId), stateBefore);
1447 yield* TestClock.adjust("1 second");
1448 const resumedAt = yield* DateTime.now;
1449 yield* projections.apply({
1450 id: EventId.make("event:native-child-stop:resume"),
1451 type: "subagent.updated",
1452 threadId,
1453 runId: run.id,
1454 nodeId: subagent.id,
1455 occurredAt: resumedAt,
1456 payload: { ...cancelled, status: "running", startedAt: resumedAt, completedAt: null },
1457 });
1458 yield* orchestrator.dispatch({
1459 type: "thread.background-work.settle",
1460 commandId: CommandId.make("old-stop-after-resume"),
1461 threadId,
1462 providerThreadId: providerThread.id,
1463 providerTurnId,
1464 subagent: { id: subagent.id, stoppedAt: now, outcome: confirmedOutcome },
1465 });
1466 assert.equal(
1467 (yield* orchestrator.getThreadProjection(threadId)).subagents.find(
1468 (task) => task.id === subagent.id,
1469 )?.status,
1470 "running",
1471 );
1472 }).pipe(Effect.provide(layerTest)),