Compare commits

...

1 Commits

Author SHA1 Message Date
Hussain Hammad
c4b64f628d fix: end a v1 turn at its result for a client in the subagents RFD form (#1603)
Fixes #1527.

A v1 client that declares `clientCapabilities.subagents` and is not AIR
gets the RFD form of subagent sessions, but still got the prompt hold of
#864/#866: `session/prompt` stayed open until the turn's background
subagents ended. The RFD has the client keep receiving child events
after the parent's prompt response, so the reason for the hold doesn't
apply to it.

`endsTurnsWithLiveSubagents` now also returns true for
`subagentForm(...) === "rfd"`. The rest is the existing no-hold path
that AIR's `backgroundSubagents` uses: the turn ends at its result, and
the subagent's updates and requests go out after the response, with the
same routing. A client that declares neither keeps the hold.

What else changes for an RFD client: the parent's summary when a child
ends used to arrive inside the held turn. It now comes from a followup
cycle out of a turn. Its result ends no turn, and a plan approval that
cycle asks for has no clear-context option, as for AIR.

Tests: the no-hold blocks of "deferred settlement for live background
subagents" run for both clients, except the streamed-tool-input test,
whose fixture has no Agent call that the RFD form could expose the child
from. The RFD test of a background child's tool call closing after a
cancel expects `end_turn` at the result and the cancel while no prompt
runs. `docs/subagent-sessions.md` and `docs/air-extensions.md` say which
clients get the hold.

---------

Co-authored-by: Andrey Bragin <andrey.bragin@jetbrains.com>
2026-11-18 15:01:48 +00:00
4 changed files with 105 additions and 80 deletions

View File

@@ -1645,7 +1645,7 @@ Claude Code sends the result of the turn when the main agent stops, also while s
### Hold without the capability
A client that does not declare `backgroundSubagents` gets the hold of issues #864 and #866.
A client that does not declare `backgroundSubagents` gets the hold of issues #864 and #866, unless it gets the RFD form of [subagent sessions](subagent-sessions.md).
The adapter keeps the `session/prompt` request open while a subagent that the turn started or resumed runs.
The subagent output, its permission requests and the followup summary of the model then go out inside the turn.
The turn ends at the followup result, at an `idle` with no live subagent, at `session/cancel`, or when the next prompt starts.

View File

@@ -32,6 +32,11 @@ Task subagent as its own child session, following the [subagents RFD](https://gi
message to the parent instead, in both transcripts and linked the same way.
- A launch whose child is never exposed is shown as a tool call after all, with its final
status.
- On v1, the parent's prompt turn ends at its result, also while a background child that it
launched or resumed still runs. The child's updates and requests follow the prompt response: the
RFD has a client keep receiving child events after it. The parent's summary when the child ends
comes from a followup cycle out of a turn. Its result ends no turn, and a plan approval it asks
for has no clear-context option.
- A SendMessage call that resumes the child is not shown either. Its message is a
`session_message` in both transcripts, the sender's outgoing view and the child's incoming one,
linked like a launch's prompt. A SendMessage call whose message resumes no announced child,

View File

@@ -8990,7 +8990,7 @@ describe("subagent permission attribution (issue #851)", () => {
}
});
it("closes a background child's tool call in its session when the SDK reports the stop after the cancelled response", async () => {
it("closes a background child's tool call in its session when the SDK reports the stop after the prompt response", async () => {
const log: string[] = [];
const updates: AcpSessionNotification[] = [];
const logError = vi.fn();
@@ -9051,9 +9051,9 @@ describe("subagent permission attribution (issue #851)", () => {
...rootToolUse("toolu_child", "Bash", { command: "make" }),
parent_tool_use_id: "toolu_agent",
};
// The turn's result comes while the subagent runs, so v1 holds the turn
// for it. The cancel settles the held turn, which leaves the subagent's
// command open, since the subagent runs.
// The turn's result comes while the subagent runs. The client declares
// `subagents`, so the turn ends at it, and the cancel comes while no
// prompt runs. The subagent's command stays open, since the subagent runs.
yield successResult();
await agent.cancel({ sessionId: "test-session" });
await responded.promise;
@@ -9090,14 +9090,14 @@ describe("subagent permission attribution (issue #851)", () => {
responded.resolve();
return response;
}),
).resolves.toMatchObject({ stopReason: "cancelled" });
).resolves.toMatchObject({ stopReason: "end_turn" });
await agent.sessions["test-session"]?.consumer;
// The command ends in the child's session, after the child reported idle.
// The background launch's own result is not shown in the parent.
expect(log).toEqual([
'agent-42 {"state":"running"}',
"prompt cancelled",
"prompt end_turn",
'agent-42 {"state":"idle","stopReason":"cancelled"}',
"tool @agent-42 toolu_child failed",
]);
@@ -23510,18 +23510,23 @@ describe("deferred settlement for live background subagents (issues #864/#866)",
// subagents are done — at the followup's terminal result, or at an idle
// with none of them left.
//
// The tests without `declareBackgroundSubagents` are the cases of a client
// that does not declare the AIR `backgroundSubagents` capability. Such a
// client keeps the hold.
// The tests without `declareNoHold` are the cases of a client that keeps
// the hold: it neither declares the AIR `backgroundSubagents` capability nor
// gets the RFD form of subagent sessions.
/** Declares the AIR `backgroundSubagents` capability: no turn is held. */
const declareBackgroundSubagents = (agent: ClaudeAcpAgent) =>
agent.initialize({
protocolVersion: 1,
clientCapabilities: {
_meta: { jetbrains: { air: { version: 1, capabilities: ["backgroundSubagents"] } } },
},
});
/** AIR's `backgroundSubagents` capability. */
const AIR_BACKGROUND_SUBAGENTS: ClientCapabilities = {
_meta: { jetbrains: { air: { version: 1, capabilities: ["backgroundSubagents"] } } },
};
/** The clients that get no hold, by what each declares in `initialize`. */
const NO_HOLD_CLIENTS: [string, ClientCapabilities][] = [
["backgroundSubagents", AIR_BACKGROUND_SUBAGENTS],
["the RFD form of subagent sessions", { subagents: {} } as ClientCapabilities],
];
/** Declares a client that gets no hold: no turn of it is held. */
const declareNoHold = (agent: ClaudeAcpAgent, clientCapabilities: ClientCapabilities) =>
agent.initialize({ protocolVersion: 1, clientCapabilities });
function createMockAgent() {
const mockClient = {
@@ -23928,7 +23933,7 @@ describe("deferred settlement for live background subagents (issues #864/#866)",
expect(agent.sessions["test-session"].pendingExitPlanModeInterruption).toBeUndefined();
});
describe("with backgroundSubagents", () => {
describe.each(NO_HOLD_CLIENTS)("with %s", (_client, noHold) => {
it("asks out of the turn without a clear-context option and drops the interrupt", async () => {
let request: RequestPermissionRequest | undefined;
const agent = new ClaudeAcpAgent(
@@ -23968,7 +23973,7 @@ describe("deferred settlement for live background subagents (issues #864/#866)",
}
return messageGenerator();
});
await declareBackgroundSubagents(agent);
await declareNoHold(agent, noHold);
const session = agent.sessions["test-session"]!;
const first = await agent.prompt({
@@ -24039,7 +24044,7 @@ describe("deferred settlement for live background subagents (issues #864/#866)",
}
return messageGenerator();
});
await declareBackgroundSubagents(agent);
await declareNoHold(agent, noHold);
agent.sessions["test-session"]!.settingsManager.getShowClearContextOnPlanAccept = () =>
true;
@@ -24087,7 +24092,7 @@ describe("deferred settlement for live background subagents (issues #864/#866)",
},
},
);
await declareBackgroundSubagents(agent);
await declareNoHold(agent, noHold);
const session = agent.sessions["test-session"]!;
const response = await agent.prompt({
@@ -24155,7 +24160,7 @@ describe("deferred settlement for live background subagents (issues #864/#866)",
}
return messageGenerator();
});
await declareBackgroundSubagents(agent);
await declareNoHold(agent, noHold);
agent.sessions["test-session"]!.settingsManager.getShowClearContextOnPlanAccept = () =>
true;
const session = agent.sessions["test-session"]!;
@@ -24209,7 +24214,7 @@ describe("deferred settlement for live background subagents (issues #864/#866)",
}
return messageGenerator();
});
await declareBackgroundSubagents(agent);
await declareNoHold(agent, noHold);
const session = agent.sessions["test-session"]!;
const first = await agent.prompt({
@@ -24328,7 +24333,7 @@ describe("deferred settlement for live background subagents (issues #864/#866)",
},
},
);
await declareBackgroundSubagents(agent);
await declareNoHold(agent, noHold);
const response = await agent.prompt({
sessionId: "test-session",
@@ -24635,7 +24640,7 @@ describe("deferred settlement for live background subagents (issues #864/#866)",
* agent-1 completes and the model sends its followup. */
function run(
resume: unknown[],
options: { subagents?: boolean; backgroundSubagents?: boolean } = {},
options: { subagents?: boolean; noHold?: ClientCapabilities } = {},
) {
const updates: AcpSessionNotification[] = [];
const requests: RequestPermissionRequest[] = [];
@@ -24686,7 +24691,7 @@ describe("deferred settlement for live background subagents (issues #864/#866)",
clientCapabilities: AIR_NATIVE_SUBAGENTS,
});
}
if (options.backgroundSubagents) await declareBackgroundSubagents(agent);
if (options.noHold) await declareNoHold(agent, options.noHold);
const first = await agent.prompt({
sessionId: "test-session",
prompt: [{ type: "text", text: "explore" }],
@@ -24696,8 +24701,8 @@ describe("deferred settlement for live background subagents (issues #864/#866)",
sessionId: "test-session",
prompt: [{ type: "text", text: "continue" }],
});
// With `backgroundSubagents` the turn is never held.
if (!options.backgroundSubagents) {
// A turn of a client that gets no hold is never held.
if (!options.noHold) {
await waitFor(() => !!agent.sessions["test-session"]?.activeTurn?.deferredSettle);
}
// Wrapped: an async function would unwrap and wait for the held prompt.
@@ -24848,7 +24853,7 @@ describe("deferred settlement for live background subagents (issues #864/#866)",
await agent.sessions["test-session"]?.consumer;
});
describe("with backgroundSubagents", () => {
describe.each(NO_HOLD_CLIENTS)("with %s", (_client, noHold) => {
const summaryChunks = (updates: AcpSessionNotification[]) =>
updates.filter(
(n) =>
@@ -24858,7 +24863,7 @@ describe("deferred settlement for live background subagents (issues #864/#866)",
it("settles the SendMessage turn at its result while the resumed subagent runs", async () => {
const { agent, updates, release, notified, start } = run([sendMessageResult()], {
backgroundSubagents: true,
noHold,
});
const { second } = await start();
const session = agent.sessions["test-session"]!;
@@ -24878,7 +24883,7 @@ describe("deferred settlement for live background subagents (issues #864/#866)",
it("sends a permission request of the resumed subagent after the prompt response", async () => {
const { agent, updates, requests, release, start } = run([sendMessageResult()], {
backgroundSubagents: true,
noHold,
});
const { second } = await start();
await expect(second).resolves.toMatchObject({ stopReason: "end_turn" });
@@ -24904,7 +24909,7 @@ describe("deferred settlement for live background subagents (issues #864/#866)",
});
});
describe("with backgroundSubagents", () => {
describe.each(NO_HOLD_CLIENTS)("with %s", (_client, noHold) => {
/** Agent whose client records the chunk texts as `chunk:<text>`, keeps
* every update, and allows every permission request. */
const recordingAgent = () => {
@@ -24949,7 +24954,7 @@ describe("deferred settlement for live background subagents (issues #864/#866)",
}
return messageGenerator();
});
await declareBackgroundSubagents(agent);
await declareNoHold(agent, noHold);
const session = agent.sessions["test-session"]!;
const response = await agent.prompt({
@@ -24991,7 +24996,12 @@ describe("deferred settlement for live background subagents (issues #864/#866)",
expect(session.owedTrailingIdles).toBe(0);
});
it("keeps the streamed tool input of a running subagent when the turn ends at its result", async () => {
it("keeps the streamed tool input of a running subagent when the turn ends at its result", async ({
skip,
}) => {
// AIR only: this fixture has no Agent call that the RFD form could
// expose the child from, so an RFD client gets none of its updates.
skip(noHold !== AIR_BACKGROUND_SUBAGENTS);
const { agent, updates } = recordingAgent();
let release!: () => void;
const gate = new Promise<void>((resolve) => (release = resolve));
@@ -25031,7 +25041,7 @@ describe("deferred settlement for live background subagents (issues #864/#866)",
}
return messageGenerator();
});
await declareBackgroundSubagents(agent);
await declareNoHold(agent, noHold);
const session = agent.sessions["test-session"]!;
const response = await agent.prompt({
@@ -25093,7 +25103,7 @@ describe("deferred settlement for live background subagents (issues #864/#866)",
}
return messageGenerator();
});
await declareBackgroundSubagents(agent);
await declareNoHold(agent, noHold);
const session = agent.sessions["test-session"]!;
const first = await agent.prompt({

View File

@@ -711,8 +711,9 @@ type Turn = {
* PREVIOUS turn's followup chain while a later turn happens to be held
* is attributed to the holder — extending that hold behind a foreign
* chain. Bounded: the hold still ends at drain, hand-off, or cancel.
* The set is also kept for a client with `backgroundSubagents`, but no
* hold reads it there (see `deferredSettle`). */
* The set is also kept for a client that gets no hold (see
* `endsTurnsWithLiveSubagents`), but no hold reads it there (see
* `deferredSettle`). */
spawnedTaskIds?: Set<string>;
/** Set instead of settling when the turn's terminal result arrives while
* subagents it spawned are still live (`spawnedTaskIds` ∩
@@ -723,8 +724,9 @@ type Turn = {
* issue #866), and the model's task-notification followup summary all
* land inside the turn.
*
* An ACP v1 AIR client that declares `backgroundSubagents` gets no hold:
* this field stays unset, and the turn settles at its result. AIR keeps
* An ACP v1 AIR client that declares `backgroundSubagents`, and an ACP v1
* client in the `rfd` form of subagent sessions, get no hold: this field
* stays unset, and the turn settles at its result. Such a client keeps
* listening after the prompt response, so the subagent updates, their
* permission requests and elicitations, and the followup summary go out
* after it, with the same routing. A held turn hides the end of the
@@ -1237,13 +1239,13 @@ export type Session = {
* `turnAwaitingSubagents` (with `spawnedTaskIds`) to decide whether a
* turn's settlement is deferred (see `Turn.deferredSettle`), so the
* subagents' post-result output and permission requests stay inside the
* turn (issues #864/#866). A client with `backgroundSubagents` gets no
* such hold. Its subagent requests keep this attribution after the
* prompt response. Deliberately false for non-subagent background
* tasks (e.g. a `run_in_background` dev server): those can outlive every
* turn, and the model's contract with them is a wake-on-exit
* notification, not a turn-scoped drain — a hold must NEVER wait on a
* shell.
* turn (issues #864/#866). A client that gets no hold (see
* `endsTurnsWithLiveSubagents`) keeps this attribution for its subagent
* requests after the prompt response. Deliberately false for
* non-subagent background tasks (e.g. a `run_in_background` dev server):
* those can outlive every turn, and the model's contract with them is a
* wake-on-exit notification, not a turn-scoped drain — a hold must NEVER
* wait on a shell.
*
* `endedPerLevel` — a `background_tasks_changed` payload did not include
* this subagent entry. The level's universe is BACKGROUND tasks only, so
@@ -1305,9 +1307,9 @@ export type Session = {
* agent id without a new `task_started` (a running `task_updated` patch or
* a SendMessage `resumedAgentId`). The resume signal puts the subagent back
* into `liveBackgroundTasks` from this record, so the resuming turn holds
* and its permission requests keep their attribution. With
* `backgroundSubagents` the resuming turn does not hold, and the
* attribution stays the same. Bounded by
* and its permission requests keep their attribution. For a client that
* gets no hold (see `endsTurnsWithLiveSubagents`) the resuming turn does
* not hold, and the attribution stays the same. Bounded by
* `MAX_RESUMABLE_SUBAGENTS`, oldest first. */
resumableSubagents?: Map<string, { parentToolUseId?: string }>;
/** The latest `run_id` seen on each task's events, so a late frame of an
@@ -1442,8 +1444,8 @@ type ForegroundOwner = Turn | typeof AUTONOMOUS_CYCLE;
/** Whether this turn's terminal result arrived but its settlement is being
* held for background subagents it spawned (see Turn.deferredSettle). The
* single spelling of the hold predicate, shared by the consumer's settle
* lanes and cancel(). Always false for a client with `backgroundSubagents`,
* because no turn of that client is held. */
* lanes and cancel(). Always false for a client that gets no hold (see
* `endsTurnsWithLiveSubagents`), because no turn of that client is held. */
function isHeldOpen(turn: Turn | null | undefined): turn is Turn & { deferredSettle: TurnOutcome } {
return turn != null && turn.deferredSettle !== undefined && !turn.settled;
}
@@ -1704,14 +1706,16 @@ export class ClaudeAcpAgent {
/**
* Whether a turn ends at its result while background subagents that it
* spawned or resumed still run. Only an AIR client that declares
* `backgroundSubagents` gets this. Every other client keeps the hold of
* spawned or resumed still run. An AIR client that declares
* `backgroundSubagents` gets this, and so does a client in the `rfd` form
* of subagent sessions: the RFD has the client keep receiving child events
* after the parent's prompt response. Every other client keeps the hold of
* `Turn.deferredSettle`.
*/
private endsTurnsWithLiveSubagents(): boolean {
return clientSupportsAirCapability(
this.clientCapabilities,
AIR_BACKGROUND_SUBAGENTS_CAPABILITY,
return (
subagentForm(this.clientCapabilities) === "rfd" ||
clientSupportsAirCapability(this.clientCapabilities, AIR_BACKGROUND_SUBAGENTS_CAPABILITY)
);
}
@@ -3196,10 +3200,11 @@ export class ClaudeAcpAgent {
// settles, since an interrupted subagent stream (keyed by a
// parent_tool_use_id that never recurs) has no boundary event of its own.
const streamedToolInputs: StreamedToolInputCache = new Map();
/** Sweeps `streamedToolInputs` when a turn ends. A turn of a client with
* `backgroundSubagents` can end while its subagents still stream tool
* input, so the sweep keeps the lanes of live subagents, unless the turn
* ends cancelled. Their own message boundaries drop them later. */
/** Sweeps `streamedToolInputs` when a turn ends. A turn of a client that
* gets no hold (see `endsTurnsWithLiveSubagents`) can end while its
* subagents still stream tool input, so the sweep keeps the lanes of
* live subagents, unless the turn ends cancelled. Their own message
* boundaries drop them later. */
const sweepStreamedToolInputs = (turnStopReason?: StopReason) => {
if (turnStopReason === "cancelled" || !this.endsTurnsWithLiveSubagents()) {
streamedToolInputs.clear();
@@ -3839,8 +3844,8 @@ export class ClaudeAcpAgent {
/** Registers a live background task (see `liveBackgroundTasks`). A
* subagent is also recorded on the active turn, so that turn holds until
* the subagent settles (see `Turn.spawnedTaskIds`). A client with
* `backgroundSubagents` gets no hold (see `turnAwaitingSubagents`).
* the subagent settles (see `Turn.spawnedTaskIds`), unless the client
* gets no hold (see `turnAwaitingSubagents`).
* Its requests may already be open, and where it runs decides
* whether they block the foreground work, so that is checked again. */
const registerLiveTask = (
@@ -3874,9 +3879,9 @@ export class ClaudeAcpAgent {
/** Registers a settled subagent again when the SDK resumes it without a
* new `task_started`. The active turn is the one that resumed it, so it
* holds until the subagent settles again, unless the client declared
* `backgroundSubagents`. A repeated resume signal finds the subagent live
* and changes nothing. */
* holds until the subagent settles again, unless the client gets no
* hold (see `endsTurnsWithLiveSubagents`). A repeated resume signal
* finds the subagent live and changes nothing. */
const resumeLiveTask = (taskId: string) => {
if (session.liveBackgroundTasks.has(taskId)) return;
const settled = session.resumableSubagents?.get(taskId);
@@ -3887,10 +3892,11 @@ export class ClaudeAcpAgent {
/** Whether any background subagent this turn spawned is still live —
* while true, the turn's settlement stays deferred so the subagent's
* output and permission requests land inside it (see
* Turn.deferredSettle). Always false for a client that declared
* `backgroundSubagents`: its turns end at their result, and the subagent
* traffic goes out after the prompt response. This is the single gate of
* the hold, so no turn of such a client is ever held open. */
* Turn.deferredSettle). Always false for a client that gets no hold
* (see `endsTurnsWithLiveSubagents`): its turns end at their result, and
* the subagent traffic goes out after the prompt response. This is the
* single gate of the hold, so no turn of such a client is ever held
* open. */
const turnAwaitingSubagents = (turn: Turn) => {
if (this.endsTurnsWithLiveSubagents() || !turn.spawnedTaskIds?.size) {
return false;
@@ -3926,7 +3932,8 @@ export class ClaudeAcpAgent {
* turn that can have spawned subagents must route through here: a site
* calling settleActive directly bypasses the hold and re-opens the
* out-of-turn permission deadlock (issue #866) through its lane. For a
* client with `backgroundSubagents` this always settles now. */
* client that gets no hold (see `endsTurnsWithLiveSubagents`) this
* always settles now. */
const settleOrDefer = async (
outcome: TurnOutcome,
{ steeredWork = true }: { steeredWork?: boolean } = {},
@@ -5960,8 +5967,9 @@ export class ClaudeAcpAgent {
await settleOrDefer({ ...heldTurn.deferredSettle, stopReason: "cancelled" });
break;
}
// The same followup with no held turn: the client declared
// `backgroundSubagents`, or the hold already ended. A user
// The same followup with no held turn: the client gets no
// hold (see `endsTurnsWithLiveSubagents`), or the hold already
// ended. A user
// turn that took the cycle over owns the request (see
// `requestOwnerTurn`), so it continues the accepted plan in a
// fresh context, as the user lane does. With no such turn
@@ -6296,9 +6304,10 @@ export class ClaudeAcpAgent {
// permission requests, and the model's promised summary all land
// inside the turn. `session/cancel` and the next prompt's echo
// hand-off still settle a deferred turn early, so a long-running
// subagent never holds the prompt hostage. A client with
// `backgroundSubagents` gets no hold: the turn settles here, and
// the subagent traffic goes out after the prompt response.
// subagent never holds the prompt hostage. A client that gets
// no hold (see `endsTurnsWithLiveSubagents`) has the turn settle
// here, and the subagent traffic goes out after the prompt
// response.
//
// is_error/auth already settled via failActive (activeTurn is null
// then, so both branches no-op); a cancelled turn settles at
@@ -9127,9 +9136,10 @@ export class ClaudeAcpAgent {
defaultToNo,
availableModes: this.sessionModes.availableModeIds(session.modes),
prePlanMode: session.prePlanMode,
// A fresh context continues the ACP turn that owns the request. With
// `backgroundSubagents` a followup cycle can ask out of a turn, and
// then there is no turn to continue.
// A fresh context continues the ACP turn that owns the request. For
// a client that gets no hold (see `endsTurnsWithLiveSubagents`) a
// followup cycle can ask out of a turn, and then there is no turn to
// continue.
allowContextReset:
!this.endsTurnsWithLiveSubagents() ||
this.requestOwnerTurn(sessionId, session) !== undefined,