diff --git a/docs/subagent-sessions.md b/docs/subagent-sessions.md index 345f773c..43d39bd8 100644 --- a/docs/subagent-sessions.md +++ b/docs/subagent-sessions.md @@ -92,6 +92,11 @@ Task subagent as its own child session, following ACP's [subagents](https://agen session messages and `session` references as live, and its end is an `idle` before the response. Each replayed child's current state follows the response: on v1, the response is what separates a replayed child state from a current one. + A replay sends no `config_option_update` of a child, since one that arrives before the response + is a past value to the client. Each replayed child's configuration follows its current state: + the configuration of a child that still runs, else its `model` option with the model of the + latest response in its transcript, as the session's `model` option names it. A child that + 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. - After a load or resume, with or without replay, a SendMessage that resumes an agent from before @@ -114,7 +119,9 @@ after the parent's copy. A replay ends each child's history with a `replay_compl session. On v2, the parent's `replay_complete` is what separates a replayed child state from a current one, so each replayed child's current state follows the root session's `replay_complete` and comes before the response: on its parent, with the cleared `cwd`, and then as the child's own -`idle`. The notice that subagent history is missing follows the root's `replay_complete` too. +`idle`. The child's configuration follows it there, since v2 asks an agent not to replay a past +`config_option_update`. The notice that subagent history is missing follows the root's +`replay_complete` too. 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 diff --git a/src/subagent-replay.ts b/src/subagent-replay.ts index ab650117..05adf55f 100644 --- a/src/subagent-replay.ts +++ b/src/subagent-replay.ts @@ -25,11 +25,12 @@ * replayed child by its agent id carries the RFD's `session` reference to it * (`ReplayTranscript.withTarget`). * - * Right after its announcement, each child gets its `model` option: the model - * of its first response, in its transcript. A later response with another - * model sends it again. A child without responses gets none. After the load - * response, a model goes again only when the session's model list, which the - * replay can lack, maps it to another entry. + * The replay sends no `config_option_update` of a child: one that arrives + * before the load response is a past value to the client. Each child's + * configuration goes out after the response, with its current state + * (`currentStates`): the configuration of a child that still runs in this + * process, else the `model` option with the model of the latest response in + * its transcript. A child that neither runs nor has a response gets none. * * 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 @@ -46,7 +47,6 @@ import { isNativeSubagentControlTool, launchReply, linkedSessionMessages, - type ModelEntry, nativeSubagentState, responseModelEntry, rfdEndState, @@ -83,8 +83,6 @@ export type ReplayChild = { promptSent: boolean; /** Whether it handed a report to its parent with a SubagentHandback call. */ handedBack?: boolean; - /** The `model` option entry that the replay sent. */ - model?: ModelEntry; /** The model id of the latest response in its transcript. */ responseModel?: string; }; @@ -219,13 +217,12 @@ export class RfdSubagentReplay { constructor( private readonly history: SubagentHistory, private readonly publish: Publish, - private readonly models?: SubagentModels, /** - * Whether the replay maps a model to the session's model list as it goes. - * A load lacks the list until the CLI started, so it maps only in - * {@link currentStates}, after the load response. + * The session's model list, which {@link currentStates} maps each child's + * model to. A load can lack the list until the CLI started, so it is read + * after the load response. */ - private readonly mapsDuringReplay = true, + private readonly models?: SubagentModels, /** The working directory of the root session, which a child inherits unless it reports its own. */ private readonly rootCwd?: string, ) { @@ -253,10 +250,8 @@ export class RfdSubagentReplay { /** * Announces `child` on its parent, as live: running, with the parent's * labels, and with its recorded `cwd` when that differs from its parent's. - * Then it sends `firstModel`, the model of the child's first response, when - * the transcript has one. */ - async announce(child: ReplayChild, firstModel?: string): Promise { + async announce(child: ReplayChild): Promise { if (child.announced) return; const labels = rfdLabels( child.record.name ?? child.input.name, @@ -282,7 +277,6 @@ export class RfdSubagentReplay { }); child.cwd = cwd; child.announced = true; - await this.responseModel(child, firstModel); } /** @@ -300,27 +294,9 @@ export class RfdSubagentReplay { return this.rootCwd; } - /** - * Takes the model of a replayed response of the child `owner`. A child - * whose model changes gets its `model` option again. - */ - async responseModel(owner: ReplayChild, model: string | undefined): Promise { - const entry = responseModelEntry(model, this.mapsDuringReplay ? this.models : undefined); - if (!entry || !owner.announced) return; - owner.responseModel = model; - await this.sendModel(owner, entry); - } - - private async sendModel(child: ReplayChild, model: ModelEntry): Promise { - if (child.model?.value === model.value && child.model.name === model.name) return; - child.model = model; - await this.publish({ - sessionId: child.sessionId, - update: { - sessionUpdate: "config_option_update", - configOptions: [childModelOption(model)], - }, - }); + /** Takes the model of a replayed response of the child `owner` (see {@link trackResponseModel}). */ + responseModel(owner: ReplayChild, model: string | undefined): void { + trackResponseModel(owner, model); } /** @@ -463,10 +439,10 @@ export class RfdSubagentReplay { } /** - * The current state of each announced child, to send after the load - * response. The RFD makes that response the freshness boundary: a client - * treats the replayed states before it as history, so they show no current - * activity and allow no cancel. + * The current state and configuration of each announced child, to send + * after the load response. The RFD makes that response the freshness + * boundary: a client treats the replayed states before it as history, so + * they show no current activity and allow no cancel. * * `live` gives the work state of a child that still runs in this process, as * when a live session is loaded again. Such a child reports that state and @@ -476,6 +452,10 @@ export class RfdSubagentReplay { * A replayed `cwd` whose directory is gone, such as a worktree that Claude * Code removed when the child finished, is cleared with `cwd: null`, as the * RFD requires after a reconnection. + * + * Each child's configuration follows its state (see + * {@link currentChildConfiguration}). `liveConfiguration` gives the one + * that the client last got for a child that still runs in this process. */ currentStates( live: (sessionId: string) => WorkState["state"] | undefined, @@ -489,13 +469,11 @@ export class RfdSubagentReplay { liveState === undefined || liveState === "idle" ? replayEndState(child) : { state: liveState }; - // The session's model list may be known only now, after the load response. - const entry = responseModelEntry(child.responseModel, this.models); - const replayed = child.model ? JSON.stringify([childModelOption(child.model)]) : undefined; - const current = - liveConfiguration?.(child.sessionId) ?? (entry ? [childModelOption(entry)] : undefined); - // A configuration that the replay already sent does not go again. - const configOptions = current && JSON.stringify(current) !== replayed ? current : undefined; + const configOptions = currentChildConfiguration( + child, + liveConfiguration?.(child.sessionId), + this.models, + ); return [ { sessionId: child.parentSessionId, @@ -584,14 +562,38 @@ export class RfdSubagentReplay { } } -/** The model of the first response in `messages`, a subagent's transcript. */ -export function firstResponseModel(messages: readonly SessionMessage[]): string | undefined { - for (const message of messages) { - if (message.type !== "assistant") continue; - const model = (message.message as { model?: unknown } | undefined)?.model; - if (typeof model === "string" && model && model !== "") return model; +/** + * Takes `model`, the model id of a replayed response of `child`. The latest + * one is the child's model after the replay (see + * {@link currentChildConfiguration}). A response without a model id, or with + * ``, which marks a message that no model wrote, changes nothing. + */ +export function trackResponseModel(child: ReplayChild, model: unknown): void { + if (typeof model === "string" && responseModelEntry(model, undefined)) { + child.responseModel = model; } - return undefined; +} + +/** + * The configuration of the replayed `child` to send once the replay is over: + * after the load response on v1, after the root's `replay_complete` on v2. A + * child's `config_option_update` inside a replay is a past value to the + * client, so the replay sends none, and this one goes also when the client + * held the same configuration before. + * + * `live` is the configuration that the client last got for a child that still + * runs in this process. Any other child gets its `model` option, with the + * model of the latest response in its transcript, as the session's model list + * `models` names it. Undefined for such a child without responses. + */ +export function currentChildConfiguration( + child: ReplayChild, + live: SessionConfigOption[] | undefined, + models: SubagentModels | undefined, +): SessionConfigOption[] | undefined { + if (live) return live; + const entry = responseModelEntry(child.responseModel, models); + return entry ? [childModelOption(entry)] : undefined; } /** diff --git a/src/tests/v1/acp-agent.test.ts b/src/tests/v1/acp-agent.test.ts index 1b2445fd..5165601e 100644 --- a/src/tests/v1/acp-agent.test.ts +++ b/src/tests/v1/acp-agent.test.ts @@ -4104,6 +4104,8 @@ describe("subagent transcript replay", () => { capabilities: ClientCapabilities = { subagents: {}, session: { notices: {} } }, afterResponse?: { live: (childSessionId: string) => string | undefined; + /** The configuration that the client last got for a child that still runs. */ + configuration?: (childSessionId: string) => SessionConfigOption[] | undefined; /** The session's config options and model list, known after the response. */ models?: { configOptions: SessionConfigOption[]; modelInfos: ModelInfo[] }; }, @@ -4171,7 +4173,10 @@ describe("subagent transcript replay", () => { if (afterResponse) { // Stands in for the live session's runtime, which knows its running children. (agent.sessions as Record)[sessionId] = { - nativeSubagentRuntime: { liveWorkState: afterResponse.live }, + nativeSubagentRuntime: { + liveWorkState: afterResponse.live, + configurationOf: afterResponse.configuration, + }, configOptions: afterResponse.models?.configOptions ?? [], modelInfos: afterResponse.models?.modelInfos ?? [], }; @@ -4510,7 +4515,7 @@ describe("subagent transcript replay", () => { ]); }); - it("sends the model of each child's responses, and after the load response only a changed entry", async () => { + it("sends no child configuration in the replay, and each child's current one after the load response", async () => { const launch = (id: string, name: string, input: object = {}) => toolUse(id, "Agent", { name, @@ -4533,6 +4538,14 @@ describe("subagent transcript replay", () => { toolUseId: launchId, requestShape: "foreground", }); + const haikuOption: SessionConfigOption = { + id: "model", + name: "Model", + category: "model", + type: "select", + currentValue: "haiku", + options: [{ value: "haiku", name: "Haiku 4.5" }], + }; const trace = await replayRfd( [ user("u1", "Go"), @@ -4540,11 +4553,13 @@ describe("subagent transcript replay", () => { launch("toolu_answered", "answered"), launch("toolu_unlisted", "unlisted", { model: "haiku" }), launch("toolu_silent", "silent"), + launch("toolu_live", "live"), ]), user("u2", [ toolResult("toolu_answered", "Done."), toolResult("toolu_unlisted", "Done."), toolResult("toolu_silent", "Done."), + toolResult("toolu_live", "Done."), ]), ], { @@ -4553,8 +4568,9 @@ describe("subagent transcript replay", () => { records: [ user("x1", "Run answered"), answer("x2", "claude-haiku-4-5", "First."), - answer("x3", "claude-haiku-4-5", "Same model."), - answer("x4", "claude-opus-5", "Fallback."), + answer("x3", "claude-opus-5", "Fallback."), + // No model wrote this message, so it is not the child's model. + answer("x4", "", "API Error"), ], }, // A model that the session's list does not have. @@ -4564,10 +4580,17 @@ describe("subagent transcript replay", () => { }, // No response: the replay does not guess the launch input's or the parent's model. ccc333: { meta: meta("silent", "toolu_silent"), records: [user("z1", "Run silent")] }, + // Still runs in this process, on another model than its stored response. + ddd444: { + meta: meta("live", "toolu_live"), + records: [user("w1", "Run live"), answer("w2", "claude-opus-5", "Working.")], + }, }, undefined, { - live: () => undefined, + live: (childSessionId) => (childSessionId === "ddd444" ? "running" : undefined), + configuration: (childSessionId) => + childSessionId === "ddd444" ? [haikuOption] : undefined, models: { configOptions: [ { @@ -4602,25 +4625,35 @@ describe("subagent transcript replay", () => { ); const opus = JSON.stringify([{ value: "opus", name: "Opus 5" }]); + const haiku = JSON.stringify([{ value: "haiku", name: "Haiku 4.5" }]); const raw = (model: string) => JSON.stringify([{ value: model, name: model }]); - expect(trace.filter((line) => / (model|subagent_update) /.test(line))).toEqual([ - // During the replay the session has no model list yet, so the model is the id. + const idle = '{"state":"idle","stopReason":"end_turn"}'; + expect( + trace.filter((line) => / (model|subagent_update) /.test(line) || line.startsWith("--")), + ).toEqual([ + // A configuration before the response is a past value to the client: + // the replay sends none. 'root subagent_update aaa111 {"state":"running"}', - `aaa111 model claude-haiku-4-5 ${raw("claude-haiku-4-5")}`, - // A response on another model sends the model again; the same model does not. - `aaa111 model claude-opus-5 ${raw("claude-opus-5")}`, 'root subagent_update bbb222 {"state":"running"}', - `bbb222 model claude-fable-9 ${raw("claude-fable-9")}`, 'root subagent_update ccc333 {"state":"running"}', - 'root subagent_update ccc333 {"state":"idle","stopReason":"end_turn"}', - 'root subagent_update bbb222 {"state":"idle","stopReason":"end_turn"}', - 'root subagent_update aaa111 {"state":"idle","stopReason":"end_turn"}', - // After the response, a model goes again only when the root session's - // `model` option maps it to another entry. - 'root subagent_update aaa111 {"state":"idle","stopReason":"end_turn"}', + 'root subagent_update ddd444 {"state":"running"}', + `root subagent_update ddd444 ${idle}`, + `root subagent_update ccc333 ${idle}`, + `root subagent_update bbb222 ${idle}`, + `root subagent_update aaa111 ${idle}`, + "-- response --", + // The model of the latest response, as the root session's `model` + // option names it. + `root subagent_update aaa111 ${idle}`, `aaa111 model opus ${opus}`, - 'root subagent_update bbb222 {"state":"idle","stopReason":"end_turn"}', - 'root subagent_update ccc333 {"state":"idle","stopReason":"end_turn"}', + // A model that the option does not list is its id. + `root subagent_update bbb222 ${idle}`, + `bbb222 model claude-fable-9 ${raw("claude-fable-9")}`, + `root subagent_update ccc333 ${idle}`, + // A child that still runs gets the configuration that the live session + // last sent for it, not its stored response's model. + 'root subagent_update ddd444 {"state":"running"} capabilities={"cancel":{}}', + `ddd444 model haiku ${haiku}`, ]); }); diff --git a/src/tests/v2/acp-v2.test.ts b/src/tests/v2/acp-v2.test.ts index 81e97701..5913eb91 100644 --- a/src/tests/v2/acp-v2.test.ts +++ b/src/tests/v2/acp-v2.test.ts @@ -2633,16 +2633,9 @@ describe("ACP v2 prompts", () => { // The child's past `running` does not replay. Its current state goes // once, after its own `replay_complete` and before the response: its // process is gone, so it is idle. - // The child's model, from its transcript, goes right after its - // announcement. It does not go again after the replay: it is unchanged. - const model = expect.objectContaining({ - sessionUpdate: "config_option_update", - configOptions: [ - expect.objectContaining({ configId: "model", currentValue: "claude-haiku-4-5" }), - ], - }); + // Its configuration is no history either: v2 asks an agent not to replay + // a past `config_option_update`, so it follows the current state. expect(child).toEqual([ - model, 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: [] }, @@ -2653,6 +2646,7 @@ describe("ACP v2 prompts", () => { }), { sessionUpdate: "replay_complete" }, { sessionUpdate: "state_update", state: "idle", stopReason: "end_turn", background: [] }, + expect.objectContaining({ sessionUpdate: "config_option_update" }), { sessionUpdate: "response" }, ]); // On the parent, the child's states before the parent's `replay_complete` @@ -2681,7 +2675,7 @@ describe("ACP v2 prompts", () => { ).toEqual([]); }); - it("replays a SendMessage call's delivery, a hand-back and a child's model change as live", async () => { + it("replays a SendMessage call's delivery and a hand-back as live", async () => { scriptTurns(); const client = v2Client(); let root = ""; @@ -2795,17 +2789,6 @@ describe("ACP v2 prompts", () => { "root toolu_send root -> abc123", ]); expect(client.updates("tool_call_update")).toEqual([]); - // The child's model goes again when a response changes it. - expect( - client.sessionUpdates.flatMap(({ sessionId, update }) => - sessionId === "abc123" && update.sessionUpdate === "config_option_update" - ? [(update as { configOptions: Array<{ currentValue: unknown }> }).configOptions[0]!] - : [], - ), - ).toEqual([ - expect.objectContaining({ currentValue: "claude-haiku-4-5" }), - expect.objectContaining({ currentValue: "claude-sonnet-4-6" }), - ]); // The client cannot fork a child, so the messages a child received get no cursor. expect(client.updates("cursor_update")).toEqual([]); }); @@ -6622,7 +6605,7 @@ describe("ACP v2 requests that subagents make", () => { }); }); - it("sends a live child's configuration again after a replay, when the replay sent another", async () => { + it("sends a live child's configuration after a replay, not the model of its stored response", async () => { scriptTurns(async function* (options) { yield toolUseMessage(options, "toolu_agent-1", "Agent", { description: "Explore the project", @@ -6708,11 +6691,10 @@ describe("ACP v2 requests that subagents make", () => { .join(" "), ]; }); - // The replay sends the model of the child's response. The live child's - // configuration has its mode too, so it goes again after the replay, - // before the response. + // The live session's configuration of the child has its mode and agent + // too. It goes once, after the replay and before the response: the + // client may not show what it held before the resume. expect(configurations).toEqual([ - "model=claude-sonnet-4-6", "model=claude-sonnet-4-6 mode=acceptEdits agent=Explore", "response", ]); @@ -6727,73 +6709,87 @@ describe("ACP v2 requests that subagents make", () => { expect(states).toEqual(["idle", "response"]); }); - it("names a replayed child's model by the session's model list, on a resume of a closed session", async () => { - scriptTurns(); - const client = v2Client(); - await client.app.connectWith(connectRouter(), async (agent) => { - await initializeV2(agent); - const { sessionId } = await agent.request(v2.methods.agent.session.new, { cwd }); - await agent.request(v2.methods.agent.session.close, { sessionId }); - await writeSubagentHistory( - sessionId, - [transcriptRecord(sessionId, "r1", null, { role: "user", content: "hi" })], - "agent-1", - { agentType: "Explore", toolUseId: "toolu_agent-1" }, - [ - transcriptRecord(sessionId, "c1", null, { role: "user", content: "Look around" }), - transcriptRecord(sessionId, "c2", "c1", { - id: "msg_child", - role: "assistant", - model: "claude-sonnet-4-6", - content: [{ type: "text", text: "Done." }], - }), - ], - ); - vi.mocked(getSessionMessages).mockResolvedValueOnce([ - transcriptEntry("assistant", randomUUID(), { - id: "msg_agent", - role: "assistant", - content: [ - { - type: "tool_use", - id: "toolu_agent-1", - name: "Agent", - input: { subagent_type: "Explore", prompt: "Look around" }, - }, + it.each([ + { + // The latest response's model, as the session's model list names it. + name: "its latest response's model", + responses: ["claude-haiku-4-5", "claude-sonnet-4-6"], + expected: ["claude-sonnet-4-6 Claude Sonnet 4.6", "response"], + }, + // The replay does not guess the launch input's or the parent's model. + { name: "none without a response", responses: [], expected: ["response"] }, + ])( + "sends a replayed child's configuration on a resume of a closed session: $name", + async ({ responses, expected }) => { + scriptTurns(); + const client = v2Client(); + await client.app.connectWith(connectRouter(), async (agent) => { + await initializeV2(agent); + const { sessionId } = await agent.request(v2.methods.agent.session.new, { cwd }); + await agent.request(v2.methods.agent.session.close, { sessionId }); + await writeSubagentHistory( + sessionId, + [transcriptRecord(sessionId, "r1", null, { role: "user", content: "hi" })], + "agent-1", + { agentType: "Explore", toolUseId: "toolu_agent-1" }, + [ + transcriptRecord(sessionId, "c1", null, { role: "user", content: "Look around" }), + ...responses.map((model, index) => + transcriptRecord(sessionId, `a${index}`, index === 0 ? "c1" : `a${index - 1}`, { + id: `msg_child_${index}`, + role: "assistant", + model, + content: [{ type: "text", text: "Done." }], + }), + ), ], - }), - transcriptEntry("user", randomUUID(), { - role: "user", - content: [{ type: "tool_result", tool_use_id: "toolu_agent-1", content: "Done." }], - }), - ] as unknown as Awaited>); - await agent.request(v2.methods.agent.session.resume, { - sessionId, - cwd, - replayFrom: { type: "start" }, + ); + vi.mocked(getSessionMessages).mockResolvedValueOnce([ + transcriptEntry("assistant", randomUUID(), { + id: "msg_agent", + role: "assistant", + content: [ + { + type: "tool_use", + id: "toolu_agent-1", + name: "Agent", + input: { subagent_type: "Explore", prompt: "Look around" }, + }, + ], + }), + transcriptEntry("user", randomUUID(), { + role: "user", + content: [{ type: "tool_result", tool_use_id: "toolu_agent-1", content: "Done." }], + }), + ] as unknown as Awaited>); + await agent.request(v2.methods.agent.session.resume, { + sessionId, + cwd, + replayFrom: { type: "start" }, + }); + client.sessionUpdates.push({ + sessionId: "agent-1", + update: { sessionUpdate: "response" }, + } as never); + await client.authUpdate(1); }); - client.sessionUpdates.push({ - sessionId: "agent-1", - update: { sessionUpdate: "response" }, - } as never); - await client.authUpdate(1); - }); - const models = client.sessionUpdates.flatMap(({ sessionId, update }) => { - if (sessionId !== "agent-1") return []; - if (update.sessionUpdate === "response") return ["response"]; - if (update.sessionUpdate !== "config_option_update") return []; - const [option] = ( - update as { - configOptions: Array<{ currentValue: unknown; options: Array<{ name: string }> }>; - } - ).configOptions; - return [`${option!.currentValue} ${option!.options[0]!.name}`]; - }); - // The core replays after Claude Code started, so the model goes as the - // model list's entry at once. - expect(models).toEqual(["claude-sonnet-4-6 Claude Sonnet 4.6", "response"]); - }); + const models = client.sessionUpdates.flatMap(({ sessionId, update }) => { + if (sessionId !== "agent-1") return []; + if (update.sessionUpdate === "response") return ["response"]; + if (update.sessionUpdate !== "config_option_update") return []; + const [option] = ( + update as { + configOptions: Array<{ currentValue: unknown; options: Array<{ name: string }> }>; + } + ).configOptions; + return [`${option!.currentValue} ${option!.options[0]!.name}`]; + }); + // After the replay, when Claude Code has started: the session's model + // list is known. + expect(models).toEqual(expected); + }, + ); it("references a replayed child from a TaskStop call that names it by its agent id", async () => { scriptTurns(); diff --git a/src/v1/acp-agent.ts b/src/v1/acp-agent.ts index 52326ea2..e7bcc233 100644 --- a/src/v1/acp-agent.ts +++ b/src/v1/acp-agent.ts @@ -228,7 +228,6 @@ import { import { type ReplayChild, RfdSubagentReplay, - firstResponseModel, replaySubagentTerminalState, } from "../subagent-replay.js"; import { @@ -1676,7 +1675,8 @@ export class ClaudeAcpAgent { toolUseWaitMs: number = TOOL_USE_WAIT_MS; /** * The subagent replay of each session's last load, until - * {@link publishCurrentSubagentStates} sends its children's current states. + * {@link publishCurrentSubagentStates} sends its children's current states + * and configurations. */ private readonly replayedSubagents = new Map(); /** @@ -8221,7 +8221,6 @@ export class ClaudeAcpAgent { rfdHistory, (notification) => this.client.sessionUpdate(asSdkSessionNotification(notification)), this.subagentModels(sessionId), - !pending, session?.cwd, ) : undefined; @@ -8348,7 +8347,7 @@ export class ClaudeAcpAgent { if (message.type === "assistant") { const model = (message.message as { model?: string }).model; if (rfdReplay && child) { - await rfdReplay.responseModel(child, model); + rfdReplay.responseModel(child, model); } else if (nativeReplayEnabled && parentToolUseId) { // AIR's draft: the entry of the model list that is known now. A load // can lack the list until the CLI started, so the entry goes again @@ -8494,7 +8493,7 @@ export class ClaudeAcpAgent { rfdHistory, this.logger, ); - await rfdReplay.announce(launched, firstResponseModel(childMessages)); + await rfdReplay.announce(launched); rfdReplay.scan(childMessages, launched.sessionId); for (const childMessage of childMessages) await replayMessage(childMessage, launched); await rfdReplay.childReplayed(launched, childMessages); @@ -9479,10 +9478,10 @@ export class ClaudeAcpAgent { } /** - * Sends the current state 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 subagent states - * as history. + * 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. */ async publishCurrentSubagentStates(sessionId: string): Promise { await this.publishReplayedChildModels(sessionId); diff --git a/src/v2/subagent-replay.ts b/src/v2/subagent-replay.ts index 16cca3ea..8e3e4e54 100644 --- a/src/v2/subagent-replay.ts +++ b/src/v2/subagent-replay.ts @@ -6,13 +6,12 @@ * metadata file names the Agent or Task call that launched it (see * `subagentHistory`). The replay announces each child right after that call, * under its live session id (the agent id), with no capabilities: it cannot - * run again in this process. Then it sends the child's `model` (of its first - * response) and its history to the child session; a later response with - * another model sends it again. As live, the parent is not shown the launch - * call: its prompt is the parent's outgoing message, and a foreground child's - * answer its reply. A child's successful SubagentHandback call is its message - * to the parent instead. Unlike live, the replay does not tell runs apart, so - * a child that handed back any report gets no reply from its launch's result. + * run again in this process. Then it sends the child's history to the child + * session. As live, the parent is not shown the launch call: its prompt is + * the parent's outgoing message, and a foreground child's answer its reply. A + * child's successful SubagentHandback call is its message to the parent + * instead. Unlike live, the replay does not tell runs apart, so a child that + * handed back any report gets no reply from its launch's result. * * A SendMessage call whose message the replay delivered to a child before it * reached the call is that message too: the sender's outgoing view, at the @@ -32,9 +31,12 @@ * ({@link currentStates}): on its parent and on its own stream. A child that * works in the live session, on a resume of the active session, gets its * current state from the resume snapshot instead - * (`SessionTasks.currentState`). A child whose configuration is not the - * `model` that the replay sent, such as a live child whose hooks reported its - * mode, gets it again then too. + * (`SessionTasks.currentState`). + * + * The replay sends no `config_option_update` of a child: v2 asks an agent not + * to replay a past one. Each child's configuration goes out after the root's + * `replay_complete` too, following the child's current state (see + * `currentChildConfiguration`). * * 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 @@ -47,11 +49,9 @@ import type { SessionMessage } from "@anthropic-ai/claude-agent-sdk"; import type { Logger } from "../logger.js"; import type { AcpSessionNotification } from "../acp-subagents.js"; import { - childModelOption, launchReply, linkedSessionMessages, nativeSubagentState, - responseModelEntry, rfdLabels, type SubagentModels, } from "../native-subagents.js"; @@ -62,14 +62,15 @@ import { type SubagentHistory, } from "../subagent-history.js"; import { + currentChildConfiguration, deliveredCall, - firstResponseModel, isDelivery, isDirectory, missingHistoryNotice, ReplayTranscript, replayEndState, textOf, + trackResponseModel, type ReplayChild as SharedReplayChild, } from "../subagent-replay.js"; import { taskNotificationsOf } from "../task-notifications.js"; @@ -195,9 +196,8 @@ export class SubagentReplay { * session: its work ended, or its process is gone, so its replayed end, on * its parent and on its own stream. A `cwd` that is gone, such as a * worktree that Claude Code removed, is cleared. Then each replayed child's - * configuration, when it is not the `model` that the replay sent: the live - * child's, else the model of its latest response, by the session's model - * list. + * configuration (see `currentChildConfiguration`): the live child's, else + * the model of its latest response, by the session's model list. * * The v1 core sends the same after the response (`currentStates`): on v1 * the response is what separates a replayed child state from a current one. @@ -211,15 +211,16 @@ export class SubagentReplay { } private sendConfiguration(child: ReplayChild): void { - const entry = responseModelEntry(child.responseModel, this.host.models()); - const current = - this.live.configuration(child.sessionId) ?? (entry ? [childModelOption(entry)] : undefined); - const replayed = child.model ? JSON.stringify([childModelOption(child.model)]) : undefined; - if (!current || JSON.stringify(current) === replayed) return; + const configOptions = currentChildConfiguration( + child, + this.live.configuration(child.sessionId), + this.host.models(), + ); + if (!configOptions) return; child.output!.emitV1([ { sessionId: child.sessionId, - update: { sessionUpdate: "config_option_update", configOptions: current }, + update: { sessionUpdate: "config_option_update", configOptions }, }, ]); } @@ -322,14 +323,15 @@ export class SubagentReplay { } /** - * Before a message of `owner`'s history (the root's when undefined): a - * child's response with another model sends its `model` again, and a - * persisted task notification of a child is the state its work ended in. + * Before a message of `owner`'s history (the root's when undefined): the + * model of a child's response is its latest one (see `trackResponseModel`), + * and a persisted task notification of a child is the state its work ended + * in. */ private replaying(message: SessionMessage, owner: ReplayChild | undefined): void { const inner = message.message as { model?: unknown; content?: unknown } | undefined; if (message.type === "assistant") { - if (owner) this.sendModel(owner, typeof inner?.model === "string" ? inner.model : undefined); + if (owner) trackResponseModel(owner, inner?.model); return; } for (const notification of taskNotificationsOf(inner?.content)) { @@ -349,7 +351,6 @@ export class SubagentReplay { const messages = this.transcripts.get(child.sessionId) ?? []; if (messages.length === 0) this.withoutHistory++; this.announce(child); - this.sendModel(child, firstResponseModel(messages)); this.transcript.scan(messages, child.sessionId); child.output!.replay(messages, this.ownerHooks(child.output!, child)); if (!child.promptSent && typeof child.input.prompt === "string") { @@ -391,21 +392,6 @@ export class SubagentReplay { ); } - /** The `model` of a response of `child`, when it is not the one the client holds. */ - private sendModel(child: ReplayChild, model: string | undefined): void { - const entry = responseModelEntry(model, this.host.models()); - if (!entry || !child.output) return; - child.responseModel = model; - if (child.model?.value === entry.value && child.model.name === entry.name) return; - child.model = entry; - child.output.emitV1([ - { - sessionId: child.sessionId, - update: { sessionUpdate: "config_option_update", configOptions: [childModelOption(entry)] }, - }, - ]); - } - /** * 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`.