diff --git a/README.md b/README.md index f7d5d21e..448bd5e5 100644 --- a/README.md +++ b/README.md @@ -58,8 +58,11 @@ Task subagent as its own child session, following the [subagents RFD](https://gi prompt resolves. A child that still runs when Claude Code exits is `idle` with no stop reason. - A child whose parent is not yet known when it ends is not exposed, since the RFD forbids guessing its parent. -- A client cannot prompt, cancel, or otherwise change a child yet, and a replay does not restore - children yet. +- A replay restores each child under its live session id, from its own transcript: its prompt and + each SendMessage message are `session_message`s, and its end is an `idle` before the response. + 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 client cannot prompt, cancel, or otherwise change a child yet. An [ACP v2](#experimental-acp-v2) client gets the same without declaring anything, since subagents are part of v2's baseline. Each child also reports its work state as its own `state_update`, right diff --git a/src/acp-agent.ts b/src/acp-agent.ts index 6e685076..ec6e1cc0 100644 --- a/src/acp-agent.ts +++ b/src/acp-agent.ts @@ -65,7 +65,6 @@ import { FastModeState, filterEscalatingDefaultMode, getSessionMessages, - getSubagentMessages, HookCallback, listSessions, McpServerConfig, @@ -184,7 +183,12 @@ import { refusalFallbackToCreateRequest, } from "./elicitation.js"; import { forkSession } from "./fork-session.js"; -import { subagentHistory } from "./subagent-history.js"; +import { readSubagentMessages, subagentHistory } from "./subagent-history.js"; +import { + type ReplayChild, + RfdSubagentReplay, + replaySubagentTerminalState, +} from "./subagent-replay.js"; import { readResumedSession, readResumedTail, @@ -1785,28 +1789,6 @@ function subagentLaunchIds(content: unknown): string[] { ); } -function replaySubagentTerminalState( - block: Record, -): "completed" | "failed" | "cancelled" { - if (block.is_error !== true) return "completed"; - const text = replayContentText(block.content).toLowerCase(); - return /\b(?:cancelled|canceled|interrupted|stopped|killed)\b/.test(text) - ? "cancelled" - : "failed"; -} - -function replayContentText(value: unknown, seen = new Set()): string { - if (typeof value === "string") return value; - if (typeof value !== "object" || value === null || seen.has(value)) return ""; - seen.add(value); - if (Array.isArray(value)) return value.map((item) => replayContentText(item, seen)).join(" "); - const record = value as Record; - return [record.text, record.content, record.message] - .map((item) => replayContentText(item, seen)) - .filter(Boolean) - .join(" "); -} - function stripSubagentTextAndThinking(content: unknown): unknown { if (!Array.isArray(content)) return content; return content.filter( @@ -8477,10 +8459,11 @@ export class ClaudeAcpAgent { }) : undefined; let replayTurnId: string | undefined; - // Only AIR's draft replays child sessions so far. A client on the RFD gets - // no children on replay, which the RFD allows (it SHOULD replay them), until - // the replay keeps the children's live session ids. - const nativeReplayEnabled = subagentForm(this.clientCapabilities) === "air"; + // AIR's draft replays each child under a replay id. A client on the RFD + // form gets each child under the session id it had live (see + // `RfdSubagentReplay`). + const form = subagentForm(this.clientCapabilities); + const nativeReplayEnabled = form === "air"; const replayCompactionUpdates = clientSupportsCompactionUpdates(this.clientCapabilities); const replayTerminalStates = new Map(); const replayChildren = new Map< @@ -8614,8 +8597,24 @@ export class ClaudeAcpAgent { const subagents = nativeReplayEnabled && replayChildren.size > 0 ? await subagentHistory(sessionId) - : { ids: new Map() }; + : { agents: new Map() }; const replayedSubagents = new Set(); + const rfdHistory = + form === "rfd" && + messages.some( + (message) => + subagentLaunchIds((message as { message?: { content?: unknown } }).message?.content) + .length > 0, + ) + ? await subagentHistory(sessionId) + : { agents: new Map() }; + const rfdReplay = + form === "rfd" + ? new RfdSubagentReplay(rfdHistory, (notification) => + this.client.sessionUpdate(asSdkSessionNotification(notification)), + ) + : undefined; + rfdReplay?.scan(messages, sessionId); // History persists no task_started frame, so a background task gets its // spawn from the notification of its stop, with the tool call that @@ -8642,6 +8641,7 @@ export class ClaudeAcpAgent { const restoreTaskNotification = async ( notification: PersistedTaskNotification, ): Promise => { + if (rfdReplay?.taskNotification(notification.task_id, notification.status)) return; const toolUseId = notification.tool_use_id; if (!toolUseId) return; const child = replayChildren.get(toolUseId); @@ -8666,7 +8666,8 @@ export class ClaudeAcpAgent { await replayAsyncTasks.taskNotification(notification); }; - const replayMessage = async (message: SessionMessage): Promise => { + /** Replays `message`, from the transcript of `child` when it is set (the RFD form). */ + const replayMessage = async (message: SessionMessage, child?: ReplayChild): Promise => { // A long history is sent in order, but with event-loop turns in between, // so other sessions and incoming requests are not starved meanwhile. const pause = messageLoopYielder.maybeYield(); @@ -8674,6 +8675,9 @@ export class ClaudeAcpAgent { if (pending?.stopped || isReplayHiddenMetaMessage(message)) { return; } + // In the RFD form a child's history comes from its own transcript, so a + // subagent message that the session transcript stores inline is skipped. + if (rfdReplay && !child && parentToolUseIdOf(message)) return; if ( message.type === "user" && message.parent_tool_use_id === null && @@ -8725,13 +8729,15 @@ export class ClaudeAcpAgent { // @ts-expect-error - untyped in SDK but we handle all of these let content: unknown = message.message.content; const parentToolUseId = parentToolUseIdOf(message); - const replayTargetSessionId = - nativeReplayEnabled && parentToolUseId + const replayTargetSessionId = child + ? child.sessionId + : nativeReplayEnabled && parentToolUseId ? await announceReplayChild(parentToolUseId) : sessionId; if ( message.type === "assistant" && parentToolUseId && + !child && !nativeReplayEnabled && !forwardSubagentText ) { @@ -8746,6 +8752,9 @@ export class ClaudeAcpAgent { } // Live, the prompt loop skips this record and the SDK frame reports the stop. content = isTaskNotificationRecord(message) ? null : stripLocalCommandMetadata(content); + if (content !== null && child && rfdReplay) { + content = await rfdReplay.childContent(child, message, content); + } if (content === null) return; } else if (Array.isArray(content)) { for (const block of content) { @@ -8835,28 +8844,42 @@ export class ClaudeAcpAgent { if (nativeReplayEnabled && message.type === "assistant") { for (const toolUseId of subagentLaunchIds(content)) { await announceReplayChild(toolUseId); - const agentId = subagents.ids.get(toolUseId); + const agentId = subagents.agents.get(toolUseId)?.agentId; if (!agentId || replayedSubagents.has(agentId)) continue; replayedSubagents.add(agentId); - let childMessages: SessionMessage[] = []; - try { - // With the project directory, the SDK skips its search of every project. - // A session opened from another directory falls back to that search. - if (subagents.dir) { - childMessages = await getSubagentMessages(sessionId, agentId, { dir: subagents.dir }); - } - if (childMessages.length === 0) { - childMessages = await getSubagentMessages(sessionId, agentId); - } - } catch (error) { - this.logger.error(`Failed to read the history of subagent ${agentId}:`, error); - } + const childMessages = await readSubagentMessages( + sessionId, + agentId, + subagents, + this.logger, + ); registerLaunches(childMessages); for (const childMessage of childMessages) await replayMessage(childMessage); } } + // The RFD form announces a child right after its launch, then sends its + // own transcript to it. + if (rfdReplay && message.type === "assistant") { + for (const toolUseId of subagentLaunchIds(content)) { + const launched = rfdReplay.childOfLaunch(toolUseId); + if (!launched || launched.announced) continue; + await rfdReplay.announce(launched); + const childMessages = await readSubagentMessages( + sessionId, + launched.sessionId, + rfdHistory, + this.logger, + ); + rfdReplay.scan(childMessages, launched.sessionId); + for (const childMessage of childMessages) await replayMessage(childMessage, launched); + await rfdReplay.childReplayed(launched, childMessages); + } + } }; for (const message of messages) await replayMessage(message); + if (rfdReplay && !pending?.stopped) { + await rfdReplay.finish(clientSupportsNotices(this.clientCapabilities), sessionId); + } if (nativeReplayEnabled && !pending?.stopped) { // Claude history persists sidechain messages and Agent/Task tool uses, diff --git a/src/native-subagents.ts b/src/native-subagents.ts index 54161422..2231a879 100644 --- a/src/native-subagents.ts +++ b/src/native-subagents.ts @@ -3,7 +3,7 @@ import type { AcpSessionNotification, SubagentForm, SubagentState } from "./acp- import { AIR_SUBAGENT_KEY, airExtensionMeta } from "./air-extension.js"; /** The work state of a child, as the RFD's `subagent_update.state` carries it. */ -type WorkState = NonNullable< +export type WorkState = NonNullable< Extract["state"] >; @@ -950,7 +950,7 @@ function isWorking(child: NativeSubagent): boolean { * stream ended, is idle with no stop reason: its work ended, but the adapter * did not see a cancellation or a failure, which the RFD forbids claiming. */ -function rfdEndState(state: SubagentState, end: TaskEnd | undefined): WorkState { +export function rfdEndState(state: SubagentState, end: TaskEnd | undefined): WorkState { if (end?.unexplained || end?.reason === "worker_restart") return { state: "idle" }; switch (state) { case "completed": @@ -976,7 +976,7 @@ function rfdEndState(state: SubagentState, end: TaskEnd | undefined): WorkState * name, with its role after it when both are known, else the role. The * description is the task's short description, never the prompt. */ -function rfdLabels( +export function rfdLabels( name: unknown, role: unknown, description: unknown, diff --git a/src/subagent-history.ts b/src/subagent-history.ts index 85e2cea0..63e40a72 100644 --- a/src/subagent-history.ts +++ b/src/subagent-history.ts @@ -1,12 +1,32 @@ -import { getSessionInfo } from "@anthropic-ai/claude-agent-sdk"; +import { + getSessionInfo, + getSubagentMessages, + type SessionMessage, +} from "@anthropic-ai/claude-agent-sdk"; import { readdir, readFile } from "node:fs/promises"; import path from "node:path"; import { findTranscript } from "./resumed-session.js"; +/** What the metadata file of a subagent says about it. */ +export interface SubagentRecord { + /** The SDK agent id, the name of its transcript. */ + agentId: string; + /** The `name` that the Agent call gave it. */ + name?: string; + /** Its role, the `subagent_type` of the Agent call. */ + agentType?: string; + /** The short `description` of the Agent call. */ + description?: string; + /** Whether the Agent call ran it in the background. */ + background: boolean; + /** Whether the user stopped it. */ + stoppedByUser: boolean; +} + /** Where the subagent transcripts of a session are. */ export interface SubagentHistory { - /** The subagent id of each Agent or Task tool use that launched a subagent. */ - ids: Map; + /** The subagent of each Agent or Task tool use that launched one. */ + agents: Map; /** * The project directory of the session, as the SDK takes it in `dir`. With * it, the SDK reads a subagent transcript without a search of every project. @@ -23,32 +43,67 @@ export interface SubagentHistory { * The ids are empty for a session without a local transcript. */ export async function subagentHistory(sessionId: string): Promise { - const ids = new Map(); + const agents = new Map(); const transcript = await findTranscript(sessionId); - if (!transcript) return { ids }; + if (!transcript) return { agents }; const directory = path.join(path.dirname(transcript), sessionId, "subagents"); let names: string[]; try { names = await readdir(directory); } catch { - return { ids }; + return { agents }; } await Promise.all( names.map(async (name) => { const match = /^agent-(.+)\.meta\.json$/.exec(name); if (!match) return; try { - const meta: unknown = JSON.parse(await readFile(path.join(directory, name), "utf8")); - const toolUseId = (meta as { toolUseId?: unknown } | null)?.toolUseId; - if (typeof toolUseId === "string") ids.set(toolUseId, match[1]!); + const meta = JSON.parse(await readFile(path.join(directory, name), "utf8")) as Record< + string, + unknown + > | null; + if (typeof meta?.toolUseId !== "string") return; + const text = (value: unknown) => (typeof value === "string" ? value : undefined); + agents.set(meta.toolUseId, { + agentId: match[1]!, + name: text(meta.name), + agentType: text(meta.agentType), + description: text(meta.description), + background: meta.requestShape === "background", + stoppedByUser: meta.stoppedByUser === true, + }); } catch { // A damaged meta file leaves its subagent without history. } }), ); - if (ids.size === 0) return { ids }; + if (agents.size === 0) return { agents }; // The folder name encodes the project directory, and the encoding loses // characters. The session info reads it back from the transcript. const dir = (await getSessionInfo(sessionId).catch(() => undefined))?.cwd; - return dir ? { ids, dir } : { ids }; + return dir ? { agents, dir } : { agents }; +} + +/** + * The transcript of the subagent `agentId` of a session, or an empty list + * when it cannot be read. With the project directory, the SDK skips its + * search of every project; a session opened from another directory falls + * back to that search. + */ +export async function readSubagentMessages( + sessionId: string, + agentId: string, + history: SubagentHistory, + logger: { error(...args: unknown[]): void }, +): Promise { + try { + if (history.dir) { + const messages = await getSubagentMessages(sessionId, agentId, { dir: history.dir }); + if (messages.length > 0) return messages; + } + return await getSubagentMessages(sessionId, agentId); + } catch (error) { + logger.error(`Failed to read the history of subagent ${agentId}:`, error); + return []; + } } diff --git a/src/subagent-replay.ts b/src/subagent-replay.ts new file mode 100644 index 00000000..45ad4754 --- /dev/null +++ b/src/subagent-replay.ts @@ -0,0 +1,346 @@ +/** + * The replay of subagents to a client on the subagents RFD form. + * + * 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 + * `subagentHistory`). The replay announces each child right after that call, + * under the session id it had live, the SDK agent id, and sends the child's + * history to the child session. Every child's end goes out before the replay + * ends, since no subagent from before the reload still runs. + * + * A launch without metadata has no known id, so it is not announced: the RFD + * forbids inventing one. Its Agent call stays an ordinary tool call of the + * parent, and a notice says that subagent history is missing. + */ +import type { SessionMessage } from "@anthropic-ai/claude-agent-sdk"; +import type { AcpSessionNotification, SubagentState } from "./acp-subagents.js"; +import { + isNativeSubagentControlTool, + nativeSubagentState, + rfdEndState, + rfdLabels, + type WorkState, +} from "./native-subagents.js"; +import { noticeUpdate } from "./session-notices.js"; +import type { SubagentHistory, SubagentRecord } from "./subagent-history.js"; + +type Publish = (notification: AcpSessionNotification) => Promise; + +/** A child that the replay shows: its launch has metadata. */ +export type ReplayChild = { + /** The Agent or Task tool use that launched it. */ + launchId: string; + /** Its session id: the SDK agent id, as live. */ + sessionId: string; + record: SubagentRecord; + /** The session that made the launch. */ + parentSessionId: string; + /** The input of the launch call. */ + input: Record; + /** How the launch's tool result ended a foreground child's run. */ + launchEnd?: SubagentState; + /** The state of the child's last persisted task notification. */ + notified?: SubagentState; + announced: boolean; + promptSent: boolean; +}; + +type SendMessageCall = { + toolUseId: string; + to: string; + message: string; + senderSessionId: string; + delivered: boolean; +}; + +export class RfdSubagentReplay { + /** The children by the id of the tool use that launched each. */ + private readonly children = new Map(); + private readonly byAgentId = new Map(); + private readonly sendMessages: SendMessageCall[] = []; + /** Launches without metadata, which the replay leaves out. */ + private readonly omitted = new Set(); + /** Children whose transcript could not be read: only their association is replayed. */ + private withoutHistory = 0; + + constructor( + private readonly history: SubagentHistory, + private readonly publish: Publish, + ) {} + + /** + * Registers the launches, the launch results, and the SendMessage calls in + * `messages`, the transcript of the session `ownerSessionId`. + */ + scan(messages: readonly SessionMessage[], ownerSessionId: string): void { + for (const message of messages) { + for (const block of contentBlocks(message)) { + if (block.type === "tool_use" && typeof block.id === "string") { + if (isNativeSubagentControlTool(block.name)) { + this.registerLaunch(block.id, inputOf(block), ownerSessionId); + } else if (block.name === "SendMessage") { + const input = inputOf(block); + if (typeof input.to === "string" && typeof input.message === "string") { + this.sendMessages.push({ + toolUseId: block.id, + to: input.to, + message: input.message, + senderSessionId: ownerSessionId, + delivered: false, + }); + } + } + } else if (block.type === "tool_result" && typeof block.tool_use_id === "string") { + 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) { + child.launchEnd = replaySubagentTerminalState(block); + } + } + } + } + } + + /** The child that the tool use `toolUseId` launched, when the replay shows it. */ + childOfLaunch(toolUseId: string): ReplayChild | undefined { + return this.children.get(toolUseId); + } + + /** Announces `child` on its parent, as live: running, with the parent's labels. */ + async announce(child: ReplayChild): Promise { + if (child.announced) return; + const labels = rfdLabels( + child.record.name ?? child.input.name, + child.record.agentType ?? child.input.subagent_type, + child.record.description ?? child.input.description, + ); + await this.publish({ + sessionId: child.parentSessionId, + update: { + sessionUpdate: "subagent_update", + sessionId: child.sessionId, + ...(labels.title ? { title: labels.title } : {}), + ...(labels.description ? { description: labels.description } : {}), + state: { state: "running" }, + }, + }); + child.announced = true; + } + + /** + * The rest of a child's user message to replay, or `null` when nothing is + * left, after its text went out as the child's incoming `session_message`. + * + * A child session has no user, so the text of its user messages is never a + * user message. The first text is the prompt of the launch. A message that + * a SendMessage call delivered (`origin.kind: "coordinator"`) is another + * incoming message. Any other text is harness text, such as "[Request + * interrupted by user for tool use]", which the live child session does not + * show. Tool results stay. + */ + async childContent( + child: ReplayChild, + message: SessionMessage, + content: unknown, + ): Promise { + const text = textOf(content); + if (text.trim()) { + if (isDelivery(message)) await this.sendDelivery(child, message, text); + else if (!child.promptSent) await this.sendPrompt(child, text); + } + if (!Array.isArray(content)) return null; + const rest = content.filter( + (block) => !(typeof block === "object" && block !== null && block.type === "text"), + ); + return rest.length > 0 ? rest : null; + } + + /** + * Ends the replay of `child`'s history. `messages` is its transcript: when + * it is empty, the replay has only the child's association, and the prompt + * comes from the launch call. + */ + async childReplayed(child: ReplayChild, messages: readonly SessionMessage[]): Promise { + if (messages.length === 0) this.withoutHistory++; + if (!child.promptSent && typeof child.input.prompt === "string") { + await this.sendPrompt(child, child.input.prompt); + } + } + + /** + * Takes a persisted task notification. Returns whether it was a child's: + * its task id is the agent id. + */ + taskNotification(taskId: string, status: string): boolean { + const child = this.byAgentId.get(taskId); + if (!child) return false; + child.notified = nativeSubagentState(status) ?? child.notified; + return true; + } + + /** + * Sends the end of every announced child, and a notice when subagent history + * is missing. The end is the state of the child's last task notification, + * else `cancelled` for a child the user stopped, else the result of its + * foreground launch, else `idle` with no stop reason. + */ + async finish(supportsNotices: boolean, rootSessionId: string): Promise { + for (const child of [...this.children.values()].reverse()) { + if (!child.announced) continue; + const end = child.notified ?? (child.record.stoppedByUser ? "cancelled" : child.launchEnd); + const state: WorkState = end ? rfdEndState(end, undefined) : { state: "idle" }; + await this.publish({ + sessionId: child.parentSessionId, + update: { sessionUpdate: "subagent_update", sessionId: child.sessionId, state }, + }); + } + const missing = this.omitted.size + this.withoutHistory; + if (missing > 0 && supportsNotices) { + await this.publish({ + sessionId: rootSessionId, + update: noticeUpdate({ + severity: "info", + title: "Some subagent history is not available", + description: + missing === 1 + ? "The history of 1 subagent of this session could not be restored." + : `The history of ${missing} subagents of this session could not be restored.`, + }), + }); + } + } + + private registerLaunch( + toolUseId: string, + input: Record, + parentSessionId: string, + ): void { + if (this.children.has(toolUseId)) return; + const record = this.history.agents.get(toolUseId); + if (!record) { + this.omitted.add(toolUseId); + return; + } + const child: ReplayChild = { + launchId: toolUseId, + sessionId: record.agentId, + record, + parentSessionId, + input, + announced: false, + promptSent: false, + }; + this.children.set(toolUseId, child); + this.byAgentId.set(record.agentId, child); + } + + /** The prompt of the launch, with the launch's id, as live. */ + private async sendPrompt(child: ReplayChild, text: string): Promise { + child.promptSent = true; + await this.sendMessage(child, child.launchId, text, child.parentSessionId); + } + + /** + * A message that a SendMessage call delivered. Claude Code frames it for the + * child's model ("The coordinator sent a message while you were working:", + * then the message, then an instruction), so the call it came from is the + * first undelivered SendMessage to the child whose message the delivered + * text contains. With that call, the message has the call's id and text and + * its sender, as live; without it, its transcript id and the delivered text. + */ + private async sendDelivery( + child: ReplayChild, + message: SessionMessage, + text: string, + ): Promise { + const names = [child.sessionId, child.record.name, child.input.name]; + const call = this.sendMessages.find( + (candidate) => + !candidate.delivered && + names.includes(candidate.to) && + text.includes(candidate.message.trim()), + ); + if (call) { + call.delivered = true; + await this.sendMessage(child, call.toolUseId, call.message, call.senderSessionId); + } else { + await this.sendMessage(child, message.uuid, text, undefined); + } + } + + private async sendMessage( + child: ReplayChild, + messageId: string, + text: string, + sender: string | undefined, + ): Promise { + await this.publish({ + sessionId: child.sessionId, + update: { + sessionUpdate: "session_message", + messageId, + ...(sender ? { senderSessionId: sender } : {}), + recipientSessionId: child.sessionId, + content: [{ type: "text", text }], + }, + }); + } +} + +/** + * The end of a foreground launch from its tool result: an error result that + * names a stop is a cancellation, any other error a failure. + */ +export function replaySubagentTerminalState( + block: Record, +): "completed" | "failed" | "cancelled" { + if (block.is_error !== true) return "completed"; + const text = replayContentText(block.content).toLowerCase(); + return /\b(?:cancelled|canceled|interrupted|stopped|killed)\b/.test(text) + ? "cancelled" + : "failed"; +} + +function replayContentText(value: unknown, seen = new Set()): string { + if (typeof value === "string") return value; + if (typeof value !== "object" || value === null || seen.has(value)) return ""; + seen.add(value); + if (Array.isArray(value)) return value.map((item) => replayContentText(item, seen)).join(" "); + const record = value as Record; + return [record.text, record.content, record.message] + .map((item) => replayContentText(item, seen)) + .filter(Boolean) + .join(" "); +} + +function contentBlocks(message: SessionMessage): Record[] { + const content = (message as { message?: { content?: unknown } }).message?.content; + return Array.isArray(content) + ? content.filter( + (block): block is Record => typeof block === "object" && block !== null, + ) + : []; +} + +function inputOf(block: Record): Record { + return typeof block.input === "object" && block.input !== null + ? (block.input as Record) + : {}; +} + +/** The text of user message content: a string, or its text blocks. */ +function textOf(content: unknown): string { + if (typeof content === "string") return content; + if (!Array.isArray(content)) return ""; + return content + .flatMap((block) => + typeof block === "object" && block !== null && block.type === "text" ? [block.text] : [], + ) + .filter((text): text is string => typeof text === "string") + .join("\n"); +} + +/** A message that a SendMessage call delivered to the child. */ +function isDelivery(message: SessionMessage): boolean { + return (message as { origin?: { kind?: unknown } | null }).origin?.kind === "coordinator"; +} diff --git a/src/tests/acp-agent.test.ts b/src/tests/acp-agent.test.ts index d356e28e..782f1438 100644 --- a/src/tests/acp-agent.test.ts +++ b/src/tests/acp-agent.test.ts @@ -3699,6 +3699,267 @@ describe("subagent transcript replay", () => { } }); + describe("for a client on the subagents RFD", () => { + const sessionId = "22222222-2222-4222-8222-222222222222"; + const lines = (records: object[]) => records.map((r) => JSON.stringify(r)).join("\n") + "\n"; + const base = { + sessionId, + cwd: "/tmp/proj", + version: "2.0.0", + userType: "external", + isSidechain: false, + timestamp: "2026-09-24T00:00:00.000Z", + }; + const user = (uuid: string, content: unknown, extra: object = {}) => ({ + ...base, + type: "user", + uuid, + message: { role: "user", content }, + ...extra, + }); + const assistant = (uuid: string, content: unknown[], extra: object = {}) => ({ + ...base, + type: "assistant", + uuid, + message: { id: `m-${uuid}`, role: "assistant", model: "claude-opus-5", content }, + ...extra, + }); + const toolUse = (id: string, name: string, input: object) => ({ + type: "tool_use", + id, + name, + input, + }); + const toolResult = (id: string, content: string) => ({ + type: "tool_result", + tool_use_id: id, + content, + }); + + /** + * Writes the session's transcripts, replays them to a client on the RFD + * form, and returns each update as ` `. + */ + async function replayRfd( + root: object[], + children: Record, + capabilities: ClientCapabilities = { subagents: {}, session: { notices: {} } }, + ): Promise { + const configDir = await mkdtemp(path.join(os.tmpdir(), "claude-acp-rfd-replay-")); + const originalConfigDir = process.env.CLAUDE_CONFIG_DIR; + process.env.CLAUDE_CONFIG_DIR = configDir; + try { + const directory = path.join(configDir, "projects", "-tmp-proj"); + await mkdir(path.join(directory, sessionId, "subagents"), { recursive: true }); + let parentUuid: string | null = null; + const chain = (records: object[]) => + records.map((record) => { + const linked = { ...record, parentUuid }; + parentUuid = (record as { uuid: string }).uuid; + return linked; + }); + await writeFile(path.join(directory, `${sessionId}.jsonl`), lines(chain(root))); + for (const [agentId, { meta, records }] of Object.entries(children)) { + parentUuid = null; + const sidechain = records.map((record) => ({ ...record, isSidechain: true, agentId })); + await writeFile( + path.join(directory, sessionId, "subagents", `agent-${agentId}.jsonl`), + lines(chain(sidechain)), + ); + await writeFile( + path.join(directory, sessionId, "subagents", `agent-${agentId}.meta.json`), + JSON.stringify(meta), + ); + } + const updates: AcpSessionNotification[] = []; + const agent = new ClaudeAcpAgent( + { + sessionUpdate: async (update: SessionNotification) => + updates.push(update as AcpSessionNotification), + } as unknown as AcpClient, + { log: () => {}, error: () => {} }, + ); + await initializeClient(agent, capabilities); + vi.mocked(getSessionInfo).mockResolvedValueOnce({ cwd: "/tmp/proj" } as any); + await ( + agent as unknown as { replaySessionHistory(sessionId: string): Promise } + ).replaySessionHistory(sessionId); + return updates.flatMap(({ sessionId: target, update }) => { + const on = target === sessionId ? "root" : target; + const u = update as any; + switch (update.sessionUpdate) { + case "subagent_update": + return [`${on} subagent_update ${u.sessionId} ${JSON.stringify(u.state)}`]; + case "session_message": + return [ + `${on} session_message ${u.messageId} from=${u.senderSessionId ?? "-"} ${u.content[0].text}`, + ]; + case "tool_call": + return [`${on} tool_call ${u.toolCallId}`]; + case "notice": + return [`${on} notice ${u.title}: ${u.description}`]; + case "user_message_chunk": + case "agent_message_chunk": + return [`${on} ${update.sessionUpdate} ${u.content.text}`]; + default: + return []; + } + }); + } finally { + if (originalConfigDir === undefined) delete process.env.CLAUDE_CONFIG_DIR; + else process.env.CLAUDE_CONFIG_DIR = originalConfigDir; + await rm(configDir, { recursive: true, force: true }); + } + } + + it("replays each child under its live session id, with its incoming messages, before the response", async () => { + const trace = await replayRfd( + [ + user("u1", "Explore it"), + assistant("a1", [ + toolUse("toolu_agent", "Agent", { + name: "scout", + subagent_type: "Explore", + description: "Explore the code", + prompt: "Look around", + }), + // A launch without a metadata file has no known id. + toolUse("toolu_lost", "Agent", { description: "Lost", prompt: "No file" }), + ]), + user("u2", [toolResult("toolu_agent", "Found it."), toolResult("toolu_lost", "Gone.")]), + assistant("a2", [ + toolUse("toolu_send", "SendMessage", { to: "scout", message: "Check the tests too" }), + ]), + user("u3", [toolResult("toolu_send", "Message sent.")]), + user( + "u4", + "\nabc123\ntoolu_send\ncompleted\n", + { origin: { kind: "task-notification" } }, + ), + assistant("a3", [{ type: "text", text: "Done." }]), + ], + { + abc123: { + meta: { + agentType: "Explore", + name: "scout", + description: "Explore the code", + toolUseId: "toolu_agent", + requestShape: "foreground", + }, + records: [ + user("c1", "Look around"), + assistant("c2", [ + { type: "text", text: "Child report." }, + toolUse("toolu_nested", "Agent", { + name: "helper", + subagent_type: "general-purpose", + description: "Read the spec", + prompt: "Read spec.md", + }), + ]), + user("c3", [toolResult("toolu_nested", "The spec says X.")]), + // Harness text that the live child session does not show. + user("c4", "[Request interrupted by user for tool use]"), + user( + "c5", + "The coordinator sent a message while you were working:\nCheck the tests too\n\nAddress this before completing your current task.", + { isMeta: true, origin: { kind: "coordinator" } }, + ), + assistant("c6", [{ type: "text", text: "Tests pass." }]), + ], + }, + def456: { + meta: { + agentType: "general-purpose", + name: "helper", + description: "Read the spec", + toolUseId: "toolu_nested", + requestShape: "foreground", + }, + records: [user("g1", "Read spec.md"), assistant("g2", [{ type: "text", text: "X." }])], + }, + }, + ); + + expect(trace).toEqual([ + "root user_message_chunk Explore it", + "root tool_call toolu_agent", + "root tool_call toolu_lost", + // The child is announced under its agent id, right after its launch. + 'root subagent_update abc123 {"state":"running"}', + "abc123 session_message toolu_agent from=" + sessionId + " Look around", + "abc123 agent_message_chunk Child report.", + "abc123 tool_call toolu_nested", + // A nested child is announced on the child that launched it. + 'abc123 subagent_update def456 {"state":"running"}', + "def456 session_message toolu_nested from=abc123 Read spec.md", + "def456 agent_message_chunk X.", + // The delivered message has the id, text, and sender of its SendMessage call. + "abc123 session_message toolu_send from=" + sessionId + " Check the tests too", + "abc123 agent_message_chunk Tests pass.", + "root tool_call toolu_send", + "root agent_message_chunk Done.", + // Every end comes before the response. + 'abc123 subagent_update def456 {"state":"idle","stopReason":"end_turn"}', + 'root subagent_update abc123 {"state":"idle","stopReason":"end_turn"}', + "root notice Some subagent history is not available: The history of 1 subagent of this session could not be restored.", + ]); + }); + + it("ends a child that the user stopped as cancelled, and one without a known end as idle", async () => { + const trace = await replayRfd( + [ + user("u1", "Run them"), + assistant("a1", [ + toolUse("toolu_stopped", "Agent", { prompt: "Sleep", run_in_background: true }), + toolUse("toolu_open", "Agent", { prompt: "Wait", run_in_background: true }), + ]), + // A background launch answers at once: its result is not the end. + user("u2", [ + toolResult("toolu_stopped", "Async agent launched successfully."), + toolResult("toolu_open", "Async agent launched successfully."), + ]), + ], + { + stopped1: { + meta: { toolUseId: "toolu_stopped", requestShape: "background", stoppedByUser: true }, + records: [user("s1", "Sleep")], + }, + open1: { + meta: { toolUseId: "toolu_open", requestShape: "background" }, + records: [user("o1", "Wait")], + }, + }, + ); + + expect(trace.filter((line) => line.includes("idle"))).toEqual([ + 'root subagent_update open1 {"state":"idle"}', + 'root subagent_update stopped1 {"state":"idle","stopReason":"cancelled"}', + ]); + }); + + it("leaves out a subagent message that the session transcript stores inline", async () => { + // The SDK returns such a message with its parent_tool_use_id. + const updates: AcpSessionNotification[] = []; + const agent = new ClaudeAcpAgent( + { + sessionUpdate: async (update: SessionNotification) => + updates.push(update as AcpSessionNotification), + } as unknown as AcpClient, + { log: () => {}, error: () => {} }, + ); + await initializeClient(agent, { subagents: {} } as ClientCapabilities); + vi.mocked(getSessionMessages).mockResolvedValueOnce(replayHistory); + await ( + agent as unknown as { replaySessionHistory(sessionId: string): Promise } + ).replaySessionHistory("s1"); + + // Neither its text nor its tool call reaches the root. + expect(updates).toEqual([]); + }); + }); + it("replays an unattributed sidechain as a deterministic disconnected child", async () => { const updates = await replay("native"); expect(updates.map(({ sessionId, update }) => [sessionId, update.sessionUpdate])).toEqual([ diff --git a/src/tests/acp-scenarios/__snapshots__/v2/session-load-replay.jsonl b/src/tests/acp-scenarios/__snapshots__/v2/session-load-replay.jsonl index aaac669c..655fbeb8 100644 --- a/src/tests/acp-scenarios/__snapshots__/v2/session-load-replay.jsonl +++ b/src/tests/acp-scenarios/__snapshots__/v2/session-load-replay.jsonl @@ -16,4 +16,5 @@ {"kind":"notification","method":"session/update","payload":{"sessionId":"","update":{"content":[{"content":{"text":"Report.","type":"text"},"type":"content"}],"rawOutput":"Report.","sessionUpdate":"tool_call_update","status":"completed","toolCallId":"toolu_r_task"}}} {"kind":"notification","method":"session/update","payload":{"sessionId":"","update":{"content":[],"messageId":"msg_r2","sessionUpdate":"agent_message"}}} {"kind":"notification","method":"session/update","payload":{"sessionId":"","update":{"content":{"text":"Fixed.","type":"text"},"messageId":"msg_r2","sessionUpdate":"agent_message_chunk"}}} +{"kind":"notification","method":"session/update","payload":{"sessionId":"","update":{"description":"The history of 1 subagent of this session could not be restored.","sessionUpdate":"notice","severity":"info","title":"Some subagent history is not available"}}} {"kind":"response","method":"session/resume","payload":{"availableCommands":[{"description":"Show the MCP servers and their status, or reconnect, enable, or disable a server","input":{"hint":"[reconnect|enable|disable [|all]]","type":"text"},"name":"mcp"}],"configOptions":[{"category":"mode","configId":"mode","currentValue":"default","description":"Session permission mode","name":"Mode","options":[{"description":"Always ask before making changes","name":"Manual","value":"default"},{"description":"Automatically accept all file edits","name":"Accept edits","value":"acceptEdits"},{"description":"Create a plan before making changes","name":"Plan","value":"plan"},{"description":"Claude handles permission decisions","name":"Auto","value":"auto"},{"description":"Accepts all permissions","name":"Bypass permissions","value":"bypassPermissions"}],"type":"select"},{"category":"model","configId":"model","currentValue":"claude-sonnet-4-6","description":"AI model to use","name":"Model","options":[{"description":"Fast","name":"Claude Sonnet 4.6","value":"claude-sonnet-4-6"}],"type":"select"}]}} diff --git a/src/tests/acp-v2.test.ts b/src/tests/acp-v2.test.ts index 1c12f7d9..9178f5f3 100644 --- a/src/tests/acp-v2.test.ts +++ b/src/tests/acp-v2.test.ts @@ -5,7 +5,7 @@ * schema, so a malformed v2 message fails the test. */ import { randomUUID } from "node:crypto"; -import { mkdtemp, rm, writeFile } from "node:fs/promises"; +import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; import * as os from "node:os"; import * as path from "node:path"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; @@ -922,6 +922,93 @@ describe("ACP v2 prompts", () => { ); }); + it("replays a subagent's history to its own session, and clears each replayed message there first", async () => { + const client = v2Client(); + await client.app.connectWith(connectRouter(), async (agent) => { + await initializeV2(agent); + const { sessionId } = await agent.request(v2.methods.agent.session.new, { cwd }); + // Claude Code keeps the subagent's history in its own transcript, beside + // the session's, with a metadata file that names its launch. + const project = path.join(tempDir, "claude", "projects", "-project"); + const subagents = path.join(project, sessionId, "subagents"); + await mkdir(subagents, { recursive: true }); + const entry = (uuid: string, parentUuid: string | null, message: unknown, sidechain = true) => + JSON.stringify({ + type: (message as { role: string }).role, + uuid, + parentUuid, + sessionId, + cwd, + version: "2.0.0", + isSidechain: sidechain, + ...(sidechain ? { agentId: "abc123" } : {}), + userType: "external", + timestamp: "2026-09-24T00:00:00.000Z", + message, + }); + await writeFile( + path.join(project, `${sessionId}.jsonl`), + entry("r1", null, { role: "user", content: "Explore it" }, false) + "\n", + ); + await writeFile( + path.join(subagents, "agent-abc123.jsonl"), + [ + entry("c1", null, { role: "user", content: "Look around" }), + entry("c2", "c1", { + id: "msg_child", + role: "assistant", + model: "claude-haiku-4-5", + content: [{ type: "text", text: "Child report." }], + }), + ].join("\n") + "\n", + ); + await writeFile( + path.join(subagents, "agent-abc123.meta.json"), + JSON.stringify({ agentType: "Explore", name: "scout", toolUseId: "toolu_agent" }), + ); + vi.mocked(getSessionMessages).mockResolvedValueOnce([ + transcriptEntry("assistant", randomUUID(), { + id: "msg_agent", + role: "assistant", + content: [ + { + type: "tool_use", + id: "toolu_agent", + name: "Agent", + input: { name: "scout", subagent_type: "Explore", prompt: "Look around" }, + }, + ], + }), + transcriptEntry("user", randomUUID(), { + role: "user", + content: [{ type: "tool_result", tool_use_id: "toolu_agent", content: "Found it." }], + }), + ] as unknown as Awaited>); + await agent.request(v2.methods.agent.session.resume, { + sessionId, + cwd, + replayFrom: { type: "start" }, + }); + await client.authUpdate(1); + }); + + const child = client.sessionUpdates.flatMap(({ sessionId, update }) => + sessionId === "abc123" ? [update] : [], + ); + expect(child).toEqual([ + { sessionUpdate: "state_update", state: "running" }, + expect.objectContaining({ sessionUpdate: "session_message", content: text("Look around") }), + // The client may still hold the child's message, so the replay clears it. + { sessionUpdate: "agent_message", messageId: "msg_child", content: [] }, + expect.objectContaining({ + sessionUpdate: "agent_message_chunk", + messageId: "msg_child", + content: text("Child report.")[0], + }), + { sessionUpdate: "state_update", state: "idle", stopReason: "end_turn" }, + ]); + }); + it("replays the plan of an approved ExitPlanMode as a markdown plan", async () => { const client = v2Client(); await client.app.connectWith(connectRouter(), async (agent) => { diff --git a/src/v2/agent.ts b/src/v2/agent.ts index 91d9ebd3..c22587ee 100644 --- a/src/v2/agent.ts +++ b/src/v2/agent.ts @@ -152,10 +152,14 @@ async function setupCommands( class V2ClientConnection implements AcpClient { /** * The sessions whose history replays, each with the messages that the - * replay has cleared so far. + * replay has cleared so far. A subagent that a replay announces replays + * with it. */ private readonly replays = new Map>(); + /** The session whose replay announced each replaying subagent. */ + private readonly replayRoots = new Map(); + /** The display terminals of the commands that the agent runs. */ readonly terminals = new V2Terminals(); @@ -181,6 +185,11 @@ class V2ClientConnection implements AcpClient { return await restore(); } finally { this.replays.delete(sessionId); + for (const [child, root] of this.replayRoots) { + if (root !== sessionId) continue; + this.replays.delete(child); + this.replayRoots.delete(child); + } } } @@ -207,6 +216,19 @@ class V2ClientConnection implements AcpClient { } async sessionUpdate({ update, ...notification }: AcpSessionNotification): Promise { + // A subagent that a replay announces replays too, so its messages are + // cleared before their first replayed chunk, as the parent's are. + if ( + update.sessionUpdate === "subagent_update" && + this.replays.has(notification.sessionId) && + !this.replays.has(update.sessionId) + ) { + this.replays.set(update.sessionId, new Set()); + this.replayRoots.set( + update.sessionId, + this.replayRoots.get(notification.sessionId) ?? notification.sessionId, + ); + } const updates = this.v2Updates(notification.sessionId, update).flatMap((v2Update) => { const clear = this.replayClear(notification.sessionId, v2Update); return clear ? [clear, v2Update] : [v2Update];