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.each(["thread.stop", "run.interrupt"] as const)(
229 "%s cancels buffered wakes and preserves durable queued messages",
230 (type) =>
231 Effect.gen(function* () {
232 const orchestrator = yield* Orchestrator.OrchestratorV2;
233 const threadId = ThreadId.make(`thread:stop-buffered:${type}`);
234 yield* createWatchingThread(threadId, 5);
235 yield* send(threadId, "active", "start_immediately");
236 yield* send(threadId, "user follow-up", "queue_after_active");
237 for (const creationSource of ["provider", "server"] as const) {
238 yield* orchestrator.dispatch({
239 type: "message.dispatch",
240 commandId: CommandId.make(`notification:${type}:${creationSource}`),
241 threadId,
242 messageId: MessageId.make(`notification:${type}:${creationSource}`),
243 text: "Background activity updated",
244 attachments: [],
245 createdBy: "agent",
246 creationSource,
247 notification: {
248 source: { kind: "background_task" },
249 outcome: "updated",
250 summary: "Background activity updated",
251 },
252 dispatchMode: { type: "queue_after_active" },
253 });
254 }
255 const before = yield* orchestrator.getThreadProjection(threadId);
256 const buffered = before.runs.find((run) =>
257 before.messages.some(
258 (message) => message.id === run.userMessageId && message.creationSource === "provider",
259 ),
260 )!;
261 const stop = { commandId: CommandId.make(`stop:${type}`), threadId };
262 yield* orchestrator.dispatch(
263 type === "run.interrupt"
264 ? { ...stop, type, runId: before.runs[0]!.id, holdQueue: true }
265 : { ...stop, type },
266 );
267 const stopped = yield* orchestrator.getThreadProjection(threadId);
268 assert.equal(stopped.runs.find((run) => run.id === buffered.id)?.status, "cancelled");
269 assert.equal(
270 stopped.attempts.find((attempt) => attempt.runId === buffered.id)?.status,
271 "cancelled",
272 );
273 assert.equal(
274 stopped.nodes.find((node) => node.id === buffered.rootNodeId)?.status,
275 "cancelled",
276 );
277 assert.deepEqual(
278 stopped.runs.filter((run) => run.status === "queued").map((run) => run.queueHeld),
279 [true, true],
280 );
281 }).pipe(Effect.provide(layerTest)),
282);
283
284it.effect(
285 "thread.stop ends an idle thread's watches and accepts a thread with nothing to stop",
286 () =>
287 Effect.gen(function* () {
288 const orchestrator = yield* Orchestrator.OrchestratorV2;
289 const threadId = ThreadId.make("thread:stop-idle");
290 yield* createWatchingThread(threadId, 3);
291
292 yield* orchestrator.dispatch({
293 type: "thread.stop",
294 commandId: CommandId.make("stop-idle"),
295 threadId,
296 });
297 assert.deepEqual(yield* threadState(threadId), { runs: [], watched: [] });
298
299 const again = yield* orchestrator.dispatch({
300 type: "thread.stop",
301 commandId: CommandId.make("stop-idle-again"),
302 threadId,
303 });
304 assert.lengthOf(again.storedEvents, 0);
305 }).pipe(Effect.provide(layerTest)),
306);
307
308it.effect("a run Stop reached cannot delegate or start a watch, even after it ends", () =>
309 Effect.gen(function* () {
310 const orchestrator = yield* Orchestrator.OrchestratorV2;
311 const projections = yield* ProjectionStore.ProjectionStoreV2;
312 const threadId = ThreadId.make("thread:stop-barrier");
313 yield* createWatchingThread(threadId, 4);
314 yield* send(threadId, "work", "start_immediately");
315 const now = yield* DateTime.now;
316 const run = { ...(yield* orchestrator.getThreadProjection(threadId)).runs[0]!, startedAt: now };
317 yield* projections.apply({
318 id: EventId.make("event:stop-barrier:running"),
319 type: "run.updated",
320 threadId,
321 runId: run.id,
322 occurredAt: now,
323 payload: { ...run, status: "running" },
324 });
325 // A queued message the user cancelled does not count as the latest run.
326 yield* send(threadId, "queued", "queue_after_active");
327 const queued = (yield* orchestrator.getThreadProjection(threadId)).runs.at(-1)!;
328 yield* orchestrator.dispatch({
329 type: "queued-run.cancel",
330 commandId: CommandId.make("cancel-queued"),
331 threadId,
332 runId: queued.id,
333 });
334 // Stop reached the run, but its provider has not stopped it yet.
335 yield* projections.apply({
336 id: EventId.make("event:stop-barrier:interrupt-request"),
337 type: "turn-item.updated",
338 threadId,
339 runId: run.id,
340 occurredAt: now,
341 payload: {
342 id: TurnItemId.make("turn-item:stop-barrier:interrupt-request"),
343 threadId,
344 runId: run.id,
345 nodeId: run.rootNodeId!,
346 providerThreadId: run.providerThreadId!,
347 providerTurnId: null,
348 nativeItemRef: null,
349 parentItemId: null,
350 ordinal: 1_000,
351 status: "completed",
352 title: "Interrupt requested",
353 startedAt: now,
354 completedAt: now,
355 updatedAt: now,
356 type: "run_interrupt_request",
357 message: "Stop",
358 },
359 });
360
361 assert.isTrue(Exit.isFailure(yield* Effect.exit(delegate(threadId, "late task"))));
362 assert.isTrue(Exit.isFailure(yield* Effect.exit(watch(threadId, 5))));
363
364 // A slow watch_pull_request call can land after the stopped run ended.
365 yield* projections.apply({
366 id: EventId.make("event:stop-barrier:interrupted"),
367 type: "run.updated",
368 threadId,
369 runId: run.id,
370 occurredAt: now,
371 payload: { ...run, status: "interrupted", completedAt: now },
372 });
373 assert.isTrue(Exit.isFailure(yield* Effect.exit(watch(threadId, 5))));
374 assert.deepEqual(yield* threadState(threadId), {
375 runs: ["interrupted", "cancelled"],
376 watched: [4],
377 });
378
379 // The user can still stop and restart a watch by hand.
380 for (const watching of [false, true]) {
381 yield* orchestrator.dispatch({
382 type: "thread.pull-request.watch",
383 commandId: CommandId.make(`manual-watch:${watching}`),
384 threadId,
385 ...pullRequest(4),
386 watching,
387 });
388 }
389 assert.deepEqual((yield* threadState(threadId)).watched, [4]);
390 }).pipe(Effect.provide(layerTest)),
391);
392
393it.effect("thread.stop keeps a restart continuation of the stopped run from starting", () =>
394 Effect.gen(function* () {
395 const orchestrator = yield* Orchestrator.OrchestratorV2;
396 const projections = yield* ProjectionStore.ProjectionStoreV2;
397 const sql = yield* SqlClient.SqlClient;
398 const threadId = ThreadId.make("thread:stop-restart");
399 yield* createWatchingThread(threadId, 8);
400 yield* send(threadId, "work", "start_immediately");
401 const now = yield* DateTime.now;
402 const run = (yield* orchestrator.getThreadProjection(threadId)).runs[0]!;
403 // A server restart cut the run before its provider started; its continuation is pending.
404 yield* projections.apply({
405 id: EventId.make("event:stop-restart:cancelled"),
406 type: "run.updated",
407 threadId,
408 runId: run.id,
409 occurredAt: now,
410 payload: { ...run, status: "cancelled", startedAt: null, completedAt: now },
411 });
412 const at = DateTime.formatIso(now);
413 yield* sql`
414 INSERT INTO orchestration_v2_effect_outbox (
415 effect_id, command_id, thread_id, effect_type, payload_json, status,
416 attempt_count, available_at, created_at, updated_at
417 ) VALUES (
418 ${`effect:restart-continuation:${run.id}`}, 'command:restart', ${threadId},
419 'provider-runtime.continue',
420 ${encodeEffectRequest({ type: "provider-runtime.continue", sourceRunId: run.id })},
421 'pending', 0, ${at}, ${at}, ${at}
422 )
423 `;
424
425 yield* orchestrator.dispatch({
426 type: "thread.stop",
427 commandId: CommandId.make("stop-restart"),
428 threadId,
429 });
430 yield* orchestrator.dispatch({
431 type: "message.dispatch",
432 commandId: CommandId.make("restart-continuation"),
433 threadId,
434 messageId: MessageId.make("message:restart-continuation"),
435 text: "Continue.",
436 attachments: [],
437 dispatchMode: { type: "start_immediately" },
438 createdBy: "agent",
439 creationSource: "server",
440 restartContinuationOfRunId: run.id,
441 });
442 assert.deepEqual(yield* threadState(threadId), { runs: ["cancelled"], watched: [] });
443 }).pipe(Effect.provide(layerTest)),
444);
445
446it.effect.each(["thread.stop", "run.interrupt"] as const)(
447 "a successful %s blocks a newer restart continuation when completion timestamps tie",
448 (stopType) =>
449 Effect.gen(function* () {
450 const orchestrator = yield* Orchestrator.OrchestratorV2;
451 const projections = yield* ProjectionStore.ProjectionStoreV2;
452 const sql = yield* SqlClient.SqlClient;
453 const threadId = ThreadId.make("thread:stop-resumed-queue");
454 yield* createWatchingThread(threadId, 12);
455 yield* send(threadId, "first", "start_immediately");
456 yield* send(threadId, "queued", "queue_after_active");
457 const now = yield* DateTime.now;
458 const [first, queued] = (yield* orchestrator.getThreadProjection(threadId)).runs;
459 assert.isDefined(first);
460 assert.isDefined(queued);
461 for (const run of [first!, queued!]) {
462 yield* projections.apply({
463 id: EventId.make(`event:stop-resumed-queue:hold:${run.id}`),
464 type: "run.updated",
465 threadId,
466 runId: run.id,
467 occurredAt: now,
468 payload:
469 run.id === first!.id
470 ? { ...run, status: "completed", completedAt: now }
471 : { ...run, queueHeld: true },
472 });
473 }
474 // A later turn runs ahead of the held queue, then recovery cancels it.
475 yield* send(threadId, "restart source", "start_immediately");
476 const source = (yield* orchestrator.getThreadProjection(threadId)).runs.at(-1)!;
477 yield* projections.apply({
478 id: EventId.make("event:stop-resumed-queue:restart-cancelled"),
479 type: "run.updated",
480 threadId,
481 runId: source.id,
482 occurredAt: now,
483 payload: { ...source, status: "cancelled", startedAt: now, completedAt: now },
484 });
485 const at = DateTime.formatIso(now);
486 yield* sql`
487 INSERT INTO orchestration_v2_effect_outbox (
488 effect_id, command_id, thread_id, effect_type, payload_json, status,
489 attempt_count, available_at, created_at, updated_at
490 ) VALUES (
491 ${`effect:restart-continuation:${source.id}`}, 'command:restart', ${threadId},
492 'provider-runtime.continue',
493 ${encodeEffectRequest({ type: "provider-runtime.continue", sourceRunId: source.id })},
494 'pending', 0, ${at}, ${at}, ${at}
495 )
496 `;
497 yield* orchestrator.dispatch({
498 type: "queue.resume",
499 commandId: CommandId.make("resume-older-queue"),
500 threadId,
501 });
502 assert.equal(
503 (yield* orchestrator.getThreadProjection(threadId)).runs.find(
504 (run) => run.id === queued!.id,
505 )?.status,
506 "starting",
507 );
508 yield* orchestrator.dispatch(
509 stopType === "thread.stop"
510 ? { type: "thread.stop", commandId: CommandId.make("stop-resumed-queue"), threadId }
511 : {
512 type: "run.interrupt",
513 commandId: CommandId.make("stop-resumed-queue"),
514 threadId,
515 runId: queued!.id,
516 holdQueue: true,
517 },
518 );
519 const stopped = yield* orchestrator.getThreadProjection(threadId);
520 const interrupted = stopped.runs.find((run) => run.id === queued!.id)!;
521 assert.equal(interrupted.status, "interrupted");
522 assert.equal(DateTime.toEpochMillis(interrupted.completedAt!), DateTime.toEpochMillis(now));
523 yield* orchestrator.dispatch({
524 type: "message.dispatch",
525 commandId: CommandId.make("restart-after-stop"),
526 threadId,
527 messageId: MessageId.make("message:restart-after-stop"),
528 text: "Continue.",
529 attachments: [],
530 dispatchMode: { type: "start_immediately" },
531 createdBy: "agent",
532 creationSource: "server",
533 restartContinuationOfRunId: source.id,
534 });
535 assert.deepEqual(yield* threadState(threadId), {
536 runs: ["completed", "interrupted", "cancelled"],
537 watched: [],
538 });
539 }).pipe(Effect.provide(layerTest.pipe(Layer.provideMerge(TestClock.layer())))),
540);
541
542it.effect("a delegated task that cannot be stopped fails the walk after its siblings stop", () =>
543 Effect.gen(function* () {
544 const orchestrator = yield* Orchestrator.OrchestratorV2;
545 const projections = yield* ProjectionStore.ProjectionStoreV2;
546 const threads = yield* ThreadManagementService.ThreadManagementService;
547 const parentThreadId = ThreadId.make("thread:stop-partial");
548 yield* createWatchingThread(parentThreadId, 6);
549 yield* send(parentThreadId, "work", "start_immediately");
550 const childThreadId = yield* delegate(parentThreadId, "stoppable task");
551 const task = (yield* orchestrator.getThreadProjection(parentThreadId)).subagents[0]!;
552 // A task whose thread is gone, listed before the one that can stop.
553 yield* projections.apply({
554 id: EventId.make("event:stop-partial:missing-task"),
555 type: "subagent.updated",
556 threadId: parentThreadId,
557 runId: task.runId!,
558 nodeId: NodeId.make("node:stop-partial:missing"),
559 providerInstanceId: instanceId,
560 occurredAt: yield* DateTime.now,
561 payload: {
562 ...task,
563 id: NodeId.make("node:stop-partial:missing"),
564 childThreadId: ThreadId.make("thread:stop-partial:missing"),
565 startedAt: DateTime.subtract(task.startedAt!, { hours: 1 }),
566 },
567 });
568
569 const walked = yield* Effect.exit(
570 threads.stopDelegatedTasks({
571 threadId: parentThreadId,
572 commandId: CommandId.make("stop-partial"),
573 }),
574 );
575 assert.isTrue(Exit.isFailure(walked));
576 assert.deepEqual((yield* threadState(childThreadId)).runs, ["interrupted"]);
577 }).pipe(Effect.provide(layerTest)),
578);
579
580it.effect("thread.stop on a finished thread refuses a late agent watch", () =>
581 Effect.gen(function* () {
582 const orchestrator = yield* Orchestrator.OrchestratorV2;
583 const projections = yield* ProjectionStore.ProjectionStoreV2;
584 const threadId = ThreadId.make("thread:stop-finished");
585 yield* createWatchingThread(threadId, 9);
586 yield* send(threadId, "work", "start_immediately");
587 const now = yield* DateTime.now;
588 const run = (yield* orchestrator.getThreadProjection(threadId)).runs[0]!;
589 yield* projections.apply({
590 id: EventId.make("event:stop-finished:completed"),
591 type: "run.updated",
592 threadId,
593 runId: run.id,
594 occurredAt: now,
595 payload: { ...run, status: "completed", startedAt: now, completedAt: now },
596 });
597
598 yield* orchestrator.dispatch({
599 type: "thread.stop",
600 commandId: CommandId.make("stop-finished"),
601 threadId,
602 });
603 assert.isTrue(Exit.isFailure(yield* Effect.exit(watch(threadId, 10))));
604 assert.deepEqual(yield* threadState(threadId), { runs: ["completed"], watched: [] });
605 }).pipe(Effect.provide(layerTest)),
606);
607
608it.effect("thread.stop marks a turn it cannot interrupt so a late agent watch is refused", () =>
609 Effect.gen(function* () {
610 const orchestrator = yield* Orchestrator.OrchestratorV2;
611 const projections = yield* ProjectionStore.ProjectionStoreV2;
612 const threadId = ThreadId.make("thread:stop-lost-session");
613 yield* createWatchingThread(threadId, 11);
614 yield* send(threadId, "work", "start_immediately");
615 const now = yield* DateTime.now;
616 const run = (yield* orchestrator.getThreadProjection(threadId)).runs[0]!;
617 // The turn is running, but its provider session is gone, so the interrupt fails.
618 yield* projections.apply({
619 id: EventId.make("event:stop-lost-session:running"),
620 type: "run.updated",
621 threadId,
622 runId: run.id,
623 occurredAt: now,
624 payload: { ...run, status: "running", startedAt: now },
625 });
626 yield* projections.apply({
627 id: EventId.make("event:stop-lost-session:turn"),
628 type: "provider-turn.updated",
629 threadId,
630 occurredAt: now,
631 payload: {
632 id: ProviderTurnId.make("provider-turn:stop-lost-session"),
633 providerThreadId: run.providerThreadId!,
634 nodeId: run.rootNodeId!,
635 runAttemptId: run.activeAttemptId!,
636 nativeTurnRef: null,
637 ordinal: 1,
638 status: "running",
639 startedAt: now,
640 completedAt: null,
641 },
642 });
643
644 yield* orchestrator.dispatch({
645 type: "thread.stop",
646 commandId: CommandId.make("stop-lost-session"),
647 threadId,
648 });
649 assert.isTrue(Exit.isFailure(yield* Effect.exit(watch(threadId, 12))));
650 assert.deepEqual(yield* threadState(threadId), { runs: ["running"], watched: [] });
651 }).pipe(Effect.provide(layerTest)),
652);
653
654it.effect.each(["missing session", "completed", "failed", "cancelled"] as const)(
655 "a native child Stop only settles a confirmed %s outcome and preserves its owner and sibling",
656 (providerState) =>
657 Effect.gen(function* () {
658 const orchestrator = yield* Orchestrator.OrchestratorV2;
659 const projections = yield* ProjectionStore.ProjectionStoreV2;
660 const sql = yield* SqlClient.SqlClient;
661 const threadId = ThreadId.make("thread:native-child-stop");
662 yield* createWatchingThread(threadId, 20);
663 yield* send(threadId, "owner", "start_immediately");
664 yield* delegate(threadId, "native-child-fixture");
665 const before = yield* orchestrator.getThreadProjection(threadId);
666 const run = before.runs[0]!;
667 const now = yield* DateTime.now;
668 const subagent = {
669 ...before.subagents[0]!,
670 origin: "provider_native" as const,
671 driver: CLAUDE_PROVIDER,
672 providerInstanceId: ProviderInstanceId.make("claudeAgent"),
673 nativeTaskRef: {
674 driver: CLAUDE_PROVIDER,
675 nativeId: "claude-task",
676 strength: "strong" as const,
677 },
678 status: "running" as const,
679 startedAt: now,
680 };
681 yield* projections.apply({
682 id: EventId.make("event:native-child-stop:agent"),
683 type: "subagent.updated",
684 threadId,
685 runId: run.id,
686 nodeId: subagent.id,
687 occurredAt: now,
688 payload: subagent,
689 });
690 const sibling = {
691 ...subagent,
692 id: NodeId.make("node:native-stop-sibling"),
693 childThreadId: null,
694 };
695 yield* projections.apply({
696 id: EventId.make("event:native-child-stop:sibling"),
697 type: "subagent.updated",
698 threadId,
699 runId: run.id,
700 nodeId: sibling.id,
701 occurredAt: now,
702 payload: sibling,
703 });
704 const item = before.turnItems.find(
705 (item) => item.type === "subagent" && item.subagentId === subagent.id,
706 )!;
707 yield* projections.apply({
708 id: EventId.make("event:native-child-stop:item"),
709 type: "turn-item.updated",
710 threadId,
711 runId: run.id,
712 occurredAt: now,
713 payload: { ...item, status: "running", completedAt: null },
714 });
715 const childRoot = {
716 ...before.nodes.find((node) => node.id === run.rootNodeId)!,
717 id: NodeId.make("node:native-stop-child-root"),
718 threadId: subagent.childThreadId!,
719 runId: null,
720 parentNodeId: null,
721 status: "running" as const,
722 countsForRun: false,
723 completedAt: null,
724 };
725 yield* projections.apply({
726 id: EventId.make("event:native-child-stop:child-root"),
727 type: "node.updated",
728 threadId: childRoot.threadId,
729 nodeId: childRoot.id,
730 occurredAt: now,
731 payload: childRoot,
732 });
733 const providerThread = before.providerThreads.find(
734 (thread) => thread.id === run.providerThreadId,
735 )!;
736 yield* projections.apply({
737 id: EventId.make("event:native-child-stop:provider-thread"),
738 type: "provider-thread.updated",
739 threadId,
740 occurredAt: now,
741 payload: {
742 ...providerThread,
743 driver: CLAUDE_PROVIDER,
744 providerInstanceId: ProviderInstanceId.make("claudeAgent"),
745 providerSessionId: ProviderSessionId.make("session:native-child-stop"),
746 },
747 });
748 const providerTurnId = ProviderTurnId.make("turn:native-child-stop");
749 yield* projections.apply({
750 id: EventId.make("event:native-child-stop:provider-turn"),
751 type: "provider-turn.updated",
752 threadId,
753 occurredAt: now,
754 payload: {
755 id: providerTurnId,
756 providerThreadId: providerThread.id,
757 nodeId: run.rootNodeId!,
758 runAttemptId: run.activeAttemptId!,
759 nativeTurnRef: null,
760 ordinal: 1,
761 status: "completed",
762 startedAt: now,
763 completedAt: now,
764 },
765 });
766 // The owner has finished but its child and queued prompt remain.
767 yield* projections.apply({
768 id: EventId.make("event:native-child-stop:owner-completed"),
769 type: "run.updated",
770 threadId,
771 runId: run.id,
772 occurredAt: now,
773 payload: { ...run, status: "completed", startedAt: now, completedAt: now },
774 });
775 yield* send(threadId, "queued", "queue_after_active");
776 const stateBefore = yield* threadState(threadId);
777 const eventStore = yield* EventStore.EventStoreV2;
778 const afterSequence = yield* eventStore.latestSequence({ threadId });
779 const confirmedStatus =
780 providerState === "completed" || providerState === "failed" || providerState === "cancelled"
781 ? providerState
782 : null;
783 const confirmedOutcome =
784 confirmedStatus === null
785 ? undefined
786 : { status: confirmedStatus, completedAt: now, result: "Actual provider outcome" };
787 const commandId = CommandId.make("stop-native-child");
788 yield* orchestrator.dispatch({
789 type: "subagent.stop",
790 commandId,
791 threadId,
792 runId: run.id,
793 subagentId: subagent.id,
794 });
795 assert.deepEqual(yield* threadState(threadId), stateBefore);
796 const effects = yield* sql<{ payload_json: string }>`
797 SELECT payload_json FROM orchestration_v2_effect_outbox WHERE command_id = ${commandId}
798 `;
799 assert.equal(effects.length, 1);
800 assert.deepEqual(JSON.parse(effects[0]!.payload_json), {
801 type: "provider-turn.interrupt",
802 providerSessionId: "session:native-child-stop",
803 providerThreadId: providerThread.id,
804 providerTurnId,
805 subagent: { id: subagent.id, nativeTaskId: "claude-task" },
806 });
807 assert.equal(
808 (yield* orchestrator.getThreadProjection(threadId)).subagents[0]?.status,
809 "running",
810 );
811 const unrelated = yield* Effect.exit(
812 orchestrator.dispatch({
813 type: "subagent.stop",
814 commandId: CommandId.make("stop-unknown-child"),
815 threadId,
816 runId: run.id,
817 subagentId: NodeId.make("unknown-child"),
818 }),
819 );
820 assert.isTrue(Exit.isFailure(unrelated));
821 // The provider outcome predates the delayed projection repair.
822 yield* TestClock.adjust("1 second");
823 // Only execute Stop's durable effect, with no terminal event ingestion.
824 yield* sql`DELETE FROM orchestration_v2_effect_outbox WHERE command_id != ${commandId}`;
825 if (providerState === "missing session") {
826 const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
827 yield* worker.drain();
828 } else {
829 yield* orchestrator.dispatch({
830 type: "thread.background-work.settle",
831 commandId: CommandId.make("repair-native-child"),
832 threadId,
833 providerThreadId: providerThread.id,
834 providerTurnId,
835 subagent: { id: subagent.id, stoppedAt: now, outcome: confirmedOutcome! },
836 });
837 }
838 const settled = yield* orchestrator.getThreadProjection(threadId);
839 const cancelled = settled.subagents.find((task) => task.id === subagent.id)!;
840 if (confirmedOutcome === undefined) {
841 const events = yield* eventStore.read({ threadId, afterSequence }).pipe(Stream.runCollect);
842 assert.isFalse(
843 events.some(
844 ({ event }) =>
845 (event.type === "subagent.updated" ||
846 event.type === "node.updated" ||
847 event.type === "turn-item.updated") &&
848 ["completed", "failed", "cancelled", "interrupted"].includes(event.payload.status),
849 ),
850 );
851 assert.equal(cancelled.status, "running");
852 assert.equal(
853 (yield* orchestrator.getThreadProjection(childRoot.threadId)).nodes.find(
854 (node) => node.id === childRoot.id,
855 )?.status,
856 "running",
857 );
858 assert.deepEqual(yield* threadState(threadId), stateBefore);
859 return;
860 }
861
862 // Cached clients resume from this sequence, so all lifecycle repairs
863 // must be stored in the parent stream, not just applied to projections.
864 const repaired = yield* eventStore.read({ threadId, afterSequence }).pipe(Stream.runCollect);
865 const terminal = repaired.flatMap(({ event }) =>
866 (event.type === "subagent.updated" ||
867 event.type === "node.updated" ||
868 event.type === "turn-item.updated") &&
869 event.payload.status === confirmedStatus
870 ? [event]
871 : [],
872 );
873 assert.deepEqual(terminal.map((event) => event.type).sort(), [
874 "node.updated",
875 "subagent.updated",
876 "turn-item.updated",
877 ]);
878 for (const event of terminal) {
879 assert.equal(event.nodeId, subagent.id);
880 assert.equal(
881 DateTime.toEpochMillis(event.payload.completedAt!),
882 DateTime.toEpochMillis(confirmedOutcome!.completedAt),
883 );
884 if (event.type === "subagent.updated" || event.type === "turn-item.updated") {
885 assert.isDefined(event.payload.updatedAt);
886 }
887 }
888
889 assert.equal(cancelled.status, confirmedStatus);
890 assert.isNotNull(cancelled.completedAt);
891 assert.equal(
892 DateTime.toEpochMillis(cancelled.completedAt!),
893 DateTime.toEpochMillis(confirmedOutcome!.completedAt),
894 );
895 assert.equal(cancelled.result, confirmedOutcome!.result);
896 assert.equal(
897 settled.turnItems.find((candidate) => candidate.id === item.id)?.status,
898 confirmedStatus,
899 );
900 const child = yield* orchestrator.getThreadProjection(childRoot.threadId);
901 assert.equal(child.nodes.find((node) => node.id === childRoot.id)?.status, confirmedStatus);
902 assert.isNotNull(child.nodes.find((node) => node.id === childRoot.id)?.completedAt);
903 assert.equal(settled.subagents.find((task) => task.id === sibling.id)?.status, "running");
904 assert.deepEqual(yield* threadState(threadId), stateBefore);
905 // An old Stop follow-up cannot cancel a genuine subsequent resume.
906 yield* TestClock.adjust("1 second");
907 const resumedAt = yield* DateTime.now;
908 yield* projections.apply({
909 id: EventId.make("event:native-child-stop:resume"),
910 type: "subagent.updated",
911 threadId,
912 runId: run.id,
913 nodeId: subagent.id,
914 occurredAt: resumedAt,
915 payload: { ...cancelled, status: "running", startedAt: resumedAt, completedAt: null },
916 });
917 yield* orchestrator.dispatch({
918 type: "thread.background-work.settle",
919 commandId: CommandId.make("old-stop-after-resume"),
920 threadId,
921 providerThreadId: providerThread.id,
922 providerTurnId,
923 subagent: { id: subagent.id, stoppedAt: now, outcome: confirmedOutcome },
924 });
925 assert.equal(
926 (yield* orchestrator.getThreadProjection(threadId)).subagents.find(
927 (task) => task.id === subagent.id,
928 )?.status,
929 "running",
930 );
931 }).pipe(Effect.provide(layerTest)),
932);