Skip to content

Commit 8c777fb

Browse files
authored
feat(server): stop Claude subagents without stopping their owner (pingdotgg#17826)
1 parent 98beed1 commit 8c777fb

15 files changed

Lines changed: 542 additions & 19 deletions

File tree

‎apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts‎

Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2130,6 +2130,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
21302130
const makeWakeHarnessWithOptions = (options?: {
21312131
readonly close?: (sdkMessages: Queue.Queue<SDKMessage>) => Effect.Effect<void>;
21322132
readonly interrupt?: Effect.Effect<void>;
2133+
readonly stopTask?: (taskId: string) => Effect.Effect<void>;
21332134
readonly environment?: NodeJS.ProcessEnv;
21342135
readonly settings?: ClaudeSettings;
21352136
// A CLI process opened after the first streams from its own queue, so the
@@ -2155,6 +2156,10 @@ describe("ClaudeAdapterV2 background wake turns", () => {
21552156
const permissionModeChanges: Array<string> = [];
21562157
const continuationRequests: Array<ProviderContinuationRequests.ProviderContinuationRequest> =
21572158
[];
2159+
const subagentReceipts =
2160+
yield* Queue.unbounded<
2161+
Extract<ProviderAdapter.ProviderAdapterV2Event, { type: "subagent.updated" }>
2162+
>();
21582163
const terminalReceipts =
21592164
yield* Queue.unbounded<
21602165
Extract<ProviderAdapter.ProviderAdapterV2Event, { type: "turn.terminal" }>
@@ -2227,6 +2232,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
22272232
Effect.sync(() => {
22282233
permissionModeChanges.push(mode);
22292234
}),
2235+
...(options?.stopTask === undefined ? {} : { stopTask: options.stopTask }),
22302236
interrupt: options?.interrupt ?? Effect.void,
22312237
close: options?.close?.(sdkMessages) ?? Effect.void,
22322238
};
@@ -2253,6 +2259,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
22532259
Stream.runForEach((event) =>
22542260
Effect.gen(function* () {
22552261
events.push(event);
2262+
if (event.type === "subagent.updated") yield* Queue.offer(subagentReceipts, event);
22562263
if (event.type === "turn.terminal") {
22572264
yield* Queue.offer(terminalReceipts, event);
22582265
}
@@ -2292,6 +2299,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
22922299
continuationRequests,
22932300
events,
22942301
terminalReceipts,
2302+
subagentReceipts,
22952303
systemNoticeReceipts,
22962304
getOpenedOptions: () => openedOptions,
22972305
terminalEvents,
@@ -8076,6 +8084,107 @@ describe("ClaudeAdapterV2 background wake turns", () => {
80768084
),
80778085
);
80788086

8087+
it.effect.each([false, true])(
8088+
"stops one native subagent while its sibling keeps running, owner settled %s",
8089+
(ownerSettled) =>
8090+
Effect.scoped(
8091+
Effect.gen(function* () {
8092+
const stopped: string[] = [];
8093+
let closes = 0;
8094+
const harness = yield* makeWakeHarnessWithOptions({
8095+
stopTask: (taskId) =>
8096+
Effect.sync(() => {
8097+
stopped.push(taskId);
8098+
}),
8099+
interrupt: Effect.die("A child stop must not interrupt its owner"),
8100+
close: () =>
8101+
Effect.sync(() => {
8102+
closes++;
8103+
}),
8104+
});
8105+
yield* harness.runtime.startTurn(
8106+
makeClaudeTestTurnInput({
8107+
threadId: harness.threadId,
8108+
providerThread: harness.providerThread,
8109+
now: yield* DateTime.now,
8110+
attemptId: RunAttemptId.make("attempt-native-child-stop"),
8111+
text: "Start two agents.",
8112+
attachments: [],
8113+
}),
8114+
);
8115+
for (const [taskId, toolUseId, uuid] of [
8116+
["agent-stop", "toolu-stop", "00000000-0000-4000-8000-000000000801"],
8117+
["agent-keep", "toolu-keep", "00000000-0000-4000-8000-000000000802"],
8118+
]) {
8119+
yield* harness.offerAndWait(
8120+
makeSubagentTaskStartedFrame({ taskId: taskId!, toolUseId: toolUseId!, uuid: uuid! }),
8121+
);
8122+
yield* Queue.take(harness.subagentReceipts);
8123+
}
8124+
if (ownerSettled) {
8125+
yield* harness.offerAndWait(
8126+
makeResultFrame({
8127+
uuid: "00000000-0000-4000-8000-000000000803",
8128+
result: "Agents are working.",
8129+
}),
8130+
);
8131+
yield* Queue.take(harness.terminalReceipts);
8132+
}
8133+
const stop = harness.runtime.stopSubagent;
8134+
assert.isDefined(stop);
8135+
yield* stop!({ providerThread: harness.providerThread, nativeTaskId: "agent-stop" });
8136+
assert.deepEqual(stopped, ["agent-stop"]);
8137+
yield* harness.offerAndWait(
8138+
claudeSdkFrame({
8139+
...makeSubagentNotificationFrame({
8140+
taskId: "agent-stop",
8141+
toolUseId: "toolu-stop",
8142+
summary: "Stopped by user",
8143+
uuid: "00000000-0000-4000-8000-000000000804",
8144+
}),
8145+
status: "stopped",
8146+
}),
8147+
);
8148+
if (ownerSettled) {
8149+
yield* harness.runtime.startTurn(
8150+
makeClaudeTestTurnInput({
8151+
threadId: harness.threadId,
8152+
providerThread: harness.providerThread,
8153+
now: yield* DateTime.now,
8154+
attemptId: RunAttemptId.make("attempt-native-child-stop-wake"),
8155+
text: "Background task stopped.",
8156+
attachments: [],
8157+
providerTurnOrdinal: 2,
8158+
messageCreatedBy: "agent",
8159+
messageCreationSource: "provider",
8160+
}),
8161+
);
8162+
}
8163+
const stoppedEvent = yield* Queue.take(harness.subagentReceipts);
8164+
assert.equal(stoppedEvent.subagent.status, "cancelled");
8165+
const tasks = harness.events.filter((event) => event.type === "subagent.updated");
8166+
assert.equal(
8167+
tasks.findLast((event) => event.subagent.nativeTaskRef?.nativeId === "agent-stop")
8168+
?.subagent.status,
8169+
"cancelled",
8170+
);
8171+
assert.equal(
8172+
tasks.findLast((event) => event.subagent.nativeTaskRef?.nativeId === "agent-keep")
8173+
?.subagent.status,
8174+
"running",
8175+
);
8176+
assert.lengthOf(harness.terminalEvents(), ownerSettled ? 1 : 0);
8177+
yield* stop!({ providerThread: harness.providerThread, nativeTaskId: "agent-stop" });
8178+
assert.deepEqual(stopped, ["agent-stop"]);
8179+
assert.equal(closes, 0);
8180+
}).pipe(
8181+
Effect.provide(
8182+
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
8183+
),
8184+
),
8185+
),
8186+
);
8187+
80798188
it.effect.each(["requested", "observed-before", "observed-after", "inherit", "unknown"] as const)(
80808189
"records the subagent model from %s without inheriting the parent override",
80818190
(source) =>

‎apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -342,6 +342,7 @@ export interface ClaudeAgentSdkQuerySession {
342342
readonly setPermissionMode: (
343343
mode: PermissionMode,
344344
) => Effect.Effect<void, ClaudeAgentSdkQueryRunnerError>;
345+
readonly stopTask?: (taskId: string) => Effect.Effect<void, ClaudeAgentSdkQueryRunnerError>;
345346
readonly interrupt: Effect.Effect<void, ClaudeAgentSdkQueryRunnerError>;
346347
readonly close: Effect.Effect<void, ClaudeAgentSdkQueryRunnerError>;
347348
}
@@ -734,6 +735,11 @@ export const layerQueryRunner: Layer.Layer<
734735
}),
735736
),
736737
),
738+
stopTask: (taskId) =>
739+
Effect.tryPromise({
740+
try: () => queryRuntime.stopTask(taskId),
741+
catch: (cause) => queryRunnerError(cause, "stopTask"),
742+
}),
737743
interrupt: Effect.tryPromise({
738744
try: () => queryRuntime.interrupt(),
739745
catch: (cause) => queryRunnerError(cause, "interrupt"),
@@ -8092,6 +8098,34 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
80928098
}),
80938099
steerTurn,
80948100
interruptTurn,
8101+
stopSubagent: Effect.fn("ClaudeAdapterV2.stopSubagent")(function* (input) {
8102+
const existing = yield* Ref.get(queryContext);
8103+
const nativeThreadId = input.providerThread.nativeThreadRef?.nativeId;
8104+
const subagent = (yield* Ref.get(sessionSubagentsByTaskId)).get(input.nativeTaskId);
8105+
if (subagent === undefined || subagent.task.status !== "running") return;
8106+
if (
8107+
existing === null ||
8108+
existing.nativeThreadId !== nativeThreadId ||
8109+
subagent.task.threadId !== input.providerThread.appThreadId ||
8110+
existing.subagentsFromEarlierProcesses.has(subagent) ||
8111+
existing.query.stopTask === undefined
8112+
) {
8113+
return yield* new ProviderAdapter.ProviderAdapterProtocolError({
8114+
driver: CLAUDE_PROVIDER,
8115+
detail: "Claude subagent has no live owning query with task stopping support.",
8116+
});
8117+
}
8118+
yield* existing.query.stopTask(input.nativeTaskId).pipe(
8119+
Effect.mapError(
8120+
(cause) =>
8121+
new ProviderAdapter.ProviderAdapterProtocolError({
8122+
driver: CLAUDE_PROVIDER,
8123+
detail: "Claude native subagent stop failed.",
8124+
cause,
8125+
}),
8126+
),
8127+
);
8128+
}),
80958129
respondToRuntimeRequest: Effect.fn("ClaudeAdapterV2.respondToRuntimeRequest")(
80968130
function* (requestInput) {
80978131
const pending = (yield* Ref.get(pendingRuntimeRequests)).get(

‎apps/server/src/orchestration-v2/EffectOutbox.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import {
33
CheckpointScopeId,
44
CommandId,
55
MessageId,
6+
NodeId,
67
ProviderSessionId,
78
RunAttemptId,
89
ProviderApprovalDecision,
@@ -48,6 +49,7 @@ export const OrchestrationEffectRequestV2 = Schema.Union([
4849
providerSessionId: ProviderSessionId,
4950
providerThreadId: ProviderThreadId,
5051
providerTurnId: ProviderTurnId,
52+
subagent: Schema.optional(Schema.Struct({ id: NodeId, nativeTaskId: Schema.String })),
5153
}),
5254
Schema.Struct({
5355
type: Schema.Literal("provider-turn.steer"),

‎apps/server/src/orchestration-v2/EffectWorker.test.ts‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { assert, it } from "@effect/vitest";
22
import {
33
CommandId,
4+
NodeId,
45
ProviderSessionId,
56
ProviderThreadId,
67
ProviderTurnId,
@@ -837,3 +838,32 @@ it.effect("settles a delegated child once its restart continuation fails for goo
837838
}).pipe(Effect.provide(layer));
838839
}),
839840
);
841+
842+
it.effect("a native subagent stop does not settle its owner's background work", () =>
843+
Effect.gen(function* () {
844+
const now = yield* DateTime.now;
845+
const events = yield* Ref.make<ReadonlyArray<string>>([]);
846+
const layer = layerExecutorFor({
847+
events,
848+
interrupt: (input) => {
849+
assert.equal(input.subagent?.nativeTaskId, "native-task");
850+
return Ref.update(events, (current) => [...current, "stop-child"]);
851+
},
852+
threads: { dispatch: () => Effect.die("The owner's background work must stay running") },
853+
});
854+
yield* Effect.gen(function* () {
855+
const executor = yield* EffectWorker.OrchestrationEffectExecutorV2;
856+
yield* executor.execute({
857+
...restartEffect(now, { type: "detach" }),
858+
request: {
859+
type: "provider-turn.interrupt",
860+
providerSessionId: oldSessionId,
861+
providerThreadId,
862+
providerTurnId,
863+
subagent: { id: NodeId.make("subagent"), nativeTaskId: "native-task" },
864+
},
865+
});
866+
}).pipe(Effect.provide(layer));
867+
assert.deepEqual(yield* Ref.get(events), ["stop-child"]);
868+
}),
869+
);

‎apps/server/src/orchestration-v2/EffectWorker.ts‎

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -169,6 +169,9 @@ export const layerExecutor: Layer.Layer<
169169
providerSessionId: effect.request.providerSessionId,
170170
providerThreadId: effect.request.providerThreadId,
171171
providerTurnId: effect.request.providerTurnId,
172+
...(effect.request.subagent === undefined
173+
? {}
174+
: { subagent: effect.request.subagent }),
172175
})
173176
.pipe(
174177
Effect.catch((cause) =>
@@ -185,13 +188,15 @@ export const layerExecutor: Layer.Layer<
185188
// One Stop can interrupt several provider threads, so the
186189
// settle is keyed by effect, not by the Stop command.
187190
Effect.andThen(
188-
threads.dispatch({
189-
type: "thread.background-work.settle",
190-
commandId: CommandId.make(`${effect.id}:background-work-settled`),
191-
threadId: effect.threadId,
192-
providerThreadId: effect.request.providerThreadId,
193-
providerTurnId: effect.request.providerTurnId,
194-
}),
191+
effect.request.subagent !== undefined
192+
? Effect.void
193+
: threads.dispatch({
194+
type: "thread.background-work.settle",
195+
commandId: CommandId.make(`${effect.id}:background-work-settled`),
196+
threadId: effect.threadId,
197+
providerThreadId: effect.request.providerThreadId,
198+
providerTurnId: effect.request.providerTurnId,
199+
}),
195200
),
196201
Effect.mapError(
197202
(cause) =>

0 commit comments

Comments
 (0)