The best way to control Claude Code, Codex and more from any computer or phone
fix(server): Stop on a delegate always clears it, even when it is stuck (#22653)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Theo Browne committed
Oct 20, 2026 at 23:27 UTC
6a6c84f9906cbdfa7f533fecfc39ce18c2f4c273
5 files changed
+151
-58
apps/server/src/mcp/OrchestratorMcpService.test.ts
+10
-3
@@ -420,6 +420,7 @@ describe("OrchestratorMcpService", () => {
420
: Effect.succeed(childProjection),
421
getThreadShell: (threadId) => Effect.succeed(liveThreadShell(threadId)),
422
delegatedTaskResultPending: () => Effect.succeed(false),
423
+ stopDelegatedTasks: () => Effect.void,
424
// The orchestrator's subagent.stop repair is covered in ThreadStop.test.ts.
425
dispatch: (command) =>
426
Ref.update(dispatched, (commands) => [...commands, command]).pipe(
@@ -458,9 +459,15 @@ describe("OrchestratorMcpService", () => {
459
clientRequestId: "cancel-orphan-task",
460
});
461
assert.deepEqual(result, { taskId, status: "cancelled" });
461
- const [stop, ...rest] = yield* Ref.get(dispatched);
462
- assert.isEmpty(rest);
463
- assert.equal(stop?.type, "subagent.stop");
462
+ const commands = yield* Ref.get(dispatched);
463
+ // A child whose run finished can still run another turn's work, so it is stopped too.
464
+ assert.deepEqual(
465
+ commands.flatMap((command) =>
466
+ command.type === "thread.stop" ? [command.threadId] : [],
467
+ ),
468
+ childState === "a finished run" ? [childThreadId] : [],
469
+ );
470
+ const stop = commands.find((command) => command.type === "subagent.stop");
471
if (stop?.type !== "subagent.stop") return;
472
assert.deepEqual(
473
{ threadId: stop.threadId, runId: stop.runId, subagentId: stop.subagentId },
apps/server/src/mcp/OrchestratorMcpService.ts
+4
-4
@@ -2359,8 +2359,7 @@ const make = Effect.gen(function* () {
2359
),
2360
);
2361
// A follow-up that lost its child run (#19002) stays running on the parent, while its
2362
- // status here comes from the child's last run. The parent cancels it, and any other
2363
- // orphan of the same child, when that child is idle.
2362
+ // status here comes from the child's last run. Stop on the parent cancels that task.
2363
const cancelOrphan = Effect.gen(function* () {
2364
if (parentTask?.runId == null || !isOrchestrationV2WorkActive(parentTask.status))
2365
return false;
@@ -2383,12 +2382,13 @@ const make = Effect.gen(function* () {
2382
return subagents.some((task) => task.id === input.taskId && task.status === "cancelled");
2383
});
2384
if (isTerminalTaskStatus(current.status)) {
2386
- if (yield* cancelOrphan) return { taskId: input.taskId, status: "cancelled" };
2385
+ // The child can still run work for another turn, so it is stopped either way.
2386
yield* stopWithinLimit;
2387
+ const cancelled = yield* cancelOrphan;
2388
yield* disposeCompletionDelivery;
2389
return {
2390
taskId: input.taskId,
2391
- status: current.status,
2391
+ status: cancelled ? "cancelled" : current.status,
2392
} satisfies OrchestratorMcpTaskCancelResult;
2393
}
2394
const child = yield* loadProjection(current.childThreadId);
apps/server/src/orchestration-v2/Orchestrator.ts
+97
-45
@@ -539,6 +539,20 @@ function withoutPreparationResult(
539
return rest;
540
}
541
542
+/** Stop ended this task, so its result is not delivered to the parent agent. */
543
+function cancelledAppOwnedTask(
544
+ task: OrchestrationV2Subagent,
545
+ now: DateTime.Utc,
546
+): OrchestrationV2Subagent {
547
+ return {
548
+ ...task,
549
+ status: "cancelled",
550
+ completedAt: now,
551
+ updatedAt: now,
552
+ completionDelivery: { state: "disposed", observedByRunId: null },
553
+ };
554
+}
555
+
556
function isBlockingRun(run: OrchestrationV2Run): boolean {
557
return (
558
run.status === "preparing" ||
@@ -9397,22 +9411,46 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
9411
]);
9412
const run = projection.runs.find((candidate) => candidate.id === command.runId);
9413
const subagent = projection.subagents.find((candidate) => candidate.id === command.subagentId);
9400
- // An app-owned task stops through its child thread. Here the parent only cancels the child's
9401
- // orphaned tasks: the child is idle and no child run is bound to them (#19002).
9414
+ // A user Stop cancels an app-owned task here when nothing else can settle it: no child run was
9415
+ // ever bound to it and it is not the child's original task (#19002). This holds whatever else
9416
+ // the child is doing. A task with a bound run, live or ended, keeps its settlement path, since
9417
+ // its result may still be on the way, and the child stop the client sends next interrupts the
9418
+ // run. A task that already ended is written again, so a client holding a stale copy, such as
9419
+ // one cached before a repair, shows it ended.
9420
if (
9421
subagent?.origin === "app_owned" &&
9422
subagent.childThreadId !== null &&
9423
subagent.runId === command.runId
9424
) {
9407
- const records = yield* loadProjectionForCommand(command, ["subagents", "turnItems"], {
9425
+ const childThreadId = subagent.childThreadId;
9426
+ const child = yield* projectionStore.getThreadRecords(childThreadId, ["runs"]).pipe(
9427
+ Effect.catchTags({ ProjectionStoreThreadNotFoundError: () => Effect.succeed(null) }),
9428
+ Effect.mapError(
9429
+ (cause) => new OrchestratorProjectionError({ threadId: childThreadId, cause }),
9430
+ ),
9431
+ );
9432
+ const active = isOrchestrationV2WorkActive(subagent.status);
9433
+ if (
9434
+ active &&
9435
+ child !== null &&
9436
+ ((child.thread.forkedFrom?.type === "node" &&
9437
+ child.thread.forkedFrom.nodeId === subagent.id) ||
9438
+ child.runs.some((run) => run.delegatedTaskId === subagent.id))
9439
+ )
9440
+ return;
9441
+ const records = yield* loadProjectionForCommand(command, ["nodes", "turnItems"], {
9442
turnItemTypes: ["subagent"],
9409
- turnItemStatuses: ["pending", "running", "waiting"],
9443
+ turnItemRunIds: [subagent.runId],
9444
+ omitSettledLeafNodes: true,
9445
});
9411
- return yield* cancelIdleOrphans({
9446
+ const now = yield* DateTime.now;
9447
+ return yield* writeAppOwnedTask({
9448
command,
9449
events,
9414
- projection: records,
9415
- childThreadId: subagent.childThreadId,
9450
+ task: active ? cancelledAppOwnedTask(subagent, now) : subagent,
9451
+ nodes: records.nodes,
9452
+ turnItems: records.turnItems,
9453
+ now,
9454
});
9455
}
9456
if (
@@ -9857,16 +9895,56 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
9895
return undefined;
9896
});
9897
9898
+ /** Writes a parent's app-owned task, and sets its node and turn items to the task's status. */
9899
+ const writeAppOwnedTask = Effect.fn("Orchestrator.writeAppOwnedTask")(function* (input: {
9900
+ readonly command: Extract<
9901
+ OrchestrationV2ServerCommand,
9902
+ { readonly type: "run.interrupt" | "thread.stop" | "subagent.stop" }
9903
+ >;
9904
+ readonly events: Ref.Ref<Array<OrchestrationV2DomainEvent>>;
9905
+ readonly task: OrchestrationV2Subagent;
9906
+ readonly nodes: ReadonlyArray<OrchestrationV2ExecutionNode>;
9907
+ readonly turnItems: ReadonlyArray<OrchestrationV2TurnItem>;
9908
+ readonly now: DateTime.Utc;
9909
+ }) {
9910
+ const { command, task, now } = input;
9911
+ const emitEvent = emit(input.events, command);
9912
+ yield* emitEvent({
9913
+ type: "subagent.updated",
9914
+ threadId: command.threadId,
9915
+ nodeId: task.id,
9916
+ occurredAt: now,
9917
+ payload: task,
9918
+ });
9919
+ const node = input.nodes.find((candidate) => candidate.id === task.id);
9920
+ if (node !== undefined)
9921
+ yield* emitEvent({
9922
+ type: "node.updated",
9923
+ threadId: command.threadId,
9924
+ nodeId: node.id,
9925
+ occurredAt: now,
9926
+ payload: { ...node, status: task.status, completedAt: task.completedAt },
9927
+ });
9928
+ for (const item of input.turnItems) {
9929
+ if (item.type !== "subagent" || item.subagentId !== task.id) continue;
9930
+ yield* emitEvent({
9931
+ type: "turn-item.updated",
9932
+ threadId: command.threadId,
9933
+ nodeId: task.id,
9934
+ occurredAt: now,
9935
+ payload: { ...item, status: task.status, completedAt: task.completedAt, updatedAt: now },
9936
+ });
9937
+ }
9938
+ });
9939
+
9940
const cancelIdleOrphans = Effect.fn("Orchestrator.cancelIdleOrphans")(
9941
function* (input: {
9942
readonly command: Extract<
9943
OrchestrationV2ServerCommand,
9864
- { readonly type: "run.interrupt" | "thread.stop" | "subagent.stop" }
9944
+ { readonly type: "run.interrupt" | "thread.stop" }
9945
>;
9946
readonly events: Ref.Ref<Array<OrchestrationV2DomainEvent>>;
9947
readonly projection: Pick<OrchestrationV2ThreadProjection, "subagents" | "turnItems">;
9868
- /** Limits the repair to tasks delegated to this child thread. */
9869
- readonly childThreadId?: ThreadId;
9948
}) {
9949
const { command, events, projection } = input;
9950
const pending = yield* Ref.get(events);
@@ -9884,8 +9962,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
9962
if (
9963
task.origin !== "app_owned" ||
9964
task.childThreadId === null ||
9887
- !isOrchestrationV2WorkActive(task.status) ||
9888
- (input.childThreadId !== undefined && task.childThreadId !== input.childThreadId)
9965
+ !isOrchestrationV2WorkActive(task.status)
9966
)
9967
continue;
9968
const childThreadId = task.childThreadId;
@@ -9932,40 +10009,15 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
10009
if (!idle) continue;
10010
// Stop can cancel an idle orphan without guessing which completed run owned its result.
10011
const now = yield* DateTime.now;
9935
- const emitEvent = emit(events, command);
9936
- yield* emitEvent({
9937
- type: "subagent.updated",
9938
- threadId: command.threadId,
9939
- nodeId: task.id,
9940
- occurredAt: now,
9941
- payload: {
9942
- ...task,
9943
- status: "cancelled",
9944
- completedAt: now,
9945
- updatedAt: now,
9946
- completionDelivery: { state: "disposed", observedByRunId: null },
9947
- },
9948
- });
10012
nodes ??= (yield* projectionStore.getThreadRecords(command.threadId, ["nodes"])).nodes;
9950
- const node = nodes.find((candidate) => candidate.id === task.id);
9951
- if (node !== undefined)
9952
- yield* emitEvent({
9953
- type: "node.updated",
9954
- threadId: command.threadId,
9955
- nodeId: node.id,
9956
- occurredAt: now,
9957
- payload: { ...node, status: "cancelled", completedAt: now },
9958
- });
9959
- for (const item of projection.turnItems) {
9960
- if (item.type !== "subagent" || item.subagentId !== task.id) continue;
9961
- yield* emitEvent({
9962
- type: "turn-item.updated",
9963
- threadId: command.threadId,
9964
- nodeId: task.id,
9965
- occurredAt: now,
9966
- payload: { ...item, status: "cancelled", completedAt: now, updatedAt: now },
9967
- });
9968
- }
10013
+ yield* writeAppOwnedTask({
10014
+ command,
10015
+ events,
10016
+ task: cancelledAppOwnedTask(task, now),
10017
+ nodes,
10018
+ turnItems: projection.turnItems,
10019
+ now,
10020
+ });
10021
}
10022
},
10023
(effect, input) =>
apps/server/src/orchestration-v2/ThreadStop.test.ts
+39
-5
@@ -166,6 +166,8 @@ it.effect.each([
166
["idle", "run.interrupt"],
167
["idle", "subagent.stop"],
168
["running", "subagent.stop"],
169
+ ["bound", "subagent.stop"],
170
+ ["correlated", "subagent.stop"],
171
["archived", "thread.stop"],
172
["missing", "thread.stop"],
173
["running", "thread.stop"],
@@ -178,7 +180,7 @@ it.effect.each([
180
["question", "thread.stop"],
181
["restart", "thread.stop"],
182
] as const)(
181
- "Stop clears an orphaned follow-up only when its child is finished (%s via %s)",
183
+ "Stop clears an orphaned follow-up when its child is finished; its own Stop does unless a run is bound (%s via %s)",
184
([childState, type]) =>
185
Effect.gen(function* () {
186
const orchestrator = yield* Orchestrator.OrchestratorV2;
@@ -279,7 +281,9 @@ it.effect.each([
281
const childRunStatus =
282
childState === "running" || childState === "queued" || childState === "waiting"
283
? childState
282
- : "completed";
284
+ : childState === "bound"
285
+ ? "running"
286
+ : "completed";
287
yield* apply({
288
type: "run.updated",
289
threadId: childThreadId,
@@ -299,12 +303,14 @@ it.effect.each([
303
...runAtStart,
304
status: childRunStatus,
305
completedAt: childRunStatus === "completed" ? now : null,
302
- ...(childState === "correlated" ? { delegatedTaskId: taskId } : {}),
306
+ ...(childState === "correlated" || childState === "bound"
307
+ ? { delegatedTaskId: taskId }
308
+ : {}),
309
},
310
});
311
assert.equal(
312
(yield* orchestrator.getThreadProjection(childThreadId)).runs[0]?.delegatedTaskId,
307
- childState === "correlated" ? taskId : undefined,
313
+ childState === "correlated" || childState === "bound" ? taskId : undefined,
314
);
315
if (childState === "provider-active" || childState === "roster") {
316
yield* apply({
@@ -438,7 +444,13 @@ it.effect.each([
444
(after.thread.pullRequests ?? []).filter((link) => link.watch !== undefined),
445
type === "subagent.stop" ? 1 : 0,
446
);
441
- const expected = childState === "idle" || childState === "archived" ? "cancelled" : "running";
447
+ // A task with a bound run, live or ended, keeps its settlement path.
448
+ const expected =
449
+ childState === "bound" || childState === "correlated"
450
+ ? "running"
451
+ : type === "subagent.stop" || childState === "idle" || childState === "archived"
452
+ ? "cancelled"
453
+ : "running";
454
assert.equal(after.subagents.find((task) => task.id === taskId)?.status, expected);
455
assert.equal(after.nodes.find((node) => node.id === taskId)?.status, expected);
456
assert.equal(after.turnItems.find((item) => item.id === itemId)?.status, expected);
@@ -468,6 +480,28 @@ it.effect.each([
480
assert.equal(repeated.subagents.find((task) => task.id === taskId)?.status, "cancelled");
481
assert.deepEqual(repeated.messages, after.messages);
482
assert.deepEqual(repeated.contextTransfers, after.contextTransfers);
483
+ if (type === "subagent.stop") {
484
+ // A client that missed the cancel, such as one resumed from an older cache, still
485
+ // shows the task as running. Its Stop gets the ended task back.
486
+ const eventStore = yield* EventStore.EventStoreV2;
487
+ const afterSequence = yield* eventStore.latestSequence({ threadId: parentThreadId });
488
+ yield* orchestrator.dispatch({
489
+ ...stop,
490
+ commandId: CommandId.make(`stop-orphan-stale-client:${childState}`),
491
+ type,
492
+ runId: original.runId!,
493
+ subagentId: taskId,
494
+ });
495
+ const resent = yield* eventStore
496
+ .read({ threadId: parentThreadId, afterSequence })
497
+ .pipe(Stream.runCollect);
498
+ assert.deepEqual(
499
+ resent.flatMap(({ event }) =>
500
+ event.type === "subagent.updated" ? [event.payload.status] : [],
501
+ ),
502
+ ["cancelled"],
503
+ );
504
+ }
505
}
506
}).pipe(Effect.provide(layerTest)),
507
);
packages/client-runtime/src/operations/commands.ts
+1
-1
@@ -774,7 +774,7 @@ export const interruptThreadTurn = Effect.fn("EnvironmentCommands.interruptThrea
774
const projection = yield* getProjection(input.threadId);
775
const subagent = projection.subagents.find((agent) => agent.id === input.subagentId);
776
if (subagent?.origin === "app_owned" && subagent.childThreadId !== null) {
777
- // The parent cancels the task if it is an orphan with an idle child (#19002). Older
777
+ // The parent ends the task even when its child lost track of it (#19002). Older
778
// servers reject this for app-owned tasks, so the child stop below still runs.
779
if (subagent.runId !== null) {
780
yield* dispatch({