The best way to control Claude Code, Codex and more from any computer or phone
fix(server): cancelling a background-only delegated task reports it interrupted (#21676)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: maria-rcks <maria@kuuro.net> Co-authored-by: Julius Marminge <julius0216@outlook.com>
Victor committed
Nov 11, 2026 at 05:13 UTC
fd9b2c3eaabd72e852e068c9d41c467e07c11ee1
10 files changed
+675
-61
apps/server/src/mcp/OrchestratorMcpService.test.ts
+20
@@ -594,6 +594,8 @@ describe("OrchestratorMcpService", () => {
594
listAppOwnedChildThreadIds: () => Effect.succeed([]),
595
delegatedTaskResultPending: () => Effect.succeed(false),
596
stopDelegatedTasks: () => Effect.void,
597
+ cancelDelegatedTask: ({ command }) =>
598
+ Ref.update(dispatched, (commands) => [...commands, command]),
599
// The orchestrator's subagent.stop repair is covered in ThreadStop.test.ts.
600
dispatch: (command) =>
601
Ref.update(dispatched, (commands) => [...commands, command]).pipe(
@@ -697,6 +699,12 @@ describe("OrchestratorMcpService", () => {
699
Ref.update(dispatched, (commands) => [...commands, command]).pipe(
700
Effect.andThen(Effect.fail(new Error("simulated stop failure") as never)),
701
),
702
+ stopDelegatedTasks: () => Effect.void,
703
+ cancelDelegatedTask: ({ command, stopDescendants }) =>
704
+ stopDescendants(() => Effect.die("No remote descendants in this test")).pipe(
705
+ Effect.andThen(Ref.update(dispatched, (commands) => [...commands, command])),
706
+ Effect.andThen(Effect.fail(new Error("simulated stop failure") as never)),
707
+ ),
708
}),
709
ServerSettings.layerTest(),
710
Layer.mock(ProviderRegistry.ProviderRegistry)({ getProviders: Effect.succeed([]) }),
@@ -786,6 +794,10 @@ describe("OrchestratorMcpService", () => {
794
),
795
),
796
stopDelegatedTasks: () => Effect.void,
797
+ cancelDelegatedTask: ({ command, stopDescendants }) =>
798
+ stopDescendants(() => Effect.die("No remote descendants in this test")).pipe(
799
+ Effect.andThen(Ref.update(dispatched, (commands) => [...commands, command])),
800
+ ),
801
}),
802
ServerSettings.layerTest(),
803
Layer.mock(ProviderRegistry.ProviderRegistry)({ getProviders: Effect.succeed([]) }),
@@ -876,6 +888,10 @@ describe("OrchestratorMcpService", () => {
888
),
889
),
890
stopDelegatedTasks: () => Effect.void,
891
+ cancelDelegatedTask: ({ command, stopDescendants }) =>
892
+ stopDescendants(() => Effect.die("No remote descendants in this test")).pipe(
893
+ Effect.andThen(Ref.update(dispatched, (commands) => [...commands, command])),
894
+ ),
895
}),
896
ServerSettings.layerTest(),
897
Layer.mock(ProviderRegistry.ProviderRegistry)({ getProviders: Effect.succeed([]) }),
@@ -1041,6 +1057,10 @@ describe("OrchestratorMcpService", () => {
1057
Ref.update(dispatched, (commands) => [...commands, command]).pipe(
1058
Effect.as({} as never),
1059
),
1060
+ cancelDelegatedTask: ({ command, stopDescendants }) =>
1061
+ stopDescendants(() => Effect.die("No remote descendants in this test")).pipe(
1062
+ Effect.andThen(Ref.update(dispatched, (commands) => [...commands, command])),
1063
+ ),
1064
stopDelegatedTasks: () =>
1065
Effect.gen(function* () {
1066
const limit = yield* DispatchModeLimit;
apps/server/src/mcp/OrchestratorMcpService.ts
+23
-17
@@ -1534,7 +1534,11 @@ const make = Effect.gen(function* () {
1534
: childRun,
1535
)
1536
: workState === "result_available"
1537
- ? taskStatusForRun(taskResultRun ?? childRun)
1537
+ ? // A cancelled task's finished turn settles it as interrupted.
1538
+ task.cancelledRunId !== undefined &&
1539
+ taskStatusForRun(taskResultRun ?? childRun) === "completed"
1540
+ ? "interrupted"
1541
+ : taskStatusForRun(taskResultRun ?? childRun)
1542
: taskStatusForRun(taskResultRun ?? childRun) === "queued"
1543
? "queued"
1544
: "running";
@@ -2640,13 +2644,25 @@ const make = Effect.gen(function* () {
2644
const stopChild = Effect.gen(function* () {
2645
const commandId = stableCommandId({ scope, requestKey: key, operation: "cancel-task" });
2646
const reason = agentStopReason(input.reason);
2647
+ const command = {
2648
+ type: "thread.stop" as const,
2649
+ commandId,
2650
+ threadId: childThreadId,
2651
+ stopDelegatedTasks: false,
2652
+ reason,
2653
+ };
2654
yield* threadManagement
2644
- .dispatch({
2645
- type: "thread.stop",
2646
- commandId,
2647
- threadId: childThreadId,
2648
- stopDelegatedTasks: false,
2649
- reason,
2655
+ .cancelDelegatedTask({
2656
+ parentThreadId: scope.thread.threadId,
2657
+ taskId: input.taskId,
2658
+ command,
2659
+ stopDescendants: (remoteDispatch) =>
2660
+ threadManagement.stopDelegatedTasks({
2661
+ threadId: childThreadId,
2662
+ commandId,
2663
+ reason,
2664
+ remoteDispatch,
2665
+ }),
2666
})
2667
.pipe(
2668
Effect.mapError((error) =>
@@ -2656,16 +2672,6 @@ const make = Effect.gen(function* () {
2672
),
2673
),
2674
);
2659
- yield* threadManagement
2660
- .stopDelegatedTasks({ threadId: childThreadId, commandId, reason })
2661
- .pipe(
2662
- Effect.mapError((error) =>
2663
- failure(
2664
- "task_not_cancellable",
2665
- `Stopped delegated task ${input.taskId}, but not every task it delegated: ${errorMessage(error)}`,
2666
- ),
2667
- ),
2668
- );
2675
const stopped = yield* threadManagement
2676
.getThreadRecords(childThreadId, ["runs"])
2677
.pipe(Effect.mapError(threadManagementFailure));
apps/server/src/mcp/TaskCancelNativeSubagent.integration.test.ts
+349
-27
@@ -4,6 +4,7 @@ import { assert, it } from "@effect/vitest";
4
import {
5
CommandId,
6
EnvironmentId,
7
+ EventId,
8
MessageId,
9
NodeId,
10
ProjectId,
@@ -11,6 +12,8 @@ import {
12
ProviderInstanceId,
13
ProviderThreadId,
14
ProviderTurnId,
15
+ RunId,
16
+ RuntimeRequestId,
17
ThreadId,
18
TurnItemId,
19
type OrchestrationV2DomainEvent,
@@ -18,13 +21,16 @@ import {
21
import * as DateTime from "effect/DateTime";
22
import * as Effect from "effect/Effect";
23
import * as Fiber from "effect/Fiber";
24
+import * as FileSystem from "effect/FileSystem";
25
import * as Layer from "effect/Layer";
26
+import * as Path from "effect/Path";
27
import * as Queue from "effect/Queue";
28
import * as Stream from "effect/Stream";
29
30
import { ClaudeProviderCapabilitiesV2 } from "../orchestration-v2/Adapters/ClaudeAdapterV2.ts";
31
import * as CommandReceiptStore from "../orchestration-v2/CommandReceiptStore.ts";
32
import * as EffectWorker from "../orchestration-v2/EffectWorker.ts";
33
+import * as EventSink from "../orchestration-v2/EventSink.ts";
34
import * as Orchestrator from "../orchestration-v2/Orchestrator.ts";
35
import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
36
import * as ProviderAdapterRegistry from "../orchestration-v2/ProviderAdapterRegistry.ts";
@@ -52,14 +58,25 @@ const driver = ProviderDriverKind.make("claudeAgent");
58
const instanceId = ProviderInstanceId.make("claudeAgent");
59
const modelSelection = { instanceId, model: "claude-test" };
60
55
-it.effect("task_cancel ends a delegated child's background native subagent", () =>
61
+// Cancellation races with turn completion and checkpoint capture; "recorded" restarts before the Stop outbox runs.
62
+const cancelBackgroundOnlyTask = (
63
+ background: "subagent" | "command",
64
+ {
65
+ cancelAt = "settled",
66
+ remote = false,
67
+ }: {
68
+ readonly remote?: boolean;
69
+ readonly cancelAt?: "settled" | "checkpoint" | "turn" | "recorded" | "monitor" | "refused";
70
+ } = {},
71
+) =>
72
Effect.scoped(
73
Effect.gen(function* () {
58
- const cwd = yield* checkpointWorkspace("task-cancel-native-subagent");
74
+ const cwd = yield* checkpointWorkspace(`task-cancel-background-${background}`);
75
const turns: Array<{
76
readonly turn: ProviderAdapter.ProviderAdapterV2TurnInput;
77
readonly events: Queue.Queue<ProviderAdapter.ProviderAdapterV2Event>;
78
}> = [];
79
+ const interrupted: Array<ReadonlyArray<string> | undefined> = [];
80
const adapter: ProviderAdapter.ProviderAdapterV2["Service"] = {
81
instanceId,
82
driver,
@@ -125,7 +142,10 @@ it.effect("task_cancel ends a delegated child's background native subagent", ()
142
});
143
}),
144
steerTurn: () => Effect.die("unused"),
128
- interruptTurn: () => Effect.void,
145
+ interruptTurn: ({ providerThread }) =>
146
+ Effect.sync(() => {
147
+ interrupted.push(providerThread.pendingBackgroundTasks?.map((t) => t.taskId));
148
+ }),
149
respondToRuntimeRequest: () => Effect.die("unused"),
150
readThreadSnapshot: () => Effect.die("unused"),
151
rollbackThread: () => Effect.die("unused"),
@@ -134,14 +154,54 @@ it.effect("task_cancel ends a delegated child's background native subagent", ()
154
}),
155
};
156
const layerAdapters = ProviderAdapterRegistry.layerSingle(adapter);
137
- const layerOrchestrator = ProviderReplayHarness.layerWithRegistry(
138
- { name: "task-cancel-native-subagent" },
139
- layerAdapters,
140
- { runEffectWorker: false },
157
+ const fs = yield* FileSystem.FileSystem;
158
+ const path = yield* Path.Path;
159
+ const directory = yield* fs.makeTempDirectoryScoped({ prefix: "t3-task-cancel-" });
160
+ const databaseLayer = SqlitePersistence.layerFromPath(
161
+ path.join(directory, "state.sqlite"),
162
+ ).pipe(Layer.provide(NodeServices.layer));
163
+ // Migrate the file first, as an existing install's database already is.
164
+ yield* Effect.provide(Effect.void, databaseLayer);
165
+ // Each build is a server on the same database; the second runs startup recovery.
166
+ let restarted = false;
167
+ const layerOrchestrator = Layer.suspend(() =>
168
+ ProviderReplayHarness.layerWithRegistry(
169
+ { name: "task-cancel-native-subagent" },
170
+ layerAdapters,
171
+ restarted
172
+ ? { databaseLayer, recoverOnStartup: true }
173
+ : { databaseLayer, runEffectWorker: false },
174
+ ),
175
);
176
const layerOrchestration = Layer.merge(
177
layerOrchestrator,
144
- ThreadManagementService.layer.pipe(
178
+ Layer.effect(
179
+ ThreadManagementService.ThreadManagementService,
180
+ Effect.map(ThreadManagementService.ThreadManagementService, (service) =>
181
+ cancelAt === "refused"
182
+ ? {
183
+ ...service,
184
+ stopDelegatedTasks: () =>
185
+ Effect.fail(
186
+ new Orchestrator.OrchestratorDispatchError({
187
+ commandId: CommandId.make("refused-descendant-stop"),
188
+ commandType: "thread.stop",
189
+ cause: "descendant refused stop",
190
+ }),
191
+ ),
192
+ }
193
+ : service,
194
+ ),
195
+ ).pipe(
196
+ Layer.provide(
197
+ ThreadManagementService.layer.pipe(
198
+ Layer.provide(layerOrchestrator),
199
+ Layer.provide(ServerSettings.layerTest()),
200
+ Layer.provide(
201
+ CommandReceiptStore.layer.pipe(Layer.provide(SqlitePersistence.layerMemory)),
202
+ ),
203
+ ),
204
+ ),
205
Layer.provide(layerOrchestrator),
206
Layer.provide(ServerSettings.layerTest()),
207
Layer.provide(
@@ -166,17 +226,25 @@ it.effect("task_cancel ends a delegated child's background native subagent", ()
226
),
227
);
228
169
- yield* Effect.gen(function* () {
229
+ const stopped = yield* Effect.gen(function* () {
230
const orchestrator = yield* Orchestrator.OrchestratorV2;
231
const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
232
const service = yield* OrchestratorMcpService.OrchestratorMcpService;
233
+ const eventSink = yield* EventSink.EventSinkV2;
234
const parentThreadId = ThreadId.make("thread:task-cancel-parent");
235
+ // Read the cursor before forking: provider events offered right after a watch can
236
+ // commit before a live-tail subscriber has read its starting sequence.
237
const watch = (predicate: (event: OrchestrationV2DomainEvent) => boolean) =>
175
- orchestrator.streamDomainEvents.pipe(
176
- Stream.filter(predicate),
177
- Stream.take(1),
178
- Stream.runDrain,
179
- Effect.forkScoped,
238
+ eventSink.latestSequence().pipe(
239
+ Effect.flatMap((afterSequence) =>
240
+ eventSink.stream({ afterSequence }).pipe(
241
+ Stream.map((stored) => stored.event),
242
+ Stream.filter(predicate),
243
+ Stream.take(1),
244
+ Stream.runDrain,
245
+ Effect.forkScoped,
246
+ ),
247
+ ),
248
);
249
const turnRunning = () =>
250
watch(
@@ -227,6 +295,41 @@ it.effect("task_cancel ends a delegated child's background native subagent", ()
295
createdBy: "agent",
296
creationSource: "mcp",
297
});
298
+ if (cancelAt === "turn") {
299
+ const pendingTask = (yield* orchestrator.getThreadProjection(parentThreadId))
300
+ .subagents[0]!;
301
+ const { runs } = yield* orchestrator.getThreadProjection(pendingTask.childThreadId!);
302
+ const now = yield* DateTime.now;
303
+ const current = runs[0]!;
304
+ const previous = {
305
+ ...current,
306
+ id: RunId.make("run:before-continuation"),
307
+ ordinal: 1,
308
+ status: "completed" as const,
309
+ startedAt: now,
310
+ completedAt: now,
311
+ };
312
+ const at = { threadId: current.threadId, occurredAt: now };
313
+ yield* eventSink.write({
314
+ commandId: CommandId.make("command:runtime-reconcile:continuation"),
315
+ events: [
316
+ {
317
+ ...at,
318
+ runId: current.id,
319
+ id: EventId.make("event:continuation"),
320
+ type: "run.updated",
321
+ payload: { ...current, ordinal: 2, restartContinuationOfRunId: previous.id },
322
+ },
323
+ {
324
+ ...at,
325
+ runId: previous.id,
326
+ id: EventId.make("event:previous"),
327
+ type: "run.updated",
328
+ payload: previous,
329
+ },
330
+ ],
331
+ });
332
+ }
333
yield* worker.drain();
334
yield* Fiber.join(childRunning);
335
const task = (yield* orchestrator.getThreadProjection(parentThreadId)).subagents[0]!;
@@ -258,7 +361,7 @@ it.effect("task_cancel ends a delegated child's background native subagent", ()
361
event.payload.id === child.turn.runId &&
362
event.payload.status === "waiting",
363
);
261
- for (const event of [
364
+ const nativeSubagentEvents = [
365
{
366
type: "node.updated",
367
driver,
@@ -307,6 +410,71 @@ it.effect("task_cancel ends a delegated child's background native subagent", ()
410
subagentId,
411
},
412
},
413
+ ] satisfies ReadonlyArray<ProviderAdapter.ProviderAdapterV2Event>;
414
+ const shellEvents = [
415
+ {
416
+ type: "provider_thread.updated",
417
+ driver,
418
+ providerThread: {
419
+ ...child.turn.providerThread,
420
+ status: "active",
421
+ pendingBackgroundTasks: [
422
+ { taskId: "bg-sleep", description: "sleep 300", kind: "command", awaited: true },
423
+ ],
424
+ updatedAt: now,
425
+ },
426
+ },
427
+ ] satisfies ReadonlyArray<ProviderAdapter.ProviderAdapterV2Event>;
428
+ const started = yield* watch((event) =>
429
+ background === "subagent"
430
+ ? event.type === "subagent.updated" && event.payload.id === subagentId
431
+ : event.type === "provider-thread.updated" &&
432
+ event.threadId === task.childThreadId &&
433
+ (event.payload.pendingBackgroundTasks?.length ?? 0) > 0,
434
+ );
435
+ // An async question the child asked during its turn, and one no run of this task owns.
436
+ const question = (id: string, nodeId: NodeId) =>
437
+ ({
438
+ type: "runtime_request.updated",
439
+ driver,
440
+ runtimeRequest: {
441
+ id: RuntimeRequestId.make(id),
442
+ nodeId,
443
+ providerTurnId: childTurn.id,
444
+ nativeRequestRef: null,
445
+ kind: "user_input",
446
+ status: "pending",
447
+ responseCapability: { type: "message" },
448
+ createdAt: now,
449
+ resolvedAt: null,
450
+ },
451
+ }) satisfies ProviderAdapter.ProviderAdapterV2Event;
452
+ for (const event of [
453
+ question("request:owned", child.turn.rootNodeId),
454
+ question("request:unrelated", NodeId.make("node:unrelated")),
455
+ ...(background === "subagent" ? nativeSubagentEvents : shellEvents),
456
+ ]) {
457
+ yield* Queue.offer(child.events, event);
458
+ }
459
+ yield* Fiber.join(started);
460
+ if (remote) {
461
+ yield* orchestrator.dispatch({
462
+ type: "delegated_task.remote.request",
463
+ commandId: CommandId.make("remote-descendant"),
464
+ parentThreadId: task.childThreadId!,
465
+ parentRunId: child.turn.runId,
466
+ parentNodeId: child.turn.rootNodeId,
467
+ task: "Work in a linked environment",
468
+ driver,
469
+ modelSelection,
470
+ remoteChild: {
471
+ environmentId: EnvironmentId.make("environment:remote-descendant"),
472
+ threadId: ThreadId.make("thread:remote-descendant"),
473
+ label: "Remote",
474
+ },
475
+ });
476
+ }
477
+ const turnEndEvents = [
478
{
479
type: "provider_turn.updated",
480
driver,
@@ -322,11 +490,32 @@ it.effect("task_cancel ends a delegated child's background native subagent", ()
490
failure: null,
491
threadDisposition: "reusable",
492
},
325
- ] satisfies ReadonlyArray<ProviderAdapter.ProviderAdapterV2Event>) {
326
- yield* Queue.offer(child.events, event);
493
+ ] satisfies ReadonlyArray<ProviderAdapter.ProviderAdapterV2Event>;
494
+ const endTurn = Effect.gen(function* () {
495
+ for (const event of turnEndEvents) yield* Queue.offer(child.events, event);
496
+ yield* Fiber.join(waiting);
497
+ });
498
+ if (cancelAt !== "turn") yield* endTurn;
499
+ const turnSettled =
500
+ cancelAt !== "checkpoint" && cancelAt !== "turn" && cancelAt !== "recorded";
501
+ if (turnSettled) yield* worker.drain();
502
+ if (cancelAt === "monitor") {
503
+ // A monitor notification then ran and completed while the shell kept running.
504
+ const { runs, messages } = yield* orchestrator.getThreadProjection(task.childThreadId!);
505
+ const run = { ...runs[0]!, id: RunId.make("run:monitor"), ordinal: 2 };
506
+ const source = { kind: "monitor" } as const;
507
+ const notification = { source, outcome: "updated", summary: "Ran" } as const;
508
+ const user = { ...messages[0]!, id: MessageId.make("message:monitor"), runId: run.id };
509
+ const message = { ...user, notification };
510
+ const at = { threadId: run.threadId, runId: run.id, occurredAt: now };
511
+ yield* (yield* EventSink.EventSinkV2).write({
512
+ commandId: CommandId.make("command:runtime-reconcile:monitor"),
513
+ events: [
514
+ { ...at, id: EventId.make("event:m1"), type: "message.updated", payload: message },
515
+ { ...at, id: EventId.make("event:m2"), type: "run.updated", payload: run },
516
+ ],
517
+ });
518
}
328
- yield* Fiber.join(waiting);
329
- yield* worker.drain();
519
520
const scope: McpInvocationScope = {
521
environmentId: EnvironmentId.make("environment:task-cancel"),
@@ -342,33 +531,166 @@ it.effect("task_cancel ends a delegated child's background native subagent", ()
531
};
532
const before = yield* service.taskStatus(scope, task.id);
533
assert.equal(before.status, "running");
345
- assert.equal(before.workState, "waiting_for_children");
534
+ assert.equal(before.workState, turnSettled ? "waiting_for_children" : "working");
535
536
+ const parentTask = Effect.map(orchestrator.getThreadProjection(parentThreadId), (parent) =>
537
+ parent.subagents.find((entry) => entry.id === task.id),
538
+ );
539
+ if (cancelAt === "recorded") {
540
+ const commandId = CommandId.make("stop-recorded");
541
+ yield* orchestrator.cancelDelegatedTask({
542
+ parentThreadId,
543
+ taskId: task.id,
544
+ command: {
545
+ type: "thread.stop",
546
+ commandId,
547
+ threadId: task.childThreadId!,
548
+ stopDelegatedTasks: false,
549
+ },
550
+ stopDescendants: () => Effect.void,
551
+ });
552
+ const committed = yield* eventSink.readByCommandId({ commandId }).pipe(Stream.runCollect);
553
+ assert.isTrue(
554
+ committed.some(
555
+ ({ event }) =>
556
+ event.type === "subagent.updated" && event.payload.cancelledRunId !== undefined,
557
+ ),
558
+ );
559
+ assert.isTrue(
560
+ committed.some(
561
+ ({ event }) =>
562
+ event.type === "turn-item.updated" &&
563
+ event.payload.type === "run_interrupt_request",
564
+ ),
565
+ );
566
+ assert.equal((yield* parentTask)?.status, "running");
567
+ return { scope, taskId: task.id, settled: undefined };
568
+ }
569
+ if (cancelAt === "refused") {
570
+ yield* Effect.flip(
571
+ service.cancelTask(scope, { taskId: task.id, clientRequestId: "refused-cancel" }),
572
+ );
573
+ const after = yield* parentTask;
574
+ assert.equal(after?.status, "running");
575
+ assert.equal(after?.result, null);
576
+ assert.isUndefined(after?.cancelledRunId);
577
+ return undefined;
578
+ }
579
+ // Settling the task ends the async question it left, after its own row.
580
+ const settled = yield* watch(
581
+ (event) =>
582
+ event.type === "runtime-request.updated" &&
583
+ event.payload.id === "request:owned" &&
584
+ event.payload.status === "resolved",
585
+ );
586
const cancelled = yield* service.cancelTask(scope, {
587
taskId: task.id,
588
clientRequestId: "cancel-task",
589
});
590
assert.equal(cancelled.status, "cancel_requested");
591
+ assert.equal((yield* parentTask)?.cancelledRunId, child.turn.runId);
592
+ // The turn completes normally after Stop, before its interrupt reaches the provider.
593
+ if (cancelAt === "turn") yield* endTurn;
594
yield* worker.drain();
595
+ const owned = Effect.map(orchestrator.getThreadProjection(task.childThreadId!), (child) =>
596
+ child.runtimeRequests.find((request) => request.id === "request:owned"),
597
+ );
598
+ // task_cancel settles a finished turn itself; a running one settles when it ends.
599
+ if ((yield* owned)?.status !== "resolved") yield* Fiber.join(settled);
600
601
const childAfter = yield* orchestrator.getThreadProjection(task.childThreadId!);
602
+ const nativeStatus = background === "subagent" ? "interrupted" : undefined;
603
assert.equal(
604
childAfter.subagents.find((entry) => entry.id === subagentId)?.status,
357
- "interrupted",
605
+ nativeStatus,
606
);
607
assert.equal(
608
childAfter.nodes.find((entry) => entry.id === subagentId)?.status,
361
- "interrupted",
609
+ nativeStatus,
610
);
611
assert.equal(
364
- childAfter.turnItems.find((item) => item.type === "subagent")?.status,
365
- "interrupted",
612
+ childAfter.turnItems.find(
613
+ (item) => item.type === "subagent" && item.subagentId === subagentId,
614
+ )?.status,
615
+ nativeStatus,
616
+ );
617
+ if (remote) {
618
+ const descendant = childAfter.subagents.find((entry) => entry.remoteChild !== undefined);
619
+ assert.equal(descendant?.status, "interrupted");
620
+ assert.notEqual(descendant?.remoteChild?.stoppedThere, true);
621
+ }
622
+ // Stop reached the provider turn that owns the shell.
623
+ if (background === "command") assert.deepEqual(interrupted, [["bg-sleep"]]);
624
+ assert.equal(childAfter.runs.length, cancelAt === "monitor" || cancelAt === "turn" ? 2 : 1);
625
+ assert.equal(childAfter.runs[0]!.status, "completed");
626
+ assert.deepEqual(
627
+ childAfter.runtimeRequests.map((request) => [request.id, request.status]),
628
+ [
629
+ ["request:owned", "resolved"],
630
+ ["request:unrelated", "pending"],
631
+ ],
632
);
633
634
const after = yield* service.taskStatus(scope, task.id);
369
- assert.equal(after.status, "completed");
370
- assert.notEqual(after.workState, "waiting_for_children");
635
+ assert.equal(after.status, "interrupted");
636
+ assert.equal(after.workState, "result_available");
637
+ const settledTask = yield* parentTask;
638
+ assert.equal(settledTask?.status, "interrupted");
639
+ assert.notEqual(settledTask?.completedAt, null);
640
+ assert.equal(settledTask?.cancelledRunId, child.turn.runId);
641
+
642
+ return { scope, taskId: task.id, settled: settledTask };
643
+ }).pipe(Effect.provide(layerTest));
644
+ if (stopped === undefined) return;
645
+ restarted = true;
646
+
647
+ // A server restarted on the same database runs startup recovery and keeps the outcome.
648
+ yield* Effect.gen(function* () {
649
+ const service = yield* OrchestratorMcpService.OrchestratorMcpService;
650
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
651
+ yield* (yield* EffectWorker.OrchestrationEffectWorkerV2).drain();
652
+ yield* orchestrator.recoverDelegatedTasks;
653
+ const task = (yield* orchestrator.getThreadProjection(
654
+ stopped.scope.thread!.threadId,
655
+ )).subagents.find((entry) => entry.id === stopped.taskId);
656
+ const status = yield* service.taskStatus(stopped.scope, stopped.taskId);
657
+ assert.equal(status.status, "interrupted");
658
+ assert.equal(status.summary, task?.result);
659
+ assert.equal(task?.status, "interrupted");
660
+ assert.notEqual(task?.completedAt, null);
661
+ if (stopped.settled !== undefined) assert.deepEqual(task, stopped.settled);
662
}).pipe(Effect.provide(layerTest));
663
}),
373
- ),
664
+ ).pipe(Effect.provide(NodeServices.layer));
665
+
666
+it.effect("task_cancel ends a delegated child's background native subagent", () =>
667
+ cancelBackgroundOnlyTask("subagent"),
668
+);
669
+
670
+it.effect("task_cancel ends a delegated child's background shell command", () =>
671
+ cancelBackgroundOnlyTask("command"),
672
+);
673
+
674
+it.effect("task_cancel ends background work while the child's run captures its checkpoint", () =>
675
+ cancelBackgroundOnlyTask("command", { cancelAt: "checkpoint" }),
676
+);
677
+
678
+it.effect("task_cancel ends background work left by a turn that finishes after Stop", () =>
679
+ cancelBackgroundOnlyTask("command", { cancelAt: "turn" }),
680
+);
681
+
682
+it.effect("task_cancel ends the shell's question though a monitor ran after the turn", () =>
683
+ cancelBackgroundOnlyTask("command", { cancelAt: "monitor" }),
684
+);
685
+
686
+it.effect("cancellation and Stop commit together and recover before the outbox ran", () =>
687
+ cancelBackgroundOnlyTask("subagent", { cancelAt: "recorded" }),
688
+);
689
+
690
+it.effect("a refused descendant stop does not settle or dispose its parent task", () =>
691
+ cancelBackgroundOnlyTask("command", { cancelAt: "refused" }),
692
+);
693
+
694
+it.effect("task_cancel stops a remote descendant without reacquiring its parent lock", () =>
695
+ cancelBackgroundOnlyTask("command", { remote: true }),
696
);
apps/server/src/orchestration-v2/DelegatedCompletionDelivery.test.ts
+130
-5
@@ -2786,6 +2786,8 @@ it.layer(Layer.merge(layerTest, ProviderContinuationRequests.layer))(
2786
"restarted",
2787
"stopped",
2788
"overlapping",
2789
+ "after-cancel",
2790
+ "cancelled",
2791
] as const;
2792
it.effect.each(outcomes)(
2793
"delivers a %s follow-up independently of the original task",
@@ -2830,6 +2832,26 @@ it.layer(Layer.merge(layerTest, ProviderContinuationRequests.layer))(
2832
taskId: child.taskId,
2833
observedByRunId: parentRunId,
2834
});
2835
+ if (outcome === "after-cancel") {
2836
+ // A follow-up is its own task, even after task_cancel reached the original.
2837
+ const settled = (yield* orchestrator.getThreadProjection(
2838
+ parentThreadId,
2839
+ )).subagents.find((task) => task.id === child.taskId)!;
2840
+ // The follow-up starts in the same millisecond the cancel was recorded.
2841
+ yield* eventSink.write({
2842
+ commandId: reconcileCommandId("followup-original-cancelled"),
2843
+ events: [
2844
+ {
2845
+ id: EventId.make("event:followup-original-cancelled"),
2846
+ type: "subagent.updated",
2847
+ threadId: parentThreadId,
2848
+ nodeId: settled.id,
2849
+ occurredAt: now,
2850
+ payload: { ...settled, cancelledRunId: child.childRunId },
2851
+ },
2852
+ ],
2853
+ });
2854
+ }
2855
const original = (yield* orchestrator.getThreadProjection(parentThreadId)).subagents.find(
2856
(task) => task.id === child.taskId,
2857
)!;
@@ -2940,9 +2962,54 @@ it.layer(Layer.merge(layerTest, ProviderContinuationRequests.layer))(
2962
commandId: CommandId.make(`command:followup-stop-${outcome}`),
2963
});
2964
}
2965
+ if (outcome === "cancelled") {
2966
+ // task_cancel reaches the follow-up after its turn ended, while background work runs.
2967
+ yield* eventSink.write({
2968
+ commandId: reconcileCommandId("followup-waiting"),
2969
+ events: [
2970
+ {
2971
+ id: EventId.make("event:followup-waiting"),
2972
+ type: "run.updated",
2973
+ threadId: child.childThreadId,
2974
+ runId: run.id,
2975
+ occurredAt: now,
2976
+ payload: { ...run, status: "waiting", startedAt: now },
2977
+ },
2978
+ ],
2979
+ });
2980
+ yield* orchestrator.cancelDelegatedTask({
2981
+ parentThreadId,
2982
+ taskId: run.delegatedTaskId!,
2983
+ command: {
2984
+ type: "thread.stop",
2985
+ commandId: CommandId.make(`cancel-followup-${outcome}`),
2986
+ threadId: child.childThreadId,
2987
+ stopDelegatedTasks: false,
2988
+ },
2989
+ stopDescendants: () => Effect.void,
2990
+ });
2991
+ }
2992
yield* eventSink.write({
2993
commandId: reconcileCommandId(`followup-finish-${outcome}`),
2994
events: [
2995
+ {
2996
+ id: EventId.make(`event:followup-question-${outcome}`),
2997
+ type: "runtime-request.updated",
2998
+ threadId: child.childThreadId,
2999
+ runId: run.id,
3000
+ occurredAt: now,
3001
+ payload: {
3002
+ id: RuntimeRequestId.make(`request:followup-${outcome}`),
3003
+ nodeId: run.rootNodeId!,
3004
+ providerTurnId: null,
3005
+ nativeRequestRef: null,
3006
+ kind: "user_input",
3007
+ status: "pending",
3008
+ responseCapability: { type: "message" },
3009
+ createdAt: now,
3010
+ resolvedAt: null,
3011
+ },
3012
+ },
3013
{
3014
id: EventId.make(`event:followup-finish-${outcome}`),
3015
type: "run.updated",
@@ -2954,7 +3021,10 @@ it.layer(Layer.merge(layerTest, ProviderContinuationRequests.layer))(
3021
status:
3022
outcome === "stopped"
3023
? "interrupted"
2957
- : outcome === "restarted" || outcome === "overlapping"
3024
+ : outcome === "restarted" ||
3025
+ outcome === "overlapping" ||
3026
+ outcome === "after-cancel" ||
3027
+ outcome === "cancelled"
3028
? "completed"
3029
: outcome,
3030
startedAt: now,
@@ -2964,6 +3034,12 @@ it.layer(Layer.merge(layerTest, ProviderContinuationRequests.layer))(
3034
],
3035
});
3036
yield* orchestrator.recoverDelegatedTasks;
3037
+ // Only an interrupted or cancelled follow-up ends its question, even after the original
3038
+ // was cancelled.
3039
+ const ended =
3040
+ outcome === "stopped" || outcome === "interrupted" || outcome === "cancelled";
3041
+ const { runtimeRequests } = yield* orchestrator.getThreadProjection(child.childThreadId);
3042
+ assert.equal(runtimeRequests[0]?.status, ended ? "resolved" : "pending");
3043
const finished = yield* orchestrator.getThreadProjection(parentThreadId);
3044
assert.deepEqual(
3045
finished.subagents.find((task) => task.id === child.taskId),
@@ -2982,17 +3058,18 @@ it.layer(Layer.merge(layerTest, ProviderContinuationRequests.layer))(
3058
}
3059
assert.equal(
3060
followup.status,
2985
- outcome === "stopped"
3061
+ outcome === "stopped" || outcome === "cancelled"
3062
? "interrupted"
2987
- : outcome === "restarted" || outcome === "overlapping"
3063
+ : outcome === "restarted" || outcome === "overlapping" || outcome === "after-cancel"
3064
? "completed"
3065
: outcome,
3066
);
3067
assert.equal(
3068
followup.completionDelivery?.state,
2993
- outcome === "stopped" ? "disposed" : "claimed",
3069
+ outcome === "stopped" || outcome === "cancelled" ? "disposed" : "claimed",
3070
);
2995
- if (outcome !== "stopped") {
3071
+ assert.equal(followup.cancelledRunId, outcome === "cancelled" ? run.id : undefined);
3072
+ if (outcome !== "stopped" && outcome !== "cancelled") {
3073
let wake = yield* requests.take;
3074
while (
3075
wake.threadId !== parentThreadId ||
@@ -3760,6 +3837,54 @@ it.layer(layerTest)("delegated tasks across a server restart", (it) => {
3837
}),
3838
);
3839
3840
+ it.effect("cancelling a task whose child already finished keeps its completed result", () =>
3841
+ Effect.gen(function* () {
3842
+ const orchestrator = yield* Orchestrator.OrchestratorV2;
3843
+ const now = yield* DateTime.now;
3844
+ const threadId = ThreadId.make("thread:cancel-finished-parent");
3845
+ const projectId = ProjectId.make("project:cancel-finished-parent");
3846
+ const runId = RunId.make("run:cancel-finished-parent");
3847
+ const rootNodeId = NodeId.make("node:cancel-finished-parent-root");
3848
+ yield* seedParentWithTerminalTask({
3849
+ threadId,
3850
+ projectId,
3851
+ runId,
3852
+ rootNodeId,
3853
+ taskId: NodeId.make("node:cancel-finished-parent-settled"),
3854
+ deliveryState: "delivered",
3855
+ now,
3856
+ });
3857
+ // The child run finished, but its parent row has not been finalized yet.
3858
+ const child = yield* seedRestartCancelledChild({
3859
+ parentThreadId: threadId,
3860
+ projectId,
3861
+ parentRunId: runId,
3862
+ rootNodeId,
3863
+ name: "cancel-finished-child",
3864
+ completionWake: "always",
3865
+ continuationPending: false,
3866
+ runStatus: "completed",
3867
+ now,
3868
+ });
3869
+ yield* orchestrator.cancelDelegatedTask({
3870
+ parentThreadId: threadId,
3871
+ taskId: child.taskId,
3872
+ command: {
3873
+ type: "thread.stop",
3874
+ commandId: CommandId.make("cancel-finished-child"),
3875
+ threadId: child.childThreadId,
3876
+ stopDelegatedTasks: false,
3877
+ },
3878
+ stopDescendants: () => Effect.void,
3879
+ });
3880
+ const task = (yield* orchestrator.getThreadProjection(threadId)).subagents.find(
3881
+ (row) => row.id === child.taskId,
3882
+ );
3883
+ assert.equal(task?.status, "completed");
3884
+ assert.isUndefined(task?.cancelledRunId);
3885
+ }),
3886
+ );
3887
+
3888
// Running does not prove prompt consumption in Claude; re-offer cut deliveries even when resuming the turn.
3889
it.effect("re-offers a cut delivery even when a continuation resumes its turn", () =>
3890
Effect.gen(function* () {
apps/server/src/orchestration-v2/Orchestrator.ts
+137
-7
@@ -381,6 +381,15 @@ export interface OrchestratorV2Shape {
381
readonly resumeQueuedRuns: Effect.Effect<number, OrchestratorV2Error>;
382
readonly recoverDelegatedTasks: Effect.Effect<void>;
383
readonly recoverDelegatedTask: (threadId: ThreadId, sourceRunId: RunId) => Effect.Effect<void>;
384
+ /** Commits cancellation with the child's Stop after descendants accept stopping. */
385
+ readonly cancelDelegatedTask: <E, R>(input: {
386
+ readonly parentThreadId: ThreadId;
387
+ readonly taskId: NodeId;
388
+ readonly command: Extract<OrchestrationV2ServerCommand, { readonly type: "thread.stop" }>;
389
+ readonly stopDescendants: (
390
+ dispatch: OrchestratorV2Shape["dispatch"],
391
+ ) => Effect.Effect<void, E, R>;
392
+ }) => Effect.Effect<void, E | OrchestratorV2Error, R>;
393
readonly delegatedTaskResultPending: (
394
childThreadId: ThreadId,
395
taskId?: NodeId,
@@ -8675,6 +8684,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
8684
completionDelivery: { state: "pending", observedByRunId: null },
8685
status: run.status === "queued" ? (run.queueHeld === true ? "idle" : "pending") : "running",
8686
progress: undefined,
8687
+ cancelledRunId: undefined,
8688
result: null,
8689
startedAt: now,
8690
completedAt: null,
@@ -13061,8 +13071,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
13071
: undefined
13072
: delegatedTaskResultRun(taskRuns, options.task.id);
13073
if (childRun === undefined) return;
13064
- const outcome = runOutcome(childRun);
13065
- const terminalStatus = delegatedTaskTerminalStatus(outcome);
13074
+ let outcome = runOutcome(childRun);
13075
+ let terminalStatus = delegatedTaskTerminalStatus(outcome);
13076
if (terminalStatus === null) {
13077
if (childRun.delegatedTaskId === undefined || childRun.id !== options.syncRunId) return;
13078
const task = options.task;
@@ -13168,6 +13178,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
13178
if (task === undefined) {
13179
return;
13180
}
13181
+ // A cancelled task's completed run ends it interrupted.
13182
+ const cancelled = task.cancelledRunId === childRun.id;
13183
+ if (cancelled && terminalStatus === "completed") outcome = terminalStatus = "interrupted";
13184
const existingResultTransfer = parentProjection.contextTransfers.find(
13185
(transfer) =>
13186
transfer.type === "subagent_result" &&
@@ -13197,6 +13210,13 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
13210
result: result.text,
13211
completedAt: now,
13212
updatedAt: now,
13213
+ // The cancelling parent gets no wake, and the task records the run it settled from.
13214
+ ...(cancelled
13215
+ ? {
13216
+ cancelledRunId: childRun.id,
13217
+ completionDelivery: { state: "disposed" as const, observedByRunId: null },
13218
+ }
13219
+ : {}),
13220
};
13221
const completionPlan = yield* planDelegatedCompletionDelivery({
13222
parentProjection,
@@ -13303,6 +13323,15 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
13323
},
13324
);
13325
13326
+ // A waiting run has ended its turn, so its task waits only on the work it left.
13327
+ const progressAfterTurn = (child: Parameters<typeof delegatedTaskProgress>[0]) =>
13328
+ delegatedTaskProgress({
13329
+ ...child,
13330
+ runs: child.runs.map((run) =>
13331
+ run.status === "waiting" ? { ...run, status: "completed" as const } : run,
13332
+ ),
13333
+ });
13334
+
13335
const finalizeAppOwnedSubagent = Effect.fn("Orchestrator.finalizeAppOwnedSubagent")(function* (
13336
childThreadId: ThreadId,
13337
options?: { readonly settledContinuationOf?: RunId; readonly syncRunId?: RunId },
@@ -13325,11 +13354,13 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
13354
"contextTransfers",
13355
]);
13356
for (const task of parent.subagents) {
13357
+ // A cancelled task does not wait for the work its cancel is stopping.
13358
+ const cancelled = task.cancelledRunId !== undefined;
13359
if (
13360
task.origin !== "app_owned" ||
13361
task.childThreadId !== childThreadId ||
13362
(task.id === childControls.thread.forkedFrom.nodeId &&
13332
- progress.state !== "result_available") ||
13363
+ (cancelled ? progress.state === "working" : progress.state !== "result_available")) ||
13364
(task.result !== null &&
13365
parent.contextTransfers.some(
13366
(transfer) =>
@@ -13344,10 +13375,20 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
13375
});
13376
}
13377
13378
+ // Only the run a cancelled task settled from ends with it. The row read above has no
13379
+ // such run yet when this call settled the task, from the same result run.
13380
const { resultRun } = progress;
13348
- if (progress.state !== "result_available" || resultRun === undefined) return;
13381
+ const resultTaskId = resultRun?.delegatedTaskId ?? childControls.thread.forkedFrom.nodeId;
13382
+ const resultTask = parent.subagents.find((task) => task.id === resultTaskId);
13383
+ const taskCancelled =
13384
+ resultTask?.cancelledRunId !== undefined && resultTask.cancelledRunId === resultRun?.id;
13385
+ if (
13386
+ resultRun === undefined ||
13387
+ (taskCancelled ? progress.state === "working" : progress.state !== "result_available")
13388
+ )
13389
+ return;
13390
const status = delegatedTaskTerminalStatus(runOutcome(resultRun));
13350
- if (status !== "cancelled" && status !== "interrupted") return;
13391
+ if (status !== "interrupted" && status !== "cancelled" && !taskCancelled) return;
13392
if (
13393
yield* childAwaitsRestartContinuation(
13394
childControls.runs,
@@ -14052,6 +14093,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
14093
const dispatchWithReceiptEffect = Effect.fn("orchestrationV2.dispatch.withReceipt")(function* (
14094
command: OrchestrationV2ServerCommand,
14095
sideChatIds: ReadonlyArray<ThreadId> = [],
14096
+ cancelledTask?: OrchestrationV2Subagent,
14097
): Effect.fn.Return<OrchestratorV2DispatchResult, OrchestratorV2Error> {
14098
yield* Effect.annotateCurrentSpan({
14099
"orchestration_v2.command_id": command.commandId,
@@ -14162,7 +14204,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
14204
),
14205
);
14206
14165
- if (plan.events.length === 0 && plan.effects.length === 0) {
14207
+ if (plan.events.length === 0 && plan.effects.length === 0 && cancelledTask === undefined) {
14208
// A settle that ended nothing still records its receipt: a replayed Stop
14209
// effect then finds it instead of settling work that appeared since.
14210
const { resultSequence, inserted } = yield* Effect.gen(function* () {
@@ -14212,7 +14254,19 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
14254
threadId: commandThreadId(command),
14255
commandType: command.type,
14256
acceptedAt,
14215
- events: plan.events,
14257
+ events:
14258
+ cancelledTask === undefined
14259
+ ? plan.events
14260
+ : [
14261
+ ...plan.events,
14262
+ yield* makeSystemEvent({
14263
+ type: "subagent.updated",
14264
+ threadId: cancelledTask.threadId,
14265
+ nodeId: cancelledTask.id,
14266
+ occurredAt: cancelledTask.updatedAt,
14267
+ payload: cancelledTask,
14268
+ }).pipe(mapDispatchError(command)),
14269
+ ],
14270
effects: plan.effects,
14271
...(plan.cancelUnsettledEffects === undefined
14272
? {}
@@ -14610,6 +14664,81 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
14664
),
14665
);
14666
14667
+ const cancelDelegatedTask: OrchestratorV2Shape["cancelDelegatedTask"] = Effect.fn(
14668
+ "Orchestrator.cancelDelegatedTask",
14669
+ )(function* (input) {
14670
+ const { command } = input;
14671
+ return yield* threadDispatch.withLock(
14672
+ input.parentThreadId,
14673
+ Effect.gen(function* () {
14674
+ const { subagents } = yield* projectionStore
14675
+ .getThreadRecords(input.parentThreadId, ["subagents"])
14676
+ .pipe(mapDispatchError(command));
14677
+ const task = subagents.find(
14678
+ (candidate) =>
14679
+ candidate.id === input.taskId &&
14680
+ candidate.origin === "app_owned" &&
14681
+ candidate.childThreadId === command.threadId &&
14682
+ isOrchestrationV2WorkActive(candidate.status),
14683
+ );
14684
+ const child = yield* projectionStore
14685
+ .getThreadRecords(
14686
+ command.threadId,
14687
+ ["runs", "messages", "subagents", "providerThreads"],
14688
+ { messageRoles: ["user"] },
14689
+ )
14690
+ .pipe(mapDispatchError(command));
14691
+ const followUpRun = child.runs
14692
+ .filter((run) => run.delegatedTaskId === input.taskId)
14693
+ .toSorted((a, b) => b.ordinal - a.ordinal)[0];
14694
+ const unsettled =
14695
+ followUpRun === undefined
14696
+ ? child.thread.forkedFrom?.type === "node" &&
14697
+ child.thread.forkedFrom.nodeId === input.taskId &&
14698
+ progressAfterTurn(child).state !== "result_available"
14699
+ : delegatedTaskTerminalStatus(runOutcome(followUpRun)) === null;
14700
+ yield* threadDispatch.withLock(
14701
+ command.threadId,
14702
+ Effect.gen(function* () {
14703
+ // Hold intake closed until descendants stop and this thread's Stop commits.
14704
+ yield* input.stopDescendants((command) =>
14705
+ commandThreadId(command) === input.command.threadId
14706
+ ? dispatchWithReceiptEffect(command)
14707
+ : dispatchWithReceipt(command),
14708
+ );
14709
+ const child = yield* projectionStore
14710
+ .getThreadRecords(
14711
+ command.threadId,
14712
+ ["runs", "messages", "subagents", "providerThreads"],
14713
+ { messageRoles: ["user"] },
14714
+ )
14715
+ .pipe(mapDispatchError(command));
14716
+ const followUpRun = child.runs
14717
+ .filter((run) => run.delegatedTaskId === input.taskId)
14718
+ .toSorted((a, b) => b.ordinal - a.ordinal)[0];
14719
+ const monitorRunIds = new Set(
14720
+ child.messages
14721
+ .filter((message) => message.notification?.source.kind === "monitor")
14722
+ .map((message) => message.runId),
14723
+ );
14724
+ const activeRun = child.runs
14725
+ .filter((run) => isLiveRun(run) && !monitorRunIds.has(run.id))
14726
+ .toSorted((a, b) => b.ordinal - a.ordinal)[0];
14727
+ const cancelledRun = followUpRun ?? activeRun ?? progressAfterTurn(child).resultRun;
14728
+ const now = yield* DateTime.now;
14729
+ const cancelledTask =
14730
+ task !== undefined && unsettled && cancelledRun !== undefined
14731
+ ? { ...task, cancelledRunId: cancelledRun.id, updatedAt: now }
14732
+ : undefined;
14733
+ // The marker, Stop receipt and interrupt outbox commit together under both locks.
14734
+ yield* dispatchWithReceiptEffect(command, [], cancelledTask);
14735
+ }),
14736
+ );
14737
+ yield* finalizeAppOwnedSubagent(command.threadId).pipe(mapDispatchError(command));
14738
+ }),
14739
+ );
14740
+ });
14741
+
14742
const shellProjectionError = (cause: unknown) =>
14743
new OrchestratorProjectionError({ threadId: ThreadId.make("thread:shell"), cause });
14744
@@ -14617,6 +14746,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
14746
resumeQueuedRuns,
14747
recoverDelegatedTasks,
14748
recoverDelegatedTask,
14749
+ cancelDelegatedTask,
14750
delegatedTaskResultPending,
14751
restartContinuationPending: Effect.fn("OrchestratorV2.restartContinuationPending")(
14752
function (run) {
apps/server/src/orchestration-v2/ThreadManagementService.ts
+7
-2
@@ -484,6 +484,7 @@ export interface ThreadManagementServiceShape {
484
ThreadManagementBackgroundWaitError
485
>;
486
readonly stopDelegatedTasks: (input: {
487
+ readonly remoteDispatch?: Orchestrator.OrchestratorV2["Service"]["dispatch"];
488
readonly threadId: ThreadId;
489
readonly commandId: CommandId;
490
readonly reason?: string | undefined;
@@ -493,6 +494,7 @@ export interface ThreadManagementServiceShape {
494
>;
495
readonly getThreadEventSequence: Orchestrator.OrchestratorV2["Service"]["getThreadEventSequence"];
496
readonly recoverDelegatedTask: Orchestrator.OrchestratorV2["Service"]["recoverDelegatedTask"];
497
+ readonly cancelDelegatedTask: Orchestrator.OrchestratorV2["Service"]["cancelDelegatedTask"];
498
readonly delegatedTaskResultPending: Orchestrator.OrchestratorV2["Service"]["delegatedTaskResultPending"];
499
readonly streamStoredEvents: Orchestrator.OrchestratorV2["Service"]["streamStoredEvents"];
500
readonly streamStoredEventsFrom: Orchestrator.OrchestratorV2["Service"]["streamStoredEventsFrom"];
@@ -1494,7 +1496,7 @@ const make = Effect.gen(function* () {
1496
// One with its result keeps it, but its thread there may run follow-up work.
1497
if (task.remoteChild === undefined) continue;
1498
const commandId = CommandId.make(`${input.commandId}:stop:${task.id}`);
1497
- yield* dispatch(
1499
+ yield* (input.remoteDispatch ?? dispatch)(
1500
task.result === null
1501
? {
1502
type: "delegated_task.remote.complete",
@@ -1535,7 +1537,9 @@ const make = Effect.gen(function* () {
1537
stopDelegatedTasks: false,
1538
...(input.reason === undefined ? {} : { reason: input.reason }),
1539
}).pipe(
1538
- Effect.andThen(stopDelegatedTasks({ ...input, threadId })),
1540
+ Effect.andThen(
1541
+ stopDelegatedTasks({ threadId, commandId: input.commandId, reason: input.reason }),
1542
+ ),
1543
Effect.catch((error) =>
1544
Effect.logWarning("Unable to stop a delegated task", {
1545
parentThreadId: input.threadId,
@@ -1640,6 +1644,7 @@ const make = Effect.gen(function* () {
1644
awaitBackgroundTasks,
1645
getThreadEventSequence: orchestrator.getThreadEventSequence,
1646
recoverDelegatedTask: orchestrator.recoverDelegatedTask,
1647
+ cancelDelegatedTask: orchestrator.cancelDelegatedTask,
1648
delegatedTaskResultPending: orchestrator.delegatedTaskResultPending,
1649
streamStoredEvents: orchestrator.streamStoredEvents,
1650
streamStoredEventsFrom: orchestrator.streamStoredEventsFrom,
apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts
+1
@@ -500,6 +500,7 @@ export function layerWithRegistry<Error>(
500
getThreadRecords: orchestrator.getThreadRecords,
501
getThreadProjection: orchestrator.getThreadProjection,
502
recoverDelegatedTask: orchestrator.recoverDelegatedTask,
503
+ cancelDelegatedTask: orchestrator.cancelDelegatedTask,
504
delegatedTaskResultPending: orchestrator.delegatedTaskResultPending,
505
});
506
}),
apps/server/src/relay/AgentAwarenessRelay.test.ts
+1
@@ -261,6 +261,7 @@ const makeTestRelay = Effect.fnUntraced(function* (
261
stopDelegatedTasks: unused,
262
getThreadEventSequence: unused,
263
recoverDelegatedTask: unused,
264
+ cancelDelegatedTask: unused,
265
delegatedTaskResultPending: unused,
266
streamStoredEvents: Stream.empty,
267
streamStoredEventsFrom: () => Stream.empty,
docs/orchestration-v2/orchestrator-mcp-server.md
+5
-3
@@ -327,10 +327,12 @@ the published task result.
327
328
### `task_cancel`
329
330
-Stops the child thread with the internal `thread.stop` command, then stops every
331
-task the child delegated, and disposes automatic parent delivery. Like a user Stop,
330
+Stops every task the child delegated, then the child thread with the internal
331
+`thread.stop` command, and disposes automatic parent delivery. Like a user Stop,
332
`thread.stop` interrupts the running turn, holds queued turns, and ends pull request
333
-watches. A nonterminal task with no interruptible run is rejected. A terminal task
333
+watches. A nonterminal task with no interruptible run is rejected unless its finished
334
+turn still waits on background work or delegated tasks. Once a cancelled task's turn ends,
335
+a completed result settles as `interrupted` and a failed one stays `failed`. A terminal task
336
returns its existing status, and its child thread still stops, including later
337
runs and watch wakes. Published task results remain available. It accepts an
338
optional cancellation reason.
packages/contracts/src/orchestrationV2.ts
+2
@@ -913,6 +913,8 @@ export const OrchestrationV2Subagent = Schema.Struct({
913
modelSelection: Schema.optional(ModelSelection),
914
completionWake: Schema.optional(Schema.Literals(["always", "settled_only"])),
915
completionDelivery: Schema.optional(OrchestrationV2DelegatedCompletionTaskDelivery),
916
+ // The run whose unfinished task was cancelled, committed with its Stop.
917
+ cancelledRunId: Schema.optional(RunId),
918
status: Schema.Literals([
919
"idle",
920
"pending",