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] 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 `: ` 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';