diff --git a/docs/architecture-invariants.md b/docs/architecture-invariants.md index 7f1dfd08..50e5cb12 100644 --- a/docs/architecture-invariants.md +++ b/docs/architecture-invariants.md @@ -253,7 +253,7 @@ Further detail: the `: ` form (`w3-myapp: fix the login redirect` **Full-scrollback replay** (COD-164/#148, reworked for #205): `GET /api/sessions/:id/terminal?full=1` returns the ENTIRE tmux scrollback (capture-pane `-e -S -<lines>` bounded by the configured history limit, explicit `maxBuffer` from the terminal-history config, early byte-cap before normalization, CRLF-normalized for shell panes). On success the capture is returned ALONE (`source='mux-full-history'` — it supersedes the byte buffer; no duplication). The first load of each non-shell TUI session per page requests `full=1` (`_fullHistoryLoaded` Set in app.js — the old one-shot `_initialFullBufferLoad` flag was consumed by whichever tab auto-selected, leaving every other TUI tab one frame of history). Shell sessions instead load a bounded window of tmux's RENDERED history on every selection, automatic drop recovery, clear and tile load (`SHELL_LOAD_QUERY` in constants.js: `?full=1&tail=1MiB&lines=10000&alt=recording`): a 100k-line shell capture can be tens of MiB, and automatically parsing it makes tab-switch latency scale with the entire session (`lines=` bounds the synchronous capture-pane, about 8 ms per 1000 lines). They never replay the raw byte recording ahead of the visible frame any more: it holds full-screen repaints (an ssh'd tmux, `less`, any TUI) drawn for the pane height of the moment, and replayed into a terminal of another height each repaint's last newline scrolls its top row into scrollback, so one line tmux holds once showed up dozens of times. Because `lines=` is shallower than xterm's scrollback, the route reports a cut: the capture's `display-message` query also reads `#{history_size}` (`PaneCaptureOptions.capturedHistoryLines`, the same field the route reports as `paneHistoryLines`), and a full capture whose CLIENT bound (`lines=` below the configured `tmuxHistoryLimit`) left lines in tmux comes back `truncated`, `truncationReason: 'tail'`. ⚠️ Only a client bound below the ceiling counts: a request without `lines=` is bounded by the ceiling itself, and on tmux before 3.7 a live pane can hold more than a lowered ceiling, which no request can read. ⚠️ **A pane in the alternate screen keeps no tmux history**, and a nested tmux client (remote SSH and Docker cases, or `tmux`/`ssh -t host tmux` run by hand) holds its pane there, so its full capture is one screen. The same query reads `#{alternate_on}` (`capturedAlternateOn`), and a request carrying `alt=recording` (only `SHELL_LOAD_QUERY`) is then answered the old way, the visible frame over the tailed byte recording, which still carries the scrollback; agents, scroll pulls and **Load full history** never send it. `#{alternate_on}` cannot tell a nested tmux from vim, `less` or `htop`, so a local shell with one of those open takes the same fallback until it exits (the pre-fix load, with its repaint duplicates). Shell FULL history is explicit-button-only; reaching the top during an ordinary wheel/touch gesture must not reset xterm and replay the multi-megabyte capture on its main thread. That gesture instead pulls a BOUNDED window of it (`?full=1&tail=<TERMINAL_TAIL_SIZE>`, so a capture beyond 1 MiB comes back `truncationReason: 'tail'` and the banner offers the rest), and skips the replay when the window holds no more rows than the browser already has. ⚠️ **That skip runs BEFORE the downgrade guard, and it never touches the banner state**: the guard reads "smaller than the browser" as "tmux has nothing more to give", true of an unbounded capture and false of a window cut at the tail size, so a bounded window that reached it marked the session `exhausted` and removed **Load full history** while tmux still held the rest; and re-labelling the banner from a skipped payload would call a terminal that holds all of a Load full history pull "the most recent 1 MiB". A skipped window that came back truncated puts the session on the 60 s cooldown (`_fullHistoryRepullUseless`), because it can never reach anything older than the browser shows and `tail` is applied AFTER the server's synchronous `capture-pane` of the whole history, so each ask costs every client an event-loop stall (about 1 s at 100k lines; measured capture details below); an untruncated one keeps the 4 s cooldown, since it is all of tmux's history and the next burst can add to it. Declining the gesture outright was a dead end: after any burst a shell pane held about one screen of browser scrollback, and the button renders only once a replay was truncated, so a young shell tab had no way back to history tmux still held. Other modes re-pull `full=1` only at the top of the local buffer, and pressing **Load full history** forces the request for any recoverably truncated session (`_maybeRefetchFullHistory`, 4s per-session gesture cooldown, in-flight + tab-switch guards, viewport position held across the replay); Shell full pulls are not retained in the tab cache, so the next switch stays bounded. Chunked replay enqueues 32 KiB pieces across safe yields, appends an xterm parse marker, then releases the live-output gate; output arriving after that release stays ordered behind the snapshot, and the marker callback supplies accurate parse timing. ⚠️ **How the load ENDS depends on where the payload came from**, and `_bufferLoadFinishOpts` (app.js) is the one place that decides it for all four fetch-and-write paths. A payload built from the server's accumulated byte history is current up to the response, so the events queued during the load already appear in it and stay DISCARDED; replaying them would duplicate output, most visibly Ink's cursor-up redraws. A pane capture (`mux-visible` or `mux-full-history`) is current only up to CAPTURE time, so `_finishBufferLoad` replays the queue from the response's own arrival timestamp (`since`) and the pre-capture events stay dropped. ⚠️ **A path that then restores a scroll position must re-take the sticky-scroll baseline** (`_syncStickyScrollBaseline`): the replay runs inside `chunkedTerminalWrite` before its promise resolves, with the terminal freshly reset, so `batchTerminalWrite` samples `_wasAtBottomBeforeWrite` as true and the next `flushPendingWrites` would scroll to the bottom over the restore. ⚠️ The cutoff is a client-side timestamp and the server broadcasts on a batch timer (8ms WebSocket, 16-50ms SSE), so a batch pending when the capture ran arrives after the response and replays although the capture holds it — bounded by one batch interval, and closable only server side by flushing that batch before the capture. Tests for the three: `test/terminal-flush-budget.test.ts` pins which sources flush, `test/terminal-buffer-flush.test.ts` pins the `since` cutoff and the baseline re-take, and `test/capture-load-window.browser.test.ts` drives both against a live server. Live output is separately one-chunk-in-flight: xterm's callback releases each 32/64 KiB write before the next is submitted, keeping the remainder in the app queue where the 128 KiB cap can observe it instead of hiding an unbounded backlog in xterm's private WriteBuffer. While WebSocket owns terminal I/O, parallel SSE terminal/output-recovery events are discarded before JSON parsing; fallback recovery is single-flight per active session so backpressure cannot start overlapping reset+replay cycles. The route exposes capture/prepare totals in `Server-Timing`, while `[TERMINAL-PERF]` separates TTFB, body/JSON, reset+parse and total time for both selection and on-demand full pulls; parse completion is not a browser compositor/GPU paint measurement. The re-pull exists because xterm's buffer is only a WINDOW onto tmux's history and two things shrink it: tmux coalesces bursty output into pane REPAINTS that overwrite rows instead of emitting linefeeds (measured: a 60-line burst added 1 row of browser scrollback and destroyed 34), and a tab switch replays only the visible frame. tmux's own history is intact throughout — the browser just has to ask for it again. Gesture-triggered rather than polling because at a 100k history limit the capture can be megabytes. ⚠️ **The capture ENDS with a cursor move back to the pane's own caret position** (`formatCursorRestore`, from the same `display-message` query the visible-frame path uses). The linear replay otherwise leaves the caret wherever the last character landed — the bottom-most row carrying text, which for an agent CLI is the status line — so the caret sat on the composer's border instead of its input line and every cursor-relative update the CLI sent afterwards was measured from the wrong row, until its next full redraw silently repaired it (that self-repair is why the report read as "it fixes itself as soon as Claude writes a line"). ⚠️ **The move is RELATIVE — up `rows - 1 - cursor_y`, then `\r`, then right `cursor_x` — never `CUP`.** `\x1b[<row>;<col>H` numbers rows from the top of the browser's screen, so it lands correctly only while the browser's row count equals `pane_height`, and nothing guarantees that: `resizeWindow` issues its tmux resize fire-and-forget and returns immediately, so a capture can be taken before a requested resize has applied, and `_onSessionNeedsRefresh` sends no resize at all. Counting up from the last replayed row anchors to the content both ends share. Restoring the cursor makes ROW ALIGNMENT load-bearing on this path: **no transform that can DELETE A LINE may run over a full-history capture**, because every deletion shifts the frame out from under the restored position. Four had accumulated — trailing blank rows stripped by `\n+$`, `stripInkRedrawBloat`, the `CLAUDE_BANNER_PATTERN` trim that cuts everything above the banner, and `LEADING_WHITESPACE_PATTERN` — each correct for a byte stream of successive frames and each wrong for a single rendered frame. ⚠️ **Those skips key on `isFullCapture`, meaning a capture actually came back — never on `?full=1` alone.** When `captureActivePaneBuffer` returns null (ENOBUFS, a timeout, a vanished pane, or a session with no mux at all) the reply falls back to `session.terminalBuffer`, which IS a byte stream and must still be stripped; gating on the query flag returned it whole, and a direct-PTY session takes that path on every first selection rather than only during an outage. ⚠️ A capture holding nothing visible (`hasVisibleContent`) returns `''`, because the caller reads an empty capture as "unavailable" and keeps its byte history — retaining trailing blank rows made an all-blank pane non-empty, which would have replaced real history with a blank screen from the server side, where `_replayWouldShrinkBuffer` cannot see it. ⚠️ **"One line per screen row" holds only where no row was hard-wrapped**: `-J` joins a wrapped row into its logical line (measured: a 100-character line in a 40-column pane captures as 10 lines against a 12-row pane), and the counts reconcile only once the browser xterm re-wraps at the same width — the same assumption `_estimateReplayRows` already documents. Tests: `test/tmux-capture-full-history.test.ts` covers the cursor move, the trim pairing and `hasVisibleContent`; `test/routes/session-routes.test.ts` covers a surviving blank first row, an unstripped byte-history fallback, and an empty capture leaving history intact. ⚠️ **The re-pull must never DOWNGRADE the buffer** (#205 round 2): the same reasoning that makes it a win for a shell pane makes it destructive for a repaint-mode CLI pane, where tmux keeps no history of its own (`history_size≈0` measured for a Claude pane) and the capture is roughly ONE frame while xterm may hold hundreds of rows of replayed frames — `_resetTerminalForReplay()` + rewrite then deletes history mid-scroll ("goes back a bit, repeats blocks, gets worse the further up I go"; measured A/B on a live pane: 341 rows → 42 with the guard off). `_replayWouldShrinkBuffer()` (terminal-ui.js) estimates the capture's rendered rows — escape sequences stripped, `capture-pane -J` re-wrapping accounted for — and the pull is skipped when that is more than one screen short of `buffer.active.length`. The one-screen tolerance matters: both sides are estimates (the buffer length counts trailing blank rows), so only a clear downgrade is refused. A refused session joins `_fullHistoryRepullUseless`, raising its cooldown from 4s to 60s so a hollow pane stops re-fetching megabytes on every scroll-up. Tests: `test/tmux-capture-full-history.test.ts`, `test/tmux-scrollback-eol.test.ts`, `test/terminal-scroll-routing.test.ts`, `test/terminal-flush-budget.test.ts`. -**Repair while reading (#814)** is a manual **Reload history** action inside the existing history banner on desktop and touch devices, enabled by default and toggleable per device in Settings → Terminal & Input → Scrolling & rendering (`historyReloadAction`). It is offered only for a marked non-shell active session while scrolled away from live output, not detached, not owned by tiles, with no pull or buffer load in flight and no terminal load state for the session (a tab switch sets it before the buffer load opens). `paneHistoryLines` is deliberately not consulted: it is recorded at the last load, so a session first opened empty keeps 0 after the very burst that opens the gap (#814). A revealed truncation notice keeps its message and its **Load full history** control; Reload is appended only when the notice has no load control, or shown alone with a short missing-output message. When Reload is eligible, that **Load full history** control stands in for it and pulls with the content anchor (eligibility read at click time), so the reader keeps their line; otherwise it keeps the top anchor. A reload-only × dismissal lasts until the mark is cleared by a successful `mux-full-history` replay, independently of the notice’s page-long dismissal. Pressing × while loading hides the bar immediately; the in-flight pull continues. Eligibility is cached per active session, with onScroll sampling coalesced to one animation frame on every device; unchanged eligibility never rebuilds the banner. Automatic history pulls and notice reveal stay top-only (#205). Live-output marking covers only live writes: a byte-history (`?tail=`) replay, for example after a burst in a background tab, never marks the session, so that gap relies on the top-of-buffer pull. The manual action forces a content-anchored pull, bypassing the gesture cooldown but retaining the downgrade guard. Any downgrade-refused pull hides Reload until the next successful `mux-full-history` replay; that refusal, not the cached history size, is what retires the action for a pane with no tmux history (fullscreen Claude). A manual reload answered by anything but `mux-full-history` (an empty response, or the byte-history fallback the route returns when the pane capture is blank or failed) retires it the same way, since only a mux replay clears the mark; a transient error envelope (`success: false`) leaves it available. A content anchor captures up to 64 visible rows, preserving indentation, and scores candidate alignments by matching viewport context. Each distinct nonblank row contributes at most one point, so repeated TUI borders cannot outvote a distinctive tool result. The best match must score at least 60% of the distinct rows and at least two of them, capped at the number of distinct rows, so a viewport with one distinct row (a lone tool result among blanks) matches on that row alone; it must also be unique within the search window. Equal-scoring copies are ambiguous, even when all furniture rows match or the distinctive tool row has disappeared; proximity to the expected position does not establish confidence. An isolated first-row match is not trusted: without confident, unambiguous context the old viewport index is retained, while readers already near live output retain their bottom distance. Search covers 4001 candidates from `expected - 4000 + rows` to `expected + rows` (at most 4064 cached line reads), leaning up because every row a reload fills in below the reader moves the reader's row up, while a capture with fewer rows below moves it down by at most the one screen the downgrade guard tolerates. Gaps up to `4000 - rows` rows therefore land exactly, including at xterm's scrollback cap, where the replay trims the top by the same number of rows. A wider gap puts the match outside the window: the restore keeps the old absolute index, which is right while the top of the buffer stays put but, at the cap, lands the reader the whole gap below their line. Live flushes use an xterm marker to track the reading row across scrollback trimming in O(1), and restore it only in the write callback; at-bottom sticky scroll is unchanged. Ordered, session-scoped travel during replay is applied with per-move clamping; a switched-to tab never donates travel. The buffer load opens BEFORE the fetch, so download-time output queues behind the replay instead of being overwritten. Non-replay exits flush the whole queue; replays retain the capture-header cutoff above. A blocked dropped-output recovery stores its session and current attempt, defers without consuming retries, and resumes only for the still-active session. Only an actual `mux-full-history` replay clears the live-output mark and reload dismissal, and a newer live-write generation keeps them marked. The drop-recovery refresh (`_onSessionNeedsRefresh`) follows the same rule: it clears both after replaying a `mux-full-history` capture, only while it still owns the active session and the live-output generation sampled before its fetch is unchanged; its `?tail=` fallback never clears them, and because that fallback means the full capture would shrink the buffer (the refusal signal), it retires the action under the same session and refresh-owner checks. The trade-off remains a full synchronous server capture (about 1 s: 1,068 ms median for `capture-pane -p -e -J -S -100000` over 100k lines of 120 characters, 12.1 MB), not a cheap automatic per-output repair. Tests: `test/shell-scroll-history-pull.test.ts`, `test/history-gap-repair.browser.test.ts`. +**Repair while reading (#814)** is a manual **Reload history** action inside the existing history banner on desktop and touch devices, enabled by default and toggleable per device in Settings → Terminal & Input → Scrolling & rendering (`historyReloadAction`). It is offered only for a marked non-shell active session while scrolled away from live output, not detached, not owned by tiles, with no pull or buffer load in flight and no terminal load state for the session (a tab switch sets it before the buffer load opens). `paneHistoryLines` is deliberately not consulted: it is recorded at the last load, so a session first opened empty keeps 0 after the very burst that opens the gap (#814). A revealed truncation notice keeps its message and its **Load full history** control; Reload is appended only when the notice has no load control, or shown alone with a short missing-output message. When Reload is eligible, that **Load full history** control stands in for it and pulls with the content anchor (eligibility read at click time), so the reader keeps their line; otherwise it keeps the top anchor. A reload-only × dismissal lasts until the mark is cleared by a successful `mux-full-history` replay, independently of the notice’s page-long dismissal. Pressing × while loading hides the bar immediately; the in-flight pull continues. Eligibility is cached per active session, with onScroll sampling coalesced to one animation frame on every device; unchanged eligibility never rebuilds the banner. Automatic history pulls and notice reveal stay top-only (#205). Live-output marking covers only live writes: a byte-history (`?tail=`) replay, for example after a burst in a background tab, never marks the session, so that gap relies on the top-of-buffer pull. The manual action forces a content-anchored pull, bypassing the gesture cooldown but retaining the downgrade guard. Any downgrade-refused pull hides Reload until the next successful `mux-full-history` replay; that refusal, not the cached history size, is what retires the action for a pane with no tmux history (fullscreen Claude). A manual reload answered by anything but `mux-full-history` (an empty response, or the byte-history fallback the route returns when the pane capture is blank or failed) retires it the same way, since only a mux replay clears the mark; a transient error envelope (`success: false`) leaves it available. A content anchor captures up to 64 visible rows, preserving indentation, and scores candidate alignments by matching viewport context. Each distinct nonblank row contributes at most one point, so repeated TUI borders cannot outvote a distinctive tool result. The best match must score at least 60% of the distinct rows and at least two of them, capped at the number of distinct rows, so a viewport with one distinct row (a lone tool result among blanks) matches on that row alone; it must also be unique within the search window. Equal-scoring copies are ambiguous, even when all furniture rows match or the distinctive tool row has disappeared; proximity to the expected position does not establish confidence. An isolated first-row match is not trusted: without confident, unambiguous context the old viewport index is retained, while readers already near live output retain their bottom distance. Search covers 4001 candidates from `expected - 4000 + rows` to `expected + rows` (at most 4064 cached line reads), leaning up because every row a reload fills in below the reader moves the reader's row up, while a capture with fewer rows below moves it down by at most the one screen the downgrade guard tolerates. Gaps up to `4000 - rows` rows therefore land exactly, including at xterm's scrollback cap, where the replay trims the top by the same number of rows. A wider gap puts the match outside the window: the restore keeps the old absolute index, which is right while the top of the buffer stays put but, at the cap, lands the reader the whole gap below their line. Live flushes use an xterm marker to track the reading row across scrollback trimming in O(1), and restore it only in the write callback; at-bottom sticky scroll is unchanged. Ordered, session-scoped travel during replay is applied with per-move clamping; a switched-to tab never donates travel. Travel that ends at row 0 reveals the partial-history notice, and travel that ends at live output retires it, as a live scroll would; a reload with no travel leaves the notice as it was. The buffer load opens BEFORE the fetch, so download-time output queues behind the replay instead of being overwritten. Non-replay exits flush the whole queue; replays retain the capture-header cutoff above. A blocked dropped-output recovery stores its session and current attempt, defers without consuming retries, and resumes only for the still-active session; a later drop for the same session during that load keeps the higher attempt, so the retry bound still holds. Only an actual `mux-full-history` replay clears the live-output mark and reload dismissal, and a newer live-write generation keeps them marked. The drop-recovery refresh (`_onSessionNeedsRefresh`) follows the same rule: it clears both after a completed replay of a `mux-full-history` capture, only while it still owns the active session and the live-output generation sampled before its fetch is unchanged; its `?tail=` fallback never clears them, and because that fallback means the full capture would shrink the buffer (the refusal signal), it retires the action under the same session and refresh-owner checks. The trade-off remains a full synchronous server capture (about 1 s: 1,068 ms median for `capture-pane -p -e -J -S -100000` over 100k lines of 120 characters, 12.1 MB), not a cheap automatic per-output repair. Tests: `test/shell-scroll-history-pull.test.ts`, `test/history-gap-repair.browser.test.ts`. **The partial-history notice is lazy and pane-gated** (`computeHistoryTruncationNotice()` in constants.js, `_renderHistoryTruncationBanner()` / `_setHistoryNoticeRevealed()` in app.js). `truncated` on a terminal response measures the server's BYTE stream, which is not what `full=1` can return: for a pane with no tmux scrollback (fullscreen claude starts in the alternate screen and never writes to the main grid, so `#{history_size}` is 0) the bytes a tail cut drops are old repaint frames. Measured on prod 2026-10-10, every claude pane: the tab-switch tail cut a 1.2 to 6.2 MB stream to 1 MiB, the local scrollback that tail replays into is repeats of the same frames (one pane: 450 non-blank rows, 44 unique, one row 33 times), and `full=1` returned 1 to 5 KB, so **Load full history** could only end in the downgrade refusal while the banner promised "4.8 MB more". The capture therefore reads `#{history_size}` in the SAME `display-message` as the cursor (no extra tmux call), the route returns it as `paneHistoryLines` (absent when the body is not a capture, and for a remote SSH session, whose local pane hosts the remote tmux client and always reports 0 while `full=1` reads the remote history), and a reported 0 hides the notice in every state; a positive count replaces the byte gap in the message. ⚠️ Key the notice decision on `history_size`, never on `alternate_on`: a shell running `less` is in the alternate screen with its whole history still retained (measured, 99,972 rows) and `full=1` returns all of it. The one place `alternate_on` decides is a shell's AUTOMATIC load (`alt=recording`, see Full-scrollback replay): there the question is whether the capture holds the scrollback a nested tmux client keeps in its byte recording, not whether a pull can return more. The notice is also LAZY: it appears only after a wheel/touch gesture reaches the top of the browser buffer and the pull that gesture started has settled (`_maybeLoadMoreHistoryOnScroll`), goes away when a downward gesture is back at live output or the tab switches (`selectSession` nulls `_historyNoticeRevealedFor` before repainting), and its × is sticky per session until reload (`_historyNoticeDismissed`). Tests: `test/history-truncation-notice.test.ts`, `test/history-notice-reveal.test.ts`. diff --git a/src/web/public/app.js b/src/web/public/app.js index 844ace32..a3102cc9 100644 --- a/src/web/public/app.js +++ b/src/web/public/app.js @@ -2610,7 +2610,11 @@ class CodemanApp { if (this._pendingDroppedOutputRecovery?.sessionId !== sessionId && Number.isFinite(queuedBytes)) { _crashDiag.log(`TERMINAL DROP: ${(queuedBytes / 1024).toFixed(0)}KB queued (recovery deferred)`); } - this._pendingDroppedOutputRecovery = { sessionId, attempt }; + const pending = this._pendingDroppedOutputRecovery; + this._pendingDroppedOutputRecovery = { + sessionId, + attempt: pending?.sessionId === sessionId ? Math.max(pending.attempt, attempt) : attempt, + }; } return; } @@ -2622,7 +2626,13 @@ class CodemanApp { // A load may have opened after this timer was armed. Defer without // advancing the attempt; _finishBufferLoad resumes only the active tab. if (this._isLoadingBuffer) { - if (sessionId === this.activeSessionId) this._pendingDroppedOutputRecovery = { sessionId, attempt }; + if (sessionId === this.activeSessionId) { + const pending = this._pendingDroppedOutputRecovery; + this._pendingDroppedOutputRecovery = { + sessionId, + attempt: pending?.sessionId === sessionId ? Math.max(pending.attempt, attempt) : attempt, + }; + } return; } let repainted = false; @@ -3541,13 +3551,14 @@ class CodemanApp { // after them and fuse into the buffer written below. See // _resetTerminalForReplay. this._resetTerminalForReplay(); - await this.chunkedTerminalWrite( + const { completed } = await this.chunkedTerminalWrite( data.terminalBuffer, TERMINAL_CHUNK_SIZE, undefined, this._bufferLoadFinishOpts(data, headersReceivedAt) ); if ( + completed && this.activeSessionId === sessionId && this._terminalRefreshOwner === refreshOwner && data.source === 'mux-full-history' && @@ -9863,6 +9874,11 @@ class CodemanApp { let row = this._restoreViewportAnchor(viewportAnchor); for (const move of this._earlyReplayTravel.moves) row = clamp(row + move); this.terminal.scrollToLine(row); + // Replay travel bypassed the live scroll handler's notice update. + if (this._earlyReplayTravel.moves.length > 0) { + if (row === 0) this._setHistoryNoticeRevealed?.(sessionId); + else if (this.isTerminalAtBottom()) this._setHistoryNoticeRevealed?.(null); + } } else { const delta = parsedBufferLength - rowsBefore; if (delta > 0) this.terminal.scrollToLine(delta); diff --git a/test/shell-scroll-history-pull.test.ts b/test/shell-scroll-history-pull.test.ts index c720e36c..5ae0e9a2 100644 --- a/test/shell-scroll-history-pull.test.ts +++ b/test/shell-scroll-history-pull.test.ts @@ -680,6 +680,43 @@ describe('manual full-history recovery while reading (#814)', () => { } }); + it.each([false, true])('keeps the highest same-session deferred attempt (timer armed: %s)', async (armed) => { + vi.useFakeTimers(); + try { + const { app } = makeApp('omp', { bufferRows: 30, capture: lines(400) }); + const retry = vi.fn(() => false); + const schedule = loadAppMethod('_scheduleDroppedOutputRecovery', { + setTimeout, + window: { CodemanDroppedOutput: { DROP_RECOVERY_DELAY_MS: 2000, shouldRetryDroppedOutputRecovery: retry } }, + }); + Object.assign(app, { + _scheduleDroppedOutputRecovery: (...args: unknown[]) => schedule.apply(app, args), + _onSessionNeedsRefresh: vi.fn(async () => false), + }); + if (armed) schedule.call(app, 's1', 0); + const owner = (app._beginBufferLoad as Function).call(app); + schedule.call(app, 's1', 3); + if (armed) await vi.advanceTimersByTimeAsync(2000); + else schedule.call(app, 's1', 0); // A later dropped frame must not reset the bound. + expect(Reflect.get(app, '_pendingDroppedOutputRecovery')).toEqual({ sessionId: 's1', attempt: 3 }); + app._finishBufferLoad(owner); + await vi.advanceTimersByTimeAsync(2000); + expect(retry).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ attempt: 3 })); + } finally { + vi.useRealTimers(); + } + }); + + it('replaces a different session’s deferred attempt rather than merging it', () => { + const { app } = makeApp('omp', { bufferRows: 30, capture: lines(400) }); + const schedule = loadAppMethod('_scheduleDroppedOutputRecovery'); + const owner = (app._beginBufferLoad as Function).call(app); + Object.assign(app, { _pendingDroppedOutputRecovery: { sessionId: 's0', attempt: 4 } }); + schedule.call(app, 's1', 0); + expect(Reflect.get(app, '_pendingDroppedOutputRecovery')).toEqual({ sessionId: 's1', attempt: 0 }); + app._finishBufferLoad(owner); + }); + it('does not resume a deferred recovery for a tab that is no longer active', () => { const { app } = makeApp('omp', { bufferRows: 30, capture: lines(400) }); const owner = (app._beginBufferLoad as Function).call(app); @@ -764,6 +801,31 @@ describe('manual full-history recovery while reading (#814)', () => { expect(app._liveOutputSinceFullPull.has('s1')).toBe(source !== 'mux-full-history'); }); + it('reveals the truncation notice after replay travel reaches the top', async () => { + const { app, active, liveOutput, reload, pauseReplay } = makeScrollApp(); + liveOutput(); + const paused = pauseReplay(); + const pull = reload(); + await paused.ready; + (mixin._maybeLoadMoreHistoryOnScroll as Function).call(app, -10000); + paused.release(); + await pull; + expect(app._setHistoryNoticeRevealed).toHaveBeenCalledWith('s1'); + expect(active.viewportY).toBe(0); + expect(app._maybeRefetchFullHistory).toHaveBeenCalledOnce(); + }); + + it('does not reveal the truncation notice on reload without replay travel', async () => { + const { app, liveOutput, reload, pauseReplay } = makeScrollApp(); + liveOutput(); + const paused = pauseReplay(); + const pull = reload(); + await paused.ready; + paused.release(); + await pull; + expect(app._setHistoryNoticeRevealed).not.toHaveBeenCalledWith('s1'); + }); + it('does not swallow another tab’s travel or clear the old mark when replay is cancelled', async () => { const { app, active, liveOutput, reload, pauseReplay } = makeScrollApp(); liveOutput(); @@ -1320,27 +1382,14 @@ describe('manual history banner action', () => { it('does no DOM work without a transition and coalesces all-device onScroll calls per frame', () => { const { app, state, frames } = fixture({ touch: false }); - let onScroll!: () => void; - const source = readFileSync(resolve(PUBLIC, 'terminal-ui.js'), 'utf8'); - const registration = source.match(/^ this\.terminal\.onScroll\(.*$/m)![0]; - vm.runInNewContext(`(function () { ${registration} }).call(app)`, { - app: { - terminal: { - onScroll: (callback: () => void) => { - onScroll = callback; - }, - }, - _scheduleHistoryReloadActionSync: app._scheduleHistoryReloadActionSync, - }, - }); app._syncHistoryReloadAction(); - for (let i = 0; i < 100; i++) onScroll(); + for (let i = 0; i < 100; i++) app._scheduleHistoryReloadActionSync(); expect(frames).toHaveLength(1); frames.shift()!(0); expect(app._renderHistoryTruncationBanner).toHaveBeenCalledOnce(); state.bottom = true; - onScroll(); - onScroll(); + app._scheduleHistoryReloadActionSync(); + app._scheduleHistoryReloadActionSync(); expect(frames).toHaveLength(1); frames.shift()!(1); expect(app._renderHistoryTruncationBanner).toHaveBeenCalledTimes(2); @@ -1502,6 +1551,20 @@ describe('drop-recovery refresh clears the live-output mark only for a mux captu expect(app._syncHistoryReloadAction).toHaveBeenCalledTimes(2); }); + it('keeps the mark and dismissal when the mux replay is incomplete', async () => { + const { app, refresh, errors } = makeRefreshApp(); + app.chunkedTerminalWrite.mockImplementationOnce(async () => ({ + parsedAt: performance.now(), + bufferLength: 400, + completed: false, + })); + await refresh.call(app); + expect(errors).not.toHaveBeenCalled(); + expect(app.chunkedTerminalWrite).toHaveBeenCalledOnce(); + expect(app._liveOutputSinceFullPull.has('s1')).toBe(true); + expect(app._historyReloadDismissed.has('s1')).toBe(true); + }); + it('keeps the mark and dismissal for a history answer', async () => { const { app, refresh, errors } = makeRefreshApp('history'); expect(await refresh.call(app)).toBe(true);