Skip to content

Commit cf0ee21

Browse files
committed
fix(server): keep Claude background subagent approvals after root completion
1 parent e58a485 commit cf0ee21

2 files changed

Lines changed: 247 additions & 11 deletions

File tree

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

Lines changed: 205 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5759,6 +5759,211 @@ describe("ClaudeAdapterV2 background wake turns", () => {
57595759
),
57605760
);
57615761

5762+
it.effect.each([
5763+
"accept",
5764+
"decline",
5765+
"full-access",
5766+
"without-agent-id",
5767+
"no-subagent",
5768+
"earlier-run",
5769+
"wrong-agent",
5770+
"aborted",
5771+
"stopping",
5772+
"replaced-process",
5773+
"resumed",
5774+
] as const)("handles a settled subagent permission request: %s", (scenario) =>
5775+
Effect.scoped(
5776+
Effect.gen(function* () {
5777+
const closeStarted = yield* Deferred.make<void>();
5778+
const finishClose = yield* Deferred.make<void>();
5779+
const harness = yield* makeWakeHarnessWithOptions({
5780+
freshQueueOnReopen: true,
5781+
close: (messages) =>
5782+
scenario === "stopping"
5783+
? Deferred.succeed(closeStarted, undefined).pipe(
5784+
Effect.andThen(Deferred.await(finishClose)),
5785+
Effect.andThen(Queue.shutdown(messages)),
5786+
)
5787+
: Queue.shutdown(messages),
5788+
});
5789+
const now = yield* DateTime.now;
5790+
const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
5791+
runtimeMode: scenario === "full-access" ? "full-access" : "approval-required",
5792+
interactionMode: "default",
5793+
cwd: "/workspace",
5794+
});
5795+
const start = (ordinal: number) =>
5796+
harness.runtime.startTurn(
5797+
makeClaudeTestTurnInput({
5798+
threadId: harness.threadId,
5799+
providerThread: harness.providerThread,
5800+
now,
5801+
attemptId: RunAttemptId.make(`attempt-idle-permission-${ordinal}`),
5802+
providerTurnOrdinal: ordinal,
5803+
text: "Start the subagent, then return.",
5804+
attachments: [],
5805+
runtimePolicy,
5806+
}),
5807+
);
5808+
const taskStarted = (toolUseId: string) =>
5809+
claudeSdkFrame({
5810+
type: "system",
5811+
subtype: "task_started",
5812+
task_id: "idle-permission-agent",
5813+
tool_use_id: toolUseId,
5814+
description: "Background permission probe",
5815+
subagent_type: "general-purpose",
5816+
task_type: "local_agent",
5817+
is_backgrounded: true,
5818+
prompt: "Read a file after the parent returns.",
5819+
uuid: `idle-permission-${toolUseId}`,
5820+
session_id: WAKE_NATIVE_SESSION,
5821+
});
5822+
const resultFrame = (ordinal: number) =>
5823+
makeResultFrame({ uuid: `idle-permission-result-${ordinal}`, result: "Started." });
5824+
yield* start(1);
5825+
const callback = harness.getOpenedOptions()!.canUseTool!;
5826+
if (scenario !== "no-subagent") {
5827+
yield* harness.offerAndWait(taskStarted("idle-launch"));
5828+
}
5829+
if (scenario === "resumed") {
5830+
yield* harness.offerAndWait(
5831+
claudeSdkFrame({
5832+
type: "system",
5833+
subtype: "task_notification",
5834+
task_id: "idle-permission-agent",
5835+
tool_use_id: "idle-launch",
5836+
status: "completed",
5837+
output_file: "/tmp/idle-permission-agent.output",
5838+
summary: "First answer.",
5839+
uuid: "idle-permission-completed",
5840+
session_id: WAKE_NATIVE_SESSION,
5841+
}),
5842+
);
5843+
}
5844+
yield* harness.offerAndWait(resultFrame(1));
5845+
yield* Queue.take(harness.terminalReceipts);
5846+
const stop =
5847+
scenario === "stopping" || scenario === "replaced-process"
5848+
? yield* harness.runtime
5849+
.interruptTurn({
5850+
providerThread: harness.providerThread,
5851+
providerTurnId: harness.terminalEvents()[0]!.providerTurnId,
5852+
requestRuntimeRestart: true,
5853+
})
5854+
.pipe(Effect.forkScoped)
5855+
: null;
5856+
if (scenario === "stopping") yield* Deferred.await(closeStarted);
5857+
else if (stop !== null) yield* Fiber.join(stop);
5858+
if (
5859+
scenario === "earlier-run" ||
5860+
scenario === "resumed" ||
5861+
scenario === "replaced-process"
5862+
) {
5863+
yield* start(2);
5864+
if (scenario === "replaced-process") {
5865+
yield* Queue.offer(harness.processQueues[1]!, taskStarted("replacement-launch"));
5866+
yield* Queue.take(harness.subagentReceipts);
5867+
yield* Queue.offer(harness.processQueues[1]!, resultFrame(2));
5868+
} else {
5869+
if (scenario === "resumed") {
5870+
yield* harness.offerAndWait(taskStarted("idle-send-message"));
5871+
}
5872+
yield* harness.offerAndWait(resultFrame(2));
5873+
}
5874+
yield* Queue.take(harness.terminalReceipts);
5875+
}
5876+
const controller = new AbortController();
5877+
if (scenario === "aborted") controller.abort();
5878+
let callbackReturned = false;
5879+
const permission = yield* Effect.promise(async () => {
5880+
const decision = await callback(
5881+
"Read",
5882+
{ file_path: "/etc/hosts" },
5883+
{
5884+
signal: controller.signal,
5885+
toolUseID: "idle-read",
5886+
requestId: "idle-permission-request",
5887+
...(scenario === "without-agent-id"
5888+
? {}
5889+
: {
5890+
agentID: scenario === "wrong-agent" ? "another-agent" : "idle-permission-agent",
5891+
}),
5892+
},
5893+
);
5894+
callbackReturned = true;
5895+
return decision;
5896+
}).pipe(Effect.forkScoped);
5897+
const needsApproval =
5898+
scenario === "accept" ||
5899+
scenario === "decline" ||
5900+
scenario === "resumed" ||
5901+
scenario === "without-agent-id";
5902+
if (needsApproval) {
5903+
yield* awaitUntil(
5904+
() =>
5905+
callbackReturned ||
5906+
harness.events.some((event) => event.type === "runtime_request.updated"),
5907+
"settled subagent approval",
5908+
);
5909+
const request = harness.events.findLast(
5910+
(event) => event.type === "runtime_request.updated",
5911+
);
5912+
assert.equal(request?.type, "runtime_request.updated");
5913+
if (request?.type !== "runtime_request.updated") return;
5914+
assert.equal(
5915+
request.runtimeRequest.providerTurnId,
5916+
harness.terminalEvents().at(-1)!.providerTurnId,
5917+
);
5918+
const node = harness.events.findLast(
5919+
(event) =>
5920+
event.type === "node.updated" && event.node.id === request.runtimeRequest.nodeId,
5921+
);
5922+
assert.equal(
5923+
node?.type === "node.updated" ? node.node.parentNodeId : null,
5924+
node?.type === "node.updated" ? node.node.rootNodeId : undefined,
5925+
);
5926+
yield* harness.runtime.respondToRuntimeRequest({
5927+
requestId: request.runtimeRequest.id,
5928+
decision: scenario === "decline" ? "decline" : "accept",
5929+
});
5930+
}
5931+
const decision = yield* Fiber.join(permission);
5932+
const allowed =
5933+
scenario === "accept" ||
5934+
scenario === "resumed" ||
5935+
scenario === "full-access" ||
5936+
scenario === "without-agent-id";
5937+
assert.equal(decision?.behavior, allowed ? "allow" : "deny");
5938+
if (!needsApproval) {
5939+
assert.isFalse(harness.events.some((event) => event.type === "runtime_request.updated"));
5940+
if (!allowed) {
5941+
assert.equal(
5942+
decision?.behavior === "deny" ? decision.message : null,
5943+
"Claude V2 adapter has no active turn for this tool request.",
5944+
);
5945+
}
5946+
}
5947+
assert.isFalse(
5948+
harness.events.some(
5949+
(event) =>
5950+
event.type === "turn_item.updated" &&
5951+
event.turnItem.type === "dynamic_tool" &&
5952+
event.turnItem.nativeItemRef?.nativeId === "idle-read",
5953+
),
5954+
);
5955+
if (scenario === "stopping" && stop !== null) {
5956+
yield* Deferred.succeed(finishClose, undefined);
5957+
yield* Fiber.join(stop);
5958+
}
5959+
}).pipe(
5960+
Effect.provide(
5961+
Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
5962+
),
5963+
),
5964+
),
5965+
);
5966+
57625967
it.effect("answers an approval a held wake turn raises without waiting for the echo", () =>
57635968
Effect.scoped(
57645969
Effect.gen(function* () {

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

Lines changed: 42 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -5410,6 +5410,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
54105410
readonly requestKind: OrchestrationV2RuntimeRequest["kind"];
54115411
readonly prompt?: string;
54125412
readonly questions?: ReadonlyArray<OrchestrationV2UserInputQuestion>;
5413+
readonly parentNodeId?: OrchestrationV2ExecutionNode["id"] | undefined;
54135414
}) {
54145415
const createdAt = yield* DateTime.now;
54155416
const requestId = yield* idAllocator.allocate.runtimeRequest({
@@ -5438,10 +5439,12 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
54385439
id: nodeId,
54395440
threadId: input.context.input.threadId,
54405441
runId: input.context.input.runId,
5441-
parentNodeId: idAllocator.derive.nodeFromProviderItem({
5442-
driver: CLAUDE_PROVIDER,
5443-
nativeItemId: input.nativeItemId,
5444-
}),
5442+
parentNodeId:
5443+
input.parentNodeId ??
5444+
idAllocator.derive.nodeFromProviderItem({
5445+
driver: CLAUDE_PROVIDER,
5446+
nativeItemId: input.nativeItemId,
5447+
}),
54455448
rootNodeId: input.context.input.rootNodeId,
54465449
kind: input.questions === undefined ? "approval_request" : "user_input_request",
54475450
status: "waiting",
@@ -7681,8 +7684,32 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
76817684
toolName: Parameters<CanUseTool>[0],
76827685
toolInput: Parameters<CanUseTool>[1],
76837686
callbackOptions: Parameters<CanUseTool>[2],
7687+
owningQueryClosed?: Deferred.Deferred<void, never>,
76847688
) {
7685-
const context = yield* Ref.get(activeTurn);
7689+
let context = yield* Ref.get(activeTurn);
7690+
const settled = context === null;
7691+
if (settled && !callbackOptions.signal.aborted) {
7692+
const live = yield* Ref.get(queryContext);
7693+
const previous =
7694+
live === null ? undefined : settledTurnByNativeThread.get(live.nativeThreadId);
7695+
if (
7696+
live !== null &&
7697+
!live.stopping &&
7698+
live.closed === owningQueryClosed &&
7699+
previous !== undefined
7700+
) {
7701+
// Only this run still ingests its subagent's approval after the root result.
7702+
const subagents = yield* Ref.get(sessionSubagentsByTaskId);
7703+
const running = [...subagents].some(
7704+
([taskId, subagent]) =>
7705+
(callbackOptions.agentID === undefined || callbackOptions.agentID === taskId) &&
7706+
subagent.task.status === "running" &&
7707+
subagent.task.runId === previous.input.runId &&
7708+
!live.subagentsFromEarlierProcesses.has(subagent),
7709+
);
7710+
if (running) context = previous;
7711+
}
7712+
}
76867713
if (context === null) {
76877714
return {
76887715
behavior: "deny",
@@ -7694,6 +7721,10 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
76947721
const nativeRequestId = callbackOptions.toolUseID;
76957722
const nativeToolInput = claudeNativeToolInputFromRecord(toolInput);
76967723
const heldForEcho = context.heldRootFrames.length > 0;
7724+
const parentNodeId =
7725+
settled && findToolCall(context, nativeRequestId) === undefined
7726+
? context.input.rootNodeId
7727+
: undefined;
76977728
if (toolName === "Agent") {
76987729
rememberClaudeSubagentLaunch(
76997730
subagentModelCatalog,
@@ -7703,7 +7734,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
77037734
nativeToolInput,
77047735
null,
77057736
);
7706-
} else if (!heldForEcho) {
7737+
} else if (!heldForEcho && (!settled || subagentToolCalls.has(nativeRequestId))) {
77077738
yield* ensureToolCallStarted({
77087739
context,
77097740
nativeItemId: nativeRequestId,
@@ -7743,6 +7774,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
77437774
nativeRequestId,
77447775
requestKind: "user_input",
77457776
questions,
7777+
parentNodeId,
77467778
});
77477779
const answers = yield* Deferred.make<ProviderUserInputAnswers, never>();
77487780
yield* Ref.update(pendingRuntimeRequests, (current) => {
@@ -7841,6 +7873,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
78417873
nativeRequestId,
78427874
requestKind,
78437875
prompt,
7876+
parentNodeId,
78447877
});
78457878
const decision = yield* Deferred.make<ProviderApprovalDecision, never>();
78467879
yield* Ref.update(pendingRuntimeRequests, (current) => {
@@ -7898,9 +7931,6 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
78987931
});
78997932
});
79007933

7901-
const canUseTool: CanUseTool = (toolName, toolInput, callbackOptions) =>
7902-
runPromise(canUseToolEffect(toolName, toolInput, callbackOptions));
7903-
79047934
const onUserDialog: NonNullable<ClaudeQueryOptions["onUserDialog"]> = (
79057935
request,
79067936
callbackOptions,
@@ -8099,6 +8129,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
80998129
turnInput.nativeThreadHasTurns ?? turnInput.providerTurnOrdinal > 1;
81008130
const shouldResume =
81018131
resumeSessionAt !== undefined || openedWithResume || hasPersistedProviderTurn;
8132+
const closed = yield* Deferred.make<void, never>();
81028133
const queryOptions = makeClaudeQueryOptions({
81038134
modelSelection: turnInput.modelSelection,
81048135
nativeThreadId,
@@ -8121,7 +8152,8 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
81218152
: {
81228153
allowDangerouslySkipPermissions: queryPolicy.allowDangerouslySkipPermissions,
81238154
}),
8124-
canUseTool,
8155+
canUseTool: (toolName, toolInput, callbackOptions) =>
8156+
runPromise(canUseToolEffect(toolName, toolInput, callbackOptions, closed)),
81258157
onUserDialog,
81268158
supportedDialogKinds: ["resume_return"],
81278159
});
@@ -8157,7 +8189,6 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
81578189
yield* resetBackgroundTaskStateForNativeThreadProcess(nativeThreadId, {
81588190
status: "active",
81598191
});
8160-
const closed = yield* Deferred.make<void, never>();
81618192
const context: ClaudeLiveQueryContext = {
81628193
nativeThreadId,
81638194
query: querySession,

0 commit comments

Comments
 (0)