Compare commits

...

2 Commits

Author SHA1 Message Date
Slapoguzov Alexander
5fb2db36eb perf: skip history replay for unchanged session reads (#1736)
A client that follows a terminal session polls `_session/read` with its
cursor. Without this change each poll renders the whole retained history
again, even when nothing was appended.

## What changes

- After a successful cursor read, the connection keeps a checkpoint: the
cursor, the scope, the working directory, the root `replay_complete`
frames, the title and the storage state of the root transcript (device,
inode, mode, size, mtime and ctime).
- A later read with the same cursor first checks that storage state: the
transcript lookup, the file identity, the `custom-title.json` title when
the replay read it, and the absence of `rewind.json`. When nothing
changed, it sends the saved boundary frames and the title, and skips the
render.
- A history gets a checkpoint only when each of its tool calls is Bash,
PowerShell, Read, Write, Edit, Glob or Grep. These tools render their
stored input and result without child transcripts or workspace files.
Any other tool, a pending rewind, a reader restart or a changed file
takes the full replay path from #1729.
- At most 32 checkpoints are kept per connection. A transition (load,
resume, close, delete) of the session drops its checkpoint.

## Verification

`npm run build`, `npm run check` and `npm run test:run` passed (4,968
passed, 65 skipped). A local stdio comparison used 750 synthetic
assistant messages and seven successive quiet polls. The median fell
from 7.7 ms to 0.5 ms on v1 and from 8.8 ms to 0.5 ms on v2.

---------

Co-authored-by: Codex <noreply@openai.com>
2026-12-01 22:18:14 +01:00
acp-release-bot[bot]
a630df5ff7 chore(main): release 0.114.0 (#1720)
🤖 I have created a release *beep* *boop*
---


##
[0.114.0](https://github.com/agentclientprotocol/claude-agent-acp/compare/v0.113.0...v0.114.0)
(2026-12-01)


### Features

* read stored Claude sessions from a replay cursor
([#1729](https://github.com/agentclientprotocol/claude-agent-acp/issues/1729))
([22ca229](22ca229363))


### Bug Fixes

* **code-splitting:** stop counting JSON modules as 0 bytes (&lt;a
([3f4c405](3f4c4058ba))
* follow the permission mode that Claude Code reports
([#1740](https://github.com/agentclientprotocol/claude-agent-acp/issues/1740))
([5ff3411](5ff3411cfa))
* record the permission mode that Claude Code names after a mode change
([#1737](https://github.com/agentclientprotocol/claude-agent-acp/issues/1737))
([4dd607c](4dd607cec1))
* refuse to start a session when Claude Code skipped an invalid settings
file
([#1719](https://github.com/agentclientprotocol/claude-agent-acp/issues/1719))
([e28b50d](e28b50d4f4))
* Respect remote managed settings for model, effort and permission modes
([#1717](https://github.com/agentclientprotocol/claude-agent-acp/issues/1717))
([1c2510d](1c2510dd45))
* send MCP servers and settings over stdin to a Claude Code that
CLAUDE_CODE_EXECUTABLE names
([#1741](https://github.com/agentclientprotocol/claude-agent-acp/issues/1741))
([9f9acd2](9f9acd2b6e))
* sign in to MCP servers of Claude Code's settings on /mcp reconnect
([#1728](https://github.com/agentclientprotocol/claude-agent-acp/issues/1728))
([bc752f8](bc752f88e1))
* stop an autonomous turn while a prompt waits
([#1727](https://github.com/agentclientprotocol/claude-agent-acp/issues/1727))
([1762ccf](1762ccff2e))
* update to @anthropic-ai/claude-agent-sdk 0.3.333
([#1739](https://github.com/agentclientprotocol/claude-agent-acp/issues/1739))
([daeda8c](daeda8cce3))

---
This PR was generated with [Release
Please](https://github.com/googleapis/release-please). See
[documentation](https://github.com/googleapis/release-please#release-please).

Co-authored-by: acp-release-bot[bot] <246668977+acp-release-bot[bot]@users.noreply.github.com>
2026-12-01 21:07:37 +01:00
13 changed files with 447 additions and 86 deletions

View File

@@ -1,3 +1,3 @@
{
".": "0.113.0"
".": "0.114.0"
}

View File

@@ -1,5 +1,25 @@
# Changelog
## [0.114.0](https://github.com/agentclientprotocol/claude-agent-acp/compare/v0.113.0...v0.114.0) (2026-12-01)
### Features
* read stored Claude sessions from a replay cursor ([#1729](https://github.com/agentclientprotocol/claude-agent-acp/issues/1729)) ([22ca229](https://github.com/agentclientprotocol/claude-agent-acp/commit/22ca2293635e0c383392e4ae7b8fab785f633b6f))
### Bug Fixes
* **code-splitting:** stop counting JSON modules as 0 bytes (&lt;a ([3f4c405](https://github.com/agentclientprotocol/claude-agent-acp/commit/3f4c4058baaed7b9fe7d94ff5a39737dcaabb4b1))
* follow the permission mode that Claude Code reports ([#1740](https://github.com/agentclientprotocol/claude-agent-acp/issues/1740)) ([5ff3411](https://github.com/agentclientprotocol/claude-agent-acp/commit/5ff3411cfa8d8c0fbf939995a4587c254d812735))
* record the permission mode that Claude Code names after a mode change ([#1737](https://github.com/agentclientprotocol/claude-agent-acp/issues/1737)) ([4dd607c](https://github.com/agentclientprotocol/claude-agent-acp/commit/4dd607cec1747c6936d9ffc9ccc68e619e36fca4))
* refuse to start a session when Claude Code skipped an invalid settings file ([#1719](https://github.com/agentclientprotocol/claude-agent-acp/issues/1719)) ([e28b50d](https://github.com/agentclientprotocol/claude-agent-acp/commit/e28b50d4f401dc9c3a4fdc8eda27e29989658ba8))
* Respect remote managed settings for model, effort and permission modes ([#1717](https://github.com/agentclientprotocol/claude-agent-acp/issues/1717)) ([1c2510d](https://github.com/agentclientprotocol/claude-agent-acp/commit/1c2510dd45abd4337e02b15921f57f29573246fd))
* send MCP servers and settings over stdin to a Claude Code that CLAUDE_CODE_EXECUTABLE names ([#1741](https://github.com/agentclientprotocol/claude-agent-acp/issues/1741)) ([9f9acd2](https://github.com/agentclientprotocol/claude-agent-acp/commit/9f9acd2b6e59212575917fc788b69853f3a03ee1))
* sign in to MCP servers of Claude Code's settings on /mcp reconnect ([#1728](https://github.com/agentclientprotocol/claude-agent-acp/issues/1728)) ([bc752f8](https://github.com/agentclientprotocol/claude-agent-acp/commit/bc752f88e1e7d46ff49064b1971eebfc23e5d020))
* stop an autonomous turn while a prompt waits ([#1727](https://github.com/agentclientprotocol/claude-agent-acp/issues/1727)) ([1762ccf](https://github.com/agentclientprotocol/claude-agent-acp/commit/1762ccff2e61197e6b0e642637488552e87c1dc1))
* update to @anthropic-ai/claude-agent-sdk 0.3.333 ([#1739](https://github.com/agentclientprotocol/claude-agent-acp/issues/1739)) ([daeda8c](https://github.com/agentclientprotocol/claude-agent-acp/commit/daeda8cce313d50116401e121626fc9820d6cb92))
## [0.113.0](https://github.com/agentclientprotocol/claude-agent-acp/compare/v0.112.0...v0.113.0) (2026-11-26)

View File

@@ -14,8 +14,8 @@ A missing transcript returns `-32002`. A session already open, opening, closing
## Polling cost and scope
Each poll renders the retained history locally and sends only the additions to the client. A changed cursor is checked against a second render before delivery. Recorded children share the root request and can append independently. The unit of delivery is the whole suffix, including updates from recorded children. Clients can virtualize that history for display.
A reader with a cached cursor for a root transcript checks the root file identity, size and timestamps, the rewind file, and the stored title when needed. When they match, it skips rendering history. This also covers sessions using Bash, PowerShell, Read, Write, Edit, Glob or Grep. Other tools can depend on child transcripts or workspace files, so their sessions take the full replay path. A reader restart, a pending rewind, or a change to the transcript or its title file also triggers full validation. A new or changed cursor is checked against a second render before delivery. Recorded children share the root request and can append independently. The unit of delivery is the whole suffix, including updates from recorded children. Clients can virtualize that history for display.
The title is the custom title from the transcript tail or `custom-title.json`, as in Claude’s session index. Otherwise it is the last `custom-title` record, or else the last `ai-title` record, of the whole captured transcript. The index reads only the first and last 64 KB of the file, so a large tool result would otherwise hide an unchanged title. The cursor describes the rendered transcript. For current session activity, AIR clients can use the [session index](air-extensions.md#session-index). For clients also talking to older adapters, a successful cursor request that returns `{}` means a full replay. Replace the saved view and clear the cursor.
The title is the custom title from the transcript tail or `custom-title.json`, as in Claude’s session index. Otherwise it is the last `custom-title` record, or else the last `ai-title` record, of the whole captured transcript. The index reads only the first and last 64 KB of the file, so a large tool result would otherwise hide an unchanged title. The quiet check assumes the local filesystem updates file identity or timestamps on rewrites. The cursor describes the rendered transcript. For current session activity, AIR clients can use the [session index](air-extensions.md#session-index). For clients also talking to older adapters, a successful cursor request that returns `{}` means a full replay. Replace the saved view and clear the cursor.
A client switching from a live load to polling closes the session on its own connection and starts a fresh read.

4
package-lock.json generated
View File

@@ -1,12 +1,12 @@
{
"name": "@agentclientprotocol/claude-agent-acp",
"version": "0.113.0",
"version": "0.114.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@agentclientprotocol/claude-agent-acp",
"version": "0.113.0",
"version": "0.114.0",
"license": "Apache-2.0",
"dependencies": {
"@agentclientprotocol/sdk": "2.12.0",

View File

@@ -3,7 +3,7 @@
"publishConfig": {
"access": "public"
},
"version": "0.113.0",
"version": "0.114.0",
"description": "An ACP-compatible coding agent powered by the Claude Agent SDK (TypeScript)",
"main": "dist/lib.js",
"types": "dist/lib.d.ts",

View File

@@ -623,13 +623,13 @@ export function customTitleSidecarPath(transcriptPath: string): string {
}
/** The custom title that the SDK reads first: the tail's, else the CLI's
* sidecar's. A strict read throws when the sidecar cannot be read. */
* sidecar's, read by `readSidecar`. */
export async function readRecentCustomTitle(
transcriptPath: string,
headTail: HeadTail,
options?: { strict: boolean },
readSidecar: (transcriptPath: string) => Promise<string | undefined> = readSidecarTitle,
): Promise<string | undefined> {
return tailCustomTitle(headTail) ?? (await readSidecarTitle(transcriptPath, options));
return tailCustomTitle(headTail) ?? (await readSidecar(transcriptPath));
}
/** The title of the CLI's sidecar, if it has a readable title. A strict read

View File

@@ -1,7 +1,8 @@
import { RequestError } from "@agentclientprotocol/sdk/unstable";
import { getSessionMessages, type SessionStoreEntry } from "@anthropic-ai/claude-agent-sdk";
import { createHash } from "node:crypto";
import { open } from "node:fs/promises";
import type { BigIntStats } from "node:fs";
import { lstat, open } from "node:fs/promises";
import path from "node:path";
import { z } from "zod";
import packageJson from "../package.json" with { type: "json" };
@@ -15,10 +16,11 @@ import { LastReportedEntity } from "./session-cursors.js";
import {
readHeadTailOf,
readRecentCustomTitle,
readSidecarTitle,
type HeadTail,
} from "./session-index/transcript-scan.js";
import { sanitizeTitle } from "./session-titles.js";
import { cutAtRewindPoint } from "./session-rewind.js";
import { activeSessionMessages, readRewindPoint } from "./session-rewind.js";
export const SESSION_READ_METHOD = "_session/read";
export const SESSION_READ_CAPABILITY = { supported: true } as const;
@@ -47,15 +49,85 @@ type ReadOptions = {
cursors: boolean;
signal?: AbortSignal;
isOpen(sessionId: string): boolean;
assertRoot?(sessionId: string): void;
replay(
sessionId: string,
cwd: string | undefined,
): Promise<{ frames: SessionReadFrame[]; cwd: string; historyEnd?: number; title?: string }>;
observeStorage: boolean,
): Promise<{
frames: SessionReadFrame[];
cwd: string;
historyEnd?: number;
title?: string;
storage?: SessionReadStorage;
}>;
send(frame: SessionReadFrame): Promise<void> | void;
};
export type SessionReadStorage = {
transcript: string;
version: string;
/** Undefined when replay skipped the sidecar, null when it had no title. */
sidecarTitle?: string | null;
};
function fileVersion(stats: BigIntStats): string {
const { dev, ino, mode, size, mtimeNs, ctimeNs } = stats;
return [dev, ino, mode, size, mtimeNs, ctimeNs].join(":");
}
/** Checks the transcript's metadata and the sidecar inputs read by the replay. */
async function storageUnchanged(sessionId: string, storage: SessionReadStorage): Promise<boolean> {
try {
// A move or a different matching project must go through the ordinary lookup.
const transcript = await findTranscript(sessionId, { strict: true });
if (transcript !== storage.transcript) return false;
const matchesTranscript = async () => {
const root = await lstat(transcript, { bigint: true });
return root.isFile() && fileVersion(root) === storage.version;
};
if (!(await matchesTranscript())) return false;
if (storage.sidecarTitle !== undefined) {
const title = await readSidecarTitle(transcript, { strict: true });
if ((title ?? null) !== storage.sidecarTitle) return false;
}
if (await readRewindPoint(sessionId, undefined, { transcript })) return false;
return await matchesTranscript();
} catch {
// An uncertain probe leaves validation and errors to the ordinary replay.
return false;
}
}
/** These tools render their stored input and result, with no child or workspace reads. */
const ROOT_ONLY_TOOLS = new Set(["Bash", "PowerShell", "Read", "Write", "Edit", "Glob", "Grep"]);
function hasIndependentHistory(content: unknown): boolean {
return (
Array.isArray(content) &&
content.some(
(block) =>
["tool_use", "server_tool_use", "mcp_tool_use"].includes(block?.type) &&
!ROOT_ONLY_TOOLS.has(block.name),
)
);
}
function currentDirectory(): string | undefined {
try {
return process.cwd();
} catch {
// The working directory could be gone; a replay with a stored cwd may still work.
return undefined;
}
}
/** The SDK follows parent links in these records, including the branch selected by rewind.json. */
export async function readSessionTranscript(sessionId: string, cwd?: string) {
export async function readSessionTranscript(
sessionId: string,
cwd?: string,
observeStorage = false,
) {
if (!isSessionId(sessionId)) {
throw RequestError.invalidParams({ sessionId }, "Read the root Claude session by its UUID.");
}
@@ -64,17 +136,26 @@ export async function readSessionTranscript(sessionId: string, cwd?: string) {
const handle = await open(transcript, "r");
let headTail: HeadTail;
let records: SessionStoreEntry[];
let version: string | undefined;
try {
const { size } = await handle.stat();
const stat = await handle.stat({ bigint: true });
if (observeStorage) version = fileVersion(stat);
const size = Number(stat.size);
headTail = await readHeadTailOf(handle, size);
records = await readTranscriptEntriesOf(transcript, handle, size);
} finally {
await handle.close();
}
let sidecarTitle: string | null | undefined;
const readTitle = async (file: string) => {
const title = await readSidecarTitle(file, { strict: true });
sidecarTitle = title ?? null;
return title;
};
const title =
records[0]?.isSidechain === true
? undefined
: ((await readRecentCustomTitle(transcript, headTail, { strict: true })) ??
: ((await readRecentCustomTitle(transcript, headTail, readTitle)) ??
lastRecordedTitle(records, "custom-title", "customTitle") ??
lastRecordedTitle(records, "ai-title", "aiTitle"));
const dir = cwd ?? records.find((r) => typeof r.cwd === "string" && path.isAbsolute(r.cwd))?.cwd;
@@ -84,7 +165,8 @@ export async function readSessionTranscript(sessionId: string, cwd?: string) {
sessionStore: { append: async () => {}, load: async () => records },
};
const chain = await getSessionMessages(sessionId, options);
const retained = await cutAtRewindPoint(sessionId, chain, undefined, { transcript });
const rewind = await readRewindPoint(sessionId, undefined, { transcript });
const retained = activeSessionMessages(chain, rewind);
const messages = await readHistoryAcrossCompactions(
sessionId,
retained,
@@ -97,6 +179,14 @@ export async function readSessionTranscript(sessionId: string, cwd?: string) {
cwd: effectiveCwd,
transcript,
title: title && sanitizeTitle(title),
storage:
version &&
!rewind &&
!messages.some((message) =>
hasIndependentHistory((message.message as { content?: unknown } | null)?.content),
)
? { transcript, version, sidecarTitle }
: undefined,
};
}
@@ -237,12 +327,25 @@ function snapshot(
return { outgoing, anchor, cursorId: anchor ? cursor(false) : undefined };
}
type Checkpoint = {
cursorId: string;
scope: string;
requestedCwd: string | undefined;
cwd: string;
processCwd: string;
storage: SessionReadStorage;
boundaries: SessionReadFrame[];
title?: string;
};
/** A read owns only a replay on this connection. Closing it invalidates the pending delivery. */
export class SessionReads {
private readonly active = new Map<string, { invalidated: boolean }>();
private readonly transitions = new Map<string, number>();
private readonly checkpoints = new Map<string, Checkpoint>();
/** Reserve a session before load, resume, close or delete can yield. */
async transition<T>(
sessionId: string | undefined,
@@ -255,6 +358,7 @@ export class SessionReads {
if (kind === "open") throw alreadyOpen(sessionId);
read.invalidated = true;
}
this.checkpoints.delete(sessionId);
this.transitions.set(sessionId, (this.transitions.get(sessionId) ?? 0) + 1);
try {
return await run();
@@ -269,7 +373,8 @@ export class SessionReads {
const parsed = request.safeParse(params);
if (!parsed.success)
throw RequestError.invalidParams(undefined, parsed.error.issues[0]?.message);
const { sessionId, cwd, replayFrom } = parsed.data;
const { sessionId, replayFrom } = parsed.data;
const cwd = parsed.data.cwd ?? undefined;
const previous = replayFrom?.type === "cursor" ? replayFrom.cursorId : undefined;
if (
replayFrom?.type === "cursor" &&
@@ -285,10 +390,22 @@ export class SessionReads {
throw alreadyOpen(sessionId);
};
check();
options.assertRoot?.(sessionId);
this.active.set(sessionId, read);
const useCursor = options.cursors && replayFrom != null;
const processCwd = useCursor ? currentDirectory() : undefined;
const scopeFor = (effectiveCwd: string) =>
json([
sessionId,
effectiveCwd,
claudeConfigDir(),
options.protocol,
options.capabilities,
packageJson.version,
]);
const replay = async () => {
try {
const view = await options.replay(sessionId, cwd ?? undefined);
const view = await options.replay(sessionId, cwd, useCursor);
if (options.protocol === 1 && view.title)
view.frames.push({
sessionId,
@@ -310,67 +427,108 @@ export class SessionReads {
);
}
};
try {
const { frames, cwd: effectiveCwd, historyEnd, title } = await replay();
check();
let outgoing = frames;
let cursorId: string | undefined;
const useCursor = options.cursors && replayFrom != null;
if (useCursor) {
const scope = json([
sessionId,
effectiveCwd,
claudeConfigDir(),
options.protocol,
options.capabilities,
packageJson.version,
]);
const next = snapshot(frames, sessionId, options.protocol, scope, cursor, historyEnd);
outgoing = next.outgoing;
cursorId = next.cursorId;
if (cursorId && cursorId !== cursor) {
// A terminal can append or rewind between the reads of the root and a child.
const again = await replay();
check();
if (
again.cwd !== effectiveCwd ||
again.historyEnd !== historyEnd ||
frames.length !== again.frames.length ||
frames.some((frame, i) => json(frame) !== json(again.frames[i]))
) {
throw RequestError.internalError(
{ sessionId, retryable: true },
"History changed during the read. Retry with the last successful cursor.",
);
}
const end = outgoing.findIndex(
(frame) =>
frame.sessionId === sessionId && frame.update.sessionUpdate === "replay_complete",
);
outgoing.splice(end < 0 ? outgoing.length : end, 0, {
sessionId,
update: {
sessionUpdate: "cursor_update",
cursorId,
anchor: next.anchor,
capabilities: { read: {} },
},
});
}
}
// On v2 the title is current session info, outside the replay cursor.
if (options.protocol === 2 && (title || useCursor)) {
outgoing.push({
sessionId,
update: { sessionUpdate: "session_info_update", title: title || null },
});
}
const deliver = async (
outgoing: SessionReadFrame[],
cursorId: string | undefined,
title: string | undefined,
) => {
for (const frame of outgoing) {
check();
await options.send(frame);
}
// On v2 the title is current session info, outside the replay cursor.
if (options.protocol === 2 && (title || useCursor)) {
check();
await options.send({
sessionId,
update: { sessionUpdate: "session_info_update", title: title || null },
});
}
check();
return cursorId ? { cursorId } : {};
};
try {
const cached = cursor ? this.checkpoints.get(sessionId) : undefined;
if (
cached &&
cached.cursorId === cursor &&
(cached.requestedCwd === cwd || cached.cwd === cwd) &&
cached.processCwd === processCwd &&
cached.scope === scopeFor(cached.cwd) &&
(await storageUnchanged(sessionId, cached.storage)) &&
cached.processCwd === currentDirectory()
) {
return await deliver(cached.boundaries, cached.cursorId, cached.title);
}
check();
if (useCursor) this.checkpoints.delete(sessionId);
const { frames, cwd: effectiveCwd, historyEnd, title, storage } = await replay();
check();
if (!useCursor) return await deliver(frames, undefined, title);
const scope = scopeFor(effectiveCwd);
const { outgoing, cursorId, anchor } = snapshot(
frames,
sessionId,
options.protocol,
scope,
cursor,
historyEnd,
);
let verifiedStorage = storage;
const isRootBoundary = (frame: SessionReadFrame) =>
frame.sessionId === sessionId && frame.update.sessionUpdate === "replay_complete";
if (cursorId && cursorId !== cursor) {
// A terminal can append or rewind between the reads of the root and a child.
const again = await replay();
check();
if (
again.cwd !== effectiveCwd ||
again.historyEnd !== historyEnd ||
frames.length !== again.frames.length ||
frames.some((frame, i) => json(frame) !== json(again.frames[i]))
) {
throw RequestError.internalError(
{ sessionId, retryable: true },
"History changed during the read. Retry with the last successful cursor.",
);
}
if (
again.storage?.transcript !== storage?.transcript ||
again.storage?.version !== storage?.version ||
again.storage?.sidecarTitle !== storage?.sidecarTitle
) {
verifiedStorage = undefined;
}
const end = outgoing.findIndex(isRootBoundary);
outgoing.splice(end < 0 ? outgoing.length : end, 0, {
sessionId,
update: {
sessionUpdate: "cursor_update",
cursorId,
anchor,
capabilities: { read: {} },
},
});
}
// Pair the cursor only with the inputs read by its render, never a later append.
const result = await deliver(outgoing, cursorId, title);
check();
if (cursorId && verifiedStorage && processCwd && processCwd === currentDirectory()) {
this.checkpoints.set(sessionId, {
cursorId,
scope,
requestedCwd: cwd,
cwd: effectiveCwd,
processCwd,
storage: verifiedStorage,
boundaries: frames.filter(isRootBoundary),
title,
});
if (this.checkpoints.size > 32) {
this.checkpoints.delete(this.checkpoints.keys().next().value!);
}
}
return result;
} finally {
this.active.delete(sessionId);
}

View File

@@ -1,5 +1,13 @@
import { randomUUID } from "node:crypto";
import { mkdtemp, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { describe, expect, it, vi } from "vitest";
import { SessionReads, type SessionReadFrame } from "../session-read.js";
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";
describe("session read cursors", () => {
const message = (messageId: string): SessionReadFrame => ({
@@ -74,4 +82,64 @@ describe("session read cursors", () => {
"cursor_update",
]);
});
it.each(["title", "rewind"] as const)(
"validates the %s observed while a sidecar briefly exists during each render",
async (kind) => {
const sessionId = randomUUID();
const dir = await mkdtemp(path.join(tmpdir(), "claude-acp-read-race-"));
const project = path.join(dir, "projects", "-project");
const transcript = path.join(project, `${sessionId}.jsonl`);
const sidecar =
kind === "title"
? transcriptScan.customTitleSidecarPath(transcript)
: path.join(project, sessionId, "rewind.json");
vi.stubEnv("CLAUDE_CONFIG_DIR", dir);
const readHeadTail = transcriptScan.readHeadTailOf;
const race = vi
.spyOn(transcriptScan, "readHeadTailOf")
.mockImplementation(async (...args) => {
if (kind === "title") await writeCustomTitleSidecar(transcript, "Temporary title");
else
await writeRewindPoint(sessionId, { resumeSessionAt: "u1", droppedPromptUuid: "a1" });
return readHeadTail(...args);
});
try {
await writeTranscript(project, sessionId, [
transcriptUser("u1", "Prompt", { cwd: dir }),
transcriptAssistant("a1", "Answer"),
]);
const reads = new SessionReads();
const options = {
...reader([]),
protocol: 2 as const,
replay: async (id: string, cwd: string | undefined, observeStorage: boolean) => {
const view = await readSessionTranscript(id, cwd, observeStorage);
await rm(sidecar, { force: true });
return {
...view,
frames: view.messages.map(({ uuid }) => ({ ...message(uuid), sessionId })),
};
},
};
const { cursorId } = await reads.read({ ...start, sessionId }, options);
expect(cursorId).toBeTruthy();
expect(race).toHaveBeenCalledTimes(2);
race.mockRestore();
options.send.mockClear();
const next = await reads.read({ ...poll(cursorId), sessionId }, options);
if (kind === "title") expect(next.cursorId).toBe(cursorId);
else expect(next.cursorId).not.toBe(cursorId);
expect(options.send.mock.calls.at(-1)?.[0]).toEqual({
sessionId,
update: { sessionUpdate: "session_info_update", title: null },
});
} finally {
race.mockRestore();
vi.unstubAllEnvs();
await rm(dir, { recursive: true, force: true });
}
},
);
});

View File

@@ -1,5 +1,5 @@
import { randomUUID } from "node:crypto";
import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { mkdir, mkdtemp, readFile, rm, utimes, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { client, methods, type InitializeResponse } from "@agentclientprotocol/sdk/unstable";
@@ -132,6 +132,9 @@ describe("_session/read on v1", () => {
transcriptAssistant("a2", "Second answer"),
];
await store(first);
const transcript = path.join(project, `${sessionId}.jsonl`);
const mtime = new Date("2026-10-11T00:00:00Z");
await utimes(transcript, mtime, mtime);
const { connection, agent, updates } = connect();
try {
const init = (await connection.agent.request("initialize", {
@@ -169,10 +172,14 @@ describe("_session/read on v1", () => {
});
const poll = (cursorId: string, dir?: string) => read({ type: "cursor", cursorId }, dir);
updates.length = 0;
vi.mocked(getSessionMessages).mockClear();
expect(await poll(initial.cursorId, cwd)).toEqual(initial);
expect(updates).toEqual([]);
expect(getSessionMessages).not.toHaveBeenCalled();
// Rewriting the same number of bytes and restoring mtime still changes ctime.
await store([...history, first[2]!, transcriptAssistant("a2", "Edited answer")]);
await utimes(transcript, mtime, mtime);
await expect(poll(initial.cursorId)).rejects.toMatchObject(invalidCursor);
expect(updates).toEqual([]);
@@ -191,7 +198,6 @@ describe("_session/read on v1", () => {
},
]);
const transcript = path.join(project, `${sessionId}.jsonl`);
const previousContents = await readFile(transcript, "utf8");
await writeRewindPoint(sessionId, { resumeSessionAt: "a1", droppedPromptUuid: "u2" });
updates.length = 0;
@@ -209,6 +215,103 @@ describe("_session/read on v1", () => {
}
});
it("finds an append that arrives after the confirmation transcript was read", async () => {
await store(history);
const actual = await vi.importActual<typeof import("@anthropic-ai/claude-agent-sdk")>(
"@anthropic-ai/claude-agent-sdk",
);
vi.mocked(getSessionMessages)
.mockImplementationOnce(actual.getSessionMessages)
.mockImplementationOnce(async (...args) => {
const messages = await actual.getSessionMessages(...args);
await store([...history, transcriptUser("u2", "Second question")]);
return messages;
});
const { agent, updates } = captureUpdates();
try {
await initializeClient(agent, { session: { cursors: {} } });
const { cursorId } = await agent.readSession({ sessionId, replayFrom: start });
expect(
updates.flatMap(({ update }) => ("content" in update ? [update.content] : [])),
).toEqual([
{ type: "text", text: "First question" },
{ type: "text", text: "First answer" },
]);
updates.length = 0;
const next = await agent.readSession({
sessionId,
replayFrom: { type: "cursor", cursorId },
});
expect(next.cursorId).not.toBe(cursorId);
expect(
updates.flatMap(({ update }) => ("content" in update ? [update.content] : [])),
).toEqual([{ type: "text", text: "Second question" }]);
await rm(path.join(project, `${sessionId}.jsonl`));
updates.length = 0;
await expect(
agent.readSession({ sessionId, replayFrom: { type: "cursor", cursorId: next.cursorId } }),
).rejects.toMatchObject({ code: -32002 });
expect(updates).toEqual([]);
} finally {
await agent.dispose();
}
});
it.each([
["Read", false],
["Skill", true],
])("checks whether %s replay needs a full scan", async (name, needsReplay) => {
const toolId = "toolu_saved";
await store([
history[0]!,
{
...transcriptAssistant("use", ""),
message: {
role: "assistant",
id: "msg_use",
content: [
{
type: "tool_use",
id: toolId,
name,
input:
name === "Read" ? { file_path: path.join(cwd, "saved.txt") } : { skill: "example" },
},
],
},
},
]);
const { agent, updates } = captureUpdates();
try {
await initializeClient(agent, { session: { cursors: {} } });
const { cursorId } = await agent.readSession({ sessionId, replayFrom: start });
expect(updates.some(({ update }) => update.sessionUpdate === "tool_call")).toBe(true);
updates.length = 0;
vi.mocked(getSessionMessages).mockClear();
expect(
await agent.readSession({ sessionId, replayFrom: { type: "cursor", cursorId } }),
).toEqual({ cursorId });
expect(updates).toEqual([]);
expect(getSessionMessages).toHaveBeenCalledTimes(needsReplay ? 1 : 0);
if (!needsReplay) {
await expect(
agent.readSession({
sessionId,
cwd: path.join(cwd, "other"),
replayFrom: { type: "cursor", cursorId },
}),
).rejects.toMatchObject(invalidCursor);
expect(updates).toEqual([]);
}
} finally {
await agent.dispose();
}
});
it("invalidates a saved cursor after a sidecar title in the replay changes", async () => {
await store(history);
const transcript = path.join(project, `${sessionId}.jsonl`);

View File

@@ -1291,12 +1291,17 @@ describe("ACP v2 sessions", () => {
expect(cursorId).toEqual(expect.any(String));
expect(client.sessionUpdates.slice(-2)).toEqual(titleUpdates("Original"));
saved = { type: "cursor", cursorId: cursorId! };
for (const title of ["Renamed", "Renamed", null]) {
if (title === null) await rm(customTitleSidecarPath(transcript));
const expectTitle = async (title: string | null) => {
client.sessionUpdates.length = 0;
expect(await read(agent, sessionId, saved)).toEqual({ cursorId });
expect(client.sessionUpdates).toEqual(titleUpdates(title));
}
};
await expectTitle("Renamed");
vi.mocked(getSessionMessages).mockClear();
await expectTitle("Renamed");
expect(getSessionMessages).not.toHaveBeenCalled();
await rm(customTitleSidecarPath(transcript));
await expectTitle(null);
});
const reconnect = v2Client();

View File

@@ -46,10 +46,10 @@ export class V1SessionReads {
capabilities: options.capabilities,
cursors: options.capabilities?.session?.cursors != null,
isOpen: options.isOpen,
assertRoot: options.assertRoot,
signal,
replay: async (sessionId, cwd) => {
options.assertRoot(sessionId);
const transcript = await readSessionTranscript(sessionId, cwd);
replay: async (sessionId, cwd, observeStorage) => {
const transcript = await readSessionTranscript(sessionId, cwd, observeStorage);
signal.throwIfAborted();
const frames: SessionReadFrame[] = [];
let historyEnd: number | undefined;
@@ -79,6 +79,7 @@ export class V1SessionReads {
return {
frames,
cwd: transcript.cwd,
storage: transcript.storage,
historyEnd,
title: transcript.title === undefined ? undefined : options.clientTitle(transcript.title),
};

View File

@@ -420,7 +420,8 @@ class V2Agent implements AgentHandle, SessionConnection {
signal,
isOpen: (sessionId) =>
this.sessions.has(sessionId) || this.stopped.has(sessionId) || this.starting.has(sessionId),
replay: (sessionId, cwd) => renderSessionRead(sessionId, cwd, this.logger, capabilities),
replay: (sessionId, cwd, observeStorage) =>
renderSessionRead(sessionId, cwd, this.logger, capabilities, observeStorage),
send: (frame) =>
this.ctx.notify(v2.methods.client.session.update, frame as v2.UpdateSessionNotification),
});

View File

@@ -12,8 +12,13 @@ export async function renderSessionRead(
dir: string | undefined,
logger: Logger,
capabilities: v2.ClientCapabilities | null | undefined,
): Promise<{ frames: SessionReadFrame[]; cwd: string; historyEnd: number; title?: string }> {
const { messages, cwd, transcript, title } = await readSessionTranscript(sessionId, dir);
observeStorage: boolean,
) {
const { messages, cwd, transcript, title, storage } = await readSessionTranscript(
sessionId,
dir,
observeStorage,
);
const frames: SessionReadFrame[] = [];
const translator = new V2UpdateTranslator();
const send = (notification: v2.UpdateSessionNotification): void => {
@@ -42,5 +47,5 @@ export async function renderSessionRead(
const end = replayEndUpdate(capabilities);
if (end) send({ sessionId, update: end });
subagents?.reportMissingHistory();
return { frames, cwd, historyEnd, title };
return { frames, cwd, historyEnd, title, storage };
}