diff --git a/docs/session-read.md b/docs/session-read.md index 8ee430d1..3f6d6723 100644 --- a/docs/session-read.md +++ b/docs/session-read.md @@ -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. diff --git a/src/session-index/transcript-scan.ts b/src/session-index/transcript-scan.ts index 225c6af4..b5e30997 100644 --- a/src/session-index/transcript-scan.ts +++ b/src/session-index/transcript-scan.ts @@ -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 = readSidecarTitle, ): Promise { - 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 diff --git a/src/session-read.ts b/src/session-read.ts index c3d496ea..bb5e1188 100644 --- a/src/session-read.ts +++ b/src/session-read.ts @@ -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; }; +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 { + 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(); private readonly transitions = new Map(); + private readonly checkpoints = new Map(); + /** Reserve a session before load, resume, close or delete can yield. */ async transition( 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); } diff --git a/src/tests/session-read.test.ts b/src/tests/session-read.test.ts index 67d48027..9c4014b1 100644 --- a/src/tests/session-read.test.ts +++ b/src/tests/session-read.test.ts @@ -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 }); + } + }, + ); }); diff --git a/src/tests/v1/session-read.test.ts b/src/tests/v1/session-read.test.ts index 6965bcf2..29f6764a 100644 --- a/src/tests/v1/session-read.test.ts +++ b/src/tests/v1/session-read.test.ts @@ -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( + "@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`); diff --git a/src/tests/v2/acp-v2.test.ts b/src/tests/v2/acp-v2.test.ts index e47791cb..0875053f 100644 --- a/src/tests/v2/acp-v2.test.ts +++ b/src/tests/v2/acp-v2.test.ts @@ -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(); diff --git a/src/v1/session-read.ts b/src/v1/session-read.ts index e5e444be..3b04f25a 100644 --- a/src/v1/session-read.ts +++ b/src/v1/session-read.ts @@ -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), }; diff --git a/src/v2/agent.ts b/src/v2/agent.ts index e7540afb..80cff3e4 100644 --- a/src/v2/agent.ts +++ b/src/v2/agent.ts @@ -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), }); diff --git a/src/v2/session-read.ts b/src/v2/session-read.ts index df4adc3e..8ee44dca 100644 --- a/src/v2/session-read.ts +++ b/src/v2/session-read.ts @@ -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 }; }