From e91c62885a3ea2445a5565d4fdb3ee553ac3b508 Mon Sep 17 00:00:00 2001 From: Hadrien Kerlero <199662351+HadrienKerlero@users.noreply.github.com> Date: Sat, 14 Nov 2026 12:26:52 +0100 Subject: [PATCH 01/23] fix(web): recover the tmux repaint gap above the live screen on the first scroll-up (#814) A tmux repaint burst overwrites rows that never reach xterm scrollback, leaving a hole just above the live screen. The #205 re-pull only fired at viewportY 0, so the user had to scroll past the hole first. Mark a non-shell session dirty on each live write; the first upward scroll from the bottom of a dirty session runs the existing full-history re-pull anchored to the bottom, keeping the viewport's distance from live output and replaying travel made during the replay. Cooldown, downgrade guard and the top-of-buffer path are unchanged. --- src/web/public/app.js | 36 ++++- src/web/public/terminal-ui.js | 38 ++++- test/shell-scroll-history-pull.test.ts | 184 ++++++++++++++++++++++++- 3 files changed, 250 insertions(+), 8 deletions(-) diff --git a/src/web/public/app.js b/src/web/public/app.js index 94636082..95302d6e 100644 --- a/src/web/public/app.js +++ b/src/web/public/app.js @@ -804,6 +804,9 @@ class CodemanApp { // Cooldown per session for the scroll-to-top "load more history" re-pull. this._fullHistoryRepullAt = new Map(); // Map this._fullHistoryRepullInFlight = false; + this._liveOutputSinceFullPull = new Set(); // Set + this._liveOutputGen = new Map(); // Map + this._earlyReplayTravel = null; // Sessions whose last re-pull came back THINNER than the live buffer (a // repaint-mode CLI pane, where tmux keeps no history of its own). The pull is // refused for those and retried far more slowly — see _maybeRefetchFullHistory. @@ -9616,7 +9619,7 @@ class CodemanApp { * gets a much longer cooldown so a hollow pane stops re-fetching megabytes on * every scroll-up (issue #205, round 2). */ - async _maybeRefetchFullHistory({ force = false } = {}) { + async _maybeRefetchFullHistory({ force = false, anchor = 'top' } = {}) { const sessionId = this.activeSessionId; if (!sessionId || this._fullHistoryRepullInFlight || this._isLoadingBuffer) return; if (this.detachedSessions?.has(sessionId)) return; @@ -9750,6 +9753,9 @@ class CodemanApp { this._fullHistoryRepullUseless?.delete(sessionId); const rowsBefore = this.terminal.buffer.active.length; const replayStartedAt = performance.now(); + const rowsFromBottom = this.terminal.buffer.active.baseY - this.terminal.buffer.active.viewportY; + const liveOutputGen = this._liveOutputGen?.get(sessionId) || 0; + if (anchor === 'bottom') this._earlyReplayTravel = 0; this._resetTerminalForReplay(); const { parsedAt, @@ -9763,6 +9769,9 @@ class CodemanApp { ); timing.resetAndParseMs = parsedAt - replayStartedAt; if (!completed || this.activeSessionId !== sessionId || selectGen !== this._selectGeneration) return; + if ((this._liveOutputGen?.get(sessionId) || 0) === liveOutputGen) { + this._liveOutputSinceFullPull?.delete(sessionId); + } // Keep shell tab restores bounded too. A user-triggered full-history pull // may be tens of MB; caching it would replay that whole payload again on // the next tab switch before the normal 1MB tail fetch replaces it. @@ -9775,9 +9784,17 @@ class CodemanApp { // UPWARD, so what used to be row 0 (what they were looking at) is now `delta` // rows down; scrolling there reveals the recovered history above it instead // of teleporting them to the bottom the way a normal buffer load does. - const delta = parsedBufferLength - rowsBefore; - if (delta > 0) this.terminal.scrollToLine(delta); - else this.terminal.scrollToTop(); + if (anchor === 'bottom') { + // Recover the tmux repaint gap above the live screen without a jump (#814). + const baseY = this.terminal.buffer.active.baseY; + const distance = rowsFromBottom - this._earlyReplayTravel; + this.terminal.scrollToLine(Math.max(0, Math.min(baseY, baseY - distance))); + this._earlyReplayTravel = null; + } else { + const delta = parsedBufferLength - rowsBefore; + if (delta > 0) this.terminal.scrollToLine(delta); + else this.terminal.scrollToTop(); + } // The load's own replay sampled the sticky-scroll baseline while the // terminal sat at the bottom of a just-rewritten buffer, so the next // flush would scroll back down and undo the restore above. This path is @@ -9793,6 +9810,7 @@ class CodemanApp { } catch { // Transient (offline, 5xx) — the next scroll-up past the cooldown retries. } finally { + if (anchor === 'bottom') this._earlyReplayTravel = null; this._fullHistoryRepullInFlight = false; } } @@ -10355,6 +10373,7 @@ class CodemanApp { const fetchStartedAt = performance.now(); const tailUrl = `/api/sessions/${sessionId}/terminal?tail=${TERMINAL_TAIL_SIZE}`; let capture; + let fullHistoryReplay = useFullHistory; try { capture = await this._fetchTerminalCapture( useFullHistory @@ -10375,6 +10394,7 @@ class CodemanApp { _crashDiag.log('FULL CAPTURE ABORTED → tail'); // It never loaded, so the next select must be allowed to try again. this._fullHistoryLoaded.delete(sessionId); + fullHistoryReplay = false; capture = await this._fetchTerminalCapture(tailUrl); } const headersReceivedAt = capture.headersAt; @@ -10413,6 +10433,7 @@ class CodemanApp { _crashDiag.log(`REWRITE: ${(data.terminalBuffer.length/1024).toFixed(0)}KB`); this._setTerminalLoadState(sessionId, selectGen, 'replaying'); const replayStartedAt = performance.now(); + const liveOutputGen = this._liveOutputGen?.get(sessionId) || 0; this._resetTerminalForReplay(); // Truncation is reported OUT OF BAND (#258). This used to write a grey // "... earlier output truncated ..." line into the @@ -10420,7 +10441,7 @@ class CodemanApp { // cannot be actioned, and is indistinguishable from real CLI output. this._setHistoryTruncation(sessionId, data); // Use chunked write for large buffers to avoid UI jank - const { parsedAt: freshParsedAt } = await this.chunkedTerminalWrite( + const { parsedAt: freshParsedAt, completed } = await this.chunkedTerminalWrite( data.terminalBuffer, TERMINAL_CHUNK_SIZE, bufferLoadOwner, @@ -10431,6 +10452,9 @@ class CodemanApp { this._clearTerminalLoadState(sessionId, selectGen); return; } + if (fullHistoryReplay && completed && (this._liveOutputGen?.get(sessionId) || 0) === liveOutputGen) { + this._liveOutputSinceFullPull?.delete(sessionId); + } // Ensure terminal is scrolled to bottom after buffer load this.terminal.scrollToBottom(); } @@ -10838,6 +10862,8 @@ class CodemanApp { } this.terminalBuffers.delete(sessionId); this.terminalBufferCache.delete(sessionId); + this._liveOutputSinceFullPull?.delete(sessionId); + this._liveOutputGen?.delete(sessionId); this._clearHistoryTruncation(sessionId); this._xtermSnapshots?.delete(sessionId); try { localStorage.removeItem(`codeman-xs-${sessionId}`); } catch {} diff --git a/src/web/public/terminal-ui.js b/src/web/public/terminal-ui.js index e3edbdac..369e2b07 100644 --- a/src/web/public/terminal-ui.js +++ b/src/web/public/terminal-ui.js @@ -4068,11 +4068,41 @@ Object.assign(CodemanApp.prototype, { * what the pull left rather than flashing the state it is about to replace. */ _maybeLoadMoreHistoryOnScroll(lines) { + if (typeof this._earlyReplayTravel === 'number') { + this._earlyReplayTravel += lines; + return; + } if (lines > 0) { if (this.isTerminalAtBottom()) this._setHistoryNoticeRevealed?.(null); return; } - if (lines === 0 || this.terminal?.buffer?.active?.viewportY !== 0) return; + if (lines === 0) return; + const buffer = this.terminal?.buffer?.active; + if (buffer?.viewportY !== 0) { + const sessionId = this.activeSessionId; + // tmux repaint bursts can leave a gap just above live output (#814). + // Called after scrollLines: include this gesture's travel in the bottom check. + if ( + lines < 0 && + sessionId && + this._liveOutputSinceFullPull?.has(sessionId) && + this.sessions.get(sessionId)?.mode !== 'shell' && + buffer?.viewportY >= buffer.baseY - 2 - Math.abs(lines) && + !this._fullHistoryRepullInFlight && + !this._isLoadingBuffer + ) { + Promise.resolve(this._maybeRefetchFullHistory?.({ anchor: 'bottom' })) + .catch(() => {}) + .then(() => { + // Travel during the replay is swallowed above, so a gesture that + // reached the top meanwhile still owes the notice its reveal. + if (this.activeSessionId === sessionId && this.terminal?.buffer?.active?.viewportY === 0) { + this._setHistoryNoticeRevealed?.(sessionId); + } + }); + } + return; + } // An earlier frame of this gesture already started the pull; its own // completion reveals the notice, so do not flash the pre-pull state now. if (this._fullHistoryRepullInFlight || this._isLoadingBuffer) return; @@ -4703,6 +4733,12 @@ Object.assign(CodemanApp.prototype, { this._scheduleTerminalWriteFlush(); this._noteMobileImeAuthoritativeOutput(flushedOutputSeq, flushSessionId); }); + // Only live writes can open a new tmux repaint gap; replays cannot (#814). + if (writeChunk.length && flushSessionId && !this._isLoadingBuffer) { + (this._liveOutputSinceFullPull ||= new Set()).add(flushSessionId); + const generations = (this._liveOutputGen ||= new Map()); + generations.set(flushSessionId, (generations.get(flushSessionId) || 0) + 1); + } } catch (err) { this._terminalWriteInFlight = false; this._terminalWriteInFlightBytes = 0; diff --git a/test/shell-scroll-history-pull.test.ts b/test/shell-scroll-history-pull.test.ts index 2b38c3f3..e80345d5 100644 --- a/test/shell-scroll-history-pull.test.ts +++ b/test/shell-scroll-history-pull.test.ts @@ -68,7 +68,7 @@ function loadTerminalMixin(): Record { return FakeCodemanApp.prototype; } -function loadRefetch(): (this: unknown, opts?: { force?: boolean }) => Promise { +function loadRefetch(): (this: unknown, opts?: { force?: boolean; anchor?: string }) => Promise { const app = readFileSync(resolve(PUBLIC, 'app.js'), 'utf8'); const body = methodSource(app, '_maybeRefetchFullHistory'); const context = vm.createContext({ performance, TERMINAL_TAIL_SIZE, TERMINAL_CHUNK_SIZE: 32 * 1024 }); @@ -134,7 +134,7 @@ function makeApp( rows: 30, // xterm's scrollback option; 0 leaves the browser-cap check out of a test. options: { scrollback }, - buffer: { active: { length: bufferRows, baseY: 0 } }, + buffer: { active: { length: bufferRows, baseY: 0, viewportY: 0 } }, scrollToLine: vi.fn(), scrollToTop: vi.fn(), }, @@ -256,6 +256,186 @@ describe('shell scroll-up pulls a bounded window of tmux history', () => { }); }); +describe('early full-history recovery above live output (#814)', () => { + function makeScrollApp(mode = 'omp') { + const { app: base, urls } = makeApp(mode, { bufferRows: 130, capture: lines(400) }); + const app = Object.assign(base, { + _liveOutputSinceFullPull: new Set(), + _liveOutputGen: new Map(), + _earlyReplayTravel: null as number | null, + pendingWrites: [] as string[], + _wasAtBottomBeforeWrite: false, + _scheduleTerminalWriteFlush: vi.fn(), + _restoreTerminalViewport: vi.fn(), + _noteMobileImeAuthoritativeOutput: vi.fn(), + _hasRecentUserScrollUp: () => false, + isTerminalAtBottom: () => app.terminal.buffer.active.viewportY >= app.terminal.buffer.active.baseY - 2, + _setHistoryNoticeRevealed: vi.fn(), + _maybeRefetchFullHistory: vi.fn((opts?: { anchor?: string }) => refetch.call(app, opts)), + }); + Object.assign(app.terminal.buffer.active, { baseY: 100, viewportY: 100 }); + const active = app.terminal.buffer.active as typeof app.terminal.buffer.active & { viewportY: number }; + Object.assign(app.terminal, { + write: vi.fn((_text: string, done: () => void) => done()), + scrollToBottom: vi.fn(), + scrollLines: (n: number) => { + active.viewportY = Math.max(0, Math.min(active.baseY, active.viewportY + n)); + }, + }); + app.terminal.scrollToLine.mockImplementation((row: number) => { + active.viewportY = row; + }); + app.chunkedTerminalWrite.mockImplementation(async () => { + active.baseY = 370; + active.viewportY = 370; + active.length = 400; + return { parsedAt: performance.now(), bufferLength: 400, completed: true }; + }); + const liveOutput = () => { + (mixin.batchTerminalWrite as Function).call(app, 'live repaint'); + (mixin.flushPendingWrites as Function).call(app); + }; + const scroll = async (n: number) => { + active.viewportY = Math.max(0, Math.min(active.baseY, active.viewportY + n)); + (mixin._maybeLoadMoreHistoryOnScroll as Function).call(app, n); + const pull = app._maybeRefetchFullHistory.mock.results.at(-1); + if (pull) await pull.value; + }; + function pauseReplay(beforeComplete = () => {}) { + const replay = app.chunkedTerminalWrite.getMockImplementation()!; + const { promise: gate, resolve: release } = Promise.withResolvers(); + const { promise: ready, resolve: started } = Promise.withResolvers(); + app.chunkedTerminalWrite.mockImplementationOnce(async () => { + app._isLoadingBuffer = true; + active.baseY = 0; + active.viewportY = 0; + started(); + await gate; + const result = await replay(); + app._isLoadingBuffer = false; + beforeComplete(); + return result; + }); + return { ready, release }; + } + return { app, active, urls, liveOutput, scroll, pauseReplay }; + } + + it('pulls on the first upward scroll after live output and preserves distance from the new bottom', async () => { + const { app, active, urls, liveOutput, scroll } = makeScrollApp(); + liveOutput(); + await scroll(-5); + expect(urls).toEqual(['/api/sessions/s1/terminal?full=1']); + expect(active.viewportY).toBe(365); + expect(active.baseY - active.viewportY).toBe(5); + expect(app._liveOutputSinceFullPull.has('s1')).toBe(false); + expect(app._syncStickyScrollBaseline).toHaveBeenCalledOnce(); + // No second early pull until another live write dirties this session. + active.viewportY = active.baseY; + app._fullHistoryRepullAt.clear(); + await scroll(-3); + expect(urls).toHaveLength(1); + }); + + it.each([ + { travel: -12, distance: 17 }, + { travel: 20, distance: 0 }, + { travel: -1000, distance: 370 }, + ])('preserves travel $travel during an unfinished replay, clamped to the buffer', async ({ travel, distance }) => { + const { app, active, liveOutput, scroll, pauseReplay } = makeScrollApp(); + liveOutput(); + const paused = pauseReplay(); + const pull = scroll(-5); + await paused.ready; + // The temporary reset buffer cannot scroll, but the gesture still counts. + active.viewportY = Math.max(0, Math.min(active.baseY, active.viewportY + travel)); + (mixin._maybeLoadMoreHistoryOnScroll as Function).call(app, travel); + expect(app._maybeRefetchFullHistory).toHaveBeenCalledTimes(1); + paused.release(); + await pull; + expect(active.baseY - active.viewportY).toBe(distance); + expect(app._earlyReplayTravel).toBeNull(); + }); + + it('keeps live output flushed before the final restore dirty for the next early pull', async () => { + const { app, active, urls, liveOutput, scroll, pauseReplay } = makeScrollApp(); + liveOutput(); + const generation = app._liveOutputGen.get('s1'); + const paused = pauseReplay(liveOutput); + const pull = scroll(-5); + await paused.ready; + paused.release(); + await pull; + expect(app._liveOutputGen.get('s1')).toBe(generation! + 1); + expect(app._liveOutputSinceFullPull.has('s1')).toBe(true); + app._fullHistoryRepullAt.clear(); + active.viewportY = active.baseY; + await scroll(-3); + expect(urls).toEqual(['/api/sessions/s1/terminal?full=1', '/api/sessions/s1/terminal?full=1']); + expect(app._liveOutputSinceFullPull.has('s1')).toBe(false); + }); + + it('keeps a clean non-shell session local until the existing top path is reached', async () => { + const { app, active, urls, scroll } = makeScrollApp(); + await scroll(-5); + expect(urls).toEqual([]); + await scroll(-active.viewportY); + expect(urls).toEqual(['/api/sessions/s1/terminal?full=1']); + expect(app._maybeRefetchFullHistory).toHaveBeenCalledWith(); + expect(app.terminal.scrollToLine).toHaveBeenCalledWith(270); + }); + + it('never pulls early for a shell, even after live output', async () => { + const { urls, liveOutput, scroll } = makeScrollApp('shell'); + liveOutput(); + await scroll(-5); + expect(urls).toEqual([]); + await scroll(-95); + expect(urls).toEqual([`/api/sessions/s1/terminal?full=1&tail=${TERMINAL_TAIL_SIZE}`]); + }); + + it('does not dirty a session while replay loading queues its output', () => { + const { app, liveOutput } = makeScrollApp(); + app._isLoadingBuffer = true; + liveOutput(); + expect(app._liveOutputSinceFullPull.size).toBe(0); + }); + + it('does not pull early for downward travel or while already reading older rows', async () => { + const { active, urls, liveOutput, scroll } = makeScrollApp(); + liveOutput(); + active.viewportY = 50; + await scroll(-5); + active.viewportY = 95; + await scroll(3); + expect(urls).toEqual([]); + }); + + it.each(['_isLoadingBuffer', '_fullHistoryRepullInFlight'] as const)('respects the %s guard', async (guard) => { + const { app, urls, liveOutput, scroll } = makeScrollApp(); + liveOutput(); + app[guard] = true; + await scroll(-5); + expect(urls).toEqual([]); + }); + + it('keeps the cooldown and downgrade guard on an early pull', async () => { + const { app, active, urls, liveOutput, scroll } = makeScrollApp(); + liveOutput(); + app._fullHistoryRepullAt.set('s1', Date.now()); + await scroll(-3); + expect(urls).toEqual([]); + app._fullHistoryRepullAt.clear(); + active.viewportY = active.baseY; + active.length = 1000; + await scroll(-3); + expect(urls).toHaveLength(1); + expect(app._resetTerminalForReplay).not.toHaveBeenCalled(); + expect(app._liveOutputSinceFullPull.has('s1')).toBe(true); + expect(app._fullHistoryRepullUseless.has('s1')).toBe(true); + }); +}); + describe('a skipped bounded window never damages the Load full history banner', () => { it('a tail-cut window smaller than the browser is not replayed and never marks the session exhausted', async () => { // The browser holds far more rows than a 1 MiB window carries, and tmux holds From fd31315582a662ac1923b0f480948292a4c702d6 Mon Sep 17 00:00:00 2001 From: Hadrien Kerlero <199662351+HadrienKerlero@users.noreply.github.com> Date: Sat, 14 Nov 2026 12:56:45 +0100 Subject: [PATCH 02/23] fix(web): keep fetch-time output dirty and clamp replay travel per move (#814) Review follow-up. The early re-pull sampled the live-output generation after its fetch, but nothing gates live output while the capture downloads, so output newer than the capture was overwritten and the session marked clean. Sample before the fetch. Travel made during the replay was one signed sum clamped once, so scrolling to the bottom and back up cancelled out. Record moves in order and clamp after each, as live scrolling does. --- src/web/public/app.js | 17 ++++++++++----- src/web/public/terminal-ui.js | 4 ++-- test/shell-scroll-history-pull.test.ts | 30 ++++++++++++++++++++------ 3 files changed, 37 insertions(+), 14 deletions(-) diff --git a/src/web/public/app.js b/src/web/public/app.js index 95302d6e..1f166e87 100644 --- a/src/web/public/app.js +++ b/src/web/public/app.js @@ -806,7 +806,7 @@ class CodemanApp { this._fullHistoryRepullInFlight = false; this._liveOutputSinceFullPull = new Set(); // Set this._liveOutputGen = new Map(); // Map - this._earlyReplayTravel = null; + this._earlyReplayTravel = null; // number[] while an early (#814) replay runs // Sessions whose last re-pull came back THINNER than the live buffer (a // repaint-mode CLI pane, where tmux keeps no history of its own). The pull is // refused for those and retried far more slowly — see _maybeRefetchFullHistory. @@ -9658,6 +9658,10 @@ class CodemanApp { // replaying its own capture, and the reset below would land in the middle // of that write. The select generation moves on every switch, so it can. const selectGen = this._selectGeneration; + // Sampled BEFORE the fetch: this path does not gate live output while the + // capture downloads, so output flushed after tmux captured would otherwise + // be overwritten by the replay and still count as covered by it (#814). + const liveOutputGen = this._liveOutputGen?.get(sessionId) || 0; try { const requestStartedAt = performance.now(); const capture = await this._fetchTerminalCapture( @@ -9754,8 +9758,9 @@ class CodemanApp { const rowsBefore = this.terminal.buffer.active.length; const replayStartedAt = performance.now(); const rowsFromBottom = this.terminal.buffer.active.baseY - this.terminal.buffer.active.viewportY; - const liveOutputGen = this._liveOutputGen?.get(sessionId) || 0; - if (anchor === 'bottom') this._earlyReplayTravel = 0; + // Ordered, not summed: each move clamps at the buffer edge as it would + // have live, so a reversal after hitting the bottom is not cancelled out. + if (anchor === 'bottom') this._earlyReplayTravel = []; this._resetTerminalForReplay(); const { parsedAt, @@ -9787,8 +9792,10 @@ class CodemanApp { if (anchor === 'bottom') { // Recover the tmux repaint gap above the live screen without a jump (#814). const baseY = this.terminal.buffer.active.baseY; - const distance = rowsFromBottom - this._earlyReplayTravel; - this.terminal.scrollToLine(Math.max(0, Math.min(baseY, baseY - distance))); + const clamp = (row) => Math.max(0, Math.min(baseY, row)); + let row = clamp(baseY - rowsFromBottom); + for (const move of this._earlyReplayTravel) row = clamp(row + move); + this.terminal.scrollToLine(row); this._earlyReplayTravel = null; } else { const delta = parsedBufferLength - rowsBefore; diff --git a/src/web/public/terminal-ui.js b/src/web/public/terminal-ui.js index 369e2b07..17c17403 100644 --- a/src/web/public/terminal-ui.js +++ b/src/web/public/terminal-ui.js @@ -4068,8 +4068,8 @@ Object.assign(CodemanApp.prototype, { * what the pull left rather than flashing the state it is about to replace. */ _maybeLoadMoreHistoryOnScroll(lines) { - if (typeof this._earlyReplayTravel === 'number') { - this._earlyReplayTravel += lines; + if (Array.isArray(this._earlyReplayTravel)) { + this._earlyReplayTravel.push(lines); return; } if (lines > 0) { diff --git a/test/shell-scroll-history-pull.test.ts b/test/shell-scroll-history-pull.test.ts index e80345d5..19c5d1f8 100644 --- a/test/shell-scroll-history-pull.test.ts +++ b/test/shell-scroll-history-pull.test.ts @@ -262,7 +262,7 @@ describe('early full-history recovery above live output (#814)', () => { const app = Object.assign(base, { _liveOutputSinceFullPull: new Set(), _liveOutputGen: new Map(), - _earlyReplayTravel: null as number | null, + _earlyReplayTravel: null as number[] | null, pendingWrites: [] as string[], _wasAtBottomBeforeWrite: false, _scheduleTerminalWriteFlush: vi.fn(), @@ -338,18 +338,20 @@ describe('early full-history recovery above live output (#814)', () => { }); it.each([ - { travel: -12, distance: 17 }, - { travel: 20, distance: 0 }, - { travel: -1000, distance: 370 }, - ])('preserves travel $travel during an unfinished replay, clamped to the buffer', async ({ travel, distance }) => { + { moves: [-12], distance: 17 }, + { moves: [20], distance: 0 }, + { moves: [-1000], distance: 370 }, + // Reversal after an edge: each move clamps as it would have live. + { moves: [20, -12], distance: 12 }, + { moves: [-1000, 30], distance: 340 }, + ])('replays travel $moves made during an unfinished replay, clamped per move', async ({ moves, distance }) => { const { app, active, liveOutput, scroll, pauseReplay } = makeScrollApp(); liveOutput(); const paused = pauseReplay(); const pull = scroll(-5); await paused.ready; // The temporary reset buffer cannot scroll, but the gesture still counts. - active.viewportY = Math.max(0, Math.min(active.baseY, active.viewportY + travel)); - (mixin._maybeLoadMoreHistoryOnScroll as Function).call(app, travel); + for (const move of moves) (mixin._maybeLoadMoreHistoryOnScroll as Function).call(app, move); expect(app._maybeRefetchFullHistory).toHaveBeenCalledTimes(1); paused.release(); await pull; @@ -357,6 +359,20 @@ describe('early full-history recovery above live output (#814)', () => { expect(app._earlyReplayTravel).toBeNull(); }); + it('keeps a session dirty when live output lands while the capture is still downloading', async () => { + const { app, urls, liveOutput, scroll } = makeScrollApp(); + liveOutput(); + const fetchCapture = app._fetchTerminalCapture.getMockImplementation()!; + app._fetchTerminalCapture.mockImplementationOnce(async (url: string) => { + const capture = await fetchCapture(url); + // tmux has captured; this output is newer than the capture the replay writes. + liveOutput(); + return capture; + }); + await scroll(-5); + expect(urls).toHaveLength(1); + expect(app._liveOutputSinceFullPull.has('s1')).toBe(true); + }); it('keeps live output flushed before the final restore dirty for the next early pull', async () => { const { app, active, urls, liveOutput, scroll, pauseReplay } = makeScrollApp(); liveOutput(); From b890ef3302d4e1deb9c474b45a038d32e5d0d8b5 Mon Sep 17 00:00:00 2001 From: Hadrien Kerlero <199662351+HadrienKerlero@users.noreply.github.com> Date: Mon, 16 Nov 2026 00:45:46 +0100 Subject: [PATCH 03/23] fix(web): repair the history gap while reading, queue download-time output, add a phone reload control (#814) Review follow-up on #815, and the phone case from #814: the gap opens below a reader who stays scrolled up while output arrives, and the bottom-only trigger never fired there. - Open the buffer load before the capture fetch so output arriving during the download is queued and replayed, not wiped by the reset. Every non-replay exit flushes the queue. A drop at the 128 KiB cap during an open load is deferred and resumed when the load ends instead of spending its retries against it. - Clear the live-output mark only when the response is source 'mux-full-history', on the scroll and tab-switch paths. - Repair on any upward scroll in a marked non-shell session, not only from the bottom. A content anchor (3-row signature, searched at most 2000 rows either side) keeps the row being read in place; no match falls back to distance from the bottom. - Tie replay travel to its session so a tab switch does not swallow moves on the new tab. - Reveal the partial-history notice when the initiating gesture reached the top, even if the anchor moved the viewport off row 0. - Touch-only Reload history button (#historyReloadBtn), styled in styles.css so wide touch viewports get it too. Non-touch pages skip its work entirely. - Docs, JSDoc and a changeset. Unit tests, and a Playwright browser test with trusted touch events and real xterm. Fixes #814 --- .../814-history-repair-while-reading.md | 5 + config/test-suites.ts | 1 + docs/architecture-invariants.md | 4 +- src/web/public/app.js | 68 ++- src/web/public/index.html | 1 + src/web/public/styles.css | 20 + src/web/public/terminal-ui.js | 146 ++++-- test/history-gap-repair.browser.test.ts | 451 ++++++++++++++++++ test/history-notice-reveal.test.ts | 25 + test/shell-scroll-history-pull.test.ts | 413 +++++++++++++++- 10 files changed, 1050 insertions(+), 84 deletions(-) create mode 100644 .changeset/814-history-repair-while-reading.md create mode 100644 test/history-gap-repair.browser.test.ts diff --git a/.changeset/814-history-repair-while-reading.md b/.changeset/814-history-repair-while-reading.md new file mode 100644 index 00000000..f67cf6c8 --- /dev/null +++ b/.changeset/814-history-repair-while-reading.md @@ -0,0 +1,5 @@ +--- +'aicodeman': patch +--- + +Fix missing terminal history above live OMP output, including when scrolling up while already reading older output on a phone. History recovery now preserves the text being read and output arriving during the download, and touch devices offer a Reload history button while scrolled away from live output. diff --git a/config/test-suites.ts b/config/test-suites.ts index 6e523cc3..44d206b4 100644 --- a/config/test-suites.ts +++ b/config/test-suites.ts @@ -39,6 +39,7 @@ export const BROWSER_TEST_GLOBS = [ 'test/terminal-copy-shortcut.test.ts', 'test/terminal-keycode229-recovery.browser.test.ts', 'test/capture-load-window.browser.test.ts', + 'test/history-gap-repair.browser.test.ts', 'test/capture-geometry-retry.browser.test.ts', 'test/codex-predictive-echo.test.ts', // also needs a real codex binary 'test/split-pane-terminal.browser.test.ts', diff --git a/docs/architecture-invariants.md b/docs/architecture-invariants.md index a10b1f72..784d696c 100644 --- a/docs/architecture-invariants.md +++ b/docs/architecture-invariants.md @@ -251,7 +251,9 @@ Further detail: the `: ` form (`w3-myapp: fix the login redirect` ### Full-scrollback replay -**Full-scrollback replay** (COD-164/#148, reworked for #205): `GET /api/sessions/:id/terminal?full=1` returns the ENTIRE tmux scrollback (capture-pane `-e -S -<lines>` bounded by the configured history limit, explicit `maxBuffer` from the terminal-history config, early byte-cap before normalization, CRLF-normalized for shell panes). On success the capture is returned ALONE (`source='mux-full-history'` — it supersedes the byte buffer; no duplication). The first load of each non-shell TUI session per page requests `full=1` (`_fullHistoryLoaded` Set in app.js — the old one-shot `_initialFullBufferLoad` flag was consumed by whichever tab auto-selected, leaving every other TUI tab one frame of history). Shell sessions instead load a bounded window of tmux's RENDERED history on every selection, automatic drop recovery, clear and tile load (`SHELL_LOAD_QUERY` in constants.js: `?full=1&tail=1MiB&lines=10000&alt=recording`): a 100k-line shell capture can be tens of MiB, and automatically parsing it makes tab-switch latency scale with the entire session (`lines=` bounds the synchronous capture-pane, about 8 ms per 1000 lines). They never replay the raw byte recording ahead of the visible frame any more: it holds full-screen repaints (an ssh'd tmux, `less`, any TUI) drawn for the pane height of the moment, and replayed into a terminal of another height each repaint's last newline scrolls its top row into scrollback, so one line tmux holds once showed up dozens of times. Because `lines=` is shallower than xterm's scrollback, the route reports a cut: the capture's `display-message` query also reads `#{history_size}` (`PaneCaptureOptions.capturedHistoryLines`, the same field the route reports as `paneHistoryLines`), and a full capture whose CLIENT bound (`lines=` below the configured `tmuxHistoryLimit`) left lines in tmux comes back `truncated`, `truncationReason: 'tail'`. ⚠️ Only a client bound below the ceiling counts: a request without `lines=` is bounded by the ceiling itself, and on tmux before 3.7 a live pane can hold more than a lowered ceiling, which no request can read. ⚠️ **A pane in the alternate screen keeps no tmux history**, and a nested tmux client (remote SSH and Docker cases, or `tmux`/`ssh -t host tmux` run by hand) holds its pane there, so its full capture is one screen. The same query reads `#{alternate_on}` (`capturedAlternateOn`), and a request carrying `alt=recording` (only `SHELL_LOAD_QUERY`) is then answered the old way, the visible frame over the tailed byte recording, which still carries the scrollback; agents, scroll pulls and **Load full history** never send it. `#{alternate_on}` cannot tell a nested tmux from vim, `less` or `htop`, so a local shell with one of those open takes the same fallback until it exits (the pre-fix load, with its repaint duplicates). Shell FULL history is explicit-button-only; reaching the top during an ordinary wheel/touch gesture must not reset xterm and replay the multi-megabyte capture on its main thread. That gesture instead pulls a BOUNDED window of it (`?full=1&tail=<TERMINAL_TAIL_SIZE>`, so a capture beyond 1 MiB comes back `truncationReason: 'tail'` and the banner offers the rest), and skips the replay when the window holds no more rows than the browser already has. ⚠️ **That skip runs BEFORE the downgrade guard, and it never touches the banner state**: the guard reads "smaller than the browser" as "tmux has nothing more to give", true of an unbounded capture and false of a window cut at the tail size, so a bounded window that reached it marked the session `exhausted` and removed **Load full history** while tmux still held the rest; and re-labelling the banner from a skipped payload would call a terminal that holds all of a Load full history pull "the most recent 1 MiB". A skipped window that came back truncated puts the session on the 60 s cooldown (`_fullHistoryRepullUseless`), because it can never reach anything older than the browser shows and `tail` is applied AFTER the server's synchronous `capture-pane` of the whole history, so each ask costs every client an event-loop stall (about 0.3 s at 100k lines); an untruncated one keeps the 4 s cooldown, since it is all of tmux's history and the next burst can add to it. Declining the gesture outright was a dead end: after any burst a shell pane held about one screen of browser scrollback, and the button renders only once a replay was truncated, so a young shell tab had no way back to history tmux still held. Other modes may still re-pull `full=1` at the TOP, and pressing **Load full history** forces the request for any recoverably truncated session (`_maybeRefetchFullHistory`, 4s per-session gesture cooldown, in-flight + tab-switch guards, viewport position held across the replay); Shell full pulls are not retained in the tab cache, so the next switch stays bounded. Chunked replay enqueues 32 KiB pieces across safe yields, appends an xterm parse marker, then releases the live-output gate; output arriving after that release stays ordered behind the snapshot, and the marker callback supplies accurate parse timing. ⚠️ **How the load ENDS depends on where the payload came from**, and `_bufferLoadFinishOpts` (app.js) is the one place that decides it for all four fetch-and-write paths. A payload built from the server's accumulated byte history is current up to the response, so the events queued during the load already appear in it and stay DISCARDED; replaying them would duplicate output, most visibly Ink's cursor-up redraws. A pane capture (`mux-visible` or `mux-full-history`) is current only up to CAPTURE time, so `_finishBufferLoad` replays the queue from the response's own arrival timestamp (`since`) and the pre-capture events stay dropped. ⚠️ **A path that then restores a scroll position must re-take the sticky-scroll baseline** (`_syncStickyScrollBaseline`): the replay runs inside `chunkedTerminalWrite` before its promise resolves, with the terminal freshly reset, so `batchTerminalWrite` samples `_wasAtBottomBeforeWrite` as true and the next `flushPendingWrites` would scroll to the bottom over the restore. ⚠️ The cutoff is a client-side timestamp and the server broadcasts on a batch timer (8ms WebSocket, 16-50ms SSE), so a batch pending when the capture ran arrives after the response and replays although the capture holds it — bounded by one batch interval, and closable only server side by flushing that batch before the capture. Tests for the three: `test/terminal-flush-budget.test.ts` pins which sources flush, `test/terminal-buffer-flush.test.ts` pins the `since` cutoff and the baseline re-take, and `test/capture-load-window.browser.test.ts` drives both against a live server. Live output is separately one-chunk-in-flight: xterm's callback releases each 32/64 KiB write before the next is submitted, keeping the remainder in the app queue where the 128 KiB cap can observe it instead of hiding an unbounded backlog in xterm's private WriteBuffer. While WebSocket owns terminal I/O, parallel SSE terminal/output-recovery events are discarded before JSON parsing; fallback recovery is single-flight per active session so backpressure cannot start overlapping reset+replay cycles. The route exposes capture/prepare totals in `Server-Timing`, while `[TERMINAL-PERF]` separates TTFB, body/JSON, reset+parse and total time for both selection and on-demand full pulls; parse completion is not a browser compositor/GPU paint measurement. The re-pull exists because xterm's buffer is only a WINDOW onto tmux's history and two things shrink it: tmux coalesces bursty output into pane REPAINTS that overwrite rows instead of emitting linefeeds (measured: a 60-line burst added 1 row of browser scrollback and destroyed 34), and a tab switch replays only the visible frame. tmux's own history is intact throughout — the browser just has to ask for it again. On-demand rather than automatic because at a 100k history limit the capture can be megabytes. ⚠️ **The capture ENDS with a cursor move back to the pane's own caret position** (`formatCursorRestore`, from the same `display-message` query the visible-frame path uses). The linear replay otherwise leaves the caret wherever the last character landed — the bottom-most row carrying text, which for an agent CLI is the status line — so the caret sat on the composer's border instead of its input line and every cursor-relative update the CLI sent afterwards was measured from the wrong row, until its next full redraw silently repaired it (that self-repair is why the report read as "it fixes itself as soon as Claude writes a line"). ⚠️ **The move is RELATIVE — up `rows - 1 - cursor_y`, then `\r`, then right `cursor_x` — never `CUP`.** `\x1b[<row>;<col>H` numbers rows from the top of the browser's screen, so it lands correctly only while the browser's row count equals `pane_height`, and nothing guarantees that: `resizeWindow` issues its tmux resize fire-and-forget and returns immediately, so a capture can be taken before a requested resize has applied, and `_onSessionNeedsRefresh` sends no resize at all. Counting up from the last replayed row anchors to the content both ends share. Restoring the cursor makes ROW ALIGNMENT load-bearing on this path: **no transform that can DELETE A LINE may run over a full-history capture**, because every deletion shifts the frame out from under the restored position. Four had accumulated — trailing blank rows stripped by `\n+$`, `stripInkRedrawBloat`, the `CLAUDE_BANNER_PATTERN` trim that cuts everything above the banner, and `LEADING_WHITESPACE_PATTERN` — each correct for a byte stream of successive frames and each wrong for a single rendered frame. ⚠️ **Those skips key on `isFullCapture`, meaning a capture actually came back — never on `?full=1` alone.** When `captureActivePaneBuffer` returns null (ENOBUFS, a timeout, a vanished pane, or a session with no mux at all) the reply falls back to `session.terminalBuffer`, which IS a byte stream and must still be stripped; gating on the query flag returned it whole, and a direct-PTY session takes that path on every first selection rather than only during an outage. ⚠️ A capture holding nothing visible (`hasVisibleContent`) returns `''`, because the caller reads an empty capture as "unavailable" and keeps its byte history — retaining trailing blank rows made an all-blank pane non-empty, which would have replaced real history with a blank screen from the server side, where `_replayWouldShrinkBuffer` cannot see it. ⚠️ **"One line per screen row" holds only where no row was hard-wrapped**: `-J` joins a wrapped row into its logical line (measured: a 100-character line in a 40-column pane captures as 10 lines against a 12-row pane), and the counts reconcile only once the browser xterm re-wraps at the same width — the same assumption `_estimateReplayRows` already documents. Tests: `test/tmux-capture-full-history.test.ts` covers the cursor move, the trim pairing and `hasVisibleContent`; `test/routes/session-routes.test.ts` covers a surviving blank first row, an unstripped byte-history fallback, and an empty capture leaving history intact. ⚠️ **The re-pull must never DOWNGRADE the buffer** (#205 round 2): the same reasoning that makes it a win for a shell pane makes it destructive for a repaint-mode CLI pane, where tmux keeps no history of its own (`history_size≈0` measured for a Claude pane) and the capture is roughly ONE frame while xterm may hold hundreds of rows of replayed frames — `_resetTerminalForReplay()` + rewrite then deletes history mid-scroll ("goes back a bit, repeats blocks, gets worse the further up I go"; measured A/B on a live pane: 341 rows → 42 with the guard off). `_replayWouldShrinkBuffer()` (terminal-ui.js) estimates the capture's rendered rows — escape sequences stripped, `capture-pane -J` re-wrapping accounted for — and the pull is skipped when that is more than one screen short of `buffer.active.length`. The one-screen tolerance matters: both sides are estimates (the buffer length counts trailing blank rows), so only a clear downgrade is refused. A refused session joins `_fullHistoryRepullUseless`, raising its cooldown from 4s to 60s so a hollow pane stops re-fetching megabytes on every scroll-up. Tests: `test/tmux-capture-full-history.test.ts`, `test/tmux-scrollback-eol.test.ts`, `test/terminal-scroll-routing.test.ts`, `test/terminal-flush-budget.test.ts`. +**Full-scrollback replay** (COD-164/#148, reworked for #205): `GET /api/sessions/:id/terminal?full=1` returns the ENTIRE tmux scrollback (capture-pane `-e -S -<lines>` bounded by the configured history limit, explicit `maxBuffer` from the terminal-history config, early byte-cap before normalization, CRLF-normalized for shell panes). On success the capture is returned ALONE (`source='mux-full-history'` — it supersedes the byte buffer; no duplication). The first load of each non-shell TUI session per page requests `full=1` (`_fullHistoryLoaded` Set in app.js — the old one-shot `_initialFullBufferLoad` flag was consumed by whichever tab auto-selected, leaving every other TUI tab one frame of history). Shell sessions instead load a bounded window of tmux's RENDERED history on every selection, automatic drop recovery, clear and tile load (`SHELL_LOAD_QUERY` in constants.js: `?full=1&tail=1MiB&lines=10000&alt=recording`): a 100k-line shell capture can be tens of MiB, and automatically parsing it makes tab-switch latency scale with the entire session (`lines=` bounds the synchronous capture-pane, about 8 ms per 1000 lines). They never replay the raw byte recording ahead of the visible frame any more: it holds full-screen repaints (an ssh'd tmux, `less`, any TUI) drawn for the pane height of the moment, and replayed into a terminal of another height each repaint's last newline scrolls its top row into scrollback, so one line tmux holds once showed up dozens of times. Because `lines=` is shallower than xterm's scrollback, the route reports a cut: the capture's `display-message` query also reads `#{history_size}` (`PaneCaptureOptions.capturedHistoryLines`, the same field the route reports as `paneHistoryLines`), and a full capture whose CLIENT bound (`lines=` below the configured `tmuxHistoryLimit`) left lines in tmux comes back `truncated`, `truncationReason: 'tail'`. ⚠️ Only a client bound below the ceiling counts: a request without `lines=` is bounded by the ceiling itself, and on tmux before 3.7 a live pane can hold more than a lowered ceiling, which no request can read. ⚠️ **A pane in the alternate screen keeps no tmux history**, and a nested tmux client (remote SSH and Docker cases, or `tmux`/`ssh -t host tmux` run by hand) holds its pane there, so its full capture is one screen. The same query reads `#{alternate_on}` (`capturedAlternateOn`), and a request carrying `alt=recording` (only `SHELL_LOAD_QUERY`) is then answered the old way, the visible frame over the tailed byte recording, which still carries the scrollback; agents, scroll pulls and **Load full history** never send it. `#{alternate_on}` cannot tell a nested tmux from vim, `less` or `htop`, so a local shell with one of those open takes the same fallback until it exits (the pre-fix load, with its repaint duplicates). Shell FULL history is explicit-button-only; reaching the top during an ordinary wheel/touch gesture must not reset xterm and replay the multi-megabyte capture on its main thread. That gesture instead pulls a BOUNDED window of it (`?full=1&tail=<TERMINAL_TAIL_SIZE>`, so a capture beyond 1 MiB comes back `truncationReason: 'tail'` and the banner offers the rest), and skips the replay when the window holds no more rows than the browser already has. ⚠️ **That skip runs BEFORE the downgrade guard, and it never touches the banner state**: the guard reads "smaller than the browser" as "tmux has nothing more to give", true of an unbounded capture and false of a window cut at the tail size, so a bounded window that reached it marked the session `exhausted` and removed **Load full history** while tmux still held the rest; and re-labelling the banner from a skipped payload would call a terminal that holds all of a Load full history pull "the most recent 1 MiB". A skipped window that came back truncated puts the session on the 60 s cooldown (`_fullHistoryRepullUseless`), because it can never reach anything older than the browser shows and `tail` is applied AFTER the server's synchronous `capture-pane` of the whole history, so each ask costs every client an event-loop stall (about 0.3 s at 100k lines); an untruncated one keeps the 4 s cooldown, since it is all of tmux's history and the next burst can add to it. Declining the gesture outright was a dead end: after any burst a shell pane held about one screen of browser scrollback, and the button renders only once a replay was truncated, so a young shell tab had no way back to history tmux still held. Other modes re-pull `full=1` at the top or on any upward scroll after live output since the last `mux-full-history` replay, and pressing **Load full history** forces the request for any recoverably truncated session (`_maybeRefetchFullHistory`, 4s per-session gesture cooldown, in-flight + tab-switch guards, viewport position held across the replay); Shell full pulls are not retained in the tab cache, so the next switch stays bounded. Chunked replay enqueues 32 KiB pieces across safe yields, appends an xterm parse marker, then releases the live-output gate; output arriving after that release stays ordered behind the snapshot, and the marker callback supplies accurate parse timing. ⚠️ **How the load ENDS depends on where the payload came from**, and `_bufferLoadFinishOpts` (app.js) is the one place that decides it for all four fetch-and-write paths. A payload built from the server's accumulated byte history is current up to the response, so the events queued during the load already appear in it and stay DISCARDED; replaying them would duplicate output, most visibly Ink's cursor-up redraws. A pane capture (`mux-visible` or `mux-full-history`) is current only up to CAPTURE time, so `_finishBufferLoad` replays the queue from the response's own arrival timestamp (`since`) and the pre-capture events stay dropped. ⚠️ **A path that then restores a scroll position must re-take the sticky-scroll baseline** (`_syncStickyScrollBaseline`): the replay runs inside `chunkedTerminalWrite` before its promise resolves, with the terminal freshly reset, so `batchTerminalWrite` samples `_wasAtBottomBeforeWrite` as true and the next `flushPendingWrites` would scroll to the bottom over the restore. ⚠️ The cutoff is a client-side timestamp and the server broadcasts on a batch timer (8ms WebSocket, 16-50ms SSE), so a batch pending when the capture ran arrives after the response and replays although the capture holds it — bounded by one batch interval, and closable only server side by flushing that batch before the capture. Tests for the three: `test/terminal-flush-budget.test.ts` pins which sources flush, `test/terminal-buffer-flush.test.ts` pins the `since` cutoff and the baseline re-take, and `test/capture-load-window.browser.test.ts` drives both against a live server. Live output is separately one-chunk-in-flight: xterm's callback releases each 32/64 KiB write before the next is submitted, keeping the remainder in the app queue where the 128 KiB cap can observe it instead of hiding an unbounded backlog in xterm's private WriteBuffer. While WebSocket owns terminal I/O, parallel SSE terminal/output-recovery events are discarded before JSON parsing; fallback recovery is single-flight per active session so backpressure cannot start overlapping reset+replay cycles. The route exposes capture/prepare totals in `Server-Timing`, while `[TERMINAL-PERF]` separates TTFB, body/JSON, reset+parse and total time for both selection and on-demand full pulls; parse completion is not a browser compositor/GPU paint measurement. The re-pull exists because xterm's buffer is only a WINDOW onto tmux's history and two things shrink it: tmux coalesces bursty output into pane REPAINTS that overwrite rows instead of emitting linefeeds (measured: a 60-line burst added 1 row of browser scrollback and destroyed 34), and a tab switch replays only the visible frame. tmux's own history is intact throughout — the browser just has to ask for it again. Gesture-triggered rather than polling because at a 100k history limit the capture can be megabytes. ⚠️ **The capture ENDS with a cursor move back to the pane's own caret position** (`formatCursorRestore`, from the same `display-message` query the visible-frame path uses). The linear replay otherwise leaves the caret wherever the last character landed — the bottom-most row carrying text, which for an agent CLI is the status line — so the caret sat on the composer's border instead of its input line and every cursor-relative update the CLI sent afterwards was measured from the wrong row, until its next full redraw silently repaired it (that self-repair is why the report read as "it fixes itself as soon as Claude writes a line"). ⚠️ **The move is RELATIVE — up `rows - 1 - cursor_y`, then `\r`, then right `cursor_x` — never `CUP`.** `\x1b[<row>;<col>H` numbers rows from the top of the browser's screen, so it lands correctly only while the browser's row count equals `pane_height`, and nothing guarantees that: `resizeWindow` issues its tmux resize fire-and-forget and returns immediately, so a capture can be taken before a requested resize has applied, and `_onSessionNeedsRefresh` sends no resize at all. Counting up from the last replayed row anchors to the content both ends share. Restoring the cursor makes ROW ALIGNMENT load-bearing on this path: **no transform that can DELETE A LINE may run over a full-history capture**, because every deletion shifts the frame out from under the restored position. Four had accumulated — trailing blank rows stripped by `\n+$`, `stripInkRedrawBloat`, the `CLAUDE_BANNER_PATTERN` trim that cuts everything above the banner, and `LEADING_WHITESPACE_PATTERN` — each correct for a byte stream of successive frames and each wrong for a single rendered frame. ⚠️ **Those skips key on `isFullCapture`, meaning a capture actually came back — never on `?full=1` alone.** When `captureActivePaneBuffer` returns null (ENOBUFS, a timeout, a vanished pane, or a session with no mux at all) the reply falls back to `session.terminalBuffer`, which IS a byte stream and must still be stripped; gating on the query flag returned it whole, and a direct-PTY session takes that path on every first selection rather than only during an outage. ⚠️ A capture holding nothing visible (`hasVisibleContent`) returns `''`, because the caller reads an empty capture as "unavailable" and keeps its byte history — retaining trailing blank rows made an all-blank pane non-empty, which would have replaced real history with a blank screen from the server side, where `_replayWouldShrinkBuffer` cannot see it. ⚠️ **"One line per screen row" holds only where no row was hard-wrapped**: `-J` joins a wrapped row into its logical line (measured: a 100-character line in a 40-column pane captures as 10 lines against a 12-row pane), and the counts reconcile only once the browser xterm re-wraps at the same width — the same assumption `_estimateReplayRows` already documents. Tests: `test/tmux-capture-full-history.test.ts` covers the cursor move, the trim pairing and `hasVisibleContent`; `test/routes/session-routes.test.ts` covers a surviving blank first row, an unstripped byte-history fallback, and an empty capture leaving history intact. ⚠️ **The re-pull must never DOWNGRADE the buffer** (#205 round 2): the same reasoning that makes it a win for a shell pane makes it destructive for a repaint-mode CLI pane, where tmux keeps no history of its own (`history_size≈0` measured for a Claude pane) and the capture is roughly ONE frame while xterm may hold hundreds of rows of replayed frames — `_resetTerminalForReplay()` + rewrite then deletes history mid-scroll ("goes back a bit, repeats blocks, gets worse the further up I go"; measured A/B on a live pane: 341 rows → 42 with the guard off). `_replayWouldShrinkBuffer()` (terminal-ui.js) estimates the capture's rendered rows — escape sequences stripped, `capture-pane -J` re-wrapping accounted for — and the pull is skipped when that is more than one screen short of `buffer.active.length`. The one-screen tolerance matters: both sides are estimates (the buffer length counts trailing blank rows), so only a clear downgrade is refused. A refused session joins `_fullHistoryRepullUseless`, raising its cooldown from 4s to 60s so a hollow pane stops re-fetching megabytes on every scroll-up. Tests: `test/tmux-capture-full-history.test.ts`, `test/tmux-scrollback-eol.test.ts`, `test/terminal-scroll-routing.test.ts`, `test/terminal-flush-budget.test.ts`. + +**Repair while reading (#814)** opens the buffer load BEFORE the capture fetch, so download-time output queues behind the replay instead of being overwritten. Every non-replay exit flushes the whole queue into the untouched buffer; a replay keeps the capture-header cutoff above. A dropped-output recovery blocked by an open load is deferred without consuming retries and resumes when the load finishes, only for the still-active session. Only an actual `mux-full-history` response may clear the live-output mark, and a newer live-write generation keeps it marked. Any upward scroll in a marked non-shell session repairs, including mid-history and at the top (one pull per gesture), still guarded by the 4 s cooldown, 60 s useless-pull latch and downgrade refusal. A gesture that reached the original top still reveals the resulting partial-history notice even if the content restore moves it below row zero; a mid-history repair does not reveal it unless subsequent travel reaches the top. A content anchor captures the first non-empty row at/after the viewport and its next two rows, restores the nearest matching signature at the same viewport offset, and falls back to the nearest first-row-only match or distance from the bottom if unmatched or already near live output. Search is bounded to 2000 rows either side of the expected row (at most 4001 candidates / 12003 line reads), never the entire 50k-row buffer. Ordered, session-scoped travel during replay is then applied with per-move clamping; a switched-to tab never donates travel. On touch devices a floating **Reload history** button offers the same forced, content-anchored recovery while scrolled up in a marked non-shell session, never while tiles own the terminal or another pull is running. `_syncHistoryReloadButton()` alone owns its visibility; its overlay/44px touch-target rules live in the unconditional stylesheet so wide touch viewports do not resize the terminal. The trade-off remains synchronous server `capture-pane`: about 0.3 s at 100k lines, blocking the event loop, not a cheap automatic per-output repair. Tests: `test/shell-scroll-history-pull.test.ts`, `test/history-gap-repair.browser.test.ts`. **The partial-history notice is lazy and pane-gated** (`computeHistoryTruncationNotice()` in constants.js, `_renderHistoryTruncationBanner()` / `_setHistoryNoticeRevealed()` in app.js). `truncated` on a terminal response measures the server's BYTE stream, which is not what `full=1` can return: for a pane with no tmux scrollback (fullscreen claude starts in the alternate screen and never writes to the main grid, so `#{history_size}` is 0) the bytes a tail cut drops are old repaint frames. Measured on prod 2026-10-10, every claude pane: the tab-switch tail cut a 1.2 to 6.2 MB stream to 1 MiB, the local scrollback that tail replays into is repeats of the same frames (one pane: 450 non-blank rows, 44 unique, one row 33 times), and `full=1` returned 1 to 5 KB, so **Load full history** could only end in the downgrade refusal while the banner promised "4.8 MB more". The capture therefore reads `#{history_size}` in the SAME `display-message` as the cursor (no extra tmux call), the route returns it as `paneHistoryLines` (absent when the body is not a capture, and for a remote SSH session, whose local pane hosts the remote tmux client and always reports 0 while `full=1` reads the remote history), and a reported 0 hides the notice in every state; a positive count replaces the byte gap in the message. ⚠️ Key the notice decision on `history_size`, never on `alternate_on`: a shell running `less` is in the alternate screen with its whole history still retained (measured, 99,972 rows) and `full=1` returns all of it. The one place `alternate_on` decides is a shell's AUTOMATIC load (`alt=recording`, see Full-scrollback replay): there the question is whether the capture holds the scrollback a nested tmux client keeps in its byte recording, not whether a pull can return more. The notice is also LAZY: it appears only after a wheel/touch gesture reaches the top of the browser buffer and the pull that gesture started has settled (`_maybeLoadMoreHistoryOnScroll`), goes away when a downward gesture is back at live output or the tab switches (`selectSession` nulls `_historyNoticeRevealedFor` before repainting), and its × is sticky per session until reload (`_historyNoticeDismissed`). Tests: `test/history-truncation-notice.test.ts`, `test/history-notice-reveal.test.ts`. diff --git a/src/web/public/app.js b/src/web/public/app.js index 1f166e87..a11230c8 100644 --- a/src/web/public/app.js +++ b/src/web/public/app.js @@ -801,12 +801,12 @@ class CodemanApp { // the small `full=1` capture instead of the 1 MiB byte tail: see // _notePaneHistory and selectSession. this._paneHistoryLines = new Map(); // Map<sessionId, number> - // Cooldown per session for the scroll-to-top "load more history" re-pull. + // Per-session cooldown for upward-scroll history repair / top-of-buffer pulls. this._fullHistoryRepullAt = new Map(); // Map<sessionId, timestamp> this._fullHistoryRepullInFlight = false; this._liveOutputSinceFullPull = new Set(); // Set<sessionId> this._liveOutputGen = new Map(); // Map<sessionId, number> - this._earlyReplayTravel = null; // number[] while an early (#814) replay runs + this._earlyReplayTravel = null; // { sessionId, moves: number[] } during a content-anchored replay // Sessions whose last re-pull came back THINNER than the live buffer (a // repaint-mode CLI pane, where tmux keeps no history of its own). The pull is // refused for those and retried far more slowly — see _maybeRefetchFullHistory. @@ -2599,13 +2599,31 @@ class CodemanApp { * @param {number} [queuedBytes] - render-queue bytes at the drop, for the crash trail */ _scheduleDroppedOutputRecovery(sessionId, attempt = 0, queuedBytes) { - if (!sessionId || this._clientDropRecoveryTimer) return; + if (!sessionId) return; // Nothing of the main terminal's to recover while the tile grid owns it. if (this._tilesOwnTerminal?.()) return; + // A slow capture owns the live-output gate. Keep the recovery owed until + // it releases instead of spending every retry against the same open load. + if (this._isLoadingBuffer) { + if (sessionId === this.activeSessionId) { + if (this._pendingDroppedOutputRecovery !== sessionId && Number.isFinite(queuedBytes)) { + _crashDiag.log(`TERMINAL DROP: ${(queuedBytes / 1024).toFixed(0)}KB queued (recovery deferred)`); + } + this._pendingDroppedOutputRecovery = sessionId; + } + return; + } + if (this._clientDropRecoveryTimer) return; // Behind the debounce guard: one line per window, not per dropped frame. if (Number.isFinite(queuedBytes)) _crashDiag.log(`TERMINAL DROP: ${(queuedBytes / 1024).toFixed(0)}KB queued`); this._clientDropRecoveryTimer = setTimeout(async () => { this._clientDropRecoveryTimer = null; + // A load may have opened after this timer was armed. Defer without + // advancing the attempt; _finishBufferLoad resumes only the active tab. + if (this._isLoadingBuffer) { + if (sessionId === this.activeSessionId) this._pendingDroppedOutputRecovery = sessionId; + return; + } let repainted = false; let timedOut = false; try { @@ -9596,8 +9614,8 @@ class CodemanApp { } /** - * "Load more history": re-pull the whole tmux scrollback when the user scrolls up - * while already at the top of what the browser has. + * Re-pull tmux history at the top, or on any upward scroll in a non-shell + * session marked by live output since its last mux-full-history replay. * * xterm's buffer is only ever a WINDOW onto tmux's real history, and two things * shrink it. tmux repaints the pane rectangle instead of emitting linefeeds @@ -9608,9 +9626,9 @@ class CodemanApp { * everything (history-limit 100k by default), so the fix is to go ask for it with * the same `?full=1` capture a page reload uses (issue #205). * - * On demand rather than automatic because that capture is unbounded-ish work: at - * the default history limit it can be megabytes, which is fine to pay when the - * user is explicitly reaching for history and not fine on every tab switch. + * Gesture-triggered and cooldown/latch guarded: a synchronous capture can cost + * about 0.3 s at 100k lines and blocks the server event loop. Content anchors + * hold the reader's place even when new history fills a gap below them. * * NEVER a downgrade: for a repaint-mode CLI pane tmux keeps no history of its * own, so the capture can be THINNER than what xterm already holds and the @@ -9653,14 +9671,15 @@ class CodemanApp { if (!force && now - (this._fullHistoryRepullAt.get(sessionId) || 0) < cooldown) return; this._fullHistoryRepullAt.set(sessionId, now); this._fullHistoryRepullInFlight = true; + const loadOwner = this._beginBufferLoad(); + let replayed = false; // The session-id check below cannot see a tab switch that came BACK during // the fetch (A -> B -> A): the id matches again while `selectSession` is // replaying its own capture, and the reset below would land in the middle // of that write. The select generation moves on every switch, so it can. const selectGen = this._selectGeneration; - // Sampled BEFORE the fetch: this path does not gate live output while the - // capture downloads, so output flushed after tmux captured would otherwise - // be overwritten by the replay and still count as covered by it (#814). + // Queued output replayed after this load may mark the session again. Never + // clear that newer generation along with the capture's original mark. const liveOutputGen = this._liveOutputGen?.get(sessionId) || 0; try { const requestStartedAt = performance.now(); @@ -9757,10 +9776,9 @@ class CodemanApp { this._fullHistoryRepullUseless?.delete(sessionId); const rowsBefore = this.terminal.buffer.active.length; const replayStartedAt = performance.now(); - const rowsFromBottom = this.terminal.buffer.active.baseY - this.terminal.buffer.active.viewportY; - // Ordered, not summed: each move clamps at the buffer edge as it would - // have live, so a reversal after hitting the bottom is not cancelled out. - if (anchor === 'bottom') this._earlyReplayTravel = []; + const viewportAnchor = anchor === 'content' ? this._captureViewportAnchor() : null; + // Ordered, not summed: each move clamps at the buffer edge as it would live. + if (anchor === 'content') this._earlyReplayTravel = { sessionId, moves: [] }; this._resetTerminalForReplay(); const { parsedAt, @@ -9769,12 +9787,13 @@ class CodemanApp { } = await this.chunkedTerminalWrite( buffer, TERMINAL_CHUNK_SIZE, - sessionId, + loadOwner, this._bufferLoadFinishOpts(payload, headersReceivedAt) ); + replayed = true; // chunkedTerminalWrite finished this load with the capture cutoff. timing.resetAndParseMs = parsedAt - replayStartedAt; if (!completed || this.activeSessionId !== sessionId || selectGen !== this._selectGeneration) return; - if ((this._liveOutputGen?.get(sessionId) || 0) === liveOutputGen) { + if (payload.source === 'mux-full-history' && (this._liveOutputGen?.get(sessionId) || 0) === liveOutputGen) { this._liveOutputSinceFullPull?.delete(sessionId); } // Keep shell tab restores bounded too. A user-triggered full-history pull @@ -9789,14 +9808,12 @@ class CodemanApp { // UPWARD, so what used to be row 0 (what they were looking at) is now `delta` // rows down; scrolling there reveals the recovered history above it instead // of teleporting them to the bottom the way a normal buffer load does. - if (anchor === 'bottom') { - // Recover the tmux repaint gap above the live screen without a jump (#814). + if (anchor === 'content') { const baseY = this.terminal.buffer.active.baseY; const clamp = (row) => Math.max(0, Math.min(baseY, row)); - let row = clamp(baseY - rowsFromBottom); - for (const move of this._earlyReplayTravel) row = clamp(row + move); + let row = this._restoreViewportAnchor(viewportAnchor); + for (const move of this._earlyReplayTravel.moves) row = clamp(row + move); this.terminal.scrollToLine(row); - this._earlyReplayTravel = null; } else { const delta = parsedBufferLength - rowsBefore; if (delta > 0) this.terminal.scrollToLine(delta); @@ -9817,8 +9834,10 @@ class CodemanApp { } catch { // Transient (offline, 5xx) — the next scroll-up past the cooldown retries. } finally { - if (anchor === 'bottom') this._earlyReplayTravel = null; + if (!replayed) this._finishBufferLoad(loadOwner, { flushQueued: true, since: 0 }); + if (anchor === 'content') this._earlyReplayTravel = null; this._fullHistoryRepullInFlight = false; + this._syncHistoryReloadButton?.(); } } @@ -10074,6 +10093,7 @@ class CodemanApp { this.activeSessionId = sessionId; this._activateFileBrowserSession?.(sessionId); if (typeof CjkInput !== 'undefined') CjkInput.restoreDraft?.(sessionId); + this._syncHistoryReloadButton?.(); // A keyboard row hold belongs to the session it was taken for: release it here // if this one resizes instead (the geometry work below then fits it). this._reconcileKeyboardHold?.({ resize: false }); @@ -10459,7 +10479,7 @@ class CodemanApp { this._clearTerminalLoadState(sessionId, selectGen); return; } - if (fullHistoryReplay && completed && (this._liveOutputGen?.get(sessionId) || 0) === liveOutputGen) { + if (fullHistoryReplay && data.source === 'mux-full-history' && completed && (this._liveOutputGen?.get(sessionId) || 0) === liveOutputGen) { this._liveOutputSinceFullPull?.delete(sessionId); } // Ensure terminal is scrolled to bottom after buffer load diff --git a/src/web/public/index.html b/src/web/public/index.html index 0660574f..b2c7ec46 100644 --- a/src/web/public/index.html +++ b/src/web/public/index.html @@ -478,6 +478,7 @@ scrolled away with the output it described and could not be acted on. Populated by app.js _renderHistoryTruncationBanner(). --> <div class="history-trunc-bar" id="historyTruncationBar" role="status" aria-live="polite" hidden></div> + <button id="historyReloadBtn" type="button" class="history-reload-btn" aria-label="Reload history" hidden>↻ Reload history</button> <div class="terminal-container" id="terminalContainer"></div> <textarea id="cjkInput" rows="1" placeholder="CJK input (Enter = send, Esc = clear)" maxlength="65536" aria-label="CJK IME input field" diff --git a/src/web/public/styles.css b/src/web/public/styles.css index 8a08c4a9..6da7d9de 100644 --- a/src/web/public/styles.css +++ b/src/web/public/styles.css @@ -4401,6 +4401,26 @@ html[data-tab-logos='off'] .home-sessions-harness { position: relative; } +/* Touch-only control; _syncHistoryReloadButton owns its hidden state. */ +.history-reload-btn { + position: absolute; + top: 0.5rem; + right: 0.5rem; + z-index: 20; + min-width: 44px; + min-height: 44px; + padding: 0.5rem 0.75rem; + border: 1px solid var(--border); + border-radius: 6px; + background: var(--bg-card); + color: var(--text); + touch-action: manipulation; +} + +.history-reload-btn:disabled { + opacity: 0.65; +} + /* Partial-history banner (#258). OVERLAY, not a flex child, on purpose: FitAddon derives rows/cols from the terminal parent's computed height, so a banner that occupied real layout diff --git a/src/web/public/terminal-ui.js b/src/web/public/terminal-ui.js index 17c17403..74bdb175 100644 --- a/src/web/public/terminal-ui.js +++ b/src/web/public/terminal-ui.js @@ -1061,6 +1061,7 @@ Object.assign(CodemanApp.prototype, { typeof PredictiveEchoOverlay !== 'undefined' ? new PredictiveEchoOverlay(this.terminal) : null; this._predictiveEcho?.setPredictWhen((terminal) => window.CodemanTerminalInput.isCodexComposerRow(terminal)); if (MobileDetection.isTouchDevice()) { + this.terminal.onScroll(() => this._syncHistoryReloadButton()); this.terminal.onCursorMove(() => this._syncMobileHelperTextareaToCursor()); this.terminal.onRender(() => this._syncMobileHelperTextareaToCursor()); // Keep the live content above the keyboard while the rows are held. @@ -4010,6 +4011,80 @@ Object.assign(CodemanApp.prototype, { return buffer.viewportY >= buffer.baseY - 2; }, + /** Capture the first readable row and its neighbours without copying the buffer. */ + _captureViewportAnchor() { + const buffer = this.terminal.buffer.active; + const { viewportY, baseY } = buffer; + let row = viewportY; + while (row < buffer.length && !buffer.getLine(row)?.translateToString(true).trim()) row++; + return { + viewportY, + rowsFromBottom: baseY - viewportY, + offset: row - viewportY, + signature: Array.from({ length: 3 }, (_, i) => buffer.getLine(row + i)?.translateToString(true).trim() || ''), + }; + }, + + /** Restore the closest matching content, falling back to distance from live output. */ + _restoreViewportAnchor(anchor) { + const buffer = this.terminal.buffer.active; + const clamp = (row) => Math.max(0, Math.min(buffer.baseY, row)); + const fallback = clamp(buffer.baseY - anchor.rowsFromBottom); + let target = fallback; + if (anchor.rowsFromBottom > 2 && anchor.signature[0]) { + const expected = Math.max(0, Math.min(buffer.length - 1, buffer.baseY - anchor.rowsFromBottom + anchor.offset)); + const text = (row) => buffer.getLine(row)?.translateToString(true).trim() || ''; + let firstRowMatch = null; + let exactMatch = null; + // Scan at most 2000 rows either side (4001 candidates / 12003 line reads). + // Nearest first: stop at the first exact signature, otherwise use the + // nearest first-row match within budget rather than scanning 50k rows. + for (let distance = 0; distance <= Math.min(2000, buffer.length - 1); distance++) { + const left = expected - distance; + const right = expected + distance; + for (let side = 0; side < (distance === 0 ? 1 : 2); side++) { + const row = side === 0 ? left : right; + if (row < 0 || row >= buffer.length || text(row) !== anchor.signature[0]) continue; + if (firstRowMatch === null) firstRowMatch = row; + if (text(row + 1) === anchor.signature[1] && text(row + 2) === anchor.signature[2]) { + exactMatch = row; + break; + } + } + if (exactMatch !== null) break; + } + const match = exactMatch ?? firstRowMatch; + if (match !== null) target = clamp(match - anchor.offset); + } + this.terminal.scrollToLine(target); + return target; + }, + + /** Sole owner of the touch-only history reload control's visibility. */ + _syncHistoryReloadButton() { + // Touch capability does not change at runtime and desktop never shows the + // control, so non-touch pages skip the DOM work entirely. + const touch = typeof MobileDetection !== 'undefined' && MobileDetection.isTouchDevice(); + if (!touch) return; + const button = document.getElementById('historyReloadBtn'); + if (!button) return; + const sessionId = this.activeSessionId; + const session = this.sessions.get(sessionId); + const visible = !!(touch && session && session.mode !== 'shell' && + !this.isTerminalAtBottom() && this._liveOutputSinceFullPull?.has(sessionId) && + !this._tilesOwnTerminal?.() && !this._fullHistoryRepullInFlight); + if (button.hidden === visible) button.hidden = !visible; + if (this._fullHistoryRepullInFlight) return; + button.disabled = false; + button.textContent = '↻ Reload history'; + button.onclick = () => { + button.disabled = true; + button.textContent = 'Loading…'; + return Promise.resolve(this._maybeRefetchFullHistory({ force: true, anchor: 'content' })) + .finally(() => this._syncHistoryReloadButton()); + }; + }, + /** * Re-take the sticky-scroll baseline from where the viewport now sits. * @@ -4054,13 +4129,11 @@ Object.assign(CodemanApp.prototype, { }, /** - * Post-scroll companion to _noteTerminalUserScroll: hitting the TOP of the - * buffer while scrolling up gives the app a chance to pull the rest of tmux's - * scrollback (issue #205, see _maybeRefetchFullHistory). Shell sessions pull a - * bounded window because their captures can be large; their banner button is - * the unbounded path. Must be called AFTER scrollLines(), since the check is on - * the resulting position, and it is deliberately not folded into - * _noteTerminalUserScroll for exactly that reason. + * After scrollLines(), repair on ANY upward gesture in a non-shell session + * marked by live output since its last mux-full-history replay (#814), using + * a content anchor to hold the reader's place. Unmarked sessions still pull + * at the top (#205); shells pull only a bounded window there. The pull owns + * cooldown/latch and downgrade guards. * * It is also what brings up the partial-history notice, and what retires it * once a downward scroll is back at live output (_setHistoryNoticeRevealed). @@ -4068,8 +4141,8 @@ Object.assign(CodemanApp.prototype, { * what the pull left rather than flashing the state it is about to replace. */ _maybeLoadMoreHistoryOnScroll(lines) { - if (Array.isArray(this._earlyReplayTravel)) { - this._earlyReplayTravel.push(lines); + if (this._earlyReplayTravel?.sessionId === this.activeSessionId) { + this._earlyReplayTravel.moves.push(lines); return; } if (lines > 0) { @@ -4078,39 +4151,22 @@ Object.assign(CodemanApp.prototype, { } if (lines === 0) return; const buffer = this.terminal?.buffer?.active; - if (buffer?.viewportY !== 0) { - const sessionId = this.activeSessionId; - // tmux repaint bursts can leave a gap just above live output (#814). - // Called after scrollLines: include this gesture's travel in the bottom check. - if ( - lines < 0 && - sessionId && - this._liveOutputSinceFullPull?.has(sessionId) && - this.sessions.get(sessionId)?.mode !== 'shell' && - buffer?.viewportY >= buffer.baseY - 2 - Math.abs(lines) && - !this._fullHistoryRepullInFlight && - !this._isLoadingBuffer - ) { - Promise.resolve(this._maybeRefetchFullHistory?.({ anchor: 'bottom' })) - .catch(() => {}) - .then(() => { - // Travel during the replay is swallowed above, so a gesture that - // reached the top meanwhile still owes the notice its reveal. - if (this.activeSessionId === sessionId && this.terminal?.buffer?.active?.viewportY === 0) { - this._setHistoryNoticeRevealed?.(sessionId); - } - }); - } - return; - } - // An earlier frame of this gesture already started the pull; its own - // completion reveals the notice, so do not flash the pre-pull state now. - if (this._fullHistoryRepullInFlight || this._isLoadingBuffer) return; + const reachedTop = buffer?.viewportY === 0; const sessionId = this.activeSessionId; - Promise.resolve(this._maybeRefetchFullHistory?.()) + const repair = sessionId && this._liveOutputSinceFullPull?.has(sessionId) && + this.sessions.get(sessionId)?.mode !== 'shell'; + if (!repair && buffer?.viewportY !== 0) return; + // An earlier frame already started a pull and owns the notice reveal. + if (this._fullHistoryRepullInFlight || this._isLoadingBuffer) return; + Promise.resolve(repair + ? this._maybeRefetchFullHistory?.({ anchor: 'content' }) + : this._maybeRefetchFullHistory?.()) .catch(() => {}) .then(() => { - if (sessionId && this.activeSessionId === sessionId) this._setHistoryNoticeRevealed?.(sessionId); + if (sessionId && this.activeSessionId === sessionId && + (reachedTop || this.terminal?.buffer?.active?.viewportY === 0)) { + this._setHistoryNoticeRevealed?.(sessionId); + } }); }, @@ -4735,9 +4791,14 @@ Object.assign(CodemanApp.prototype, { }); // Only live writes can open a new tmux repaint gap; replays cannot (#814). if (writeChunk.length && flushSessionId && !this._isLoadingBuffer) { - (this._liveOutputSinceFullPull ||= new Set()).add(flushSessionId); + const marked = (this._liveOutputSinceFullPull ||= new Set()); + const newlyMarked = !marked.has(flushSessionId); + marked.add(flushSessionId); const generations = (this._liveOutputGen ||= new Map()); generations.set(flushSessionId, (generations.get(flushSessionId) || 0) + 1); + // Visibility only changes here when the mark appears; scrolling is + // covered by the touch-only onScroll hook. + if (newlyMarked) this._syncHistoryReloadButton?.(); } } catch (err) { this._terminalWriteInFlight = false; @@ -5079,6 +5140,11 @@ Object.assign(CodemanApp.prototype, { this.batchTerminalWrite(entry.data); } } + const recoverySession = this._pendingDroppedOutputRecovery; + this._pendingDroppedOutputRecovery = null; + if (recoverySession && recoverySession === this.activeSessionId) { + this._scheduleDroppedOutputRecovery?.(recoverySession); + } return true; }, diff --git a/test/history-gap-repair.browser.test.ts b/test/history-gap-repair.browser.test.ts new file mode 100644 index 00000000..de00fef5 --- /dev/null +++ b/test/history-gap-repair.browser.test.ts @@ -0,0 +1,451 @@ +/** Real xterm + trusted phone gestures recover tmux repaint gaps while reading (#814). */ +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { chromium, type Browser, type BrowserContext, type Page } from 'playwright'; +import type { Terminal } from '@xterm/xterm'; +import { WebServer } from '../src/web/server.js'; + +type Anchor = { signature: string[]; offset: number; viewportY: number; rowsFromBottom: number }; +type HistoryApp = { + terminal: Terminal & { + _core?: { _renderService?: { dimensions?: { css?: { cell?: { height: number } } } } }; + }; + fitAddon: { proposeDimensions(): { cols: number; rows: number } | undefined }; + sessions: Map<string, object>; + activeSessionId: string; + hideWelcome(): void; + _onSessionTerminal(event: { id: string; data: string }): void; + _liveOutputSinceFullPull: Set<string>; + _fullHistoryRepullInFlight: boolean; + _isLoadingBuffer: boolean; + pendingWrites: string[]; + _terminalWriteInFlight: boolean; + _bufferLoadOwner: unknown; + _loadBufferQueue: { data: string; at: number }[] | null; + _selectGeneration: number; + _initGeneration: number; + terminalLoadStates: Map<string, unknown>; + _terminalFontReady: Promise<void>; + _resizeTimeout: number | null; + _lastResizeDims: { cols: number; rows: number } | null; + _syncStickyScrollBaseline(): void; + _captureViewportAnchor(): Anchor; + _syncHistoryReloadButton(): void; +}; +type RepairWindow = Window & { + app: HistoryApp; + repairTest: { pulls: number; anchor: Anchor | null; inject: boolean }; + repairReadiness?: { cols: number; rows: number; frames: number }; +}; + +const SESSION = 'history-repair-browser'; +const MARKER = 'AFTER-CAPTURE-DURING-DOWNLOAD'; +let server: WebServer; +let browser: Browser; +let baseUrl: string; +const pageEvents = new WeakMap<Page, string[]>(); + +async function setupState(page: Page) { + return page.evaluate(() => { + const app = (window as RepairWindow).app; + const buffer = app?.terminal?.buffer.active; + return { + appLoaded: document.body.classList.contains('app-loaded'), + baseY: buffer?.baseY, + length: buffer?.length, + viewportY: buffer?.viewportY, + cols: app?.terminal?.cols, + rows: app?.terminal?.rows, + resizePending: Boolean(app?._resizeTimeout), + lastResizeDims: app?._lastResizeDims, + proposedDims: app?.fitAddon?.proposeDimensions(), + cellHeight: app?.terminal?._core?._renderService?.dimensions?.css?.cell?.height, + pendingWrites: app?.pendingWrites?.length, + terminalWriteInFlight: app?._terminalWriteInFlight, + isLoadingBuffer: app?._isLoadingBuffer, + bufferLoadOwner: app?._bufferLoadOwner, + loadBufferQueue: app?._loadBufferQueue?.length ?? 0, + activeSessionId: app?.activeSessionId, + selectGeneration: app?._selectGeneration, + sessions: app?.sessions ? [...app.sessions.keys()] : [], + initGeneration: app?._initGeneration, + terminalLoadStates: app?.terminalLoadStates ? [...app.terminalLoadStates] : [], + }; + }); +} + +async function failureDetails(page: Page, error: unknown): Promise<Error> { + const setup = await setupState(page).catch(String); + const buffer = await bufferState(page).catch(String); + return new Error(JSON.stringify({ setup, buffer, events: pageEvents.get(page) }), { cause: error }); +} + +beforeAll(async () => { + server = new WebServer(0, false, true); + await server.start(); + baseUrl = `http://localhost:${server.boundPort}`; + browser = await chromium.launch({ headless: true }); +}, 60_000); + +afterAll(async () => { + await browser?.close(); + await server?.stop(); +}, 30_000); + +async function openTerminal( + touch: boolean, + viewport = touch ? { width: 390, height: 640 } : { width: 1280, height: 800 } +): Promise<{ context: BrowserContext; page: Page }> { + const context = await browser.newContext({ + hasTouch: touch, + isMobile: touch, + viewport, + }); + const page = await context.newPage(); + const events: string[] = []; + pageEvents.set(page, events); + page.on('console', (message) => { + events.push(`console.${message.type()}: ${message.text()}`); + if (events.length > 100) events.shift(); + }); + page.on('pageerror', (error) => events.push(`pageerror: ${error.stack || error.message}`)); + try { + await page.goto(baseUrl, { waitUntil: 'domcontentloaded' }); + await page.waitForFunction(() => document.body.classList.contains('app-loaded')); + await page.waitForFunction(() => { + const app = (window as RepairWindow).app; + return app?.terminal && app._initGeneration > 0 && !app._isLoadingBuffer && app.terminalLoadStates.size === 0; + }); + await page.evaluate(async (session) => { + const app = (window as RepairWindow).app; + // A client-only OMP session isolates the rendering path from real CLI/PTYS. + // Opening it changes layout, so finish the real resize path BEFORE seeding. + app.sessions.set(session, { id: session, mode: 'omp', status: 'idle', name: 'History repair' }); + app.activeSessionId = session; + app.hideWelcome(); + await app._terminalFontReady; + await document.fonts.ready; + // Empty xterm can still carry fallback render metrics. Paint a glyph + // before fitting, then clear it before the fixture's numbered output. + const rendered = Promise.withResolvers<void>(); + const listener = app.terminal.onRender(() => { + listener.dispose(); + rendered.resolve(); + }); + app.terminal.write('W'); + await rendered.promise; + const { promise, resolve } = Promise.withResolvers<void>(); + app.terminal.write('\x1bc', resolve); + await promise; + window.dispatchEvent(new Event('resize')); + }, SESSION); + await page.waitForFunction(() => { + const w = window as RepairWindow; + const app = w.app; + const { cols, rows } = app.terminal; + const proposed = app.fitAddon.proposeDimensions(); + const cellHeight = app.terminal._core?._renderService?.dimensions?.css?.cell?.height || 0; + if ( + cellHeight <= 0 || + proposed?.cols !== cols || + proposed?.rows !== rows || + app._resizeTimeout || + app._isLoadingBuffer || + app.terminalLoadStates.size || + app.pendingWrites.length || + app._terminalWriteInFlight || + app._lastResizeDims?.cols !== cols || + app._lastResizeDims?.rows !== rows + ) { + w.repairReadiness = undefined; + return false; + } + // Synchronous rAF polling: require the initial match plus two more frames. + // An async predicate returns a truthy Promise, which Playwright won't retry. + const previous = w.repairReadiness; + const frames = previous?.cols === cols && previous.rows === rows ? previous.frames + 1 : 1; + w.repairReadiness = { cols, rows, frames }; + return frames >= 3; + }); + await page.evaluate( + async ({ session, marker }) => { + const w = window as RepairWindow; + const app = w.app; + // Startup resets and resize clears have already parsed at fitted geometry. + w.repairTest = { pulls: 0, anchor: null, inject: false }; + const captureAnchor = app._captureViewportAnchor.bind(app); + app._captureViewportAnchor = () => { + const anchor = captureAnchor(); + w.repairTest.anchor = anchor; + return anchor; + }; + const realFetch = window.fetch.bind(window); + window.fetch = ((input: RequestInfo | URL, init?: RequestInit) => { + const url = String(typeof input === 'string' ? input : ((input as Request).url ?? input)); + if (!url.includes(`/api/sessions/${session}/terminal`)) return realFetch(input, init); + if (!url.includes('full=1')) throw new Error(`Unexpected history request: ${url}`); + w.repairTest.pulls++; + return Promise.resolve({ + ok: true, + status: 200, + headers: new Headers(), + json: async () => { + // This is after headers and before replay, inside the real load window. + if (w.repairTest.inject) app._onSessionTerminal({ id: session, data: `\r\n${marker}\r\n` }); + const terminalBuffer = + Array.from({ length: 144 }, (_, i) => `NUMBER-${String(i).padStart(3, '0')}`).join('\r\n') + '\r\n'; + return { + success: true, + data: { + terminalBuffer, + source: 'mux-full-history', + paneHistoryLines: 121, + truncated: false, + fullSize: terminalBuffer.length, + retainedBytes: terminalBuffer.length, + }, + }; + }, + }) as unknown as Promise<Response>; + }) as typeof window.fetch; + // All output still enters through the production terminal event path. + app._onSessionTerminal({ + id: session, + data: Array.from({ length: 60 }, (_, i) => `NUMBER-${String(i).padStart(3, '0')}\r\n`).join(''), + }); + await new Promise<void>((resolve) => app.terminal.write('', resolve)); + }, + { session: SESSION, marker: MARKER } + ); + await page.waitForFunction(() => { + const app = (window as RepairWindow).app; + const buffer = app.terminal.buffer.active; + return ( + buffer.length === 61 && + buffer.baseY === 61 - app.terminal.rows && + !app.pendingWrites.length && + !app._terminalWriteInFlight && + Array.from({ length: 60 }, (_, i) => buffer.getLine(i)?.translateToString(true)).every( + (row, i) => row === `NUMBER-${String(i).padStart(3, '0')}` + ) + ); + }); + // The initial 60 lines stand in for the last successful full-history replay. + await page.evaluate((session) => { + const app = (window as RepairWindow).app; + app.terminal.scrollToBottom(); + app._syncStickyScrollBaseline(); + app._liveOutputSinceFullPull.delete(session); + }, SESSION); + } catch (error) { + const state = await setupState(page).catch(String); + await context.close(); + throw new Error(`Terminal setup failed: ${JSON.stringify({ state, events })}`, { cause: error }); + } + return { context, page }; +} + +/** Finger down scrolls history up; cancel at the endpoint to avoid momentum. */ +async function scrollHistoryByTouch(page: Page, distance: number): Promise<void> { + const box = await page.locator('#terminalContainer').boundingBox(); + if (!box) throw new Error('Terminal container is not visible'); + const x = box.x + box.width / 2; + const y = box.y + Math.min(80, box.height / 4); + const cdp = await page.context().newCDPSession(page); + const before = await page.evaluate(() => (window as RepairWindow).app.terminal.buffer.active.viewportY); + try { + await cdp.send('Input.dispatchTouchEvent', { type: 'touchStart', touchPoints: [{ x, y }] }); + await cdp.send('Input.dispatchTouchEvent', { type: 'touchMove', touchPoints: [{ x, y: y + distance }] }); + await page.waitForFunction((previous) => { + const app = (window as RepairWindow).app; + return app.terminal.buffer.active.viewportY !== previous || app._fullHistoryRepullInFlight; + }, before); + // A trusted cancellation ends the drag without xterm/app momentum changing + // the reading position after the gesture or starting another top pull. + await cdp.send('Input.dispatchTouchEvent', { type: 'touchCancel', touchPoints: [] }); + } finally { + await cdp.detach(); + } +} + +async function burst(page: Page): Promise<void> { + await page.evaluate((session) => { + const app = (window as RepairWindow).app; + // tmux scrolls a whole screen and repaints the last 24 rows. The numbered + // rows 60..119 exist only in tmux and are deliberately absent from this stream. + const repaint = Array.from({ length: 24 }, (_, row) => `\x1b[${row + 1};1H\x1b[2KNUMBER-${120 + row}`).join(''); + app._onSessionTerminal({ id: session, data: `\x1b[24S${repaint}` }); + }, SESSION); + await page.waitForFunction((session) => (window as RepairWindow).app._liveOutputSinceFullPull.has(session), SESSION); +} + +async function bufferState(page: Page) { + return page.evaluate((marker) => { + const w = window as RepairWindow; + const buffer = w.app.terminal.buffer.active; + const rows = Array.from( + { length: buffer.length }, + (_, i) => buffer.getLine(i)?.translateToString(true).trim() || '' + ); + const anchor = w.repairTest.anchor; + return { + numbers: rows.filter((row) => /^NUMBER-\d+$/.test(row)), + markerHits: rows.filter((row) => row.includes(marker)).length, + anchorOffset: anchor ? rows.indexOf(anchor.signature[0]) - buffer.viewportY : null, + expectedOffset: anchor?.offset, + pulls: w.repairTest.pulls, + viewportY: buffer.viewportY, + baseY: buffer.baseY, + session: w.app.activeSessionId, + length: buffer.length, + pendingWrites: w.app.pendingWrites.length, + terminalWriteInFlight: w.app._terminalWriteInFlight, + bufferLoadOwner: w.app._bufferLoadOwner, + loadBufferQueue: w.app._loadBufferQueue, + selectGeneration: w.app._selectGeneration, + initGeneration: w.app._initGeneration, + sessions: [...w.app.sessions.keys()], + marked: w.app._liveOutputSinceFullPull.has(w.app.activeSessionId), + loading: w.app._isLoadingBuffer, + inFlight: w.app._fullHistoryRepullInFlight, + }; + }, MARKER); +} + +async function waitForRepair(page: Page): Promise<void> { + await page.waitForFunction(() => { + const w = window as RepairWindow; + return ( + w.repairTest.pulls === 1 && + !w.app._fullHistoryRepullInFlight && + !w.app._isLoadingBuffer && + !w.app.pendingWrites.length && + !w.app._terminalWriteInFlight + ); + }); + // xterm's parse marker is the completion signal for the production flush. + await page.evaluate(async () => { + const app = (window as RepairWindow).app; + await new Promise<void>((resolve) => app.terminal.write('', resolve)); + }); +} + +const allNumbers = Array.from({ length: 144 }, (_, i) => `NUMBER-${String(i).padStart(3, '0')}`); + +describe('history gap repair on phones', () => { + it('repairs from mid-history after a real upward scroll and holds the content anchor', async () => { + const { context, page } = await openTerminal(true); + try { + await scrollHistoryByTouch(page, 100); + const position = await page.evaluate(() => { + const b = (window as RepairWindow).app.terminal.buffer.active; + return { viewportY: b.viewportY, baseY: b.baseY }; + }); + expect(position.viewportY).toBeGreaterThan(0); + expect(position.baseY - position.viewportY).toBeGreaterThan(5); + await burst(page); + expect((await bufferState(page)).numbers).not.toContain('NUMBER-090'); + await scrollHistoryByTouch(page, 40); + await waitForRepair(page); + const state = await bufferState(page); + expect(state.numbers).toEqual(allNumbers); + expect(state.anchorOffset).toBe(state.expectedOffset); + expect(state.pulls).toBe(1); + } catch (error) { + throw await failureDetails(page, error); + } finally { + await context.close(); + } + }, 60_000); + + it('keeps output arriving during the capture download exactly once', async () => { + const { context, page } = await openTerminal(true); + try { + await scrollHistoryByTouch(page, 100); + await burst(page); + await page.evaluate(() => { + (window as RepairWindow).repairTest.inject = true; + }); + await scrollHistoryByTouch(page, 40); + await waitForRepair(page); + const state = await bufferState(page); + const detail = JSON.stringify({ state, events: pageEvents.get(page) }); + expect(state.markerHits, detail).toBe(1); + expect(state.numbers, detail).toEqual(allNumbers); + } catch (error) { + throw await failureDetails(page, error); + } finally { + await context.close(); + } + }, 60_000); + + it('offers a touch reload while reading and tapping it recovers the missing rows', async () => { + const { context, page } = await openTerminal(true); + try { + await scrollHistoryByTouch(page, 100); + await burst(page); + const button = page.getByRole('button', { name: 'Reload history' }); + await button.waitFor({ state: 'visible' }); + const box = await button.boundingBox(); + expect(box!.height).toBeGreaterThanOrEqual(44); + expect(box!.width).toBeGreaterThanOrEqual(44); + await button.tap(); + await waitForRepair(page); + const state = await bufferState(page); + expect(state.numbers).toEqual(allNumbers); + expect(state.anchorOffset).toBe(state.expectedOffset); + expect(await button.isVisible()).toBe(false); + } catch (error) { + throw await failureDetails(page, error); + } finally { + await context.close(); + } + }, 60_000); + + it('floats a 44px reload control on wide touch viewports without resizing the terminal', async () => { + const { context, page } = await openTerminal(true, { width: 1280, height: 800 }); + try { + await page.evaluate(() => { + (window as RepairWindow).app.terminal.scrollToLine(10); + }); + const dimensions = () => + page.evaluate(() => { + const terminal = (window as RepairWindow).app.terminal; + const box = document.getElementById('terminalContainer')!.getBoundingClientRect(); + return { width: box.width, height: box.height, cols: terminal.cols, rows: terminal.rows }; + }); + const before = await dimensions(); + expect(await page.locator('#historyReloadBtn').isVisible()).toBe(false); + await burst(page); + const button = page.getByRole('button', { name: 'Reload history' }); + await button.waitFor({ state: 'visible' }); + expect(await button.evaluate((element) => getComputedStyle(element).position)).toBe('absolute'); + const box = await button.boundingBox(); + expect(box!.height).toBeGreaterThanOrEqual(44); + expect(box!.width).toBeGreaterThanOrEqual(44); + expect(await dimensions()).toEqual(before); + } catch (error) { + throw await failureDetails(page, error); + } finally { + await context.close(); + } + }, 60_000); + + it('never shows the reload control in a non-touch context', async () => { + const { context, page } = await openTerminal(false); + try { + await page.evaluate(() => { + (window as RepairWindow).app.terminal.scrollToLine(10); + }); + await burst(page); + await page.evaluate(() => { + (window as RepairWindow).app._syncHistoryReloadButton(); + }); + expect(await page.locator('#historyReloadBtn').isVisible()).toBe(false); + expect((await bufferState(page)).pulls).toBe(0); + } catch (error) { + throw await failureDetails(page, error); + } finally { + await context.close(); + } + }, 60_000); +}); diff --git a/test/history-notice-reveal.test.ts b/test/history-notice-reveal.test.ts index 435a3954..6b749f63 100644 --- a/test/history-notice-reveal.test.ts +++ b/test/history-notice-reveal.test.ts @@ -121,6 +121,8 @@ function makeApp() { let resolvePull: (() => void) | null = null; const app = { activeSessionId: 's1' as string | null, + sessions: new Map([['s1', { mode: 'omp' }]]), + _liveOutputSinceFullPull: new Set<string>(), terminal: { buffer: { active: buffer } }, // Each gesture's pull is held open until the test settles it. _maybeRefetchFullHistory: vi.fn( @@ -184,6 +186,29 @@ describe('partial-history notice: lazy reveal', () => { expect(loadButton(bar)?.textContent).toBe('Load full history'); }); + it.each([ + { viewportY: 0, revealed: true }, + { viewportY: 200, revealed: false }, + ])( + 'retains the initiating top state through a marked repair from row $viewportY', + async ({ viewportY, revealed }) => { + const { app, bar, buffer } = makeApp(); + app._setHistoryTruncation('s1', TAIL); + app._liveOutputSinceFullPull.add('s1'); + app._maybeRefetchFullHistory.mockImplementation(async () => { + app._setHistoryTruncation('s1', { ...TAIL, source: 'mux-full-history' }); + buffer.viewportY = 100; // The content anchor restored the old top below recovered rows. + }); + buffer.viewportY = viewportY; + app._maybeLoadMoreHistoryOnScroll(-5); + for (let i = 0; i < 5; i++) await Promise.resolve(); + expect(app._maybeRefetchFullHistory).toHaveBeenCalledOnce(); + expect(app._maybeRefetchFullHistory).toHaveBeenCalledWith({ anchor: 'content' }); + expect(bar.hidden).toBe(!revealed); + if (revealed) expect(loadButton(bar)?.textContent).toBe('Load full history'); + } + ); + it('a later frame of the same gesture does not flash the pre-pull state while the pull runs', async () => { const { app, bar, buffer } = makeApp(); app._setHistoryTruncation('s1', TAIL); diff --git a/test/shell-scroll-history-pull.test.ts b/test/shell-scroll-history-pull.test.ts index 19c5d1f8..85d9fdd0 100644 --- a/test/shell-scroll-history-pull.test.ts +++ b/test/shell-scroll-history-pull.test.ts @@ -49,7 +49,7 @@ function methodSource(source: string, method: string): string { } /** Real terminal-ui.js mixin, for `_estimateReplayRows` / `_replayWouldShrinkBuffer`. */ -function loadTerminalMixin(): Record<string, unknown> { +function loadTerminalMixin(globals: Record<string, unknown> = {}): Record<string, unknown> { const source = readFileSync(resolve(PUBLIC, 'terminal-ui.js'), 'utf8'); const FakeCodemanApp = function () {} as unknown as { prototype: Record<string, unknown> }; const context = vm.createContext({ @@ -63,6 +63,7 @@ function loadTerminalMixin(): Record<string, unknown> { CodemanApp: FakeCodemanApp, window: { addEventListener: vi.fn(), removeEventListener: vi.fn() }, document: { addEventListener: vi.fn() }, + ...globals, }); vm.runInContext(source, context); return FakeCodemanApp.prototype; @@ -75,6 +76,20 @@ function loadRefetch(): (this: unknown, opts?: { force?: boolean; anchor?: strin return vm.runInContext(`({ ${body} })._maybeRefetchFullHistory`, context); } +function loadAppMethod(name: string, globals: Record<string, unknown> = {}): Function { + const source = readFileSync(resolve(PUBLIC, 'app.js'), 'utf8'); + return vm.runInContext( + `({ ${methodSource(source, name)} }).${name}`, + vm.createContext({ + performance, + TERMINAL_TAIL_SIZE, + TERMINAL_CHUNK_SIZE: 32 * 1024, + _crashDiag: { log: vi.fn() }, + ...globals, + }) + ); +} + /** The REAL `_setHistoryTruncation`, so the banner state a pull leaves behind is what production would hold. */ function loadSetHistoryTruncation(): (this: unknown, sessionId: string, payload?: Record<string, unknown>) => void { const app = readFileSync(resolve(PUBLIC, 'app.js'), 'utf8'); @@ -125,6 +140,7 @@ function makeApp( _selectGeneration: 7, _fullHistoryRepullInFlight: false, _isLoadingBuffer: false, + _loadBufferQueue: null as { at: number; data: string }[] | null, _fullHistoryRepullAt: new Map<string, number>(), _fullHistoryRepullUseless: new Set<string>(), _paneHistoryLines: new Map<string, number>(), @@ -134,12 +150,25 @@ function makeApp( rows: 30, // xterm's scrollback option; 0 leaves the browser-cap check out of a test. options: { scrollback }, - buffer: { active: { length: bufferRows, baseY: 0, viewportY: 0 } }, scrollToLine: vi.fn(), + buffer: { active: { length: bufferRows, baseY: 0, viewportY: 0, getLine: (_row: number) => undefined } }, scrollToTop: vi.fn(), }, _estimateReplayRows: mixin._estimateReplayRows, _replayWouldShrinkBuffer: mixin._replayWouldShrinkBuffer, + _beginBufferLoad: mixin._beginBufferLoad, + _finishBufferLoad: vi.fn(function (this: unknown, owner: string, opts?: object) { + return (mixin._finishBufferLoad as Function).call(this, owner, opts); + }), + batchTerminalWrite: vi.fn(function (this: unknown, data: string) { + return (mixin.batchTerminalWrite as Function).call(this, data); + }), + _captureViewportAnchor: mixin._captureViewportAnchor, + _restoreViewportAnchor: mixin._restoreViewportAnchor, + pendingWrites: [] as string[], + _scheduleTerminalWriteFlush: vi.fn(), + isTerminalAtBottom: () => true, + _scheduleDroppedOutputRecovery: vi.fn(), _fetchTerminalCapture: vi.fn(async (url: string) => { urls.push(url); return { @@ -159,8 +188,11 @@ function makeApp( setHistoryTruncation.call(app, sessionId, p); }), _resetTerminalForReplay: vi.fn(), - _bufferLoadFinishOpts: vi.fn(() => ({})), - chunkedTerminalWrite: vi.fn(async () => ({ parsedAt: performance.now(), bufferLength: 400, completed: true })), + _bufferLoadFinishOpts: loadAppMethod('_bufferLoadFinishOpts'), + chunkedTerminalWrite: vi.fn(async (_buffer?: string, _size?: number, owner?: string, opts?: object) => { + (mixin._finishBufferLoad as Function).call(app, owner, opts); + return { parsedAt: performance.now(), bufferLength: 400, completed: true }; + }), _syncStickyScrollBaseline: vi.fn(), }; return { app, urls }; @@ -262,8 +294,7 @@ describe('early full-history recovery above live output (#814)', () => { const app = Object.assign(base, { _liveOutputSinceFullPull: new Set<string>(), _liveOutputGen: new Map<string, number>(), - _earlyReplayTravel: null as number[] | null, - pendingWrites: [] as string[], + _earlyReplayTravel: null as { sessionId: string; moves: number[] } | null, _wasAtBottomBeforeWrite: false, _scheduleTerminalWriteFlush: vi.fn(), _restoreTerminalViewport: vi.fn(), @@ -285,10 +316,11 @@ describe('early full-history recovery above live output (#814)', () => { app.terminal.scrollToLine.mockImplementation((row: number) => { active.viewportY = row; }); - app.chunkedTerminalWrite.mockImplementation(async () => { + app.chunkedTerminalWrite.mockImplementation(async (_buffer, _size, owner, opts) => { active.baseY = 370; active.viewportY = 370; active.length = 400; + (mixin._finishBufferLoad as Function).call(app, owner, opts); return { parsedAt: performance.now(), bufferLength: 400, completed: true }; }); const liveOutput = () => { @@ -305,14 +337,12 @@ describe('early full-history recovery above live output (#814)', () => { const replay = app.chunkedTerminalWrite.getMockImplementation()!; const { promise: gate, resolve: release } = Promise.withResolvers<void>(); const { promise: ready, resolve: started } = Promise.withResolvers<void>(); - app.chunkedTerminalWrite.mockImplementationOnce(async () => { - app._isLoadingBuffer = true; + app.chunkedTerminalWrite.mockImplementationOnce(async (...args) => { active.baseY = 0; active.viewportY = 0; started(); await gate; - const result = await replay(); - app._isLoadingBuffer = false; + const result = await replay(...args); beforeComplete(); return result; }); @@ -326,6 +356,12 @@ describe('early full-history recovery above live output (#814)', () => { liveOutput(); await scroll(-5); expect(urls).toEqual(['/api/sessions/s1/terminal?full=1']); + expect(app.chunkedTerminalWrite).toHaveBeenCalledWith( + expect.any(String), + 32 * 1024, + expect.stringMatching(/^buffer-/), + expect.objectContaining({ flushQueued: true }) + ); expect(active.viewportY).toBe(365); expect(active.baseY - active.viewportY).toBe(5); expect(app._liveOutputSinceFullPull.has('s1')).toBe(false); @@ -359,20 +395,31 @@ describe('early full-history recovery above live output (#814)', () => { expect(app._earlyReplayTravel).toBeNull(); }); - it('keeps a session dirty when live output lands while the capture is still downloading', async () => { + it('queues download-time output and replays it through batchTerminalWrite after the capture', async () => { const { app, urls, liveOutput, scroll } = makeScrollApp(); liveOutput(); const fetchCapture = app._fetchTerminalCapture.getMockImplementation()!; + const { promise, resolve: release } = Promise.withResolvers<void>(); app._fetchTerminalCapture.mockImplementationOnce(async (url: string) => { + expect(app._isLoadingBuffer).toBe(true); const capture = await fetchCapture(url); - // tmux has captured; this output is newer than the capture the replay writes. - liveOutput(); + await promise; return capture; }); - await scroll(-5); + const pull = scroll(-5); + loadAppMethod('_onSessionTerminal').call(app, { id: 's1', data: 'download-time output' }); + expect(app._loadBufferQueue).toEqual([expect.objectContaining({ data: 'download-time output' })]); + release(); + await pull; expect(urls).toHaveLength(1); + expect(app.batchTerminalWrite).toHaveBeenCalledWith('download-time output'); + expect(app.pendingWrites).toContain('download-time output'); + expect(app._isLoadingBuffer).toBe(false); + // Flushing the replayed queue marks the session again. + (mixin.flushPendingWrites as Function).call(app); expect(app._liveOutputSinceFullPull.has('s1')).toBe(true); }); + it('keeps live output flushed before the final restore dirty for the next early pull', async () => { const { app, active, urls, liveOutput, scroll, pauseReplay } = makeScrollApp(); liveOutput(); @@ -417,14 +464,17 @@ describe('early full-history recovery above live output (#814)', () => { expect(app._liveOutputSinceFullPull.size).toBe(0); }); - it('does not pull early for downward travel or while already reading older rows', async () => { - const { active, urls, liveOutput, scroll } = makeScrollApp(); + it('repairs while already reading mid-history, but never on downward travel', async () => { + const { app, active, urls, liveOutput, scroll } = makeScrollApp(); liveOutput(); active.viewportY = 50; await scroll(-5); - active.viewportY = 95; + expect(urls).toHaveLength(1); + expect(app._maybeRefetchFullHistory).toHaveBeenCalledWith({ anchor: 'content' }); + app._fullHistoryRepullAt.clear(); + liveOutput(); await scroll(3); - expect(urls).toEqual([]); + expect(urls).toHaveLength(1); }); it.each(['_isLoadingBuffer', '_fullHistoryRepullInFlight'] as const)('respects the %s guard', async (guard) => { @@ -450,6 +500,144 @@ describe('early full-history recovery above live output (#814)', () => { expect(app._liveOutputSinceFullPull.has('s1')).toBe(true); expect(app._fullHistoryRepullUseless.has('s1')).toBe(true); }); + + it.each(['empty', 'tab-switch', 'downgrade', 'bounded-shell', 'rejection'])( + 'flushes download-time output on the %s non-replay path', + async (exit) => { + const { app } = makeApp(exit === 'bounded-shell' ? 'shell' : 'omp', { + bufferRows: 200, + capture: lines(400), + }); + const { promise, resolve: release } = Promise.withResolvers<void>(); + app._fetchTerminalCapture.mockImplementationOnce(async () => { + await promise; + if (exit === 'rejection') throw new Error('offline'); + if (exit === 'tab-switch') app._selectGeneration++; + return { + headersAt: performance.now(), + headers: { get: () => '' }, + json: { data: { terminalBuffer: exit === 'empty' ? '' : lines(10), source: 'mux-full-history' } }, + }; + }); + const pull = refetch.call(app); + expect(app._isLoadingBuffer).toBe(true); + loadAppMethod('_onSessionTerminal').call(app, { id: 's1', data: 'queued while fetching' }); + release(); + await pull; + expect(app.chunkedTerminalWrite).not.toHaveBeenCalled(); + expect(app._finishBufferLoad).toHaveBeenCalledOnce(); + expect(app._finishBufferLoad).toHaveBeenCalledWith(expect.any(String), { flushQueued: true, since: 0 }); + expect(app.pendingWrites).toContain('queued while fetching'); + expect(app._isLoadingBuffer).toBe(false); + } + ); + + it('counts download-time output toward the 128 KiB dropped-output recovery cap', async () => { + const { app } = makeApp('omp', { bufferRows: 30, capture: lines(400) }); + const { promise, resolve: release } = Promise.withResolvers<void>(); + app._fetchTerminalCapture.mockImplementationOnce(async () => { + await promise; + return { + headersAt: performance.now(), + headers: { get: () => '' }, + json: { data: { terminalBuffer: '', source: 'history' } }, + }; + }); + const pull = refetch.call(app); + const onTerminal = loadAppMethod('_onSessionTerminal'); + onTerminal.call(app, { id: 's1', data: 'x'.repeat(70_000) }); + onTerminal.call(app, { id: 's1', data: 'y'.repeat(70_000) }); + expect(app._scheduleDroppedOutputRecovery).toHaveBeenCalledWith('s1', 0, 70_000); + expect(app._loadBufferQueue).toHaveLength(1); + release(); + await pull; + }); + + it.each([false, true])( + 'defers real dropped-output recovery through a slow pull (timer already armed: %s)', + async (armed) => { + vi.useFakeTimers(); + const { promise, resolve: release } = Promise.withResolvers<void>(); + try { + const { app } = makeApp('omp', { bufferRows: 30, capture: lines(400) }); + const retry = vi.fn(({ repainted, stillActive, attempt }) => !repainted && stillActive && attempt < 4); + const schedule = loadAppMethod('_scheduleDroppedOutputRecovery', { + setTimeout, + window: { CodemanDroppedOutput: { DROP_RECOVERY_DELAY_MS: 2000, shouldRetryDroppedOutputRecovery: retry } }, + }); + const refresh = vi.fn(async () => true); + Object.assign(app, { + _scheduleDroppedOutputRecovery: (...args: unknown[]) => schedule.apply(app, args), + _onSessionNeedsRefresh: refresh, + }); + if (armed) schedule.call(app, 's1'); + const fetchCapture = app._fetchTerminalCapture.getMockImplementation()!; + app._fetchTerminalCapture.mockImplementationOnce(async (url) => { + await promise; + return fetchCapture(url); + }); + const pull = refetch.call(app); + const onTerminal = loadAppMethod('_onSessionTerminal'); + onTerminal.call(app, { id: 's1', data: 'x'.repeat(70_000) }); + onTerminal.call(app, { id: 's1', data: 'y'.repeat(70_000) }); + await vi.advanceTimersByTimeAsync(20_000); // Longer than all five normal retry intervals. + expect(app._isLoadingBuffer).toBe(true); + expect(refresh).not.toHaveBeenCalled(); + expect(retry).not.toHaveBeenCalled(); + release(); + await pull; + expect(app._isLoadingBuffer).toBe(false); + await vi.advanceTimersByTimeAsync(2000); + expect(refresh).toHaveBeenCalledOnce(); + expect(refresh).toHaveBeenCalledWith({ id: 's1' }); + expect(retry).toHaveBeenCalledWith(expect.objectContaining({ attempt: 0, repainted: true })); + } finally { + release(); + vi.useRealTimers(); + } + } + ); + + it('does not resume a deferred recovery for a tab that is no longer active', () => { + const { app } = makeApp('omp', { bufferRows: 30, capture: lines(400) }); + const owner = (app._beginBufferLoad as Function).call(app); + Object.assign(app, { _pendingDroppedOutputRecovery: 's1', activeSessionId: 's2' }); + app._finishBufferLoad(owner); + expect(app._scheduleDroppedOutputRecovery).not.toHaveBeenCalled(); + expect(Reflect.get(app, '_pendingDroppedOutputRecovery')).toBeNull(); + }); + + it.each(['mux-full-history', 'history'])('clears the scroll-pull mark only for a mux capture: %s', async (source) => { + const { app, liveOutput, scroll } = makeScrollApp(); + liveOutput(); + const fetchCapture = app._fetchTerminalCapture.getMockImplementation()!; + app._fetchTerminalCapture.mockImplementationOnce(async (url) => { + const capture = await fetchCapture(url); + capture.json.data.source = source; + return capture; + }); + await scroll(-5); + expect(app._liveOutputSinceFullPull.has('s1')).toBe(source !== 'mux-full-history'); + }); + + it('does not swallow another tab’s travel or clear the old mark when replay is cancelled', async () => { + const { app, active, liveOutput, scroll, pauseReplay } = makeScrollApp(); + liveOutput(); + const paused = pauseReplay(); + const pull = scroll(-5); + await paused.ready; + app.activeSessionId = 's2'; + app._selectGeneration++; + active.baseY = 100; + active.viewportY = 100; + (mixin._maybeLoadMoreHistoryOnScroll as Function).call(app, 3); + expect(app._setHistoryNoticeRevealed).toHaveBeenCalledWith(null); + expect(app._earlyReplayTravel?.moves).toEqual([]); + paused.release(); + await pull; + expect(app._liveOutputSinceFullPull.has('s1')).toBe(true); + expect(app._earlyReplayTravel).toBeNull(); + }); }); describe('a skipped bounded window never damages the Load full history banner', () => { @@ -635,3 +823,190 @@ describe('an unloaded buffer is not held to an older downgrade refusal', () => { expect(app._fullHistoryRepullInFlight).toBe(false); }); }); + +describe('content anchors hold the reader through a history repair', () => { + function fixture(rows: string[], viewportY = 5) { + let content = rows; + const active = { + viewportY, + baseY: rows.length - 3, + length: rows.length, + getLine: vi.fn((row: number) => + content[row] === undefined + ? undefined + : { + translateToString: () => content[row], + } + ), + }; + const app = { terminal: { buffer: { active }, scrollToLine: vi.fn() } }; + const capture = () => (mixin._captureViewportAnchor as Function).call(app); + const restore = (anchor: unknown, next: string[]) => { + content = next; + active.baseY = next.length - 3; + active.length = next.length; + return (mixin._restoreViewportAnchor as Function).call(app, anchor); + }; + return { app, active, capture, restore }; + } + + it('keeps a three-row signature at its viewport offset when rows are inserted below the reader', () => { + const rows = Array.from({ length: 30 }, (_, i) => `row ${i}`); + rows[5] = ''; + const { app, capture, restore } = fixture(rows); + const anchor = capture(); + const target = restore(anchor, [...rows.slice(0, 12), ...Array(20).fill('recovered'), ...rows.slice(12)]); + expect(target).toBe(5); + expect(app.terminal.scrollToLine).toHaveBeenCalledWith(5); + expect(anchor.viewportY).toBe(5); + expect(anchor.offset).toBe(1); + }); + + it('chooses the nearest exact signature over a nearer first-row-only match', () => { + const { capture, restore } = fixture(['head', 'A', 'B', 'C', ...Array(20).fill('tail')], 1); + const anchor = capture(); + const next = Array(34).fill('other'); + next.splice(3, 3, 'A', 'B', 'C'); + next.splice(10, 3, 'A', 'wrong', 'wrong'); + next.splice(17, 3, 'A', 'B', 'C'); + expect(restore(anchor, next)).toBe(17); + }); + + it('falls back to the nearest first row, then distance from the bottom when nothing matches', () => { + const rows = Array.from({ length: 30 }, (_, i) => `row ${i}`); + const { capture, restore } = fixture(rows); + const anchor = capture(); + const next = Array(40).fill('other'); + next[8] = 'row 5'; + next[17] = 'row 5'; + expect(restore(anchor, next)).toBe(17); + expect(restore(anchor, Array(40).fill('no match'))).toBe(15); + }); + + it('keeps bottom distance within the bottom tolerance even if matching text exists', () => { + const rows = Array.from({ length: 30 }, (_, i) => `row ${i}`); + const { capture, restore } = fixture(rows, 26); + expect(restore(capture(), [...rows, ...Array(10).fill('new')])).toBe(36); + }); + + it.each(['first-row-only', 'absent'])('bounds a 50k-row search with an %s signature', (kind) => { + const rows = Array.from({ length: 50_000 }, (_, i) => `original ${i}`); + const { active, capture, restore } = fixture(rows, 25_000); + const anchor = capture(); + const next = Array(50_000).fill('other'); + if (kind === 'first-row-only') { + next[25_100] = anchor.signature[0]; + next[24_800] = anchor.signature[0]; + } + // An exact match outside the budget must not make the scan traverse 50k rows. + next.splice(30_000, 3, ...anchor.signature); + active.getLine.mockClear(); + expect(restore(anchor, next)).toBe(kind === 'first-row-only' ? 25_100 : 25_000); + expect(active.getLine.mock.calls.length).toBeLessThanOrEqual(4005); + }); +}); + +describe('touch history reload control', () => { + function fixture({ + touch = true, + mode = 'omp', + bottom = false, + marked = true, + inFlight = false, + tiles = false, + active = true, + } = {}) { + const button = { hidden: true, disabled: false, textContent: '', onclick: null as (() => void) | null }; + const ui = loadTerminalMixin({ + MobileDetection: { isTouchDevice: () => touch }, + document: { addEventListener: vi.fn(), getElementById: () => button }, + }); + const app = { + activeSessionId: active ? 's1' : null, + sessions: new Map([['s1', { mode }]]), + isTerminalAtBottom: () => bottom, + _liveOutputSinceFullPull: new Set(marked ? ['s1'] : []), + _fullHistoryRepullInFlight: inFlight, + _tilesOwnTerminal: () => tiles, + _maybeRefetchFullHistory: vi.fn(async (_opts: object) => {}), + _syncHistoryReloadButton: () => (ui._syncHistoryReloadButton as Function).call(app), + }; + return { app, button }; + } + + it.each([ + { opts: {}, visible: true }, + { opts: { touch: false }, visible: false }, + { opts: { mode: 'shell' }, visible: false }, + { opts: { bottom: true }, visible: false }, + { opts: { marked: false }, visible: false }, + { opts: { inFlight: true }, visible: false }, + { opts: { tiles: true }, visible: false }, + { opts: { active: false }, visible: false }, + ])('visibility is $visible for $opts', ({ opts, visible }) => { + const { app, button } = fixture(opts); + app._syncHistoryReloadButton(); + expect(button.hidden).toBe(!visible); + }); + + it('forces a content-anchored pull on tap and resets the loading state on settle', async () => { + const { app, button } = fixture(); + const { promise, resolve: release } = Promise.withResolvers<void>(); + app._maybeRefetchFullHistory.mockReturnValueOnce(promise); + app._syncHistoryReloadButton(); + const tapped = button.onclick!(); + expect(app._maybeRefetchFullHistory).toHaveBeenCalledWith({ force: true, anchor: 'content' }); + expect(button.disabled).toBe(true); + expect(button.textContent).toBe('Loading…'); + release(); + await tapped; + expect(button.disabled).toBe(false); + expect(button.textContent).toBe('↻ Reload history'); + }); +}); + +describe('selectSession only clears live-output marks for actual full mux captures', () => { + it.each(['mux-full-history', 'history'])('checks the response source: %s', async (source) => { + const errors = vi.fn(); + const select = loadAppMethod('selectSession', { + console: { log: vi.fn(), error: errors }, + document: { querySelector: () => null }, + localStorage: { setItem: vi.fn(), getItem: () => null }, + requestIdleCallback: vi.fn(), + }); + const { app } = makeApp('omp', { bufferRows: 30, capture: lines(60), payload: { source } }); + const methods = Object.fromEntries( + [ + '_setTerminalLoadState', + '_clearTerminalLoadState', + '_cleanupPreviousSession', + '_renderHistoryTruncationBanner', + '_updateSseSubscription', + 'hideWelcome', + 'markIdleAlertSeen', + '_updateActiveTabImmediate', + 'closeSessionSidebarOnHandheld', + 'renderSessionTabs', + '_updateLocalEchoState', + 'syncTerminalGeometry', + '_markTerminalBufferReconciled', + '_connectWs', + 'scrollToLastNonEmptyLine', + ].map((name) => [name, vi.fn()]) + ); + Object.assign(app, methods, { + activeSessionId: 's2', + _fullHistoryLoaded: new Set(), + _liveOutputSinceFullPull: new Set(['s1']), + _liveOutputGen: new Map(), + _shouldFocusTerminalForTabSwitch: () => false, + _isStaleSelect: () => false, + sendResize: async () => false, + }); + Object.assign(app.terminal, { scrollToBottom: vi.fn() }); + await select.call(app, 's1'); + expect(errors).not.toHaveBeenCalled(); + expect(app.chunkedTerminalWrite).toHaveBeenCalledOnce(); + expect(Reflect.get(app, '_liveOutputSinceFullPull').has('s1')).toBe(source !== 'mux-full-history'); + }); +}); From fd6b392b4d65b74bbb26845fa5515ba081108c0f Mon Sep 17 00:00:00 2001 From: Hadrien Kerlero <199662351+HadrienKerlero@users.noreply.github.com> Date: Mon, 16 Nov 2026 15:45:35 +0100 Subject: [PATCH 04/23] fix(web): make the early history repair a manual Reload history action (#814) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Scrolling pulls tmux history only at the top of the buffer again (#205); the automatic pull on any upward scroll is removed. - Reload history lives in the existing #historyTruncationBar on desktop and touch, shown for a marked non-shell session scrolled away from live output. It never duplicates Load full history; one × dismisses what the bar carried. - New per-device setting historyReloadAction (Terminal & Input > Scrolling & rendering), default on, kept out of SettingsUpdateSchema. - Eligibility sync is transition-only and onScroll is coalesced per frame. - Remove the floating #historyReloadBtn and its z-index 20 layer. - Deferred dropped-output recovery resumes at its saved attempt. - zh-CN entries for the new strings; docs and changeset updated. --- .../814-history-repair-while-reading.md | 2 +- docs/architecture-invariants.md | 4 +- src/web/CLAUDE.md | 2 +- src/web/public/app.js | 103 ++++-- src/web/public/i18n.js | 6 + src/web/public/index.html | 8 +- src/web/public/settings-ui.js | 7 + src/web/public/styles.css | 20 -- src/web/public/terminal-ui.js | 64 ++-- test/history-gap-repair.browser.test.ts | 161 +++++---- test/history-notice-reveal.test.ts | 49 +-- test/settings-admin-only-ui.test.ts | 39 +++ test/shell-scroll-history-pull.test.ts | 323 +++++++++++++----- 13 files changed, 517 insertions(+), 271 deletions(-) diff --git a/.changeset/814-history-repair-while-reading.md b/.changeset/814-history-repair-while-reading.md index f67cf6c8..caa91c5d 100644 --- a/.changeset/814-history-repair-while-reading.md +++ b/.changeset/814-history-repair-while-reading.md @@ -2,4 +2,4 @@ 'aicodeman': patch --- -Fix missing terminal history above live OMP output, including when scrolling up while already reading older output on a phone. History recovery now preserves the text being read and output arriving during the download, and touch devices offer a Reload history button while scrolled away from live output. +Fix missing terminal history above live OMP output with a manual Reload history action in the existing history banner on desktop and mobile. The action preserves the text being read and output arriving during the download, and can be disabled per device in Settings > Terminal & Input > Scrolling & rendering. Ordinary scrolling only pulls history at the top; deferred dropped-output recovery retains its retry attempt. diff --git a/docs/architecture-invariants.md b/docs/architecture-invariants.md index 784d696c..750caa8d 100644 --- a/docs/architecture-invariants.md +++ b/docs/architecture-invariants.md @@ -251,9 +251,9 @@ Further detail: the `<prefix>: <title>` form (`w3-myapp: fix the login redirect` ### Full-scrollback replay -**Full-scrollback replay** (COD-164/#148, reworked for #205): `GET /api/sessions/:id/terminal?full=1` returns the ENTIRE tmux scrollback (capture-pane `-e -S -<lines>` bounded by the configured history limit, explicit `maxBuffer` from the terminal-history config, early byte-cap before normalization, CRLF-normalized for shell panes). On success the capture is returned ALONE (`source='mux-full-history'` — it supersedes the byte buffer; no duplication). The first load of each non-shell TUI session per page requests `full=1` (`_fullHistoryLoaded` Set in app.js — the old one-shot `_initialFullBufferLoad` flag was consumed by whichever tab auto-selected, leaving every other TUI tab one frame of history). Shell sessions instead load a bounded window of tmux's RENDERED history on every selection, automatic drop recovery, clear and tile load (`SHELL_LOAD_QUERY` in constants.js: `?full=1&tail=1MiB&lines=10000&alt=recording`): a 100k-line shell capture can be tens of MiB, and automatically parsing it makes tab-switch latency scale with the entire session (`lines=` bounds the synchronous capture-pane, about 8 ms per 1000 lines). They never replay the raw byte recording ahead of the visible frame any more: it holds full-screen repaints (an ssh'd tmux, `less`, any TUI) drawn for the pane height of the moment, and replayed into a terminal of another height each repaint's last newline scrolls its top row into scrollback, so one line tmux holds once showed up dozens of times. Because `lines=` is shallower than xterm's scrollback, the route reports a cut: the capture's `display-message` query also reads `#{history_size}` (`PaneCaptureOptions.capturedHistoryLines`, the same field the route reports as `paneHistoryLines`), and a full capture whose CLIENT bound (`lines=` below the configured `tmuxHistoryLimit`) left lines in tmux comes back `truncated`, `truncationReason: 'tail'`. ⚠️ Only a client bound below the ceiling counts: a request without `lines=` is bounded by the ceiling itself, and on tmux before 3.7 a live pane can hold more than a lowered ceiling, which no request can read. ⚠️ **A pane in the alternate screen keeps no tmux history**, and a nested tmux client (remote SSH and Docker cases, or `tmux`/`ssh -t host tmux` run by hand) holds its pane there, so its full capture is one screen. The same query reads `#{alternate_on}` (`capturedAlternateOn`), and a request carrying `alt=recording` (only `SHELL_LOAD_QUERY`) is then answered the old way, the visible frame over the tailed byte recording, which still carries the scrollback; agents, scroll pulls and **Load full history** never send it. `#{alternate_on}` cannot tell a nested tmux from vim, `less` or `htop`, so a local shell with one of those open takes the same fallback until it exits (the pre-fix load, with its repaint duplicates). Shell FULL history is explicit-button-only; reaching the top during an ordinary wheel/touch gesture must not reset xterm and replay the multi-megabyte capture on its main thread. That gesture instead pulls a BOUNDED window of it (`?full=1&tail=<TERMINAL_TAIL_SIZE>`, so a capture beyond 1 MiB comes back `truncationReason: 'tail'` and the banner offers the rest), and skips the replay when the window holds no more rows than the browser already has. ⚠️ **That skip runs BEFORE the downgrade guard, and it never touches the banner state**: the guard reads "smaller than the browser" as "tmux has nothing more to give", true of an unbounded capture and false of a window cut at the tail size, so a bounded window that reached it marked the session `exhausted` and removed **Load full history** while tmux still held the rest; and re-labelling the banner from a skipped payload would call a terminal that holds all of a Load full history pull "the most recent 1 MiB". A skipped window that came back truncated puts the session on the 60 s cooldown (`_fullHistoryRepullUseless`), because it can never reach anything older than the browser shows and `tail` is applied AFTER the server's synchronous `capture-pane` of the whole history, so each ask costs every client an event-loop stall (about 0.3 s at 100k lines); an untruncated one keeps the 4 s cooldown, since it is all of tmux's history and the next burst can add to it. Declining the gesture outright was a dead end: after any burst a shell pane held about one screen of browser scrollback, and the button renders only once a replay was truncated, so a young shell tab had no way back to history tmux still held. Other modes re-pull `full=1` at the top or on any upward scroll after live output since the last `mux-full-history` replay, and pressing **Load full history** forces the request for any recoverably truncated session (`_maybeRefetchFullHistory`, 4s per-session gesture cooldown, in-flight + tab-switch guards, viewport position held across the replay); Shell full pulls are not retained in the tab cache, so the next switch stays bounded. Chunked replay enqueues 32 KiB pieces across safe yields, appends an xterm parse marker, then releases the live-output gate; output arriving after that release stays ordered behind the snapshot, and the marker callback supplies accurate parse timing. ⚠️ **How the load ENDS depends on where the payload came from**, and `_bufferLoadFinishOpts` (app.js) is the one place that decides it for all four fetch-and-write paths. A payload built from the server's accumulated byte history is current up to the response, so the events queued during the load already appear in it and stay DISCARDED; replaying them would duplicate output, most visibly Ink's cursor-up redraws. A pane capture (`mux-visible` or `mux-full-history`) is current only up to CAPTURE time, so `_finishBufferLoad` replays the queue from the response's own arrival timestamp (`since`) and the pre-capture events stay dropped. ⚠️ **A path that then restores a scroll position must re-take the sticky-scroll baseline** (`_syncStickyScrollBaseline`): the replay runs inside `chunkedTerminalWrite` before its promise resolves, with the terminal freshly reset, so `batchTerminalWrite` samples `_wasAtBottomBeforeWrite` as true and the next `flushPendingWrites` would scroll to the bottom over the restore. ⚠️ The cutoff is a client-side timestamp and the server broadcasts on a batch timer (8ms WebSocket, 16-50ms SSE), so a batch pending when the capture ran arrives after the response and replays although the capture holds it — bounded by one batch interval, and closable only server side by flushing that batch before the capture. Tests for the three: `test/terminal-flush-budget.test.ts` pins which sources flush, `test/terminal-buffer-flush.test.ts` pins the `since` cutoff and the baseline re-take, and `test/capture-load-window.browser.test.ts` drives both against a live server. Live output is separately one-chunk-in-flight: xterm's callback releases each 32/64 KiB write before the next is submitted, keeping the remainder in the app queue where the 128 KiB cap can observe it instead of hiding an unbounded backlog in xterm's private WriteBuffer. While WebSocket owns terminal I/O, parallel SSE terminal/output-recovery events are discarded before JSON parsing; fallback recovery is single-flight per active session so backpressure cannot start overlapping reset+replay cycles. The route exposes capture/prepare totals in `Server-Timing`, while `[TERMINAL-PERF]` separates TTFB, body/JSON, reset+parse and total time for both selection and on-demand full pulls; parse completion is not a browser compositor/GPU paint measurement. The re-pull exists because xterm's buffer is only a WINDOW onto tmux's history and two things shrink it: tmux coalesces bursty output into pane REPAINTS that overwrite rows instead of emitting linefeeds (measured: a 60-line burst added 1 row of browser scrollback and destroyed 34), and a tab switch replays only the visible frame. tmux's own history is intact throughout — the browser just has to ask for it again. Gesture-triggered rather than polling because at a 100k history limit the capture can be megabytes. ⚠️ **The capture ENDS with a cursor move back to the pane's own caret position** (`formatCursorRestore`, from the same `display-message` query the visible-frame path uses). The linear replay otherwise leaves the caret wherever the last character landed — the bottom-most row carrying text, which for an agent CLI is the status line — so the caret sat on the composer's border instead of its input line and every cursor-relative update the CLI sent afterwards was measured from the wrong row, until its next full redraw silently repaired it (that self-repair is why the report read as "it fixes itself as soon as Claude writes a line"). ⚠️ **The move is RELATIVE — up `rows - 1 - cursor_y`, then `\r`, then right `cursor_x` — never `CUP`.** `\x1b[<row>;<col>H` numbers rows from the top of the browser's screen, so it lands correctly only while the browser's row count equals `pane_height`, and nothing guarantees that: `resizeWindow` issues its tmux resize fire-and-forget and returns immediately, so a capture can be taken before a requested resize has applied, and `_onSessionNeedsRefresh` sends no resize at all. Counting up from the last replayed row anchors to the content both ends share. Restoring the cursor makes ROW ALIGNMENT load-bearing on this path: **no transform that can DELETE A LINE may run over a full-history capture**, because every deletion shifts the frame out from under the restored position. Four had accumulated — trailing blank rows stripped by `\n+$`, `stripInkRedrawBloat`, the `CLAUDE_BANNER_PATTERN` trim that cuts everything above the banner, and `LEADING_WHITESPACE_PATTERN` — each correct for a byte stream of successive frames and each wrong for a single rendered frame. ⚠️ **Those skips key on `isFullCapture`, meaning a capture actually came back — never on `?full=1` alone.** When `captureActivePaneBuffer` returns null (ENOBUFS, a timeout, a vanished pane, or a session with no mux at all) the reply falls back to `session.terminalBuffer`, which IS a byte stream and must still be stripped; gating on the query flag returned it whole, and a direct-PTY session takes that path on every first selection rather than only during an outage. ⚠️ A capture holding nothing visible (`hasVisibleContent`) returns `''`, because the caller reads an empty capture as "unavailable" and keeps its byte history — retaining trailing blank rows made an all-blank pane non-empty, which would have replaced real history with a blank screen from the server side, where `_replayWouldShrinkBuffer` cannot see it. ⚠️ **"One line per screen row" holds only where no row was hard-wrapped**: `-J` joins a wrapped row into its logical line (measured: a 100-character line in a 40-column pane captures as 10 lines against a 12-row pane), and the counts reconcile only once the browser xterm re-wraps at the same width — the same assumption `_estimateReplayRows` already documents. Tests: `test/tmux-capture-full-history.test.ts` covers the cursor move, the trim pairing and `hasVisibleContent`; `test/routes/session-routes.test.ts` covers a surviving blank first row, an unstripped byte-history fallback, and an empty capture leaving history intact. ⚠️ **The re-pull must never DOWNGRADE the buffer** (#205 round 2): the same reasoning that makes it a win for a shell pane makes it destructive for a repaint-mode CLI pane, where tmux keeps no history of its own (`history_size≈0` measured for a Claude pane) and the capture is roughly ONE frame while xterm may hold hundreds of rows of replayed frames — `_resetTerminalForReplay()` + rewrite then deletes history mid-scroll ("goes back a bit, repeats blocks, gets worse the further up I go"; measured A/B on a live pane: 341 rows → 42 with the guard off). `_replayWouldShrinkBuffer()` (terminal-ui.js) estimates the capture's rendered rows — escape sequences stripped, `capture-pane -J` re-wrapping accounted for — and the pull is skipped when that is more than one screen short of `buffer.active.length`. The one-screen tolerance matters: both sides are estimates (the buffer length counts trailing blank rows), so only a clear downgrade is refused. A refused session joins `_fullHistoryRepullUseless`, raising its cooldown from 4s to 60s so a hollow pane stops re-fetching megabytes on every scroll-up. Tests: `test/tmux-capture-full-history.test.ts`, `test/tmux-scrollback-eol.test.ts`, `test/terminal-scroll-routing.test.ts`, `test/terminal-flush-budget.test.ts`. +**Full-scrollback replay** (COD-164/#148, reworked for #205): `GET /api/sessions/:id/terminal?full=1` returns the ENTIRE tmux scrollback (capture-pane `-e -S -<lines>` bounded by the configured history limit, explicit `maxBuffer` from the terminal-history config, early byte-cap before normalization, CRLF-normalized for shell panes). On success the capture is returned ALONE (`source='mux-full-history'` — it supersedes the byte buffer; no duplication). The first load of each non-shell TUI session per page requests `full=1` (`_fullHistoryLoaded` Set in app.js — the old one-shot `_initialFullBufferLoad` flag was consumed by whichever tab auto-selected, leaving every other TUI tab one frame of history). Shell sessions instead load a bounded window of tmux's RENDERED history on every selection, automatic drop recovery, clear and tile load (`SHELL_LOAD_QUERY` in constants.js: `?full=1&tail=1MiB&lines=10000&alt=recording`): a 100k-line shell capture can be tens of MiB, and automatically parsing it makes tab-switch latency scale with the entire session (`lines=` bounds the synchronous capture-pane, about 8 ms per 1000 lines). They never replay the raw byte recording ahead of the visible frame any more: it holds full-screen repaints (an ssh'd tmux, `less`, any TUI) drawn for the pane height of the moment, and replayed into a terminal of another height each repaint's last newline scrolls its top row into scrollback, so one line tmux holds once showed up dozens of times. Because `lines=` is shallower than xterm's scrollback, the route reports a cut: the capture's `display-message` query also reads `#{history_size}` (`PaneCaptureOptions.capturedHistoryLines`, the same field the route reports as `paneHistoryLines`), and a full capture whose CLIENT bound (`lines=` below the configured `tmuxHistoryLimit`) left lines in tmux comes back `truncated`, `truncationReason: 'tail'`. ⚠️ Only a client bound below the ceiling counts: a request without `lines=` is bounded by the ceiling itself, and on tmux before 3.7 a live pane can hold more than a lowered ceiling, which no request can read. ⚠️ **A pane in the alternate screen keeps no tmux history**, and a nested tmux client (remote SSH and Docker cases, or `tmux`/`ssh -t host tmux` run by hand) holds its pane there, so its full capture is one screen. The same query reads `#{alternate_on}` (`capturedAlternateOn`), and a request carrying `alt=recording` (only `SHELL_LOAD_QUERY`) is then answered the old way, the visible frame over the tailed byte recording, which still carries the scrollback; agents, scroll pulls and **Load full history** never send it. `#{alternate_on}` cannot tell a nested tmux from vim, `less` or `htop`, so a local shell with one of those open takes the same fallback until it exits (the pre-fix load, with its repaint duplicates). Shell FULL history is explicit-button-only; reaching the top during an ordinary wheel/touch gesture must not reset xterm and replay the multi-megabyte capture on its main thread. That gesture instead pulls a BOUNDED window of it (`?full=1&tail=<TERMINAL_TAIL_SIZE>`, so a capture beyond 1 MiB comes back `truncationReason: 'tail'` and the banner offers the rest), and skips the replay when the window holds no more rows than the browser already has. ⚠️ **That skip runs BEFORE the downgrade guard, and it never touches the banner state**: the guard reads "smaller than the browser" as "tmux has nothing more to give", true of an unbounded capture and false of a window cut at the tail size, so a bounded window that reached it marked the session `exhausted` and removed **Load full history** while tmux still held the rest; and re-labelling the banner from a skipped payload would call a terminal that holds all of a Load full history pull "the most recent 1 MiB". A skipped window that came back truncated puts the session on the 60 s cooldown (`_fullHistoryRepullUseless`), because it can never reach anything older than the browser shows and `tail` is applied AFTER the server's synchronous `capture-pane` of the whole history, so each ask costs every client an event-loop stall (about 0.3 s at 100k lines); an untruncated one keeps the 4 s cooldown, since it is all of tmux's history and the next burst can add to it. Declining the gesture outright was a dead end: after any burst a shell pane held about one screen of browser scrollback, and the button renders only once a replay was truncated, so a young shell tab had no way back to history tmux still held. Other modes re-pull `full=1` only at the top of the local buffer, and pressing **Load full history** forces the request for any recoverably truncated session (`_maybeRefetchFullHistory`, 4s per-session gesture cooldown, in-flight + tab-switch guards, viewport position held across the replay); Shell full pulls are not retained in the tab cache, so the next switch stays bounded. Chunked replay enqueues 32 KiB pieces across safe yields, appends an xterm parse marker, then releases the live-output gate; output arriving after that release stays ordered behind the snapshot, and the marker callback supplies accurate parse timing. ⚠️ **How the load ENDS depends on where the payload came from**, and `_bufferLoadFinishOpts` (app.js) is the one place that decides it for all four fetch-and-write paths. A payload built from the server's accumulated byte history is current up to the response, so the events queued during the load already appear in it and stay DISCARDED; replaying them would duplicate output, most visibly Ink's cursor-up redraws. A pane capture (`mux-visible` or `mux-full-history`) is current only up to CAPTURE time, so `_finishBufferLoad` replays the queue from the response's own arrival timestamp (`since`) and the pre-capture events stay dropped. ⚠️ **A path that then restores a scroll position must re-take the sticky-scroll baseline** (`_syncStickyScrollBaseline`): the replay runs inside `chunkedTerminalWrite` before its promise resolves, with the terminal freshly reset, so `batchTerminalWrite` samples `_wasAtBottomBeforeWrite` as true and the next `flushPendingWrites` would scroll to the bottom over the restore. ⚠️ The cutoff is a client-side timestamp and the server broadcasts on a batch timer (8ms WebSocket, 16-50ms SSE), so a batch pending when the capture ran arrives after the response and replays although the capture holds it — bounded by one batch interval, and closable only server side by flushing that batch before the capture. Tests for the three: `test/terminal-flush-budget.test.ts` pins which sources flush, `test/terminal-buffer-flush.test.ts` pins the `since` cutoff and the baseline re-take, and `test/capture-load-window.browser.test.ts` drives both against a live server. Live output is separately one-chunk-in-flight: xterm's callback releases each 32/64 KiB write before the next is submitted, keeping the remainder in the app queue where the 128 KiB cap can observe it instead of hiding an unbounded backlog in xterm's private WriteBuffer. While WebSocket owns terminal I/O, parallel SSE terminal/output-recovery events are discarded before JSON parsing; fallback recovery is single-flight per active session so backpressure cannot start overlapping reset+replay cycles. The route exposes capture/prepare totals in `Server-Timing`, while `[TERMINAL-PERF]` separates TTFB, body/JSON, reset+parse and total time for both selection and on-demand full pulls; parse completion is not a browser compositor/GPU paint measurement. The re-pull exists because xterm's buffer is only a WINDOW onto tmux's history and two things shrink it: tmux coalesces bursty output into pane REPAINTS that overwrite rows instead of emitting linefeeds (measured: a 60-line burst added 1 row of browser scrollback and destroyed 34), and a tab switch replays only the visible frame. tmux's own history is intact throughout — the browser just has to ask for it again. Gesture-triggered rather than polling because at a 100k history limit the capture can be megabytes. ⚠️ **The capture ENDS with a cursor move back to the pane's own caret position** (`formatCursorRestore`, from the same `display-message` query the visible-frame path uses). The linear replay otherwise leaves the caret wherever the last character landed — the bottom-most row carrying text, which for an agent CLI is the status line — so the caret sat on the composer's border instead of its input line and every cursor-relative update the CLI sent afterwards was measured from the wrong row, until its next full redraw silently repaired it (that self-repair is why the report read as "it fixes itself as soon as Claude writes a line"). ⚠️ **The move is RELATIVE — up `rows - 1 - cursor_y`, then `\r`, then right `cursor_x` — never `CUP`.** `\x1b[<row>;<col>H` numbers rows from the top of the browser's screen, so it lands correctly only while the browser's row count equals `pane_height`, and nothing guarantees that: `resizeWindow` issues its tmux resize fire-and-forget and returns immediately, so a capture can be taken before a requested resize has applied, and `_onSessionNeedsRefresh` sends no resize at all. Counting up from the last replayed row anchors to the content both ends share. Restoring the cursor makes ROW ALIGNMENT load-bearing on this path: **no transform that can DELETE A LINE may run over a full-history capture**, because every deletion shifts the frame out from under the restored position. Four had accumulated — trailing blank rows stripped by `\n+$`, `stripInkRedrawBloat`, the `CLAUDE_BANNER_PATTERN` trim that cuts everything above the banner, and `LEADING_WHITESPACE_PATTERN` — each correct for a byte stream of successive frames and each wrong for a single rendered frame. ⚠️ **Those skips key on `isFullCapture`, meaning a capture actually came back — never on `?full=1` alone.** When `captureActivePaneBuffer` returns null (ENOBUFS, a timeout, a vanished pane, or a session with no mux at all) the reply falls back to `session.terminalBuffer`, which IS a byte stream and must still be stripped; gating on the query flag returned it whole, and a direct-PTY session takes that path on every first selection rather than only during an outage. ⚠️ A capture holding nothing visible (`hasVisibleContent`) returns `''`, because the caller reads an empty capture as "unavailable" and keeps its byte history — retaining trailing blank rows made an all-blank pane non-empty, which would have replaced real history with a blank screen from the server side, where `_replayWouldShrinkBuffer` cannot see it. ⚠️ **"One line per screen row" holds only where no row was hard-wrapped**: `-J` joins a wrapped row into its logical line (measured: a 100-character line in a 40-column pane captures as 10 lines against a 12-row pane), and the counts reconcile only once the browser xterm re-wraps at the same width — the same assumption `_estimateReplayRows` already documents. Tests: `test/tmux-capture-full-history.test.ts` covers the cursor move, the trim pairing and `hasVisibleContent`; `test/routes/session-routes.test.ts` covers a surviving blank first row, an unstripped byte-history fallback, and an empty capture leaving history intact. ⚠️ **The re-pull must never DOWNGRADE the buffer** (#205 round 2): the same reasoning that makes it a win for a shell pane makes it destructive for a repaint-mode CLI pane, where tmux keeps no history of its own (`history_size≈0` measured for a Claude pane) and the capture is roughly ONE frame while xterm may hold hundreds of rows of replayed frames — `_resetTerminalForReplay()` + rewrite then deletes history mid-scroll ("goes back a bit, repeats blocks, gets worse the further up I go"; measured A/B on a live pane: 341 rows → 42 with the guard off). `_replayWouldShrinkBuffer()` (terminal-ui.js) estimates the capture's rendered rows — escape sequences stripped, `capture-pane -J` re-wrapping accounted for — and the pull is skipped when that is more than one screen short of `buffer.active.length`. The one-screen tolerance matters: both sides are estimates (the buffer length counts trailing blank rows), so only a clear downgrade is refused. A refused session joins `_fullHistoryRepullUseless`, raising its cooldown from 4s to 60s so a hollow pane stops re-fetching megabytes on every scroll-up. Tests: `test/tmux-capture-full-history.test.ts`, `test/tmux-scrollback-eol.test.ts`, `test/terminal-scroll-routing.test.ts`, `test/terminal-flush-budget.test.ts`. -**Repair while reading (#814)** opens the buffer load BEFORE the capture fetch, so download-time output queues behind the replay instead of being overwritten. Every non-replay exit flushes the whole queue into the untouched buffer; a replay keeps the capture-header cutoff above. A dropped-output recovery blocked by an open load is deferred without consuming retries and resumes when the load finishes, only for the still-active session. Only an actual `mux-full-history` response may clear the live-output mark, and a newer live-write generation keeps it marked. Any upward scroll in a marked non-shell session repairs, including mid-history and at the top (one pull per gesture), still guarded by the 4 s cooldown, 60 s useless-pull latch and downgrade refusal. A gesture that reached the original top still reveals the resulting partial-history notice even if the content restore moves it below row zero; a mid-history repair does not reveal it unless subsequent travel reaches the top. A content anchor captures the first non-empty row at/after the viewport and its next two rows, restores the nearest matching signature at the same viewport offset, and falls back to the nearest first-row-only match or distance from the bottom if unmatched or already near live output. Search is bounded to 2000 rows either side of the expected row (at most 4001 candidates / 12003 line reads), never the entire 50k-row buffer. Ordered, session-scoped travel during replay is then applied with per-move clamping; a switched-to tab never donates travel. On touch devices a floating **Reload history** button offers the same forced, content-anchored recovery while scrolled up in a marked non-shell session, never while tiles own the terminal or another pull is running. `_syncHistoryReloadButton()` alone owns its visibility; its overlay/44px touch-target rules live in the unconditional stylesheet so wide touch viewports do not resize the terminal. The trade-off remains synchronous server `capture-pane`: about 0.3 s at 100k lines, blocking the event loop, not a cheap automatic per-output repair. Tests: `test/shell-scroll-history-pull.test.ts`, `test/history-gap-repair.browser.test.ts`. +**Repair while reading (#814)** is a manual **Reload history** action inside the existing history banner on desktop and touch devices, enabled by default and toggleable per device in Settings → Terminal & Input → Scrolling & rendering (`historyReloadAction`). It is offered only for a marked non-shell active session while scrolled away from live output, not detached, not owned by tiles and with no pull in flight. A revealed truncation notice keeps its message and its **Load full history** control; Reload is appended only when the notice has no load control, or shown alone with a short missing-output message. A reload-only × dismissal lasts until the mark is cleared by a successful full mux replay, independently of the notice’s page-long dismissal. Eligibility is cached per active session, with onScroll sampling coalesced to one animation frame on every device; unchanged eligibility never rebuilds the banner. Automatic history pulls and notice reveal stay top-only (#205). The manual action forces a content-anchored pull, bypassing the gesture cooldown but retaining the downgrade guard. A content anchor captures the first non-empty row at/after the viewport and its next two rows, restores the nearest matching signature at the same viewport offset, and falls back to the nearest first-row-only match or distance from the bottom if unmatched or already near live output. Search is bounded to 2000 rows either side of the expected row (at most 4001 candidates / 12003 line reads). Ordered, session-scoped travel during replay is applied with per-move clamping; a switched-to tab never donates travel. The buffer load opens BEFORE the fetch, so download-time output queues behind the replay instead of being overwritten. Non-replay exits flush the whole queue; replays retain the capture-header cutoff above. A blocked dropped-output recovery stores its session and current attempt, defers without consuming retries, and resumes only for the still-active session. Only an actual `mux-full-history` replay clears the live-output mark and reload dismissal, and a newer live-write generation keeps them marked. The trade-off remains a full synchronous server capture (about 0.3 s at 100k lines), not a cheap automatic per-output repair. Tests: `test/shell-scroll-history-pull.test.ts`, `test/history-gap-repair.browser.test.ts`. **The partial-history notice is lazy and pane-gated** (`computeHistoryTruncationNotice()` in constants.js, `_renderHistoryTruncationBanner()` / `_setHistoryNoticeRevealed()` in app.js). `truncated` on a terminal response measures the server's BYTE stream, which is not what `full=1` can return: for a pane with no tmux scrollback (fullscreen claude starts in the alternate screen and never writes to the main grid, so `#{history_size}` is 0) the bytes a tail cut drops are old repaint frames. Measured on prod 2026-10-10, every claude pane: the tab-switch tail cut a 1.2 to 6.2 MB stream to 1 MiB, the local scrollback that tail replays into is repeats of the same frames (one pane: 450 non-blank rows, 44 unique, one row 33 times), and `full=1` returned 1 to 5 KB, so **Load full history** could only end in the downgrade refusal while the banner promised "4.8 MB more". The capture therefore reads `#{history_size}` in the SAME `display-message` as the cursor (no extra tmux call), the route returns it as `paneHistoryLines` (absent when the body is not a capture, and for a remote SSH session, whose local pane hosts the remote tmux client and always reports 0 while `full=1` reads the remote history), and a reported 0 hides the notice in every state; a positive count replaces the byte gap in the message. ⚠️ Key the notice decision on `history_size`, never on `alternate_on`: a shell running `less` is in the alternate screen with its whole history still retained (measured, 99,972 rows) and `full=1` returns all of it. The one place `alternate_on` decides is a shell's AUTOMATIC load (`alt=recording`, see Full-scrollback replay): there the question is whether the capture holds the scrollback a nested tmux client keeps in its byte recording, not whether a pull can return more. The notice is also LAZY: it appears only after a wheel/touch gesture reaches the top of the browser buffer and the pull that gesture started has settled (`_maybeLoadMoreHistoryOnScroll`), goes away when a downward gesture is back at live output or the tab switches (`selectSession` nulls `_historyNoticeRevealedFor` before repainting), and its × is sticky per session until reload (`_historyNoticeDismissed`). Tests: `test/history-truncation-notice.test.ts`, `test/history-notice-reveal.test.ts`. diff --git a/src/web/CLAUDE.md b/src/web/CLAUDE.md index 5260666a..f28012a2 100644 --- a/src/web/CLAUDE.md +++ b/src/web/CLAUDE.md @@ -56,7 +56,7 @@ Frontend JS modules have `@fileoverview` with `@dependency`/`@loadorder` tags. L **Command palette + shortcut registry**: `Ctrl/Cmd/Alt+K` opens the session palette; shortcuts live in a rebindable registry (`DEFAULT_SHORTCUTS`/`getShortcutRegistry()`/`matchesShortcutEvent()` in app.js, overrides in `settings.shortcutOverrides`). ⚠️ Palette-chord keys must ALSO be swallowed in `attachCustomKeyEventHandler` (terminal-ui.js) or xterm writes the control byte into the PTY. ⚠️ The global Escape handler (app.js) calls EVERY close method on every Escape, in the capture phase, so a close method that does more than hide (the palette and Session Manager restore focus) must return early when its overlay is not open. ⚠️ `saveAppSettings()` rebuilds settings from the DOM, so keys edited elsewhere (`shortcutOverrides`, `showTokenCount`, `showCost`) need explicit `_prev` carry-over. ⚠️ **Smart copy (`Ctrl+C`)**: with no selection it must `return true` without `preventDefault()` or the interrupt is lost; keep `copyTerminalSelection` out of `SHORTCUT_ACTIONS`. The gate tests the CLEANED selection (`CodemanCopySelection.clean`: trailing padding, plus a LEADING margin only up to the width the CLI declares in `capabilities.transcriptGutter`, never one derived from the pane); the strip is not idempotent, so clean once and pass the RAW selection on, and leave Alt+drag column selections untouched. → [architecture-invariants#command-palette-and-shortcut-registry](../../docs/architecture-invariants.md#command-palette-and-shortcut-registry) -**Per-device vs synced settings**: the `displayKeys` set in settings-ui.js is a **client-side merge policy**, not a wire filter. A display key seeds from the server only when localStorage has no value for it, which is what prevents one device overwriting another; `showPlanUsageLimits` is additionally `delete`d from the incoming payload outright. Separately, `SettingsUpdateSchema` is `.strict()` and simply **does not declare** `skin`, `showFileViewerButton`, `showCronButton`, `webglRendererEnabled`, `localEchoEnabled`, `keyboardHoldsRows`, `cjkInputEnabled`, `cjkInputHoldUntilEnter`, or `extendedKeyboardBar`, so sending one of those is a validation error. The rest (`showResponseViewer`, `showPlanUsageLimits`, `language`, and most `show*` keys) ARE in the schema and do persist server-side; they are per-device by client policy only. ⚠️ Adding a new per-device setting means deciding **both** questions: membership in `displayKeys`, and presence in the schema. +**Per-device vs synced settings**: the `displayKeys` set in settings-ui.js is a **client-side merge policy**, not a wire filter. A display key seeds from the server only when localStorage has no value for it, which is what prevents one device overwriting another; `showPlanUsageLimits` is additionally `delete`d from the incoming payload outright. Separately, `SettingsUpdateSchema` is `.strict()` and simply **does not declare** `skin`, `showFileViewerButton`, `showCronButton`, `webglRendererEnabled`, `localEchoEnabled`, `keyboardHoldsRows`, `cjkInputEnabled`, `cjkInputHoldUntilEnter`, `extendedKeyboardBar`, or `historyReloadAction`, so sending one of those is a validation error. The rest (`showResponseViewer`, `showPlanUsageLimits`, `language`, and most `show*` keys) ARE in the schema and do persist server-side; they are per-device by client policy only. ⚠️ Adding a new per-device setting means deciding **both** questions: membership in `displayKeys`, and presence in the schema. **Settings surface** (`#appSettingsModal` + `#sessionOptionsModal` + `#createCaseModal`): one `set-*` language shared through a single `:is(...)` id scope in styles.css. App Settings' rail is a table of contents over ONE scrolling document (`switchSettingsTab` scrolls); Session Options and Add Case really switch (`switchOptionsTab` / `switchCaseModalTab`), and their larger per-modal size blocks are the design, not drift. ⚠️ **The load/save contract is `getElementById` by id**: renaming or dropping a control id silently stops it loading or saving. ⚠️ The Session Options "Session" entry still keys off `context` (label-only rename). ⚠️ Add Case keeps its legacy `.form-row` markup via an adapter; every `<details>` there needs `.set-adv-chev` plus both marker suppressions. ⚠️ Model cards and the effort segment are views over hidden `<select>`s, which stay the source of truth. ⚠️ `.modal-tabs*` classes are retired; `admin-ui.js` needs `.set-rail-items` + `.set-doc` to survive any restructure. Guard: `test/app-settings-structure.test.ts`. → [architecture-invariants#settings-surface-app-settings-session-options-add-case](../../docs/architecture-invariants.md#settings-surface-app-settings-session-options-add-case) diff --git a/src/web/public/app.js b/src/web/public/app.js index a11230c8..8e40dcf8 100644 --- a/src/web/public/app.js +++ b/src/web/public/app.js @@ -801,10 +801,11 @@ class CodemanApp { // the small `full=1` capture instead of the 1 MiB byte tail: see // _notePaneHistory and selectSession. this._paneHistoryLines = new Map(); // Map<sessionId, number> - // Per-session cooldown for upward-scroll history repair / top-of-buffer pulls. + // Per-session cooldown for top-of-buffer pulls; manual actions bypass it. this._fullHistoryRepullAt = new Map(); // Map<sessionId, timestamp> this._fullHistoryRepullInFlight = false; this._liveOutputSinceFullPull = new Set(); // Set<sessionId> + this._historyReloadDismissed = new Set(); // Until the next successful full mux replay this._liveOutputGen = new Map(); // Map<sessionId, number> this._earlyReplayTravel = null; // { sessionId, moves: number[] } during a content-anchored replay // Sessions whose last re-pull came back THINNER than the live buffer (a @@ -2606,10 +2607,10 @@ class CodemanApp { // it releases instead of spending every retry against the same open load. if (this._isLoadingBuffer) { if (sessionId === this.activeSessionId) { - if (this._pendingDroppedOutputRecovery !== sessionId && Number.isFinite(queuedBytes)) { + if (this._pendingDroppedOutputRecovery?.sessionId !== sessionId && Number.isFinite(queuedBytes)) { _crashDiag.log(`TERMINAL DROP: ${(queuedBytes / 1024).toFixed(0)}KB queued (recovery deferred)`); } - this._pendingDroppedOutputRecovery = sessionId; + this._pendingDroppedOutputRecovery = { sessionId, attempt }; } return; } @@ -2621,7 +2622,7 @@ class CodemanApp { // A load may have opened after this timer was armed. Defer without // advancing the attempt; _finishBufferLoad resumes only the active tab. if (this._isLoadingBuffer) { - if (sessionId === this.activeSessionId) this._pendingDroppedOutputRecovery = sessionId; + if (sessionId === this.activeSessionId) this._pendingDroppedOutputRecovery = { sessionId, attempt }; return; } let repainted = false; @@ -9614,8 +9615,8 @@ class CodemanApp { } /** - * Re-pull tmux history at the top, or on any upward scroll in a non-shell - * session marked by live output since its last mux-full-history replay. + * Re-pull tmux history automatically at the top, or explicitly from the + * history banner's Load full history / Reload history actions. * * xterm's buffer is only ever a WINDOW onto tmux's real history, and two things * shrink it. tmux repaints the pane rectangle instead of emitting linefeeds @@ -9626,9 +9627,10 @@ class CodemanApp { * everything (history-limit 100k by default), so the fix is to go ask for it with * the same `?full=1` capture a page reload uses (issue #205). * - * Gesture-triggered and cooldown/latch guarded: a synchronous capture can cost - * about 0.3 s at 100k lines and blocks the server event loop. Content anchors - * hold the reader's place even when new history fills a gap below them. + * Automatic pulls are top-only and cooldown/latch guarded: a synchronous + * capture can cost about 0.3 s at 100k lines and blocks the server event loop. + * The manual Reload history action uses a content anchor to hold the reader's + * place even when new history fills a gap below them. * * NEVER a downgrade: for a repaint-mode CLI pane tmux keeps no history of its * own, so the capture can be THINNER than what xterm already holds and the @@ -9795,6 +9797,8 @@ class CodemanApp { if (!completed || this.activeSessionId !== sessionId || selectGen !== this._selectGeneration) return; if (payload.source === 'mux-full-history' && (this._liveOutputGen?.get(sessionId) || 0) === liveOutputGen) { this._liveOutputSinceFullPull?.delete(sessionId); + this._historyReloadDismissed?.delete(sessionId); + this._syncHistoryReloadAction?.(); } // Keep shell tab restores bounded too. A user-triggered full-history pull // may be tens of MB; caching it would replay that whole payload again on @@ -9837,7 +9841,7 @@ class CodemanApp { if (!replayed) this._finishBufferLoad(loadOwner, { flushQueued: true, since: 0 }); if (anchor === 'content') this._earlyReplayTravel = null; this._fullHistoryRepullInFlight = false; - this._syncHistoryReloadButton?.(); + this._syncHistoryReloadAction?.(); } } @@ -9913,6 +9917,29 @@ class CodemanApp { this._renderHistoryTruncationBanner(); } + /** Whether the active session can offer a manual, content-anchored repair. */ + _historyReloadActionEligible() { + const sessionId = this.activeSessionId; + const session = this.sessions.get(sessionId); + // Cheap state checks first: the terminal is read only for a marked session. + return !!(this.loadAppSettingsFromStorage?.()?.historyReloadAction !== false && + session && session.mode !== 'shell' && this._liveOutputSinceFullPull?.has(sessionId) && + !this._fullHistoryRepullInFlight && !this.detachedSessions?.has(sessionId) && + !this._historyReloadDismissed?.has(sessionId) && !this._tilesOwnTerminal?.() && + !this.isTerminalAtBottom()); + } + + /** Only eligibility/session/loading transitions may rebuild the banner. */ + _syncHistoryReloadAction() { + const sessionId = this.activeSessionId; + const eligible = this._historyReloadActionEligible(); + const loading = !!sessionId && this._historyReloadActionLoadingFor === sessionId; + const last = this._historyReloadActionState; + if (last && last.sessionId === sessionId && last.eligible === eligible && last.loading === loading) return; + this._historyReloadActionState = { sessionId, eligible, loading }; + this._renderHistoryTruncationBanner(); + } + /** * Paint the partial-history banner for the active session. * @@ -9920,12 +9947,12 @@ class CodemanApp { * is gone forever" are not the same message and the old single boolean could * not tell them apart: * - recoverable → offer to load the rest - * - exhausted → say so plainly, offer nothing + * - exhausted → say so plainly * - at the limit → the full capture ITSELF hit the byte ceiling * - * Shown only while revealed (`_setHistoryNoticeRevealed`: the user scrolled - * to the top of this tab's buffer) and never again for a session whose notice - * the user dismissed on this page. + * Notices wait for a scroll to the top and respect their page-long dismissal. + * Independently, eligible marked sessions offer Reload history while reading; + * the same bar carries it without duplicating a Load full history control. */ _renderHistoryTruncationBanner() { const bar = document.getElementById('historyTruncationBar'); @@ -9933,11 +9960,12 @@ class CodemanApp { const sessionId = this.activeSessionId; const state = sessionId ? this._historyTruncation?.get(sessionId) : null; const notice = computeHistoryTruncationNotice(state || {}); - if ( - !notice.visible || - this._historyNoticeRevealedFor !== sessionId || - this._historyNoticeDismissed?.has(sessionId) - ) { + const showNotice = notice.visible && this._historyNoticeRevealedFor === sessionId && + !this._historyNoticeDismissed?.has(sessionId); + const eligible = this._historyReloadActionEligible?.() ?? false; + const loading = !!sessionId && this._historyReloadActionLoadingFor === sessionId; + this._historyReloadActionState = { sessionId, eligible, loading }; + if (!showNotice && !eligible && !loading) { bar.hidden = true; return; } @@ -9945,10 +9973,10 @@ class CodemanApp { bar.textContent = ''; const label = document.createElement('span'); label.className = 'history-trunc-text'; - label.textContent = notice.message; + label.textContent = showNotice ? notice.message : 'Recent output may be missing from this view.'; bar.appendChild(label); - if (notice.canLoadMore) { + if (showNotice && notice.canLoadMore) { const btn = document.createElement('button'); btn.type = 'button'; btn.className = 'history-trunc-load'; @@ -9962,6 +9990,23 @@ class CodemanApp { }); }; bar.appendChild(btn); + } else if (eligible || loading) { + const btn = document.createElement('button'); + btn.type = 'button'; + btn.className = 'history-trunc-load'; + btn.disabled = loading; + btn.textContent = loading ? 'Loading…' : 'Reload history'; + btn.onclick = () => { + btn.disabled = true; + btn.textContent = 'Loading…'; + this._historyReloadActionLoadingFor = sessionId; + this._syncHistoryReloadAction(); + return this._maybeRefetchFullHistory({ force: true, anchor: 'content' }).finally(() => { + if (this._historyReloadActionLoadingFor === sessionId) this._historyReloadActionLoadingFor = null; + this._syncHistoryReloadAction(); + }); + }; + bar.appendChild(btn); } const dismiss = document.createElement('button'); @@ -9970,10 +10015,12 @@ class CodemanApp { dismiss.setAttribute('aria-label', 'Dismiss history notice'); dismiss.textContent = '×'; dismiss.onclick = () => { - // Sticky for this session until the page reloads: a dismissed notice used - // to come straight back on the next tab switch. - (this._historyNoticeDismissed ||= new Set()).add(sessionId); - bar.hidden = true; + // One × dismisses everything this bar carried. A notice dismissal sticks + // for the lifetime of this page; a reload dismissal lasts until a + // successful full mux replay clears the session's mark. + if (showNotice) (this._historyNoticeDismissed ||= new Set()).add(sessionId); + if (eligible || loading) (this._historyReloadDismissed ||= new Set()).add(sessionId); + this._renderHistoryTruncationBanner(); }; bar.appendChild(dismiss); @@ -10093,7 +10140,7 @@ class CodemanApp { this.activeSessionId = sessionId; this._activateFileBrowserSession?.(sessionId); if (typeof CjkInput !== 'undefined') CjkInput.restoreDraft?.(sessionId); - this._syncHistoryReloadButton?.(); + this._syncHistoryReloadAction?.(); // A keyboard row hold belongs to the session it was taken for: release it here // if this one resizes instead (the geometry work below then fits it). this._reconcileKeyboardHold?.({ resize: false }); @@ -10481,6 +10528,8 @@ class CodemanApp { } if (fullHistoryReplay && data.source === 'mux-full-history' && completed && (this._liveOutputGen?.get(sessionId) || 0) === liveOutputGen) { this._liveOutputSinceFullPull?.delete(sessionId); + this._historyReloadDismissed?.delete(sessionId); + this._syncHistoryReloadAction?.(); } // Ensure terminal is scrolled to bottom after buffer load this.terminal.scrollToBottom(); @@ -10890,6 +10939,8 @@ class CodemanApp { this.terminalBuffers.delete(sessionId); this.terminalBufferCache.delete(sessionId); this._liveOutputSinceFullPull?.delete(sessionId); + this._historyReloadDismissed?.delete(sessionId); + this._syncHistoryReloadAction?.(); this._liveOutputGen?.delete(sessionId); this._clearHistoryTruncation(sessionId); this._xtermSnapshots?.delete(sessionId); diff --git a/src/web/public/i18n.js b/src/web/public/i18n.js index 5b768a14..790f210b 100644 --- a/src/web/public/i18n.js +++ b/src/web/public/i18n.js @@ -751,6 +751,12 @@ 'Extended Keyboard Bar': '扩展键盘栏', 'Gesture Control (beta)': '手势控制(测试版)', 'Wheel Scrolls Local History': '滚轮滚动本地历史', + 'History Reload Button': '历史重新加载按钮', + 'When scrolled up after new output, offer a Reload history action that re-reads the full tmux history (a full capture on the server).': + '有新输出后向上滚动时,提供“重新加载历史”操作,重新读取完整的 tmux 历史(在服务器上完整捕获)。', + 'Recent output may be missing from this view.': '此视图可能缺少最近的输出。', + 'Reload history': '重新加载历史', + 'Load full history': '加载完整历史', 'Auto Copy Selection': '自动复制选中内容', 'Selection & clipboard': '选中与剪贴板', 'Auto Copy: selection copied': '自动复制:已复制选中内容', diff --git a/src/web/public/index.html b/src/web/public/index.html index b2c7ec46..a38ca396 100644 --- a/src/web/public/index.html +++ b/src/web/public/index.html @@ -478,7 +478,6 @@ scrolled away with the output it described and could not be acted on. Populated by app.js _renderHistoryTruncationBanner(). --> <div class="history-trunc-bar" id="historyTruncationBar" role="status" aria-live="polite" hidden></div> - <button id="historyReloadBtn" type="button" class="history-reload-btn" aria-label="Reload history" hidden>↻ Reload history</button> <div class="terminal-container" id="terminalContainer"></div> <textarea id="cjkInput" rows="1" placeholder="CJK input (Enter = send, Esc = clear)" maxlength="65536" aria-label="CJK IME input field" @@ -2162,6 +2161,13 @@ </div> <label class="switch switch-sm"><input type="checkbox" id="appSettingsTerminalWheelLocal"><span class="slider"></span></label> </div> + <div class="set-row" data-search="history reload button repair scrollback"> + <div class="set-row-text"> + <span class="set-row-label">History Reload Button <span class="set-scope">device</span></span> + <span class="set-row-desc">When scrolled up after new output, offer a Reload history action that re-reads the full tmux history (a full capture on the server).</span> + </div> + <label class="switch switch-sm"><input type="checkbox" id="appSettingsHistoryReloadAction"><span class="slider"></span></label> + </div> <div class="set-row" id="appSettingsWebglRendererItem" data-search="webgl renderer gpu terminal"> <div class="set-row-text"> <span class="set-row-label">WebGL Renderer <span class="set-tag">desktop</span> <span class="set-scope">device</span></span> diff --git a/src/web/public/settings-ui.js b/src/web/public/settings-ui.js index 8a9f9c76..84bc29db 100644 --- a/src/web/public/settings-ui.js +++ b/src/web/public/settings-ui.js @@ -648,6 +648,8 @@ Object.assign(CodemanApp.prototype, { ); document.getElementById('appSettingsTerminalWheelLocal').checked = settings.terminalWheelLocalScrollback ?? defaults.terminalWheelLocalScrollback ?? false; + document.getElementById('appSettingsHistoryReloadAction').checked = + settings.historyReloadAction ?? defaults.historyReloadAction ?? true; document.getElementById('appSettingsCjkInput').checked = settings.cjkInputEnabled ?? defaults.cjkInputEnabled ?? false; document.getElementById('appSettingsCjkHoldUntilEnter').checked = settings.cjkInputHoldUntilEnter ?? defaults.cjkInputHoldUntilEnter ?? false; @@ -3196,6 +3198,7 @@ Object.assign(CodemanApp.prototype, { document.getElementById('appSettingsTerminalFontWeightBold') ), terminalWheelLocalScrollback: document.getElementById('appSettingsTerminalWheelLocal').checked, + historyReloadAction: document.getElementById('appSettingsHistoryReloadAction').checked, cjkInputEnabled: document.getElementById('appSettingsCjkInput').checked, cjkInputHoldUntilEnter: document.getElementById('appSettingsCjkHoldUntilEnter').checked, webglRendererEnabled: document.getElementById('appSettingsWebglRenderer').checked, @@ -3285,6 +3288,7 @@ Object.assign(CodemanApp.prototype, { this._updateLocalEchoState(); // Turning Keep Size Under Keyboard off while it holds releases it now. this._reconcileKeyboardHold?.(); + this._syncHistoryReloadAction?.(); this.applyTerminalFontFamily?.(settings.terminalFontFamily); this.applyTerminalFontWeights?.(settings); @@ -3459,6 +3463,7 @@ Object.assign(CodemanApp.prototype, { showTileGridButton: _stg, webglRendererEnabled: _wgl, terminalWheelLocalScrollback: _twls, + historyReloadAction: _hra, // Copy-on-select. Per-device (clipboard access differs by device and by // origin: the plain-HTTP LAN install has no navigator.clipboard at all) // and absent from SettingsUpdateSchema (.strict()), so sending it would @@ -4484,6 +4489,7 @@ Object.assign(CodemanApp.prototype, { cjkInputEnabled: false, cjkInputHoldUntilEnter: false, terminalWheelLocalScrollback: false, // mobile scrolls via touch, not wheel + historyReloadAction: true, webglRendererEnabled: false, // mobile always uses the DOM renderer skin: 'daylight-blue', }; @@ -5216,6 +5222,7 @@ Object.assign(CodemanApp.prototype, { 'terminalFontFamily', 'terminalFontWeight', 'terminalFontWeightBold', 'language', 'terminalWheelLocalScrollback', + 'historyReloadAction', 'autoCopySelection', 'copyStripMargin', 'showSessionButton', 'showAwayDigestButton', 'showCronButton', 'showGitStatus', 'gitStatusTree', 'gitStatusMaxRepos', 'gitStatusTimeoutSeconds', 'showEditHistory', 'showTabDetachButton', diff --git a/src/web/public/styles.css b/src/web/public/styles.css index 6da7d9de..8a08c4a9 100644 --- a/src/web/public/styles.css +++ b/src/web/public/styles.css @@ -4401,26 +4401,6 @@ html[data-tab-logos='off'] .home-sessions-harness { position: relative; } -/* Touch-only control; _syncHistoryReloadButton owns its hidden state. */ -.history-reload-btn { - position: absolute; - top: 0.5rem; - right: 0.5rem; - z-index: 20; - min-width: 44px; - min-height: 44px; - padding: 0.5rem 0.75rem; - border: 1px solid var(--border); - border-radius: 6px; - background: var(--bg-card); - color: var(--text); - touch-action: manipulation; -} - -.history-reload-btn:disabled { - opacity: 0.65; -} - /* Partial-history banner (#258). OVERLAY, not a flex child, on purpose: FitAddon derives rows/cols from the terminal parent's computed height, so a banner that occupied real layout diff --git a/src/web/public/terminal-ui.js b/src/web/public/terminal-ui.js index 74bdb175..4a6a6b10 100644 --- a/src/web/public/terminal-ui.js +++ b/src/web/public/terminal-ui.js @@ -1060,8 +1060,8 @@ Object.assign(CodemanApp.prototype, { this._predictiveEcho = typeof PredictiveEchoOverlay !== 'undefined' ? new PredictiveEchoOverlay(this.terminal) : null; this._predictiveEcho?.setPredictWhen((terminal) => window.CodemanTerminalInput.isCodexComposerRow(terminal)); + this.terminal.onScroll(() => this._scheduleHistoryReloadActionSync()); if (MobileDetection.isTouchDevice()) { - this.terminal.onScroll(() => this._syncHistoryReloadButton()); this.terminal.onCursorMove(() => this._syncMobileHelperTextareaToCursor()); this.terminal.onRender(() => this._syncMobileHelperTextareaToCursor()); // Keep the live content above the keyboard while the rows are held. @@ -4060,29 +4060,13 @@ Object.assign(CodemanApp.prototype, { return target; }, - /** Sole owner of the touch-only history reload control's visibility. */ - _syncHistoryReloadButton() { - // Touch capability does not change at runtime and desktop never shows the - // control, so non-touch pages skip the DOM work entirely. - const touch = typeof MobileDetection !== 'undefined' && MobileDetection.isTouchDevice(); - if (!touch) return; - const button = document.getElementById('historyReloadBtn'); - if (!button) return; - const sessionId = this.activeSessionId; - const session = this.sessions.get(sessionId); - const visible = !!(touch && session && session.mode !== 'shell' && - !this.isTerminalAtBottom() && this._liveOutputSinceFullPull?.has(sessionId) && - !this._tilesOwnTerminal?.() && !this._fullHistoryRepullInFlight); - if (button.hidden === visible) button.hidden = !visible; - if (this._fullHistoryRepullInFlight) return; - button.disabled = false; - button.textContent = '↻ Reload history'; - button.onclick = () => { - button.disabled = true; - button.textContent = 'Loading…'; - return Promise.resolve(this._maybeRefetchFullHistory({ force: true, anchor: 'content' })) - .finally(() => this._syncHistoryReloadButton()); - }; + /** xterm may emit once per scrolled line; sample eligibility once per frame. */ + _scheduleHistoryReloadActionSync() { + if (this._historyReloadActionFrame != null) return; + this._historyReloadActionFrame = requestAnimationFrame(() => { + this._historyReloadActionFrame = null; + this._syncHistoryReloadAction(); + }); }, /** @@ -4129,11 +4113,10 @@ Object.assign(CodemanApp.prototype, { }, /** - * After scrollLines(), repair on ANY upward gesture in a non-shell session - * marked by live output since its last mux-full-history replay (#814), using - * a content anchor to hold the reader's place. Unmarked sessions still pull - * at the top (#205); shells pull only a bounded window there. The pull owns - * cooldown/latch and downgrade guards. + * After scrollLines(), pull only at the top of the local buffer (#205). + * Shells pull a bounded window; full captures while reading require the + * explicit Reload history action (#814). The pull owns cooldown/latch and + * downgrade guards. Content-anchored replays keep session-scoped travel. * * It is also what brings up the partial-history notice, and what retires it * once a downward scroll is back at live output (_setHistoryNoticeRevealed). @@ -4151,20 +4134,14 @@ Object.assign(CodemanApp.prototype, { } if (lines === 0) return; const buffer = this.terminal?.buffer?.active; - const reachedTop = buffer?.viewportY === 0; + if (buffer?.viewportY !== 0) return; const sessionId = this.activeSessionId; - const repair = sessionId && this._liveOutputSinceFullPull?.has(sessionId) && - this.sessions.get(sessionId)?.mode !== 'shell'; - if (!repair && buffer?.viewportY !== 0) return; // An earlier frame already started a pull and owns the notice reveal. if (this._fullHistoryRepullInFlight || this._isLoadingBuffer) return; - Promise.resolve(repair - ? this._maybeRefetchFullHistory?.({ anchor: 'content' }) - : this._maybeRefetchFullHistory?.()) + Promise.resolve(this._maybeRefetchFullHistory?.()) .catch(() => {}) .then(() => { - if (sessionId && this.activeSessionId === sessionId && - (reachedTop || this.terminal?.buffer?.active?.viewportY === 0)) { + if (sessionId && this.activeSessionId === sessionId) { this._setHistoryNoticeRevealed?.(sessionId); } }); @@ -4796,9 +4773,8 @@ Object.assign(CodemanApp.prototype, { marked.add(flushSessionId); const generations = (this._liveOutputGen ||= new Map()); generations.set(flushSessionId, (generations.get(flushSessionId) || 0) + 1); - // Visibility only changes here when the mark appears; scrolling is - // covered by the touch-only onScroll hook. - if (newlyMarked) this._syncHistoryReloadButton?.(); + // Mark transitions sync immediately; onScroll is coalesced on all devices. + if (newlyMarked) this._syncHistoryReloadAction?.(); } } catch (err) { this._terminalWriteInFlight = false; @@ -5140,10 +5116,10 @@ Object.assign(CodemanApp.prototype, { this.batchTerminalWrite(entry.data); } } - const recoverySession = this._pendingDroppedOutputRecovery; + const recovery = this._pendingDroppedOutputRecovery; this._pendingDroppedOutputRecovery = null; - if (recoverySession && recoverySession === this.activeSessionId) { - this._scheduleDroppedOutputRecovery?.(recoverySession); + if (recovery && recovery.sessionId === this.activeSessionId) { + this._scheduleDroppedOutputRecovery?.(recovery.sessionId, recovery.attempt); } return true; }, diff --git a/test/history-gap-repair.browser.test.ts b/test/history-gap-repair.browser.test.ts index de00fef5..1eb32403 100644 --- a/test/history-gap-repair.browser.test.ts +++ b/test/history-gap-repair.browser.test.ts @@ -1,4 +1,4 @@ -/** Real xterm + trusted phone gestures recover tmux repaint gaps while reading (#814). */ +/** Real xterm + manual banner actions recover tmux repaint gaps while reading (#814). */ import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import { chromium, type Browser, type BrowserContext, type Page } from 'playwright'; import type { Terminal } from '@xterm/xterm'; @@ -29,7 +29,11 @@ type HistoryApp = { _lastResizeDims: { cols: number; rows: number } | null; _syncStickyScrollBaseline(): void; _captureViewportAnchor(): Anchor; - _syncHistoryReloadButton(): void; + _syncHistoryReloadAction(): void; + loadAppSettingsFromStorage(): Record<string, unknown>; + saveAppSettingsToStorage(settings: Record<string, unknown>): void; + _setHistoryTruncation(sessionId: string, payload: Record<string, unknown>): void; + _setHistoryNoticeRevealed(sessionId: string): void; }; type RepairWindow = Window & { app: HistoryApp; @@ -331,20 +335,29 @@ async function waitForRepair(page: Page): Promise<void> { const allNumbers = Array.from({ length: 144 }, (_, i) => `NUMBER-${String(i).padStart(3, '0')}`); -describe('history gap repair on phones', () => { - it('repairs from mid-history after a real upward scroll and holds the content anchor', async () => { - const { context, page } = await openTerminal(true); +describe.each([true, false])('manual history gap repair (touch: %s)', (touch) => { + async function readHistory(page: Page) { + if (touch) await scrollHistoryByTouch(page, 100); + else await page.evaluate(() => (window as RepairWindow).app.terminal.scrollToLine(10)); + const position = await page.evaluate(() => { + const b = (window as RepairWindow).app.terminal.buffer.active; + return { viewportY: b.viewportY, baseY: b.baseY }; + }); + expect(position.viewportY).toBeGreaterThan(0); + expect(position.baseY - position.viewportY).toBeGreaterThan(5); + } + + it('repairs mid-history only on a banner tap/click and holds the reading line offset', async () => { + const { context, page } = await openTerminal(touch); try { - await scrollHistoryByTouch(page, 100); - const position = await page.evaluate(() => { - const b = (window as RepairWindow).app.terminal.buffer.active; - return { viewportY: b.viewportY, baseY: b.baseY }; - }); - expect(position.viewportY).toBeGreaterThan(0); - expect(position.baseY - position.viewportY).toBeGreaterThan(5); + await readHistory(page); await burst(page); expect((await bufferState(page)).numbers).not.toContain('NUMBER-090'); - await scrollHistoryByTouch(page, 40); + expect((await bufferState(page)).pulls).toBe(0); + const button = page.locator('#historyTruncationBar').getByRole('button', { name: 'Reload history' }); + await button.waitFor({ state: 'visible' }); + if (touch) await button.tap(); + else await button.click(); await waitForRepair(page); const state = await bufferState(page); expect(state.numbers).toEqual(allNumbers); @@ -358,14 +371,16 @@ describe('history gap repair on phones', () => { }, 60_000); it('keeps output arriving during the capture download exactly once', async () => { - const { context, page } = await openTerminal(true); + const { context, page } = await openTerminal(touch); try { - await scrollHistoryByTouch(page, 100); + await readHistory(page); await burst(page); await page.evaluate(() => { (window as RepairWindow).repairTest.inject = true; }); - await scrollHistoryByTouch(page, 40); + const button = page.locator('#historyTruncationBar').getByRole('button', { name: 'Reload history' }); + if (touch) await button.tap(); + else await button.click(); await waitForRepair(page); const state = await bufferState(page); const detail = JSON.stringify({ state, events: pageEvents.get(page) }); @@ -378,69 +393,71 @@ describe('history gap repair on phones', () => { } }, 60_000); - it('offers a touch reload while reading and tapping it recovers the missing rows', async () => { - const { context, page } = await openTerminal(true); - try { - await scrollHistoryByTouch(page, 100); - await burst(page); - const button = page.getByRole('button', { name: 'Reload history' }); - await button.waitFor({ state: 'visible' }); - const box = await button.boundingBox(); - expect(box!.height).toBeGreaterThanOrEqual(44); - expect(box!.width).toBeGreaterThanOrEqual(44); - await button.tap(); - await waitForRepair(page); - const state = await bufferState(page); - expect(state.numbers).toEqual(allNumbers); - expect(state.anchorOffset).toBe(state.expectedOffset); - expect(await button.isVisible()).toBe(false); - } catch (error) { - throw await failureDetails(page, error); - } finally { - await context.close(); - } - }, 60_000); + it.each([false, true])( + 'keeps the revealed notice and one unobstructed load control (exhausted: %s)', + async (exhausted) => { + const { context, page } = await openTerminal(touch); + try { + await readHistory(page); + await burst(page); + await page.evaluate( + ({ session, exhausted }) => { + const app = (window as RepairWindow).app; + app._setHistoryTruncation(session, { + truncated: true, + truncationReason: 'tail', + source: 'mux-full-history', + fullSize: 2 * 1024 * 1024, + retainedBytes: 1024 * 1024, + paneHistoryLines: 121, + exhausted, + }); + app._setHistoryNoticeRevealed(session); + }, + { session: SESSION, exhausted } + ); + const bar = page.locator('#historyTruncationBar'); + await bar.waitFor({ state: 'visible' }); + expect(await bar.locator('.history-trunc-text').textContent()).not.toBe( + 'Recent output may be missing from this view.' + ); + const button = bar.locator('.history-trunc-load'); + expect(await button.count()).toBe(1); + expect(await button.textContent()).toBe(exhausted ? 'Reload history' : 'Load full history'); + for (const control of await bar.getByRole('button').all()) { + expect( + await control.evaluate((element) => { + const box = element.getBoundingClientRect(); + return document.elementFromPoint(box.x + box.width / 2, box.y + box.height / 2) === element; + }) + ).toBe(true); + } + } catch (error) { + throw await failureDetails(page, error); + } finally { + await context.close(); + } + }, + 60_000 + ); - it('floats a 44px reload control on wide touch viewports without resizing the terminal', async () => { - const { context, page } = await openTerminal(true, { width: 1280, height: 800 }); + it('does not offer a reload action when disabled on this device', async () => { + const { context, page } = await openTerminal(touch); try { await page.evaluate(() => { - (window as RepairWindow).app.terminal.scrollToLine(10); + const app = (window as RepairWindow).app; + app.saveAppSettingsToStorage({ ...app.loadAppSettingsFromStorage(), historyReloadAction: false }); + app._syncHistoryReloadAction(); }); - const dimensions = () => - page.evaluate(() => { - const terminal = (window as RepairWindow).app.terminal; - const box = document.getElementById('terminalContainer')!.getBoundingClientRect(); - return { width: box.width, height: box.height, cols: terminal.cols, rows: terminal.rows }; - }); - const before = await dimensions(); - expect(await page.locator('#historyReloadBtn').isVisible()).toBe(false); + await readHistory(page); await burst(page); - const button = page.getByRole('button', { name: 'Reload history' }); - await button.waitFor({ state: 'visible' }); - expect(await button.evaluate((element) => getComputedStyle(element).position)).toBe('absolute'); - const box = await button.boundingBox(); - expect(box!.height).toBeGreaterThanOrEqual(44); - expect(box!.width).toBeGreaterThanOrEqual(44); - expect(await dimensions()).toEqual(before); - } catch (error) { - throw await failureDetails(page, error); - } finally { - await context.close(); - } - }, 60_000); - - it('never shows the reload control in a non-touch context', async () => { - const { context, page } = await openTerminal(false); - try { + // Wait for the same coalesced scroll synchronization used in production. await page.evaluate(() => { - (window as RepairWindow).app.terminal.scrollToLine(10); + const { promise, resolve } = Promise.withResolvers<void>(); + requestAnimationFrame(() => requestAnimationFrame(() => resolve())); + return promise; }); - await burst(page); - await page.evaluate(() => { - (window as RepairWindow).app._syncHistoryReloadButton(); - }); - expect(await page.locator('#historyReloadBtn').isVisible()).toBe(false); + expect(await page.getByRole('button', { name: 'Reload history' }).isVisible()).toBe(false); expect((await bufferState(page)).pulls).toBe(0); } catch (error) { throw await failureDetails(page, error); diff --git a/test/history-notice-reveal.test.ts b/test/history-notice-reveal.test.ts index 6b749f63..1607244e 100644 --- a/test/history-notice-reveal.test.ts +++ b/test/history-notice-reveal.test.ts @@ -186,28 +186,33 @@ describe('partial-history notice: lazy reveal', () => { expect(loadButton(bar)?.textContent).toBe('Load full history'); }); - it.each([ - { viewportY: 0, revealed: true }, - { viewportY: 200, revealed: false }, - ])( - 'retains the initiating top state through a marked repair from row $viewportY', - async ({ viewportY, revealed }) => { - const { app, bar, buffer } = makeApp(); - app._setHistoryTruncation('s1', TAIL); - app._liveOutputSinceFullPull.add('s1'); - app._maybeRefetchFullHistory.mockImplementation(async () => { - app._setHistoryTruncation('s1', { ...TAIL, source: 'mux-full-history' }); - buffer.viewportY = 100; // The content anchor restored the old top below recovered rows. - }); - buffer.viewportY = viewportY; - app._maybeLoadMoreHistoryOnScroll(-5); - for (let i = 0; i < 5; i++) await Promise.resolve(); - expect(app._maybeRefetchFullHistory).toHaveBeenCalledOnce(); - expect(app._maybeRefetchFullHistory).toHaveBeenCalledWith({ anchor: 'content' }); - expect(bar.hidden).toBe(!revealed); - if (revealed) expect(loadButton(bar)?.textContent).toBe('Load full history'); - } - ); + it.each([0, 200])('marked scrolling from row %s remains top-only', async (viewportY) => { + const { app, bar, buffer, settle } = makeApp(); + app._setHistoryTruncation('s1', TAIL); + app._liveOutputSinceFullPull.add('s1'); + buffer.viewportY = viewportY; + app._maybeLoadMoreHistoryOnScroll(-5); + await settle(); + expect(app._maybeRefetchFullHistory).toHaveBeenCalledTimes(viewportY === 0 ? 1 : 0); + if (viewportY === 0) expect(app._maybeRefetchFullHistory).toHaveBeenCalledWith(); + expect(bar.hidden).toBe(viewportY !== 0); + }); + + it('reveals the resulting notice when a top pull grows the buffer and restores below row zero', async () => { + const { app, bar, buffer } = makeApp(); + app._setHistoryTruncation('s1', TAIL); + app._maybeRefetchFullHistory.mockImplementation(async () => { + buffer.baseY += 100; + buffer.viewportY = 100; // Recovered rows precede the old top reading position. + }); + buffer.viewportY = 0; + app._maybeLoadMoreHistoryOnScroll(-500); + for (let i = 0; i < 5; i++) await Promise.resolve(); + expect(buffer.viewportY).toBe(100); + expect(app._historyNoticeRevealedFor).toBe('s1'); + expect(bar.hidden).toBe(false); + expect(loadButton(bar)?.textContent).toBe('Load full history'); + }); it('a later frame of the same gesture does not flash the pre-pull state while the pull runs', async () => { const { app, bar, buffer } = makeApp(); diff --git a/test/settings-admin-only-ui.test.ts b/test/settings-admin-only-ui.test.ts index 16d1480e..8bb83474 100644 --- a/test/settings-admin-only-ui.test.ts +++ b/test/settings-admin-only-ui.test.ts @@ -182,6 +182,45 @@ async function boot(who: Who, stored: Settings, server: Settings | null) { // What the server already holds for this instance: an admin has saved App Settings before. const SERVER: Settings = { autoNameSessions: false, workspaceHooksEnabled: true, claudeMode: 'auto' }; +describe('the per-device History Reload Button setting', () => { + it.each(['non-admin', 'admin', 'single-user'] as const)( + '%s saves locally and never sends the device key', + async (who) => { + const { app, target, box, storedBlob } = await boot(who, { ...SERVER }, SERVER); + target._syncHistoryReloadAction = vi.fn(); + await open_(app); + expect(box('appSettingsHistoryReloadAction').checked).toBe(true); + expect(app._displaySettingKeySet().has('historyReloadAction')).toBe(true); + box('appSettingsHistoryReloadAction').checked = false; + await app.saveAppSettings(); + expect(storedBlob().historyReloadAction).toBe(false); + expect(target._syncHistoryReloadAction).toHaveBeenCalledOnce(); + if (who === 'non-admin') expect(target._apiPut).not.toHaveBeenCalled(); + else { + const [path, body] = target._apiPut.mock.calls[0] as [string, Settings]; + expect(path).toBe('/api/settings'); + expect(body).not.toHaveProperty('historyReloadAction'); + expect(SettingsUpdateSchema.safeParse(body).error?.issues ?? []).toEqual([]); + } + await open_(app); + expect(box('appSettingsHistoryReloadAction').checked).toBe(false); + } + ); + + it('preserves the local choice when another device saved a different value', async () => { + const { app, box, storedBlob } = await boot('admin', { historyReloadAction: false }, { historyReloadAction: true }); + await open_(app); + expect(box('appSettingsHistoryReloadAction').checked).toBe(false); + expect(storedBlob().historyReloadAction).toBe(false); + }); + + it('also defaults to enabled on handheld devices', async () => { + const { app, win } = await boot('admin', {}, {}); + win.eval('MobileDetection.isHandheldDevice = () => true;'); + expect(app.getDefaultSettings().historyReloadAction).toBe(true); + }); +}); + describe('a non-admin in multi-user mode saving App Settings', () => { it('keeps the per-device keys, sends no PUT, keeps the synced key at the server value, and toasts once', async () => { const { app, target, box, storedBlob, toasts, puts } = await boot('non-admin', { ...SERVER }, SERVER); diff --git a/test/shell-scroll-history-pull.test.ts b/test/shell-scroll-history-pull.test.ts index 85d9fdd0..da9b9800 100644 --- a/test/shell-scroll-history-pull.test.ts +++ b/test/shell-scroll-history-pull.test.ts @@ -288,7 +288,7 @@ describe('shell scroll-up pulls a bounded window of tmux history', () => { }); }); -describe('early full-history recovery above live output (#814)', () => { +describe('manual full-history recovery while reading (#814)', () => { function makeScrollApp(mode = 'omp') { const { app: base, urls } = makeApp(mode, { bufferRows: 130, capture: lines(400) }); const app = Object.assign(base, { @@ -348,29 +348,20 @@ describe('early full-history recovery above live output (#814)', () => { }); return { ready, release }; } - return { app, active, urls, liveOutput, scroll, pauseReplay }; + const reload = () => app._maybeRefetchFullHistory({ force: true, anchor: 'content' }); + return { app, active, urls, liveOutput, scroll, reload, pauseReplay }; } - it('pulls on the first upward scroll after live output and preserves distance from the new bottom', async () => { + it('never pulls mid-history after live output, but still pulls at the top', async () => { const { app, active, urls, liveOutput, scroll } = makeScrollApp(); liveOutput(); await scroll(-5); + expect(urls).toEqual([]); + expect(app._liveOutputSinceFullPull.has('s1')).toBe(true); + await scroll(-active.viewportY); expect(urls).toEqual(['/api/sessions/s1/terminal?full=1']); - expect(app.chunkedTerminalWrite).toHaveBeenCalledWith( - expect.any(String), - 32 * 1024, - expect.stringMatching(/^buffer-/), - expect.objectContaining({ flushQueued: true }) - ); - expect(active.viewportY).toBe(365); - expect(active.baseY - active.viewportY).toBe(5); + expect(app._maybeRefetchFullHistory).toHaveBeenCalledWith(); expect(app._liveOutputSinceFullPull.has('s1')).toBe(false); - expect(app._syncStickyScrollBaseline).toHaveBeenCalledOnce(); - // No second early pull until another live write dirties this session. - active.viewportY = active.baseY; - app._fullHistoryRepullAt.clear(); - await scroll(-3); - expect(urls).toHaveLength(1); }); it.each([ @@ -381,10 +372,11 @@ describe('early full-history recovery above live output (#814)', () => { { moves: [20, -12], distance: 12 }, { moves: [-1000, 30], distance: 340 }, ])('replays travel $moves made during an unfinished replay, clamped per move', async ({ moves, distance }) => { - const { app, active, liveOutput, scroll, pauseReplay } = makeScrollApp(); + const { app, active, liveOutput, reload, pauseReplay } = makeScrollApp(); liveOutput(); + active.viewportY -= 5; // Read five rows above live output before the manual action. const paused = pauseReplay(); - const pull = scroll(-5); + const pull = reload(); await paused.ready; // The temporary reset buffer cannot scroll, but the gesture still counts. for (const move of moves) (mixin._maybeLoadMoreHistoryOnScroll as Function).call(app, move); @@ -396,7 +388,7 @@ describe('early full-history recovery above live output (#814)', () => { }); it('queues download-time output and replays it through batchTerminalWrite after the capture', async () => { - const { app, urls, liveOutput, scroll } = makeScrollApp(); + const { app, urls, liveOutput, reload } = makeScrollApp(); liveOutput(); const fetchCapture = app._fetchTerminalCapture.getMockImplementation()!; const { promise, resolve: release } = Promise.withResolvers<void>(); @@ -406,7 +398,7 @@ describe('early full-history recovery above live output (#814)', () => { await promise; return capture; }); - const pull = scroll(-5); + const pull = reload(); loadAppMethod('_onSessionTerminal').call(app, { id: 's1', data: 'download-time output' }); expect(app._loadBufferQueue).toEqual([expect.objectContaining({ data: 'download-time output' })]); release(); @@ -420,12 +412,12 @@ describe('early full-history recovery above live output (#814)', () => { expect(app._liveOutputSinceFullPull.has('s1')).toBe(true); }); - it('keeps live output flushed before the final restore dirty for the next early pull', async () => { - const { app, active, urls, liveOutput, scroll, pauseReplay } = makeScrollApp(); + it('keeps live output flushed before the final restore dirty for the next manual pull', async () => { + const { app, active, urls, liveOutput, reload, pauseReplay } = makeScrollApp(); liveOutput(); const generation = app._liveOutputGen.get('s1'); const paused = pauseReplay(liveOutput); - const pull = scroll(-5); + const pull = reload(); await paused.ready; paused.release(); await pull; @@ -433,7 +425,7 @@ describe('early full-history recovery above live output (#814)', () => { expect(app._liveOutputSinceFullPull.has('s1')).toBe(true); app._fullHistoryRepullAt.clear(); active.viewportY = active.baseY; - await scroll(-3); + await reload(); expect(urls).toEqual(['/api/sessions/s1/terminal?full=1', '/api/sessions/s1/terminal?full=1']); expect(app._liveOutputSinceFullPull.has('s1')).toBe(false); }); @@ -464,37 +456,29 @@ describe('early full-history recovery above live output (#814)', () => { expect(app._liveOutputSinceFullPull.size).toBe(0); }); - it('repairs while already reading mid-history, but never on downward travel', async () => { - const { app, active, urls, liveOutput, scroll } = makeScrollApp(); + it('keeps marked mid-history travel local in either direction', async () => { + const { active, urls, liveOutput, scroll } = makeScrollApp(); liveOutput(); active.viewportY = 50; await scroll(-5); - expect(urls).toHaveLength(1); - expect(app._maybeRefetchFullHistory).toHaveBeenCalledWith({ anchor: 'content' }); - app._fullHistoryRepullAt.clear(); - liveOutput(); await scroll(3); - expect(urls).toHaveLength(1); + expect(urls).toEqual([]); }); it.each(['_isLoadingBuffer', '_fullHistoryRepullInFlight'] as const)('respects the %s guard', async (guard) => { - const { app, urls, liveOutput, scroll } = makeScrollApp(); + const { app, urls, liveOutput, reload } = makeScrollApp(); liveOutput(); app[guard] = true; - await scroll(-5); + await reload(); expect(urls).toEqual([]); }); - it('keeps the cooldown and downgrade guard on an early pull', async () => { - const { app, active, urls, liveOutput, scroll } = makeScrollApp(); + it('bypasses the cooldown for manual reload but keeps the downgrade guard', async () => { + const { app, active, urls, liveOutput, reload } = makeScrollApp(); liveOutput(); app._fullHistoryRepullAt.set('s1', Date.now()); - await scroll(-3); - expect(urls).toEqual([]); - app._fullHistoryRepullAt.clear(); - active.viewportY = active.baseY; active.length = 1000; - await scroll(-3); + await reload(); expect(urls).toHaveLength(1); expect(app._resetTerminalForReplay).not.toHaveBeenCalled(); expect(app._liveOutputSinceFullPull.has('s1')).toBe(true); @@ -598,17 +582,43 @@ describe('early full-history recovery above live output (#814)', () => { } ); + it.each([false, true])('resumes a deferred recovery at its saved attempt (timer armed: %s)', async (armed) => { + vi.useFakeTimers(); + try { + const { app } = makeApp('omp', { bufferRows: 30, capture: lines(400) }); + const retry = vi.fn(() => false); + const schedule = loadAppMethod('_scheduleDroppedOutputRecovery', { + setTimeout, + window: { CodemanDroppedOutput: { DROP_RECOVERY_DELAY_MS: 2000, shouldRetryDroppedOutputRecovery: retry } }, + }); + Object.assign(app, { + _scheduleDroppedOutputRecovery: (...args: unknown[]) => schedule.apply(app, args), + _onSessionNeedsRefresh: vi.fn(async () => false), + }); + if (armed) schedule.call(app, 's1', 3); + const owner = (app._beginBufferLoad as Function).call(app); + if (armed) await vi.advanceTimersByTimeAsync(2000); + else schedule.call(app, 's1', 3); + expect(Reflect.get(app, '_pendingDroppedOutputRecovery')).toEqual({ sessionId: 's1', attempt: 3 }); + app._finishBufferLoad(owner); + await vi.advanceTimersByTimeAsync(2000); + expect(retry).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ attempt: 3 })); + } finally { + vi.useRealTimers(); + } + }); + it('does not resume a deferred recovery for a tab that is no longer active', () => { const { app } = makeApp('omp', { bufferRows: 30, capture: lines(400) }); const owner = (app._beginBufferLoad as Function).call(app); - Object.assign(app, { _pendingDroppedOutputRecovery: 's1', activeSessionId: 's2' }); + Object.assign(app, { _pendingDroppedOutputRecovery: { sessionId: 's1', attempt: 3 }, activeSessionId: 's2' }); app._finishBufferLoad(owner); expect(app._scheduleDroppedOutputRecovery).not.toHaveBeenCalled(); expect(Reflect.get(app, '_pendingDroppedOutputRecovery')).toBeNull(); }); it.each(['mux-full-history', 'history'])('clears the scroll-pull mark only for a mux capture: %s', async (source) => { - const { app, liveOutput, scroll } = makeScrollApp(); + const { app, liveOutput, reload } = makeScrollApp(); liveOutput(); const fetchCapture = app._fetchTerminalCapture.getMockImplementation()!; app._fetchTerminalCapture.mockImplementationOnce(async (url) => { @@ -616,15 +626,15 @@ describe('early full-history recovery above live output (#814)', () => { capture.json.data.source = source; return capture; }); - await scroll(-5); + await reload(); expect(app._liveOutputSinceFullPull.has('s1')).toBe(source !== 'mux-full-history'); }); it('does not swallow another tab’s travel or clear the old mark when replay is cancelled', async () => { - const { app, active, liveOutput, scroll, pauseReplay } = makeScrollApp(); + const { app, active, liveOutput, reload, pauseReplay } = makeScrollApp(); liveOutput(); const paused = pauseReplay(); - const pull = scroll(-5); + const pull = reload(); await paused.ready; app.activeSessionId = 's2'; app._selectGeneration++; @@ -906,62 +916,211 @@ describe('content anchors hold the reader through a history repair', () => { }); }); -describe('touch history reload control', () => { - function fixture({ - touch = true, - mode = 'omp', - bottom = false, - marked = true, - inFlight = false, - tiles = false, - active = true, - } = {}) { - const button = { hidden: true, disabled: false, textContent: '', onclick: null as (() => void) | null }; - const ui = loadTerminalMixin({ - MobileDetection: { isTouchDevice: () => touch }, - document: { addEventListener: vi.fn(), getElementById: () => button }, - }); - const app = { - activeSessionId: active ? 's1' : null, - sessions: new Map([['s1', { mode }]]), - isTerminalAtBottom: () => bottom, - _liveOutputSinceFullPull: new Set(marked ? ['s1'] : []), - _fullHistoryRepullInFlight: inFlight, - _tilesOwnTerminal: () => tiles, - _maybeRefetchFullHistory: vi.fn(async (_opts: object) => {}), - _syncHistoryReloadButton: () => (ui._syncHistoryReloadButton as Function).call(app), +describe('manual history banner action', () => { + type BannerElement = { + hidden: boolean; + disabled: boolean; + textContent: string; + className: string; + type: string; + children: BannerElement[]; + onclick: (() => Promise<void> | void) | null; + appendChild(child: BannerElement): void; + setAttribute: Function; + }; + function fixture(options: Record<string, unknown> = {}) { + const state = { + touch: true, + mode: 'omp', + bottom: false, + marked: true, + inFlight: false, + tiles: false, + active: true, + detached: false, + enabled: true, + ...options, }; - return { app, button }; + const element = (): BannerElement => ({ + hidden: true, + disabled: false, + textContent: '', + className: '', + type: '', + children: [], + onclick: null, + appendChild(child) { + this.children.push(child); + }, + setAttribute: vi.fn(), + }); + const bar = element(); + const frames: FrameRequestCallback[] = []; + const document = { addEventListener: vi.fn(), getElementById: () => bar, createElement: element }; + const ui = loadTerminalMixin({ + document, + MobileDetection: { isTouchDevice: () => state.touch }, + requestAnimationFrame: (callback: FrameRequestCallback) => frames.push(callback), + }); + const { app: base } = makeApp(String(state.mode), { bufferRows: 130, capture: lines(400) }); + const render = loadAppMethod('_renderHistoryTruncationBanner', { + document, + computeHistoryTruncationNotice: computeNotice, + }); + const app = Object.assign(base, { + activeSessionId: state.active ? 's1' : '', + isTerminalAtBottom: () => state.bottom, + loadAppSettingsFromStorage: () => ({ historyReloadAction: state.enabled }), + _liveOutputSinceFullPull: new Set(state.marked ? ['s1'] : []), + _historyReloadDismissed: new Set<string>(), + _historyNoticeDismissed: new Set<string>(), + _historyNoticeRevealedFor: null as string | null, + _fullHistoryRepullInFlight: Boolean(state.inFlight), + detachedSessions: new Set(state.detached ? ['s1'] : []), + _tilesOwnTerminal: () => state.tiles, + _maybeRefetchFullHistory: vi.fn(async (_opts: object) => {}), + _historyReloadActionEligible: () => loadAppMethod('_historyReloadActionEligible').call(app), + _syncHistoryReloadAction: () => loadAppMethod('_syncHistoryReloadAction').call(app), + _scheduleHistoryReloadActionSync: () => (ui._scheduleHistoryReloadActionSync as Function).call(app), + _renderHistoryTruncationBanner: vi.fn(() => { + bar.children = []; + render.call(app); + }), + }); + const button = () => bar.children.find((child) => child.className === 'history-trunc-load'); + const dismiss = () => bar.children.find((child) => child.className === 'history-trunc-dismiss'); + return { app, bar, button, dismiss, state, frames }; } it.each([ { opts: {}, visible: true }, - { opts: { touch: false }, visible: false }, + { opts: { touch: false }, visible: true }, + { opts: { enabled: false }, visible: false }, { opts: { mode: 'shell' }, visible: false }, { opts: { bottom: true }, visible: false }, { opts: { marked: false }, visible: false }, { opts: { inFlight: true }, visible: false }, { opts: { tiles: true }, visible: false }, { opts: { active: false }, visible: false }, + { opts: { detached: true }, visible: false }, ])('visibility is $visible for $opts', ({ opts, visible }) => { - const { app, button } = fixture(opts); - app._syncHistoryReloadButton(); - expect(button.hidden).toBe(!visible); + const { app, bar, button } = fixture(opts); + app._syncHistoryReloadAction(); + expect(bar.hidden).toBe(!visible); + if (visible) expect(button()?.textContent).toBe('Reload history'); }); - it('forces a content-anchored pull on tap and resets the loading state on settle', async () => { + it('forces a content-anchored pull on tap and resets loading on settle', async () => { const { app, button } = fixture(); const { promise, resolve: release } = Promise.withResolvers<void>(); app._maybeRefetchFullHistory.mockReturnValueOnce(promise); - app._syncHistoryReloadButton(); - const tapped = button.onclick!(); + app._syncHistoryReloadAction(); + const tapped = button()!.onclick!(); expect(app._maybeRefetchFullHistory).toHaveBeenCalledWith({ force: true, anchor: 'content' }); - expect(button.disabled).toBe(true); - expect(button.textContent).toBe('Loading…'); + expect(button()!.disabled).toBe(true); + expect(button()!.textContent).toBe('Loading…'); release(); await tapped; - expect(button.disabled).toBe(false); - expect(button.textContent).toBe('↻ Reload history'); + expect(button()!.disabled).toBe(false); + expect(button()!.textContent).toBe('Reload history'); + }); + + it.each(['recoverable', 'exhausted', 'capped'])('never duplicates the %s notice load control', (kind) => { + const { app, bar, button } = fixture(); + app._historyNoticeRevealedFor = 's1'; + app._setHistoryTruncation('s1', { + ...TAIL_CUT, + exhausted: kind === 'exhausted', + truncationReason: kind === 'capped' ? 'capped' : 'tail', + }); + expect(bar.children.filter((child) => child.className === 'history-trunc-load')).toHaveLength(1); + expect(button()!.textContent).toBe(kind === 'recoverable' ? 'Load full history' : 'Reload history'); + }); + + it('does no DOM work without a transition and coalesces all-device onScroll calls per frame', () => { + const { app, state, frames } = fixture({ touch: false }); + let onScroll!: () => void; + const source = readFileSync(resolve(PUBLIC, 'terminal-ui.js'), 'utf8'); + const registration = source.match(/^ this\.terminal\.onScroll\(.*$/m)![0]; + vm.runInNewContext(`(function () { ${registration} }).call(app)`, { + app: { + terminal: { + onScroll: (callback: () => void) => { + onScroll = callback; + }, + }, + _scheduleHistoryReloadActionSync: app._scheduleHistoryReloadActionSync, + }, + }); + app._syncHistoryReloadAction(); + for (let i = 0; i < 100; i++) onScroll(); + expect(frames).toHaveLength(1); + frames.shift()!(0); + expect(app._renderHistoryTruncationBanner).toHaveBeenCalledOnce(); + state.bottom = true; + onScroll(); + onScroll(); + expect(frames).toHaveLength(1); + frames.shift()!(1); + expect(app._renderHistoryTruncationBanner).toHaveBeenCalledTimes(2); + app._syncHistoryReloadAction(); + expect(app._renderHistoryTruncationBanner).toHaveBeenCalledTimes(2); + app.activeSessionId = 's2'; + app._syncHistoryReloadAction(); + expect(app._renderHistoryTruncationBanner).toHaveBeenCalledTimes(3); + }); + + it.each(['mux-full-history', 'history'])('dismisses reload until an actual full mux replay: %s', async (source) => { + const { app, bar, dismiss, state } = fixture(); + app._syncHistoryReloadAction(); + dismiss()!.onclick!(); + expect(bar.hidden).toBe(true); + expect(app._historyNoticeDismissed.size).toBe(0); + state.bottom = true; + app._syncHistoryReloadAction(); + state.bottom = false; + app._syncHistoryReloadAction(); + expect(bar.hidden).toBe(true); + const capture = app._fetchTerminalCapture.getMockImplementation()!; + app._fetchTerminalCapture.mockImplementationOnce(async (url) => { + const result = await capture(url); + result.json.data.source = source; + return result; + }); + await refetch.call(app, { force: true }); + expect(app._historyReloadDismissed.has('s1')).toBe(source !== 'mux-full-history'); + app._liveOutputSinceFullPull.add('s1'); + app._syncHistoryReloadAction(); + expect(bar.hidden).toBe(source !== 'mux-full-history'); + }); + + it('one × on a combined notice dismisses both, and scroll frames keep the bar hidden', () => { + const { app, bar, button, dismiss, frames } = fixture(); + app._historyNoticeRevealedFor = 's1'; + app._setHistoryTruncation('s1', { ...TAIL_CUT, exhausted: true, truncationReason: 'tail' }); + expect(button()!.textContent).toBe('Reload history'); + dismiss()!.onclick!(); + expect(bar.hidden).toBe(true); + expect(app._historyNoticeDismissed.has('s1')).toBe(true); + expect(app._historyReloadDismissed.has('s1')).toBe(true); + app._scheduleHistoryReloadActionSync(); + frames.shift()!(0); + expect(bar.hidden).toBe(true); + }); + + it('dismissing a notice that carried no reload action lets a later eligible action show', () => { + const { app, bar, button, dismiss, state } = fixture({ marked: false }); + app._historyNoticeRevealedFor = 's1'; + app._setHistoryTruncation('s1', { ...TAIL_CUT, exhausted: true, truncationReason: 'tail' }); + expect(button()).toBeUndefined(); + dismiss()!.onclick!(); + expect(bar.hidden).toBe(true); + expect(app._historyReloadDismissed.has('s1')).toBe(false); + state.marked = true; + app._liveOutputSinceFullPull.add('s1'); + app._syncHistoryReloadAction(); + expect(bar.hidden).toBe(false); + expect(button()!.textContent).toBe('Reload history'); }); }); From 9ef47aca6cba95ecace6ad4e93425f0bef9010e2 Mon Sep 17 00:00:00 2001 From: Hadrien Kerlero <199662351+HadrienKerlero@users.noreply.github.com> Date: Mon, 16 Nov 2026 22:54:39 +0100 Subject: [PATCH 05/23] fix(web): retire refused Reload history and hold the reading row (#814) - Reload history requires pane history and no buffer load in flight; a downgrade-refused pull hides it until the next mux-full-history replay, and a stale tap re-checks eligibility before fetching. - x during Loading... hides the bar at once; the pull continues. - The content anchor scores up to 64 visible rows, so repeated TUI borders cannot outvote the row being read; ambiguous matches keep the viewport. - Live flushes track the reading row with an xterm marker across scrollback trimming at the cap. - Docs: Settings-Reference row, Dashboard notice text, ~1 s capture cost, byte-history replays rely on the top-of-buffer pull. --- docs/architecture-invariants.md | 4 +- docs/wiki/Settings-Reference.md | 1 + docs/wiki/The-Dashboard.md | 9 +- src/web/public/app.js | 15 ++- src/web/public/terminal-ui.js | 99 ++++++++++++------ test/history-gap-repair.browser.test.ts | 117 ++++++++++++++++++++++ test/shell-scroll-history-pull.test.ts | 127 ++++++++++++++++++++++-- 7 files changed, 322 insertions(+), 50 deletions(-) diff --git a/docs/architecture-invariants.md b/docs/architecture-invariants.md index 750caa8d..92fa804a 100644 --- a/docs/architecture-invariants.md +++ b/docs/architecture-invariants.md @@ -251,9 +251,9 @@ Further detail: the `<prefix>: <title>` form (`w3-myapp: fix the login redirect` ### Full-scrollback replay -**Full-scrollback replay** (COD-164/#148, reworked for #205): `GET /api/sessions/:id/terminal?full=1` returns the ENTIRE tmux scrollback (capture-pane `-e -S -<lines>` bounded by the configured history limit, explicit `maxBuffer` from the terminal-history config, early byte-cap before normalization, CRLF-normalized for shell panes). On success the capture is returned ALONE (`source='mux-full-history'` — it supersedes the byte buffer; no duplication). The first load of each non-shell TUI session per page requests `full=1` (`_fullHistoryLoaded` Set in app.js — the old one-shot `_initialFullBufferLoad` flag was consumed by whichever tab auto-selected, leaving every other TUI tab one frame of history). Shell sessions instead load a bounded window of tmux's RENDERED history on every selection, automatic drop recovery, clear and tile load (`SHELL_LOAD_QUERY` in constants.js: `?full=1&tail=1MiB&lines=10000&alt=recording`): a 100k-line shell capture can be tens of MiB, and automatically parsing it makes tab-switch latency scale with the entire session (`lines=` bounds the synchronous capture-pane, about 8 ms per 1000 lines). They never replay the raw byte recording ahead of the visible frame any more: it holds full-screen repaints (an ssh'd tmux, `less`, any TUI) drawn for the pane height of the moment, and replayed into a terminal of another height each repaint's last newline scrolls its top row into scrollback, so one line tmux holds once showed up dozens of times. Because `lines=` is shallower than xterm's scrollback, the route reports a cut: the capture's `display-message` query also reads `#{history_size}` (`PaneCaptureOptions.capturedHistoryLines`, the same field the route reports as `paneHistoryLines`), and a full capture whose CLIENT bound (`lines=` below the configured `tmuxHistoryLimit`) left lines in tmux comes back `truncated`, `truncationReason: 'tail'`. ⚠️ Only a client bound below the ceiling counts: a request without `lines=` is bounded by the ceiling itself, and on tmux before 3.7 a live pane can hold more than a lowered ceiling, which no request can read. ⚠️ **A pane in the alternate screen keeps no tmux history**, and a nested tmux client (remote SSH and Docker cases, or `tmux`/`ssh -t host tmux` run by hand) holds its pane there, so its full capture is one screen. The same query reads `#{alternate_on}` (`capturedAlternateOn`), and a request carrying `alt=recording` (only `SHELL_LOAD_QUERY`) is then answered the old way, the visible frame over the tailed byte recording, which still carries the scrollback; agents, scroll pulls and **Load full history** never send it. `#{alternate_on}` cannot tell a nested tmux from vim, `less` or `htop`, so a local shell with one of those open takes the same fallback until it exits (the pre-fix load, with its repaint duplicates). Shell FULL history is explicit-button-only; reaching the top during an ordinary wheel/touch gesture must not reset xterm and replay the multi-megabyte capture on its main thread. That gesture instead pulls a BOUNDED window of it (`?full=1&tail=<TERMINAL_TAIL_SIZE>`, so a capture beyond 1 MiB comes back `truncationReason: 'tail'` and the banner offers the rest), and skips the replay when the window holds no more rows than the browser already has. ⚠️ **That skip runs BEFORE the downgrade guard, and it never touches the banner state**: the guard reads "smaller than the browser" as "tmux has nothing more to give", true of an unbounded capture and false of a window cut at the tail size, so a bounded window that reached it marked the session `exhausted` and removed **Load full history** while tmux still held the rest; and re-labelling the banner from a skipped payload would call a terminal that holds all of a Load full history pull "the most recent 1 MiB". A skipped window that came back truncated puts the session on the 60 s cooldown (`_fullHistoryRepullUseless`), because it can never reach anything older than the browser shows and `tail` is applied AFTER the server's synchronous `capture-pane` of the whole history, so each ask costs every client an event-loop stall (about 0.3 s at 100k lines); an untruncated one keeps the 4 s cooldown, since it is all of tmux's history and the next burst can add to it. Declining the gesture outright was a dead end: after any burst a shell pane held about one screen of browser scrollback, and the button renders only once a replay was truncated, so a young shell tab had no way back to history tmux still held. Other modes re-pull `full=1` only at the top of the local buffer, and pressing **Load full history** forces the request for any recoverably truncated session (`_maybeRefetchFullHistory`, 4s per-session gesture cooldown, in-flight + tab-switch guards, viewport position held across the replay); Shell full pulls are not retained in the tab cache, so the next switch stays bounded. Chunked replay enqueues 32 KiB pieces across safe yields, appends an xterm parse marker, then releases the live-output gate; output arriving after that release stays ordered behind the snapshot, and the marker callback supplies accurate parse timing. ⚠️ **How the load ENDS depends on where the payload came from**, and `_bufferLoadFinishOpts` (app.js) is the one place that decides it for all four fetch-and-write paths. A payload built from the server's accumulated byte history is current up to the response, so the events queued during the load already appear in it and stay DISCARDED; replaying them would duplicate output, most visibly Ink's cursor-up redraws. A pane capture (`mux-visible` or `mux-full-history`) is current only up to CAPTURE time, so `_finishBufferLoad` replays the queue from the response's own arrival timestamp (`since`) and the pre-capture events stay dropped. ⚠️ **A path that then restores a scroll position must re-take the sticky-scroll baseline** (`_syncStickyScrollBaseline`): the replay runs inside `chunkedTerminalWrite` before its promise resolves, with the terminal freshly reset, so `batchTerminalWrite` samples `_wasAtBottomBeforeWrite` as true and the next `flushPendingWrites` would scroll to the bottom over the restore. ⚠️ The cutoff is a client-side timestamp and the server broadcasts on a batch timer (8ms WebSocket, 16-50ms SSE), so a batch pending when the capture ran arrives after the response and replays although the capture holds it — bounded by one batch interval, and closable only server side by flushing that batch before the capture. Tests for the three: `test/terminal-flush-budget.test.ts` pins which sources flush, `test/terminal-buffer-flush.test.ts` pins the `since` cutoff and the baseline re-take, and `test/capture-load-window.browser.test.ts` drives both against a live server. Live output is separately one-chunk-in-flight: xterm's callback releases each 32/64 KiB write before the next is submitted, keeping the remainder in the app queue where the 128 KiB cap can observe it instead of hiding an unbounded backlog in xterm's private WriteBuffer. While WebSocket owns terminal I/O, parallel SSE terminal/output-recovery events are discarded before JSON parsing; fallback recovery is single-flight per active session so backpressure cannot start overlapping reset+replay cycles. The route exposes capture/prepare totals in `Server-Timing`, while `[TERMINAL-PERF]` separates TTFB, body/JSON, reset+parse and total time for both selection and on-demand full pulls; parse completion is not a browser compositor/GPU paint measurement. The re-pull exists because xterm's buffer is only a WINDOW onto tmux's history and two things shrink it: tmux coalesces bursty output into pane REPAINTS that overwrite rows instead of emitting linefeeds (measured: a 60-line burst added 1 row of browser scrollback and destroyed 34), and a tab switch replays only the visible frame. tmux's own history is intact throughout — the browser just has to ask for it again. Gesture-triggered rather than polling because at a 100k history limit the capture can be megabytes. ⚠️ **The capture ENDS with a cursor move back to the pane's own caret position** (`formatCursorRestore`, from the same `display-message` query the visible-frame path uses). The linear replay otherwise leaves the caret wherever the last character landed — the bottom-most row carrying text, which for an agent CLI is the status line — so the caret sat on the composer's border instead of its input line and every cursor-relative update the CLI sent afterwards was measured from the wrong row, until its next full redraw silently repaired it (that self-repair is why the report read as "it fixes itself as soon as Claude writes a line"). ⚠️ **The move is RELATIVE — up `rows - 1 - cursor_y`, then `\r`, then right `cursor_x` — never `CUP`.** `\x1b[<row>;<col>H` numbers rows from the top of the browser's screen, so it lands correctly only while the browser's row count equals `pane_height`, and nothing guarantees that: `resizeWindow` issues its tmux resize fire-and-forget and returns immediately, so a capture can be taken before a requested resize has applied, and `_onSessionNeedsRefresh` sends no resize at all. Counting up from the last replayed row anchors to the content both ends share. Restoring the cursor makes ROW ALIGNMENT load-bearing on this path: **no transform that can DELETE A LINE may run over a full-history capture**, because every deletion shifts the frame out from under the restored position. Four had accumulated — trailing blank rows stripped by `\n+$`, `stripInkRedrawBloat`, the `CLAUDE_BANNER_PATTERN` trim that cuts everything above the banner, and `LEADING_WHITESPACE_PATTERN` — each correct for a byte stream of successive frames and each wrong for a single rendered frame. ⚠️ **Those skips key on `isFullCapture`, meaning a capture actually came back — never on `?full=1` alone.** When `captureActivePaneBuffer` returns null (ENOBUFS, a timeout, a vanished pane, or a session with no mux at all) the reply falls back to `session.terminalBuffer`, which IS a byte stream and must still be stripped; gating on the query flag returned it whole, and a direct-PTY session takes that path on every first selection rather than only during an outage. ⚠️ A capture holding nothing visible (`hasVisibleContent`) returns `''`, because the caller reads an empty capture as "unavailable" and keeps its byte history — retaining trailing blank rows made an all-blank pane non-empty, which would have replaced real history with a blank screen from the server side, where `_replayWouldShrinkBuffer` cannot see it. ⚠️ **"One line per screen row" holds only where no row was hard-wrapped**: `-J` joins a wrapped row into its logical line (measured: a 100-character line in a 40-column pane captures as 10 lines against a 12-row pane), and the counts reconcile only once the browser xterm re-wraps at the same width — the same assumption `_estimateReplayRows` already documents. Tests: `test/tmux-capture-full-history.test.ts` covers the cursor move, the trim pairing and `hasVisibleContent`; `test/routes/session-routes.test.ts` covers a surviving blank first row, an unstripped byte-history fallback, and an empty capture leaving history intact. ⚠️ **The re-pull must never DOWNGRADE the buffer** (#205 round 2): the same reasoning that makes it a win for a shell pane makes it destructive for a repaint-mode CLI pane, where tmux keeps no history of its own (`history_size≈0` measured for a Claude pane) and the capture is roughly ONE frame while xterm may hold hundreds of rows of replayed frames — `_resetTerminalForReplay()` + rewrite then deletes history mid-scroll ("goes back a bit, repeats blocks, gets worse the further up I go"; measured A/B on a live pane: 341 rows → 42 with the guard off). `_replayWouldShrinkBuffer()` (terminal-ui.js) estimates the capture's rendered rows — escape sequences stripped, `capture-pane -J` re-wrapping accounted for — and the pull is skipped when that is more than one screen short of `buffer.active.length`. The one-screen tolerance matters: both sides are estimates (the buffer length counts trailing blank rows), so only a clear downgrade is refused. A refused session joins `_fullHistoryRepullUseless`, raising its cooldown from 4s to 60s so a hollow pane stops re-fetching megabytes on every scroll-up. Tests: `test/tmux-capture-full-history.test.ts`, `test/tmux-scrollback-eol.test.ts`, `test/terminal-scroll-routing.test.ts`, `test/terminal-flush-budget.test.ts`. +**Full-scrollback replay** (COD-164/#148, reworked for #205): `GET /api/sessions/:id/terminal?full=1` returns the ENTIRE tmux scrollback (capture-pane `-e -S -<lines>` bounded by the configured history limit, explicit `maxBuffer` from the terminal-history config, early byte-cap before normalization, CRLF-normalized for shell panes). On success the capture is returned ALONE (`source='mux-full-history'` — it supersedes the byte buffer; no duplication). The first load of each non-shell TUI session per page requests `full=1` (`_fullHistoryLoaded` Set in app.js — the old one-shot `_initialFullBufferLoad` flag was consumed by whichever tab auto-selected, leaving every other TUI tab one frame of history). Shell sessions instead load a bounded window of tmux's RENDERED history on every selection, automatic drop recovery, clear and tile load (`SHELL_LOAD_QUERY` in constants.js: `?full=1&tail=1MiB&lines=10000&alt=recording`): a 100k-line shell capture can be tens of MiB, and automatically parsing it makes tab-switch latency scale with the entire session (`lines=` bounds the synchronous capture-pane, about 8 ms per 1000 lines). They never replay the raw byte recording ahead of the visible frame any more: it holds full-screen repaints (an ssh'd tmux, `less`, any TUI) drawn for the pane height of the moment, and replayed into a terminal of another height each repaint's last newline scrolls its top row into scrollback, so one line tmux holds once showed up dozens of times. Because `lines=` is shallower than xterm's scrollback, the route reports a cut: the capture's `display-message` query also reads `#{history_size}` (`PaneCaptureOptions.capturedHistoryLines`, the same field the route reports as `paneHistoryLines`), and a full capture whose CLIENT bound (`lines=` below the configured `tmuxHistoryLimit`) left lines in tmux comes back `truncated`, `truncationReason: 'tail'`. ⚠️ Only a client bound below the ceiling counts: a request without `lines=` is bounded by the ceiling itself, and on tmux before 3.7 a live pane can hold more than a lowered ceiling, which no request can read. ⚠️ **A pane in the alternate screen keeps no tmux history**, and a nested tmux client (remote SSH and Docker cases, or `tmux`/`ssh -t host tmux` run by hand) holds its pane there, so its full capture is one screen. The same query reads `#{alternate_on}` (`capturedAlternateOn`), and a request carrying `alt=recording` (only `SHELL_LOAD_QUERY`) is then answered the old way, the visible frame over the tailed byte recording, which still carries the scrollback; agents, scroll pulls and **Load full history** never send it. `#{alternate_on}` cannot tell a nested tmux from vim, `less` or `htop`, so a local shell with one of those open takes the same fallback until it exits (the pre-fix load, with its repaint duplicates). Shell FULL history is explicit-button-only; reaching the top during an ordinary wheel/touch gesture must not reset xterm and replay the multi-megabyte capture on its main thread. That gesture instead pulls a BOUNDED window of it (`?full=1&tail=<TERMINAL_TAIL_SIZE>`, so a capture beyond 1 MiB comes back `truncationReason: 'tail'` and the banner offers the rest), and skips the replay when the window holds no more rows than the browser already has. ⚠️ **That skip runs BEFORE the downgrade guard, and it never touches the banner state**: the guard reads "smaller than the browser" as "tmux has nothing more to give", true of an unbounded capture and false of a window cut at the tail size, so a bounded window that reached it marked the session `exhausted` and removed **Load full history** while tmux still held the rest; and re-labelling the banner from a skipped payload would call a terminal that holds all of a Load full history pull "the most recent 1 MiB". A skipped window that came back truncated puts the session on the 60 s cooldown (`_fullHistoryRepullUseless`), because it can never reach anything older than the browser shows and `tail` is applied AFTER the server's synchronous `capture-pane` of the whole history, so each ask costs every client an event-loop stall (about 1 s at 100k lines; measured capture details below); an untruncated one keeps the 4 s cooldown, since it is all of tmux's history and the next burst can add to it. Declining the gesture outright was a dead end: after any burst a shell pane held about one screen of browser scrollback, and the button renders only once a replay was truncated, so a young shell tab had no way back to history tmux still held. Other modes re-pull `full=1` only at the top of the local buffer, and pressing **Load full history** forces the request for any recoverably truncated session (`_maybeRefetchFullHistory`, 4s per-session gesture cooldown, in-flight + tab-switch guards, viewport position held across the replay); Shell full pulls are not retained in the tab cache, so the next switch stays bounded. Chunked replay enqueues 32 KiB pieces across safe yields, appends an xterm parse marker, then releases the live-output gate; output arriving after that release stays ordered behind the snapshot, and the marker callback supplies accurate parse timing. ⚠️ **How the load ENDS depends on where the payload came from**, and `_bufferLoadFinishOpts` (app.js) is the one place that decides it for all four fetch-and-write paths. A payload built from the server's accumulated byte history is current up to the response, so the events queued during the load already appear in it and stay DISCARDED; replaying them would duplicate output, most visibly Ink's cursor-up redraws. A pane capture (`mux-visible` or `mux-full-history`) is current only up to CAPTURE time, so `_finishBufferLoad` replays the queue from the response's own arrival timestamp (`since`) and the pre-capture events stay dropped. ⚠️ **A path that then restores a scroll position must re-take the sticky-scroll baseline** (`_syncStickyScrollBaseline`): the replay runs inside `chunkedTerminalWrite` before its promise resolves, with the terminal freshly reset, so `batchTerminalWrite` samples `_wasAtBottomBeforeWrite` as true and the next `flushPendingWrites` would scroll to the bottom over the restore. ⚠️ The cutoff is a client-side timestamp and the server broadcasts on a batch timer (8ms WebSocket, 16-50ms SSE), so a batch pending when the capture ran arrives after the response and replays although the capture holds it — bounded by one batch interval, and closable only server side by flushing that batch before the capture. Tests for the three: `test/terminal-flush-budget.test.ts` pins which sources flush, `test/terminal-buffer-flush.test.ts` pins the `since` cutoff and the baseline re-take, and `test/capture-load-window.browser.test.ts` drives both against a live server. Live output is separately one-chunk-in-flight: xterm's callback releases each 32/64 KiB write before the next is submitted, keeping the remainder in the app queue where the 128 KiB cap can observe it instead of hiding an unbounded backlog in xterm's private WriteBuffer. While WebSocket owns terminal I/O, parallel SSE terminal/output-recovery events are discarded before JSON parsing; fallback recovery is single-flight per active session so backpressure cannot start overlapping reset+replay cycles. The route exposes capture/prepare totals in `Server-Timing`, while `[TERMINAL-PERF]` separates TTFB, body/JSON, reset+parse and total time for both selection and on-demand full pulls; parse completion is not a browser compositor/GPU paint measurement. The re-pull exists because xterm's buffer is only a WINDOW onto tmux's history and two things shrink it: tmux coalesces bursty output into pane REPAINTS that overwrite rows instead of emitting linefeeds (measured: a 60-line burst added 1 row of browser scrollback and destroyed 34), and a tab switch replays only the visible frame. tmux's own history is intact throughout — the browser just has to ask for it again. Gesture-triggered rather than polling because at a 100k history limit the capture can be megabytes. ⚠️ **The capture ENDS with a cursor move back to the pane's own caret position** (`formatCursorRestore`, from the same `display-message` query the visible-frame path uses). The linear replay otherwise leaves the caret wherever the last character landed — the bottom-most row carrying text, which for an agent CLI is the status line — so the caret sat on the composer's border instead of its input line and every cursor-relative update the CLI sent afterwards was measured from the wrong row, until its next full redraw silently repaired it (that self-repair is why the report read as "it fixes itself as soon as Claude writes a line"). ⚠️ **The move is RELATIVE — up `rows - 1 - cursor_y`, then `\r`, then right `cursor_x` — never `CUP`.** `\x1b[<row>;<col>H` numbers rows from the top of the browser's screen, so it lands correctly only while the browser's row count equals `pane_height`, and nothing guarantees that: `resizeWindow` issues its tmux resize fire-and-forget and returns immediately, so a capture can be taken before a requested resize has applied, and `_onSessionNeedsRefresh` sends no resize at all. Counting up from the last replayed row anchors to the content both ends share. Restoring the cursor makes ROW ALIGNMENT load-bearing on this path: **no transform that can DELETE A LINE may run over a full-history capture**, because every deletion shifts the frame out from under the restored position. Four had accumulated — trailing blank rows stripped by `\n+$`, `stripInkRedrawBloat`, the `CLAUDE_BANNER_PATTERN` trim that cuts everything above the banner, and `LEADING_WHITESPACE_PATTERN` — each correct for a byte stream of successive frames and each wrong for a single rendered frame. ⚠️ **Those skips key on `isFullCapture`, meaning a capture actually came back — never on `?full=1` alone.** When `captureActivePaneBuffer` returns null (ENOBUFS, a timeout, a vanished pane, or a session with no mux at all) the reply falls back to `session.terminalBuffer`, which IS a byte stream and must still be stripped; gating on the query flag returned it whole, and a direct-PTY session takes that path on every first selection rather than only during an outage. ⚠️ A capture holding nothing visible (`hasVisibleContent`) returns `''`, because the caller reads an empty capture as "unavailable" and keeps its byte history — retaining trailing blank rows made an all-blank pane non-empty, which would have replaced real history with a blank screen from the server side, where `_replayWouldShrinkBuffer` cannot see it. ⚠️ **"One line per screen row" holds only where no row was hard-wrapped**: `-J` joins a wrapped row into its logical line (measured: a 100-character line in a 40-column pane captures as 10 lines against a 12-row pane), and the counts reconcile only once the browser xterm re-wraps at the same width — the same assumption `_estimateReplayRows` already documents. Tests: `test/tmux-capture-full-history.test.ts` covers the cursor move, the trim pairing and `hasVisibleContent`; `test/routes/session-routes.test.ts` covers a surviving blank first row, an unstripped byte-history fallback, and an empty capture leaving history intact. ⚠️ **The re-pull must never DOWNGRADE the buffer** (#205 round 2): the same reasoning that makes it a win for a shell pane makes it destructive for a repaint-mode CLI pane, where tmux keeps no history of its own (`history_size≈0` measured for a Claude pane) and the capture is roughly ONE frame while xterm may hold hundreds of rows of replayed frames — `_resetTerminalForReplay()` + rewrite then deletes history mid-scroll ("goes back a bit, repeats blocks, gets worse the further up I go"; measured A/B on a live pane: 341 rows → 42 with the guard off). `_replayWouldShrinkBuffer()` (terminal-ui.js) estimates the capture's rendered rows — escape sequences stripped, `capture-pane -J` re-wrapping accounted for — and the pull is skipped when that is more than one screen short of `buffer.active.length`. The one-screen tolerance matters: both sides are estimates (the buffer length counts trailing blank rows), so only a clear downgrade is refused. A refused session joins `_fullHistoryRepullUseless`, raising its cooldown from 4s to 60s so a hollow pane stops re-fetching megabytes on every scroll-up. Tests: `test/tmux-capture-full-history.test.ts`, `test/tmux-scrollback-eol.test.ts`, `test/terminal-scroll-routing.test.ts`, `test/terminal-flush-budget.test.ts`. -**Repair while reading (#814)** is a manual **Reload history** action inside the existing history banner on desktop and touch devices, enabled by default and toggleable per device in Settings → Terminal & Input → Scrolling & rendering (`historyReloadAction`). It is offered only for a marked non-shell active session while scrolled away from live output, not detached, not owned by tiles and with no pull in flight. A revealed truncation notice keeps its message and its **Load full history** control; Reload is appended only when the notice has no load control, or shown alone with a short missing-output message. A reload-only × dismissal lasts until the mark is cleared by a successful full mux replay, independently of the notice’s page-long dismissal. Eligibility is cached per active session, with onScroll sampling coalesced to one animation frame on every device; unchanged eligibility never rebuilds the banner. Automatic history pulls and notice reveal stay top-only (#205). The manual action forces a content-anchored pull, bypassing the gesture cooldown but retaining the downgrade guard. A content anchor captures the first non-empty row at/after the viewport and its next two rows, restores the nearest matching signature at the same viewport offset, and falls back to the nearest first-row-only match or distance from the bottom if unmatched or already near live output. Search is bounded to 2000 rows either side of the expected row (at most 4001 candidates / 12003 line reads). Ordered, session-scoped travel during replay is applied with per-move clamping; a switched-to tab never donates travel. The buffer load opens BEFORE the fetch, so download-time output queues behind the replay instead of being overwritten. Non-replay exits flush the whole queue; replays retain the capture-header cutoff above. A blocked dropped-output recovery stores its session and current attempt, defers without consuming retries, and resumes only for the still-active session. Only an actual `mux-full-history` replay clears the live-output mark and reload dismissal, and a newer live-write generation keeps them marked. The trade-off remains a full synchronous server capture (about 0.3 s at 100k lines), not a cheap automatic per-output repair. Tests: `test/shell-scroll-history-pull.test.ts`, `test/history-gap-repair.browser.test.ts`. +**Repair while reading (#814)** is a manual **Reload history** action inside the existing history banner on desktop and touch devices, enabled by default and toggleable per device in Settings → Terminal & Input → Scrolling & rendering (`historyReloadAction`). It is offered only for a marked non-shell active session while scrolled away from live output, not detached, not owned by tiles, with no pull or buffer load in flight and with `paneHistoryLines` not 0. A revealed truncation notice keeps its message and its **Load full history** control; Reload is appended only when the notice has no load control, or shown alone with a short missing-output message. A reload-only × dismissal lasts until the mark is cleared by a successful `mux-full-history` replay, independently of the notice’s page-long dismissal. Pressing × while loading hides the bar immediately; the in-flight pull continues. Eligibility is cached per active session, with onScroll sampling coalesced to one animation frame on every device; unchanged eligibility never rebuilds the banner. Automatic history pulls and notice reveal stay top-only (#205). Live-output marking covers only live writes: a byte-history (`?tail=`) replay, for example after a burst in a background tab, never marks the session, so that gap relies on the top-of-buffer pull. The manual action forces a content-anchored pull, bypassing the gesture cooldown but retaining the downgrade guard. Any downgrade-refused pull hides Reload until the next successful `mux-full-history` replay. A content anchor captures up to 64 visible rows, preserving indentation, and scores candidate alignments by matching viewport context. Each distinct nonblank row contributes at most one point, so repeated TUI borders cannot outvote a distinctive tool result. The best match must cover at least two distinct rows and 60% of the context and must be unique within the search window. Equal-scoring copies are ambiguous, even when all furniture rows match or the distinctive tool row has disappeared; proximity to the expected position does not establish confidence. An isolated first-row match is not trusted: without confident, unambiguous context the old viewport index is retained, while readers already near live output retain their bottom distance. Search is bounded to 2000 rows either side of the expected viewport (at most 4001 candidates / 4064 cached line reads). Live flushes use an xterm marker to track the reading row across scrollback trimming in O(1), and restore it only in the write callback; at-bottom sticky scroll is unchanged. Ordered, session-scoped travel during replay is applied with per-move clamping; a switched-to tab never donates travel. The buffer load opens BEFORE the fetch, so download-time output queues behind the replay instead of being overwritten. Non-replay exits flush the whole queue; replays retain the capture-header cutoff above. A blocked dropped-output recovery stores its session and current attempt, defers without consuming retries, and resumes only for the still-active session. Only an actual `mux-full-history` replay clears the live-output mark and reload dismissal, and a newer live-write generation keeps them marked. The trade-off remains a full synchronous server capture (about 1 s: 1,068 ms median for `capture-pane -p -e -J -S -100000` over 100k lines of 120 characters, 12.1 MB), not a cheap automatic per-output repair. Tests: `test/shell-scroll-history-pull.test.ts`, `test/history-gap-repair.browser.test.ts`. **The partial-history notice is lazy and pane-gated** (`computeHistoryTruncationNotice()` in constants.js, `_renderHistoryTruncationBanner()` / `_setHistoryNoticeRevealed()` in app.js). `truncated` on a terminal response measures the server's BYTE stream, which is not what `full=1` can return: for a pane with no tmux scrollback (fullscreen claude starts in the alternate screen and never writes to the main grid, so `#{history_size}` is 0) the bytes a tail cut drops are old repaint frames. Measured on prod 2026-10-10, every claude pane: the tab-switch tail cut a 1.2 to 6.2 MB stream to 1 MiB, the local scrollback that tail replays into is repeats of the same frames (one pane: 450 non-blank rows, 44 unique, one row 33 times), and `full=1` returned 1 to 5 KB, so **Load full history** could only end in the downgrade refusal while the banner promised "4.8 MB more". The capture therefore reads `#{history_size}` in the SAME `display-message` as the cursor (no extra tmux call), the route returns it as `paneHistoryLines` (absent when the body is not a capture, and for a remote SSH session, whose local pane hosts the remote tmux client and always reports 0 while `full=1` reads the remote history), and a reported 0 hides the notice in every state; a positive count replaces the byte gap in the message. ⚠️ Key the notice decision on `history_size`, never on `alternate_on`: a shell running `less` is in the alternate screen with its whole history still retained (measured, 99,972 rows) and `full=1` returns all of it. The one place `alternate_on` decides is a shell's AUTOMATIC load (`alt=recording`, see Full-scrollback replay): there the question is whether the capture holds the scrollback a nested tmux client keeps in its byte recording, not whether a pull can return more. The notice is also LAZY: it appears only after a wheel/touch gesture reaches the top of the browser buffer and the pull that gesture started has settled (`_maybeLoadMoreHistoryOnScroll`), goes away when a downward gesture is back at live output or the tab switches (`selectSession` nulls `_historyNoticeRevealedFor` before repainting), and its × is sticky per session until reload (`_historyNoticeDismissed`). Tests: `test/history-truncation-notice.test.ts`, `test/history-notice-reveal.test.ts`. diff --git a/docs/wiki/Settings-Reference.md b/docs/wiki/Settings-Reference.md index 5bfd53a2..978da0c8 100644 --- a/docs/wiki/Settings-Reference.md +++ b/docs/wiki/Settings-Reference.md @@ -51,6 +51,7 @@ non-updatable. See [Running As A Service](Running-As-A-Service). | Input Field: Send on Enter | Off | With CJK Input on, typed text stays in the pinned field until Enter instead of streaming to the CLI, so on a phone you can scroll the terminal and edit an answer first. With a hardware keyboard, Shift+Enter adds a line (a phone's on-screen keyboard has none). Esc clears, autocorrect is on. | | Extended Keyboard Bar | Per device | Which accessory bar phones get. Shell sessions override it while they are active. | | Wheel Scrolls Local History | Off | Keeps the wheel on the local buffer instead of forwarding it to the CLI. Fullscreen pi leaves that buffer empty and has no paging fallback, so with this on the wheel does nothing there. | +| History Reload Button | On (per device) | Offers **Reload history** in the history banner while you are scrolled up in a non-shell session that has had live output since its last full capture; a tap re-pulls the full tmux history and keeps your reading position. | | Auto Copy Selection | Off | Copies highlighted terminal text to the clipboard the moment you finish selecting it. Ctrl+C still copies on demand. | | Trim The Pane Margin On Copy | On | Takes the left margin a full-screen agent CLI paints down its own edge off a copy, so the text pastes flush. Each CLI declares its own width, and the strip never exceeds the indent every selected line shares, so nesting is kept. Claude Code and Codex declare a margin; a shell does not. | | Normal / Bold font weight | xterm defaults | Per device, each slot from 100 to 900. The bundled JetBrains Mono renders every step, so a lighter normal weight makes Claude's bold headings stand out. Applies live to the terminal, both echo overlays and open team panes. | diff --git a/docs/wiki/The-Dashboard.md b/docs/wiki/The-Dashboard.md index 59d6e22c..07633175 100644 --- a/docs/wiki/The-Dashboard.md +++ b/docs/wiki/The-Dashboard.md @@ -243,11 +243,14 @@ Worth knowing: reloads only the current screen, which keeps tab switches fast. Shell sessions open from a bounded recent tail so a large transcript cannot stall tab switching. Scrolling to the top of a Shell pane pulls the most recent 1 MiB of its tmux - history; press **Load full history** to pull the rest explicitly. That notice only + history; press **Load full history** to pull the rest explicitly. That truncation notice only appears once you scroll to the top, leaves when you scroll back down, and stays away for that tab once you close it. Sessions whose CLI keeps its own history (fullscreen - Claude) never show it, since there is nothing more to load. Automatic output - recovery stays within the bounded browser buffer. + Claude) never show it, since there is nothing more to load. The same bar can also offer + **Reload history** while scrolled up in an agent session after new output (toggle: + Settings → Terminal & Input → History Reload Button); it is not offered for panes + with no tmux history, such as fullscreen Claude. Automatic output recovery stays within + the bounded browser buffer. - **Wheel and touch scrolling** are forwarded into Claude's own transcript when a recent Claude runs fullscreen (`CLAUDE_CODE_NO_FLICKER=1`, or `"tui": "fullscreen"` in `~/.claude/settings.json`), so the wheel scrolls the conversation rather than the terminal. diff --git a/src/web/public/app.js b/src/web/public/app.js index 8e40dcf8..992307e1 100644 --- a/src/web/public/app.js +++ b/src/web/public/app.js @@ -9628,7 +9628,8 @@ class CodemanApp { * the same `?full=1` capture a page reload uses (issue #205). * * Automatic pulls are top-only and cooldown/latch guarded: a synchronous - * capture can cost about 0.3 s at 100k lines and blocks the server event loop. + * capture can cost about 1 s at 100k lines (1,068 ms median for 12.1 MB of + * 120-character lines, `capture-pane -p -e -J -S -100000`) and blocks the server event loop. * The manual Reload history action uses a content anchor to hold the reader's * place even when new history fills a gap below them. * @@ -9761,6 +9762,7 @@ class CodemanApp { timing.totalMs = performance.now() - requestStartedAt; this._recordTerminalLoadTiming(timing); (this._fullHistoryRepullUseless ||= new Set()).add(sessionId); + (this._historyReloadDismissed ||= new Set()).add(sessionId); this._logScrollRouting?.('repull-refused-downgrade'); // The browser already holds more than tmux can give back, so there is // nothing further to offer and the indicator must stop promising it. @@ -9924,6 +9926,7 @@ class CodemanApp { // Cheap state checks first: the terminal is read only for a marked session. return !!(this.loadAppSettingsFromStorage?.()?.historyReloadAction !== false && session && session.mode !== 'shell' && this._liveOutputSinceFullPull?.has(sessionId) && + this._paneHistoryLines?.get(sessionId) !== 0 && !this._isLoadingBuffer && !this._fullHistoryRepullInFlight && !this.detachedSessions?.has(sessionId) && !this._historyReloadDismissed?.has(sessionId) && !this._tilesOwnTerminal?.() && !this.isTerminalAtBottom()); @@ -9933,7 +9936,8 @@ class CodemanApp { _syncHistoryReloadAction() { const sessionId = this.activeSessionId; const eligible = this._historyReloadActionEligible(); - const loading = !!sessionId && this._historyReloadActionLoadingFor === sessionId; + const loading = !!sessionId && this._historyReloadActionLoadingFor === sessionId && + !this._historyReloadDismissed?.has(sessionId); const last = this._historyReloadActionState; if (last && last.sessionId === sessionId && last.eligible === eligible && last.loading === loading) return; this._historyReloadActionState = { sessionId, eligible, loading }; @@ -9963,7 +9967,8 @@ class CodemanApp { const showNotice = notice.visible && this._historyNoticeRevealedFor === sessionId && !this._historyNoticeDismissed?.has(sessionId); const eligible = this._historyReloadActionEligible?.() ?? false; - const loading = !!sessionId && this._historyReloadActionLoadingFor === sessionId; + const loading = !!sessionId && this._historyReloadActionLoadingFor === sessionId && + !this._historyReloadDismissed?.has(sessionId); this._historyReloadActionState = { sessionId, eligible, loading }; if (!showNotice && !eligible && !loading) { bar.hidden = true; @@ -9997,6 +10002,10 @@ class CodemanApp { btn.disabled = loading; btn.textContent = loading ? 'Loading…' : 'Reload history'; btn.onclick = () => { + if (!this._historyReloadActionEligible()) { + this._syncHistoryReloadAction(); + return; + } btn.disabled = true; btn.textContent = 'Loading…'; this._historyReloadActionLoadingFor = sessionId; diff --git a/src/web/public/terminal-ui.js b/src/web/public/terminal-ui.js index 4a6a6b10..41a45be0 100644 --- a/src/web/public/terminal-ui.js +++ b/src/web/public/terminal-ui.js @@ -4011,50 +4011,72 @@ Object.assign(CodemanApp.prototype, { return buffer.viewportY >= buffer.baseY - 2; }, - /** Capture the first readable row and its neighbours without copying the buffer. */ + /** Capture bounded viewport context, not just repeated TUI borders/status rows. */ _captureViewportAnchor() { const buffer = this.terminal.buffer.active; const { viewportY, baseY } = buffer; - let row = viewportY; - while (row < buffer.length && !buffer.getLine(row)?.translateToString(true).trim()) row++; + const context = Array.from( + { length: Math.min(this.terminal.rows || 3, 64, buffer.length - viewportY) }, + (_, i) => buffer.getLine(viewportY + i)?.translateToString(true) || '' + ); + const offset = Math.max(0, context.findIndex((text) => text.trim())); return { viewportY, rowsFromBottom: baseY - viewportY, - offset: row - viewportY, - signature: Array.from({ length: 3 }, (_, i) => buffer.getLine(row + i)?.translateToString(true).trim() || ''), + offset, + signature: Array.from({ length: 3 }, (_, i) => context[offset + i] || ''), + context, }; }, - /** Restore the closest matching content, falling back to distance from live output. */ + /** Match the visible context; a lone repeated row is not a reliable anchor. */ _restoreViewportAnchor(anchor) { const buffer = this.terminal.buffer.active; const clamp = (row) => Math.max(0, Math.min(buffer.baseY, row)); - const fallback = clamp(buffer.baseY - anchor.rowsFromBottom); - let target = fallback; - if (anchor.rowsFromBottom > 2 && anchor.signature[0]) { - const expected = Math.max(0, Math.min(buffer.length - 1, buffer.baseY - anchor.rowsFromBottom + anchor.offset)); - const text = (row) => buffer.getLine(row)?.translateToString(true).trim() || ''; - let firstRowMatch = null; - let exactMatch = null; - // Scan at most 2000 rows either side (4001 candidates / 12003 line reads). - // Nearest first: stop at the first exact signature, otherwise use the - // nearest first-row match within budget rather than scanning 50k rows. - for (let distance = 0; distance <= Math.min(2000, buffer.length - 1); distance++) { - const left = expected - distance; - const right = expected + distance; - for (let side = 0; side < (distance === 0 ? 1 : 2); side++) { - const row = side === 0 ? left : right; - if (row < 0 || row >= buffer.length || text(row) !== anchor.signature[0]) continue; - if (firstRowMatch === null) firstRowMatch = row; - if (text(row + 1) === anchor.signature[1] && text(row + 2) === anchor.signature[2]) { - exactMatch = row; - break; - } - } - if (exactMatch !== null) break; + let target = clamp(anchor.viewportY); + if (anchor.rowsFromBottom <= 2) { + target = clamp(buffer.baseY - anchor.rowsFromBottom); + } else { + const expected = clamp(buffer.baseY - anchor.rowsFromBottom); + const frequencies = new Map(); + for (const text of anchor.context) { + if (text.trim()) frequencies.set(text, (frequencies.get(text) || 0) + 1); } - const match = exactMatch ?? firstRowMatch; - if (match !== null) target = clamp(match - anchor.offset); + const samples = anchor.context.flatMap((text, offset) => + text.trim() ? [{ text, offset, weight: 1 / frequencies.get(text) }] : [] + ); + // Each distinct visible row contributes at most one point: repeated box + // borders cannot outvote the tool result the user is actually reading. + // Capped at the distinct-row count so a sparse viewport (one unique row + // among blanks) can still match; the ambiguity check rejects repeats. + const minimumScore = Math.min(frequencies.size, Math.max(2, frequencies.size * 0.6)); + const first = Math.max(0, expected - 2000); + const last = Math.min(buffer.baseY, expected + 2000); + // Cache the search window once: <= 4064 getLine calls, even when all + // 4001 candidates match repeated TUI furniture in a 50k-row buffer. + const text = Array.from( + { length: Math.min(buffer.length, last + anchor.context.length) - first }, + (_, i) => buffer.getLine(first + i)?.translateToString(true) || '' + ); + let bestScore = 0; + let bestRow = null; + let ambiguous = false; + for (let row = first; row <= last; row++) { + let score = 0; + for (const sample of samples) { + if (text[row - first + sample.offset] === sample.text) score += sample.weight; + } + if (score > bestScore + 1e-9) { + bestScore = score; + bestRow = row; + ambiguous = false; + } else if (Math.abs(score - bestScore) <= 1e-9) { + ambiguous = true; + } + } + // Equally good copies are evidence of repeated furniture, not of the + // reader's location. A gap below them makes nearest-to-expected wrong. + if (!ambiguous && bestScore + 1e-9 >= minimumScore) target = bestRow; } this.terminal.scrollToLine(target); return target; @@ -4736,6 +4758,13 @@ Object.assign(CodemanApp.prototype, { this.terminal.buffer?.active && !this.isTerminalAtBottom() ? this.terminal.buffer.active.viewportY : null; // Which buffer the anchor belongs to, checked again when the write parses. const flushSessionId = this.activeSessionId; + // xterm adjusts marker lines when its circular scrollback trims rows. An + // absolute viewport index does not track that trim and would move the + // reader upward on every live flush at the scrollback cap (#814). + const viewportBuffer = this.terminal.buffer?.active; + const viewportMarker = preserveViewportY !== null + ? this.terminal.registerMarker?.(preserveViewportY - (viewportBuffer.baseY + viewportBuffer.cursorY)) + : null; const writeChunk = joined.slice(0, MAX_FRAME_BYTES); if (_joinedLen > MAX_FRAME_BYTES) { @@ -4762,7 +4791,11 @@ Object.assign(CodemanApp.prototype, { // signal, which is the earliest point the anchor can actually be // reasserted. (The synchronous version passed its regression test only // because the test's write mock moved the viewport synchronously.) - this._restoreTerminalViewport(preserveViewportY, flushSessionId); + const viewportY = viewportMarker + ? (viewportMarker.isDisposed ? 0 : viewportMarker.line) + : preserveViewportY; + viewportMarker?.dispose(); + this._restoreTerminalViewport(viewportY, flushSessionId); this._scheduleTerminalWriteFlush(); this._noteMobileImeAuthoritativeOutput(flushedOutputSeq, flushSessionId); }); @@ -4777,6 +4810,7 @@ Object.assign(CodemanApp.prototype, { if (newlyMarked) this._syncHistoryReloadAction?.(); } } catch (err) { + viewportMarker?.dispose(); this._terminalWriteInFlight = false; this._terminalWriteInFlightBytes = 0; throw err; @@ -5105,6 +5139,7 @@ Object.assign(CodemanApp.prototype, { this._isLoadingBuffer = false; this._loadBufferQueue = null; this._bufferLoadOwner = null; + this._syncHistoryReloadAction?.(); // COD-144: replay (rather than discard) queued live events when the load // painted nothing — the queued prompt is the only content a new session has. // A tmux-capture load replays too, but only the tail: `since` cuts the queue diff --git a/test/history-gap-repair.browser.test.ts b/test/history-gap-repair.browser.test.ts index 1eb32403..c6566f8b 100644 --- a/test/history-gap-repair.browser.test.ts +++ b/test/history-gap-repair.browser.test.ts @@ -466,3 +466,120 @@ describe.each([true, false])('manual history gap repair (touch: %s)', (touch) => } }, 60_000); }); + +it('holds an OMP reading row through repeated repaint history and capped live flushes', async () => { + const { context, page } = await openTerminal(true); + const readingRow = 'Reading tool result: src/engine.ts — preserve this row'; + try { + const before = await page.evaluate( + async ({ session, readingRow }) => { + const w = window as RepairWindow; + const app = w.app; + const terminal = app.terminal; + const write = async (data: string) => { + const { promise, resolve } = Promise.withResolvers<void>(); + terminal.write(data, resolve); + await promise; + }; + terminal.reset(); + terminal.options.scrollback = 50_000; + const repeated = [ + '╭──────────────────╮', + '', + '│ Working… │', + '╰──────────────────╯', + '', + '⠋ OMP · processing', + ]; + const rows = Array.from({ length: 50_100 }, (_, i) => + i % 1000 === 999 ? `tool output ${'wrapped context '.repeat(18)}` : repeated[i % repeated.length] + ); + await write(rows.join('\r\n') + '\r\n'); + terminal.scrollToLine(25_000); + app._syncStickyScrollBaseline(); + // Cursor-addressed redraws and CSI S leave repeated TUI furniture in history. + const repaint = repeated.map((text, row) => `\x1b[${row + 1};1H\x1b[2K${text}`).join(''); + app._onSessionTerminal({ id: session, data: `\x1b[6S${repaint}\x1b[6S${repaint}` }); + await write(''); + while (app.pendingWrites.length || app._terminalWriteInFlight) { + const { promise, resolve } = Promise.withResolvers<void>(); + requestAnimationFrame(() => resolve()); + await promise; + } + // Put the distinctive tool result BELOW the three repeated anchor rows. + const buffer = terminal.buffer.active; + const top = buffer.viewportY; + const snapshot = Array.from( + { length: buffer.length }, + (_, i) => buffer.getLine(i)?.translateToString(true) || '' + ); + snapshot[top + 5] = readingRow; + await write('\x1bc' + snapshot.join('\r\n')); + terminal.scrollToLine(top); + app._syncStickyScrollBaseline(); + const seeded = terminal.buffer.active; + const captured = Array.from( + { length: seeded.length }, + (_, i) => seeded.getLine(i)?.translateToString(true) || '' + ); + captured.splice(top + 500, 0, ...Array.from({ length: 120 }, (_, i) => `Recovered tool detail ${i}`)); + const terminalBuffer = captured.join('\r\n'); + const realFetch = window.fetch.bind(window); + window.fetch = ((input: RequestInfo | URL, init?: RequestInit) => { + const url = String(typeof input === 'string' ? input : ((input as Request).url ?? input)); + if (!url.includes(`/api/sessions/${session}/terminal`)) return realFetch(input, init); + w.repairTest.pulls++; + return Promise.resolve({ + ok: true, + status: 200, + headers: new Headers(), + json: async () => { + app._onSessionTerminal({ id: session, data: '\r\nDownload-time output\r\n' }); + return { + success: true, + data: { terminalBuffer, source: 'mux-full-history', paneHistoryLines: 100_000, truncated: false }, + }; + }, + }) as unknown as Promise<Response>; + }) as typeof window.fetch; + app._liveOutputSinceFullPull.add(session); + app._syncHistoryReloadAction(); + return { + offset: captured.indexOf(readingRow) - seeded.viewportY, + viewportY: seeded.viewportY, + baseY: seeded.baseY, + }; + }, + { session: SESSION, readingRow } + ); + const button = page.locator('#historyTruncationBar').getByRole('button', { name: 'Reload history' }); + await button.tap(); + await waitForRepair(page); + const measure = () => + page.evaluate((readingRow) => { + const app = (window as RepairWindow).app; + const buffer = app.terminal.buffer.active; + let row = -1; + for (let i = 0; i < buffer.length; i++) { + if (buffer.getLine(i)?.translateToString(true) === readingRow) { + row = i; + break; + } + } + return { offset: row - buffer.viewportY, viewportY: buffer.viewportY, baseY: buffer.baseY }; + }, readingRow); + const afterReplay = await measure(); + await page.evaluate((session) => { + (window as RepairWindow).app._onSessionTerminal({ id: session, data: '\r\nPost-replay output\r\n' }); + }, SESSION); + await waitForRepair(page); + const afterFlush = await measure(); + expect({ before, afterReplay, afterFlush }).toEqual({ + before, + afterReplay: { ...afterReplay, offset: before.offset }, + afterFlush: { ...afterFlush, offset: before.offset }, + }); + } finally { + await context.close(); + } +}, 120_000); diff --git a/test/shell-scroll-history-pull.test.ts b/test/shell-scroll-history-pull.test.ts index da9b9800..f4d0983a 100644 --- a/test/shell-scroll-history-pull.test.ts +++ b/test/shell-scroll-history-pull.test.ts @@ -143,6 +143,7 @@ function makeApp( _loadBufferQueue: null as { at: number; data: string }[] | null, _fullHistoryRepullAt: new Map<string, number>(), _fullHistoryRepullUseless: new Set<string>(), + _historyReloadDismissed: new Set<string>(), _paneHistoryLines: new Map<string, number>(), terminalBufferCache: new Map<string, string>(), terminal: { @@ -373,6 +374,11 @@ describe('manual full-history recovery while reading (#814)', () => { { moves: [-1000, 30], distance: 340 }, ])('replays travel $moves made during an unfinished replay, clamped per move', async ({ moves, distance }) => { const { app, active, liveOutput, reload, pauseReplay } = makeScrollApp(); + // The replay prepends older rows; give the reader real matching content + // rather than relying on the old blank-buffer bottom-distance fallback. + Object.assign(active, { + getLine: (row: number) => ({ translateToString: () => `history ${row - active.baseY}` }), + }); liveOutput(); active.viewportY -= 5; // Read five rows above live output before the manual action. const paused = pauseReplay(); @@ -478,11 +484,16 @@ describe('manual full-history recovery while reading (#814)', () => { liveOutput(); app._fullHistoryRepullAt.set('s1', Date.now()); active.length = 1000; + active.viewportY -= 5; + const eligible = loadAppMethod('_historyReloadActionEligible'); + expect(eligible.call(app)).toBe(true); await reload(); expect(urls).toHaveLength(1); expect(app._resetTerminalForReplay).not.toHaveBeenCalled(); expect(app._liveOutputSinceFullPull.has('s1')).toBe(true); expect(app._fullHistoryRepullUseless.has('s1')).toBe(true); + expect(app._historyReloadDismissed.has('s1')).toBe(true); + expect(eligible.call(app)).toBe(false); }); it.each(['empty', 'tab-switch', 'downgrade', 'bounded-shell', 'rejection'])( @@ -872,25 +883,25 @@ describe('content anchors hold the reader through a history repair', () => { expect(anchor.offset).toBe(1); }); - it('chooses the nearest exact signature over a nearer first-row-only match', () => { + it('keeps the old viewport when two complete contexts match equally well', () => { const { capture, restore } = fixture(['head', 'A', 'B', 'C', ...Array(20).fill('tail')], 1); const anchor = capture(); const next = Array(34).fill('other'); next.splice(3, 3, 'A', 'B', 'C'); next.splice(10, 3, 'A', 'wrong', 'wrong'); next.splice(17, 3, 'A', 'B', 'C'); - expect(restore(anchor, next)).toBe(17); + expect(restore(anchor, next)).toBe(1); }); - it('falls back to the nearest first row, then distance from the bottom when nothing matches', () => { + it('keeps the old viewport rather than trusting an isolated or absent row', () => { const rows = Array.from({ length: 30 }, (_, i) => `row ${i}`); const { capture, restore } = fixture(rows); const anchor = capture(); const next = Array(40).fill('other'); next[8] = 'row 5'; next[17] = 'row 5'; - expect(restore(anchor, next)).toBe(17); - expect(restore(anchor, Array(40).fill('no match'))).toBe(15); + expect(restore(anchor, next)).toBe(5); + expect(restore(anchor, Array(40).fill('no match'))).toBe(5); }); it('keeps bottom distance within the bottom tolerance even if matching text exists', () => { @@ -899,20 +910,56 @@ describe('content anchors hold the reader through a history repair', () => { expect(restore(capture(), [...rows, ...Array(10).fill('new')])).toBe(36); }); + it('follows a lone distinctive row among blanks when history is inserted above the reader', () => { + const rows = Array.from({ length: 60 }, (_, i) => `row ${i}`); + for (let i = 20; i < 30; i++) rows[i] = ''; + rows[25] = 'tool result: src/engine.ts'; + const { app, capture, restore } = fixture(rows, 20); + Object.assign(app.terminal, { rows: 10 }); + const anchor = capture(); + const next = [...Array.from({ length: 40 }, (_, i) => `recovered ${i}`), ...rows]; + expect(restore(anchor, next)).toBe(60); + }); + + it('uses the visible tool result rather than a nearer copy of repeated TUI borders', () => { + const repeated = ['╭────────╮', '', '│ Working │', '╰────────╯', '', 'OMP · processing']; + const rows = Array.from({ length: 300 }, (_, i) => repeated[i % repeated.length]); + rows[125] = 'tool result: src/engine.ts'; + const { app, capture, restore } = fixture(rows, 120); + Object.assign(app.terminal, { rows: 18 }); + const anchor = capture(); + const next = [...rows.slice(0, 200), ...Array(60).fill('recovered below reader'), ...rows.slice(200)]; + expect(restore(anchor, next)).toBe(120); + }); + + it.each([false, true])('keeps the old viewport for ambiguous furniture (distinctive row lost: %s)', (lost) => { + const repeated = ['╭────────╮', '', '│ Working │', '╰────────╯', '', 'OMP · processing']; + const rows = Array.from({ length: 300 }, (_, i) => repeated[i % repeated.length]); + if (lost) rows[125] = 'tool result absent from the capture'; + const { app, capture, restore } = fixture(rows, 120); + Object.assign(app.terminal, { rows: 18 }); + const anchor = capture(); + const retained = rows.map((text, i) => (lost && i === 125 ? repeated[i % repeated.length] : text)); + const next = [...retained.slice(0, 200), ...Array(60).fill('recovered below reader'), ...retained.slice(200)]; + expect(restore(anchor, next)).toBe(120); + }); + it.each(['first-row-only', 'absent'])('bounds a 50k-row search with an %s signature', (kind) => { const rows = Array.from({ length: 50_000 }, (_, i) => `original ${i}`); - const { active, capture, restore } = fixture(rows, 25_000); + const { app, active, capture, restore } = fixture(rows, 25_000); + Object.assign(app.terminal, { rows: 64 }); const anchor = capture(); const next = Array(50_000).fill('other'); if (kind === 'first-row-only') { next[25_100] = anchor.signature[0]; next[24_800] = anchor.signature[0]; } - // An exact match outside the budget must not make the scan traverse 50k rows. - next.splice(30_000, 3, ...anchor.signature); + // Even a whole matching viewport outside the budget cannot extend the scan. + next.splice(30_000, anchor.context.length, ...anchor.context); active.getLine.mockClear(); - expect(restore(anchor, next)).toBe(kind === 'first-row-only' ? 25_100 : 25_000); - expect(active.getLine.mock.calls.length).toBeLessThanOrEqual(4005); + expect(restore(anchor, next)).toBe(25_000); + // 4001 possible starts plus the other 63 rows in the full viewport context. + expect(active.getLine.mock.calls.length).toBeLessThanOrEqual(4064); }); }); @@ -939,6 +986,8 @@ describe('manual history banner action', () => { active: true, detached: false, enabled: true, + loadingBuffer: false, + paneHistoryLines: undefined as number | undefined, ...options, }; const element = (): BannerElement => ({ @@ -976,6 +1025,10 @@ describe('manual history banner action', () => { _historyNoticeDismissed: new Set<string>(), _historyNoticeRevealedFor: null as string | null, _fullHistoryRepullInFlight: Boolean(state.inFlight), + _isLoadingBuffer: Boolean(state.loadingBuffer), + _paneHistoryLines: new Map<string, number>( + state.paneHistoryLines === undefined ? [] : [['s1', Number(state.paneHistoryLines)]] + ), detachedSessions: new Set(state.detached ? ['s1'] : []), _tilesOwnTerminal: () => state.tiles, _maybeRefetchFullHistory: vi.fn(async (_opts: object) => {}), @@ -1000,6 +1053,9 @@ describe('manual history banner action', () => { { opts: { bottom: true }, visible: false }, { opts: { marked: false }, visible: false }, { opts: { inFlight: true }, visible: false }, + { opts: { paneHistoryLines: 0 }, visible: false }, + { opts: { paneHistoryLines: 5 }, visible: true }, + { opts: { loadingBuffer: true }, visible: false }, { opts: { tiles: true }, visible: false }, { opts: { active: false }, visible: false }, { opts: { detached: true }, visible: false }, @@ -1025,6 +1081,57 @@ describe('manual history banner action', () => { expect(button()!.textContent).toBe('Reload history'); }); + it('retires a refused reload and ignores another tap on the same stale button', async () => { + const { app, bar, button } = fixture(); + app.terminal.buffer.active.length = 1000; + app._maybeRefetchFullHistory.mockImplementation((opts) => refetch.call(app, opts)); + app._syncHistoryReloadAction(); + const staleButton = button()!; + await staleButton.onclick!(); + expect(app._resetTerminalForReplay).not.toHaveBeenCalled(); + expect(app._historyReloadDismissed.has('s1')).toBe(true); + expect(bar.hidden).toBe(true); + expect(button()).toBeUndefined(); + await staleButton.onclick!(); + expect(app._fetchTerminalCapture).toHaveBeenCalledExactlyOnceWith('/api/sessions/s1/terminal?full=1', { + full: true, + }); + expect(app._maybeRefetchFullHistory).toHaveBeenCalledOnce(); + expect(bar.hidden).toBe(true); + }); + + it('syncs the action after a marked session finishes loading', () => { + const { app, bar, button } = fixture({ marked: false }); + const owner = (mixin._beginBufferLoad as Function).call(app); + app._liveOutputSinceFullPull.add('s1'); + app._syncHistoryReloadAction(); + expect(app._historyReloadActionEligible()).toBe(false); + expect(bar.hidden).toBe(true); + (mixin._finishBufferLoad as Function).call(app, owner); + expect(app._isLoadingBuffer).toBe(false); + expect(app._historyReloadActionEligible()).toBe(true); + expect(bar.hidden).toBe(false); + expect(button()!.textContent).toBe('Reload history'); + }); + + it('hides a dismissed loading action before the pull settles and keeps it hidden', async () => { + const { app, bar, button, dismiss } = fixture(); + const { promise, resolve: release } = Promise.withResolvers<void>(); + app._maybeRefetchFullHistory.mockReturnValueOnce(promise); + app._syncHistoryReloadAction(); + const tapped = button()!.onclick!(); + expect(button()!.textContent).toBe('Loading…'); + dismiss()!.onclick!(); + expect(bar.hidden).toBe(true); + expect(app._historyReloadDismissed.has('s1')).toBe(true); + app._syncHistoryReloadAction(); + expect(bar.hidden).toBe(true); + release(); + await tapped; + expect(bar.hidden).toBe(true); + expect(button()).toBeUndefined(); + }); + it.each(['recoverable', 'exhausted', 'capped'])('never duplicates the %s notice load control', (kind) => { const { app, bar, button } = fixture(); app._historyNoticeRevealedFor = 's1'; From b4d729a05498f2adb476eae84f91b0c9af1f03f9 Mon Sep 17 00:00:00 2001 From: Hadrien Kerlero <199662351+HadrienKerlero@users.noreply.github.com> Date: Tue, 17 Nov 2026 00:12:44 +0100 Subject: [PATCH 06/23] fix(web): offer Reload history after a burst in a session opened empty (#814) - _historyReloadActionEligible() no longer reads _paneHistoryLines: it is recorded at the last load, so a session first opened empty kept 0 after the burst that opens the gap, and the action never appeared (found by the live #814 recipe). - A pane with no tmux history is still retired by the downgrade refusal, which dismisses the action until the next mux-full-history replay. --- docs/architecture-invariants.md | 2 +- docs/wiki/The-Dashboard.md | 7 ++++--- src/web/public/app.js | 7 ++++++- test/shell-scroll-history-pull.test.ts | 4 +++- 4 files changed, 14 insertions(+), 6 deletions(-) diff --git a/docs/architecture-invariants.md b/docs/architecture-invariants.md index 92fa804a..90b8641a 100644 --- a/docs/architecture-invariants.md +++ b/docs/architecture-invariants.md @@ -253,7 +253,7 @@ Further detail: the `<prefix>: <title>` form (`w3-myapp: fix the login redirect` **Full-scrollback replay** (COD-164/#148, reworked for #205): `GET /api/sessions/:id/terminal?full=1` returns the ENTIRE tmux scrollback (capture-pane `-e -S -<lines>` bounded by the configured history limit, explicit `maxBuffer` from the terminal-history config, early byte-cap before normalization, CRLF-normalized for shell panes). On success the capture is returned ALONE (`source='mux-full-history'` — it supersedes the byte buffer; no duplication). The first load of each non-shell TUI session per page requests `full=1` (`_fullHistoryLoaded` Set in app.js — the old one-shot `_initialFullBufferLoad` flag was consumed by whichever tab auto-selected, leaving every other TUI tab one frame of history). Shell sessions instead load a bounded window of tmux's RENDERED history on every selection, automatic drop recovery, clear and tile load (`SHELL_LOAD_QUERY` in constants.js: `?full=1&tail=1MiB&lines=10000&alt=recording`): a 100k-line shell capture can be tens of MiB, and automatically parsing it makes tab-switch latency scale with the entire session (`lines=` bounds the synchronous capture-pane, about 8 ms per 1000 lines). They never replay the raw byte recording ahead of the visible frame any more: it holds full-screen repaints (an ssh'd tmux, `less`, any TUI) drawn for the pane height of the moment, and replayed into a terminal of another height each repaint's last newline scrolls its top row into scrollback, so one line tmux holds once showed up dozens of times. Because `lines=` is shallower than xterm's scrollback, the route reports a cut: the capture's `display-message` query also reads `#{history_size}` (`PaneCaptureOptions.capturedHistoryLines`, the same field the route reports as `paneHistoryLines`), and a full capture whose CLIENT bound (`lines=` below the configured `tmuxHistoryLimit`) left lines in tmux comes back `truncated`, `truncationReason: 'tail'`. ⚠️ Only a client bound below the ceiling counts: a request without `lines=` is bounded by the ceiling itself, and on tmux before 3.7 a live pane can hold more than a lowered ceiling, which no request can read. ⚠️ **A pane in the alternate screen keeps no tmux history**, and a nested tmux client (remote SSH and Docker cases, or `tmux`/`ssh -t host tmux` run by hand) holds its pane there, so its full capture is one screen. The same query reads `#{alternate_on}` (`capturedAlternateOn`), and a request carrying `alt=recording` (only `SHELL_LOAD_QUERY`) is then answered the old way, the visible frame over the tailed byte recording, which still carries the scrollback; agents, scroll pulls and **Load full history** never send it. `#{alternate_on}` cannot tell a nested tmux from vim, `less` or `htop`, so a local shell with one of those open takes the same fallback until it exits (the pre-fix load, with its repaint duplicates). Shell FULL history is explicit-button-only; reaching the top during an ordinary wheel/touch gesture must not reset xterm and replay the multi-megabyte capture on its main thread. That gesture instead pulls a BOUNDED window of it (`?full=1&tail=<TERMINAL_TAIL_SIZE>`, so a capture beyond 1 MiB comes back `truncationReason: 'tail'` and the banner offers the rest), and skips the replay when the window holds no more rows than the browser already has. ⚠️ **That skip runs BEFORE the downgrade guard, and it never touches the banner state**: the guard reads "smaller than the browser" as "tmux has nothing more to give", true of an unbounded capture and false of a window cut at the tail size, so a bounded window that reached it marked the session `exhausted` and removed **Load full history** while tmux still held the rest; and re-labelling the banner from a skipped payload would call a terminal that holds all of a Load full history pull "the most recent 1 MiB". A skipped window that came back truncated puts the session on the 60 s cooldown (`_fullHistoryRepullUseless`), because it can never reach anything older than the browser shows and `tail` is applied AFTER the server's synchronous `capture-pane` of the whole history, so each ask costs every client an event-loop stall (about 1 s at 100k lines; measured capture details below); an untruncated one keeps the 4 s cooldown, since it is all of tmux's history and the next burst can add to it. Declining the gesture outright was a dead end: after any burst a shell pane held about one screen of browser scrollback, and the button renders only once a replay was truncated, so a young shell tab had no way back to history tmux still held. Other modes re-pull `full=1` only at the top of the local buffer, and pressing **Load full history** forces the request for any recoverably truncated session (`_maybeRefetchFullHistory`, 4s per-session gesture cooldown, in-flight + tab-switch guards, viewport position held across the replay); Shell full pulls are not retained in the tab cache, so the next switch stays bounded. Chunked replay enqueues 32 KiB pieces across safe yields, appends an xterm parse marker, then releases the live-output gate; output arriving after that release stays ordered behind the snapshot, and the marker callback supplies accurate parse timing. ⚠️ **How the load ENDS depends on where the payload came from**, and `_bufferLoadFinishOpts` (app.js) is the one place that decides it for all four fetch-and-write paths. A payload built from the server's accumulated byte history is current up to the response, so the events queued during the load already appear in it and stay DISCARDED; replaying them would duplicate output, most visibly Ink's cursor-up redraws. A pane capture (`mux-visible` or `mux-full-history`) is current only up to CAPTURE time, so `_finishBufferLoad` replays the queue from the response's own arrival timestamp (`since`) and the pre-capture events stay dropped. ⚠️ **A path that then restores a scroll position must re-take the sticky-scroll baseline** (`_syncStickyScrollBaseline`): the replay runs inside `chunkedTerminalWrite` before its promise resolves, with the terminal freshly reset, so `batchTerminalWrite` samples `_wasAtBottomBeforeWrite` as true and the next `flushPendingWrites` would scroll to the bottom over the restore. ⚠️ The cutoff is a client-side timestamp and the server broadcasts on a batch timer (8ms WebSocket, 16-50ms SSE), so a batch pending when the capture ran arrives after the response and replays although the capture holds it — bounded by one batch interval, and closable only server side by flushing that batch before the capture. Tests for the three: `test/terminal-flush-budget.test.ts` pins which sources flush, `test/terminal-buffer-flush.test.ts` pins the `since` cutoff and the baseline re-take, and `test/capture-load-window.browser.test.ts` drives both against a live server. Live output is separately one-chunk-in-flight: xterm's callback releases each 32/64 KiB write before the next is submitted, keeping the remainder in the app queue where the 128 KiB cap can observe it instead of hiding an unbounded backlog in xterm's private WriteBuffer. While WebSocket owns terminal I/O, parallel SSE terminal/output-recovery events are discarded before JSON parsing; fallback recovery is single-flight per active session so backpressure cannot start overlapping reset+replay cycles. The route exposes capture/prepare totals in `Server-Timing`, while `[TERMINAL-PERF]` separates TTFB, body/JSON, reset+parse and total time for both selection and on-demand full pulls; parse completion is not a browser compositor/GPU paint measurement. The re-pull exists because xterm's buffer is only a WINDOW onto tmux's history and two things shrink it: tmux coalesces bursty output into pane REPAINTS that overwrite rows instead of emitting linefeeds (measured: a 60-line burst added 1 row of browser scrollback and destroyed 34), and a tab switch replays only the visible frame. tmux's own history is intact throughout — the browser just has to ask for it again. Gesture-triggered rather than polling because at a 100k history limit the capture can be megabytes. ⚠️ **The capture ENDS with a cursor move back to the pane's own caret position** (`formatCursorRestore`, from the same `display-message` query the visible-frame path uses). The linear replay otherwise leaves the caret wherever the last character landed — the bottom-most row carrying text, which for an agent CLI is the status line — so the caret sat on the composer's border instead of its input line and every cursor-relative update the CLI sent afterwards was measured from the wrong row, until its next full redraw silently repaired it (that self-repair is why the report read as "it fixes itself as soon as Claude writes a line"). ⚠️ **The move is RELATIVE — up `rows - 1 - cursor_y`, then `\r`, then right `cursor_x` — never `CUP`.** `\x1b[<row>;<col>H` numbers rows from the top of the browser's screen, so it lands correctly only while the browser's row count equals `pane_height`, and nothing guarantees that: `resizeWindow` issues its tmux resize fire-and-forget and returns immediately, so a capture can be taken before a requested resize has applied, and `_onSessionNeedsRefresh` sends no resize at all. Counting up from the last replayed row anchors to the content both ends share. Restoring the cursor makes ROW ALIGNMENT load-bearing on this path: **no transform that can DELETE A LINE may run over a full-history capture**, because every deletion shifts the frame out from under the restored position. Four had accumulated — trailing blank rows stripped by `\n+$`, `stripInkRedrawBloat`, the `CLAUDE_BANNER_PATTERN` trim that cuts everything above the banner, and `LEADING_WHITESPACE_PATTERN` — each correct for a byte stream of successive frames and each wrong for a single rendered frame. ⚠️ **Those skips key on `isFullCapture`, meaning a capture actually came back — never on `?full=1` alone.** When `captureActivePaneBuffer` returns null (ENOBUFS, a timeout, a vanished pane, or a session with no mux at all) the reply falls back to `session.terminalBuffer`, which IS a byte stream and must still be stripped; gating on the query flag returned it whole, and a direct-PTY session takes that path on every first selection rather than only during an outage. ⚠️ A capture holding nothing visible (`hasVisibleContent`) returns `''`, because the caller reads an empty capture as "unavailable" and keeps its byte history — retaining trailing blank rows made an all-blank pane non-empty, which would have replaced real history with a blank screen from the server side, where `_replayWouldShrinkBuffer` cannot see it. ⚠️ **"One line per screen row" holds only where no row was hard-wrapped**: `-J` joins a wrapped row into its logical line (measured: a 100-character line in a 40-column pane captures as 10 lines against a 12-row pane), and the counts reconcile only once the browser xterm re-wraps at the same width — the same assumption `_estimateReplayRows` already documents. Tests: `test/tmux-capture-full-history.test.ts` covers the cursor move, the trim pairing and `hasVisibleContent`; `test/routes/session-routes.test.ts` covers a surviving blank first row, an unstripped byte-history fallback, and an empty capture leaving history intact. ⚠️ **The re-pull must never DOWNGRADE the buffer** (#205 round 2): the same reasoning that makes it a win for a shell pane makes it destructive for a repaint-mode CLI pane, where tmux keeps no history of its own (`history_size≈0` measured for a Claude pane) and the capture is roughly ONE frame while xterm may hold hundreds of rows of replayed frames — `_resetTerminalForReplay()` + rewrite then deletes history mid-scroll ("goes back a bit, repeats blocks, gets worse the further up I go"; measured A/B on a live pane: 341 rows → 42 with the guard off). `_replayWouldShrinkBuffer()` (terminal-ui.js) estimates the capture's rendered rows — escape sequences stripped, `capture-pane -J` re-wrapping accounted for — and the pull is skipped when that is more than one screen short of `buffer.active.length`. The one-screen tolerance matters: both sides are estimates (the buffer length counts trailing blank rows), so only a clear downgrade is refused. A refused session joins `_fullHistoryRepullUseless`, raising its cooldown from 4s to 60s so a hollow pane stops re-fetching megabytes on every scroll-up. Tests: `test/tmux-capture-full-history.test.ts`, `test/tmux-scrollback-eol.test.ts`, `test/terminal-scroll-routing.test.ts`, `test/terminal-flush-budget.test.ts`. -**Repair while reading (#814)** is a manual **Reload history** action inside the existing history banner on desktop and touch devices, enabled by default and toggleable per device in Settings → Terminal & Input → Scrolling & rendering (`historyReloadAction`). It is offered only for a marked non-shell active session while scrolled away from live output, not detached, not owned by tiles, with no pull or buffer load in flight and with `paneHistoryLines` not 0. A revealed truncation notice keeps its message and its **Load full history** control; Reload is appended only when the notice has no load control, or shown alone with a short missing-output message. A reload-only × dismissal lasts until the mark is cleared by a successful `mux-full-history` replay, independently of the notice’s page-long dismissal. Pressing × while loading hides the bar immediately; the in-flight pull continues. Eligibility is cached per active session, with onScroll sampling coalesced to one animation frame on every device; unchanged eligibility never rebuilds the banner. Automatic history pulls and notice reveal stay top-only (#205). Live-output marking covers only live writes: a byte-history (`?tail=`) replay, for example after a burst in a background tab, never marks the session, so that gap relies on the top-of-buffer pull. The manual action forces a content-anchored pull, bypassing the gesture cooldown but retaining the downgrade guard. Any downgrade-refused pull hides Reload until the next successful `mux-full-history` replay. A content anchor captures up to 64 visible rows, preserving indentation, and scores candidate alignments by matching viewport context. Each distinct nonblank row contributes at most one point, so repeated TUI borders cannot outvote a distinctive tool result. The best match must cover at least two distinct rows and 60% of the context and must be unique within the search window. Equal-scoring copies are ambiguous, even when all furniture rows match or the distinctive tool row has disappeared; proximity to the expected position does not establish confidence. An isolated first-row match is not trusted: without confident, unambiguous context the old viewport index is retained, while readers already near live output retain their bottom distance. Search is bounded to 2000 rows either side of the expected viewport (at most 4001 candidates / 4064 cached line reads). Live flushes use an xterm marker to track the reading row across scrollback trimming in O(1), and restore it only in the write callback; at-bottom sticky scroll is unchanged. Ordered, session-scoped travel during replay is applied with per-move clamping; a switched-to tab never donates travel. The buffer load opens BEFORE the fetch, so download-time output queues behind the replay instead of being overwritten. Non-replay exits flush the whole queue; replays retain the capture-header cutoff above. A blocked dropped-output recovery stores its session and current attempt, defers without consuming retries, and resumes only for the still-active session. Only an actual `mux-full-history` replay clears the live-output mark and reload dismissal, and a newer live-write generation keeps them marked. The trade-off remains a full synchronous server capture (about 1 s: 1,068 ms median for `capture-pane -p -e -J -S -100000` over 100k lines of 120 characters, 12.1 MB), not a cheap automatic per-output repair. Tests: `test/shell-scroll-history-pull.test.ts`, `test/history-gap-repair.browser.test.ts`. +**Repair while reading (#814)** is a manual **Reload history** action inside the existing history banner on desktop and touch devices, enabled by default and toggleable per device in Settings → Terminal & Input → Scrolling & rendering (`historyReloadAction`). It is offered only for a marked non-shell active session while scrolled away from live output, not detached, not owned by tiles, with no pull or buffer load in flight. `paneHistoryLines` is deliberately not consulted: it is recorded at the last load, so a session first opened empty keeps 0 after the very burst that opens the gap (#814). A revealed truncation notice keeps its message and its **Load full history** control; Reload is appended only when the notice has no load control, or shown alone with a short missing-output message. A reload-only × dismissal lasts until the mark is cleared by a successful `mux-full-history` replay, independently of the notice’s page-long dismissal. Pressing × while loading hides the bar immediately; the in-flight pull continues. Eligibility is cached per active session, with onScroll sampling coalesced to one animation frame on every device; unchanged eligibility never rebuilds the banner. Automatic history pulls and notice reveal stay top-only (#205). Live-output marking covers only live writes: a byte-history (`?tail=`) replay, for example after a burst in a background tab, never marks the session, so that gap relies on the top-of-buffer pull. The manual action forces a content-anchored pull, bypassing the gesture cooldown but retaining the downgrade guard. Any downgrade-refused pull hides Reload until the next successful `mux-full-history` replay; that refusal, not the cached history size, is what retires the action for a pane with no tmux history (fullscreen Claude). A content anchor captures up to 64 visible rows, preserving indentation, and scores candidate alignments by matching viewport context. Each distinct nonblank row contributes at most one point, so repeated TUI borders cannot outvote a distinctive tool result. The best match must cover at least two distinct rows and 60% of the context and must be unique within the search window. Equal-scoring copies are ambiguous, even when all furniture rows match or the distinctive tool row has disappeared; proximity to the expected position does not establish confidence. An isolated first-row match is not trusted: without confident, unambiguous context the old viewport index is retained, while readers already near live output retain their bottom distance. Search is bounded to 2000 rows either side of the expected viewport (at most 4001 candidates / 4064 cached line reads). Live flushes use an xterm marker to track the reading row across scrollback trimming in O(1), and restore it only in the write callback; at-bottom sticky scroll is unchanged. Ordered, session-scoped travel during replay is applied with per-move clamping; a switched-to tab never donates travel. The buffer load opens BEFORE the fetch, so download-time output queues behind the replay instead of being overwritten. Non-replay exits flush the whole queue; replays retain the capture-header cutoff above. A blocked dropped-output recovery stores its session and current attempt, defers without consuming retries, and resumes only for the still-active session. Only an actual `mux-full-history` replay clears the live-output mark and reload dismissal, and a newer live-write generation keeps them marked. The trade-off remains a full synchronous server capture (about 1 s: 1,068 ms median for `capture-pane -p -e -J -S -100000` over 100k lines of 120 characters, 12.1 MB), not a cheap automatic per-output repair. Tests: `test/shell-scroll-history-pull.test.ts`, `test/history-gap-repair.browser.test.ts`. **The partial-history notice is lazy and pane-gated** (`computeHistoryTruncationNotice()` in constants.js, `_renderHistoryTruncationBanner()` / `_setHistoryNoticeRevealed()` in app.js). `truncated` on a terminal response measures the server's BYTE stream, which is not what `full=1` can return: for a pane with no tmux scrollback (fullscreen claude starts in the alternate screen and never writes to the main grid, so `#{history_size}` is 0) the bytes a tail cut drops are old repaint frames. Measured on prod 2026-10-10, every claude pane: the tab-switch tail cut a 1.2 to 6.2 MB stream to 1 MiB, the local scrollback that tail replays into is repeats of the same frames (one pane: 450 non-blank rows, 44 unique, one row 33 times), and `full=1` returned 1 to 5 KB, so **Load full history** could only end in the downgrade refusal while the banner promised "4.8 MB more". The capture therefore reads `#{history_size}` in the SAME `display-message` as the cursor (no extra tmux call), the route returns it as `paneHistoryLines` (absent when the body is not a capture, and for a remote SSH session, whose local pane hosts the remote tmux client and always reports 0 while `full=1` reads the remote history), and a reported 0 hides the notice in every state; a positive count replaces the byte gap in the message. ⚠️ Key the notice decision on `history_size`, never on `alternate_on`: a shell running `less` is in the alternate screen with its whole history still retained (measured, 99,972 rows) and `full=1` returns all of it. The one place `alternate_on` decides is a shell's AUTOMATIC load (`alt=recording`, see Full-scrollback replay): there the question is whether the capture holds the scrollback a nested tmux client keeps in its byte recording, not whether a pull can return more. The notice is also LAZY: it appears only after a wheel/touch gesture reaches the top of the browser buffer and the pull that gesture started has settled (`_maybeLoadMoreHistoryOnScroll`), goes away when a downward gesture is back at live output or the tab switches (`selectSession` nulls `_historyNoticeRevealedFor` before repainting), and its × is sticky per session until reload (`_historyNoticeDismissed`). Tests: `test/history-truncation-notice.test.ts`, `test/history-notice-reveal.test.ts`. diff --git a/docs/wiki/The-Dashboard.md b/docs/wiki/The-Dashboard.md index 07633175..3d26152f 100644 --- a/docs/wiki/The-Dashboard.md +++ b/docs/wiki/The-Dashboard.md @@ -248,9 +248,10 @@ Worth knowing: for that tab once you close it. Sessions whose CLI keeps its own history (fullscreen Claude) never show it, since there is nothing more to load. The same bar can also offer **Reload history** while scrolled up in an agent session after new output (toggle: - Settings → Terminal & Input → History Reload Button); it is not offered for panes - with no tmux history, such as fullscreen Claude. Automatic output recovery stays within - the bounded browser buffer. + Settings → Terminal & Input → History Reload Button). When a reload finds nothing more + than the browser already shows, such as fullscreen Claude whose pane keeps no tmux + history, the action is withdrawn until the next full capture. Automatic output + recovery stays within the bounded browser buffer. - **Wheel and touch scrolling** are forwarded into Claude's own transcript when a recent Claude runs fullscreen (`CLAUDE_CODE_NO_FLICKER=1`, or `"tui": "fullscreen"` in `~/.claude/settings.json`), so the wheel scrolls the conversation rather than the terminal. diff --git a/src/web/public/app.js b/src/web/public/app.js index 992307e1..633e4660 100644 --- a/src/web/public/app.js +++ b/src/web/public/app.js @@ -9924,9 +9924,14 @@ class CodemanApp { const sessionId = this.activeSessionId; const session = this.sessions.get(sessionId); // Cheap state checks first: the terminal is read only for a marked session. + // `_paneHistoryLines` is deliberately not consulted: it is recorded at the last + // load, so a session first opened empty keeps 0 after the very burst that + // opens the gap (#814). A pane that really holds no history (fullscreen + // Claude) captures one screen, `_replayWouldShrinkBuffer` refuses it, and the + // refusal dismisses the action until the next `mux-full-history` replay. return !!(this.loadAppSettingsFromStorage?.()?.historyReloadAction !== false && session && session.mode !== 'shell' && this._liveOutputSinceFullPull?.has(sessionId) && - this._paneHistoryLines?.get(sessionId) !== 0 && !this._isLoadingBuffer && + !this._isLoadingBuffer && !this._fullHistoryRepullInFlight && !this.detachedSessions?.has(sessionId) && !this._historyReloadDismissed?.has(sessionId) && !this._tilesOwnTerminal?.() && !this.isTerminalAtBottom()); diff --git a/test/shell-scroll-history-pull.test.ts b/test/shell-scroll-history-pull.test.ts index f4d0983a..efa5d431 100644 --- a/test/shell-scroll-history-pull.test.ts +++ b/test/shell-scroll-history-pull.test.ts @@ -1053,7 +1053,9 @@ describe('manual history banner action', () => { { opts: { bottom: true }, visible: false }, { opts: { marked: false }, visible: false }, { opts: { inFlight: true }, visible: false }, - { opts: { paneHistoryLines: 0 }, visible: false }, + // Recorded at the session's first load: a pane opened empty keeps 0 after the + // burst that opens the gap, so a stale 0 must not hide the action (#814). + { opts: { paneHistoryLines: 0 }, visible: true }, { opts: { paneHistoryLines: 5 }, visible: true }, { opts: { loadingBuffer: true }, visible: false }, { opts: { tiles: true }, visible: false }, From 5f0366c060b06ea87926308ad5e248b7f6ed3403 Mon Sep 17 00:00:00 2001 From: Hadrien Kerlero <199662351+HadrienKerlero@users.noreply.github.com> Date: Tue, 17 Nov 2026 01:14:27 +0100 Subject: [PATCH 07/23] fix(web): keep Reload history off while the incoming tab loads (#814) - _historyReloadActionEligible() also requires no terminal load state: selectSession sets it before switching activeSessionId, so the sync right after the switch no longer offers Reload for the loading tab. - _clearTerminalLoadState() re-syncs the action, so a marked tab offers Reload once its load ends. - Changeset: note the reading-position fix for live flushes at the scrollback cap. --- .../814-history-repair-while-reading.md | 2 + docs/architecture-invariants.md | 2 +- src/web/public/app.js | 2 + test/history-gap-repair.browser.test.ts | 81 +++++++++++++++++++ test/shell-scroll-history-pull.test.ts | 15 ++++ 5 files changed, 101 insertions(+), 1 deletion(-) diff --git a/.changeset/814-history-repair-while-reading.md b/.changeset/814-history-repair-while-reading.md index caa91c5d..bdc91d7d 100644 --- a/.changeset/814-history-repair-while-reading.md +++ b/.changeset/814-history-repair-while-reading.md @@ -3,3 +3,5 @@ --- Fix missing terminal history above live OMP output with a manual Reload history action in the existing history banner on desktop and mobile. The action preserves the text being read and output arriving during the download, and can be disabled per device in Settings > Terminal & Input > Scrolling & rendering. Ordinary scrolling only pulls history at the top; deferred dropped-output recovery retains its retry attempt. + +While you are scrolled up, new output no longer moves the text you are reading once the terminal's scrollback is full. This applies to every session type, whether or not the Reload history setting is on. diff --git a/docs/architecture-invariants.md b/docs/architecture-invariants.md index 90b8641a..0ca83115 100644 --- a/docs/architecture-invariants.md +++ b/docs/architecture-invariants.md @@ -253,7 +253,7 @@ Further detail: the `<prefix>: <title>` form (`w3-myapp: fix the login redirect` **Full-scrollback replay** (COD-164/#148, reworked for #205): `GET /api/sessions/:id/terminal?full=1` returns the ENTIRE tmux scrollback (capture-pane `-e -S -<lines>` bounded by the configured history limit, explicit `maxBuffer` from the terminal-history config, early byte-cap before normalization, CRLF-normalized for shell panes). On success the capture is returned ALONE (`source='mux-full-history'` — it supersedes the byte buffer; no duplication). The first load of each non-shell TUI session per page requests `full=1` (`_fullHistoryLoaded` Set in app.js — the old one-shot `_initialFullBufferLoad` flag was consumed by whichever tab auto-selected, leaving every other TUI tab one frame of history). Shell sessions instead load a bounded window of tmux's RENDERED history on every selection, automatic drop recovery, clear and tile load (`SHELL_LOAD_QUERY` in constants.js: `?full=1&tail=1MiB&lines=10000&alt=recording`): a 100k-line shell capture can be tens of MiB, and automatically parsing it makes tab-switch latency scale with the entire session (`lines=` bounds the synchronous capture-pane, about 8 ms per 1000 lines). They never replay the raw byte recording ahead of the visible frame any more: it holds full-screen repaints (an ssh'd tmux, `less`, any TUI) drawn for the pane height of the moment, and replayed into a terminal of another height each repaint's last newline scrolls its top row into scrollback, so one line tmux holds once showed up dozens of times. Because `lines=` is shallower than xterm's scrollback, the route reports a cut: the capture's `display-message` query also reads `#{history_size}` (`PaneCaptureOptions.capturedHistoryLines`, the same field the route reports as `paneHistoryLines`), and a full capture whose CLIENT bound (`lines=` below the configured `tmuxHistoryLimit`) left lines in tmux comes back `truncated`, `truncationReason: 'tail'`. ⚠️ Only a client bound below the ceiling counts: a request without `lines=` is bounded by the ceiling itself, and on tmux before 3.7 a live pane can hold more than a lowered ceiling, which no request can read. ⚠️ **A pane in the alternate screen keeps no tmux history**, and a nested tmux client (remote SSH and Docker cases, or `tmux`/`ssh -t host tmux` run by hand) holds its pane there, so its full capture is one screen. The same query reads `#{alternate_on}` (`capturedAlternateOn`), and a request carrying `alt=recording` (only `SHELL_LOAD_QUERY`) is then answered the old way, the visible frame over the tailed byte recording, which still carries the scrollback; agents, scroll pulls and **Load full history** never send it. `#{alternate_on}` cannot tell a nested tmux from vim, `less` or `htop`, so a local shell with one of those open takes the same fallback until it exits (the pre-fix load, with its repaint duplicates). Shell FULL history is explicit-button-only; reaching the top during an ordinary wheel/touch gesture must not reset xterm and replay the multi-megabyte capture on its main thread. That gesture instead pulls a BOUNDED window of it (`?full=1&tail=<TERMINAL_TAIL_SIZE>`, so a capture beyond 1 MiB comes back `truncationReason: 'tail'` and the banner offers the rest), and skips the replay when the window holds no more rows than the browser already has. ⚠️ **That skip runs BEFORE the downgrade guard, and it never touches the banner state**: the guard reads "smaller than the browser" as "tmux has nothing more to give", true of an unbounded capture and false of a window cut at the tail size, so a bounded window that reached it marked the session `exhausted` and removed **Load full history** while tmux still held the rest; and re-labelling the banner from a skipped payload would call a terminal that holds all of a Load full history pull "the most recent 1 MiB". A skipped window that came back truncated puts the session on the 60 s cooldown (`_fullHistoryRepullUseless`), because it can never reach anything older than the browser shows and `tail` is applied AFTER the server's synchronous `capture-pane` of the whole history, so each ask costs every client an event-loop stall (about 1 s at 100k lines; measured capture details below); an untruncated one keeps the 4 s cooldown, since it is all of tmux's history and the next burst can add to it. Declining the gesture outright was a dead end: after any burst a shell pane held about one screen of browser scrollback, and the button renders only once a replay was truncated, so a young shell tab had no way back to history tmux still held. Other modes re-pull `full=1` only at the top of the local buffer, and pressing **Load full history** forces the request for any recoverably truncated session (`_maybeRefetchFullHistory`, 4s per-session gesture cooldown, in-flight + tab-switch guards, viewport position held across the replay); Shell full pulls are not retained in the tab cache, so the next switch stays bounded. Chunked replay enqueues 32 KiB pieces across safe yields, appends an xterm parse marker, then releases the live-output gate; output arriving after that release stays ordered behind the snapshot, and the marker callback supplies accurate parse timing. ⚠️ **How the load ENDS depends on where the payload came from**, and `_bufferLoadFinishOpts` (app.js) is the one place that decides it for all four fetch-and-write paths. A payload built from the server's accumulated byte history is current up to the response, so the events queued during the load already appear in it and stay DISCARDED; replaying them would duplicate output, most visibly Ink's cursor-up redraws. A pane capture (`mux-visible` or `mux-full-history`) is current only up to CAPTURE time, so `_finishBufferLoad` replays the queue from the response's own arrival timestamp (`since`) and the pre-capture events stay dropped. ⚠️ **A path that then restores a scroll position must re-take the sticky-scroll baseline** (`_syncStickyScrollBaseline`): the replay runs inside `chunkedTerminalWrite` before its promise resolves, with the terminal freshly reset, so `batchTerminalWrite` samples `_wasAtBottomBeforeWrite` as true and the next `flushPendingWrites` would scroll to the bottom over the restore. ⚠️ The cutoff is a client-side timestamp and the server broadcasts on a batch timer (8ms WebSocket, 16-50ms SSE), so a batch pending when the capture ran arrives after the response and replays although the capture holds it — bounded by one batch interval, and closable only server side by flushing that batch before the capture. Tests for the three: `test/terminal-flush-budget.test.ts` pins which sources flush, `test/terminal-buffer-flush.test.ts` pins the `since` cutoff and the baseline re-take, and `test/capture-load-window.browser.test.ts` drives both against a live server. Live output is separately one-chunk-in-flight: xterm's callback releases each 32/64 KiB write before the next is submitted, keeping the remainder in the app queue where the 128 KiB cap can observe it instead of hiding an unbounded backlog in xterm's private WriteBuffer. While WebSocket owns terminal I/O, parallel SSE terminal/output-recovery events are discarded before JSON parsing; fallback recovery is single-flight per active session so backpressure cannot start overlapping reset+replay cycles. The route exposes capture/prepare totals in `Server-Timing`, while `[TERMINAL-PERF]` separates TTFB, body/JSON, reset+parse and total time for both selection and on-demand full pulls; parse completion is not a browser compositor/GPU paint measurement. The re-pull exists because xterm's buffer is only a WINDOW onto tmux's history and two things shrink it: tmux coalesces bursty output into pane REPAINTS that overwrite rows instead of emitting linefeeds (measured: a 60-line burst added 1 row of browser scrollback and destroyed 34), and a tab switch replays only the visible frame. tmux's own history is intact throughout — the browser just has to ask for it again. Gesture-triggered rather than polling because at a 100k history limit the capture can be megabytes. ⚠️ **The capture ENDS with a cursor move back to the pane's own caret position** (`formatCursorRestore`, from the same `display-message` query the visible-frame path uses). The linear replay otherwise leaves the caret wherever the last character landed — the bottom-most row carrying text, which for an agent CLI is the status line — so the caret sat on the composer's border instead of its input line and every cursor-relative update the CLI sent afterwards was measured from the wrong row, until its next full redraw silently repaired it (that self-repair is why the report read as "it fixes itself as soon as Claude writes a line"). ⚠️ **The move is RELATIVE — up `rows - 1 - cursor_y`, then `\r`, then right `cursor_x` — never `CUP`.** `\x1b[<row>;<col>H` numbers rows from the top of the browser's screen, so it lands correctly only while the browser's row count equals `pane_height`, and nothing guarantees that: `resizeWindow` issues its tmux resize fire-and-forget and returns immediately, so a capture can be taken before a requested resize has applied, and `_onSessionNeedsRefresh` sends no resize at all. Counting up from the last replayed row anchors to the content both ends share. Restoring the cursor makes ROW ALIGNMENT load-bearing on this path: **no transform that can DELETE A LINE may run over a full-history capture**, because every deletion shifts the frame out from under the restored position. Four had accumulated — trailing blank rows stripped by `\n+$`, `stripInkRedrawBloat`, the `CLAUDE_BANNER_PATTERN` trim that cuts everything above the banner, and `LEADING_WHITESPACE_PATTERN` — each correct for a byte stream of successive frames and each wrong for a single rendered frame. ⚠️ **Those skips key on `isFullCapture`, meaning a capture actually came back — never on `?full=1` alone.** When `captureActivePaneBuffer` returns null (ENOBUFS, a timeout, a vanished pane, or a session with no mux at all) the reply falls back to `session.terminalBuffer`, which IS a byte stream and must still be stripped; gating on the query flag returned it whole, and a direct-PTY session takes that path on every first selection rather than only during an outage. ⚠️ A capture holding nothing visible (`hasVisibleContent`) returns `''`, because the caller reads an empty capture as "unavailable" and keeps its byte history — retaining trailing blank rows made an all-blank pane non-empty, which would have replaced real history with a blank screen from the server side, where `_replayWouldShrinkBuffer` cannot see it. ⚠️ **"One line per screen row" holds only where no row was hard-wrapped**: `-J` joins a wrapped row into its logical line (measured: a 100-character line in a 40-column pane captures as 10 lines against a 12-row pane), and the counts reconcile only once the browser xterm re-wraps at the same width — the same assumption `_estimateReplayRows` already documents. Tests: `test/tmux-capture-full-history.test.ts` covers the cursor move, the trim pairing and `hasVisibleContent`; `test/routes/session-routes.test.ts` covers a surviving blank first row, an unstripped byte-history fallback, and an empty capture leaving history intact. ⚠️ **The re-pull must never DOWNGRADE the buffer** (#205 round 2): the same reasoning that makes it a win for a shell pane makes it destructive for a repaint-mode CLI pane, where tmux keeps no history of its own (`history_size≈0` measured for a Claude pane) and the capture is roughly ONE frame while xterm may hold hundreds of rows of replayed frames — `_resetTerminalForReplay()` + rewrite then deletes history mid-scroll ("goes back a bit, repeats blocks, gets worse the further up I go"; measured A/B on a live pane: 341 rows → 42 with the guard off). `_replayWouldShrinkBuffer()` (terminal-ui.js) estimates the capture's rendered rows — escape sequences stripped, `capture-pane -J` re-wrapping accounted for — and the pull is skipped when that is more than one screen short of `buffer.active.length`. The one-screen tolerance matters: both sides are estimates (the buffer length counts trailing blank rows), so only a clear downgrade is refused. A refused session joins `_fullHistoryRepullUseless`, raising its cooldown from 4s to 60s so a hollow pane stops re-fetching megabytes on every scroll-up. Tests: `test/tmux-capture-full-history.test.ts`, `test/tmux-scrollback-eol.test.ts`, `test/terminal-scroll-routing.test.ts`, `test/terminal-flush-budget.test.ts`. -**Repair while reading (#814)** is a manual **Reload history** action inside the existing history banner on desktop and touch devices, enabled by default and toggleable per device in Settings → Terminal & Input → Scrolling & rendering (`historyReloadAction`). It is offered only for a marked non-shell active session while scrolled away from live output, not detached, not owned by tiles, with no pull or buffer load in flight. `paneHistoryLines` is deliberately not consulted: it is recorded at the last load, so a session first opened empty keeps 0 after the very burst that opens the gap (#814). A revealed truncation notice keeps its message and its **Load full history** control; Reload is appended only when the notice has no load control, or shown alone with a short missing-output message. A reload-only × dismissal lasts until the mark is cleared by a successful `mux-full-history` replay, independently of the notice’s page-long dismissal. Pressing × while loading hides the bar immediately; the in-flight pull continues. Eligibility is cached per active session, with onScroll sampling coalesced to one animation frame on every device; unchanged eligibility never rebuilds the banner. Automatic history pulls and notice reveal stay top-only (#205). Live-output marking covers only live writes: a byte-history (`?tail=`) replay, for example after a burst in a background tab, never marks the session, so that gap relies on the top-of-buffer pull. The manual action forces a content-anchored pull, bypassing the gesture cooldown but retaining the downgrade guard. Any downgrade-refused pull hides Reload until the next successful `mux-full-history` replay; that refusal, not the cached history size, is what retires the action for a pane with no tmux history (fullscreen Claude). A content anchor captures up to 64 visible rows, preserving indentation, and scores candidate alignments by matching viewport context. Each distinct nonblank row contributes at most one point, so repeated TUI borders cannot outvote a distinctive tool result. The best match must cover at least two distinct rows and 60% of the context and must be unique within the search window. Equal-scoring copies are ambiguous, even when all furniture rows match or the distinctive tool row has disappeared; proximity to the expected position does not establish confidence. An isolated first-row match is not trusted: without confident, unambiguous context the old viewport index is retained, while readers already near live output retain their bottom distance. Search is bounded to 2000 rows either side of the expected viewport (at most 4001 candidates / 4064 cached line reads). Live flushes use an xterm marker to track the reading row across scrollback trimming in O(1), and restore it only in the write callback; at-bottom sticky scroll is unchanged. Ordered, session-scoped travel during replay is applied with per-move clamping; a switched-to tab never donates travel. The buffer load opens BEFORE the fetch, so download-time output queues behind the replay instead of being overwritten. Non-replay exits flush the whole queue; replays retain the capture-header cutoff above. A blocked dropped-output recovery stores its session and current attempt, defers without consuming retries, and resumes only for the still-active session. Only an actual `mux-full-history` replay clears the live-output mark and reload dismissal, and a newer live-write generation keeps them marked. The trade-off remains a full synchronous server capture (about 1 s: 1,068 ms median for `capture-pane -p -e -J -S -100000` over 100k lines of 120 characters, 12.1 MB), not a cheap automatic per-output repair. Tests: `test/shell-scroll-history-pull.test.ts`, `test/history-gap-repair.browser.test.ts`. +**Repair while reading (#814)** is a manual **Reload history** action inside the existing history banner on desktop and touch devices, enabled by default and toggleable per device in Settings → Terminal & Input → Scrolling & rendering (`historyReloadAction`). It is offered only for a marked non-shell active session while scrolled away from live output, not detached, not owned by tiles, with no pull or buffer load in flight and no terminal load state for the session (a tab switch sets it before the buffer load opens). `paneHistoryLines` is deliberately not consulted: it is recorded at the last load, so a session first opened empty keeps 0 after the very burst that opens the gap (#814). A revealed truncation notice keeps its message and its **Load full history** control; Reload is appended only when the notice has no load control, or shown alone with a short missing-output message. A reload-only × dismissal lasts until the mark is cleared by a successful `mux-full-history` replay, independently of the notice’s page-long dismissal. Pressing × while loading hides the bar immediately; the in-flight pull continues. Eligibility is cached per active session, with onScroll sampling coalesced to one animation frame on every device; unchanged eligibility never rebuilds the banner. Automatic history pulls and notice reveal stay top-only (#205). Live-output marking covers only live writes: a byte-history (`?tail=`) replay, for example after a burst in a background tab, never marks the session, so that gap relies on the top-of-buffer pull. The manual action forces a content-anchored pull, bypassing the gesture cooldown but retaining the downgrade guard. Any downgrade-refused pull hides Reload until the next successful `mux-full-history` replay; that refusal, not the cached history size, is what retires the action for a pane with no tmux history (fullscreen Claude). A content anchor captures up to 64 visible rows, preserving indentation, and scores candidate alignments by matching viewport context. Each distinct nonblank row contributes at most one point, so repeated TUI borders cannot outvote a distinctive tool result. The best match must cover at least two distinct rows and 60% of the context and must be unique within the search window. Equal-scoring copies are ambiguous, even when all furniture rows match or the distinctive tool row has disappeared; proximity to the expected position does not establish confidence. An isolated first-row match is not trusted: without confident, unambiguous context the old viewport index is retained, while readers already near live output retain their bottom distance. Search is bounded to 2000 rows either side of the expected viewport (at most 4001 candidates / 4064 cached line reads). Live flushes use an xterm marker to track the reading row across scrollback trimming in O(1), and restore it only in the write callback; at-bottom sticky scroll is unchanged. Ordered, session-scoped travel during replay is applied with per-move clamping; a switched-to tab never donates travel. The buffer load opens BEFORE the fetch, so download-time output queues behind the replay instead of being overwritten. Non-replay exits flush the whole queue; replays retain the capture-header cutoff above. A blocked dropped-output recovery stores its session and current attempt, defers without consuming retries, and resumes only for the still-active session. Only an actual `mux-full-history` replay clears the live-output mark and reload dismissal, and a newer live-write generation keeps them marked. The trade-off remains a full synchronous server capture (about 1 s: 1,068 ms median for `capture-pane -p -e -J -S -100000` over 100k lines of 120 characters, 12.1 MB), not a cheap automatic per-output repair. Tests: `test/shell-scroll-history-pull.test.ts`, `test/history-gap-repair.browser.test.ts`. **The partial-history notice is lazy and pane-gated** (`computeHistoryTruncationNotice()` in constants.js, `_renderHistoryTruncationBanner()` / `_setHistoryNoticeRevealed()` in app.js). `truncated` on a terminal response measures the server's BYTE stream, which is not what `full=1` can return: for a pane with no tmux scrollback (fullscreen claude starts in the alternate screen and never writes to the main grid, so `#{history_size}` is 0) the bytes a tail cut drops are old repaint frames. Measured on prod 2026-10-10, every claude pane: the tab-switch tail cut a 1.2 to 6.2 MB stream to 1 MiB, the local scrollback that tail replays into is repeats of the same frames (one pane: 450 non-blank rows, 44 unique, one row 33 times), and `full=1` returned 1 to 5 KB, so **Load full history** could only end in the downgrade refusal while the banner promised "4.8 MB more". The capture therefore reads `#{history_size}` in the SAME `display-message` as the cursor (no extra tmux call), the route returns it as `paneHistoryLines` (absent when the body is not a capture, and for a remote SSH session, whose local pane hosts the remote tmux client and always reports 0 while `full=1` reads the remote history), and a reported 0 hides the notice in every state; a positive count replaces the byte gap in the message. ⚠️ Key the notice decision on `history_size`, never on `alternate_on`: a shell running `less` is in the alternate screen with its whole history still retained (measured, 99,972 rows) and `full=1` returns all of it. The one place `alternate_on` decides is a shell's AUTOMATIC load (`alt=recording`, see Full-scrollback replay): there the question is whether the capture holds the scrollback a nested tmux client keeps in its byte recording, not whether a pull can return more. The notice is also LAZY: it appears only after a wheel/touch gesture reaches the top of the browser buffer and the pull that gesture started has settled (`_maybeLoadMoreHistoryOnScroll`), goes away when a downward gesture is back at live output or the tab switches (`selectSession` nulls `_historyNoticeRevealedFor` before repainting), and its × is sticky per session until reload (`_historyNoticeDismissed`). Tests: `test/history-truncation-notice.test.ts`, `test/history-notice-reveal.test.ts`. diff --git a/src/web/public/app.js b/src/web/public/app.js index 633e4660..3371417d 100644 --- a/src/web/public/app.js +++ b/src/web/public/app.js @@ -6695,6 +6695,7 @@ class CodemanApp { if (state && state.generation !== selectGen) return; this.terminalLoadStates.delete(sessionId); this._updateTerminalLoadTab(sessionId); + if (state) this._syncHistoryReloadAction?.(); } _updateTerminalLoadTab(sessionId) { @@ -9932,6 +9933,7 @@ class CodemanApp { return !!(this.loadAppSettingsFromStorage?.()?.historyReloadAction !== false && session && session.mode !== 'shell' && this._liveOutputSinceFullPull?.has(sessionId) && !this._isLoadingBuffer && + !this.terminalLoadStates?.has(sessionId) && // Tab switches set this before the buffer load opens. !this._fullHistoryRepullInFlight && !this.detachedSessions?.has(sessionId) && !this._historyReloadDismissed?.has(sessionId) && !this._tilesOwnTerminal?.() && !this.isTerminalAtBottom()); diff --git a/test/history-gap-repair.browser.test.ts b/test/history-gap-repair.browser.test.ts index c6566f8b..355e664d 100644 --- a/test/history-gap-repair.browser.test.ts +++ b/test/history-gap-repair.browser.test.ts @@ -13,6 +13,7 @@ type HistoryApp = { sessions: Map<string, object>; activeSessionId: string; hideWelcome(): void; + selectSession(sessionId: string): Promise<void>; _onSessionTerminal(event: { id: string; data: string }): void; _liveOutputSinceFullPull: Set<string>; _fullHistoryRepullInFlight: boolean; @@ -39,6 +40,7 @@ type RepairWindow = Window & { app: HistoryApp; repairTest: { pulls: number; anchor: Anchor | null; inject: boolean }; repairReadiness?: { cols: number; rows: number; frames: number }; + tabLoadTest?: { requested: boolean; release(): void; selection: Promise<void> }; }; const SESSION = 'history-repair-browser'; @@ -467,6 +469,85 @@ describe.each([true, false])('manual history gap repair (touch: %s)', (touch) => }, 60_000); }); +it('hides Reload history while a marked incoming tab capture is pending', async () => { + const { context, page } = await openTerminal(false); + const incoming = `${SESSION}-incoming`; + try { + await page.evaluate((session) => { + const w = window as RepairWindow; + const app = w.app; + app.terminal.scrollToLine(10); + app.sessions.set(session, { id: session, mode: 'omp', status: 'idle', name: 'Incoming history' }); + app._liveOutputSinceFullPull.add(session); + const response = Promise.withResolvers<Response>(); + const realFetch = window.fetch.bind(window); + const terminalBuffer = 'INCOMING-HISTORY\r\n'; + w.tabLoadTest = { + requested: false, + release: () => + response.resolve( + new Response( + JSON.stringify({ + success: true, + data: { terminalBuffer, source: 'mux-full-history', paneHistoryLines: 1, truncated: false }, + }), + { status: 200, headers: { 'Content-Type': 'application/json' } } + ) + ), + selection: Promise.resolve(), + }; + window.fetch = ((input: RequestInfo | URL, init?: RequestInit) => { + const url = String(typeof input === 'string' ? input : ((input as Request).url ?? input)); + if (!url.includes(`/api/sessions/${session}/terminal`)) return realFetch(input, init); + w.tabLoadTest!.requested = true; + return response.promise; + }) as typeof window.fetch; + }, incoming); + expect((await bufferState(page)).baseY - (await bufferState(page)).viewportY).toBeGreaterThan(5); + await page.evaluate((session) => { + const w = window as RepairWindow; + w.tabLoadTest!.selection = w.app.selectSession(session); + }, incoming); + await page.waitForFunction((session) => { + const w = window as RepairWindow; + return ( + w.tabLoadTest?.requested && + w.app.activeSessionId === session && + w.app.terminalLoadStates.has(session) && + w.app._isLoadingBuffer + ); + }, incoming); + const bar = page.locator('#historyTruncationBar'); + expect(await bar.getByRole('button', { name: 'Reload history' }).count()).toBe(0); + expect(await bar.isHidden()).toBe(true); + await page.evaluate(async () => { + const test = (window as RepairWindow).tabLoadTest!; + test.release(); + await test.selection; + }); + await page.waitForFunction((session) => { + const app = (window as RepairWindow).app; + return ( + app.activeSessionId === session && + !app.terminalLoadStates.has(session) && + !app._isLoadingBuffer && + !app.pendingWrites.length && + !app._terminalWriteInFlight + ); + }, incoming); + expect( + await page.evaluate(() => { + const buffer = (window as RepairWindow).app.terminal.buffer.active; + return buffer.getLine(0)?.translateToString(true); + }) + ).toBe('INCOMING-HISTORY'); + } catch (error) { + throw await failureDetails(page, error); + } finally { + await context.close(); + } +}, 60_000); + it('holds an OMP reading row through repeated repaint history and capped live flushes', async () => { const { context, page } = await openTerminal(true); const readingRow = 'Reading tool result: src/engine.ts — preserve this row'; diff --git a/test/shell-scroll-history-pull.test.ts b/test/shell-scroll-history-pull.test.ts index efa5d431..28c3dd94 100644 --- a/test/shell-scroll-history-pull.test.ts +++ b/test/shell-scroll-history-pull.test.ts @@ -987,6 +987,7 @@ describe('manual history banner action', () => { detached: false, enabled: true, loadingBuffer: false, + loadState: false, paneHistoryLines: undefined as number | undefined, ...options, }; @@ -1026,6 +1027,7 @@ describe('manual history banner action', () => { _historyNoticeRevealedFor: null as string | null, _fullHistoryRepullInFlight: Boolean(state.inFlight), _isLoadingBuffer: Boolean(state.loadingBuffer), + terminalLoadStates: new Map(state.loadState ? [['s1', { generation: 1, phase: 'resizing' }]] : []), _paneHistoryLines: new Map<string, number>( state.paneHistoryLines === undefined ? [] : [['s1', Number(state.paneHistoryLines)]] ), @@ -1058,6 +1060,7 @@ describe('manual history banner action', () => { { opts: { paneHistoryLines: 0 }, visible: true }, { opts: { paneHistoryLines: 5 }, visible: true }, { opts: { loadingBuffer: true }, visible: false }, + { opts: { loadState: true }, visible: false }, { opts: { tiles: true }, visible: false }, { opts: { active: false }, visible: false }, { opts: { detached: true }, visible: false }, @@ -1102,6 +1105,18 @@ describe('manual history banner action', () => { expect(bar.hidden).toBe(true); }); + it('shows the action when the matching terminal load state clears', () => { + const { app, bar, button } = fixture({ loadState: true }); + Object.assign(app, { _updateTerminalLoadTab: vi.fn() }); + app._syncHistoryReloadAction(); + expect(bar.hidden).toBe(true); + expect(button()).toBeUndefined(); + loadAppMethod('_clearTerminalLoadState').call(app, 's1', 1); + expect(app.terminalLoadStates.has('s1')).toBe(false); + expect(bar.hidden).toBe(false); + expect(button()!.textContent).toBe('Reload history'); + }); + it('syncs the action after a marked session finishes loading', () => { const { app, bar, button } = fixture({ marked: false }); const owner = (mixin._beginBufferLoad as Function).call(app); From 444f375ac738c3a55a3aa7cd1f29b2054b914787 Mon Sep 17 00:00:00 2001 From: Hadrien Kerlero <199662351+HadrienKerlero@users.noreply.github.com> Date: Tue, 17 Nov 2026 01:52:30 +0100 Subject: [PATCH 08/23] fix(web): retire Reload history after a non-capture answer (#814) - A content-anchored reload answered by anything but mux-full-history (an empty response, or the byte-history fallback for a blank or failed pane capture) adds the session to _historyReloadDismissed until the next mux replay; only a mux replay clears the mark, so each tap repeated a forced, unbounded capture. An error envelope leaves it available. - Only the request still current (active session and select generation) may dismiss: a slow answer from before an A -> B -> A switch must not retire the action a newer capture already cleared. --- docs/architecture-invariants.md | 2 +- src/web/public/app.js | 16 +++++++ test/shell-scroll-history-pull.test.ts | 61 ++++++++++++++++++++++++++ 3 files changed, 78 insertions(+), 1 deletion(-) diff --git a/docs/architecture-invariants.md b/docs/architecture-invariants.md index 0ca83115..eeda066d 100644 --- a/docs/architecture-invariants.md +++ b/docs/architecture-invariants.md @@ -253,7 +253,7 @@ Further detail: the `<prefix>: <title>` form (`w3-myapp: fix the login redirect` **Full-scrollback replay** (COD-164/#148, reworked for #205): `GET /api/sessions/:id/terminal?full=1` returns the ENTIRE tmux scrollback (capture-pane `-e -S -<lines>` bounded by the configured history limit, explicit `maxBuffer` from the terminal-history config, early byte-cap before normalization, CRLF-normalized for shell panes). On success the capture is returned ALONE (`source='mux-full-history'` — it supersedes the byte buffer; no duplication). The first load of each non-shell TUI session per page requests `full=1` (`_fullHistoryLoaded` Set in app.js — the old one-shot `_initialFullBufferLoad` flag was consumed by whichever tab auto-selected, leaving every other TUI tab one frame of history). Shell sessions instead load a bounded window of tmux's RENDERED history on every selection, automatic drop recovery, clear and tile load (`SHELL_LOAD_QUERY` in constants.js: `?full=1&tail=1MiB&lines=10000&alt=recording`): a 100k-line shell capture can be tens of MiB, and automatically parsing it makes tab-switch latency scale with the entire session (`lines=` bounds the synchronous capture-pane, about 8 ms per 1000 lines). They never replay the raw byte recording ahead of the visible frame any more: it holds full-screen repaints (an ssh'd tmux, `less`, any TUI) drawn for the pane height of the moment, and replayed into a terminal of another height each repaint's last newline scrolls its top row into scrollback, so one line tmux holds once showed up dozens of times. Because `lines=` is shallower than xterm's scrollback, the route reports a cut: the capture's `display-message` query also reads `#{history_size}` (`PaneCaptureOptions.capturedHistoryLines`, the same field the route reports as `paneHistoryLines`), and a full capture whose CLIENT bound (`lines=` below the configured `tmuxHistoryLimit`) left lines in tmux comes back `truncated`, `truncationReason: 'tail'`. ⚠️ Only a client bound below the ceiling counts: a request without `lines=` is bounded by the ceiling itself, and on tmux before 3.7 a live pane can hold more than a lowered ceiling, which no request can read. ⚠️ **A pane in the alternate screen keeps no tmux history**, and a nested tmux client (remote SSH and Docker cases, or `tmux`/`ssh -t host tmux` run by hand) holds its pane there, so its full capture is one screen. The same query reads `#{alternate_on}` (`capturedAlternateOn`), and a request carrying `alt=recording` (only `SHELL_LOAD_QUERY`) is then answered the old way, the visible frame over the tailed byte recording, which still carries the scrollback; agents, scroll pulls and **Load full history** never send it. `#{alternate_on}` cannot tell a nested tmux from vim, `less` or `htop`, so a local shell with one of those open takes the same fallback until it exits (the pre-fix load, with its repaint duplicates). Shell FULL history is explicit-button-only; reaching the top during an ordinary wheel/touch gesture must not reset xterm and replay the multi-megabyte capture on its main thread. That gesture instead pulls a BOUNDED window of it (`?full=1&tail=<TERMINAL_TAIL_SIZE>`, so a capture beyond 1 MiB comes back `truncationReason: 'tail'` and the banner offers the rest), and skips the replay when the window holds no more rows than the browser already has. ⚠️ **That skip runs BEFORE the downgrade guard, and it never touches the banner state**: the guard reads "smaller than the browser" as "tmux has nothing more to give", true of an unbounded capture and false of a window cut at the tail size, so a bounded window that reached it marked the session `exhausted` and removed **Load full history** while tmux still held the rest; and re-labelling the banner from a skipped payload would call a terminal that holds all of a Load full history pull "the most recent 1 MiB". A skipped window that came back truncated puts the session on the 60 s cooldown (`_fullHistoryRepullUseless`), because it can never reach anything older than the browser shows and `tail` is applied AFTER the server's synchronous `capture-pane` of the whole history, so each ask costs every client an event-loop stall (about 1 s at 100k lines; measured capture details below); an untruncated one keeps the 4 s cooldown, since it is all of tmux's history and the next burst can add to it. Declining the gesture outright was a dead end: after any burst a shell pane held about one screen of browser scrollback, and the button renders only once a replay was truncated, so a young shell tab had no way back to history tmux still held. Other modes re-pull `full=1` only at the top of the local buffer, and pressing **Load full history** forces the request for any recoverably truncated session (`_maybeRefetchFullHistory`, 4s per-session gesture cooldown, in-flight + tab-switch guards, viewport position held across the replay); Shell full pulls are not retained in the tab cache, so the next switch stays bounded. Chunked replay enqueues 32 KiB pieces across safe yields, appends an xterm parse marker, then releases the live-output gate; output arriving after that release stays ordered behind the snapshot, and the marker callback supplies accurate parse timing. ⚠️ **How the load ENDS depends on where the payload came from**, and `_bufferLoadFinishOpts` (app.js) is the one place that decides it for all four fetch-and-write paths. A payload built from the server's accumulated byte history is current up to the response, so the events queued during the load already appear in it and stay DISCARDED; replaying them would duplicate output, most visibly Ink's cursor-up redraws. A pane capture (`mux-visible` or `mux-full-history`) is current only up to CAPTURE time, so `_finishBufferLoad` replays the queue from the response's own arrival timestamp (`since`) and the pre-capture events stay dropped. ⚠️ **A path that then restores a scroll position must re-take the sticky-scroll baseline** (`_syncStickyScrollBaseline`): the replay runs inside `chunkedTerminalWrite` before its promise resolves, with the terminal freshly reset, so `batchTerminalWrite` samples `_wasAtBottomBeforeWrite` as true and the next `flushPendingWrites` would scroll to the bottom over the restore. ⚠️ The cutoff is a client-side timestamp and the server broadcasts on a batch timer (8ms WebSocket, 16-50ms SSE), so a batch pending when the capture ran arrives after the response and replays although the capture holds it — bounded by one batch interval, and closable only server side by flushing that batch before the capture. Tests for the three: `test/terminal-flush-budget.test.ts` pins which sources flush, `test/terminal-buffer-flush.test.ts` pins the `since` cutoff and the baseline re-take, and `test/capture-load-window.browser.test.ts` drives both against a live server. Live output is separately one-chunk-in-flight: xterm's callback releases each 32/64 KiB write before the next is submitted, keeping the remainder in the app queue where the 128 KiB cap can observe it instead of hiding an unbounded backlog in xterm's private WriteBuffer. While WebSocket owns terminal I/O, parallel SSE terminal/output-recovery events are discarded before JSON parsing; fallback recovery is single-flight per active session so backpressure cannot start overlapping reset+replay cycles. The route exposes capture/prepare totals in `Server-Timing`, while `[TERMINAL-PERF]` separates TTFB, body/JSON, reset+parse and total time for both selection and on-demand full pulls; parse completion is not a browser compositor/GPU paint measurement. The re-pull exists because xterm's buffer is only a WINDOW onto tmux's history and two things shrink it: tmux coalesces bursty output into pane REPAINTS that overwrite rows instead of emitting linefeeds (measured: a 60-line burst added 1 row of browser scrollback and destroyed 34), and a tab switch replays only the visible frame. tmux's own history is intact throughout — the browser just has to ask for it again. Gesture-triggered rather than polling because at a 100k history limit the capture can be megabytes. ⚠️ **The capture ENDS with a cursor move back to the pane's own caret position** (`formatCursorRestore`, from the same `display-message` query the visible-frame path uses). The linear replay otherwise leaves the caret wherever the last character landed — the bottom-most row carrying text, which for an agent CLI is the status line — so the caret sat on the composer's border instead of its input line and every cursor-relative update the CLI sent afterwards was measured from the wrong row, until its next full redraw silently repaired it (that self-repair is why the report read as "it fixes itself as soon as Claude writes a line"). ⚠️ **The move is RELATIVE — up `rows - 1 - cursor_y`, then `\r`, then right `cursor_x` — never `CUP`.** `\x1b[<row>;<col>H` numbers rows from the top of the browser's screen, so it lands correctly only while the browser's row count equals `pane_height`, and nothing guarantees that: `resizeWindow` issues its tmux resize fire-and-forget and returns immediately, so a capture can be taken before a requested resize has applied, and `_onSessionNeedsRefresh` sends no resize at all. Counting up from the last replayed row anchors to the content both ends share. Restoring the cursor makes ROW ALIGNMENT load-bearing on this path: **no transform that can DELETE A LINE may run over a full-history capture**, because every deletion shifts the frame out from under the restored position. Four had accumulated — trailing blank rows stripped by `\n+$`, `stripInkRedrawBloat`, the `CLAUDE_BANNER_PATTERN` trim that cuts everything above the banner, and `LEADING_WHITESPACE_PATTERN` — each correct for a byte stream of successive frames and each wrong for a single rendered frame. ⚠️ **Those skips key on `isFullCapture`, meaning a capture actually came back — never on `?full=1` alone.** When `captureActivePaneBuffer` returns null (ENOBUFS, a timeout, a vanished pane, or a session with no mux at all) the reply falls back to `session.terminalBuffer`, which IS a byte stream and must still be stripped; gating on the query flag returned it whole, and a direct-PTY session takes that path on every first selection rather than only during an outage. ⚠️ A capture holding nothing visible (`hasVisibleContent`) returns `''`, because the caller reads an empty capture as "unavailable" and keeps its byte history — retaining trailing blank rows made an all-blank pane non-empty, which would have replaced real history with a blank screen from the server side, where `_replayWouldShrinkBuffer` cannot see it. ⚠️ **"One line per screen row" holds only where no row was hard-wrapped**: `-J` joins a wrapped row into its logical line (measured: a 100-character line in a 40-column pane captures as 10 lines against a 12-row pane), and the counts reconcile only once the browser xterm re-wraps at the same width — the same assumption `_estimateReplayRows` already documents. Tests: `test/tmux-capture-full-history.test.ts` covers the cursor move, the trim pairing and `hasVisibleContent`; `test/routes/session-routes.test.ts` covers a surviving blank first row, an unstripped byte-history fallback, and an empty capture leaving history intact. ⚠️ **The re-pull must never DOWNGRADE the buffer** (#205 round 2): the same reasoning that makes it a win for a shell pane makes it destructive for a repaint-mode CLI pane, where tmux keeps no history of its own (`history_size≈0` measured for a Claude pane) and the capture is roughly ONE frame while xterm may hold hundreds of rows of replayed frames — `_resetTerminalForReplay()` + rewrite then deletes history mid-scroll ("goes back a bit, repeats blocks, gets worse the further up I go"; measured A/B on a live pane: 341 rows → 42 with the guard off). `_replayWouldShrinkBuffer()` (terminal-ui.js) estimates the capture's rendered rows — escape sequences stripped, `capture-pane -J` re-wrapping accounted for — and the pull is skipped when that is more than one screen short of `buffer.active.length`. The one-screen tolerance matters: both sides are estimates (the buffer length counts trailing blank rows), so only a clear downgrade is refused. A refused session joins `_fullHistoryRepullUseless`, raising its cooldown from 4s to 60s so a hollow pane stops re-fetching megabytes on every scroll-up. Tests: `test/tmux-capture-full-history.test.ts`, `test/tmux-scrollback-eol.test.ts`, `test/terminal-scroll-routing.test.ts`, `test/terminal-flush-budget.test.ts`. -**Repair while reading (#814)** is a manual **Reload history** action inside the existing history banner on desktop and touch devices, enabled by default and toggleable per device in Settings → Terminal & Input → Scrolling & rendering (`historyReloadAction`). It is offered only for a marked non-shell active session while scrolled away from live output, not detached, not owned by tiles, with no pull or buffer load in flight and no terminal load state for the session (a tab switch sets it before the buffer load opens). `paneHistoryLines` is deliberately not consulted: it is recorded at the last load, so a session first opened empty keeps 0 after the very burst that opens the gap (#814). A revealed truncation notice keeps its message and its **Load full history** control; Reload is appended only when the notice has no load control, or shown alone with a short missing-output message. A reload-only × dismissal lasts until the mark is cleared by a successful `mux-full-history` replay, independently of the notice’s page-long dismissal. Pressing × while loading hides the bar immediately; the in-flight pull continues. Eligibility is cached per active session, with onScroll sampling coalesced to one animation frame on every device; unchanged eligibility never rebuilds the banner. Automatic history pulls and notice reveal stay top-only (#205). Live-output marking covers only live writes: a byte-history (`?tail=`) replay, for example after a burst in a background tab, never marks the session, so that gap relies on the top-of-buffer pull. The manual action forces a content-anchored pull, bypassing the gesture cooldown but retaining the downgrade guard. Any downgrade-refused pull hides Reload until the next successful `mux-full-history` replay; that refusal, not the cached history size, is what retires the action for a pane with no tmux history (fullscreen Claude). A content anchor captures up to 64 visible rows, preserving indentation, and scores candidate alignments by matching viewport context. Each distinct nonblank row contributes at most one point, so repeated TUI borders cannot outvote a distinctive tool result. The best match must cover at least two distinct rows and 60% of the context and must be unique within the search window. Equal-scoring copies are ambiguous, even when all furniture rows match or the distinctive tool row has disappeared; proximity to the expected position does not establish confidence. An isolated first-row match is not trusted: without confident, unambiguous context the old viewport index is retained, while readers already near live output retain their bottom distance. Search is bounded to 2000 rows either side of the expected viewport (at most 4001 candidates / 4064 cached line reads). Live flushes use an xterm marker to track the reading row across scrollback trimming in O(1), and restore it only in the write callback; at-bottom sticky scroll is unchanged. Ordered, session-scoped travel during replay is applied with per-move clamping; a switched-to tab never donates travel. The buffer load opens BEFORE the fetch, so download-time output queues behind the replay instead of being overwritten. Non-replay exits flush the whole queue; replays retain the capture-header cutoff above. A blocked dropped-output recovery stores its session and current attempt, defers without consuming retries, and resumes only for the still-active session. Only an actual `mux-full-history` replay clears the live-output mark and reload dismissal, and a newer live-write generation keeps them marked. The trade-off remains a full synchronous server capture (about 1 s: 1,068 ms median for `capture-pane -p -e -J -S -100000` over 100k lines of 120 characters, 12.1 MB), not a cheap automatic per-output repair. Tests: `test/shell-scroll-history-pull.test.ts`, `test/history-gap-repair.browser.test.ts`. +**Repair while reading (#814)** is a manual **Reload history** action inside the existing history banner on desktop and touch devices, enabled by default and toggleable per device in Settings → Terminal & Input → Scrolling & rendering (`historyReloadAction`). It is offered only for a marked non-shell active session while scrolled away from live output, not detached, not owned by tiles, with no pull or buffer load in flight and no terminal load state for the session (a tab switch sets it before the buffer load opens). `paneHistoryLines` is deliberately not consulted: it is recorded at the last load, so a session first opened empty keeps 0 after the very burst that opens the gap (#814). A revealed truncation notice keeps its message and its **Load full history** control; Reload is appended only when the notice has no load control, or shown alone with a short missing-output message. A reload-only × dismissal lasts until the mark is cleared by a successful `mux-full-history` replay, independently of the notice’s page-long dismissal. Pressing × while loading hides the bar immediately; the in-flight pull continues. Eligibility is cached per active session, with onScroll sampling coalesced to one animation frame on every device; unchanged eligibility never rebuilds the banner. Automatic history pulls and notice reveal stay top-only (#205). Live-output marking covers only live writes: a byte-history (`?tail=`) replay, for example after a burst in a background tab, never marks the session, so that gap relies on the top-of-buffer pull. The manual action forces a content-anchored pull, bypassing the gesture cooldown but retaining the downgrade guard. Any downgrade-refused pull hides Reload until the next successful `mux-full-history` replay; that refusal, not the cached history size, is what retires the action for a pane with no tmux history (fullscreen Claude). A manual reload answered by anything but `mux-full-history` (an empty response, or the byte-history fallback the route returns when the pane capture is blank or failed) retires it the same way, since only a mux replay clears the mark; a transient error envelope (`success: false`) leaves it available. A content anchor captures up to 64 visible rows, preserving indentation, and scores candidate alignments by matching viewport context. Each distinct nonblank row contributes at most one point, so repeated TUI borders cannot outvote a distinctive tool result. The best match must cover at least two distinct rows and 60% of the context and must be unique within the search window. Equal-scoring copies are ambiguous, even when all furniture rows match or the distinctive tool row has disappeared; proximity to the expected position does not establish confidence. An isolated first-row match is not trusted: without confident, unambiguous context the old viewport index is retained, while readers already near live output retain their bottom distance. Search is bounded to 2000 rows either side of the expected viewport (at most 4001 candidates / 4064 cached line reads). Live flushes use an xterm marker to track the reading row across scrollback trimming in O(1), and restore it only in the write callback; at-bottom sticky scroll is unchanged. Ordered, session-scoped travel during replay is applied with per-move clamping; a switched-to tab never donates travel. The buffer load opens BEFORE the fetch, so download-time output queues behind the replay instead of being overwritten. Non-replay exits flush the whole queue; replays retain the capture-header cutoff above. A blocked dropped-output recovery stores its session and current attempt, defers without consuming retries, and resumes only for the still-active session. Only an actual `mux-full-history` replay clears the live-output mark and reload dismissal, and a newer live-write generation keeps them marked. The trade-off remains a full synchronous server capture (about 1 s: 1,068 ms median for `capture-pane -p -e -J -S -100000` over 100k lines of 120 characters, 12.1 MB), not a cheap automatic per-output repair. Tests: `test/shell-scroll-history-pull.test.ts`, `test/history-gap-repair.browser.test.ts`. **The partial-history notice is lazy and pane-gated** (`computeHistoryTruncationNotice()` in constants.js, `_renderHistoryTruncationBanner()` / `_setHistoryNoticeRevealed()` in app.js). `truncated` on a terminal response measures the server's BYTE stream, which is not what `full=1` can return: for a pane with no tmux scrollback (fullscreen claude starts in the alternate screen and never writes to the main grid, so `#{history_size}` is 0) the bytes a tail cut drops are old repaint frames. Measured on prod 2026-10-10, every claude pane: the tab-switch tail cut a 1.2 to 6.2 MB stream to 1 MiB, the local scrollback that tail replays into is repeats of the same frames (one pane: 450 non-blank rows, 44 unique, one row 33 times), and `full=1` returned 1 to 5 KB, so **Load full history** could only end in the downgrade refusal while the banner promised "4.8 MB more". The capture therefore reads `#{history_size}` in the SAME `display-message` as the cursor (no extra tmux call), the route returns it as `paneHistoryLines` (absent when the body is not a capture, and for a remote SSH session, whose local pane hosts the remote tmux client and always reports 0 while `full=1` reads the remote history), and a reported 0 hides the notice in every state; a positive count replaces the byte gap in the message. ⚠️ Key the notice decision on `history_size`, never on `alternate_on`: a shell running `less` is in the alternate screen with its whole history still retained (measured, 99,972 rows) and `full=1` returns all of it. The one place `alternate_on` decides is a shell's AUTOMATIC load (`alt=recording`, see Full-scrollback replay): there the question is whether the capture holds the scrollback a nested tmux client keeps in its byte recording, not whether a pull can return more. The notice is also LAZY: it appears only after a wheel/touch gesture reaches the top of the browser buffer and the pull that gesture started has settled (`_maybeLoadMoreHistoryOnScroll`), goes away when a downward gesture is back at live output or the tab switches (`selectSession` nulls `_historyNoticeRevealedFor` before repainting), and its × is sticky per session until reload (`_historyNoticeDismissed`). Tests: `test/history-truncation-notice.test.ts`, `test/history-notice-reveal.test.ts`. diff --git a/src/web/public/app.js b/src/web/public/app.js index 3371417d..5dbce36a 100644 --- a/src/web/public/app.js +++ b/src/web/public/app.js @@ -9703,6 +9703,22 @@ class CodemanApp { // recording its empty data would forget the count and hand the next // gesture back to the paging fallback, the bug this pull exists to avoid. if (selectGen === this._selectGeneration && capture.json?.success !== false) this._notePaneHistory?.(sessionId, payload); + // A manual reload answered by anything but a full mux capture (an empty + // response, or the byte-history fallback the route returns when the pane + // capture is blank or failed) cannot fill the gap, and only a mux replay + // clears the mark: offering it again would repeat the forced capture on + // every tap. Retire it until the next `mux-full-history` replay. Only for + // the request still current: a slow answer from before an A -> B -> A + // switch must not retire the action a newer capture of A already cleared. + if ( + anchor === 'content' && + this.activeSessionId === sessionId && + selectGen === this._selectGeneration && + capture.json?.success !== false && + payload.source !== 'mux-full-history' + ) { + (this._historyReloadDismissed ||= new Set()).add(sessionId); + } const buffer = payload.terminalBuffer; const timing = { trigger: force ? 'full-history-button' : 'full-history-scroll', diff --git a/test/shell-scroll-history-pull.test.ts b/test/shell-scroll-history-pull.test.ts index 28c3dd94..dd50b2e4 100644 --- a/test/shell-scroll-history-pull.test.ts +++ b/test/shell-scroll-history-pull.test.ts @@ -496,6 +496,67 @@ describe('manual full-history recovery while reading (#814)', () => { expect(eligible.call(app)).toBe(false); }); + it.each([ + { kind: 'byte-history fallback', data: { terminalBuffer: lines(400), source: 'history' } }, + { kind: 'empty response', data: { terminalBuffer: '', source: 'history' } }, + ])('retires manual reload after a $kind answer', async ({ data }) => { + const { app, active, urls, liveOutput, reload } = makeScrollApp(); + app._fetchTerminalCapture.mockImplementation(async (url: string) => { + urls.push(url); + return { headersAt: performance.now(), headers: { get: () => '' }, json: { success: true, data } }; + }); + liveOutput(); + active.viewportY -= 5; + const eligible = loadAppMethod('_historyReloadActionEligible'); + expect(eligible.call(app)).toBe(true); + await reload(); + expect(urls).toHaveLength(1); + // Only a mux replay clears the mark, so without retiring the action every + // tap would repeat the forced, unbounded capture. + expect(app._liveOutputSinceFullPull.has('s1')).toBe(true); + active.viewportY = Math.max(0, active.baseY - 5); + expect(eligible.call(app)).toBe(false); + }); + + it('keeps manual reload available after a transient error envelope', async () => { + const { app, active, urls, liveOutput, reload } = makeScrollApp(); + app._fetchTerminalCapture.mockImplementation(async (url: string) => { + urls.push(url); + return { headersAt: performance.now(), headers: { get: () => '' }, json: { success: false, data: {} } }; + }); + liveOutput(); + active.viewportY -= 5; + await reload(); + expect(urls).toHaveLength(1); + expect(loadAppMethod('_historyReloadActionEligible').call(app)).toBe(true); + }); + + it('ignores a fallback answer that arrives after an A -> B -> A switch', async () => { + const { app, active, urls, liveOutput, reload } = makeScrollApp(); + const { promise: answer, resolve: respond } = Promise.withResolvers<void>(); + app._fetchTerminalCapture.mockImplementation(async (url: string) => { + urls.push(url); + await answer; + return { + headersAt: performance.now(), + headers: { get: () => '' }, + json: { success: true, data: { terminalBuffer: lines(400), source: 'history' } }, + }; + }); + liveOutput(); + active.viewportY -= 5; + const pending = reload(); + // The user switched away and back; that newer select's capture already + // cleared the dismissal, so the old request's answer is stale. + app._selectGeneration += 2; + app._historyReloadDismissed.delete('s1'); + respond(); + await pending; + expect(urls).toHaveLength(1); + expect(app._historyReloadDismissed.has('s1')).toBe(false); + expect(loadAppMethod('_historyReloadActionEligible').call(app)).toBe(true); + }); + it.each(['empty', 'tab-switch', 'downgrade', 'bounded-shell', 'rejection'])( 'flushes download-time output on the %s non-replay path', async (exit) => { From bc00ad4335ffa31d1d945fff983de5e50a4ca209 Mon Sep 17 00:00:00 2001 From: Hadrien Kerlero <199662351+HadrienKerlero@users.noreply.github.com> Date: Tue, 17 Nov 2026 19:10:18 +0100 Subject: [PATCH 09/23] fix(web): clear the Reload mark after a drop-recovery capture (#814) - _onSessionNeedsRefresh samples the live-output generation before its fetch and, after replaying a mux-full-history capture, clears _liveOutputSinceFullPull and _historyReloadDismissed while it still owns the active session and the generation is unchanged; the ?tail= fallback never clears them. - test/terminal-viewport-marker.test.ts: gated test driving the real flushPendingWrites over @xterm/headless at a full scrollback; the reading row holds with the marker and drifts without it. - Docs: the anchor sentence matches minimumScore, and the refresh rule is in the Repair while reading paragraph. --- docs/architecture-invariants.md | 2 +- src/web/public/app.js | 12 +++ test/shell-scroll-history-pull.test.ts | 96 ++++++++++++++++++++++ test/terminal-viewport-marker.test.ts | 105 +++++++++++++++++++++++++ 4 files changed, 214 insertions(+), 1 deletion(-) create mode 100644 test/terminal-viewport-marker.test.ts diff --git a/docs/architecture-invariants.md b/docs/architecture-invariants.md index eeda066d..f93b49be 100644 --- a/docs/architecture-invariants.md +++ b/docs/architecture-invariants.md @@ -253,7 +253,7 @@ Further detail: the `<prefix>: <title>` form (`w3-myapp: fix the login redirect` **Full-scrollback replay** (COD-164/#148, reworked for #205): `GET /api/sessions/:id/terminal?full=1` returns the ENTIRE tmux scrollback (capture-pane `-e -S -<lines>` bounded by the configured history limit, explicit `maxBuffer` from the terminal-history config, early byte-cap before normalization, CRLF-normalized for shell panes). On success the capture is returned ALONE (`source='mux-full-history'` — it supersedes the byte buffer; no duplication). The first load of each non-shell TUI session per page requests `full=1` (`_fullHistoryLoaded` Set in app.js — the old one-shot `_initialFullBufferLoad` flag was consumed by whichever tab auto-selected, leaving every other TUI tab one frame of history). Shell sessions instead load a bounded window of tmux's RENDERED history on every selection, automatic drop recovery, clear and tile load (`SHELL_LOAD_QUERY` in constants.js: `?full=1&tail=1MiB&lines=10000&alt=recording`): a 100k-line shell capture can be tens of MiB, and automatically parsing it makes tab-switch latency scale with the entire session (`lines=` bounds the synchronous capture-pane, about 8 ms per 1000 lines). They never replay the raw byte recording ahead of the visible frame any more: it holds full-screen repaints (an ssh'd tmux, `less`, any TUI) drawn for the pane height of the moment, and replayed into a terminal of another height each repaint's last newline scrolls its top row into scrollback, so one line tmux holds once showed up dozens of times. Because `lines=` is shallower than xterm's scrollback, the route reports a cut: the capture's `display-message` query also reads `#{history_size}` (`PaneCaptureOptions.capturedHistoryLines`, the same field the route reports as `paneHistoryLines`), and a full capture whose CLIENT bound (`lines=` below the configured `tmuxHistoryLimit`) left lines in tmux comes back `truncated`, `truncationReason: 'tail'`. ⚠️ Only a client bound below the ceiling counts: a request without `lines=` is bounded by the ceiling itself, and on tmux before 3.7 a live pane can hold more than a lowered ceiling, which no request can read. ⚠️ **A pane in the alternate screen keeps no tmux history**, and a nested tmux client (remote SSH and Docker cases, or `tmux`/`ssh -t host tmux` run by hand) holds its pane there, so its full capture is one screen. The same query reads `#{alternate_on}` (`capturedAlternateOn`), and a request carrying `alt=recording` (only `SHELL_LOAD_QUERY`) is then answered the old way, the visible frame over the tailed byte recording, which still carries the scrollback; agents, scroll pulls and **Load full history** never send it. `#{alternate_on}` cannot tell a nested tmux from vim, `less` or `htop`, so a local shell with one of those open takes the same fallback until it exits (the pre-fix load, with its repaint duplicates). Shell FULL history is explicit-button-only; reaching the top during an ordinary wheel/touch gesture must not reset xterm and replay the multi-megabyte capture on its main thread. That gesture instead pulls a BOUNDED window of it (`?full=1&tail=<TERMINAL_TAIL_SIZE>`, so a capture beyond 1 MiB comes back `truncationReason: 'tail'` and the banner offers the rest), and skips the replay when the window holds no more rows than the browser already has. ⚠️ **That skip runs BEFORE the downgrade guard, and it never touches the banner state**: the guard reads "smaller than the browser" as "tmux has nothing more to give", true of an unbounded capture and false of a window cut at the tail size, so a bounded window that reached it marked the session `exhausted` and removed **Load full history** while tmux still held the rest; and re-labelling the banner from a skipped payload would call a terminal that holds all of a Load full history pull "the most recent 1 MiB". A skipped window that came back truncated puts the session on the 60 s cooldown (`_fullHistoryRepullUseless`), because it can never reach anything older than the browser shows and `tail` is applied AFTER the server's synchronous `capture-pane` of the whole history, so each ask costs every client an event-loop stall (about 1 s at 100k lines; measured capture details below); an untruncated one keeps the 4 s cooldown, since it is all of tmux's history and the next burst can add to it. Declining the gesture outright was a dead end: after any burst a shell pane held about one screen of browser scrollback, and the button renders only once a replay was truncated, so a young shell tab had no way back to history tmux still held. Other modes re-pull `full=1` only at the top of the local buffer, and pressing **Load full history** forces the request for any recoverably truncated session (`_maybeRefetchFullHistory`, 4s per-session gesture cooldown, in-flight + tab-switch guards, viewport position held across the replay); Shell full pulls are not retained in the tab cache, so the next switch stays bounded. Chunked replay enqueues 32 KiB pieces across safe yields, appends an xterm parse marker, then releases the live-output gate; output arriving after that release stays ordered behind the snapshot, and the marker callback supplies accurate parse timing. ⚠️ **How the load ENDS depends on where the payload came from**, and `_bufferLoadFinishOpts` (app.js) is the one place that decides it for all four fetch-and-write paths. A payload built from the server's accumulated byte history is current up to the response, so the events queued during the load already appear in it and stay DISCARDED; replaying them would duplicate output, most visibly Ink's cursor-up redraws. A pane capture (`mux-visible` or `mux-full-history`) is current only up to CAPTURE time, so `_finishBufferLoad` replays the queue from the response's own arrival timestamp (`since`) and the pre-capture events stay dropped. ⚠️ **A path that then restores a scroll position must re-take the sticky-scroll baseline** (`_syncStickyScrollBaseline`): the replay runs inside `chunkedTerminalWrite` before its promise resolves, with the terminal freshly reset, so `batchTerminalWrite` samples `_wasAtBottomBeforeWrite` as true and the next `flushPendingWrites` would scroll to the bottom over the restore. ⚠️ The cutoff is a client-side timestamp and the server broadcasts on a batch timer (8ms WebSocket, 16-50ms SSE), so a batch pending when the capture ran arrives after the response and replays although the capture holds it — bounded by one batch interval, and closable only server side by flushing that batch before the capture. Tests for the three: `test/terminal-flush-budget.test.ts` pins which sources flush, `test/terminal-buffer-flush.test.ts` pins the `since` cutoff and the baseline re-take, and `test/capture-load-window.browser.test.ts` drives both against a live server. Live output is separately one-chunk-in-flight: xterm's callback releases each 32/64 KiB write before the next is submitted, keeping the remainder in the app queue where the 128 KiB cap can observe it instead of hiding an unbounded backlog in xterm's private WriteBuffer. While WebSocket owns terminal I/O, parallel SSE terminal/output-recovery events are discarded before JSON parsing; fallback recovery is single-flight per active session so backpressure cannot start overlapping reset+replay cycles. The route exposes capture/prepare totals in `Server-Timing`, while `[TERMINAL-PERF]` separates TTFB, body/JSON, reset+parse and total time for both selection and on-demand full pulls; parse completion is not a browser compositor/GPU paint measurement. The re-pull exists because xterm's buffer is only a WINDOW onto tmux's history and two things shrink it: tmux coalesces bursty output into pane REPAINTS that overwrite rows instead of emitting linefeeds (measured: a 60-line burst added 1 row of browser scrollback and destroyed 34), and a tab switch replays only the visible frame. tmux's own history is intact throughout — the browser just has to ask for it again. Gesture-triggered rather than polling because at a 100k history limit the capture can be megabytes. ⚠️ **The capture ENDS with a cursor move back to the pane's own caret position** (`formatCursorRestore`, from the same `display-message` query the visible-frame path uses). The linear replay otherwise leaves the caret wherever the last character landed — the bottom-most row carrying text, which for an agent CLI is the status line — so the caret sat on the composer's border instead of its input line and every cursor-relative update the CLI sent afterwards was measured from the wrong row, until its next full redraw silently repaired it (that self-repair is why the report read as "it fixes itself as soon as Claude writes a line"). ⚠️ **The move is RELATIVE — up `rows - 1 - cursor_y`, then `\r`, then right `cursor_x` — never `CUP`.** `\x1b[<row>;<col>H` numbers rows from the top of the browser's screen, so it lands correctly only while the browser's row count equals `pane_height`, and nothing guarantees that: `resizeWindow` issues its tmux resize fire-and-forget and returns immediately, so a capture can be taken before a requested resize has applied, and `_onSessionNeedsRefresh` sends no resize at all. Counting up from the last replayed row anchors to the content both ends share. Restoring the cursor makes ROW ALIGNMENT load-bearing on this path: **no transform that can DELETE A LINE may run over a full-history capture**, because every deletion shifts the frame out from under the restored position. Four had accumulated — trailing blank rows stripped by `\n+$`, `stripInkRedrawBloat`, the `CLAUDE_BANNER_PATTERN` trim that cuts everything above the banner, and `LEADING_WHITESPACE_PATTERN` — each correct for a byte stream of successive frames and each wrong for a single rendered frame. ⚠️ **Those skips key on `isFullCapture`, meaning a capture actually came back — never on `?full=1` alone.** When `captureActivePaneBuffer` returns null (ENOBUFS, a timeout, a vanished pane, or a session with no mux at all) the reply falls back to `session.terminalBuffer`, which IS a byte stream and must still be stripped; gating on the query flag returned it whole, and a direct-PTY session takes that path on every first selection rather than only during an outage. ⚠️ A capture holding nothing visible (`hasVisibleContent`) returns `''`, because the caller reads an empty capture as "unavailable" and keeps its byte history — retaining trailing blank rows made an all-blank pane non-empty, which would have replaced real history with a blank screen from the server side, where `_replayWouldShrinkBuffer` cannot see it. ⚠️ **"One line per screen row" holds only where no row was hard-wrapped**: `-J` joins a wrapped row into its logical line (measured: a 100-character line in a 40-column pane captures as 10 lines against a 12-row pane), and the counts reconcile only once the browser xterm re-wraps at the same width — the same assumption `_estimateReplayRows` already documents. Tests: `test/tmux-capture-full-history.test.ts` covers the cursor move, the trim pairing and `hasVisibleContent`; `test/routes/session-routes.test.ts` covers a surviving blank first row, an unstripped byte-history fallback, and an empty capture leaving history intact. ⚠️ **The re-pull must never DOWNGRADE the buffer** (#205 round 2): the same reasoning that makes it a win for a shell pane makes it destructive for a repaint-mode CLI pane, where tmux keeps no history of its own (`history_size≈0` measured for a Claude pane) and the capture is roughly ONE frame while xterm may hold hundreds of rows of replayed frames — `_resetTerminalForReplay()` + rewrite then deletes history mid-scroll ("goes back a bit, repeats blocks, gets worse the further up I go"; measured A/B on a live pane: 341 rows → 42 with the guard off). `_replayWouldShrinkBuffer()` (terminal-ui.js) estimates the capture's rendered rows — escape sequences stripped, `capture-pane -J` re-wrapping accounted for — and the pull is skipped when that is more than one screen short of `buffer.active.length`. The one-screen tolerance matters: both sides are estimates (the buffer length counts trailing blank rows), so only a clear downgrade is refused. A refused session joins `_fullHistoryRepullUseless`, raising its cooldown from 4s to 60s so a hollow pane stops re-fetching megabytes on every scroll-up. Tests: `test/tmux-capture-full-history.test.ts`, `test/tmux-scrollback-eol.test.ts`, `test/terminal-scroll-routing.test.ts`, `test/terminal-flush-budget.test.ts`. -**Repair while reading (#814)** is a manual **Reload history** action inside the existing history banner on desktop and touch devices, enabled by default and toggleable per device in Settings → Terminal & Input → Scrolling & rendering (`historyReloadAction`). It is offered only for a marked non-shell active session while scrolled away from live output, not detached, not owned by tiles, with no pull or buffer load in flight and no terminal load state for the session (a tab switch sets it before the buffer load opens). `paneHistoryLines` is deliberately not consulted: it is recorded at the last load, so a session first opened empty keeps 0 after the very burst that opens the gap (#814). A revealed truncation notice keeps its message and its **Load full history** control; Reload is appended only when the notice has no load control, or shown alone with a short missing-output message. A reload-only × dismissal lasts until the mark is cleared by a successful `mux-full-history` replay, independently of the notice’s page-long dismissal. Pressing × while loading hides the bar immediately; the in-flight pull continues. Eligibility is cached per active session, with onScroll sampling coalesced to one animation frame on every device; unchanged eligibility never rebuilds the banner. Automatic history pulls and notice reveal stay top-only (#205). Live-output marking covers only live writes: a byte-history (`?tail=`) replay, for example after a burst in a background tab, never marks the session, so that gap relies on the top-of-buffer pull. The manual action forces a content-anchored pull, bypassing the gesture cooldown but retaining the downgrade guard. Any downgrade-refused pull hides Reload until the next successful `mux-full-history` replay; that refusal, not the cached history size, is what retires the action for a pane with no tmux history (fullscreen Claude). A manual reload answered by anything but `mux-full-history` (an empty response, or the byte-history fallback the route returns when the pane capture is blank or failed) retires it the same way, since only a mux replay clears the mark; a transient error envelope (`success: false`) leaves it available. A content anchor captures up to 64 visible rows, preserving indentation, and scores candidate alignments by matching viewport context. Each distinct nonblank row contributes at most one point, so repeated TUI borders cannot outvote a distinctive tool result. The best match must cover at least two distinct rows and 60% of the context and must be unique within the search window. Equal-scoring copies are ambiguous, even when all furniture rows match or the distinctive tool row has disappeared; proximity to the expected position does not establish confidence. An isolated first-row match is not trusted: without confident, unambiguous context the old viewport index is retained, while readers already near live output retain their bottom distance. Search is bounded to 2000 rows either side of the expected viewport (at most 4001 candidates / 4064 cached line reads). Live flushes use an xterm marker to track the reading row across scrollback trimming in O(1), and restore it only in the write callback; at-bottom sticky scroll is unchanged. Ordered, session-scoped travel during replay is applied with per-move clamping; a switched-to tab never donates travel. The buffer load opens BEFORE the fetch, so download-time output queues behind the replay instead of being overwritten. Non-replay exits flush the whole queue; replays retain the capture-header cutoff above. A blocked dropped-output recovery stores its session and current attempt, defers without consuming retries, and resumes only for the still-active session. Only an actual `mux-full-history` replay clears the live-output mark and reload dismissal, and a newer live-write generation keeps them marked. The trade-off remains a full synchronous server capture (about 1 s: 1,068 ms median for `capture-pane -p -e -J -S -100000` over 100k lines of 120 characters, 12.1 MB), not a cheap automatic per-output repair. Tests: `test/shell-scroll-history-pull.test.ts`, `test/history-gap-repair.browser.test.ts`. +**Repair while reading (#814)** is a manual **Reload history** action inside the existing history banner on desktop and touch devices, enabled by default and toggleable per device in Settings → Terminal & Input → Scrolling & rendering (`historyReloadAction`). It is offered only for a marked non-shell active session while scrolled away from live output, not detached, not owned by tiles, with no pull or buffer load in flight and no terminal load state for the session (a tab switch sets it before the buffer load opens). `paneHistoryLines` is deliberately not consulted: it is recorded at the last load, so a session first opened empty keeps 0 after the very burst that opens the gap (#814). A revealed truncation notice keeps its message and its **Load full history** control; Reload is appended only when the notice has no load control, or shown alone with a short missing-output message. A reload-only × dismissal lasts until the mark is cleared by a successful `mux-full-history` replay, independently of the notice’s page-long dismissal. Pressing × while loading hides the bar immediately; the in-flight pull continues. Eligibility is cached per active session, with onScroll sampling coalesced to one animation frame on every device; unchanged eligibility never rebuilds the banner. Automatic history pulls and notice reveal stay top-only (#205). Live-output marking covers only live writes: a byte-history (`?tail=`) replay, for example after a burst in a background tab, never marks the session, so that gap relies on the top-of-buffer pull. The manual action forces a content-anchored pull, bypassing the gesture cooldown but retaining the downgrade guard. Any downgrade-refused pull hides Reload until the next successful `mux-full-history` replay; that refusal, not the cached history size, is what retires the action for a pane with no tmux history (fullscreen Claude). A manual reload answered by anything but `mux-full-history` (an empty response, or the byte-history fallback the route returns when the pane capture is blank or failed) retires it the same way, since only a mux replay clears the mark; a transient error envelope (`success: false`) leaves it available. A content anchor captures up to 64 visible rows, preserving indentation, and scores candidate alignments by matching viewport context. Each distinct nonblank row contributes at most one point, so repeated TUI borders cannot outvote a distinctive tool result. The best match must score at least 60% of the distinct rows and at least two of them, capped at the number of distinct rows, so a viewport with one distinct row (a lone tool result among blanks) matches on that row alone; it must also be unique within the search window. Equal-scoring copies are ambiguous, even when all furniture rows match or the distinctive tool row has disappeared; proximity to the expected position does not establish confidence. An isolated first-row match is not trusted: without confident, unambiguous context the old viewport index is retained, while readers already near live output retain their bottom distance. Search is bounded to 2000 rows either side of the expected viewport (at most 4001 candidates / 4064 cached line reads). Live flushes use an xterm marker to track the reading row across scrollback trimming in O(1), and restore it only in the write callback; at-bottom sticky scroll is unchanged. Ordered, session-scoped travel during replay is applied with per-move clamping; a switched-to tab never donates travel. The buffer load opens BEFORE the fetch, so download-time output queues behind the replay instead of being overwritten. Non-replay exits flush the whole queue; replays retain the capture-header cutoff above. A blocked dropped-output recovery stores its session and current attempt, defers without consuming retries, and resumes only for the still-active session. Only an actual `mux-full-history` replay clears the live-output mark and reload dismissal, and a newer live-write generation keeps them marked. The drop-recovery refresh (`_onSessionNeedsRefresh`) follows the same rule: it clears both after replaying a `mux-full-history` capture, only while it still owns the active session and the live-output generation sampled before its fetch is unchanged; its `?tail=` fallback never clears them. The trade-off remains a full synchronous server capture (about 1 s: 1,068 ms median for `capture-pane -p -e -J -S -100000` over 100k lines of 120 characters, 12.1 MB), not a cheap automatic per-output repair. Tests: `test/shell-scroll-history-pull.test.ts`, `test/history-gap-repair.browser.test.ts`. **The partial-history notice is lazy and pane-gated** (`computeHistoryTruncationNotice()` in constants.js, `_renderHistoryTruncationBanner()` / `_setHistoryNoticeRevealed()` in app.js). `truncated` on a terminal response measures the server's BYTE stream, which is not what `full=1` can return: for a pane with no tmux scrollback (fullscreen claude starts in the alternate screen and never writes to the main grid, so `#{history_size}` is 0) the bytes a tail cut drops are old repaint frames. Measured on prod 2026-10-10, every claude pane: the tab-switch tail cut a 1.2 to 6.2 MB stream to 1 MiB, the local scrollback that tail replays into is repeats of the same frames (one pane: 450 non-blank rows, 44 unique, one row 33 times), and `full=1` returned 1 to 5 KB, so **Load full history** could only end in the downgrade refusal while the banner promised "4.8 MB more". The capture therefore reads `#{history_size}` in the SAME `display-message` as the cursor (no extra tmux call), the route returns it as `paneHistoryLines` (absent when the body is not a capture, and for a remote SSH session, whose local pane hosts the remote tmux client and always reports 0 while `full=1` reads the remote history), and a reported 0 hides the notice in every state; a positive count replaces the byte gap in the message. ⚠️ Key the notice decision on `history_size`, never on `alternate_on`: a shell running `less` is in the alternate screen with its whole history still retained (measured, 99,972 rows) and `full=1` returns all of it. The one place `alternate_on` decides is a shell's AUTOMATIC load (`alt=recording`, see Full-scrollback replay): there the question is whether the capture holds the scrollback a nested tmux client keeps in its byte recording, not whether a pull can return more. The notice is also LAZY: it appears only after a wheel/touch gesture reaches the top of the browser buffer and the pull that gesture started has settled (`_maybeLoadMoreHistoryOnScroll`), goes away when a downward gesture is back at live output or the tab switches (`selectSession` nulls `_historyNoticeRevealedFor` before repainting), and its × is sticky per session until reload (`_historyNoticeDismissed`). Tests: `test/history-truncation-notice.test.ts`, `test/history-notice-reveal.test.ts`. diff --git a/src/web/public/app.js b/src/web/public/app.js index 5dbce36a..e8cdedea 100644 --- a/src/web/public/app.js +++ b/src/web/public/app.js @@ -3495,6 +3495,8 @@ class CodemanApp { // TUI modes still recover the whole picture, with the downgrade guard for // repaint-mode panes whose tmux capture can be smaller than xterm's buffer. const useFullHistory = this.sessions.get(sessionId)?.mode !== 'shell'; + // Keep live output received during the capture marked for another full-history pull. + const liveOutputGen = this._liveOutputGen?.get(sessionId) || 0; let capture = await this._fetchTerminalCapture( useFullHistory ? `/api/sessions/${sessionId}/terminal?full=1` @@ -3535,6 +3537,16 @@ class CodemanApp { undefined, this._bufferLoadFinishOpts(data, headersReceivedAt) ); + if ( + this.activeSessionId === sessionId && + this._terminalRefreshOwner === refreshOwner && + data.source === 'mux-full-history' && + (this._liveOutputGen?.get(sessionId) || 0) === liveOutputGen + ) { + this._liveOutputSinceFullPull?.delete(sessionId); + this._historyReloadDismissed?.delete(sessionId); + this._syncHistoryReloadAction?.(); + } // A tail fetch can be partial, and the banner would otherwise keep // describing the pre-refresh buffer (#258). this._setHistoryTruncation(sessionId, data); diff --git a/test/shell-scroll-history-pull.test.ts b/test/shell-scroll-history-pull.test.ts index dd50b2e4..685140ac 100644 --- a/test/shell-scroll-history-pull.test.ts +++ b/test/shell-scroll-history-pull.test.ts @@ -1354,3 +1354,99 @@ describe('selectSession only clears live-output marks for actual full mux captur expect(Reflect.get(app, '_liveOutputSinceFullPull').has('s1')).toBe(source !== 'mux-full-history'); }); }); + +describe('drop-recovery refresh clears the live-output mark only for a mux capture', () => { + function makeRefreshApp(source = 'mux-full-history') { + const errors = vi.fn(); + const refresh = loadAppMethod('_onSessionNeedsRefresh', { + console: { error: errors }, + computeRewriteScrollLine: () => null, + }); + const { app } = makeApp('omp', { bufferRows: 30, capture: lines(60), payload: { source } }); + const recovery = Object.assign(app, { + _tilesOwnTerminal: () => false, + _markTerminalBufferReconciled: vi.fn(), + sendResize: vi.fn(), + _localEchoOverlay: { rerender: vi.fn() }, + _liveOutputSinceFullPull: new Set(['s1']), + _liveOutputGen: new Map([['s1', 7]]), + _historyReloadDismissed: new Set(['s1']), + _syncHistoryReloadAction: vi.fn(), + }); + Object.assign(app.terminal, { scrollToBottom: vi.fn() }); + return { app: recovery, refresh, errors }; + } + + it('clears the mark and dismissal after replaying a full mux capture', async () => { + const { app, refresh, errors } = makeRefreshApp(); + expect(await refresh.call(app)).toBe(true); + expect(errors).not.toHaveBeenCalled(); + expect(app._fetchTerminalCapture).toHaveBeenCalledWith('/api/sessions/s1/terminal?full=1', { full: true }); + expect(app.chunkedTerminalWrite).toHaveBeenCalledOnce(); + expect(app._liveOutputSinceFullPull.has('s1')).toBe(false); + expect(app._historyReloadDismissed.has('s1')).toBe(false); + // The clear syncs once, and the real truncation-banner update syncs again. + expect(app._syncHistoryReloadAction).toHaveBeenCalledTimes(2); + }); + + it('keeps the mark and dismissal for a history answer', async () => { + const { app, refresh, errors } = makeRefreshApp('history'); + expect(await refresh.call(app)).toBe(true); + expect(errors).not.toHaveBeenCalled(); + expect(app.chunkedTerminalWrite).toHaveBeenCalledOnce(); + expect(app._liveOutputSinceFullPull.has('s1')).toBe(true); + expect(app._historyReloadDismissed.has('s1')).toBe(true); + expect(app._syncHistoryReloadAction).toHaveBeenCalledOnce(); + }); + + it('keeps the mark and dismissal when live output arrives during the fetch', async () => { + const { app, refresh, errors } = makeRefreshApp(); + const fetchCapture = app._fetchTerminalCapture.getMockImplementation()!; + app._fetchTerminalCapture.mockImplementation(async (url) => { + app._liveOutputGen.set('s1', 8); + return fetchCapture(url); + }); + expect(await refresh.call(app)).toBe(true); + expect(errors).not.toHaveBeenCalled(); + expect(app.chunkedTerminalWrite).toHaveBeenCalledOnce(); + expect(app._liveOutputSinceFullPull.has('s1')).toBe(true); + expect(app._historyReloadDismissed.has('s1')).toBe(true); + expect(app._syncHistoryReloadAction).toHaveBeenCalledOnce(); + }); + + it('keeps the mark and dismissal when a full mux capture falls back to a history tail', async () => { + const { app, refresh, errors } = makeRefreshApp(); + app._replayWouldShrinkBuffer = vi.fn(() => true); + app._fetchTerminalCapture.mockResolvedValueOnce({ + headersAt: performance.now(), + headers: { get: () => '' }, + json: { data: { terminalBuffer: lines(10), source: 'mux-full-history' } }, + }); + app._fetchTerminalCapture.mockResolvedValueOnce({ + headersAt: performance.now(), + headers: { get: () => '' }, + json: { data: { terminalBuffer: lines(60), source: 'history' } }, + }); + expect(await refresh.call(app)).toBe(true); + expect(errors).not.toHaveBeenCalled(); + expect(app._fetchTerminalCapture).toHaveBeenLastCalledWith(`/api/sessions/s1/terminal?tail=${TERMINAL_TAIL_SIZE}`); + expect(app.chunkedTerminalWrite).toHaveBeenCalledOnce(); + expect(app._liveOutputSinceFullPull.has('s1')).toBe(true); + expect(app._historyReloadDismissed.has('s1')).toBe(true); + expect(app._syncHistoryReloadAction).toHaveBeenCalledOnce(); + }); + + it.each(['session', 'owner'])('keeps the mark when the refresh loses its %s during replay', async (changed) => { + const { app, refresh, errors } = makeRefreshApp(); + app.chunkedTerminalWrite.mockImplementationOnce(async () => { + if (changed === 'session') app.activeSessionId = 's2'; + else Reflect.set(app, '_terminalRefreshOwner', { sessionId: 's1' }); + return { parsedAt: performance.now(), bufferLength: 400, completed: true }; + }); + expect(await refresh.call(app)).toBe(true); + expect(errors).not.toHaveBeenCalled(); + expect(app._liveOutputSinceFullPull.has('s1')).toBe(true); + expect(app._historyReloadDismissed.has('s1')).toBe(true); + expect(app._syncHistoryReloadAction).not.toHaveBeenCalled(); + }); +}); diff --git a/test/terminal-viewport-marker.test.ts b/test/terminal-viewport-marker.test.ts new file mode 100644 index 00000000..3f241009 --- /dev/null +++ b/test/terminal-viewport-marker.test.ts @@ -0,0 +1,105 @@ +/** + * Live flushes at the scrollback cap must preserve the row being read, not its + * absolute buffer index. Use real asynchronous xterm parsing so markers track + * circular-buffer trimming before the mixin restores the viewport (#814). + */ +import { readFileSync } from 'node:fs'; +import { resolve } from 'node:path'; +import vm from 'node:vm'; +import { describe, expect, it } from 'vitest'; +import xtermHeadless, { type Terminal as HeadlessTerminal } from '@xterm/headless'; + +const { Terminal } = xtermHeadless as unknown as { + Terminal: new (opts: Record<string, unknown>) => HeadlessTerminal; +}; + +const read = (rel: string) => readFileSync(resolve(import.meta.dirname, '..', rel), 'utf8'); +const write = (terminal: HeadlessTerminal, data: string) => new Promise<void>((done) => terminal.write(data, done)); +const topRow = (terminal: HeadlessTerminal) => { + const buffer = terminal.buffer.active; + return buffer.getLine(buffer.viewportY)?.translateToString(true); +}; + +function loadHarness(terminal: HeadlessTerminal) { + const CodemanApp = function CodemanApp(this: unknown) {}; + const context = vm.createContext({ + CodemanApp, + window: {}, + globalThis: {}, + document: { getElementById: () => null, querySelector: () => null }, + console, + MobileDetection: { isTouchDevice: () => false, getDeviceType: () => 'desktop' }, + Object, + performance, + setTimeout, + clearTimeout, + }); + vm.runInContext(read('src/web/public/constants.js'), context, { filename: 'constants.js' }); + vm.runInContext(read('src/web/public/terminal-ui.js'), context, { filename: 'terminal-ui.js' }); + + const app = new (CodemanApp as unknown as new () => Record<string, any>)(); + Object.assign(app, { + terminal, + pendingWrites: [], + sessions: new Map([['reading', { mode: 'claude' }]]), + activeSessionId: 'reading', + _isLoadingBuffer: false, + _wasAtBottomBeforeWrite: false, + _localEchoOverlay: null, + isTerminalAtBottom: () => terminal.buffer.active.viewportY === terminal.buffer.active.baseY, + _scheduleTerminalWriteFlush: () => {}, + _noteMobileImeAuthoritativeOutput: () => {}, + _hasRecentUserScrollUp: () => false, + _syncHistoryReloadAction: () => {}, + }); + return app; +} + +async function flushAtScrollbackCap(markersEnabled: boolean) { + const terminal = new Terminal({ cols: 80, rows: 10, scrollback: 100, allowProposedApi: true }); + try { + // Hide only the marker API for the negative control; writes, buffer trims, + // scrolling, and _restoreTerminalViewport remain the real implementations. + if (!markersEnabled) Object.defineProperty(terminal, 'registerMarker', { value: undefined }); + const app = loadHarness(terminal); + await write(terminal, Array.from({ length: 200 }, (_, i) => `line ${i}\r\n`).join('')); + expect(terminal.buffer.active.baseY).toBe(100); + + const buffer = terminal.buffer.active; + let readingRow = -1; + for (let row = 0; row < buffer.length; row++) { + if (buffer.getLine(row)?.translateToString(true) === 'line 140') { + readingRow = row; + break; + } + } + expect(readingRow).toBeGreaterThanOrEqual(0); + terminal.scrollToLine(readingRow); + expect(topRow(terminal)).toBe('line 140'); + expect(app.isTerminalAtBottom()).toBe(false); + + for (let flush = 0; flush < 5; flush++) { + app.pendingWrites.push(Array.from({ length: 4 }, (_, i) => `line ${200 + flush * 4 + i}\r\n`).join('')); + app.flushPendingWrites(); + // This barrier runs after the flush's write callback, including its + // viewport restoration. No wall-clock delay stands in for parsing. + await write(terminal, ''); + expect(app._terminalWriteInFlight).toBe(false); + } + return topRow(terminal); + } finally { + terminal.dispose(); + } +} + +describe('live terminal viewport at the scrollback cap', () => { + it('keeps line 140 visible across five flushes using xterm markers', async () => { + expect(await flushAtScrollbackCap(true)).toBe('line 140'); + }); + + it('discriminates against absolute-index restoration without markers', async () => { + const row = await flushAtScrollbackCap(false); + expect(row).not.toBe('line 140'); + expect(row).toBe('line 160'); + }); +}); From b3698756a27196345104c6b3084b360f4a5c3d1f Mon Sep 17 00:00:00 2001 From: Hadrien Kerlero <199662351+HadrienKerlero@users.noreply.github.com> Date: Wed, 18 Nov 2026 17:27:02 +0100 Subject: [PATCH 10/23] fix(web): retire Reload history on the drop-recovery shrink fallback (#814) - _onSessionNeedsRefresh adds the session to _historyReloadDismissed when the full capture would shrink the buffer and it falls back to ?tail=, past the ownership guard, so a no-history pane is not re-captured by the next tap. - Changeset: scope the note to agent sessions (seen with OMP). - CLAUDE.md: one warning sentence on the Reload history rules. - terminal-resilience test reads each whole method instead of a 4,000-character window. --- .../814-history-repair-while-reading.md | 2 +- CLAUDE.md | 2 +- docs/architecture-invariants.md | 2 +- src/web/public/app.js | 10 ++++ test/shell-scroll-history-pull.test.ts | 49 +++++++++++++------ test/terminal-resilience.test.ts | 5 +- 6 files changed, 51 insertions(+), 19 deletions(-) diff --git a/.changeset/814-history-repair-while-reading.md b/.changeset/814-history-repair-while-reading.md index bdc91d7d..5d89e082 100644 --- a/.changeset/814-history-repair-while-reading.md +++ b/.changeset/814-history-repair-while-reading.md @@ -2,6 +2,6 @@ 'aicodeman': patch --- -Fix missing terminal history above live OMP output with a manual Reload history action in the existing history banner on desktop and mobile. The action preserves the text being read and output arriving during the download, and can be disabled per device in Settings > Terminal & Input > Scrolling & rendering. Ordinary scrolling only pulls history at the top; deferred dropped-output recovery retains its retry attempt. +Fix missing terminal history above live output in agent sessions (seen with OMP) with a manual Reload history action in the existing history banner on desktop and mobile. The action preserves the text being read and output arriving during the download, and can be disabled per device in Settings > Terminal & Input > Scrolling & rendering. Ordinary scrolling only pulls history at the top; deferred dropped-output recovery retains its retry attempt. While you are scrolled up, new output no longer moves the text you are reading once the terminal's scrollback is full. This applies to every session type, whether or not the Reload history setting is on. diff --git a/CLAUDE.md b/CLAUDE.md index 7f6d7d16..423df438 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -228,7 +228,7 @@ Codeman is a Claude Code session manager with web interface and autonomous Ralph **Circuit breakers**: the Ralph breaker prevents respawn thrashing (`CLOSED` → `HALF_OPEN` → `OPEN`; reset via `/api/sessions/:id/ralph-circuit-breaker/reset`). **Distinct: the PTY-exit breaker** (`session-pty-exit-breaker.ts`) trips after repeated rapid PTY exits and blocks auto-restarts. ⚠️ It resets ONLY via an explicit `{clearBreaker:true}` body on `POST /api/sessions/:id/interactive`; the frontend's auto-reattach in `selectSession()` sends no body and must never clear it. → [architecture-invariants#circuit-breakers-ralph-and-pty-exit](docs/architecture-invariants.md#circuit-breakers-ralph-and-pty-exit) -**Full-scrollback replay**: `GET /api/sessions/:id/terminal?full=1` returns the whole tmux scrollback ALONE (`source='mux-full-history'`), superseding the byte buffer. First load of each non-shell TUI session requests it (`_fullHistoryLoaded`); Shell selection, drop recovery, clear and a tile's load use `SHELL_LOAD_QUERY` (constants.js), a bounded window of tmux's RENDERED history (`?full=1&tail=1MiB&alt=recording&lines=10000`), never the raw byte recording, whose full-screen repaints replayed at another pane height push copies of their top row into scrollback; the route reports a client `lines=` bound below the history ceiling that left lines in tmux as `truncationReason: 'tail'`, and `alt=recording` falls back to the visible frame over the tailed byte recording when the pane is in the alternate screen (a nested tmux in a remote or Docker case keeps no tmux history; vim/less take it too while open). A Shell scroll-to-top pulls a bounded `?full=1&tail=` window (a window no longer than the browser's buffer is skipped before the downgrade guard, so it never marks the session exhausted); the unbounded pull stays behind **Load full history**. A Shell split-pane Pane B has its own copy of the bounded pull against its own xterm (`TerminalTile._pullHistory`, terminal-tile.js); keep the two in step. → [architecture-invariants#split-pane-sessions](docs/architecture-invariants.md#split-pane-sessions) ⚠️ The capture ends with a RELATIVE cursor move back to the pane's caret (never `CUP`), so no line-deleting transform may run over it; those skips key on `isFullCapture`, never on `?full=1` alone. ⚠️ A re-pull must never shrink the buffer (`_replayWouldShrinkBuffer()`). ⚠️ `captureCols`/`captureRows` are absent when no frame was positioned: test `Number.isFinite`, never truthiness. ⚠️ A frame dropped at the 128 KiB render cap MUST be recovered, and the recovery verifies itself: `_scheduleDroppedOutputRecovery` re-arms (bounded by `DROP_RECOVERY_MAX_ATTEMPTS`) while `_onSessionNeedsRefresh` reports no repaint, but never after a capture-fetch `'deadline'`. → [architecture-invariants#full-scrollback-replay](docs/architecture-invariants.md#full-scrollback-replay) +**Full-scrollback replay**: `GET /api/sessions/:id/terminal?full=1` returns the whole tmux scrollback ALONE (`source='mux-full-history'`), superseding the byte buffer. First load of each non-shell TUI session requests it (`_fullHistoryLoaded`); Shell selection, drop recovery, clear and a tile's load use `SHELL_LOAD_QUERY` (constants.js), a bounded window of tmux's RENDERED history (`?full=1&tail=1MiB&alt=recording&lines=10000`), never the raw byte recording, whose full-screen repaints replayed at another pane height push copies of their top row into scrollback; the route reports a client `lines=` bound below the history ceiling that left lines in tmux as `truncationReason: 'tail'`, and `alt=recording` falls back to the visible frame over the tailed byte recording when the pane is in the alternate screen (a nested tmux in a remote or Docker case keeps no tmux history; vim/less take it too while open). A Shell scroll-to-top pulls a bounded `?full=1&tail=` window (a window no longer than the browser's buffer is skipped before the downgrade guard, so it never marks the session exhausted); the unbounded pull stays behind **Load full history**. A Shell split-pane Pane B has its own copy of the bounded pull against its own xterm (`TerminalTile._pullHistory`, terminal-tile.js); keep the two in step. → [architecture-invariants#split-pane-sessions](docs/architecture-invariants.md#split-pane-sessions) ⚠️ The capture ends with a RELATIVE cursor move back to the pane's caret (never `CUP`), so no line-deleting transform may run over it; those skips key on `isFullCapture`, never on `?full=1` alone. ⚠️ A re-pull must never shrink the buffer (`_replayWouldShrinkBuffer()`). ⚠️ `captureCols`/`captureRows` are absent when no frame was positioned: test `Number.isFinite`, never truthiness. ⚠️ A frame dropped at the 128 KiB render cap MUST be recovered, and the recovery verifies itself: `_scheduleDroppedOutputRecovery` re-arms (bounded by `DROP_RECOVERY_MAX_ATTEMPTS`) while `_onSessionNeedsRefresh` reports no repaint, but never after a capture-fetch `'deadline'`. ⚠️ **Reload history** (#814, manual early repair; rules in the invariants paragraph "Repair while reading"): only a `mux-full-history` replay whose live-output generation is unchanged since before its fetch clears `_liveOutputSinceFullPull` and `_historyReloadDismissed`; a refused or non-mux answer to a manual reload retires the action until then; and the buffer load opens BEFORE the fetch, so download-time output queues behind the replay. → [architecture-invariants#full-scrollback-replay](docs/architecture-invariants.md#full-scrollback-replay) **Terminal scrollback strip + wheel/touch forwarding**: codex/claude/gemini get the FULL strip (alt-screen, `3J`, mouse DECSETs); tmux-backed opencode, copilot and pi get the MIDDLE strip (alt-screen toggles + mouse DECSETs, `3J` kept); every other tmux-backed mode (shell/antigravity/grok/deepseek/omp) gets the NARROW strip (alt-screen toggles only). Table: `CliCapabilities.altScreen` JSDoc, pinned in test/claude-scrollback-strip.test.ts. ⚠️ Gated on `useMux`: direct-PTY sessions must keep the alt screen. Wheel and touch forward only with observed `cliMouseTracking`: **Claude ≥ 2.1.187, tracked Codex, tracked Copilot, or tracked Pi**. Which CLIs forward is the registry's `wheelForward`, published as `window.__codemanWheelForward` and never an id list in the gate, so a custom `clis.json` entry opts in with it plus `altScreen: 'strip-mux-and-mouse'` (`docs/cli-registry.md`). Codex 0.163.0 fullscreen was measured with `alternate_on=1`, `mouse_any_flag=1`: one SGR report moves one transcript row; see the fresh measurement in architecture-invariants. Inline/untracked Codex retains local history or the capability-gated paging fallback. Copilot has no version gate; a stale/false tracking flag falls back to PageUp/PageDown. Pi has no version gate either, and is fullscreen by default since 1.0.0: it enables tracking once at start, so the flag is what survives a tab switch or reload (xterm's own mode does not). ⚠️ Pi deliberately has no `transcriptPageKeys`: its `tuiMode: regular` binds those keys to the editor, so paging there moves a draft's caret. Touch alone has one more branch (`_shouldForwardTouchToApp`): in any mode, a drag also forwards as SGR wheel reports while xterm ITSELF tracks the mouse with SGR encoding (an app in the pane asked for it; a tracking mode other than `x10` and `coreMouseService.activeEncoding === 'SGR'`, so DEFAULT, X10 and SGR-pixel apps fail closed), because xterm encodes a wheel there but the touch listeners consume the drag. ⚠️ `getClaudeCliVersion()` must never cache a FAILED probe. ⚠️ Hand-report clicks only while the CLI has mouse tracking on: `_shouldReportMouseToCli()` gates all three report sites on `cliMouseTracking` (from `_recordStrippedMouseMode()`, session.ts), or a plain shell prints the reports as literal text. ⚠️ A `TerminalTile` (grid tile, split Pane B) forwards the wheel as SGR reports, pages it and reports clicks through these SAME gates with itself as the target (its terminal, its session, never `activeSessionId`), and scrolls Shift+wheel itself (xterm makes it a horizontal no-op); never copy the mode lists into terminal-tile.js. ⚠️ The hollow-buffer PageUp/PageDown fallback (`_maybePageCliTranscript`) stands down when the last capture reported tmux scrollback (`paneHistoryLines` > 0: a tail replayed after a server restart carries only the attach repaint), so the gesture scrolls locally and the scroll-to-top pull loads `full=1`; 0 and unknown keep paging. Read `_logScrollRouting()` before diagnosing a scroll report. → [architecture-invariants#terminal-scrollback-strip-flavors-and-wheeltouch-forwarding](docs/architecture-invariants.md#terminal-scrollback-strip-flavors-and-wheeltouch-forwarding) **Detached start + service install**: `codeman web -d` relaunches the same entry script `detached:true` (setsid); `nohup` is not what makes it survive. ⚠️ Both `-d` and `service install` must REFUSE when a server is already up on this data dir (pidfile + `/api/status` probe), or a second instance attaches to the first one's live sessions. ⚠️ Never report success not observed: poll `/api/status` until the child answers or dies. `--stop` must verify the pid still looks like Codeman (`ps -o command=`) before signalling. Unit/label names live only in `config/service-names.ts`. `service install` bakes the installing shell's PATH into the unit and never writes `CODEMAN_PASSWORD` into it. → [architecture-invariants#detached-start-and-service-install](docs/architecture-invariants.md#detached-start-and-service-install) diff --git a/docs/architecture-invariants.md b/docs/architecture-invariants.md index f93b49be..959c29d0 100644 --- a/docs/architecture-invariants.md +++ b/docs/architecture-invariants.md @@ -253,7 +253,7 @@ Further detail: the `<prefix>: <title>` form (`w3-myapp: fix the login redirect` **Full-scrollback replay** (COD-164/#148, reworked for #205): `GET /api/sessions/:id/terminal?full=1` returns the ENTIRE tmux scrollback (capture-pane `-e -S -<lines>` bounded by the configured history limit, explicit `maxBuffer` from the terminal-history config, early byte-cap before normalization, CRLF-normalized for shell panes). On success the capture is returned ALONE (`source='mux-full-history'` — it supersedes the byte buffer; no duplication). The first load of each non-shell TUI session per page requests `full=1` (`_fullHistoryLoaded` Set in app.js — the old one-shot `_initialFullBufferLoad` flag was consumed by whichever tab auto-selected, leaving every other TUI tab one frame of history). Shell sessions instead load a bounded window of tmux's RENDERED history on every selection, automatic drop recovery, clear and tile load (`SHELL_LOAD_QUERY` in constants.js: `?full=1&tail=1MiB&lines=10000&alt=recording`): a 100k-line shell capture can be tens of MiB, and automatically parsing it makes tab-switch latency scale with the entire session (`lines=` bounds the synchronous capture-pane, about 8 ms per 1000 lines). They never replay the raw byte recording ahead of the visible frame any more: it holds full-screen repaints (an ssh'd tmux, `less`, any TUI) drawn for the pane height of the moment, and replayed into a terminal of another height each repaint's last newline scrolls its top row into scrollback, so one line tmux holds once showed up dozens of times. Because `lines=` is shallower than xterm's scrollback, the route reports a cut: the capture's `display-message` query also reads `#{history_size}` (`PaneCaptureOptions.capturedHistoryLines`, the same field the route reports as `paneHistoryLines`), and a full capture whose CLIENT bound (`lines=` below the configured `tmuxHistoryLimit`) left lines in tmux comes back `truncated`, `truncationReason: 'tail'`. ⚠️ Only a client bound below the ceiling counts: a request without `lines=` is bounded by the ceiling itself, and on tmux before 3.7 a live pane can hold more than a lowered ceiling, which no request can read. ⚠️ **A pane in the alternate screen keeps no tmux history**, and a nested tmux client (remote SSH and Docker cases, or `tmux`/`ssh -t host tmux` run by hand) holds its pane there, so its full capture is one screen. The same query reads `#{alternate_on}` (`capturedAlternateOn`), and a request carrying `alt=recording` (only `SHELL_LOAD_QUERY`) is then answered the old way, the visible frame over the tailed byte recording, which still carries the scrollback; agents, scroll pulls and **Load full history** never send it. `#{alternate_on}` cannot tell a nested tmux from vim, `less` or `htop`, so a local shell with one of those open takes the same fallback until it exits (the pre-fix load, with its repaint duplicates). Shell FULL history is explicit-button-only; reaching the top during an ordinary wheel/touch gesture must not reset xterm and replay the multi-megabyte capture on its main thread. That gesture instead pulls a BOUNDED window of it (`?full=1&tail=<TERMINAL_TAIL_SIZE>`, so a capture beyond 1 MiB comes back `truncationReason: 'tail'` and the banner offers the rest), and skips the replay when the window holds no more rows than the browser already has. ⚠️ **That skip runs BEFORE the downgrade guard, and it never touches the banner state**: the guard reads "smaller than the browser" as "tmux has nothing more to give", true of an unbounded capture and false of a window cut at the tail size, so a bounded window that reached it marked the session `exhausted` and removed **Load full history** while tmux still held the rest; and re-labelling the banner from a skipped payload would call a terminal that holds all of a Load full history pull "the most recent 1 MiB". A skipped window that came back truncated puts the session on the 60 s cooldown (`_fullHistoryRepullUseless`), because it can never reach anything older than the browser shows and `tail` is applied AFTER the server's synchronous `capture-pane` of the whole history, so each ask costs every client an event-loop stall (about 1 s at 100k lines; measured capture details below); an untruncated one keeps the 4 s cooldown, since it is all of tmux's history and the next burst can add to it. Declining the gesture outright was a dead end: after any burst a shell pane held about one screen of browser scrollback, and the button renders only once a replay was truncated, so a young shell tab had no way back to history tmux still held. Other modes re-pull `full=1` only at the top of the local buffer, and pressing **Load full history** forces the request for any recoverably truncated session (`_maybeRefetchFullHistory`, 4s per-session gesture cooldown, in-flight + tab-switch guards, viewport position held across the replay); Shell full pulls are not retained in the tab cache, so the next switch stays bounded. Chunked replay enqueues 32 KiB pieces across safe yields, appends an xterm parse marker, then releases the live-output gate; output arriving after that release stays ordered behind the snapshot, and the marker callback supplies accurate parse timing. ⚠️ **How the load ENDS depends on where the payload came from**, and `_bufferLoadFinishOpts` (app.js) is the one place that decides it for all four fetch-and-write paths. A payload built from the server's accumulated byte history is current up to the response, so the events queued during the load already appear in it and stay DISCARDED; replaying them would duplicate output, most visibly Ink's cursor-up redraws. A pane capture (`mux-visible` or `mux-full-history`) is current only up to CAPTURE time, so `_finishBufferLoad` replays the queue from the response's own arrival timestamp (`since`) and the pre-capture events stay dropped. ⚠️ **A path that then restores a scroll position must re-take the sticky-scroll baseline** (`_syncStickyScrollBaseline`): the replay runs inside `chunkedTerminalWrite` before its promise resolves, with the terminal freshly reset, so `batchTerminalWrite` samples `_wasAtBottomBeforeWrite` as true and the next `flushPendingWrites` would scroll to the bottom over the restore. ⚠️ The cutoff is a client-side timestamp and the server broadcasts on a batch timer (8ms WebSocket, 16-50ms SSE), so a batch pending when the capture ran arrives after the response and replays although the capture holds it — bounded by one batch interval, and closable only server side by flushing that batch before the capture. Tests for the three: `test/terminal-flush-budget.test.ts` pins which sources flush, `test/terminal-buffer-flush.test.ts` pins the `since` cutoff and the baseline re-take, and `test/capture-load-window.browser.test.ts` drives both against a live server. Live output is separately one-chunk-in-flight: xterm's callback releases each 32/64 KiB write before the next is submitted, keeping the remainder in the app queue where the 128 KiB cap can observe it instead of hiding an unbounded backlog in xterm's private WriteBuffer. While WebSocket owns terminal I/O, parallel SSE terminal/output-recovery events are discarded before JSON parsing; fallback recovery is single-flight per active session so backpressure cannot start overlapping reset+replay cycles. The route exposes capture/prepare totals in `Server-Timing`, while `[TERMINAL-PERF]` separates TTFB, body/JSON, reset+parse and total time for both selection and on-demand full pulls; parse completion is not a browser compositor/GPU paint measurement. The re-pull exists because xterm's buffer is only a WINDOW onto tmux's history and two things shrink it: tmux coalesces bursty output into pane REPAINTS that overwrite rows instead of emitting linefeeds (measured: a 60-line burst added 1 row of browser scrollback and destroyed 34), and a tab switch replays only the visible frame. tmux's own history is intact throughout — the browser just has to ask for it again. Gesture-triggered rather than polling because at a 100k history limit the capture can be megabytes. ⚠️ **The capture ENDS with a cursor move back to the pane's own caret position** (`formatCursorRestore`, from the same `display-message` query the visible-frame path uses). The linear replay otherwise leaves the caret wherever the last character landed — the bottom-most row carrying text, which for an agent CLI is the status line — so the caret sat on the composer's border instead of its input line and every cursor-relative update the CLI sent afterwards was measured from the wrong row, until its next full redraw silently repaired it (that self-repair is why the report read as "it fixes itself as soon as Claude writes a line"). ⚠️ **The move is RELATIVE — up `rows - 1 - cursor_y`, then `\r`, then right `cursor_x` — never `CUP`.** `\x1b[<row>;<col>H` numbers rows from the top of the browser's screen, so it lands correctly only while the browser's row count equals `pane_height`, and nothing guarantees that: `resizeWindow` issues its tmux resize fire-and-forget and returns immediately, so a capture can be taken before a requested resize has applied, and `_onSessionNeedsRefresh` sends no resize at all. Counting up from the last replayed row anchors to the content both ends share. Restoring the cursor makes ROW ALIGNMENT load-bearing on this path: **no transform that can DELETE A LINE may run over a full-history capture**, because every deletion shifts the frame out from under the restored position. Four had accumulated — trailing blank rows stripped by `\n+$`, `stripInkRedrawBloat`, the `CLAUDE_BANNER_PATTERN` trim that cuts everything above the banner, and `LEADING_WHITESPACE_PATTERN` — each correct for a byte stream of successive frames and each wrong for a single rendered frame. ⚠️ **Those skips key on `isFullCapture`, meaning a capture actually came back — never on `?full=1` alone.** When `captureActivePaneBuffer` returns null (ENOBUFS, a timeout, a vanished pane, or a session with no mux at all) the reply falls back to `session.terminalBuffer`, which IS a byte stream and must still be stripped; gating on the query flag returned it whole, and a direct-PTY session takes that path on every first selection rather than only during an outage. ⚠️ A capture holding nothing visible (`hasVisibleContent`) returns `''`, because the caller reads an empty capture as "unavailable" and keeps its byte history — retaining trailing blank rows made an all-blank pane non-empty, which would have replaced real history with a blank screen from the server side, where `_replayWouldShrinkBuffer` cannot see it. ⚠️ **"One line per screen row" holds only where no row was hard-wrapped**: `-J` joins a wrapped row into its logical line (measured: a 100-character line in a 40-column pane captures as 10 lines against a 12-row pane), and the counts reconcile only once the browser xterm re-wraps at the same width — the same assumption `_estimateReplayRows` already documents. Tests: `test/tmux-capture-full-history.test.ts` covers the cursor move, the trim pairing and `hasVisibleContent`; `test/routes/session-routes.test.ts` covers a surviving blank first row, an unstripped byte-history fallback, and an empty capture leaving history intact. ⚠️ **The re-pull must never DOWNGRADE the buffer** (#205 round 2): the same reasoning that makes it a win for a shell pane makes it destructive for a repaint-mode CLI pane, where tmux keeps no history of its own (`history_size≈0` measured for a Claude pane) and the capture is roughly ONE frame while xterm may hold hundreds of rows of replayed frames — `_resetTerminalForReplay()` + rewrite then deletes history mid-scroll ("goes back a bit, repeats blocks, gets worse the further up I go"; measured A/B on a live pane: 341 rows → 42 with the guard off). `_replayWouldShrinkBuffer()` (terminal-ui.js) estimates the capture's rendered rows — escape sequences stripped, `capture-pane -J` re-wrapping accounted for — and the pull is skipped when that is more than one screen short of `buffer.active.length`. The one-screen tolerance matters: both sides are estimates (the buffer length counts trailing blank rows), so only a clear downgrade is refused. A refused session joins `_fullHistoryRepullUseless`, raising its cooldown from 4s to 60s so a hollow pane stops re-fetching megabytes on every scroll-up. Tests: `test/tmux-capture-full-history.test.ts`, `test/tmux-scrollback-eol.test.ts`, `test/terminal-scroll-routing.test.ts`, `test/terminal-flush-budget.test.ts`. -**Repair while reading (#814)** is a manual **Reload history** action inside the existing history banner on desktop and touch devices, enabled by default and toggleable per device in Settings → Terminal & Input → Scrolling & rendering (`historyReloadAction`). It is offered only for a marked non-shell active session while scrolled away from live output, not detached, not owned by tiles, with no pull or buffer load in flight and no terminal load state for the session (a tab switch sets it before the buffer load opens). `paneHistoryLines` is deliberately not consulted: it is recorded at the last load, so a session first opened empty keeps 0 after the very burst that opens the gap (#814). A revealed truncation notice keeps its message and its **Load full history** control; Reload is appended only when the notice has no load control, or shown alone with a short missing-output message. A reload-only × dismissal lasts until the mark is cleared by a successful `mux-full-history` replay, independently of the notice’s page-long dismissal. Pressing × while loading hides the bar immediately; the in-flight pull continues. Eligibility is cached per active session, with onScroll sampling coalesced to one animation frame on every device; unchanged eligibility never rebuilds the banner. Automatic history pulls and notice reveal stay top-only (#205). Live-output marking covers only live writes: a byte-history (`?tail=`) replay, for example after a burst in a background tab, never marks the session, so that gap relies on the top-of-buffer pull. The manual action forces a content-anchored pull, bypassing the gesture cooldown but retaining the downgrade guard. Any downgrade-refused pull hides Reload until the next successful `mux-full-history` replay; that refusal, not the cached history size, is what retires the action for a pane with no tmux history (fullscreen Claude). A manual reload answered by anything but `mux-full-history` (an empty response, or the byte-history fallback the route returns when the pane capture is blank or failed) retires it the same way, since only a mux replay clears the mark; a transient error envelope (`success: false`) leaves it available. A content anchor captures up to 64 visible rows, preserving indentation, and scores candidate alignments by matching viewport context. Each distinct nonblank row contributes at most one point, so repeated TUI borders cannot outvote a distinctive tool result. The best match must score at least 60% of the distinct rows and at least two of them, capped at the number of distinct rows, so a viewport with one distinct row (a lone tool result among blanks) matches on that row alone; it must also be unique within the search window. Equal-scoring copies are ambiguous, even when all furniture rows match or the distinctive tool row has disappeared; proximity to the expected position does not establish confidence. An isolated first-row match is not trusted: without confident, unambiguous context the old viewport index is retained, while readers already near live output retain their bottom distance. Search is bounded to 2000 rows either side of the expected viewport (at most 4001 candidates / 4064 cached line reads). Live flushes use an xterm marker to track the reading row across scrollback trimming in O(1), and restore it only in the write callback; at-bottom sticky scroll is unchanged. Ordered, session-scoped travel during replay is applied with per-move clamping; a switched-to tab never donates travel. The buffer load opens BEFORE the fetch, so download-time output queues behind the replay instead of being overwritten. Non-replay exits flush the whole queue; replays retain the capture-header cutoff above. A blocked dropped-output recovery stores its session and current attempt, defers without consuming retries, and resumes only for the still-active session. Only an actual `mux-full-history` replay clears the live-output mark and reload dismissal, and a newer live-write generation keeps them marked. The drop-recovery refresh (`_onSessionNeedsRefresh`) follows the same rule: it clears both after replaying a `mux-full-history` capture, only while it still owns the active session and the live-output generation sampled before its fetch is unchanged; its `?tail=` fallback never clears them. The trade-off remains a full synchronous server capture (about 1 s: 1,068 ms median for `capture-pane -p -e -J -S -100000` over 100k lines of 120 characters, 12.1 MB), not a cheap automatic per-output repair. Tests: `test/shell-scroll-history-pull.test.ts`, `test/history-gap-repair.browser.test.ts`. +**Repair while reading (#814)** is a manual **Reload history** action inside the existing history banner on desktop and touch devices, enabled by default and toggleable per device in Settings → Terminal & Input → Scrolling & rendering (`historyReloadAction`). It is offered only for a marked non-shell active session while scrolled away from live output, not detached, not owned by tiles, with no pull or buffer load in flight and no terminal load state for the session (a tab switch sets it before the buffer load opens). `paneHistoryLines` is deliberately not consulted: it is recorded at the last load, so a session first opened empty keeps 0 after the very burst that opens the gap (#814). A revealed truncation notice keeps its message and its **Load full history** control; Reload is appended only when the notice has no load control, or shown alone with a short missing-output message. A reload-only × dismissal lasts until the mark is cleared by a successful `mux-full-history` replay, independently of the notice’s page-long dismissal. Pressing × while loading hides the bar immediately; the in-flight pull continues. Eligibility is cached per active session, with onScroll sampling coalesced to one animation frame on every device; unchanged eligibility never rebuilds the banner. Automatic history pulls and notice reveal stay top-only (#205). Live-output marking covers only live writes: a byte-history (`?tail=`) replay, for example after a burst in a background tab, never marks the session, so that gap relies on the top-of-buffer pull. The manual action forces a content-anchored pull, bypassing the gesture cooldown but retaining the downgrade guard. Any downgrade-refused pull hides Reload until the next successful `mux-full-history` replay; that refusal, not the cached history size, is what retires the action for a pane with no tmux history (fullscreen Claude). A manual reload answered by anything but `mux-full-history` (an empty response, or the byte-history fallback the route returns when the pane capture is blank or failed) retires it the same way, since only a mux replay clears the mark; a transient error envelope (`success: false`) leaves it available. A content anchor captures up to 64 visible rows, preserving indentation, and scores candidate alignments by matching viewport context. Each distinct nonblank row contributes at most one point, so repeated TUI borders cannot outvote a distinctive tool result. The best match must score at least 60% of the distinct rows and at least two of them, capped at the number of distinct rows, so a viewport with one distinct row (a lone tool result among blanks) matches on that row alone; it must also be unique within the search window. Equal-scoring copies are ambiguous, even when all furniture rows match or the distinctive tool row has disappeared; proximity to the expected position does not establish confidence. An isolated first-row match is not trusted: without confident, unambiguous context the old viewport index is retained, while readers already near live output retain their bottom distance. Search is bounded to 2000 rows either side of the expected viewport (at most 4001 candidates / 4064 cached line reads). Live flushes use an xterm marker to track the reading row across scrollback trimming in O(1), and restore it only in the write callback; at-bottom sticky scroll is unchanged. Ordered, session-scoped travel during replay is applied with per-move clamping; a switched-to tab never donates travel. The buffer load opens BEFORE the fetch, so download-time output queues behind the replay instead of being overwritten. Non-replay exits flush the whole queue; replays retain the capture-header cutoff above. A blocked dropped-output recovery stores its session and current attempt, defers without consuming retries, and resumes only for the still-active session. Only an actual `mux-full-history` replay clears the live-output mark and reload dismissal, and a newer live-write generation keeps them marked. The drop-recovery refresh (`_onSessionNeedsRefresh`) follows the same rule: it clears both after replaying a `mux-full-history` capture, only while it still owns the active session and the live-output generation sampled before its fetch is unchanged; its `?tail=` fallback never clears them, and because that fallback means the full capture would shrink the buffer (the refusal signal), it retires the action under the same session and refresh-owner checks. The trade-off remains a full synchronous server capture (about 1 s: 1,068 ms median for `capture-pane -p -e -J -S -100000` over 100k lines of 120 characters, 12.1 MB), not a cheap automatic per-output repair. Tests: `test/shell-scroll-history-pull.test.ts`, `test/history-gap-repair.browser.test.ts`. **The partial-history notice is lazy and pane-gated** (`computeHistoryTruncationNotice()` in constants.js, `_renderHistoryTruncationBanner()` / `_setHistoryNoticeRevealed()` in app.js). `truncated` on a terminal response measures the server's BYTE stream, which is not what `full=1` can return: for a pane with no tmux scrollback (fullscreen claude starts in the alternate screen and never writes to the main grid, so `#{history_size}` is 0) the bytes a tail cut drops are old repaint frames. Measured on prod 2026-10-10, every claude pane: the tab-switch tail cut a 1.2 to 6.2 MB stream to 1 MiB, the local scrollback that tail replays into is repeats of the same frames (one pane: 450 non-blank rows, 44 unique, one row 33 times), and `full=1` returned 1 to 5 KB, so **Load full history** could only end in the downgrade refusal while the banner promised "4.8 MB more". The capture therefore reads `#{history_size}` in the SAME `display-message` as the cursor (no extra tmux call), the route returns it as `paneHistoryLines` (absent when the body is not a capture, and for a remote SSH session, whose local pane hosts the remote tmux client and always reports 0 while `full=1` reads the remote history), and a reported 0 hides the notice in every state; a positive count replaces the byte gap in the message. ⚠️ Key the notice decision on `history_size`, never on `alternate_on`: a shell running `less` is in the alternate screen with its whole history still retained (measured, 99,972 rows) and `full=1` returns all of it. The one place `alternate_on` decides is a shell's AUTOMATIC load (`alt=recording`, see Full-scrollback replay): there the question is whether the capture holds the scrollback a nested tmux client keeps in its byte recording, not whether a pull can return more. The notice is also LAZY: it appears only after a wheel/touch gesture reaches the top of the browser buffer and the pull that gesture started has settled (`_maybeLoadMoreHistoryOnScroll`), goes away when a downward gesture is back at live output or the tab switches (`selectSession` nulls `_historyNoticeRevealedFor` before repainting), and its × is sticky per session until reload (`_historyNoticeDismissed`). Tests: `test/history-truncation-notice.test.ts`, `test/history-notice-reveal.test.ts`. diff --git a/src/web/public/app.js b/src/web/public/app.js index e8cdedea..565c4eca 100644 --- a/src/web/public/app.js +++ b/src/web/public/app.js @@ -3505,7 +3505,13 @@ class CodemanApp { ); let headersReceivedAt = capture.headersAt; let data = capture.json?.data ?? {}; + // The full capture would shrink the buffer: tmux holds less than the browser, + // the signal `_maybeRefetchFullHistory` retires Reload history on. Record it + // and apply it past the ownership guard below, so the next tap does not run + // another forced full capture only to be refused. + let refusedFullCapture = false; if (useFullHistory && data.terminalBuffer && this._replayWouldShrinkBuffer(data.terminalBuffer)) { + refusedFullCapture = true; capture = await this._fetchTerminalCapture(`/api/sessions/${sessionId}/terminal?tail=${TERMINAL_TAIL_SIZE}`); headersReceivedAt = capture.headersAt; data = capture.json?.data ?? {}; @@ -3519,6 +3525,10 @@ class CodemanApp { // pane), and an error envelope is not a capture at all. if (this.activeSessionId !== sessionId || this._terminalRefreshOwner !== refreshOwner) return false; if (capture.json?.success !== false) this._notePaneHistory?.(sessionId, data); + if (refusedFullCapture) { + (this._historyReloadDismissed ||= new Set()).add(sessionId); + this._syncHistoryReloadAction?.(); + } if (data.terminalBuffer) { // This refresh is SERVER-triggered, so a user quietly reading scrollback // did not ask for it and must not be dragged to the bottom by it (#259). diff --git a/test/shell-scroll-history-pull.test.ts b/test/shell-scroll-history-pull.test.ts index 685140ac..07cc1a21 100644 --- a/test/shell-scroll-history-pull.test.ts +++ b/test/shell-scroll-history-pull.test.ts @@ -1374,7 +1374,24 @@ describe('drop-recovery refresh clears the live-output mark only for a mux captu _syncHistoryReloadAction: vi.fn(), }); Object.assign(app.terminal, { scrollToBottom: vi.fn() }); - return { app: recovery, refresh, errors }; + /** Full capture refused by the shrink guard, then the `?tail=` fallback. */ + const mockShrinkFallback = (beforeTail = () => {}) => { + recovery._replayWouldShrinkBuffer = vi.fn(() => true); + recovery._fetchTerminalCapture.mockResolvedValueOnce({ + headersAt: performance.now(), + headers: { get: () => '' }, + json: { data: { terminalBuffer: lines(10), source: 'mux-full-history' } }, + }); + recovery._fetchTerminalCapture.mockImplementationOnce(async () => { + beforeTail(); + return { + headersAt: performance.now(), + headers: { get: () => '' }, + json: { data: { terminalBuffer: lines(60), source: 'history' } }, + }; + }); + }; + return { app: recovery, refresh, errors, mockShrinkFallback }; } it('clears the mark and dismissal after replaying a full mux capture', async () => { @@ -1414,26 +1431,28 @@ describe('drop-recovery refresh clears the live-output mark only for a mux captu expect(app._syncHistoryReloadAction).toHaveBeenCalledOnce(); }); - it('keeps the mark and dismissal when a full mux capture falls back to a history tail', async () => { - const { app, refresh, errors } = makeRefreshApp(); - app._replayWouldShrinkBuffer = vi.fn(() => true); - app._fetchTerminalCapture.mockResolvedValueOnce({ - headersAt: performance.now(), - headers: { get: () => '' }, - json: { data: { terminalBuffer: lines(10), source: 'mux-full-history' } }, - }); - app._fetchTerminalCapture.mockResolvedValueOnce({ - headersAt: performance.now(), - headers: { get: () => '' }, - json: { data: { terminalBuffer: lines(60), source: 'history' } }, - }); + it('retires Reload history when a full mux capture falls back to a history tail', async () => { + const { app, refresh, errors, mockShrinkFallback } = makeRefreshApp(); + app._historyReloadDismissed.clear(); + mockShrinkFallback(); expect(await refresh.call(app)).toBe(true); expect(errors).not.toHaveBeenCalled(); expect(app._fetchTerminalCapture).toHaveBeenLastCalledWith(`/api/sessions/s1/terminal?tail=${TERMINAL_TAIL_SIZE}`); expect(app.chunkedTerminalWrite).toHaveBeenCalledOnce(); + // tmux holds less than the browser: the same refusal signal the manual + // reload retires on, so a tap would only run another forced full capture. expect(app._liveOutputSinceFullPull.has('s1')).toBe(true); expect(app._historyReloadDismissed.has('s1')).toBe(true); - expect(app._syncHistoryReloadAction).toHaveBeenCalledOnce(); + }); + + it('does not retire Reload history from a fallback whose refresh lost its owner', async () => { + const { app, refresh, errors, mockShrinkFallback } = makeRefreshApp(); + app._historyReloadDismissed.clear(); + mockShrinkFallback(() => Reflect.set(app, '_terminalRefreshOwner', { sessionId: 's1' })); + expect(await refresh.call(app)).toBe(false); + expect(errors).not.toHaveBeenCalled(); + expect(app.chunkedTerminalWrite).not.toHaveBeenCalled(); + expect(app._historyReloadDismissed.has('s1')).toBe(false); }); it.each(['session', 'owner'])('keeps the mark when the refresh loses its %s during replay', async (changed) => { diff --git a/test/terminal-resilience.test.ts b/test/terminal-resilience.test.ts index 94fb7b1c..939b7989 100644 --- a/test/terminal-resilience.test.ts +++ b/test/terminal-resilience.test.ts @@ -250,7 +250,10 @@ describe('terminal capture deadline covers the response body', () => { for (const site of ['_onSessionNeedsRefresh(event = {}) {', 'async _onSessionClearTerminal(data) {']) { const start = app.indexOf(site); expect(start, `${site} not found — renamed?`).toBeGreaterThan(-1); - const body = app.slice(start, start + 4000); + // The whole method, not a fixed-size window: a byte count broke on an + // unrelated comment, and a reset past it would have read as missing. + const next = /^ {2}(?:async )?[A-Za-z_$][\w$]*\(/m.exec(app.slice(start + 1)); + const body = next ? app.slice(start, start + 1 + next.index) : app.slice(start); expect(body, `${site} must clear via _resetTerminalForReplay`).toContain('this._resetTerminalForReplay()'); expect(body, `${site} hand-rolled a clear again`).not.toContain('this.terminal.clear()'); } From 6311e59412f15e9474f8aba8e1534b468580e566 Mon Sep 17 00:00:00 2001 From: Hadrien Kerlero <199662351+HadrienKerlero@users.noreply.github.com> Date: Wed, 18 Nov 2026 19:49:28 +0100 Subject: [PATCH 11/23] fix(web): keep the reader's line when Load full history stands in for Reload (#814) - The notice's Load full history button pulls with anchor 'content' when Reload history is eligible (read at click time, since the bar only re-renders on eligibility transitions) and keeps 'top' otherwise. - Tests: the single load control asserts the content anchor; an ineligible session keeps the top anchor. --- docs/architecture-invariants.md | 2 +- src/web/public/app.js | 7 ++++++- test/shell-scroll-history-pull.test.ts | 18 +++++++++++++++++- 3 files changed, 24 insertions(+), 3 deletions(-) diff --git a/docs/architecture-invariants.md b/docs/architecture-invariants.md index 959c29d0..4eba6c51 100644 --- a/docs/architecture-invariants.md +++ b/docs/architecture-invariants.md @@ -253,7 +253,7 @@ Further detail: the `<prefix>: <title>` form (`w3-myapp: fix the login redirect` **Full-scrollback replay** (COD-164/#148, reworked for #205): `GET /api/sessions/:id/terminal?full=1` returns the ENTIRE tmux scrollback (capture-pane `-e -S -<lines>` bounded by the configured history limit, explicit `maxBuffer` from the terminal-history config, early byte-cap before normalization, CRLF-normalized for shell panes). On success the capture is returned ALONE (`source='mux-full-history'` — it supersedes the byte buffer; no duplication). The first load of each non-shell TUI session per page requests `full=1` (`_fullHistoryLoaded` Set in app.js — the old one-shot `_initialFullBufferLoad` flag was consumed by whichever tab auto-selected, leaving every other TUI tab one frame of history). Shell sessions instead load a bounded window of tmux's RENDERED history on every selection, automatic drop recovery, clear and tile load (`SHELL_LOAD_QUERY` in constants.js: `?full=1&tail=1MiB&lines=10000&alt=recording`): a 100k-line shell capture can be tens of MiB, and automatically parsing it makes tab-switch latency scale with the entire session (`lines=` bounds the synchronous capture-pane, about 8 ms per 1000 lines). They never replay the raw byte recording ahead of the visible frame any more: it holds full-screen repaints (an ssh'd tmux, `less`, any TUI) drawn for the pane height of the moment, and replayed into a terminal of another height each repaint's last newline scrolls its top row into scrollback, so one line tmux holds once showed up dozens of times. Because `lines=` is shallower than xterm's scrollback, the route reports a cut: the capture's `display-message` query also reads `#{history_size}` (`PaneCaptureOptions.capturedHistoryLines`, the same field the route reports as `paneHistoryLines`), and a full capture whose CLIENT bound (`lines=` below the configured `tmuxHistoryLimit`) left lines in tmux comes back `truncated`, `truncationReason: 'tail'`. ⚠️ Only a client bound below the ceiling counts: a request without `lines=` is bounded by the ceiling itself, and on tmux before 3.7 a live pane can hold more than a lowered ceiling, which no request can read. ⚠️ **A pane in the alternate screen keeps no tmux history**, and a nested tmux client (remote SSH and Docker cases, or `tmux`/`ssh -t host tmux` run by hand) holds its pane there, so its full capture is one screen. The same query reads `#{alternate_on}` (`capturedAlternateOn`), and a request carrying `alt=recording` (only `SHELL_LOAD_QUERY`) is then answered the old way, the visible frame over the tailed byte recording, which still carries the scrollback; agents, scroll pulls and **Load full history** never send it. `#{alternate_on}` cannot tell a nested tmux from vim, `less` or `htop`, so a local shell with one of those open takes the same fallback until it exits (the pre-fix load, with its repaint duplicates). Shell FULL history is explicit-button-only; reaching the top during an ordinary wheel/touch gesture must not reset xterm and replay the multi-megabyte capture on its main thread. That gesture instead pulls a BOUNDED window of it (`?full=1&tail=<TERMINAL_TAIL_SIZE>`, so a capture beyond 1 MiB comes back `truncationReason: 'tail'` and the banner offers the rest), and skips the replay when the window holds no more rows than the browser already has. ⚠️ **That skip runs BEFORE the downgrade guard, and it never touches the banner state**: the guard reads "smaller than the browser" as "tmux has nothing more to give", true of an unbounded capture and false of a window cut at the tail size, so a bounded window that reached it marked the session `exhausted` and removed **Load full history** while tmux still held the rest; and re-labelling the banner from a skipped payload would call a terminal that holds all of a Load full history pull "the most recent 1 MiB". A skipped window that came back truncated puts the session on the 60 s cooldown (`_fullHistoryRepullUseless`), because it can never reach anything older than the browser shows and `tail` is applied AFTER the server's synchronous `capture-pane` of the whole history, so each ask costs every client an event-loop stall (about 1 s at 100k lines; measured capture details below); an untruncated one keeps the 4 s cooldown, since it is all of tmux's history and the next burst can add to it. Declining the gesture outright was a dead end: after any burst a shell pane held about one screen of browser scrollback, and the button renders only once a replay was truncated, so a young shell tab had no way back to history tmux still held. Other modes re-pull `full=1` only at the top of the local buffer, and pressing **Load full history** forces the request for any recoverably truncated session (`_maybeRefetchFullHistory`, 4s per-session gesture cooldown, in-flight + tab-switch guards, viewport position held across the replay); Shell full pulls are not retained in the tab cache, so the next switch stays bounded. Chunked replay enqueues 32 KiB pieces across safe yields, appends an xterm parse marker, then releases the live-output gate; output arriving after that release stays ordered behind the snapshot, and the marker callback supplies accurate parse timing. ⚠️ **How the load ENDS depends on where the payload came from**, and `_bufferLoadFinishOpts` (app.js) is the one place that decides it for all four fetch-and-write paths. A payload built from the server's accumulated byte history is current up to the response, so the events queued during the load already appear in it and stay DISCARDED; replaying them would duplicate output, most visibly Ink's cursor-up redraws. A pane capture (`mux-visible` or `mux-full-history`) is current only up to CAPTURE time, so `_finishBufferLoad` replays the queue from the response's own arrival timestamp (`since`) and the pre-capture events stay dropped. ⚠️ **A path that then restores a scroll position must re-take the sticky-scroll baseline** (`_syncStickyScrollBaseline`): the replay runs inside `chunkedTerminalWrite` before its promise resolves, with the terminal freshly reset, so `batchTerminalWrite` samples `_wasAtBottomBeforeWrite` as true and the next `flushPendingWrites` would scroll to the bottom over the restore. ⚠️ The cutoff is a client-side timestamp and the server broadcasts on a batch timer (8ms WebSocket, 16-50ms SSE), so a batch pending when the capture ran arrives after the response and replays although the capture holds it — bounded by one batch interval, and closable only server side by flushing that batch before the capture. Tests for the three: `test/terminal-flush-budget.test.ts` pins which sources flush, `test/terminal-buffer-flush.test.ts` pins the `since` cutoff and the baseline re-take, and `test/capture-load-window.browser.test.ts` drives both against a live server. Live output is separately one-chunk-in-flight: xterm's callback releases each 32/64 KiB write before the next is submitted, keeping the remainder in the app queue where the 128 KiB cap can observe it instead of hiding an unbounded backlog in xterm's private WriteBuffer. While WebSocket owns terminal I/O, parallel SSE terminal/output-recovery events are discarded before JSON parsing; fallback recovery is single-flight per active session so backpressure cannot start overlapping reset+replay cycles. The route exposes capture/prepare totals in `Server-Timing`, while `[TERMINAL-PERF]` separates TTFB, body/JSON, reset+parse and total time for both selection and on-demand full pulls; parse completion is not a browser compositor/GPU paint measurement. The re-pull exists because xterm's buffer is only a WINDOW onto tmux's history and two things shrink it: tmux coalesces bursty output into pane REPAINTS that overwrite rows instead of emitting linefeeds (measured: a 60-line burst added 1 row of browser scrollback and destroyed 34), and a tab switch replays only the visible frame. tmux's own history is intact throughout — the browser just has to ask for it again. Gesture-triggered rather than polling because at a 100k history limit the capture can be megabytes. ⚠️ **The capture ENDS with a cursor move back to the pane's own caret position** (`formatCursorRestore`, from the same `display-message` query the visible-frame path uses). The linear replay otherwise leaves the caret wherever the last character landed — the bottom-most row carrying text, which for an agent CLI is the status line — so the caret sat on the composer's border instead of its input line and every cursor-relative update the CLI sent afterwards was measured from the wrong row, until its next full redraw silently repaired it (that self-repair is why the report read as "it fixes itself as soon as Claude writes a line"). ⚠️ **The move is RELATIVE — up `rows - 1 - cursor_y`, then `\r`, then right `cursor_x` — never `CUP`.** `\x1b[<row>;<col>H` numbers rows from the top of the browser's screen, so it lands correctly only while the browser's row count equals `pane_height`, and nothing guarantees that: `resizeWindow` issues its tmux resize fire-and-forget and returns immediately, so a capture can be taken before a requested resize has applied, and `_onSessionNeedsRefresh` sends no resize at all. Counting up from the last replayed row anchors to the content both ends share. Restoring the cursor makes ROW ALIGNMENT load-bearing on this path: **no transform that can DELETE A LINE may run over a full-history capture**, because every deletion shifts the frame out from under the restored position. Four had accumulated — trailing blank rows stripped by `\n+$`, `stripInkRedrawBloat`, the `CLAUDE_BANNER_PATTERN` trim that cuts everything above the banner, and `LEADING_WHITESPACE_PATTERN` — each correct for a byte stream of successive frames and each wrong for a single rendered frame. ⚠️ **Those skips key on `isFullCapture`, meaning a capture actually came back — never on `?full=1` alone.** When `captureActivePaneBuffer` returns null (ENOBUFS, a timeout, a vanished pane, or a session with no mux at all) the reply falls back to `session.terminalBuffer`, which IS a byte stream and must still be stripped; gating on the query flag returned it whole, and a direct-PTY session takes that path on every first selection rather than only during an outage. ⚠️ A capture holding nothing visible (`hasVisibleContent`) returns `''`, because the caller reads an empty capture as "unavailable" and keeps its byte history — retaining trailing blank rows made an all-blank pane non-empty, which would have replaced real history with a blank screen from the server side, where `_replayWouldShrinkBuffer` cannot see it. ⚠️ **"One line per screen row" holds only where no row was hard-wrapped**: `-J` joins a wrapped row into its logical line (measured: a 100-character line in a 40-column pane captures as 10 lines against a 12-row pane), and the counts reconcile only once the browser xterm re-wraps at the same width — the same assumption `_estimateReplayRows` already documents. Tests: `test/tmux-capture-full-history.test.ts` covers the cursor move, the trim pairing and `hasVisibleContent`; `test/routes/session-routes.test.ts` covers a surviving blank first row, an unstripped byte-history fallback, and an empty capture leaving history intact. ⚠️ **The re-pull must never DOWNGRADE the buffer** (#205 round 2): the same reasoning that makes it a win for a shell pane makes it destructive for a repaint-mode CLI pane, where tmux keeps no history of its own (`history_size≈0` measured for a Claude pane) and the capture is roughly ONE frame while xterm may hold hundreds of rows of replayed frames — `_resetTerminalForReplay()` + rewrite then deletes history mid-scroll ("goes back a bit, repeats blocks, gets worse the further up I go"; measured A/B on a live pane: 341 rows → 42 with the guard off). `_replayWouldShrinkBuffer()` (terminal-ui.js) estimates the capture's rendered rows — escape sequences stripped, `capture-pane -J` re-wrapping accounted for — and the pull is skipped when that is more than one screen short of `buffer.active.length`. The one-screen tolerance matters: both sides are estimates (the buffer length counts trailing blank rows), so only a clear downgrade is refused. A refused session joins `_fullHistoryRepullUseless`, raising its cooldown from 4s to 60s so a hollow pane stops re-fetching megabytes on every scroll-up. Tests: `test/tmux-capture-full-history.test.ts`, `test/tmux-scrollback-eol.test.ts`, `test/terminal-scroll-routing.test.ts`, `test/terminal-flush-budget.test.ts`. -**Repair while reading (#814)** is a manual **Reload history** action inside the existing history banner on desktop and touch devices, enabled by default and toggleable per device in Settings → Terminal & Input → Scrolling & rendering (`historyReloadAction`). It is offered only for a marked non-shell active session while scrolled away from live output, not detached, not owned by tiles, with no pull or buffer load in flight and no terminal load state for the session (a tab switch sets it before the buffer load opens). `paneHistoryLines` is deliberately not consulted: it is recorded at the last load, so a session first opened empty keeps 0 after the very burst that opens the gap (#814). A revealed truncation notice keeps its message and its **Load full history** control; Reload is appended only when the notice has no load control, or shown alone with a short missing-output message. A reload-only × dismissal lasts until the mark is cleared by a successful `mux-full-history` replay, independently of the notice’s page-long dismissal. Pressing × while loading hides the bar immediately; the in-flight pull continues. Eligibility is cached per active session, with onScroll sampling coalesced to one animation frame on every device; unchanged eligibility never rebuilds the banner. Automatic history pulls and notice reveal stay top-only (#205). Live-output marking covers only live writes: a byte-history (`?tail=`) replay, for example after a burst in a background tab, never marks the session, so that gap relies on the top-of-buffer pull. The manual action forces a content-anchored pull, bypassing the gesture cooldown but retaining the downgrade guard. Any downgrade-refused pull hides Reload until the next successful `mux-full-history` replay; that refusal, not the cached history size, is what retires the action for a pane with no tmux history (fullscreen Claude). A manual reload answered by anything but `mux-full-history` (an empty response, or the byte-history fallback the route returns when the pane capture is blank or failed) retires it the same way, since only a mux replay clears the mark; a transient error envelope (`success: false`) leaves it available. A content anchor captures up to 64 visible rows, preserving indentation, and scores candidate alignments by matching viewport context. Each distinct nonblank row contributes at most one point, so repeated TUI borders cannot outvote a distinctive tool result. The best match must score at least 60% of the distinct rows and at least two of them, capped at the number of distinct rows, so a viewport with one distinct row (a lone tool result among blanks) matches on that row alone; it must also be unique within the search window. Equal-scoring copies are ambiguous, even when all furniture rows match or the distinctive tool row has disappeared; proximity to the expected position does not establish confidence. An isolated first-row match is not trusted: without confident, unambiguous context the old viewport index is retained, while readers already near live output retain their bottom distance. Search is bounded to 2000 rows either side of the expected viewport (at most 4001 candidates / 4064 cached line reads). Live flushes use an xterm marker to track the reading row across scrollback trimming in O(1), and restore it only in the write callback; at-bottom sticky scroll is unchanged. Ordered, session-scoped travel during replay is applied with per-move clamping; a switched-to tab never donates travel. The buffer load opens BEFORE the fetch, so download-time output queues behind the replay instead of being overwritten. Non-replay exits flush the whole queue; replays retain the capture-header cutoff above. A blocked dropped-output recovery stores its session and current attempt, defers without consuming retries, and resumes only for the still-active session. Only an actual `mux-full-history` replay clears the live-output mark and reload dismissal, and a newer live-write generation keeps them marked. The drop-recovery refresh (`_onSessionNeedsRefresh`) follows the same rule: it clears both after replaying a `mux-full-history` capture, only while it still owns the active session and the live-output generation sampled before its fetch is unchanged; its `?tail=` fallback never clears them, and because that fallback means the full capture would shrink the buffer (the refusal signal), it retires the action under the same session and refresh-owner checks. The trade-off remains a full synchronous server capture (about 1 s: 1,068 ms median for `capture-pane -p -e -J -S -100000` over 100k lines of 120 characters, 12.1 MB), not a cheap automatic per-output repair. Tests: `test/shell-scroll-history-pull.test.ts`, `test/history-gap-repair.browser.test.ts`. +**Repair while reading (#814)** is a manual **Reload history** action inside the existing history banner on desktop and touch devices, enabled by default and toggleable per device in Settings → Terminal & Input → Scrolling & rendering (`historyReloadAction`). It is offered only for a marked non-shell active session while scrolled away from live output, not detached, not owned by tiles, with no pull or buffer load in flight and no terminal load state for the session (a tab switch sets it before the buffer load opens). `paneHistoryLines` is deliberately not consulted: it is recorded at the last load, so a session first opened empty keeps 0 after the very burst that opens the gap (#814). A revealed truncation notice keeps its message and its **Load full history** control; Reload is appended only when the notice has no load control, or shown alone with a short missing-output message. When Reload is eligible, that **Load full history** control stands in for it and pulls with the content anchor (eligibility read at click time), so the reader keeps their line; otherwise it keeps the top anchor. A reload-only × dismissal lasts until the mark is cleared by a successful `mux-full-history` replay, independently of the notice’s page-long dismissal. Pressing × while loading hides the bar immediately; the in-flight pull continues. Eligibility is cached per active session, with onScroll sampling coalesced to one animation frame on every device; unchanged eligibility never rebuilds the banner. Automatic history pulls and notice reveal stay top-only (#205). Live-output marking covers only live writes: a byte-history (`?tail=`) replay, for example after a burst in a background tab, never marks the session, so that gap relies on the top-of-buffer pull. The manual action forces a content-anchored pull, bypassing the gesture cooldown but retaining the downgrade guard. Any downgrade-refused pull hides Reload until the next successful `mux-full-history` replay; that refusal, not the cached history size, is what retires the action for a pane with no tmux history (fullscreen Claude). A manual reload answered by anything but `mux-full-history` (an empty response, or the byte-history fallback the route returns when the pane capture is blank or failed) retires it the same way, since only a mux replay clears the mark; a transient error envelope (`success: false`) leaves it available. A content anchor captures up to 64 visible rows, preserving indentation, and scores candidate alignments by matching viewport context. Each distinct nonblank row contributes at most one point, so repeated TUI borders cannot outvote a distinctive tool result. The best match must score at least 60% of the distinct rows and at least two of them, capped at the number of distinct rows, so a viewport with one distinct row (a lone tool result among blanks) matches on that row alone; it must also be unique within the search window. Equal-scoring copies are ambiguous, even when all furniture rows match or the distinctive tool row has disappeared; proximity to the expected position does not establish confidence. An isolated first-row match is not trusted: without confident, unambiguous context the old viewport index is retained, while readers already near live output retain their bottom distance. Search is bounded to 2000 rows either side of the expected viewport (at most 4001 candidates / 4064 cached line reads). Live flushes use an xterm marker to track the reading row across scrollback trimming in O(1), and restore it only in the write callback; at-bottom sticky scroll is unchanged. Ordered, session-scoped travel during replay is applied with per-move clamping; a switched-to tab never donates travel. The buffer load opens BEFORE the fetch, so download-time output queues behind the replay instead of being overwritten. Non-replay exits flush the whole queue; replays retain the capture-header cutoff above. A blocked dropped-output recovery stores its session and current attempt, defers without consuming retries, and resumes only for the still-active session. Only an actual `mux-full-history` replay clears the live-output mark and reload dismissal, and a newer live-write generation keeps them marked. The drop-recovery refresh (`_onSessionNeedsRefresh`) follows the same rule: it clears both after replaying a `mux-full-history` capture, only while it still owns the active session and the live-output generation sampled before its fetch is unchanged; its `?tail=` fallback never clears them, and because that fallback means the full capture would shrink the buffer (the refusal signal), it retires the action under the same session and refresh-owner checks. The trade-off remains a full synchronous server capture (about 1 s: 1,068 ms median for `capture-pane -p -e -J -S -100000` over 100k lines of 120 characters, 12.1 MB), not a cheap automatic per-output repair. Tests: `test/shell-scroll-history-pull.test.ts`, `test/history-gap-repair.browser.test.ts`. **The partial-history notice is lazy and pane-gated** (`computeHistoryTruncationNotice()` in constants.js, `_renderHistoryTruncationBanner()` / `_setHistoryNoticeRevealed()` in app.js). `truncated` on a terminal response measures the server's BYTE stream, which is not what `full=1` can return: for a pane with no tmux scrollback (fullscreen claude starts in the alternate screen and never writes to the main grid, so `#{history_size}` is 0) the bytes a tail cut drops are old repaint frames. Measured on prod 2026-10-10, every claude pane: the tab-switch tail cut a 1.2 to 6.2 MB stream to 1 MiB, the local scrollback that tail replays into is repeats of the same frames (one pane: 450 non-blank rows, 44 unique, one row 33 times), and `full=1` returned 1 to 5 KB, so **Load full history** could only end in the downgrade refusal while the banner promised "4.8 MB more". The capture therefore reads `#{history_size}` in the SAME `display-message` as the cursor (no extra tmux call), the route returns it as `paneHistoryLines` (absent when the body is not a capture, and for a remote SSH session, whose local pane hosts the remote tmux client and always reports 0 while `full=1` reads the remote history), and a reported 0 hides the notice in every state; a positive count replaces the byte gap in the message. ⚠️ Key the notice decision on `history_size`, never on `alternate_on`: a shell running `less` is in the alternate screen with its whole history still retained (measured, 99,972 rows) and `full=1` returns all of it. The one place `alternate_on` decides is a shell's AUTOMATIC load (`alt=recording`, see Full-scrollback replay): there the question is whether the capture holds the scrollback a nested tmux client keeps in its byte recording, not whether a pull can return more. The notice is also LAZY: it appears only after a wheel/touch gesture reaches the top of the browser buffer and the pull that gesture started has settled (`_maybeLoadMoreHistoryOnScroll`), goes away when a downward gesture is back at live output or the tab switches (`selectSession` nulls `_historyNoticeRevealedFor` before repainting), and its × is sticky per session until reload (`_historyNoticeDismissed`). Tests: `test/history-truncation-notice.test.ts`, `test/history-notice-reveal.test.ts`. diff --git a/src/web/public/app.js b/src/web/public/app.js index 565c4eca..5662ff02 100644 --- a/src/web/public/app.js +++ b/src/web/public/app.js @@ -10035,7 +10035,12 @@ class CodemanApp { btn.disabled = true; btn.textContent = 'Loading…'; // Forced: the cooldown exists to throttle scroll gestures, not choices. - this._maybeRefetchFullHistory({ force: true }).finally(() => { + // When Reload history is eligible, this button is shown in its place + // (one load control per bar), so it must keep the reader's line the same + // way. Checked at click time, not render time: the bar only re-renders on + // eligibility transitions, and the reader may have scrolled since. + const anchor = this._historyReloadActionEligible() ? 'content' : 'top'; + this._maybeRefetchFullHistory({ force: true, anchor }).finally(() => { this._renderHistoryTruncationBanner(); }); }; diff --git a/test/shell-scroll-history-pull.test.ts b/test/shell-scroll-history-pull.test.ts index 07cc1a21..6a0a2c32 100644 --- a/test/shell-scroll-history-pull.test.ts +++ b/test/shell-scroll-history-pull.test.ts @@ -1210,7 +1210,7 @@ describe('manual history banner action', () => { expect(button()).toBeUndefined(); }); - it.each(['recoverable', 'exhausted', 'capped'])('never duplicates the %s notice load control', (kind) => { + it.each(['recoverable', 'exhausted', 'capped'])('never duplicates the %s notice load control', async (kind) => { const { app, bar, button } = fixture(); app._historyNoticeRevealedFor = 's1'; app._setHistoryTruncation('s1', { @@ -1220,6 +1220,22 @@ describe('manual history banner action', () => { }); expect(bar.children.filter((child) => child.className === 'history-trunc-load')).toHaveLength(1); expect(button()!.textContent).toBe(kind === 'recoverable' ? 'Load full history' : 'Reload history'); + // Either way the one control stands in for Reload history, so it keeps the + // reader's line rather than landing on the old row 0. + await button()!.onclick!(); + expect(app._maybeRefetchFullHistory).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ force: true, anchor: 'content' }) + ); + }); + + it('keeps the top anchor for Load full history when Reload history is not eligible', async () => { + const { app, bar, button } = fixture({ marked: false }); + app._historyNoticeRevealedFor = 's1'; + app._setHistoryTruncation('s1', { ...TAIL_CUT, truncationReason: 'tail' }); + expect(bar.hidden).toBe(false); + expect(button()!.textContent).toBe('Load full history'); + await button()!.onclick!(); + expect(app._maybeRefetchFullHistory).toHaveBeenCalledExactlyOnceWith({ force: true, anchor: 'top' }); }); it('does no DOM work without a transition and coalesces all-device onScroll calls per frame', () => { From 193f220f5edb503e2f27587e289d86efd5bbaab9 Mon Sep 17 00:00:00 2001 From: Hadrien Kerlero <199662351+HadrienKerlero@users.noreply.github.com> Date: Fri, 20 Nov 2026 02:20:22 +0100 Subject: [PATCH 12/23] fix(web): hold the reader past a 2,000-row gap and drop stale drop recoveries (#814) - _restoreViewportAnchor searches expected - 4000 + rows .. expected + rows (same 4,001 candidates / 4,064 reads): filled rows only move the reader up, so gaps up to 4000 - rows land exactly, also at the scrollback cap. - _resetAllAppState and _cleanupPreviousSession clear _pendingDroppedOutputRecovery next to the recovery timer, so a reconnect load does not resume a stale recovery and run a second full capture. - Tests: capped 2,500- and 3,900-row gaps; both real cleanup methods drop the pending recovery. Docs: the window and the beyond-window fallback. --- docs/architecture-invariants.md | 2 +- src/web/public/app.js | 4 ++ src/web/public/terminal-ui.js | 11 +++- test/shell-scroll-history-pull.test.ts | 84 +++++++++++++++++++++++++- 4 files changed, 96 insertions(+), 5 deletions(-) diff --git a/docs/architecture-invariants.md b/docs/architecture-invariants.md index 4eba6c51..7f1dfd08 100644 --- a/docs/architecture-invariants.md +++ b/docs/architecture-invariants.md @@ -253,7 +253,7 @@ Further detail: the `<prefix>: <title>` form (`w3-myapp: fix the login redirect` **Full-scrollback replay** (COD-164/#148, reworked for #205): `GET /api/sessions/:id/terminal?full=1` returns the ENTIRE tmux scrollback (capture-pane `-e -S -<lines>` bounded by the configured history limit, explicit `maxBuffer` from the terminal-history config, early byte-cap before normalization, CRLF-normalized for shell panes). On success the capture is returned ALONE (`source='mux-full-history'` — it supersedes the byte buffer; no duplication). The first load of each non-shell TUI session per page requests `full=1` (`_fullHistoryLoaded` Set in app.js — the old one-shot `_initialFullBufferLoad` flag was consumed by whichever tab auto-selected, leaving every other TUI tab one frame of history). Shell sessions instead load a bounded window of tmux's RENDERED history on every selection, automatic drop recovery, clear and tile load (`SHELL_LOAD_QUERY` in constants.js: `?full=1&tail=1MiB&lines=10000&alt=recording`): a 100k-line shell capture can be tens of MiB, and automatically parsing it makes tab-switch latency scale with the entire session (`lines=` bounds the synchronous capture-pane, about 8 ms per 1000 lines). They never replay the raw byte recording ahead of the visible frame any more: it holds full-screen repaints (an ssh'd tmux, `less`, any TUI) drawn for the pane height of the moment, and replayed into a terminal of another height each repaint's last newline scrolls its top row into scrollback, so one line tmux holds once showed up dozens of times. Because `lines=` is shallower than xterm's scrollback, the route reports a cut: the capture's `display-message` query also reads `#{history_size}` (`PaneCaptureOptions.capturedHistoryLines`, the same field the route reports as `paneHistoryLines`), and a full capture whose CLIENT bound (`lines=` below the configured `tmuxHistoryLimit`) left lines in tmux comes back `truncated`, `truncationReason: 'tail'`. ⚠️ Only a client bound below the ceiling counts: a request without `lines=` is bounded by the ceiling itself, and on tmux before 3.7 a live pane can hold more than a lowered ceiling, which no request can read. ⚠️ **A pane in the alternate screen keeps no tmux history**, and a nested tmux client (remote SSH and Docker cases, or `tmux`/`ssh -t host tmux` run by hand) holds its pane there, so its full capture is one screen. The same query reads `#{alternate_on}` (`capturedAlternateOn`), and a request carrying `alt=recording` (only `SHELL_LOAD_QUERY`) is then answered the old way, the visible frame over the tailed byte recording, which still carries the scrollback; agents, scroll pulls and **Load full history** never send it. `#{alternate_on}` cannot tell a nested tmux from vim, `less` or `htop`, so a local shell with one of those open takes the same fallback until it exits (the pre-fix load, with its repaint duplicates). Shell FULL history is explicit-button-only; reaching the top during an ordinary wheel/touch gesture must not reset xterm and replay the multi-megabyte capture on its main thread. That gesture instead pulls a BOUNDED window of it (`?full=1&tail=<TERMINAL_TAIL_SIZE>`, so a capture beyond 1 MiB comes back `truncationReason: 'tail'` and the banner offers the rest), and skips the replay when the window holds no more rows than the browser already has. ⚠️ **That skip runs BEFORE the downgrade guard, and it never touches the banner state**: the guard reads "smaller than the browser" as "tmux has nothing more to give", true of an unbounded capture and false of a window cut at the tail size, so a bounded window that reached it marked the session `exhausted` and removed **Load full history** while tmux still held the rest; and re-labelling the banner from a skipped payload would call a terminal that holds all of a Load full history pull "the most recent 1 MiB". A skipped window that came back truncated puts the session on the 60 s cooldown (`_fullHistoryRepullUseless`), because it can never reach anything older than the browser shows and `tail` is applied AFTER the server's synchronous `capture-pane` of the whole history, so each ask costs every client an event-loop stall (about 1 s at 100k lines; measured capture details below); an untruncated one keeps the 4 s cooldown, since it is all of tmux's history and the next burst can add to it. Declining the gesture outright was a dead end: after any burst a shell pane held about one screen of browser scrollback, and the button renders only once a replay was truncated, so a young shell tab had no way back to history tmux still held. Other modes re-pull `full=1` only at the top of the local buffer, and pressing **Load full history** forces the request for any recoverably truncated session (`_maybeRefetchFullHistory`, 4s per-session gesture cooldown, in-flight + tab-switch guards, viewport position held across the replay); Shell full pulls are not retained in the tab cache, so the next switch stays bounded. Chunked replay enqueues 32 KiB pieces across safe yields, appends an xterm parse marker, then releases the live-output gate; output arriving after that release stays ordered behind the snapshot, and the marker callback supplies accurate parse timing. ⚠️ **How the load ENDS depends on where the payload came from**, and `_bufferLoadFinishOpts` (app.js) is the one place that decides it for all four fetch-and-write paths. A payload built from the server's accumulated byte history is current up to the response, so the events queued during the load already appear in it and stay DISCARDED; replaying them would duplicate output, most visibly Ink's cursor-up redraws. A pane capture (`mux-visible` or `mux-full-history`) is current only up to CAPTURE time, so `_finishBufferLoad` replays the queue from the response's own arrival timestamp (`since`) and the pre-capture events stay dropped. ⚠️ **A path that then restores a scroll position must re-take the sticky-scroll baseline** (`_syncStickyScrollBaseline`): the replay runs inside `chunkedTerminalWrite` before its promise resolves, with the terminal freshly reset, so `batchTerminalWrite` samples `_wasAtBottomBeforeWrite` as true and the next `flushPendingWrites` would scroll to the bottom over the restore. ⚠️ The cutoff is a client-side timestamp and the server broadcasts on a batch timer (8ms WebSocket, 16-50ms SSE), so a batch pending when the capture ran arrives after the response and replays although the capture holds it — bounded by one batch interval, and closable only server side by flushing that batch before the capture. Tests for the three: `test/terminal-flush-budget.test.ts` pins which sources flush, `test/terminal-buffer-flush.test.ts` pins the `since` cutoff and the baseline re-take, and `test/capture-load-window.browser.test.ts` drives both against a live server. Live output is separately one-chunk-in-flight: xterm's callback releases each 32/64 KiB write before the next is submitted, keeping the remainder in the app queue where the 128 KiB cap can observe it instead of hiding an unbounded backlog in xterm's private WriteBuffer. While WebSocket owns terminal I/O, parallel SSE terminal/output-recovery events are discarded before JSON parsing; fallback recovery is single-flight per active session so backpressure cannot start overlapping reset+replay cycles. The route exposes capture/prepare totals in `Server-Timing`, while `[TERMINAL-PERF]` separates TTFB, body/JSON, reset+parse and total time for both selection and on-demand full pulls; parse completion is not a browser compositor/GPU paint measurement. The re-pull exists because xterm's buffer is only a WINDOW onto tmux's history and two things shrink it: tmux coalesces bursty output into pane REPAINTS that overwrite rows instead of emitting linefeeds (measured: a 60-line burst added 1 row of browser scrollback and destroyed 34), and a tab switch replays only the visible frame. tmux's own history is intact throughout — the browser just has to ask for it again. Gesture-triggered rather than polling because at a 100k history limit the capture can be megabytes. ⚠️ **The capture ENDS with a cursor move back to the pane's own caret position** (`formatCursorRestore`, from the same `display-message` query the visible-frame path uses). The linear replay otherwise leaves the caret wherever the last character landed — the bottom-most row carrying text, which for an agent CLI is the status line — so the caret sat on the composer's border instead of its input line and every cursor-relative update the CLI sent afterwards was measured from the wrong row, until its next full redraw silently repaired it (that self-repair is why the report read as "it fixes itself as soon as Claude writes a line"). ⚠️ **The move is RELATIVE — up `rows - 1 - cursor_y`, then `\r`, then right `cursor_x` — never `CUP`.** `\x1b[<row>;<col>H` numbers rows from the top of the browser's screen, so it lands correctly only while the browser's row count equals `pane_height`, and nothing guarantees that: `resizeWindow` issues its tmux resize fire-and-forget and returns immediately, so a capture can be taken before a requested resize has applied, and `_onSessionNeedsRefresh` sends no resize at all. Counting up from the last replayed row anchors to the content both ends share. Restoring the cursor makes ROW ALIGNMENT load-bearing on this path: **no transform that can DELETE A LINE may run over a full-history capture**, because every deletion shifts the frame out from under the restored position. Four had accumulated — trailing blank rows stripped by `\n+$`, `stripInkRedrawBloat`, the `CLAUDE_BANNER_PATTERN` trim that cuts everything above the banner, and `LEADING_WHITESPACE_PATTERN` — each correct for a byte stream of successive frames and each wrong for a single rendered frame. ⚠️ **Those skips key on `isFullCapture`, meaning a capture actually came back — never on `?full=1` alone.** When `captureActivePaneBuffer` returns null (ENOBUFS, a timeout, a vanished pane, or a session with no mux at all) the reply falls back to `session.terminalBuffer`, which IS a byte stream and must still be stripped; gating on the query flag returned it whole, and a direct-PTY session takes that path on every first selection rather than only during an outage. ⚠️ A capture holding nothing visible (`hasVisibleContent`) returns `''`, because the caller reads an empty capture as "unavailable" and keeps its byte history — retaining trailing blank rows made an all-blank pane non-empty, which would have replaced real history with a blank screen from the server side, where `_replayWouldShrinkBuffer` cannot see it. ⚠️ **"One line per screen row" holds only where no row was hard-wrapped**: `-J` joins a wrapped row into its logical line (measured: a 100-character line in a 40-column pane captures as 10 lines against a 12-row pane), and the counts reconcile only once the browser xterm re-wraps at the same width — the same assumption `_estimateReplayRows` already documents. Tests: `test/tmux-capture-full-history.test.ts` covers the cursor move, the trim pairing and `hasVisibleContent`; `test/routes/session-routes.test.ts` covers a surviving blank first row, an unstripped byte-history fallback, and an empty capture leaving history intact. ⚠️ **The re-pull must never DOWNGRADE the buffer** (#205 round 2): the same reasoning that makes it a win for a shell pane makes it destructive for a repaint-mode CLI pane, where tmux keeps no history of its own (`history_size≈0` measured for a Claude pane) and the capture is roughly ONE frame while xterm may hold hundreds of rows of replayed frames — `_resetTerminalForReplay()` + rewrite then deletes history mid-scroll ("goes back a bit, repeats blocks, gets worse the further up I go"; measured A/B on a live pane: 341 rows → 42 with the guard off). `_replayWouldShrinkBuffer()` (terminal-ui.js) estimates the capture's rendered rows — escape sequences stripped, `capture-pane -J` re-wrapping accounted for — and the pull is skipped when that is more than one screen short of `buffer.active.length`. The one-screen tolerance matters: both sides are estimates (the buffer length counts trailing blank rows), so only a clear downgrade is refused. A refused session joins `_fullHistoryRepullUseless`, raising its cooldown from 4s to 60s so a hollow pane stops re-fetching megabytes on every scroll-up. Tests: `test/tmux-capture-full-history.test.ts`, `test/tmux-scrollback-eol.test.ts`, `test/terminal-scroll-routing.test.ts`, `test/terminal-flush-budget.test.ts`. -**Repair while reading (#814)** is a manual **Reload history** action inside the existing history banner on desktop and touch devices, enabled by default and toggleable per device in Settings → Terminal & Input → Scrolling & rendering (`historyReloadAction`). It is offered only for a marked non-shell active session while scrolled away from live output, not detached, not owned by tiles, with no pull or buffer load in flight and no terminal load state for the session (a tab switch sets it before the buffer load opens). `paneHistoryLines` is deliberately not consulted: it is recorded at the last load, so a session first opened empty keeps 0 after the very burst that opens the gap (#814). A revealed truncation notice keeps its message and its **Load full history** control; Reload is appended only when the notice has no load control, or shown alone with a short missing-output message. When Reload is eligible, that **Load full history** control stands in for it and pulls with the content anchor (eligibility read at click time), so the reader keeps their line; otherwise it keeps the top anchor. A reload-only × dismissal lasts until the mark is cleared by a successful `mux-full-history` replay, independently of the notice’s page-long dismissal. Pressing × while loading hides the bar immediately; the in-flight pull continues. Eligibility is cached per active session, with onScroll sampling coalesced to one animation frame on every device; unchanged eligibility never rebuilds the banner. Automatic history pulls and notice reveal stay top-only (#205). Live-output marking covers only live writes: a byte-history (`?tail=`) replay, for example after a burst in a background tab, never marks the session, so that gap relies on the top-of-buffer pull. The manual action forces a content-anchored pull, bypassing the gesture cooldown but retaining the downgrade guard. Any downgrade-refused pull hides Reload until the next successful `mux-full-history` replay; that refusal, not the cached history size, is what retires the action for a pane with no tmux history (fullscreen Claude). A manual reload answered by anything but `mux-full-history` (an empty response, or the byte-history fallback the route returns when the pane capture is blank or failed) retires it the same way, since only a mux replay clears the mark; a transient error envelope (`success: false`) leaves it available. A content anchor captures up to 64 visible rows, preserving indentation, and scores candidate alignments by matching viewport context. Each distinct nonblank row contributes at most one point, so repeated TUI borders cannot outvote a distinctive tool result. The best match must score at least 60% of the distinct rows and at least two of them, capped at the number of distinct rows, so a viewport with one distinct row (a lone tool result among blanks) matches on that row alone; it must also be unique within the search window. Equal-scoring copies are ambiguous, even when all furniture rows match or the distinctive tool row has disappeared; proximity to the expected position does not establish confidence. An isolated first-row match is not trusted: without confident, unambiguous context the old viewport index is retained, while readers already near live output retain their bottom distance. Search is bounded to 2000 rows either side of the expected viewport (at most 4001 candidates / 4064 cached line reads). Live flushes use an xterm marker to track the reading row across scrollback trimming in O(1), and restore it only in the write callback; at-bottom sticky scroll is unchanged. Ordered, session-scoped travel during replay is applied with per-move clamping; a switched-to tab never donates travel. The buffer load opens BEFORE the fetch, so download-time output queues behind the replay instead of being overwritten. Non-replay exits flush the whole queue; replays retain the capture-header cutoff above. A blocked dropped-output recovery stores its session and current attempt, defers without consuming retries, and resumes only for the still-active session. Only an actual `mux-full-history` replay clears the live-output mark and reload dismissal, and a newer live-write generation keeps them marked. The drop-recovery refresh (`_onSessionNeedsRefresh`) follows the same rule: it clears both after replaying a `mux-full-history` capture, only while it still owns the active session and the live-output generation sampled before its fetch is unchanged; its `?tail=` fallback never clears them, and because that fallback means the full capture would shrink the buffer (the refusal signal), it retires the action under the same session and refresh-owner checks. The trade-off remains a full synchronous server capture (about 1 s: 1,068 ms median for `capture-pane -p -e -J -S -100000` over 100k lines of 120 characters, 12.1 MB), not a cheap automatic per-output repair. Tests: `test/shell-scroll-history-pull.test.ts`, `test/history-gap-repair.browser.test.ts`. +**Repair while reading (#814)** is a manual **Reload history** action inside the existing history banner on desktop and touch devices, enabled by default and toggleable per device in Settings → Terminal & Input → Scrolling & rendering (`historyReloadAction`). It is offered only for a marked non-shell active session while scrolled away from live output, not detached, not owned by tiles, with no pull or buffer load in flight and no terminal load state for the session (a tab switch sets it before the buffer load opens). `paneHistoryLines` is deliberately not consulted: it is recorded at the last load, so a session first opened empty keeps 0 after the very burst that opens the gap (#814). A revealed truncation notice keeps its message and its **Load full history** control; Reload is appended only when the notice has no load control, or shown alone with a short missing-output message. When Reload is eligible, that **Load full history** control stands in for it and pulls with the content anchor (eligibility read at click time), so the reader keeps their line; otherwise it keeps the top anchor. A reload-only × dismissal lasts until the mark is cleared by a successful `mux-full-history` replay, independently of the notice’s page-long dismissal. Pressing × while loading hides the bar immediately; the in-flight pull continues. Eligibility is cached per active session, with onScroll sampling coalesced to one animation frame on every device; unchanged eligibility never rebuilds the banner. Automatic history pulls and notice reveal stay top-only (#205). Live-output marking covers only live writes: a byte-history (`?tail=`) replay, for example after a burst in a background tab, never marks the session, so that gap relies on the top-of-buffer pull. The manual action forces a content-anchored pull, bypassing the gesture cooldown but retaining the downgrade guard. Any downgrade-refused pull hides Reload until the next successful `mux-full-history` replay; that refusal, not the cached history size, is what retires the action for a pane with no tmux history (fullscreen Claude). A manual reload answered by anything but `mux-full-history` (an empty response, or the byte-history fallback the route returns when the pane capture is blank or failed) retires it the same way, since only a mux replay clears the mark; a transient error envelope (`success: false`) leaves it available. A content anchor captures up to 64 visible rows, preserving indentation, and scores candidate alignments by matching viewport context. Each distinct nonblank row contributes at most one point, so repeated TUI borders cannot outvote a distinctive tool result. The best match must score at least 60% of the distinct rows and at least two of them, capped at the number of distinct rows, so a viewport with one distinct row (a lone tool result among blanks) matches on that row alone; it must also be unique within the search window. Equal-scoring copies are ambiguous, even when all furniture rows match or the distinctive tool row has disappeared; proximity to the expected position does not establish confidence. An isolated first-row match is not trusted: without confident, unambiguous context the old viewport index is retained, while readers already near live output retain their bottom distance. Search covers 4001 candidates from `expected - 4000 + rows` to `expected + rows` (at most 4064 cached line reads), leaning up because every row a reload fills in below the reader moves the reader's row up, while a capture with fewer rows below moves it down by at most the one screen the downgrade guard tolerates. Gaps up to `4000 - rows` rows therefore land exactly, including at xterm's scrollback cap, where the replay trims the top by the same number of rows. A wider gap puts the match outside the window: the restore keeps the old absolute index, which is right while the top of the buffer stays put but, at the cap, lands the reader the whole gap below their line. Live flushes use an xterm marker to track the reading row across scrollback trimming in O(1), and restore it only in the write callback; at-bottom sticky scroll is unchanged. Ordered, session-scoped travel during replay is applied with per-move clamping; a switched-to tab never donates travel. The buffer load opens BEFORE the fetch, so download-time output queues behind the replay instead of being overwritten. Non-replay exits flush the whole queue; replays retain the capture-header cutoff above. A blocked dropped-output recovery stores its session and current attempt, defers without consuming retries, and resumes only for the still-active session. Only an actual `mux-full-history` replay clears the live-output mark and reload dismissal, and a newer live-write generation keeps them marked. The drop-recovery refresh (`_onSessionNeedsRefresh`) follows the same rule: it clears both after replaying a `mux-full-history` capture, only while it still owns the active session and the live-output generation sampled before its fetch is unchanged; its `?tail=` fallback never clears them, and because that fallback means the full capture would shrink the buffer (the refusal signal), it retires the action under the same session and refresh-owner checks. The trade-off remains a full synchronous server capture (about 1 s: 1,068 ms median for `capture-pane -p -e -J -S -100000` over 100k lines of 120 characters, 12.1 MB), not a cheap automatic per-output repair. Tests: `test/shell-scroll-history-pull.test.ts`, `test/history-gap-repair.browser.test.ts`. **The partial-history notice is lazy and pane-gated** (`computeHistoryTruncationNotice()` in constants.js, `_renderHistoryTruncationBanner()` / `_setHistoryNoticeRevealed()` in app.js). `truncated` on a terminal response measures the server's BYTE stream, which is not what `full=1` can return: for a pane with no tmux scrollback (fullscreen claude starts in the alternate screen and never writes to the main grid, so `#{history_size}` is 0) the bytes a tail cut drops are old repaint frames. Measured on prod 2026-10-10, every claude pane: the tab-switch tail cut a 1.2 to 6.2 MB stream to 1 MiB, the local scrollback that tail replays into is repeats of the same frames (one pane: 450 non-blank rows, 44 unique, one row 33 times), and `full=1` returned 1 to 5 KB, so **Load full history** could only end in the downgrade refusal while the banner promised "4.8 MB more". The capture therefore reads `#{history_size}` in the SAME `display-message` as the cursor (no extra tmux call), the route returns it as `paneHistoryLines` (absent when the body is not a capture, and for a remote SSH session, whose local pane hosts the remote tmux client and always reports 0 while `full=1` reads the remote history), and a reported 0 hides the notice in every state; a positive count replaces the byte gap in the message. ⚠️ Key the notice decision on `history_size`, never on `alternate_on`: a shell running `less` is in the alternate screen with its whole history still retained (measured, 99,972 rows) and `full=1` returns all of it. The one place `alternate_on` decides is a shell's AUTOMATIC load (`alt=recording`, see Full-scrollback replay): there the question is whether the capture holds the scrollback a nested tmux client keeps in its byte recording, not whether a pull can return more. The notice is also LAZY: it appears only after a wheel/touch gesture reaches the top of the browser buffer and the pull that gesture started has settled (`_maybeLoadMoreHistoryOnScroll`), goes away when a downward gesture is back at live output or the tab switches (`selectSession` nulls `_historyNoticeRevealedFor` before repainting), and its × is sticky per session until reload (`_historyNoticeDismissed`). Tests: `test/history-truncation-notice.test.ts`, `test/history-notice-reveal.test.ts`. diff --git a/src/web/public/app.js b/src/web/public/app.js index 5662ff02..844ace32 100644 --- a/src/web/public/app.js +++ b/src/web/public/app.js @@ -5013,6 +5013,9 @@ class CodemanApp { // Clear pending terminal writes this._clearTimer('syncWaitTimeout'); this._clearTimer('_clientDropRecoveryTimer'); + // A recovery deferred behind a load would otherwise resume once the next + // load (the reconnect's own refresh) finishes, and run a second full capture. + this._pendingDroppedOutputRecovery = null; this.pendingWrites = []; this.writeFrameScheduled = false; // Release the one-chunk-in-flight gate with the rest of the write queue. @@ -9508,6 +9511,7 @@ class CodemanApp { this._tabCompletionBaseText = null; this._clearTimer('_tabCompletionFallback'); this._clearTimer('_clientDropRecoveryTimer'); + this._pendingDroppedOutputRecovery = null; this._terminalRefreshOwner = null; // Clean up pending terminal writes to prevent old session data from appearing in new session diff --git a/src/web/public/terminal-ui.js b/src/web/public/terminal-ui.js index 41a45be0..bce41fa8 100644 --- a/src/web/public/terminal-ui.js +++ b/src/web/public/terminal-ui.js @@ -4050,8 +4050,15 @@ Object.assign(CodemanApp.prototype, { // Capped at the distinct-row count so a sparse viewport (one unique row // among blanks) can still match; the ambiguity check rejects repeats. const minimumScore = Math.min(frequencies.size, Math.max(2, frequencies.size * 0.6)); - const first = Math.max(0, expected - 2000); - const last = Math.min(buffer.baseY, expected + 2000); + // Every row a reload fills in BELOW the reader moves the reader's row one + // up from `expected`; a capture with fewer rows below moves it down by at + // most the one screen the downgrade guard tolerates. So the window leans + // up: 4001 candidates from `expected - 4000 + rows` to `expected + rows`, + // which lands gaps up to `4000 - rows` exactly even at the scrollback cap, + // where the replay trims the top and the old index is no longer a fallback. + const rows = this.terminal.rows || 0; + const first = Math.max(0, expected - 4000 + rows); + const last = Math.min(buffer.baseY, expected + rows); // Cache the search window once: <= 4064 getLine calls, even when all // 4001 candidates match repeated TUI furniture in a 50k-row buffer. const text = Array.from( diff --git a/test/shell-scroll-history-pull.test.ts b/test/shell-scroll-history-pull.test.ts index 6a0a2c32..c720e36c 100644 --- a/test/shell-scroll-history-pull.test.ts +++ b/test/shell-scroll-history-pull.test.ts @@ -689,6 +689,68 @@ describe('manual full-history recovery while reading (#814)', () => { expect(Reflect.get(app, '_pendingDroppedOutputRecovery')).toBeNull(); }); + it.each(['_resetAllAppState', '_cleanupPreviousSession'])( + '%s drops a deferred recovery, so the next load on the same tab does not resume it', + (method) => { + const { app } = makeApp('omp', { bufferRows: 30, capture: lines(400) }); + Object.assign(app, { + sessions: new Map(), + ralphStates: new Map(), + terminalBuffers: new Map(), + terminalBufferCache: new Map(), + _xtermSnapshots: new Map(), + projectInsights: new Map(), + idleTimers: new Map(), + pendingHooks: new Map(), + approvals: new Map(), + _parentNameCache: new Map(), + subagentActivity: new Map(), + subagentToolResults: new Map(), + workflowRuns: new Map(), + workflowRunDetails: new Map(), + tabAlerts: new Map(), + attachmentHistoryCounts: new Map(), + _shownCompletions: new Set(), + _flushedOffsets: new Map(), + _localEchoOverlay: { + clear: vi.fn(), + rerender: vi.fn(), + suppressBufferDetection: vi.fn(), + pendingText: '', + }, + _predictiveEcho: { clearPredictions: vi.fn() }, + notificationManager: null, + timerCountdownInterval: null, + runSummaryAutoRefreshTimer: null, + _chunkedWriteGen: 0, + _serializeAddon: null, + _disconnectWs: vi.fn(), + _flushLocalEchoTo: vi.fn(), + _clearTimer: vi.fn(), + _pendingDroppedOutputRecovery: { sessionId: 's1', attempt: 2 }, + activeSessionId: 's1', + }); + const cleanup = loadAppMethod(method, { + MobileDetection: { cleanup: vi.fn(), init: vi.fn() }, + KeyboardHandler: { cleanup: vi.fn(), init: vi.fn() }, + CjkInput: { clear: vi.fn() }, + localStorage: { removeItem: vi.fn() }, + document: { getElementById: () => null }, + clearTimeout, + clearInterval, + CompositionEvent: vi.fn(), + }); + if (method === '_resetAllAppState') cleanup.call(app); + else cleanup.call(app, 's1', { skipSnapshot: true }); + expect(app._clearTimer).toHaveBeenCalledWith('_clientDropRecoveryTimer'); + expect(Reflect.get(app, '_pendingDroppedOutputRecovery')).toBeNull(); + // The reconnect's own refresh on the same tab then finishes a load. + app.activeSessionId = 's1'; + app._finishBufferLoad((app._beginBufferLoad as Function).call(app)); + expect(app._scheduleDroppedOutputRecovery).not.toHaveBeenCalled(); + } + ); + it.each(['mux-full-history', 'history'])('clears the scroll-pull mark only for a mux capture: %s', async (source) => { const { app, liveOutput, reload } = makeScrollApp(); liveOutput(); @@ -948,9 +1010,11 @@ describe('content anchors hold the reader through a history repair', () => { const { capture, restore } = fixture(['head', 'A', 'B', 'C', ...Array(20).fill('tail')], 1); const anchor = capture(); const next = Array(34).fill('other'); + // Both complete copies sit inside the search window, which reaches up from + // the expected row (11 here) and at most one screen below it. next.splice(3, 3, 'A', 'B', 'C'); - next.splice(10, 3, 'A', 'wrong', 'wrong'); - next.splice(17, 3, 'A', 'B', 'C'); + next.splice(6, 3, 'A', 'wrong', 'wrong'); + next.splice(9, 3, 'A', 'B', 'C'); expect(restore(anchor, next)).toBe(1); }); @@ -1022,6 +1086,22 @@ describe('content anchors hold the reader through a history repair', () => { // 4001 possible starts plus the other 63 rows in the full viewport context. expect(active.getLine.mock.calls.length).toBeLessThanOrEqual(4064); }); + + it.each([2_500, 3_900])('lands the reader exactly at the scrollback cap with a %i-row gap filled below', (gap) => { + const rows = Array.from({ length: 10_000 }, (_, i) => `line ${i}`); + const { app, capture, restore } = fixture(rows, 6_000); + Object.assign(app.terminal, { rows: 30 }); + const anchor = capture(); + // At the cap the buffer length is fixed: filling `gap` rows below the reader + // trims as many from the top, so the reader's row moves `gap` rows up and the + // old absolute index lands `gap` rows too far down. + const below = 6_000 + 30 + 100; + const recovered = Array.from({ length: gap }, (_, i) => `recovered ${i}`); + const next = [...rows.slice(gap, below), ...recovered, ...rows.slice(below)]; + expect(next).toHaveLength(rows.length); + expect(restore(anchor, next)).toBe(6_000 - gap); + expect(next[6_000 - gap]).toBe('line 6000'); + }); }); describe('manual history banner action', () => { From 1f9b17e29a88a3f7012443939f723113ea933494 Mon Sep 17 00:00:00 2001 From: Hadrien Kerlero <199662351+HadrienKerlero@users.noreply.github.com> Date: Sat, 21 Nov 2026 23:32:01 +0100 Subject: [PATCH 13/23] fix(web): keep drop recovery bounded and the notice in step with replay travel (#814) - _onSessionNeedsRefresh clears the Reload mark only after a completed mux replay. - A later drop during an open load keeps the deferred recovery's higher attempt. - Replay travel that reaches row 0 reveals the partial-history notice; at live output it retires it. - The onScroll coalescing test drives the scheduler instead of evaluating a source line. --- docs/architecture-invariants.md | 2 +- src/web/public/app.js | 22 +++++- test/shell-scroll-history-pull.test.ts | 95 +++++++++++++++++++++----- 3 files changed, 99 insertions(+), 20 deletions(-) diff --git a/docs/architecture-invariants.md b/docs/architecture-invariants.md index 7f1dfd08..50e5cb12 100644 --- a/docs/architecture-invariants.md +++ b/docs/architecture-invariants.md @@ -253,7 +253,7 @@ Further detail: the `<prefix>: <title>` form (`w3-myapp: fix the login redirect` **Full-scrollback replay** (COD-164/#148, reworked for #205): `GET /api/sessions/:id/terminal?full=1` returns the ENTIRE tmux scrollback (capture-pane `-e -S -<lines>` bounded by the configured history limit, explicit `maxBuffer` from the terminal-history config, early byte-cap before normalization, CRLF-normalized for shell panes). On success the capture is returned ALONE (`source='mux-full-history'` — it supersedes the byte buffer; no duplication). The first load of each non-shell TUI session per page requests `full=1` (`_fullHistoryLoaded` Set in app.js — the old one-shot `_initialFullBufferLoad` flag was consumed by whichever tab auto-selected, leaving every other TUI tab one frame of history). Shell sessions instead load a bounded window of tmux's RENDERED history on every selection, automatic drop recovery, clear and tile load (`SHELL_LOAD_QUERY` in constants.js: `?full=1&tail=1MiB&lines=10000&alt=recording`): a 100k-line shell capture can be tens of MiB, and automatically parsing it makes tab-switch latency scale with the entire session (`lines=` bounds the synchronous capture-pane, about 8 ms per 1000 lines). They never replay the raw byte recording ahead of the visible frame any more: it holds full-screen repaints (an ssh'd tmux, `less`, any TUI) drawn for the pane height of the moment, and replayed into a terminal of another height each repaint's last newline scrolls its top row into scrollback, so one line tmux holds once showed up dozens of times. Because `lines=` is shallower than xterm's scrollback, the route reports a cut: the capture's `display-message` query also reads `#{history_size}` (`PaneCaptureOptions.capturedHistoryLines`, the same field the route reports as `paneHistoryLines`), and a full capture whose CLIENT bound (`lines=` below the configured `tmuxHistoryLimit`) left lines in tmux comes back `truncated`, `truncationReason: 'tail'`. ⚠️ Only a client bound below the ceiling counts: a request without `lines=` is bounded by the ceiling itself, and on tmux before 3.7 a live pane can hold more than a lowered ceiling, which no request can read. ⚠️ **A pane in the alternate screen keeps no tmux history**, and a nested tmux client (remote SSH and Docker cases, or `tmux`/`ssh -t host tmux` run by hand) holds its pane there, so its full capture is one screen. The same query reads `#{alternate_on}` (`capturedAlternateOn`), and a request carrying `alt=recording` (only `SHELL_LOAD_QUERY`) is then answered the old way, the visible frame over the tailed byte recording, which still carries the scrollback; agents, scroll pulls and **Load full history** never send it. `#{alternate_on}` cannot tell a nested tmux from vim, `less` or `htop`, so a local shell with one of those open takes the same fallback until it exits (the pre-fix load, with its repaint duplicates). Shell FULL history is explicit-button-only; reaching the top during an ordinary wheel/touch gesture must not reset xterm and replay the multi-megabyte capture on its main thread. That gesture instead pulls a BOUNDED window of it (`?full=1&tail=<TERMINAL_TAIL_SIZE>`, so a capture beyond 1 MiB comes back `truncationReason: 'tail'` and the banner offers the rest), and skips the replay when the window holds no more rows than the browser already has. ⚠️ **That skip runs BEFORE the downgrade guard, and it never touches the banner state**: the guard reads "smaller than the browser" as "tmux has nothing more to give", true of an unbounded capture and false of a window cut at the tail size, so a bounded window that reached it marked the session `exhausted` and removed **Load full history** while tmux still held the rest; and re-labelling the banner from a skipped payload would call a terminal that holds all of a Load full history pull "the most recent 1 MiB". A skipped window that came back truncated puts the session on the 60 s cooldown (`_fullHistoryRepullUseless`), because it can never reach anything older than the browser shows and `tail` is applied AFTER the server's synchronous `capture-pane` of the whole history, so each ask costs every client an event-loop stall (about 1 s at 100k lines; measured capture details below); an untruncated one keeps the 4 s cooldown, since it is all of tmux's history and the next burst can add to it. Declining the gesture outright was a dead end: after any burst a shell pane held about one screen of browser scrollback, and the button renders only once a replay was truncated, so a young shell tab had no way back to history tmux still held. Other modes re-pull `full=1` only at the top of the local buffer, and pressing **Load full history** forces the request for any recoverably truncated session (`_maybeRefetchFullHistory`, 4s per-session gesture cooldown, in-flight + tab-switch guards, viewport position held across the replay); Shell full pulls are not retained in the tab cache, so the next switch stays bounded. Chunked replay enqueues 32 KiB pieces across safe yields, appends an xterm parse marker, then releases the live-output gate; output arriving after that release stays ordered behind the snapshot, and the marker callback supplies accurate parse timing. ⚠️ **How the load ENDS depends on where the payload came from**, and `_bufferLoadFinishOpts` (app.js) is the one place that decides it for all four fetch-and-write paths. A payload built from the server's accumulated byte history is current up to the response, so the events queued during the load already appear in it and stay DISCARDED; replaying them would duplicate output, most visibly Ink's cursor-up redraws. A pane capture (`mux-visible` or `mux-full-history`) is current only up to CAPTURE time, so `_finishBufferLoad` replays the queue from the response's own arrival timestamp (`since`) and the pre-capture events stay dropped. ⚠️ **A path that then restores a scroll position must re-take the sticky-scroll baseline** (`_syncStickyScrollBaseline`): the replay runs inside `chunkedTerminalWrite` before its promise resolves, with the terminal freshly reset, so `batchTerminalWrite` samples `_wasAtBottomBeforeWrite` as true and the next `flushPendingWrites` would scroll to the bottom over the restore. ⚠️ The cutoff is a client-side timestamp and the server broadcasts on a batch timer (8ms WebSocket, 16-50ms SSE), so a batch pending when the capture ran arrives after the response and replays although the capture holds it — bounded by one batch interval, and closable only server side by flushing that batch before the capture. Tests for the three: `test/terminal-flush-budget.test.ts` pins which sources flush, `test/terminal-buffer-flush.test.ts` pins the `since` cutoff and the baseline re-take, and `test/capture-load-window.browser.test.ts` drives both against a live server. Live output is separately one-chunk-in-flight: xterm's callback releases each 32/64 KiB write before the next is submitted, keeping the remainder in the app queue where the 128 KiB cap can observe it instead of hiding an unbounded backlog in xterm's private WriteBuffer. While WebSocket owns terminal I/O, parallel SSE terminal/output-recovery events are discarded before JSON parsing; fallback recovery is single-flight per active session so backpressure cannot start overlapping reset+replay cycles. The route exposes capture/prepare totals in `Server-Timing`, while `[TERMINAL-PERF]` separates TTFB, body/JSON, reset+parse and total time for both selection and on-demand full pulls; parse completion is not a browser compositor/GPU paint measurement. The re-pull exists because xterm's buffer is only a WINDOW onto tmux's history and two things shrink it: tmux coalesces bursty output into pane REPAINTS that overwrite rows instead of emitting linefeeds (measured: a 60-line burst added 1 row of browser scrollback and destroyed 34), and a tab switch replays only the visible frame. tmux's own history is intact throughout — the browser just has to ask for it again. Gesture-triggered rather than polling because at a 100k history limit the capture can be megabytes. ⚠️ **The capture ENDS with a cursor move back to the pane's own caret position** (`formatCursorRestore`, from the same `display-message` query the visible-frame path uses). The linear replay otherwise leaves the caret wherever the last character landed — the bottom-most row carrying text, which for an agent CLI is the status line — so the caret sat on the composer's border instead of its input line and every cursor-relative update the CLI sent afterwards was measured from the wrong row, until its next full redraw silently repaired it (that self-repair is why the report read as "it fixes itself as soon as Claude writes a line"). ⚠️ **The move is RELATIVE — up `rows - 1 - cursor_y`, then `\r`, then right `cursor_x` — never `CUP`.** `\x1b[<row>;<col>H` numbers rows from the top of the browser's screen, so it lands correctly only while the browser's row count equals `pane_height`, and nothing guarantees that: `resizeWindow` issues its tmux resize fire-and-forget and returns immediately, so a capture can be taken before a requested resize has applied, and `_onSessionNeedsRefresh` sends no resize at all. Counting up from the last replayed row anchors to the content both ends share. Restoring the cursor makes ROW ALIGNMENT load-bearing on this path: **no transform that can DELETE A LINE may run over a full-history capture**, because every deletion shifts the frame out from under the restored position. Four had accumulated — trailing blank rows stripped by `\n+$`, `stripInkRedrawBloat`, the `CLAUDE_BANNER_PATTERN` trim that cuts everything above the banner, and `LEADING_WHITESPACE_PATTERN` — each correct for a byte stream of successive frames and each wrong for a single rendered frame. ⚠️ **Those skips key on `isFullCapture`, meaning a capture actually came back — never on `?full=1` alone.** When `captureActivePaneBuffer` returns null (ENOBUFS, a timeout, a vanished pane, or a session with no mux at all) the reply falls back to `session.terminalBuffer`, which IS a byte stream and must still be stripped; gating on the query flag returned it whole, and a direct-PTY session takes that path on every first selection rather than only during an outage. ⚠️ A capture holding nothing visible (`hasVisibleContent`) returns `''`, because the caller reads an empty capture as "unavailable" and keeps its byte history — retaining trailing blank rows made an all-blank pane non-empty, which would have replaced real history with a blank screen from the server side, where `_replayWouldShrinkBuffer` cannot see it. ⚠️ **"One line per screen row" holds only where no row was hard-wrapped**: `-J` joins a wrapped row into its logical line (measured: a 100-character line in a 40-column pane captures as 10 lines against a 12-row pane), and the counts reconcile only once the browser xterm re-wraps at the same width — the same assumption `_estimateReplayRows` already documents. Tests: `test/tmux-capture-full-history.test.ts` covers the cursor move, the trim pairing and `hasVisibleContent`; `test/routes/session-routes.test.ts` covers a surviving blank first row, an unstripped byte-history fallback, and an empty capture leaving history intact. ⚠️ **The re-pull must never DOWNGRADE the buffer** (#205 round 2): the same reasoning that makes it a win for a shell pane makes it destructive for a repaint-mode CLI pane, where tmux keeps no history of its own (`history_size≈0` measured for a Claude pane) and the capture is roughly ONE frame while xterm may hold hundreds of rows of replayed frames — `_resetTerminalForReplay()` + rewrite then deletes history mid-scroll ("goes back a bit, repeats blocks, gets worse the further up I go"; measured A/B on a live pane: 341 rows → 42 with the guard off). `_replayWouldShrinkBuffer()` (terminal-ui.js) estimates the capture's rendered rows — escape sequences stripped, `capture-pane -J` re-wrapping accounted for — and the pull is skipped when that is more than one screen short of `buffer.active.length`. The one-screen tolerance matters: both sides are estimates (the buffer length counts trailing blank rows), so only a clear downgrade is refused. A refused session joins `_fullHistoryRepullUseless`, raising its cooldown from 4s to 60s so a hollow pane stops re-fetching megabytes on every scroll-up. Tests: `test/tmux-capture-full-history.test.ts`, `test/tmux-scrollback-eol.test.ts`, `test/terminal-scroll-routing.test.ts`, `test/terminal-flush-budget.test.ts`. -**Repair while reading (#814)** is a manual **Reload history** action inside the existing history banner on desktop and touch devices, enabled by default and toggleable per device in Settings → Terminal & Input → Scrolling & rendering (`historyReloadAction`). It is offered only for a marked non-shell active session while scrolled away from live output, not detached, not owned by tiles, with no pull or buffer load in flight and no terminal load state for the session (a tab switch sets it before the buffer load opens). `paneHistoryLines` is deliberately not consulted: it is recorded at the last load, so a session first opened empty keeps 0 after the very burst that opens the gap (#814). A revealed truncation notice keeps its message and its **Load full history** control; Reload is appended only when the notice has no load control, or shown alone with a short missing-output message. When Reload is eligible, that **Load full history** control stands in for it and pulls with the content anchor (eligibility read at click time), so the reader keeps their line; otherwise it keeps the top anchor. A reload-only × dismissal lasts until the mark is cleared by a successful `mux-full-history` replay, independently of the notice’s page-long dismissal. Pressing × while loading hides the bar immediately; the in-flight pull continues. Eligibility is cached per active session, with onScroll sampling coalesced to one animation frame on every device; unchanged eligibility never rebuilds the banner. Automatic history pulls and notice reveal stay top-only (#205). Live-output marking covers only live writes: a byte-history (`?tail=`) replay, for example after a burst in a background tab, never marks the session, so that gap relies on the top-of-buffer pull. The manual action forces a content-anchored pull, bypassing the gesture cooldown but retaining the downgrade guard. Any downgrade-refused pull hides Reload until the next successful `mux-full-history` replay; that refusal, not the cached history size, is what retires the action for a pane with no tmux history (fullscreen Claude). A manual reload answered by anything but `mux-full-history` (an empty response, or the byte-history fallback the route returns when the pane capture is blank or failed) retires it the same way, since only a mux replay clears the mark; a transient error envelope (`success: false`) leaves it available. A content anchor captures up to 64 visible rows, preserving indentation, and scores candidate alignments by matching viewport context. Each distinct nonblank row contributes at most one point, so repeated TUI borders cannot outvote a distinctive tool result. The best match must score at least 60% of the distinct rows and at least two of them, capped at the number of distinct rows, so a viewport with one distinct row (a lone tool result among blanks) matches on that row alone; it must also be unique within the search window. Equal-scoring copies are ambiguous, even when all furniture rows match or the distinctive tool row has disappeared; proximity to the expected position does not establish confidence. An isolated first-row match is not trusted: without confident, unambiguous context the old viewport index is retained, while readers already near live output retain their bottom distance. Search covers 4001 candidates from `expected - 4000 + rows` to `expected + rows` (at most 4064 cached line reads), leaning up because every row a reload fills in below the reader moves the reader's row up, while a capture with fewer rows below moves it down by at most the one screen the downgrade guard tolerates. Gaps up to `4000 - rows` rows therefore land exactly, including at xterm's scrollback cap, where the replay trims the top by the same number of rows. A wider gap puts the match outside the window: the restore keeps the old absolute index, which is right while the top of the buffer stays put but, at the cap, lands the reader the whole gap below their line. Live flushes use an xterm marker to track the reading row across scrollback trimming in O(1), and restore it only in the write callback; at-bottom sticky scroll is unchanged. Ordered, session-scoped travel during replay is applied with per-move clamping; a switched-to tab never donates travel. The buffer load opens BEFORE the fetch, so download-time output queues behind the replay instead of being overwritten. Non-replay exits flush the whole queue; replays retain the capture-header cutoff above. A blocked dropped-output recovery stores its session and current attempt, defers without consuming retries, and resumes only for the still-active session. Only an actual `mux-full-history` replay clears the live-output mark and reload dismissal, and a newer live-write generation keeps them marked. The drop-recovery refresh (`_onSessionNeedsRefresh`) follows the same rule: it clears both after replaying a `mux-full-history` capture, only while it still owns the active session and the live-output generation sampled before its fetch is unchanged; its `?tail=` fallback never clears them, and because that fallback means the full capture would shrink the buffer (the refusal signal), it retires the action under the same session and refresh-owner checks. The trade-off remains a full synchronous server capture (about 1 s: 1,068 ms median for `capture-pane -p -e -J -S -100000` over 100k lines of 120 characters, 12.1 MB), not a cheap automatic per-output repair. Tests: `test/shell-scroll-history-pull.test.ts`, `test/history-gap-repair.browser.test.ts`. +**Repair while reading (#814)** is a manual **Reload history** action inside the existing history banner on desktop and touch devices, enabled by default and toggleable per device in Settings → Terminal & Input → Scrolling & rendering (`historyReloadAction`). It is offered only for a marked non-shell active session while scrolled away from live output, not detached, not owned by tiles, with no pull or buffer load in flight and no terminal load state for the session (a tab switch sets it before the buffer load opens). `paneHistoryLines` is deliberately not consulted: it is recorded at the last load, so a session first opened empty keeps 0 after the very burst that opens the gap (#814). A revealed truncation notice keeps its message and its **Load full history** control; Reload is appended only when the notice has no load control, or shown alone with a short missing-output message. When Reload is eligible, that **Load full history** control stands in for it and pulls with the content anchor (eligibility read at click time), so the reader keeps their line; otherwise it keeps the top anchor. A reload-only × dismissal lasts until the mark is cleared by a successful `mux-full-history` replay, independently of the notice’s page-long dismissal. Pressing × while loading hides the bar immediately; the in-flight pull continues. Eligibility is cached per active session, with onScroll sampling coalesced to one animation frame on every device; unchanged eligibility never rebuilds the banner. Automatic history pulls and notice reveal stay top-only (#205). Live-output marking covers only live writes: a byte-history (`?tail=`) replay, for example after a burst in a background tab, never marks the session, so that gap relies on the top-of-buffer pull. The manual action forces a content-anchored pull, bypassing the gesture cooldown but retaining the downgrade guard. Any downgrade-refused pull hides Reload until the next successful `mux-full-history` replay; that refusal, not the cached history size, is what retires the action for a pane with no tmux history (fullscreen Claude). A manual reload answered by anything but `mux-full-history` (an empty response, or the byte-history fallback the route returns when the pane capture is blank or failed) retires it the same way, since only a mux replay clears the mark; a transient error envelope (`success: false`) leaves it available. A content anchor captures up to 64 visible rows, preserving indentation, and scores candidate alignments by matching viewport context. Each distinct nonblank row contributes at most one point, so repeated TUI borders cannot outvote a distinctive tool result. The best match must score at least 60% of the distinct rows and at least two of them, capped at the number of distinct rows, so a viewport with one distinct row (a lone tool result among blanks) matches on that row alone; it must also be unique within the search window. Equal-scoring copies are ambiguous, even when all furniture rows match or the distinctive tool row has disappeared; proximity to the expected position does not establish confidence. An isolated first-row match is not trusted: without confident, unambiguous context the old viewport index is retained, while readers already near live output retain their bottom distance. Search covers 4001 candidates from `expected - 4000 + rows` to `expected + rows` (at most 4064 cached line reads), leaning up because every row a reload fills in below the reader moves the reader's row up, while a capture with fewer rows below moves it down by at most the one screen the downgrade guard tolerates. Gaps up to `4000 - rows` rows therefore land exactly, including at xterm's scrollback cap, where the replay trims the top by the same number of rows. A wider gap puts the match outside the window: the restore keeps the old absolute index, which is right while the top of the buffer stays put but, at the cap, lands the reader the whole gap below their line. Live flushes use an xterm marker to track the reading row across scrollback trimming in O(1), and restore it only in the write callback; at-bottom sticky scroll is unchanged. Ordered, session-scoped travel during replay is applied with per-move clamping; a switched-to tab never donates travel. Travel that ends at row 0 reveals the partial-history notice, and travel that ends at live output retires it, as a live scroll would; a reload with no travel leaves the notice as it was. The buffer load opens BEFORE the fetch, so download-time output queues behind the replay instead of being overwritten. Non-replay exits flush the whole queue; replays retain the capture-header cutoff above. A blocked dropped-output recovery stores its session and current attempt, defers without consuming retries, and resumes only for the still-active session; a later drop for the same session during that load keeps the higher attempt, so the retry bound still holds. Only an actual `mux-full-history` replay clears the live-output mark and reload dismissal, and a newer live-write generation keeps them marked. The drop-recovery refresh (`_onSessionNeedsRefresh`) follows the same rule: it clears both after a completed replay of a `mux-full-history` capture, only while it still owns the active session and the live-output generation sampled before its fetch is unchanged; its `?tail=` fallback never clears them, and because that fallback means the full capture would shrink the buffer (the refusal signal), it retires the action under the same session and refresh-owner checks. The trade-off remains a full synchronous server capture (about 1 s: 1,068 ms median for `capture-pane -p -e -J -S -100000` over 100k lines of 120 characters, 12.1 MB), not a cheap automatic per-output repair. Tests: `test/shell-scroll-history-pull.test.ts`, `test/history-gap-repair.browser.test.ts`. **The partial-history notice is lazy and pane-gated** (`computeHistoryTruncationNotice()` in constants.js, `_renderHistoryTruncationBanner()` / `_setHistoryNoticeRevealed()` in app.js). `truncated` on a terminal response measures the server's BYTE stream, which is not what `full=1` can return: for a pane with no tmux scrollback (fullscreen claude starts in the alternate screen and never writes to the main grid, so `#{history_size}` is 0) the bytes a tail cut drops are old repaint frames. Measured on prod 2026-10-10, every claude pane: the tab-switch tail cut a 1.2 to 6.2 MB stream to 1 MiB, the local scrollback that tail replays into is repeats of the same frames (one pane: 450 non-blank rows, 44 unique, one row 33 times), and `full=1` returned 1 to 5 KB, so **Load full history** could only end in the downgrade refusal while the banner promised "4.8 MB more". The capture therefore reads `#{history_size}` in the SAME `display-message` as the cursor (no extra tmux call), the route returns it as `paneHistoryLines` (absent when the body is not a capture, and for a remote SSH session, whose local pane hosts the remote tmux client and always reports 0 while `full=1` reads the remote history), and a reported 0 hides the notice in every state; a positive count replaces the byte gap in the message. ⚠️ Key the notice decision on `history_size`, never on `alternate_on`: a shell running `less` is in the alternate screen with its whole history still retained (measured, 99,972 rows) and `full=1` returns all of it. The one place `alternate_on` decides is a shell's AUTOMATIC load (`alt=recording`, see Full-scrollback replay): there the question is whether the capture holds the scrollback a nested tmux client keeps in its byte recording, not whether a pull can return more. The notice is also LAZY: it appears only after a wheel/touch gesture reaches the top of the browser buffer and the pull that gesture started has settled (`_maybeLoadMoreHistoryOnScroll`), goes away when a downward gesture is back at live output or the tab switches (`selectSession` nulls `_historyNoticeRevealedFor` before repainting), and its × is sticky per session until reload (`_historyNoticeDismissed`). Tests: `test/history-truncation-notice.test.ts`, `test/history-notice-reveal.test.ts`. diff --git a/src/web/public/app.js b/src/web/public/app.js index 844ace32..a3102cc9 100644 --- a/src/web/public/app.js +++ b/src/web/public/app.js @@ -2610,7 +2610,11 @@ class CodemanApp { if (this._pendingDroppedOutputRecovery?.sessionId !== sessionId && Number.isFinite(queuedBytes)) { _crashDiag.log(`TERMINAL DROP: ${(queuedBytes / 1024).toFixed(0)}KB queued (recovery deferred)`); } - this._pendingDroppedOutputRecovery = { sessionId, attempt }; + const pending = this._pendingDroppedOutputRecovery; + this._pendingDroppedOutputRecovery = { + sessionId, + attempt: pending?.sessionId === sessionId ? Math.max(pending.attempt, attempt) : attempt, + }; } return; } @@ -2622,7 +2626,13 @@ class CodemanApp { // A load may have opened after this timer was armed. Defer without // advancing the attempt; _finishBufferLoad resumes only the active tab. if (this._isLoadingBuffer) { - if (sessionId === this.activeSessionId) this._pendingDroppedOutputRecovery = { sessionId, attempt }; + if (sessionId === this.activeSessionId) { + const pending = this._pendingDroppedOutputRecovery; + this._pendingDroppedOutputRecovery = { + sessionId, + attempt: pending?.sessionId === sessionId ? Math.max(pending.attempt, attempt) : attempt, + }; + } return; } let repainted = false; @@ -3541,13 +3551,14 @@ class CodemanApp { // after them and fuse into the buffer written below. See // _resetTerminalForReplay. this._resetTerminalForReplay(); - await this.chunkedTerminalWrite( + const { completed } = await this.chunkedTerminalWrite( data.terminalBuffer, TERMINAL_CHUNK_SIZE, undefined, this._bufferLoadFinishOpts(data, headersReceivedAt) ); if ( + completed && this.activeSessionId === sessionId && this._terminalRefreshOwner === refreshOwner && data.source === 'mux-full-history' && @@ -9863,6 +9874,11 @@ class CodemanApp { let row = this._restoreViewportAnchor(viewportAnchor); for (const move of this._earlyReplayTravel.moves) row = clamp(row + move); this.terminal.scrollToLine(row); + // Replay travel bypassed the live scroll handler's notice update. + if (this._earlyReplayTravel.moves.length > 0) { + if (row === 0) this._setHistoryNoticeRevealed?.(sessionId); + else if (this.isTerminalAtBottom()) this._setHistoryNoticeRevealed?.(null); + } } else { const delta = parsedBufferLength - rowsBefore; if (delta > 0) this.terminal.scrollToLine(delta); diff --git a/test/shell-scroll-history-pull.test.ts b/test/shell-scroll-history-pull.test.ts index c720e36c..5ae0e9a2 100644 --- a/test/shell-scroll-history-pull.test.ts +++ b/test/shell-scroll-history-pull.test.ts @@ -680,6 +680,43 @@ describe('manual full-history recovery while reading (#814)', () => { } }); + it.each([false, true])('keeps the highest same-session deferred attempt (timer armed: %s)', async (armed) => { + vi.useFakeTimers(); + try { + const { app } = makeApp('omp', { bufferRows: 30, capture: lines(400) }); + const retry = vi.fn(() => false); + const schedule = loadAppMethod('_scheduleDroppedOutputRecovery', { + setTimeout, + window: { CodemanDroppedOutput: { DROP_RECOVERY_DELAY_MS: 2000, shouldRetryDroppedOutputRecovery: retry } }, + }); + Object.assign(app, { + _scheduleDroppedOutputRecovery: (...args: unknown[]) => schedule.apply(app, args), + _onSessionNeedsRefresh: vi.fn(async () => false), + }); + if (armed) schedule.call(app, 's1', 0); + const owner = (app._beginBufferLoad as Function).call(app); + schedule.call(app, 's1', 3); + if (armed) await vi.advanceTimersByTimeAsync(2000); + else schedule.call(app, 's1', 0); // A later dropped frame must not reset the bound. + expect(Reflect.get(app, '_pendingDroppedOutputRecovery')).toEqual({ sessionId: 's1', attempt: 3 }); + app._finishBufferLoad(owner); + await vi.advanceTimersByTimeAsync(2000); + expect(retry).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ attempt: 3 })); + } finally { + vi.useRealTimers(); + } + }); + + it('replaces a different session’s deferred attempt rather than merging it', () => { + const { app } = makeApp('omp', { bufferRows: 30, capture: lines(400) }); + const schedule = loadAppMethod('_scheduleDroppedOutputRecovery'); + const owner = (app._beginBufferLoad as Function).call(app); + Object.assign(app, { _pendingDroppedOutputRecovery: { sessionId: 's0', attempt: 4 } }); + schedule.call(app, 's1', 0); + expect(Reflect.get(app, '_pendingDroppedOutputRecovery')).toEqual({ sessionId: 's1', attempt: 0 }); + app._finishBufferLoad(owner); + }); + it('does not resume a deferred recovery for a tab that is no longer active', () => { const { app } = makeApp('omp', { bufferRows: 30, capture: lines(400) }); const owner = (app._beginBufferLoad as Function).call(app); @@ -764,6 +801,31 @@ describe('manual full-history recovery while reading (#814)', () => { expect(app._liveOutputSinceFullPull.has('s1')).toBe(source !== 'mux-full-history'); }); + it('reveals the truncation notice after replay travel reaches the top', async () => { + const { app, active, liveOutput, reload, pauseReplay } = makeScrollApp(); + liveOutput(); + const paused = pauseReplay(); + const pull = reload(); + await paused.ready; + (mixin._maybeLoadMoreHistoryOnScroll as Function).call(app, -10000); + paused.release(); + await pull; + expect(app._setHistoryNoticeRevealed).toHaveBeenCalledWith('s1'); + expect(active.viewportY).toBe(0); + expect(app._maybeRefetchFullHistory).toHaveBeenCalledOnce(); + }); + + it('does not reveal the truncation notice on reload without replay travel', async () => { + const { app, liveOutput, reload, pauseReplay } = makeScrollApp(); + liveOutput(); + const paused = pauseReplay(); + const pull = reload(); + await paused.ready; + paused.release(); + await pull; + expect(app._setHistoryNoticeRevealed).not.toHaveBeenCalledWith('s1'); + }); + it('does not swallow another tab’s travel or clear the old mark when replay is cancelled', async () => { const { app, active, liveOutput, reload, pauseReplay } = makeScrollApp(); liveOutput(); @@ -1320,27 +1382,14 @@ describe('manual history banner action', () => { it('does no DOM work without a transition and coalesces all-device onScroll calls per frame', () => { const { app, state, frames } = fixture({ touch: false }); - let onScroll!: () => void; - const source = readFileSync(resolve(PUBLIC, 'terminal-ui.js'), 'utf8'); - const registration = source.match(/^ this\.terminal\.onScroll\(.*$/m)![0]; - vm.runInNewContext(`(function () { ${registration} }).call(app)`, { - app: { - terminal: { - onScroll: (callback: () => void) => { - onScroll = callback; - }, - }, - _scheduleHistoryReloadActionSync: app._scheduleHistoryReloadActionSync, - }, - }); app._syncHistoryReloadAction(); - for (let i = 0; i < 100; i++) onScroll(); + for (let i = 0; i < 100; i++) app._scheduleHistoryReloadActionSync(); expect(frames).toHaveLength(1); frames.shift()!(0); expect(app._renderHistoryTruncationBanner).toHaveBeenCalledOnce(); state.bottom = true; - onScroll(); - onScroll(); + app._scheduleHistoryReloadActionSync(); + app._scheduleHistoryReloadActionSync(); expect(frames).toHaveLength(1); frames.shift()!(1); expect(app._renderHistoryTruncationBanner).toHaveBeenCalledTimes(2); @@ -1502,6 +1551,20 @@ describe('drop-recovery refresh clears the live-output mark only for a mux captu expect(app._syncHistoryReloadAction).toHaveBeenCalledTimes(2); }); + it('keeps the mark and dismissal when the mux replay is incomplete', async () => { + const { app, refresh, errors } = makeRefreshApp(); + app.chunkedTerminalWrite.mockImplementationOnce(async () => ({ + parsedAt: performance.now(), + bufferLength: 400, + completed: false, + })); + await refresh.call(app); + expect(errors).not.toHaveBeenCalled(); + expect(app.chunkedTerminalWrite).toHaveBeenCalledOnce(); + expect(app._liveOutputSinceFullPull.has('s1')).toBe(true); + expect(app._historyReloadDismissed.has('s1')).toBe(true); + }); + it('keeps the mark and dismissal for a history answer', async () => { const { app, refresh, errors } = makeRefreshApp('history'); expect(await refresh.call(app)).toBe(true); From a692f9f19398e137abb6b450ecbfb0816e627167 Mon Sep 17 00:00:00 2001 From: Hadrien Kerlero <199662351+HadrienKerlero@users.noreply.github.com> Date: Sun, 22 Nov 2026 01:40:42 +0100 Subject: [PATCH 14/23] fix(web): decide the history notice per replay move and drop unused anchor fields (#814) - Content-anchored replay travel reveals the notice on an upward move that reaches row 0 and retires it on a downward move back at live output, as a live scroll does. - _captureViewportAnchor returns only viewportY, rowsFromBottom and context; tests read anchor.context. --- docs/architecture-invariants.md | 2 +- src/web/public/app.js | 16 ++++++++++------ src/web/public/terminal-ui.js | 9 +-------- test/history-gap-repair.browser.test.ts | 8 +++++--- test/shell-scroll-history-pull.test.ts | 25 +++++++++++++++++++++---- 5 files changed, 38 insertions(+), 22 deletions(-) diff --git a/docs/architecture-invariants.md b/docs/architecture-invariants.md index 50e5cb12..00020436 100644 --- a/docs/architecture-invariants.md +++ b/docs/architecture-invariants.md @@ -253,7 +253,7 @@ Further detail: the `<prefix>: <title>` form (`w3-myapp: fix the login redirect` **Full-scrollback replay** (COD-164/#148, reworked for #205): `GET /api/sessions/:id/terminal?full=1` returns the ENTIRE tmux scrollback (capture-pane `-e -S -<lines>` bounded by the configured history limit, explicit `maxBuffer` from the terminal-history config, early byte-cap before normalization, CRLF-normalized for shell panes). On success the capture is returned ALONE (`source='mux-full-history'` — it supersedes the byte buffer; no duplication). The first load of each non-shell TUI session per page requests `full=1` (`_fullHistoryLoaded` Set in app.js — the old one-shot `_initialFullBufferLoad` flag was consumed by whichever tab auto-selected, leaving every other TUI tab one frame of history). Shell sessions instead load a bounded window of tmux's RENDERED history on every selection, automatic drop recovery, clear and tile load (`SHELL_LOAD_QUERY` in constants.js: `?full=1&tail=1MiB&lines=10000&alt=recording`): a 100k-line shell capture can be tens of MiB, and automatically parsing it makes tab-switch latency scale with the entire session (`lines=` bounds the synchronous capture-pane, about 8 ms per 1000 lines). They never replay the raw byte recording ahead of the visible frame any more: it holds full-screen repaints (an ssh'd tmux, `less`, any TUI) drawn for the pane height of the moment, and replayed into a terminal of another height each repaint's last newline scrolls its top row into scrollback, so one line tmux holds once showed up dozens of times. Because `lines=` is shallower than xterm's scrollback, the route reports a cut: the capture's `display-message` query also reads `#{history_size}` (`PaneCaptureOptions.capturedHistoryLines`, the same field the route reports as `paneHistoryLines`), and a full capture whose CLIENT bound (`lines=` below the configured `tmuxHistoryLimit`) left lines in tmux comes back `truncated`, `truncationReason: 'tail'`. ⚠️ Only a client bound below the ceiling counts: a request without `lines=` is bounded by the ceiling itself, and on tmux before 3.7 a live pane can hold more than a lowered ceiling, which no request can read. ⚠️ **A pane in the alternate screen keeps no tmux history**, and a nested tmux client (remote SSH and Docker cases, or `tmux`/`ssh -t host tmux` run by hand) holds its pane there, so its full capture is one screen. The same query reads `#{alternate_on}` (`capturedAlternateOn`), and a request carrying `alt=recording` (only `SHELL_LOAD_QUERY`) is then answered the old way, the visible frame over the tailed byte recording, which still carries the scrollback; agents, scroll pulls and **Load full history** never send it. `#{alternate_on}` cannot tell a nested tmux from vim, `less` or `htop`, so a local shell with one of those open takes the same fallback until it exits (the pre-fix load, with its repaint duplicates). Shell FULL history is explicit-button-only; reaching the top during an ordinary wheel/touch gesture must not reset xterm and replay the multi-megabyte capture on its main thread. That gesture instead pulls a BOUNDED window of it (`?full=1&tail=<TERMINAL_TAIL_SIZE>`, so a capture beyond 1 MiB comes back `truncationReason: 'tail'` and the banner offers the rest), and skips the replay when the window holds no more rows than the browser already has. ⚠️ **That skip runs BEFORE the downgrade guard, and it never touches the banner state**: the guard reads "smaller than the browser" as "tmux has nothing more to give", true of an unbounded capture and false of a window cut at the tail size, so a bounded window that reached it marked the session `exhausted` and removed **Load full history** while tmux still held the rest; and re-labelling the banner from a skipped payload would call a terminal that holds all of a Load full history pull "the most recent 1 MiB". A skipped window that came back truncated puts the session on the 60 s cooldown (`_fullHistoryRepullUseless`), because it can never reach anything older than the browser shows and `tail` is applied AFTER the server's synchronous `capture-pane` of the whole history, so each ask costs every client an event-loop stall (about 1 s at 100k lines; measured capture details below); an untruncated one keeps the 4 s cooldown, since it is all of tmux's history and the next burst can add to it. Declining the gesture outright was a dead end: after any burst a shell pane held about one screen of browser scrollback, and the button renders only once a replay was truncated, so a young shell tab had no way back to history tmux still held. Other modes re-pull `full=1` only at the top of the local buffer, and pressing **Load full history** forces the request for any recoverably truncated session (`_maybeRefetchFullHistory`, 4s per-session gesture cooldown, in-flight + tab-switch guards, viewport position held across the replay); Shell full pulls are not retained in the tab cache, so the next switch stays bounded. Chunked replay enqueues 32 KiB pieces across safe yields, appends an xterm parse marker, then releases the live-output gate; output arriving after that release stays ordered behind the snapshot, and the marker callback supplies accurate parse timing. ⚠️ **How the load ENDS depends on where the payload came from**, and `_bufferLoadFinishOpts` (app.js) is the one place that decides it for all four fetch-and-write paths. A payload built from the server's accumulated byte history is current up to the response, so the events queued during the load already appear in it and stay DISCARDED; replaying them would duplicate output, most visibly Ink's cursor-up redraws. A pane capture (`mux-visible` or `mux-full-history`) is current only up to CAPTURE time, so `_finishBufferLoad` replays the queue from the response's own arrival timestamp (`since`) and the pre-capture events stay dropped. ⚠️ **A path that then restores a scroll position must re-take the sticky-scroll baseline** (`_syncStickyScrollBaseline`): the replay runs inside `chunkedTerminalWrite` before its promise resolves, with the terminal freshly reset, so `batchTerminalWrite` samples `_wasAtBottomBeforeWrite` as true and the next `flushPendingWrites` would scroll to the bottom over the restore. ⚠️ The cutoff is a client-side timestamp and the server broadcasts on a batch timer (8ms WebSocket, 16-50ms SSE), so a batch pending when the capture ran arrives after the response and replays although the capture holds it — bounded by one batch interval, and closable only server side by flushing that batch before the capture. Tests for the three: `test/terminal-flush-budget.test.ts` pins which sources flush, `test/terminal-buffer-flush.test.ts` pins the `since` cutoff and the baseline re-take, and `test/capture-load-window.browser.test.ts` drives both against a live server. Live output is separately one-chunk-in-flight: xterm's callback releases each 32/64 KiB write before the next is submitted, keeping the remainder in the app queue where the 128 KiB cap can observe it instead of hiding an unbounded backlog in xterm's private WriteBuffer. While WebSocket owns terminal I/O, parallel SSE terminal/output-recovery events are discarded before JSON parsing; fallback recovery is single-flight per active session so backpressure cannot start overlapping reset+replay cycles. The route exposes capture/prepare totals in `Server-Timing`, while `[TERMINAL-PERF]` separates TTFB, body/JSON, reset+parse and total time for both selection and on-demand full pulls; parse completion is not a browser compositor/GPU paint measurement. The re-pull exists because xterm's buffer is only a WINDOW onto tmux's history and two things shrink it: tmux coalesces bursty output into pane REPAINTS that overwrite rows instead of emitting linefeeds (measured: a 60-line burst added 1 row of browser scrollback and destroyed 34), and a tab switch replays only the visible frame. tmux's own history is intact throughout — the browser just has to ask for it again. Gesture-triggered rather than polling because at a 100k history limit the capture can be megabytes. ⚠️ **The capture ENDS with a cursor move back to the pane's own caret position** (`formatCursorRestore`, from the same `display-message` query the visible-frame path uses). The linear replay otherwise leaves the caret wherever the last character landed — the bottom-most row carrying text, which for an agent CLI is the status line — so the caret sat on the composer's border instead of its input line and every cursor-relative update the CLI sent afterwards was measured from the wrong row, until its next full redraw silently repaired it (that self-repair is why the report read as "it fixes itself as soon as Claude writes a line"). ⚠️ **The move is RELATIVE — up `rows - 1 - cursor_y`, then `\r`, then right `cursor_x` — never `CUP`.** `\x1b[<row>;<col>H` numbers rows from the top of the browser's screen, so it lands correctly only while the browser's row count equals `pane_height`, and nothing guarantees that: `resizeWindow` issues its tmux resize fire-and-forget and returns immediately, so a capture can be taken before a requested resize has applied, and `_onSessionNeedsRefresh` sends no resize at all. Counting up from the last replayed row anchors to the content both ends share. Restoring the cursor makes ROW ALIGNMENT load-bearing on this path: **no transform that can DELETE A LINE may run over a full-history capture**, because every deletion shifts the frame out from under the restored position. Four had accumulated — trailing blank rows stripped by `\n+$`, `stripInkRedrawBloat`, the `CLAUDE_BANNER_PATTERN` trim that cuts everything above the banner, and `LEADING_WHITESPACE_PATTERN` — each correct for a byte stream of successive frames and each wrong for a single rendered frame. ⚠️ **Those skips key on `isFullCapture`, meaning a capture actually came back — never on `?full=1` alone.** When `captureActivePaneBuffer` returns null (ENOBUFS, a timeout, a vanished pane, or a session with no mux at all) the reply falls back to `session.terminalBuffer`, which IS a byte stream and must still be stripped; gating on the query flag returned it whole, and a direct-PTY session takes that path on every first selection rather than only during an outage. ⚠️ A capture holding nothing visible (`hasVisibleContent`) returns `''`, because the caller reads an empty capture as "unavailable" and keeps its byte history — retaining trailing blank rows made an all-blank pane non-empty, which would have replaced real history with a blank screen from the server side, where `_replayWouldShrinkBuffer` cannot see it. ⚠️ **"One line per screen row" holds only where no row was hard-wrapped**: `-J` joins a wrapped row into its logical line (measured: a 100-character line in a 40-column pane captures as 10 lines against a 12-row pane), and the counts reconcile only once the browser xterm re-wraps at the same width — the same assumption `_estimateReplayRows` already documents. Tests: `test/tmux-capture-full-history.test.ts` covers the cursor move, the trim pairing and `hasVisibleContent`; `test/routes/session-routes.test.ts` covers a surviving blank first row, an unstripped byte-history fallback, and an empty capture leaving history intact. ⚠️ **The re-pull must never DOWNGRADE the buffer** (#205 round 2): the same reasoning that makes it a win for a shell pane makes it destructive for a repaint-mode CLI pane, where tmux keeps no history of its own (`history_size≈0` measured for a Claude pane) and the capture is roughly ONE frame while xterm may hold hundreds of rows of replayed frames — `_resetTerminalForReplay()` + rewrite then deletes history mid-scroll ("goes back a bit, repeats blocks, gets worse the further up I go"; measured A/B on a live pane: 341 rows → 42 with the guard off). `_replayWouldShrinkBuffer()` (terminal-ui.js) estimates the capture's rendered rows — escape sequences stripped, `capture-pane -J` re-wrapping accounted for — and the pull is skipped when that is more than one screen short of `buffer.active.length`. The one-screen tolerance matters: both sides are estimates (the buffer length counts trailing blank rows), so only a clear downgrade is refused. A refused session joins `_fullHistoryRepullUseless`, raising its cooldown from 4s to 60s so a hollow pane stops re-fetching megabytes on every scroll-up. Tests: `test/tmux-capture-full-history.test.ts`, `test/tmux-scrollback-eol.test.ts`, `test/terminal-scroll-routing.test.ts`, `test/terminal-flush-budget.test.ts`. -**Repair while reading (#814)** is a manual **Reload history** action inside the existing history banner on desktop and touch devices, enabled by default and toggleable per device in Settings → Terminal & Input → Scrolling & rendering (`historyReloadAction`). It is offered only for a marked non-shell active session while scrolled away from live output, not detached, not owned by tiles, with no pull or buffer load in flight and no terminal load state for the session (a tab switch sets it before the buffer load opens). `paneHistoryLines` is deliberately not consulted: it is recorded at the last load, so a session first opened empty keeps 0 after the very burst that opens the gap (#814). A revealed truncation notice keeps its message and its **Load full history** control; Reload is appended only when the notice has no load control, or shown alone with a short missing-output message. When Reload is eligible, that **Load full history** control stands in for it and pulls with the content anchor (eligibility read at click time), so the reader keeps their line; otherwise it keeps the top anchor. A reload-only × dismissal lasts until the mark is cleared by a successful `mux-full-history` replay, independently of the notice’s page-long dismissal. Pressing × while loading hides the bar immediately; the in-flight pull continues. Eligibility is cached per active session, with onScroll sampling coalesced to one animation frame on every device; unchanged eligibility never rebuilds the banner. Automatic history pulls and notice reveal stay top-only (#205). Live-output marking covers only live writes: a byte-history (`?tail=`) replay, for example after a burst in a background tab, never marks the session, so that gap relies on the top-of-buffer pull. The manual action forces a content-anchored pull, bypassing the gesture cooldown but retaining the downgrade guard. Any downgrade-refused pull hides Reload until the next successful `mux-full-history` replay; that refusal, not the cached history size, is what retires the action for a pane with no tmux history (fullscreen Claude). A manual reload answered by anything but `mux-full-history` (an empty response, or the byte-history fallback the route returns when the pane capture is blank or failed) retires it the same way, since only a mux replay clears the mark; a transient error envelope (`success: false`) leaves it available. A content anchor captures up to 64 visible rows, preserving indentation, and scores candidate alignments by matching viewport context. Each distinct nonblank row contributes at most one point, so repeated TUI borders cannot outvote a distinctive tool result. The best match must score at least 60% of the distinct rows and at least two of them, capped at the number of distinct rows, so a viewport with one distinct row (a lone tool result among blanks) matches on that row alone; it must also be unique within the search window. Equal-scoring copies are ambiguous, even when all furniture rows match or the distinctive tool row has disappeared; proximity to the expected position does not establish confidence. An isolated first-row match is not trusted: without confident, unambiguous context the old viewport index is retained, while readers already near live output retain their bottom distance. Search covers 4001 candidates from `expected - 4000 + rows` to `expected + rows` (at most 4064 cached line reads), leaning up because every row a reload fills in below the reader moves the reader's row up, while a capture with fewer rows below moves it down by at most the one screen the downgrade guard tolerates. Gaps up to `4000 - rows` rows therefore land exactly, including at xterm's scrollback cap, where the replay trims the top by the same number of rows. A wider gap puts the match outside the window: the restore keeps the old absolute index, which is right while the top of the buffer stays put but, at the cap, lands the reader the whole gap below their line. Live flushes use an xterm marker to track the reading row across scrollback trimming in O(1), and restore it only in the write callback; at-bottom sticky scroll is unchanged. Ordered, session-scoped travel during replay is applied with per-move clamping; a switched-to tab never donates travel. Travel that ends at row 0 reveals the partial-history notice, and travel that ends at live output retires it, as a live scroll would; a reload with no travel leaves the notice as it was. The buffer load opens BEFORE the fetch, so download-time output queues behind the replay instead of being overwritten. Non-replay exits flush the whole queue; replays retain the capture-header cutoff above. A blocked dropped-output recovery stores its session and current attempt, defers without consuming retries, and resumes only for the still-active session; a later drop for the same session during that load keeps the higher attempt, so the retry bound still holds. Only an actual `mux-full-history` replay clears the live-output mark and reload dismissal, and a newer live-write generation keeps them marked. The drop-recovery refresh (`_onSessionNeedsRefresh`) follows the same rule: it clears both after a completed replay of a `mux-full-history` capture, only while it still owns the active session and the live-output generation sampled before its fetch is unchanged; its `?tail=` fallback never clears them, and because that fallback means the full capture would shrink the buffer (the refusal signal), it retires the action under the same session and refresh-owner checks. The trade-off remains a full synchronous server capture (about 1 s: 1,068 ms median for `capture-pane -p -e -J -S -100000` over 100k lines of 120 characters, 12.1 MB), not a cheap automatic per-output repair. Tests: `test/shell-scroll-history-pull.test.ts`, `test/history-gap-repair.browser.test.ts`. +**Repair while reading (#814)** is a manual **Reload history** action inside the existing history banner on desktop and touch devices, enabled by default and toggleable per device in Settings → Terminal & Input → Scrolling & rendering (`historyReloadAction`). It is offered only for a marked non-shell active session while scrolled away from live output, not detached, not owned by tiles, with no pull or buffer load in flight and no terminal load state for the session (a tab switch sets it before the buffer load opens). `paneHistoryLines` is deliberately not consulted: it is recorded at the last load, so a session first opened empty keeps 0 after the very burst that opens the gap (#814). A revealed truncation notice keeps its message and its **Load full history** control; Reload is appended only when the notice has no load control, or shown alone with a short missing-output message. When Reload is eligible, that **Load full history** control stands in for it and pulls with the content anchor (eligibility read at click time), so the reader keeps their line; otherwise it keeps the top anchor. A reload-only × dismissal lasts until the mark is cleared by a successful `mux-full-history` replay, independently of the notice’s page-long dismissal. Pressing × while loading hides the bar immediately; the in-flight pull continues. Eligibility is cached per active session, with onScroll sampling coalesced to one animation frame on every device; unchanged eligibility never rebuilds the banner. Automatic history pulls and notice reveal stay top-only (#205). Live-output marking covers only live writes: a byte-history (`?tail=`) replay, for example after a burst in a background tab, never marks the session, so that gap relies on the top-of-buffer pull. The manual action forces a content-anchored pull, bypassing the gesture cooldown but retaining the downgrade guard. Any downgrade-refused pull hides Reload until the next successful `mux-full-history` replay; that refusal, not the cached history size, is what retires the action for a pane with no tmux history (fullscreen Claude). A manual reload answered by anything but `mux-full-history` (an empty response, or the byte-history fallback the route returns when the pane capture is blank or failed) retires it the same way, since only a mux replay clears the mark; a transient error envelope (`success: false`) leaves it available. A content anchor captures up to 64 visible rows, preserving indentation, and scores candidate alignments by matching viewport context. Each distinct nonblank row contributes at most one point, so repeated TUI borders cannot outvote a distinctive tool result. The best match must score at least 60% of the distinct rows and at least two of them, capped at the number of distinct rows, so a viewport with one distinct row (a lone tool result among blanks) matches on that row alone; it must also be unique within the search window. Equal-scoring copies are ambiguous, even when all furniture rows match or the distinctive tool row has disappeared; proximity to the expected position does not establish confidence. An isolated first-row match is not trusted: without confident, unambiguous context the old viewport index is retained, while readers already near live output retain their bottom distance. Search covers 4001 candidates from `expected - 4000 + rows` to `expected + rows` (at most 4064 cached line reads), leaning up because every row a reload fills in below the reader moves the reader's row up, while a capture with fewer rows below moves it down by at most the one screen the downgrade guard tolerates. Gaps up to `4000 - rows` rows therefore land exactly, including at xterm's scrollback cap, where the replay trims the top by the same number of rows. A wider gap puts the match outside the window: the restore keeps the old absolute index, which is right while the top of the buffer stays put but, at the cap, lands the reader the whole gap below their line. Live flushes use an xterm marker to track the reading row across scrollback trimming in O(1), and restore it only in the write callback; at-bottom sticky scroll is unchanged. Ordered, session-scoped travel during replay is applied with per-move clamping; a switched-to tab never donates travel. The notice is decided per recorded move, as a live scroll decides it: an upward move that reaches row 0 reveals the partial-history notice, a downward move that reaches live output retires it, and other moves leave the last decision standing, so reaching the top and then scrolling a few rows down still reveals it; a reload with no travel leaves the notice as it was. The buffer load opens BEFORE the fetch, so download-time output queues behind the replay instead of being overwritten. Non-replay exits flush the whole queue; replays retain the capture-header cutoff above. A blocked dropped-output recovery stores its session and current attempt, defers without consuming retries, and resumes only for the still-active session; a later drop for the same session during that load keeps the higher attempt, so the retry bound still holds. Only an actual `mux-full-history` replay clears the live-output mark and reload dismissal, and a newer live-write generation keeps them marked. The drop-recovery refresh (`_onSessionNeedsRefresh`) follows the same rule: it clears both after a completed replay of a `mux-full-history` capture, only while it still owns the active session and the live-output generation sampled before its fetch is unchanged; its `?tail=` fallback never clears them, and because that fallback means the full capture would shrink the buffer (the refusal signal), it retires the action under the same session and refresh-owner checks. The trade-off remains a full synchronous server capture (about 1 s: 1,068 ms median for `capture-pane -p -e -J -S -100000` over 100k lines of 120 characters, 12.1 MB), not a cheap automatic per-output repair. Tests: `test/shell-scroll-history-pull.test.ts`, `test/history-gap-repair.browser.test.ts`. **The partial-history notice is lazy and pane-gated** (`computeHistoryTruncationNotice()` in constants.js, `_renderHistoryTruncationBanner()` / `_setHistoryNoticeRevealed()` in app.js). `truncated` on a terminal response measures the server's BYTE stream, which is not what `full=1` can return: for a pane with no tmux scrollback (fullscreen claude starts in the alternate screen and never writes to the main grid, so `#{history_size}` is 0) the bytes a tail cut drops are old repaint frames. Measured on prod 2026-10-10, every claude pane: the tab-switch tail cut a 1.2 to 6.2 MB stream to 1 MiB, the local scrollback that tail replays into is repeats of the same frames (one pane: 450 non-blank rows, 44 unique, one row 33 times), and `full=1` returned 1 to 5 KB, so **Load full history** could only end in the downgrade refusal while the banner promised "4.8 MB more". The capture therefore reads `#{history_size}` in the SAME `display-message` as the cursor (no extra tmux call), the route returns it as `paneHistoryLines` (absent when the body is not a capture, and for a remote SSH session, whose local pane hosts the remote tmux client and always reports 0 while `full=1` reads the remote history), and a reported 0 hides the notice in every state; a positive count replaces the byte gap in the message. ⚠️ Key the notice decision on `history_size`, never on `alternate_on`: a shell running `less` is in the alternate screen with its whole history still retained (measured, 99,972 rows) and `full=1` returns all of it. The one place `alternate_on` decides is a shell's AUTOMATIC load (`alt=recording`, see Full-scrollback replay): there the question is whether the capture holds the scrollback a nested tmux client keeps in its byte recording, not whether a pull can return more. The notice is also LAZY: it appears only after a wheel/touch gesture reaches the top of the browser buffer and the pull that gesture started has settled (`_maybeLoadMoreHistoryOnScroll`), goes away when a downward gesture is back at live output or the tab switches (`selectSession` nulls `_historyNoticeRevealedFor` before repainting), and its × is sticky per session until reload (`_historyNoticeDismissed`). Tests: `test/history-truncation-notice.test.ts`, `test/history-notice-reveal.test.ts`. diff --git a/src/web/public/app.js b/src/web/public/app.js index a3102cc9..3a4b7dc6 100644 --- a/src/web/public/app.js +++ b/src/web/public/app.js @@ -9872,13 +9872,17 @@ class CodemanApp { const baseY = this.terminal.buffer.active.baseY; const clamp = (row) => Math.max(0, Math.min(baseY, row)); let row = this._restoreViewportAnchor(viewportAnchor); - for (const move of this._earlyReplayTravel.moves) row = clamp(row + move); - this.terminal.scrollToLine(row); - // Replay travel bypassed the live scroll handler's notice update. - if (this._earlyReplayTravel.moves.length > 0) { - if (row === 0) this._setHistoryNoticeRevealed?.(sessionId); - else if (this.isTerminalAtBottom()) this._setHistoryNoticeRevealed?.(null); + // Replay travel bypassed the live scroll handler's notice update, so + // decide it per move as that handler would: an upward move that reaches + // row 0 reveals the notice, a downward move back at live output retires it. + let reveal = null; + for (const move of this._earlyReplayTravel.moves) { + row = clamp(row + move); + if (move < 0 && row === 0) reveal = true; + else if (move > 0 && row >= baseY - 2) reveal = false; } + this.terminal.scrollToLine(row); + if (reveal !== null) this._setHistoryNoticeRevealed?.(reveal ? sessionId : null); } else { const delta = parsedBufferLength - rowsBefore; if (delta > 0) this.terminal.scrollToLine(delta); diff --git a/src/web/public/terminal-ui.js b/src/web/public/terminal-ui.js index bce41fa8..888e2276 100644 --- a/src/web/public/terminal-ui.js +++ b/src/web/public/terminal-ui.js @@ -4019,14 +4019,7 @@ Object.assign(CodemanApp.prototype, { { length: Math.min(this.terminal.rows || 3, 64, buffer.length - viewportY) }, (_, i) => buffer.getLine(viewportY + i)?.translateToString(true) || '' ); - const offset = Math.max(0, context.findIndex((text) => text.trim())); - return { - viewportY, - rowsFromBottom: baseY - viewportY, - offset, - signature: Array.from({ length: 3 }, (_, i) => context[offset + i] || ''), - context, - }; + return { viewportY, rowsFromBottom: baseY - viewportY, context }; }, /** Match the visible context; a lone repeated row is not a reliable anchor. */ diff --git a/test/history-gap-repair.browser.test.ts b/test/history-gap-repair.browser.test.ts index 355e664d..5fbabdd3 100644 --- a/test/history-gap-repair.browser.test.ts +++ b/test/history-gap-repair.browser.test.ts @@ -4,7 +4,7 @@ import { chromium, type Browser, type BrowserContext, type Page } from 'playwrig import type { Terminal } from '@xterm/xterm'; import { WebServer } from '../src/web/server.js'; -type Anchor = { signature: string[]; offset: number; viewportY: number; rowsFromBottom: number }; +type Anchor = { context: string[]; viewportY: number; rowsFromBottom: number }; type HistoryApp = { terminal: Terminal & { _core?: { _renderService?: { dimensions?: { css?: { cell?: { height: number } } } } }; @@ -293,11 +293,13 @@ async function bufferState(page: Page) { (_, i) => buffer.getLine(i)?.translateToString(true).trim() || '' ); const anchor = w.repairTest.anchor; + // The first non-blank visible row the anchor captured, and where it sat. + const anchorRow = anchor ? anchor.context.findIndex((text) => text.trim()) : -1; return { numbers: rows.filter((row) => /^NUMBER-\d+$/.test(row)), markerHits: rows.filter((row) => row.includes(marker)).length, - anchorOffset: anchor ? rows.indexOf(anchor.signature[0]) - buffer.viewportY : null, - expectedOffset: anchor?.offset, + anchorOffset: anchor ? rows.indexOf(anchor.context[anchorRow]) - buffer.viewportY : null, + expectedOffset: anchor ? anchorRow : undefined, pulls: w.repairTest.pulls, viewportY: buffer.viewportY, baseY: buffer.baseY, diff --git a/test/shell-scroll-history-pull.test.ts b/test/shell-scroll-history-pull.test.ts index 5ae0e9a2..2442edd7 100644 --- a/test/shell-scroll-history-pull.test.ts +++ b/test/shell-scroll-history-pull.test.ts @@ -815,6 +815,23 @@ describe('manual full-history recovery while reading (#814)', () => { expect(app._maybeRefetchFullHistory).toHaveBeenCalledOnce(); }); + it.each([ + { moves: [-10000, 3], revealed: 's1', row: 3 }, + { moves: [-10000, 10000], revealed: null, row: 370 }, + ])('decides the notice per replay move like a live scroll: $moves', async ({ moves, revealed, row }) => { + const { app, active, liveOutput, reload, pauseReplay } = makeScrollApp(); + liveOutput(); + const paused = pauseReplay(); + const pull = reload(); + await paused.ready; + for (const move of moves) (mixin._maybeLoadMoreHistoryOnScroll as Function).call(app, move); + paused.release(); + await pull; + expect(active.viewportY).toBe(row); + expect(app._setHistoryNoticeRevealed).toHaveBeenLastCalledWith(revealed); + expect(app._maybeRefetchFullHistory).toHaveBeenCalledOnce(); + }); + it('does not reveal the truncation notice on reload without replay travel', async () => { const { app, liveOutput, reload, pauseReplay } = makeScrollApp(); liveOutput(); @@ -1056,7 +1073,7 @@ describe('content anchors hold the reader through a history repair', () => { return { app, active, capture, restore }; } - it('keeps a three-row signature at its viewport offset when rows are inserted below the reader', () => { + it('keeps the visible context at its viewport offset when rows are inserted below the reader', () => { const rows = Array.from({ length: 30 }, (_, i) => `row ${i}`); rows[5] = ''; const { app, capture, restore } = fixture(rows); @@ -1065,7 +1082,7 @@ describe('content anchors hold the reader through a history repair', () => { expect(target).toBe(5); expect(app.terminal.scrollToLine).toHaveBeenCalledWith(5); expect(anchor.viewportY).toBe(5); - expect(anchor.offset).toBe(1); + expect(anchor.context).toEqual(['', 'row 6', 'row 7']); }); it('keeps the old viewport when two complete contexts match equally well', () => { @@ -1138,8 +1155,8 @@ describe('content anchors hold the reader through a history repair', () => { const anchor = capture(); const next = Array(50_000).fill('other'); if (kind === 'first-row-only') { - next[25_100] = anchor.signature[0]; - next[24_800] = anchor.signature[0]; + next[25_100] = anchor.context[0]; + next[24_800] = anchor.context[0]; } // Even a whole matching viewport outside the budget cannot extend the scan. next.splice(30_000, anchor.context.length, ...anchor.context); From e7f90cb3ec405c48f3ba9c4f31e94fc8f4f4e430 Mon Sep 17 00:00:00 2001 From: Hadrien Kerlero <199662351+HadrienKerlero@users.noreply.github.com> Date: Sun, 22 Nov 2026 04:40:40 +0100 Subject: [PATCH 15/23] =?UTF-8?q?fix(web):=20keep=20Load=20full=20history?= =?UTF-8?q?=20on=20Loading=E2=80=A6=20while=20it=20stands=20in=20for=20Rel?= =?UTF-8?q?oad=20(#814)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - A content-anchored Load full history pull sets _historyReloadActionLoadingFor and clears it on settle, as Reload history does. - The button renders from that loading state, so the re-render the in-flight pull triggers keeps it disabled on Loading…. - The top-anchor case keeps no loading state, so the bar still hides on a scroll back to live output. --- docs/architecture-invariants.md | 2 +- src/web/public/app.js | 17 +++++++++++++++-- test/shell-scroll-history-pull.test.ts | 22 ++++++++++++++++++++-- 3 files changed, 36 insertions(+), 5 deletions(-) diff --git a/docs/architecture-invariants.md b/docs/architecture-invariants.md index 00020436..34c0129c 100644 --- a/docs/architecture-invariants.md +++ b/docs/architecture-invariants.md @@ -253,7 +253,7 @@ Further detail: the `<prefix>: <title>` form (`w3-myapp: fix the login redirect` **Full-scrollback replay** (COD-164/#148, reworked for #205): `GET /api/sessions/:id/terminal?full=1` returns the ENTIRE tmux scrollback (capture-pane `-e -S -<lines>` bounded by the configured history limit, explicit `maxBuffer` from the terminal-history config, early byte-cap before normalization, CRLF-normalized for shell panes). On success the capture is returned ALONE (`source='mux-full-history'` — it supersedes the byte buffer; no duplication). The first load of each non-shell TUI session per page requests `full=1` (`_fullHistoryLoaded` Set in app.js — the old one-shot `_initialFullBufferLoad` flag was consumed by whichever tab auto-selected, leaving every other TUI tab one frame of history). Shell sessions instead load a bounded window of tmux's RENDERED history on every selection, automatic drop recovery, clear and tile load (`SHELL_LOAD_QUERY` in constants.js: `?full=1&tail=1MiB&lines=10000&alt=recording`): a 100k-line shell capture can be tens of MiB, and automatically parsing it makes tab-switch latency scale with the entire session (`lines=` bounds the synchronous capture-pane, about 8 ms per 1000 lines). They never replay the raw byte recording ahead of the visible frame any more: it holds full-screen repaints (an ssh'd tmux, `less`, any TUI) drawn for the pane height of the moment, and replayed into a terminal of another height each repaint's last newline scrolls its top row into scrollback, so one line tmux holds once showed up dozens of times. Because `lines=` is shallower than xterm's scrollback, the route reports a cut: the capture's `display-message` query also reads `#{history_size}` (`PaneCaptureOptions.capturedHistoryLines`, the same field the route reports as `paneHistoryLines`), and a full capture whose CLIENT bound (`lines=` below the configured `tmuxHistoryLimit`) left lines in tmux comes back `truncated`, `truncationReason: 'tail'`. ⚠️ Only a client bound below the ceiling counts: a request without `lines=` is bounded by the ceiling itself, and on tmux before 3.7 a live pane can hold more than a lowered ceiling, which no request can read. ⚠️ **A pane in the alternate screen keeps no tmux history**, and a nested tmux client (remote SSH and Docker cases, or `tmux`/`ssh -t host tmux` run by hand) holds its pane there, so its full capture is one screen. The same query reads `#{alternate_on}` (`capturedAlternateOn`), and a request carrying `alt=recording` (only `SHELL_LOAD_QUERY`) is then answered the old way, the visible frame over the tailed byte recording, which still carries the scrollback; agents, scroll pulls and **Load full history** never send it. `#{alternate_on}` cannot tell a nested tmux from vim, `less` or `htop`, so a local shell with one of those open takes the same fallback until it exits (the pre-fix load, with its repaint duplicates). Shell FULL history is explicit-button-only; reaching the top during an ordinary wheel/touch gesture must not reset xterm and replay the multi-megabyte capture on its main thread. That gesture instead pulls a BOUNDED window of it (`?full=1&tail=<TERMINAL_TAIL_SIZE>`, so a capture beyond 1 MiB comes back `truncationReason: 'tail'` and the banner offers the rest), and skips the replay when the window holds no more rows than the browser already has. ⚠️ **That skip runs BEFORE the downgrade guard, and it never touches the banner state**: the guard reads "smaller than the browser" as "tmux has nothing more to give", true of an unbounded capture and false of a window cut at the tail size, so a bounded window that reached it marked the session `exhausted` and removed **Load full history** while tmux still held the rest; and re-labelling the banner from a skipped payload would call a terminal that holds all of a Load full history pull "the most recent 1 MiB". A skipped window that came back truncated puts the session on the 60 s cooldown (`_fullHistoryRepullUseless`), because it can never reach anything older than the browser shows and `tail` is applied AFTER the server's synchronous `capture-pane` of the whole history, so each ask costs every client an event-loop stall (about 1 s at 100k lines; measured capture details below); an untruncated one keeps the 4 s cooldown, since it is all of tmux's history and the next burst can add to it. Declining the gesture outright was a dead end: after any burst a shell pane held about one screen of browser scrollback, and the button renders only once a replay was truncated, so a young shell tab had no way back to history tmux still held. Other modes re-pull `full=1` only at the top of the local buffer, and pressing **Load full history** forces the request for any recoverably truncated session (`_maybeRefetchFullHistory`, 4s per-session gesture cooldown, in-flight + tab-switch guards, viewport position held across the replay); Shell full pulls are not retained in the tab cache, so the next switch stays bounded. Chunked replay enqueues 32 KiB pieces across safe yields, appends an xterm parse marker, then releases the live-output gate; output arriving after that release stays ordered behind the snapshot, and the marker callback supplies accurate parse timing. ⚠️ **How the load ENDS depends on where the payload came from**, and `_bufferLoadFinishOpts` (app.js) is the one place that decides it for all four fetch-and-write paths. A payload built from the server's accumulated byte history is current up to the response, so the events queued during the load already appear in it and stay DISCARDED; replaying them would duplicate output, most visibly Ink's cursor-up redraws. A pane capture (`mux-visible` or `mux-full-history`) is current only up to CAPTURE time, so `_finishBufferLoad` replays the queue from the response's own arrival timestamp (`since`) and the pre-capture events stay dropped. ⚠️ **A path that then restores a scroll position must re-take the sticky-scroll baseline** (`_syncStickyScrollBaseline`): the replay runs inside `chunkedTerminalWrite` before its promise resolves, with the terminal freshly reset, so `batchTerminalWrite` samples `_wasAtBottomBeforeWrite` as true and the next `flushPendingWrites` would scroll to the bottom over the restore. ⚠️ The cutoff is a client-side timestamp and the server broadcasts on a batch timer (8ms WebSocket, 16-50ms SSE), so a batch pending when the capture ran arrives after the response and replays although the capture holds it — bounded by one batch interval, and closable only server side by flushing that batch before the capture. Tests for the three: `test/terminal-flush-budget.test.ts` pins which sources flush, `test/terminal-buffer-flush.test.ts` pins the `since` cutoff and the baseline re-take, and `test/capture-load-window.browser.test.ts` drives both against a live server. Live output is separately one-chunk-in-flight: xterm's callback releases each 32/64 KiB write before the next is submitted, keeping the remainder in the app queue where the 128 KiB cap can observe it instead of hiding an unbounded backlog in xterm's private WriteBuffer. While WebSocket owns terminal I/O, parallel SSE terminal/output-recovery events are discarded before JSON parsing; fallback recovery is single-flight per active session so backpressure cannot start overlapping reset+replay cycles. The route exposes capture/prepare totals in `Server-Timing`, while `[TERMINAL-PERF]` separates TTFB, body/JSON, reset+parse and total time for both selection and on-demand full pulls; parse completion is not a browser compositor/GPU paint measurement. The re-pull exists because xterm's buffer is only a WINDOW onto tmux's history and two things shrink it: tmux coalesces bursty output into pane REPAINTS that overwrite rows instead of emitting linefeeds (measured: a 60-line burst added 1 row of browser scrollback and destroyed 34), and a tab switch replays only the visible frame. tmux's own history is intact throughout — the browser just has to ask for it again. Gesture-triggered rather than polling because at a 100k history limit the capture can be megabytes. ⚠️ **The capture ENDS with a cursor move back to the pane's own caret position** (`formatCursorRestore`, from the same `display-message` query the visible-frame path uses). The linear replay otherwise leaves the caret wherever the last character landed — the bottom-most row carrying text, which for an agent CLI is the status line — so the caret sat on the composer's border instead of its input line and every cursor-relative update the CLI sent afterwards was measured from the wrong row, until its next full redraw silently repaired it (that self-repair is why the report read as "it fixes itself as soon as Claude writes a line"). ⚠️ **The move is RELATIVE — up `rows - 1 - cursor_y`, then `\r`, then right `cursor_x` — never `CUP`.** `\x1b[<row>;<col>H` numbers rows from the top of the browser's screen, so it lands correctly only while the browser's row count equals `pane_height`, and nothing guarantees that: `resizeWindow` issues its tmux resize fire-and-forget and returns immediately, so a capture can be taken before a requested resize has applied, and `_onSessionNeedsRefresh` sends no resize at all. Counting up from the last replayed row anchors to the content both ends share. Restoring the cursor makes ROW ALIGNMENT load-bearing on this path: **no transform that can DELETE A LINE may run over a full-history capture**, because every deletion shifts the frame out from under the restored position. Four had accumulated — trailing blank rows stripped by `\n+$`, `stripInkRedrawBloat`, the `CLAUDE_BANNER_PATTERN` trim that cuts everything above the banner, and `LEADING_WHITESPACE_PATTERN` — each correct for a byte stream of successive frames and each wrong for a single rendered frame. ⚠️ **Those skips key on `isFullCapture`, meaning a capture actually came back — never on `?full=1` alone.** When `captureActivePaneBuffer` returns null (ENOBUFS, a timeout, a vanished pane, or a session with no mux at all) the reply falls back to `session.terminalBuffer`, which IS a byte stream and must still be stripped; gating on the query flag returned it whole, and a direct-PTY session takes that path on every first selection rather than only during an outage. ⚠️ A capture holding nothing visible (`hasVisibleContent`) returns `''`, because the caller reads an empty capture as "unavailable" and keeps its byte history — retaining trailing blank rows made an all-blank pane non-empty, which would have replaced real history with a blank screen from the server side, where `_replayWouldShrinkBuffer` cannot see it. ⚠️ **"One line per screen row" holds only where no row was hard-wrapped**: `-J` joins a wrapped row into its logical line (measured: a 100-character line in a 40-column pane captures as 10 lines against a 12-row pane), and the counts reconcile only once the browser xterm re-wraps at the same width — the same assumption `_estimateReplayRows` already documents. Tests: `test/tmux-capture-full-history.test.ts` covers the cursor move, the trim pairing and `hasVisibleContent`; `test/routes/session-routes.test.ts` covers a surviving blank first row, an unstripped byte-history fallback, and an empty capture leaving history intact. ⚠️ **The re-pull must never DOWNGRADE the buffer** (#205 round 2): the same reasoning that makes it a win for a shell pane makes it destructive for a repaint-mode CLI pane, where tmux keeps no history of its own (`history_size≈0` measured for a Claude pane) and the capture is roughly ONE frame while xterm may hold hundreds of rows of replayed frames — `_resetTerminalForReplay()` + rewrite then deletes history mid-scroll ("goes back a bit, repeats blocks, gets worse the further up I go"; measured A/B on a live pane: 341 rows → 42 with the guard off). `_replayWouldShrinkBuffer()` (terminal-ui.js) estimates the capture's rendered rows — escape sequences stripped, `capture-pane -J` re-wrapping accounted for — and the pull is skipped when that is more than one screen short of `buffer.active.length`. The one-screen tolerance matters: both sides are estimates (the buffer length counts trailing blank rows), so only a clear downgrade is refused. A refused session joins `_fullHistoryRepullUseless`, raising its cooldown from 4s to 60s so a hollow pane stops re-fetching megabytes on every scroll-up. Tests: `test/tmux-capture-full-history.test.ts`, `test/tmux-scrollback-eol.test.ts`, `test/terminal-scroll-routing.test.ts`, `test/terminal-flush-budget.test.ts`. -**Repair while reading (#814)** is a manual **Reload history** action inside the existing history banner on desktop and touch devices, enabled by default and toggleable per device in Settings → Terminal & Input → Scrolling & rendering (`historyReloadAction`). It is offered only for a marked non-shell active session while scrolled away from live output, not detached, not owned by tiles, with no pull or buffer load in flight and no terminal load state for the session (a tab switch sets it before the buffer load opens). `paneHistoryLines` is deliberately not consulted: it is recorded at the last load, so a session first opened empty keeps 0 after the very burst that opens the gap (#814). A revealed truncation notice keeps its message and its **Load full history** control; Reload is appended only when the notice has no load control, or shown alone with a short missing-output message. When Reload is eligible, that **Load full history** control stands in for it and pulls with the content anchor (eligibility read at click time), so the reader keeps their line; otherwise it keeps the top anchor. A reload-only × dismissal lasts until the mark is cleared by a successful `mux-full-history` replay, independently of the notice’s page-long dismissal. Pressing × while loading hides the bar immediately; the in-flight pull continues. Eligibility is cached per active session, with onScroll sampling coalesced to one animation frame on every device; unchanged eligibility never rebuilds the banner. Automatic history pulls and notice reveal stay top-only (#205). Live-output marking covers only live writes: a byte-history (`?tail=`) replay, for example after a burst in a background tab, never marks the session, so that gap relies on the top-of-buffer pull. The manual action forces a content-anchored pull, bypassing the gesture cooldown but retaining the downgrade guard. Any downgrade-refused pull hides Reload until the next successful `mux-full-history` replay; that refusal, not the cached history size, is what retires the action for a pane with no tmux history (fullscreen Claude). A manual reload answered by anything but `mux-full-history` (an empty response, or the byte-history fallback the route returns when the pane capture is blank or failed) retires it the same way, since only a mux replay clears the mark; a transient error envelope (`success: false`) leaves it available. A content anchor captures up to 64 visible rows, preserving indentation, and scores candidate alignments by matching viewport context. Each distinct nonblank row contributes at most one point, so repeated TUI borders cannot outvote a distinctive tool result. The best match must score at least 60% of the distinct rows and at least two of them, capped at the number of distinct rows, so a viewport with one distinct row (a lone tool result among blanks) matches on that row alone; it must also be unique within the search window. Equal-scoring copies are ambiguous, even when all furniture rows match or the distinctive tool row has disappeared; proximity to the expected position does not establish confidence. An isolated first-row match is not trusted: without confident, unambiguous context the old viewport index is retained, while readers already near live output retain their bottom distance. Search covers 4001 candidates from `expected - 4000 + rows` to `expected + rows` (at most 4064 cached line reads), leaning up because every row a reload fills in below the reader moves the reader's row up, while a capture with fewer rows below moves it down by at most the one screen the downgrade guard tolerates. Gaps up to `4000 - rows` rows therefore land exactly, including at xterm's scrollback cap, where the replay trims the top by the same number of rows. A wider gap puts the match outside the window: the restore keeps the old absolute index, which is right while the top of the buffer stays put but, at the cap, lands the reader the whole gap below their line. Live flushes use an xterm marker to track the reading row across scrollback trimming in O(1), and restore it only in the write callback; at-bottom sticky scroll is unchanged. Ordered, session-scoped travel during replay is applied with per-move clamping; a switched-to tab never donates travel. The notice is decided per recorded move, as a live scroll decides it: an upward move that reaches row 0 reveals the partial-history notice, a downward move that reaches live output retires it, and other moves leave the last decision standing, so reaching the top and then scrolling a few rows down still reveals it; a reload with no travel leaves the notice as it was. The buffer load opens BEFORE the fetch, so download-time output queues behind the replay instead of being overwritten. Non-replay exits flush the whole queue; replays retain the capture-header cutoff above. A blocked dropped-output recovery stores its session and current attempt, defers without consuming retries, and resumes only for the still-active session; a later drop for the same session during that load keeps the higher attempt, so the retry bound still holds. Only an actual `mux-full-history` replay clears the live-output mark and reload dismissal, and a newer live-write generation keeps them marked. The drop-recovery refresh (`_onSessionNeedsRefresh`) follows the same rule: it clears both after a completed replay of a `mux-full-history` capture, only while it still owns the active session and the live-output generation sampled before its fetch is unchanged; its `?tail=` fallback never clears them, and because that fallback means the full capture would shrink the buffer (the refusal signal), it retires the action under the same session and refresh-owner checks. The trade-off remains a full synchronous server capture (about 1 s: 1,068 ms median for `capture-pane -p -e -J -S -100000` over 100k lines of 120 characters, 12.1 MB), not a cheap automatic per-output repair. Tests: `test/shell-scroll-history-pull.test.ts`, `test/history-gap-repair.browser.test.ts`. +**Repair while reading (#814)** is a manual **Reload history** action inside the existing history banner on desktop and touch devices, enabled by default and toggleable per device in Settings → Terminal & Input → Scrolling & rendering (`historyReloadAction`). It is offered only for a marked non-shell active session while scrolled away from live output, not detached, not owned by tiles, with no pull or buffer load in flight and no terminal load state for the session (a tab switch sets it before the buffer load opens). `paneHistoryLines` is deliberately not consulted: it is recorded at the last load, so a session first opened empty keeps 0 after the very burst that opens the gap (#814). A revealed truncation notice keeps its message and its **Load full history** control; Reload is appended only when the notice has no load control, or shown alone with a short missing-output message. When Reload is eligible, that **Load full history** control stands in for it and pulls with the content anchor (eligibility read at click time), so the reader keeps their line, and shares Reload's loading state, so the re-render the in-flight pull triggers keeps it on Loading… instead of bringing it back enabled; otherwise it keeps the top anchor and no loading state, so the bar still hides on a scroll back to live output. A reload-only × dismissal lasts until the mark is cleared by a successful `mux-full-history` replay, independently of the notice’s page-long dismissal. Pressing × while loading hides the bar immediately; the in-flight pull continues. Eligibility is cached per active session, with onScroll sampling coalesced to one animation frame on every device; unchanged eligibility never rebuilds the banner. Automatic history pulls and notice reveal stay top-only (#205). Live-output marking covers only live writes: a byte-history (`?tail=`) replay, for example after a burst in a background tab, never marks the session, so that gap relies on the top-of-buffer pull. The manual action forces a content-anchored pull, bypassing the gesture cooldown but retaining the downgrade guard. Any downgrade-refused pull hides Reload until the next successful `mux-full-history` replay; that refusal, not the cached history size, is what retires the action for a pane with no tmux history (fullscreen Claude). A manual reload answered by anything but `mux-full-history` (an empty response, or the byte-history fallback the route returns when the pane capture is blank or failed) retires it the same way, since only a mux replay clears the mark; a transient error envelope (`success: false`) leaves it available. A content anchor captures up to 64 visible rows, preserving indentation, and scores candidate alignments by matching viewport context. Each distinct nonblank row contributes at most one point, so repeated TUI borders cannot outvote a distinctive tool result. The best match must score at least 60% of the distinct rows and at least two of them, capped at the number of distinct rows, so a viewport with one distinct row (a lone tool result among blanks) matches on that row alone; it must also be unique within the search window. Equal-scoring copies are ambiguous, even when all furniture rows match or the distinctive tool row has disappeared; proximity to the expected position does not establish confidence. An isolated first-row match is not trusted: without confident, unambiguous context the old viewport index is retained, while readers already near live output retain their bottom distance. Search covers 4001 candidates from `expected - 4000 + rows` to `expected + rows` (at most 4064 cached line reads), leaning up because every row a reload fills in below the reader moves the reader's row up, while a capture with fewer rows below moves it down by at most the one screen the downgrade guard tolerates. Gaps up to `4000 - rows` rows therefore land exactly, including at xterm's scrollback cap, where the replay trims the top by the same number of rows. A wider gap puts the match outside the window: the restore keeps the old absolute index, which is right while the top of the buffer stays put but, at the cap, lands the reader the whole gap below their line. Live flushes use an xterm marker to track the reading row across scrollback trimming in O(1), and restore it only in the write callback; at-bottom sticky scroll is unchanged. Ordered, session-scoped travel during replay is applied with per-move clamping; a switched-to tab never donates travel. The notice is decided per recorded move, as a live scroll decides it: an upward move that reaches row 0 reveals the partial-history notice, a downward move that reaches live output retires it, and other moves leave the last decision standing, so reaching the top and then scrolling a few rows down still reveals it; a reload with no travel leaves the notice as it was. The buffer load opens BEFORE the fetch, so download-time output queues behind the replay instead of being overwritten. Non-replay exits flush the whole queue; replays retain the capture-header cutoff above. A blocked dropped-output recovery stores its session and current attempt, defers without consuming retries, and resumes only for the still-active session; a later drop for the same session during that load keeps the higher attempt, so the retry bound still holds. Only an actual `mux-full-history` replay clears the live-output mark and reload dismissal, and a newer live-write generation keeps them marked. The drop-recovery refresh (`_onSessionNeedsRefresh`) follows the same rule: it clears both after a completed replay of a `mux-full-history` capture, only while it still owns the active session and the live-output generation sampled before its fetch is unchanged; its `?tail=` fallback never clears them, and because that fallback means the full capture would shrink the buffer (the refusal signal), it retires the action under the same session and refresh-owner checks. The trade-off remains a full synchronous server capture (about 1 s: 1,068 ms median for `capture-pane -p -e -J -S -100000` over 100k lines of 120 characters, 12.1 MB), not a cheap automatic per-output repair. Tests: `test/shell-scroll-history-pull.test.ts`, `test/history-gap-repair.browser.test.ts`. **The partial-history notice is lazy and pane-gated** (`computeHistoryTruncationNotice()` in constants.js, `_renderHistoryTruncationBanner()` / `_setHistoryNoticeRevealed()` in app.js). `truncated` on a terminal response measures the server's BYTE stream, which is not what `full=1` can return: for a pane with no tmux scrollback (fullscreen claude starts in the alternate screen and never writes to the main grid, so `#{history_size}` is 0) the bytes a tail cut drops are old repaint frames. Measured on prod 2026-10-10, every claude pane: the tab-switch tail cut a 1.2 to 6.2 MB stream to 1 MiB, the local scrollback that tail replays into is repeats of the same frames (one pane: 450 non-blank rows, 44 unique, one row 33 times), and `full=1` returned 1 to 5 KB, so **Load full history** could only end in the downgrade refusal while the banner promised "4.8 MB more". The capture therefore reads `#{history_size}` in the SAME `display-message` as the cursor (no extra tmux call), the route returns it as `paneHistoryLines` (absent when the body is not a capture, and for a remote SSH session, whose local pane hosts the remote tmux client and always reports 0 while `full=1` reads the remote history), and a reported 0 hides the notice in every state; a positive count replaces the byte gap in the message. ⚠️ Key the notice decision on `history_size`, never on `alternate_on`: a shell running `less` is in the alternate screen with its whole history still retained (measured, 99,972 rows) and `full=1` returns all of it. The one place `alternate_on` decides is a shell's AUTOMATIC load (`alt=recording`, see Full-scrollback replay): there the question is whether the capture holds the scrollback a nested tmux client keeps in its byte recording, not whether a pull can return more. The notice is also LAZY: it appears only after a wheel/touch gesture reaches the top of the browser buffer and the pull that gesture started has settled (`_maybeLoadMoreHistoryOnScroll`), goes away when a downward gesture is back at live output or the tab switches (`selectSession` nulls `_historyNoticeRevealedFor` before repainting), and its × is sticky per session until reload (`_historyNoticeDismissed`). Tests: `test/history-truncation-notice.test.ts`, `test/history-notice-reveal.test.ts`. diff --git a/src/web/public/app.js b/src/web/public/app.js index 3a4b7dc6..e30b5555 100644 --- a/src/web/public/app.js +++ b/src/web/public/app.js @@ -10054,7 +10054,11 @@ class CodemanApp { const btn = document.createElement('button'); btn.type = 'button'; btn.className = 'history-trunc-load'; - btn.textContent = 'Load full history'; + // A content-anchored pull from here stands in for Reload history, so it + // shares Reload's loading state: the pull flips Reload eligibility, and the + // re-render that follows must not bring the button back enabled mid-pull. + btn.disabled = loading; + btn.textContent = loading ? 'Loading…' : 'Load full history'; btn.onclick = () => { btn.disabled = true; btn.textContent = 'Loading…'; @@ -10064,7 +10068,16 @@ class CodemanApp { // way. Checked at click time, not render time: the bar only re-renders on // eligibility transitions, and the reader may have scrolled since. const anchor = this._historyReloadActionEligible() ? 'content' : 'top'; - this._maybeRefetchFullHistory({ force: true, anchor }).finally(() => { + // The top anchor keeps no loading state: it would hold the bar up after + // a scroll back to live output, where it hides today. + if (anchor === 'content') { + this._historyReloadActionLoadingFor = sessionId; + this._syncHistoryReloadAction(); + } + return this._maybeRefetchFullHistory({ force: true, anchor }).finally(() => { + if (anchor === 'content' && this._historyReloadActionLoadingFor === sessionId) { + this._historyReloadActionLoadingFor = null; + } this._renderHistoryTruncationBanner(); }); }; diff --git a/test/shell-scroll-history-pull.test.ts b/test/shell-scroll-history-pull.test.ts index 2442edd7..fc0025d2 100644 --- a/test/shell-scroll-history-pull.test.ts +++ b/test/shell-scroll-history-pull.test.ts @@ -1378,13 +1378,31 @@ describe('manual history banner action', () => { truncationReason: kind === 'capped' ? 'capped' : 'tail', }); expect(bar.children.filter((child) => child.className === 'history-trunc-load')).toHaveLength(1); - expect(button()!.textContent).toBe(kind === 'recoverable' ? 'Load full history' : 'Reload history'); + const label = kind === 'recoverable' ? 'Load full history' : 'Reload history'; + expect(button()!.textContent).toBe(label); + // Hold the pull open the way the real one does: in flight, Reload history + // is no longer eligible, and the sync that follows rebuilds the bar. + const { promise, resolve: release } = Promise.withResolvers<void>(); + app._maybeRefetchFullHistory.mockImplementationOnce(() => { + app._fullHistoryRepullInFlight = true; + return promise.finally(() => { + app._fullHistoryRepullInFlight = false; + }); + }); + const clicked = button()!.onclick!(); + app._syncHistoryReloadAction(); + expect({ text: button()!.textContent, disabled: button()!.disabled }).toEqual({ + text: 'Loading…', + disabled: true, + }); + release(); + await clicked; // Either way the one control stands in for Reload history, so it keeps the // reader's line rather than landing on the old row 0. - await button()!.onclick!(); expect(app._maybeRefetchFullHistory).toHaveBeenCalledExactlyOnceWith( expect.objectContaining({ force: true, anchor: 'content' }) ); + expect({ text: button()!.textContent, disabled: button()!.disabled }).toEqual({ text: label, disabled: false }); }); it('keeps the top anchor for Load full history when Reload history is not eligible', async () => { From 6f5b3aca2386695840b44bdf57aaa6d43b6c036b Mon Sep 17 00:00:00 2001 From: Hadrien Kerlero <199662351+HadrienKerlero@users.noreply.github.com> Date: Sun, 22 Nov 2026 18:24:47 +0100 Subject: [PATCH 16/23] fix(web): keep Reload history and history pulls aside while a drop-recovery refresh fetches (#814) - _historyReloadActionEligible() and _maybeRefetchFullHistory stand aside while _terminalRefreshOwner holds the active session, so Reload, Load full history and the top-of-buffer pull no longer start a second capture whose download-time queue the refresh's own load would replace. - _onSessionNeedsRefresh re-syncs the action when it takes the owner and again in its finally once it releases it. - Tests: a refresh-in-flight visibility row, and a tap during a held refresh that fetches nothing and gets the action back afterwards. --- docs/architecture-invariants.md | 2 +- src/web/public/app.js | 14 ++++++- test/shell-scroll-history-pull.test.ts | 51 +++++++++++++++++++++++--- 3 files changed, 60 insertions(+), 7 deletions(-) diff --git a/docs/architecture-invariants.md b/docs/architecture-invariants.md index 34c0129c..665f726a 100644 --- a/docs/architecture-invariants.md +++ b/docs/architecture-invariants.md @@ -253,7 +253,7 @@ Further detail: the `<prefix>: <title>` form (`w3-myapp: fix the login redirect` **Full-scrollback replay** (COD-164/#148, reworked for #205): `GET /api/sessions/:id/terminal?full=1` returns the ENTIRE tmux scrollback (capture-pane `-e -S -<lines>` bounded by the configured history limit, explicit `maxBuffer` from the terminal-history config, early byte-cap before normalization, CRLF-normalized for shell panes). On success the capture is returned ALONE (`source='mux-full-history'` — it supersedes the byte buffer; no duplication). The first load of each non-shell TUI session per page requests `full=1` (`_fullHistoryLoaded` Set in app.js — the old one-shot `_initialFullBufferLoad` flag was consumed by whichever tab auto-selected, leaving every other TUI tab one frame of history). Shell sessions instead load a bounded window of tmux's RENDERED history on every selection, automatic drop recovery, clear and tile load (`SHELL_LOAD_QUERY` in constants.js: `?full=1&tail=1MiB&lines=10000&alt=recording`): a 100k-line shell capture can be tens of MiB, and automatically parsing it makes tab-switch latency scale with the entire session (`lines=` bounds the synchronous capture-pane, about 8 ms per 1000 lines). They never replay the raw byte recording ahead of the visible frame any more: it holds full-screen repaints (an ssh'd tmux, `less`, any TUI) drawn for the pane height of the moment, and replayed into a terminal of another height each repaint's last newline scrolls its top row into scrollback, so one line tmux holds once showed up dozens of times. Because `lines=` is shallower than xterm's scrollback, the route reports a cut: the capture's `display-message` query also reads `#{history_size}` (`PaneCaptureOptions.capturedHistoryLines`, the same field the route reports as `paneHistoryLines`), and a full capture whose CLIENT bound (`lines=` below the configured `tmuxHistoryLimit`) left lines in tmux comes back `truncated`, `truncationReason: 'tail'`. ⚠️ Only a client bound below the ceiling counts: a request without `lines=` is bounded by the ceiling itself, and on tmux before 3.7 a live pane can hold more than a lowered ceiling, which no request can read. ⚠️ **A pane in the alternate screen keeps no tmux history**, and a nested tmux client (remote SSH and Docker cases, or `tmux`/`ssh -t host tmux` run by hand) holds its pane there, so its full capture is one screen. The same query reads `#{alternate_on}` (`capturedAlternateOn`), and a request carrying `alt=recording` (only `SHELL_LOAD_QUERY`) is then answered the old way, the visible frame over the tailed byte recording, which still carries the scrollback; agents, scroll pulls and **Load full history** never send it. `#{alternate_on}` cannot tell a nested tmux from vim, `less` or `htop`, so a local shell with one of those open takes the same fallback until it exits (the pre-fix load, with its repaint duplicates). Shell FULL history is explicit-button-only; reaching the top during an ordinary wheel/touch gesture must not reset xterm and replay the multi-megabyte capture on its main thread. That gesture instead pulls a BOUNDED window of it (`?full=1&tail=<TERMINAL_TAIL_SIZE>`, so a capture beyond 1 MiB comes back `truncationReason: 'tail'` and the banner offers the rest), and skips the replay when the window holds no more rows than the browser already has. ⚠️ **That skip runs BEFORE the downgrade guard, and it never touches the banner state**: the guard reads "smaller than the browser" as "tmux has nothing more to give", true of an unbounded capture and false of a window cut at the tail size, so a bounded window that reached it marked the session `exhausted` and removed **Load full history** while tmux still held the rest; and re-labelling the banner from a skipped payload would call a terminal that holds all of a Load full history pull "the most recent 1 MiB". A skipped window that came back truncated puts the session on the 60 s cooldown (`_fullHistoryRepullUseless`), because it can never reach anything older than the browser shows and `tail` is applied AFTER the server's synchronous `capture-pane` of the whole history, so each ask costs every client an event-loop stall (about 1 s at 100k lines; measured capture details below); an untruncated one keeps the 4 s cooldown, since it is all of tmux's history and the next burst can add to it. Declining the gesture outright was a dead end: after any burst a shell pane held about one screen of browser scrollback, and the button renders only once a replay was truncated, so a young shell tab had no way back to history tmux still held. Other modes re-pull `full=1` only at the top of the local buffer, and pressing **Load full history** forces the request for any recoverably truncated session (`_maybeRefetchFullHistory`, 4s per-session gesture cooldown, in-flight + tab-switch guards, viewport position held across the replay); Shell full pulls are not retained in the tab cache, so the next switch stays bounded. Chunked replay enqueues 32 KiB pieces across safe yields, appends an xterm parse marker, then releases the live-output gate; output arriving after that release stays ordered behind the snapshot, and the marker callback supplies accurate parse timing. ⚠️ **How the load ENDS depends on where the payload came from**, and `_bufferLoadFinishOpts` (app.js) is the one place that decides it for all four fetch-and-write paths. A payload built from the server's accumulated byte history is current up to the response, so the events queued during the load already appear in it and stay DISCARDED; replaying them would duplicate output, most visibly Ink's cursor-up redraws. A pane capture (`mux-visible` or `mux-full-history`) is current only up to CAPTURE time, so `_finishBufferLoad` replays the queue from the response's own arrival timestamp (`since`) and the pre-capture events stay dropped. ⚠️ **A path that then restores a scroll position must re-take the sticky-scroll baseline** (`_syncStickyScrollBaseline`): the replay runs inside `chunkedTerminalWrite` before its promise resolves, with the terminal freshly reset, so `batchTerminalWrite` samples `_wasAtBottomBeforeWrite` as true and the next `flushPendingWrites` would scroll to the bottom over the restore. ⚠️ The cutoff is a client-side timestamp and the server broadcasts on a batch timer (8ms WebSocket, 16-50ms SSE), so a batch pending when the capture ran arrives after the response and replays although the capture holds it — bounded by one batch interval, and closable only server side by flushing that batch before the capture. Tests for the three: `test/terminal-flush-budget.test.ts` pins which sources flush, `test/terminal-buffer-flush.test.ts` pins the `since` cutoff and the baseline re-take, and `test/capture-load-window.browser.test.ts` drives both against a live server. Live output is separately one-chunk-in-flight: xterm's callback releases each 32/64 KiB write before the next is submitted, keeping the remainder in the app queue where the 128 KiB cap can observe it instead of hiding an unbounded backlog in xterm's private WriteBuffer. While WebSocket owns terminal I/O, parallel SSE terminal/output-recovery events are discarded before JSON parsing; fallback recovery is single-flight per active session so backpressure cannot start overlapping reset+replay cycles. The route exposes capture/prepare totals in `Server-Timing`, while `[TERMINAL-PERF]` separates TTFB, body/JSON, reset+parse and total time for both selection and on-demand full pulls; parse completion is not a browser compositor/GPU paint measurement. The re-pull exists because xterm's buffer is only a WINDOW onto tmux's history and two things shrink it: tmux coalesces bursty output into pane REPAINTS that overwrite rows instead of emitting linefeeds (measured: a 60-line burst added 1 row of browser scrollback and destroyed 34), and a tab switch replays only the visible frame. tmux's own history is intact throughout — the browser just has to ask for it again. Gesture-triggered rather than polling because at a 100k history limit the capture can be megabytes. ⚠️ **The capture ENDS with a cursor move back to the pane's own caret position** (`formatCursorRestore`, from the same `display-message` query the visible-frame path uses). The linear replay otherwise leaves the caret wherever the last character landed — the bottom-most row carrying text, which for an agent CLI is the status line — so the caret sat on the composer's border instead of its input line and every cursor-relative update the CLI sent afterwards was measured from the wrong row, until its next full redraw silently repaired it (that self-repair is why the report read as "it fixes itself as soon as Claude writes a line"). ⚠️ **The move is RELATIVE — up `rows - 1 - cursor_y`, then `\r`, then right `cursor_x` — never `CUP`.** `\x1b[<row>;<col>H` numbers rows from the top of the browser's screen, so it lands correctly only while the browser's row count equals `pane_height`, and nothing guarantees that: `resizeWindow` issues its tmux resize fire-and-forget and returns immediately, so a capture can be taken before a requested resize has applied, and `_onSessionNeedsRefresh` sends no resize at all. Counting up from the last replayed row anchors to the content both ends share. Restoring the cursor makes ROW ALIGNMENT load-bearing on this path: **no transform that can DELETE A LINE may run over a full-history capture**, because every deletion shifts the frame out from under the restored position. Four had accumulated — trailing blank rows stripped by `\n+$`, `stripInkRedrawBloat`, the `CLAUDE_BANNER_PATTERN` trim that cuts everything above the banner, and `LEADING_WHITESPACE_PATTERN` — each correct for a byte stream of successive frames and each wrong for a single rendered frame. ⚠️ **Those skips key on `isFullCapture`, meaning a capture actually came back — never on `?full=1` alone.** When `captureActivePaneBuffer` returns null (ENOBUFS, a timeout, a vanished pane, or a session with no mux at all) the reply falls back to `session.terminalBuffer`, which IS a byte stream and must still be stripped; gating on the query flag returned it whole, and a direct-PTY session takes that path on every first selection rather than only during an outage. ⚠️ A capture holding nothing visible (`hasVisibleContent`) returns `''`, because the caller reads an empty capture as "unavailable" and keeps its byte history — retaining trailing blank rows made an all-blank pane non-empty, which would have replaced real history with a blank screen from the server side, where `_replayWouldShrinkBuffer` cannot see it. ⚠️ **"One line per screen row" holds only where no row was hard-wrapped**: `-J` joins a wrapped row into its logical line (measured: a 100-character line in a 40-column pane captures as 10 lines against a 12-row pane), and the counts reconcile only once the browser xterm re-wraps at the same width — the same assumption `_estimateReplayRows` already documents. Tests: `test/tmux-capture-full-history.test.ts` covers the cursor move, the trim pairing and `hasVisibleContent`; `test/routes/session-routes.test.ts` covers a surviving blank first row, an unstripped byte-history fallback, and an empty capture leaving history intact. ⚠️ **The re-pull must never DOWNGRADE the buffer** (#205 round 2): the same reasoning that makes it a win for a shell pane makes it destructive for a repaint-mode CLI pane, where tmux keeps no history of its own (`history_size≈0` measured for a Claude pane) and the capture is roughly ONE frame while xterm may hold hundreds of rows of replayed frames — `_resetTerminalForReplay()` + rewrite then deletes history mid-scroll ("goes back a bit, repeats blocks, gets worse the further up I go"; measured A/B on a live pane: 341 rows → 42 with the guard off). `_replayWouldShrinkBuffer()` (terminal-ui.js) estimates the capture's rendered rows — escape sequences stripped, `capture-pane -J` re-wrapping accounted for — and the pull is skipped when that is more than one screen short of `buffer.active.length`. The one-screen tolerance matters: both sides are estimates (the buffer length counts trailing blank rows), so only a clear downgrade is refused. A refused session joins `_fullHistoryRepullUseless`, raising its cooldown from 4s to 60s so a hollow pane stops re-fetching megabytes on every scroll-up. Tests: `test/tmux-capture-full-history.test.ts`, `test/tmux-scrollback-eol.test.ts`, `test/terminal-scroll-routing.test.ts`, `test/terminal-flush-budget.test.ts`. -**Repair while reading (#814)** is a manual **Reload history** action inside the existing history banner on desktop and touch devices, enabled by default and toggleable per device in Settings → Terminal & Input → Scrolling & rendering (`historyReloadAction`). It is offered only for a marked non-shell active session while scrolled away from live output, not detached, not owned by tiles, with no pull or buffer load in flight and no terminal load state for the session (a tab switch sets it before the buffer load opens). `paneHistoryLines` is deliberately not consulted: it is recorded at the last load, so a session first opened empty keeps 0 after the very burst that opens the gap (#814). A revealed truncation notice keeps its message and its **Load full history** control; Reload is appended only when the notice has no load control, or shown alone with a short missing-output message. When Reload is eligible, that **Load full history** control stands in for it and pulls with the content anchor (eligibility read at click time), so the reader keeps their line, and shares Reload's loading state, so the re-render the in-flight pull triggers keeps it on Loading… instead of bringing it back enabled; otherwise it keeps the top anchor and no loading state, so the bar still hides on a scroll back to live output. A reload-only × dismissal lasts until the mark is cleared by a successful `mux-full-history` replay, independently of the notice’s page-long dismissal. Pressing × while loading hides the bar immediately; the in-flight pull continues. Eligibility is cached per active session, with onScroll sampling coalesced to one animation frame on every device; unchanged eligibility never rebuilds the banner. Automatic history pulls and notice reveal stay top-only (#205). Live-output marking covers only live writes: a byte-history (`?tail=`) replay, for example after a burst in a background tab, never marks the session, so that gap relies on the top-of-buffer pull. The manual action forces a content-anchored pull, bypassing the gesture cooldown but retaining the downgrade guard. Any downgrade-refused pull hides Reload until the next successful `mux-full-history` replay; that refusal, not the cached history size, is what retires the action for a pane with no tmux history (fullscreen Claude). A manual reload answered by anything but `mux-full-history` (an empty response, or the byte-history fallback the route returns when the pane capture is blank or failed) retires it the same way, since only a mux replay clears the mark; a transient error envelope (`success: false`) leaves it available. A content anchor captures up to 64 visible rows, preserving indentation, and scores candidate alignments by matching viewport context. Each distinct nonblank row contributes at most one point, so repeated TUI borders cannot outvote a distinctive tool result. The best match must score at least 60% of the distinct rows and at least two of them, capped at the number of distinct rows, so a viewport with one distinct row (a lone tool result among blanks) matches on that row alone; it must also be unique within the search window. Equal-scoring copies are ambiguous, even when all furniture rows match or the distinctive tool row has disappeared; proximity to the expected position does not establish confidence. An isolated first-row match is not trusted: without confident, unambiguous context the old viewport index is retained, while readers already near live output retain their bottom distance. Search covers 4001 candidates from `expected - 4000 + rows` to `expected + rows` (at most 4064 cached line reads), leaning up because every row a reload fills in below the reader moves the reader's row up, while a capture with fewer rows below moves it down by at most the one screen the downgrade guard tolerates. Gaps up to `4000 - rows` rows therefore land exactly, including at xterm's scrollback cap, where the replay trims the top by the same number of rows. A wider gap puts the match outside the window: the restore keeps the old absolute index, which is right while the top of the buffer stays put but, at the cap, lands the reader the whole gap below their line. Live flushes use an xterm marker to track the reading row across scrollback trimming in O(1), and restore it only in the write callback; at-bottom sticky scroll is unchanged. Ordered, session-scoped travel during replay is applied with per-move clamping; a switched-to tab never donates travel. The notice is decided per recorded move, as a live scroll decides it: an upward move that reaches row 0 reveals the partial-history notice, a downward move that reaches live output retires it, and other moves leave the last decision standing, so reaching the top and then scrolling a few rows down still reveals it; a reload with no travel leaves the notice as it was. The buffer load opens BEFORE the fetch, so download-time output queues behind the replay instead of being overwritten. Non-replay exits flush the whole queue; replays retain the capture-header cutoff above. A blocked dropped-output recovery stores its session and current attempt, defers without consuming retries, and resumes only for the still-active session; a later drop for the same session during that load keeps the higher attempt, so the retry bound still holds. Only an actual `mux-full-history` replay clears the live-output mark and reload dismissal, and a newer live-write generation keeps them marked. The drop-recovery refresh (`_onSessionNeedsRefresh`) follows the same rule: it clears both after a completed replay of a `mux-full-history` capture, only while it still owns the active session and the live-output generation sampled before its fetch is unchanged; its `?tail=` fallback never clears them, and because that fallback means the full capture would shrink the buffer (the refusal signal), it retires the action under the same session and refresh-owner checks. The trade-off remains a full synchronous server capture (about 1 s: 1,068 ms median for `capture-pane -p -e -J -S -100000` over 100k lines of 120 characters, 12.1 MB), not a cheap automatic per-output repair. Tests: `test/shell-scroll-history-pull.test.ts`, `test/history-gap-repair.browser.test.ts`. +**Repair while reading (#814)** is a manual **Reload history** action inside the existing history banner on desktop and touch devices, enabled by default and toggleable per device in Settings → Terminal & Input → Scrolling & rendering (`historyReloadAction`). It is offered only for a marked non-shell active session while scrolled away from live output, not detached, not owned by tiles, with no pull or buffer load in flight no terminal load state for the session (a tab switch sets it before the buffer load opens), and no drop-recovery refresh owning the session (`_terminalRefreshOwner`, set for the whole fetch, before that refresh opens its buffer load). `_maybeRefetchFullHistory` returns early on that same owner, so Reload, Load full history and the top-of-buffer pull all stand aside instead of running a second capture whose download-time queue the refresh's own load would replace; the refresh re-syncs the action when it starts and when its `finally` releases the owner. `paneHistoryLines` is deliberately not consulted: it is recorded at the last load, so a session first opened empty keeps 0 after the very burst that opens the gap (#814). A revealed truncation notice keeps its message and its **Load full history** control; Reload is appended only when the notice has no load control, or shown alone with a short missing-output message. When Reload is eligible, that **Load full history** control stands in for it and pulls with the content anchor (eligibility read at click time), so the reader keeps their line, and shares Reload's loading state, so the re-render the in-flight pull triggers keeps it on Loading… instead of bringing it back enabled; otherwise it keeps the top anchor and no loading state, so the bar still hides on a scroll back to live output. A reload-only × dismissal lasts until the mark is cleared by a successful `mux-full-history` replay, independently of the notice’s page-long dismissal. Pressing × while loading hides the bar immediately; the in-flight pull continues. Eligibility is cached per active session, with onScroll sampling coalesced to one animation frame on every device; unchanged eligibility never rebuilds the banner. Automatic history pulls and notice reveal stay top-only (#205). Live-output marking covers only live writes: a byte-history (`?tail=`) replay, for example after a burst in a background tab, never marks the session, so that gap relies on the top-of-buffer pull. The manual action forces a content-anchored pull, bypassing the gesture cooldown but retaining the downgrade guard. Any downgrade-refused pull hides Reload until the next successful `mux-full-history` replay; that refusal, not the cached history size, is what retires the action for a pane with no tmux history (fullscreen Claude). A manual reload answered by anything but `mux-full-history` (an empty response, or the byte-history fallback the route returns when the pane capture is blank or failed) retires it the same way, since only a mux replay clears the mark; a transient error envelope (`success: false`) leaves it available. A content anchor captures up to 64 visible rows, preserving indentation, and scores candidate alignments by matching viewport context. Each distinct nonblank row contributes at most one point, so repeated TUI borders cannot outvote a distinctive tool result. The best match must score at least 60% of the distinct rows and at least two of them, capped at the number of distinct rows, so a viewport with one distinct row (a lone tool result among blanks) matches on that row alone; it must also be unique within the search window. Equal-scoring copies are ambiguous, even when all furniture rows match or the distinctive tool row has disappeared; proximity to the expected position does not establish confidence. An isolated first-row match is not trusted: without confident, unambiguous context the old viewport index is retained, while readers already near live output retain their bottom distance. Search covers 4001 candidates from `expected - 4000 + rows` to `expected + rows` (at most 4064 cached line reads), leaning up because every row a reload fills in below the reader moves the reader's row up, while a capture with fewer rows below moves it down by at most the one screen the downgrade guard tolerates. Gaps up to `4000 - rows` rows therefore land exactly, including at xterm's scrollback cap, where the replay trims the top by the same number of rows. A wider gap puts the match outside the window: the restore keeps the old absolute index, which is right while the top of the buffer stays put but, at the cap, lands the reader the whole gap below their line. Live flushes use an xterm marker to track the reading row across scrollback trimming in O(1), and restore it only in the write callback; at-bottom sticky scroll is unchanged. Ordered, session-scoped travel during replay is applied with per-move clamping; a switched-to tab never donates travel. The notice is decided per recorded move, as a live scroll decides it: an upward move that reaches row 0 reveals the partial-history notice, a downward move that reaches live output retires it, and other moves leave the last decision standing, so reaching the top and then scrolling a few rows down still reveals it; a reload with no travel leaves the notice as it was. The buffer load opens BEFORE the fetch, so download-time output queues behind the replay instead of being overwritten. Non-replay exits flush the whole queue; replays retain the capture-header cutoff above. A blocked dropped-output recovery stores its session and current attempt, defers without consuming retries, and resumes only for the still-active session; a later drop for the same session during that load keeps the higher attempt, so the retry bound still holds. Only an actual `mux-full-history` replay clears the live-output mark and reload dismissal, and a newer live-write generation keeps them marked. The drop-recovery refresh (`_onSessionNeedsRefresh`) follows the same rule: it clears both after a completed replay of a `mux-full-history` capture, only while it still owns the active session and the live-output generation sampled before its fetch is unchanged; its `?tail=` fallback never clears them, and because that fallback means the full capture would shrink the buffer (the refusal signal), it retires the action under the same session and refresh-owner checks. The trade-off remains a full synchronous server capture (about 1 s: 1,068 ms median for `capture-pane -p -e -J -S -100000` over 100k lines of 120 characters, 12.1 MB), not a cheap automatic per-output repair. Tests: `test/shell-scroll-history-pull.test.ts`, `test/history-gap-repair.browser.test.ts`. **The partial-history notice is lazy and pane-gated** (`computeHistoryTruncationNotice()` in constants.js, `_renderHistoryTruncationBanner()` / `_setHistoryNoticeRevealed()` in app.js). `truncated` on a terminal response measures the server's BYTE stream, which is not what `full=1` can return: for a pane with no tmux scrollback (fullscreen claude starts in the alternate screen and never writes to the main grid, so `#{history_size}` is 0) the bytes a tail cut drops are old repaint frames. Measured on prod 2026-10-10, every claude pane: the tab-switch tail cut a 1.2 to 6.2 MB stream to 1 MiB, the local scrollback that tail replays into is repeats of the same frames (one pane: 450 non-blank rows, 44 unique, one row 33 times), and `full=1` returned 1 to 5 KB, so **Load full history** could only end in the downgrade refusal while the banner promised "4.8 MB more". The capture therefore reads `#{history_size}` in the SAME `display-message` as the cursor (no extra tmux call), the route returns it as `paneHistoryLines` (absent when the body is not a capture, and for a remote SSH session, whose local pane hosts the remote tmux client and always reports 0 while `full=1` reads the remote history), and a reported 0 hides the notice in every state; a positive count replaces the byte gap in the message. ⚠️ Key the notice decision on `history_size`, never on `alternate_on`: a shell running `less` is in the alternate screen with its whole history still retained (measured, 99,972 rows) and `full=1` returns all of it. The one place `alternate_on` decides is a shell's AUTOMATIC load (`alt=recording`, see Full-scrollback replay): there the question is whether the capture holds the scrollback a nested tmux client keeps in its byte recording, not whether a pull can return more. The notice is also LAZY: it appears only after a wheel/touch gesture reaches the top of the browser buffer and the pull that gesture started has settled (`_maybeLoadMoreHistoryOnScroll`), goes away when a downward gesture is back at live output or the tab switches (`selectSession` nulls `_historyNoticeRevealedFor` before repainting), and its × is sticky per session until reload (`_historyNoticeDismissed`). Tests: `test/history-truncation-notice.test.ts`, `test/history-notice-reveal.test.ts`. diff --git a/src/web/public/app.js b/src/web/public/app.js index e30b5555..c48bae36 100644 --- a/src/web/public/app.js +++ b/src/web/public/app.js @@ -3497,6 +3497,9 @@ class CodemanApp { if (this._terminalRefreshOwner?.sessionId === sessionId) return false; const refreshOwner = { sessionId }; this._terminalRefreshOwner = refreshOwner; + // Reload history stands aside for the length of this refresh (see + // _historyReloadActionEligible); take it off an already-painted bar now. + this._syncHistoryReloadAction?.(); try { // A shell can retain a multi-megabyte/100k-line tmux history. Automatic // recovery stays bounded just like normal shell selection (tmux's rendered @@ -3604,7 +3607,11 @@ class CodemanApp { console.error('needsRefresh reload failed:', err); return err?.name === 'AbortError' ? 'deadline' : false; } finally { - if (this._terminalRefreshOwner === refreshOwner) this._terminalRefreshOwner = null; + if (this._terminalRefreshOwner === refreshOwner) { + this._terminalRefreshOwner = null; + // Reload history stands aside while this refresh fetches; offer it again. + this._syncHistoryReloadAction?.(); + } } } @@ -9681,6 +9688,10 @@ class CodemanApp { async _maybeRefetchFullHistory({ force = false, anchor = 'top' } = {}) { const sessionId = this.activeSessionId; if (!sessionId || this._fullHistoryRepullInFlight || this._isLoadingBuffer) return; + // A drop-recovery refresh owns this session until its replay ends: a second + // capture would run back to back with it, and its load would replace this + // pull's queue, losing the output that arrived during the download. + if (this._terminalRefreshOwner?.sessionId === sessionId) return; if (this.detachedSessions?.has(sessionId)) return; // The parked main terminal has no history to pull while tiles own the screen. if (this._tilesOwnTerminal?.()) return; @@ -9996,6 +10007,7 @@ class CodemanApp { session && session.mode !== 'shell' && this._liveOutputSinceFullPull?.has(sessionId) && !this._isLoadingBuffer && !this.terminalLoadStates?.has(sessionId) && // Tab switches set this before the buffer load opens. + this._terminalRefreshOwner?.sessionId !== sessionId && // A drop-recovery refresh is fetching. !this._fullHistoryRepullInFlight && !this.detachedSessions?.has(sessionId) && !this._historyReloadDismissed?.has(sessionId) && !this._tilesOwnTerminal?.() && !this.isTerminalAtBottom()); diff --git a/test/shell-scroll-history-pull.test.ts b/test/shell-scroll-history-pull.test.ts index fc0025d2..c5dee885 100644 --- a/test/shell-scroll-history-pull.test.ts +++ b/test/shell-scroll-history-pull.test.ts @@ -1209,6 +1209,7 @@ describe('manual history banner action', () => { loadingBuffer: false, loadState: false, paneHistoryLines: undefined as number | undefined, + refreshing: false, ...options, }; const element = (): BannerElement => ({ @@ -1248,6 +1249,7 @@ describe('manual history banner action', () => { _fullHistoryRepullInFlight: Boolean(state.inFlight), _isLoadingBuffer: Boolean(state.loadingBuffer), terminalLoadStates: new Map(state.loadState ? [['s1', { generation: 1, phase: 'resizing' }]] : []), + _terminalRefreshOwner: state.refreshing ? { sessionId: 's1' } : null, _paneHistoryLines: new Map<string, number>( state.paneHistoryLines === undefined ? [] : [['s1', Number(state.paneHistoryLines)]] ), @@ -1284,6 +1286,8 @@ describe('manual history banner action', () => { { opts: { tiles: true }, visible: false }, { opts: { active: false }, visible: false }, { opts: { detached: true }, visible: false }, + // A drop-recovery refresh owns the session while it fetches. + { opts: { refreshing: true }, visible: false }, ])('visibility is $visible for $opts', ({ opts, visible }) => { const { app, bar, button } = fixture(opts); app._syncHistoryReloadAction(); @@ -1291,6 +1295,48 @@ describe('manual history banner action', () => { if (visible) expect(button()?.textContent).toBe('Reload history'); }); + it('stands aside while a drop-recovery refresh fetches, then offers Reload again', async () => { + const { app, bar, button } = fixture(); + app._syncHistoryReloadAction(); + const staleButton = button()!; + expect(staleButton.textContent).toBe('Reload history'); + // Hold the recovery's own `?full=1` open: only its owner marks it. + const fetchCapture = app._fetchTerminalCapture.getMockImplementation()!; + const { promise, resolve: release } = Promise.withResolvers<void>(); + app._fetchTerminalCapture.mockImplementationOnce(async (url) => { + await promise; + // A history answer keeps the mark, so Reload is due again afterwards. + const capture = await fetchCapture(url); + capture.json.data.source = 'history'; + return capture; + }); + Object.assign(app, { + _markTerminalBufferReconciled: vi.fn(), + sendResize: vi.fn(), + _localEchoOverlay: { rerender: vi.fn() }, + }); + Object.assign(app.terminal, { scrollToBottom: vi.fn() }); + app._maybeRefetchFullHistory.mockImplementation((opts) => refetch.call(app, opts)); + const recovery = loadAppMethod('_onSessionNeedsRefresh', { + console: { error: vi.fn() }, + computeRewriteScrollLine: () => null, + }).call(app); + expect(app._terminalRefreshOwner).toEqual({ sessionId: 's1' }); + expect(bar.hidden).toBe(true); + // A tap on the button painted before the refresh started fetches nothing. + await staleButton.onclick!(); + await refetch.call(app, { force: true, anchor: 'top' }); + expect(app._fetchTerminalCapture).toHaveBeenCalledOnce(); + expect(app._isLoadingBuffer).toBe(false); + release(); + await recovery; + expect(app._terminalRefreshOwner).toBeNull(); + // The recovery replayed a history answer, so the session is still marked + // and its `finally` offers the action again. + expect(bar.hidden).toBe(false); + expect(button()!.textContent).toBe('Reload history'); + }); + it('forces a content-anchored pull on tap and resets loading on settle', async () => { const { app, button } = fixture(); const { promise, resolve: release } = Promise.withResolvers<void>(); @@ -1582,8 +1628,6 @@ describe('drop-recovery refresh clears the live-output mark only for a mux captu expect(app.chunkedTerminalWrite).toHaveBeenCalledOnce(); expect(app._liveOutputSinceFullPull.has('s1')).toBe(false); expect(app._historyReloadDismissed.has('s1')).toBe(false); - // The clear syncs once, and the real truncation-banner update syncs again. - expect(app._syncHistoryReloadAction).toHaveBeenCalledTimes(2); }); it('keeps the mark and dismissal when the mux replay is incomplete', async () => { @@ -1607,7 +1651,6 @@ describe('drop-recovery refresh clears the live-output mark only for a mux captu expect(app.chunkedTerminalWrite).toHaveBeenCalledOnce(); expect(app._liveOutputSinceFullPull.has('s1')).toBe(true); expect(app._historyReloadDismissed.has('s1')).toBe(true); - expect(app._syncHistoryReloadAction).toHaveBeenCalledOnce(); }); it('keeps the mark and dismissal when live output arrives during the fetch', async () => { @@ -1622,7 +1665,6 @@ describe('drop-recovery refresh clears the live-output mark only for a mux captu expect(app.chunkedTerminalWrite).toHaveBeenCalledOnce(); expect(app._liveOutputSinceFullPull.has('s1')).toBe(true); expect(app._historyReloadDismissed.has('s1')).toBe(true); - expect(app._syncHistoryReloadAction).toHaveBeenCalledOnce(); }); it('retires Reload history when a full mux capture falls back to a history tail', async () => { @@ -1660,6 +1702,5 @@ describe('drop-recovery refresh clears the live-output mark only for a mux captu expect(errors).not.toHaveBeenCalled(); expect(app._liveOutputSinceFullPull.has('s1')).toBe(true); expect(app._historyReloadDismissed.has('s1')).toBe(true); - expect(app._syncHistoryReloadAction).not.toHaveBeenCalled(); }); }); From 7794f74282c8d40caaab2bbbd52899c0395e9071 Mon Sep 17 00:00:00 2001 From: Hadrien Kerlero <199662351+HadrienKerlero@users.noreply.github.com> Date: Sun, 22 Nov 2026 23:49:19 +0100 Subject: [PATCH 17/23] fix(web): announce only the truncation notice from the history bar (#814) - _renderHistoryTruncationBanner sets aria-live to polite for the truncation notice and off for a reload-only bar, which re-renders on nearly every scroll-up in a busy tab; its button stays reachable with Tab. - docs: comma in the Reload eligibility list, and the live-region rule in the invariants paragraph. --- docs/architecture-invariants.md | 2 +- src/web/public/app.js | 5 +++++ test/shell-scroll-history-pull.test.ts | 12 ++++++++++++ 3 files changed, 18 insertions(+), 1 deletion(-) diff --git a/docs/architecture-invariants.md b/docs/architecture-invariants.md index 665f726a..b0a5dcfc 100644 --- a/docs/architecture-invariants.md +++ b/docs/architecture-invariants.md @@ -253,7 +253,7 @@ Further detail: the `<prefix>: <title>` form (`w3-myapp: fix the login redirect` **Full-scrollback replay** (COD-164/#148, reworked for #205): `GET /api/sessions/:id/terminal?full=1` returns the ENTIRE tmux scrollback (capture-pane `-e -S -<lines>` bounded by the configured history limit, explicit `maxBuffer` from the terminal-history config, early byte-cap before normalization, CRLF-normalized for shell panes). On success the capture is returned ALONE (`source='mux-full-history'` — it supersedes the byte buffer; no duplication). The first load of each non-shell TUI session per page requests `full=1` (`_fullHistoryLoaded` Set in app.js — the old one-shot `_initialFullBufferLoad` flag was consumed by whichever tab auto-selected, leaving every other TUI tab one frame of history). Shell sessions instead load a bounded window of tmux's RENDERED history on every selection, automatic drop recovery, clear and tile load (`SHELL_LOAD_QUERY` in constants.js: `?full=1&tail=1MiB&lines=10000&alt=recording`): a 100k-line shell capture can be tens of MiB, and automatically parsing it makes tab-switch latency scale with the entire session (`lines=` bounds the synchronous capture-pane, about 8 ms per 1000 lines). They never replay the raw byte recording ahead of the visible frame any more: it holds full-screen repaints (an ssh'd tmux, `less`, any TUI) drawn for the pane height of the moment, and replayed into a terminal of another height each repaint's last newline scrolls its top row into scrollback, so one line tmux holds once showed up dozens of times. Because `lines=` is shallower than xterm's scrollback, the route reports a cut: the capture's `display-message` query also reads `#{history_size}` (`PaneCaptureOptions.capturedHistoryLines`, the same field the route reports as `paneHistoryLines`), and a full capture whose CLIENT bound (`lines=` below the configured `tmuxHistoryLimit`) left lines in tmux comes back `truncated`, `truncationReason: 'tail'`. ⚠️ Only a client bound below the ceiling counts: a request without `lines=` is bounded by the ceiling itself, and on tmux before 3.7 a live pane can hold more than a lowered ceiling, which no request can read. ⚠️ **A pane in the alternate screen keeps no tmux history**, and a nested tmux client (remote SSH and Docker cases, or `tmux`/`ssh -t host tmux` run by hand) holds its pane there, so its full capture is one screen. The same query reads `#{alternate_on}` (`capturedAlternateOn`), and a request carrying `alt=recording` (only `SHELL_LOAD_QUERY`) is then answered the old way, the visible frame over the tailed byte recording, which still carries the scrollback; agents, scroll pulls and **Load full history** never send it. `#{alternate_on}` cannot tell a nested tmux from vim, `less` or `htop`, so a local shell with one of those open takes the same fallback until it exits (the pre-fix load, with its repaint duplicates). Shell FULL history is explicit-button-only; reaching the top during an ordinary wheel/touch gesture must not reset xterm and replay the multi-megabyte capture on its main thread. That gesture instead pulls a BOUNDED window of it (`?full=1&tail=<TERMINAL_TAIL_SIZE>`, so a capture beyond 1 MiB comes back `truncationReason: 'tail'` and the banner offers the rest), and skips the replay when the window holds no more rows than the browser already has. ⚠️ **That skip runs BEFORE the downgrade guard, and it never touches the banner state**: the guard reads "smaller than the browser" as "tmux has nothing more to give", true of an unbounded capture and false of a window cut at the tail size, so a bounded window that reached it marked the session `exhausted` and removed **Load full history** while tmux still held the rest; and re-labelling the banner from a skipped payload would call a terminal that holds all of a Load full history pull "the most recent 1 MiB". A skipped window that came back truncated puts the session on the 60 s cooldown (`_fullHistoryRepullUseless`), because it can never reach anything older than the browser shows and `tail` is applied AFTER the server's synchronous `capture-pane` of the whole history, so each ask costs every client an event-loop stall (about 1 s at 100k lines; measured capture details below); an untruncated one keeps the 4 s cooldown, since it is all of tmux's history and the next burst can add to it. Declining the gesture outright was a dead end: after any burst a shell pane held about one screen of browser scrollback, and the button renders only once a replay was truncated, so a young shell tab had no way back to history tmux still held. Other modes re-pull `full=1` only at the top of the local buffer, and pressing **Load full history** forces the request for any recoverably truncated session (`_maybeRefetchFullHistory`, 4s per-session gesture cooldown, in-flight + tab-switch guards, viewport position held across the replay); Shell full pulls are not retained in the tab cache, so the next switch stays bounded. Chunked replay enqueues 32 KiB pieces across safe yields, appends an xterm parse marker, then releases the live-output gate; output arriving after that release stays ordered behind the snapshot, and the marker callback supplies accurate parse timing. ⚠️ **How the load ENDS depends on where the payload came from**, and `_bufferLoadFinishOpts` (app.js) is the one place that decides it for all four fetch-and-write paths. A payload built from the server's accumulated byte history is current up to the response, so the events queued during the load already appear in it and stay DISCARDED; replaying them would duplicate output, most visibly Ink's cursor-up redraws. A pane capture (`mux-visible` or `mux-full-history`) is current only up to CAPTURE time, so `_finishBufferLoad` replays the queue from the response's own arrival timestamp (`since`) and the pre-capture events stay dropped. ⚠️ **A path that then restores a scroll position must re-take the sticky-scroll baseline** (`_syncStickyScrollBaseline`): the replay runs inside `chunkedTerminalWrite` before its promise resolves, with the terminal freshly reset, so `batchTerminalWrite` samples `_wasAtBottomBeforeWrite` as true and the next `flushPendingWrites` would scroll to the bottom over the restore. ⚠️ The cutoff is a client-side timestamp and the server broadcasts on a batch timer (8ms WebSocket, 16-50ms SSE), so a batch pending when the capture ran arrives after the response and replays although the capture holds it — bounded by one batch interval, and closable only server side by flushing that batch before the capture. Tests for the three: `test/terminal-flush-budget.test.ts` pins which sources flush, `test/terminal-buffer-flush.test.ts` pins the `since` cutoff and the baseline re-take, and `test/capture-load-window.browser.test.ts` drives both against a live server. Live output is separately one-chunk-in-flight: xterm's callback releases each 32/64 KiB write before the next is submitted, keeping the remainder in the app queue where the 128 KiB cap can observe it instead of hiding an unbounded backlog in xterm's private WriteBuffer. While WebSocket owns terminal I/O, parallel SSE terminal/output-recovery events are discarded before JSON parsing; fallback recovery is single-flight per active session so backpressure cannot start overlapping reset+replay cycles. The route exposes capture/prepare totals in `Server-Timing`, while `[TERMINAL-PERF]` separates TTFB, body/JSON, reset+parse and total time for both selection and on-demand full pulls; parse completion is not a browser compositor/GPU paint measurement. The re-pull exists because xterm's buffer is only a WINDOW onto tmux's history and two things shrink it: tmux coalesces bursty output into pane REPAINTS that overwrite rows instead of emitting linefeeds (measured: a 60-line burst added 1 row of browser scrollback and destroyed 34), and a tab switch replays only the visible frame. tmux's own history is intact throughout — the browser just has to ask for it again. Gesture-triggered rather than polling because at a 100k history limit the capture can be megabytes. ⚠️ **The capture ENDS with a cursor move back to the pane's own caret position** (`formatCursorRestore`, from the same `display-message` query the visible-frame path uses). The linear replay otherwise leaves the caret wherever the last character landed — the bottom-most row carrying text, which for an agent CLI is the status line — so the caret sat on the composer's border instead of its input line and every cursor-relative update the CLI sent afterwards was measured from the wrong row, until its next full redraw silently repaired it (that self-repair is why the report read as "it fixes itself as soon as Claude writes a line"). ⚠️ **The move is RELATIVE — up `rows - 1 - cursor_y`, then `\r`, then right `cursor_x` — never `CUP`.** `\x1b[<row>;<col>H` numbers rows from the top of the browser's screen, so it lands correctly only while the browser's row count equals `pane_height`, and nothing guarantees that: `resizeWindow` issues its tmux resize fire-and-forget and returns immediately, so a capture can be taken before a requested resize has applied, and `_onSessionNeedsRefresh` sends no resize at all. Counting up from the last replayed row anchors to the content both ends share. Restoring the cursor makes ROW ALIGNMENT load-bearing on this path: **no transform that can DELETE A LINE may run over a full-history capture**, because every deletion shifts the frame out from under the restored position. Four had accumulated — trailing blank rows stripped by `\n+$`, `stripInkRedrawBloat`, the `CLAUDE_BANNER_PATTERN` trim that cuts everything above the banner, and `LEADING_WHITESPACE_PATTERN` — each correct for a byte stream of successive frames and each wrong for a single rendered frame. ⚠️ **Those skips key on `isFullCapture`, meaning a capture actually came back — never on `?full=1` alone.** When `captureActivePaneBuffer` returns null (ENOBUFS, a timeout, a vanished pane, or a session with no mux at all) the reply falls back to `session.terminalBuffer`, which IS a byte stream and must still be stripped; gating on the query flag returned it whole, and a direct-PTY session takes that path on every first selection rather than only during an outage. ⚠️ A capture holding nothing visible (`hasVisibleContent`) returns `''`, because the caller reads an empty capture as "unavailable" and keeps its byte history — retaining trailing blank rows made an all-blank pane non-empty, which would have replaced real history with a blank screen from the server side, where `_replayWouldShrinkBuffer` cannot see it. ⚠️ **"One line per screen row" holds only where no row was hard-wrapped**: `-J` joins a wrapped row into its logical line (measured: a 100-character line in a 40-column pane captures as 10 lines against a 12-row pane), and the counts reconcile only once the browser xterm re-wraps at the same width — the same assumption `_estimateReplayRows` already documents. Tests: `test/tmux-capture-full-history.test.ts` covers the cursor move, the trim pairing and `hasVisibleContent`; `test/routes/session-routes.test.ts` covers a surviving blank first row, an unstripped byte-history fallback, and an empty capture leaving history intact. ⚠️ **The re-pull must never DOWNGRADE the buffer** (#205 round 2): the same reasoning that makes it a win for a shell pane makes it destructive for a repaint-mode CLI pane, where tmux keeps no history of its own (`history_size≈0` measured for a Claude pane) and the capture is roughly ONE frame while xterm may hold hundreds of rows of replayed frames — `_resetTerminalForReplay()` + rewrite then deletes history mid-scroll ("goes back a bit, repeats blocks, gets worse the further up I go"; measured A/B on a live pane: 341 rows → 42 with the guard off). `_replayWouldShrinkBuffer()` (terminal-ui.js) estimates the capture's rendered rows — escape sequences stripped, `capture-pane -J` re-wrapping accounted for — and the pull is skipped when that is more than one screen short of `buffer.active.length`. The one-screen tolerance matters: both sides are estimates (the buffer length counts trailing blank rows), so only a clear downgrade is refused. A refused session joins `_fullHistoryRepullUseless`, raising its cooldown from 4s to 60s so a hollow pane stops re-fetching megabytes on every scroll-up. Tests: `test/tmux-capture-full-history.test.ts`, `test/tmux-scrollback-eol.test.ts`, `test/terminal-scroll-routing.test.ts`, `test/terminal-flush-budget.test.ts`. -**Repair while reading (#814)** is a manual **Reload history** action inside the existing history banner on desktop and touch devices, enabled by default and toggleable per device in Settings → Terminal & Input → Scrolling & rendering (`historyReloadAction`). It is offered only for a marked non-shell active session while scrolled away from live output, not detached, not owned by tiles, with no pull or buffer load in flight no terminal load state for the session (a tab switch sets it before the buffer load opens), and no drop-recovery refresh owning the session (`_terminalRefreshOwner`, set for the whole fetch, before that refresh opens its buffer load). `_maybeRefetchFullHistory` returns early on that same owner, so Reload, Load full history and the top-of-buffer pull all stand aside instead of running a second capture whose download-time queue the refresh's own load would replace; the refresh re-syncs the action when it starts and when its `finally` releases the owner. `paneHistoryLines` is deliberately not consulted: it is recorded at the last load, so a session first opened empty keeps 0 after the very burst that opens the gap (#814). A revealed truncation notice keeps its message and its **Load full history** control; Reload is appended only when the notice has no load control, or shown alone with a short missing-output message. When Reload is eligible, that **Load full history** control stands in for it and pulls with the content anchor (eligibility read at click time), so the reader keeps their line, and shares Reload's loading state, so the re-render the in-flight pull triggers keeps it on Loading… instead of bringing it back enabled; otherwise it keeps the top anchor and no loading state, so the bar still hides on a scroll back to live output. A reload-only × dismissal lasts until the mark is cleared by a successful `mux-full-history` replay, independently of the notice’s page-long dismissal. Pressing × while loading hides the bar immediately; the in-flight pull continues. Eligibility is cached per active session, with onScroll sampling coalesced to one animation frame on every device; unchanged eligibility never rebuilds the banner. Automatic history pulls and notice reveal stay top-only (#205). Live-output marking covers only live writes: a byte-history (`?tail=`) replay, for example after a burst in a background tab, never marks the session, so that gap relies on the top-of-buffer pull. The manual action forces a content-anchored pull, bypassing the gesture cooldown but retaining the downgrade guard. Any downgrade-refused pull hides Reload until the next successful `mux-full-history` replay; that refusal, not the cached history size, is what retires the action for a pane with no tmux history (fullscreen Claude). A manual reload answered by anything but `mux-full-history` (an empty response, or the byte-history fallback the route returns when the pane capture is blank or failed) retires it the same way, since only a mux replay clears the mark; a transient error envelope (`success: false`) leaves it available. A content anchor captures up to 64 visible rows, preserving indentation, and scores candidate alignments by matching viewport context. Each distinct nonblank row contributes at most one point, so repeated TUI borders cannot outvote a distinctive tool result. The best match must score at least 60% of the distinct rows and at least two of them, capped at the number of distinct rows, so a viewport with one distinct row (a lone tool result among blanks) matches on that row alone; it must also be unique within the search window. Equal-scoring copies are ambiguous, even when all furniture rows match or the distinctive tool row has disappeared; proximity to the expected position does not establish confidence. An isolated first-row match is not trusted: without confident, unambiguous context the old viewport index is retained, while readers already near live output retain their bottom distance. Search covers 4001 candidates from `expected - 4000 + rows` to `expected + rows` (at most 4064 cached line reads), leaning up because every row a reload fills in below the reader moves the reader's row up, while a capture with fewer rows below moves it down by at most the one screen the downgrade guard tolerates. Gaps up to `4000 - rows` rows therefore land exactly, including at xterm's scrollback cap, where the replay trims the top by the same number of rows. A wider gap puts the match outside the window: the restore keeps the old absolute index, which is right while the top of the buffer stays put but, at the cap, lands the reader the whole gap below their line. Live flushes use an xterm marker to track the reading row across scrollback trimming in O(1), and restore it only in the write callback; at-bottom sticky scroll is unchanged. Ordered, session-scoped travel during replay is applied with per-move clamping; a switched-to tab never donates travel. The notice is decided per recorded move, as a live scroll decides it: an upward move that reaches row 0 reveals the partial-history notice, a downward move that reaches live output retires it, and other moves leave the last decision standing, so reaching the top and then scrolling a few rows down still reveals it; a reload with no travel leaves the notice as it was. The buffer load opens BEFORE the fetch, so download-time output queues behind the replay instead of being overwritten. Non-replay exits flush the whole queue; replays retain the capture-header cutoff above. A blocked dropped-output recovery stores its session and current attempt, defers without consuming retries, and resumes only for the still-active session; a later drop for the same session during that load keeps the higher attempt, so the retry bound still holds. Only an actual `mux-full-history` replay clears the live-output mark and reload dismissal, and a newer live-write generation keeps them marked. The drop-recovery refresh (`_onSessionNeedsRefresh`) follows the same rule: it clears both after a completed replay of a `mux-full-history` capture, only while it still owns the active session and the live-output generation sampled before its fetch is unchanged; its `?tail=` fallback never clears them, and because that fallback means the full capture would shrink the buffer (the refusal signal), it retires the action under the same session and refresh-owner checks. The trade-off remains a full synchronous server capture (about 1 s: 1,068 ms median for `capture-pane -p -e -J -S -100000` over 100k lines of 120 characters, 12.1 MB), not a cheap automatic per-output repair. Tests: `test/shell-scroll-history-pull.test.ts`, `test/history-gap-repair.browser.test.ts`. +**Repair while reading (#814)** is a manual **Reload history** action inside the existing history banner on desktop and touch devices, enabled by default and toggleable per device in Settings → Terminal & Input → Scrolling & rendering (`historyReloadAction`). It is offered only for a marked non-shell active session while scrolled away from live output, not detached, not owned by tiles, with no pull or buffer load in flight, no terminal load state for the session (a tab switch sets it before the buffer load opens), and no drop-recovery refresh owning the session (`_terminalRefreshOwner`, set for the whole fetch, before that refresh opens its buffer load). `_maybeRefetchFullHistory` returns early on that same owner, so Reload, Load full history and the top-of-buffer pull all stand aside instead of running a second capture whose download-time queue the refresh's own load would replace; the refresh re-syncs the action when it starts and when its `finally` releases the owner. `paneHistoryLines` is deliberately not consulted: it is recorded at the last load, so a session first opened empty keeps 0 after the very burst that opens the gap (#814). The bar is a polite live region (`role="status"`), but only the truncation notice is announced: a reload-only bar sets `aria-live="off"` before it re-renders, since it comes back on nearly every scroll-up in a busy tab, and its button stays reachable with Tab. A revealed truncation notice keeps its message and its **Load full history** control; Reload is appended only when the notice has no load control, or shown alone with a short missing-output message. When Reload is eligible, that **Load full history** control stands in for it and pulls with the content anchor (eligibility read at click time), so the reader keeps their line, and shares Reload's loading state, so the re-render the in-flight pull triggers keeps it on Loading… instead of bringing it back enabled; otherwise it keeps the top anchor and no loading state, so the bar still hides on a scroll back to live output. A reload-only × dismissal lasts until the mark is cleared by a successful `mux-full-history` replay, independently of the notice’s page-long dismissal. Pressing × while loading hides the bar immediately; the in-flight pull continues. Eligibility is cached per active session, with onScroll sampling coalesced to one animation frame on every device; unchanged eligibility never rebuilds the banner. Automatic history pulls and notice reveal stay top-only (#205). Live-output marking covers only live writes: a byte-history (`?tail=`) replay, for example after a burst in a background tab, never marks the session, so that gap relies on the top-of-buffer pull. The manual action forces a content-anchored pull, bypassing the gesture cooldown but retaining the downgrade guard. Any downgrade-refused pull hides Reload until the next successful `mux-full-history` replay; that refusal, not the cached history size, is what retires the action for a pane with no tmux history (fullscreen Claude). A manual reload answered by anything but `mux-full-history` (an empty response, or the byte-history fallback the route returns when the pane capture is blank or failed) retires it the same way, since only a mux replay clears the mark; a transient error envelope (`success: false`) leaves it available. A content anchor captures up to 64 visible rows, preserving indentation, and scores candidate alignments by matching viewport context. Each distinct nonblank row contributes at most one point, so repeated TUI borders cannot outvote a distinctive tool result. The best match must score at least 60% of the distinct rows and at least two of them, capped at the number of distinct rows, so a viewport with one distinct row (a lone tool result among blanks) matches on that row alone; it must also be unique within the search window. Equal-scoring copies are ambiguous, even when all furniture rows match or the distinctive tool row has disappeared; proximity to the expected position does not establish confidence. An isolated first-row match is not trusted: without confident, unambiguous context the old viewport index is retained, while readers already near live output retain their bottom distance. Search covers 4001 candidates from `expected - 4000 + rows` to `expected + rows` (at most 4064 cached line reads), leaning up because every row a reload fills in below the reader moves the reader's row up, while a capture with fewer rows below moves it down by at most the one screen the downgrade guard tolerates. Gaps up to `4000 - rows` rows therefore land exactly, including at xterm's scrollback cap, where the replay trims the top by the same number of rows. A wider gap puts the match outside the window: the restore keeps the old absolute index, which is right while the top of the buffer stays put but, at the cap, lands the reader the whole gap below their line. Live flushes use an xterm marker to track the reading row across scrollback trimming in O(1), and restore it only in the write callback; at-bottom sticky scroll is unchanged. Ordered, session-scoped travel during replay is applied with per-move clamping; a switched-to tab never donates travel. The notice is decided per recorded move, as a live scroll decides it: an upward move that reaches row 0 reveals the partial-history notice, a downward move that reaches live output retires it, and other moves leave the last decision standing, so reaching the top and then scrolling a few rows down still reveals it; a reload with no travel leaves the notice as it was. The buffer load opens BEFORE the fetch, so download-time output queues behind the replay instead of being overwritten. Non-replay exits flush the whole queue; replays retain the capture-header cutoff above. A blocked dropped-output recovery stores its session and current attempt, defers without consuming retries, and resumes only for the still-active session; a later drop for the same session during that load keeps the higher attempt, so the retry bound still holds. Only an actual `mux-full-history` replay clears the live-output mark and reload dismissal, and a newer live-write generation keeps them marked. The drop-recovery refresh (`_onSessionNeedsRefresh`) follows the same rule: it clears both after a completed replay of a `mux-full-history` capture, only while it still owns the active session and the live-output generation sampled before its fetch is unchanged; its `?tail=` fallback never clears them, and because that fallback means the full capture would shrink the buffer (the refusal signal), it retires the action under the same session and refresh-owner checks. The trade-off remains a full synchronous server capture (about 1 s: 1,068 ms median for `capture-pane -p -e -J -S -100000` over 100k lines of 120 characters, 12.1 MB), not a cheap automatic per-output repair. Tests: `test/shell-scroll-history-pull.test.ts`, `test/history-gap-repair.browser.test.ts`. **The partial-history notice is lazy and pane-gated** (`computeHistoryTruncationNotice()` in constants.js, `_renderHistoryTruncationBanner()` / `_setHistoryNoticeRevealed()` in app.js). `truncated` on a terminal response measures the server's BYTE stream, which is not what `full=1` can return: for a pane with no tmux scrollback (fullscreen claude starts in the alternate screen and never writes to the main grid, so `#{history_size}` is 0) the bytes a tail cut drops are old repaint frames. Measured on prod 2026-10-10, every claude pane: the tab-switch tail cut a 1.2 to 6.2 MB stream to 1 MiB, the local scrollback that tail replays into is repeats of the same frames (one pane: 450 non-blank rows, 44 unique, one row 33 times), and `full=1` returned 1 to 5 KB, so **Load full history** could only end in the downgrade refusal while the banner promised "4.8 MB more". The capture therefore reads `#{history_size}` in the SAME `display-message` as the cursor (no extra tmux call), the route returns it as `paneHistoryLines` (absent when the body is not a capture, and for a remote SSH session, whose local pane hosts the remote tmux client and always reports 0 while `full=1` reads the remote history), and a reported 0 hides the notice in every state; a positive count replaces the byte gap in the message. ⚠️ Key the notice decision on `history_size`, never on `alternate_on`: a shell running `less` is in the alternate screen with its whole history still retained (measured, 99,972 rows) and `full=1` returns all of it. The one place `alternate_on` decides is a shell's AUTOMATIC load (`alt=recording`, see Full-scrollback replay): there the question is whether the capture holds the scrollback a nested tmux client keeps in its byte recording, not whether a pull can return more. The notice is also LAZY: it appears only after a wheel/touch gesture reaches the top of the browser buffer and the pull that gesture started has settled (`_maybeLoadMoreHistoryOnScroll`), goes away when a downward gesture is back at live output or the tab switches (`selectSession` nulls `_historyNoticeRevealedFor` before repainting), and its × is sticky per session until reload (`_historyNoticeDismissed`). Tests: `test/history-truncation-notice.test.ts`, `test/history-notice-reveal.test.ts`. diff --git a/src/web/public/app.js b/src/web/public/app.js index c48bae36..c5859d4e 100644 --- a/src/web/public/app.js +++ b/src/web/public/app.js @@ -10056,6 +10056,11 @@ class CodemanApp { return; } + // `#historyTruncationBar` is a polite live region. Only the truncation + // notice is news worth announcing; a reload-only bar re-renders on every + // eligible scroll-up in a busy tab, so it stays silent and is reached by Tab. + // Set before the rewrite below, so the new content is judged by it. + bar.setAttribute('aria-live', showNotice ? 'polite' : 'off'); bar.textContent = ''; const label = document.createElement('span'); label.className = 'history-trunc-text'; diff --git a/test/shell-scroll-history-pull.test.ts b/test/shell-scroll-history-pull.test.ts index c5dee885..775813a3 100644 --- a/test/shell-scroll-history-pull.test.ts +++ b/test/shell-scroll-history-pull.test.ts @@ -1295,6 +1295,18 @@ describe('manual history banner action', () => { if (visible) expect(button()?.textContent).toBe('Reload history'); }); + it('announces the truncation notice but keeps a reload-only bar silent', () => { + const { app, bar, button } = fixture(); + app._syncHistoryReloadAction(); + expect(button()!.textContent).toBe('Reload history'); + expect(bar.setAttribute).toHaveBeenLastCalledWith('aria-live', 'off'); + // Revealing the truncation notice in the same bar makes it news again. + app._historyNoticeRevealedFor = 's1'; + app._setHistoryTruncation('s1', { ...TAIL_CUT, truncationReason: 'tail' }); + expect(button()!.textContent).toBe('Load full history'); + expect(bar.setAttribute).toHaveBeenLastCalledWith('aria-live', 'polite'); + }); + it('stands aside while a drop-recovery refresh fetches, then offers Reload again', async () => { const { app, bar, button } = fixture(); app._syncHistoryReloadAction(); From 48488863306473c4d4752a180b37e124ab0cf65a Mon Sep 17 00:00:00 2001 From: Hadrien Kerlero <199662351+HadrienKerlero@users.noreply.github.com> Date: Mon, 23 Nov 2026 00:31:49 +0100 Subject: [PATCH 18/23] fix(web): sample the live-output generation before selectSession fetches (#814) - selectSession now samples _liveOutputGen before its fresh fetch, as the refresh and manual-pull paths do, so output that arrives during the download keeps the session marked for Reload history. - Test: live output during the fresh fetch keeps the mark after a mux-full-history replay. --- src/web/public/app.js | 3 ++- test/shell-scroll-history-pull.test.ts | 22 ++++++++++++++++++++-- 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/src/web/public/app.js b/src/web/public/app.js index c5859d4e..db589667 100644 --- a/src/web/public/app.js +++ b/src/web/public/app.js @@ -10557,6 +10557,8 @@ class CodemanApp { !session?.remote && !session?.docker && !session?.adopt && this._paneHistoryLines?.get(sessionId) === 0; const useFullHistory = !shellSession && (paneKeepsNoHistory || !this._fullHistoryLoaded.has(sessionId)); if (useFullHistory) this._fullHistoryLoaded.add(sessionId); + // Sample before fetching, as other replays do, so output during download keeps the session marked. + const liveOutputGen = this._liveOutputGen?.get(sessionId) || 0; const fetchStartedAt = performance.now(); const tailUrl = `/api/sessions/${sessionId}/terminal?tail=${TERMINAL_TAIL_SIZE}`; let capture; @@ -10620,7 +10622,6 @@ class CodemanApp { _crashDiag.log(`REWRITE: ${(data.terminalBuffer.length/1024).toFixed(0)}KB`); this._setTerminalLoadState(sessionId, selectGen, 'replaying'); const replayStartedAt = performance.now(); - const liveOutputGen = this._liveOutputGen?.get(sessionId) || 0; this._resetTerminalForReplay(); // Truncation is reported OUT OF BAND (#258). This used to write a grey // "... earlier output truncated ..." line into the diff --git a/test/shell-scroll-history-pull.test.ts b/test/shell-scroll-history-pull.test.ts index 775813a3..2a3b2c75 100644 --- a/test/shell-scroll-history-pull.test.ts +++ b/test/shell-scroll-history-pull.test.ts @@ -1548,7 +1548,7 @@ describe('manual history banner action', () => { }); describe('selectSession only clears live-output marks for actual full mux captures', () => { - it.each(['mux-full-history', 'history'])('checks the response source: %s', async (source) => { + function makeSelectApp(source = 'mux-full-history') { const errors = vi.fn(); const select = loadAppMethod('selectSession', { console: { log: vi.fn(), error: errors }, @@ -1576,7 +1576,7 @@ describe('selectSession only clears live-output marks for actual full mux captur 'scrollToLastNonEmptyLine', ].map((name) => [name, vi.fn()]) ); - Object.assign(app, methods, { + const selection = Object.assign(app, methods, { activeSessionId: 's2', _fullHistoryLoaded: new Set(), _liveOutputSinceFullPull: new Set(['s1']), @@ -1586,11 +1586,29 @@ describe('selectSession only clears live-output marks for actual full mux captur sendResize: async () => false, }); Object.assign(app.terminal, { scrollToBottom: vi.fn() }); + return { app: selection, select, errors }; + } + + it.each(['mux-full-history', 'history'])('checks the response source: %s', async (source) => { + const { app, select, errors } = makeSelectApp(source); await select.call(app, 's1'); expect(errors).not.toHaveBeenCalled(); expect(app.chunkedTerminalWrite).toHaveBeenCalledOnce(); expect(Reflect.get(app, '_liveOutputSinceFullPull').has('s1')).toBe(source !== 'mux-full-history'); }); + + it('keeps the mark when live output arrives during the fresh fetch', async () => { + const { app, select, errors } = makeSelectApp(); + const fetchCapture = app._fetchTerminalCapture.getMockImplementation()!; + app._fetchTerminalCapture.mockImplementationOnce(async (url) => { + app._liveOutputGen.set('s1', (app._liveOutputGen.get('s1') || 0) + 1); + return fetchCapture(url); + }); + await select.call(app, 's1'); + expect(errors).not.toHaveBeenCalled(); + expect(app.chunkedTerminalWrite).toHaveBeenCalledOnce(); + expect(app._liveOutputSinceFullPull.has('s1')).toBe(true); + }); }); describe('drop-recovery refresh clears the live-output mark only for a mux capture', () => { From 82071d47bd11d1b1f16e187abe362ed4459e21b4 Mon Sep 17 00:00:00 2001 From: Hadrien Kerlero <199662351+HadrienKerlero@users.noreply.github.com> Date: Mon, 23 Nov 2026 12:07:13 +0100 Subject: [PATCH 19/23] =?UTF-8?q?fix(web):=20skip=20Reload=20history=20for?= =?UTF-8?q?=20Docker=20and=20adopted=20panes,=20label=20the=20=C3=97=20for?= =?UTF-8?q?=20what=20the=20bar=20carries=20(#814)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - _historyReloadActionEligible() leaves out Docker and adopted sessions, whose nested tmux client keeps the local pane in the alternate screen so ?full=1 returns one screen the downgrade guard refuses; remote sessions stay eligible. - The bar's × is labelled "Dismiss Reload history" when the bar carries no truncation notice, with a zh-CN entry. --- docs/architecture-invariants.md | 2 +- src/web/public/app.js | 11 +++++++++-- src/web/public/i18n.js | 1 + test/shell-scroll-history-pull.test.ts | 16 ++++++++++++++++ 4 files changed, 27 insertions(+), 3 deletions(-) diff --git a/docs/architecture-invariants.md b/docs/architecture-invariants.md index b0a5dcfc..5763384e 100644 --- a/docs/architecture-invariants.md +++ b/docs/architecture-invariants.md @@ -253,7 +253,7 @@ Further detail: the `<prefix>: <title>` form (`w3-myapp: fix the login redirect` **Full-scrollback replay** (COD-164/#148, reworked for #205): `GET /api/sessions/:id/terminal?full=1` returns the ENTIRE tmux scrollback (capture-pane `-e -S -<lines>` bounded by the configured history limit, explicit `maxBuffer` from the terminal-history config, early byte-cap before normalization, CRLF-normalized for shell panes). On success the capture is returned ALONE (`source='mux-full-history'` — it supersedes the byte buffer; no duplication). The first load of each non-shell TUI session per page requests `full=1` (`_fullHistoryLoaded` Set in app.js — the old one-shot `_initialFullBufferLoad` flag was consumed by whichever tab auto-selected, leaving every other TUI tab one frame of history). Shell sessions instead load a bounded window of tmux's RENDERED history on every selection, automatic drop recovery, clear and tile load (`SHELL_LOAD_QUERY` in constants.js: `?full=1&tail=1MiB&lines=10000&alt=recording`): a 100k-line shell capture can be tens of MiB, and automatically parsing it makes tab-switch latency scale with the entire session (`lines=` bounds the synchronous capture-pane, about 8 ms per 1000 lines). They never replay the raw byte recording ahead of the visible frame any more: it holds full-screen repaints (an ssh'd tmux, `less`, any TUI) drawn for the pane height of the moment, and replayed into a terminal of another height each repaint's last newline scrolls its top row into scrollback, so one line tmux holds once showed up dozens of times. Because `lines=` is shallower than xterm's scrollback, the route reports a cut: the capture's `display-message` query also reads `#{history_size}` (`PaneCaptureOptions.capturedHistoryLines`, the same field the route reports as `paneHistoryLines`), and a full capture whose CLIENT bound (`lines=` below the configured `tmuxHistoryLimit`) left lines in tmux comes back `truncated`, `truncationReason: 'tail'`. ⚠️ Only a client bound below the ceiling counts: a request without `lines=` is bounded by the ceiling itself, and on tmux before 3.7 a live pane can hold more than a lowered ceiling, which no request can read. ⚠️ **A pane in the alternate screen keeps no tmux history**, and a nested tmux client (remote SSH and Docker cases, or `tmux`/`ssh -t host tmux` run by hand) holds its pane there, so its full capture is one screen. The same query reads `#{alternate_on}` (`capturedAlternateOn`), and a request carrying `alt=recording` (only `SHELL_LOAD_QUERY`) is then answered the old way, the visible frame over the tailed byte recording, which still carries the scrollback; agents, scroll pulls and **Load full history** never send it. `#{alternate_on}` cannot tell a nested tmux from vim, `less` or `htop`, so a local shell with one of those open takes the same fallback until it exits (the pre-fix load, with its repaint duplicates). Shell FULL history is explicit-button-only; reaching the top during an ordinary wheel/touch gesture must not reset xterm and replay the multi-megabyte capture on its main thread. That gesture instead pulls a BOUNDED window of it (`?full=1&tail=<TERMINAL_TAIL_SIZE>`, so a capture beyond 1 MiB comes back `truncationReason: 'tail'` and the banner offers the rest), and skips the replay when the window holds no more rows than the browser already has. ⚠️ **That skip runs BEFORE the downgrade guard, and it never touches the banner state**: the guard reads "smaller than the browser" as "tmux has nothing more to give", true of an unbounded capture and false of a window cut at the tail size, so a bounded window that reached it marked the session `exhausted` and removed **Load full history** while tmux still held the rest; and re-labelling the banner from a skipped payload would call a terminal that holds all of a Load full history pull "the most recent 1 MiB". A skipped window that came back truncated puts the session on the 60 s cooldown (`_fullHistoryRepullUseless`), because it can never reach anything older than the browser shows and `tail` is applied AFTER the server's synchronous `capture-pane` of the whole history, so each ask costs every client an event-loop stall (about 1 s at 100k lines; measured capture details below); an untruncated one keeps the 4 s cooldown, since it is all of tmux's history and the next burst can add to it. Declining the gesture outright was a dead end: after any burst a shell pane held about one screen of browser scrollback, and the button renders only once a replay was truncated, so a young shell tab had no way back to history tmux still held. Other modes re-pull `full=1` only at the top of the local buffer, and pressing **Load full history** forces the request for any recoverably truncated session (`_maybeRefetchFullHistory`, 4s per-session gesture cooldown, in-flight + tab-switch guards, viewport position held across the replay); Shell full pulls are not retained in the tab cache, so the next switch stays bounded. Chunked replay enqueues 32 KiB pieces across safe yields, appends an xterm parse marker, then releases the live-output gate; output arriving after that release stays ordered behind the snapshot, and the marker callback supplies accurate parse timing. ⚠️ **How the load ENDS depends on where the payload came from**, and `_bufferLoadFinishOpts` (app.js) is the one place that decides it for all four fetch-and-write paths. A payload built from the server's accumulated byte history is current up to the response, so the events queued during the load already appear in it and stay DISCARDED; replaying them would duplicate output, most visibly Ink's cursor-up redraws. A pane capture (`mux-visible` or `mux-full-history`) is current only up to CAPTURE time, so `_finishBufferLoad` replays the queue from the response's own arrival timestamp (`since`) and the pre-capture events stay dropped. ⚠️ **A path that then restores a scroll position must re-take the sticky-scroll baseline** (`_syncStickyScrollBaseline`): the replay runs inside `chunkedTerminalWrite` before its promise resolves, with the terminal freshly reset, so `batchTerminalWrite` samples `_wasAtBottomBeforeWrite` as true and the next `flushPendingWrites` would scroll to the bottom over the restore. ⚠️ The cutoff is a client-side timestamp and the server broadcasts on a batch timer (8ms WebSocket, 16-50ms SSE), so a batch pending when the capture ran arrives after the response and replays although the capture holds it — bounded by one batch interval, and closable only server side by flushing that batch before the capture. Tests for the three: `test/terminal-flush-budget.test.ts` pins which sources flush, `test/terminal-buffer-flush.test.ts` pins the `since` cutoff and the baseline re-take, and `test/capture-load-window.browser.test.ts` drives both against a live server. Live output is separately one-chunk-in-flight: xterm's callback releases each 32/64 KiB write before the next is submitted, keeping the remainder in the app queue where the 128 KiB cap can observe it instead of hiding an unbounded backlog in xterm's private WriteBuffer. While WebSocket owns terminal I/O, parallel SSE terminal/output-recovery events are discarded before JSON parsing; fallback recovery is single-flight per active session so backpressure cannot start overlapping reset+replay cycles. The route exposes capture/prepare totals in `Server-Timing`, while `[TERMINAL-PERF]` separates TTFB, body/JSON, reset+parse and total time for both selection and on-demand full pulls; parse completion is not a browser compositor/GPU paint measurement. The re-pull exists because xterm's buffer is only a WINDOW onto tmux's history and two things shrink it: tmux coalesces bursty output into pane REPAINTS that overwrite rows instead of emitting linefeeds (measured: a 60-line burst added 1 row of browser scrollback and destroyed 34), and a tab switch replays only the visible frame. tmux's own history is intact throughout — the browser just has to ask for it again. Gesture-triggered rather than polling because at a 100k history limit the capture can be megabytes. ⚠️ **The capture ENDS with a cursor move back to the pane's own caret position** (`formatCursorRestore`, from the same `display-message` query the visible-frame path uses). The linear replay otherwise leaves the caret wherever the last character landed — the bottom-most row carrying text, which for an agent CLI is the status line — so the caret sat on the composer's border instead of its input line and every cursor-relative update the CLI sent afterwards was measured from the wrong row, until its next full redraw silently repaired it (that self-repair is why the report read as "it fixes itself as soon as Claude writes a line"). ⚠️ **The move is RELATIVE — up `rows - 1 - cursor_y`, then `\r`, then right `cursor_x` — never `CUP`.** `\x1b[<row>;<col>H` numbers rows from the top of the browser's screen, so it lands correctly only while the browser's row count equals `pane_height`, and nothing guarantees that: `resizeWindow` issues its tmux resize fire-and-forget and returns immediately, so a capture can be taken before a requested resize has applied, and `_onSessionNeedsRefresh` sends no resize at all. Counting up from the last replayed row anchors to the content both ends share. Restoring the cursor makes ROW ALIGNMENT load-bearing on this path: **no transform that can DELETE A LINE may run over a full-history capture**, because every deletion shifts the frame out from under the restored position. Four had accumulated — trailing blank rows stripped by `\n+$`, `stripInkRedrawBloat`, the `CLAUDE_BANNER_PATTERN` trim that cuts everything above the banner, and `LEADING_WHITESPACE_PATTERN` — each correct for a byte stream of successive frames and each wrong for a single rendered frame. ⚠️ **Those skips key on `isFullCapture`, meaning a capture actually came back — never on `?full=1` alone.** When `captureActivePaneBuffer` returns null (ENOBUFS, a timeout, a vanished pane, or a session with no mux at all) the reply falls back to `session.terminalBuffer`, which IS a byte stream and must still be stripped; gating on the query flag returned it whole, and a direct-PTY session takes that path on every first selection rather than only during an outage. ⚠️ A capture holding nothing visible (`hasVisibleContent`) returns `''`, because the caller reads an empty capture as "unavailable" and keeps its byte history — retaining trailing blank rows made an all-blank pane non-empty, which would have replaced real history with a blank screen from the server side, where `_replayWouldShrinkBuffer` cannot see it. ⚠️ **"One line per screen row" holds only where no row was hard-wrapped**: `-J` joins a wrapped row into its logical line (measured: a 100-character line in a 40-column pane captures as 10 lines against a 12-row pane), and the counts reconcile only once the browser xterm re-wraps at the same width — the same assumption `_estimateReplayRows` already documents. Tests: `test/tmux-capture-full-history.test.ts` covers the cursor move, the trim pairing and `hasVisibleContent`; `test/routes/session-routes.test.ts` covers a surviving blank first row, an unstripped byte-history fallback, and an empty capture leaving history intact. ⚠️ **The re-pull must never DOWNGRADE the buffer** (#205 round 2): the same reasoning that makes it a win for a shell pane makes it destructive for a repaint-mode CLI pane, where tmux keeps no history of its own (`history_size≈0` measured for a Claude pane) and the capture is roughly ONE frame while xterm may hold hundreds of rows of replayed frames — `_resetTerminalForReplay()` + rewrite then deletes history mid-scroll ("goes back a bit, repeats blocks, gets worse the further up I go"; measured A/B on a live pane: 341 rows → 42 with the guard off). `_replayWouldShrinkBuffer()` (terminal-ui.js) estimates the capture's rendered rows — escape sequences stripped, `capture-pane -J` re-wrapping accounted for — and the pull is skipped when that is more than one screen short of `buffer.active.length`. The one-screen tolerance matters: both sides are estimates (the buffer length counts trailing blank rows), so only a clear downgrade is refused. A refused session joins `_fullHistoryRepullUseless`, raising its cooldown from 4s to 60s so a hollow pane stops re-fetching megabytes on every scroll-up. Tests: `test/tmux-capture-full-history.test.ts`, `test/tmux-scrollback-eol.test.ts`, `test/terminal-scroll-routing.test.ts`, `test/terminal-flush-budget.test.ts`. -**Repair while reading (#814)** is a manual **Reload history** action inside the existing history banner on desktop and touch devices, enabled by default and toggleable per device in Settings → Terminal & Input → Scrolling & rendering (`historyReloadAction`). It is offered only for a marked non-shell active session while scrolled away from live output, not detached, not owned by tiles, with no pull or buffer load in flight, no terminal load state for the session (a tab switch sets it before the buffer load opens), and no drop-recovery refresh owning the session (`_terminalRefreshOwner`, set for the whole fetch, before that refresh opens its buffer load). `_maybeRefetchFullHistory` returns early on that same owner, so Reload, Load full history and the top-of-buffer pull all stand aside instead of running a second capture whose download-time queue the refresh's own load would replace; the refresh re-syncs the action when it starts and when its `finally` releases the owner. `paneHistoryLines` is deliberately not consulted: it is recorded at the last load, so a session first opened empty keeps 0 after the very burst that opens the gap (#814). The bar is a polite live region (`role="status"`), but only the truncation notice is announced: a reload-only bar sets `aria-live="off"` before it re-renders, since it comes back on nearly every scroll-up in a busy tab, and its button stays reachable with Tab. A revealed truncation notice keeps its message and its **Load full history** control; Reload is appended only when the notice has no load control, or shown alone with a short missing-output message. When Reload is eligible, that **Load full history** control stands in for it and pulls with the content anchor (eligibility read at click time), so the reader keeps their line, and shares Reload's loading state, so the re-render the in-flight pull triggers keeps it on Loading… instead of bringing it back enabled; otherwise it keeps the top anchor and no loading state, so the bar still hides on a scroll back to live output. A reload-only × dismissal lasts until the mark is cleared by a successful `mux-full-history` replay, independently of the notice’s page-long dismissal. Pressing × while loading hides the bar immediately; the in-flight pull continues. Eligibility is cached per active session, with onScroll sampling coalesced to one animation frame on every device; unchanged eligibility never rebuilds the banner. Automatic history pulls and notice reveal stay top-only (#205). Live-output marking covers only live writes: a byte-history (`?tail=`) replay, for example after a burst in a background tab, never marks the session, so that gap relies on the top-of-buffer pull. The manual action forces a content-anchored pull, bypassing the gesture cooldown but retaining the downgrade guard. Any downgrade-refused pull hides Reload until the next successful `mux-full-history` replay; that refusal, not the cached history size, is what retires the action for a pane with no tmux history (fullscreen Claude). A manual reload answered by anything but `mux-full-history` (an empty response, or the byte-history fallback the route returns when the pane capture is blank or failed) retires it the same way, since only a mux replay clears the mark; a transient error envelope (`success: false`) leaves it available. A content anchor captures up to 64 visible rows, preserving indentation, and scores candidate alignments by matching viewport context. Each distinct nonblank row contributes at most one point, so repeated TUI borders cannot outvote a distinctive tool result. The best match must score at least 60% of the distinct rows and at least two of them, capped at the number of distinct rows, so a viewport with one distinct row (a lone tool result among blanks) matches on that row alone; it must also be unique within the search window. Equal-scoring copies are ambiguous, even when all furniture rows match or the distinctive tool row has disappeared; proximity to the expected position does not establish confidence. An isolated first-row match is not trusted: without confident, unambiguous context the old viewport index is retained, while readers already near live output retain their bottom distance. Search covers 4001 candidates from `expected - 4000 + rows` to `expected + rows` (at most 4064 cached line reads), leaning up because every row a reload fills in below the reader moves the reader's row up, while a capture with fewer rows below moves it down by at most the one screen the downgrade guard tolerates. Gaps up to `4000 - rows` rows therefore land exactly, including at xterm's scrollback cap, where the replay trims the top by the same number of rows. A wider gap puts the match outside the window: the restore keeps the old absolute index, which is right while the top of the buffer stays put but, at the cap, lands the reader the whole gap below their line. Live flushes use an xterm marker to track the reading row across scrollback trimming in O(1), and restore it only in the write callback; at-bottom sticky scroll is unchanged. Ordered, session-scoped travel during replay is applied with per-move clamping; a switched-to tab never donates travel. The notice is decided per recorded move, as a live scroll decides it: an upward move that reaches row 0 reveals the partial-history notice, a downward move that reaches live output retires it, and other moves leave the last decision standing, so reaching the top and then scrolling a few rows down still reveals it; a reload with no travel leaves the notice as it was. The buffer load opens BEFORE the fetch, so download-time output queues behind the replay instead of being overwritten. Non-replay exits flush the whole queue; replays retain the capture-header cutoff above. A blocked dropped-output recovery stores its session and current attempt, defers without consuming retries, and resumes only for the still-active session; a later drop for the same session during that load keeps the higher attempt, so the retry bound still holds. Only an actual `mux-full-history` replay clears the live-output mark and reload dismissal, and a newer live-write generation keeps them marked. The drop-recovery refresh (`_onSessionNeedsRefresh`) follows the same rule: it clears both after a completed replay of a `mux-full-history` capture, only while it still owns the active session and the live-output generation sampled before its fetch is unchanged; its `?tail=` fallback never clears them, and because that fallback means the full capture would shrink the buffer (the refusal signal), it retires the action under the same session and refresh-owner checks. The trade-off remains a full synchronous server capture (about 1 s: 1,068 ms median for `capture-pane -p -e -J -S -100000` over 100k lines of 120 characters, 12.1 MB), not a cheap automatic per-output repair. Tests: `test/shell-scroll-history-pull.test.ts`, `test/history-gap-repair.browser.test.ts`. +**Repair while reading (#814)** is a manual **Reload history** action inside the existing history banner on desktop and touch devices, enabled by default and toggleable per device in Settings → Terminal & Input → Scrolling & rendering (`historyReloadAction`). It is offered only for a marked non-shell active session while scrolled away from live output, not Docker or adopted (their local pane hosts a nested tmux client in the alternate screen, so `?full=1` returns one screen the downgrade guard refuses; remote sessions stay eligible, since the route splices the remote scrollback in), not detached, not owned by tiles, with no pull or buffer load in flight, no terminal load state for the session (a tab switch sets it before the buffer load opens), and no drop-recovery refresh owning the session (`_terminalRefreshOwner`, set for the whole fetch, before that refresh opens its buffer load). `_maybeRefetchFullHistory` returns early on that same owner, so Reload, Load full history and the top-of-buffer pull all stand aside instead of running a second capture whose download-time queue the refresh's own load would replace; the refresh re-syncs the action when it starts and when its `finally` releases the owner. `paneHistoryLines` is deliberately not consulted: it is recorded at the last load, so a session first opened empty keeps 0 after the very burst that opens the gap (#814). The bar is a polite live region (`role="status"`), but only the truncation notice is announced: a reload-only bar sets `aria-live="off"` before it re-renders, since it comes back on nearly every scroll-up in a busy tab, and its button stays reachable with Tab. Its × is labelled for what the bar carries: "Dismiss history notice" with the notice, "Dismiss Reload history" without it. A revealed truncation notice keeps its message and its **Load full history** control; Reload is appended only when the notice has no load control, or shown alone with a short missing-output message. When Reload is eligible, that **Load full history** control stands in for it and pulls with the content anchor (eligibility read at click time), so the reader keeps their line, and shares Reload's loading state, so the re-render the in-flight pull triggers keeps it on Loading… instead of bringing it back enabled; otherwise it keeps the top anchor and no loading state, so the bar still hides on a scroll back to live output. A reload-only × dismissal lasts until the mark is cleared by a successful `mux-full-history` replay, independently of the notice’s page-long dismissal. Pressing × while loading hides the bar immediately; the in-flight pull continues. Eligibility is cached per active session, with onScroll sampling coalesced to one animation frame on every device; unchanged eligibility never rebuilds the banner. Automatic history pulls and notice reveal stay top-only (#205). Live-output marking covers only live writes: a byte-history (`?tail=`) replay, for example after a burst in a background tab, never marks the session, so that gap relies on the top-of-buffer pull. The manual action forces a content-anchored pull, bypassing the gesture cooldown but retaining the downgrade guard. Any downgrade-refused pull hides Reload until the next successful `mux-full-history` replay; that refusal, not the cached history size, is what retires the action for a pane with no tmux history (fullscreen Claude). A manual reload answered by anything but `mux-full-history` (an empty response, or the byte-history fallback the route returns when the pane capture is blank or failed) retires it the same way, since only a mux replay clears the mark; a transient error envelope (`success: false`) leaves it available. A content anchor captures up to 64 visible rows, preserving indentation, and scores candidate alignments by matching viewport context. Each distinct nonblank row contributes at most one point, so repeated TUI borders cannot outvote a distinctive tool result. The best match must score at least 60% of the distinct rows and at least two of them, capped at the number of distinct rows, so a viewport with one distinct row (a lone tool result among blanks) matches on that row alone; it must also be unique within the search window. Equal-scoring copies are ambiguous, even when all furniture rows match or the distinctive tool row has disappeared; proximity to the expected position does not establish confidence. An isolated first-row match is not trusted: without confident, unambiguous context the old viewport index is retained, while readers already near live output retain their bottom distance. Search covers 4001 candidates from `expected - 4000 + rows` to `expected + rows` (at most 4064 cached line reads), leaning up because every row a reload fills in below the reader moves the reader's row up, while a capture with fewer rows below moves it down by at most the one screen the downgrade guard tolerates. Gaps up to `4000 - rows` rows therefore land exactly, including at xterm's scrollback cap, where the replay trims the top by the same number of rows. A wider gap puts the match outside the window: the restore keeps the old absolute index, which is right while the top of the buffer stays put but, at the cap, lands the reader the whole gap below their line. Live flushes use an xterm marker to track the reading row across scrollback trimming in O(1), and restore it only in the write callback; at-bottom sticky scroll is unchanged. Ordered, session-scoped travel during replay is applied with per-move clamping; a switched-to tab never donates travel. The notice is decided per recorded move, as a live scroll decides it: an upward move that reaches row 0 reveals the partial-history notice, a downward move that reaches live output retires it, and other moves leave the last decision standing, so reaching the top and then scrolling a few rows down still reveals it; a reload with no travel leaves the notice as it was. The buffer load opens BEFORE the fetch, so download-time output queues behind the replay instead of being overwritten. Non-replay exits flush the whole queue; replays retain the capture-header cutoff above. A blocked dropped-output recovery stores its session and current attempt, defers without consuming retries, and resumes only for the still-active session; a later drop for the same session during that load keeps the higher attempt, so the retry bound still holds. Only an actual `mux-full-history` replay clears the live-output mark and reload dismissal, and a newer live-write generation keeps them marked. The drop-recovery refresh (`_onSessionNeedsRefresh`) follows the same rule: it clears both after a completed replay of a `mux-full-history` capture, only while it still owns the active session and the live-output generation sampled before its fetch is unchanged; its `?tail=` fallback never clears them, and because that fallback means the full capture would shrink the buffer (the refusal signal), it retires the action under the same session and refresh-owner checks. The trade-off remains a full synchronous server capture (about 1 s: 1,068 ms median for `capture-pane -p -e -J -S -100000` over 100k lines of 120 characters, 12.1 MB), not a cheap automatic per-output repair. Tests: `test/shell-scroll-history-pull.test.ts`, `test/history-gap-repair.browser.test.ts`. **The partial-history notice is lazy and pane-gated** (`computeHistoryTruncationNotice()` in constants.js, `_renderHistoryTruncationBanner()` / `_setHistoryNoticeRevealed()` in app.js). `truncated` on a terminal response measures the server's BYTE stream, which is not what `full=1` can return: for a pane with no tmux scrollback (fullscreen claude starts in the alternate screen and never writes to the main grid, so `#{history_size}` is 0) the bytes a tail cut drops are old repaint frames. Measured on prod 2026-10-10, every claude pane: the tab-switch tail cut a 1.2 to 6.2 MB stream to 1 MiB, the local scrollback that tail replays into is repeats of the same frames (one pane: 450 non-blank rows, 44 unique, one row 33 times), and `full=1` returned 1 to 5 KB, so **Load full history** could only end in the downgrade refusal while the banner promised "4.8 MB more". The capture therefore reads `#{history_size}` in the SAME `display-message` as the cursor (no extra tmux call), the route returns it as `paneHistoryLines` (absent when the body is not a capture, and for a remote SSH session, whose local pane hosts the remote tmux client and always reports 0 while `full=1` reads the remote history), and a reported 0 hides the notice in every state; a positive count replaces the byte gap in the message. ⚠️ Key the notice decision on `history_size`, never on `alternate_on`: a shell running `less` is in the alternate screen with its whole history still retained (measured, 99,972 rows) and `full=1` returns all of it. The one place `alternate_on` decides is a shell's AUTOMATIC load (`alt=recording`, see Full-scrollback replay): there the question is whether the capture holds the scrollback a nested tmux client keeps in its byte recording, not whether a pull can return more. The notice is also LAZY: it appears only after a wheel/touch gesture reaches the top of the browser buffer and the pull that gesture started has settled (`_maybeLoadMoreHistoryOnScroll`), goes away when a downward gesture is back at live output or the tab switches (`selectSession` nulls `_historyNoticeRevealedFor` before repainting), and its × is sticky per session until reload (`_historyNoticeDismissed`). Tests: `test/history-truncation-notice.test.ts`, `test/history-notice-reveal.test.ts`. diff --git a/src/web/public/app.js b/src/web/public/app.js index db589667..e87d8122 100644 --- a/src/web/public/app.js +++ b/src/web/public/app.js @@ -10003,8 +10003,14 @@ class CodemanApp { // opens the gap (#814). A pane that really holds no history (fullscreen // Claude) captures one screen, `_replayWouldShrinkBuffer` refuses it, and the // refusal dismisses the action until the next `mux-full-history` replay. + // Docker and adopted sessions are left out: their local pane hosts a nested + // tmux client in the alternate screen, so `?full=1` returns one screen that + // the downgrade guard always refuses (the exclusions `paneKeepsNoHistory` + // uses in selectSession). Remote sessions stay eligible, since the route + // splices the remote scrollback into their capture. return !!(this.loadAppSettingsFromStorage?.()?.historyReloadAction !== false && - session && session.mode !== 'shell' && this._liveOutputSinceFullPull?.has(sessionId) && + session && session.mode !== 'shell' && !session.docker && !session.adopt && + this._liveOutputSinceFullPull?.has(sessionId) && !this._isLoadingBuffer && !this.terminalLoadStates?.has(sessionId) && // Tab switches set this before the buffer load opens. this._terminalRefreshOwner?.sessionId !== sessionId && // A drop-recovery refresh is fetching. @@ -10125,7 +10131,8 @@ class CodemanApp { const dismiss = document.createElement('button'); dismiss.type = 'button'; dismiss.className = 'history-trunc-dismiss'; - dismiss.setAttribute('aria-label', 'Dismiss history notice'); + // Name what the × actually dismisses: a reload-only bar has no notice. + dismiss.setAttribute('aria-label', showNotice ? 'Dismiss history notice' : 'Dismiss Reload history'); dismiss.textContent = '×'; dismiss.onclick = () => { // One × dismisses everything this bar carried. A notice dismissal sticks diff --git a/src/web/public/i18n.js b/src/web/public/i18n.js index 790f210b..a87f3ef1 100644 --- a/src/web/public/i18n.js +++ b/src/web/public/i18n.js @@ -757,6 +757,7 @@ 'Recent output may be missing from this view.': '此视图可能缺少最近的输出。', 'Reload history': '重新加载历史', 'Load full history': '加载完整历史', + 'Dismiss Reload history': '忽略“重新加载历史”', 'Auto Copy Selection': '自动复制选中内容', 'Selection & clipboard': '选中与剪贴板', 'Auto Copy: selection copied': '自动复制:已复制选中内容', diff --git a/test/shell-scroll-history-pull.test.ts b/test/shell-scroll-history-pull.test.ts index 2a3b2c75..56853297 100644 --- a/test/shell-scroll-history-pull.test.ts +++ b/test/shell-scroll-history-pull.test.ts @@ -1210,6 +1210,7 @@ describe('manual history banner action', () => { loadState: false, paneHistoryLines: undefined as number | undefined, refreshing: false, + sessionFlags: {} as Record<string, unknown>, ...options, }; const element = (): BannerElement => ({ @@ -1234,6 +1235,7 @@ describe('manual history banner action', () => { requestAnimationFrame: (callback: FrameRequestCallback) => frames.push(callback), }); const { app: base } = makeApp(String(state.mode), { bufferRows: 130, capture: lines(400) }); + Object.assign(base.sessions.get('s1')!, state.sessionFlags); const render = loadAppMethod('_renderHistoryTruncationBanner', { document, computeHistoryTruncationNotice: computeNotice, @@ -1288,6 +1290,11 @@ describe('manual history banner action', () => { { opts: { detached: true }, visible: false }, // A drop-recovery refresh owns the session while it fetches. { opts: { refreshing: true }, visible: false }, + // A nested tmux client keeps the local pane in the alternate screen, so + // `?full=1` returns one screen; the route splices in a remote's scrollback. + { opts: { sessionFlags: { docker: true } }, visible: false }, + { opts: { sessionFlags: { adopt: true } }, visible: false }, + { opts: { sessionFlags: { remote: true } }, visible: true }, ])('visibility is $visible for $opts', ({ opts, visible }) => { const { app, bar, button } = fixture(opts); app._syncHistoryReloadAction(); @@ -1307,6 +1314,15 @@ describe('manual history banner action', () => { expect(bar.setAttribute).toHaveBeenLastCalledWith('aria-live', 'polite'); }); + it('labels the dismiss button for what the bar carries', () => { + const { app, dismiss } = fixture(); + app._syncHistoryReloadAction(); + expect(dismiss()!.setAttribute).toHaveBeenCalledWith('aria-label', 'Dismiss Reload history'); + app._historyNoticeRevealedFor = 's1'; + app._setHistoryTruncation('s1', { ...TAIL_CUT, truncationReason: 'tail' }); + expect(dismiss()!.setAttribute).toHaveBeenCalledWith('aria-label', 'Dismiss history notice'); + }); + it('stands aside while a drop-recovery refresh fetches, then offers Reload again', async () => { const { app, bar, button } = fixture(); app._syncHistoryReloadAction(); From a92d512459a83b6d4dd1aa5b82e0f9845e392ed3 Mon Sep 17 00:00:00 2001 From: Hadrien Kerlero <199662351+HadrienKerlero@users.noreply.github.com> Date: Mon, 23 Nov 2026 13:02:47 +0100 Subject: [PATCH 20/23] test(web): match the Reload history button by its exact name (#814) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - The reload-only bar's × is now labelled "Dismiss Reload history", which Playwright's default substring name match also selected; the five Reload history locators in history-gap-repair.browser.test.ts pass exact: true. --- test/history-gap-repair.browser.test.ts | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/test/history-gap-repair.browser.test.ts b/test/history-gap-repair.browser.test.ts index 5fbabdd3..c9a371b3 100644 --- a/test/history-gap-repair.browser.test.ts +++ b/test/history-gap-repair.browser.test.ts @@ -358,7 +358,7 @@ describe.each([true, false])('manual history gap repair (touch: %s)', (touch) => await burst(page); expect((await bufferState(page)).numbers).not.toContain('NUMBER-090'); expect((await bufferState(page)).pulls).toBe(0); - const button = page.locator('#historyTruncationBar').getByRole('button', { name: 'Reload history' }); + const button = page.locator('#historyTruncationBar').getByRole('button', { name: 'Reload history', exact: true }); await button.waitFor({ state: 'visible' }); if (touch) await button.tap(); else await button.click(); @@ -382,7 +382,7 @@ describe.each([true, false])('manual history gap repair (touch: %s)', (touch) => await page.evaluate(() => { (window as RepairWindow).repairTest.inject = true; }); - const button = page.locator('#historyTruncationBar').getByRole('button', { name: 'Reload history' }); + const button = page.locator('#historyTruncationBar').getByRole('button', { name: 'Reload history', exact: true }); if (touch) await button.tap(); else await button.click(); await waitForRepair(page); @@ -461,7 +461,7 @@ describe.each([true, false])('manual history gap repair (touch: %s)', (touch) => requestAnimationFrame(() => requestAnimationFrame(() => resolve())); return promise; }); - expect(await page.getByRole('button', { name: 'Reload history' }).isVisible()).toBe(false); + expect(await page.getByRole('button', { name: 'Reload history', exact: true }).isVisible()).toBe(false); expect((await bufferState(page)).pulls).toBe(0); } catch (error) { throw await failureDetails(page, error); @@ -520,7 +520,7 @@ it('hides Reload history while a marked incoming tab capture is pending', async ); }, incoming); const bar = page.locator('#historyTruncationBar'); - expect(await bar.getByRole('button', { name: 'Reload history' }).count()).toBe(0); + expect(await bar.getByRole('button', { name: 'Reload history', exact: true }).count()).toBe(0); expect(await bar.isHidden()).toBe(true); await page.evaluate(async () => { const test = (window as RepairWindow).tabLoadTest!; @@ -635,7 +635,7 @@ it('holds an OMP reading row through repeated repaint history and capped live fl }, { session: SESSION, readingRow } ); - const button = page.locator('#historyTruncationBar').getByRole('button', { name: 'Reload history' }); + const button = page.locator('#historyTruncationBar').getByRole('button', { name: 'Reload history', exact: true }); await button.tap(); await waitForRepair(page); const measure = () => From e44d586f9375fc6cbef0d5aa1943b73b66d84433 Mon Sep 17 00:00:00 2001 From: Hadrien Kerlero <199662351+HadrienKerlero@users.noreply.github.com> Date: Mon, 23 Nov 2026 15:22:07 +0100 Subject: [PATCH 21/23] fix(web): keep the reader's row when a flush clears scrollback (#814) - flushPendingWrites falls back to the absolute viewport index when the write disposed the marker, which ESC[3J or RIS also do (the narrow and middle strips keep 3J), instead of sending the reader to row 0. - The live-output mark block moves below the write's try/catch, so the catch only covers the write. - Test: one flush of ESC[H ESC[2J ESC[3J plus a reprint keeps the reader on line 100, with and without markers. --- docs/architecture-invariants.md | 2 +- src/web/public/terminal-ui.js | 29 +++++++++++++++------------ test/terminal-viewport-marker.test.ts | 26 ++++++++++++++++++++++++ 3 files changed, 43 insertions(+), 14 deletions(-) diff --git a/docs/architecture-invariants.md b/docs/architecture-invariants.md index 5763384e..2fb1ce2e 100644 --- a/docs/architecture-invariants.md +++ b/docs/architecture-invariants.md @@ -253,7 +253,7 @@ Further detail: the `<prefix>: <title>` form (`w3-myapp: fix the login redirect` **Full-scrollback replay** (COD-164/#148, reworked for #205): `GET /api/sessions/:id/terminal?full=1` returns the ENTIRE tmux scrollback (capture-pane `-e -S -<lines>` bounded by the configured history limit, explicit `maxBuffer` from the terminal-history config, early byte-cap before normalization, CRLF-normalized for shell panes). On success the capture is returned ALONE (`source='mux-full-history'` — it supersedes the byte buffer; no duplication). The first load of each non-shell TUI session per page requests `full=1` (`_fullHistoryLoaded` Set in app.js — the old one-shot `_initialFullBufferLoad` flag was consumed by whichever tab auto-selected, leaving every other TUI tab one frame of history). Shell sessions instead load a bounded window of tmux's RENDERED history on every selection, automatic drop recovery, clear and tile load (`SHELL_LOAD_QUERY` in constants.js: `?full=1&tail=1MiB&lines=10000&alt=recording`): a 100k-line shell capture can be tens of MiB, and automatically parsing it makes tab-switch latency scale with the entire session (`lines=` bounds the synchronous capture-pane, about 8 ms per 1000 lines). They never replay the raw byte recording ahead of the visible frame any more: it holds full-screen repaints (an ssh'd tmux, `less`, any TUI) drawn for the pane height of the moment, and replayed into a terminal of another height each repaint's last newline scrolls its top row into scrollback, so one line tmux holds once showed up dozens of times. Because `lines=` is shallower than xterm's scrollback, the route reports a cut: the capture's `display-message` query also reads `#{history_size}` (`PaneCaptureOptions.capturedHistoryLines`, the same field the route reports as `paneHistoryLines`), and a full capture whose CLIENT bound (`lines=` below the configured `tmuxHistoryLimit`) left lines in tmux comes back `truncated`, `truncationReason: 'tail'`. ⚠️ Only a client bound below the ceiling counts: a request without `lines=` is bounded by the ceiling itself, and on tmux before 3.7 a live pane can hold more than a lowered ceiling, which no request can read. ⚠️ **A pane in the alternate screen keeps no tmux history**, and a nested tmux client (remote SSH and Docker cases, or `tmux`/`ssh -t host tmux` run by hand) holds its pane there, so its full capture is one screen. The same query reads `#{alternate_on}` (`capturedAlternateOn`), and a request carrying `alt=recording` (only `SHELL_LOAD_QUERY`) is then answered the old way, the visible frame over the tailed byte recording, which still carries the scrollback; agents, scroll pulls and **Load full history** never send it. `#{alternate_on}` cannot tell a nested tmux from vim, `less` or `htop`, so a local shell with one of those open takes the same fallback until it exits (the pre-fix load, with its repaint duplicates). Shell FULL history is explicit-button-only; reaching the top during an ordinary wheel/touch gesture must not reset xterm and replay the multi-megabyte capture on its main thread. That gesture instead pulls a BOUNDED window of it (`?full=1&tail=<TERMINAL_TAIL_SIZE>`, so a capture beyond 1 MiB comes back `truncationReason: 'tail'` and the banner offers the rest), and skips the replay when the window holds no more rows than the browser already has. ⚠️ **That skip runs BEFORE the downgrade guard, and it never touches the banner state**: the guard reads "smaller than the browser" as "tmux has nothing more to give", true of an unbounded capture and false of a window cut at the tail size, so a bounded window that reached it marked the session `exhausted` and removed **Load full history** while tmux still held the rest; and re-labelling the banner from a skipped payload would call a terminal that holds all of a Load full history pull "the most recent 1 MiB". A skipped window that came back truncated puts the session on the 60 s cooldown (`_fullHistoryRepullUseless`), because it can never reach anything older than the browser shows and `tail` is applied AFTER the server's synchronous `capture-pane` of the whole history, so each ask costs every client an event-loop stall (about 1 s at 100k lines; measured capture details below); an untruncated one keeps the 4 s cooldown, since it is all of tmux's history and the next burst can add to it. Declining the gesture outright was a dead end: after any burst a shell pane held about one screen of browser scrollback, and the button renders only once a replay was truncated, so a young shell tab had no way back to history tmux still held. Other modes re-pull `full=1` only at the top of the local buffer, and pressing **Load full history** forces the request for any recoverably truncated session (`_maybeRefetchFullHistory`, 4s per-session gesture cooldown, in-flight + tab-switch guards, viewport position held across the replay); Shell full pulls are not retained in the tab cache, so the next switch stays bounded. Chunked replay enqueues 32 KiB pieces across safe yields, appends an xterm parse marker, then releases the live-output gate; output arriving after that release stays ordered behind the snapshot, and the marker callback supplies accurate parse timing. ⚠️ **How the load ENDS depends on where the payload came from**, and `_bufferLoadFinishOpts` (app.js) is the one place that decides it for all four fetch-and-write paths. A payload built from the server's accumulated byte history is current up to the response, so the events queued during the load already appear in it and stay DISCARDED; replaying them would duplicate output, most visibly Ink's cursor-up redraws. A pane capture (`mux-visible` or `mux-full-history`) is current only up to CAPTURE time, so `_finishBufferLoad` replays the queue from the response's own arrival timestamp (`since`) and the pre-capture events stay dropped. ⚠️ **A path that then restores a scroll position must re-take the sticky-scroll baseline** (`_syncStickyScrollBaseline`): the replay runs inside `chunkedTerminalWrite` before its promise resolves, with the terminal freshly reset, so `batchTerminalWrite` samples `_wasAtBottomBeforeWrite` as true and the next `flushPendingWrites` would scroll to the bottom over the restore. ⚠️ The cutoff is a client-side timestamp and the server broadcasts on a batch timer (8ms WebSocket, 16-50ms SSE), so a batch pending when the capture ran arrives after the response and replays although the capture holds it — bounded by one batch interval, and closable only server side by flushing that batch before the capture. Tests for the three: `test/terminal-flush-budget.test.ts` pins which sources flush, `test/terminal-buffer-flush.test.ts` pins the `since` cutoff and the baseline re-take, and `test/capture-load-window.browser.test.ts` drives both against a live server. Live output is separately one-chunk-in-flight: xterm's callback releases each 32/64 KiB write before the next is submitted, keeping the remainder in the app queue where the 128 KiB cap can observe it instead of hiding an unbounded backlog in xterm's private WriteBuffer. While WebSocket owns terminal I/O, parallel SSE terminal/output-recovery events are discarded before JSON parsing; fallback recovery is single-flight per active session so backpressure cannot start overlapping reset+replay cycles. The route exposes capture/prepare totals in `Server-Timing`, while `[TERMINAL-PERF]` separates TTFB, body/JSON, reset+parse and total time for both selection and on-demand full pulls; parse completion is not a browser compositor/GPU paint measurement. The re-pull exists because xterm's buffer is only a WINDOW onto tmux's history and two things shrink it: tmux coalesces bursty output into pane REPAINTS that overwrite rows instead of emitting linefeeds (measured: a 60-line burst added 1 row of browser scrollback and destroyed 34), and a tab switch replays only the visible frame. tmux's own history is intact throughout — the browser just has to ask for it again. Gesture-triggered rather than polling because at a 100k history limit the capture can be megabytes. ⚠️ **The capture ENDS with a cursor move back to the pane's own caret position** (`formatCursorRestore`, from the same `display-message` query the visible-frame path uses). The linear replay otherwise leaves the caret wherever the last character landed — the bottom-most row carrying text, which for an agent CLI is the status line — so the caret sat on the composer's border instead of its input line and every cursor-relative update the CLI sent afterwards was measured from the wrong row, until its next full redraw silently repaired it (that self-repair is why the report read as "it fixes itself as soon as Claude writes a line"). ⚠️ **The move is RELATIVE — up `rows - 1 - cursor_y`, then `\r`, then right `cursor_x` — never `CUP`.** `\x1b[<row>;<col>H` numbers rows from the top of the browser's screen, so it lands correctly only while the browser's row count equals `pane_height`, and nothing guarantees that: `resizeWindow` issues its tmux resize fire-and-forget and returns immediately, so a capture can be taken before a requested resize has applied, and `_onSessionNeedsRefresh` sends no resize at all. Counting up from the last replayed row anchors to the content both ends share. Restoring the cursor makes ROW ALIGNMENT load-bearing on this path: **no transform that can DELETE A LINE may run over a full-history capture**, because every deletion shifts the frame out from under the restored position. Four had accumulated — trailing blank rows stripped by `\n+$`, `stripInkRedrawBloat`, the `CLAUDE_BANNER_PATTERN` trim that cuts everything above the banner, and `LEADING_WHITESPACE_PATTERN` — each correct for a byte stream of successive frames and each wrong for a single rendered frame. ⚠️ **Those skips key on `isFullCapture`, meaning a capture actually came back — never on `?full=1` alone.** When `captureActivePaneBuffer` returns null (ENOBUFS, a timeout, a vanished pane, or a session with no mux at all) the reply falls back to `session.terminalBuffer`, which IS a byte stream and must still be stripped; gating on the query flag returned it whole, and a direct-PTY session takes that path on every first selection rather than only during an outage. ⚠️ A capture holding nothing visible (`hasVisibleContent`) returns `''`, because the caller reads an empty capture as "unavailable" and keeps its byte history — retaining trailing blank rows made an all-blank pane non-empty, which would have replaced real history with a blank screen from the server side, where `_replayWouldShrinkBuffer` cannot see it. ⚠️ **"One line per screen row" holds only where no row was hard-wrapped**: `-J` joins a wrapped row into its logical line (measured: a 100-character line in a 40-column pane captures as 10 lines against a 12-row pane), and the counts reconcile only once the browser xterm re-wraps at the same width — the same assumption `_estimateReplayRows` already documents. Tests: `test/tmux-capture-full-history.test.ts` covers the cursor move, the trim pairing and `hasVisibleContent`; `test/routes/session-routes.test.ts` covers a surviving blank first row, an unstripped byte-history fallback, and an empty capture leaving history intact. ⚠️ **The re-pull must never DOWNGRADE the buffer** (#205 round 2): the same reasoning that makes it a win for a shell pane makes it destructive for a repaint-mode CLI pane, where tmux keeps no history of its own (`history_size≈0` measured for a Claude pane) and the capture is roughly ONE frame while xterm may hold hundreds of rows of replayed frames — `_resetTerminalForReplay()` + rewrite then deletes history mid-scroll ("goes back a bit, repeats blocks, gets worse the further up I go"; measured A/B on a live pane: 341 rows → 42 with the guard off). `_replayWouldShrinkBuffer()` (terminal-ui.js) estimates the capture's rendered rows — escape sequences stripped, `capture-pane -J` re-wrapping accounted for — and the pull is skipped when that is more than one screen short of `buffer.active.length`. The one-screen tolerance matters: both sides are estimates (the buffer length counts trailing blank rows), so only a clear downgrade is refused. A refused session joins `_fullHistoryRepullUseless`, raising its cooldown from 4s to 60s so a hollow pane stops re-fetching megabytes on every scroll-up. Tests: `test/tmux-capture-full-history.test.ts`, `test/tmux-scrollback-eol.test.ts`, `test/terminal-scroll-routing.test.ts`, `test/terminal-flush-budget.test.ts`. -**Repair while reading (#814)** is a manual **Reload history** action inside the existing history banner on desktop and touch devices, enabled by default and toggleable per device in Settings → Terminal & Input → Scrolling & rendering (`historyReloadAction`). It is offered only for a marked non-shell active session while scrolled away from live output, not Docker or adopted (their local pane hosts a nested tmux client in the alternate screen, so `?full=1` returns one screen the downgrade guard refuses; remote sessions stay eligible, since the route splices the remote scrollback in), not detached, not owned by tiles, with no pull or buffer load in flight, no terminal load state for the session (a tab switch sets it before the buffer load opens), and no drop-recovery refresh owning the session (`_terminalRefreshOwner`, set for the whole fetch, before that refresh opens its buffer load). `_maybeRefetchFullHistory` returns early on that same owner, so Reload, Load full history and the top-of-buffer pull all stand aside instead of running a second capture whose download-time queue the refresh's own load would replace; the refresh re-syncs the action when it starts and when its `finally` releases the owner. `paneHistoryLines` is deliberately not consulted: it is recorded at the last load, so a session first opened empty keeps 0 after the very burst that opens the gap (#814). The bar is a polite live region (`role="status"`), but only the truncation notice is announced: a reload-only bar sets `aria-live="off"` before it re-renders, since it comes back on nearly every scroll-up in a busy tab, and its button stays reachable with Tab. Its × is labelled for what the bar carries: "Dismiss history notice" with the notice, "Dismiss Reload history" without it. A revealed truncation notice keeps its message and its **Load full history** control; Reload is appended only when the notice has no load control, or shown alone with a short missing-output message. When Reload is eligible, that **Load full history** control stands in for it and pulls with the content anchor (eligibility read at click time), so the reader keeps their line, and shares Reload's loading state, so the re-render the in-flight pull triggers keeps it on Loading… instead of bringing it back enabled; otherwise it keeps the top anchor and no loading state, so the bar still hides on a scroll back to live output. A reload-only × dismissal lasts until the mark is cleared by a successful `mux-full-history` replay, independently of the notice’s page-long dismissal. Pressing × while loading hides the bar immediately; the in-flight pull continues. Eligibility is cached per active session, with onScroll sampling coalesced to one animation frame on every device; unchanged eligibility never rebuilds the banner. Automatic history pulls and notice reveal stay top-only (#205). Live-output marking covers only live writes: a byte-history (`?tail=`) replay, for example after a burst in a background tab, never marks the session, so that gap relies on the top-of-buffer pull. The manual action forces a content-anchored pull, bypassing the gesture cooldown but retaining the downgrade guard. Any downgrade-refused pull hides Reload until the next successful `mux-full-history` replay; that refusal, not the cached history size, is what retires the action for a pane with no tmux history (fullscreen Claude). A manual reload answered by anything but `mux-full-history` (an empty response, or the byte-history fallback the route returns when the pane capture is blank or failed) retires it the same way, since only a mux replay clears the mark; a transient error envelope (`success: false`) leaves it available. A content anchor captures up to 64 visible rows, preserving indentation, and scores candidate alignments by matching viewport context. Each distinct nonblank row contributes at most one point, so repeated TUI borders cannot outvote a distinctive tool result. The best match must score at least 60% of the distinct rows and at least two of them, capped at the number of distinct rows, so a viewport with one distinct row (a lone tool result among blanks) matches on that row alone; it must also be unique within the search window. Equal-scoring copies are ambiguous, even when all furniture rows match or the distinctive tool row has disappeared; proximity to the expected position does not establish confidence. An isolated first-row match is not trusted: without confident, unambiguous context the old viewport index is retained, while readers already near live output retain their bottom distance. Search covers 4001 candidates from `expected - 4000 + rows` to `expected + rows` (at most 4064 cached line reads), leaning up because every row a reload fills in below the reader moves the reader's row up, while a capture with fewer rows below moves it down by at most the one screen the downgrade guard tolerates. Gaps up to `4000 - rows` rows therefore land exactly, including at xterm's scrollback cap, where the replay trims the top by the same number of rows. A wider gap puts the match outside the window: the restore keeps the old absolute index, which is right while the top of the buffer stays put but, at the cap, lands the reader the whole gap below their line. Live flushes use an xterm marker to track the reading row across scrollback trimming in O(1), and restore it only in the write callback; at-bottom sticky scroll is unchanged. Ordered, session-scoped travel during replay is applied with per-move clamping; a switched-to tab never donates travel. The notice is decided per recorded move, as a live scroll decides it: an upward move that reaches row 0 reveals the partial-history notice, a downward move that reaches live output retires it, and other moves leave the last decision standing, so reaching the top and then scrolling a few rows down still reveals it; a reload with no travel leaves the notice as it was. The buffer load opens BEFORE the fetch, so download-time output queues behind the replay instead of being overwritten. Non-replay exits flush the whole queue; replays retain the capture-header cutoff above. A blocked dropped-output recovery stores its session and current attempt, defers without consuming retries, and resumes only for the still-active session; a later drop for the same session during that load keeps the higher attempt, so the retry bound still holds. Only an actual `mux-full-history` replay clears the live-output mark and reload dismissal, and a newer live-write generation keeps them marked. The drop-recovery refresh (`_onSessionNeedsRefresh`) follows the same rule: it clears both after a completed replay of a `mux-full-history` capture, only while it still owns the active session and the live-output generation sampled before its fetch is unchanged; its `?tail=` fallback never clears them, and because that fallback means the full capture would shrink the buffer (the refusal signal), it retires the action under the same session and refresh-owner checks. The trade-off remains a full synchronous server capture (about 1 s: 1,068 ms median for `capture-pane -p -e -J -S -100000` over 100k lines of 120 characters, 12.1 MB), not a cheap automatic per-output repair. Tests: `test/shell-scroll-history-pull.test.ts`, `test/history-gap-repair.browser.test.ts`. +**Repair while reading (#814)** is a manual **Reload history** action inside the existing history banner on desktop and touch devices, enabled by default and toggleable per device in Settings → Terminal & Input → Scrolling & rendering (`historyReloadAction`). It is offered only for a marked non-shell active session while scrolled away from live output, not Docker or adopted (their local pane hosts a nested tmux client in the alternate screen, so `?full=1` returns one screen the downgrade guard refuses; remote sessions stay eligible, since the route splices the remote scrollback in), not detached, not owned by tiles, with no pull or buffer load in flight, no terminal load state for the session (a tab switch sets it before the buffer load opens), and no drop-recovery refresh owning the session (`_terminalRefreshOwner`, set for the whole fetch, before that refresh opens its buffer load). `_maybeRefetchFullHistory` returns early on that same owner, so Reload, Load full history and the top-of-buffer pull all stand aside instead of running a second capture whose download-time queue the refresh's own load would replace; the refresh re-syncs the action when it starts and when its `finally` releases the owner. `paneHistoryLines` is deliberately not consulted: it is recorded at the last load, so a session first opened empty keeps 0 after the very burst that opens the gap (#814). The bar is a polite live region (`role="status"`), but only the truncation notice is announced: a reload-only bar sets `aria-live="off"` before it re-renders, since it comes back on nearly every scroll-up in a busy tab, and its button stays reachable with Tab. Its × is labelled for what the bar carries: "Dismiss history notice" with the notice, "Dismiss Reload history" without it. A revealed truncation notice keeps its message and its **Load full history** control; Reload is appended only when the notice has no load control, or shown alone with a short missing-output message. When Reload is eligible, that **Load full history** control stands in for it and pulls with the content anchor (eligibility read at click time), so the reader keeps their line, and shares Reload's loading state, so the re-render the in-flight pull triggers keeps it on Loading… instead of bringing it back enabled; otherwise it keeps the top anchor and no loading state, so the bar still hides on a scroll back to live output. A reload-only × dismissal lasts until the mark is cleared by a successful `mux-full-history` replay, independently of the notice’s page-long dismissal. Pressing × while loading hides the bar immediately; the in-flight pull continues. Eligibility is cached per active session, with onScroll sampling coalesced to one animation frame on every device; unchanged eligibility never rebuilds the banner. Automatic history pulls and notice reveal stay top-only (#205). Live-output marking covers only live writes: a byte-history (`?tail=`) replay, for example after a burst in a background tab, never marks the session, so that gap relies on the top-of-buffer pull. The manual action forces a content-anchored pull, bypassing the gesture cooldown but retaining the downgrade guard. Any downgrade-refused pull hides Reload until the next successful `mux-full-history` replay; that refusal, not the cached history size, is what retires the action for a pane with no tmux history (fullscreen Claude). A manual reload answered by anything but `mux-full-history` (an empty response, or the byte-history fallback the route returns when the pane capture is blank or failed) retires it the same way, since only a mux replay clears the mark; a transient error envelope (`success: false`) leaves it available. A content anchor captures up to 64 visible rows, preserving indentation, and scores candidate alignments by matching viewport context. Each distinct nonblank row contributes at most one point, so repeated TUI borders cannot outvote a distinctive tool result. The best match must score at least 60% of the distinct rows and at least two of them, capped at the number of distinct rows, so a viewport with one distinct row (a lone tool result among blanks) matches on that row alone; it must also be unique within the search window. Equal-scoring copies are ambiguous, even when all furniture rows match or the distinctive tool row has disappeared; proximity to the expected position does not establish confidence. An isolated first-row match is not trusted: without confident, unambiguous context the old viewport index is retained, while readers already near live output retain their bottom distance. Search covers 4001 candidates from `expected - 4000 + rows` to `expected + rows` (at most 4064 cached line reads), leaning up because every row a reload fills in below the reader moves the reader's row up, while a capture with fewer rows below moves it down by at most the one screen the downgrade guard tolerates. Gaps up to `4000 - rows` rows therefore land exactly, including at xterm's scrollback cap, where the replay trims the top by the same number of rows. A wider gap puts the match outside the window: the restore keeps the old absolute index, which is right while the top of the buffer stays put but, at the cap, lands the reader the whole gap below their line. Live flushes use an xterm marker to track the reading row across scrollback trimming in O(1), and restore it only in the write callback; a marker the write disposed (its row trimmed, or scrollback erased by `ESC[3J` or RIS, which the narrow and middle strips keep) falls back to the absolute index instead of row 0; at-bottom sticky scroll is unchanged. Ordered, session-scoped travel during replay is applied with per-move clamping; a switched-to tab never donates travel. The notice is decided per recorded move, as a live scroll decides it: an upward move that reaches row 0 reveals the partial-history notice, a downward move that reaches live output retires it, and other moves leave the last decision standing, so reaching the top and then scrolling a few rows down still reveals it; a reload with no travel leaves the notice as it was. The buffer load opens BEFORE the fetch, so download-time output queues behind the replay instead of being overwritten. Non-replay exits flush the whole queue; replays retain the capture-header cutoff above. A blocked dropped-output recovery stores its session and current attempt, defers without consuming retries, and resumes only for the still-active session; a later drop for the same session during that load keeps the higher attempt, so the retry bound still holds. Only an actual `mux-full-history` replay clears the live-output mark and reload dismissal, and a newer live-write generation keeps them marked. The drop-recovery refresh (`_onSessionNeedsRefresh`) follows the same rule: it clears both after a completed replay of a `mux-full-history` capture, only while it still owns the active session and the live-output generation sampled before its fetch is unchanged; its `?tail=` fallback never clears them, and because that fallback means the full capture would shrink the buffer (the refusal signal), it retires the action under the same session and refresh-owner checks. The trade-off remains a full synchronous server capture (about 1 s: 1,068 ms median for `capture-pane -p -e -J -S -100000` over 100k lines of 120 characters, 12.1 MB), not a cheap automatic per-output repair. Tests: `test/shell-scroll-history-pull.test.ts`, `test/history-gap-repair.browser.test.ts`. **The partial-history notice is lazy and pane-gated** (`computeHistoryTruncationNotice()` in constants.js, `_renderHistoryTruncationBanner()` / `_setHistoryNoticeRevealed()` in app.js). `truncated` on a terminal response measures the server's BYTE stream, which is not what `full=1` can return: for a pane with no tmux scrollback (fullscreen claude starts in the alternate screen and never writes to the main grid, so `#{history_size}` is 0) the bytes a tail cut drops are old repaint frames. Measured on prod 2026-10-10, every claude pane: the tab-switch tail cut a 1.2 to 6.2 MB stream to 1 MiB, the local scrollback that tail replays into is repeats of the same frames (one pane: 450 non-blank rows, 44 unique, one row 33 times), and `full=1` returned 1 to 5 KB, so **Load full history** could only end in the downgrade refusal while the banner promised "4.8 MB more". The capture therefore reads `#{history_size}` in the SAME `display-message` as the cursor (no extra tmux call), the route returns it as `paneHistoryLines` (absent when the body is not a capture, and for a remote SSH session, whose local pane hosts the remote tmux client and always reports 0 while `full=1` reads the remote history), and a reported 0 hides the notice in every state; a positive count replaces the byte gap in the message. ⚠️ Key the notice decision on `history_size`, never on `alternate_on`: a shell running `less` is in the alternate screen with its whole history still retained (measured, 99,972 rows) and `full=1` returns all of it. The one place `alternate_on` decides is a shell's AUTOMATIC load (`alt=recording`, see Full-scrollback replay): there the question is whether the capture holds the scrollback a nested tmux client keeps in its byte recording, not whether a pull can return more. The notice is also LAZY: it appears only after a wheel/touch gesture reaches the top of the browser buffer and the pull that gesture started has settled (`_maybeLoadMoreHistoryOnScroll`), goes away when a downward gesture is back at live output or the tab switches (`selectSession` nulls `_historyNoticeRevealedFor` before repainting), and its × is sticky per session until reload (`_historyNoticeDismissed`). Tests: `test/history-truncation-notice.test.ts`, `test/history-notice-reveal.test.ts`. diff --git a/src/web/public/terminal-ui.js b/src/web/public/terminal-ui.js index 888e2276..0b159508 100644 --- a/src/web/public/terminal-ui.js +++ b/src/web/public/terminal-ui.js @@ -4791,30 +4791,33 @@ Object.assign(CodemanApp.prototype, { // signal, which is the earliest point the anchor can actually be // reasserted. (The synchronous version passed its regression test only // because the test's write mock moved the viewport synchronously.) - const viewportY = viewportMarker - ? (viewportMarker.isDisposed ? 0 : viewportMarker.line) - : preserveViewportY; + // A marker is disposed when its row is trimmed off a full scrollback, + // but also when the stream itself erases scrollback (`ESC[3J`, RIS), + // which the narrow and middle strips keep. Fall back to the absolute + // index then, as before markers, rather than sending the reader to row 0. + const viewportY = viewportMarker && !viewportMarker.isDisposed ? viewportMarker.line : preserveViewportY; viewportMarker?.dispose(); this._restoreTerminalViewport(viewportY, flushSessionId); this._scheduleTerminalWriteFlush(); this._noteMobileImeAuthoritativeOutput(flushedOutputSeq, flushSessionId); }); - // Only live writes can open a new tmux repaint gap; replays cannot (#814). - if (writeChunk.length && flushSessionId && !this._isLoadingBuffer) { - const marked = (this._liveOutputSinceFullPull ||= new Set()); - const newlyMarked = !marked.has(flushSessionId); - marked.add(flushSessionId); - const generations = (this._liveOutputGen ||= new Map()); - generations.set(flushSessionId, (generations.get(flushSessionId) || 0) + 1); - // Mark transitions sync immediately; onScroll is coalesced on all devices. - if (newlyMarked) this._syncHistoryReloadAction?.(); - } } catch (err) { viewportMarker?.dispose(); this._terminalWriteInFlight = false; this._terminalWriteInFlightBytes = 0; throw err; } + // Only live writes can open a new tmux repaint gap; replays cannot (#814). + // Outside the try: the catch above must only cover the write itself. + if (writeChunk.length && flushSessionId && !this._isLoadingBuffer) { + const marked = (this._liveOutputSinceFullPull ||= new Set()); + const newlyMarked = !marked.has(flushSessionId); + marked.add(flushSessionId); + const generations = (this._liveOutputGen ||= new Map()); + generations.set(flushSessionId, (generations.get(flushSessionId) || 0) + 1); + // Mark transitions sync immediately; onScroll is coalesced on all devices. + if (newlyMarked) this._syncHistoryReloadAction?.(); + } const bytesThisFrame = deferred ? MAX_FRAME_BYTES : _joinedLen; const _dt = performance.now() - _t0; if (_dt > 100 || deferred) diff --git a/test/terminal-viewport-marker.test.ts b/test/terminal-viewport-marker.test.ts index 3f241009..28f3cce3 100644 --- a/test/terminal-viewport-marker.test.ts +++ b/test/terminal-viewport-marker.test.ts @@ -102,4 +102,30 @@ describe('live terminal viewport at the scrollback cap', () => { expect(row).not.toBe('line 140'); expect(row).toBe('line 160'); }); + + // ESC[3J (kept by the narrow and middle strips) erases scrollback and disposes + // the marker the same way a trim does; the reader must keep their row, not + // land on row 0. + it.each([true, false])( + 'keeps the reader on their row when one flush clears scrollback and reprints it (markers: %s)', + async (markersEnabled) => { + const terminal = new Terminal({ cols: 80, rows: 10, scrollback: 1000, allowProposedApi: true }); + try { + if (!markersEnabled) Object.defineProperty(terminal, 'registerMarker', { value: undefined }); + const app = loadHarness(terminal); + const history = Array.from({ length: 200 }, (_, i) => `line ${i}\r\n`).join(''); + await write(terminal, history); + terminal.scrollToLine(100); + expect(topRow(terminal)).toBe('line 100'); + expect(app.isTerminalAtBottom()).toBe(false); + app.pendingWrites.push(`\x1b[H\x1b[2J\x1b[3J${history}`); + app.flushPendingWrites(); + await write(terminal, ''); + expect(app._terminalWriteInFlight).toBe(false); + expect(topRow(terminal)).toBe('line 100'); + } finally { + terminal.dispose(); + } + } + ); }); From c52137a2ec4cef1ede8b2143cc86291797f51a93 Mon Sep 17 00:00:00 2001 From: Hadrien Kerlero <199662351+HadrienKerlero@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:06:04 +0100 Subject: [PATCH 22/23] docs(web): RIS leaves the reading-row marker alive (#814) - In xterm 6 only ESC[3J (and a trim) disposes the marker; RIS swaps in a new buffer and leaves it on its old line, which is the same index as the fallback. The flushPendingWrites comment and the invariants paragraph now say so. --- docs/architecture-invariants.md | 2 +- src/web/public/terminal-ui.js | 4 +++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/docs/architecture-invariants.md b/docs/architecture-invariants.md index 2fb1ce2e..b3a59cfb 100644 --- a/docs/architecture-invariants.md +++ b/docs/architecture-invariants.md @@ -253,7 +253,7 @@ Further detail: the `<prefix>: <title>` form (`w3-myapp: fix the login redirect` **Full-scrollback replay** (COD-164/#148, reworked for #205): `GET /api/sessions/:id/terminal?full=1` returns the ENTIRE tmux scrollback (capture-pane `-e -S -<lines>` bounded by the configured history limit, explicit `maxBuffer` from the terminal-history config, early byte-cap before normalization, CRLF-normalized for shell panes). On success the capture is returned ALONE (`source='mux-full-history'` — it supersedes the byte buffer; no duplication). The first load of each non-shell TUI session per page requests `full=1` (`_fullHistoryLoaded` Set in app.js — the old one-shot `_initialFullBufferLoad` flag was consumed by whichever tab auto-selected, leaving every other TUI tab one frame of history). Shell sessions instead load a bounded window of tmux's RENDERED history on every selection, automatic drop recovery, clear and tile load (`SHELL_LOAD_QUERY` in constants.js: `?full=1&tail=1MiB&lines=10000&alt=recording`): a 100k-line shell capture can be tens of MiB, and automatically parsing it makes tab-switch latency scale with the entire session (`lines=` bounds the synchronous capture-pane, about 8 ms per 1000 lines). They never replay the raw byte recording ahead of the visible frame any more: it holds full-screen repaints (an ssh'd tmux, `less`, any TUI) drawn for the pane height of the moment, and replayed into a terminal of another height each repaint's last newline scrolls its top row into scrollback, so one line tmux holds once showed up dozens of times. Because `lines=` is shallower than xterm's scrollback, the route reports a cut: the capture's `display-message` query also reads `#{history_size}` (`PaneCaptureOptions.capturedHistoryLines`, the same field the route reports as `paneHistoryLines`), and a full capture whose CLIENT bound (`lines=` below the configured `tmuxHistoryLimit`) left lines in tmux comes back `truncated`, `truncationReason: 'tail'`. ⚠️ Only a client bound below the ceiling counts: a request without `lines=` is bounded by the ceiling itself, and on tmux before 3.7 a live pane can hold more than a lowered ceiling, which no request can read. ⚠️ **A pane in the alternate screen keeps no tmux history**, and a nested tmux client (remote SSH and Docker cases, or `tmux`/`ssh -t host tmux` run by hand) holds its pane there, so its full capture is one screen. The same query reads `#{alternate_on}` (`capturedAlternateOn`), and a request carrying `alt=recording` (only `SHELL_LOAD_QUERY`) is then answered the old way, the visible frame over the tailed byte recording, which still carries the scrollback; agents, scroll pulls and **Load full history** never send it. `#{alternate_on}` cannot tell a nested tmux from vim, `less` or `htop`, so a local shell with one of those open takes the same fallback until it exits (the pre-fix load, with its repaint duplicates). Shell FULL history is explicit-button-only; reaching the top during an ordinary wheel/touch gesture must not reset xterm and replay the multi-megabyte capture on its main thread. That gesture instead pulls a BOUNDED window of it (`?full=1&tail=<TERMINAL_TAIL_SIZE>`, so a capture beyond 1 MiB comes back `truncationReason: 'tail'` and the banner offers the rest), and skips the replay when the window holds no more rows than the browser already has. ⚠️ **That skip runs BEFORE the downgrade guard, and it never touches the banner state**: the guard reads "smaller than the browser" as "tmux has nothing more to give", true of an unbounded capture and false of a window cut at the tail size, so a bounded window that reached it marked the session `exhausted` and removed **Load full history** while tmux still held the rest; and re-labelling the banner from a skipped payload would call a terminal that holds all of a Load full history pull "the most recent 1 MiB". A skipped window that came back truncated puts the session on the 60 s cooldown (`_fullHistoryRepullUseless`), because it can never reach anything older than the browser shows and `tail` is applied AFTER the server's synchronous `capture-pane` of the whole history, so each ask costs every client an event-loop stall (about 1 s at 100k lines; measured capture details below); an untruncated one keeps the 4 s cooldown, since it is all of tmux's history and the next burst can add to it. Declining the gesture outright was a dead end: after any burst a shell pane held about one screen of browser scrollback, and the button renders only once a replay was truncated, so a young shell tab had no way back to history tmux still held. Other modes re-pull `full=1` only at the top of the local buffer, and pressing **Load full history** forces the request for any recoverably truncated session (`_maybeRefetchFullHistory`, 4s per-session gesture cooldown, in-flight + tab-switch guards, viewport position held across the replay); Shell full pulls are not retained in the tab cache, so the next switch stays bounded. Chunked replay enqueues 32 KiB pieces across safe yields, appends an xterm parse marker, then releases the live-output gate; output arriving after that release stays ordered behind the snapshot, and the marker callback supplies accurate parse timing. ⚠️ **How the load ENDS depends on where the payload came from**, and `_bufferLoadFinishOpts` (app.js) is the one place that decides it for all four fetch-and-write paths. A payload built from the server's accumulated byte history is current up to the response, so the events queued during the load already appear in it and stay DISCARDED; replaying them would duplicate output, most visibly Ink's cursor-up redraws. A pane capture (`mux-visible` or `mux-full-history`) is current only up to CAPTURE time, so `_finishBufferLoad` replays the queue from the response's own arrival timestamp (`since`) and the pre-capture events stay dropped. ⚠️ **A path that then restores a scroll position must re-take the sticky-scroll baseline** (`_syncStickyScrollBaseline`): the replay runs inside `chunkedTerminalWrite` before its promise resolves, with the terminal freshly reset, so `batchTerminalWrite` samples `_wasAtBottomBeforeWrite` as true and the next `flushPendingWrites` would scroll to the bottom over the restore. ⚠️ The cutoff is a client-side timestamp and the server broadcasts on a batch timer (8ms WebSocket, 16-50ms SSE), so a batch pending when the capture ran arrives after the response and replays although the capture holds it — bounded by one batch interval, and closable only server side by flushing that batch before the capture. Tests for the three: `test/terminal-flush-budget.test.ts` pins which sources flush, `test/terminal-buffer-flush.test.ts` pins the `since` cutoff and the baseline re-take, and `test/capture-load-window.browser.test.ts` drives both against a live server. Live output is separately one-chunk-in-flight: xterm's callback releases each 32/64 KiB write before the next is submitted, keeping the remainder in the app queue where the 128 KiB cap can observe it instead of hiding an unbounded backlog in xterm's private WriteBuffer. While WebSocket owns terminal I/O, parallel SSE terminal/output-recovery events are discarded before JSON parsing; fallback recovery is single-flight per active session so backpressure cannot start overlapping reset+replay cycles. The route exposes capture/prepare totals in `Server-Timing`, while `[TERMINAL-PERF]` separates TTFB, body/JSON, reset+parse and total time for both selection and on-demand full pulls; parse completion is not a browser compositor/GPU paint measurement. The re-pull exists because xterm's buffer is only a WINDOW onto tmux's history and two things shrink it: tmux coalesces bursty output into pane REPAINTS that overwrite rows instead of emitting linefeeds (measured: a 60-line burst added 1 row of browser scrollback and destroyed 34), and a tab switch replays only the visible frame. tmux's own history is intact throughout — the browser just has to ask for it again. Gesture-triggered rather than polling because at a 100k history limit the capture can be megabytes. ⚠️ **The capture ENDS with a cursor move back to the pane's own caret position** (`formatCursorRestore`, from the same `display-message` query the visible-frame path uses). The linear replay otherwise leaves the caret wherever the last character landed — the bottom-most row carrying text, which for an agent CLI is the status line — so the caret sat on the composer's border instead of its input line and every cursor-relative update the CLI sent afterwards was measured from the wrong row, until its next full redraw silently repaired it (that self-repair is why the report read as "it fixes itself as soon as Claude writes a line"). ⚠️ **The move is RELATIVE — up `rows - 1 - cursor_y`, then `\r`, then right `cursor_x` — never `CUP`.** `\x1b[<row>;<col>H` numbers rows from the top of the browser's screen, so it lands correctly only while the browser's row count equals `pane_height`, and nothing guarantees that: `resizeWindow` issues its tmux resize fire-and-forget and returns immediately, so a capture can be taken before a requested resize has applied, and `_onSessionNeedsRefresh` sends no resize at all. Counting up from the last replayed row anchors to the content both ends share. Restoring the cursor makes ROW ALIGNMENT load-bearing on this path: **no transform that can DELETE A LINE may run over a full-history capture**, because every deletion shifts the frame out from under the restored position. Four had accumulated — trailing blank rows stripped by `\n+$`, `stripInkRedrawBloat`, the `CLAUDE_BANNER_PATTERN` trim that cuts everything above the banner, and `LEADING_WHITESPACE_PATTERN` — each correct for a byte stream of successive frames and each wrong for a single rendered frame. ⚠️ **Those skips key on `isFullCapture`, meaning a capture actually came back — never on `?full=1` alone.** When `captureActivePaneBuffer` returns null (ENOBUFS, a timeout, a vanished pane, or a session with no mux at all) the reply falls back to `session.terminalBuffer`, which IS a byte stream and must still be stripped; gating on the query flag returned it whole, and a direct-PTY session takes that path on every first selection rather than only during an outage. ⚠️ A capture holding nothing visible (`hasVisibleContent`) returns `''`, because the caller reads an empty capture as "unavailable" and keeps its byte history — retaining trailing blank rows made an all-blank pane non-empty, which would have replaced real history with a blank screen from the server side, where `_replayWouldShrinkBuffer` cannot see it. ⚠️ **"One line per screen row" holds only where no row was hard-wrapped**: `-J` joins a wrapped row into its logical line (measured: a 100-character line in a 40-column pane captures as 10 lines against a 12-row pane), and the counts reconcile only once the browser xterm re-wraps at the same width — the same assumption `_estimateReplayRows` already documents. Tests: `test/tmux-capture-full-history.test.ts` covers the cursor move, the trim pairing and `hasVisibleContent`; `test/routes/session-routes.test.ts` covers a surviving blank first row, an unstripped byte-history fallback, and an empty capture leaving history intact. ⚠️ **The re-pull must never DOWNGRADE the buffer** (#205 round 2): the same reasoning that makes it a win for a shell pane makes it destructive for a repaint-mode CLI pane, where tmux keeps no history of its own (`history_size≈0` measured for a Claude pane) and the capture is roughly ONE frame while xterm may hold hundreds of rows of replayed frames — `_resetTerminalForReplay()` + rewrite then deletes history mid-scroll ("goes back a bit, repeats blocks, gets worse the further up I go"; measured A/B on a live pane: 341 rows → 42 with the guard off). `_replayWouldShrinkBuffer()` (terminal-ui.js) estimates the capture's rendered rows — escape sequences stripped, `capture-pane -J` re-wrapping accounted for — and the pull is skipped when that is more than one screen short of `buffer.active.length`. The one-screen tolerance matters: both sides are estimates (the buffer length counts trailing blank rows), so only a clear downgrade is refused. A refused session joins `_fullHistoryRepullUseless`, raising its cooldown from 4s to 60s so a hollow pane stops re-fetching megabytes on every scroll-up. Tests: `test/tmux-capture-full-history.test.ts`, `test/tmux-scrollback-eol.test.ts`, `test/terminal-scroll-routing.test.ts`, `test/terminal-flush-budget.test.ts`. -**Repair while reading (#814)** is a manual **Reload history** action inside the existing history banner on desktop and touch devices, enabled by default and toggleable per device in Settings → Terminal & Input → Scrolling & rendering (`historyReloadAction`). It is offered only for a marked non-shell active session while scrolled away from live output, not Docker or adopted (their local pane hosts a nested tmux client in the alternate screen, so `?full=1` returns one screen the downgrade guard refuses; remote sessions stay eligible, since the route splices the remote scrollback in), not detached, not owned by tiles, with no pull or buffer load in flight, no terminal load state for the session (a tab switch sets it before the buffer load opens), and no drop-recovery refresh owning the session (`_terminalRefreshOwner`, set for the whole fetch, before that refresh opens its buffer load). `_maybeRefetchFullHistory` returns early on that same owner, so Reload, Load full history and the top-of-buffer pull all stand aside instead of running a second capture whose download-time queue the refresh's own load would replace; the refresh re-syncs the action when it starts and when its `finally` releases the owner. `paneHistoryLines` is deliberately not consulted: it is recorded at the last load, so a session first opened empty keeps 0 after the very burst that opens the gap (#814). The bar is a polite live region (`role="status"`), but only the truncation notice is announced: a reload-only bar sets `aria-live="off"` before it re-renders, since it comes back on nearly every scroll-up in a busy tab, and its button stays reachable with Tab. Its × is labelled for what the bar carries: "Dismiss history notice" with the notice, "Dismiss Reload history" without it. A revealed truncation notice keeps its message and its **Load full history** control; Reload is appended only when the notice has no load control, or shown alone with a short missing-output message. When Reload is eligible, that **Load full history** control stands in for it and pulls with the content anchor (eligibility read at click time), so the reader keeps their line, and shares Reload's loading state, so the re-render the in-flight pull triggers keeps it on Loading… instead of bringing it back enabled; otherwise it keeps the top anchor and no loading state, so the bar still hides on a scroll back to live output. A reload-only × dismissal lasts until the mark is cleared by a successful `mux-full-history` replay, independently of the notice’s page-long dismissal. Pressing × while loading hides the bar immediately; the in-flight pull continues. Eligibility is cached per active session, with onScroll sampling coalesced to one animation frame on every device; unchanged eligibility never rebuilds the banner. Automatic history pulls and notice reveal stay top-only (#205). Live-output marking covers only live writes: a byte-history (`?tail=`) replay, for example after a burst in a background tab, never marks the session, so that gap relies on the top-of-buffer pull. The manual action forces a content-anchored pull, bypassing the gesture cooldown but retaining the downgrade guard. Any downgrade-refused pull hides Reload until the next successful `mux-full-history` replay; that refusal, not the cached history size, is what retires the action for a pane with no tmux history (fullscreen Claude). A manual reload answered by anything but `mux-full-history` (an empty response, or the byte-history fallback the route returns when the pane capture is blank or failed) retires it the same way, since only a mux replay clears the mark; a transient error envelope (`success: false`) leaves it available. A content anchor captures up to 64 visible rows, preserving indentation, and scores candidate alignments by matching viewport context. Each distinct nonblank row contributes at most one point, so repeated TUI borders cannot outvote a distinctive tool result. The best match must score at least 60% of the distinct rows and at least two of them, capped at the number of distinct rows, so a viewport with one distinct row (a lone tool result among blanks) matches on that row alone; it must also be unique within the search window. Equal-scoring copies are ambiguous, even when all furniture rows match or the distinctive tool row has disappeared; proximity to the expected position does not establish confidence. An isolated first-row match is not trusted: without confident, unambiguous context the old viewport index is retained, while readers already near live output retain their bottom distance. Search covers 4001 candidates from `expected - 4000 + rows` to `expected + rows` (at most 4064 cached line reads), leaning up because every row a reload fills in below the reader moves the reader's row up, while a capture with fewer rows below moves it down by at most the one screen the downgrade guard tolerates. Gaps up to `4000 - rows` rows therefore land exactly, including at xterm's scrollback cap, where the replay trims the top by the same number of rows. A wider gap puts the match outside the window: the restore keeps the old absolute index, which is right while the top of the buffer stays put but, at the cap, lands the reader the whole gap below their line. Live flushes use an xterm marker to track the reading row across scrollback trimming in O(1), and restore it only in the write callback; a marker the write disposed (its row trimmed, or scrollback erased by `ESC[3J` or RIS, which the narrow and middle strips keep) falls back to the absolute index instead of row 0; at-bottom sticky scroll is unchanged. Ordered, session-scoped travel during replay is applied with per-move clamping; a switched-to tab never donates travel. The notice is decided per recorded move, as a live scroll decides it: an upward move that reaches row 0 reveals the partial-history notice, a downward move that reaches live output retires it, and other moves leave the last decision standing, so reaching the top and then scrolling a few rows down still reveals it; a reload with no travel leaves the notice as it was. The buffer load opens BEFORE the fetch, so download-time output queues behind the replay instead of being overwritten. Non-replay exits flush the whole queue; replays retain the capture-header cutoff above. A blocked dropped-output recovery stores its session and current attempt, defers without consuming retries, and resumes only for the still-active session; a later drop for the same session during that load keeps the higher attempt, so the retry bound still holds. Only an actual `mux-full-history` replay clears the live-output mark and reload dismissal, and a newer live-write generation keeps them marked. The drop-recovery refresh (`_onSessionNeedsRefresh`) follows the same rule: it clears both after a completed replay of a `mux-full-history` capture, only while it still owns the active session and the live-output generation sampled before its fetch is unchanged; its `?tail=` fallback never clears them, and because that fallback means the full capture would shrink the buffer (the refusal signal), it retires the action under the same session and refresh-owner checks. The trade-off remains a full synchronous server capture (about 1 s: 1,068 ms median for `capture-pane -p -e -J -S -100000` over 100k lines of 120 characters, 12.1 MB), not a cheap automatic per-output repair. Tests: `test/shell-scroll-history-pull.test.ts`, `test/history-gap-repair.browser.test.ts`. +**Repair while reading (#814)** is a manual **Reload history** action inside the existing history banner on desktop and touch devices, enabled by default and toggleable per device in Settings → Terminal & Input → Scrolling & rendering (`historyReloadAction`). It is offered only for a marked non-shell active session while scrolled away from live output, not Docker or adopted (their local pane hosts a nested tmux client in the alternate screen, so `?full=1` returns one screen the downgrade guard refuses; remote sessions stay eligible, since the route splices the remote scrollback in), not detached, not owned by tiles, with no pull or buffer load in flight, no terminal load state for the session (a tab switch sets it before the buffer load opens), and no drop-recovery refresh owning the session (`_terminalRefreshOwner`, set for the whole fetch, before that refresh opens its buffer load). `_maybeRefetchFullHistory` returns early on that same owner, so Reload, Load full history and the top-of-buffer pull all stand aside instead of running a second capture whose download-time queue the refresh's own load would replace; the refresh re-syncs the action when it starts and when its `finally` releases the owner. `paneHistoryLines` is deliberately not consulted: it is recorded at the last load, so a session first opened empty keeps 0 after the very burst that opens the gap (#814). The bar is a polite live region (`role="status"`), but only the truncation notice is announced: a reload-only bar sets `aria-live="off"` before it re-renders, since it comes back on nearly every scroll-up in a busy tab, and its button stays reachable with Tab. Its × is labelled for what the bar carries: "Dismiss history notice" with the notice, "Dismiss Reload history" without it. A revealed truncation notice keeps its message and its **Load full history** control; Reload is appended only when the notice has no load control, or shown alone with a short missing-output message. When Reload is eligible, that **Load full history** control stands in for it and pulls with the content anchor (eligibility read at click time), so the reader keeps their line, and shares Reload's loading state, so the re-render the in-flight pull triggers keeps it on Loading… instead of bringing it back enabled; otherwise it keeps the top anchor and no loading state, so the bar still hides on a scroll back to live output. A reload-only × dismissal lasts until the mark is cleared by a successful `mux-full-history` replay, independently of the notice’s page-long dismissal. Pressing × while loading hides the bar immediately; the in-flight pull continues. Eligibility is cached per active session, with onScroll sampling coalesced to one animation frame on every device; unchanged eligibility never rebuilds the banner. Automatic history pulls and notice reveal stay top-only (#205). Live-output marking covers only live writes: a byte-history (`?tail=`) replay, for example after a burst in a background tab, never marks the session, so that gap relies on the top-of-buffer pull. The manual action forces a content-anchored pull, bypassing the gesture cooldown but retaining the downgrade guard. Any downgrade-refused pull hides Reload until the next successful `mux-full-history` replay; that refusal, not the cached history size, is what retires the action for a pane with no tmux history (fullscreen Claude). A manual reload answered by anything but `mux-full-history` (an empty response, or the byte-history fallback the route returns when the pane capture is blank or failed) retires it the same way, since only a mux replay clears the mark; a transient error envelope (`success: false`) leaves it available. A content anchor captures up to 64 visible rows, preserving indentation, and scores candidate alignments by matching viewport context. Each distinct nonblank row contributes at most one point, so repeated TUI borders cannot outvote a distinctive tool result. The best match must score at least 60% of the distinct rows and at least two of them, capped at the number of distinct rows, so a viewport with one distinct row (a lone tool result among blanks) matches on that row alone; it must also be unique within the search window. Equal-scoring copies are ambiguous, even when all furniture rows match or the distinctive tool row has disappeared; proximity to the expected position does not establish confidence. An isolated first-row match is not trusted: without confident, unambiguous context the old viewport index is retained, while readers already near live output retain their bottom distance. Search covers 4001 candidates from `expected - 4000 + rows` to `expected + rows` (at most 4064 cached line reads), leaning up because every row a reload fills in below the reader moves the reader's row up, while a capture with fewer rows below moves it down by at most the one screen the downgrade guard tolerates. Gaps up to `4000 - rows` rows therefore land exactly, including at xterm's scrollback cap, where the replay trims the top by the same number of rows. A wider gap puts the match outside the window: the restore keeps the old absolute index, which is right while the top of the buffer stays put but, at the cap, lands the reader the whole gap below their line. Live flushes use an xterm marker to track the reading row across scrollback trimming in O(1), and restore it only in the write callback; a marker the write disposed (its row trimmed, or scrollback erased by `ESC[3J`, which the narrow and middle strips keep) falls back to the absolute index instead of row 0, while RIS leaves the marker alive on its old line, which is the same index; at-bottom sticky scroll is unchanged. Ordered, session-scoped travel during replay is applied with per-move clamping; a switched-to tab never donates travel. The notice is decided per recorded move, as a live scroll decides it: an upward move that reaches row 0 reveals the partial-history notice, a downward move that reaches live output retires it, and other moves leave the last decision standing, so reaching the top and then scrolling a few rows down still reveals it; a reload with no travel leaves the notice as it was. The buffer load opens BEFORE the fetch, so download-time output queues behind the replay instead of being overwritten. Non-replay exits flush the whole queue; replays retain the capture-header cutoff above. A blocked dropped-output recovery stores its session and current attempt, defers without consuming retries, and resumes only for the still-active session; a later drop for the same session during that load keeps the higher attempt, so the retry bound still holds. Only an actual `mux-full-history` replay clears the live-output mark and reload dismissal, and a newer live-write generation keeps them marked. The drop-recovery refresh (`_onSessionNeedsRefresh`) follows the same rule: it clears both after a completed replay of a `mux-full-history` capture, only while it still owns the active session and the live-output generation sampled before its fetch is unchanged; its `?tail=` fallback never clears them, and because that fallback means the full capture would shrink the buffer (the refusal signal), it retires the action under the same session and refresh-owner checks. The trade-off remains a full synchronous server capture (about 1 s: 1,068 ms median for `capture-pane -p -e -J -S -100000` over 100k lines of 120 characters, 12.1 MB), not a cheap automatic per-output repair. Tests: `test/shell-scroll-history-pull.test.ts`, `test/history-gap-repair.browser.test.ts`. **The partial-history notice is lazy and pane-gated** (`computeHistoryTruncationNotice()` in constants.js, `_renderHistoryTruncationBanner()` / `_setHistoryNoticeRevealed()` in app.js). `truncated` on a terminal response measures the server's BYTE stream, which is not what `full=1` can return: for a pane with no tmux scrollback (fullscreen claude starts in the alternate screen and never writes to the main grid, so `#{history_size}` is 0) the bytes a tail cut drops are old repaint frames. Measured on prod 2026-10-10, every claude pane: the tab-switch tail cut a 1.2 to 6.2 MB stream to 1 MiB, the local scrollback that tail replays into is repeats of the same frames (one pane: 450 non-blank rows, 44 unique, one row 33 times), and `full=1` returned 1 to 5 KB, so **Load full history** could only end in the downgrade refusal while the banner promised "4.8 MB more". The capture therefore reads `#{history_size}` in the SAME `display-message` as the cursor (no extra tmux call), the route returns it as `paneHistoryLines` (absent when the body is not a capture, and for a remote SSH session, whose local pane hosts the remote tmux client and always reports 0 while `full=1` reads the remote history), and a reported 0 hides the notice in every state; a positive count replaces the byte gap in the message. ⚠️ Key the notice decision on `history_size`, never on `alternate_on`: a shell running `less` is in the alternate screen with its whole history still retained (measured, 99,972 rows) and `full=1` returns all of it. The one place `alternate_on` decides is a shell's AUTOMATIC load (`alt=recording`, see Full-scrollback replay): there the question is whether the capture holds the scrollback a nested tmux client keeps in its byte recording, not whether a pull can return more. The notice is also LAZY: it appears only after a wheel/touch gesture reaches the top of the browser buffer and the pull that gesture started has settled (`_maybeLoadMoreHistoryOnScroll`), goes away when a downward gesture is back at live output or the tab switches (`selectSession` nulls `_historyNoticeRevealedFor` before repainting), and its × is sticky per session until reload (`_historyNoticeDismissed`). Tests: `test/history-truncation-notice.test.ts`, `test/history-notice-reveal.test.ts`. diff --git a/src/web/public/terminal-ui.js b/src/web/public/terminal-ui.js index 0b159508..09a94b54 100644 --- a/src/web/public/terminal-ui.js +++ b/src/web/public/terminal-ui.js @@ -4792,9 +4792,11 @@ Object.assign(CodemanApp.prototype, { // reasserted. (The synchronous version passed its regression test only // because the test's write mock moved the viewport synchronously.) // A marker is disposed when its row is trimmed off a full scrollback, - // but also when the stream itself erases scrollback (`ESC[3J`, RIS), + // but also when the stream itself erases scrollback with `ESC[3J`, // which the narrow and middle strips keep. Fall back to the absolute // index then, as before markers, rather than sending the reader to row 0. + // (RIS does not dispose it: xterm swaps in a new buffer and the marker + // stays on its old line, which is the same index as this fallback.) const viewportY = viewportMarker && !viewportMarker.isDisposed ? viewportMarker.line : preserveViewportY; viewportMarker?.dispose(); this._restoreTerminalViewport(viewportY, flushSessionId); From 58a5ef51bc3363aa693176353fe3198b0e00e674 Mon Sep 17 00:00:00 2001 From: Hadrien Kerlero <199662351+HadrienKerlero@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:37:12 +0100 Subject: [PATCH 23/23] docs(changeset): drop internal recovery bookkeeping from the release note (#814) - The deferred dropped-output recovery's retry attempt is internal; the release note no longer mentions it. --- .changeset/814-history-repair-while-reading.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/814-history-repair-while-reading.md b/.changeset/814-history-repair-while-reading.md index 5d89e082..8845526e 100644 --- a/.changeset/814-history-repair-while-reading.md +++ b/.changeset/814-history-repair-while-reading.md @@ -2,6 +2,6 @@ 'aicodeman': patch --- -Fix missing terminal history above live output in agent sessions (seen with OMP) with a manual Reload history action in the existing history banner on desktop and mobile. The action preserves the text being read and output arriving during the download, and can be disabled per device in Settings > Terminal & Input > Scrolling & rendering. Ordinary scrolling only pulls history at the top; deferred dropped-output recovery retains its retry attempt. +Fix missing terminal history above live output in agent sessions (seen with OMP) with a manual Reload history action in the existing history banner on desktop and mobile. The action preserves the text being read and output arriving during the download, and can be disabled per device in Settings > Terminal & Input > Scrolling & rendering. Ordinary scrolling only pulls history at the top. While you are scrolled up, new output no longer moves the text you are reading once the terminal's scrollback is full. This applies to every session type, whether or not the Reload history setting is on.