Skip to content

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.

feat(chat): progressive transcript loading in the ⌘M panel

reviewfce46e084886
diff --git a/CLAUDE.md b/CLAUDE.md
index 0063087c6..995bd4574 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -2395,6 +2395,21 @@ command-bearing opens; this does not add a human-confirm dialog or change mobile
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.
+ **ChatPanel consumes it progressively** (pure state in `renderer/lib/chatPaging.ts`): the first
+ read is a 256 KB tail (`CHAT_TAIL_PAGE_BYTES`, with a "Loading conversation…" row), older 512 KB
+ pages load when the user scrolls within 200 px of the top (or by themselves while the thread is
+ shorter than the viewport — it cannot scroll), one at a time behind their own token, prepended
+ with the scroll position ANCHORED on the scrollHeight delta (the loading row's own appearance
+ included). A turn-end reload / ↻ re-reads only the tail and **merges by key**, keeping the older
+ pages already loaded — unless no rendered message reaches into the new window (the turn wrote
+ more than a whole window, so the bytes in between were never read): then it RESETS to the tail
+ rather than stitch over a hole. Carried tool results are held until their tool's page arrives and
+ dropped at the start of the file. `found:false` on an OLDER page is a failed page load (retry row,
+ thread kept), not a missing transcript; a reload that fails to resolve never blanks a rendered
+ thread — only a read with nothing on screen says "No transcript found". The remote leg's
+ forget-a-located-ref rule lives in `main/remote-transcript-page.ts` (a hook-fed ref is never
+ dropped on a failed read, and a hook event re-marks a located ref as hook-fed). Grok: one
+ unkeyed read, no older pages, no "Beginning of conversation" marker (a capped read cannot know).
**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 TUI
diff --git a/src/main/index.ts b/src/main/index.ts
index 0e4dea53b..d4ebed12f 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -226,6 +226,12 @@ import {
remoteTranscriptRoots
} from '../core/remote-transcript-locate'
import { registerTranscriptIpc, resolveTranscript } from '../core/transcript-ipc'
+import {
+ createReadRemotePage,
+ forgetLocatedRef,
+ rememberHookRef,
+ type RemoteTranscriptRefCache
+} from './remote-transcript-page'
import { createRemoteContextTail } from './remote-context-tail'
import { createRemoteSubagentTail } from './remote-subagent-tail'
import { RemoteFile, type RemoteFileRef } from './remote-ssh/remote-file'
@@ -2451,6 +2457,10 @@ app.whenReady().then(async () => {
// separately so a stale entry can be dropped on a failed read without touching the hook-fed
// ones — see `readRemoteTranscript`.
const locatedTranscriptSessions = new Set<string>()
+ const remoteTranscriptRefs: RemoteTranscriptRefCache = {
+ bySession: remoteTranscriptBySession,
+ located: locatedTranscriptSessions
+ }
// Route the session-name read (the node-title poll) through the same remote ref. An SSH
// project's agent runs on the remote host, so its transcript is NOT under the local
// `~/.claude/projects` — without this, `/rename` never reached the node title on remote nodes
@@ -2640,9 +2650,7 @@ app.whenReady().then(async () => {
cap: number = REMOTE_TRANSCRIPT_CAP
): Promise<string> => {
const text = await remoteFile.readTail(ref, cap)
- if (!text && locatedTranscriptSessions.delete(sessionId)) {
- remoteTranscriptBySession.delete(sessionId)
- }
+ if (!text) forgetLocatedRef(remoteTranscriptRefs, sessionId)
return text
}
@@ -2659,17 +2667,12 @@ app.whenReady().then(async () => {
// 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 }
- }
- },
+ readRemotePage: createReadRemotePage({
+ cache: remoteTranscriptRefs,
+ refFor: ({ sessionId, cwd, accountId, nodeId }) =>
+ remoteTranscriptRefFor(sessionId, cwd, accountId, nodeId),
+ readPage: (ref, before, maxBytes) => remoteFile.readTranscriptPage(ref, before, maxBytes)
+ }),
remoteExists: async ({ sessionId, accountId, nodeId }) =>
sessionId ? await remoteTranscriptPresence(sessionId, accountId, nodeId) : null
})
@@ -3181,7 +3184,8 @@ app.whenReady().then(async () => {
if (p.session_id && transcriptPath) {
const ref: RemoteFileRef = { conn: rt.conn, controlPath: rt.controlPath, path: transcriptPath }
remoteContextTail.track(p.session_id, ref, _meta.contextWindow)
- remoteTranscriptBySession.set(p.session_id, ref)
+ // Hook-fed from now on: a later failed read must not drop it (see remote-transcript-page).
+ rememberHookRef(remoteTranscriptRefs, p.session_id, ref)
}
if (nodeId && p.session_id) nodeContextSession.set(nodeId, p.session_id)
// Context Link: remember the node's transcript path for remote nodes too. This branch used
diff --git a/src/main/remote-transcript-page.test.ts b/src/main/remote-transcript-page.test.ts
new file mode 100644
index 000000000..767f7efed
--- /dev/null
+++ b/src/main/remote-transcript-page.test.ts
@@ -0,0 +1,78 @@
+import { describe, expect, it, vi } from 'vitest'
+import { createReadRemotePage, forgetLocatedRef, rememberHookRef, type RemoteTranscriptRefCache } from './remote-transcript-page'
+import type { RemoteFileRef } from './remote-ssh/remote-file'
+
+const ref = (path: string): RemoteFileRef => ({
+ conn: { host: 'h', user: 'u' } as RemoteFileRef['conn'],
+ controlPath: '/cm',
+ path
+})
+const cache = (): RemoteTranscriptRefCache => ({ bySession: new Map(), located: new Set() })
+const q = { sessionId: 'sid', cwd: '/w', accountId: undefined, nodeId: 'nt-1' }
+const PAGE = { before: null, maxBytes: 65536 }
+
+describe('forgetLocatedRef', () => {
+ it('drops a ref WE located, and only that', () => {
+ const c = cache()
+ c.bySession.set('located', ref('/a'))
+ c.located.add('located')
+ c.bySession.set('hooked', ref('/b'))
+ expect(forgetLocatedRef(c, 'located')).toBe(true)
+ expect(forgetLocatedRef(c, 'hooked')).toBe(false)
+ expect([...c.bySession.keys()]).toEqual(['hooked'])
+ })
+
+ it('a hook event for a session we had located makes its ref hook-fed (no longer droppable)', () => {
+ const c = cache()
+ c.bySession.set('sid', ref('/located'))
+ c.located.add('sid')
+ rememberHookRef(c, 'sid', ref('/from-hook'))
+ expect(forgetLocatedRef(c, 'sid')).toBe(false)
+ expect(c.bySession.get('sid')?.path).toBe('/from-hook')
+ })
+})
+
+describe('createReadRemotePage — the desktop remote leg of a paged chat read', () => {
+ it('null when the session is not remote (core takes the local path)', async () => {
+ const read = createReadRemotePage({ cache: cache(), refFor: async () => undefined, readPage: vi.fn() })
+ expect(await read(q, PAGE)).toBeNull()
+ })
+
+ it('returns the ranged window it read', async () => {
+ const readPage = vi.fn(async () => ({ data: Buffer.from('xy'), start: 7, end: 9, size: 9 }))
+ const read = createReadRemotePage({ cache: cache(), refFor: async () => ref('/t.jsonl'), readPage })
+ const r = await read(q, { before: 9, maxBytes: 70000 })
+ expect(readPage).toHaveBeenCalledWith(ref('/t.jsonl'), 9, 70000)
+ expect(r).toEqual({ ok: true, data: Buffer.from('xy'), start: 7 })
+ })
+
+ it('on a failed read: a HOOK-FED ref is kept (a master blip must not send the next read local)', async () => {
+ const c = cache()
+ c.bySession.set('sid', ref('/hooked'))
+ const read = createReadRemotePage({
+ cache: c,
+ refFor: async () => c.bySession.get('sid'),
+ readPage: async () => {
+ throw new Error('master down')
+ }
+ })
+ expect(await read(q, PAGE)).toEqual({ ok: false })
+ expect(c.bySession.has('sid')).toBe(true)
+ })
+
+ it('on a failed read: a ref WE located is forgotten (so Retry locates again instead of replaying a dead path)', async () => {
+ const c = cache()
+ c.bySession.set('sid', ref('/located'))
+ c.located.add('sid')
+ const read = createReadRemotePage({
+ cache: c,
+ refFor: async () => c.bySession.get('sid'),
+ readPage: async () => {
+ throw new Error('gone')
+ }
+ })
+ expect(await read(q, PAGE)).toEqual({ ok: false })
+ expect(c.bySession.has('sid')).toBe(false)
+ expect(c.located.has('sid')).toBe(false)
+ })
+})
diff --git a/src/main/remote-transcript-page.ts b/src/main/remote-transcript-page.ts
new file mode 100644
index 000000000..27579bd76
--- /dev/null
+++ b/src/main/remote-transcript-page.ts
@@ -0,0 +1,49 @@
+// The desktop's remote leg of a PAGED ⌘M transcript read, pulled out of `src/main/index.ts` so its
+// one load-bearing rule is testable without booting the shell: on a failed read, forget a ref WE
+// located (so Retry locates it again instead of replaying a dead path), but KEEP a hook-fed one
+// (an empty read there is usually a ControlMaster blip, and dropping it would send the next read
+// down the LOCAL resolver — the wrong machine).
+import type { RemoteTranscriptPage, TranscriptQuery } from '../core/transcript-ipc'
+import type { ChatTranscriptPage } from '../shared/chat-page'
+import type { TranscriptPage } from '../core/remote-ssh/transcript-window'
+import type { RemoteFileRef } from './remote-ssh/remote-file'
+
+/** Remote transcript refs by sessionId, and which of them we located ourselves (vs hook-fed). */
+export interface RemoteTranscriptRefCache {
+ bySession: Map<string, RemoteFileRef>
+ located: Set<string>
+}
+
+/** Forget `sessionId`'s ref only if WE located it. True when something was dropped. */
+export function forgetLocatedRef(cache: RemoteTranscriptRefCache, sessionId: string): boolean {
+ if (!cache.located.delete(sessionId)) return false
+ cache.bySession.delete(sessionId)
+ return true
+}
+
+/** A hook event named this session's transcript: the ref is now hook-fed. Clearing the `located`
+ * mark matters — left in place, a later failed read would drop the authoritative hook-fed ref. */
+export function rememberHookRef(cache: RemoteTranscriptRefCache, sessionId: string, ref: RemoteFileRef): void {
+ cache.bySession.set(sessionId, ref)
+ cache.located.delete(sessionId)
+}
+
+export function createReadRemotePage(deps: {
+ cache: RemoteTranscriptRefCache
+ /** The session's remote ref (cached, or located on the host); undefined = not a remote session. */
+ refFor(q: TranscriptQuery): Promise<RemoteFileRef | undefined>
+ /** Strict ranged read (`RemoteFile.readTranscriptPage`): throws on any failure. */
+ readPage(ref: RemoteFileRef, before: number | null, maxBytes: number): Promise<TranscriptPage>
+}): (q: TranscriptQuery, page: ChatTranscriptPage) => Promise<RemoteTranscriptPage | null> {
+ return async (q, page) => {
+ const ref = await deps.refFor(q)
+ if (!ref) return null
+ try {
+ const w = await deps.readPage(ref, page.before, page.maxBytes)
+ return { ok: true, data: w.data, start: w.start }
+ } catch {
+ if (q.sessionId) forgetLocatedRef(deps.cache, q.sessionId)
+ return { ok: false }
+ }
+ }
+}
diff --git a/src/renderer/lib/chatPaging.test.ts b/src/renderer/lib/chatPaging.test.ts
new file mode 100644
index 000000000..98576ff2a
--- /dev/null
+++ b/src/renderer/lib/chatPaging.test.ts
@@ -0,0 +1,159 @@
+import { describe, expect, it } from 'vitest'
+import type { ChatMessage, ChatTranscriptResult } from '@shared/types'
+import {
+ anchoredScrollTop,
+ applyOlder,
+ applyTail,
+ attachCarried,
+ emptyThread,
+ shouldFetchOlder,
+ type ChatThread
+} from './chatPaging'
+
+const say = (key: number | undefined, t: string, role: 'user' | 'assistant' = 'assistant'): ChatMessage =>
+ key === undefined ? { role, parts: [{ kind: 'text', text: t }] } : { role, parts: [{ kind: 'text', text: t }], key }
+const tool = (key: number, id: string, result?: string): ChatMessage => ({
+ role: 'assistant',
+ key,
+ parts: [{ kind: 'tool', name: 'Bash', arg: 'ls', id, ...(result ? { result } : {}) }]
+})
+const page = (
+ messages: ChatMessage[],
+ olderCursor: number | null,
+ unmatchedResults: { id: string; result: string }[] = []
+): ChatTranscriptResult => ({ messages, found: true, olderCursor, unmatchedResults })
+const texts = (t: ChatThread): string[] =>
+ t.messages.map((m) => {
+ const p = m.parts[0]
+ return p.kind === 'tool' ? `tool:${p.id}:${p.result ?? '-'}` : p.text
+ })
+
+describe('attachCarried', () => {
+ it('attaches a held result to the tool with that id and consumes it', () => {
+ const msgs = [say(0, 'a'), tool(10, 't1')]
+ const r = attachCarried(msgs, new Map([['t1', 'out'], ['t2', 'other']]))
+ expect(r.messages[1].parts[0]).toMatchObject({ id: 't1', result: 'out' })
+ expect([...r.pending]).toEqual([['t2', 'other']])
+ // Untouched messages keep their identity (no needless re-render); the input is not mutated.
+ expect(r.messages[0]).toBe(msgs[0])
+ expect(msgs[1].parts[0]).not.toHaveProperty('result')
+ })
+
+ it('never overwrites a result the tool already has', () => {
+ const r = attachCarried([tool(0, 't1', 'mine')], new Map([['t1', 'carried']]))
+ expect(r.messages[0].parts[0]).toMatchObject({ result: 'mine' })
+ })
+})
+
+describe('applyTail', () => {
+ it('first read of an identity replaces everything', () => {
+ const t = applyTail(emptyThread('A'), 'A', page([say(100, 'x')], 90))
+ expect(texts(t)).toEqual(['x'])
+ expect(t.olderCursor).toBe(90)
+ })
+
+ it('a different identity never merges with the previous session (offsets are per file)', () => {
+ const a = applyTail(emptyThread('A'), 'A', page([say(0, 'from A'), say(50, 'A2')], null))
+ const b = applyTail(a, 'B', page([say(50, 'from B')], 40))
+ expect(texts(b)).toEqual(['from B'])
+ expect(b.identity).toBe('B')
+ })
+
+ it('a reload keeps loaded OLDER pages and replaces the tail by key — no duplicates', () => {
+ let t = applyTail(emptyThread('A'), 'A', page([say(100, 'm100'), say(200, 'm200')], 100))
+ t = applyOlder(t, page([say(0, 'm0'), say(50, 'm50')], null))
+ // The file grew: the new tail window starts at 200 and re-reads m200.
+ t = applyTail(t, 'A', page([say(200, 'm200'), say(300, 'm300')], 200))
+ expect(texts(t)).toEqual(['m0', 'm50', 'm100', 'm200', 'm300'])
+ expect(t.olderCursor).toBeNull() // older pages already reached the start — kept
+ })
+
+ it('drops the optimistic (unkeyed) sent message — the transcript reconciles it', () => {
+ let t = applyTail(emptyThread('A'), 'A', page([say(100, 'm100')], 100))
+ t = { ...t, messages: [...t.messages, say(undefined, 'just sent', 'user')] }
+ t = applyTail(t, 'A', page([say(100, 'm100'), say(150, 'just sent', 'user')], 100))
+ expect(texts(t)).toEqual(['m100', 'just sent'])
+ })
+
+ it('resets when the new tail shares no message with what is loaded (a gap may exist)', () => {
+ // The turn wrote more than a whole window: the new tail starts past everything rendered, and
+ // what lies between was never read. Stitching would silently hide it; reset + page back instead.
+ let t = applyTail(emptyThread('A'), 'A', page([say(100, 'm100')], 100))
+ t = applyTail(t, 'A', page([say(900, 'm900')], 800))
+ expect(texts(t)).toEqual(['m900'])
+ expect(t.olderCursor).toBe(800)
+ })
+
+ it('attaches a newly written result to a tool rendered from the previous tail', () => {
+ let t = applyTail(emptyThread('A'), 'A', page([tool(100, 't1'), say(160, 'still running')], 100))
+ // The window slid past the tool's line (it is kept from before); its result is new.
+ t = applyTail(t, 'A', page([say(160, 'still running'), say(300, 'after')], 140, [{ id: 't1', result: 'finally' }]))
+ expect(texts(t)).toEqual(['tool:t1:finally', 'still running', 'after'])
+ expect(t.pending.size).toBe(0)
+ })
+
+ it('a non-paging reader (grok: olderCursor null, no keys) simply replaces the thread', () => {
+ let t = applyTail(emptyThread('G'), 'G', page([say(undefined, 'g1')], null))
+ t = applyTail(t, 'G', page([say(undefined, 'g1'), say(undefined, 'g2')], null))
+ expect(texts(t)).toEqual(['g1', 'g2'])
+ })
+
+ it('treats a legacy-shaped result (no paging fields) as a whole thread', () => {
+ const t = applyTail(emptyThread('A'), 'A', { messages: [say(undefined, 'x')], found: true })
+ expect(t.olderCursor).toBeNull()
+ })
+})
+
+describe('applyOlder — the page-boundary carry', () => {
+ it('prepends and attaches results the newer page carried', () => {
+ let t = applyTail(emptyThread('A'), 'A', page([say(200, 'done')], 180, [{ id: 't9', result: 'build ok' }]))
+ expect(t.pending.get('t9')).toBe('build ok')
+ t = applyOlder(t, page([tool(100, 't9')], 90))
+ expect(texts(t)).toEqual(['tool:t9:build ok', 'done'])
+ expect(t.pending.size).toBe(0)
+ expect(t.olderCursor).toBe(90)
+ })
+
+ it('holds results whose tool is older still, and drops what is left at the start of the file', () => {
+ let t = applyTail(emptyThread('A'), 'A', page([say(200, 'x')], 180, [{ id: 'gone', result: 'r' }]))
+ t = applyOlder(t, page([say(100, 'y')], 90, [{ id: 'older', result: 'r2' }]))
+ expect([...t.pending.keys()].sort()).toEqual(['gone', 'older'])
+ t = applyOlder(t, page([say(0, 'z')], null))
+ expect(t.pending.size).toBe(0) // nothing older can ever claim them
+ expect(texts(t)).toEqual(['z', 'y', 'x'])
+ })
+
+ it('never duplicates a message already loaded', () => {
+ let t = applyTail(emptyThread('A'), 'A', page([say(100, 'm100')], 100))
+ t = applyOlder(t, page([say(50, 'm50'), say(100, 'm100')], 40))
+ expect(texts(t)).toEqual(['m50', 'm100'])
+ })
+
+ it('stops paging if a cursor fails to move backwards (never re-requests the same window)', () => {
+ let t = applyTail(emptyThread('A'), 'A', page([say(100, 'm')], 100))
+ t = applyOlder(t, page([], 100))
+ expect(t.olderCursor).toBeNull()
+ })
+})
+
+describe('anchoredScrollTop', () => {
+ it('keeps the same content under the viewport after a prepend', () => {
+ expect(anchoredScrollTop({ scrollTop: 30, scrollHeight: 1000 }, 1600)).toBe(630)
+ })
+})
+
+describe('shouldFetchOlder', () => {
+ const base = { scrollTop: 10, olderCursor: 500 as number | null, inFlight: false, failed: false, loaded: true }
+ it('fetches near the top when there is something older', () => {
+ expect(shouldFetchOlder(base)).toBe(true)
+ })
+ it.each([
+ ['far from the top', { scrollTop: 5000 }],
+ ['at the start of the file', { olderCursor: null }],
+ ['one already in flight', { inFlight: true }],
+ ['after a failure (the retry row owns it)', { failed: true }],
+ ['before the first read landed', { loaded: false }]
+ ])('does not fetch %s', (_label, over) => {
+ expect(shouldFetchOlder({ ...base, ...over })).toBe(false)
+ })
+})
diff --git a/src/renderer/lib/chatPaging.ts b/src/renderer/lib/chatPaging.ts
new file mode 100644
index 000000000..e5aa0e052
--- /dev/null
+++ b/src/renderer/lib/chatPaging.ts
@@ -0,0 +1,141 @@
+import type { ChatMessage, ChatPart, ChatTranscriptResult } from '@shared/types'
+
+/**
+ * Pure paging state for the ⌘M chat panel (`nodes/ChatPanel.tsx`). The panel reads a SMALL tail
+ * window first and older windows as the user scrolls up (`chat.readTranscript`'s `page` argument —
+ * see `shared/chat-page.ts` and the ⌘M bullet in CLAUDE.md). Everything that decides what the
+ * thread looks like after a read lives here so it is unit-tested without a DOM.
+ */
+
+/** First (and every turn-end / ↻) read: the newest window only. Small on purpose — it is what the
+ * user waits for, and on an SSH project it crosses the network on every open and every turn end. */
+export const CHAT_TAIL_PAGE_BYTES = 256 * 1024
+/** Each older page fetched on scroll-up. Larger than the tail: the user is already reading. */
+export const CHAT_OLDER_PAGE_BYTES = 512 * 1024
+/** Within this many px of the top, the next older page is fetched. */
+export const CHAT_OLDER_FETCH_THRESHOLD_PX = 200
+
+export interface ChatThread {
+ /** Which transcript these messages came from. Keys are byte offsets INTO ONE FILE, so a thread
+ * of another session/node must never be merged by key with this one. */
+ identity: string
+ messages: ChatMessage[]
+ /** Cursor of the OLDEST loaded page: pass as `before` to fetch the next older one. `null` = the
+ * start of the transcript is loaded (or the reader does not page — grok). */
+ olderCursor: number | null
+ /** Tool results whose `tool_use` has not been loaded yet (it is in an older page), by id. */
+ pending: ReadonlyMap<string, string>
+}
+
+export const emptyThread = (identity: string): ChatThread => ({
+ identity,
+ messages: [],
+ olderCursor: null,
+ pending: new Map()
+})
+
+type ToolPart = Extract<ChatPart, { kind: 'tool' }>
+
+/**
+ * Attach held results to the tool parts they belong to. Returns a new array in which ONLY the
+ * messages that changed are new objects (the rest keep identity, so their bubbles don't
+ * re-render), plus what is still unclaimed. A tool that already has a result keeps it.
+ */
+export function attachCarried(
+ messages: ChatMessage[],
+ pending: ReadonlyMap<string, string>
+): { messages: ChatMessage[]; pending: Map<string, string> } {
+ const left = new Map(pending)
+ if (left.size === 0) return { messages, pending: left }
+ const out = messages.map((m) => {
+ let changed = false
+ const parts = m.parts.map((p) => {
+ if (p.kind !== 'tool' || !p.id || p.result || !left.has(p.id)) return p
+ const withResult: ToolPart = { ...p, result: left.get(p.id)! }
+ left.delete(p.id)
+ changed = true
+ return withResult
+ })
+ return changed ? { ...m, parts } : m
+ })
+ return { messages: out, pending: left }
+}
+
+const carriedOf = (res: ChatTranscriptResult): Array<[string, string]> =>
+ (res.unmatchedResults ?? []).map((r) => [r.id, r.result])
+
+/**
+ * Apply a TAIL read (first open, turn-end reload, ↻) to the thread.
+ *
+ * - Another identity, or a reader that returned the whole thing (`olderCursor` null — grok, a
+ * small file, a legacy-shaped result): replace.
+ * - Otherwise merge by key: every loaded message older than the tail window is KEPT (older pages
+ * the user already scrolled through survive a turn end), everything from the window on is
+ * replaced by the tail — so nothing duplicates, and the optimistic unkeyed "just sent" bubble
+ * is dropped because the transcript now carries the real one.
+ * - Unless no loaded message reaches into the new window: then the turn wrote more than a whole
+ * window, and the bytes between what is rendered and the new window were never read. Stitching
+ * would hide them silently, so the thread resets to the tail and pages back normally.
+ */
+export function applyTail(t: ChatThread, identity: string, res: ChatTranscriptResult): ChatThread {
+ const cursor = res.olderCursor ?? null
+ const fresh = (): ChatThread => ({
+ identity,
+ messages: res.messages,
+ olderCursor: cursor,
+ pending: cursor === null ? new Map() : new Map(carriedOf(res))
+ })
+ if (t.identity !== identity || cursor === null) return fresh()
+ const keyed = t.messages.filter((m) => m.key !== undefined)
+ if (!keyed.some((m) => m.key! >= cursor)) return fresh()
+ const kept = keyed.filter((m) => m.key! < cursor)
+ // A result written this turn for a tool rendered from an earlier read arrives as carried.
+ const attached = attachCarried(kept, new Map([...t.pending, ...carriedOf(res)]))
+ return {
+ identity,
+ messages: [...attached.messages, ...res.messages],
+ olderCursor: t.olderCursor,
+ pending: t.olderCursor === null ? new Map() : attached.pending
+ }
+}
+
+/**
+ * Prepend an OLDER page (a read with `before` = the thread's cursor). Held results claim their
+ * tools in it; its own carried results (tools older still) join the held set; at the start of the
+ * file whatever is still held is dropped — nothing older can ever claim it.
+ *
+ * Defensive: messages at or after the oldest loaded key are skipped (no duplicate), and a cursor
+ * that did not move backwards ends paging rather than re-requesting the same window forever.
+ */
+export function applyOlder(t: ChatThread, res: ChatTranscriptResult): ChatThread {
+ let oldest = Infinity
+ for (const m of t.messages) if (m.key !== undefined && m.key < oldest) oldest = m.key
+ const older = res.messages.filter((m) => m.key === undefined || m.key < oldest)
+ let cursor = res.olderCursor ?? null
+ if (cursor !== null && t.olderCursor !== null && cursor >= t.olderCursor) cursor = null
+ const attached = attachCarried(older, new Map([...t.pending, ...carriedOf(res)]))
+ return {
+ identity: t.identity,
+ messages: [...attached.messages, ...t.messages],
+ olderCursor: cursor,
+ pending: cursor === null ? new Map() : attached.pending
+ }
+}
+
+/** Scroll position that keeps the same content under the viewport after content was inserted
+ * ABOVE it: shift by exactly the height that was added. */
+export function anchoredScrollTop(prev: { scrollTop: number; scrollHeight: number }, nextScrollHeight: number): number {
+ return prev.scrollTop + (nextScrollHeight - prev.scrollHeight)
+}
+
+/** Fetch the next older page? Only near the top, only when there is one, one at a time, never on
+ * its own after a failure (the retry row owns that), and never before the first read landed. */
+export function shouldFetchOlder(s: {
+ scrollTop: number
+ olderCursor: number | null
+ inFlight: boolean
+ failed: boolean
+ loaded: boolean
+}, threshold = CHAT_OLDER_FETCH_THRESHOLD_PX): boolean {
+ return s.loaded && !s.inFlight && !s.failed && s.olderCursor !== null && s.scrollTop <= threshold
+}
diff --git a/src/renderer/nodes/ChatPanel.paging.test.tsx b/src/renderer/nodes/ChatPanel.paging.test.tsx
new file mode 100644
index 000000000..a595b5234
--- /dev/null
+++ b/src/renderer/nodes/ChatPanel.paging.test.tsx
@@ -0,0 +1,225 @@
+// @vitest-environment jsdom
+import { act } from 'react'
+import { createRoot, type Root } from 'react-dom/client'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import type { ChatMessage, ChatTranscriptResult } from '@shared/types'
+import type { ChatTranscriptPageRequest } from '@shared/chat-page'
+import { useAgentStatus } from '../state/agentStatus'
+import { CHAT_OLDER_PAGE_BYTES, CHAT_TAIL_PAGE_BYTES } from '../lib/chatPaging'
+
+/**
+ * The ⌘M panel's progressive loading glue (the merge/attach/anchor decisions are unit-tested in
+ * `lib/chatPaging.test.ts`): a small tail first, older pages on scroll-up with the scroll position
+ * preserved, one older fetch at a time, a retryable failed older page, and a turn-end reload that
+ * keeps the pages already loaded.
+ */
+
+;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true
+
+interface Pending {
+ page: ChatTranscriptPageRequest | undefined
+ resolve: (r: ChatTranscriptResult) => void
+ reject: (e: unknown) => void
+}
+
+const { readTranscript, pending, session } = vi.hoisted(() => {
+ const pending: Pending[] = []
+ const readTranscript = vi.fn(
+ (
+ _s: string | undefined,
+ _c: string | undefined,
+ _a?: string,
+ _n?: string,
+ _g?: string,
+ page?: ChatTranscriptPageRequest
+ ) => new Promise<ChatTranscriptResult>((resolve, reject) => pending.push({ page, resolve, reject }))
+ )
+ const session = { api: { chat: { readTranscript }, pty: { sendText: vi.fn(async () => true as const) } } }
+ return { readTranscript, pending, session }
+})
+vi.mock('../session/session', () => ({ useSession: () => session }))
+
+import { ChatPanel } from './ChatPanel'
+
+const NODE = 'n-chat-paging'
+let host: HTMLDivElement
+let root: Root
+
+const say = (key: number, t: string): ChatMessage => ({ role: 'assistant', key, parts: [{ kind: 'text', text: t }] })
+const msgs = (): HTMLDivElement => host.querySelector('.term-chat__msgs') as HTMLDivElement
+const bubbles = (): string[] =>
+ [...host.querySelectorAll('.term-chat__msg')].map((e) => e.textContent?.trim() ?? '')
+
+/**
+ * jsdom has no layout, so the scroller gets a tiny model of one: its height is DERIVED from what is
+ * rendered (each bubble `perMsg` px, each top status row `ROW` px) — so a measurement taken before
+ * a render really is the pre-render height — and scrollTop clamps like a browser's.
+ */
+const ROW = 30
+const geo = { perMsg: 700, clientHeight: 400 }
+const heightOf = (el: HTMLElement): number =>
+ el.querySelectorAll('.term-chat__msg').length * geo.perMsg + el.querySelectorAll('.term-chat__older').length * ROW
+function installGeometry(el: HTMLElement): void {
+ let top = 0
+ Object.defineProperty(el, 'scrollHeight', { configurable: true, get: () => heightOf(el) })
+ Object.defineProperty(el, 'clientHeight', { configurable: true, get: () => geo.clientHeight })
+ Object.defineProperty(el, 'scrollTop', {
+ configurable: true,
+ get: () => top,
+ set: (v: number) => {
+ top = Math.max(0, Math.min(v, heightOf(el) - geo.clientHeight))
+ }
+ })
+}
+
+async function render(): Promise<void> {
+ await act(async () => {
+ root.render(<ChatPanel nodeId={NODE} sessionId="s1" agentId="claude" />)
+ })
+ installGeometry(msgs())
+}
+async function settle(i: number, r: Partial<ChatTranscriptResult>): Promise<void> {
+ await act(async () => {
+ pending[i].resolve({ messages: [], found: true, olderCursor: null, unmatchedResults: [], ...r })
+ })
+}
+async function scrollTo(top: number): Promise<void> {
+ await act(async () => {
+ msgs().scrollTop = top
+ msgs().dispatchEvent(new Event('scroll'))
+ })
+}
+
+beforeEach(() => {
+ readTranscript.mockClear()
+ pending.length = 0
+ geo.perMsg = 700
+ geo.clientHeight = 400
+ host = document.createElement('div')
+ document.body.appendChild(host)
+ root = createRoot(host)
+})
+afterEach(async () => {
+ await act(async () => root.unmount())
+ host.remove()
+ useAgentStatus.setState((s) => {
+ const byId = { ...s.byId }
+ delete byId[NODE]
+ return { byId }
+ })
+})
+
+describe('ChatPanel progressive loading', () => {
+ it('shows a loading row while the first read is in flight', async () => {
+ await render()
+ const row = host.querySelector('.term-chat__loading')
+ expect(row?.textContent).toContain('Loading conversation…')
+ expect(row?.querySelector('.term-chat__spinner')).not.toBeNull()
+ await settle(0, { messages: [say(100, 'hi')] })
+ expect(host.querySelector('.term-chat__loading')).toBeNull()
+ })
+
+ it('reads only a small tail window first', async () => {
+ await render()
+ expect(pending[0].page).toEqual({ maxBytes: CHAT_TAIL_PAGE_BYTES })
+ })
+
+ it('pages back on scroll-up, prepends, and keeps the viewport on the same content', async () => {
+ await render()
+ geo.perMsg = 1000
+ await settle(0, { messages: [say(1000, 'tail')], olderCursor: 1000 })
+ expect(msgs().scrollTop).toBe(600) // pinned to the bottom; far from the top → no fetch yet
+ expect(pending).toHaveLength(1)
+
+ await scrollTo(50)
+ expect(pending).toHaveLength(2)
+ expect(pending[1].page).toEqual({ before: 1000, maxBytes: CHAT_OLDER_PAGE_BYTES })
+ expect(host.querySelector('.term-chat__older')?.textContent).toContain('Loading earlier messages…')
+ // The loading row appeared ABOVE the viewport: shifted by its height, not jumped.
+ expect(msgs().scrollTop).toBe(50 + ROW)
+
+ await settle(1, { messages: [say(0, 'first'), say(500, 'second')], olderCursor: null })
+ expect(bubbles()).toEqual(['first', 'second', 'tail'])
+ // Two bubbles added, the loading row replaced by the start marker (same height): the 'tail'
+ // bubble sits exactly where it was under the viewport.
+ expect(msgs().scrollTop).toBe(50 + ROW + 2 * 1000)
+ expect(host.querySelector('.term-chat__older--start')?.textContent).toBe('Beginning of conversation')
+ })
+
+ it('keeps ONE older fetch in flight however many scroll events arrive', async () => {
+ await render()
+ await settle(0, { messages: [say(1000, 'tail')], olderCursor: 1000 })
+ await scrollTo(10)
+ await scrollTo(5)
+ await scrollTo(0)
+ expect(pending).toHaveLength(2)
+ })
+
+ it('a failed older page keeps the thread and offers a retry — it is not a missing transcript', async () => {
+ await render()
+ await settle(0, { messages: [say(1000, 'tail')], olderCursor: 1000 })
+ await scrollTo(0)
+ await settle(1, { found: false })
+ expect(bubbles()).toEqual(['tail'])
+ expect(host.textContent).not.toContain('No transcript found')
+ const row = host.querySelector('.term-chat__older--error')!
+ expect(row.textContent).toContain("Couldn't load earlier messages")
+ // No automatic retry on the next scroll: the row owns it.
+ await scrollTo(0)
+ expect(pending).toHaveLength(2)
+ await act(async () => row.querySelector('button')!.click())
+ expect(pending).toHaveLength(3)
+ expect(pending[2].page).toEqual({ before: 1000, maxBytes: CHAT_OLDER_PAGE_BYTES })
+ await settle(2, { messages: [say(0, 'older')], olderCursor: null })
+ expect(bubbles()).toEqual(['older', 'tail'])
+ })
+
+ it('an older page that lands after a newer tail reload is dropped', async () => {
+ await render()
+ await settle(0, { messages: [say(1000, 'tail')], olderCursor: 1000 })
+ await scrollTo(0)
+ await act(async () => host.querySelector<HTMLButtonElement>('.term-chat__refresh')!.click())
+ await settle(1, { messages: [say(0, 'STALE OLDER')], olderCursor: null })
+ expect(bubbles()).not.toContain('STALE OLDER')
+ })
+
+ it('a turn-end reload re-reads only the tail and keeps the older pages already loaded', async () => {
+ useAgentStatus.setState((s) => ({ byId: { ...s.byId, [NODE]: { state: 'working' } as never } }))
+ await render()
+ await settle(0, { messages: [say(1000, 'm1000')], olderCursor: 1000 })
+ await scrollTo(0)
+ await settle(1, { messages: [say(0, 'm0')], olderCursor: null })
+ expect(bubbles()).toEqual(['m0', 'm1000'])
+
+ await act(async () => {
+ useAgentStatus.setState((s) => ({ byId: { ...s.byId, [NODE]: { state: 'done' } as never } }))
+ })
+ expect(pending).toHaveLength(3)
+ expect(pending[2].page).toEqual({ maxBytes: CHAT_TAIL_PAGE_BYTES })
+ await settle(2, { messages: [say(1000, 'm1000'), say(2000, 'm2000')], olderCursor: 1000 })
+ expect(bubbles()).toEqual(['m0', 'm1000', 'm2000'])
+ })
+
+ it('a reload that fails to resolve does not blank a rendered thread', async () => {
+ await render()
+ await settle(0, { messages: [say(1000, 'kept')], olderCursor: null })
+ await act(async () => host.querySelector<HTMLButtonElement>('.term-chat__refresh')!.click())
+ await settle(1, { found: false })
+ expect(bubbles()).toEqual(['kept'])
+ expect(host.textContent).not.toContain('No transcript found')
+ })
+
+ it('the FIRST read that finds nothing still says the transcript is missing', async () => {
+ await render()
+ await settle(0, { found: false })
+ expect(host.textContent).toContain('No transcript found for this session.')
+ })
+
+ it('a thread shorter than the viewport pages back on its own (it cannot scroll)', async () => {
+ geo.perMsg = 100 // one bubble is shorter than the 400px viewport: scrollTop stays 0
+ await render()
+ await settle(0, { messages: [say(1000, 'short')], olderCursor: 1000 })
+ expect(pending).toHaveLength(2)
+ expect(pending[1].page).toEqual({ before: 1000, maxBytes: CHAT_OLDER_PAGE_BYTES })
+ })
+})
diff --git a/src/renderer/nodes/ChatPanel.tsx b/src/renderer/nodes/ChatPanel.tsx
index 15e0135ee..8688d5855 100644
--- a/src/renderer/nodes/ChatPanel.tsx
+++ b/src/renderer/nodes/ChatPanel.tsx
@@ -3,11 +3,20 @@ import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useStat
import { renderMarkdown } from '../lib/markdown'
import { useAgentStatus } from '../state/agentStatus'
import { useSession } from '../session/session'
-import type { ChatMessage } from '@shared/types'
import { chipFor } from '../lib/keybindingOverrides'
import { chatComposerPlaceholder, chatSendRefusal } from '../lib/chatSendGate'
import { chatAgentLabel, chatKeyAction, isNearBottom, shouldFollowOnLoad } from '../lib/chatPanel'
import { useSettings } from '../state/settings'
+import {
+ CHAT_OLDER_PAGE_BYTES,
+ CHAT_TAIL_PAGE_BYTES,
+ anchoredScrollTop,
+ applyOlder,
+ applyTail,
+ emptyThread,
+ shouldFetchOlder,
+ type ChatThread
+} from '../lib/chatPaging'
import { E_UNSUPPORTED } from '@shared/rpc'
// Memoized bubble: marked+DOMPurify re-ran for EVERY message on each ChatPanel render (each
@@ -91,8 +100,19 @@ export function ChatPanel({
// This node's core api (stable for the session — the chat transcript and the tmux session
// both live on the core this panel's project belongs to).
const { api } = useSession()
- const [messages, setMessages] = useState<ChatMessage[]>([])
+ // Which transcript this panel reads. Keys are byte offsets into ONE file, so a thread is only
+ // ever merged with a read of the same identity (see lib/chatPaging.ts).
+ const identity = JSON.stringify([nodeId, sessionId ?? null, cwd ?? null, accountId ?? null, agentId])
+ const [thread, setThread] = useState<ChatThread>(() => emptyThread(identity))
+ const messages = thread.messages
+ // Read by the async handlers, which must decide against the thread as it is NOW, not as it was
+ // when the read was issued.
+ const threadRef = useRef(thread)
+ threadRef.current = thread
const [loadState, setLoadState] = useState<LoadState>('loading')
+ // The older-page fetch (scroll-up paging): its own in-flight flag and token, and a failed page
+ // gets a retry row instead of retrying on every scroll event.
+ const [olderState, setOlderState] = useState<'idle' | 'loading' | 'error'>('idle')
const [input, setInput] = useState('')
const [readonly, setReadonly] = useState(false)
const state = useAgentStatus((s) => s.byId[nodeId]?.state)
@@ -114,25 +134,89 @@ export function ChatPanel({
// bottom (updated on every scroll), and did they just send (they expect to see it land).
const nearBottomRef = useRef(true)
const justSentRef = useRef(false)
+ // Token for the older-page fetch. A TAIL load bumps it too: a tail read can reset the thread
+ // (see applyTail), and an older page computed against the previous cursor must not land on it.
+ const olderReqRef = useRef(0)
+ const olderInFlightRef = useRef(false)
+ // Geometry captured just BEFORE content is inserted above the viewport (an older page, or the
+ // "Loading earlier messages…" row appearing); the layout effect shifts scrollTop by the height
+ // that was added, so what the user is reading stays put.
+ const anchorRef = useRef<{ scrollTop: number; scrollHeight: number } | null>(null)
+ const captureAnchor = () => {
+ const el = msgsRef.current
+ if (el) anchorRef.current = { scrollTop: el.scrollTop, scrollHeight: el.scrollHeight }
+ }
const load = useCallback(() => {
const token = ++reqRef.current
+ olderReqRef.current++
+ olderInFlightRef.current = false
+ setOlderState('idle')
setLoadState((s) => (s === 'ok' ? s : 'loading')) // a reload never blanks a rendered thread
// `nodeId` is what lets an SSH-project node resolve on its host; the rejection branch is what
// keeps a surface that cannot read transcripts (Server Edition, relay tab) from silently
- // presenting itself as an empty conversation.
- void api.chat.readTranscript(sessionId, cwd, accountId, nodeId, agentId).then(
+ // presenting itself as an empty conversation. Only the newest TAIL window is read — older
+ // history pages in on scroll-up, and a reload merges by key instead of discarding it.
+ void api.chat.readTranscript(sessionId, cwd, accountId, nodeId, agentId, {
+ maxBytes: CHAT_TAIL_PAGE_BYTES
+ }).then(
(res) => {
if (token !== reqRef.current) return
- setMessages(res.messages)
- setLoadState(res.found ? 'ok' : 'missing')
+ if (!res.found) {
+ // `missing` only when there is nothing of THIS transcript on screen. A reload that
+ // failed to resolve (an SSH master blip) must not blank a thread the user is reading.
+ const t = threadRef.current
+ if (t.identity === identity && t.messages.length > 0) return
+ setThread(emptyThread(identity))
+ setLoadState('missing')
+ return
+ }
+ setThread((t) => applyTail(t, identity, res))
+ setLoadState('ok')
},
(e: unknown) => {
if (token !== reqRef.current) return
setLoadState(isUnsupported(e) ? 'unsupported' : 'error')
}
)
- }, [api, sessionId, cwd, accountId, nodeId, agentId])
+ }, [api, sessionId, cwd, accountId, nodeId, agentId, identity])
+
+ // Fetch the next OLDER page and prepend it. One in flight at a time; a result that arrives
+ // after a newer tail load (or unmount) is dropped by its token. A `found:false` here is a failed
+ // older-page load, NOT a missing transcript: the rendered thread stays, and a retry row appears.
+ const loadOlder = useCallback(() => {
+ const before = thread.olderCursor
+ if (before === null || olderInFlightRef.current || thread.identity !== identity) return
+ const token = ++olderReqRef.current
+ olderInFlightRef.current = true
+ captureAnchor()
+ setOlderState('loading')
+ const settle = () => {
+ olderInFlightRef.current = false
+ }
+ void api.chat.readTranscript(sessionId, cwd, accountId, nodeId, agentId, {
+ before,
+ maxBytes: CHAT_OLDER_PAGE_BYTES
+ }).then(
+ (res) => {
+ if (token !== olderReqRef.current) return
+ settle()
+ captureAnchor()
+ if (!res.found) {
+ setOlderState('error')
+ return
+ }
+ setThread((t) => (t.identity === identity && t.olderCursor === before ? applyOlder(t, res) : t))
+ setOlderState('idle')
+ },
+ () => {
+ if (token !== olderReqRef.current) return
+ settle()
+ captureAnchor()
+ setOlderState('error')
+ }
+ )
+ }, [api, sessionId, cwd, accountId, nodeId, agentId, identity, thread.olderCursor, thread.identity])
// Initial load.
useEffect(() => {
@@ -143,6 +227,7 @@ export function ChatPanel({
useEffect(
() => () => {
reqRef.current++
+ olderReqRef.current++
},
[]
)
@@ -157,19 +242,52 @@ export function ChatPanel({
// Follow the newest message only when the user was already at the bottom or just sent; a user
// scrolled up reading an earlier answer keeps their place. Layout effect: the jump lands before
// paint, so a followed thread never flashes one frame short.
+ //
+ // Content inserted ABOVE the viewport (an older page, the loading row) is the other case: there
+ // the anchor captured before the change wins, and the view is shifted by exactly the added
+ // height — no jump, and no follow (the user is at the top, reading history).
useLayoutEffect(() => {
const el = msgsRef.current
if (!el) return
+ const anchor = anchorRef.current
+ if (anchor) {
+ anchorRef.current = null
+ el.scrollTop = anchoredScrollTop(anchor, el.scrollHeight)
+ return
+ }
if (shouldFollowOnLoad({ wasNearBottom: nearBottomRef.current, justSent: justSentRef.current })) {
el.scrollTop = el.scrollHeight
nearBottomRef.current = true
}
justSentRef.current = false
- }, [messages])
+ }, [messages, olderState])
+
+ const maybeLoadOlder = useCallback(() => {
+ const el = msgsRef.current
+ if (!el) return
+ if (
+ shouldFetchOlder({
+ scrollTop: el.scrollTop,
+ olderCursor: thread.identity === identity ? thread.olderCursor : null,
+ inFlight: olderInFlightRef.current,
+ failed: olderState === 'error',
+ loaded: loadState === 'ok'
+ })
+ ) {
+ loadOlder()
+ }
+ }, [thread.identity, thread.olderCursor, identity, olderState, loadState, loadOlder])
+
+ // After every thread change too, not only on scroll: a thread shorter than the viewport cannot
+ // scroll, so without this its older history would be unreachable.
+ useEffect(() => {
+ maybeLoadOlder()
+ }, [maybeLoadOlder])
const onScroll = () => {
const el = msgsRef.current
if (el) nearBottomRef.current = isNearBottom(el)
+ maybeLoadOlder()
}
// Not just `working`: a TUI dialog (`waiting`/`blocked`) would be ANSWERED by sendText's Enter,
@@ -194,7 +312,7 @@ export function ChatPanel({
}
// Optimistic: show the prompt immediately; the next load() reconciles from the transcript.
justSentRef.current = true
- setMessages((m) => [...m, { role: 'user', parts: [{ kind: 'text', text }] }])
+ setThread((t) => ({ ...t, messages: [...t.messages, { role: 'user', parts: [{ kind: 'text', text }] }] }))
setInput('')
}, [api, input, nodeId, agentId])
@@ -231,6 +349,31 @@ export function ChatPanel({
</span>
</div>
<div className="term-chat__msgs" ref={msgsRef} onScroll={onScroll}>
+ {messages.length === 0 && loadState === 'loading' && (
+ <div className="term-chat__loading" role="status">
+ <span className="term-chat__spinner" aria-hidden="true" />
+ <span>{EMPTY_TEXT.loading.title}</span>
+ </div>
+ )}
+ {messages.length > 0 && olderState === 'loading' && (
+ <div className="term-chat__older" role="status">
+ <span className="term-chat__spinner" aria-hidden="true" />
+ <span>Loading earlier messages…</span>
+ </div>
+ )}
+ {messages.length > 0 && olderState === 'error' && (
+ <div className="term-chat__older term-chat__older--error">
+ <span>Couldn't load earlier messages.</span>
+ <button className="term-chat__retry" onClick={loadOlder}>
+ Retry
+ </button>
+ </div>
+ )}
+ {/* Only a PAGED thread (keyed messages) can know it reached the start; grok's capped
+ whole-file read says nothing about what lies before it. */}
+ {olderState === 'idle' && thread.olderCursor === null && messages.some((m) => m.key !== undefined) && (
+ <div className="term-chat__older term-chat__older--start">Beginning of conversation</div>
+ )}
{messages.length === 0 && loadState !== 'loading' && (
<div className="term-chat__empty">
<div>{EMPTY_TEXT[loadState].title}</div>
@@ -245,7 +388,10 @@ export function ChatPanel({
</div>
)}
{messages.map((m, i) => (
- <div key={i} className={`term-chat__msg term-chat__msg--${m.role}`}>
+ // Keyed by the source line's byte offset: a prepended page does not re-key (and so does
+ // not re-render) a single existing bubble. Unkeyed ones (grok, the optimistic sent
+ // bubble) fall back to their position.
+ <div key={m.key !== undefined ? `k${m.key}` : `i${i}`} className={`term-chat__msg term-chat__msg--${m.role}`}>
{m.parts.map((p, j) =>
p.kind === 'text' ? (
<MarkdownText key={j} text={p.text} />
diff --git a/src/renderer/styles.css b/src/renderer/styles.css
index 10e74316b..6f066889f 100644
--- a/src/renderer/styles.css
+++ b/src/renderer/styles.css
@@ -3154,6 +3154,51 @@ body,
.term-chat__retry:hover {
background: rgba(var(--tint-rgb), 0.12);
}
+/* Progressive loading (lane B, chat paging). A LOCAL spinner on purpose: the shared one lives on
+ another branch and is unified at integration. */
+.term-chat__loading {
+ margin: auto;
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ font-size: 12px;
+ color: rgba(var(--tint-rgb), 0.4);
+}
+.term-chat__older {
+ flex: 0 0 auto;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ gap: 8px;
+ min-height: 22px;
+ font-size: 11px;
+ color: rgba(var(--tint-rgb), 0.35);
+}
+.term-chat__older .term-chat__retry {
+ margin-top: 0;
+}
+.term-chat__older--start {
+ color: rgba(var(--tint-rgb), 0.22);
+}
+.term-chat__spinner {
+ width: 12px;
+ height: 12px;
+ border-radius: 50%;
+ border: 1.5px solid rgba(var(--tint-rgb), 0.15);
+ border-top-color: rgba(var(--tint-rgb), 0.55);
+ animation: term-chat-spin 0.8s linear infinite;
+ animation-play-state: var(--nt-anim-state);
+}
+@keyframes term-chat-spin {
+ to {
+ transform: rotate(360deg);
+ }
+}
+@media (prefers-reduced-motion: reduce) {
+ .term-chat__spinner {
+ animation-duration: 2.4s;
+ }
+}
.term-chat__msg {
max-width: 92%;
padding: 8px 10px;
diff --git a/src/shared/types.ts b/src/shared/types.ts
index eee1fe619..d63bfe02c 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -2822,6 +2822,10 @@ export interface ChatTranscriptResult {
* 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).
+ *
+ * `found: false` on a read WITH `page.before` set is a FAILED OLDER-PAGE load (the host blipped,
+ * the file became unreadable), NOT a missing transcript: the caller keeps what it rendered and
+ * offers a retry. Only the first (tail) read's `found: false` means "no transcript".
*/
olderCursor?: number | null
/**