mirror of
https://github.com/agentclientprotocol/claude-agent-acp.git
synced 2026-11-21 16:51:28 +00:00
fix: announce a live subagent again when its session is loaded or resumed (#1688)
A session that is loaded or resumed while it runs keeps its subagents'
runs. A child that works then, and that the request's replay does not
announce, was not reported as the protocol asks, on v1 or v2. A forked
skill's child is one such child: its metadata names no launch call, so
no replay has it. A subagent launched after the stored history was
written is another.
Found while reviewing the protocol changes since ACP SDK 2.8.0. One
commit per protocol version.
## v2: `session/resume` with replay of the active session
The rules, from the session setup and subagents pages:
- "The Agent **MUST** send `replay_complete` exactly once on each child
session that it announces with `subagent_update` between the request and
the response… An announced child with no replayed history gets one too."
- "The Agent **MUST** send the announcing `subagent_update` before any
request or notification that carries the child's `sessionId`", and "The
announcement rule applies again on every resume".
- "The Agent sends current updates for a child after that child's
marker."
Before, with a forked skill's child running and one of its messages sent
while the history was read:
```
root replay_complete
child agent_message_chunk <- held update, before any announcement in this resume
root subagent_update <- from the state snapshot
child state_update
root state_update
```
The child never got a `replay_complete`, and its held update came before
its announcement.
After:
```
root replay_complete
root subagent_update <- labels and the cancel capability
child replay_complete
child agent_message_chunk
root subagent_update running
child state_update running
root state_update
```
Right after the root's `replay_complete`, in the same synchronous replay
step, each current child that the replay did not announce is announced
again on its parent and gets its own `replay_complete`. What the replay
held follows, then the snapshot. A child counts as current when it
works, when its parent lists it, or when the replay holds something its
session sent, such as the end of a run that ended while the history was
read.
`SessionTasks.unreplayedChildren` builds these updates, and
`ReplayHolds` now records which sessions sent what it holds. A child
whose launch is in the history was already handled and is unchanged.
## v1: `session/load` or `session/resume` of the active session
The rules, from the v1 subagents page:
- "When the Client sends `session/load` or `session/resume` for a
session, it **MUST** discard the state and capabilities it holds for
that session's children."
- "The Client **MUST NOT** send `session/cancel` for a child until the
request succeeds and a current `subagent_update` advertises `cancel`."
- "The Agent **SHOULD** report each child's current state when it can
determine it."
Before, the adapter reported only the children that a load's replay had
announced. A working child of a resumed session, which replays nothing,
got no `subagent_update` after the response. Nor did a working child
whose launch a loaded history does not have. A conforming client could
no longer cancel either one.
After, each working child that no replay announced is announced again on
its parent after the response, with its labels, `cwd`, `capabilities: {
cancel: {} }` and its state, and then gets the configuration that the
client last had for it. A child that no longer works but has a working
child of its own is named first, with its labels only, so parents come
before children.
`NativeSubagentRuntime.currentChildren` builds these, and
`publishCurrentSubagentStates` sends them after the replayed children's
current states. AIR's draft form is unchanged.
## Tests
- v2 (`src/tests/v2/v2.test.ts`): one `it.each` with three cases, a
forked skill's child that reports during the resume, a quiet subagent,
and a subagent whose run ends during the resume.
- v1: a runtime test in `src/tests/native-subagents.test.ts` (a nested
working child under an ended parent, a `requires_action` child with its
own `cwd`, an ended child, a child the replay covers, and the
configuration), an `it.each` over resume and load of the active session
in `src/tests/v1/create-session-options.test.ts`, and a working child
that the replay lacks in the existing load test.
Each new case fails without its source change. `npm run build`, `npm run
check` and `npm run test:run` pass, and so does the whole suite against
the real Claude Code CLI (4,465 passed, 9 skipped).
## Not covered
- v2: a child that is first announced between the root's
`replay_complete` and the response still gets no marker. The window is a
few awaits long.
- v2: an unreplayed live child's configuration is not sent again after
its marker.
- v1 has no hold, so a working child's own updates can still reach the
client between the request and this announcement. The change restores
the child's capabilities, state and configuration after the response,
not that order.
- v1 covers working children only, as the v2 snapshot does.
## Not verified
The tests drive the frames that Claude Code is known to send for a
forked skill, but no live session was resumed while one ran. Two things
only a live run shows: the real timing of a forked skill's frames during
a resume, and whether the stored history of an active session already
has a launch that was just made.
This commit is contained in:
@@ -99,6 +99,13 @@ Task subagent as its own child session, following ACP's [subagents](https://agen
|
||||
neither runs nor has a response gets none.
|
||||
A launch without Claude Code's metadata file for the child stays an ordinary tool call of the
|
||||
parent, and a notice, for a client that takes notices, says that subagent history is missing.
|
||||
- A session that is loaded or resumed with the same settings while it runs keeps its children's
|
||||
runs. After the response, each child that works and that no replay announced is announced
|
||||
again on its parent, with its labels, the `cancel` capability and its state, and then gets the
|
||||
configuration that the client last had for it: every working child after a `session/resume`,
|
||||
which replays nothing, and after a `session/load` a child whose launch the history does not
|
||||
have, such as a forked skill's. A child that no longer works but has a working child of its own
|
||||
is named first, with its labels only.
|
||||
- After a load or resume, with or without replay, a SendMessage that resumes an agent from before
|
||||
it runs that agent in its session from before. Before the agent's traffic, each of its ancestors
|
||||
that the client was not told about in this connection is announced, parent before child and
|
||||
@@ -125,6 +132,12 @@ and comes before the response: on its parent, with the cleared `cwd`, and then a
|
||||
`config_option_update`. The notice that subagent history is missing follows the root's
|
||||
`replay_complete` too.
|
||||
|
||||
On v2, a resume of the active session that replays can meet a child that the stored history does
|
||||
not launch: a forked skill's child, or a subagent that Claude launched after the history was written.
|
||||
Such a child is announced again right after the root's `replay_complete`, when it works, when its
|
||||
parent lists it, or when the replay held one of its updates. Its own `replay_complete` follows at
|
||||
once, since its replay is empty, and then come the updates that the replay held.
|
||||
|
||||
JetBrains AIR keeps the earlier draft of the RFD (`subagent_spawned`, `subagent_state_update`),
|
||||
which it enables with `nativeSubagentSessions` in `_meta.jetbrains.air.capabilities`. See
|
||||
[AIR extensions](air-extensions.md#native-subagent-sessions).
|
||||
|
||||
@@ -403,6 +403,58 @@ export class NativeSubagentRuntime {
|
||||
return JSON.parse(published) as SessionConfigOption[];
|
||||
}
|
||||
|
||||
/**
|
||||
* The RFD form: what is current of the children that work now, for the
|
||||
* time after a `session/load` or `session/resume` of the session that runs
|
||||
* them. The client discarded the state and the capabilities it held for
|
||||
* them, and need not keep their place in the session tree, so each one is
|
||||
* announced again on its parent: with its labels, its `cwd`, the `cancel`
|
||||
* capability and its state, then the configuration that the client last
|
||||
* got for it. `covered` names the children that the load's replay reports
|
||||
* instead (see `RfdSubagentReplay.currentStates`).
|
||||
*
|
||||
* An announced child that no longer works but has one that does, such as a
|
||||
* background child of its own, is announced first, with its labels and
|
||||
* `cwd` only: nothing of it is current, but its child's updates name it.
|
||||
* Parents come before their children.
|
||||
*/
|
||||
currentChildren(covered: (sessionId: string) => boolean): AcpSessionNotification[] {
|
||||
if (this.form !== "rfd") return [];
|
||||
const bySession = new Map<string, NativeSubagent>();
|
||||
for (const child of this.children.values()) {
|
||||
if (child.announced && !covered(child.sessionId)) bySession.set(child.sessionId, child);
|
||||
}
|
||||
const ordered: NativeSubagent[] = [];
|
||||
const add = (child: NativeSubagent) => {
|
||||
if (ordered.includes(child)) return;
|
||||
const parent = bySession.get(child.parentSessionId);
|
||||
if (parent) add(parent);
|
||||
ordered.push(child);
|
||||
};
|
||||
for (const child of bySession.values()) if (isWorking(child)) add(child);
|
||||
return ordered.flatMap((child): AcpSessionNotification[] => {
|
||||
const announcement = rfdAnnouncement(child, child.reportedCwd);
|
||||
if (!isWorking(child)) return [{ sessionId: child.parentSessionId, update: announcement }];
|
||||
const configOptions = this.configurationOf(child.sessionId);
|
||||
const state: WorkState =
|
||||
child.workState === "requires_action" ? { state: "requires_action" } : { state: "running" };
|
||||
return [
|
||||
{
|
||||
sessionId: child.parentSessionId,
|
||||
update: { ...announcement, capabilities: { cancel: {} }, state },
|
||||
},
|
||||
...(configOptions
|
||||
? [
|
||||
{
|
||||
sessionId: child.sessionId,
|
||||
update: { sessionUpdate: "config_option_update" as const, configOptions },
|
||||
},
|
||||
]
|
||||
: []),
|
||||
];
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Takes configuration options of the child `agentId`: an SDK agent id, as a
|
||||
* hook names it, or a child session id. Hook observations can precede the
|
||||
@@ -1951,6 +2003,24 @@ export function responseModelEntry(
|
||||
return models?.entry(model) ?? { value: model, name: models?.name(model) ?? model };
|
||||
}
|
||||
|
||||
/**
|
||||
* The RFD form: the `subagent_update` that names `child` on its parent, with
|
||||
* the parent's labels for it and `cwd`, its working directory when that is
|
||||
* not its parent's.
|
||||
*/
|
||||
function rfdAnnouncement(
|
||||
child: NativeSubagent,
|
||||
cwd: string | null | undefined,
|
||||
): Extract<AcpSessionNotification["update"], { sessionUpdate: "subagent_update" }> {
|
||||
return {
|
||||
sessionUpdate: "subagent_update",
|
||||
sessionId: child.sessionId,
|
||||
...(child.title ? { title: child.title } : {}),
|
||||
...(child.description ? { description: child.description } : {}),
|
||||
...(cwd ? { cwd } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Announces the child on its parent, once, before any update of the child.
|
||||
* The RFD form announces it as running and then sends the prompt as the
|
||||
@@ -1973,11 +2043,7 @@ export async function announceNativeSubagent(
|
||||
await publish({
|
||||
sessionId: child.parentSessionId,
|
||||
update: {
|
||||
sessionUpdate: "subagent_update",
|
||||
sessionId: child.sessionId,
|
||||
...(child.title ? { title: child.title } : {}),
|
||||
...(child.description ? { description: child.description } : {}),
|
||||
...(cwd ? { cwd } : {}),
|
||||
...rfdAnnouncement(child, cwd),
|
||||
capabilities: { cancel: {} },
|
||||
state: { state: "running" },
|
||||
},
|
||||
|
||||
@@ -438,6 +438,11 @@ export class RfdSubagentReplay {
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether the replay announced the child session `sessionId`. */
|
||||
announced(sessionId: string): boolean {
|
||||
return this.transcript.byAgentId.get(sessionId)?.announced === true;
|
||||
}
|
||||
|
||||
/**
|
||||
* The current state and configuration of each announced child, to send
|
||||
* after the load response. The RFD makes that response the freshness
|
||||
|
||||
@@ -900,6 +900,78 @@ describe("NativeSubagentRuntime in the RFD form", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("gives what is current of the children that work, each after its parent", async () => {
|
||||
const published: AcpSessionNotification[] = [];
|
||||
const runtime = new NativeSubagentRuntime(
|
||||
"rfd",
|
||||
"root",
|
||||
{ cwd: "/project" },
|
||||
async (notification) => {
|
||||
published.push(notification);
|
||||
},
|
||||
{ log: () => {} },
|
||||
);
|
||||
const deliver = async (notification: AcpSessionNotification) => {
|
||||
const routed = await runtime.route(notification, deliver);
|
||||
if (routed) published.push(routed);
|
||||
};
|
||||
const start = async (taskId: string, parentLaunch?: string) => {
|
||||
await deliver(launch(`launch-${taskId}`, { description: `Run ${taskId}` }, parentLaunch));
|
||||
await runtime.taskStarted(
|
||||
{ taskId, toolUseId: `launch-${taskId}`, subagentType: "Explore" },
|
||||
deliver,
|
||||
);
|
||||
};
|
||||
await start("outer");
|
||||
await start("inner", "launch-outer");
|
||||
const worktree = "/project/.claude/worktrees/asking";
|
||||
await runtime.reportCwd("asking", worktree);
|
||||
await start("asking");
|
||||
await start("ended");
|
||||
await start("replayed");
|
||||
// `outer` ends while its child works on, as the parent of a background child does.
|
||||
await runtime.finishTask("outer", "completed", deliver, "launch-outer");
|
||||
await runtime.finishTask("ended", "completed", deliver, "launch-ended");
|
||||
await runtime.reportModel("launch-inner", "child-model", deliver);
|
||||
const answer = Promise.withResolvers<string>();
|
||||
const request = runtime.awaitingUser("asking", () => answer.promise);
|
||||
await vi.waitFor(() => expect(runtime.liveWorkState("asking")).toBe("requires_action"));
|
||||
|
||||
const labels = (sessionId: string) => ({
|
||||
sessionUpdate: "subagent_update",
|
||||
sessionId,
|
||||
title: `Run ${sessionId}`,
|
||||
description: "Explore",
|
||||
});
|
||||
// `ended` does not work, and `replayed` is one that a load's replay reports.
|
||||
expect(runtime.currentChildren((sessionId) => sessionId === "replayed")).toEqual([
|
||||
// Nothing of `outer` is current: it is named for its child.
|
||||
{ sessionId: "root", update: labels("outer") },
|
||||
{
|
||||
sessionId: "outer",
|
||||
update: { ...labels("inner"), capabilities: { cancel: {} }, state: { state: "running" } },
|
||||
},
|
||||
{
|
||||
sessionId: "inner",
|
||||
update: {
|
||||
sessionUpdate: "config_option_update",
|
||||
configOptions: [expect.objectContaining({ id: "model", currentValue: "child-model" })],
|
||||
},
|
||||
},
|
||||
{
|
||||
sessionId: "root",
|
||||
update: {
|
||||
...labels("asking"),
|
||||
cwd: worktree,
|
||||
capabilities: { cancel: {} },
|
||||
state: { state: "requires_action" },
|
||||
},
|
||||
},
|
||||
]);
|
||||
answer.resolve("allow");
|
||||
await request;
|
||||
});
|
||||
|
||||
it("buffers model observations until the child is announced", async () => {
|
||||
const published: AcpSessionNotification[] = [];
|
||||
const runtime = new NativeSubagentRuntime(
|
||||
|
||||
@@ -4106,6 +4106,8 @@ describe("subagent transcript replay", () => {
|
||||
live: (childSessionId: string) => string | undefined;
|
||||
/** The configuration that the client last got for a child that still runs. */
|
||||
configuration?: (childSessionId: string) => SessionConfigOption[] | undefined;
|
||||
/** The children that work in the live session, of which the replay can lack some. */
|
||||
working?: string[];
|
||||
/** The session's config options and model list, known after the response. */
|
||||
models?: { configOptions: SessionConfigOption[]; modelInfos: ModelInfo[] };
|
||||
},
|
||||
@@ -4180,6 +4182,18 @@ describe("subagent transcript replay", () => {
|
||||
nativeSubagentRuntime: {
|
||||
liveWorkState: afterResponse.live,
|
||||
configurationOf: afterResponse.configuration,
|
||||
currentChildren: (covered: (childSessionId: string) => boolean) =>
|
||||
(afterResponse.working ?? [])
|
||||
.filter((child) => !covered(child))
|
||||
.map((child) => ({
|
||||
sessionId,
|
||||
update: {
|
||||
sessionUpdate: "subagent_update",
|
||||
sessionId: child,
|
||||
capabilities: { cancel: {} },
|
||||
state: { state: "running" },
|
||||
},
|
||||
})),
|
||||
},
|
||||
configOptions: afterResponse.models?.configOptions ?? [],
|
||||
modelInfos: afterResponse.models?.modelInfos ?? [],
|
||||
@@ -4505,8 +4519,12 @@ describe("subagent transcript replay", () => {
|
||||
],
|
||||
{ aaa111: child("live", "toolu_live"), bbb222: child("gone", "toolu_gone") },
|
||||
undefined,
|
||||
// The session is loaded again in the process that still runs `aaa111`.
|
||||
{ live: (childSessionId) => (childSessionId === "aaa111" ? "running" : undefined) },
|
||||
// The session is loaded again in the process that still runs `aaa111`,
|
||||
// and `ccc333`, whose launch the history does not have.
|
||||
{
|
||||
live: (childSessionId) => (childSessionId === "aaa111" ? "running" : undefined),
|
||||
working: ["aaa111", "ccc333"],
|
||||
},
|
||||
);
|
||||
|
||||
expect(trace.slice(trace.indexOf("-- response --"))).toEqual([
|
||||
@@ -4516,6 +4534,9 @@ describe("subagent transcript replay", () => {
|
||||
// Any other child's process is gone: its replayed end is its current
|
||||
// state, and nothing can cancel it.
|
||||
'root subagent_update bbb222 {"state":"idle","stopReason":"end_turn"}',
|
||||
// The live session reports the child that the replay did not announce,
|
||||
// and not `aaa111` a second time.
|
||||
'root subagent_update ccc333 {"state":"running"} capabilities={"cancel":{}}',
|
||||
]);
|
||||
});
|
||||
|
||||
|
||||
@@ -396,6 +396,60 @@ describe("createSession options merging", () => {
|
||||
expect(announcements[1]).not.toHaveProperty("cwd");
|
||||
});
|
||||
|
||||
it.each(["session/resume", "session/load"] as const)(
|
||||
"announces a child that still works again after the response of a %s of the active session",
|
||||
async (request) => {
|
||||
const updates: AcpSessionNotification[] = [];
|
||||
const client = createMockClient();
|
||||
client.sessionUpdate = async (notification) => {
|
||||
updates.push(notification);
|
||||
};
|
||||
const observedAgent = new ClaudeAcpAgent(client);
|
||||
await observedAgent.initialize({ protocolVersion: 1, clientCapabilities: { subagents: {} } });
|
||||
const params = { cwd: process.cwd(), mcpServers: [] };
|
||||
const { sessionId } = await observedAgent.newSession(params);
|
||||
// The new session's own work after its response is done.
|
||||
await new Promise((resolve) => setTimeout(resolve, 20));
|
||||
const session = observedAgent.sessions[sessionId]!;
|
||||
const runtime = (session.nativeSubagentRuntime = new NativeSubagentRuntime(
|
||||
"rfd",
|
||||
sessionId,
|
||||
session,
|
||||
(notification) => client.sessionUpdate(notification),
|
||||
{ log: () => {} },
|
||||
));
|
||||
await runtime.taskStarted(
|
||||
{ taskId: "working", subagentType: "Explore", description: "Map the code" },
|
||||
async () => {},
|
||||
);
|
||||
await runtime.taskStarted({ taskId: "ended", subagentType: "Explore" }, async () => {});
|
||||
await runtime.finishTask("ended", "completed", async () => {});
|
||||
updates.length = 0;
|
||||
|
||||
// The same settings: the session's query, and the child's run, go on. The
|
||||
// stored history launches no subagent, so a load's replay announces none.
|
||||
if (request === "session/load") await observedAgent.loadSession({ sessionId, ...params });
|
||||
else await observedAgent.resumeSession({ sessionId, ...params });
|
||||
expect(observedAgent.sessions[sessionId]).toBe(session);
|
||||
|
||||
await vi.waitFor(() =>
|
||||
expect(updates.filter(({ update }) => update.sessionUpdate === "subagent_update")).toEqual([
|
||||
{
|
||||
sessionId,
|
||||
update: {
|
||||
sessionUpdate: "subagent_update",
|
||||
sessionId: "working",
|
||||
title: "Map the code",
|
||||
description: "Explore",
|
||||
capabilities: { cancel: {} },
|
||||
state: { state: "running" },
|
||||
},
|
||||
},
|
||||
]),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it("reports an AIR child's model switch under its current generation", async () => {
|
||||
const updates: AcpSessionNotification[] = [];
|
||||
const client = createMockClient();
|
||||
|
||||
@@ -4823,6 +4823,105 @@ describe("ACP v2 core", () => {
|
||||
expect(received.indexOf("live report")).toBeGreaterThan(received.indexOf("replay_complete"));
|
||||
});
|
||||
|
||||
describe("a live child that the replayed history does not launch", () => {
|
||||
type LiveChild = ReturnType<typeof subagent> | ReturnType<typeof forkedSkill>;
|
||||
/** A subagent that Claude launched after the stored history was written. */
|
||||
const launched = (claude: FakeClaudeCode): LiveChild => {
|
||||
const child = subagent("a5966d", "toolu_agent");
|
||||
claude.send(cycleStart());
|
||||
claude.send(child.launch());
|
||||
claude.send(child.started());
|
||||
return child;
|
||||
};
|
||||
// What the resume's snapshot sends of a child that works: its state, on its parent and its own stream.
|
||||
const works = ["root subagent_update running", "child state_update running"];
|
||||
|
||||
it.each<{
|
||||
name: string;
|
||||
start: (claude: FakeClaudeCode) => LiveChild;
|
||||
/** What Claude Code sends of the child while the transcript is read. */
|
||||
during: (child: LiveChild) => Record<string, unknown>[];
|
||||
/** What the client gets after the child's `replay_complete`, before the root's state. */
|
||||
current: string[];
|
||||
}>([
|
||||
{
|
||||
// Claude Code's metadata of a forked skill's agent names no call, so no replay has it.
|
||||
name: "a forked skill's child that reports meanwhile",
|
||||
start: (claude) => {
|
||||
const fork = forkedSkill("a5966d");
|
||||
claude.send(fork.started());
|
||||
return fork;
|
||||
},
|
||||
during: (child) => [child.says("Live report")],
|
||||
current: ["child agent_message_chunk", ...works],
|
||||
},
|
||||
{
|
||||
name: "a subagent that sends nothing meanwhile",
|
||||
start: launched,
|
||||
during: () => [],
|
||||
current: works,
|
||||
},
|
||||
{
|
||||
name: "a subagent whose run ends meanwhile",
|
||||
start: launched,
|
||||
during: (child) => [child.ended()],
|
||||
// The end that the replay held. The snapshot has nothing of a child that no longer works.
|
||||
current: ["root subagent_update idle", "child state_update idle"],
|
||||
},
|
||||
])(
|
||||
"is announced again after the root's replay_complete and gets its own, before its other updates: $name",
|
||||
async ({ start, during, current }) => {
|
||||
const client = v2Client();
|
||||
const read = Promise.withResolvers<Awaited<ReturnType<typeof getSessionMessages>>>();
|
||||
let resumedAt = 0;
|
||||
const sessionId = await client.connect(async (agent) => {
|
||||
const { response, claude } = await openSession(agent);
|
||||
const child = start(claude);
|
||||
await vi.waitFor(() =>
|
||||
expect(updatesOf(client.notifications, "a5966d")).toContainEqual(
|
||||
expect.objectContaining({ sessionUpdate: "state_update", state: "running" }),
|
||||
),
|
||||
);
|
||||
vi.mocked(getSessionMessages).mockReturnValueOnce(read.promise);
|
||||
resumedAt = client.notifications.length;
|
||||
const resume = agent.request(v2.methods.agent.session.resume, {
|
||||
sessionId: response.sessionId,
|
||||
cwd,
|
||||
replayFrom: { type: "start" },
|
||||
});
|
||||
await vi.waitFor(() => expect(getSessionMessages).toHaveBeenCalled());
|
||||
for (const message of during(child)) claude.send(message);
|
||||
await new Promise((resolve) => setTimeout(resolve, 20));
|
||||
// The replay holds what the child sends.
|
||||
expect(client.notifications.slice(resumedAt)).toEqual([]);
|
||||
read.resolve([]);
|
||||
await resume;
|
||||
return response.sessionId;
|
||||
});
|
||||
|
||||
const received = client.notifications
|
||||
.slice(resumedAt)
|
||||
.map(({ sessionId: of, update }) => {
|
||||
const state = (update as { state?: unknown }).state;
|
||||
const name =
|
||||
typeof state === "object" ? (state as { state?: unknown } | null)?.state : state;
|
||||
return `${of === sessionId ? "root" : "child"} ${update.sessionUpdate}${
|
||||
typeof name === "string" ? ` ${name}` : ""
|
||||
}`;
|
||||
});
|
||||
expect(received).toEqual([
|
||||
"root replay_complete",
|
||||
// Current, as it follows its parent's `replay_complete`: the child's labels, with no state.
|
||||
"root subagent_update",
|
||||
// The child's replay is empty.
|
||||
"child replay_complete",
|
||||
...current,
|
||||
expect.stringMatching(/^root state_update /),
|
||||
]);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["session/prompt", v2.methods.agent.session.prompt, { prompt: PROMPT }, false],
|
||||
["session/close", v2.methods.agent.session.close, {}, false],
|
||||
|
||||
@@ -9496,22 +9496,30 @@ export class ClaudeAcpAgent {
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends the current state and configuration of each subagent that the last
|
||||
* load of `sessionId` replayed (see {@link RfdSubagentReplay.currentStates}).
|
||||
* Run it only after the load response: before it, the client treats a
|
||||
* subagent's state and configuration as history.
|
||||
* Sends what is current of the subagents of `sessionId` after a session
|
||||
* setup response: the state and configuration of each one that the last
|
||||
* load replayed (see {@link RfdSubagentReplay.currentStates}), then each
|
||||
* one that works in the session and that no replay announced, with its
|
||||
* announcement again (see `NativeSubagentRuntime.currentChildren`). The
|
||||
* second kind is a child of a session that was resumed, which replays
|
||||
* nothing, or one whose launch the loaded history does not have, such as a
|
||||
* forked skill's. Run it only after the response: before a load's response,
|
||||
* the client treats a subagent's state and configuration as history.
|
||||
*/
|
||||
async publishCurrentSubagentStates(sessionId: string): Promise<void> {
|
||||
await this.publishReplayedChildModels(sessionId);
|
||||
const replay = this.replayedSubagents.get(sessionId);
|
||||
if (!replay) return;
|
||||
this.replayedSubagents.delete(sessionId);
|
||||
const runtime = this.sessions[sessionId]?.nativeSubagentRuntime;
|
||||
try {
|
||||
for (const notification of replay.currentStates(
|
||||
(child) => runtime?.liveWorkState(child),
|
||||
(child) => runtime?.configurationOf?.(child),
|
||||
)) {
|
||||
const current = [
|
||||
...(replay?.currentStates(
|
||||
(child) => runtime?.liveWorkState(child),
|
||||
(child) => runtime?.configurationOf?.(child),
|
||||
) ?? []),
|
||||
...(runtime?.currentChildren((child) => replay?.announced(child) === true) ?? []),
|
||||
];
|
||||
for (const notification of current) {
|
||||
await this.client.sessionUpdate(asSdkSessionNotification(notification));
|
||||
}
|
||||
} catch (error) {
|
||||
|
||||
@@ -259,7 +259,7 @@ class V2Agent implements AgentHandle, SessionConnection {
|
||||
};
|
||||
const held = this.heldBy(notification.sessionId);
|
||||
if (held === undefined) send();
|
||||
else this.replays.defer(held, send);
|
||||
else this.replays.defer(held, send, notification.sessionId);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -285,12 +285,16 @@ class V2Agent implements AgentHandle, SessionConnection {
|
||||
send: () => Promise<T>,
|
||||
): Promise<T> {
|
||||
const held = sessionId === undefined ? undefined : this.heldBy(sessionId);
|
||||
if (held === undefined) return send();
|
||||
if (sessionId === undefined || held === undefined) return send();
|
||||
return new Promise((resolve, reject) =>
|
||||
this.replays.defer(held, () => {
|
||||
if (signal.aborted) reject(new Error("The request was withdrawn"));
|
||||
else send().then(resolve, reject);
|
||||
}),
|
||||
this.replays.defer(
|
||||
held,
|
||||
() => {
|
||||
if (signal.aborted) reject(new Error("The request was withdrawn"));
|
||||
else send().then(resolve, reject);
|
||||
},
|
||||
sessionId,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -581,7 +585,10 @@ class V2Agent implements AgentHandle, SessionConnection {
|
||||
* subagents (`subagents`), and ends the replay: each replayed child's
|
||||
* `replay_complete` (see `SubagentReplay.finish`), then the session's. An
|
||||
* AIR client that declared `loadReplayEnd` gets AIR's own mark after it.
|
||||
* All in one synchronous step, as `ReplayHolds.replay` requires.
|
||||
* Then each live child that the history did not have is announced again and
|
||||
* gets its `replay_complete` (see `SessionTasks.unreplayedChildren`), ahead
|
||||
* of what the replay held of it. All in one synchronous step, as
|
||||
* `ReplayHolds.replay` requires.
|
||||
*/
|
||||
private replay(
|
||||
session: V2Session,
|
||||
@@ -600,6 +607,11 @@ class V2Agent implements AgentHandle, SessionConnection {
|
||||
this.send({ sessionId, update: REPLAY_COMPLETE });
|
||||
const end = replayEndUpdate(this.clientCapabilities);
|
||||
if (end) this.send({ sessionId, update: end });
|
||||
const unreplayed = session.tasks.unreplayedChildren(
|
||||
(child) => subagents?.announced(child) === true,
|
||||
this.replays.senders(sessionId),
|
||||
);
|
||||
for (const notification of unreplayed) this.send(notification);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -7,12 +7,20 @@
|
||||
* permission request or an elicitation.
|
||||
*
|
||||
* The replay itself runs in one synchronous step ({@link ReplayHolds.replay}),
|
||||
* so what a session sends during that step is its replayed history. Nothing
|
||||
* else tells the two apart.
|
||||
* so what a session sends during that step is not held: its replayed history
|
||||
* and the `replay_complete` updates that end it. Nothing else tells that from
|
||||
* what waits.
|
||||
*/
|
||||
export class ReplayHolds {
|
||||
/** What each session with a replay in flight holds, in send order, with the count of its replays. */
|
||||
private readonly sessions = new Map<string, { resumes: number; sends: Array<() => void> }>();
|
||||
/**
|
||||
* What each session with a replay in flight holds, in send order, with the
|
||||
* count of its replays and the sessions that sent what it holds: itself and
|
||||
* its subagent sessions.
|
||||
*/
|
||||
private readonly sessions = new Map<
|
||||
string,
|
||||
{ resumes: number; sends: Array<() => void>; senders: Set<string> }
|
||||
>();
|
||||
/** Whether {@link replay} runs. */
|
||||
private replaying = false;
|
||||
|
||||
@@ -34,7 +42,7 @@ export class ReplayHolds {
|
||||
* Calling it again does nothing.
|
||||
*/
|
||||
begin(sessionId: string): () => void {
|
||||
const hold = this.sessions.get(sessionId) ?? { resumes: 0, sends: [] };
|
||||
const hold = this.sessions.get(sessionId) ?? { resumes: 0, sends: [], senders: new Set() };
|
||||
hold.resumes++;
|
||||
this.sessions.set(sessionId, hold);
|
||||
let released = false;
|
||||
@@ -47,9 +55,19 @@ export class ReplayHolds {
|
||||
};
|
||||
}
|
||||
|
||||
/** Runs `send` once the session `sessionId` no longer holds its sends (see {@link holds}). */
|
||||
defer(sessionId: string, send: () => void): void {
|
||||
this.sessions.get(sessionId)!.sends.push(send);
|
||||
/**
|
||||
* Runs `send`, an update or a request of the session `sender`, once the
|
||||
* session `sessionId` no longer holds its sends (see {@link holds}).
|
||||
*/
|
||||
defer(sessionId: string, send: () => void, sender: string): void {
|
||||
const hold = this.sessions.get(sessionId)!;
|
||||
hold.sends.push(send);
|
||||
hold.senders.add(sender);
|
||||
}
|
||||
|
||||
/** The sessions whose updates or requests the session `sessionId` holds now. */
|
||||
senders(sessionId: string): ReadonlySet<string> {
|
||||
return this.sessions.get(sessionId)?.senders ?? new Set();
|
||||
}
|
||||
|
||||
/** Runs `replay`, which must send the history and its `replay_complete` before it returns. */
|
||||
|
||||
@@ -151,6 +151,11 @@ export class SubagentReplay {
|
||||
return this.ownerHooks(output, undefined);
|
||||
}
|
||||
|
||||
/** Whether the replay announced the child session `sessionId`. */
|
||||
announced(sessionId: string): boolean {
|
||||
return this.transcript.byAgentId.get(sessionId)?.announced === true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ends the replay of the children. Every child's end goes out on its
|
||||
* parent, whose history it is. Then each announced child gets its
|
||||
|
||||
@@ -108,6 +108,7 @@ import type { V2UpdateTranslator } from "./update-translator.js";
|
||||
import { type WorkflowCardProgress, workflowCard, workflowSnapshot } from "../workflow-progress.js";
|
||||
import { ChildConfigurations } from "./child-config.js";
|
||||
import { SessionOutput } from "./stream.js";
|
||||
import { REPLAY_COMPLETE } from "./setup.js";
|
||||
import { SubagentReplay } from "./subagent-replay.js";
|
||||
|
||||
/** What the tasks need of their root session. */
|
||||
@@ -812,6 +813,50 @@ export class SessionTasks {
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* For a resume of the active session that replays: the announcement and
|
||||
* the `replay_complete` of each current child that the replay did not
|
||||
* announce (`replayed`), parents first. The stored history has no launch of
|
||||
* such a child: a forked skill's, whose metadata names no call, or a
|
||||
* subagent that Claude launched after the history was written. Its replay
|
||||
* is empty, so its `replay_complete` follows its announcement at once.
|
||||
*
|
||||
* A child is current when it works, when its parent lists it, or when the
|
||||
* replay holds something its session sent (`held`), such as the end of a
|
||||
* run that ended while the history was read. v2 asks for a child's
|
||||
* announcement again on every resume, before any other update of its
|
||||
* session, and for a `replay_complete` on every child that is announced
|
||||
* before the response. The caller sends these after the root's
|
||||
* `replay_complete`, where an announcement is current, and before what the
|
||||
* replay held.
|
||||
*/
|
||||
unreplayedChildren(
|
||||
replayed: (sessionId: string) => boolean,
|
||||
held: ReadonlySet<string>,
|
||||
): v2.UpdateSessionNotification[] {
|
||||
const lists = this.lists();
|
||||
return this.parentsFirst()
|
||||
.filter(
|
||||
(child) =>
|
||||
!replayed(child.sessionId) &&
|
||||
(held.has(child.sessionId) || this.worksOrListed(child, lists)),
|
||||
)
|
||||
.flatMap((child) => [
|
||||
{ sessionId: child.parentSessionId, update: this.announcement(child) },
|
||||
{ sessionId: child.sessionId, update: REPLAY_COMPLETE },
|
||||
]);
|
||||
}
|
||||
|
||||
/** Whether `child` works, or its parent's `background` list (of `lists`) names it. */
|
||||
private worksOrListed(child: Child, lists: Map<string, BackgroundItem[]>): boolean {
|
||||
return (
|
||||
child.working ||
|
||||
(lists.get(child.parentSessionId) ?? []).some(
|
||||
(item) => item.type === "subagent" && item.sessionId === child.sessionId,
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The current state of the session's work, for a resume of the active
|
||||
* session: each subagent that a session lists, or that works in its
|
||||
@@ -827,10 +872,7 @@ export class SessionTasks {
|
||||
const visit = (sessionId: string) => {
|
||||
const listed = lists.get(sessionId) ?? [];
|
||||
const children = this.parentsFirst().filter(
|
||||
(child) =>
|
||||
child.parentSessionId === sessionId &&
|
||||
(child.working ||
|
||||
listed.some((item) => item.type === "subagent" && item.sessionId === child.sessionId)),
|
||||
(child) => child.parentSessionId === sessionId && this.worksOrListed(child, lists),
|
||||
);
|
||||
for (const child of children) {
|
||||
const state = stateObject(this.childState(child), undefined);
|
||||
|
||||
Reference in New Issue
Block a user