Open History to see the last commit
1import { assert, it } from "@effect/vitest";
2import {
3 CommandId,
4 EventId,
5 MessageId,
6 NodeId,
7 ProjectId,
8 ProviderDriverKind,
9 ProviderInstanceId,
10 ProviderSessionId,
11 ProviderTurnId,
12 ThreadId,
13 TurnItemId,
14} from "@t3tools/contracts";
15import * as DateTime from "effect/DateTime";
16import * as Effect from "effect/Effect";
17import * as Exit from "effect/Exit";
18import * as Layer from "effect/Layer";
19import * as Schema from "effect/Schema";
20import * as SqlClient from "effect/sql/SqlClient";
21import * as Stream from "effect/Stream";
22import * as EventStore from "./EventStore.ts";
23import * as TestClock from "effect/testing/TestClock";
24
25import * as SqlitePersistence from "../persistence/Sqlite.ts";
26import * as ServerSettings from "../serverSettings.ts";
27import { CLAUDE_PROVIDER } from "./Adapters/ClaudeAdapterV2.ts";
28import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts";
29import * as CommandReceiptStore from "./CommandReceiptStore.ts";
30import { OrchestrationEffectRequestV2 } from "./EffectOutbox.ts";
31import * as Orchestrator from "./Orchestrator.ts";
32import * as EffectWorker from "./EffectWorker.ts";
33import * as EffectOutbox from "./EffectOutbox.ts";
34import * as ProjectionStore from "./ProjectionStore.ts";
35import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts";
36import * as ThreadManagementService from "./ThreadManagementService.ts";
37import * as ProviderReplayHarness from "./testkit/ProviderReplayHarness.ts";
38import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
39
40const instanceId = ProviderInstanceId.make("codex");
41const modelSelection = { instanceId, model: "gpt-5.1-codex" };
42const adapter = {
43 instanceId,
44 driver: ProviderDriverKind.make("codex"),
45 getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2),
46 planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" as const }),
47 openSession: () => Effect.die("Runs here never reach a provider"),
48} as ProviderAdapter.ProviderAdapterV2["Service"];
49const layerDatabase = SqlitePersistence.layerMemory;
50// No effect worker: runs stay unstarted, so Stop ends them without a provider.
51const layerTest = ThreadManagementService.layer.pipe(
52 Layer.provideMerge(
53 Layer.mergeAll(
54 layerDatabase,
55 ProjectionStore.layer.pipe(Layer.provide(layerDatabase)),
56 EventStore.layer.pipe(Layer.provide(layerDatabase)),
57 EffectOutbox.layer.pipe(Layer.provide(layerDatabase)),
58 ProviderReplayHarness.layerWithRegistry(
59 { name: "thread-stop" },
60 ProviderAdapterRegistry.layerFromAdapters([adapter]),
61 { databaseLayer: layerDatabase, runEffectWorker: false },
62 ),
63 ),
64 ),
65 Layer.provideMerge(ServerSettings.layerTest()),
66 Layer.provideMerge(CommandReceiptStore.layer.pipe(Layer.provide(layerDatabase))),
67);
68
69const encodeEffectRequest = Schema.encodeSync(Schema.fromJsonString(OrchestrationEffectRequestV2));
70
71const pullRequest = (number: number) => ({
72 host: "github.com",
73 repository: "pingdotgg/t3code",
74 number,
75});
76
77const createWatchingThread = (threadId: ThreadId, number: number) =>
78 Effect.gen(function* () {
79 const orchestrator = yield* Orchestrator.OrchestratorV2;
80 yield* orchestrator.dispatch({
81 type: "thread.create",
82 commandId: CommandId.make(`create:${threadId}`),
83 threadId,
84 projectId: ProjectId.make("project:thread-stop"),
85 title: threadId,
86 modelSelection,
87 runtimeMode: "full-access",
88 interactionMode: "default",
89 branch: null,
90 worktreePath: null,
91 createdBy: "user",
92 creationSource: "web",
93 });
94 yield* watch(threadId, number);
95 });
96
97const watch = (threadId: ThreadId, number: number) =>
98 Effect.gen(function* () {
99 const orchestrator = yield* Orchestrator.OrchestratorV2;
100 yield* orchestrator.dispatch({
101 type: "thread.pull-request.watch",
102 commandId: CommandId.make(`watch:${threadId}:${number}`),
103 threadId,
104 ...pullRequest(number),
105 watching: true,
106 link: { url: `https://github.com/pingdotgg/t3code/pull/${number}`, source: "agent" },
107 });
108 });
109
110const send = (threadId: ThreadId, text: string, type: "start_immediately" | "queue_after_active") =>
111 Effect.gen(function* () {
112 const orchestrator = yield* Orchestrator.OrchestratorV2;
113 yield* orchestrator.dispatch({
114 type: "message.dispatch",
115 commandId: CommandId.make(`send:${threadId}:${text}`),
116 threadId,
117 messageId: MessageId.make(`message:${threadId}:${text}`),
118 text,
119 attachments: [],
120 dispatchMode: { type },
121 createdBy: "user",
122 creationSource: "web",
123 });
124 });
125
126/** Delegates `task` from the parent's latest run and returns the child thread. */
127const delegate = (parentThreadId: ThreadId, task: string) =>
128 Effect.gen(function* () {
129 const orchestrator = yield* Orchestrator.OrchestratorV2;
130 const parentRun = (yield* orchestrator.getThreadProjection(parentThreadId)).runs.at(-1)!;
131 yield* orchestrator.dispatch({
132 type: "delegated_task.request",
133 commandId: CommandId.make(`delegate:${task}`),
134 parentThreadId,
135 parentRunId: parentRun.id,
136 parentNodeId: parentRun.rootNodeId!,
137 task,
138 modelSelection,
139 runtimeMode: "full-access",
140 interactionMode: "default",
141 completionWake: "always",
142 createdBy: "agent",
143 creationSource: "mcp",
144 });
145 const projection = yield* orchestrator.getThreadProjection(parentThreadId);
146 return projection.subagents.find((candidate) => candidate.prompt === task)!.childThreadId!;
147 });
148
149const threadState = (threadId: ThreadId) =>
150 Effect.gen(function* () {
151 const orchestrator = yield* Orchestrator.OrchestratorV2;
152 const projection = yield* orchestrator.getThreadProjection(threadId);
153 return {
154 runs: projection.runs.map((run) => `${run.status}${run.queueHeld === true ? ":held" : ""}`),
155 watched: (projection.thread.pullRequests ?? [])
156 .filter((link) => link.watch !== undefined)
157 .map((link) => link.number),
158 };
159 });
160
161it.effect("Stop ends watches, holds queues, and stops the delegated tasks under the thread", () =>
162 Effect.gen(function* () {
163 const orchestrator = yield* Orchestrator.OrchestratorV2;
164 const projections = yield* ProjectionStore.ProjectionStoreV2;
165 const threads = yield* ThreadManagementService.ThreadManagementService;
166 const sql = yield* SqlClient.SqlClient;
167 const parentThreadId = ThreadId.make("thread:stop-parent");
168 yield* createWatchingThread(parentThreadId, 1);
169 yield* send(parentThreadId, "first", "start_immediately");
170 const childThreadId = yield* delegate(parentThreadId, "child task");
171 // The parent owns its pull requests; a delegated task cannot watch one.
172 assert.isTrue(Exit.isFailure(yield* Effect.exit(watch(childThreadId, 2))));
173 const grandchildThreadId = yield* delegate(childThreadId, "grandchild task");
174 yield* send(childThreadId, "child follow-up", "queue_after_active");
175
176 // The run that delegated the child ends before the run the user stops, so
177 // only a Stop that covers earlier runs keeps the stopped child from waking it.
178 const now = yield* DateTime.now;
179 const firstRun = (yield* orchestrator.getThreadProjection(parentThreadId)).runs[0]!;
180 yield* projections.apply({
181 id: EventId.make("event:stop-parent:first-run-completed"),
182 type: "run.updated",
183 threadId: parentThreadId,
184 runId: firstRun.id,
185 occurredAt: now,
186 payload: { ...firstRun, status: "completed", completedAt: now },
187 });
188 yield* send(parentThreadId, "second", "start_immediately");
189 const secondRun = (yield* orchestrator.getThreadProjection(parentThreadId)).runs.at(-1)!;
190
191 const stopCommandId = CommandId.make("stop-parent");
192 yield* orchestrator.dispatch({
193 type: "run.interrupt",
194 commandId: stopCommandId,
195 threadId: parentThreadId,
196 runId: secondRun.id,
197 holdQueue: true,
198 });
199
200 assert.deepEqual(yield* threadState(parentThreadId), {
201 runs: ["completed", "interrupted"],
202 watched: [],
203 });
204 const parent = yield* orchestrator.getThreadProjection(parentThreadId);
205 assert.equal(parent.subagents[0]?.completionDelivery?.state, "disposed");
206 const effects = yield* sql<{ readonly effect_type: string }>`
207 SELECT effect_type FROM orchestration_v2_effect_outbox WHERE command_id = ${stopCommandId}
208 `;
209 assert.include(
210 effects.map((row) => row.effect_type),
211 "delegated-tasks.stop",
212 );
213
214 // What the delegated-tasks.stop effect runs once the Stop commits.
215 yield* threads.stopDelegatedTasks({ threadId: parentThreadId, commandId: stopCommandId });
216 assert.deepEqual(yield* threadState(childThreadId), {
217 runs: ["interrupted", "queued:held"],
218 watched: [],
219 });
220 assert.deepEqual((yield* threadState(grandchildThreadId)).runs, ["interrupted"]);
221
222 // A retried effect stops nothing twice.
223 yield* threads.stopDelegatedTasks({ threadId: parentThreadId, commandId: stopCommandId });
224 assert.deepEqual((yield* threadState(childThreadId)).runs, ["interrupted", "queued:held"]);
225 }).pipe(Effect.provide(layerTest)),
226);
227
228it.effect(
229 "thread.stop ends an idle thread's watches and accepts a thread with nothing to stop",
230 () =>
231 Effect.gen(function* () {
232 const orchestrator = yield* Orchestrator.OrchestratorV2;
233 const threadId = ThreadId.make("thread:stop-idle");
234 yield* createWatchingThread(threadId, 3);
235
236 yield* orchestrator.dispatch({
237 type: "thread.stop",
238 commandId: CommandId.make("stop-idle"),
239 threadId,
240 });
241 assert.deepEqual(yield* threadState(threadId), { runs: [], watched: [] });
242
243 const again = yield* orchestrator.dispatch({
244 type: "thread.stop",
245 commandId: CommandId.make("stop-idle-again"),
246 threadId,
247 });
248 assert.lengthOf(again.storedEvents, 0);
249 }).pipe(Effect.provide(layerTest)),
250);
251
252it.effect("a run Stop reached cannot delegate or start a watch, even after it ends", () =>
253 Effect.gen(function* () {
254 const orchestrator = yield* Orchestrator.OrchestratorV2;
255 const projections = yield* ProjectionStore.ProjectionStoreV2;
256 const threadId = ThreadId.make("thread:stop-barrier");
257 yield* createWatchingThread(threadId, 4);
258 yield* send(threadId, "work", "start_immediately");
259 const now = yield* DateTime.now;
260 const run = { ...(yield* orchestrator.getThreadProjection(threadId)).runs[0]!, startedAt: now };
261 yield* projections.apply({
262 id: EventId.make("event:stop-barrier:running"),
263 type: "run.updated",
264 threadId,
265 runId: run.id,
266 occurredAt: now,
267 payload: { ...run, status: "running" },
268 });
269 // A queued message the user cancelled does not count as the latest run.
270 yield* send(threadId, "queued", "queue_after_active");
271 const queued = (yield* orchestrator.getThreadProjection(threadId)).runs.at(-1)!;
272 yield* orchestrator.dispatch({
273 type: "queued-run.cancel",
274 commandId: CommandId.make("cancel-queued"),
275 threadId,
276 runId: queued.id,
277 });
278 // Stop reached the run, but its provider has not stopped it yet.
279 yield* projections.apply({
280 id: EventId.make("event:stop-barrier:interrupt-request"),
281 type: "turn-item.updated",
282 threadId,
283 runId: run.id,
284 occurredAt: now,
285 payload: {
286 id: TurnItemId.make("turn-item:stop-barrier:interrupt-request"),
287 threadId,
288 runId: run.id,
289 nodeId: run.rootNodeId!,
290 providerThreadId: run.providerThreadId!,
291 providerTurnId: null,
292 nativeItemRef: null,
293 parentItemId: null,
294 ordinal: 1_000,
295 status: "completed",
296 title: "Interrupt requested",
297 startedAt: now,
298 completedAt: now,
299 updatedAt: now,
300 type: "run_interrupt_request",
301 message: "Stop",
302 },
303 });
304
305 assert.isTrue(Exit.isFailure(yield* Effect.exit(delegate(threadId, "late task"))));
306 assert.isTrue(Exit.isFailure(yield* Effect.exit(watch(threadId, 5))));
307
308 // A slow watch_pull_request call can land after the stopped run ended.
309 yield* projections.apply({
310 id: EventId.make("event:stop-barrier:interrupted"),
311 type: "run.updated",
312 threadId,
313 runId: run.id,
314 occurredAt: now,
315 payload: { ...run, status: "interrupted", completedAt: now },
316 });
317 assert.isTrue(Exit.isFailure(yield* Effect.exit(watch(threadId, 5))));
318 assert.deepEqual(yield* threadState(threadId), {
319 runs: ["interrupted", "cancelled"],
320 watched: [4],
321 });
322
323 // The user can still stop and restart a watch by hand.
324 for (const watching of [false, true]) {
325 yield* orchestrator.dispatch({
326 type: "thread.pull-request.watch",
327 commandId: CommandId.make(`manual-watch:${watching}`),
328 threadId,
329 ...pullRequest(4),
330 watching,
331 });
332 }
333 assert.deepEqual((yield* threadState(threadId)).watched, [4]);
334 }).pipe(Effect.provide(layerTest)),
335);
336
337it.effect("thread.stop keeps a restart continuation of the stopped run from starting", () =>
338 Effect.gen(function* () {
339 const orchestrator = yield* Orchestrator.OrchestratorV2;
340 const projections = yield* ProjectionStore.ProjectionStoreV2;
341 const sql = yield* SqlClient.SqlClient;
342 const threadId = ThreadId.make("thread:stop-restart");
343 yield* createWatchingThread(threadId, 8);
344 yield* send(threadId, "work", "start_immediately");
345 const now = yield* DateTime.now;
346 const run = (yield* orchestrator.getThreadProjection(threadId)).runs[0]!;
347 // A server restart cut the run before its provider started; its continuation is pending.
348 yield* projections.apply({
349 id: EventId.make("event:stop-restart:cancelled"),
350 type: "run.updated",
351 threadId,
352 runId: run.id,
353 occurredAt: now,
354 payload: { ...run, status: "cancelled", startedAt: null, completedAt: now },
355 });
356 const at = DateTime.formatIso(now);
357 yield* sql`
358 INSERT INTO orchestration_v2_effect_outbox (
359 effect_id, command_id, thread_id, effect_type, payload_json, status,
360 attempt_count, available_at, created_at, updated_at
361 ) VALUES (
362 ${`effect:restart-continuation:${run.id}`}, 'command:restart', ${threadId},
363 'provider-runtime.continue',
364 ${encodeEffectRequest({ type: "provider-runtime.continue", sourceRunId: run.id })},
365 'pending', 0, ${at}, ${at}, ${at}
366 )
367 `;
368
369 yield* orchestrator.dispatch({
370 type: "thread.stop",
371 commandId: CommandId.make("stop-restart"),
372 threadId,
373 });
374 yield* orchestrator.dispatch({
375 type: "message.dispatch",
376 commandId: CommandId.make("restart-continuation"),
377 threadId,
378 messageId: MessageId.make("message:restart-continuation"),
379 text: "Continue.",
380 attachments: [],
381 dispatchMode: { type: "start_immediately" },
382 createdBy: "agent",
383 creationSource: "server",
384 restartContinuationOfRunId: run.id,
385 });
386 assert.deepEqual(yield* threadState(threadId), { runs: ["cancelled"], watched: [] });
387 }).pipe(Effect.provide(layerTest)),
388);
389
390it.effect.each(["thread.stop", "run.interrupt"] as const)(
391 "a successful %s blocks a newer restart continuation when completion timestamps tie",
392 (stopType) =>
393 Effect.gen(function* () {
394 const orchestrator = yield* Orchestrator.OrchestratorV2;
395 const projections = yield* ProjectionStore.ProjectionStoreV2;
396 const sql = yield* SqlClient.SqlClient;
397 const threadId = ThreadId.make("thread:stop-resumed-queue");
398 yield* createWatchingThread(threadId, 12);
399 yield* send(threadId, "first", "start_immediately");
400 yield* send(threadId, "queued", "queue_after_active");
401 const now = yield* DateTime.now;
402 const [first, queued] = (yield* orchestrator.getThreadProjection(threadId)).runs;
403 assert.isDefined(first);
404 assert.isDefined(queued);
405 for (const run of [first!, queued!]) {
406 yield* projections.apply({
407 id: EventId.make(`event:stop-resumed-queue:hold:${run.id}`),
408 type: "run.updated",
409 threadId,
410 runId: run.id,
411 occurredAt: now,
412 payload:
413 run.id === first!.id
414 ? { ...run, status: "completed", completedAt: now }
415 : { ...run, queueHeld: true },
416 });
417 }
418 // A later turn runs ahead of the held queue, then recovery cancels it.
419 yield* send(threadId, "restart source", "start_immediately");
420 const source = (yield* orchestrator.getThreadProjection(threadId)).runs.at(-1)!;
421 yield* projections.apply({
422 id: EventId.make("event:stop-resumed-queue:restart-cancelled"),
423 type: "run.updated",
424 threadId,
425 runId: source.id,
426 occurredAt: now,
427 payload: { ...source, status: "cancelled", startedAt: now, completedAt: now },
428 });
429 const at = DateTime.formatIso(now);
430 yield* sql`
431 INSERT INTO orchestration_v2_effect_outbox (
432 effect_id, command_id, thread_id, effect_type, payload_json, status,
433 attempt_count, available_at, created_at, updated_at
434 ) VALUES (
435 ${`effect:restart-continuation:${source.id}`}, 'command:restart', ${threadId},
436 'provider-runtime.continue',
437 ${encodeEffectRequest({ type: "provider-runtime.continue", sourceRunId: source.id })},
438 'pending', 0, ${at}, ${at}, ${at}
439 )
440 `;
441 yield* orchestrator.dispatch({
442 type: "queue.resume",
443 commandId: CommandId.make("resume-older-queue"),
444 threadId,
445 });
446 assert.equal(
447 (yield* orchestrator.getThreadProjection(threadId)).runs.find(
448 (run) => run.id === queued!.id,
449 )?.status,
450 "starting",
451 );
452 yield* orchestrator.dispatch(
453 stopType === "thread.stop"
454 ? { type: "thread.stop", commandId: CommandId.make("stop-resumed-queue"), threadId }
455 : {
456 type: "run.interrupt",
457 commandId: CommandId.make("stop-resumed-queue"),
458 threadId,
459 runId: queued!.id,
460 holdQueue: true,
461 },
462 );
463 const stopped = yield* orchestrator.getThreadProjection(threadId);
464 const interrupted = stopped.runs.find((run) => run.id === queued!.id)!;
465 assert.equal(interrupted.status, "interrupted");
466 assert.equal(DateTime.toEpochMillis(interrupted.completedAt!), DateTime.toEpochMillis(now));
467 yield* orchestrator.dispatch({
468 type: "message.dispatch",
469 commandId: CommandId.make("restart-after-stop"),
470 threadId,
471 messageId: MessageId.make("message:restart-after-stop"),
472 text: "Continue.",
473 attachments: [],
474 dispatchMode: { type: "start_immediately" },
475 createdBy: "agent",
476 creationSource: "server",
477 restartContinuationOfRunId: source.id,
478 });
479 assert.deepEqual(yield* threadState(threadId), {
480 runs: ["completed", "interrupted", "cancelled"],
481 watched: [],
482 });
483 }).pipe(Effect.provide(layerTest.pipe(Layer.provideMerge(TestClock.layer())))),
484);
485
486it.effect("a delegated task that cannot be stopped fails the walk after its siblings stop", () =>
487 Effect.gen(function* () {
488 const orchestrator = yield* Orchestrator.OrchestratorV2;
489 const projections = yield* ProjectionStore.ProjectionStoreV2;
490 const threads = yield* ThreadManagementService.ThreadManagementService;
491 const parentThreadId = ThreadId.make("thread:stop-partial");
492 yield* createWatchingThread(parentThreadId, 6);
493 yield* send(parentThreadId, "work", "start_immediately");
494 const childThreadId = yield* delegate(parentThreadId, "stoppable task");
495 const task = (yield* orchestrator.getThreadProjection(parentThreadId)).subagents[0]!;
496 // A task whose thread is gone, listed before the one that can stop.
497 yield* projections.apply({
498 id: EventId.make("event:stop-partial:missing-task"),
499 type: "subagent.updated",
500 threadId: parentThreadId,
501 runId: task.runId!,
502 nodeId: NodeId.make("node:stop-partial:missing"),
503 providerInstanceId: instanceId,
504 occurredAt: yield* DateTime.now,
505 payload: {
506 ...task,
507 id: NodeId.make("node:stop-partial:missing"),
508 childThreadId: ThreadId.make("thread:stop-partial:missing"),
509 startedAt: DateTime.subtract(task.startedAt!, { hours: 1 }),
510 },
511 });
512
513 const walked = yield* Effect.exit(
514 threads.stopDelegatedTasks({
515 threadId: parentThreadId,
516 commandId: CommandId.make("stop-partial"),
517 }),
518 );
519 assert.isTrue(Exit.isFailure(walked));
520 assert.deepEqual((yield* threadState(childThreadId)).runs, ["interrupted"]);
521 }).pipe(Effect.provide(layerTest)),
522);
523
524it.effect("thread.stop on a finished thread refuses a late agent watch", () =>
525 Effect.gen(function* () {
526 const orchestrator = yield* Orchestrator.OrchestratorV2;
527 const projections = yield* ProjectionStore.ProjectionStoreV2;
528 const threadId = ThreadId.make("thread:stop-finished");
529 yield* createWatchingThread(threadId, 9);
530 yield* send(threadId, "work", "start_immediately");
531 const now = yield* DateTime.now;
532 const run = (yield* orchestrator.getThreadProjection(threadId)).runs[0]!;
533 yield* projections.apply({
534 id: EventId.make("event:stop-finished:completed"),
535 type: "run.updated",
536 threadId,
537 runId: run.id,
538 occurredAt: now,
539 payload: { ...run, status: "completed", startedAt: now, completedAt: now },
540 });
541
542 yield* orchestrator.dispatch({
543 type: "thread.stop",
544 commandId: CommandId.make("stop-finished"),
545 threadId,
546 });
547 assert.isTrue(Exit.isFailure(yield* Effect.exit(watch(threadId, 10))));
548 assert.deepEqual(yield* threadState(threadId), { runs: ["completed"], watched: [] });
549 }).pipe(Effect.provide(layerTest)),
550);
551
552it.effect("thread.stop marks a turn it cannot interrupt so a late agent watch is refused", () =>
553 Effect.gen(function* () {
554 const orchestrator = yield* Orchestrator.OrchestratorV2;
555 const projections = yield* ProjectionStore.ProjectionStoreV2;
556 const threadId = ThreadId.make("thread:stop-lost-session");
557 yield* createWatchingThread(threadId, 11);
558 yield* send(threadId, "work", "start_immediately");
559 const now = yield* DateTime.now;
560 const run = (yield* orchestrator.getThreadProjection(threadId)).runs[0]!;
561 // The turn is running, but its provider session is gone, so the interrupt fails.
562 yield* projections.apply({
563 id: EventId.make("event:stop-lost-session:running"),
564 type: "run.updated",
565 threadId,
566 runId: run.id,
567 occurredAt: now,
568 payload: { ...run, status: "running", startedAt: now },
569 });
570 yield* projections.apply({
571 id: EventId.make("event:stop-lost-session:turn"),
572 type: "provider-turn.updated",
573 threadId,
574 occurredAt: now,
575 payload: {
576 id: ProviderTurnId.make("provider-turn:stop-lost-session"),
577 providerThreadId: run.providerThreadId!,
578 nodeId: run.rootNodeId!,
579 runAttemptId: run.activeAttemptId!,
580 nativeTurnRef: null,
581 ordinal: 1,
582 status: "running",
583 startedAt: now,
584 completedAt: null,
585 },
586 });
587
588 yield* orchestrator.dispatch({
589 type: "thread.stop",
590 commandId: CommandId.make("stop-lost-session"),
591 threadId,
592 });
593 assert.isTrue(Exit.isFailure(yield* Effect.exit(watch(threadId, 12))));
594 assert.deepEqual(yield* threadState(threadId), { runs: ["running"], watched: [] });
595 }).pipe(Effect.provide(layerTest)),
596);
597
598it.effect.each(["missing session", "completed", "failed", "cancelled"] as const)(
599 "a native child Stop only settles a confirmed %s outcome and preserves its owner and sibling",
600 (providerState) =>
601 Effect.gen(function* () {
602 const orchestrator = yield* Orchestrator.OrchestratorV2;
603 const projections = yield* ProjectionStore.ProjectionStoreV2;
604 const sql = yield* SqlClient.SqlClient;
605 const threadId = ThreadId.make("thread:native-child-stop");
606 yield* createWatchingThread(threadId, 20);
607 yield* send(threadId, "owner", "start_immediately");
608 yield* delegate(threadId, "native-child-fixture");
609 const before = yield* orchestrator.getThreadProjection(threadId);
610 const run = before.runs[0]!;
611 const now = yield* DateTime.now;
612 const subagent = {
613 ...before.subagents[0]!,
614 origin: "provider_native" as const,
615 driver: CLAUDE_PROVIDER,
616 providerInstanceId: ProviderInstanceId.make("claudeAgent"),
617 nativeTaskRef: {
618 driver: CLAUDE_PROVIDER,
619 nativeId: "claude-task",
620 strength: "strong" as const,
621 },
622 status: "running" as const,
623 startedAt: now,
624 };
625 yield* projections.apply({
626 id: EventId.make("event:native-child-stop:agent"),
627 type: "subagent.updated",
628 threadId,
629 runId: run.id,
630 nodeId: subagent.id,
631 occurredAt: now,
632 payload: subagent,
633 });
634 const sibling = {
635 ...subagent,
636 id: NodeId.make("node:native-stop-sibling"),
637 childThreadId: null,
638 };
639 yield* projections.apply({
640 id: EventId.make("event:native-child-stop:sibling"),
641 type: "subagent.updated",
642 threadId,
643 runId: run.id,
644 nodeId: sibling.id,
645 occurredAt: now,
646 payload: sibling,
647 });
648 const item = before.turnItems.find(
649 (item) => item.type === "subagent" && item.subagentId === subagent.id,
650 )!;
651 yield* projections.apply({
652 id: EventId.make("event:native-child-stop:item"),
653 type: "turn-item.updated",
654 threadId,
655 runId: run.id,
656 occurredAt: now,
657 payload: { ...item, status: "running", completedAt: null },
658 });
659 const childRoot = {
660 ...before.nodes.find((node) => node.id === run.rootNodeId)!,
661 id: NodeId.make("node:native-stop-child-root"),
662 threadId: subagent.childThreadId!,
663 runId: null,
664 parentNodeId: null,
665 status: "running" as const,
666 countsForRun: false,
667 completedAt: null,
668 };
669 yield* projections.apply({
670 id: EventId.make("event:native-child-stop:child-root"),
671 type: "node.updated",
672 threadId: childRoot.threadId,
673 nodeId: childRoot.id,
674 occurredAt: now,
675 payload: childRoot,
676 });
677 const providerThread = before.providerThreads.find(
678 (thread) => thread.id === run.providerThreadId,
679 )!;
680 yield* projections.apply({
681 id: EventId.make("event:native-child-stop:provider-thread"),
682 type: "provider-thread.updated",
683 threadId,
684 occurredAt: now,
685 payload: {
686 ...providerThread,
687 driver: CLAUDE_PROVIDER,
688 providerInstanceId: ProviderInstanceId.make("claudeAgent"),
689 providerSessionId: ProviderSessionId.make("session:native-child-stop"),
690 },
691 });
692 const providerTurnId = ProviderTurnId.make("turn:native-child-stop");
693 yield* projections.apply({
694 id: EventId.make("event:native-child-stop:provider-turn"),
695 type: "provider-turn.updated",
696 threadId,
697 occurredAt: now,
698 payload: {
699 id: providerTurnId,
700 providerThreadId: providerThread.id,
701 nodeId: run.rootNodeId!,
702 runAttemptId: run.activeAttemptId!,
703 nativeTurnRef: null,
704 ordinal: 1,
705 status: "completed",
706 startedAt: now,
707 completedAt: now,
708 },
709 });
710 // The owner has finished but its child and queued prompt remain.
711 yield* projections.apply({
712 id: EventId.make("event:native-child-stop:owner-completed"),
713 type: "run.updated",
714 threadId,
715 runId: run.id,
716 occurredAt: now,
717 payload: { ...run, status: "completed", startedAt: now, completedAt: now },
718 });
719 yield* send(threadId, "queued", "queue_after_active");
720 const stateBefore = yield* threadState(threadId);
721 const eventStore = yield* EventStore.EventStoreV2;
722 const afterSequence = yield* eventStore.latestSequence({ threadId });
723 const confirmedStatus =
724 providerState === "completed" || providerState === "failed" || providerState === "cancelled"
725 ? providerState
726 : null;
727 const confirmedOutcome =
728 confirmedStatus === null
729 ? undefined
730 : { status: confirmedStatus, completedAt: now, result: "Actual provider outcome" };
731 const commandId = CommandId.make("stop-native-child");
732 yield* orchestrator.dispatch({
733 type: "subagent.stop",
734 commandId,
735 threadId,
736 runId: run.id,
737 subagentId: subagent.id,
738 });
739 assert.deepEqual(yield* threadState(threadId), stateBefore);
740 const effects = yield* sql<{ payload_json: string }>`
741 SELECT payload_json FROM orchestration_v2_effect_outbox WHERE command_id = ${commandId}
742 `;
743 assert.equal(effects.length, 1);
744 assert.deepEqual(JSON.parse(effects[0]!.payload_json), {
745 type: "provider-turn.interrupt",
746 providerSessionId: "session:native-child-stop",
747 providerThreadId: providerThread.id,
748 providerTurnId,
749 subagent: { id: subagent.id, nativeTaskId: "claude-task" },
750 });
751 assert.equal(
752 (yield* orchestrator.getThreadProjection(threadId)).subagents[0]?.status,
753 "running",
754 );
755 const unrelated = yield* Effect.exit(
756 orchestrator.dispatch({
757 type: "subagent.stop",
758 commandId: CommandId.make("stop-unknown-child"),
759 threadId,
760 runId: run.id,
761 subagentId: NodeId.make("unknown-child"),
762 }),
763 );
764 assert.isTrue(Exit.isFailure(unrelated));
765 // The provider outcome predates the delayed projection repair.
766 yield* TestClock.adjust("1 second");
767 // Only execute Stop's durable effect, with no terminal event ingestion.
768 yield* sql`DELETE FROM orchestration_v2_effect_outbox WHERE command_id != ${commandId}`;
769 if (providerState === "missing session") {
770 const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
771 yield* worker.drain();
772 } else {
773 yield* orchestrator.dispatch({
774 type: "thread.background-work.settle",
775 commandId: CommandId.make("repair-native-child"),
776 threadId,
777 providerThreadId: providerThread.id,
778 providerTurnId,
779 subagent: { id: subagent.id, stoppedAt: now, outcome: confirmedOutcome! },
780 });
781 }
782 const settled = yield* orchestrator.getThreadProjection(threadId);
783 const cancelled = settled.subagents.find((task) => task.id === subagent.id)!;
784 if (confirmedOutcome === undefined) {
785 const events = yield* eventStore.read({ threadId, afterSequence }).pipe(Stream.runCollect);
786 assert.isFalse(
787 events.some(
788 ({ event }) =>
789 (event.type === "subagent.updated" ||
790 event.type === "node.updated" ||
791 event.type === "turn-item.updated") &&
792 ["completed", "failed", "cancelled", "interrupted"].includes(event.payload.status),
793 ),
794 );
795 assert.equal(cancelled.status, "running");
796 assert.equal(
797 (yield* orchestrator.getThreadProjection(childRoot.threadId)).nodes.find(
798 (node) => node.id === childRoot.id,
799 )?.status,
800 "running",
801 );
802 assert.deepEqual(yield* threadState(threadId), stateBefore);
803 return;
804 }
805
806 // Cached clients resume from this sequence, so all lifecycle repairs
807 // must be stored in the parent stream, not just applied to projections.
808 const repaired = yield* eventStore.read({ threadId, afterSequence }).pipe(Stream.runCollect);
809 const terminal = repaired.flatMap(({ event }) =>
810 (event.type === "subagent.updated" ||
811 event.type === "node.updated" ||
812 event.type === "turn-item.updated") &&
813 event.payload.status === confirmedStatus
814 ? [event]
815 : [],
816 );
817 assert.deepEqual(terminal.map((event) => event.type).sort(), [
818 "node.updated",
819 "subagent.updated",
820 "turn-item.updated",
821 ]);
822 for (const event of terminal) {
823 assert.equal(event.nodeId, subagent.id);
824 assert.equal(
825 DateTime.toEpochMillis(event.payload.completedAt!),
826 DateTime.toEpochMillis(confirmedOutcome!.completedAt),
827 );
828 if (event.type === "subagent.updated" || event.type === "turn-item.updated") {
829 assert.isDefined(event.payload.updatedAt);
830 }
831 }
832
833 assert.equal(cancelled.status, confirmedStatus);
834 assert.isNotNull(cancelled.completedAt);
835 assert.equal(
836 DateTime.toEpochMillis(cancelled.completedAt!),
837 DateTime.toEpochMillis(confirmedOutcome!.completedAt),
838 );
839 assert.equal(cancelled.result, confirmedOutcome!.result);
840 assert.equal(
841 settled.turnItems.find((candidate) => candidate.id === item.id)?.status,
842 confirmedStatus,
843 );
844 const child = yield* orchestrator.getThreadProjection(childRoot.threadId);
845 assert.equal(child.nodes.find((node) => node.id === childRoot.id)?.status, confirmedStatus);
846 assert.isNotNull(child.nodes.find((node) => node.id === childRoot.id)?.completedAt);
847 assert.equal(settled.subagents.find((task) => task.id === sibling.id)?.status, "running");
848 assert.deepEqual(yield* threadState(threadId), stateBefore);
849 // An old Stop follow-up cannot cancel a genuine subsequent resume.
850 yield* TestClock.adjust("1 second");
851 const resumedAt = yield* DateTime.now;
852 yield* projections.apply({
853 id: EventId.make("event:native-child-stop:resume"),
854 type: "subagent.updated",
855 threadId,
856 runId: run.id,
857 nodeId: subagent.id,
858 occurredAt: resumedAt,
859 payload: { ...cancelled, status: "running", startedAt: resumedAt, completedAt: null },
860 });
861 yield* orchestrator.dispatch({
862 type: "thread.background-work.settle",
863 commandId: CommandId.make("old-stop-after-resume"),
864 threadId,
865 providerThreadId: providerThread.id,
866 providerTurnId,
867 subagent: { id: subagent.id, stoppedAt: now, outcome: confirmedOutcome },
868 });
869 assert.equal(
870 (yield* orchestrator.getThreadProjection(threadId)).subagents.find(
871 (task) => task.id === subagent.id,
872 )?.status,
873 "running",
874 );
875 }).pipe(Effect.provide(layerTest)),
876);