diff --git a/.changeset/814-history-repair-while-reading.md b/.changeset/814-history-repair-while-reading.md new file mode 100644 index 00000000..8845526e --- /dev/null +++ b/.changeset/814-history-repair-while-reading.md @@ -0,0 +1,7 @@ +--- +'aicodeman': patch +--- + +Fix missing terminal history above live output in agent sessions (seen with OMP) with a manual Reload history action in the existing history banner on desktop and mobile. The action preserves the text being read and output arriving during the download, and can be disabled per device in Settings > Terminal & Input > Scrolling & rendering. Ordinary scrolling only pulls history at the top. + +While you are scrolled up, new output no longer moves the text you are reading once the terminal's scrollback is full. This applies to every session type, whether or not the Reload history setting is on. diff --git a/CLAUDE.md b/CLAUDE.md index c158bd5c..af9d54c9 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -228,7 +228,7 @@ Codeman is a Claude Code session manager with web interface and autonomous Ralph **Circuit breakers**: the Ralph breaker prevents respawn thrashing (`CLOSED` → `HALF_OPEN` → `OPEN`; reset via `/api/sessions/:id/ralph-circuit-breaker/reset`). **Distinct: the PTY-exit breaker** (`session-pty-exit-breaker.ts`) trips after repeated rapid PTY exits and blocks auto-restarts. ⚠️ It resets ONLY via an explicit `{clearBreaker:true}` body on `POST /api/sessions/:id/interactive`; the frontend's auto-reattach in `selectSession()` sends no body and must never clear it. → [architecture-invariants#circuit-breakers-ralph-and-pty-exit](docs/architecture-invariants.md#circuit-breakers-ralph-and-pty-exit) -**Full-scrollback replay**: `GET /api/sessions/:id/terminal?full=1` returns the whole tmux scrollback ALONE (`source='mux-full-history'`), superseding the byte buffer. First load of each non-shell TUI session requests it (`_fullHistoryLoaded`); Shell selection, drop recovery, clear and a tile's load use `SHELL_LOAD_QUERY` (constants.js), a bounded window of tmux's RENDERED history (`?full=1&tail=1MiB&alt=recording&lines=10000`), never the raw byte recording, whose full-screen repaints replayed at another pane height push copies of their top row into scrollback; the route reports a client `lines=` bound below the history ceiling that left lines in tmux as `truncationReason: 'tail'`, and `alt=recording` falls back to the visible frame over the tailed byte recording when the pane is in the alternate screen (a nested tmux in a remote or Docker case keeps no tmux history; vim/less take it too while open). A Shell scroll-to-top pulls a bounded `?full=1&tail=` window (a window no longer than the browser's buffer is skipped before the downgrade guard, so it never marks the session exhausted); the unbounded pull stays behind **Load full history**. A Shell split-pane Pane B has its own copy of the bounded pull against its own xterm (`TerminalTile._pullHistory`, terminal-tile.js); keep the two in step. → [architecture-invariants#split-pane-sessions](docs/architecture-invariants.md#split-pane-sessions) ⚠️ The capture ends with a RELATIVE cursor move back to the pane's caret (never `CUP`), so no line-deleting transform may run over it; those skips key on `isFullCapture`, never on `?full=1` alone. ⚠️ A re-pull must never shrink the buffer (`_replayWouldShrinkBuffer()`). ⚠️ `captureCols`/`captureRows` are absent when no frame was positioned: test `Number.isFinite`, never truthiness. ⚠️ A frame dropped at the 128 KiB render cap MUST be recovered, and the recovery verifies itself: `_scheduleDroppedOutputRecovery` re-arms (bounded by `DROP_RECOVERY_MAX_ATTEMPTS`) while `_onSessionNeedsRefresh` reports no repaint, but never after a capture-fetch `'deadline'`. → [architecture-invariants#full-scrollback-replay](docs/architecture-invariants.md#full-scrollback-replay) +**Full-scrollback replay**: `GET /api/sessions/:id/terminal?full=1` returns the whole tmux scrollback ALONE (`source='mux-full-history'`), superseding the byte buffer. First load of each non-shell TUI session requests it (`_fullHistoryLoaded`); Shell selection, drop recovery, clear and a tile's load use `SHELL_LOAD_QUERY` (constants.js), a bounded window of tmux's RENDERED history (`?full=1&tail=1MiB&alt=recording&lines=10000`), never the raw byte recording, whose full-screen repaints replayed at another pane height push copies of their top row into scrollback; the route reports a client `lines=` bound below the history ceiling that left lines in tmux as `truncationReason: 'tail'`, and `alt=recording` falls back to the visible frame over the tailed byte recording when the pane is in the alternate screen (a nested tmux in a remote or Docker case keeps no tmux history; vim/less take it too while open). A Shell scroll-to-top pulls a bounded `?full=1&tail=` window (a window no longer than the browser's buffer is skipped before the downgrade guard, so it never marks the session exhausted); the unbounded pull stays behind **Load full history**. A Shell split-pane Pane B has its own copy of the bounded pull against its own xterm (`TerminalTile._pullHistory`, terminal-tile.js); keep the two in step. → [architecture-invariants#split-pane-sessions](docs/architecture-invariants.md#split-pane-sessions) ⚠️ The capture ends with a RELATIVE cursor move back to the pane's caret (never `CUP`), so no line-deleting transform may run over it; those skips key on `isFullCapture`, never on `?full=1` alone. ⚠️ A re-pull must never shrink the buffer (`_replayWouldShrinkBuffer()`). ⚠️ `captureCols`/`captureRows` are absent when no frame was positioned: test `Number.isFinite`, never truthiness. ⚠️ A frame dropped at the 128 KiB render cap MUST be recovered, and the recovery verifies itself: `_scheduleDroppedOutputRecovery` re-arms (bounded by `DROP_RECOVERY_MAX_ATTEMPTS`) while `_onSessionNeedsRefresh` reports no repaint, but never after a capture-fetch `'deadline'`. ⚠️ **Reload history** (#814, manual early repair; rules in the invariants paragraph "Repair while reading"): only a `mux-full-history` replay whose live-output generation is unchanged since before its fetch clears `_liveOutputSinceFullPull` and `_historyReloadDismissed`; a refused or non-mux answer to a manual reload retires the action until then; and the buffer load opens BEFORE the fetch, so download-time output queues behind the replay. → [architecture-invariants#full-scrollback-replay](docs/architecture-invariants.md#full-scrollback-replay) **Terminal scrollback strip + wheel/touch forwarding**: codex/claude/gemini get the FULL strip (alt-screen, `3J`, mouse DECSETs); tmux-backed opencode, copilot and pi get the MIDDLE strip (alt-screen toggles + mouse DECSETs, `3J` kept); every other tmux-backed mode (shell/antigravity/grok/deepseek/omp) gets the NARROW strip (alt-screen toggles only). Table: `CliCapabilities.altScreen` JSDoc, pinned in test/claude-scrollback-strip.test.ts. ⚠️ Gated on `useMux`: direct-PTY sessions must keep the alt screen. Wheel and touch forward only with observed `cliMouseTracking`: **Claude ≥ 2.1.187, tracked Codex, tracked Copilot, or tracked Pi**. Which CLIs forward is the registry's `wheelForward`, published as `window.__codemanWheelForward` and never an id list in the gate, so a custom `clis.json` entry opts in with it plus `altScreen: 'strip-mux-and-mouse'` (`docs/cli-registry.md`). Codex 0.163.0 fullscreen was measured with `alternate_on=1`, `mouse_any_flag=1`: one SGR report moves one transcript row; see the fresh measurement in architecture-invariants. Inline/untracked Codex retains local history or the capability-gated paging fallback. Copilot has no version gate; a stale/false tracking flag falls back to PageUp/PageDown. Pi has no version gate either, and is fullscreen by default since 1.0.0: it enables tracking once at start, so the flag is what survives a tab switch or reload (xterm's own mode does not). ⚠️ Pi deliberately has no `transcriptPageKeys`: its `tuiMode: regular` binds those keys to the editor, so paging there moves a draft's caret. Touch alone has one more branch (`_shouldForwardTouchToApp`): in any mode, a drag also forwards as SGR wheel reports while xterm ITSELF tracks the mouse with SGR encoding (an app in the pane asked for it; a tracking mode other than `x10` and `coreMouseService.activeEncoding === 'SGR'`, so DEFAULT, X10 and SGR-pixel apps fail closed), because xterm encodes a wheel there but the touch listeners consume the drag. ⚠️ `getClaudeCliVersion()` must never cache a FAILED probe. ⚠️ Hand-report clicks only while the CLI has mouse tracking on: `_shouldReportMouseToCli()` gates all three report sites on `cliMouseTracking` (from `_recordStrippedMouseMode()`, session.ts), or a plain shell prints the reports as literal text. ⚠️ A `TerminalTile` (grid tile, split Pane B) forwards the wheel as SGR reports, pages it and reports clicks through these SAME gates with itself as the target (its terminal, its session, never `activeSessionId`), and scrolls Shift+wheel itself (xterm makes it a horizontal no-op); never copy the mode lists into terminal-tile.js. ⚠️ The hollow-buffer PageUp/PageDown fallback (`_maybePageCliTranscript`) stands down when the last capture reported tmux scrollback (`paneHistoryLines` > 0: a tail replayed after a server restart carries only the attach repaint), so the gesture scrolls locally and the scroll-to-top pull loads `full=1`; 0 and unknown keep paging. Read `_logScrollRouting()` before diagnosing a scroll report. → [architecture-invariants#terminal-scrollback-strip-flavors-and-wheeltouch-forwarding](docs/architecture-invariants.md#terminal-scrollback-strip-flavors-and-wheeltouch-forwarding) **Detached start + service install**: `codeman web -d` relaunches the same entry script `detached:true` (setsid); `nohup` is not what makes it survive. ⚠️ Both `-d` and `service install` must REFUSE when a server is already up on this data dir (pidfile + `/api/status` probe), or a second instance attaches to the first one's live sessions. ⚠️ Never report success not observed: poll `/api/status` until the child answers or dies. `--stop` must verify the pid still looks like Codeman (`ps -o command=`) before signalling. Unit/label names live only in `config/service-names.ts`. `service install` bakes the installing shell's PATH into the unit and never writes `CODEMAN_PASSWORD` into it. → [architecture-invariants#detached-start-and-service-install](docs/architecture-invariants.md#detached-start-and-service-install) diff --git a/config/test-suites.ts b/config/test-suites.ts index ef921f98..ed32b76d 100644 --- a/config/test-suites.ts +++ b/config/test-suites.ts @@ -41,6 +41,7 @@ export const BROWSER_TEST_GLOBS = [ 'test/terminal-keycode229-recovery.browser.test.ts', 'test/ios-native-input.browser.test.ts', 'test/capture-load-window.browser.test.ts', + 'test/history-gap-repair.browser.test.ts', 'test/capture-geometry-retry.browser.test.ts', 'test/codex-predictive-echo.test.ts', // also needs a real codex binary 'test/split-pane-terminal.browser.test.ts', diff --git a/docs/architecture-invariants.md b/docs/architecture-invariants.md index 501a2978..99dbe9cc 100644 --- a/docs/architecture-invariants.md +++ b/docs/architecture-invariants.md @@ -253,7 +253,9 @@ Further detail: the `: ` form (`w3-myapp: fix the login redirect` ### Full-scrollback replay -**Full-scrollback replay** (COD-164/#148, reworked for #205): `GET /api/sessions/:id/terminal?full=1` returns the ENTIRE tmux scrollback (capture-pane `-e -S -<lines>` bounded by the configured history limit, explicit `maxBuffer` from the terminal-history config, early byte-cap before normalization, CRLF-normalized for shell panes). On success the capture is returned ALONE (`source='mux-full-history'` — it supersedes the byte buffer; no duplication). The first load of each non-shell TUI session per page requests `full=1` (`_fullHistoryLoaded` Set in app.js — the old one-shot `_initialFullBufferLoad` flag was consumed by whichever tab auto-selected, leaving every other TUI tab one frame of history). Shell sessions instead load a bounded window of tmux's RENDERED history on every selection, automatic drop recovery, clear and tile load (`SHELL_LOAD_QUERY` in constants.js: `?full=1&tail=1MiB&lines=10000&alt=recording`): a 100k-line shell capture can be tens of MiB, and automatically parsing it makes tab-switch latency scale with the entire session (`lines=` bounds the synchronous capture-pane, about 8 ms per 1000 lines). They never replay the raw byte recording ahead of the visible frame any more: it holds full-screen repaints (an ssh'd tmux, `less`, any TUI) drawn for the pane height of the moment, and replayed into a terminal of another height each repaint's last newline scrolls its top row into scrollback, so one line tmux holds once showed up dozens of times. Because `lines=` is shallower than xterm's scrollback, the route reports a cut: the capture's `display-message` query also reads `#{history_size}` (`PaneCaptureOptions.capturedHistoryLines`, the same field the route reports as `paneHistoryLines`), and a full capture whose CLIENT bound (`lines=` below the configured `tmuxHistoryLimit`) left lines in tmux comes back `truncated`, `truncationReason: 'tail'`. ⚠️ Only a client bound below the ceiling counts: a request without `lines=` is bounded by the ceiling itself, and on tmux before 3.7 a live pane can hold more than a lowered ceiling, which no request can read. ⚠️ **A pane in the alternate screen keeps no tmux history**, and a nested tmux client (remote SSH and Docker cases, or `tmux`/`ssh -t host tmux` run by hand) holds its pane there, so its full capture is one screen. The same query reads `#{alternate_on}` (`capturedAlternateOn`), and a request carrying `alt=recording` (only `SHELL_LOAD_QUERY`) is then answered the old way, the visible frame over the tailed byte recording, which still carries the scrollback; agents, scroll pulls and **Load full history** never send it. `#{alternate_on}` cannot tell a nested tmux from vim, `less` or `htop`, so a local shell with one of those open takes the same fallback until it exits (the pre-fix load, with its repaint duplicates). Shell FULL history is explicit-button-only; reaching the top during an ordinary wheel/touch gesture must not reset xterm and replay the multi-megabyte capture on its main thread. That gesture instead pulls a BOUNDED window of it (`?full=1&tail=<TERMINAL_TAIL_SIZE>`, so a capture beyond 1 MiB comes back `truncationReason: 'tail'` and the banner offers the rest), and skips the replay when the window holds no more rows than the browser already has. ⚠️ **That skip runs BEFORE the downgrade guard, and it never touches the banner state**: the guard reads "smaller than the browser" as "tmux has nothing more to give", true of an unbounded capture and false of a window cut at the tail size, so a bounded window that reached it marked the session `exhausted` and removed **Load full history** while tmux still held the rest; and re-labelling the banner from a skipped payload would call a terminal that holds all of a Load full history pull "the most recent 1 MiB". A skipped window that came back truncated puts the session on the 60 s cooldown (`_fullHistoryRepullUseless`), because it can never reach anything older than the browser shows and `tail` is applied AFTER the server's synchronous `capture-pane` of the whole history, so each ask costs every client an event-loop stall (about 0.3 s at 100k lines); an untruncated one keeps the 4 s cooldown, since it is all of tmux's history and the next burst can add to it. Declining the gesture outright was a dead end: after any burst a shell pane held about one screen of browser scrollback, and the button renders only once a replay was truncated, so a young shell tab had no way back to history tmux still held. Other modes may still re-pull `full=1` at the TOP, and pressing **Load full history** forces the request for any recoverably truncated session (`_maybeRefetchFullHistory`, 4s per-session gesture cooldown, in-flight + tab-switch guards, viewport position held across the replay); Shell full pulls are not retained in the tab cache, so the next switch stays bounded. Chunked replay enqueues 32 KiB pieces across safe yields, appends an xterm parse marker, then releases the live-output gate; output arriving after that release stays ordered behind the snapshot, and the marker callback supplies accurate parse timing. ⚠️ **How the load ENDS depends on where the payload came from**, and `_bufferLoadFinishOpts` (app.js) is the one place that decides it for all four fetch-and-write paths. A payload built from the server's accumulated byte history is current up to the response, so the events queued during the load already appear in it and stay DISCARDED; replaying them would duplicate output, most visibly Ink's cursor-up redraws. A pane capture (`mux-visible` or `mux-full-history`) is current only up to CAPTURE time, so `_finishBufferLoad` replays the queue from the response's own arrival timestamp (`since`) and the pre-capture events stay dropped. ⚠️ **A path that then restores a scroll position must re-take the sticky-scroll baseline** (`_syncStickyScrollBaseline`): the replay runs inside `chunkedTerminalWrite` before its promise resolves, with the terminal freshly reset, so `batchTerminalWrite` samples `_wasAtBottomBeforeWrite` as true and the next `flushPendingWrites` would scroll to the bottom over the restore. ⚠️ The cutoff is a client-side timestamp and the server broadcasts on a batch timer (8ms WebSocket, 16-50ms SSE), so a batch pending when the capture ran arrives after the response and replays although the capture holds it — bounded by one batch interval, and closable only server side by flushing that batch before the capture. Tests for the three: `test/terminal-flush-budget.test.ts` pins which sources flush, `test/terminal-buffer-flush.test.ts` pins the `since` cutoff and the baseline re-take, and `test/capture-load-window.browser.test.ts` drives both against a live server. Live output is separately one-chunk-in-flight: xterm's callback releases each 32/64 KiB write before the next is submitted, keeping the remainder in the app queue where the 128 KiB cap can observe it instead of hiding an unbounded backlog in xterm's private WriteBuffer. While WebSocket owns terminal I/O, parallel SSE terminal/output-recovery events are discarded before JSON parsing; fallback recovery is single-flight per active session so backpressure cannot start overlapping reset+replay cycles. The route exposes capture/prepare totals in `Server-Timing`, while `[TERMINAL-PERF]` separates TTFB, body/JSON, reset+parse and total time for both selection and on-demand full pulls; parse completion is not a browser compositor/GPU paint measurement. The re-pull exists because xterm's buffer is only a WINDOW onto tmux's history and two things shrink it: tmux coalesces bursty output into pane REPAINTS that overwrite rows instead of emitting linefeeds (measured: a 60-line burst added 1 row of browser scrollback and destroyed 34), and a tab switch replays only the visible frame. tmux's own history is intact throughout — the browser just has to ask for it again. On-demand rather than automatic because at a 100k history limit the capture can be megabytes. ⚠️ **The capture ENDS with a cursor move back to the pane's own caret position** (`formatCursorRestore`, from the same `display-message` query the visible-frame path uses). The linear replay otherwise leaves the caret wherever the last character landed — the bottom-most row carrying text, which for an agent CLI is the status line — so the caret sat on the composer's border instead of its input line and every cursor-relative update the CLI sent afterwards was measured from the wrong row, until its next full redraw silently repaired it (that self-repair is why the report read as "it fixes itself as soon as Claude writes a line"). ⚠️ **The move is RELATIVE — up `rows - 1 - cursor_y`, then `\r`, then right `cursor_x` — never `CUP`.** `\x1b[<row>;<col>H` numbers rows from the top of the browser's screen, so it lands correctly only while the browser's row count equals `pane_height`, and nothing guarantees that: `resizeWindow` issues its tmux resize fire-and-forget and returns immediately, so a capture can be taken before a requested resize has applied, and `_onSessionNeedsRefresh` sends no resize at all. Counting up from the last replayed row anchors to the content both ends share. Restoring the cursor makes ROW ALIGNMENT load-bearing on this path: **no transform that can DELETE A LINE may run over a full-history capture**, because every deletion shifts the frame out from under the restored position. Four had accumulated — trailing blank rows stripped by `\n+$`, `stripInkRedrawBloat`, the `CLAUDE_BANNER_PATTERN` trim that cuts everything above the banner, and `LEADING_WHITESPACE_PATTERN` — each correct for a byte stream of successive frames and each wrong for a single rendered frame. ⚠️ **Those skips key on `isFullCapture`, meaning a capture actually came back — never on `?full=1` alone.** When `captureActivePaneBuffer` returns null (ENOBUFS, a timeout, a vanished pane, or a session with no mux at all) the reply falls back to `session.terminalBuffer`, which IS a byte stream and must still be stripped; gating on the query flag returned it whole, and a direct-PTY session takes that path on every first selection rather than only during an outage. ⚠️ A capture holding nothing visible (`hasVisibleContent`) returns `''`, because the caller reads an empty capture as "unavailable" and keeps its byte history — retaining trailing blank rows made an all-blank pane non-empty, which would have replaced real history with a blank screen from the server side, where `_replayWouldShrinkBuffer` cannot see it. ⚠️ **"One line per screen row" holds only where no row was hard-wrapped**: `-J` joins a wrapped row into its logical line (measured: a 100-character line in a 40-column pane captures as 10 lines against a 12-row pane), and the counts reconcile only once the browser xterm re-wraps at the same width — the same assumption `_estimateReplayRows` already documents. Tests: `test/tmux-capture-full-history.test.ts` covers the cursor move, the trim pairing and `hasVisibleContent`; `test/routes/session-routes.test.ts` covers a surviving blank first row, an unstripped byte-history fallback, and an empty capture leaving history intact. ⚠️ **The re-pull must never DOWNGRADE the buffer** (#205 round 2): the same reasoning that makes it a win for a shell pane makes it destructive for a repaint-mode CLI pane, where tmux keeps no history of its own (`history_size≈0` measured for a Claude pane) and the capture is roughly ONE frame while xterm may hold hundreds of rows of replayed frames — `_resetTerminalForReplay()` + rewrite then deletes history mid-scroll ("goes back a bit, repeats blocks, gets worse the further up I go"; measured A/B on a live pane: 341 rows → 42 with the guard off). `_replayWouldShrinkBuffer()` (terminal-ui.js) estimates the capture's rendered rows — escape sequences stripped, `capture-pane -J` re-wrapping accounted for — and the pull is skipped when that is more than one screen short of `buffer.active.length`. The one-screen tolerance matters: both sides are estimates (the buffer length counts trailing blank rows), so only a clear downgrade is refused. A refused session joins `_fullHistoryRepullUseless`, raising its cooldown from 4s to 60s so a hollow pane stops re-fetching megabytes on every scroll-up. Tests: `test/tmux-capture-full-history.test.ts`, `test/tmux-scrollback-eol.test.ts`, `test/terminal-scroll-routing.test.ts`, `test/terminal-flush-budget.test.ts`. +**Full-scrollback replay** (COD-164/#148, reworked for #205): `GET /api/sessions/:id/terminal?full=1` returns the ENTIRE tmux scrollback (capture-pane `-e -S -<lines>` bounded by the configured history limit, explicit `maxBuffer` from the terminal-history config, early byte-cap before normalization, CRLF-normalized for shell panes). On success the capture is returned ALONE (`source='mux-full-history'` — it supersedes the byte buffer; no duplication). The first load of each non-shell TUI session per page requests `full=1` (`_fullHistoryLoaded` Set in app.js — the old one-shot `_initialFullBufferLoad` flag was consumed by whichever tab auto-selected, leaving every other TUI tab one frame of history). Shell sessions instead load a bounded window of tmux's RENDERED history on every selection, automatic drop recovery, clear and tile load (`SHELL_LOAD_QUERY` in constants.js: `?full=1&tail=1MiB&lines=10000&alt=recording`): a 100k-line shell capture can be tens of MiB, and automatically parsing it makes tab-switch latency scale with the entire session (`lines=` bounds the synchronous capture-pane, about 8 ms per 1000 lines). They never replay the raw byte recording ahead of the visible frame any more: it holds full-screen repaints (an ssh'd tmux, `less`, any TUI) drawn for the pane height of the moment, and replayed into a terminal of another height each repaint's last newline scrolls its top row into scrollback, so one line tmux holds once showed up dozens of times. Because `lines=` is shallower than xterm's scrollback, the route reports a cut: the capture's `display-message` query also reads `#{history_size}` (`PaneCaptureOptions.capturedHistoryLines`, the same field the route reports as `paneHistoryLines`), and a full capture whose CLIENT bound (`lines=` below the configured `tmuxHistoryLimit`) left lines in tmux comes back `truncated`, `truncationReason: 'tail'`. ⚠️ Only a client bound below the ceiling counts: a request without `lines=` is bounded by the ceiling itself, and on tmux before 3.7 a live pane can hold more than a lowered ceiling, which no request can read. ⚠️ **A pane in the alternate screen keeps no tmux history**, and a nested tmux client (remote SSH and Docker cases, or `tmux`/`ssh -t host tmux` run by hand) holds its pane there, so its full capture is one screen. The same query reads `#{alternate_on}` (`capturedAlternateOn`), and a request carrying `alt=recording` (only `SHELL_LOAD_QUERY`) is then answered the old way, the visible frame over the tailed byte recording, which still carries the scrollback; agents, scroll pulls and **Load full history** never send it. `#{alternate_on}` cannot tell a nested tmux from vim, `less` or `htop`, so a local shell with one of those open takes the same fallback until it exits (the pre-fix load, with its repaint duplicates). Shell FULL history is explicit-button-only; reaching the top during an ordinary wheel/touch gesture must not reset xterm and replay the multi-megabyte capture on its main thread. That gesture instead pulls a BOUNDED window of it (`?full=1&tail=<TERMINAL_TAIL_SIZE>`, so a capture beyond 1 MiB comes back `truncationReason: 'tail'` and the banner offers the rest), and skips the replay when the window holds no more rows than the browser already has. ⚠️ **That skip runs BEFORE the downgrade guard, and it never touches the banner state**: the guard reads "smaller than the browser" as "tmux has nothing more to give", true of an unbounded capture and false of a window cut at the tail size, so a bounded window that reached it marked the session `exhausted` and removed **Load full history** while tmux still held the rest; and re-labelling the banner from a skipped payload would call a terminal that holds all of a Load full history pull "the most recent 1 MiB". A skipped window that came back truncated puts the session on the 60 s cooldown (`_fullHistoryRepullUseless`), because it can never reach anything older than the browser shows and `tail` is applied AFTER the server's synchronous `capture-pane` of the whole history, so each ask costs every client an event-loop stall (about 1 s at 100k lines; measured capture details below); an untruncated one keeps the 4 s cooldown, since it is all of tmux's history and the next burst can add to it. Declining the gesture outright was a dead end: after any burst a shell pane held about one screen of browser scrollback, and the button renders only once a replay was truncated, so a young shell tab had no way back to history tmux still held. Other modes re-pull `full=1` only at the top of the local buffer, and pressing **Load full history** forces the request for any recoverably truncated session (`_maybeRefetchFullHistory`, 4s per-session gesture cooldown, in-flight + tab-switch guards, viewport position held across the replay); Shell full pulls are not retained in the tab cache, so the next switch stays bounded. Chunked replay enqueues 32 KiB pieces across safe yields, appends an xterm parse marker, then releases the live-output gate; output arriving after that release stays ordered behind the snapshot, and the marker callback supplies accurate parse timing. ⚠️ **How the load ENDS depends on where the payload came from**, and `_bufferLoadFinishOpts` (app.js) is the one place that decides it for all four fetch-and-write paths. A payload built from the server's accumulated byte history is current up to the response, so the events queued during the load already appear in it and stay DISCARDED; replaying them would duplicate output, most visibly Ink's cursor-up redraws. A pane capture (`mux-visible` or `mux-full-history`) is current only up to CAPTURE time, so `_finishBufferLoad` replays the queue from the response's own arrival timestamp (`since`) and the pre-capture events stay dropped. ⚠️ **A path that then restores a scroll position must re-take the sticky-scroll baseline** (`_syncStickyScrollBaseline`): the replay runs inside `chunkedTerminalWrite` before its promise resolves, with the terminal freshly reset, so `batchTerminalWrite` samples `_wasAtBottomBeforeWrite` as true and the next `flushPendingWrites` would scroll to the bottom over the restore. ⚠️ The cutoff is a client-side timestamp and the server broadcasts on a batch timer (8ms WebSocket, 16-50ms SSE), so a batch pending when the capture ran arrives after the response and replays although the capture holds it — bounded by one batch interval, and closable only server side by flushing that batch before the capture. Tests for the three: `test/terminal-flush-budget.test.ts` pins which sources flush, `test/terminal-buffer-flush.test.ts` pins the `since` cutoff and the baseline re-take, and `test/capture-load-window.browser.test.ts` drives both against a live server. Live output is separately one-chunk-in-flight: xterm's callback releases each 32/64 KiB write before the next is submitted, keeping the remainder in the app queue where the 128 KiB cap can observe it instead of hiding an unbounded backlog in xterm's private WriteBuffer. While WebSocket owns terminal I/O, parallel SSE terminal/output-recovery events are discarded before JSON parsing; fallback recovery is single-flight per active session so backpressure cannot start overlapping reset+replay cycles. The route exposes capture/prepare totals in `Server-Timing`, while `[TERMINAL-PERF]` separates TTFB, body/JSON, reset+parse and total time for both selection and on-demand full pulls; parse completion is not a browser compositor/GPU paint measurement. The re-pull exists because xterm's buffer is only a WINDOW onto tmux's history and two things shrink it: tmux coalesces bursty output into pane REPAINTS that overwrite rows instead of emitting linefeeds (measured: a 60-line burst added 1 row of browser scrollback and destroyed 34), and a tab switch replays only the visible frame. tmux's own history is intact throughout — the browser just has to ask for it again. Gesture-triggered rather than polling because at a 100k history limit the capture can be megabytes. ⚠️ **The capture ENDS with a cursor move back to the pane's own caret position** (`formatCursorRestore`, from the same `display-message` query the visible-frame path uses). The linear replay otherwise leaves the caret wherever the last character landed — the bottom-most row carrying text, which for an agent CLI is the status line — so the caret sat on the composer's border instead of its input line and every cursor-relative update the CLI sent afterwards was measured from the wrong row, until its next full redraw silently repaired it (that self-repair is why the report read as "it fixes itself as soon as Claude writes a line"). ⚠️ **The move is RELATIVE — up `rows - 1 - cursor_y`, then `\r`, then right `cursor_x` — never `CUP`.** `\x1b[<row>;<col>H` numbers rows from the top of the browser's screen, so it lands correctly only while the browser's row count equals `pane_height`, and nothing guarantees that: `resizeWindow` issues its tmux resize fire-and-forget and returns immediately, so a capture can be taken before a requested resize has applied, and `_onSessionNeedsRefresh` sends no resize at all. Counting up from the last replayed row anchors to the content both ends share. Restoring the cursor makes ROW ALIGNMENT load-bearing on this path: **no transform that can DELETE A LINE may run over a full-history capture**, because every deletion shifts the frame out from under the restored position. Four had accumulated — trailing blank rows stripped by `\n+$`, `stripInkRedrawBloat`, the `CLAUDE_BANNER_PATTERN` trim that cuts everything above the banner, and `LEADING_WHITESPACE_PATTERN` — each correct for a byte stream of successive frames and each wrong for a single rendered frame. ⚠️ **Those skips key on `isFullCapture`, meaning a capture actually came back — never on `?full=1` alone.** When `captureActivePaneBuffer` returns null (ENOBUFS, a timeout, a vanished pane, or a session with no mux at all) the reply falls back to `session.terminalBuffer`, which IS a byte stream and must still be stripped; gating on the query flag returned it whole, and a direct-PTY session takes that path on every first selection rather than only during an outage. ⚠️ A capture holding nothing visible (`hasVisibleContent`) returns `''`, because the caller reads an empty capture as "unavailable" and keeps its byte history — retaining trailing blank rows made an all-blank pane non-empty, which would have replaced real history with a blank screen from the server side, where `_replayWouldShrinkBuffer` cannot see it. ⚠️ **"One line per screen row" holds only where no row was hard-wrapped**: `-J` joins a wrapped row into its logical line (measured: a 100-character line in a 40-column pane captures as 10 lines against a 12-row pane), and the counts reconcile only once the browser xterm re-wraps at the same width — the same assumption `_estimateReplayRows` already documents. Tests: `test/tmux-capture-full-history.test.ts` covers the cursor move, the trim pairing and `hasVisibleContent`; `test/routes/session-routes.test.ts` covers a surviving blank first row, an unstripped byte-history fallback, and an empty capture leaving history intact. ⚠️ **The re-pull must never DOWNGRADE the buffer** (#205 round 2): the same reasoning that makes it a win for a shell pane makes it destructive for a repaint-mode CLI pane, where tmux keeps no history of its own (`history_size≈0` measured for a Claude pane) and the capture is roughly ONE frame while xterm may hold hundreds of rows of replayed frames — `_resetTerminalForReplay()` + rewrite then deletes history mid-scroll ("goes back a bit, repeats blocks, gets worse the further up I go"; measured A/B on a live pane: 341 rows → 42 with the guard off). `_replayWouldShrinkBuffer()` (terminal-ui.js) estimates the capture's rendered rows — escape sequences stripped, `capture-pane -J` re-wrapping accounted for — and the pull is skipped when that is more than one screen short of `buffer.active.length`. The one-screen tolerance matters: both sides are estimates (the buffer length counts trailing blank rows), so only a clear downgrade is refused. A refused session joins `_fullHistoryRepullUseless`, raising its cooldown from 4s to 60s so a hollow pane stops re-fetching megabytes on every scroll-up. Tests: `test/tmux-capture-full-history.test.ts`, `test/tmux-scrollback-eol.test.ts`, `test/terminal-scroll-routing.test.ts`, `test/terminal-flush-budget.test.ts`. + +**Repair while reading (#814)** is a manual **Reload history** action inside the existing history banner on desktop and touch devices, enabled by default and toggleable per device in Settings → Terminal & Input → Scrolling & rendering (`historyReloadAction`). It is offered only for a marked non-shell active session while scrolled away from live output, not Docker or adopted (their local pane hosts a nested tmux client in the alternate screen, so `?full=1` returns one screen the downgrade guard refuses; remote sessions stay eligible, since the route splices the remote scrollback in), not detached, not owned by tiles, with no pull or buffer load in flight, no terminal load state for the session (a tab switch sets it before the buffer load opens), and no drop-recovery refresh owning the session (`_terminalRefreshOwner`, set for the whole fetch, before that refresh opens its buffer load). `_maybeRefetchFullHistory` returns early on that same owner, so Reload, Load full history and the top-of-buffer pull all stand aside instead of running a second capture whose download-time queue the refresh's own load would replace; the refresh re-syncs the action when it starts and when its `finally` releases the owner. `paneHistoryLines` is deliberately not consulted: it is recorded at the last load, so a session first opened empty keeps 0 after the very burst that opens the gap (#814). The bar is a polite live region (`role="status"`), but only the truncation notice is announced: a reload-only bar sets `aria-live="off"` before it re-renders, since it comes back on nearly every scroll-up in a busy tab, and its button stays reachable with Tab. Its × is labelled for what the bar carries: "Dismiss history notice" with the notice, "Dismiss Reload history" without it. A revealed truncation notice keeps its message and its **Load full history** control; Reload is appended only when the notice has no load control, or shown alone with a short missing-output message. When Reload is eligible, that **Load full history** control stands in for it and pulls with the content anchor (eligibility read at click time), so the reader keeps their line, and shares Reload's loading state, so the re-render the in-flight pull triggers keeps it on Loading… instead of bringing it back enabled; otherwise it keeps the top anchor and no loading state, so the bar still hides on a scroll back to live output. A reload-only × dismissal lasts until the mark is cleared by a successful `mux-full-history` replay, independently of the notice’s page-long dismissal. Pressing × while loading hides the bar immediately; the in-flight pull continues. Eligibility is cached per active session, with onScroll sampling coalesced to one animation frame on every device; unchanged eligibility never rebuilds the banner. Automatic history pulls and notice reveal stay top-only (#205). Live-output marking covers only live writes: a byte-history (`?tail=`) replay, for example after a burst in a background tab, never marks the session, so that gap relies on the top-of-buffer pull. The manual action forces a content-anchored pull, bypassing the gesture cooldown but retaining the downgrade guard. Any downgrade-refused pull hides Reload until the next successful `mux-full-history` replay; that refusal, not the cached history size, is what retires the action for a pane with no tmux history (fullscreen Claude). A manual reload answered by anything but `mux-full-history` (an empty response, or the byte-history fallback the route returns when the pane capture is blank or failed) retires it the same way, since only a mux replay clears the mark; a transient error envelope (`success: false`) leaves it available. A content anchor captures up to 64 visible rows, preserving indentation, and scores candidate alignments by matching viewport context. Each distinct nonblank row contributes at most one point, so repeated TUI borders cannot outvote a distinctive tool result. The best match must score at least 60% of the distinct rows and at least two of them, capped at the number of distinct rows, so a viewport with one distinct row (a lone tool result among blanks) matches on that row alone; it must also be unique within the search window. Equal-scoring copies are ambiguous, even when all furniture rows match or the distinctive tool row has disappeared; proximity to the expected position does not establish confidence. An isolated first-row match is not trusted: without confident, unambiguous context the old viewport index is retained, while readers already near live output retain their bottom distance. Search covers 4001 candidates from `expected - 4000 + rows` to `expected + rows` (at most 4064 cached line reads), leaning up because every row a reload fills in below the reader moves the reader's row up, while a capture with fewer rows below moves it down by at most the one screen the downgrade guard tolerates. Gaps up to `4000 - rows` rows therefore land exactly, including at xterm's scrollback cap, where the replay trims the top by the same number of rows. A wider gap puts the match outside the window: the restore keeps the old absolute index, which is right while the top of the buffer stays put but, at the cap, lands the reader the whole gap below their line. Live flushes use an xterm marker to track the reading row across scrollback trimming in O(1), and restore it only in the write callback; a marker the write disposed (its row trimmed, or scrollback erased by `ESC[3J`, which the narrow and middle strips keep) falls back to the absolute index instead of row 0, while RIS leaves the marker alive on its old line, which is the same index; at-bottom sticky scroll is unchanged. Ordered, session-scoped travel during replay is applied with per-move clamping; a switched-to tab never donates travel. The notice is decided per recorded move, as a live scroll decides it: an upward move that reaches row 0 reveals the partial-history notice, a downward move that reaches live output retires it, and other moves leave the last decision standing, so reaching the top and then scrolling a few rows down still reveals it; a reload with no travel leaves the notice as it was. The buffer load opens BEFORE the fetch, so download-time output queues behind the replay instead of being overwritten. Non-replay exits flush the whole queue; replays retain the capture-header cutoff above. A blocked dropped-output recovery stores its session and current attempt, defers without consuming retries, and resumes only for the still-active session; a later drop for the same session during that load keeps the higher attempt, so the retry bound still holds. Only an actual `mux-full-history` replay clears the live-output mark and reload dismissal, and a newer live-write generation keeps them marked. The drop-recovery refresh (`_onSessionNeedsRefresh`) follows the same rule: it clears both after a completed replay of a `mux-full-history` capture, only while it still owns the active session and the live-output generation sampled before its fetch is unchanged; its `?tail=` fallback never clears them, and because that fallback means the full capture would shrink the buffer (the refusal signal), it retires the action under the same session and refresh-owner checks. The trade-off remains a full synchronous server capture (about 1 s: 1,068 ms median for `capture-pane -p -e -J -S -100000` over 100k lines of 120 characters, 12.1 MB), not a cheap automatic per-output repair. Tests: `test/shell-scroll-history-pull.test.ts`, `test/history-gap-repair.browser.test.ts`. **The partial-history notice is lazy and pane-gated** (`computeHistoryTruncationNotice()` in constants.js, `_renderHistoryTruncationBanner()` / `_setHistoryNoticeRevealed()` in app.js). `truncated` on a terminal response measures the server's BYTE stream, which is not what `full=1` can return: for a pane with no tmux scrollback (fullscreen claude starts in the alternate screen and never writes to the main grid, so `#{history_size}` is 0) the bytes a tail cut drops are old repaint frames. Measured on prod 2026-10-10, every claude pane: the tab-switch tail cut a 1.2 to 6.2 MB stream to 1 MiB, the local scrollback that tail replays into is repeats of the same frames (one pane: 450 non-blank rows, 44 unique, one row 33 times), and `full=1` returned 1 to 5 KB, so **Load full history** could only end in the downgrade refusal while the banner promised "4.8 MB more". The capture therefore reads `#{history_size}` in the SAME `display-message` as the cursor (no extra tmux call), the route returns it as `paneHistoryLines` (absent when the body is not a capture, and for a remote SSH session, whose local pane hosts the remote tmux client and always reports 0 while `full=1` reads the remote history), and a reported 0 hides the notice in every state; a positive count replaces the byte gap in the message. ⚠️ Key the notice decision on `history_size`, never on `alternate_on`: a shell running `less` is in the alternate screen with its whole history still retained (measured, 99,972 rows) and `full=1` returns all of it. The one place `alternate_on` decides is a shell's AUTOMATIC load (`alt=recording`, see Full-scrollback replay): there the question is whether the capture holds the scrollback a nested tmux client keeps in its byte recording, not whether a pull can return more. The notice is also LAZY: it appears only after a wheel/touch gesture reaches the top of the browser buffer and the pull that gesture started has settled (`_maybeLoadMoreHistoryOnScroll`), goes away when a downward gesture is back at live output or the tab switches (`selectSession` nulls `_historyNoticeRevealedFor` before repainting), and its × is sticky per session until reload (`_historyNoticeDismissed`). Tests: `test/history-truncation-notice.test.ts`, `test/history-notice-reveal.test.ts`. diff --git a/docs/wiki/Settings-Reference.md b/docs/wiki/Settings-Reference.md index 5bfd53a2..978da0c8 100644 --- a/docs/wiki/Settings-Reference.md +++ b/docs/wiki/Settings-Reference.md @@ -51,6 +51,7 @@ non-updatable. See [Running As A Service](Running-As-A-Service). | Input Field: Send on Enter | Off | With CJK Input on, typed text stays in the pinned field until Enter instead of streaming to the CLI, so on a phone you can scroll the terminal and edit an answer first. With a hardware keyboard, Shift+Enter adds a line (a phone's on-screen keyboard has none). Esc clears, autocorrect is on. | | Extended Keyboard Bar | Per device | Which accessory bar phones get. Shell sessions override it while they are active. | | Wheel Scrolls Local History | Off | Keeps the wheel on the local buffer instead of forwarding it to the CLI. Fullscreen pi leaves that buffer empty and has no paging fallback, so with this on the wheel does nothing there. | +| History Reload Button | On (per device) | Offers **Reload history** in the history banner while you are scrolled up in a non-shell session that has had live output since its last full capture; a tap re-pulls the full tmux history and keeps your reading position. | | Auto Copy Selection | Off | Copies highlighted terminal text to the clipboard the moment you finish selecting it. Ctrl+C still copies on demand. | | Trim The Pane Margin On Copy | On | Takes the left margin a full-screen agent CLI paints down its own edge off a copy, so the text pastes flush. Each CLI declares its own width, and the strip never exceeds the indent every selected line shares, so nesting is kept. Claude Code and Codex declare a margin; a shell does not. | | Normal / Bold font weight | xterm defaults | Per device, each slot from 100 to 900. The bundled JetBrains Mono renders every step, so a lighter normal weight makes Claude's bold headings stand out. Applies live to the terminal, both echo overlays and open team panes. | diff --git a/docs/wiki/The-Dashboard.md b/docs/wiki/The-Dashboard.md index 4e0470f3..dfa80aa9 100644 --- a/docs/wiki/The-Dashboard.md +++ b/docs/wiki/The-Dashboard.md @@ -243,10 +243,14 @@ Worth knowing: reloads only the current screen, which keeps tab switches fast. Shell sessions open from a bounded recent tail so a large transcript cannot stall tab switching. Scrolling to the top of a Shell pane pulls the most recent 1 MiB of its tmux - history; press **Load full history** to pull the rest explicitly. That notice only + history; press **Load full history** to pull the rest explicitly. That truncation notice only appears once you scroll to the top, leaves when you scroll back down, and stays away for that tab once you close it. Sessions whose CLI keeps its own history (fullscreen - Claude) never show it, since there is nothing more to load. Automatic output + Claude) never show it, since there is nothing more to load. The same bar can also offer + **Reload history** while scrolled up in an agent session after new output (toggle: + Settings → Terminal & Input → History Reload Button). When a reload finds nothing more + than the browser already shows, such as fullscreen Claude whose pane keeps no tmux + history, the action is withdrawn until the next full capture. Automatic output recovery stays within the bounded browser buffer. - **Wheel and touch scrolling** are forwarded into Claude's own transcript when a recent Claude runs fullscreen (`CLAUDE_CODE_NO_FLICKER=1`, or `"tui": "fullscreen"` in diff --git a/src/web/CLAUDE.md b/src/web/CLAUDE.md index 4ca8c8b9..3914b580 100644 --- a/src/web/CLAUDE.md +++ b/src/web/CLAUDE.md @@ -60,7 +60,7 @@ Frontend JS modules have `@fileoverview` with `@dependency`/`@loadorder` tags. L **Where a dialog hands the keyboard back to** (`FocusTrap.focusToReturn()`, keyboard-accessory.js): a dialog that saves focus on open asks this, never `document.activeElement`. By the time a dialog opens, the mouse press that opened it has already moved focus (onto the pressed control in Chromium and Firefox, onto `<body>` in WebKit on macOS, where a button takes no focus from the mouse), and restoring that left the keyboard out of the terminal until it was clicked. The answer is the typing field (textarea, text-like input, editable region) that had focus at `pointerdown`, whenever focus now sits on the pressed control or on `<body>`. ⚠️ `pointerdown`, never `mousedown` or `click`: moving focus is `mousedown`'s default action, so only the earlier event still sees what had the keyboard. ⚠️ One press, from a typing field, by mouse: the field of an earlier press is not carried over (it can be behind a dialog opened since), a press that began on a button (a dialog opened inside a dialog) still returns to the pressed control, any key but a held modifier forgets the press (a keyboard user gets the control back), and a finger or pen records nothing (a focused field there means the on-screen keyboard). The one press that inherits a field is a press on an item inside `[role="menu"]`, from the press that opened the menu (a tile's menu button, then "Session options"); a menu that hands focus back to its trigger before running the item is not covered. ⚠️ Asking spends the press, so nothing pressed inside the opening dialog can hand the keyboard to a field behind it; call it once, when the dialog opens. Callers: `FocusTrap.activate()` (App Settings, Session Options, Help, Kill All, the phone composer) and `_rememberOverlayFocus()` (command palette, Session Manager); the local model window places its own focus. A dialog that never handed focus back (most of the small confirm dialogs) is not changed by this. Tests: `test/dialog-focus-return.test.ts`, `test/dialog-focus-return.browser.test.ts` (real Chromium, not in the gate). -**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 c53cfb3b..f98715dc 100644 --- a/src/web/public/app.js +++ b/src/web/public/app.js @@ -801,9 +801,13 @@ class CodemanApp { // the small `full=1` capture instead of the 1 MiB byte tail: see // _notePaneHistory and selectSession. this._paneHistoryLines = new Map(); // Map<sessionId, number> - // Cooldown per session for the scroll-to-top "load more history" re-pull. + // Per-session cooldown for 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 // repaint-mode CLI pane, where tmux keeps no history of its own). The pull is // refused for those and retried far more slowly — see _maybeRefetchFullHistory. @@ -2596,13 +2600,41 @@ class CodemanApp { * @param {number} [queuedBytes] - render-queue bytes at the drop, for the crash trail */ _scheduleDroppedOutputRecovery(sessionId, attempt = 0, queuedBytes) { - if (!sessionId || this._clientDropRecoveryTimer) return; + if (!sessionId) return; // Nothing of the main terminal's to recover while the tile grid owns it. if (this._tilesOwnTerminal?.()) return; + // A slow capture owns the live-output gate. Keep the recovery owed until + // it releases instead of spending every retry against the same open load. + if (this._isLoadingBuffer) { + if (sessionId === this.activeSessionId) { + if (this._pendingDroppedOutputRecovery?.sessionId !== sessionId && Number.isFinite(queuedBytes)) { + _crashDiag.log(`TERMINAL DROP: ${(queuedBytes / 1024).toFixed(0)}KB queued (recovery deferred)`); + } + const pending = this._pendingDroppedOutputRecovery; + this._pendingDroppedOutputRecovery = { + sessionId, + attempt: pending?.sessionId === sessionId ? Math.max(pending.attempt, attempt) : attempt, + }; + } + return; + } + if (this._clientDropRecoveryTimer) return; // Behind the debounce guard: one line per window, not per dropped frame. if (Number.isFinite(queuedBytes)) _crashDiag.log(`TERMINAL DROP: ${(queuedBytes / 1024).toFixed(0)}KB queued`); this._clientDropRecoveryTimer = setTimeout(async () => { this._clientDropRecoveryTimer = null; + // A load may have opened after this timer was armed. Defer without + // advancing the attempt; _finishBufferLoad resumes only the active tab. + if (this._isLoadingBuffer) { + if (sessionId === this.activeSessionId) { + const pending = this._pendingDroppedOutputRecovery; + this._pendingDroppedOutputRecovery = { + sessionId, + attempt: pending?.sessionId === sessionId ? Math.max(pending.attempt, attempt) : attempt, + }; + } + return; + } let repainted = false; let timedOut = false; try { @@ -3465,6 +3497,9 @@ class CodemanApp { if (this._terminalRefreshOwner?.sessionId === sessionId) return false; const refreshOwner = { sessionId }; this._terminalRefreshOwner = refreshOwner; + // Reload history stands aside for the length of this refresh (see + // _historyReloadActionEligible); take it off an already-painted bar now. + this._syncHistoryReloadAction?.(); try { // A shell can retain a multi-megabyte/100k-line tmux history. Automatic // recovery stays bounded just like normal shell selection (tmux's rendered @@ -3473,6 +3508,8 @@ class CodemanApp { // TUI modes still recover the whole picture, with the downgrade guard for // repaint-mode panes whose tmux capture can be smaller than xterm's buffer. const useFullHistory = this.sessions.get(sessionId)?.mode !== 'shell'; + // Keep live output received during the capture marked for another full-history pull. + const liveOutputGen = this._liveOutputGen?.get(sessionId) || 0; let capture = await this._fetchTerminalCapture( useFullHistory ? `/api/sessions/${sessionId}/terminal?full=1` @@ -3481,7 +3518,13 @@ class CodemanApp { ); let headersReceivedAt = capture.headersAt; let data = capture.json?.data ?? {}; + // The full capture would shrink the buffer: tmux holds less than the browser, + // the signal `_maybeRefetchFullHistory` retires Reload history on. Record it + // and apply it past the ownership guard below, so the next tap does not run + // another forced full capture only to be refused. + let refusedFullCapture = false; if (useFullHistory && data.terminalBuffer && this._replayWouldShrinkBuffer(data.terminalBuffer)) { + refusedFullCapture = true; capture = await this._fetchTerminalCapture(`/api/sessions/${sessionId}/terminal?tail=${TERMINAL_TAIL_SIZE}`); headersReceivedAt = capture.headersAt; data = capture.json?.data ?? {}; @@ -3495,6 +3538,10 @@ class CodemanApp { // pane), and an error envelope is not a capture at all. if (this.activeSessionId !== sessionId || this._terminalRefreshOwner !== refreshOwner) return false; if (capture.json?.success !== false) this._notePaneHistory?.(sessionId, data); + if (refusedFullCapture) { + (this._historyReloadDismissed ||= new Set()).add(sessionId); + this._syncHistoryReloadAction?.(); + } if (data.terminalBuffer) { // This refresh is SERVER-triggered, so a user quietly reading scrollback // did not ask for it and must not be dragged to the bottom by it (#259). @@ -3507,12 +3554,23 @@ class CodemanApp { // after them and fuse into the buffer written below. See // _resetTerminalForReplay. this._resetTerminalForReplay(); - await this.chunkedTerminalWrite( + const { completed } = await this.chunkedTerminalWrite( data.terminalBuffer, TERMINAL_CHUNK_SIZE, undefined, this._bufferLoadFinishOpts(data, headersReceivedAt) ); + if ( + completed && + this.activeSessionId === sessionId && + this._terminalRefreshOwner === refreshOwner && + data.source === 'mux-full-history' && + (this._liveOutputGen?.get(sessionId) || 0) === liveOutputGen + ) { + this._liveOutputSinceFullPull?.delete(sessionId); + this._historyReloadDismissed?.delete(sessionId); + this._syncHistoryReloadAction?.(); + } // A tail fetch can be partial, and the banner would otherwise keep // describing the pre-refresh buffer (#258). this._setHistoryTruncation(sessionId, data); @@ -3549,7 +3607,11 @@ class CodemanApp { console.error('needsRefresh reload failed:', err); return err?.name === 'AbortError' ? 'deadline' : false; } finally { - if (this._terminalRefreshOwner === refreshOwner) this._terminalRefreshOwner = null; + if (this._terminalRefreshOwner === refreshOwner) { + this._terminalRefreshOwner = null; + // Reload history stands aside while this refresh fetches; offer it again. + this._syncHistoryReloadAction?.(); + } } } @@ -5039,6 +5101,9 @@ class CodemanApp { // Clear pending terminal writes this._clearTimer('syncWaitTimeout'); this._clearTimer('_clientDropRecoveryTimer'); + // A recovery deferred behind a load would otherwise resume once the next + // load (the reconnect's own refresh) finishes, and run a second full capture. + this._pendingDroppedOutputRecovery = null; this.pendingWrites = []; this.writeFrameScheduled = false; // Release the one-chunk-in-flight gate with the rest of the write queue. @@ -6743,6 +6808,7 @@ class CodemanApp { if (state && state.generation !== selectGen) return; this.terminalLoadStates.delete(sessionId); this._updateTerminalLoadTab(sessionId); + if (state) this._syncHistoryReloadAction?.(); } _updateTerminalLoadTab(sessionId) { @@ -9533,6 +9599,7 @@ class CodemanApp { this._tabCompletionBaseText = null; this._clearTimer('_tabCompletionFallback'); this._clearTimer('_clientDropRecoveryTimer'); + this._pendingDroppedOutputRecovery = null; this._terminalRefreshOwner = null; // Clean up pending terminal writes to prevent old session data from appearing in new session @@ -9662,8 +9729,8 @@ class CodemanApp { } /** - * "Load more history": re-pull the whole tmux scrollback when the user scrolls up - * while already at the top of what the browser has. + * Re-pull tmux history 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 @@ -9674,9 +9741,11 @@ class CodemanApp { * everything (history-limit 100k by default), so the fix is to go ask for it with * the same `?full=1` capture a page reload uses (issue #205). * - * On demand rather than automatic because that capture is unbounded-ish work: at - * the default history limit it can be megabytes, which is fine to pay when the - * user is explicitly reaching for history and not fine on every tab switch. + * Automatic pulls are top-only and cooldown/latch guarded: a synchronous + * capture can cost about 1 s at 100k lines (1,068 ms median for 12.1 MB of + * 120-character lines, `capture-pane -p -e -J -S -100000`) and blocks the server event loop. + * The manual Reload history action uses a content anchor to hold the reader's + * place even when new history fills a gap below them. * * 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 @@ -9685,9 +9754,13 @@ class CodemanApp { * gets a much longer cooldown so a hollow pane stops re-fetching megabytes on * every scroll-up (issue #205, round 2). */ - async _maybeRefetchFullHistory({ force = false } = {}) { + async _maybeRefetchFullHistory({ force = false, anchor = 'top' } = {}) { const sessionId = this.activeSessionId; if (!sessionId || this._fullHistoryRepullInFlight || this._isLoadingBuffer) return; + // A drop-recovery refresh owns this session until its replay ends: a second + // capture would run back to back with it, and its load would replace this + // pull's queue, losing the output that arrived during the download. + if (this._terminalRefreshOwner?.sessionId === sessionId) return; if (this.detachedSessions?.has(sessionId)) return; // The parked main terminal has no history to pull while tiles own the screen. if (this._tilesOwnTerminal?.()) return; @@ -9719,11 +9792,16 @@ class CodemanApp { if (!force && now - (this._fullHistoryRepullAt.get(sessionId) || 0) < cooldown) return; this._fullHistoryRepullAt.set(sessionId, now); this._fullHistoryRepullInFlight = true; + const loadOwner = this._beginBufferLoad(); + let replayed = false; // The session-id check below cannot see a tab switch that came BACK during // the fetch (A -> B -> A): the id matches again while `selectSession` is // replaying its own capture, and the reset below would land in the middle // of that write. The select generation moves on every switch, so it can. const selectGen = this._selectGeneration; + // Queued output replayed after this load may mark the session again. Never + // clear that newer generation along with the capture's original mark. + const liveOutputGen = this._liveOutputGen?.get(sessionId) || 0; try { const requestStartedAt = performance.now(); const capture = await this._fetchTerminalCapture( @@ -9742,6 +9820,22 @@ class CodemanApp { // recording its empty data would forget the count and hand the next // gesture back to the paging fallback, the bug this pull exists to avoid. if (selectGen === this._selectGeneration && capture.json?.success !== false) this._notePaneHistory?.(sessionId, payload); + // A manual reload answered by anything but a full mux capture (an empty + // response, or the byte-history fallback the route returns when the pane + // capture is blank or failed) cannot fill the gap, and only a mux replay + // clears the mark: offering it again would repeat the forced capture on + // every tap. Retire it until the next `mux-full-history` replay. Only for + // the request still current: a slow answer from before an A -> B -> A + // switch must not retire the action a newer capture of A already cleared. + if ( + anchor === 'content' && + this.activeSessionId === sessionId && + selectGen === this._selectGeneration && + capture.json?.success !== false && + payload.source !== 'mux-full-history' + ) { + (this._historyReloadDismissed ||= new Set()).add(sessionId); + } const buffer = payload.terminalBuffer; const timing = { trigger: force ? 'full-history-button' : 'full-history-scroll', @@ -9802,6 +9896,7 @@ class CodemanApp { timing.totalMs = performance.now() - requestStartedAt; this._recordTerminalLoadTiming(timing); (this._fullHistoryRepullUseless ||= new Set()).add(sessionId); + (this._historyReloadDismissed ||= new Set()).add(sessionId); this._logScrollRouting?.('repull-refused-downgrade'); // The browser already holds more than tmux can give back, so there is // nothing further to offer and the indicator must stop promising it. @@ -9819,6 +9914,9 @@ class CodemanApp { this._fullHistoryRepullUseless?.delete(sessionId); const rowsBefore = this.terminal.buffer.active.length; const replayStartedAt = performance.now(); + const viewportAnchor = anchor === 'content' ? this._captureViewportAnchor() : null; + // Ordered, not summed: each move clamps at the buffer edge as it would live. + if (anchor === 'content') this._earlyReplayTravel = { sessionId, moves: [] }; this._resetTerminalForReplay(); const { parsedAt, @@ -9827,11 +9925,17 @@ class CodemanApp { } = await this.chunkedTerminalWrite( buffer, TERMINAL_CHUNK_SIZE, - sessionId, + loadOwner, this._bufferLoadFinishOpts(payload, headersReceivedAt) ); + replayed = true; // chunkedTerminalWrite finished this load with the capture cutoff. timing.resetAndParseMs = parsedAt - replayStartedAt; if (!completed || this.activeSessionId !== sessionId || selectGen !== this._selectGeneration) return; + if (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 // the next tab switch before the normal 1MB tail fetch replaces it. @@ -9844,9 +9948,26 @@ class CodemanApp { // UPWARD, so what used to be row 0 (what they were looking at) is now `delta` // rows down; scrolling there reveals the recovered history above it instead // of teleporting them to the bottom the way a normal buffer load does. - const delta = parsedBufferLength - rowsBefore; - if (delta > 0) this.terminal.scrollToLine(delta); - else this.terminal.scrollToTop(); + if (anchor === 'content') { + const baseY = this.terminal.buffer.active.baseY; + const clamp = (row) => Math.max(0, Math.min(baseY, row)); + let row = this._restoreViewportAnchor(viewportAnchor); + // Replay travel bypassed the live scroll handler's notice update, so + // decide it per move as that handler would: an upward move that reaches + // row 0 reveals the notice, a downward move back at live output retires it. + let reveal = null; + for (const move of this._earlyReplayTravel.moves) { + row = clamp(row + move); + if (move < 0 && row === 0) reveal = true; + else if (move > 0 && row >= baseY - 2) reveal = false; + } + this.terminal.scrollToLine(row); + if (reveal !== null) this._setHistoryNoticeRevealed?.(reveal ? sessionId : null); + } else { + const delta = parsedBufferLength - rowsBefore; + if (delta > 0) this.terminal.scrollToLine(delta); + else this.terminal.scrollToTop(); + } // The load's own replay sampled the sticky-scroll baseline while the // terminal sat at the bottom of a just-rewritten buffer, so the next // flush would scroll back down and undo the restore above. This path is @@ -9862,7 +9983,10 @@ class CodemanApp { } catch { // Transient (offline, 5xx) — the next scroll-up past the cooldown retries. } finally { + if (!replayed) this._finishBufferLoad(loadOwner, { flushQueued: true, since: 0 }); + if (anchor === 'content') this._earlyReplayTravel = null; this._fullHistoryRepullInFlight = false; + this._syncHistoryReloadAction?.(); } } @@ -9938,6 +10062,44 @@ 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. + // `_paneHistoryLines` is deliberately not consulted: it is recorded at the last + // load, so a session first opened empty keeps 0 after the very burst that + // opens the gap (#814). A pane that really holds no history (fullscreen + // Claude) captures one screen, `_replayWouldShrinkBuffer` refuses it, and the + // refusal dismisses the action until the next `mux-full-history` replay. + // Docker and adopted sessions are left out: their local pane hosts a nested + // tmux client in the alternate screen, so `?full=1` returns one screen that + // the downgrade guard always refuses (the exclusions `paneKeepsNoHistory` + // uses in selectSession). Remote sessions stay eligible, since the route + // splices the remote scrollback into their capture. + return !!(this.loadAppSettingsFromStorage?.()?.historyReloadAction !== false && + session && session.mode !== 'shell' && !session.docker && !session.adopt && + this._liveOutputSinceFullPull?.has(sessionId) && + !this._isLoadingBuffer && + !this.terminalLoadStates?.has(sessionId) && // Tab switches set this before the buffer load opens. + this._terminalRefreshOwner?.sessionId !== sessionId && // A drop-recovery refresh is fetching. + !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 && + !this._historyReloadDismissed?.has(sessionId); + const last = this._historyReloadActionState; + if (last && last.sessionId === sessionId && last.eligible === eligible && last.loading === loading) return; + this._historyReloadActionState = { sessionId, eligible, loading }; + this._renderHistoryTruncationBanner(); + } + /** * Paint the partial-history banner for the active session. * @@ -9945,12 +10107,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'); @@ -9958,47 +10120,96 @@ 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._historyReloadDismissed?.has(sessionId); + this._historyReloadActionState = { sessionId, eligible, loading }; + if (!showNotice && !eligible && !loading) { bar.hidden = true; return; } + // `#historyTruncationBar` is a polite live region. Only the truncation + // notice is news worth announcing; a reload-only bar re-renders on every + // eligible scroll-up in a busy tab, so it stays silent and is reached by Tab. + // Set before the rewrite below, so the new content is judged by it. + bar.setAttribute('aria-live', showNotice ? 'polite' : 'off'); bar.textContent = ''; const label = document.createElement('span'); label.className = 'history-trunc-text'; - 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'; - btn.textContent = 'Load full history'; + // A content-anchored pull from here stands in for Reload history, so it + // shares Reload's loading state: the pull flips Reload eligibility, and the + // re-render that follows must not bring the button back enabled mid-pull. + btn.disabled = loading; + btn.textContent = loading ? 'Loading…' : 'Load full history'; btn.onclick = () => { btn.disabled = true; btn.textContent = 'Loading…'; // Forced: the cooldown exists to throttle scroll gestures, not choices. - this._maybeRefetchFullHistory({ force: true }).finally(() => { + // When Reload history is eligible, this button is shown in its place + // (one load control per bar), so it must keep the reader's line the same + // way. Checked at click time, not render time: the bar only re-renders on + // eligibility transitions, and the reader may have scrolled since. + const anchor = this._historyReloadActionEligible() ? 'content' : 'top'; + // The top anchor keeps no loading state: it would hold the bar up after + // a scroll back to live output, where it hides today. + if (anchor === 'content') { + this._historyReloadActionLoadingFor = sessionId; + this._syncHistoryReloadAction(); + } + return this._maybeRefetchFullHistory({ force: true, anchor }).finally(() => { + if (anchor === 'content' && this._historyReloadActionLoadingFor === sessionId) { + this._historyReloadActionLoadingFor = null; + } this._renderHistoryTruncationBanner(); }); }; 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 = () => { + if (!this._historyReloadActionEligible()) { + this._syncHistoryReloadAction(); + return; + } + 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'); dismiss.type = 'button'; dismiss.className = 'history-trunc-dismiss'; - dismiss.setAttribute('aria-label', 'Dismiss history notice'); + // Name what the × actually dismisses: a reload-only bar has no notice. + dismiss.setAttribute('aria-label', showNotice ? 'Dismiss history notice' : 'Dismiss Reload history'); dismiss.textContent = '×'; dismiss.onclick = () => { - // 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); @@ -10118,6 +10329,7 @@ class CodemanApp { this.activeSessionId = sessionId; this._activateFileBrowserSession?.(sessionId); if (typeof CjkInput !== 'undefined') CjkInput.restoreDraft?.(sessionId); + 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 }); @@ -10421,9 +10633,12 @@ class CodemanApp { !session?.remote && !session?.docker && !session?.adopt && this._paneHistoryLines?.get(sessionId) === 0; const useFullHistory = !shellSession && (paneKeepsNoHistory || !this._fullHistoryLoaded.has(sessionId)); if (useFullHistory) this._fullHistoryLoaded.add(sessionId); + // Sample before fetching, as other replays do, so output during download keeps the session marked. + const liveOutputGen = this._liveOutputGen?.get(sessionId) || 0; const fetchStartedAt = performance.now(); const tailUrl = `/api/sessions/${sessionId}/terminal?tail=${TERMINAL_TAIL_SIZE}`; let capture; + let fullHistoryReplay = useFullHistory; try { capture = await this._fetchTerminalCapture( useFullHistory @@ -10444,6 +10659,7 @@ class CodemanApp { _crashDiag.log('FULL CAPTURE ABORTED → tail'); // It never loaded, so the next select must be allowed to try again. this._fullHistoryLoaded.delete(sessionId); + fullHistoryReplay = false; capture = await this._fetchTerminalCapture(tailUrl); } const headersReceivedAt = capture.headersAt; @@ -10489,7 +10705,7 @@ class CodemanApp { // cannot be actioned, and is indistinguishable from real CLI output. this._setHistoryTruncation(sessionId, data); // Use chunked write for large buffers to avoid UI jank - const { parsedAt: freshParsedAt } = await this.chunkedTerminalWrite( + const { parsedAt: freshParsedAt, completed } = await this.chunkedTerminalWrite( data.terminalBuffer, TERMINAL_CHUNK_SIZE, bufferLoadOwner, @@ -10500,6 +10716,11 @@ class CodemanApp { this._clearTerminalLoadState(sessionId, selectGen); return; } + 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(); } @@ -10915,6 +11136,10 @@ 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); try { localStorage.removeItem(`codeman-xs-${sessionId}`); } catch {} diff --git a/src/web/public/i18n.js b/src/web/public/i18n.js index 408f000f..d12db773 100644 --- a/src/web/public/i18n.js +++ b/src/web/public/i18n.js @@ -751,6 +751,13 @@ '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': '加载完整历史', + 'Dismiss Reload 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 42f86621..9d7614bd 100644 --- a/src/web/public/index.html +++ b/src/web/public/index.html @@ -2161,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/terminal-ui.js b/src/web/public/terminal-ui.js index a48484cc..c728638f 100644 --- a/src/web/public/terminal-ui.js +++ b/src/web/public/terminal-ui.js @@ -1451,6 +1451,7 @@ 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.onCursorMove(() => this._syncMobileHelperTextareaToCursor()); this.terminal.onRender(() => this._syncMobileHelperTextareaToCursor()); @@ -4043,6 +4044,86 @@ Object.assign(CodemanApp.prototype, { return buffer.viewportY >= buffer.baseY - 2; }, + /** Capture bounded viewport context, not just repeated TUI borders/status rows. */ + _captureViewportAnchor() { + const buffer = this.terminal.buffer.active; + const { viewportY, baseY } = buffer; + const context = Array.from( + { length: Math.min(this.terminal.rows || 3, 64, buffer.length - viewportY) }, + (_, i) => buffer.getLine(viewportY + i)?.translateToString(true) || '' + ); + return { viewportY, rowsFromBottom: baseY - viewportY, context }; + }, + + /** Match the visible context; a lone repeated row is not a reliable anchor. */ + _restoreViewportAnchor(anchor) { + const buffer = this.terminal.buffer.active; + const clamp = (row) => Math.max(0, Math.min(buffer.baseY, row)); + let target = clamp(anchor.viewportY); + if (anchor.rowsFromBottom <= 2) { + target = clamp(buffer.baseY - anchor.rowsFromBottom); + } else { + const expected = clamp(buffer.baseY - anchor.rowsFromBottom); + const frequencies = new Map(); + for (const text of anchor.context) { + if (text.trim()) frequencies.set(text, (frequencies.get(text) || 0) + 1); + } + const samples = anchor.context.flatMap((text, offset) => + text.trim() ? [{ text, offset, weight: 1 / frequencies.get(text) }] : [] + ); + // Each distinct visible row contributes at most one point: repeated box + // borders cannot outvote the tool result the user is actually reading. + // Capped at the distinct-row count so a sparse viewport (one unique row + // among blanks) can still match; the ambiguity check rejects repeats. + const minimumScore = Math.min(frequencies.size, Math.max(2, frequencies.size * 0.6)); + // Every row a reload fills in BELOW the reader moves the reader's row one + // up from `expected`; a capture with fewer rows below moves it down by at + // most the one screen the downgrade guard tolerates. So the window leans + // up: 4001 candidates from `expected - 4000 + rows` to `expected + rows`, + // which lands gaps up to `4000 - rows` exactly even at the scrollback cap, + // where the replay trims the top and the old index is no longer a fallback. + const rows = this.terminal.rows || 0; + const first = Math.max(0, expected - 4000 + rows); + const last = Math.min(buffer.baseY, expected + rows); + // Cache the search window once: <= 4064 getLine calls, even when all + // 4001 candidates match repeated TUI furniture in a 50k-row buffer. + const text = Array.from( + { length: Math.min(buffer.length, last + anchor.context.length) - first }, + (_, i) => buffer.getLine(first + i)?.translateToString(true) || '' + ); + let bestScore = 0; + let bestRow = null; + let ambiguous = false; + for (let row = first; row <= last; row++) { + let score = 0; + for (const sample of samples) { + if (text[row - first + sample.offset] === sample.text) score += sample.weight; + } + if (score > bestScore + 1e-9) { + bestScore = score; + bestRow = row; + ambiguous = false; + } else if (Math.abs(score - bestScore) <= 1e-9) { + ambiguous = true; + } + } + // Equally good copies are evidence of repeated furniture, not of the + // reader's location. A gap below them makes nearest-to-expected wrong. + if (!ambiguous && bestScore + 1e-9 >= minimumScore) target = bestRow; + } + this.terminal.scrollToLine(target); + return target; + }, + + /** 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(); + }); + }, + /** * Re-take the sticky-scroll baseline from where the viewport now sits. * @@ -4087,13 +4168,10 @@ Object.assign(CodemanApp.prototype, { }, /** - * Post-scroll companion to _noteTerminalUserScroll: hitting the TOP of the - * buffer while scrolling up gives the app a chance to pull the rest of tmux's - * scrollback (issue #205, see _maybeRefetchFullHistory). Shell sessions pull a - * bounded window because their captures can be large; their banner button is - * the unbounded path. Must be called AFTER scrollLines(), since the check is on - * the resulting position, and it is deliberately not folded into - * _noteTerminalUserScroll for exactly that reason. + * After scrollLines(), 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). @@ -4101,19 +4179,26 @@ Object.assign(CodemanApp.prototype, { * what the pull left rather than flashing the state it is about to replace. */ _maybeLoadMoreHistoryOnScroll(lines) { + if (this._earlyReplayTravel?.sessionId === this.activeSessionId) { + this._earlyReplayTravel.moves.push(lines); + return; + } if (lines > 0) { if (this.isTerminalAtBottom()) this._setHistoryNoticeRevealed?.(null); return; } - if (lines === 0 || this.terminal?.buffer?.active?.viewportY !== 0) return; - // An earlier frame of this gesture already started the pull; its own - // completion reveals the notice, so do not flash the pre-pull state now. - if (this._fullHistoryRepullInFlight || this._isLoadingBuffer) return; + if (lines === 0) return; + const buffer = this.terminal?.buffer?.active; + if (buffer?.viewportY !== 0) return; const sessionId = this.activeSessionId; + // An earlier frame already started a pull and owns the notice reveal. + if (this._fullHistoryRepullInFlight || this._isLoadingBuffer) return; Promise.resolve(this._maybeRefetchFullHistory?.()) .catch(() => {}) .then(() => { - if (sessionId && this.activeSessionId === sessionId) this._setHistoryNoticeRevealed?.(sessionId); + if (sessionId && this.activeSessionId === sessionId) { + this._setHistoryNoticeRevealed?.(sessionId); + } }); }, @@ -4698,6 +4783,13 @@ Object.assign(CodemanApp.prototype, { this.terminal.buffer?.active && !this.isTerminalAtBottom() ? this.terminal.buffer.active.viewportY : null; // Which buffer the anchor belongs to, checked again when the write parses. const flushSessionId = this.activeSessionId; + // xterm adjusts marker lines when its circular scrollback trims rows. An + // absolute viewport index does not track that trim and would move the + // reader upward on every live flush at the scrollback cap (#814). + const viewportBuffer = this.terminal.buffer?.active; + const viewportMarker = preserveViewportY !== null + ? this.terminal.registerMarker?.(preserveViewportY - (viewportBuffer.baseY + viewportBuffer.cursorY)) + : null; const writeChunk = joined.slice(0, MAX_FRAME_BYTES); if (_joinedLen > MAX_FRAME_BYTES) { @@ -4724,15 +4816,35 @@ Object.assign(CodemanApp.prototype, { // signal, which is the earliest point the anchor can actually be // reasserted. (The synchronous version passed its regression test only // because the test's write mock moved the viewport synchronously.) - this._restoreTerminalViewport(preserveViewportY, flushSessionId); + // A marker is disposed when its row is trimmed off a full scrollback, + // but also when the stream itself erases scrollback with `ESC[3J`, + // which the narrow and middle strips keep. Fall back to the absolute + // index then, as before markers, rather than sending the reader to row 0. + // (RIS does not dispose it: xterm swaps in a new buffer and the marker + // stays on its old line, which is the same index as this fallback.) + const viewportY = viewportMarker && !viewportMarker.isDisposed ? viewportMarker.line : preserveViewportY; + viewportMarker?.dispose(); + this._restoreTerminalViewport(viewportY, flushSessionId); this._scheduleTerminalWriteFlush(); this._noteMobileImeAuthoritativeOutput(flushedOutputSeq, flushSessionId); }); } catch (err) { + viewportMarker?.dispose(); this._terminalWriteInFlight = false; this._terminalWriteInFlightBytes = 0; throw err; } + // Only live writes can open a new tmux repaint gap; replays cannot (#814). + // Outside the try: the catch above must only cover the write itself. + if (writeChunk.length && flushSessionId && !this._isLoadingBuffer) { + const marked = (this._liveOutputSinceFullPull ||= new Set()); + const newlyMarked = !marked.has(flushSessionId); + marked.add(flushSessionId); + const generations = (this._liveOutputGen ||= new Map()); + generations.set(flushSessionId, (generations.get(flushSessionId) || 0) + 1); + // Mark transitions sync immediately; onScroll is coalesced on all devices. + if (newlyMarked) this._syncHistoryReloadAction?.(); + } const bytesThisFrame = deferred ? MAX_FRAME_BYTES : _joinedLen; const _dt = performance.now() - _t0; if (_dt > 100 || deferred) @@ -5057,6 +5169,7 @@ Object.assign(CodemanApp.prototype, { this._isLoadingBuffer = false; this._loadBufferQueue = null; this._bufferLoadOwner = null; + this._syncHistoryReloadAction?.(); // COD-144: replay (rather than discard) queued live events when the load // painted nothing — the queued prompt is the only content a new session has. // A tmux-capture load replays too, but only the tail: `since` cuts the queue @@ -5068,6 +5181,11 @@ Object.assign(CodemanApp.prototype, { this.batchTerminalWrite(entry.data); } } + const recovery = this._pendingDroppedOutputRecovery; + this._pendingDroppedOutputRecovery = null; + 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 new file mode 100644 index 00000000..c9a371b3 --- /dev/null +++ b/test/history-gap-repair.browser.test.ts @@ -0,0 +1,668 @@ +/** 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'; +import { WebServer } from '../src/web/server.js'; + +type Anchor = { context: string[]; viewportY: number; rowsFromBottom: number }; +type HistoryApp = { + terminal: Terminal & { + _core?: { _renderService?: { dimensions?: { css?: { cell?: { height: number } } } } }; + }; + fitAddon: { proposeDimensions(): { cols: number; rows: number } | undefined }; + sessions: Map<string, object>; + activeSessionId: string; + hideWelcome(): void; + selectSession(sessionId: string): Promise<void>; + _onSessionTerminal(event: { id: string; data: string }): void; + _liveOutputSinceFullPull: Set<string>; + _fullHistoryRepullInFlight: boolean; + _isLoadingBuffer: boolean; + pendingWrites: string[]; + _terminalWriteInFlight: boolean; + _bufferLoadOwner: unknown; + _loadBufferQueue: { data: string; at: number }[] | null; + _selectGeneration: number; + _initGeneration: number; + terminalLoadStates: Map<string, unknown>; + _terminalFontReady: Promise<void>; + _resizeTimeout: number | null; + _lastResizeDims: { cols: number; rows: number } | null; + _syncStickyScrollBaseline(): void; + _captureViewportAnchor(): Anchor; + _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; + repairTest: { pulls: number; anchor: Anchor | null; inject: boolean }; + repairReadiness?: { cols: number; rows: number; frames: number }; + tabLoadTest?: { requested: boolean; release(): void; selection: Promise<void> }; +}; + +const SESSION = 'history-repair-browser'; +const MARKER = 'AFTER-CAPTURE-DURING-DOWNLOAD'; +let server: WebServer; +let browser: Browser; +let baseUrl: string; +const pageEvents = new WeakMap<Page, string[]>(); + +async function setupState(page: Page) { + return page.evaluate(() => { + const app = (window as RepairWindow).app; + const buffer = app?.terminal?.buffer.active; + return { + appLoaded: document.body.classList.contains('app-loaded'), + baseY: buffer?.baseY, + length: buffer?.length, + viewportY: buffer?.viewportY, + cols: app?.terminal?.cols, + rows: app?.terminal?.rows, + resizePending: Boolean(app?._resizeTimeout), + lastResizeDims: app?._lastResizeDims, + proposedDims: app?.fitAddon?.proposeDimensions(), + cellHeight: app?.terminal?._core?._renderService?.dimensions?.css?.cell?.height, + pendingWrites: app?.pendingWrites?.length, + terminalWriteInFlight: app?._terminalWriteInFlight, + isLoadingBuffer: app?._isLoadingBuffer, + bufferLoadOwner: app?._bufferLoadOwner, + loadBufferQueue: app?._loadBufferQueue?.length ?? 0, + activeSessionId: app?.activeSessionId, + selectGeneration: app?._selectGeneration, + sessions: app?.sessions ? [...app.sessions.keys()] : [], + initGeneration: app?._initGeneration, + terminalLoadStates: app?.terminalLoadStates ? [...app.terminalLoadStates] : [], + }; + }); +} + +async function failureDetails(page: Page, error: unknown): Promise<Error> { + const setup = await setupState(page).catch(String); + const buffer = await bufferState(page).catch(String); + return new Error(JSON.stringify({ setup, buffer, events: pageEvents.get(page) }), { cause: error }); +} + +beforeAll(async () => { + server = new WebServer(0, false, true); + await server.start(); + baseUrl = `http://localhost:${server.boundPort}`; + browser = await chromium.launch({ headless: true }); +}, 60_000); + +afterAll(async () => { + await browser?.close(); + await server?.stop(); +}, 30_000); + +async function openTerminal( + touch: boolean, + viewport = touch ? { width: 390, height: 640 } : { width: 1280, height: 800 } +): Promise<{ context: BrowserContext; page: Page }> { + const context = await browser.newContext({ + hasTouch: touch, + isMobile: touch, + viewport, + }); + const page = await context.newPage(); + const events: string[] = []; + pageEvents.set(page, events); + page.on('console', (message) => { + events.push(`console.${message.type()}: ${message.text()}`); + if (events.length > 100) events.shift(); + }); + page.on('pageerror', (error) => events.push(`pageerror: ${error.stack || error.message}`)); + try { + await page.goto(baseUrl, { waitUntil: 'domcontentloaded' }); + await page.waitForFunction(() => document.body.classList.contains('app-loaded')); + await page.waitForFunction(() => { + const app = (window as RepairWindow).app; + return app?.terminal && app._initGeneration > 0 && !app._isLoadingBuffer && app.terminalLoadStates.size === 0; + }); + await page.evaluate(async (session) => { + const app = (window as RepairWindow).app; + // A client-only OMP session isolates the rendering path from real CLI/PTYS. + // Opening it changes layout, so finish the real resize path BEFORE seeding. + app.sessions.set(session, { id: session, mode: 'omp', status: 'idle', name: 'History repair' }); + app.activeSessionId = session; + app.hideWelcome(); + await app._terminalFontReady; + await document.fonts.ready; + // Empty xterm can still carry fallback render metrics. Paint a glyph + // before fitting, then clear it before the fixture's numbered output. + const rendered = Promise.withResolvers<void>(); + const listener = app.terminal.onRender(() => { + listener.dispose(); + rendered.resolve(); + }); + app.terminal.write('W'); + await rendered.promise; + const { promise, resolve } = Promise.withResolvers<void>(); + app.terminal.write('\x1bc', resolve); + await promise; + window.dispatchEvent(new Event('resize')); + }, SESSION); + await page.waitForFunction(() => { + const w = window as RepairWindow; + const app = w.app; + const { cols, rows } = app.terminal; + const proposed = app.fitAddon.proposeDimensions(); + const cellHeight = app.terminal._core?._renderService?.dimensions?.css?.cell?.height || 0; + if ( + cellHeight <= 0 || + proposed?.cols !== cols || + proposed?.rows !== rows || + app._resizeTimeout || + app._isLoadingBuffer || + app.terminalLoadStates.size || + app.pendingWrites.length || + app._terminalWriteInFlight || + app._lastResizeDims?.cols !== cols || + app._lastResizeDims?.rows !== rows + ) { + w.repairReadiness = undefined; + return false; + } + // Synchronous rAF polling: require the initial match plus two more frames. + // An async predicate returns a truthy Promise, which Playwright won't retry. + const previous = w.repairReadiness; + const frames = previous?.cols === cols && previous.rows === rows ? previous.frames + 1 : 1; + w.repairReadiness = { cols, rows, frames }; + return frames >= 3; + }); + await page.evaluate( + async ({ session, marker }) => { + const w = window as RepairWindow; + const app = w.app; + // Startup resets and resize clears have already parsed at fitted geometry. + w.repairTest = { pulls: 0, anchor: null, inject: false }; + const captureAnchor = app._captureViewportAnchor.bind(app); + app._captureViewportAnchor = () => { + const anchor = captureAnchor(); + w.repairTest.anchor = anchor; + return anchor; + }; + const realFetch = window.fetch.bind(window); + window.fetch = ((input: RequestInfo | URL, init?: RequestInit) => { + const url = String(typeof input === 'string' ? input : ((input as Request).url ?? input)); + if (!url.includes(`/api/sessions/${session}/terminal`)) return realFetch(input, init); + if (!url.includes('full=1')) throw new Error(`Unexpected history request: ${url}`); + w.repairTest.pulls++; + return Promise.resolve({ + ok: true, + status: 200, + headers: new Headers(), + json: async () => { + // This is after headers and before replay, inside the real load window. + if (w.repairTest.inject) app._onSessionTerminal({ id: session, data: `\r\n${marker}\r\n` }); + const terminalBuffer = + Array.from({ length: 144 }, (_, i) => `NUMBER-${String(i).padStart(3, '0')}`).join('\r\n') + '\r\n'; + return { + success: true, + data: { + terminalBuffer, + source: 'mux-full-history', + paneHistoryLines: 121, + truncated: false, + fullSize: terminalBuffer.length, + retainedBytes: terminalBuffer.length, + }, + }; + }, + }) as unknown as Promise<Response>; + }) as typeof window.fetch; + // All output still enters through the production terminal event path. + app._onSessionTerminal({ + id: session, + data: Array.from({ length: 60 }, (_, i) => `NUMBER-${String(i).padStart(3, '0')}\r\n`).join(''), + }); + await new Promise<void>((resolve) => app.terminal.write('', resolve)); + }, + { session: SESSION, marker: MARKER } + ); + await page.waitForFunction(() => { + const app = (window as RepairWindow).app; + const buffer = app.terminal.buffer.active; + return ( + buffer.length === 61 && + buffer.baseY === 61 - app.terminal.rows && + !app.pendingWrites.length && + !app._terminalWriteInFlight && + Array.from({ length: 60 }, (_, i) => buffer.getLine(i)?.translateToString(true)).every( + (row, i) => row === `NUMBER-${String(i).padStart(3, '0')}` + ) + ); + }); + // The initial 60 lines stand in for the last successful full-history replay. + await page.evaluate((session) => { + const app = (window as RepairWindow).app; + app.terminal.scrollToBottom(); + app._syncStickyScrollBaseline(); + app._liveOutputSinceFullPull.delete(session); + }, SESSION); + } catch (error) { + const state = await setupState(page).catch(String); + await context.close(); + throw new Error(`Terminal setup failed: ${JSON.stringify({ state, events })}`, { cause: error }); + } + return { context, page }; +} + +/** Finger down scrolls history up; cancel at the endpoint to avoid momentum. */ +async function scrollHistoryByTouch(page: Page, distance: number): Promise<void> { + const box = await page.locator('#terminalContainer').boundingBox(); + if (!box) throw new Error('Terminal container is not visible'); + const x = box.x + box.width / 2; + const y = box.y + Math.min(80, box.height / 4); + const cdp = await page.context().newCDPSession(page); + const before = await page.evaluate(() => (window as RepairWindow).app.terminal.buffer.active.viewportY); + try { + await cdp.send('Input.dispatchTouchEvent', { type: 'touchStart', touchPoints: [{ x, y }] }); + await cdp.send('Input.dispatchTouchEvent', { type: 'touchMove', touchPoints: [{ x, y: y + distance }] }); + await page.waitForFunction((previous) => { + const app = (window as RepairWindow).app; + return app.terminal.buffer.active.viewportY !== previous || app._fullHistoryRepullInFlight; + }, before); + // A trusted cancellation ends the drag without xterm/app momentum changing + // the reading position after the gesture or starting another top pull. + await cdp.send('Input.dispatchTouchEvent', { type: 'touchCancel', touchPoints: [] }); + } finally { + await cdp.detach(); + } +} + +async function burst(page: Page): Promise<void> { + await page.evaluate((session) => { + const app = (window as RepairWindow).app; + // tmux scrolls a whole screen and repaints the last 24 rows. The numbered + // rows 60..119 exist only in tmux and are deliberately absent from this stream. + const repaint = Array.from({ length: 24 }, (_, row) => `\x1b[${row + 1};1H\x1b[2KNUMBER-${120 + row}`).join(''); + app._onSessionTerminal({ id: session, data: `\x1b[24S${repaint}` }); + }, SESSION); + await page.waitForFunction((session) => (window as RepairWindow).app._liveOutputSinceFullPull.has(session), SESSION); +} + +async function bufferState(page: Page) { + return page.evaluate((marker) => { + const w = window as RepairWindow; + const buffer = w.app.terminal.buffer.active; + const rows = Array.from( + { length: buffer.length }, + (_, i) => buffer.getLine(i)?.translateToString(true).trim() || '' + ); + const anchor = w.repairTest.anchor; + // The first non-blank visible row the anchor captured, and where it sat. + const anchorRow = anchor ? anchor.context.findIndex((text) => text.trim()) : -1; + return { + numbers: rows.filter((row) => /^NUMBER-\d+$/.test(row)), + markerHits: rows.filter((row) => row.includes(marker)).length, + anchorOffset: anchor ? rows.indexOf(anchor.context[anchorRow]) - buffer.viewportY : null, + expectedOffset: anchor ? anchorRow : undefined, + pulls: w.repairTest.pulls, + viewportY: buffer.viewportY, + baseY: buffer.baseY, + session: w.app.activeSessionId, + length: buffer.length, + pendingWrites: w.app.pendingWrites.length, + terminalWriteInFlight: w.app._terminalWriteInFlight, + bufferLoadOwner: w.app._bufferLoadOwner, + loadBufferQueue: w.app._loadBufferQueue, + selectGeneration: w.app._selectGeneration, + initGeneration: w.app._initGeneration, + sessions: [...w.app.sessions.keys()], + marked: w.app._liveOutputSinceFullPull.has(w.app.activeSessionId), + loading: w.app._isLoadingBuffer, + inFlight: w.app._fullHistoryRepullInFlight, + }; + }, MARKER); +} + +async function waitForRepair(page: Page): Promise<void> { + await page.waitForFunction(() => { + const w = window as RepairWindow; + return ( + w.repairTest.pulls === 1 && + !w.app._fullHistoryRepullInFlight && + !w.app._isLoadingBuffer && + !w.app.pendingWrites.length && + !w.app._terminalWriteInFlight + ); + }); + // xterm's parse marker is the completion signal for the production flush. + await page.evaluate(async () => { + const app = (window as RepairWindow).app; + await new Promise<void>((resolve) => app.terminal.write('', resolve)); + }); +} + +const allNumbers = Array.from({ length: 144 }, (_, i) => `NUMBER-${String(i).padStart(3, '0')}`); + +describe.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 readHistory(page); + await burst(page); + expect((await bufferState(page)).numbers).not.toContain('NUMBER-090'); + expect((await bufferState(page)).pulls).toBe(0); + const button = page.locator('#historyTruncationBar').getByRole('button', { name: 'Reload history', exact: true }); + 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); + expect(state.anchorOffset).toBe(state.expectedOffset); + expect(state.pulls).toBe(1); + } catch (error) { + throw await failureDetails(page, error); + } finally { + await context.close(); + } + }, 60_000); + + it('keeps output arriving during the capture download exactly once', async () => { + const { context, page } = await openTerminal(touch); + try { + await readHistory(page); + await burst(page); + await page.evaluate(() => { + (window as RepairWindow).repairTest.inject = true; + }); + const button = page.locator('#historyTruncationBar').getByRole('button', { name: 'Reload history', exact: true }); + 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) }); + expect(state.markerHits, detail).toBe(1); + expect(state.numbers, detail).toEqual(allNumbers); + } catch (error) { + throw await failureDetails(page, error); + } finally { + await context.close(); + } + }, 60_000); + + it.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('does not offer a reload action when disabled on this device', async () => { + const { context, page } = await openTerminal(touch); + try { + await page.evaluate(() => { + const app = (window as RepairWindow).app; + app.saveAppSettingsToStorage({ ...app.loadAppSettingsFromStorage(), historyReloadAction: false }); + app._syncHistoryReloadAction(); + }); + await readHistory(page); + await burst(page); + // Wait for the same coalesced scroll synchronization used in production. + await page.evaluate(() => { + const { promise, resolve } = Promise.withResolvers<void>(); + requestAnimationFrame(() => requestAnimationFrame(() => resolve())); + return promise; + }); + expect(await page.getByRole('button', { name: 'Reload history', exact: true }).isVisible()).toBe(false); + expect((await bufferState(page)).pulls).toBe(0); + } catch (error) { + throw await failureDetails(page, error); + } finally { + await context.close(); + } + }, 60_000); +}); + +it('hides Reload history while a marked incoming tab capture is pending', async () => { + const { context, page } = await openTerminal(false); + const incoming = `${SESSION}-incoming`; + try { + await page.evaluate((session) => { + const w = window as RepairWindow; + const app = w.app; + app.terminal.scrollToLine(10); + app.sessions.set(session, { id: session, mode: 'omp', status: 'idle', name: 'Incoming history' }); + app._liveOutputSinceFullPull.add(session); + const response = Promise.withResolvers<Response>(); + const realFetch = window.fetch.bind(window); + const terminalBuffer = 'INCOMING-HISTORY\r\n'; + w.tabLoadTest = { + requested: false, + release: () => + response.resolve( + new Response( + JSON.stringify({ + success: true, + data: { terminalBuffer, source: 'mux-full-history', paneHistoryLines: 1, truncated: false }, + }), + { status: 200, headers: { 'Content-Type': 'application/json' } } + ) + ), + selection: Promise.resolve(), + }; + window.fetch = ((input: RequestInfo | URL, init?: RequestInit) => { + const url = String(typeof input === 'string' ? input : ((input as Request).url ?? input)); + if (!url.includes(`/api/sessions/${session}/terminal`)) return realFetch(input, init); + w.tabLoadTest!.requested = true; + return response.promise; + }) as typeof window.fetch; + }, incoming); + expect((await bufferState(page)).baseY - (await bufferState(page)).viewportY).toBeGreaterThan(5); + await page.evaluate((session) => { + const w = window as RepairWindow; + w.tabLoadTest!.selection = w.app.selectSession(session); + }, incoming); + await page.waitForFunction((session) => { + const w = window as RepairWindow; + return ( + w.tabLoadTest?.requested && + w.app.activeSessionId === session && + w.app.terminalLoadStates.has(session) && + w.app._isLoadingBuffer + ); + }, incoming); + const bar = page.locator('#historyTruncationBar'); + expect(await bar.getByRole('button', { name: 'Reload history', exact: true }).count()).toBe(0); + expect(await bar.isHidden()).toBe(true); + await page.evaluate(async () => { + const test = (window as RepairWindow).tabLoadTest!; + test.release(); + await test.selection; + }); + await page.waitForFunction((session) => { + const app = (window as RepairWindow).app; + return ( + app.activeSessionId === session && + !app.terminalLoadStates.has(session) && + !app._isLoadingBuffer && + !app.pendingWrites.length && + !app._terminalWriteInFlight + ); + }, incoming); + expect( + await page.evaluate(() => { + const buffer = (window as RepairWindow).app.terminal.buffer.active; + return buffer.getLine(0)?.translateToString(true); + }) + ).toBe('INCOMING-HISTORY'); + } catch (error) { + throw await failureDetails(page, error); + } finally { + await context.close(); + } +}, 60_000); + +it('holds an OMP reading row through repeated repaint history and capped live flushes', async () => { + const { context, page } = await openTerminal(true); + const readingRow = 'Reading tool result: src/engine.ts — preserve this row'; + try { + const before = await page.evaluate( + async ({ session, readingRow }) => { + const w = window as RepairWindow; + const app = w.app; + const terminal = app.terminal; + const write = async (data: string) => { + const { promise, resolve } = Promise.withResolvers<void>(); + terminal.write(data, resolve); + await promise; + }; + terminal.reset(); + terminal.options.scrollback = 50_000; + const repeated = [ + '╭──────────────────╮', + '', + '│ Working… │', + '╰──────────────────╯', + '', + '⠋ OMP · processing', + ]; + const rows = Array.from({ length: 50_100 }, (_, i) => + i % 1000 === 999 ? `tool output ${'wrapped context '.repeat(18)}` : repeated[i % repeated.length] + ); + await write(rows.join('\r\n') + '\r\n'); + terminal.scrollToLine(25_000); + app._syncStickyScrollBaseline(); + // Cursor-addressed redraws and CSI S leave repeated TUI furniture in history. + const repaint = repeated.map((text, row) => `\x1b[${row + 1};1H\x1b[2K${text}`).join(''); + app._onSessionTerminal({ id: session, data: `\x1b[6S${repaint}\x1b[6S${repaint}` }); + await write(''); + while (app.pendingWrites.length || app._terminalWriteInFlight) { + const { promise, resolve } = Promise.withResolvers<void>(); + requestAnimationFrame(() => resolve()); + await promise; + } + // Put the distinctive tool result BELOW the three repeated anchor rows. + const buffer = terminal.buffer.active; + const top = buffer.viewportY; + const snapshot = Array.from( + { length: buffer.length }, + (_, i) => buffer.getLine(i)?.translateToString(true) || '' + ); + snapshot[top + 5] = readingRow; + await write('\x1bc' + snapshot.join('\r\n')); + terminal.scrollToLine(top); + app._syncStickyScrollBaseline(); + const seeded = terminal.buffer.active; + const captured = Array.from( + { length: seeded.length }, + (_, i) => seeded.getLine(i)?.translateToString(true) || '' + ); + captured.splice(top + 500, 0, ...Array.from({ length: 120 }, (_, i) => `Recovered tool detail ${i}`)); + const terminalBuffer = captured.join('\r\n'); + const realFetch = window.fetch.bind(window); + window.fetch = ((input: RequestInfo | URL, init?: RequestInit) => { + const url = String(typeof input === 'string' ? input : ((input as Request).url ?? input)); + if (!url.includes(`/api/sessions/${session}/terminal`)) return realFetch(input, init); + w.repairTest.pulls++; + return Promise.resolve({ + ok: true, + status: 200, + headers: new Headers(), + json: async () => { + app._onSessionTerminal({ id: session, data: '\r\nDownload-time output\r\n' }); + return { + success: true, + data: { terminalBuffer, source: 'mux-full-history', paneHistoryLines: 100_000, truncated: false }, + }; + }, + }) as unknown as Promise<Response>; + }) as typeof window.fetch; + app._liveOutputSinceFullPull.add(session); + app._syncHistoryReloadAction(); + return { + offset: captured.indexOf(readingRow) - seeded.viewportY, + viewportY: seeded.viewportY, + baseY: seeded.baseY, + }; + }, + { session: SESSION, readingRow } + ); + const button = page.locator('#historyTruncationBar').getByRole('button', { name: 'Reload history', exact: true }); + await button.tap(); + await waitForRepair(page); + const measure = () => + page.evaluate((readingRow) => { + const app = (window as RepairWindow).app; + const buffer = app.terminal.buffer.active; + let row = -1; + for (let i = 0; i < buffer.length; i++) { + if (buffer.getLine(i)?.translateToString(true) === readingRow) { + row = i; + break; + } + } + return { offset: row - buffer.viewportY, viewportY: buffer.viewportY, baseY: buffer.baseY }; + }, readingRow); + const afterReplay = await measure(); + await page.evaluate((session) => { + (window as RepairWindow).app._onSessionTerminal({ id: session, data: '\r\nPost-replay output\r\n' }); + }, SESSION); + await waitForRepair(page); + const afterFlush = await measure(); + expect({ before, afterReplay, afterFlush }).toEqual({ + before, + afterReplay: { ...afterReplay, offset: before.offset }, + afterFlush: { ...afterFlush, offset: before.offset }, + }); + } finally { + await context.close(); + } +}, 120_000); diff --git a/test/history-notice-reveal.test.ts b/test/history-notice-reveal.test.ts index 435a3954..1607244e 100644 --- a/test/history-notice-reveal.test.ts +++ b/test/history-notice-reveal.test.ts @@ -121,6 +121,8 @@ function makeApp() { let resolvePull: (() => void) | null = null; const app = { activeSessionId: 's1' as string | null, + sessions: new Map([['s1', { mode: 'omp' }]]), + _liveOutputSinceFullPull: new Set<string>(), terminal: { buffer: { active: buffer } }, // Each gesture's pull is held open until the test settles it. _maybeRefetchFullHistory: vi.fn( @@ -184,6 +186,34 @@ describe('partial-history notice: lazy reveal', () => { 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(); app._setHistoryTruncation('s1', TAIL); 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 2b38c3f3..56853297 100644 --- a/test/shell-scroll-history-pull.test.ts +++ b/test/shell-scroll-history-pull.test.ts @@ -49,7 +49,7 @@ function methodSource(source: string, method: string): string { } /** Real terminal-ui.js mixin, for `_estimateReplayRows` / `_replayWouldShrinkBuffer`. */ -function loadTerminalMixin(): Record<string, unknown> { +function loadTerminalMixin(globals: Record<string, unknown> = {}): Record<string, unknown> { const source = readFileSync(resolve(PUBLIC, 'terminal-ui.js'), 'utf8'); const FakeCodemanApp = function () {} as unknown as { prototype: Record<string, unknown> }; const context = vm.createContext({ @@ -63,18 +63,33 @@ function loadTerminalMixin(): Record<string, unknown> { CodemanApp: FakeCodemanApp, window: { addEventListener: vi.fn(), removeEventListener: vi.fn() }, document: { addEventListener: vi.fn() }, + ...globals, }); vm.runInContext(source, context); return FakeCodemanApp.prototype; } -function loadRefetch(): (this: unknown, opts?: { force?: boolean }) => Promise<void> { +function loadRefetch(): (this: unknown, opts?: { force?: boolean; anchor?: string }) => Promise<void> { const app = readFileSync(resolve(PUBLIC, 'app.js'), 'utf8'); const body = methodSource(app, '_maybeRefetchFullHistory'); const context = vm.createContext({ performance, TERMINAL_TAIL_SIZE, TERMINAL_CHUNK_SIZE: 32 * 1024 }); return vm.runInContext(`({ ${body} })._maybeRefetchFullHistory`, context); } +function loadAppMethod(name: string, globals: Record<string, unknown> = {}): Function { + const source = readFileSync(resolve(PUBLIC, 'app.js'), 'utf8'); + return vm.runInContext( + `({ ${methodSource(source, name)} }).${name}`, + vm.createContext({ + performance, + TERMINAL_TAIL_SIZE, + TERMINAL_CHUNK_SIZE: 32 * 1024, + _crashDiag: { log: vi.fn() }, + ...globals, + }) + ); +} + /** The REAL `_setHistoryTruncation`, so the banner state a pull leaves behind is what production would hold. */ function loadSetHistoryTruncation(): (this: unknown, sessionId: string, payload?: Record<string, unknown>) => void { const app = readFileSync(resolve(PUBLIC, 'app.js'), 'utf8'); @@ -125,8 +140,10 @@ function makeApp( _selectGeneration: 7, _fullHistoryRepullInFlight: false, _isLoadingBuffer: false, + _loadBufferQueue: null as { at: number; data: string }[] | null, _fullHistoryRepullAt: new Map<string, number>(), _fullHistoryRepullUseless: new Set<string>(), + _historyReloadDismissed: new Set<string>(), _paneHistoryLines: new Map<string, number>(), terminalBufferCache: new Map<string, string>(), terminal: { @@ -134,12 +151,25 @@ function makeApp( rows: 30, // xterm's scrollback option; 0 leaves the browser-cap check out of a test. options: { scrollback }, - buffer: { active: { length: bufferRows, baseY: 0 } }, scrollToLine: vi.fn(), + buffer: { active: { length: bufferRows, baseY: 0, viewportY: 0, getLine: (_row: number) => undefined } }, scrollToTop: vi.fn(), }, _estimateReplayRows: mixin._estimateReplayRows, _replayWouldShrinkBuffer: mixin._replayWouldShrinkBuffer, + _beginBufferLoad: mixin._beginBufferLoad, + _finishBufferLoad: vi.fn(function (this: unknown, owner: string, opts?: object) { + return (mixin._finishBufferLoad as Function).call(this, owner, opts); + }), + batchTerminalWrite: vi.fn(function (this: unknown, data: string) { + return (mixin.batchTerminalWrite as Function).call(this, data); + }), + _captureViewportAnchor: mixin._captureViewportAnchor, + _restoreViewportAnchor: mixin._restoreViewportAnchor, + pendingWrites: [] as string[], + _scheduleTerminalWriteFlush: vi.fn(), + isTerminalAtBottom: () => true, + _scheduleDroppedOutputRecovery: vi.fn(), _fetchTerminalCapture: vi.fn(async (url: string) => { urls.push(url); return { @@ -159,8 +189,11 @@ function makeApp( setHistoryTruncation.call(app, sessionId, p); }), _resetTerminalForReplay: vi.fn(), - _bufferLoadFinishOpts: vi.fn(() => ({})), - chunkedTerminalWrite: vi.fn(async () => ({ parsedAt: performance.now(), bufferLength: 400, completed: true })), + _bufferLoadFinishOpts: loadAppMethod('_bufferLoadFinishOpts'), + chunkedTerminalWrite: vi.fn(async (_buffer?: string, _size?: number, owner?: string, opts?: object) => { + (mixin._finishBufferLoad as Function).call(app, owner, opts); + return { parsedAt: performance.now(), bufferLength: 400, completed: true }; + }), _syncStickyScrollBaseline: vi.fn(), }; return { app, urls }; @@ -256,6 +289,580 @@ describe('shell scroll-up pulls a bounded window of tmux history', () => { }); }); +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, { + _liveOutputSinceFullPull: new Set<string>(), + _liveOutputGen: new Map<string, number>(), + _earlyReplayTravel: null as { sessionId: string; moves: number[] } | null, + _wasAtBottomBeforeWrite: false, + _scheduleTerminalWriteFlush: vi.fn(), + _restoreTerminalViewport: vi.fn(), + _noteMobileImeAuthoritativeOutput: vi.fn(), + _hasRecentUserScrollUp: () => false, + isTerminalAtBottom: () => app.terminal.buffer.active.viewportY >= app.terminal.buffer.active.baseY - 2, + _setHistoryNoticeRevealed: vi.fn(), + _maybeRefetchFullHistory: vi.fn((opts?: { anchor?: string }) => refetch.call(app, opts)), + }); + Object.assign(app.terminal.buffer.active, { baseY: 100, viewportY: 100 }); + const active = app.terminal.buffer.active as typeof app.terminal.buffer.active & { viewportY: number }; + Object.assign(app.terminal, { + write: vi.fn((_text: string, done: () => void) => done()), + scrollToBottom: vi.fn(), + scrollLines: (n: number) => { + active.viewportY = Math.max(0, Math.min(active.baseY, active.viewportY + n)); + }, + }); + app.terminal.scrollToLine.mockImplementation((row: number) => { + active.viewportY = row; + }); + app.chunkedTerminalWrite.mockImplementation(async (_buffer, _size, owner, opts) => { + active.baseY = 370; + active.viewportY = 370; + active.length = 400; + (mixin._finishBufferLoad as Function).call(app, owner, opts); + return { parsedAt: performance.now(), bufferLength: 400, completed: true }; + }); + const liveOutput = () => { + (mixin.batchTerminalWrite as Function).call(app, 'live repaint'); + (mixin.flushPendingWrites as Function).call(app); + }; + const scroll = async (n: number) => { + active.viewportY = Math.max(0, Math.min(active.baseY, active.viewportY + n)); + (mixin._maybeLoadMoreHistoryOnScroll as Function).call(app, n); + const pull = app._maybeRefetchFullHistory.mock.results.at(-1); + if (pull) await pull.value; + }; + function pauseReplay(beforeComplete = () => {}) { + const replay = app.chunkedTerminalWrite.getMockImplementation()!; + const { promise: gate, resolve: release } = Promise.withResolvers<void>(); + const { promise: ready, resolve: started } = Promise.withResolvers<void>(); + app.chunkedTerminalWrite.mockImplementationOnce(async (...args) => { + active.baseY = 0; + active.viewportY = 0; + started(); + await gate; + const result = await replay(...args); + beforeComplete(); + return result; + }); + return { ready, release }; + } + const reload = () => app._maybeRefetchFullHistory({ force: true, anchor: 'content' }); + return { app, active, urls, liveOutput, scroll, reload, pauseReplay }; + } + + 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._maybeRefetchFullHistory).toHaveBeenCalledWith(); + expect(app._liveOutputSinceFullPull.has('s1')).toBe(false); + }); + + it.each([ + { moves: [-12], distance: 17 }, + { moves: [20], distance: 0 }, + { moves: [-1000], distance: 370 }, + // Reversal after an edge: each move clamps as it would have live. + { moves: [20, -12], distance: 12 }, + { moves: [-1000, 30], distance: 340 }, + ])('replays travel $moves made during an unfinished replay, clamped per move', async ({ moves, distance }) => { + const { app, active, liveOutput, reload, pauseReplay } = makeScrollApp(); + // The replay prepends older rows; give the reader real matching content + // rather than relying on the old blank-buffer bottom-distance fallback. + Object.assign(active, { + getLine: (row: number) => ({ translateToString: () => `history ${row - active.baseY}` }), + }); + liveOutput(); + active.viewportY -= 5; // Read five rows above live output before the manual action. + const paused = pauseReplay(); + 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); + expect(app._maybeRefetchFullHistory).toHaveBeenCalledTimes(1); + paused.release(); + await pull; + expect(active.baseY - active.viewportY).toBe(distance); + expect(app._earlyReplayTravel).toBeNull(); + }); + + it('queues download-time output and replays it through batchTerminalWrite after the capture', async () => { + const { app, urls, liveOutput, reload } = makeScrollApp(); + liveOutput(); + const fetchCapture = app._fetchTerminalCapture.getMockImplementation()!; + const { promise, resolve: release } = Promise.withResolvers<void>(); + app._fetchTerminalCapture.mockImplementationOnce(async (url: string) => { + expect(app._isLoadingBuffer).toBe(true); + const capture = await fetchCapture(url); + await promise; + return capture; + }); + const pull = reload(); + loadAppMethod('_onSessionTerminal').call(app, { id: 's1', data: 'download-time output' }); + expect(app._loadBufferQueue).toEqual([expect.objectContaining({ data: 'download-time output' })]); + release(); + await pull; + expect(urls).toHaveLength(1); + expect(app.batchTerminalWrite).toHaveBeenCalledWith('download-time output'); + expect(app.pendingWrites).toContain('download-time output'); + expect(app._isLoadingBuffer).toBe(false); + // Flushing the replayed queue marks the session again. + (mixin.flushPendingWrites as Function).call(app); + expect(app._liveOutputSinceFullPull.has('s1')).toBe(true); + }); + + it('keeps live output flushed before the final restore dirty for the next manual pull', async () => { + const { app, active, urls, liveOutput, reload, pauseReplay } = makeScrollApp(); + liveOutput(); + const generation = app._liveOutputGen.get('s1'); + const paused = pauseReplay(liveOutput); + const pull = reload(); + await paused.ready; + paused.release(); + await pull; + expect(app._liveOutputGen.get('s1')).toBe(generation! + 1); + expect(app._liveOutputSinceFullPull.has('s1')).toBe(true); + app._fullHistoryRepullAt.clear(); + active.viewportY = active.baseY; + await reload(); + expect(urls).toEqual(['/api/sessions/s1/terminal?full=1', '/api/sessions/s1/terminal?full=1']); + expect(app._liveOutputSinceFullPull.has('s1')).toBe(false); + }); + + it('keeps a clean non-shell session local until the existing top path is reached', async () => { + const { app, active, urls, scroll } = makeScrollApp(); + await scroll(-5); + expect(urls).toEqual([]); + await scroll(-active.viewportY); + expect(urls).toEqual(['/api/sessions/s1/terminal?full=1']); + expect(app._maybeRefetchFullHistory).toHaveBeenCalledWith(); + expect(app.terminal.scrollToLine).toHaveBeenCalledWith(270); + }); + + it('never pulls early for a shell, even after live output', async () => { + const { urls, liveOutput, scroll } = makeScrollApp('shell'); + liveOutput(); + await scroll(-5); + expect(urls).toEqual([]); + await scroll(-95); + expect(urls).toEqual([`/api/sessions/s1/terminal?full=1&tail=${TERMINAL_TAIL_SIZE}`]); + }); + + it('does not dirty a session while replay loading queues its output', () => { + const { app, liveOutput } = makeScrollApp(); + app._isLoadingBuffer = true; + liveOutput(); + expect(app._liveOutputSinceFullPull.size).toBe(0); + }); + + it('keeps marked mid-history travel local in either direction', async () => { + const { active, urls, liveOutput, scroll } = makeScrollApp(); + liveOutput(); + active.viewportY = 50; + await scroll(-5); + await scroll(3); + expect(urls).toEqual([]); + }); + + it.each(['_isLoadingBuffer', '_fullHistoryRepullInFlight'] as const)('respects the %s guard', async (guard) => { + const { app, urls, liveOutput, reload } = makeScrollApp(); + liveOutput(); + app[guard] = true; + await reload(); + expect(urls).toEqual([]); + }); + + 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()); + active.length = 1000; + active.viewportY -= 5; + const eligible = loadAppMethod('_historyReloadActionEligible'); + expect(eligible.call(app)).toBe(true); + await reload(); + expect(urls).toHaveLength(1); + expect(app._resetTerminalForReplay).not.toHaveBeenCalled(); + expect(app._liveOutputSinceFullPull.has('s1')).toBe(true); + expect(app._fullHistoryRepullUseless.has('s1')).toBe(true); + expect(app._historyReloadDismissed.has('s1')).toBe(true); + expect(eligible.call(app)).toBe(false); + }); + + it.each([ + { kind: 'byte-history fallback', data: { terminalBuffer: lines(400), source: 'history' } }, + { kind: 'empty response', data: { terminalBuffer: '', source: 'history' } }, + ])('retires manual reload after a $kind answer', async ({ data }) => { + const { app, active, urls, liveOutput, reload } = makeScrollApp(); + app._fetchTerminalCapture.mockImplementation(async (url: string) => { + urls.push(url); + return { headersAt: performance.now(), headers: { get: () => '' }, json: { success: true, data } }; + }); + liveOutput(); + active.viewportY -= 5; + const eligible = loadAppMethod('_historyReloadActionEligible'); + expect(eligible.call(app)).toBe(true); + await reload(); + expect(urls).toHaveLength(1); + // Only a mux replay clears the mark, so without retiring the action every + // tap would repeat the forced, unbounded capture. + expect(app._liveOutputSinceFullPull.has('s1')).toBe(true); + active.viewportY = Math.max(0, active.baseY - 5); + expect(eligible.call(app)).toBe(false); + }); + + it('keeps manual reload available after a transient error envelope', async () => { + const { app, active, urls, liveOutput, reload } = makeScrollApp(); + app._fetchTerminalCapture.mockImplementation(async (url: string) => { + urls.push(url); + return { headersAt: performance.now(), headers: { get: () => '' }, json: { success: false, data: {} } }; + }); + liveOutput(); + active.viewportY -= 5; + await reload(); + expect(urls).toHaveLength(1); + expect(loadAppMethod('_historyReloadActionEligible').call(app)).toBe(true); + }); + + it('ignores a fallback answer that arrives after an A -> B -> A switch', async () => { + const { app, active, urls, liveOutput, reload } = makeScrollApp(); + const { promise: answer, resolve: respond } = Promise.withResolvers<void>(); + app._fetchTerminalCapture.mockImplementation(async (url: string) => { + urls.push(url); + await answer; + return { + headersAt: performance.now(), + headers: { get: () => '' }, + json: { success: true, data: { terminalBuffer: lines(400), source: 'history' } }, + }; + }); + liveOutput(); + active.viewportY -= 5; + const pending = reload(); + // The user switched away and back; that newer select's capture already + // cleared the dismissal, so the old request's answer is stale. + app._selectGeneration += 2; + app._historyReloadDismissed.delete('s1'); + respond(); + await pending; + expect(urls).toHaveLength(1); + expect(app._historyReloadDismissed.has('s1')).toBe(false); + expect(loadAppMethod('_historyReloadActionEligible').call(app)).toBe(true); + }); + + it.each(['empty', 'tab-switch', 'downgrade', 'bounded-shell', 'rejection'])( + 'flushes download-time output on the %s non-replay path', + async (exit) => { + const { app } = makeApp(exit === 'bounded-shell' ? 'shell' : 'omp', { + bufferRows: 200, + capture: lines(400), + }); + const { promise, resolve: release } = Promise.withResolvers<void>(); + app._fetchTerminalCapture.mockImplementationOnce(async () => { + await promise; + if (exit === 'rejection') throw new Error('offline'); + if (exit === 'tab-switch') app._selectGeneration++; + return { + headersAt: performance.now(), + headers: { get: () => '' }, + json: { data: { terminalBuffer: exit === 'empty' ? '' : lines(10), source: 'mux-full-history' } }, + }; + }); + const pull = refetch.call(app); + expect(app._isLoadingBuffer).toBe(true); + loadAppMethod('_onSessionTerminal').call(app, { id: 's1', data: 'queued while fetching' }); + release(); + await pull; + expect(app.chunkedTerminalWrite).not.toHaveBeenCalled(); + expect(app._finishBufferLoad).toHaveBeenCalledOnce(); + expect(app._finishBufferLoad).toHaveBeenCalledWith(expect.any(String), { flushQueued: true, since: 0 }); + expect(app.pendingWrites).toContain('queued while fetching'); + expect(app._isLoadingBuffer).toBe(false); + } + ); + + it('counts download-time output toward the 128 KiB dropped-output recovery cap', async () => { + const { app } = makeApp('omp', { bufferRows: 30, capture: lines(400) }); + const { promise, resolve: release } = Promise.withResolvers<void>(); + app._fetchTerminalCapture.mockImplementationOnce(async () => { + await promise; + return { + headersAt: performance.now(), + headers: { get: () => '' }, + json: { data: { terminalBuffer: '', source: 'history' } }, + }; + }); + const pull = refetch.call(app); + const onTerminal = loadAppMethod('_onSessionTerminal'); + onTerminal.call(app, { id: 's1', data: 'x'.repeat(70_000) }); + onTerminal.call(app, { id: 's1', data: 'y'.repeat(70_000) }); + expect(app._scheduleDroppedOutputRecovery).toHaveBeenCalledWith('s1', 0, 70_000); + expect(app._loadBufferQueue).toHaveLength(1); + release(); + await pull; + }); + + it.each([false, true])( + 'defers real dropped-output recovery through a slow pull (timer already armed: %s)', + async (armed) => { + vi.useFakeTimers(); + const { promise, resolve: release } = Promise.withResolvers<void>(); + try { + const { app } = makeApp('omp', { bufferRows: 30, capture: lines(400) }); + const retry = vi.fn(({ repainted, stillActive, attempt }) => !repainted && stillActive && attempt < 4); + const schedule = loadAppMethod('_scheduleDroppedOutputRecovery', { + setTimeout, + window: { CodemanDroppedOutput: { DROP_RECOVERY_DELAY_MS: 2000, shouldRetryDroppedOutputRecovery: retry } }, + }); + const refresh = vi.fn(async () => true); + Object.assign(app, { + _scheduleDroppedOutputRecovery: (...args: unknown[]) => schedule.apply(app, args), + _onSessionNeedsRefresh: refresh, + }); + if (armed) schedule.call(app, 's1'); + const fetchCapture = app._fetchTerminalCapture.getMockImplementation()!; + app._fetchTerminalCapture.mockImplementationOnce(async (url) => { + await promise; + return fetchCapture(url); + }); + const pull = refetch.call(app); + const onTerminal = loadAppMethod('_onSessionTerminal'); + onTerminal.call(app, { id: 's1', data: 'x'.repeat(70_000) }); + onTerminal.call(app, { id: 's1', data: 'y'.repeat(70_000) }); + await vi.advanceTimersByTimeAsync(20_000); // Longer than all five normal retry intervals. + expect(app._isLoadingBuffer).toBe(true); + expect(refresh).not.toHaveBeenCalled(); + expect(retry).not.toHaveBeenCalled(); + release(); + await pull; + expect(app._isLoadingBuffer).toBe(false); + await vi.advanceTimersByTimeAsync(2000); + expect(refresh).toHaveBeenCalledOnce(); + expect(refresh).toHaveBeenCalledWith({ id: 's1' }); + expect(retry).toHaveBeenCalledWith(expect.objectContaining({ attempt: 0, repainted: true })); + } finally { + release(); + vi.useRealTimers(); + } + } + ); + + it.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.each([false, true])('keeps the highest same-session deferred attempt (timer armed: %s)', async (armed) => { + vi.useFakeTimers(); + try { + const { app } = makeApp('omp', { bufferRows: 30, capture: lines(400) }); + const retry = vi.fn(() => false); + const schedule = loadAppMethod('_scheduleDroppedOutputRecovery', { + setTimeout, + window: { CodemanDroppedOutput: { DROP_RECOVERY_DELAY_MS: 2000, shouldRetryDroppedOutputRecovery: retry } }, + }); + Object.assign(app, { + _scheduleDroppedOutputRecovery: (...args: unknown[]) => schedule.apply(app, args), + _onSessionNeedsRefresh: vi.fn(async () => false), + }); + if (armed) schedule.call(app, 's1', 0); + const owner = (app._beginBufferLoad as Function).call(app); + schedule.call(app, 's1', 3); + if (armed) await vi.advanceTimersByTimeAsync(2000); + else schedule.call(app, 's1', 0); // A later dropped frame must not reset the bound. + expect(Reflect.get(app, '_pendingDroppedOutputRecovery')).toEqual({ sessionId: 's1', attempt: 3 }); + app._finishBufferLoad(owner); + await vi.advanceTimersByTimeAsync(2000); + expect(retry).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ attempt: 3 })); + } finally { + vi.useRealTimers(); + } + }); + + it('replaces a different session’s deferred attempt rather than merging it', () => { + const { app } = makeApp('omp', { bufferRows: 30, capture: lines(400) }); + const schedule = loadAppMethod('_scheduleDroppedOutputRecovery'); + const owner = (app._beginBufferLoad as Function).call(app); + Object.assign(app, { _pendingDroppedOutputRecovery: { sessionId: 's0', attempt: 4 } }); + schedule.call(app, 's1', 0); + expect(Reflect.get(app, '_pendingDroppedOutputRecovery')).toEqual({ sessionId: 's1', attempt: 0 }); + app._finishBufferLoad(owner); + }); + + it('does not resume a deferred recovery for a tab that is no longer active', () => { + const { app } = makeApp('omp', { bufferRows: 30, capture: lines(400) }); + const owner = (app._beginBufferLoad as Function).call(app); + 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(['_resetAllAppState', '_cleanupPreviousSession'])( + '%s drops a deferred recovery, so the next load on the same tab does not resume it', + (method) => { + const { app } = makeApp('omp', { bufferRows: 30, capture: lines(400) }); + Object.assign(app, { + sessions: new Map(), + ralphStates: new Map(), + terminalBuffers: new Map(), + terminalBufferCache: new Map(), + _xtermSnapshots: new Map(), + projectInsights: new Map(), + idleTimers: new Map(), + pendingHooks: new Map(), + approvals: new Map(), + _parentNameCache: new Map(), + subagentActivity: new Map(), + subagentToolResults: new Map(), + workflowRuns: new Map(), + workflowRunDetails: new Map(), + tabAlerts: new Map(), + attachmentHistoryCounts: new Map(), + _shownCompletions: new Set(), + _flushedOffsets: new Map(), + _localEchoOverlay: { + clear: vi.fn(), + rerender: vi.fn(), + suppressBufferDetection: vi.fn(), + pendingText: '', + }, + _predictiveEcho: { clearPredictions: vi.fn() }, + notificationManager: null, + timerCountdownInterval: null, + runSummaryAutoRefreshTimer: null, + _chunkedWriteGen: 0, + _serializeAddon: null, + _disconnectWs: vi.fn(), + _flushLocalEchoTo: vi.fn(), + _clearTimer: vi.fn(), + _pendingDroppedOutputRecovery: { sessionId: 's1', attempt: 2 }, + activeSessionId: 's1', + }); + const cleanup = loadAppMethod(method, { + MobileDetection: { cleanup: vi.fn(), init: vi.fn() }, + KeyboardHandler: { cleanup: vi.fn(), init: vi.fn() }, + CjkInput: { clear: vi.fn() }, + localStorage: { removeItem: vi.fn() }, + document: { getElementById: () => null }, + clearTimeout, + clearInterval, + CompositionEvent: vi.fn(), + }); + if (method === '_resetAllAppState') cleanup.call(app); + else cleanup.call(app, 's1', { skipSnapshot: true }); + expect(app._clearTimer).toHaveBeenCalledWith('_clientDropRecoveryTimer'); + expect(Reflect.get(app, '_pendingDroppedOutputRecovery')).toBeNull(); + // The reconnect's own refresh on the same tab then finishes a load. + app.activeSessionId = 's1'; + app._finishBufferLoad((app._beginBufferLoad as Function).call(app)); + expect(app._scheduleDroppedOutputRecovery).not.toHaveBeenCalled(); + } + ); + + it.each(['mux-full-history', 'history'])('clears the scroll-pull mark only for a mux capture: %s', async (source) => { + const { app, liveOutput, reload } = makeScrollApp(); + liveOutput(); + const fetchCapture = app._fetchTerminalCapture.getMockImplementation()!; + app._fetchTerminalCapture.mockImplementationOnce(async (url) => { + const capture = await fetchCapture(url); + capture.json.data.source = source; + return capture; + }); + await reload(); + expect(app._liveOutputSinceFullPull.has('s1')).toBe(source !== 'mux-full-history'); + }); + + it('reveals the truncation notice after replay travel reaches the top', async () => { + const { app, active, liveOutput, reload, pauseReplay } = makeScrollApp(); + liveOutput(); + const paused = pauseReplay(); + const pull = reload(); + await paused.ready; + (mixin._maybeLoadMoreHistoryOnScroll as Function).call(app, -10000); + paused.release(); + await pull; + expect(app._setHistoryNoticeRevealed).toHaveBeenCalledWith('s1'); + expect(active.viewportY).toBe(0); + expect(app._maybeRefetchFullHistory).toHaveBeenCalledOnce(); + }); + + it.each([ + { moves: [-10000, 3], revealed: 's1', row: 3 }, + { moves: [-10000, 10000], revealed: null, row: 370 }, + ])('decides the notice per replay move like a live scroll: $moves', async ({ moves, revealed, row }) => { + const { app, active, liveOutput, reload, pauseReplay } = makeScrollApp(); + liveOutput(); + const paused = pauseReplay(); + const pull = reload(); + await paused.ready; + for (const move of moves) (mixin._maybeLoadMoreHistoryOnScroll as Function).call(app, move); + paused.release(); + await pull; + expect(active.viewportY).toBe(row); + expect(app._setHistoryNoticeRevealed).toHaveBeenLastCalledWith(revealed); + expect(app._maybeRefetchFullHistory).toHaveBeenCalledOnce(); + }); + + it('does not reveal the truncation notice on reload without replay travel', async () => { + const { app, liveOutput, reload, pauseReplay } = makeScrollApp(); + liveOutput(); + const paused = pauseReplay(); + const pull = reload(); + await paused.ready; + paused.release(); + await pull; + expect(app._setHistoryNoticeRevealed).not.toHaveBeenCalledWith('s1'); + }); + + it('does not swallow another tab’s travel or clear the old mark when replay is cancelled', async () => { + const { app, active, liveOutput, reload, pauseReplay } = makeScrollApp(); + liveOutput(); + const paused = pauseReplay(); + const pull = reload(); + await paused.ready; + app.activeSessionId = 's2'; + app._selectGeneration++; + active.baseY = 100; + active.viewportY = 100; + (mixin._maybeLoadMoreHistoryOnScroll as Function).call(app, 3); + expect(app._setHistoryNoticeRevealed).toHaveBeenCalledWith(null); + expect(app._earlyReplayTravel?.moves).toEqual([]); + paused.release(); + await pull; + expect(app._liveOutputSinceFullPull.has('s1')).toBe(true); + expect(app._earlyReplayTravel).toBeNull(); + }); +}); + describe('a skipped bounded window never damages the Load full history banner', () => { it('a tail-cut window smaller than the browser is not replayed and never marks the session exhausted', async () => { // The browser holds far more rows than a 1 MiB window carries, and tmux holds @@ -439,3 +1046,707 @@ describe('an unloaded buffer is not held to an older downgrade refusal', () => { expect(app._fullHistoryRepullInFlight).toBe(false); }); }); + +describe('content anchors hold the reader through a history repair', () => { + function fixture(rows: string[], viewportY = 5) { + let content = rows; + const active = { + viewportY, + baseY: rows.length - 3, + length: rows.length, + getLine: vi.fn((row: number) => + content[row] === undefined + ? undefined + : { + translateToString: () => content[row], + } + ), + }; + const app = { terminal: { buffer: { active }, scrollToLine: vi.fn() } }; + const capture = () => (mixin._captureViewportAnchor as Function).call(app); + const restore = (anchor: unknown, next: string[]) => { + content = next; + active.baseY = next.length - 3; + active.length = next.length; + return (mixin._restoreViewportAnchor as Function).call(app, anchor); + }; + return { app, active, capture, restore }; + } + + it('keeps the visible context at its viewport offset when rows are inserted below the reader', () => { + const rows = Array.from({ length: 30 }, (_, i) => `row ${i}`); + rows[5] = ''; + const { app, capture, restore } = fixture(rows); + const anchor = capture(); + const target = restore(anchor, [...rows.slice(0, 12), ...Array(20).fill('recovered'), ...rows.slice(12)]); + expect(target).toBe(5); + expect(app.terminal.scrollToLine).toHaveBeenCalledWith(5); + expect(anchor.viewportY).toBe(5); + expect(anchor.context).toEqual(['', 'row 6', 'row 7']); + }); + + it('keeps the old viewport when two complete contexts match equally well', () => { + const { capture, restore } = fixture(['head', 'A', 'B', 'C', ...Array(20).fill('tail')], 1); + const anchor = capture(); + const next = Array(34).fill('other'); + // Both complete copies sit inside the search window, which reaches up from + // the expected row (11 here) and at most one screen below it. + next.splice(3, 3, 'A', 'B', 'C'); + next.splice(6, 3, 'A', 'wrong', 'wrong'); + next.splice(9, 3, 'A', 'B', 'C'); + expect(restore(anchor, next)).toBe(1); + }); + + it('keeps the old viewport rather than trusting an isolated or absent row', () => { + const rows = Array.from({ length: 30 }, (_, i) => `row ${i}`); + const { capture, restore } = fixture(rows); + const anchor = capture(); + const next = Array(40).fill('other'); + next[8] = 'row 5'; + next[17] = 'row 5'; + expect(restore(anchor, next)).toBe(5); + expect(restore(anchor, Array(40).fill('no match'))).toBe(5); + }); + + it('keeps bottom distance within the bottom tolerance even if matching text exists', () => { + const rows = Array.from({ length: 30 }, (_, i) => `row ${i}`); + const { capture, restore } = fixture(rows, 26); + expect(restore(capture(), [...rows, ...Array(10).fill('new')])).toBe(36); + }); + + it('follows a lone distinctive row among blanks when history is inserted above the reader', () => { + const rows = Array.from({ length: 60 }, (_, i) => `row ${i}`); + for (let i = 20; i < 30; i++) rows[i] = ''; + rows[25] = 'tool result: src/engine.ts'; + const { app, capture, restore } = fixture(rows, 20); + Object.assign(app.terminal, { rows: 10 }); + const anchor = capture(); + const next = [...Array.from({ length: 40 }, (_, i) => `recovered ${i}`), ...rows]; + expect(restore(anchor, next)).toBe(60); + }); + + it('uses the visible tool result rather than a nearer copy of repeated TUI borders', () => { + const repeated = ['╭────────╮', '', '│ Working │', '╰────────╯', '', 'OMP · processing']; + const rows = Array.from({ length: 300 }, (_, i) => repeated[i % repeated.length]); + rows[125] = 'tool result: src/engine.ts'; + const { app, capture, restore } = fixture(rows, 120); + Object.assign(app.terminal, { rows: 18 }); + const anchor = capture(); + const next = [...rows.slice(0, 200), ...Array(60).fill('recovered below reader'), ...rows.slice(200)]; + expect(restore(anchor, next)).toBe(120); + }); + + it.each([false, true])('keeps the old viewport for ambiguous furniture (distinctive row lost: %s)', (lost) => { + const repeated = ['╭────────╮', '', '│ Working │', '╰────────╯', '', 'OMP · processing']; + const rows = Array.from({ length: 300 }, (_, i) => repeated[i % repeated.length]); + if (lost) rows[125] = 'tool result absent from the capture'; + const { app, capture, restore } = fixture(rows, 120); + Object.assign(app.terminal, { rows: 18 }); + const anchor = capture(); + const retained = rows.map((text, i) => (lost && i === 125 ? repeated[i % repeated.length] : text)); + const next = [...retained.slice(0, 200), ...Array(60).fill('recovered below reader'), ...retained.slice(200)]; + expect(restore(anchor, next)).toBe(120); + }); + + it.each(['first-row-only', 'absent'])('bounds a 50k-row search with an %s signature', (kind) => { + const rows = Array.from({ length: 50_000 }, (_, i) => `original ${i}`); + const { app, active, capture, restore } = fixture(rows, 25_000); + Object.assign(app.terminal, { rows: 64 }); + const anchor = capture(); + const next = Array(50_000).fill('other'); + if (kind === 'first-row-only') { + next[25_100] = anchor.context[0]; + next[24_800] = anchor.context[0]; + } + // Even a whole matching viewport outside the budget cannot extend the scan. + next.splice(30_000, anchor.context.length, ...anchor.context); + active.getLine.mockClear(); + expect(restore(anchor, next)).toBe(25_000); + // 4001 possible starts plus the other 63 rows in the full viewport context. + expect(active.getLine.mock.calls.length).toBeLessThanOrEqual(4064); + }); + + it.each([2_500, 3_900])('lands the reader exactly at the scrollback cap with a %i-row gap filled below', (gap) => { + const rows = Array.from({ length: 10_000 }, (_, i) => `line ${i}`); + const { app, capture, restore } = fixture(rows, 6_000); + Object.assign(app.terminal, { rows: 30 }); + const anchor = capture(); + // At the cap the buffer length is fixed: filling `gap` rows below the reader + // trims as many from the top, so the reader's row moves `gap` rows up and the + // old absolute index lands `gap` rows too far down. + const below = 6_000 + 30 + 100; + const recovered = Array.from({ length: gap }, (_, i) => `recovered ${i}`); + const next = [...rows.slice(gap, below), ...recovered, ...rows.slice(below)]; + expect(next).toHaveLength(rows.length); + expect(restore(anchor, next)).toBe(6_000 - gap); + expect(next[6_000 - gap]).toBe('line 6000'); + }); +}); + +describe('manual history banner action', () => { + 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, + loadingBuffer: false, + loadState: false, + paneHistoryLines: undefined as number | undefined, + refreshing: false, + sessionFlags: {} as Record<string, unknown>, + ...options, + }; + 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) }); + Object.assign(base.sessions.get('s1')!, state.sessionFlags); + 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), + _isLoadingBuffer: Boolean(state.loadingBuffer), + terminalLoadStates: new Map(state.loadState ? [['s1', { generation: 1, phase: 'resizing' }]] : []), + _terminalRefreshOwner: state.refreshing ? { sessionId: 's1' } : null, + _paneHistoryLines: new Map<string, number>( + state.paneHistoryLines === undefined ? [] : [['s1', Number(state.paneHistoryLines)]] + ), + 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: 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 }, + // Recorded at the session's first load: a pane opened empty keeps 0 after the + // burst that opens the gap, so a stale 0 must not hide the action (#814). + { opts: { paneHistoryLines: 0 }, visible: true }, + { opts: { paneHistoryLines: 5 }, visible: true }, + { opts: { loadingBuffer: true }, visible: false }, + { opts: { loadState: true }, visible: false }, + { opts: { tiles: true }, visible: false }, + { opts: { active: false }, visible: false }, + { opts: { detached: true }, visible: false }, + // A drop-recovery refresh owns the session while it fetches. + { opts: { refreshing: true }, visible: false }, + // A nested tmux client keeps the local pane in the alternate screen, so + // `?full=1` returns one screen; the route splices in a remote's scrollback. + { opts: { sessionFlags: { docker: true } }, visible: false }, + { opts: { sessionFlags: { adopt: true } }, visible: false }, + { opts: { sessionFlags: { remote: true } }, visible: true }, + ])('visibility is $visible for $opts', ({ opts, visible }) => { + const { app, bar, button } = fixture(opts); + app._syncHistoryReloadAction(); + expect(bar.hidden).toBe(!visible); + if (visible) expect(button()?.textContent).toBe('Reload history'); + }); + + it('announces the truncation notice but keeps a reload-only bar silent', () => { + const { app, bar, button } = fixture(); + app._syncHistoryReloadAction(); + expect(button()!.textContent).toBe('Reload history'); + expect(bar.setAttribute).toHaveBeenLastCalledWith('aria-live', 'off'); + // Revealing the truncation notice in the same bar makes it news again. + app._historyNoticeRevealedFor = 's1'; + app._setHistoryTruncation('s1', { ...TAIL_CUT, truncationReason: 'tail' }); + expect(button()!.textContent).toBe('Load full history'); + expect(bar.setAttribute).toHaveBeenLastCalledWith('aria-live', 'polite'); + }); + + it('labels the dismiss button for what the bar carries', () => { + const { app, dismiss } = fixture(); + app._syncHistoryReloadAction(); + expect(dismiss()!.setAttribute).toHaveBeenCalledWith('aria-label', 'Dismiss Reload history'); + app._historyNoticeRevealedFor = 's1'; + app._setHistoryTruncation('s1', { ...TAIL_CUT, truncationReason: 'tail' }); + expect(dismiss()!.setAttribute).toHaveBeenCalledWith('aria-label', 'Dismiss history notice'); + }); + + it('stands aside while a drop-recovery refresh fetches, then offers Reload again', async () => { + const { app, bar, button } = fixture(); + app._syncHistoryReloadAction(); + const staleButton = button()!; + expect(staleButton.textContent).toBe('Reload history'); + // Hold the recovery's own `?full=1` open: only its owner marks it. + const fetchCapture = app._fetchTerminalCapture.getMockImplementation()!; + const { promise, resolve: release } = Promise.withResolvers<void>(); + app._fetchTerminalCapture.mockImplementationOnce(async (url) => { + await promise; + // A history answer keeps the mark, so Reload is due again afterwards. + const capture = await fetchCapture(url); + capture.json.data.source = 'history'; + return capture; + }); + Object.assign(app, { + _markTerminalBufferReconciled: vi.fn(), + sendResize: vi.fn(), + _localEchoOverlay: { rerender: vi.fn() }, + }); + Object.assign(app.terminal, { scrollToBottom: vi.fn() }); + app._maybeRefetchFullHistory.mockImplementation((opts) => refetch.call(app, opts)); + const recovery = loadAppMethod('_onSessionNeedsRefresh', { + console: { error: vi.fn() }, + computeRewriteScrollLine: () => null, + }).call(app); + expect(app._terminalRefreshOwner).toEqual({ sessionId: 's1' }); + expect(bar.hidden).toBe(true); + // A tap on the button painted before the refresh started fetches nothing. + await staleButton.onclick!(); + await refetch.call(app, { force: true, anchor: 'top' }); + expect(app._fetchTerminalCapture).toHaveBeenCalledOnce(); + expect(app._isLoadingBuffer).toBe(false); + release(); + await recovery; + expect(app._terminalRefreshOwner).toBeNull(); + // The recovery replayed a history answer, so the session is still marked + // and its `finally` offers the action again. + expect(bar.hidden).toBe(false); + expect(button()!.textContent).toBe('Reload history'); + }); + + it('forces a content-anchored pull on tap and resets loading on settle', async () => { + const { app, button } = fixture(); + const { promise, resolve: release } = Promise.withResolvers<void>(); + app._maybeRefetchFullHistory.mockReturnValueOnce(promise); + app._syncHistoryReloadAction(); + const tapped = button()!.onclick!(); + expect(app._maybeRefetchFullHistory).toHaveBeenCalledWith({ force: true, anchor: 'content' }); + expect(button()!.disabled).toBe(true); + expect(button()!.textContent).toBe('Loading…'); + release(); + await tapped; + expect(button()!.disabled).toBe(false); + expect(button()!.textContent).toBe('Reload history'); + }); + + it('retires a refused reload and ignores another tap on the same stale button', async () => { + const { app, bar, button } = fixture(); + app.terminal.buffer.active.length = 1000; + app._maybeRefetchFullHistory.mockImplementation((opts) => refetch.call(app, opts)); + app._syncHistoryReloadAction(); + const staleButton = button()!; + await staleButton.onclick!(); + expect(app._resetTerminalForReplay).not.toHaveBeenCalled(); + expect(app._historyReloadDismissed.has('s1')).toBe(true); + expect(bar.hidden).toBe(true); + expect(button()).toBeUndefined(); + await staleButton.onclick!(); + expect(app._fetchTerminalCapture).toHaveBeenCalledExactlyOnceWith('/api/sessions/s1/terminal?full=1', { + full: true, + }); + expect(app._maybeRefetchFullHistory).toHaveBeenCalledOnce(); + expect(bar.hidden).toBe(true); + }); + + it('shows the action when the matching terminal load state clears', () => { + const { app, bar, button } = fixture({ loadState: true }); + Object.assign(app, { _updateTerminalLoadTab: vi.fn() }); + app._syncHistoryReloadAction(); + expect(bar.hidden).toBe(true); + expect(button()).toBeUndefined(); + loadAppMethod('_clearTerminalLoadState').call(app, 's1', 1); + expect(app.terminalLoadStates.has('s1')).toBe(false); + expect(bar.hidden).toBe(false); + expect(button()!.textContent).toBe('Reload history'); + }); + + it('syncs the action after a marked session finishes loading', () => { + const { app, bar, button } = fixture({ marked: false }); + const owner = (mixin._beginBufferLoad as Function).call(app); + app._liveOutputSinceFullPull.add('s1'); + app._syncHistoryReloadAction(); + expect(app._historyReloadActionEligible()).toBe(false); + expect(bar.hidden).toBe(true); + (mixin._finishBufferLoad as Function).call(app, owner); + expect(app._isLoadingBuffer).toBe(false); + expect(app._historyReloadActionEligible()).toBe(true); + expect(bar.hidden).toBe(false); + expect(button()!.textContent).toBe('Reload history'); + }); + + it('hides a dismissed loading action before the pull settles and keeps it hidden', async () => { + const { app, bar, button, dismiss } = fixture(); + const { promise, resolve: release } = Promise.withResolvers<void>(); + app._maybeRefetchFullHistory.mockReturnValueOnce(promise); + app._syncHistoryReloadAction(); + const tapped = button()!.onclick!(); + expect(button()!.textContent).toBe('Loading…'); + dismiss()!.onclick!(); + expect(bar.hidden).toBe(true); + expect(app._historyReloadDismissed.has('s1')).toBe(true); + app._syncHistoryReloadAction(); + expect(bar.hidden).toBe(true); + release(); + await tapped; + expect(bar.hidden).toBe(true); + expect(button()).toBeUndefined(); + }); + + it.each(['recoverable', 'exhausted', 'capped'])('never duplicates the %s notice load control', async (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); + const label = kind === 'recoverable' ? 'Load full history' : 'Reload history'; + expect(button()!.textContent).toBe(label); + // Hold the pull open the way the real one does: in flight, Reload history + // is no longer eligible, and the sync that follows rebuilds the bar. + const { promise, resolve: release } = Promise.withResolvers<void>(); + app._maybeRefetchFullHistory.mockImplementationOnce(() => { + app._fullHistoryRepullInFlight = true; + return promise.finally(() => { + app._fullHistoryRepullInFlight = false; + }); + }); + const clicked = button()!.onclick!(); + app._syncHistoryReloadAction(); + expect({ text: button()!.textContent, disabled: button()!.disabled }).toEqual({ + text: 'Loading…', + disabled: true, + }); + release(); + await clicked; + // Either way the one control stands in for Reload history, so it keeps the + // reader's line rather than landing on the old row 0. + expect(app._maybeRefetchFullHistory).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ force: true, anchor: 'content' }) + ); + expect({ text: button()!.textContent, disabled: button()!.disabled }).toEqual({ text: label, disabled: false }); + }); + + it('keeps the top anchor for Load full history when Reload history is not eligible', async () => { + const { app, bar, button } = fixture({ marked: false }); + app._historyNoticeRevealedFor = 's1'; + app._setHistoryTruncation('s1', { ...TAIL_CUT, truncationReason: 'tail' }); + expect(bar.hidden).toBe(false); + expect(button()!.textContent).toBe('Load full history'); + await button()!.onclick!(); + expect(app._maybeRefetchFullHistory).toHaveBeenCalledExactlyOnceWith({ force: true, anchor: 'top' }); + }); + + it('does no DOM work without a transition and coalesces all-device onScroll calls per frame', () => { + const { app, state, frames } = fixture({ touch: false }); + app._syncHistoryReloadAction(); + for (let i = 0; i < 100; i++) app._scheduleHistoryReloadActionSync(); + expect(frames).toHaveLength(1); + frames.shift()!(0); + expect(app._renderHistoryTruncationBanner).toHaveBeenCalledOnce(); + state.bottom = true; + app._scheduleHistoryReloadActionSync(); + app._scheduleHistoryReloadActionSync(); + 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'); + }); +}); + +describe('selectSession only clears live-output marks for actual full mux captures', () => { + function makeSelectApp(source = 'mux-full-history') { + const errors = vi.fn(); + const select = loadAppMethod('selectSession', { + console: { log: vi.fn(), error: errors }, + document: { querySelector: () => null }, + localStorage: { setItem: vi.fn(), getItem: () => null }, + requestIdleCallback: vi.fn(), + }); + const { app } = makeApp('omp', { bufferRows: 30, capture: lines(60), payload: { source } }); + const methods = Object.fromEntries( + [ + '_setTerminalLoadState', + '_clearTerminalLoadState', + '_cleanupPreviousSession', + '_renderHistoryTruncationBanner', + '_updateSseSubscription', + 'hideWelcome', + 'markIdleAlertSeen', + '_updateActiveTabImmediate', + 'closeSessionSidebarOnHandheld', + 'renderSessionTabs', + '_updateLocalEchoState', + 'syncTerminalGeometry', + '_markTerminalBufferReconciled', + '_connectWs', + 'scrollToLastNonEmptyLine', + ].map((name) => [name, vi.fn()]) + ); + const selection = Object.assign(app, methods, { + activeSessionId: 's2', + _fullHistoryLoaded: new Set(), + _liveOutputSinceFullPull: new Set(['s1']), + _liveOutputGen: new Map(), + _shouldFocusTerminalForTabSwitch: () => false, + _isStaleSelect: () => false, + sendResize: async () => false, + }); + Object.assign(app.terminal, { scrollToBottom: vi.fn() }); + return { app: selection, select, errors }; + } + + it.each(['mux-full-history', 'history'])('checks the response source: %s', async (source) => { + const { app, select, errors } = makeSelectApp(source); + await select.call(app, 's1'); + expect(errors).not.toHaveBeenCalled(); + expect(app.chunkedTerminalWrite).toHaveBeenCalledOnce(); + expect(Reflect.get(app, '_liveOutputSinceFullPull').has('s1')).toBe(source !== 'mux-full-history'); + }); + + it('keeps the mark when live output arrives during the fresh fetch', async () => { + const { app, select, errors } = makeSelectApp(); + const fetchCapture = app._fetchTerminalCapture.getMockImplementation()!; + app._fetchTerminalCapture.mockImplementationOnce(async (url) => { + app._liveOutputGen.set('s1', (app._liveOutputGen.get('s1') || 0) + 1); + return fetchCapture(url); + }); + await select.call(app, 's1'); + expect(errors).not.toHaveBeenCalled(); + expect(app.chunkedTerminalWrite).toHaveBeenCalledOnce(); + expect(app._liveOutputSinceFullPull.has('s1')).toBe(true); + }); +}); + +describe('drop-recovery refresh clears the live-output mark only for a mux capture', () => { + function makeRefreshApp(source = 'mux-full-history') { + const errors = vi.fn(); + const refresh = loadAppMethod('_onSessionNeedsRefresh', { + console: { error: errors }, + computeRewriteScrollLine: () => null, + }); + const { app } = makeApp('omp', { bufferRows: 30, capture: lines(60), payload: { source } }); + const recovery = Object.assign(app, { + _tilesOwnTerminal: () => false, + _markTerminalBufferReconciled: vi.fn(), + sendResize: vi.fn(), + _localEchoOverlay: { rerender: vi.fn() }, + _liveOutputSinceFullPull: new Set(['s1']), + _liveOutputGen: new Map([['s1', 7]]), + _historyReloadDismissed: new Set(['s1']), + _syncHistoryReloadAction: vi.fn(), + }); + Object.assign(app.terminal, { scrollToBottom: vi.fn() }); + /** Full capture refused by the shrink guard, then the `?tail=` fallback. */ + const mockShrinkFallback = (beforeTail = () => {}) => { + recovery._replayWouldShrinkBuffer = vi.fn(() => true); + recovery._fetchTerminalCapture.mockResolvedValueOnce({ + headersAt: performance.now(), + headers: { get: () => '' }, + json: { data: { terminalBuffer: lines(10), source: 'mux-full-history' } }, + }); + recovery._fetchTerminalCapture.mockImplementationOnce(async () => { + beforeTail(); + return { + headersAt: performance.now(), + headers: { get: () => '' }, + json: { data: { terminalBuffer: lines(60), source: 'history' } }, + }; + }); + }; + return { app: recovery, refresh, errors, mockShrinkFallback }; + } + + it('clears the mark and dismissal after replaying a full mux capture', async () => { + const { app, refresh, errors } = makeRefreshApp(); + expect(await refresh.call(app)).toBe(true); + expect(errors).not.toHaveBeenCalled(); + expect(app._fetchTerminalCapture).toHaveBeenCalledWith('/api/sessions/s1/terminal?full=1', { full: true }); + expect(app.chunkedTerminalWrite).toHaveBeenCalledOnce(); + expect(app._liveOutputSinceFullPull.has('s1')).toBe(false); + expect(app._historyReloadDismissed.has('s1')).toBe(false); + }); + + it('keeps the mark and dismissal when the mux replay is incomplete', async () => { + const { app, refresh, errors } = makeRefreshApp(); + app.chunkedTerminalWrite.mockImplementationOnce(async () => ({ + parsedAt: performance.now(), + bufferLength: 400, + completed: false, + })); + await refresh.call(app); + expect(errors).not.toHaveBeenCalled(); + expect(app.chunkedTerminalWrite).toHaveBeenCalledOnce(); + expect(app._liveOutputSinceFullPull.has('s1')).toBe(true); + expect(app._historyReloadDismissed.has('s1')).toBe(true); + }); + + it('keeps the mark and dismissal for a history answer', async () => { + const { app, refresh, errors } = makeRefreshApp('history'); + expect(await refresh.call(app)).toBe(true); + expect(errors).not.toHaveBeenCalled(); + expect(app.chunkedTerminalWrite).toHaveBeenCalledOnce(); + expect(app._liveOutputSinceFullPull.has('s1')).toBe(true); + expect(app._historyReloadDismissed.has('s1')).toBe(true); + }); + + it('keeps the mark and dismissal when live output arrives during the fetch', async () => { + const { app, refresh, errors } = makeRefreshApp(); + const fetchCapture = app._fetchTerminalCapture.getMockImplementation()!; + app._fetchTerminalCapture.mockImplementation(async (url) => { + app._liveOutputGen.set('s1', 8); + return fetchCapture(url); + }); + expect(await refresh.call(app)).toBe(true); + expect(errors).not.toHaveBeenCalled(); + expect(app.chunkedTerminalWrite).toHaveBeenCalledOnce(); + expect(app._liveOutputSinceFullPull.has('s1')).toBe(true); + expect(app._historyReloadDismissed.has('s1')).toBe(true); + }); + + it('retires Reload history when a full mux capture falls back to a history tail', async () => { + const { app, refresh, errors, mockShrinkFallback } = makeRefreshApp(); + app._historyReloadDismissed.clear(); + mockShrinkFallback(); + expect(await refresh.call(app)).toBe(true); + expect(errors).not.toHaveBeenCalled(); + expect(app._fetchTerminalCapture).toHaveBeenLastCalledWith(`/api/sessions/s1/terminal?tail=${TERMINAL_TAIL_SIZE}`); + expect(app.chunkedTerminalWrite).toHaveBeenCalledOnce(); + // tmux holds less than the browser: the same refusal signal the manual + // reload retires on, so a tap would only run another forced full capture. + expect(app._liveOutputSinceFullPull.has('s1')).toBe(true); + expect(app._historyReloadDismissed.has('s1')).toBe(true); + }); + + it('does not retire Reload history from a fallback whose refresh lost its owner', async () => { + const { app, refresh, errors, mockShrinkFallback } = makeRefreshApp(); + app._historyReloadDismissed.clear(); + mockShrinkFallback(() => Reflect.set(app, '_terminalRefreshOwner', { sessionId: 's1' })); + expect(await refresh.call(app)).toBe(false); + expect(errors).not.toHaveBeenCalled(); + expect(app.chunkedTerminalWrite).not.toHaveBeenCalled(); + expect(app._historyReloadDismissed.has('s1')).toBe(false); + }); + + it.each(['session', 'owner'])('keeps the mark when the refresh loses its %s during replay', async (changed) => { + const { app, refresh, errors } = makeRefreshApp(); + app.chunkedTerminalWrite.mockImplementationOnce(async () => { + if (changed === 'session') app.activeSessionId = 's2'; + else Reflect.set(app, '_terminalRefreshOwner', { sessionId: 's1' }); + return { parsedAt: performance.now(), bufferLength: 400, completed: true }; + }); + expect(await refresh.call(app)).toBe(true); + expect(errors).not.toHaveBeenCalled(); + expect(app._liveOutputSinceFullPull.has('s1')).toBe(true); + expect(app._historyReloadDismissed.has('s1')).toBe(true); + }); +}); diff --git a/test/terminal-resilience.test.ts b/test/terminal-resilience.test.ts index 94fb7b1c..939b7989 100644 --- a/test/terminal-resilience.test.ts +++ b/test/terminal-resilience.test.ts @@ -250,7 +250,10 @@ describe('terminal capture deadline covers the response body', () => { for (const site of ['_onSessionNeedsRefresh(event = {}) {', 'async _onSessionClearTerminal(data) {']) { const start = app.indexOf(site); expect(start, `${site} not found — renamed?`).toBeGreaterThan(-1); - const body = app.slice(start, start + 4000); + // The whole method, not a fixed-size window: a byte count broke on an + // unrelated comment, and a reset past it would have read as missing. + const next = /^ {2}(?:async )?[A-Za-z_$][\w$]*\(/m.exec(app.slice(start + 1)); + const body = next ? app.slice(start, start + 1 + next.index) : app.slice(start); expect(body, `${site} must clear via _resetTerminalForReplay`).toContain('this._resetTerminalForReplay()'); expect(body, `${site} hand-rolled a clear again`).not.toContain('this.terminal.clear()'); } diff --git a/test/terminal-viewport-marker.test.ts b/test/terminal-viewport-marker.test.ts new file mode 100644 index 00000000..28f3cce3 --- /dev/null +++ b/test/terminal-viewport-marker.test.ts @@ -0,0 +1,131 @@ +/** + * Live flushes at the scrollback cap must preserve the row being read, not its + * absolute buffer index. Use real asynchronous xterm parsing so markers track + * circular-buffer trimming before the mixin restores the viewport (#814). + */ +import { readFileSync } from 'node:fs'; +import { resolve } from 'node:path'; +import vm from 'node:vm'; +import { describe, expect, it } from 'vitest'; +import xtermHeadless, { type Terminal as HeadlessTerminal } from '@xterm/headless'; + +const { Terminal } = xtermHeadless as unknown as { + Terminal: new (opts: Record<string, unknown>) => HeadlessTerminal; +}; + +const read = (rel: string) => readFileSync(resolve(import.meta.dirname, '..', rel), 'utf8'); +const write = (terminal: HeadlessTerminal, data: string) => new Promise<void>((done) => terminal.write(data, done)); +const topRow = (terminal: HeadlessTerminal) => { + const buffer = terminal.buffer.active; + return buffer.getLine(buffer.viewportY)?.translateToString(true); +}; + +function loadHarness(terminal: HeadlessTerminal) { + const CodemanApp = function CodemanApp(this: unknown) {}; + const context = vm.createContext({ + CodemanApp, + window: {}, + globalThis: {}, + document: { getElementById: () => null, querySelector: () => null }, + console, + MobileDetection: { isTouchDevice: () => false, getDeviceType: () => 'desktop' }, + Object, + performance, + setTimeout, + clearTimeout, + }); + vm.runInContext(read('src/web/public/constants.js'), context, { filename: 'constants.js' }); + vm.runInContext(read('src/web/public/terminal-ui.js'), context, { filename: 'terminal-ui.js' }); + + const app = new (CodemanApp as unknown as new () => Record<string, any>)(); + Object.assign(app, { + terminal, + pendingWrites: [], + sessions: new Map([['reading', { mode: 'claude' }]]), + activeSessionId: 'reading', + _isLoadingBuffer: false, + _wasAtBottomBeforeWrite: false, + _localEchoOverlay: null, + isTerminalAtBottom: () => terminal.buffer.active.viewportY === terminal.buffer.active.baseY, + _scheduleTerminalWriteFlush: () => {}, + _noteMobileImeAuthoritativeOutput: () => {}, + _hasRecentUserScrollUp: () => false, + _syncHistoryReloadAction: () => {}, + }); + return app; +} + +async function flushAtScrollbackCap(markersEnabled: boolean) { + const terminal = new Terminal({ cols: 80, rows: 10, scrollback: 100, allowProposedApi: true }); + try { + // Hide only the marker API for the negative control; writes, buffer trims, + // scrolling, and _restoreTerminalViewport remain the real implementations. + if (!markersEnabled) Object.defineProperty(terminal, 'registerMarker', { value: undefined }); + const app = loadHarness(terminal); + await write(terminal, Array.from({ length: 200 }, (_, i) => `line ${i}\r\n`).join('')); + expect(terminal.buffer.active.baseY).toBe(100); + + const buffer = terminal.buffer.active; + let readingRow = -1; + for (let row = 0; row < buffer.length; row++) { + if (buffer.getLine(row)?.translateToString(true) === 'line 140') { + readingRow = row; + break; + } + } + expect(readingRow).toBeGreaterThanOrEqual(0); + terminal.scrollToLine(readingRow); + expect(topRow(terminal)).toBe('line 140'); + expect(app.isTerminalAtBottom()).toBe(false); + + for (let flush = 0; flush < 5; flush++) { + app.pendingWrites.push(Array.from({ length: 4 }, (_, i) => `line ${200 + flush * 4 + i}\r\n`).join('')); + app.flushPendingWrites(); + // This barrier runs after the flush's write callback, including its + // viewport restoration. No wall-clock delay stands in for parsing. + await write(terminal, ''); + expect(app._terminalWriteInFlight).toBe(false); + } + return topRow(terminal); + } finally { + terminal.dispose(); + } +} + +describe('live terminal viewport at the scrollback cap', () => { + it('keeps line 140 visible across five flushes using xterm markers', async () => { + expect(await flushAtScrollbackCap(true)).toBe('line 140'); + }); + + it('discriminates against absolute-index restoration without markers', async () => { + const row = await flushAtScrollbackCap(false); + expect(row).not.toBe('line 140'); + expect(row).toBe('line 160'); + }); + + // ESC[3J (kept by the narrow and middle strips) erases scrollback and disposes + // the marker the same way a trim does; the reader must keep their row, not + // land on row 0. + it.each([true, false])( + 'keeps the reader on their row when one flush clears scrollback and reprints it (markers: %s)', + async (markersEnabled) => { + const terminal = new Terminal({ cols: 80, rows: 10, scrollback: 1000, allowProposedApi: true }); + try { + if (!markersEnabled) Object.defineProperty(terminal, 'registerMarker', { value: undefined }); + const app = loadHarness(terminal); + const history = Array.from({ length: 200 }, (_, i) => `line ${i}\r\n`).join(''); + await write(terminal, history); + terminal.scrollToLine(100); + expect(topRow(terminal)).toBe('line 100'); + expect(app.isTerminalAtBottom()).toBe(false); + app.pendingWrites.push(`\x1b[H\x1b[2J\x1b[3J${history}`); + app.flushPendingWrites(); + await write(terminal, ''); + expect(app._terminalWriteInFlight).toBe(false); + expect(topRow(terminal)).toBe('line 100'); + } finally { + terminal.dispose(); + } + } + ); +});