@devries-cameron20 / t3code-1 / commits / fbc6a08159
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

fix(server): Stop stops a thread's subagents again (#23886)

Co-authored-by: PR Batch Tester <agent@local.test> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

shivam committed Oct 23, 2026 at 17:15 UTC fbc6a08159c81d14ac02f43f421ca8739c82b56b
6 files changed +140 -51
apps/server/src/mcp/OrchestratorMcpService.ts
+1
@@ -2385,6 +2385,7 @@ const make = Effect.gen(function* () {
2385 type: "thread.stop",
2386 commandId,
2387 threadId: current.childThreadId,
2388 + stopDelegatedTasks: false,
2389 ...(reason === undefined ? {} : { reason }),
2390 })
2391 .pipe(
apps/server/src/orchestration-v2/EventSink.ts
+6 -1
@@ -661,7 +661,12 @@ const layerBase: Layer.Layer<
661 commandId: input.commandId,
662 events: normalized,
663 });
664 - const sequence = storedEvents.at(-1)?.sequence;
664 + // A Stop that changes nothing can still queue the stop of its delegated tasks.
665 + const sequence =
666 + storedEvents.at(-1)?.sequence ??
667 + (input.effects.length === 0
668 + ? undefined
669 + : yield* eventStore.latestSequence({ threadId: input.threadId }));
670 if (sequence === undefined) {
671 return yield* Effect.die(
672 new Error(`Command ${input.commandId} produced no orchestration events.`),
apps/server/src/orchestration-v2/Orchestrator.ts
+28 -10
@@ -535,6 +535,22 @@ function pendingThreadTitleGenerationEffect(
535 };
536 }
537
538 +function delegatedTasksStopEffect(command: {
539 + readonly commandId: CommandId;
540 + readonly threadId: ThreadId;
541 + readonly reason?: string | undefined;
542 +}): PendingOrchestrationEffectV2 {
543 + return {
544 + id: `effect:${command.commandId}:delegated-tasks.stop`,
545 + commandId: command.commandId,
546 + threadId: command.threadId,
547 + request: {
548 + type: "delegated-tasks.stop",
549 + ...(command.reason === undefined ? {} : { reason: command.reason }),
550 + },
551 + };
552 +}
553 +
554 const WORKSPACE_PREPARATION_INPUT = "Preparing workspace";
555
556 function withoutPreparationResult(
@@ -10150,6 +10166,14 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
10166 ),
10167 );
10168 if (projection.thread.deletedAt !== null) return undefined;
10169 + // Queued after the interrupt, since a thread's effects run in order.
10170 + const stopDelegatedTasks =
10171 + command.stopDelegatedTasks === false ||
10172 + !projection.subagents.some(
10173 + (task) => task.origin === "app_owned" && task.childThreadId !== null,
10174 + )
10175 + ? Effect.void
10176 + : Ref.update(effects, (existing) => [...existing, delegatedTasksStopEffect(command)]);
10177 const latestRun = projection.runs.findLast((run) => run.status !== "queued");
10178 const target =
10179 projection.runs.findLast(
@@ -10189,6 +10213,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
10213 yield* Ref.update(events, (existing) => [...existing, ...written]);
10214 yield* Ref.update(effects, (existing) => [...existing, ...enqueued]);
10215 yield* cancelIdleOrphans({ command, events, projection });
10216 + yield* stopDelegatedTasks;
10217 return interrupted.value;
10218 }
10219 yield* Effect.logWarning("thread.stop could not interrupt the running turn", {
@@ -10209,6 +10234,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
10234 }
10235 yield* holdStoppedThread({ command, events, projection, cohortRunIds: [], now });
10236 yield* cancelIdleOrphans({ command, events, projection });
10237 + yield* stopDelegatedTasks;
10238 return undefined;
10239 });
10240
@@ -11509,15 +11535,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
11535 });
11536 yield* Ref.update(effects, (existing) => [
11537 ...existing,
11512 - {
11513 - id: `effect:${command.commandId}:delegated-tasks.stop`,
11514 - commandId: command.commandId,
11515 - threadId: command.threadId,
11516 - request: {
11517 - type: "delegated-tasks.stop",
11518 - ...(command.reason === undefined ? {} : { reason: command.reason }),
11519 - },
11520 - } satisfies PendingOrchestrationEffectV2,
11538 + delegatedTasksStopEffect(command),
11539 ]);
11540 }
11541 break;
@@ -11787,7 +11805,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
11805 ),
11806 );
11807
11790 - if (plan.events.length === 0) {
11808 + if (plan.events.length === 0 && plan.effects.length === 0) {
11809 // A settle that ended nothing still records its receipt: a replayed Stop
11810 // effect then finds it instead of settling work that appeared since.
11811 const resultSequence = yield* Effect.gen(function* () {
apps/server/src/orchestration-v2/ThreadManagementService.ts
+1
@@ -1115,6 +1115,7 @@ const make = Effect.gen(function* () {
1115 type: "thread.stop",
1116 commandId: CommandId.make(`${input.commandId}:stop:${threadId}`),
1117 threadId,
1118 + stopDelegatedTasks: false,
1119 ...(input.reason === undefined ? {} : { reason: input.reason }),
1120 }).pipe(
1121 Effect.andThen(stopDelegatedTasks({ ...input, threadId })),
apps/server/src/orchestration-v2/ThreadStop.test.ts
+99 -40
@@ -530,65 +530,124 @@ it.effect("Stop still stops the thread when a delegated child cannot be read", (
530 }).pipe(Effect.provide(layerTest)),
531 );
532
533 -it.effect("Stop ends watches, holds queues, and stops the delegated tasks under the thread", () =>
533 +it.effect.each(["run.interrupt", "thread.stop"] as const)(
534 + "%s Stop ends watches, holds queues, and stops the delegated tasks under the thread",
535 + (type) =>
536 + Effect.gen(function* () {
537 + const orchestrator = yield* Orchestrator.OrchestratorV2;
538 + const projections = yield* ProjectionStore.ProjectionStoreV2;
539 + const threads = yield* ThreadManagementService.ThreadManagementService;
540 + const sql = yield* SqlClient.SqlClient;
541 + const parentThreadId = ThreadId.make("thread:stop-parent");
542 + yield* createWatchingThread(parentThreadId, 1);
543 + yield* send(parentThreadId, "first", "start_immediately");
544 + const childThreadId = yield* delegate(parentThreadId, "child task");
545 + assert.isTrue(Exit.isFailure(yield* Effect.exit(watch(childThreadId, 2))));
546 + const grandchildThreadId = yield* delegate(childThreadId, "grandchild task");
547 + yield* send(childThreadId, "child follow-up", "queue_after_active");
548 +
549 + const now = yield* DateTime.now;
550 + const firstRun = (yield* orchestrator.getThreadProjection(parentThreadId)).runs[0]!;
551 + yield* projections.apply({
552 + id: EventId.make("event:stop-parent:first-run-completed"),
553 + type: "run.updated",
554 + threadId: parentThreadId,
555 + runId: firstRun.id,
556 + occurredAt: now,
557 + payload: { ...firstRun, status: "completed", completedAt: now },
558 + });
559 + yield* send(parentThreadId, "second", "start_immediately");
560 + const secondRun = (yield* orchestrator.getThreadProjection(parentThreadId)).runs.at(-1)!;
561 +
562 + const stopCommandId = CommandId.make("stop-parent");
563 + yield* orchestrator.dispatch(
564 + type === "thread.stop"
565 + ? { type, commandId: stopCommandId, threadId: parentThreadId }
566 + : {
567 + type,
568 + commandId: stopCommandId,
569 + threadId: parentThreadId,
570 + runId: secondRun.id,
571 + holdQueue: true,
572 + },
573 + );
574 +
575 + assert.deepEqual(yield* threadState(parentThreadId), {
576 + runs: ["completed", "interrupted"],
577 + watched: [],
578 + });
579 + const parent = yield* orchestrator.getThreadProjection(parentThreadId);
580 + assert.equal(parent.subagents[0]?.completionDelivery?.state, "disposed");
581 + const effects = yield* sql<{ readonly effect_type: string }>`
582 + SELECT effect_type FROM orchestration_v2_effect_outbox WHERE command_id = ${stopCommandId}
583 + `;
584 + assert.include(
585 + effects.map((row) => row.effect_type),
586 + "delegated-tasks.stop",
587 + );
588 +
589 + yield* threads.stopDelegatedTasks({ threadId: parentThreadId, commandId: stopCommandId });
590 + assert.deepEqual(yield* threadState(childThreadId), {
591 + runs: ["interrupted", "queued:held"],
592 + watched: [],
593 + });
594 + assert.deepEqual((yield* threadState(grandchildThreadId)).runs, ["interrupted"]);
595 +
596 + yield* threads.stopDelegatedTasks({ threadId: parentThreadId, commandId: stopCommandId });
597 + assert.deepEqual((yield* threadState(childThreadId)).runs, ["interrupted", "queued:held"]);
598 + // The walk stops each level itself, so the child stops it sends queue no walk of their own.
599 + const walks = yield* sql<{ readonly command_id: string }>`
600 + SELECT command_id FROM orchestration_v2_effect_outbox
601 + WHERE effect_type = 'delegated-tasks.stop'
602 + `;
603 + assert.deepEqual(
604 + walks.map((row) => row.command_id),
605 + [stopCommandId],
606 + );
607 + }).pipe(Effect.provide(layerTest)),
608 +);
609 +
610 +it.effect("a repeated Stop that changes nothing still stops the delegated tasks", () =>
611 Effect.gen(function* () {
612 const orchestrator = yield* Orchestrator.OrchestratorV2;
613 const projections = yield* ProjectionStore.ProjectionStoreV2;
537 - const threads = yield* ThreadManagementService.ThreadManagementService;
614 const sql = yield* SqlClient.SqlClient;
539 - const parentThreadId = ThreadId.make("thread:stop-parent");
615 + const parentThreadId = ThreadId.make("thread:stop-again");
616 yield* createWatchingThread(parentThreadId, 1);
617 yield* send(parentThreadId, "first", "start_immediately");
542 - const childThreadId = yield* delegate(parentThreadId, "child task");
543 - assert.isTrue(Exit.isFailure(yield* Effect.exit(watch(childThreadId, 2))));
544 - const grandchildThreadId = yield* delegate(childThreadId, "grandchild task");
545 - yield* send(childThreadId, "child follow-up", "queue_after_active");
546 -
618 + yield* delegate(parentThreadId, "stop-again child");
619 const now = yield* DateTime.now;
548 - const firstRun = (yield* orchestrator.getThreadProjection(parentThreadId)).runs[0]!;
620 + const run = (yield* orchestrator.getThreadProjection(parentThreadId)).runs[0]!;
621 yield* projections.apply({
550 - id: EventId.make("event:stop-parent:first-run-completed"),
622 + id: EventId.make("event:stop-again:run-completed"),
623 type: "run.updated",
624 threadId: parentThreadId,
553 - runId: firstRun.id,
625 + runId: run.id,
626 occurredAt: now,
555 - payload: { ...firstRun, status: "completed", completedAt: now },
627 + payload: { ...run, status: "completed", completedAt: now },
628 });
557 - yield* send(parentThreadId, "second", "start_immediately");
558 - const secondRun = (yield* orchestrator.getThreadProjection(parentThreadId)).runs.at(-1)!;
559 -
560 - const stopCommandId = CommandId.make("stop-parent");
629 yield* orchestrator.dispatch({
562 - type: "run.interrupt",
563 - commandId: stopCommandId,
630 + type: "thread.stop",
631 + commandId: CommandId.make("stop-again:first"),
632 threadId: parentThreadId,
565 - runId: secondRun.id,
566 - holdQueue: true,
633 });
634
569 - assert.deepEqual(yield* threadState(parentThreadId), {
570 - runs: ["completed", "interrupted"],
571 - watched: [],
635 + // The first Stop already disposed the delivery and ended the watch, so this one writes no
636 + // events, like Stop on a thread an older server stopped without stopping its children.
637 + const again = yield* orchestrator.dispatch({
638 + type: "thread.stop",
639 + commandId: CommandId.make("stop-again:second"),
640 + threadId: parentThreadId,
641 });
573 - const parent = yield* orchestrator.getThreadProjection(parentThreadId);
574 - assert.equal(parent.subagents[0]?.completionDelivery?.state, "disposed");
575 - const effects = yield* sql<{ readonly effect_type: string }>`
576 - SELECT effect_type FROM orchestration_v2_effect_outbox WHERE command_id = ${stopCommandId}
642 + assert.lengthOf(again.storedEvents, 0);
643 + const walks = yield* sql<{ readonly command_id: string }>`
644 + SELECT command_id FROM orchestration_v2_effect_outbox
645 + WHERE effect_type = 'delegated-tasks.stop'
646 `;
578 - assert.include(
579 - effects.map((row) => row.effect_type),
580 - "delegated-tasks.stop",
647 + assert.deepEqual(
648 + walks.map((row) => row.command_id),
649 + ["stop-again:first", "stop-again:second"],
650 );
582 -
583 - yield* threads.stopDelegatedTasks({ threadId: parentThreadId, commandId: stopCommandId });
584 - assert.deepEqual(yield* threadState(childThreadId), {
585 - runs: ["interrupted", "queued:held"],
586 - watched: [],
587 - });
588 - assert.deepEqual((yield* threadState(grandchildThreadId)).runs, ["interrupted"]);
589 -
590 - yield* threads.stopDelegatedTasks({ threadId: parentThreadId, commandId: stopCommandId });
591 - assert.deepEqual((yield* threadState(childThreadId)).runs, ["interrupted", "queued:held"]);
651 }).pipe(Effect.provide(layerTest)),
652 );
653
packages/contracts/src/orchestrationV2.ts
+5
@@ -2577,6 +2577,11 @@ export const OrchestrationV2Command = Schema.Union([
2577 commandId: CommandId,
2578 threadId: ThreadId,
2579 reason: Schema.optional(Schema.String),
2580 + /**
2581 + * False when the caller stops the thread's delegated tasks itself, as the server's tree walks
2582 + * do under their caller's dispatch limit. Otherwise Stop also stops every task under the thread.
2583 + */
2584 + stopDelegatedTasks: Schema.optional(Schema.Boolean),
2585 }),
2586 Schema.Struct({
2587 type: Schema.Literal("thread.create"),