From e44d586f9375fc6cbef0d5aa1943b73b66d84433 Mon Sep 17 00:00:00 2001 From: Hadrien Kerlero <199662351+HadrienKerlero@users.noreply.github.com> Date: Mon, 23 Nov 2026 15:22:07 +0100 Subject: [PATCH] fix(web): keep the reader's row when a flush clears scrollback (#814) - flushPendingWrites falls back to the absolute viewport index when the write disposed the marker, which ESC[3J or RIS also do (the narrow and middle strips keep 3J), instead of sending the reader to row 0. - The live-output mark block moves below the write's try/catch, so the catch only covers the write. - Test: one flush of ESC[H ESC[2J ESC[3J plus a reprint keeps the reader on line 100, with and without markers. --- docs/architecture-invariants.md | 2 +- src/web/public/terminal-ui.js | 29 +++++++++++++++------------ test/terminal-viewport-marker.test.ts | 26 ++++++++++++++++++++++++ 3 files changed, 43 insertions(+), 14 deletions(-) diff --git a/docs/architecture-invariants.md b/docs/architecture-invariants.md index 5763384e..2fb1ce2e 100644 --- a/docs/architecture-invariants.md +++ b/docs/architecture-invariants.md @@ -253,7 +253,7 @@ Further detail: the `: ` form (`w3-myapp: fix the login redirect` **Full-scrollback replay** (COD-164/#148, reworked for #205): `GET /api/sessions/:id/terminal?full=1` returns the ENTIRE tmux scrollback (capture-pane `-e -S -<lines>` bounded by the configured history limit, explicit `maxBuffer` from the terminal-history config, early byte-cap before normalization, CRLF-normalized for shell panes). On success the capture is returned ALONE (`source='mux-full-history'` — it supersedes the byte buffer; no duplication). The first load of each non-shell TUI session per page requests `full=1` (`_fullHistoryLoaded` Set in app.js — the old one-shot `_initialFullBufferLoad` flag was consumed by whichever tab auto-selected, leaving every other TUI tab one frame of history). Shell sessions instead load a bounded window of tmux's RENDERED history on every selection, automatic drop recovery, clear and tile load (`SHELL_LOAD_QUERY` in constants.js: `?full=1&tail=1MiB&lines=10000&alt=recording`): a 100k-line shell capture can be tens of MiB, and automatically parsing it makes tab-switch latency scale with the entire session (`lines=` bounds the synchronous capture-pane, about 8 ms per 1000 lines). They never replay the raw byte recording ahead of the visible frame any more: it holds full-screen repaints (an ssh'd tmux, `less`, any TUI) drawn for the pane height of the moment, and replayed into a terminal of another height each repaint's last newline scrolls its top row into scrollback, so one line tmux holds once showed up dozens of times. Because `lines=` is shallower than xterm's scrollback, the route reports a cut: the capture's `display-message` query also reads `#{history_size}` (`PaneCaptureOptions.capturedHistoryLines`, the same field the route reports as `paneHistoryLines`), and a full capture whose CLIENT bound (`lines=` below the configured `tmuxHistoryLimit`) left lines in tmux comes back `truncated`, `truncationReason: 'tail'`. ⚠️ Only a client bound below the ceiling counts: a request without `lines=` is bounded by the ceiling itself, and on tmux before 3.7 a live pane can hold more than a lowered ceiling, which no request can read. ⚠️ **A pane in the alternate screen keeps no tmux history**, and a nested tmux client (remote SSH and Docker cases, or `tmux`/`ssh -t host tmux` run by hand) holds its pane there, so its full capture is one screen. The same query reads `#{alternate_on}` (`capturedAlternateOn`), and a request carrying `alt=recording` (only `SHELL_LOAD_QUERY`) is then answered the old way, the visible frame over the tailed byte recording, which still carries the scrollback; agents, scroll pulls and **Load full history** never send it. `#{alternate_on}` cannot tell a nested tmux from vim, `less` or `htop`, so a local shell with one of those open takes the same fallback until it exits (the pre-fix load, with its repaint duplicates). Shell FULL history is explicit-button-only; reaching the top during an ordinary wheel/touch gesture must not reset xterm and replay the multi-megabyte capture on its main thread. That gesture instead pulls a BOUNDED window of it (`?full=1&tail=<TERMINAL_TAIL_SIZE>`, so a capture beyond 1 MiB comes back `truncationReason: 'tail'` and the banner offers the rest), and skips the replay when the window holds no more rows than the browser already has. ⚠️ **That skip runs BEFORE the downgrade guard, and it never touches the banner state**: the guard reads "smaller than the browser" as "tmux has nothing more to give", true of an unbounded capture and false of a window cut at the tail size, so a bounded window that reached it marked the session `exhausted` and removed **Load full history** while tmux still held the rest; and re-labelling the banner from a skipped payload would call a terminal that holds all of a Load full history pull "the most recent 1 MiB". A skipped window that came back truncated puts the session on the 60 s cooldown (`_fullHistoryRepullUseless`), because it can never reach anything older than the browser shows and `tail` is applied AFTER the server's synchronous `capture-pane` of the whole history, so each ask costs every client an event-loop stall (about 1 s at 100k lines; measured capture details below); an untruncated one keeps the 4 s cooldown, since it is all of tmux's history and the next burst can add to it. Declining the gesture outright was a dead end: after any burst a shell pane held about one screen of browser scrollback, and the button renders only once a replay was truncated, so a young shell tab had no way back to history tmux still held. Other modes re-pull `full=1` only at the top of the local buffer, and pressing **Load full history** forces the request for any recoverably truncated session (`_maybeRefetchFullHistory`, 4s per-session gesture cooldown, in-flight + tab-switch guards, viewport position held across the replay); Shell full pulls are not retained in the tab cache, so the next switch stays bounded. Chunked replay enqueues 32 KiB pieces across safe yields, appends an xterm parse marker, then releases the live-output gate; output arriving after that release stays ordered behind the snapshot, and the marker callback supplies accurate parse timing. ⚠️ **How the load ENDS depends on where the payload came from**, and `_bufferLoadFinishOpts` (app.js) is the one place that decides it for all four fetch-and-write paths. A payload built from the server's accumulated byte history is current up to the response, so the events queued during the load already appear in it and stay DISCARDED; replaying them would duplicate output, most visibly Ink's cursor-up redraws. A pane capture (`mux-visible` or `mux-full-history`) is current only up to CAPTURE time, so `_finishBufferLoad` replays the queue from the response's own arrival timestamp (`since`) and the pre-capture events stay dropped. ⚠️ **A path that then restores a scroll position must re-take the sticky-scroll baseline** (`_syncStickyScrollBaseline`): the replay runs inside `chunkedTerminalWrite` before its promise resolves, with the terminal freshly reset, so `batchTerminalWrite` samples `_wasAtBottomBeforeWrite` as true and the next `flushPendingWrites` would scroll to the bottom over the restore. ⚠️ The cutoff is a client-side timestamp and the server broadcasts on a batch timer (8ms WebSocket, 16-50ms SSE), so a batch pending when the capture ran arrives after the response and replays although the capture holds it — bounded by one batch interval, and closable only server side by flushing that batch before the capture. Tests for the three: `test/terminal-flush-budget.test.ts` pins which sources flush, `test/terminal-buffer-flush.test.ts` pins the `since` cutoff and the baseline re-take, and `test/capture-load-window.browser.test.ts` drives both against a live server. Live output is separately one-chunk-in-flight: xterm's callback releases each 32/64 KiB write before the next is submitted, keeping the remainder in the app queue where the 128 KiB cap can observe it instead of hiding an unbounded backlog in xterm's private WriteBuffer. While WebSocket owns terminal I/O, parallel SSE terminal/output-recovery events are discarded before JSON parsing; fallback recovery is single-flight per active session so backpressure cannot start overlapping reset+replay cycles. The route exposes capture/prepare totals in `Server-Timing`, while `[TERMINAL-PERF]` separates TTFB, body/JSON, reset+parse and total time for both selection and on-demand full pulls; parse completion is not a browser compositor/GPU paint measurement. The re-pull exists because xterm's buffer is only a WINDOW onto tmux's history and two things shrink it: tmux coalesces bursty output into pane REPAINTS that overwrite rows instead of emitting linefeeds (measured: a 60-line burst added 1 row of browser scrollback and destroyed 34), and a tab switch replays only the visible frame. tmux's own history is intact throughout — the browser just has to ask for it again. Gesture-triggered rather than polling because at a 100k history limit the capture can be megabytes. ⚠️ **The capture ENDS with a cursor move back to the pane's own caret position** (`formatCursorRestore`, from the same `display-message` query the visible-frame path uses). The linear replay otherwise leaves the caret wherever the last character landed — the bottom-most row carrying text, which for an agent CLI is the status line — so the caret sat on the composer's border instead of its input line and every cursor-relative update the CLI sent afterwards was measured from the wrong row, until its next full redraw silently repaired it (that self-repair is why the report read as "it fixes itself as soon as Claude writes a line"). ⚠️ **The move is RELATIVE — up `rows - 1 - cursor_y`, then `\r`, then right `cursor_x` — never `CUP`.** `\x1b[<row>;<col>H` numbers rows from the top of the browser's screen, so it lands correctly only while the browser's row count equals `pane_height`, and nothing guarantees that: `resizeWindow` issues its tmux resize fire-and-forget and returns immediately, so a capture can be taken before a requested resize has applied, and `_onSessionNeedsRefresh` sends no resize at all. Counting up from the last replayed row anchors to the content both ends share. Restoring the cursor makes ROW ALIGNMENT load-bearing on this path: **no transform that can DELETE A LINE may run over a full-history capture**, because every deletion shifts the frame out from under the restored position. Four had accumulated — trailing blank rows stripped by `\n+$`, `stripInkRedrawBloat`, the `CLAUDE_BANNER_PATTERN` trim that cuts everything above the banner, and `LEADING_WHITESPACE_PATTERN` — each correct for a byte stream of successive frames and each wrong for a single rendered frame. ⚠️ **Those skips key on `isFullCapture`, meaning a capture actually came back — never on `?full=1` alone.** When `captureActivePaneBuffer` returns null (ENOBUFS, a timeout, a vanished pane, or a session with no mux at all) the reply falls back to `session.terminalBuffer`, which IS a byte stream and must still be stripped; gating on the query flag returned it whole, and a direct-PTY session takes that path on every first selection rather than only during an outage. ⚠️ A capture holding nothing visible (`hasVisibleContent`) returns `''`, because the caller reads an empty capture as "unavailable" and keeps its byte history — retaining trailing blank rows made an all-blank pane non-empty, which would have replaced real history with a blank screen from the server side, where `_replayWouldShrinkBuffer` cannot see it. ⚠️ **"One line per screen row" holds only where no row was hard-wrapped**: `-J` joins a wrapped row into its logical line (measured: a 100-character line in a 40-column pane captures as 10 lines against a 12-row pane), and the counts reconcile only once the browser xterm re-wraps at the same width — the same assumption `_estimateReplayRows` already documents. Tests: `test/tmux-capture-full-history.test.ts` covers the cursor move, the trim pairing and `hasVisibleContent`; `test/routes/session-routes.test.ts` covers a surviving blank first row, an unstripped byte-history fallback, and an empty capture leaving history intact. ⚠️ **The re-pull must never DOWNGRADE the buffer** (#205 round 2): the same reasoning that makes it a win for a shell pane makes it destructive for a repaint-mode CLI pane, where tmux keeps no history of its own (`history_size≈0` measured for a Claude pane) and the capture is roughly ONE frame while xterm may hold hundreds of rows of replayed frames — `_resetTerminalForReplay()` + rewrite then deletes history mid-scroll ("goes back a bit, repeats blocks, gets worse the further up I go"; measured A/B on a live pane: 341 rows → 42 with the guard off). `_replayWouldShrinkBuffer()` (terminal-ui.js) estimates the capture's rendered rows — escape sequences stripped, `capture-pane -J` re-wrapping accounted for — and the pull is skipped when that is more than one screen short of `buffer.active.length`. The one-screen tolerance matters: both sides are estimates (the buffer length counts trailing blank rows), so only a clear downgrade is refused. A refused session joins `_fullHistoryRepullUseless`, raising its cooldown from 4s to 60s so a hollow pane stops re-fetching megabytes on every scroll-up. Tests: `test/tmux-capture-full-history.test.ts`, `test/tmux-scrollback-eol.test.ts`, `test/terminal-scroll-routing.test.ts`, `test/terminal-flush-budget.test.ts`. -**Repair while reading (#814)** is a manual **Reload history** action inside the existing history banner on desktop and touch devices, enabled by default and toggleable per device in Settings → Terminal & Input → Scrolling & rendering (`historyReloadAction`). It is offered only for a marked non-shell active session while scrolled away from live output, not Docker or adopted (their local pane hosts a nested tmux client in the alternate screen, so `?full=1` returns one screen the downgrade guard refuses; remote sessions stay eligible, since the route splices the remote scrollback in), not detached, not owned by tiles, with no pull or buffer load in flight, no terminal load state for the session (a tab switch sets it before the buffer load opens), and no drop-recovery refresh owning the session (`_terminalRefreshOwner`, set for the whole fetch, before that refresh opens its buffer load). `_maybeRefetchFullHistory` returns early on that same owner, so Reload, Load full history and the top-of-buffer pull all stand aside instead of running a second capture whose download-time queue the refresh's own load would replace; the refresh re-syncs the action when it starts and when its `finally` releases the owner. `paneHistoryLines` is deliberately not consulted: it is recorded at the last load, so a session first opened empty keeps 0 after the very burst that opens the gap (#814). The bar is a polite live region (`role="status"`), but only the truncation notice is announced: a reload-only bar sets `aria-live="off"` before it re-renders, since it comes back on nearly every scroll-up in a busy tab, and its button stays reachable with Tab. Its × is labelled for what the bar carries: "Dismiss history notice" with the notice, "Dismiss Reload history" without it. A revealed truncation notice keeps its message and its **Load full history** control; Reload is appended only when the notice has no load control, or shown alone with a short missing-output message. When Reload is eligible, that **Load full history** control stands in for it and pulls with the content anchor (eligibility read at click time), so the reader keeps their line, and shares Reload's loading state, so the re-render the in-flight pull triggers keeps it on Loading… instead of bringing it back enabled; otherwise it keeps the top anchor and no loading state, so the bar still hides on a scroll back to live output. A reload-only × dismissal lasts until the mark is cleared by a successful `mux-full-history` replay, independently of the notice’s page-long dismissal. Pressing × while loading hides the bar immediately; the in-flight pull continues. Eligibility is cached per active session, with onScroll sampling coalesced to one animation frame on every device; unchanged eligibility never rebuilds the banner. Automatic history pulls and notice reveal stay top-only (#205). Live-output marking covers only live writes: a byte-history (`?tail=`) replay, for example after a burst in a background tab, never marks the session, so that gap relies on the top-of-buffer pull. The manual action forces a content-anchored pull, bypassing the gesture cooldown but retaining the downgrade guard. Any downgrade-refused pull hides Reload until the next successful `mux-full-history` replay; that refusal, not the cached history size, is what retires the action for a pane with no tmux history (fullscreen Claude). A manual reload answered by anything but `mux-full-history` (an empty response, or the byte-history fallback the route returns when the pane capture is blank or failed) retires it the same way, since only a mux replay clears the mark; a transient error envelope (`success: false`) leaves it available. A content anchor captures up to 64 visible rows, preserving indentation, and scores candidate alignments by matching viewport context. Each distinct nonblank row contributes at most one point, so repeated TUI borders cannot outvote a distinctive tool result. The best match must score at least 60% of the distinct rows and at least two of them, capped at the number of distinct rows, so a viewport with one distinct row (a lone tool result among blanks) matches on that row alone; it must also be unique within the search window. Equal-scoring copies are ambiguous, even when all furniture rows match or the distinctive tool row has disappeared; proximity to the expected position does not establish confidence. An isolated first-row match is not trusted: without confident, unambiguous context the old viewport index is retained, while readers already near live output retain their bottom distance. Search covers 4001 candidates from `expected - 4000 + rows` to `expected + rows` (at most 4064 cached line reads), leaning up because every row a reload fills in below the reader moves the reader's row up, while a capture with fewer rows below moves it down by at most the one screen the downgrade guard tolerates. Gaps up to `4000 - rows` rows therefore land exactly, including at xterm's scrollback cap, where the replay trims the top by the same number of rows. A wider gap puts the match outside the window: the restore keeps the old absolute index, which is right while the top of the buffer stays put but, at the cap, lands the reader the whole gap below their line. Live flushes use an xterm marker to track the reading row across scrollback trimming in O(1), and restore it only in the write callback; at-bottom sticky scroll is unchanged. Ordered, session-scoped travel during replay is applied with per-move clamping; a switched-to tab never donates travel. The notice is decided per recorded move, as a live scroll decides it: an upward move that reaches row 0 reveals the partial-history notice, a downward move that reaches live output retires it, and other moves leave the last decision standing, so reaching the top and then scrolling a few rows down still reveals it; a reload with no travel leaves the notice as it was. The buffer load opens BEFORE the fetch, so download-time output queues behind the replay instead of being overwritten. Non-replay exits flush the whole queue; replays retain the capture-header cutoff above. A blocked dropped-output recovery stores its session and current attempt, defers without consuming retries, and resumes only for the still-active session; a later drop for the same session during that load keeps the higher attempt, so the retry bound still holds. Only an actual `mux-full-history` replay clears the live-output mark and reload dismissal, and a newer live-write generation keeps them marked. The drop-recovery refresh (`_onSessionNeedsRefresh`) follows the same rule: it clears both after a completed replay of a `mux-full-history` capture, only while it still owns the active session and the live-output generation sampled before its fetch is unchanged; its `?tail=` fallback never clears them, and because that fallback means the full capture would shrink the buffer (the refusal signal), it retires the action under the same session and refresh-owner checks. The trade-off remains a full synchronous server capture (about 1 s: 1,068 ms median for `capture-pane -p -e -J -S -100000` over 100k lines of 120 characters, 12.1 MB), not a cheap automatic per-output repair. Tests: `test/shell-scroll-history-pull.test.ts`, `test/history-gap-repair.browser.test.ts`. +**Repair while reading (#814)** is a manual **Reload history** action inside the existing history banner on desktop and touch devices, enabled by default and toggleable per device in Settings → Terminal & Input → Scrolling & rendering (`historyReloadAction`). It is offered only for a marked non-shell active session while scrolled away from live output, not Docker or adopted (their local pane hosts a nested tmux client in the alternate screen, so `?full=1` returns one screen the downgrade guard refuses; remote sessions stay eligible, since the route splices the remote scrollback in), not detached, not owned by tiles, with no pull or buffer load in flight, no terminal load state for the session (a tab switch sets it before the buffer load opens), and no drop-recovery refresh owning the session (`_terminalRefreshOwner`, set for the whole fetch, before that refresh opens its buffer load). `_maybeRefetchFullHistory` returns early on that same owner, so Reload, Load full history and the top-of-buffer pull all stand aside instead of running a second capture whose download-time queue the refresh's own load would replace; the refresh re-syncs the action when it starts and when its `finally` releases the owner. `paneHistoryLines` is deliberately not consulted: it is recorded at the last load, so a session first opened empty keeps 0 after the very burst that opens the gap (#814). The bar is a polite live region (`role="status"`), but only the truncation notice is announced: a reload-only bar sets `aria-live="off"` before it re-renders, since it comes back on nearly every scroll-up in a busy tab, and its button stays reachable with Tab. Its × is labelled for what the bar carries: "Dismiss history notice" with the notice, "Dismiss Reload history" without it. A revealed truncation notice keeps its message and its **Load full history** control; Reload is appended only when the notice has no load control, or shown alone with a short missing-output message. When Reload is eligible, that **Load full history** control stands in for it and pulls with the content anchor (eligibility read at click time), so the reader keeps their line, and shares Reload's loading state, so the re-render the in-flight pull triggers keeps it on Loading… instead of bringing it back enabled; otherwise it keeps the top anchor and no loading state, so the bar still hides on a scroll back to live output. A reload-only × dismissal lasts until the mark is cleared by a successful `mux-full-history` replay, independently of the notice’s page-long dismissal. Pressing × while loading hides the bar immediately; the in-flight pull continues. Eligibility is cached per active session, with onScroll sampling coalesced to one animation frame on every device; unchanged eligibility never rebuilds the banner. Automatic history pulls and notice reveal stay top-only (#205). Live-output marking covers only live writes: a byte-history (`?tail=`) replay, for example after a burst in a background tab, never marks the session, so that gap relies on the top-of-buffer pull. The manual action forces a content-anchored pull, bypassing the gesture cooldown but retaining the downgrade guard. Any downgrade-refused pull hides Reload until the next successful `mux-full-history` replay; that refusal, not the cached history size, is what retires the action for a pane with no tmux history (fullscreen Claude). A manual reload answered by anything but `mux-full-history` (an empty response, or the byte-history fallback the route returns when the pane capture is blank or failed) retires it the same way, since only a mux replay clears the mark; a transient error envelope (`success: false`) leaves it available. A content anchor captures up to 64 visible rows, preserving indentation, and scores candidate alignments by matching viewport context. Each distinct nonblank row contributes at most one point, so repeated TUI borders cannot outvote a distinctive tool result. The best match must score at least 60% of the distinct rows and at least two of them, capped at the number of distinct rows, so a viewport with one distinct row (a lone tool result among blanks) matches on that row alone; it must also be unique within the search window. Equal-scoring copies are ambiguous, even when all furniture rows match or the distinctive tool row has disappeared; proximity to the expected position does not establish confidence. An isolated first-row match is not trusted: without confident, unambiguous context the old viewport index is retained, while readers already near live output retain their bottom distance. Search covers 4001 candidates from `expected - 4000 + rows` to `expected + rows` (at most 4064 cached line reads), leaning up because every row a reload fills in below the reader moves the reader's row up, while a capture with fewer rows below moves it down by at most the one screen the downgrade guard tolerates. Gaps up to `4000 - rows` rows therefore land exactly, including at xterm's scrollback cap, where the replay trims the top by the same number of rows. A wider gap puts the match outside the window: the restore keeps the old absolute index, which is right while the top of the buffer stays put but, at the cap, lands the reader the whole gap below their line. Live flushes use an xterm marker to track the reading row across scrollback trimming in O(1), and restore it only in the write callback; a marker the write disposed (its row trimmed, or scrollback erased by `ESC[3J` or RIS, which the narrow and middle strips keep) falls back to the absolute index instead of row 0; at-bottom sticky scroll is unchanged. Ordered, session-scoped travel during replay is applied with per-move clamping; a switched-to tab never donates travel. The notice is decided per recorded move, as a live scroll decides it: an upward move that reaches row 0 reveals the partial-history notice, a downward move that reaches live output retires it, and other moves leave the last decision standing, so reaching the top and then scrolling a few rows down still reveals it; a reload with no travel leaves the notice as it was. The buffer load opens BEFORE the fetch, so download-time output queues behind the replay instead of being overwritten. Non-replay exits flush the whole queue; replays retain the capture-header cutoff above. A blocked dropped-output recovery stores its session and current attempt, defers without consuming retries, and resumes only for the still-active session; a later drop for the same session during that load keeps the higher attempt, so the retry bound still holds. Only an actual `mux-full-history` replay clears the live-output mark and reload dismissal, and a newer live-write generation keeps them marked. The drop-recovery refresh (`_onSessionNeedsRefresh`) follows the same rule: it clears both after a completed replay of a `mux-full-history` capture, only while it still owns the active session and the live-output generation sampled before its fetch is unchanged; its `?tail=` fallback never clears them, and because that fallback means the full capture would shrink the buffer (the refusal signal), it retires the action under the same session and refresh-owner checks. The trade-off remains a full synchronous server capture (about 1 s: 1,068 ms median for `capture-pane -p -e -J -S -100000` over 100k lines of 120 characters, 12.1 MB), not a cheap automatic per-output repair. Tests: `test/shell-scroll-history-pull.test.ts`, `test/history-gap-repair.browser.test.ts`. **The partial-history notice is lazy and pane-gated** (`computeHistoryTruncationNotice()` in constants.js, `_renderHistoryTruncationBanner()` / `_setHistoryNoticeRevealed()` in app.js). `truncated` on a terminal response measures the server's BYTE stream, which is not what `full=1` can return: for a pane with no tmux scrollback (fullscreen claude starts in the alternate screen and never writes to the main grid, so `#{history_size}` is 0) the bytes a tail cut drops are old repaint frames. Measured on prod 2026-10-10, every claude pane: the tab-switch tail cut a 1.2 to 6.2 MB stream to 1 MiB, the local scrollback that tail replays into is repeats of the same frames (one pane: 450 non-blank rows, 44 unique, one row 33 times), and `full=1` returned 1 to 5 KB, so **Load full history** could only end in the downgrade refusal while the banner promised "4.8 MB more". The capture therefore reads `#{history_size}` in the SAME `display-message` as the cursor (no extra tmux call), the route returns it as `paneHistoryLines` (absent when the body is not a capture, and for a remote SSH session, whose local pane hosts the remote tmux client and always reports 0 while `full=1` reads the remote history), and a reported 0 hides the notice in every state; a positive count replaces the byte gap in the message. ⚠️ Key the notice decision on `history_size`, never on `alternate_on`: a shell running `less` is in the alternate screen with its whole history still retained (measured, 99,972 rows) and `full=1` returns all of it. The one place `alternate_on` decides is a shell's AUTOMATIC load (`alt=recording`, see Full-scrollback replay): there the question is whether the capture holds the scrollback a nested tmux client keeps in its byte recording, not whether a pull can return more. The notice is also LAZY: it appears only after a wheel/touch gesture reaches the top of the browser buffer and the pull that gesture started has settled (`_maybeLoadMoreHistoryOnScroll`), goes away when a downward gesture is back at live output or the tab switches (`selectSession` nulls `_historyNoticeRevealedFor` before repainting), and its × is sticky per session until reload (`_historyNoticeDismissed`). Tests: `test/history-truncation-notice.test.ts`, `test/history-notice-reveal.test.ts`. diff --git a/src/web/public/terminal-ui.js b/src/web/public/terminal-ui.js index 888e2276..0b159508 100644 --- a/src/web/public/terminal-ui.js +++ b/src/web/public/terminal-ui.js @@ -4791,30 +4791,33 @@ Object.assign(CodemanApp.prototype, { // signal, which is the earliest point the anchor can actually be // reasserted. (The synchronous version passed its regression test only // because the test's write mock moved the viewport synchronously.) - const viewportY = viewportMarker - ? (viewportMarker.isDisposed ? 0 : viewportMarker.line) - : preserveViewportY; + // A marker is disposed when its row is trimmed off a full scrollback, + // but also when the stream itself erases scrollback (`ESC[3J`, RIS), + // which the narrow and middle strips keep. Fall back to the absolute + // index then, as before markers, rather than sending the reader to row 0. + const viewportY = viewportMarker && !viewportMarker.isDisposed ? viewportMarker.line : preserveViewportY; viewportMarker?.dispose(); this._restoreTerminalViewport(viewportY, flushSessionId); this._scheduleTerminalWriteFlush(); this._noteMobileImeAuthoritativeOutput(flushedOutputSeq, flushSessionId); }); - // Only live writes can open a new tmux repaint gap; replays cannot (#814). - if (writeChunk.length && flushSessionId && !this._isLoadingBuffer) { - const marked = (this._liveOutputSinceFullPull ||= new Set()); - const newlyMarked = !marked.has(flushSessionId); - marked.add(flushSessionId); - const generations = (this._liveOutputGen ||= new Map()); - generations.set(flushSessionId, (generations.get(flushSessionId) || 0) + 1); - // Mark transitions sync immediately; onScroll is coalesced on all devices. - if (newlyMarked) this._syncHistoryReloadAction?.(); - } } catch (err) { viewportMarker?.dispose(); this._terminalWriteInFlight = false; this._terminalWriteInFlightBytes = 0; throw err; } + // Only live writes can open a new tmux repaint gap; replays cannot (#814). + // Outside the try: the catch above must only cover the write itself. + if (writeChunk.length && flushSessionId && !this._isLoadingBuffer) { + const marked = (this._liveOutputSinceFullPull ||= new Set()); + const newlyMarked = !marked.has(flushSessionId); + marked.add(flushSessionId); + const generations = (this._liveOutputGen ||= new Map()); + generations.set(flushSessionId, (generations.get(flushSessionId) || 0) + 1); + // Mark transitions sync immediately; onScroll is coalesced on all devices. + if (newlyMarked) this._syncHistoryReloadAction?.(); + } const bytesThisFrame = deferred ? MAX_FRAME_BYTES : _joinedLen; const _dt = performance.now() - _t0; if (_dt > 100 || deferred) diff --git a/test/terminal-viewport-marker.test.ts b/test/terminal-viewport-marker.test.ts index 3f241009..28f3cce3 100644 --- a/test/terminal-viewport-marker.test.ts +++ b/test/terminal-viewport-marker.test.ts @@ -102,4 +102,30 @@ describe('live terminal viewport at the scrollback cap', () => { expect(row).not.toBe('line 140'); expect(row).toBe('line 160'); }); + + // ESC[3J (kept by the narrow and middle strips) erases scrollback and disposes + // the marker the same way a trim does; the reader must keep their row, not + // land on row 0. + it.each([true, false])( + 'keeps the reader on their row when one flush clears scrollback and reprints it (markers: %s)', + async (markersEnabled) => { + const terminal = new Terminal({ cols: 80, rows: 10, scrollback: 1000, allowProposedApi: true }); + try { + if (!markersEnabled) Object.defineProperty(terminal, 'registerMarker', { value: undefined }); + const app = loadHarness(terminal); + const history = Array.from({ length: 200 }, (_, i) => `line ${i}\r\n`).join(''); + await write(terminal, history); + terminal.scrollToLine(100); + expect(topRow(terminal)).toBe('line 100'); + expect(app.isTerminalAtBottom()).toBe(false); + app.pendingWrites.push(`\x1b[H\x1b[2J\x1b[3J${history}`); + app.flushPendingWrites(); + await write(terminal, ''); + expect(app._terminalWriteInFlight).toBe(false); + expect(topRow(terminal)).toBe('line 100'); + } finally { + terminal.dispose(); + } + } + ); });