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