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