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