Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
feat(chat): paged transcript reads in core + every transport
reviewdcc423766c70
diff --git a/CLAUDE.md b/CLAUDE.mdindex 813a9595c..0063087c6 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -2375,6 +2375,26 @@ command-bearing opens; this does not add a human-confirm dialog or change mobileits `contextTail`, the hook-fed path authority). The browser's real reader is`buildTranscriptApi` in ws-bridge — deliberately NOT folded into `buildClaudeApi`, which therelay shares and must not adopt it.+ **Paged reads (2026-09).** `chat.readTranscript` takes a trailing optional `page`+ (`{before?, maxBytes?}`, `shared/chat-page.ts`). Absent = the legacy 5 MB-tail read, byte for byte+ (result is exactly `{messages, found}`). Present = ONE window of at most `maxBytes` (clamped+ 64 KB…5 MB — it is untrusted IPC/WS input; an invalid `before` REJECTS rather than being coerced+ to "end of file") ending at byte `before`, and the result adds `olderCursor` (where the window's+ first complete line starts — the next page's `before`; `null` = reached the start), a per-message+ `key` (the line's ABSOLUTE byte offset — stable across prepends and appends), `id` on tool parts,+ and `unmatchedResults` (tool results whose `tool_use` sits in an OLDER window: the newer page is+ read first, so the renderer holds them until that page arrives). Parsing is the pure+ `parseChatWindow` over BYTES (a multi-byte char cut by the window edge only lands in the dropped+ partial line), and every window is read with **one byte of lookbehind** — the only way to know a+ line begins exactly on the edge; without it that line is dropped as "partial" and lost. A line+ longer than the whole window is skipped (`olderCursor = window start`, never the window end,+ which would re-request the identical window forever). The **SSH leg** is a ranged read+ (`transcriptPageCommand`, `core/remote-ssh/transcript-window.ts` — size + window in ONE round+ trip, dd status inside the base64 like the context-tail's window command) instead of pulling the+ 5 MB tail on every open and every turn-end reload; its `{ok:false}` is terminal (never the local+ disk), and it is tested under a real `/bin/sh` (`transcript-page.realsh.test.ts`). **Grok does not+ page**: a paged request gets its whole capped read with `olderCursor: null` and no keys.+ Server Edition passes `page` through ws-bridge to the same core handler; relay still refuses.**The composer sends only in `done` or an unknown state** (`canSendFromChat`,`renderer/lib/chatSendGate.ts`) — never in `waiting`/`blocked`, not just never in `working`:PermissionRequest and AskUserQuestion both normalize to `waiting`, the pane then holds a TUIdiff --git a/src/core/remote-ssh/transcript-page.realsh.test.ts b/src/core/remote-ssh/transcript-page.realsh.test.tsnew file mode 100644index 000000000..0d1c299b6--- /dev/null+++ b/src/core/remote-ssh/transcript-page.realsh.test.ts@@ -0,0 +1,98 @@+// The paged ⌘M transcript read's remote command, executed by a REAL /bin/sh against a real file.+//+// Generated shell is source no compiler checks (see canvas-control-shim / remote-claude-usage /+// session-memory-remote tests for the same discipline): only running it proves the arithmetic, the+// dd block alignment and the framing agree with the parser — and that a hostile path stays a path.+import { afterAll, beforeAll, describe, expect, it } from 'vitest'+import { execFileSync } from 'child_process'+import fs from 'fs'+import os from 'os'+import path from 'path'+import { parseTranscriptPage, transcriptPageCommand } from './transcript-window'+import { parseChatWindow } from '../transcript-reader'++let dir: string+beforeAll(() => {+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-page-sh-'))+})+afterAll(() => fs.rmSync(dir, { recursive: true, force: true }))++const run = (cmd: string): string =>+ execFileSync('/bin/sh', ['-c', cmd], { encoding: 'utf8', cwd: dir, stdio: ['ignore', 'pipe', 'ignore'] })+const write = (name: string, body: Buffer | string): string => {+ const p = path.join(dir, name)+ fs.writeFileSync(p, body)+ return p+}+const page = (p: string, before: number | null, maxBytes: number) =>+ parseTranscriptPage(run(transcriptPageCommand(p, before, maxBytes)), maxBytes)++// Expected window, computed independently of the shell: [windowStart - lookbehind, end).+const expected = (file: Buffer, before: number | null, maxBytes: number) => {+ const end = before === null || before > file.length ? file.length : before+ const ws = Math.max(0, end - maxBytes)+ const start = ws > 0 ? ws - 1 : 0+ return { start, end, data: file.subarray(start, end) }+}++describe('transcriptPageCommand under /bin/sh', () => {+ // Bigger than two dd blocks (64 KiB), with multi-byte chars everywhere, so unaligned starts,+ // block-straddling windows and split characters are all exercised.+ const lines: string[] = []+ for (let i = 0; i < 3000; i++) {+ lines.push(JSON.stringify({ type: 'user', message: { content: `satır ${i} — ğüşiöç ✓` } }))+ }+ const file = Buffer.from(lines.join('\n') + '\n')++ it.each([+ [null, 65536],+ [null, 1_000_000],+ [70_001, 65536],+ [131_073, 65537],+ [10, 65536],+ [0, 65536],+ [999_999_999, 65536]+ ])('before=%s maxBytes=%s returns exactly the expected bytes', (before, maxBytes) => {+ const p = write('big.jsonl', file)+ const got = page(p, before, maxBytes)+ const want = expected(file, before, maxBytes)+ expect(got.start).toBe(want.start)+ expect(got.end).toBe(want.end)+ expect(got.size).toBe(file.length)+ expect(got.data.equals(want.data)).toBe(true)+ })++ it('pages back to the start of the file with every line seen exactly once', () => {+ const p = write('big.jsonl', file)+ const seen: string[] = []+ let before: number | null = null+ for (let guard = 0; guard < 100; guard++) {+ const w = page(p, before, 65536)+ const r = parseChatWindow(w.data, w.start)+ seen.unshift(...r.messages.map((m) => (m.parts[0] as { text: string }).text))+ if (r.olderCursor === null) break+ before = r.olderCursor+ }+ expect(seen).toEqual(Array.from({ length: 3000 }, (_, i) => `satır ${i} — ğüşiöç ✓`))+ })++ it('an empty file is an answer (size 0, no bytes), not a failure', () => {+ const p = write('empty.jsonl', '')+ const got = page(p, null, 65536)+ expect(got).toMatchObject({ start: 0, end: 0, size: 0 })+ expect(got.data.length).toBe(0)+ })++ it('a missing file fails the command (non-zero exit), never an empty page', () => {+ expect(() => run(transcriptPageCommand(path.join(dir, 'nope.jsonl'), null, 65536))).toThrow()+ })++ it('a hostile path stays one quoted word', () => {+ // Runs with cwd = dir, so an injected `touch pwned` would leave the marker right here.+ const marker = path.join(dir, 'pwned')+ const evil = write(`x'; touch pwned; echo $(touch pwned) '.jsonl`, 'hello\n')+ const got = page(evil, null, 65536)+ expect(got.data.toString()).toBe('hello\n')+ expect(fs.existsSync(marker)).toBe(false)+ })+})diff --git a/src/core/remote-ssh/transcript-window.test.ts b/src/core/remote-ssh/transcript-window.test.tsindex 239cbfc6f..b5d280fd3 100644--- a/src/core/remote-ssh/transcript-window.test.ts+++ b/src/core/remote-ssh/transcript-window.test.ts@@ -1,5 +1,5 @@import { describe, expect, it } from 'vitest'-import { parseTranscriptWindow, transcriptWindowCommand } from './transcript-window'+import { parseTranscriptPage, parseTranscriptWindow, transcriptPageCommand, transcriptWindowCommand } from './transcript-window'const frame = (payload: string, status = 0): string => Buffer.from(payload + `\nNODETERM_READ_STATUS:${status}\n`).toString('base64')describe('strict transcript window framing', () => {@@ -22,3 +22,30 @@ describe('strict transcript window framing', () => {expect(() => transcriptWindowCommand('/fixture', null, cap)).toThrow()})})++describe('paged transcript read (⌘M panel) framing', () => {+ it('trims block alignment to exactly the asked range, lookbehind byte included', () => {+ const r = parseTranscriptPage('1 2 3\n' + frame('aéb'), 65536)+ expect(r.data).toEqual(Buffer.from('é'))+ expect(r).toMatchObject({ start: 1, end: 3, size: 3 })+ })+ it('an empty file is a valid empty page', () => {+ expect(parseTranscriptPage('0 0 0\n', 65536)).toMatchObject({ start: 0, end: 0, size: 0 })+ })+ it.each([+ 'bad\n', '0 5 4\n', '0 1 1 0\n' + frame('a'), '0 0 0\nAAAA',+ '0 1 1\n' + frame('a', 1), '0 1 1\n' + frame(''), '0 1 1\n' + Buffer.from('a').toString('base64')+ ])('rejects malformed, failed or short responses: %s', response => {+ expect(() => parseTranscriptPage(response, 65536)).toThrow()+ })+ it('rejects a reply wider than maxBytes + the lookbehind byte', () => {+ expect(() => parseTranscriptPage('0 3 3\n' + frame('abc'), 1)).toThrow()+ expect(parseTranscriptPage('0 2 2\n' + frame('ab'), 1).data.toString()).toBe('ab')+ })+ it.each([-1, 1.5, NaN, Infinity])('rejects an invalid before %s before invoking a shell', before => {+ expect(() => transcriptPageCommand('/fixture', before, 65536)).toThrow()+ })+ it.each([0, -1, 1.5, Infinity, 5 * 1024 * 1024 + 1])('rejects an invalid maxBytes %s', maxBytes => {+ expect(() => transcriptPageCommand('/fixture', null, maxBytes)).toThrow()+ })+})diff --git a/src/core/remote-ssh/transcript-window.ts b/src/core/remote-ssh/transcript-window.tsindex 5dc86770a..64408230b 100644--- a/src/core/remote-ssh/transcript-window.ts+++ b/src/core/remote-ssh/transcript-window.ts@@ -1,4 +1,5 @@import { posixQuote } from '../../shared/ssh'+import { CHAT_PAGE_MAX_BYTES } from '../../shared/chat-page'const BLOCK = 65536const STATUS = '\nNODETERM_READ_STATUS:0\n'@@ -42,10 +43,17 @@ export function parseTranscriptWindow(stdout: string, cap: number): TranscriptWiif (![start, count, size].every(Number.isSafeInteger) || count > cap || start + count > size) {throw new Error('Invalid transcript read range')}- const encoded = stdout.slice(end + 1).replace(/\s/g, '')+ const data = decodeFramedBlocks(stdout.slice(end + 1), start, count, cap)+ return { data, start, newOffset: start + count, initial: !!initial }+}++/** Decode the base64 dd payload shared by both commands: verify the in-band dd status, then trim+ * the block alignment back to exactly `count` bytes from `start`. */+function decodeFramedBlocks(payload: string, start: number, count: number, cap: number): Buffer {+ const encoded = payload.replace(/\s/g, '')if (!count) {if (encoded) throw new Error('Unexpected transcript read payload')- return { data: Buffer.alloc(0), start, newOffset: start, initial: !!initial }+ return Buffer.alloc(0)}const decoded = Buffer.from(encoded, 'base64')if (decoded.toString('base64') !== encoded || !decoded.subarray(-STATUS.length).equals(Buffer.from(STATUS))) {@@ -54,5 +62,61 @@ export function parseTranscriptWindow(stdout: string, cap: number): TranscriptWiconst bytes = decoded.subarray(0, -STATUS.length)const leading = start % BLOCKif (bytes.length < leading + count || bytes.length > cap + 2 * BLOCK) throw new Error('Short or oversized transcript read')- return { data: bytes.subarray(leading, leading + count), start, newOffset: start + count, initial: !!initial }+ return bytes.subarray(leading, leading + count)+}++/**+ * The ⌘M panel's PAGED read (`chat:read-transcript` with a page): at most `maxBytes` ending at+ * byte offset `before` (`null`, or past EOF = the file size), plus ONE byte of lookbehind when the+ * window does not start at 0 — `parseChatWindow` needs it to recognize a line that begins exactly+ * on the window edge. One round trip answers the size too, which is what "the end of the file"+ * means on the host.+ *+ * Same shape and guarantees as `transcriptWindowCommand` above (read-forward, for the context+ * tail): one fd opened up front, the size snapshotted once, whole dd blocks read and trimmed by+ * the parser, and the dd exit status carried INSIDE the base64 so a failed read cannot pass for a+ * short one. Only integers we validated here and a `posixQuote`d path reach the line; the path is+ * already jailed by `isSafeRemoteTranscriptPath` before any caller gets here.+ */+export function transcriptPageCommand(path: string, before: number | null, maxBytes: number): string {+ if ((before !== null && (!Number.isSafeInteger(before) || before < 0)) ||+ !Number.isSafeInteger(maxBytes) || maxBytes < 1 || maxBytes > CHAT_PAGE_MAX_BYTES) {+ throw new Error('Invalid transcript page bounds')+ }+ return `exec 3< ${posixQuote(path)} || exit 1+size=$(wc -c < ${posixQuote(path)}) || exit 1+size=$((size + 0))+end=${before ?? -1}+if [ "$end" -lt 0 ] || [ "$end" -gt "$size" ]; then end=$size; fi+start=$((end > ${maxBytes} ? end - ${maxBytes} - 1 : 0))+count=$((end - start))+printf '%s %s %s\n' "$start" "$count" "$size"+if [ "$count" -gt 0 ]; then+ skip=$((start / ${BLOCK}))+ blocks=$(((start % ${BLOCK} + count + ${BLOCK - 1}) / ${BLOCK}))+ { dd bs=${BLOCK} skip="$skip" count="$blocks" <&3 2>/dev/null; result=$?; printf '\nNODETERM_READ_STATUS:%s\n' "$result"; } | base64+fi`+}++export interface TranscriptPage {+ /** Bytes `[start, end)` of the file — `start` includes the lookbehind byte, when there is one. */+ data: Buffer+ start: number+ end: number+ size: number+}++/** Strict parser for `transcriptPageCommand`'s reply: anything malformed, short or failed throws. */+export function parseTranscriptPage(stdout: string, maxBytes: number): TranscriptPage {+ const nl = stdout.indexOf('\n')+ const match = /^(\d+) (\d+) (\d+)$/.exec(stdout.slice(0, nl))+ if (!match) throw new Error('Invalid transcript page header')+ const [start, count, size] = match.slice(1).map(Number)+ // +1: the lookbehind byte rides on top of the window.+ const cap = maxBytes + 1+ if (![start, count, size].every(Number.isSafeInteger) || count > cap || start + count > size) {+ throw new Error('Invalid transcript page range')+ }+ const data = decodeFramedBlocks(stdout.slice(nl + 1), start, count, cap)+ return { data, start, end: start + count, size }}diff --git a/src/core/transcript-ipc.test.ts b/src/core/transcript-ipc.test.tsindex 6bae361e4..12f8ee6d8 100644--- a/src/core/transcript-ipc.test.ts+++ b/src/core/transcript-ipc.test.ts@@ -272,3 +272,129 @@ describe('registerTranscriptIpc — transcript presence', () => {})})})++// ─────────────────────────────────────────────────────────────────────────────────────────────+// Paged chat reads — the trailing optional `page` argument. Absent = the legacy read (every test+// above), present = one byte window plus the paging fields.+// ─────────────────────────────────────────────────────────────────────────────────────────────+describe('registerTranscriptIpc — paged chat reads', () => {+ const paged = (page: unknown, nodeId?: string, agentId?: string) =>+ f.handlers[IPC.chatReadTranscript](+ SID,+ CWD,+ undefined,+ nodeId,+ agentId,+ page+ ) as Promise<ChatTranscriptResult>++ const bigBody = (n: number): string => {+ const out: object[] = []+ for (let i = 0; i < n; i++) out.push(i % 2 ? assistantLine(`a${i} ${'x'.repeat(200)}`) : userLine(`u${i} ${'y'.repeat(200)}`))+ return lines(...out)+ }++ it('legacy (no page) result carries none of the paging fields', async () => {+ writeTranscript(lines(userLine('merhaba')))+ registerTranscriptIpc()+ const res = await chat()+ expect(Object.keys(res).sort()).toEqual(['found', 'messages'])+ expect(res.messages[0]).not.toHaveProperty('key')+ })++ it('reads only the newest window, keyed, with a cursor to page back to the start', async () => {+ const body = bigBody(1000) // ~220 KB+ const p = writeTranscript(body)+ registerTranscriptIpc()+ const first = await paged({ maxBytes: 65536 })+ expect(first.found).toBe(true)+ expect(first.messages.length).toBeGreaterThan(0)+ expect(first.messages.length).toBeLessThan(1000)+ expect(typeof first.olderCursor).toBe('number')+ expect(first.unmatchedResults).toEqual([])+ const all = [...first.messages]+ let cursor = first.olderCursor+ while (cursor !== null && cursor !== undefined) {+ const older = await paged({ before: cursor, maxBytes: 65536 })+ expect(older.olderCursor === null || older.olderCursor! < cursor).toBe(true)+ all.unshift(...older.messages)+ cursor = older.olderCursor+ }+ expect(all.length).toBe(1000)+ // Keys are unique absolute offsets of real line starts.+ const text = fs.readFileSync(p)+ for (const m of all) expect(m.key === 0 || text[m.key! - 1] === 0x0a).toBe(true)+ expect(new Set(all.map((m) => m.key)).size).toBe(1000)+ })++ it('an unresolvable transcript is still not-found, with no cursor to follow', async () => {+ registerTranscriptIpc()+ expect(await paged({})).toEqual({ messages: [], found: false, olderCursor: null, unmatchedResults: [] })+ })++ it('rejects a forged `before` instead of reading some other window', async () => {+ writeTranscript(lines(userLine('merhaba')))+ registerTranscriptIpc()+ await expect(paged({ before: -5 })).rejects.toThrow(/Invalid transcript page/)+ await expect(paged({ before: '1; id' })).rejects.toThrow(/Invalid transcript page/)+ })++ it('grok does not page: its whole read, olderCursor null', async () => {+ const GROK_SID = '01a06126-b981-73f1-8b68-4547e4d7da84'+ const dir = path.join(home, '.grok', 'sessions', 'proj', GROK_SID)+ fs.mkdirSync(dir, { recursive: true })+ fs.writeFileSync(path.join(dir, 'chat_history.jsonl'), lines({ type: 'user', content: 'hey grok' }))+ rememberGrokSessionDir(GROK_SID, dir)+ registerTranscriptIpc()+ const res = (await f.handlers[IPC.chatReadTranscript](+ GROK_SID, CWD, undefined, undefined, 'grok', { maxBytes: 65536 }+ )) as ChatTranscriptResult+ expect(res.found).toBe(true)+ expect(res.olderCursor).toBeNull()+ expect(res.unmatchedResults).toEqual([])+ expect(JSON.stringify(res.messages)).toContain('hey grok')+ })++ describe('the remote leg', () => {+ it('asks the host for the RANGED window and parses it like the local one', async () => {+ writeTranscript(lines(assistantLine('the LOCAL machine')))+ const body = Buffer.from(lines(userLine('older'), assistantLine('on the HOST')))+ const asked: unknown[] = []+ registerTranscriptIpc({+ readRemote: async () => {+ throw new Error('the paged read must not pull the legacy 5 MB tail')+ },+ readRemotePage: async (_q, page) => {+ asked.push(page)+ const start = 10+ return { ok: true, data: body.subarray(start), start }+ }+ })+ const res = await paged({ maxBytes: 70000 }, 'nt-1')+ expect(asked).toEqual([{ before: null, maxBytes: 70000 }])+ expect(res.found).toBe(true)+ expect(res.messages.map((m) => m.role)).toEqual(['assistant'])+ expect(JSON.stringify(res.messages)).toContain('on the HOST')+ expect(res.olderCursor).toBe(body.indexOf(0x0a) + 1)+ })++ it('a failed host read is not-found — never an empty conversation, never the local disk', async () => {+ writeTranscript(lines(assistantLine('the LOCAL machine')))+ registerTranscriptIpc({ readRemotePage: async () => ({ ok: false }) })+ expect(await paged({}, 'nt-1')).toEqual({+ messages: [],+ found: false,+ olderCursor: null,+ unmatchedResults: []+ })+ })++ it('null means "not a remote session" — the local path pages', async () => {+ writeTranscript(lines(assistantLine('local')))+ registerTranscriptIpc({ readRemotePage: async () => null })+ const res = await paged({}, 'nt-1')+ expect(res.messages[0].parts[0]).toMatchObject({ text: 'local' })+ expect(res.olderCursor).toBeNull()+ })+ })+})diff --git a/src/core/transcript-ipc.ts b/src/core/transcript-ipc.tsindex 8cf0d6644..93403235d 100644--- a/src/core/transcript-ipc.ts+++ b/src/core/transcript-ipc.ts@@ -12,12 +12,15 @@import fsp from 'node:fs/promises'import { IPC } from '../shared/ipc'import type { ChatTranscriptResult, TranscriptLine, TranscriptPresence } from '../shared/types'+import { normalizeChatPage, type ChatTranscriptPage } from '../shared/chat-page'import { platform } from './platform'import { chatMessagesFromGrok } from './grok-chat'import { locateGrok } from './handoff/locate'import {parseChatMessages,+ parseChatWindow,parseTranscriptLines,+ readChatWindow,readCappedTail,readChatMessages,readTranscriptLines,@@ -53,6 +56,60 @@ export interface TranscriptIpcDeps {* host and report `absent` — the one answer that destroys a resume. Electron-only.*/remoteExists?(q: TranscriptQuery): Promise<TranscriptPresence | null>+ /**+ * ONE page of a REMOTE node's transcript — a ranged read on the host, so a paged ⌘M open moves+ * a window over ssh instead of the legacy 5 MB tail. `null` = not a remote session (same+ * convention as `readRemote`); `{ok:false}` = it IS remote and the host could not be read, which+ * must end as not-found rather than fall through to THIS machine's disk. `data` is the file's+ * bytes from absolute offset `start` (one lookbehind byte included — see `parseChatWindow`).+ * Electron-only.+ */+ readRemotePage?(q: TranscriptQuery, page: ChatTranscriptPage): Promise<RemoteTranscriptPage | null>+}++export type RemoteTranscriptPage = { ok: true; data: Buffer; start: number } | { ok: false }++const notFoundPage = (): ChatTranscriptResult => ({+ messages: [],+ found: false,+ olderCursor: null,+ unmatchedResults: []+})++/**+ * A paged chat read (`chat:read-transcript` with its trailing `page` argument). Kept apart from the+ * legacy branch so the unpaged result stays byte-for-byte what it was.+ *+ * Remote first, as in the legacy path, and a remote failure is TERMINAL: a remote session's+ * transcript lives on the host, so falling through to the local resolver would answer from the+ * wrong machine. A shell that injects only the legacy `readRemote` (none does today) still gets a+ * correct — unpaged — answer from it rather than a local one.+ */+async function readChatPage(+ q: TranscriptQuery,+ page: ChatTranscriptPage,+ deps: TranscriptIpcDeps+): Promise<ChatTranscriptResult> {+ if (deps.readRemotePage) {+ const remote = await deps.readRemotePage(q, page)+ if (remote !== null) {+ if (!remote.ok) return notFoundPage()+ return { found: true, ...parseChatWindow(remote.data, remote.start) }+ }+ } else if (deps.readRemote) {+ const text = await deps.readRemote(q)+ if (text !== null) {+ return text+ ? { messages: parseChatMessages(text.split('\n')), found: true, olderCursor: null, unmatchedResults: [] }+ : notFoundPage()+ }+ }+ const p = await resolveTranscript(q, deps.pathFor)+ if (!p) return notFoundPage()+ const w = await readChatWindow(p, page)+ // Resolved but unreadable (deleted between resolve and read): not-found, like a failed remote.+ if (!w) return notFoundPage()+ return { found: true, ...parseChatWindow(w.data, w.start) }}/**@@ -127,8 +184,12 @@ export function registerTranscriptIpc(deps: TranscriptIpcDeps = {}): void {cwd: string | undefined,accountId: string | undefined,nodeId: string | undefined,- agentId: string | undefined+ agentId: string | undefined,+ rawPage?: unknown): Promise<ChatTranscriptResult> => {+ // Validated FIRST: it arrived over IPC / the WS bridge, and `before` reaches a remote shell+ // line. `null` = no page asked for = the legacy read below, byte for byte.+ const page = normalizeChatPage(rawPage)// Routed by agent BEFORE anything claude-shaped runs. `resolveTranscript` below falls back to// the newest claude transcript for the cwd when its sessionId leg misses, and a grok id always// misses — so reaching that fallback with a grok node would answer with a stranger's@@ -136,12 +197,17 @@ export function registerTranscriptIpc(deps: TranscriptIpcDeps = {}): void {// node is served locally or not at all rather than being handed the wrong host's claude log.if (agentId === 'grok') {const gp = sessionId ? await locateGrok(sessionId) : undefined- if (!gp) return { messages: [], found: false }+ // Grok does NOT page: its history is small and its reader has no byte-offset keys, so a+ // paged request gets the whole (capped) read with `olderCursor: null` — "nothing older to+ // fetch" — and no carried results. Keys are absent; the panel falls back to its own.+ const paging = page ? { olderCursor: null, unmatchedResults: [] } : {}+ if (!gp) return { messages: [], found: false, ...paging }const buf = await readCappedTail(gp)return buf === undefined- ? { messages: [], found: false }- : { messages: chatMessagesFromGrok(buf), found: true }+ ? { messages: [], found: false, ...paging }+ : { messages: chatMessagesFromGrok(buf), found: true, ...paging }}+ if (page) return readChatPage({ sessionId, cwd, accountId, nodeId }, page, deps)const remote = await remoteText({ sessionId, cwd, accountId, nodeId })// A resolved-but-unreadable remote file is NOT "no conversation yet" — the read failed// (master down, transcript gone), and the panel must be able to say so.diff --git a/src/core/transcript-reader.test.ts b/src/core/transcript-reader.test.tsindex 9d7d3289d..ef66677a9 100644--- a/src/core/transcript-reader.test.ts+++ b/src/core/transcript-reader.test.ts@@ -101,3 +101,201 @@ describe('readSessionName — remote (SSH project) sessions', () => {expect(await readSessionName(sid)).toBeNull()})})++// ─────────────────────────────────────────────────────────────────────────────────────────────+// Paged chat reads (the ⌘M panel's progressive loading). A window is `[start, end)` in BYTES of the+// transcript file; `parseChatWindow` is the pure half, `readChatWindow` the fs half.+// ─────────────────────────────────────────────────────────────────────────────────────────────+import os from 'os'+import path from 'path'+import { parseChatMessages, parseChatWindow, readChatWindow } from './transcript-reader'++const jl = (o: object): string => JSON.stringify(o) + '\n'+const said = (role: 'user' | 'assistant', text: string): string =>+ role === 'user'+ ? jl({ type: 'user', message: { content: text } })+ : jl({ type: 'assistant', message: { content: [{ type: 'text', text }] } })+const toolUse = (id: string, command: string): string =>+ jl({+ type: 'assistant',+ message: { content: [{ type: 'tool_use', id, name: 'Bash', input: { command } }] }+ })+const toolResult = (id: string, out: string): string =>+ jl({ type: 'user', message: { content: [{ type: 'tool_result', tool_use_id: id, content: out }] } })++const textOfMsg = (m: { parts: Array<{ kind: string; text?: string }> }): string =>+ m.parts.map((p) => p.text ?? '').join('')++describe('parseChatWindow — pure window parsing', () => {+ it('a window starting at 0 parses every line and reports it reached the start', () => {+ const file = Buffer.from(said('user', 'a') + said('assistant', 'b'))+ const r = parseChatWindow(file, 0)+ expect(r.olderCursor).toBeNull()+ expect(r.messages.map(textOfMsg)).toEqual(['a', 'b'])+ })++ it('keys each message by the ABSOLUTE byte offset of its source line', () => {+ const l1 = said('user', 'first')+ const l2 = said('assistant', 'ğüşé multibyte') // byte length != string length+ const l3 = said('user', 'third')+ const file = Buffer.from(l1 + l2 + l3)+ const r = parseChatWindow(file, 0)+ const b1 = Buffer.byteLength(l1)+ const b2 = Buffer.byteLength(l2)+ expect(r.messages.map((m) => m.key)).toEqual([0, b1, b1 + b2])+ // The same line read through a later window keeps its key — a prepend never re-keys.+ const tail = parseChatWindow(file.subarray(b1 - 1), b1 - 1)+ expect(tail.messages.map((m) => m.key)).toEqual([b1, b1 + b2])+ })++ it('drops the partial leading line and points olderCursor at the first COMPLETE line', () => {+ const l1 = said('user', 'x'.repeat(50))+ const l2 = said('assistant', 'kept')+ const file = Buffer.from(l1 + l2)+ const start = 10 // mid-l1+ const r = parseChatWindow(file.subarray(start), start)+ expect(r.messages.map(textOfMsg)).toEqual(['kept'])+ expect(r.olderCursor).toBe(Buffer.byteLength(l1))+ })++ it('keeps a line that begins exactly on the window edge when the caller passes the one-byte lookbehind', () => {+ // The byte BEFORE the window is the only way to know a line starts exactly on its edge, which+ // is why readChatWindow reads one byte of lookbehind. Without it that line would be dropped as+ // "partial" — and, being the window's only line, skipped for good.+ const l1 = said('user', 'one')+ const l2 = said('assistant', 'two')+ const file = Buffer.from(l1 + l2)+ const edge = Buffer.byteLength(l1)+ const r = parseChatWindow(file.subarray(edge - 1), edge - 1)+ expect(r.messages.map(textOfMsg)).toEqual(['two'])+ expect(r.olderCursor).toBe(edge)+ })++ it('never returns an olderCursor equal to the window end (a line larger than the window is skipped, not looped on)', () => {+ const huge = said('user', 'h'.repeat(300))+ const file = Buffer.from(huge)+ const start = 100+ const r = parseChatWindow(file.subarray(start), start)+ expect(r.messages).toEqual([])+ expect(r.olderCursor).toBe(start) // strictly older than the window end → paging progresses+ })++ it('pages stitched together equal the unpaged parse, with no line lost or duplicated', () => {+ let body = ''+ for (let i = 0; i < 40; i++) body += said(i % 2 ? 'assistant' : 'user', `msg ${i} ç`)+ const file = Buffer.from(body)+ const whole = parseChatWindow(file, 0).messages+ const pages: (typeof whole)[] = []+ let end = file.length+ for (;;) {+ const winStart = Math.max(0, end - 200)+ const start = winStart > 0 ? winStart - 1 : 0 // one byte of lookbehind, as the reader does+ const r = parseChatWindow(file.subarray(start, end), start)+ pages.unshift(r.messages)+ if (r.olderCursor === null) break+ expect(r.olderCursor).toBeLessThan(end)+ end = r.olderCursor+ }+ expect(pages.flat()).toEqual(whole)+ expect(whole.map(textOfMsg)).toEqual(Array.from({ length: 40 }, (_, i) => `msg ${i} ç`))+ })++ it('gives tool parts their tool_use id and matches results inside one window', () => {+ const r = parseChatWindow(Buffer.from(toolUse('t1', 'ls') + toolResult('t1', 'a.txt')), 0)+ expect(r.messages[0].parts[0]).toMatchObject({ kind: 'tool', id: 't1', arg: 'ls', result: 'a.txt' })+ expect(r.unmatchedResults).toEqual([])+ })++ it('carries a result whose tool_use lives in an OLDER window (the page boundary case)', () => {+ const older = toolUse('t9', 'make build')+ const newer = toolResult('t9', 'build ok') + said('assistant', 'done')+ const file = Buffer.from(older + newer)+ const split = Buffer.byteLength(older)+ // Newest page first — its result has no tool to land on.+ const newest = parseChatWindow(file.subarray(split - 1), split - 1)+ expect(newest.messages.map(textOfMsg)).toEqual(['done'])+ expect(newest.unmatchedResults).toEqual([{ id: 't9', result: 'build ok' }])+ expect(newest.olderCursor).toBe(split)+ // The older page carries the tool with the id the carried result names, and no result of its own.+ const olderPage = parseChatWindow(file.subarray(0, newest.olderCursor!), 0)+ const tool = olderPage.messages[0].parts[0]+ expect(tool).toMatchObject({ kind: 'tool', id: 't9' })+ expect((tool as { result?: string }).result).toBeUndefined()+ })++ it('the legacy parser is untouched: no keys, no tool ids', () => {+ const msgs = parseChatMessages((toolUse('t1', 'ls') + toolResult('t1', 'x') + said('user', 'u')).split('\n'))+ expect(msgs).toEqual([+ { role: 'assistant', parts: [{ kind: 'tool', name: 'Bash', arg: 'ls', result: 'x' }] },+ { role: 'user', parts: [{ kind: 'text', text: 'u' }] }+ ])+ })+})++describe('readChatWindow — byte windows read from a real file', () => {+ let dir: string+ afterEach(() => {+ if (dir) fs.rmSync(dir, { recursive: true, force: true })+ })+ const write = (body: string | Buffer): string => {+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-chat-window-'))+ const p = path.join(dir, 't.jsonl')+ fs.writeFileSync(p, body)+ return p+ }++ it('reads the newest window ending at EOF when `before` is null', async () => {+ const l1 = said('user', 'old')+ const l2 = said('assistant', 'new')+ const p = write(l1 + l2)+ const w = await readChatWindow(p, { before: null, maxBytes: Buffer.byteLength(l2) + 3 })+ expect(w).toBeDefined()+ expect(w!.start).toBe(Buffer.byteLength(l1) - 3 - 1) // window start minus the lookbehind byte+ const r = parseChatWindow(w!.data, w!.start)+ expect(r.messages.map(textOfMsg)).toEqual(['new'])+ })++ it('clamps a `before` past EOF to the file size and reads the whole of a small file', async () => {+ const p = write(said('user', 'only'))+ const w = await readChatWindow(p, { before: 10_000_000, maxBytes: 65536 })+ expect(w!.start).toBe(0)+ expect(w!.end).toBe(fs.statSync(p).size)+ expect(parseChatWindow(w!.data, 0).messages.map(textOfMsg)).toEqual(['only'])+ })++ it('a multi-byte UTF-8 character straddling the window edge never corrupts a returned message', async () => {+ const l1 = said('user', 'ğğğğğğğğ') // every char is 2 bytes+ const l2 = said('assistant', 'çok güzel — ✓')+ const file = Buffer.from(l1 + l2)+ const p = write(file)+ // Start the window one byte INTO a 2-byte char of l1.+ const firstG = file.indexOf(Buffer.from('ğ'))+ const start = firstG + 1+ const w = await readChatWindow(p, { before: null, maxBytes: file.length - start })+ expect(w!.start).toBe(start - 1) // the lookbehind byte is the FIRST byte of that ğ+ const r = parseChatWindow(w!.data, w!.start)+ expect(r.messages.map(textOfMsg)).toEqual(['çok güzel — ✓'])+ expect(JSON.stringify(r.messages)).not.toContain('�')+ expect(r.olderCursor).toBe(Buffer.byteLength(l1))+ // …and the older page re-reads l1 whole, straddling char included.+ const w2 = await readChatWindow(p, { before: r.olderCursor, maxBytes: 65536 })+ expect(parseChatWindow(w2!.data, w2!.start).messages.map(textOfMsg)).toEqual(['ğğğğğğğğ'])+ })++ it('a window whose edge falls exactly on a line start keeps that line (one byte of lookbehind)', async () => {+ const l1 = said('user', 'a'.repeat(100))+ const l2 = said('assistant', 'exactly-fits')+ const l3 = said('user', 'newer')+ const p = write(l1 + l2 + l3)+ const before = Buffer.byteLength(l1 + l2)+ const w = await readChatWindow(p, { before, maxBytes: Buffer.byteLength(l2) })+ expect(w!.end).toBe(before)+ const r = parseChatWindow(w!.data, w!.start)+ expect(r.messages.map(textOfMsg)).toEqual(['exactly-fits'])+ expect(r.olderCursor).toBe(Buffer.byteLength(l1))+ })++ it('returns undefined for an unreadable file', async () => {+ expect(await readChatWindow('/nonexistent/nt/x.jsonl', { before: null, maxBytes: 65536 })).toBeUndefined()+ })+})diff --git a/src/core/transcript-reader.ts b/src/core/transcript-reader.tsindex 1388c44e1..374a8713d 100644--- a/src/core/transcript-reader.ts+++ b/src/core/transcript-reader.ts@@ -4,7 +4,7 @@import fs from 'fs'import os from 'os'import path from 'path'-import type { TranscriptLine, ChatMessage, ChatPart } from '../shared/types'+import type { TranscriptLine, ChatMessage, ChatPart, ChatCarriedToolResult } from '../shared/types'import { transcriptRootFor } from './claude-accounts-core'import { linkedClaudeConfigDirFor } from './claude-config-dir'import { platform } from './platform'@@ -128,10 +128,25 @@ export async function readTranscriptLines(filePath: string): Promise<TranscriptL// text + tool_use blocks become one message's ordered parts; a later user-line tool_result is// correlated back onto its tool part by tool_use_id. User lines that carry only tool_results// (no prose) are NOT rendered as bubbles — they're tool output, attached to the tool instead.-export function parseChatMessages(rawLines: string[]): ChatMessage[] {+//+// `paged` switches on the three things only a paged read needs (and the legacy result must NOT+// grow, byte for byte): a `key` per message (its line's absolute byte offset), the `tool_use` id on+// each tool part, and the list of results whose tool was not among these lines.+interface ChatRecordsOut {+ messages: ChatMessage[]+ unmatched: Map<string, string>+}+function parseChatRecords(+ records: Iterable<{ raw: string; offset: number }>,+ paged: boolean+): ChatRecordsOut {const messages: ChatMessage[] = []+ const unmatched = new Map<string, string>()const toolById = new Map<string, Extract<ChatPart, { kind: 'tool' }>>()- for (const raw of rawLines) {+ const push = (m: ChatMessage, offset: number): void => {+ messages.push(paged ? { ...m, key: offset } : m)+ }+ for (const { raw, offset } of records) {if (!raw.trim()) continuelet o: { type?: string; message?: { content?: unknown } }try {@@ -156,11 +171,12 @@ export function parseChatMessages(rawLines: string[]): ChatMessage[] {name: c.name ?? 'tool',arg: toolArg(c.input)}+ if (paged && typeof c.id === 'string' && c.id) part.id = c.idparts.push(part)if (c.id) toolById.set(c.id, part)}}- if (parts.length) messages.push({ role: 'assistant', parts })+ if (parts.length) push({ role: 'assistant', parts }, offset)} else if (o.type === 'user' && Array.isArray(content)) {const parts: ChatPart[] = []for (const c of content as Array<{@@ -172,18 +188,117 @@ export function parseChatMessages(rawLines: string[]): ChatMessage[] {if (c.type === 'text' && c.text) parts.push({ kind: 'text', text: c.text })else if (c.type === 'tool_result') {const tool = c.tool_use_id ? toolById.get(c.tool_use_id) : undefined+ const s = summarizeResult(c.content)if (tool) {- const s = summarizeResult(c.content)if (s) tool.result = s+ } else if (paged && s && typeof c.tool_use_id === 'string' && c.tool_use_id) {+ // Its tool_use is in an OLDER window (claude writes the call before its result, so it+ // can never be in a newer one). Carried so the renderer can attach it later.+ unmatched.set(c.tool_use_id, s)}}}- if (parts.length) messages.push({ role: 'user', parts })+ if (parts.length) push({ role: 'user', parts }, offset)} else if (o.type === 'user' && typeof content === 'string' && content.trim()) {- messages.push({ role: 'user', parts: [{ kind: 'text', text: content }] })+ push({ role: 'user', parts: [{ kind: 'text', text: content }] }, offset)+ }+ }+ return { messages, unmatched }+}++export function parseChatMessages(rawLines: string[]): ChatMessage[] {+ return parseChatRecords(+ rawLines.map((raw) => ({ raw, offset: 0 })),+ false+ ).messages+}++/** A paged chat read's answer, minus `found` (the caller knows whether anything resolved). */+export interface ChatWindowParse {+ messages: ChatMessage[]+ olderCursor: number | null+ unmatchedResults: ChatCarriedToolResult[]+}++/**+ * Parse one byte window of a transcript. PURE — the local reader and the remote (SSH) leg hand it+ * the same kind of buffer, so both sides page identically.+ *+ * `buf` holds the file's bytes from absolute offset `bufStart` to the window end. When `bufStart`+ * is not 0, everything up to and including the first `\n` is dropped as a partial line, and+ * `olderCursor` is the offset right after that newline — where the first COMPLETE line starts,+ * i.e. the `before` of the next older page. Callers should start `buf` ONE BYTE before the window+ * they want (`readChatWindow` / `transcriptPageCommand` do): that lookbehind byte is the only way+ * to recognize a line that begins exactly on the window edge; without it such a line would be+ * dropped as partial.+ *+ * Working in bytes, not a decoded string, is what keeps the offsets exact: a line's key is the+ * absolute byte offset of its first byte, which a prepend or an append can never change, and a+ * multi-byte character cut by the window edge only ever lands in the dropped partial line (each+ * kept line is decoded on its own, from newline to newline).+ *+ * A line longer than the whole window leaves no complete line in it. `olderCursor` is then+ * `bufStart` — strictly older than the window end — so paging keeps moving and that one oversized+ * record is skipped. Answering the window end instead would ask for the identical window forever.+ */+export function parseChatWindow(buf: Buffer, bufStart: number): ChatWindowParse {+ const end = bufStart + buf.length+ let from = 0+ let olderCursor: number | null = null+ if (bufStart > 0) {+ const nl = buf.indexOf(0x0a)+ if (nl < 0 || bufStart + nl + 1 >= end) {+ return { messages: [], olderCursor: bufStart, unmatchedResults: [] }}+ from = nl + 1+ olderCursor = bufStart + from+ }+ const records: Array<{ raw: string; offset: number }> = []+ while (from < buf.length) {+ const nl = buf.indexOf(0x0a, from)+ const to = nl < 0 ? buf.length : nl+ if (to > from) records.push({ raw: buf.toString('utf8', from, to), offset: bufStart + from })+ from = to + 1+ }+ const { messages, unmatched } = parseChatRecords(records, true)+ return {+ messages,+ olderCursor,+ unmatchedResults: [...unmatched].map(([id, result]) => ({ id, result }))+ }+}++/**+ * Read one window of a transcript for `parseChatWindow`: at most `maxBytes` ending at `before`+ * (`null`, or past EOF = the file size), plus one byte of lookbehind when the window does not start+ * at 0. `start` is the absolute offset of `data[0]` (the lookbehind byte, when there is one); `end`+ * the window end actually used. Undefined when the file cannot be read.+ */+export async function readChatWindow(+ filePath: string,+ page: { before: number | null; maxBytes: number }+): Promise<{ data: Buffer; start: number; end: number } | undefined> {+ try {+ const fd = await fs.promises.open(filePath, 'r')+ try {+ const { size } = await fd.stat()+ const end = page.before === null || page.before > size ? size : page.before+ const windowStart = Math.max(0, end - page.maxBytes)+ const start = windowStart > 0 ? windowStart - 1 : 0+ const length = end - start+ if (length <= 0) return { data: Buffer.alloc(0), start, end }+ const { buffer, bytesRead } = await fd.read({+ position: start,+ length,+ buffer: Buffer.alloc(length)+ })+ return { data: buffer.subarray(0, bytesRead), start, end: start + bytesRead }+ } finally {+ await fd.close()+ }+ } catch {+ return undefined}- return messages}export async function readChatMessages(filePath: string): Promise<ChatMessage[]> {diff --git a/src/main/index.ts b/src/main/index.tsindex 94f716b8a..0e4dea53b 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -2655,6 +2655,21 @@ app.whenReady().then(async () => {const ref = await remoteTranscriptRefFor(sessionId, cwd, accountId, nodeId)return ref ? await readRemoteTranscript(sessionId!, ref) : null},+ // The paged ⌘M read: a RANGED read on the host (window + file size in one ssh round trip)+ // instead of `readTail`'s 5 MB, which this leg used to pull on every panel open and every+ // turn-end reload. Same ref resolution and same forget-a-located-ref-on-failure rule as+ // `readRemoteTranscript`; the path it reads is already jailed by `isSafeRemoteTranscriptPath`.+ readRemotePage: async ({ sessionId, cwd, accountId, nodeId }, page) => {+ const ref = await remoteTranscriptRefFor(sessionId, cwd, accountId, nodeId)+ if (!ref) return null+ try {+ const w = await remoteFile.readTranscriptPage(ref, page.before, page.maxBytes)+ return { ok: true, data: w.data, start: w.start }+ } catch {+ if (locatedTranscriptSessions.delete(sessionId!)) remoteTranscriptBySession.delete(sessionId!)+ return { ok: false }+ }+ },remoteExists: async ({ sessionId, accountId, nodeId }) =>sessionId ? await remoteTranscriptPresence(sessionId, accountId, nodeId) : null})diff --git a/src/main/remote-ssh/remote-file.test.ts b/src/main/remote-ssh/remote-file.test.tsindex 5289dc5b9..05b549eb3 100644--- a/src/main/remote-ssh/remote-file.test.ts+++ b/src/main/remote-ssh/remote-file.test.ts@@ -100,3 +100,28 @@ describe('RemoteFile.readContextWindow', () => {await expect(new RemoteFile(async () => ({ code: 0, stdout: 'invalid' })).readContextWindow(ref, 42, 1024)).rejects.toThrow()})})++describe('RemoteFile.readTranscriptPage', () => {+ const framed = (payload: string): string =>+ Buffer.from(payload + '\nNODETERM_READ_STATUS:0\n').toString('base64')+ it('runs the ranged page command over the master and returns the exact bytes', async () => {+ let seen: string[] = []+ const rf = new RemoteFile(async (args) => {+ seen = args+ return { code: 0, stdout: '0 3 3\n' + framed('abc') }+ })+ const page = await rf.readTranscriptPage(ref, null, 65536)+ expect(page.data.toString()).toBe('abc')+ expect(page).toMatchObject({ start: 0, end: 3, size: 3 })+ expect(seen.join(' ')).toContain('NODETERM_READ_STATUS')+ })+ it('throws on transport failure or a malformed reply — never an empty page', async () => {+ for (const run of [+ async () => ({ code: 1, stdout: '' }),+ async () => ({ code: 0, stdout: 'junk' }),+ async () => { throw new Error('offline') }+ ]) {+ await expect(new RemoteFile(run).readTranscriptPage(ref, 10, 65536)).rejects.toThrow()+ }+ })+})diff --git a/src/main/remote-ssh/remote-file.ts b/src/main/remote-ssh/remote-file.tsindex 41014ca94..f6f665ad1 100644--- a/src/main/remote-ssh/remote-file.ts+++ b/src/main/remote-ssh/remote-file.ts@@ -1,7 +1,14 @@// Reads remote files over the project's existing ControlMaster (`ssh <childArgs> 'tail …'`).// Pure builders + an injected-runner class so the read logic is electron-free and unit-testable;// the actual ssh spawn is injected by the caller (Tasks 2/3 wire it to the project's runner).-import { transcriptWindowCommand, parseTranscriptWindow, type TranscriptWindow } from '../../core/remote-ssh/transcript-window'+import {+ transcriptWindowCommand,+ parseTranscriptWindow,+ transcriptPageCommand,+ parseTranscriptPage,+ type TranscriptWindow,+ type TranscriptPage+} from '../../core/remote-ssh/transcript-window'import { childArgs } from '../../core/remote-ssh/control-master'import { posixQuote, type SshConnection } from '../../shared/ssh'@@ -41,6 +48,19 @@ export class RemoteFile {return parseTranscriptWindow(stdout, cap)}+ /**+ * One PAGE of a transcript for the ⌘M panel — a ranged read (window end + size in the same round+ * trip) instead of `readTail`'s whole 5 MB. STRICT like `readContextWindow`: a failed or malformed+ * read throws, because the caller must be able to tell "the host could not be read" from "an+ * empty page" (the latter is a real answer for an empty transcript).+ */+ async readTranscriptPage(ref: RemoteFileRef, before: number | null, maxBytes: number): Promise<TranscriptPage> {+ const { code, stdout } = await this.run(childArgs(ref.conn, ref.controlPath,+ transcriptPageCommand(ref.path, before, maxBytes)))+ if (code !== 0) throw new Error('Remote transcript command failed')+ return parseTranscriptPage(stdout, maxBytes)+ }+async readFrom(ref: RemoteFileRef, offset: number): Promise<{ text: string; newOffset: number }> {try {const { code, stdout } = await this.run(tailFromOffsetArgs(ref.conn, ref.controlPath, ref.path, offset))diff --git a/src/preload/index.ts b/src/preload/index.tsindex e81e246bc..228751888 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -555,8 +555,8 @@ const api: NodeTerminalApi = {clearGatewayCredential: () => ipcRenderer.invoke(IPC.agentGatewayCredentialClear)},chat: {- readTranscript: (sessionId, cwd, accountId, nodeId, agentId) =>- ipcRenderer.invoke(IPC.chatReadTranscript, sessionId, cwd, accountId, nodeId, agentId),+ readTranscript: (sessionId, cwd, accountId, nodeId, agentId, page) =>+ ipcRenderer.invoke(IPC.chatReadTranscript, sessionId, cwd, accountId, nodeId, agentId, page),transcriptExists: (sessionId, accountId, nodeId) =>ipcRenderer.invoke(IPC.transcriptExists, sessionId, accountId, nodeId)},diff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.tsindex 0124f92d1..6b5fb11bf 100644--- a/src/renderer/bridge/ws-bridge.ts+++ b/src/renderer/bridge/ws-bridge.ts@@ -937,14 +937,17 @@ export function buildTranscriptApi(): Pick<NodeTerminalApi, 'chat'> & { claudeReadTranscript: ClaudeApi['readTranscript'] } {return {chat: {- readTranscript: (sessionId, cwd, accountId, nodeId, agentId) =>+ // `page` rides through untouched: the server validates it (`normalizeChatPage`) — the+ // browser is the untrusted side of this wire, so checking it here would prove nothing.+ readTranscript: (sessionId, cwd, accountId, nodeId, agentId, page) =>client.request(IPC.chatReadTranscript,sessionId,cwd,accountId,nodeId,- agentId+ agentId,+ page) as Promise<ChatTranscriptResult>,// A REAL implementation, not a stub: the server runs on the machine holding these// transcripts, so its answer is as good as the desktop's local leg. A failed requestdiff --git a/src/shared/chat-page.test.ts b/src/shared/chat-page.test.tsnew file mode 100644index 000000000..cb53f6119--- /dev/null+++ b/src/shared/chat-page.test.ts@@ -0,0 +1,51 @@+import { describe, expect, it } from 'vitest'+import {+ CHAT_PAGE_DEFAULT_BYTES,+ CHAT_PAGE_MAX_BYTES,+ CHAT_PAGE_MIN_BYTES,+ normalizeChatPage+} from './chat-page'++describe('normalizeChatPage — the page arg arrives over IPC/WS and is untrusted', () => {+ it('absent (undefined / null) means the legacy, unpaged read', () => {+ expect(normalizeChatPage(undefined)).toBeNull()+ expect(normalizeChatPage(null)).toBeNull()+ })++ it('an empty page is the newest window at the default size', () => {+ expect(normalizeChatPage({})).toEqual({ before: null, maxBytes: CHAT_PAGE_DEFAULT_BYTES })+ })++ it('clamps maxBytes into [MIN, MAX] and floors fractions', () => {+ expect(normalizeChatPage({ maxBytes: 1 })!.maxBytes).toBe(CHAT_PAGE_MIN_BYTES)+ expect(normalizeChatPage({ maxBytes: 1e12 })!.maxBytes).toBe(CHAT_PAGE_MAX_BYTES)+ expect(normalizeChatPage({ maxBytes: CHAT_PAGE_MIN_BYTES + 0.5 })!.maxBytes).toBe(+ CHAT_PAGE_MIN_BYTES+ )+ expect(CHAT_PAGE_MAX_BYTES).toBe(5 * 1024 * 1024)+ })++ it.each([NaN, Infinity, -Infinity, '100000', {}, true])(+ 'a non-numeric / non-finite maxBytes (%s) takes the default',+ (maxBytes) => {+ expect(normalizeChatPage({ maxBytes })!.maxBytes).toBe(CHAT_PAGE_DEFAULT_BYTES)+ }+ )++ it('accepts a non-negative safe integer `before`, including 0', () => {+ expect(normalizeChatPage({ before: 0 })!.before).toBe(0)+ expect(normalizeChatPage({ before: 123456 })!.before).toBe(123456)+ })++ it.each([-1, 1.5, NaN, Infinity, 2 ** 53, '10', '1; rm -rf ~'])(+ 'refuses an invalid `before` (%s) instead of guessing a window',+ (before) => {+ expect(() => normalizeChatPage({ before })).toThrow(/Invalid transcript page/)+ }+ )++ it('refuses a page that is not an object', () => {+ expect(() => normalizeChatPage(42)).toThrow(/Invalid transcript page/)+ expect(() => normalizeChatPage('x')).toThrow(/Invalid transcript page/)+ })+})diff --git a/src/shared/chat-page.ts b/src/shared/chat-page.tsnew file mode 100644index 000000000..73b82563f--- /dev/null+++ b/src/shared/chat-page.ts@@ -0,0 +1,55 @@+// The paging contract of `chat:read-transcript` (the ⌘M ChatPanel). Shared so the renderer that+// ASKS for a window and the core that SERVES it agree on the same bounds.+//+// Why paging exists: the legacy read always parses the last 5 MB of a transcript, and on an SSH+// project it pulls those 5 MB over ssh — on every panel open AND every turn-end reload. The panel+// only ever shows the newest screenful first, so the first read is now a small window ending at+// the end of the file, and older history is fetched a window at a time as the user scrolls up.++/** Smallest window a caller may ask for. A tinier one would mostly be one partial line. */+export const CHAT_PAGE_MIN_BYTES = 64 * 1024+/** Largest window — the legacy read's cap, so no paged read can cost more than an unpaged one. */+export const CHAT_PAGE_MAX_BYTES = 5 * 1024 * 1024+/** Window size when the caller names none. */+export const CHAT_PAGE_DEFAULT_BYTES = 256 * 1024++/** What the renderer sends: a window of at most `maxBytes` ending at byte offset `before`+ * (absent = end of file). Pass the previous result's `olderCursor` as `before` to page back. */+export interface ChatTranscriptPageRequest {+ before?: number+ maxBytes?: number+}++/** A validated page: `before: null` = end of file. */+export interface ChatTranscriptPage {+ before: number | null+ maxBytes: number+}++/**+ * Validate the page argument. It crosses IPC / the WS bridge, so it is untrusted, and `before` in+ * particular ends up on a remote shell command line (`transcriptPageCommand`) — the type is only a+ * compile-time promise.+ *+ * `undefined` / `null` ⇒ `null`: the caller did not ask for paging, and the legacy read runs+ * byte-for-byte. A bad `maxBytes` is harmless and takes the default (it is only a size); a bad+ * `before` THROWS rather than being coerced to "end of file", because silently answering with a+ * different window than the one asked for would splice the wrong history into the panel.+ */+export function normalizeChatPage(page: unknown): ChatTranscriptPage | null {+ if (page === undefined || page === null) return null+ if (typeof page !== 'object') throw new Error('Invalid transcript page')+ const { before, maxBytes } = page as { before?: unknown; maxBytes?: unknown }+ let b: number | null = null+ if (before !== undefined) {+ if (typeof before !== 'number' || !Number.isSafeInteger(before) || before < 0) {+ throw new Error('Invalid transcript page')+ }+ b = before+ }+ let m = CHAT_PAGE_DEFAULT_BYTES+ if (typeof maxBytes === 'number' && Number.isFinite(maxBytes)) {+ m = Math.min(CHAT_PAGE_MAX_BYTES, Math.max(CHAT_PAGE_MIN_BYTES, Math.floor(maxBytes)))+ }+ return { before: b, maxBytes: m }+}diff --git a/src/shared/types.ts b/src/shared/types.tsindex 8b1a94500..eee1fe619 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -10,6 +10,7 @@ import type { PaneOwner } from './agents/pane-owner-predicate'import type { AgentId, AgentPermissionMode, BuiltinAgentId, PromptInjectionMode } from './agents/config'import type { ControlConfirmWaivers } from './control-confirm'import type { AgentMessageDeliverRequest, AgentMessageReply } from './agents/agent-messaging'+import type { ChatTranscriptPageRequest } from './chat-page'import type { BrowserLeasePush } from './browser-indicator'import type { GroupWorktree } from './worktree'import type { ClientId, DinoSnapshot, PeerDiff, PeerIdentity, PeerState } from './presence'@@ -2768,12 +2769,35 @@ export interface TranscriptLine {export type ChatPart =| { kind: 'text'; text: string }| { kind: 'thinking'; text: string }- | { kind: 'tool'; name: string; arg: string; result?: string; summary?: ChatToolSummary }+ | {+ kind: 'tool'+ name: string+ arg: string+ result?: string+ summary?: ChatToolSummary+ /** The transcript's `tool_use` id. Set only by a PAGED read (`ChatTranscriptResult.olderCursor`+ * present): a result carried across a page boundary (`unmatchedResults`) is attached by it. */+ id?: string+ }/** A structured chat message reconstructed from a Claude session transcript. */export interface ChatMessage {role: 'user' | 'assistant'parts: ChatPart[]+ /**+ * Stable identity for list rendering: the absolute byte offset of the transcript line this+ * message came from. Set only by a PAGED claude read — an absolute offset does not change when+ * an older page is prepended or the file grows, so a prepend does not re-key the list. Absent on+ * the legacy read and on grok (whose reader does not page).+ */+ key?: number+}++/** A `tool_result` whose `tool_use` was not in the same page (it lives in an OLDER one). */+export interface ChatCarriedToolResult {+ /** The `tool_use_id` — matches `ChatPart.id` of a tool part in an older page. */+ id: string+ result: string}/** Edit/Write tool summary for diff-preview cards. */@@ -2793,6 +2817,19 @@ export interface ChatToolSummary {export interface ChatTranscriptResult {messages: ChatMessage[]found: boolean+ /**+ * PAGED reads only (absent on the legacy unpaged read, which is unchanged byte for byte). The+ * byte offset where this window's first complete line starts — pass it back as `page.before` to+ * read the next OLDER window. `null` = this window reached the start of the file, or the reader+ * does not page (grok).+ */+ olderCursor?: number | null+ /**+ * PAGED reads only. Tool results in this window whose `tool_use` is NOT in it: the newer page is+ * read first, so its results precede their tools. Hold them and attach each to the tool part with+ * the same `id` when an older page arrives. Always `[]` from a reader that does not page.+ */+ unmatchedResults?: ChatCarriedToolResult[]}/**@@ -2818,13 +2855,19 @@ export interface ChatApi {* it was. It is NOT optional in spirit: without it a grok node falls into claude's resolver, whose* cwd fallback returns the newest CLAUDE transcript for that directory — someone else's* conversation. `CHAT_CAPABLE` decides who may ask; this decides who answers.+ *+ * `page` (optional, trailing) asks for ONE window instead of the whole 5 MB tail — see+ * `shared/chat-page.ts`. Absent = the legacy read, byte for byte. Present = a result carrying+ * `olderCursor`, per-message `key`s, tool-part `id`s and `unmatchedResults`. An invalid+ * `before` rejects.*/readTranscript(sessionId: string | undefined,cwd: string | undefined,accountId?: string,nodeId?: string,- agentId?: string+ agentId?: string,+ page?: ChatTranscriptPageRequest): Promise<ChatTranscriptResult>/**