Compare commits

...

1 Commits

Author SHA1 Message Date
Sergey Ignatov
75376d11d6 fix: keep each record of parallel tool calls in _session/read and the subagent load replay (#1747)
## What

`_session/read` and the subagent load replay read a transcript through
the SDK chain. With parallel tool calls, a later record can move or drop
an earlier record of the same model reply. This change keeps every
record of a reply in file order, so the history of a poll only grows.

- New `withReplyBranches` (`src/transcript-branches.ts`). After the SDK
chain, it collects each record that grows from the records of one model
reply (same `message.id`), up to the next reply. Then it puts them in
file order. The SDK reads the records again with the new parent links,
so the SDK still converts and selects the messages.
- A record whose branch leads to another reply stays out. An example is
the prompt before a rewind.
- A prompt outside the chain stays out. A prompt is a user record with
no tool result that is not a meta record. An example is a prompt that
the user sent again with a change.
- A record written after the next chain record stays out, because it
would go before a record that the client already has. For the last
reply, the newest record of the reply in the chain sets this limit.
- If the second SDK read drops a message of the first chain, or gives
another order, the first chain is the result.
- It runs for subagents in `_session/read` and in the load replay, and
for the root in `_session/read`.

## Why

Claude Code writes each tool_use block as its own record, and parents
each result on the record of its call. A Skill text has its result as
parent. The SDK reads one chain from the last record back. Two patterns
break the prefix:

- A third tool_use of the reply, with the second result as parent, moves
the first result after it.
- The second result drops a record whose parent is the first result,
such as a Skill text.

Then a cursor taken before the new record gets `invalid_cursor`, and a
record that the client got can be lost.

SDK 0.3.333 (#1739) already fixes the plain case: two calls, then two
results. The test fixture of that case passed on main before this
change. It stays as a regression test.

Measured on frozen copies of real transcripts, with a read at each
record after a parallel call:

- 150 subagent transcripts: 37 prefix breaks in 23 files on main, 5 in 5
files with this change. 4 of the 5 are subagent compactions, which is a
different gap. The last one is an assistant record with another
`message.id` whose parent is a tool_use record.
- 60 root transcripts: 51 prefix breaks in 14 files on main, 1 with this
change.
- No result has a prompt from outside the SDK chain.
- Load replay: on 167 subagents of 2 real sessions, 34 transcripts
change order. Each message of the SDK result stays, with equal fields.

Cost: the review measured a synthetic session where each subagent reply
needs the new order. A quiet poll went from 1.46 s to 1.87 s, and an
append poll from 3.2 s to 4.0 s. A session with no parallel calls showed
no cost.

## Not in this change

- The root history of a load or resume still uses the SDK order. A
future cursor handoff from load to read needs the same order there.
- The cursor rules of #1729 and #1736 do not change. A cursor from main
gets `invalid_cursor` one time when the new order changes a reply.

## Tests

- `src/tests/transcript-branches.test.ts`: a Skill text on the first
result is kept; a branch that leads to another reply stays out; a record
after the next chain record stays out; the SDK chain is the result when
the second read drops a message or gives another order.
- `src/tests/subagent-history.test.ts` and
`src/tests/session-read.test.ts`: for each fixture, the read at each
record count is a prefix of the next read, and the last read has all
records. The fixtures are: two results; a third call on the second
result; a streamed third call; and three calls with a Skill text on the
third result and a streamed fourth call.
- `src/tests/subagent-history.test.ts`: the same check for the load
replay (`readSubagentMessages`), with `parent_tool_use_id` on each
message.
- `src/tests/session-read.test.ts`: a prompt that the user left for
another prompt stays out, with and without a rewind point.
- `src/tests/v1/session-read.test.ts` and `src/tests/v2/acp-v2.test.ts`:
a cursor taken after `p134` stays valid after each later record, and the
updates have both results.
- The three new parallel fixtures fail on main, in the read and in the
load replay. The two-results fixture and the left-prompt tests pass on
main.
- `npm run build`, `npm run check` and `npm run test:run` pass. With
`ANTHROPIC_BASE_URL` set in the shell, 12 provider tests fail, the same
12 as on main.
2026-12-02 16:03:09 +01:00
10 changed files with 752 additions and 15 deletions

View File

@@ -11,6 +11,7 @@ import { isCompactSummaryMessage } from "./context-compaction.js";
import { projectsRoot } from "./paths.js";
import { errorCode } from "./session-index/project-dirs.js";
import { SessionTiming } from "./session-timing.js";
import { withReplyBranches } from "./transcript-branches.js";
/** The size of one backward read of a transcript. */
const TAIL_CHUNK_BYTES = 64 * 1024;
@@ -112,10 +113,16 @@ export async function readHistoryAcrossCompactions(
const entries = (snapshot ?? (await loadFullSessionHistory(sessionId, dir))).map(
linkCompactBoundary,
);
const history = await getSessionMessages(sessionId, {
dir,
sessionStore: { append: async () => {}, load: async () => entries },
});
const read = (records: SessionStoreEntry[]) =>
getSessionMessages(sessionId, {
dir,
sessionStore: { append: async () => {}, load: async () => records },
});
// `_session/read` gives `messages` with the branches of each model reply,
// and passes its records: the history before it gets them too.
const history = snapshot
? await withReplyBranches(entries, await read(entries), read)
: await read(entries);
const leaf = messages.at(-1)?.uuid;
const end = history.findIndex((message) => message.uuid === leaf);
if (end < 0) {

View File

@@ -21,6 +21,7 @@ import {
} from "./session-index/transcript-scan.js";
import { sanitizeTitle } from "./session-titles.js";
import { activeSessionMessages, readRewindPoint } from "./session-rewind.js";
import { withReplyBranches } from "./transcript-branches.js";
export const SESSION_READ_METHOD = "_session/read";
export const SESSION_READ_CAPABILITY = { supported: true } as const;
@@ -160,11 +161,13 @@ export async function readSessionTranscript(
lastRecordedTitle(records, "ai-title", "aiTitle"));
const dir = cwd ?? records.find((r) => typeof r.cwd === "string" && path.isAbsolute(r.cwd))?.cwd;
const effectiveCwd = typeof dir === "string" ? dir : process.cwd();
const options = {
dir: effectiveCwd,
sessionStore: { append: async () => {}, load: async () => records },
};
const chain = await getSessionMessages(sessionId, options);
const read = (entries: SessionStoreEntry[]) =>
getSessionMessages(sessionId, {
dir: effectiveCwd,
sessionStore: { append: async () => {}, load: async () => entries },
});
// A poll must see the earlier history as a prefix (see `withReplyBranches`).
const chain = await withReplyBranches(records, await read(records), read);
const rewind = await readRewindPoint(sessionId, undefined, { transcript });
const retained = activeSessionMessages(chain, rewind);
const messages = await readHistoryAcrossCompactions(

View File

@@ -2,6 +2,7 @@ import {
getSessionInfo,
getSubagentMessages,
type SessionMessage,
type SessionStoreEntry,
} from "@anthropic-ai/claude-agent-sdk";
import { createReadStream } from "node:fs";
import { readdir, readFile } from "node:fs/promises";
@@ -9,6 +10,7 @@ import path from "node:path";
import readline from "node:readline";
import { isNativeSubagentControlTool, type HistoricalSubagent } from "./native-subagents.js";
import { findTranscript, readTranscriptEntries } from "./resumed-session.js";
import { withReplyBranches } from "./transcript-branches.js";
/** What the metadata file of a subagent says about it. */
export interface SubagentRecord {
@@ -307,15 +309,66 @@ export async function readSubagentMessages(
try {
if (history.dir) {
const messages = await getSubagentMessages(sessionId, agentId, { dir: history.dir });
if (messages.length > 0) return stripForkPrefix(messages);
if (messages.length > 0) {
return stripForkPrefix(await withSubagentBranches(sessionId, agentId, history, messages));
}
}
return stripForkPrefix(await getSubagentMessages(sessionId, agentId));
const messages = await getSubagentMessages(sessionId, agentId);
return stripForkPrefix(await withSubagentBranches(sessionId, agentId, history, messages));
} catch (error) {
logger.error(`Failed to read the history of subagent ${agentId}:`, error);
return [];
}
}
/**
* The chain of the subagent `agentId` in its transcript records `entries`,
* with the branches of its model replies (see {@link withReplyBranches}).
*/
async function readSubagentChain(
sessionId: string,
agentId: string,
entries: SessionStoreEntry[],
): Promise<SessionMessage[]> {
const read = (records: SessionStoreEntry[]) =>
getSubagentMessages(sessionId, agentId, {
sessionStore: { append: async () => {}, load: async () => records },
});
return withReplyBranches(entries, await read(entries), read);
}
/**
* `messages`, the chain that the SDK read from the files of the subagent
* `agentId`, with the branches of its model replies. It is `messages` when
* the transcript in `history.directory` cannot be read.
*/
async function withSubagentBranches(
sessionId: string,
agentId: string,
history: SubagentHistory,
messages: SessionMessage[],
): Promise<SessionMessage[]> {
if (messages.length === 0 || !history.directory) return messages;
let entries: SessionStoreEntry[];
try {
entries = await readTranscriptEntries(path.join(history.directory, `agent-${agentId}.jsonl`));
} catch {
return messages;
}
const read = async (records: SessionStoreEntry[]) =>
(
await getSubagentMessages(sessionId, agentId, {
sessionStore: { append: async () => {}, load: async () => records },
})
).map((message) => ({
...message,
// The SDK reads these fields from agent-*.meta.json only with its filesystem store.
parent_tool_use_id: messages[0]!.parent_tool_use_id,
parent_agent_id: messages[0]!.parent_agent_id,
}));
return withReplyBranches(entries, messages, read);
}
/** Whether a filesystem error means a file does not exist. */
function isMissing(error: unknown): boolean {
return (error as { code?: unknown } | null)?.code === "ENOENT";
@@ -340,8 +393,7 @@ export async function readSubagentMessagesOrFail(
const file = path.join(history.directory, `agent-${agentId}.jsonl`);
try {
const entries = await readTranscriptEntries(file);
const sessionStore = { append: async () => {}, load: async () => entries };
const messages = await getSubagentMessages(sessionId, agentId, { sessionStore });
const messages = await readSubagentChain(sessionId, agentId, entries);
// The SDK reads these fields from agent-*.meta.json only with its filesystem store.
const parent = history.agents.get(launchId)?.parentAgentId ?? null;
return stripForkPrefix(

View File

@@ -203,6 +203,94 @@ export function transcriptCompactSummary(
return transcriptUser(uuid, content, { isCompactSummary: true });
}
/**
* A prompt and one model reply with parallel Read calls, in the record order
* of Claude Code 2.1.332. Each tool_use block is a record of its own whose
* parent is the record before it, and each result has the record of its call
* as parent:
*
* - `results`: two calls, then the result of each call;
* - `third call`: a third call of the same reply, whose parent is the second result;
* - `streamed call`: the first result comes while the reply streams a third
* call, which then has that result as parent.
*
* Each record has its `parentUuid`, for {@link writeTranscript}.
*/
export function parallelToolCallRecords(
variant: "results" | "third call" | "streamed call" | "skill text",
): Record<string, unknown>[] {
let clock = 0;
const at = () => new Date(Date.UTC(2026, 9, 11, 0, 0, clock++)).toISOString();
const call = (uuid: string, parentUuid: string, id: string) => ({
type: "assistant",
uuid,
parentUuid,
timestamp: at(),
message: {
id: "msg_parallel",
role: "assistant",
model: "claude-opus-5",
content: [{ type: "tool_use", id, name: "Read", input: { file_path: `/work/${id}.txt` } }],
},
});
const result = (uuid: string, parentUuid: string, id: string) => ({
type: "user",
uuid,
parentUuid,
sourceToolAssistantUUID: parentUuid,
timestamp: at(),
message: {
role: "user",
content: [{ type: "tool_result", tool_use_id: id, content: `Text of ${id}` }],
},
});
const prompt = { ...transcriptUser("p132", "Read the files"), parentUuid: null, timestamp: at() };
if (variant === "skill text") {
// Three calls; the third result has a Skill text; a fourth call streams in.
return [
prompt,
call("p133", "p132", "toolu_1"),
call("p134", "p133", "toolu_2"),
call("p135", "p134", "toolu_3"),
result("p136", "p135", "toolu_3"),
{
type: "user",
uuid: "p137",
parentUuid: "p136",
isMeta: true,
timestamp: at(),
message: { role: "user", content: [{ type: "text", text: "Text of the Skill" }] },
},
result("p138", "p134", "toolu_2"),
call("p139", "p138", "toolu_4"),
result("p140", "p133", "toolu_1"),
result("p141", "p139", "toolu_4"),
];
}
const records: Record<string, unknown>[] = [
prompt,
call("p133", "p132", "toolu_1"),
call("p134", "p133", "toolu_2"),
result("p135", "p133", "toolu_1"),
];
if (variant === "results") records.push(result("p136", "p134", "toolu_2"));
if (variant === "third call") {
records.push(
result("p136", "p134", "toolu_2"),
call("p137", "p136", "toolu_3"),
result("p138", "p137", "toolu_3"),
);
}
if (variant === "streamed call") {
records.push(
call("p136", "p135", "toolu_3"),
result("p137", "p134", "toolu_2"),
result("p138", "p136", "toolu_3"),
);
}
return records;
}
/** Writes `<directory>/<sessionId>.jsonl` as Claude Code does: each record
* links to the record before it, except a record that sets its own
* `parentUuid`. */

View File

@@ -7,7 +7,12 @@ import { writeCustomTitleSidecar } from "../session-index/service.js";
import * as transcriptScan from "../session-index/transcript-scan.js";
import { readSessionTranscript, SessionReads, type SessionReadFrame } from "../session-read.js";
import { writeRewindPoint } from "../session-rewind.js";
import { transcriptAssistant, transcriptUser, writeTranscript } from "./helpers.js";
import {
parallelToolCallRecords,
transcriptAssistant,
transcriptUser,
writeTranscript,
} from "./helpers.js";
describe("session read cursors", () => {
const message = (messageId: string): SessionReadFrame => ({
@@ -142,4 +147,62 @@ describe("session read cursors", () => {
}
},
);
it.each([false, true])(
"leaves out a prompt that the user left for another prompt (rewind point: %s)",
async (rewind) => {
const sessionId = randomUUID();
const dir = await mkdtemp(path.join(tmpdir(), "claude-acp-read-left-prompt-"));
const project = path.join(dir, "projects", "-project");
vi.stubEnv("CLAUDE_CONFIG_DIR", dir);
try {
await writeTranscript(project, sessionId, [
{ cwd: dir, ...transcriptUser("u1", "One") },
{ cwd: dir, ...transcriptAssistant("a1", "Answer one") },
{ cwd: dir, ...transcriptUser("uA", "A prompt with a typo") },
{ cwd: dir, ...transcriptUser("uB", "The same prompt"), parentUuid: "a1" },
{ cwd: dir, ...transcriptAssistant("a2", "Answer two") },
]);
if (rewind) {
await writeRewindPoint(sessionId, { resumeSessionAt: "a1", droppedPromptUuid: "uA" });
}
const { messages } = await readSessionTranscript(sessionId);
expect(messages.map((message) => message.uuid)).toEqual(["u1", "a1", "uB", "a2"]);
} finally {
vi.unstubAllEnvs();
await rm(dir, { recursive: true, force: true });
}
},
);
it.each(["results", "third call", "streamed call", "skill text"] as const)(
"reads each record of parallel tool calls of the root in file order: %s",
async (variant) => {
const sessionId = randomUUID();
const dir = await mkdtemp(path.join(tmpdir(), "claude-acp-read-parallel-"));
const project = path.join(dir, "projects", "-project");
vi.stubEnv("CLAUDE_CONFIG_DIR", dir);
try {
const records = parallelToolCallRecords(variant).map((record): Record<string, unknown> => ({
cwd: dir,
...record,
}));
let previous: string[] = [];
for (let count = 1; count <= records.length; count++) {
await writeTranscript(project, sessionId, records.slice(0, count));
const { messages } = await readSessionTranscript(sessionId);
const uuids = messages.map((message) => message.uuid);
expect(uuids.slice(0, previous.length)).toEqual(previous);
previous = uuids;
}
// The SDK leaves out a meta record of the main thread, such as a Skill text.
expect(previous).toEqual(
records.filter((record) => record.isMeta !== true).map((record) => record.uuid),
);
} finally {
vi.unstubAllEnvs();
await rm(dir, { recursive: true, force: true });
}
},
);
});

View File

@@ -1,12 +1,14 @@
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { parallelToolCallRecords } from "./helpers.js";
import type { SessionMessage } from "@anthropic-ai/claude-agent-sdk";
import {
stripForkPrefix,
subagentLineage,
subagentHistory,
readSubagentMessages,
readSubagentMessagesOrFail,
} from "../subagent-history.js";
@@ -374,6 +376,36 @@ describe("strict subagent history", () => {
expect(messages.map((message) => message.uuid)).toEqual(["child-1", "child-2"]);
});
it.each(["results", "third call", "streamed call", "skill text"] as const)(
"keeps each record of parallel tool calls in file order: %s",
async (variant) => {
const file = path.join(dir, "agent-child.jsonl");
const records = parallelToolCallRecords(variant).map((record): Record<string, unknown> => ({
...base,
...record,
isSidechain: true,
agentId: "child",
}));
const history = { agents: new Map(), directory: dir };
let previous: string[] = [];
for (let count = 1; count <= records.length; count++) {
await writeFile(
file,
records
.slice(0, count)
.map((record) => JSON.stringify(record) + "\n")
.join(""),
);
const uuids = (await readSubagentMessagesOrFail(sessionId, "child", history, "launch")).map(
(message) => message.uuid,
);
expect(uuids.slice(0, previous.length)).toEqual(previous);
previous = uuids;
}
expect(previous).toEqual(records.map((record) => record.uuid));
},
);
it("fails rather than silently accepting an unreadable child transcript", async () => {
const file = path.join(dir, "agent-bad.jsonl");
await mkdir(file);
@@ -382,3 +414,67 @@ describe("strict subagent history", () => {
).rejects.toMatchObject({ path: file });
});
});
describe("subagent load replay", () => {
let config: string;
beforeEach(async () => {
config = await mkdtemp(path.join(os.tmpdir(), "claude-acp-subagent-load-"));
vi.stubEnv("CLAUDE_CONFIG_DIR", config);
});
afterEach(async () => {
vi.unstubAllEnvs();
await rm(config, { recursive: true, force: true });
});
it.each(["results", "third call", "streamed call", "skill text"] as const)(
"loads each record of parallel tool calls in file order: %s",
async (variant) => {
const cwd = path.join(config, "work");
await mkdir(cwd);
const project = path.join(config, "projects", cwd.replace(/[^a-zA-Z0-9]/g, "-"));
const children = path.join(project, sessionId, "subagents");
await mkdir(children, { recursive: true });
await writeFile(
path.join(project, `${sessionId}.jsonl`),
[
{ ...user("u1", "Go"), parentUuid: null, cwd },
{ ...launch("a1", "toolu_agent"), parentUuid: "u1", cwd },
]
.map((record) => JSON.stringify(record) + "\n")
.join(""),
);
await writeFile(
path.join(children, "agent-child.meta.json"),
JSON.stringify({ agentType: "Explore", toolUseId: "toolu_agent", description: "Work" }),
);
const records = parallelToolCallRecords(variant).map((record): Record<string, unknown> => ({
...base,
cwd,
...record,
isSidechain: true,
agentId: "child",
}));
const logger = { error: vi.fn() };
let previous: string[] = [];
for (let count = 1; count <= records.length; count++) {
await writeFile(
path.join(children, "agent-child.jsonl"),
records
.slice(0, count)
.map((record) => JSON.stringify(record) + "\n")
.join(""),
);
const history = await subagentHistory(sessionId);
const messages = await readSubagentMessages(sessionId, "child", history, logger);
expect(messages.every((message) => message.parent_tool_use_id === "toolu_agent")).toBe(
true,
);
const uuids = messages.map((message) => message.uuid);
expect(uuids.slice(0, previous.length)).toEqual(previous);
previous = uuids;
}
expect(previous).toEqual(records.map((record) => record.uuid));
expect(logger.error).not.toHaveBeenCalled();
},
);
});

View File

@@ -0,0 +1,72 @@
import type { SessionMessage, SessionStoreEntry } from "@anthropic-ai/claude-agent-sdk";
import { describe, expect, it } from "vitest";
import { replyBranchOrder, withReplyBranches } from "../transcript-branches.js";
import { parallelToolCallRecords } from "./helpers.js";
/** The records of the `results` fixture, with the records of `extra` after them. */
function records(...extra: Record<string, unknown>[]): SessionStoreEntry[] {
return [...parallelToolCallRecords("results"), ...extra] as SessionStoreEntry[];
}
/** The records of the `results` fixture, with a Skill text on the first result before the second result. */
function withSkillText(): SessionStoreEntry[] {
const fixture = records();
return [
...fixture.slice(0, 4),
text("skill", "p135", { isMeta: true }),
...fixture.slice(4),
] as SessionStoreEntry[];
}
const text = (uuid: string, parentUuid: string, fields: Record<string, unknown> = {}) => ({
type: "user",
uuid,
parentUuid,
message: { role: "user", content: [{ type: "text", text: uuid }] },
...fields,
});
const reply = (uuid: string, parentUuid: string) => ({
type: "assistant",
uuid,
parentUuid,
message: { id: `msg_${uuid}`, role: "assistant", content: [{ type: "text", text: uuid }] },
});
const messages = (uuids: string[]) => uuids.map((uuid) => ({ uuid }) as SessionMessage);
describe("replyBranchOrder", () => {
it("adds a record that grows from a result of another branch, such as the text of a Skill", () => {
const entries = withSkillText();
// The SDK chain follows the second result and drops the text on the first one.
const plan = replyBranchOrder(entries, ["p132", "p133", "p134", "p135", "p136"]);
expect(plan?.order).toEqual(["p132", "p133", "p134", "p135", "skill", "p136"]);
});
it("leaves out a branch that leads to another reply, such as the prompt before a rewind", () => {
const entries = records(text("old prompt", "p135"), reply("old answer", "old prompt"));
expect(replyBranchOrder(entries, ["p132", "p133", "p134", "p135", "p136"])).toBeUndefined();
});
it("leaves out a record that comes after the next record of the chain", () => {
const entries = records(reply("next", "p136"), text("late", "p135", { isMeta: true }));
expect(
replyBranchOrder(entries, ["p132", "p133", "p134", "p135", "p136", "next"]),
).toBeUndefined();
});
});
describe("withReplyBranches", () => {
const entries = withSkillText();
const chain = messages(["p132", "p133", "p134", "p135", "p136"]);
it.each([
["drops a message of the chain", ["p132", "p133", "p134", "skill", "p136"]],
["gives another order", ["p132", "p133", "p134", "skill", "p135", "p136"]],
])("keeps the SDK chain when the read %s", async (_name, read) => {
expect(await withReplyBranches(entries, chain, async () => messages(read))).toBe(chain);
});
it("gives a read that leaves out a planned record, such as a meta prompt that the SDK hides", async () => {
const read = messages(["p132", "p133", "p134", "p135", "p136"]);
expect(await withReplyBranches(entries, chain, async () => read)).toBe(read);
});
});

View File

@@ -18,6 +18,7 @@ import { writeRewindPoint } from "../../session-rewind.js";
import { ClaudeAcpAgent, v1AgentApp } from "../../v1/acp-agent.js";
import {
initializeClient,
parallelToolCallRecords,
transcriptAssistant,
transcriptUser,
writeTranscript,
@@ -522,6 +523,75 @@ describe("_session/read on v1", () => {
},
);
it.each(["results", "third call", "streamed call"] as const)(
"keeps a cursor valid while the results of parallel tool calls of a child arrive: %s",
async (variant) => {
const childId = "a1122334455667788";
const launchId = "toolu_review";
const launched = {
...transcriptAssistant("launch", ""),
message: {
role: "assistant",
model: "claude-opus-5",
id: "msg_launch",
content: [
{
type: "tool_use",
id: launchId,
name: "Agent",
input: { prompt: "Read the files", description: "Read files" },
},
],
},
};
await store([...history, launched]);
const directory = path.join(project, sessionId, "subagents");
await mkdir(directory, { recursive: true });
await writeFile(
path.join(directory, `agent-${childId}.meta.json`),
JSON.stringify({ toolUseId: launchId, description: "Read files" }),
);
const records = parallelToolCallRecords(variant).map((record) => ({
sessionId,
cwd,
agentId: childId,
isSidechain: true,
...record,
}));
const writeChild = (count: number) =>
writeTranscript(directory, `agent-${childId}`, records.slice(0, count));
// The prompt and the two tool_use records: the cursor comes after `p134`.
await writeChild(3);
const { agent, updates } = captureUpdates();
try {
await initializeClient(agent, {
session: { cursors: {} },
_meta: {
jetbrains: {
air: { version: 1, capabilities: [AIR_NATIVE_SUBAGENT_SESSIONS_CAPABILITY] },
},
},
});
let { cursorId } = await agent.readSession({ sessionId, replayFrom: start });
for (let count = 4; count <= records.length; count++) {
await writeChild(count);
({ cursorId } = await agent.readSession({
sessionId,
replayFrom: { type: "cursor", cursorId },
}));
}
const completed = updates.flatMap(({ update }) =>
update.sessionUpdate === "tool_call_update" && update.status === "completed"
? [update.toolCallId]
: [],
);
expect(completed).toEqual(expect.arrayContaining(["toolu_1", "toolu_2"]));
} finally {
await agent.dispose();
}
},
);
it.each(["close", "cancel"] as const)("releases a fenced read after %s", async (action) => {
await store(history);
const actual = await vi.importActual<typeof import("@anthropic-ai/claude-agent-sdk")>(

View File

@@ -46,6 +46,7 @@ import { customTitleSidecarPath } from "../../session-index/transcript-scan.js";
import {
claudeCodeMcpRequest,
cliSettingsReport,
parallelToolCallRecords,
runMcpToolHooks,
setModelRefusal,
startupFailure,
@@ -1261,6 +1262,53 @@ describe("ACP v2 sessions", () => {
});
});
it.each(["results", "third call", "streamed call"] as const)(
"keeps a cursor valid while the results of parallel tool calls of a child arrive: %s",
async (variant) => {
const sessionId = randomUUID();
const childId = "abc123";
const prompt = randomUUID();
const root = [
transcriptRecord(sessionId, prompt, null, { role: "user", content: "Explore it" }),
transcriptRecord(sessionId, randomUUID(), prompt, {
id: "msg_launch",
role: "assistant",
content: [
{
type: "tool_use",
id: "toolu_agent",
name: "Agent",
input: { prompt: "Read the files", description: "Explore" },
},
],
}),
];
const records = parallelToolCallRecords(variant).map((record) => ({
sessionId,
cwd,
...record,
}));
const meta = { agentType: "Explore", toolUseId: "toolu_agent" };
// The prompt and the two tool_use records: the cursor comes after `p134`.
await writeSubagentHistory(sessionId, root, childId, meta, records.slice(0, 3));
const client = v2Client();
await client.app.connectWith(connectRouter(), async (agent) => {
await initializeV2(agent);
let { cursorId } = await read(agent, sessionId, { type: "start" });
for (let count = 4; count <= records.length; count++) {
await writeSubagentHistory(sessionId, root, childId, meta, records.slice(0, count));
({ cursorId } = await read(agent, sessionId, { type: "cursor", cursorId: cursorId! }));
}
const completed = client.sessionUpdates.flatMap(({ update }) =>
update.sessionUpdate === "tool_call_update" && update.status === "completed"
? [update.toolCallId]
: [],
);
expect(completed).toEqual(expect.arrayContaining(["toolu_1", "toolu_2"]));
});
},
);
it("delivers the current title after replay without changing the saved cursor", async () => {
const sessionId = randomUUID();
const project = path.join(tempDir, "claude", "projects", "-project");

238
src/transcript-branches.ts Normal file
View File

@@ -0,0 +1,238 @@
import type { SessionMessage, SessionStoreEntry } from "@anthropic-ai/claude-agent-sdk";
/** One record of a transcript file, with the fields that the branch order reads. */
type TranscriptRecord = SessionStoreEntry & {
uuid?: unknown;
parentUuid?: unknown;
isSidechain?: unknown;
agentId?: unknown;
message?: unknown;
};
/**
* The history of a transcript with each record of a model reply's branches,
* in file order. `chain` is what the SDK read from `entries`, and `read`
* reads the history from other entries in the same way.
*
* Claude Code writes each tool_use block of one model reply as its own
* record, and parents the result of each call on the record of that call. A
* record that comes with a result, such as the text of a Skill, has that
* result as parent. So parallel calls make one branch per call. The SDK reads
* one chain, from the last record back by `parentUuid`, and adds some of the
* other records of the reply after the last chain record of the reply. So a
* new record can move a record of the reply or drop it from the history:
*
* - a third tool_use of the reply, with the second result as parent, moves
* the first result after it;
* - the second result drops a record whose parent is the first result.
*
* The earlier history is then no prefix of the later one, and a record that
* a client got is gone. Here each reply of the chain keeps every record that
* grows from its records, up to the next reply, in file order, as Claude
* Code appended them. A record whose branch leads to another reply is an
* other history, such as the prompt before a rewind, and stays out. A
* record that Claude Code wrote after the next record of the chain, or after
* the last record of the chain, stays out too: it would go before a record
* that a client already got. A later read adds a record of the second kind
* when a record after it comes.
*
* The SDK still converts and selects the records: they go back to `read`
* with the `parentUuid` of each record of a changed reply set to the record
* before it in file order. The result is `chain` when no reply changes, or
* when `read` drops a message of `chain` or gives another order.
*/
export async function withReplyBranches(
entries: readonly SessionStoreEntry[],
chain: SessionMessage[],
read: (entries: SessionStoreEntry[]) => Promise<SessionMessage[]>,
): Promise<SessionMessage[]> {
const plan = replyBranchOrder(
entries,
chain.map((message) => message.uuid),
);
if (!plan) return chain;
const history = await read(plan.entries);
// The SDK leaves out some records, such as a meta prompt of the main thread.
// The result must keep each message of `chain`, in the planned order.
const kept = new Set(history.map((message) => message.uuid));
if (chain.some((message) => !kept.has(message.uuid))) return chain;
let at = 0;
for (const message of history) {
while (at < plan.order.length && plan.order[at] !== message.uuid) at++;
if (at === plan.order.length) return chain;
at++;
}
return history;
}
/**
* The record order of {@link withReplyBranches} for the SDK chain `chain`
* (its uuids), and the entries to read it from. Undefined when the chain
* already has that order.
*/
export function replyBranchOrder(
entries: readonly SessionStoreEntry[],
chain: readonly string[],
): { order: string[]; entries: SessionStoreEntry[] } | undefined {
const records = entries as readonly TranscriptRecord[];
const byUuid = new Map<string, TranscriptRecord>();
const position = new Map<string, number>();
const children = new Map<string, string[]>();
const replies = new Map<string, string[]>();
records.forEach((record, index) => {
if (typeof record.uuid !== "string") return;
if (!byUuid.has(record.uuid) && typeof record.parentUuid === "string") {
const siblings = children.get(record.parentUuid);
if (siblings) siblings.push(record.uuid);
else children.set(record.parentUuid, [record.uuid]);
}
if (!byUuid.has(record.uuid)) {
const id = replyId(record);
if (id !== undefined) {
const members = replies.get(id);
if (members) members.push(record.uuid);
else replies.set(id, [record.uuid]);
}
}
byUuid.set(record.uuid, record);
if (!position.has(record.uuid)) position.set(record.uuid, index);
});
const inChain = new Set(chain);
const order: string[] = [];
/** The records of each changed reply, of every type, in file order. */
const relinked: { region: string[]; next?: string }[] = [];
const done = new Set<string>();
for (let at = 0; at < chain.length;) {
const record = byUuid.get(chain[at]!);
const id = record && replyId(record);
if (!record || id === undefined || done.has(id)) {
order.push(chain[at]!);
at++;
continue;
}
done.add(id);
const region = growth(record, id);
let end = at;
while (end < chain.length && region.has(chain[end]!)) end++;
const run = chain.slice(at, end);
// A record that Claude Code wrote after the next record of the chain would
// go before a record that a client already got, so it stays out. So does a
// record after the last one of the chain: the SDK ends the history at the
// record that it chose, and a later read adds the record after it.
// The SDK can move an earlier record of the run to its end, so the newest
// record of the run sets the limit, not the last one.
const limit =
end < chain.length
? position.get(chain[end]!)!
: Math.max(...run.map((uuid) => position.get(uuid)!)) + 1;
const sorted = [...region]
.filter((uuid) => inChain.has(uuid) || position.get(uuid)! < limit)
.sort((a, b) => position.get(a)! - position.get(b)!);
const messages = sorted.filter((uuid) => isMessage(byUuid.get(uuid)!));
// A record of the reply that the chain has at another place: keep the SDK order.
const inRun = new Set(run);
const inMessages = new Set(messages);
if (messages.some((uuid) => inChain.has(uuid) && !inRun.has(uuid))) return undefined;
if (run.some((uuid) => !inMessages.has(uuid))) return undefined;
order.push(...messages);
if (messages.length !== run.length || messages.some((uuid, index) => uuid !== run[index])) {
relinked.push({ region: sorted, next: chain[end] });
}
at = end;
}
if (relinked.length === 0) return undefined;
const replaced = new Map<TranscriptRecord, TranscriptRecord>();
const relink = (uuid: string, parentUuid: string) => {
const record = byUuid.get(uuid)!;
replaced.set(record, { ...(replaced.get(record) ?? record), parentUuid });
};
for (const { region, next } of relinked) {
for (let index = 1; index < region.length; index++) relink(region[index]!, region[index - 1]!);
if (next !== undefined) relink(next, region.at(-1)!);
}
return {
order,
entries: records.map((record) => replaced.get(record) ?? record),
};
/**
* The records of the reply `id` of `first`, and each record of the same
* agent that grows from them up to the next reply. A record outside the
* chain whose branch reaches another reply is left out, with its branch.
*/
function growth(first: TranscriptRecord, id: string): Set<string> {
const region = new Set(replies.get(id)!.filter((uuid) => sameAgent(byUuid.get(uuid)!, first)));
const queue = [...region];
/** Whether the branch of each visited record reaches a record of another reply. */
const leads = new Map<string, boolean>();
const leadsElsewhere = (start: string): boolean => {
// A walk with a stack: a branch can be thousands of records long.
const stack: [string, boolean][] = [[start, false]];
const entered = new Set<string>();
while (stack.length > 0) {
const [uuid, expanded] = stack.pop()!;
if (expanded) {
leads.set(
uuid,
(children.get(uuid) ?? []).some((child) => leads.get(child) === true),
);
continue;
}
// A record seen before, or a cycle of `parentUuid` links.
if (leads.has(uuid) || entered.has(uuid)) continue;
entered.add(uuid);
const other = replyId(byUuid.get(uuid)!);
if (other !== undefined && other !== id) {
leads.set(uuid, true);
continue;
}
stack.push([uuid, true]);
for (const child of children.get(uuid) ?? []) stack.push([child, false]);
}
return leads.get(start) === true;
};
while (queue.length > 0) {
for (const child of children.get(queue.shift()!) ?? []) {
if (region.has(child)) continue;
const record = byUuid.get(child)!;
const other = replyId(record);
if (other !== undefined && other !== id) continue;
if (!sameAgent(record, first)) continue;
// A prompt outside the chain is a prompt that the user left, such as
// the prompt before an edit or a rewind.
if (!inChain.has(child) && (isPrompt(record) || leadsElsewhere(child))) continue;
region.add(child);
queue.push(child);
}
}
return region;
}
}
/** The `message.id` of the model reply of an assistant record, or undefined. */
function replyId(record: TranscriptRecord): string | undefined {
if (record.type !== "assistant") return undefined;
const id = (record.message as { id?: unknown } | null | undefined)?.id;
return typeof id === "string" ? id : undefined;
}
/** Whether `record` is a prompt: a user record with no tool result that is not a meta record. */
function isPrompt(record: TranscriptRecord): boolean {
if (record.type !== "user" || (record as { isMeta?: unknown }).isMeta === true) return false;
const content = (record.message as { content?: unknown } | null | undefined)?.content;
return !(
Array.isArray(content) &&
content.some((block) => (block as { type?: unknown } | null)?.type === "tool_result")
);
}
/** Whether the SDK gives `record` as a message of the history. */
function isMessage(record: TranscriptRecord): boolean {
return record.type === "user" || record.type === "assistant";
}
/** Whether two records belong to one thread: the main thread or one subagent. */
function sameAgent(a: TranscriptRecord, b: TranscriptRecord): boolean {
return (a.isSidechain === true) === (b.isSidechain === true) && a.agentId === b.agentId;
}