fix(web): keep drop recovery bounded and the notice in step with replay travel (#814)

- _onSessionNeedsRefresh clears the Reload mark only after a completed mux replay.
- A later drop during an open load keeps the deferred recovery's higher attempt.
- Replay travel that reaches row 0 reveals the partial-history notice; at live output it retires it.
- The onScroll coalescing test drives the scheduler instead of evaluating a source line.
This commit is contained in:
Hadrien Kerlero committed 2026-11-22 02:44:24 +01:00
1 parent 193f220f5e
commit 1f9b17e29a
3 files changed
+99 -20

No files matched your search

+1 -1
View File
@@ -253,7 +253,7 @@ Further detail: the `<prefix>: <title>` 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 marLine truncated
**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 sampledLine truncated
**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 marLine truncated
**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`.
+19 -3
View File
@@ -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);
+79 -16
View File
@@ -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);