mirror of
https://github.com/agentclientprotocol/claude-agent-acp.git
synced 2026-12-04 23:22:01 +00:00
Compare commits
2 Commits
main
...
fix/backgr
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a9db323d38 | ||
|
|
a42e68cc22 |
@@ -1,5 +1,6 @@
|
||||
/**
|
||||
* The replay of subagents to a client on the subagents RFD form.
|
||||
* The replay of subagents to a client on the subagents RFD form, and the ends
|
||||
* of the children of the v1 AIR form (`NativeReplayEnds`).
|
||||
*
|
||||
* Claude Code keeps each subagent's history in its own transcript, and the
|
||||
* subagent's metadata file names the Agent or Task call that launched it (see
|
||||
@@ -59,6 +60,7 @@ import {
|
||||
} from "./native-subagents.js";
|
||||
import { noticeUpdate } from "./session-notices.js";
|
||||
import type { SubagentHistory, SubagentRecord } from "./subagent-history.js";
|
||||
import type { PersistedTaskNotification } from "./task-notifications.js";
|
||||
|
||||
type Publish = (notification: AcpSessionNotification) => Promise<void>;
|
||||
|
||||
@@ -179,7 +181,7 @@ export class ReplayTranscript<Child extends ReplayChild = ReplayChild> {
|
||||
if (handback) handback.status = block.is_error === true ? "failed" : "completed";
|
||||
const child = this.children.get(block.tool_use_id);
|
||||
// A background launch answers at once; its result is not the end.
|
||||
if (child && !child.record.background) {
|
||||
if (child && !isBackgroundLaunch(child.record, child.input, block)) {
|
||||
child.launchEnd = replaySubagentTerminalState(block);
|
||||
}
|
||||
}
|
||||
@@ -637,6 +639,207 @@ export function replaySubagentTerminalState(
|
||||
: "failed";
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a launch ran its child in the background. Claude Code answers such
|
||||
* a launch at once, so its tool result `result` is not the end of the child.
|
||||
* The task notification of the child tells the end.
|
||||
*
|
||||
* Each sign only adds evidence: the subagent `record`, the
|
||||
* `run_in_background` flag of the launch `input`, and the text of the result,
|
||||
* "Async agent launched". A metadata file of an older CLI has no request
|
||||
* shape, and Claude Code can move a foreground child to the background, so a
|
||||
* record that says foreground does not hide the other two.
|
||||
*/
|
||||
export function isBackgroundLaunch(
|
||||
record: SubagentRecord | undefined,
|
||||
input: Record<string, unknown> | undefined,
|
||||
result: Record<string, unknown>,
|
||||
): boolean {
|
||||
return (
|
||||
record?.background === true ||
|
||||
input?.run_in_background === true ||
|
||||
(result.is_error !== true &&
|
||||
/^\s*Async agent launched\b/.test(replayContentText(result.content)))
|
||||
);
|
||||
}
|
||||
|
||||
/** A child of the v1 AIR replay, which sends `subagent_spawned` and `subagent_state_update`. */
|
||||
export type NativeReplayChild = {
|
||||
/** Its replay session id. */
|
||||
sessionId: string;
|
||||
/** The launch of its parent child, when a child launched it. */
|
||||
parentToolUseId?: string;
|
||||
/** False for a child without launch metadata or with a cyclic lineage. */
|
||||
reconstructable: boolean;
|
||||
announced: boolean;
|
||||
/** The input of its launch call. */
|
||||
input?: Record<string, unknown>;
|
||||
/** The end that the replay sent. */
|
||||
ended?: SubagentState;
|
||||
};
|
||||
|
||||
/**
|
||||
* The ends of the children of the v1 AIR replay. As live, the client gets one
|
||||
* end of each child.
|
||||
*
|
||||
* The replay registers the task notifications of a transcript before it
|
||||
* replays the transcript. The last notification of a child with a known
|
||||
* status decides its end, as in the RFD form, and the end goes out at the
|
||||
* position of that notification. The open children that the child launched
|
||||
* end first, deepest first. A child that has its own notification ends with
|
||||
* the state of it, so a real end always beats an end that its parent caused.
|
||||
* A notification of a child that already ended sends nothing. The end of its
|
||||
* parent sent the state of its last registered notification, or the replay
|
||||
* read the notification in a later transcript.
|
||||
* {@link afterHistory} ends each other announced child.
|
||||
*/
|
||||
export class NativeReplayEnds {
|
||||
/** The subagent records of the session, by launch id. */
|
||||
private records: ReadonlyMap<string, SubagentRecord> = new Map();
|
||||
/** The launch id of each subagent record, by agent id. */
|
||||
private launchByAgent = new Map<string, string>();
|
||||
/** The tool results of the history, by tool use id. */
|
||||
private readonly results = new Map<string, Record<string, unknown>>();
|
||||
/**
|
||||
* The states of the registered task notifications, in registration order,
|
||||
* by `tool:<tool use id>`, or by `agent:<task id>` for a notification
|
||||
* without a tool use id.
|
||||
*/
|
||||
private readonly notified = new Map<string, { order: number; state: SubagentState }[]>();
|
||||
private registered = 0;
|
||||
/** How many task notifications of each launch the replay reached. */
|
||||
private readonly reached = new Map<string, number>();
|
||||
|
||||
constructor(
|
||||
private readonly children: ReadonlyMap<string, NativeReplayChild>,
|
||||
private readonly rootSessionId: string,
|
||||
) {}
|
||||
|
||||
/** Takes the subagent records of the session, once the replay read them. */
|
||||
setRecords(records: ReadonlyMap<string, SubagentRecord>): void {
|
||||
this.records = records;
|
||||
this.launchByAgent = new Map(
|
||||
[...records].map(([launchId, record]) => [record.agentId, launchId]),
|
||||
);
|
||||
}
|
||||
|
||||
/** Takes the tool result `block` of the tool use `toolUseId`. */
|
||||
takeResult(toolUseId: string, block: Record<string, unknown>): void {
|
||||
this.results.set(toolUseId, block);
|
||||
}
|
||||
|
||||
/** Registers a task notification of a transcript before the replay of it. */
|
||||
takeNotification(notification: PersistedTaskNotification): void {
|
||||
const state = nativeSubagentState(notification.status);
|
||||
if (!state) return;
|
||||
const key = notification.tool_use_id
|
||||
? `tool:${notification.tool_use_id}`
|
||||
: `agent:${notification.task_id}`;
|
||||
const states = this.notified.get(key) ?? [];
|
||||
states.push({ order: this.registered++, state });
|
||||
this.notified.set(key, states);
|
||||
}
|
||||
|
||||
/**
|
||||
* The launch of the task of `notification`: its tool use id, else, as live,
|
||||
* the launch of the subagent whose agent id is the task id.
|
||||
*/
|
||||
launchIdOf(notification: PersistedTaskNotification): string | undefined {
|
||||
return notification.tool_use_id ?? this.launchByAgent.get(notification.task_id);
|
||||
}
|
||||
|
||||
/** The session that shows `child`: its parent child, else the root session. */
|
||||
parentSessionId(child: NativeReplayChild): string {
|
||||
return child.parentToolUseId
|
||||
? (this.children.get(child.parentToolUseId)?.sessionId ?? this.rootSessionId)
|
||||
: this.rootSessionId;
|
||||
}
|
||||
|
||||
/**
|
||||
* The ends that the replay sends at `notification`. Only the last
|
||||
* registered notification of a child with a known status sends them.
|
||||
*/
|
||||
atNotification(notification: PersistedTaskNotification): AcpSessionNotification[] {
|
||||
const toolUseId = this.launchIdOf(notification);
|
||||
const child = toolUseId !== undefined ? this.children.get(toolUseId) : undefined;
|
||||
const state = nativeSubagentState(notification.status);
|
||||
if (toolUseId === undefined || !child || !state) return [];
|
||||
const reached = (this.reached.get(toolUseId) ?? 0) + 1;
|
||||
this.reached.set(toolUseId, reached);
|
||||
if (reached < this.notifiedStates(toolUseId).length) return [];
|
||||
if (!child.announced || !child.reconstructable || child.ended) return [];
|
||||
const descendants = [...this.children.entries()]
|
||||
.reverse()
|
||||
.filter(([id, other]) => other.announced && !other.ended && this.descends(id, toolUseId));
|
||||
return [
|
||||
...descendants.map(([id, other]) => this.end(other, this.endState(id, other))),
|
||||
this.end(child, state),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* The end of each announced child that is not ended, deepest first: its
|
||||
* last notification, else the end of its launch result, else `disconnected`.
|
||||
*/
|
||||
afterHistory(): AcpSessionNotification[] {
|
||||
return [...this.children.entries()]
|
||||
.reverse()
|
||||
.filter(([, child]) => child.announced && !child.ended)
|
||||
.map(([id, child]) => this.end(child, this.endState(id, child)));
|
||||
}
|
||||
|
||||
/** The registered notification states of the launch `toolUseId`, in order. */
|
||||
private notifiedStates(toolUseId: string): { order: number; state: SubagentState }[] {
|
||||
const agentId = this.records.get(toolUseId)?.agentId;
|
||||
return [
|
||||
...(this.notified.get(`tool:${toolUseId}`) ?? []),
|
||||
...((agentId !== undefined ? this.notified.get(`agent:${agentId}`) : undefined) ?? []),
|
||||
].sort((a, b) => a.order - b.order);
|
||||
}
|
||||
|
||||
private endState(toolUseId: string, child: NativeReplayChild): SubagentState {
|
||||
if (!child.reconstructable) return "disconnected";
|
||||
return (
|
||||
this.notifiedStates(toolUseId).at(-1)?.state ??
|
||||
this.launchEnd(toolUseId, child) ??
|
||||
"disconnected"
|
||||
);
|
||||
}
|
||||
|
||||
/** The end from the launch result. A background launch has none. */
|
||||
private launchEnd(toolUseId: string, child: NativeReplayChild): SubagentState | undefined {
|
||||
const result = this.results.get(toolUseId);
|
||||
if (!result || isBackgroundLaunch(this.records.get(toolUseId), child.input, result)) {
|
||||
return undefined;
|
||||
}
|
||||
return replaySubagentTerminalState(result);
|
||||
}
|
||||
|
||||
/** Whether the launch `toolUseId` is under the launch `ancestorId`. */
|
||||
private descends(toolUseId: string, ancestorId: string): boolean {
|
||||
const seen = new Set<string>();
|
||||
let parent = this.children.get(toolUseId)?.parentToolUseId;
|
||||
while (parent !== undefined && !seen.has(parent)) {
|
||||
if (parent === ancestorId) return true;
|
||||
seen.add(parent);
|
||||
parent = this.children.get(parent)?.parentToolUseId;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private end(child: NativeReplayChild, state: SubagentState): AcpSessionNotification {
|
||||
child.ended = state;
|
||||
return {
|
||||
sessionId: this.parentSessionId(child),
|
||||
update: {
|
||||
sessionUpdate: "subagent_state_update",
|
||||
subagentSessionId: child.sessionId,
|
||||
state,
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* How `child`'s work ended: the state of its last task notification, else
|
||||
* `cancelled` for a child the user stopped, else the result of its foreground
|
||||
|
||||
@@ -2965,6 +2965,7 @@ describe("task notification replay", () => {
|
||||
capabilities: ClientCapabilities = {
|
||||
_meta: { jetbrains: { air: { version: 1, capabilities: ["asyncTasks"] } } },
|
||||
},
|
||||
sessionId = "s1",
|
||||
): Promise<AcpSessionNotification[]> {
|
||||
const updates: AcpSessionNotification[] = [];
|
||||
const agent = new ClaudeAcpAgent(
|
||||
@@ -2978,7 +2979,7 @@ describe("task notification replay", () => {
|
||||
vi.mocked(getSessionMessages).mockResolvedValueOnce(history);
|
||||
await (
|
||||
agent as unknown as { replaySessionHistory(sessionId: string): Promise<void> }
|
||||
).replaySessionHistory("s1");
|
||||
).replaySessionHistory(sessionId);
|
||||
return updates;
|
||||
}
|
||||
|
||||
@@ -3259,6 +3260,481 @@ describe("task notification replay", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("the end of a background Agent", () => {
|
||||
const agentCapabilities = {
|
||||
subagents: {},
|
||||
_meta: { jetbrains: { air: { version: 1, capabilities: ["asyncTasks"] } } },
|
||||
} as ClientCapabilities;
|
||||
// The SDK reads the transcript of a subagent only for a session with a UUID.
|
||||
const sid = "33333333-3333-4333-8333-333333333333";
|
||||
const replayed = (history: Parameters<typeof replay>[0]) =>
|
||||
replay(history, agentCapabilities, sid);
|
||||
// `subagentHistory` reads this directory, never the real config.
|
||||
let configDir: string;
|
||||
let projectDir: string;
|
||||
let originalConfigDir: string | undefined;
|
||||
beforeEach(async () => {
|
||||
configDir = await mkdtemp(path.join(os.tmpdir(), "claude-acp-background-end-"));
|
||||
projectDir = path.join(configDir, "projects", "-tmp-proj");
|
||||
await mkdir(path.join(projectDir, sid, "subagents"), { recursive: true });
|
||||
// The SDK reads a subagent transcript only beside a session transcript with a record.
|
||||
await writeFile(
|
||||
path.join(projectDir, `${sid}.jsonl`),
|
||||
JSON.stringify({
|
||||
sessionId: sid,
|
||||
type: "user",
|
||||
uuid: "u0",
|
||||
parentUuid: null,
|
||||
timestamp: "2026-09-24T00:00:00.000Z",
|
||||
message: { role: "user", content: "Explore it" },
|
||||
}) + "\n",
|
||||
);
|
||||
originalConfigDir = process.env.CLAUDE_CONFIG_DIR;
|
||||
process.env.CLAUDE_CONFIG_DIR = configDir;
|
||||
});
|
||||
afterEach(async () => {
|
||||
if (originalConfigDir === undefined) delete process.env.CLAUDE_CONFIG_DIR;
|
||||
else process.env.CLAUDE_CONFIG_DIR = originalConfigDir;
|
||||
vi.mocked(getSessionInfo).mockReset();
|
||||
await rm(configDir, { recursive: true, force: true });
|
||||
});
|
||||
/** Writes the metadata of the child `agentId` of the launch `toolUseId`, and its transcript. */
|
||||
const writeChild = async (
|
||||
agentId: string,
|
||||
toolUseId: string,
|
||||
meta: Record<string, unknown>,
|
||||
transcript: object[] = [],
|
||||
) => {
|
||||
// The project directory of the session, which names `projectDir`.
|
||||
vi.mocked(getSessionInfo).mockResolvedValueOnce({ cwd: "/tmp/proj" } as any);
|
||||
const directory = path.join(projectDir, sid, "subagents");
|
||||
await writeFile(
|
||||
path.join(directory, `agent-${agentId}.meta.json`),
|
||||
JSON.stringify({ toolUseId, agentType: "general-purpose", ...meta }),
|
||||
);
|
||||
await writeFile(
|
||||
path.join(directory, `agent-${agentId}.jsonl`),
|
||||
transcript.map((line) => JSON.stringify(line)).join("\n") + "\n",
|
||||
);
|
||||
};
|
||||
const launch = (
|
||||
toolUseId: string,
|
||||
input: Record<string, unknown>,
|
||||
result: string,
|
||||
parent?: string,
|
||||
) => [
|
||||
record({
|
||||
type: "assistant",
|
||||
uuid: `launch-${toolUseId}`,
|
||||
...(parent ? { parent_tool_use_id: parent } : {}),
|
||||
message: {
|
||||
id: `m-${toolUseId}`,
|
||||
role: "assistant",
|
||||
model: "claude-opus-5",
|
||||
content: [
|
||||
{
|
||||
type: "tool_use",
|
||||
id: toolUseId,
|
||||
name: "Agent",
|
||||
input: { description: "Explore", prompt: "Look around", ...input },
|
||||
},
|
||||
],
|
||||
},
|
||||
}),
|
||||
record({
|
||||
type: "user",
|
||||
uuid: `result-${toolUseId}`,
|
||||
...(parent ? { parent_tool_use_id: parent } : {}),
|
||||
message: {
|
||||
role: "user",
|
||||
content: [
|
||||
{
|
||||
type: "tool_result",
|
||||
tool_use_id: toolUseId,
|
||||
content: [{ type: "text", text: result }],
|
||||
},
|
||||
],
|
||||
},
|
||||
}),
|
||||
];
|
||||
const launched = "Async agent launched successfully.\nagentId: a1";
|
||||
const backgroundLaunch = (inputFlag: boolean) =>
|
||||
launch("toolu_agent", inputFlag ? { run_in_background: true } : {}, launched);
|
||||
const notificationOf = (status: string, toolUseId: string | null, taskId: string) =>
|
||||
"<task-notification>\n" +
|
||||
`<task-id>${taskId}</task-id>\n` +
|
||||
(toolUseId ? `<tool-use-id>${toolUseId}</tool-use-id>\n` : "") +
|
||||
`<status>${status}</status>\n` +
|
||||
'<summary>Agent "Explore" finished</summary>\n</task-notification>';
|
||||
/** A task notification of the child `taskId`; `toolUseId: null` leaves out the tool use id. */
|
||||
const agentNotification = (
|
||||
status: string,
|
||||
{
|
||||
uuid = `u-${status}`,
|
||||
toolUseId = "toolu_agent",
|
||||
taskId = "a1",
|
||||
}: { uuid?: string; toolUseId?: string | null; taskId?: string } = {},
|
||||
) =>
|
||||
record({
|
||||
type: "user",
|
||||
uuid,
|
||||
message: { role: "user", content: notificationOf(status, toolUseId, taskId) },
|
||||
origin: { kind: "task-notification" },
|
||||
});
|
||||
const later = record({
|
||||
type: "user",
|
||||
uuid: "u9",
|
||||
message: { role: "user", content: "What did it find?" },
|
||||
});
|
||||
const short = (id: string | undefined) =>
|
||||
id === sid ? "s1" : id?.replace(`${sid}:replay-subagent:`, "");
|
||||
const trace = (updates: AcpSessionNotification[]) =>
|
||||
updates.flatMap(({ sessionId: target, update }) => {
|
||||
const fields = update as {
|
||||
subagentSessionId?: string;
|
||||
state?: string;
|
||||
content?: { text?: string };
|
||||
};
|
||||
switch (update.sessionUpdate) {
|
||||
case "subagent_spawned":
|
||||
return [[short(target), "spawned", short(fields.subagentSessionId)]];
|
||||
case "subagent_state_update":
|
||||
return [[short(target), "end", short(fields.subagentSessionId), fields.state]];
|
||||
case "user_message_chunk":
|
||||
case "agent_message_chunk":
|
||||
return [[short(target), update.sessionUpdate, fields.content?.text]];
|
||||
default:
|
||||
return [];
|
||||
}
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ status: "completed", state: "completed" },
|
||||
{ status: "failed", state: "failed" },
|
||||
{ status: "stopped", state: "cancelled" },
|
||||
{ status: "killed", state: "cancelled" },
|
||||
])(
|
||||
"sends the $status end once, at the position of its notification",
|
||||
async ({ status, state }) => {
|
||||
const updates = await replayed([
|
||||
...backgroundLaunch(false),
|
||||
agentNotification(status),
|
||||
later,
|
||||
]);
|
||||
|
||||
expect(trace(updates)).toEqual([
|
||||
["s1", "spawned", "toolu_agent"],
|
||||
["s1", "end", "toolu_agent", state],
|
||||
["s1", "user_message_chunk", "What did it find?"],
|
||||
]);
|
||||
expect(
|
||||
updates.find(({ update }) => update.sessionUpdate === "subagent_state_update")?.update,
|
||||
).toEqual({
|
||||
sessionUpdate: "subagent_state_update",
|
||||
subagentSessionId: `${sid}:replay-subagent:toolu_agent`,
|
||||
state,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
{ statuses: ["completed", "completed"], state: "completed" },
|
||||
{ statuses: ["completed", "killed"], state: "cancelled" },
|
||||
])(
|
||||
"sends one end, from the last of the notifications $statuses",
|
||||
async ({ statuses, state }) => {
|
||||
const updates = await replayed([
|
||||
...backgroundLaunch(true),
|
||||
...statuses.map((status, index) => agentNotification(status, { uuid: `u-${index}` })),
|
||||
later,
|
||||
]);
|
||||
|
||||
expect(trace(updates)).toEqual([
|
||||
["s1", "spawned", "toolu_agent"],
|
||||
["s1", "end", "toolu_agent", state],
|
||||
["s1", "user_message_chunk", "What did it find?"],
|
||||
]);
|
||||
},
|
||||
);
|
||||
|
||||
it("sends the end at the last notification of a child that ran again", async () => {
|
||||
const updates = await replayed([
|
||||
...backgroundLaunch(true),
|
||||
agentNotification("completed"),
|
||||
record({ type: "user", uuid: "u-again", message: { role: "user", content: "Go on" } }),
|
||||
agentNotification("failed"),
|
||||
later,
|
||||
]);
|
||||
|
||||
expect(trace(updates)).toEqual([
|
||||
["s1", "spawned", "toolu_agent"],
|
||||
["s1", "user_message_chunk", "Go on"],
|
||||
["s1", "end", "toolu_agent", "failed"],
|
||||
["s1", "user_message_chunk", "What did it find?"],
|
||||
]);
|
||||
});
|
||||
|
||||
it.each([false, true])(
|
||||
"does not take the launch result for the end of a child without a notification (input flag %s)",
|
||||
async (inputFlag) => {
|
||||
const updates = await replayed(backgroundLaunch(inputFlag));
|
||||
|
||||
// Nothing in the history ends the child, so the load ends it as disconnected.
|
||||
expect(trace(updates)).toEqual([
|
||||
["s1", "spawned", "toolu_agent"],
|
||||
["s1", "end", "toolu_agent", "disconnected"],
|
||||
]);
|
||||
},
|
||||
);
|
||||
|
||||
it("takes no end from a notification with an unknown status", async () => {
|
||||
const updates = await replayed([
|
||||
...backgroundLaunch(true),
|
||||
agentNotification("paused"),
|
||||
later,
|
||||
]);
|
||||
|
||||
expect(trace(updates)).toEqual([
|
||||
["s1", "spawned", "toolu_agent"],
|
||||
["s1", "user_message_chunk", "What did it find?"],
|
||||
["s1", "end", "toolu_agent", "disconnected"],
|
||||
]);
|
||||
});
|
||||
|
||||
it("ends a foreground child after the history, from its launch result", async () => {
|
||||
const updates = await replayed([...launch("toolu_agent", {}, "Found it."), later]);
|
||||
|
||||
expect(trace(updates)).toEqual([
|
||||
["s1", "spawned", "toolu_agent"],
|
||||
["s1", "user_message_chunk", "What did it find?"],
|
||||
["s1", "end", "toolu_agent", "completed"],
|
||||
]);
|
||||
});
|
||||
|
||||
it("takes the result text of a foreground child that moved to the background", async () => {
|
||||
// Claude Code can move a foreground child to the background. Its metadata still says foreground.
|
||||
await writeChild("a1", "toolu_agent", { requestShape: "foreground" });
|
||||
|
||||
const updates = await replayed([...launch("toolu_agent", {}, launched), later]);
|
||||
|
||||
expect(trace(updates).filter(([, kind]) => kind === "end")).toEqual([
|
||||
["s1", "end", "toolu_agent", "disconnected"],
|
||||
]);
|
||||
});
|
||||
|
||||
it("takes the run_in_background flag of a launch for a background child", async () => {
|
||||
const updates = await replayed([
|
||||
...launch("toolu_agent", { run_in_background: true }, "Started."),
|
||||
later,
|
||||
]);
|
||||
|
||||
expect(trace(updates).filter(([, kind]) => kind === "end")).toEqual([
|
||||
["s1", "end", "toolu_agent", "disconnected"],
|
||||
]);
|
||||
});
|
||||
|
||||
it("ends an open child with its own later notification, not with its parent's end", async () => {
|
||||
const updates = await replayed([
|
||||
...backgroundLaunch(true),
|
||||
...launch(
|
||||
"toolu_inner",
|
||||
{ run_in_background: true },
|
||||
"Async agent launched successfully.\nagentId: a2",
|
||||
"toolu_agent",
|
||||
),
|
||||
agentNotification("completed"),
|
||||
later,
|
||||
agentNotification("failed", { uuid: "u-inner", toolUseId: "toolu_inner", taskId: "a2" }),
|
||||
]);
|
||||
|
||||
expect(trace(updates)).toEqual([
|
||||
["s1", "spawned", "toolu_agent"],
|
||||
["toolu_agent", "spawned", "toolu_inner"],
|
||||
["toolu_agent", "end", "toolu_inner", "failed"],
|
||||
["s1", "end", "toolu_agent", "completed"],
|
||||
["s1", "user_message_chunk", "What did it find?"],
|
||||
]);
|
||||
});
|
||||
|
||||
it("ends the open children of a child before the child, deepest first", async () => {
|
||||
const updates = await replayed([
|
||||
...backgroundLaunch(true),
|
||||
...launch("toolu_inner", {}, "Inner done.", "toolu_agent"),
|
||||
...launch("toolu_deep", {}, "Deep done.", "toolu_inner"),
|
||||
agentNotification("completed"),
|
||||
later,
|
||||
]);
|
||||
|
||||
expect(trace(updates)).toEqual([
|
||||
["s1", "spawned", "toolu_agent"],
|
||||
["toolu_agent", "spawned", "toolu_inner"],
|
||||
["toolu_inner", "spawned", "toolu_deep"],
|
||||
["toolu_inner", "end", "toolu_deep", "completed"],
|
||||
["toolu_agent", "end", "toolu_inner", "completed"],
|
||||
["s1", "end", "toolu_agent", "completed"],
|
||||
["s1", "user_message_chunk", "What did it find?"],
|
||||
]);
|
||||
});
|
||||
|
||||
it("finds the child of a notification without a tool use id by its agent id", async () => {
|
||||
await writeChild("a1", "toolu_agent", { requestShape: "background" });
|
||||
|
||||
const updates = await replayed([
|
||||
...backgroundLaunch(true),
|
||||
agentNotification("completed", { uuid: "u-done", toolUseId: null }),
|
||||
later,
|
||||
]);
|
||||
|
||||
expect(trace(updates)).toEqual([
|
||||
["s1", "spawned", "toolu_agent"],
|
||||
["s1", "end", "toolu_agent", "completed"],
|
||||
["s1", "user_message_chunk", "What did it find?"],
|
||||
]);
|
||||
});
|
||||
|
||||
it("sends the end after the frames of the child from its transcript", async () => {
|
||||
const child = {
|
||||
sessionId: sid,
|
||||
cwd: "/tmp/proj",
|
||||
version: "2.0.0",
|
||||
userType: "external",
|
||||
isSidechain: true,
|
||||
agentId: "a1",
|
||||
timestamp: "2026-09-24T00:00:00.000Z",
|
||||
};
|
||||
await writeChild("a1", "toolu_agent", { requestShape: "background" }, [
|
||||
{
|
||||
...child,
|
||||
type: "user",
|
||||
uuid: "c1",
|
||||
parentUuid: null,
|
||||
message: { role: "user", content: "Look around" },
|
||||
},
|
||||
{
|
||||
...child,
|
||||
type: "assistant",
|
||||
uuid: "c2",
|
||||
parentUuid: "c1",
|
||||
message: {
|
||||
id: "m3",
|
||||
role: "assistant",
|
||||
model: "claude-haiku-4-5",
|
||||
content: [{ type: "text", text: "Child report." }],
|
||||
},
|
||||
},
|
||||
]);
|
||||
|
||||
const updates = await replayed([
|
||||
...backgroundLaunch(true),
|
||||
agentNotification("completed"),
|
||||
later,
|
||||
]);
|
||||
|
||||
expect(trace(updates)).toEqual([
|
||||
["s1", "spawned", "toolu_agent"],
|
||||
["toolu_agent", "user_message_chunk", "Look around"],
|
||||
["toolu_agent", "agent_message_chunk", "Child report."],
|
||||
["s1", "end", "toolu_agent", "completed"],
|
||||
["s1", "user_message_chunk", "What did it find?"],
|
||||
]);
|
||||
});
|
||||
|
||||
it("does not end again a child of a transcript that ended before its parent", async () => {
|
||||
const child = {
|
||||
sessionId: sid,
|
||||
cwd: "/tmp/proj",
|
||||
version: "2.0.0",
|
||||
userType: "external",
|
||||
isSidechain: true,
|
||||
agentId: "a1",
|
||||
timestamp: "2026-09-24T00:00:00.000Z",
|
||||
};
|
||||
await writeChild("a2", "toolu_inner", { requestShape: "background" });
|
||||
await writeChild("a1", "toolu_agent", { requestShape: "background" }, [
|
||||
{
|
||||
...child,
|
||||
type: "user",
|
||||
uuid: "c1",
|
||||
parentUuid: null,
|
||||
message: { role: "user", content: "Look around" },
|
||||
},
|
||||
{
|
||||
...child,
|
||||
type: "assistant",
|
||||
uuid: "c2",
|
||||
parentUuid: "c1",
|
||||
message: {
|
||||
id: "m3",
|
||||
role: "assistant",
|
||||
model: "claude-haiku-4-5",
|
||||
content: [
|
||||
{
|
||||
type: "tool_use",
|
||||
id: "toolu_inner",
|
||||
name: "Agent",
|
||||
input: { description: "Dig", prompt: "Dig deeper", run_in_background: true },
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
...child,
|
||||
type: "user",
|
||||
uuid: "c3",
|
||||
parentUuid: "c2",
|
||||
message: {
|
||||
role: "user",
|
||||
content: [
|
||||
{
|
||||
type: "tool_result",
|
||||
tool_use_id: "toolu_inner",
|
||||
content: [
|
||||
{ type: "text", text: "Async agent launched successfully.\nagentId: a2" },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
...child,
|
||||
type: "user",
|
||||
uuid: "c4",
|
||||
parentUuid: "c3",
|
||||
message: { role: "user", content: notificationOf("failed", "toolu_inner", "a2") },
|
||||
origin: { kind: "task-notification" },
|
||||
},
|
||||
{
|
||||
...child,
|
||||
type: "assistant",
|
||||
uuid: "c5",
|
||||
parentUuid: "c4",
|
||||
message: {
|
||||
id: "m4",
|
||||
role: "assistant",
|
||||
model: "claude-haiku-4-5",
|
||||
content: [{ type: "text", text: "Child report." }],
|
||||
},
|
||||
},
|
||||
]);
|
||||
|
||||
const updates = await replayed([
|
||||
...backgroundLaunch(true),
|
||||
agentNotification("completed"),
|
||||
later,
|
||||
]);
|
||||
|
||||
expect(trace(updates)).toEqual([
|
||||
["s1", "spawned", "toolu_agent"],
|
||||
["toolu_agent", "user_message_chunk", "Look around"],
|
||||
["toolu_agent", "spawned", "toolu_inner"],
|
||||
["toolu_agent", "end", "toolu_inner", "failed"],
|
||||
["toolu_agent", "agent_message_chunk", "Child report."],
|
||||
["s1", "end", "toolu_agent", "completed"],
|
||||
["s1", "user_message_chunk", "What did it find?"],
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps a task-notification delivery with a subkind as a prompt", async () => {
|
||||
const updates = await replay([
|
||||
record({
|
||||
|
||||
@@ -119,7 +119,6 @@ import {
|
||||
restrictedChild,
|
||||
SubagentAwareSessionCapabilities,
|
||||
subagentForm,
|
||||
type SubagentState,
|
||||
} from "../acp-subagents.js";
|
||||
import {
|
||||
childModelOption,
|
||||
@@ -127,7 +126,6 @@ import {
|
||||
isNativeSubagentControlUpdate,
|
||||
NativeSubagent,
|
||||
NativeSubagentRuntime,
|
||||
nativeSubagentState,
|
||||
type ModelEntry,
|
||||
responseModelEntry,
|
||||
resumedNativeSubagentId,
|
||||
@@ -262,8 +260,9 @@ import {
|
||||
import {
|
||||
type ReplayChild,
|
||||
RfdSubagentReplay,
|
||||
NativeReplayEnds,
|
||||
type NativeReplayChild,
|
||||
ReplayTranscript,
|
||||
replaySubagentTerminalState,
|
||||
} from "../subagent-replay.js";
|
||||
import {
|
||||
readHistoryAcrossCompactions,
|
||||
@@ -8568,20 +8567,11 @@ export class ClaudeAcpAgent {
|
||||
const form = subagentForm(this.clientCapabilities);
|
||||
const nativeReplayEnabled = form === "air";
|
||||
const replayCompactionUpdates = clientSupportsCompactionUpdates(this.clientCapabilities);
|
||||
const replayTerminalStates = new Map<string, "completed" | "failed" | "cancelled">();
|
||||
const replayChildren = new Map<
|
||||
string,
|
||||
{
|
||||
sessionId: string;
|
||||
parentToolUseId?: string;
|
||||
NativeReplayChild & {
|
||||
name: string;
|
||||
task: string;
|
||||
reconstructable: boolean;
|
||||
announced: boolean;
|
||||
terminalState?: "completed" | "failed" | "cancelled";
|
||||
/** The state of the last persisted task notification of the child.
|
||||
* It comes after the launch tool_result, so it wins. */
|
||||
notifiedState?: SubagentState;
|
||||
/** The model id of the child's latest response in its transcript. */
|
||||
responseModel?: string;
|
||||
/** The `model` option entry that the replay sent to the child. */
|
||||
@@ -8593,6 +8583,7 @@ export class ClaudeAcpAgent {
|
||||
// no model to the list, and each child's model is its id until the load
|
||||
// response refines it (see `publishCurrentSubagentStates`).
|
||||
const replayModels = pending ? undefined : this.subagentModels(sessionId);
|
||||
const replayEnds = new NativeReplayEnds(replayChildren, sessionId);
|
||||
const readSubagentHistory = () =>
|
||||
detached
|
||||
? subagentHistory(sessionId, { strict: true, transcript: detached.transcript })
|
||||
@@ -8602,12 +8593,19 @@ export class ClaudeAcpAgent {
|
||||
? readSubagentMessagesOrFail(sessionId, agentId, history, launchId)
|
||||
: readSubagentMessages(sessionId, agentId, history, this.logger);
|
||||
|
||||
// Registers the Agent and Task launches of `list`, and the terminal state
|
||||
// of each launch from its tool_result.
|
||||
// Registers the Agent and Task launches of `list`, and the tool results
|
||||
// and the task notifications that can end them. The replay reads the
|
||||
// notifications of the same messages (see `restoreTaskNotification`).
|
||||
const registerLaunches = (list: SessionMessage[]): void => {
|
||||
for (const message of list) {
|
||||
const content = (message as unknown as { message?: { content?: unknown } }).message
|
||||
?.content;
|
||||
const inner = (message as unknown as { message?: { role?: unknown; content?: unknown } })
|
||||
.message;
|
||||
const content = inner?.content;
|
||||
if (inner?.role === "user" && !isReplayHiddenMetaMessage(message)) {
|
||||
for (const notification of taskNotificationsOf(content)) {
|
||||
replayEnds.takeNotification(notification);
|
||||
}
|
||||
}
|
||||
if (!Array.isArray(content)) continue;
|
||||
const ownerToolUseId = parentToolUseIdOf(message);
|
||||
for (const block of content) {
|
||||
@@ -8619,7 +8617,7 @@ export class ClaudeAcpAgent {
|
||||
"tool_use_id" in block &&
|
||||
typeof block.tool_use_id === "string"
|
||||
) {
|
||||
replayTerminalStates.set(block.tool_use_id, replaySubagentTerminalState(block));
|
||||
replayEnds.takeResult(block.tool_use_id, block);
|
||||
}
|
||||
if (
|
||||
typeof block !== "object" ||
|
||||
@@ -8656,14 +8654,10 @@ export class ClaudeAcpAgent {
|
||||
task,
|
||||
reconstructable: true,
|
||||
announced: false,
|
||||
terminalState: replayTerminalStates.get(block.id),
|
||||
input,
|
||||
});
|
||||
}
|
||||
}
|
||||
for (const [toolUseId, terminalState] of replayTerminalStates) {
|
||||
const child = replayChildren.get(toolUseId);
|
||||
if (child) child.terminalState = terminalState;
|
||||
}
|
||||
};
|
||||
if (nativeReplayEnabled) registerLaunches(messages);
|
||||
|
||||
@@ -8684,7 +8678,6 @@ export class ClaudeAcpAgent {
|
||||
}
|
||||
if (ancestors.has(parentToolUseId)) {
|
||||
child.reconstructable = false;
|
||||
child.terminalState = undefined;
|
||||
child.parentToolUseId = undefined;
|
||||
}
|
||||
if (child.parentToolUseId) {
|
||||
@@ -8693,12 +8686,9 @@ export class ClaudeAcpAgent {
|
||||
await announceReplayChild(child.parentToolUseId, nextAncestors);
|
||||
}
|
||||
if (!child.announced) {
|
||||
const parentSessionId = child.parentToolUseId
|
||||
? (replayChildren.get(child.parentToolUseId)?.sessionId ?? sessionId)
|
||||
: sessionId;
|
||||
await publish(
|
||||
asSdkSessionNotification({
|
||||
sessionId: parentSessionId,
|
||||
sessionId: replayEnds.parentSessionId(child),
|
||||
update: {
|
||||
sessionUpdate: "subagent_spawned",
|
||||
subagentSessionId: child.sessionId,
|
||||
@@ -8718,6 +8708,7 @@ export class ClaudeAcpAgent {
|
||||
nativeReplayEnabled && replayChildren.size > 0
|
||||
? await readSubagentHistory()
|
||||
: { agents: new Map() };
|
||||
replayEnds.setRecords(subagents.agents);
|
||||
const airReplay = nativeReplayEnabled ? new ReplayTranscript(subagents) : undefined;
|
||||
airReplay?.scan(messages, sessionId);
|
||||
const replayedSubagents = new Set<string>();
|
||||
@@ -8767,13 +8758,15 @@ export class ClaudeAcpAgent {
|
||||
notification: PersistedTaskNotification,
|
||||
): Promise<void> => {
|
||||
if (rfdReplay?.taskNotification(notification.task_id, notification.status)) return;
|
||||
const toolUseId = notification.tool_use_id;
|
||||
const toolUseId = replayEnds.launchIdOf(notification);
|
||||
if (!toolUseId) return;
|
||||
const child = replayChildren.get(toolUseId);
|
||||
const toolUse = replayToolUses.get(toolUseId);
|
||||
if (child || (toolUse && isNativeSubagentControlTool(toolUse.name))) {
|
||||
const state = nativeSubagentState(notification.status);
|
||||
if (child && state) child.notifiedState = state;
|
||||
// The end goes at the position of the notification, as the live frame sends it.
|
||||
for (const end of replayEnds.atNotification(notification)) {
|
||||
await publish(asSdkSessionNotification(end));
|
||||
}
|
||||
return;
|
||||
}
|
||||
// Like live, a task that no tool call started stays unknown.
|
||||
@@ -9059,26 +9052,17 @@ export class ClaudeAcpAgent {
|
||||
}
|
||||
if (!detached && childModels.size > 0) this.replayedChildModels.set(sessionId, childModels);
|
||||
// Claude history persists sidechain messages and Agent/Task tool uses,
|
||||
// but not task_started/task_updated lifecycle frames. Recover terminal
|
||||
// state from the launch tool_result. Missing results and malformed or
|
||||
// orphan lineage use the draft protocol's deterministic disconnected state.
|
||||
for (const child of [...replayChildren.values()].reverse()) {
|
||||
if (!child.announced) continue;
|
||||
const parentSessionId = child.parentToolUseId
|
||||
? (replayChildren.get(child.parentToolUseId)?.sessionId ?? sessionId)
|
||||
: sessionId;
|
||||
await publish(
|
||||
asSdkSessionNotification({
|
||||
sessionId: parentSessionId,
|
||||
update: {
|
||||
sessionUpdate: "subagent_state_update",
|
||||
subagentSessionId: child.sessionId,
|
||||
state: child.reconstructable
|
||||
? (child.notifiedState ?? child.terminalState ?? "disconnected")
|
||||
: "disconnected",
|
||||
},
|
||||
}),
|
||||
);
|
||||
// but not task_started/task_updated lifecycle frames. A child that no
|
||||
// task notification ended gets its end from its launch result:
|
||||
// `completed`, or `failed` (`cancelled` for a stop) for an error. A
|
||||
// background launch, a missing result, and malformed or orphan lineage
|
||||
// give the draft protocol's deterministic `disconnected` state.
|
||||
// A load of a session that runs in this process also ends a child that
|
||||
// still runs. AIR's draft allows no update after a child's end, and the
|
||||
// live stream reports the child under its live session id, not its
|
||||
// replay id. So nothing corrects this replayed end.
|
||||
for (const end of replayEnds.afterHistory()) {
|
||||
await publish(asSdkSessionNotification(end));
|
||||
}
|
||||
}
|
||||
const replayFinishedAt = performance.now();
|
||||
|
||||
Reference in New Issue
Block a user