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
fix(chat): never page a hidden panel; keep paging alive across failed reloads
review5466ae7181dd
diff --git a/src/renderer/lib/chatPaging.test.ts b/src/renderer/lib/chatPaging.test.tsindex 98576ff2a..e40c285c8 100644--- a/src/renderer/lib/chatPaging.test.ts+++ b/src/renderer/lib/chatPaging.test.ts@@ -143,17 +143,45 @@ describe('anchoredScrollTop', () => {})describe('shouldFetchOlder', () => {- const base = { scrollTop: 10, olderCursor: 500 as number | null, inFlight: false, failed: false, loaded: true }+ const base = {+ scrollTop: 10,+ scrollHeight: 3000,+ clientHeight: 400,+ 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('fetches when the content is shorter than the viewport (it cannot scroll)', () => {+ expect(shouldFetchOlder({ ...base, scrollTop: 0, scrollHeight: 300 })).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 }]+ ['before the first read landed', { loaded: false }],+ // A collapsed node keeps the panel mounted under display:none: every metric reads 0, which+ // would otherwise look like "at the top" and page the WHOLE history in the background.+ ['with no layout box (hidden panel)', { scrollTop: 0, scrollHeight: 0, clientHeight: 0 }]])('does not fetch %s', (_label, over) => {expect(shouldFetchOlder({ ...base, ...over })).toBe(false)})})++describe('held results whose tool is already loaded are dropped', () => {+ it('after a tail merge: the tool is on screen WITH a result, so nothing older can claim it', () => {+ let t = applyTail(emptyThread('A'), 'A', page([tool(100, 't1', 'first'), say(160, 'x')], 90))+ t = applyTail(t, 'A', page([say(160, 'x')], 140, [{ id: 't1', result: 'dup' }]))+ expect(t.pending.has('t1')).toBe(false)+ expect(texts(t)[0]).toBe('tool:t1:first')+ })+ it('after an older page', () => {+ let t = applyTail(emptyThread('A'), 'A', page([say(200, 'x')], 180, [{ id: 't1', result: 'r' }]))+ t = applyOlder(t, page([tool(100, 't1', 'own')], 90))+ expect(t.pending.has('t1')).toBe(false)+ })+})diff --git a/src/renderer/lib/chatPaging.ts b/src/renderer/lib/chatPaging.tsindex e5aa0e052..a2fa05061 100644--- a/src/renderer/lib/chatPaging.ts+++ b/src/renderer/lib/chatPaging.ts@@ -61,6 +61,14 @@ export function attachCarried(return { messages: out, pending: left }}+/** Held results whose tool is ALREADY loaded can never be claimed (the tool has its own result —+ * `attachCarried` never overwrites one), so holding them until the start of the file is waste. */+function pruneLoaded(messages: ChatMessage[], pending: Map<string, string>): Map<string, string> {+ if (pending.size === 0) return pending+ for (const m of messages) for (const p of m.parts) if (p.kind === 'tool' && p.id) pending.delete(p.id)+ return pending+}+const carriedOf = (res: ChatTranscriptResult): Array<[string, string]> =>(res.unmatchedResults ?? []).map((r) => [r.id, r.result])@@ -91,11 +99,12 @@ export function applyTail(t: ChatThread, identity: string, res: ChatTranscriptReconst 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)]))+ const messages = [...attached.messages, ...res.messages]return {identity,- messages: [...attached.messages, ...res.messages],+ messages,olderCursor: t.olderCursor,- pending: t.olderCursor === null ? new Map() : attached.pending+ pending: t.olderCursor === null ? new Map() : pruneLoaded(messages, attached.pending)}}@@ -118,7 +127,7 @@ export function applyOlder(t: ChatThread, res: ChatTranscriptResult): ChatThreadidentity: t.identity,messages: [...attached.messages, ...t.messages],olderCursor: cursor,- pending: cursor === null ? new Map() : attached.pending+ pending: cursor === null ? new Map() : pruneLoaded(attached.messages, attached.pending)}}@@ -128,14 +137,28 @@ export function anchoredScrollTop(prev: { scrollTop: number; scrollHeight: numbereturn 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. */+/**+ * Fetch the next older page? Only near the top — or when the content is shorter than the viewport+ * (it cannot scroll, so "near the top" would never be reached by a user) — 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.+ *+ * And never WITHOUT A LAYOUT BOX: a collapsed node keeps its ⌘M panel mounted under+ * `display:none`, where scrollTop, scrollHeight and clientHeight all read 0. Zero looks exactly+ * like "at the top", and every page landing re-triggers the check — so an ungated hidden panel+ * paged the whole history in the background (one ssh read per page on an SSH project). Paging+ * resumes when the panel gets a size again.+ */export function shouldFetchOlder(s: {scrollTop: number+ scrollHeight: number+ clientHeight: numberolderCursor: number | nullinFlight: booleanfailed: booleanloaded: boolean}, threshold = CHAT_OLDER_FETCH_THRESHOLD_PX): boolean {- return s.loaded && !s.inFlight && !s.failed && s.olderCursor !== null && s.scrollTop <= threshold+ if (!s.loaded || s.inFlight || s.failed || s.olderCursor === null) return false+ if (s.clientHeight <= 0) return false+ return s.scrollHeight <= s.clientHeight || s.scrollTop <= threshold}diff --git a/src/renderer/nodes/ChatPanel.paging.test.tsx b/src/renderer/nodes/ChatPanel.paging.test.tsxindex a595b5234..cb8db26d3 100644--- a/src/renderer/nodes/ChatPanel.paging.test.tsx+++ b/src/renderer/nodes/ChatPanel.paging.test.tsx@@ -72,11 +72,32 @@ function installGeometry(el: HTMLElement): void {})}-async function render(): Promise<void> {+async function render(sessionId = 's1'): Promise<void> {+ const first = !host.querySelector('.term-chat__msgs')await act(async () => {- root.render(<ChatPanel nodeId={NODE} sessionId="s1" agentId="claude" />)+ root.render(<ChatPanel nodeId={NODE} sessionId={sessionId} agentId="claude" />)+ })+ if (first) installGeometry(msgs())+}++/** jsdom has no ResizeObserver; this one lets a test say "the panel's box changed". */+const observers: Array<() => void> = []+class FakeResizeObserver {+ constructor(private cb: () => void) {}+ observe(): void {+ observers.push(this.cb)+ }+ unobserve(): void {}+ disconnect(): void {+ const i = observers.indexOf(this.cb)+ if (i >= 0) observers.splice(i, 1)+ }+}+;(globalThis as { ResizeObserver?: unknown }).ResizeObserver = FakeResizeObserver+async function resized(): Promise<void> {+ await act(async () => {+ for (const cb of [...observers]) cb()})- installGeometry(msgs())}async function settle(i: number, r: Partial<ChatTranscriptResult>): Promise<void> {await act(async () => {@@ -93,6 +114,7 @@ async function scrollTo(top: number): Promise<void> {beforeEach(() => {readTranscript.mockClear()pending.length = 0+ observers.length = 0geo.perMsg = 700geo.clientHeight = 400host = document.createElement('div')@@ -222,4 +244,80 @@ describe('ChatPanel progressive loading', () => {expect(pending).toHaveLength(2)expect(pending[1].page).toEqual({ before: 1000, maxBytes: CHAT_OLDER_PAGE_BYTES })})++ it('a HIDDEN panel (collapsed node, display:none: every metric 0) never pages in the background', async () => {+ geo.perMsg = 0+ geo.clientHeight = 0+ await render()+ await settle(0, { messages: [say(1000, 'tail')], olderCursor: 1000 })+ expect(pending).toHaveLength(1)+ await scrollTo(0)+ expect(pending).toHaveLength(1)++ // Expanded: the box gets a size. The view lands at the bottom, far from the top — no fetch.+ geo.perMsg = 1000+ geo.clientHeight = 400+ await resized()+ expect(msgs().scrollTop).toBe(600)+ expect(pending).toHaveLength(1)+ // …and paging works normally from there.+ await scrollTo(0)+ expect(pending).toHaveLength(2)+ })++ it('a panel revealed with a SHORT thread pages back as soon as it has a size', async () => {+ geo.perMsg = 0+ geo.clientHeight = 0+ await render()+ await settle(0, { messages: [say(1000, 'tail')], olderCursor: 1000 })+ expect(pending).toHaveLength(1)+ geo.perMsg = 100+ geo.clientHeight = 400+ await resized()+ expect(pending).toHaveLength(2)+ })++ it('paging survives a rejected reload followed by a reload that finds nothing', async () => {+ geo.perMsg = 1000+ await render()+ await settle(0, { messages: [say(1000, 'tail')], olderCursor: 1000 })+ const refresh = () => host.querySelector<HTMLButtonElement>('.term-chat__refresh')!.click()+ await act(async () => refresh())+ await act(async () => pending[1].reject(new Error('socket blip')))+ await act(async () => refresh())+ await settle(2, { found: false })+ expect(bubbles()).toEqual(['tail'])+ await scrollTo(0)+ expect(pending).toHaveLength(4)+ expect(pending[3].page).toEqual({ before: 1000, maxBytes: CHAT_OLDER_PAGE_BYTES })+ })++ it('switching session while an older page is in flight drops that page and starts clean', async () => {+ geo.perMsg = 1000+ await render('s1')+ await settle(0, { messages: [say(1000, 'OLD tail')], olderCursor: 1000 })+ await scrollTo(0)+ expect(pending).toHaveLength(2)+ await render('s2')+ expect(pending).toHaveLength(3)+ await settle(1, { messages: [say(0, 'OLD older')], olderCursor: null })+ await settle(2, { messages: [say(1000, 'NEW tail')], olderCursor: null })+ expect(bubbles()).toEqual(['NEW tail'])+ })++ it('a reload that cancels an in-flight older fetch removes its row WITHOUT a jump', async () => {+ geo.perMsg = 1000+ await render()+ await settle(0, { messages: [say(1000, 'tail')], olderCursor: 1000 })+ await scrollTo(50)+ expect(msgs().scrollTop).toBe(50 + ROW) // the loading row appeared above+ await act(async () => host.querySelector<HTMLButtonElement>('.term-chat__refresh')!.click())+ expect(host.querySelector('.term-chat__older')).toBeNull()+ expect(msgs().scrollTop).toBe(50) // and went away again: same content under the viewport+ // Paging waits for the tail, then resumes (the user is still at the top).+ expect(pending).toHaveLength(3)+ await settle(2, { messages: [say(1000, 'tail')], olderCursor: 1000 })+ expect(pending).toHaveLength(4)+ expect(pending[3].page).toEqual({ before: 1000, maxBytes: CHAT_OLDER_PAGE_BYTES })+ })})diff --git a/src/renderer/nodes/ChatPanel.tsx b/src/renderer/nodes/ChatPanel.tsxindex 8688d5855..b134b3dad 100644--- a/src/renderer/nodes/ChatPanel.tsx+++ b/src/renderer/nodes/ChatPanel.tsx@@ -113,6 +113,13 @@ export function ChatPanel({// 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')+ // A tail read in flight. Older paging waits for it: the tail can RESET the thread (see+ // applyTail), and an older page fetched against the pre-reload cursor would be thrown away. State,+ // not a ref, so the paging check re-runs when the tail lands.+ const [tailLoading, setTailLoading] = useState(false)+ // Mirror for `load`, which must not depend on it (its identity drives the initial-load effect).+ const olderStateRef = useRef(olderState)+ olderStateRef.current = olderStateconst [input, setInput] = useState('')const [readonly, setReadonly] = useState(false)const state = useAgentStatus((s) => s.byId[nodeId]?.state)@@ -142,16 +149,22 @@ export function ChatPanel({// "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)+ // Never on a panel with no layout box (collapsed node, `display:none`): every metric is 0 there,+ // and an "anchor" at 0 would pin the view to the top of whatever loads while hidden.const captureAnchor = () => {const el = msgsRef.current- if (el) anchorRef.current = { scrollTop: el.scrollTop, scrollHeight: el.scrollHeight }+ if (el && el.clientHeight > 0) anchorRef.current = { scrollTop: el.scrollTop, scrollHeight: el.scrollHeight }}const load = useCallback(() => {const token = ++reqRef.currentolderReqRef.current++olderInFlightRef.current = false+ // Cancelling an older fetch (or clearing its error) removes a row ABOVE the viewport: anchor it+ // like any other change up there, or the view jumps by the row's height.+ if (olderStateRef.current !== 'idle') captureAnchor()setOlderState('idle')+ setTailLoading(true)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@@ -162,11 +175,17 @@ export function ChatPanel({}).then((res) => {if (token !== reqRef.current) return+ setTailLoading(false)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+ if (t.identity === identity && t.messages.length > 0) {+ // The thread on screen is still this transcript's: back to `ok`, or the `loading` this+ // reload set would stick and silently disable older paging (it waits for `ok`).+ setLoadState('ok')+ return+ }setThread(emptyThread(identity))setLoadState('missing')return@@ -176,6 +195,13 @@ export function ChatPanel({},(e: unknown) => {if (token !== reqRef.current) return+ setTailLoading(false)+ // Same rule as a failed resolution: a rendered thread of this transcript stays usable.+ const t = threadRef.current+ if (t.identity === identity && t.messages.length > 0) {+ setLoadState('ok')+ return+ }setLoadState(isUnsupported(e) ? 'unsupported' : 'error')})@@ -268,15 +294,17 @@ export function ChatPanel({if (shouldFetchOlder({scrollTop: el.scrollTop,+ scrollHeight: el.scrollHeight,+ clientHeight: el.clientHeight,olderCursor: thread.identity === identity ? thread.olderCursor : null,- inFlight: olderInFlightRef.current,+ inFlight: olderInFlightRef.current || tailLoading,failed: olderState === 'error',loaded: loadState === 'ok'})) {loadOlder()}- }, [thread.identity, thread.olderCursor, identity, olderState, loadState, loadOlder])+ }, [thread.identity, thread.olderCursor, identity, olderState, loadState, tailLoading, 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.@@ -284,6 +312,27 @@ export function ChatPanel({maybeLoadOlder()}, [maybeLoadOlder])+ // The panel's box changing size — above all a collapsed node being EXPANDED (display:none → a+ // real box). Nothing else re-runs the checks then: while hidden, follow and anchor had zero+ // geometry to work with and paging was refused. So: a user who was following lands at the+ // bottom, and paging resumes (a short thread fetches older right away). Guarded: jsdom and old+ // engines have no ResizeObserver, and the panel works without it.+ const maybeLoadOlderRef = useRef(maybeLoadOlder)+ maybeLoadOlderRef.current = maybeLoadOlder+ useEffect(() => {+ const el = msgsRef.current+ if (!el || typeof ResizeObserver === 'undefined') return+ let hadBox = el.clientHeight > 0+ const ro = new ResizeObserver(() => {+ const hasBox = el.clientHeight > 0+ if (hasBox && !hadBox && nearBottomRef.current) el.scrollTop = el.scrollHeight+ hadBox = hasBox+ maybeLoadOlderRef.current()+ })+ ro.observe(el)+ return () => ro.disconnect()+ }, [])+const onScroll = () => {const el = msgsRef.currentif (el) nearBottomRef.current = isNearBottom(el)