fix(web): retire refused Reload history and hold the reading row (#814)

- Reload history requires pane history and no buffer load in flight; a
  downgrade-refused pull hides it until the next mux-full-history replay,
  and a stale tap re-checks eligibility before fetching.
- x during Loading... hides the bar at once; the pull continues.
- The content anchor scores up to 64 visible rows, so repeated TUI borders
  cannot outvote the row being read; ambiguous matches keep the viewport.
- Live flushes track the reading row with an xterm marker across
  scrollback trimming at the cap.
- Docs: Settings-Reference row, Dashboard notice text, ~1 s capture cost,
  byte-history replays rely on the top-of-buffer pull.
This commit is contained in:
Hadrien Kerlero committed 2026-11-22 02:44:23 +01:00
1 parent fd6b392b4d
commit 9ef47aca6c
7 files changed
+322 -50

No files matched your search

+2 -2
View File
@@ -251,9 +251,9 @@ Further detail: the `<prefix>: <title>` form (`w3-myapp: fix the login redirect`
### Full-scrollback replay
**Full-scrollback replay** (COD-164/#148, reworked for #205): `GET /api/sessions/:id/terminal?full=1` returns the ENTIRE tmux scrollback (capture-pane `-e -S -<lines>` bounded by the configured history limit, explicit `maxBuffer` from the terminal-history config, early byte-cap before normalization, CRLF-normalized for shell panes). On success the capture is returned ALONE (`source='mux-full-history'` — it supersedes the byte buffer; no duplication). The first load of each non-shell TUI session per page requests `full=1` (`_fullHistoryLoaded` Set in app.js — the old one-shot `_initialFullBufferLoad` flag was consumed by whichever tab auto-selected, leaving every other TUI tab one frame of history). Shell sessions instead load a bounded window of tmux's RENDERED history on every selection, automatic drop recovery, clear and tile load (`SHELL_LOAD_QUERY` in constants.js: `?full=1&tail=1MiB&lines=10000&alt=recording`): a 100k-line shell capture can be tens of MiB, and automatically parsing it makes tab-switch latency scale with the entire session (`lines=` bounds the synchronous capture-pane, about 8 ms per 1000 lines). They never replay the raw byte recording ahead of the visible frame any more: it holds full-screen repaints (an ssh'd tmux, `less`, any TUI) drawn for the pane height of the moment, and replayed into a terminal of another height each repaint's last newline scrolls its top row into scrollback, so one line tmux holds once showed up dozens of times. Because `lines=` is shallower than xterm's scrollback, the route reports a cut: the capture's `display-message` query also reads `#{history_size}` (`PaneCaptureOptions.capturedHistoryLines`, the same field the route reports as `paneHistoryLines`), and a full capture whose CLIENT bound (`lines=` below the configured `tmuxHistoryLimit`) left lines in tmux comes back `truncated`, `truncationReason: 'tail'`. ⚠️ Only a client bound below the ceiling counts: a request without `lines=` is bounded by the ceiling itself, and on tmux before 3.7 a live pane can hold more than a lowered ceiling, which no request can read. ⚠️ **A pane in the alternate screen keeps no tmux history**, and a nested tmux client (remote SSH and Docker cases, or `tmux`/`ssh -t host tmux` run by hand) holds its pane there, so its full capture is one screen. The same query reads `#{alternate_on}` (`capturedAlternateOn`), and a request carrying `alt=recording` (only `SHELL_LOAD_QUERY`) is then answered the old way, the visible frame over the tailed byte recording, which still carries the scrollback; agents, scroll pulls and **Load full history** never send it. `#{alternate_on}` cannot tell a nested tmux from vim, `less` or `htop`, so a local shell with one of those open takes the same fallback until it exits (the pre-fix load, with its repaint duplicates). Shell FULL history is explicit-button-only; reaching the top during an ordinary wheel/touch gesture must not reset xterm and replay the multi-megabyte capture on its main thread. That gesture instead pulls a BOUNDED window of it (`?full=1&tail=<TERMINAL_TAIL_SIZE>`, so a capture beyond 1 MiB comes back `truncationReason: 'tail'` and the banner offers the rest), and skips the replay when the window holds no more rows than the browser already has. ⚠️ **That skip runs BEFORE the downgrade guard, and it never touches the banner state**: the guard reads "smaller than the browser" as "tmux has nothing more to give", true of an unbounded capture and false of a window cut at the tail size, so a bounded window that reached it marked the session `exhausted` and removed **Load full history** while tmux still held the rest; and re-labelling the banner from a skipped payload would call a terminal that holds all of a Load full history pull "the most recent 1 MiB". A skipped window that came back truncated puts the session on the 60 s cooldown (`_fullHistoryRepullUseless`), because it can never reach anything older than the browser shows and `tail` is applied AFTER the server's synchronous `capture-pane` of the whole history, so each ask costs every client an event-loop stall (about 0.3 s at 100k lines); an untruncated one keeps the 4 s cooldown, since it is all of tmux's history and the next burst can add to it. Declining the gesture outright was a dead end: after any burst a shell pane held about one screen of browser scrollback, and the button renders only once a replay was truncated, so a young shell tab had no way back to history tmux still held. Other modes re-pull `full=1` 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-ouLine truncated
**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 and with no pull in flight. A revealed truncation notice keeps its message and its **Load full history** control; Reload is appended only when the notice has no load control, or shown alone with a short missing-output message. A reload-only × dismissal lasts until the mark is cleared by a successful full mux replay, independently of the notice’s page-long dismissal. Eligibility is cached per active session, with onScroll sampling coalesced to one animation frame on every device; unchanged eligibility never rebuilds the banner. Automatic history pulls and notice reveal stay top-only (#205). The manual action forces a content-anchored pull, bypassing the gesture cooldown but retaining the downgrade guard. A content anchor captures the first non-empty row at/after the viewport and its next two rows, restores the nearest matching signature at the same viewport offset, and falls back to the nearest first-row-only match or distance from the bottom if unmatched or already near live output. Search is bounded to 2000 rows either side of the expected row (at most 4001 candidates / 12003 line reads). Ordered, session-scoped travel during replay is applied with per-move clamping; a switched-to tab never donates travel. The buffer load opens BEFORE the fetch, so download-time output queues behind the replay instead of being overwritten. Non-replay exits flush the whole queue; replays retain the capture-header cutoff above. A blocked dropped-output recovery stores its session and current attempt, defers without consuming retries, and resumes only for the still-active session. Only an actual `mux-full-history` replay clears the live-output mark and reload dismissal, and a newer live-write generation keeps them marked. The trade-off remains a full synchronous server capture (about 0.3 s at 100k lines), not a cheap automatic per-output repair. Tests: `test/shell-scroll-history-pull.test.ts`, `test/history-gap-repair.browser.test.ts`.
**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 with `paneHistoryLines` not 0. A revealed truncation notice keeps its message and its **Load full history** control; Reload is appended only when the notice has no load control, or shown alone with a short missing-output message. A reload-only × dismissal lasts until the mark is cleared by a successful `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. 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 cover at least two distinct rows and 60% of the context and must 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 is bounded to 2000 rows either side of the expected viewport (at most 4001 candidates / 4064 cached line reads). 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 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`.
+1
View File
@@ -51,6 +51,7 @@ non-updatable. See [Running As A Service](Running-As-A-Service).
| Input Field: Send on Enter | Off | With CJK Input on, typed text stays in the pinned field until Enter instead of streaming to the CLI, so on a phone you can scroll the terminal and edit an answer first. With a hardware keyboard, Shift+Enter adds a line (a phone's on-screen keyboard has none). Esc clears, autocorrect is on. |
| Extended Keyboard Bar | Per device | Which accessory bar phones get. Shell sessions override it while they are active. |
| Wheel Scrolls Local History | Off | Keeps the wheel on the local buffer instead of forwarding it to the CLI. Fullscreen pi leaves that buffer empty and has no paging fallback, so with this on the wheel does nothing there. |
| History Reload Button | On (per device) | Offers **Reload history** in the history banner while you are scrolled up in a non-shell session that has had live output since its last full capture; a tap re-pulls the full tmux history and keeps your reading position. |
| Auto Copy Selection | Off | Copies highlighted terminal text to the clipboard the moment you finish selecting it. Ctrl+C still copies on demand. |
| Trim The Pane Margin On Copy | On | Takes the left margin a full-screen agent CLI paints down its own edge off a copy, so the text pastes flush. Each CLI declares its own width, and the strip never exceeds the indent every selected line shares, so nesting is kept. Claude Code and Codex declare a margin; a shell does not. |
| Normal / Bold font weight | xterm defaults | Per device, each slot from 100 to 900. The bundled JetBrains Mono renders every step, so a lighter normal weight makes Claude's bold headings stand out. Applies live to the terminal, both echo overlays and open team panes. |
+6 -3
View File
@@ -243,11 +243,14 @@ Worth knowing:
reloads only the current screen, which keeps tab switches fast.
Shell sessions open from a bounded recent tail so a large transcript cannot stall tab
switching. Scrolling to the top of a Shell pane pulls the most recent 1 MiB of its tmux
history; press **Load full history** to pull the rest explicitly. That notice only
history; press **Load full history** to pull the rest explicitly. That truncation notice only
appears once you scroll to the top, leaves when you scroll back down, and stays away
for that tab once you close it. Sessions whose CLI keeps its own history (fullscreen
Claude) never show it, since there is nothing more to load. Automatic output
recovery stays within the bounded browser buffer.
Claude) never show it, since there is nothing more to load. The same bar can also offer
**Reload history** while scrolled up in an agent session after new output (toggle:
Settings → Terminal & Input → History Reload Button); it is not offered for panes
with no tmux history, such as fullscreen Claude. Automatic output recovery stays within
the bounded browser buffer.
- **Wheel and touch scrolling** are forwarded into Claude's own transcript when a recent
Claude runs fullscreen (`CLAUDE_CODE_NO_FLICKER=1`, or `"tui": "fullscreen"` in
`~/.claude/settings.json`), so the wheel scrolls the conversation rather than the terminal.
+12 -3
View File
@@ -9628,7 +9628,8 @@ class CodemanApp {
* the same `?full=1` capture a page reload uses (issue #205).
*
* Automatic pulls are top-only and cooldown/latch guarded: a synchronous
* capture can cost about 0.3 s at 100k lines and blocks the server event loop.
* capture can cost about 1 s at 100k lines (1,068 ms median for 12.1 MB of
* 120-character lines, `capture-pane -p -e -J -S -100000`) and blocks the server event loop.
* The manual Reload history action uses a content anchor to hold the reader's
* place even when new history fills a gap below them.
*
@@ -9761,6 +9762,7 @@ class CodemanApp {
timing.totalMs = performance.now() - requestStartedAt;
this._recordTerminalLoadTiming(timing);
(this._fullHistoryRepullUseless ||= new Set()).add(sessionId);
(this._historyReloadDismissed ||= new Set()).add(sessionId);
this._logScrollRouting?.('repull-refused-downgrade');
// The browser already holds more than tmux can give back, so there is
// nothing further to offer and the indicator must stop promising it.
@@ -9924,6 +9926,7 @@ class CodemanApp {
// Cheap state checks first: the terminal is read only for a marked session.
return !!(this.loadAppSettingsFromStorage?.()?.historyReloadAction !== false &&
session && session.mode !== 'shell' && this._liveOutputSinceFullPull?.has(sessionId) &&
this._paneHistoryLines?.get(sessionId) !== 0 && !this._isLoadingBuffer &&
!this._fullHistoryRepullInFlight && !this.detachedSessions?.has(sessionId) &&
!this._historyReloadDismissed?.has(sessionId) && !this._tilesOwnTerminal?.() &&
!this.isTerminalAtBottom());
@@ -9933,7 +9936,8 @@ class CodemanApp {
_syncHistoryReloadAction() {
const sessionId = this.activeSessionId;
const eligible = this._historyReloadActionEligible();
const loading = !!sessionId && this._historyReloadActionLoadingFor === sessionId;
const loading = !!sessionId && this._historyReloadActionLoadingFor === sessionId &&
!this._historyReloadDismissed?.has(sessionId);
const last = this._historyReloadActionState;
if (last && last.sessionId === sessionId && last.eligible === eligible && last.loading === loading) return;
this._historyReloadActionState = { sessionId, eligible, loading };
@@ -9963,7 +9967,8 @@ class CodemanApp {
const showNotice = notice.visible && this._historyNoticeRevealedFor === sessionId &&
!this._historyNoticeDismissed?.has(sessionId);
const eligible = this._historyReloadActionEligible?.() ?? false;
const loading = !!sessionId && this._historyReloadActionLoadingFor === sessionId;
const loading = !!sessionId && this._historyReloadActionLoadingFor === sessionId &&
!this._historyReloadDismissed?.has(sessionId);
this._historyReloadActionState = { sessionId, eligible, loading };
if (!showNotice && !eligible && !loading) {
bar.hidden = true;
@@ -9997,6 +10002,10 @@ class CodemanApp {
btn.disabled = loading;
btn.textContent = loading ? 'Loading…' : 'Reload history';
btn.onclick = () => {
if (!this._historyReloadActionEligible()) {
this._syncHistoryReloadAction();
return;
}
btn.disabled = true;
btn.textContent = 'Loading…';
this._historyReloadActionLoadingFor = sessionId;
+67 -32
View File
@@ -4011,50 +4011,72 @@ Object.assign(CodemanApp.prototype, {
return buffer.viewportY >= buffer.baseY - 2;
},
/** Capture the first readable row and its neighbours without copying the buffer. */
/** Capture bounded viewport context, not just repeated TUI borders/status rows. */
_captureViewportAnchor() {
const buffer = this.terminal.buffer.active;
const { viewportY, baseY } = buffer;
let row = viewportY;
while (row < buffer.length && !buffer.getLine(row)?.translateToString(true).trim()) row++;
const context = Array.from(
{ length: Math.min(this.terminal.rows || 3, 64, buffer.length - viewportY) },
(_, i) => buffer.getLine(viewportY + i)?.translateToString(true) || ''
);
const offset = Math.max(0, context.findIndex((text) => text.trim()));
return {
viewportY,
rowsFromBottom: baseY - viewportY,
offset: row - viewportY,
signature: Array.from({ length: 3 }, (_, i) => buffer.getLine(row + i)?.translateToString(true).trim() || ''),
offset,
signature: Array.from({ length: 3 }, (_, i) => context[offset + i] || ''),
context,
};
},
/** Restore the closest matching content, falling back to distance from live output. */
/** Match the visible context; a lone repeated row is not a reliable anchor. */
_restoreViewportAnchor(anchor) {
const buffer = this.terminal.buffer.active;
const clamp = (row) => Math.max(0, Math.min(buffer.baseY, row));
const fallback = clamp(buffer.baseY - anchor.rowsFromBottom);
let target = fallback;
if (anchor.rowsFromBottom > 2 && anchor.signature[0]) {
const expected = Math.max(0, Math.min(buffer.length - 1, buffer.baseY - anchor.rowsFromBottom + anchor.offset));
const text = (row) => buffer.getLine(row)?.translateToString(true).trim() || '';
let firstRowMatch = null;
let exactMatch = null;
// Scan at most 2000 rows either side (4001 candidates / 12003 line reads).
// Nearest first: stop at the first exact signature, otherwise use the
// nearest first-row match within budget rather than scanning 50k rows.
for (let distance = 0; distance <= Math.min(2000, buffer.length - 1); distance++) {
const left = expected - distance;
const right = expected + distance;
for (let side = 0; side < (distance === 0 ? 1 : 2); side++) {
const row = side === 0 ? left : right;
if (row < 0 || row >= buffer.length || text(row) !== anchor.signature[0]) continue;
if (firstRowMatch === null) firstRowMatch = row;
if (text(row + 1) === anchor.signature[1] && text(row + 2) === anchor.signature[2]) {
exactMatch = row;
break;
}
}
if (exactMatch !== null) break;
let target = clamp(anchor.viewportY);
if (anchor.rowsFromBottom <= 2) {
target = clamp(buffer.baseY - anchor.rowsFromBottom);
} else {
const expected = clamp(buffer.baseY - anchor.rowsFromBottom);
const frequencies = new Map();
for (const text of anchor.context) {
if (text.trim()) frequencies.set(text, (frequencies.get(text) || 0) + 1);
}
const match = exactMatch ?? firstRowMatch;
if (match !== null) target = clamp(match - anchor.offset);
const samples = anchor.context.flatMap((text, offset) =>
text.trim() ? [{ text, offset, weight: 1 / frequencies.get(text) }] : []
);
// Each distinct visible row contributes at most one point: repeated box
// borders cannot outvote the tool result the user is actually reading.
// Capped at the distinct-row count so a sparse viewport (one unique row
// among blanks) can still match; the ambiguity check rejects repeats.
const minimumScore = Math.min(frequencies.size, Math.max(2, frequencies.size * 0.6));
const first = Math.max(0, expected - 2000);
const last = Math.min(buffer.baseY, expected + 2000);
// Cache the search window once: <= 4064 getLine calls, even when all
// 4001 candidates match repeated TUI furniture in a 50k-row buffer.
const text = Array.from(
{ length: Math.min(buffer.length, last + anchor.context.length) - first },
(_, i) => buffer.getLine(first + i)?.translateToString(true) || ''
);
let bestScore = 0;
let bestRow = null;
let ambiguous = false;
for (let row = first; row <= last; row++) {
let score = 0;
for (const sample of samples) {
if (text[row - first + sample.offset] === sample.text) score += sample.weight;
}
if (score > bestScore + 1e-9) {
bestScore = score;
bestRow = row;
ambiguous = false;
} else if (Math.abs(score - bestScore) <= 1e-9) {
ambiguous = true;
}
}
// Equally good copies are evidence of repeated furniture, not of the
// reader's location. A gap below them makes nearest-to-expected wrong.
if (!ambiguous && bestScore + 1e-9 >= minimumScore) target = bestRow;
}
this.terminal.scrollToLine(target);
return target;
@@ -4736,6 +4758,13 @@ Object.assign(CodemanApp.prototype, {
this.terminal.buffer?.active && !this.isTerminalAtBottom() ? this.terminal.buffer.active.viewportY : null;
// Which buffer the anchor belongs to, checked again when the write parses.
const flushSessionId = this.activeSessionId;
// xterm adjusts marker lines when its circular scrollback trims rows. An
// absolute viewport index does not track that trim and would move the
// reader upward on every live flush at the scrollback cap (#814).
const viewportBuffer = this.terminal.buffer?.active;
const viewportMarker = preserveViewportY !== null
? this.terminal.registerMarker?.(preserveViewportY - (viewportBuffer.baseY + viewportBuffer.cursorY))
: null;
const writeChunk = joined.slice(0, MAX_FRAME_BYTES);
if (_joinedLen > MAX_FRAME_BYTES) {
@@ -4762,7 +4791,11 @@ Object.assign(CodemanApp.prototype, {
// signal, which is the earliest point the anchor can actually be
// reasserted. (The synchronous version passed its regression test only
// because the test's write mock moved the viewport synchronously.)
this._restoreTerminalViewport(preserveViewportY, flushSessionId);
const viewportY = viewportMarker
? (viewportMarker.isDisposed ? 0 : viewportMarker.line)
: preserveViewportY;
viewportMarker?.dispose();
this._restoreTerminalViewport(viewportY, flushSessionId);
this._scheduleTerminalWriteFlush();
this._noteMobileImeAuthoritativeOutput(flushedOutputSeq, flushSessionId);
});
@@ -4777,6 +4810,7 @@ Object.assign(CodemanApp.prototype, {
if (newlyMarked) this._syncHistoryReloadAction?.();
}
} catch (err) {
viewportMarker?.dispose();
this._terminalWriteInFlight = false;
this._terminalWriteInFlightBytes = 0;
throw err;
@@ -5105,6 +5139,7 @@ Object.assign(CodemanApp.prototype, {
this._isLoadingBuffer = false;
this._loadBufferQueue = null;
this._bufferLoadOwner = null;
this._syncHistoryReloadAction?.();
// COD-144: replay (rather than discard) queued live events when the load
// painted nothing — the queued prompt is the only content a new session has.
// A tmux-capture load replays too, but only the tail: `since` cuts the queue
+117
View File
@@ -466,3 +466,120 @@ describe.each([true, false])('manual history gap repair (touch: %s)', (touch) =>
}
}, 60_000);
});
it('holds an OMP reading row through repeated repaint history and capped live flushes', async () => {
const { context, page } = await openTerminal(true);
const readingRow = 'Reading tool result: src/engine.ts — preserve this row';
try {
const before = await page.evaluate(
async ({ session, readingRow }) => {
const w = window as RepairWindow;
const app = w.app;
const terminal = app.terminal;
const write = async (data: string) => {
const { promise, resolve } = Promise.withResolvers<void>();
terminal.write(data, resolve);
await promise;
};
terminal.reset();
terminal.options.scrollback = 50_000;
const repeated = [
'╭──────────────────╮',
'',
'│ Working… │',
'╰──────────────────╯',
'',
'⠋ OMP · processing',
];
const rows = Array.from({ length: 50_100 }, (_, i) =>
i % 1000 === 999 ? `tool output ${'wrapped context '.repeat(18)}` : repeated[i % repeated.length]
);
await write(rows.join('\r\n') + '\r\n');
terminal.scrollToLine(25_000);
app._syncStickyScrollBaseline();
// Cursor-addressed redraws and CSI S leave repeated TUI furniture in history.
const repaint = repeated.map((text, row) => `\x1b[${row + 1};1H\x1b[2K${text}`).join('');
app._onSessionTerminal({ id: session, data: `\x1b[6S${repaint}\x1b[6S${repaint}` });
await write('');
while (app.pendingWrites.length || app._terminalWriteInFlight) {
const { promise, resolve } = Promise.withResolvers<void>();
requestAnimationFrame(() => resolve());
await promise;
}
// Put the distinctive tool result BELOW the three repeated anchor rows.
const buffer = terminal.buffer.active;
const top = buffer.viewportY;
const snapshot = Array.from(
{ length: buffer.length },
(_, i) => buffer.getLine(i)?.translateToString(true) || ''
);
snapshot[top + 5] = readingRow;
await write('\x1bc' + snapshot.join('\r\n'));
terminal.scrollToLine(top);
app._syncStickyScrollBaseline();
const seeded = terminal.buffer.active;
const captured = Array.from(
{ length: seeded.length },
(_, i) => seeded.getLine(i)?.translateToString(true) || ''
);
captured.splice(top + 500, 0, ...Array.from({ length: 120 }, (_, i) => `Recovered tool detail ${i}`));
const terminalBuffer = captured.join('\r\n');
const realFetch = window.fetch.bind(window);
window.fetch = ((input: RequestInfo | URL, init?: RequestInit) => {
const url = String(typeof input === 'string' ? input : ((input as Request).url ?? input));
if (!url.includes(`/api/sessions/${session}/terminal`)) return realFetch(input, init);
w.repairTest.pulls++;
return Promise.resolve({
ok: true,
status: 200,
headers: new Headers(),
json: async () => {
app._onSessionTerminal({ id: session, data: '\r\nDownload-time output\r\n' });
return {
success: true,
data: { terminalBuffer, source: 'mux-full-history', paneHistoryLines: 100_000, truncated: false },
};
},
}) as unknown as Promise<Response>;
}) as typeof window.fetch;
app._liveOutputSinceFullPull.add(session);
app._syncHistoryReloadAction();
return {
offset: captured.indexOf(readingRow) - seeded.viewportY,
viewportY: seeded.viewportY,
baseY: seeded.baseY,
};
},
{ session: SESSION, readingRow }
);
const button = page.locator('#historyTruncationBar').getByRole('button', { name: 'Reload history' });
await button.tap();
await waitForRepair(page);
const measure = () =>
page.evaluate((readingRow) => {
const app = (window as RepairWindow).app;
const buffer = app.terminal.buffer.active;
let row = -1;
for (let i = 0; i < buffer.length; i++) {
if (buffer.getLine(i)?.translateToString(true) === readingRow) {
row = i;
break;
}
}
return { offset: row - buffer.viewportY, viewportY: buffer.viewportY, baseY: buffer.baseY };
}, readingRow);
const afterReplay = await measure();
await page.evaluate((session) => {
(window as RepairWindow).app._onSessionTerminal({ id: session, data: '\r\nPost-replay output\r\n' });
}, SESSION);
await waitForRepair(page);
const afterFlush = await measure();
expect({ before, afterReplay, afterFlush }).toEqual({
before,
afterReplay: { ...afterReplay, offset: before.offset },
afterFlush: { ...afterFlush, offset: before.offset },
});
} finally {
await context.close();
}
}, 120_000);
+117 -10
View File
@@ -143,6 +143,7 @@ function makeApp(
_loadBufferQueue: null as { at: number; data: string }[] | null,
_fullHistoryRepullAt: new Map<string, number>(),
_fullHistoryRepullUseless: new Set<string>(),
_historyReloadDismissed: new Set<string>(),
_paneHistoryLines: new Map<string, number>(),
terminalBufferCache: new Map<string, string>(),
terminal: {
@@ -373,6 +374,11 @@ describe('manual full-history recovery while reading (#814)', () => {
{ moves: [-1000, 30], distance: 340 },
])('replays travel $moves made during an unfinished replay, clamped per move', async ({ moves, distance }) => {
const { app, active, liveOutput, reload, pauseReplay } = makeScrollApp();
// The replay prepends older rows; give the reader real matching content
// rather than relying on the old blank-buffer bottom-distance fallback.
Object.assign(active, {
getLine: (row: number) => ({ translateToString: () => `history ${row - active.baseY}` }),
});
liveOutput();
active.viewportY -= 5; // Read five rows above live output before the manual action.
const paused = pauseReplay();
@@ -478,11 +484,16 @@ describe('manual full-history recovery while reading (#814)', () => {
liveOutput();
app._fullHistoryRepullAt.set('s1', Date.now());
active.length = 1000;
active.viewportY -= 5;
const eligible = loadAppMethod('_historyReloadActionEligible');
expect(eligible.call(app)).toBe(true);
await reload();
expect(urls).toHaveLength(1);
expect(app._resetTerminalForReplay).not.toHaveBeenCalled();
expect(app._liveOutputSinceFullPull.has('s1')).toBe(true);
expect(app._fullHistoryRepullUseless.has('s1')).toBe(true);
expect(app._historyReloadDismissed.has('s1')).toBe(true);
expect(eligible.call(app)).toBe(false);
});
it.each(['empty', 'tab-switch', 'downgrade', 'bounded-shell', 'rejection'])(
@@ -872,25 +883,25 @@ describe('content anchors hold the reader through a history repair', () => {
expect(anchor.offset).toBe(1);
});
it('chooses the nearest exact signature over a nearer first-row-only match', () => {
it('keeps the old viewport when two complete contexts match equally well', () => {
const { capture, restore } = fixture(['head', 'A', 'B', 'C', ...Array(20).fill('tail')], 1);
const anchor = capture();
const next = Array(34).fill('other');
next.splice(3, 3, 'A', 'B', 'C');
next.splice(10, 3, 'A', 'wrong', 'wrong');
next.splice(17, 3, 'A', 'B', 'C');
expect(restore(anchor, next)).toBe(17);
expect(restore(anchor, next)).toBe(1);
});
it('falls back to the nearest first row, then distance from the bottom when nothing matches', () => {
it('keeps the old viewport rather than trusting an isolated or absent row', () => {
const rows = Array.from({ length: 30 }, (_, i) => `row ${i}`);
const { capture, restore } = fixture(rows);
const anchor = capture();
const next = Array(40).fill('other');
next[8] = 'row 5';
next[17] = 'row 5';
expect(restore(anchor, next)).toBe(17);
expect(restore(anchor, Array(40).fill('no match'))).toBe(15);
expect(restore(anchor, next)).toBe(5);
expect(restore(anchor, Array(40).fill('no match'))).toBe(5);
});
it('keeps bottom distance within the bottom tolerance even if matching text exists', () => {
@@ -899,20 +910,56 @@ describe('content anchors hold the reader through a history repair', () => {
expect(restore(capture(), [...rows, ...Array(10).fill('new')])).toBe(36);
});
it('follows a lone distinctive row among blanks when history is inserted above the reader', () => {
const rows = Array.from({ length: 60 }, (_, i) => `row ${i}`);
for (let i = 20; i < 30; i++) rows[i] = '';
rows[25] = 'tool result: src/engine.ts';
const { app, capture, restore } = fixture(rows, 20);
Object.assign(app.terminal, { rows: 10 });
const anchor = capture();
const next = [...Array.from({ length: 40 }, (_, i) => `recovered ${i}`), ...rows];
expect(restore(anchor, next)).toBe(60);
});
it('uses the visible tool result rather than a nearer copy of repeated TUI borders', () => {
const repeated = ['╭────────╮', '', '│ Working │', '╰────────╯', '', 'OMP · processing'];
const rows = Array.from({ length: 300 }, (_, i) => repeated[i % repeated.length]);
rows[125] = 'tool result: src/engine.ts';
const { app, capture, restore } = fixture(rows, 120);
Object.assign(app.terminal, { rows: 18 });
const anchor = capture();
const next = [...rows.slice(0, 200), ...Array(60).fill('recovered below reader'), ...rows.slice(200)];
expect(restore(anchor, next)).toBe(120);
});
it.each([false, true])('keeps the old viewport for ambiguous furniture (distinctive row lost: %s)', (lost) => {
const repeated = ['╭────────╮', '', '│ Working │', '╰────────╯', '', 'OMP · processing'];
const rows = Array.from({ length: 300 }, (_, i) => repeated[i % repeated.length]);
if (lost) rows[125] = 'tool result absent from the capture';
const { app, capture, restore } = fixture(rows, 120);
Object.assign(app.terminal, { rows: 18 });
const anchor = capture();
const retained = rows.map((text, i) => (lost && i === 125 ? repeated[i % repeated.length] : text));
const next = [...retained.slice(0, 200), ...Array(60).fill('recovered below reader'), ...retained.slice(200)];
expect(restore(anchor, next)).toBe(120);
});
it.each(['first-row-only', 'absent'])('bounds a 50k-row search with an %s signature', (kind) => {
const rows = Array.from({ length: 50_000 }, (_, i) => `original ${i}`);
const { active, capture, restore } = fixture(rows, 25_000);
const { app, active, capture, restore } = fixture(rows, 25_000);
Object.assign(app.terminal, { rows: 64 });
const anchor = capture();
const next = Array(50_000).fill('other');
if (kind === 'first-row-only') {
next[25_100] = anchor.signature[0];
next[24_800] = anchor.signature[0];
}
// An exact match outside the budget must not make the scan traverse 50k rows.
next.splice(30_000, 3, ...anchor.signature);
// Even a whole matching viewport outside the budget cannot extend the scan.
next.splice(30_000, anchor.context.length, ...anchor.context);
active.getLine.mockClear();
expect(restore(anchor, next)).toBe(kind === 'first-row-only' ? 25_100 : 25_000);
expect(active.getLine.mock.calls.length).toBeLessThanOrEqual(4005);
expect(restore(anchor, next)).toBe(25_000);
// 4001 possible starts plus the other 63 rows in the full viewport context.
expect(active.getLine.mock.calls.length).toBeLessThanOrEqual(4064);
});
});
@@ -939,6 +986,8 @@ describe('manual history banner action', () => {
active: true,
detached: false,
enabled: true,
loadingBuffer: false,
paneHistoryLines: undefined as number | undefined,
...options,
};
const element = (): BannerElement => ({
@@ -976,6 +1025,10 @@ describe('manual history banner action', () => {
_historyNoticeDismissed: new Set<string>(),
_historyNoticeRevealedFor: null as string | null,
_fullHistoryRepullInFlight: Boolean(state.inFlight),
_isLoadingBuffer: Boolean(state.loadingBuffer),
_paneHistoryLines: new Map<string, number>(
state.paneHistoryLines === undefined ? [] : [['s1', Number(state.paneHistoryLines)]]
),
detachedSessions: new Set(state.detached ? ['s1'] : []),
_tilesOwnTerminal: () => state.tiles,
_maybeRefetchFullHistory: vi.fn(async (_opts: object) => {}),
@@ -1000,6 +1053,9 @@ describe('manual history banner action', () => {
{ opts: { bottom: true }, visible: false },
{ opts: { marked: false }, visible: false },
{ opts: { inFlight: true }, visible: false },
{ opts: { paneHistoryLines: 0 }, visible: false },
{ opts: { paneHistoryLines: 5 }, visible: true },
{ opts: { loadingBuffer: true }, visible: false },
{ opts: { tiles: true }, visible: false },
{ opts: { active: false }, visible: false },
{ opts: { detached: true }, visible: false },
@@ -1025,6 +1081,57 @@ describe('manual history banner action', () => {
expect(button()!.textContent).toBe('Reload history');
});
it('retires a refused reload and ignores another tap on the same stale button', async () => {
const { app, bar, button } = fixture();
app.terminal.buffer.active.length = 1000;
app._maybeRefetchFullHistory.mockImplementation((opts) => refetch.call(app, opts));
app._syncHistoryReloadAction();
const staleButton = button()!;
await staleButton.onclick!();
expect(app._resetTerminalForReplay).not.toHaveBeenCalled();
expect(app._historyReloadDismissed.has('s1')).toBe(true);
expect(bar.hidden).toBe(true);
expect(button()).toBeUndefined();
await staleButton.onclick!();
expect(app._fetchTerminalCapture).toHaveBeenCalledExactlyOnceWith('/api/sessions/s1/terminal?full=1', {
full: true,
});
expect(app._maybeRefetchFullHistory).toHaveBeenCalledOnce();
expect(bar.hidden).toBe(true);
});
it('syncs the action after a marked session finishes loading', () => {
const { app, bar, button } = fixture({ marked: false });
const owner = (mixin._beginBufferLoad as Function).call(app);
app._liveOutputSinceFullPull.add('s1');
app._syncHistoryReloadAction();
expect(app._historyReloadActionEligible()).toBe(false);
expect(bar.hidden).toBe(true);
(mixin._finishBufferLoad as Function).call(app, owner);
expect(app._isLoadingBuffer).toBe(false);
expect(app._historyReloadActionEligible()).toBe(true);
expect(bar.hidden).toBe(false);
expect(button()!.textContent).toBe('Reload history');
});
it('hides a dismissed loading action before the pull settles and keeps it hidden', async () => {
const { app, bar, button, dismiss } = fixture();
const { promise, resolve: release } = Promise.withResolvers<void>();
app._maybeRefetchFullHistory.mockReturnValueOnce(promise);
app._syncHistoryReloadAction();
const tapped = button()!.onclick!();
expect(button()!.textContent).toBe('Loading…');
dismiss()!.onclick!();
expect(bar.hidden).toBe(true);
expect(app._historyReloadDismissed.has('s1')).toBe(true);
app._syncHistoryReloadAction();
expect(bar.hidden).toBe(true);
release();
await tapped;
expect(bar.hidden).toBe(true);
expect(button()).toBeUndefined();
});
it.each(['recoverable', 'exhausted', 'capped'])('never duplicates the %s notice load control', (kind) => {
const { app, bar, button } = fixture();
app._historyNoticeRevealedFor = 's1';