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