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