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