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