mirror of
https://github.com/Ark0N/Codeman.git
synced 2026-11-30 16:39:33 +01:00
fix(web): repair the history gap while reading, queue download-time output, add a phone reload control (#814)
Review follow-up on #815, and the phone case from #814: the gap opens below a reader who stays scrolled up while output arrives, and the bottom-only trigger never fired there. - Open the buffer load before the capture fetch so output arriving during the download is queued and replayed, not wiped by the reset. Every non-replay exit flushes the queue. A drop at the 128 KiB cap during an open load is deferred and resumed when the load ends instead of spending its retries against it. - Clear the live-output mark only when the response is source 'mux-full-history', on the scroll and tab-switch paths. - Repair on any upward scroll in a marked non-shell session, not only from the bottom. A content anchor (3-row signature, searched at most 2000 rows either side) keeps the row being read in place; no match falls back to distance from the bottom. - Tie replay travel to its session so a tab switch does not swallow moves on the new tab. - Reveal the partial-history notice when the initiating gesture reached the top, even if the anchor moved the viewport off row 0. - Touch-only Reload history button (#historyReloadBtn), styled in styles.css so wide touch viewports get it too. Non-touch pages skip its work entirely. - Docs, JSDoc and a changeset. Unit tests, and a Playwright browser test with trusted touch events and real xterm. Fixes #814
This commit is contained in:
1 parent
fd31315582
commit
b890ef3302
10 files changed
+1050
-84
No files matched your search
@@ -0,0 +1,5 @@
|
||||
---
|
||||
'aicodeman': patch
|
||||
---
|
||||
|
||||
Fix missing terminal history above live OMP output, including when scrolling up while already reading older output on a phone. History recovery now preserves the text being read and output arriving during the download, and touch devices offer a Reload history button while scrolled away from live output.
|
||||
@@ -39,6 +39,7 @@ export const BROWSER_TEST_GLOBS = [
|
||||
'test/terminal-copy-shortcut.test.ts',
|
||||
'test/terminal-keycode229-recovery.browser.test.ts',
|
||||
'test/capture-load-window.browser.test.ts',
|
||||
'test/history-gap-repair.browser.test.ts',
|
||||
'test/capture-geometry-retry.browser.test.ts',
|
||||
'test/codex-predictive-echo.test.ts', // also needs a real codex binary
|
||||
'test/split-pane-terminal.browser.test.ts',
|
||||
|
||||
@@ -251,7 +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 may still re-pull `full=1` at the TOP, and pressing **Load full history** forces the request for any recoverably truncated session (`_maybeRefetchFullHistory`, 4s per-session gesture cooldown, in-flight + tab-switch guards, viewport position held across the replay); Shell full pulls are not retained in the tab cache, so the next switch stays bounded. Chunked replay enqueues 32 KiB pieces across safe yields, appends an xterm parse marker, then releases the live-output gate; outpLine 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 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` at the top or on any upward scroll after live output since the last `mux-full-history` replay, 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 yieldsLine truncated
|
||||
|
||||
**Repair while reading (#814)** opens the buffer load BEFORE the capture fetch, so download-time output queues behind the replay instead of being overwritten. Every non-replay exit flushes the whole queue into the untouched buffer; a replay keeps the capture-header cutoff above. A dropped-output recovery blocked by an open load is deferred without consuming retries and resumes when the load finishes, only for the still-active session. Only an actual `mux-full-history` response may clear the live-output mark, and a newer live-write generation keeps it marked. Any upward scroll in a marked non-shell session repairs, including mid-history and at the top (one pull per gesture), still guarded by the 4 s cooldown, 60 s useless-pull latch and downgrade refusal. A gesture that reached the original top still reveals the resulting partial-history notice even if the content restore moves it below row zero; a mid-history repair does not reveal it unless subsequent travel reaches the top. 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), never the entire 50k-row buffer. Ordered, session-scoped travel during replay is then applied with per-move clamping; a switched-to tab never donates travel. On touch devices a floating **Reload history** button offers the same forced, content-anchored recovery while scrolled up in a marked non-shell session, never while tiles own the terminal or another pull is running. `_syncHistoryReloadButton()` alone owns its visibility; its overlay/44px touch-target rules live in the unconditional stylesheet so wide touch viewports do not resize the terminal. The trade-off remains synchronous server `capture-pane`: about 0.3 s at 100k lines, blocking the event loop, 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`.
|
||||
|
||||
|
||||
+44
-24
@@ -801,12 +801,12 @@ class CodemanApp {
|
||||
// the small `full=1` capture instead of the 1 MiB byte tail: see
|
||||
// _notePaneHistory and selectSession.
|
||||
this._paneHistoryLines = new Map(); // Map<sessionId, number>
|
||||
// Cooldown per session for the scroll-to-top "load more history" re-pull.
|
||||
// Per-session cooldown for upward-scroll history repair / top-of-buffer pulls.
|
||||
this._fullHistoryRepullAt = new Map(); // Map<sessionId, timestamp>
|
||||
this._fullHistoryRepullInFlight = false;
|
||||
this._liveOutputSinceFullPull = new Set(); // Set<sessionId>
|
||||
this._liveOutputGen = new Map(); // Map<sessionId, number>
|
||||
this._earlyReplayTravel = null; // number[] while an early (#814) replay runs
|
||||
this._earlyReplayTravel = null; // { sessionId, moves: number[] } during a content-anchored replay
|
||||
// Sessions whose last re-pull came back THINNER than the live buffer (a
|
||||
// repaint-mode CLI pane, where tmux keeps no history of its own). The pull is
|
||||
// refused for those and retried far more slowly — see _maybeRefetchFullHistory.
|
||||
@@ -2599,13 +2599,31 @@ class CodemanApp {
|
||||
* @param {number} [queuedBytes] - render-queue bytes at the drop, for the crash trail
|
||||
*/
|
||||
_scheduleDroppedOutputRecovery(sessionId, attempt = 0, queuedBytes) {
|
||||
if (!sessionId || this._clientDropRecoveryTimer) return;
|
||||
if (!sessionId) return;
|
||||
// Nothing of the main terminal's to recover while the tile grid owns it.
|
||||
if (this._tilesOwnTerminal?.()) return;
|
||||
// A slow capture owns the live-output gate. Keep the recovery owed until
|
||||
// it releases instead of spending every retry against the same open load.
|
||||
if (this._isLoadingBuffer) {
|
||||
if (sessionId === this.activeSessionId) {
|
||||
if (this._pendingDroppedOutputRecovery !== sessionId && Number.isFinite(queuedBytes)) {
|
||||
_crashDiag.log(`TERMINAL DROP: ${(queuedBytes / 1024).toFixed(0)}KB queued (recovery deferred)`);
|
||||
}
|
||||
this._pendingDroppedOutputRecovery = sessionId;
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (this._clientDropRecoveryTimer) return;
|
||||
// Behind the debounce guard: one line per window, not per dropped frame.
|
||||
if (Number.isFinite(queuedBytes)) _crashDiag.log(`TERMINAL DROP: ${(queuedBytes / 1024).toFixed(0)}KB queued`);
|
||||
this._clientDropRecoveryTimer = setTimeout(async () => {
|
||||
this._clientDropRecoveryTimer = null;
|
||||
// A load may have opened after this timer was armed. Defer without
|
||||
// advancing the attempt; _finishBufferLoad resumes only the active tab.
|
||||
if (this._isLoadingBuffer) {
|
||||
if (sessionId === this.activeSessionId) this._pendingDroppedOutputRecovery = sessionId;
|
||||
return;
|
||||
}
|
||||
let repainted = false;
|
||||
let timedOut = false;
|
||||
try {
|
||||
@@ -9596,8 +9614,8 @@ class CodemanApp {
|
||||
}
|
||||
|
||||
/**
|
||||
* "Load more history": re-pull the whole tmux scrollback when the user scrolls up
|
||||
* while already at the top of what the browser has.
|
||||
* Re-pull tmux history at the top, or on any upward scroll in a non-shell
|
||||
* session marked by live output since its last mux-full-history replay.
|
||||
*
|
||||
* xterm's buffer is only ever a WINDOW onto tmux's real history, and two things
|
||||
* shrink it. tmux repaints the pane rectangle instead of emitting linefeeds
|
||||
@@ -9608,9 +9626,9 @@ class CodemanApp {
|
||||
* everything (history-limit 100k by default), so the fix is to go ask for it with
|
||||
* the same `?full=1` capture a page reload uses (issue #205).
|
||||
*
|
||||
* On demand rather than automatic because that capture is unbounded-ish work: at
|
||||
* the default history limit it can be megabytes, which is fine to pay when the
|
||||
* user is explicitly reaching for history and not fine on every tab switch.
|
||||
* Gesture-triggered and cooldown/latch guarded: a synchronous capture can cost
|
||||
* about 0.3 s at 100k lines and blocks the server event loop. Content anchors
|
||||
* hold the reader's place even when new history fills a gap below them.
|
||||
*
|
||||
* NEVER a downgrade: for a repaint-mode CLI pane tmux keeps no history of its
|
||||
* own, so the capture can be THINNER than what xterm already holds and the
|
||||
@@ -9653,14 +9671,15 @@ class CodemanApp {
|
||||
if (!force && now - (this._fullHistoryRepullAt.get(sessionId) || 0) < cooldown) return;
|
||||
this._fullHistoryRepullAt.set(sessionId, now);
|
||||
this._fullHistoryRepullInFlight = true;
|
||||
const loadOwner = this._beginBufferLoad();
|
||||
let replayed = false;
|
||||
// The session-id check below cannot see a tab switch that came BACK during
|
||||
// the fetch (A -> B -> A): the id matches again while `selectSession` is
|
||||
// replaying its own capture, and the reset below would land in the middle
|
||||
// of that write. The select generation moves on every switch, so it can.
|
||||
const selectGen = this._selectGeneration;
|
||||
// Sampled BEFORE the fetch: this path does not gate live output while the
|
||||
// capture downloads, so output flushed after tmux captured would otherwise
|
||||
// be overwritten by the replay and still count as covered by it (#814).
|
||||
// Queued output replayed after this load may mark the session again. Never
|
||||
// clear that newer generation along with the capture's original mark.
|
||||
const liveOutputGen = this._liveOutputGen?.get(sessionId) || 0;
|
||||
try {
|
||||
const requestStartedAt = performance.now();
|
||||
@@ -9757,10 +9776,9 @@ class CodemanApp {
|
||||
this._fullHistoryRepullUseless?.delete(sessionId);
|
||||
const rowsBefore = this.terminal.buffer.active.length;
|
||||
const replayStartedAt = performance.now();
|
||||
const rowsFromBottom = this.terminal.buffer.active.baseY - this.terminal.buffer.active.viewportY;
|
||||
// Ordered, not summed: each move clamps at the buffer edge as it would
|
||||
// have live, so a reversal after hitting the bottom is not cancelled out.
|
||||
if (anchor === 'bottom') this._earlyReplayTravel = [];
|
||||
const viewportAnchor = anchor === 'content' ? this._captureViewportAnchor() : null;
|
||||
// Ordered, not summed: each move clamps at the buffer edge as it would live.
|
||||
if (anchor === 'content') this._earlyReplayTravel = { sessionId, moves: [] };
|
||||
this._resetTerminalForReplay();
|
||||
const {
|
||||
parsedAt,
|
||||
@@ -9769,12 +9787,13 @@ class CodemanApp {
|
||||
} = await this.chunkedTerminalWrite(
|
||||
buffer,
|
||||
TERMINAL_CHUNK_SIZE,
|
||||
sessionId,
|
||||
loadOwner,
|
||||
this._bufferLoadFinishOpts(payload, headersReceivedAt)
|
||||
);
|
||||
replayed = true; // chunkedTerminalWrite finished this load with the capture cutoff.
|
||||
timing.resetAndParseMs = parsedAt - replayStartedAt;
|
||||
if (!completed || this.activeSessionId !== sessionId || selectGen !== this._selectGeneration) return;
|
||||
if ((this._liveOutputGen?.get(sessionId) || 0) === liveOutputGen) {
|
||||
if (payload.source === 'mux-full-history' && (this._liveOutputGen?.get(sessionId) || 0) === liveOutputGen) {
|
||||
this._liveOutputSinceFullPull?.delete(sessionId);
|
||||
}
|
||||
// Keep shell tab restores bounded too. A user-triggered full-history pull
|
||||
@@ -9789,14 +9808,12 @@ class CodemanApp {
|
||||
// UPWARD, so what used to be row 0 (what they were looking at) is now `delta`
|
||||
// rows down; scrolling there reveals the recovered history above it instead
|
||||
// of teleporting them to the bottom the way a normal buffer load does.
|
||||
if (anchor === 'bottom') {
|
||||
// Recover the tmux repaint gap above the live screen without a jump (#814).
|
||||
if (anchor === 'content') {
|
||||
const baseY = this.terminal.buffer.active.baseY;
|
||||
const clamp = (row) => Math.max(0, Math.min(baseY, row));
|
||||
let row = clamp(baseY - rowsFromBottom);
|
||||
for (const move of this._earlyReplayTravel) row = clamp(row + move);
|
||||
let row = this._restoreViewportAnchor(viewportAnchor);
|
||||
for (const move of this._earlyReplayTravel.moves) row = clamp(row + move);
|
||||
this.terminal.scrollToLine(row);
|
||||
this._earlyReplayTravel = null;
|
||||
} else {
|
||||
const delta = parsedBufferLength - rowsBefore;
|
||||
if (delta > 0) this.terminal.scrollToLine(delta);
|
||||
@@ -9817,8 +9834,10 @@ class CodemanApp {
|
||||
} catch {
|
||||
// Transient (offline, 5xx) — the next scroll-up past the cooldown retries.
|
||||
} finally {
|
||||
if (anchor === 'bottom') this._earlyReplayTravel = null;
|
||||
if (!replayed) this._finishBufferLoad(loadOwner, { flushQueued: true, since: 0 });
|
||||
if (anchor === 'content') this._earlyReplayTravel = null;
|
||||
this._fullHistoryRepullInFlight = false;
|
||||
this._syncHistoryReloadButton?.();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10074,6 +10093,7 @@ class CodemanApp {
|
||||
this.activeSessionId = sessionId;
|
||||
this._activateFileBrowserSession?.(sessionId);
|
||||
if (typeof CjkInput !== 'undefined') CjkInput.restoreDraft?.(sessionId);
|
||||
this._syncHistoryReloadButton?.();
|
||||
// A keyboard row hold belongs to the session it was taken for: release it here
|
||||
// if this one resizes instead (the geometry work below then fits it).
|
||||
this._reconcileKeyboardHold?.({ resize: false });
|
||||
@@ -10459,7 +10479,7 @@ class CodemanApp {
|
||||
this._clearTerminalLoadState(sessionId, selectGen);
|
||||
return;
|
||||
}
|
||||
if (fullHistoryReplay && completed && (this._liveOutputGen?.get(sessionId) || 0) === liveOutputGen) {
|
||||
if (fullHistoryReplay && data.source === 'mux-full-history' && completed && (this._liveOutputGen?.get(sessionId) || 0) === liveOutputGen) {
|
||||
this._liveOutputSinceFullPull?.delete(sessionId);
|
||||
}
|
||||
// Ensure terminal is scrolled to bottom after buffer load
|
||||
|
||||
@@ -478,6 +478,7 @@
|
||||
scrolled away with the output it described and could not be acted
|
||||
on. Populated by app.js _renderHistoryTruncationBanner(). -->
|
||||
<div class="history-trunc-bar" id="historyTruncationBar" role="status" aria-live="polite" hidden></div>
|
||||
<button id="historyReloadBtn" type="button" class="history-reload-btn" aria-label="Reload history" hidden>↻ Reload history</button>
|
||||
<div class="terminal-container" id="terminalContainer"></div>
|
||||
<textarea id="cjkInput" rows="1" placeholder="CJK input (Enter = send, Esc = clear)"
|
||||
maxlength="65536" aria-label="CJK IME input field"
|
||||
|
||||
@@ -4401,6 +4401,26 @@ html[data-tab-logos='off'] .home-sessions-harness {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
/* Touch-only control; _syncHistoryReloadButton owns its hidden state. */
|
||||
.history-reload-btn {
|
||||
position: absolute;
|
||||
top: 0.5rem;
|
||||
right: 0.5rem;
|
||||
z-index: 20;
|
||||
min-width: 44px;
|
||||
min-height: 44px;
|
||||
padding: 0.5rem 0.75rem;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 6px;
|
||||
background: var(--bg-card);
|
||||
color: var(--text);
|
||||
touch-action: manipulation;
|
||||
}
|
||||
|
||||
.history-reload-btn:disabled {
|
||||
opacity: 0.65;
|
||||
}
|
||||
|
||||
/* Partial-history banner (#258).
|
||||
OVERLAY, not a flex child, on purpose: FitAddon derives rows/cols from the
|
||||
terminal parent's computed height, so a banner that occupied real layout
|
||||
|
||||
+106
-40
@@ -1061,6 +1061,7 @@ Object.assign(CodemanApp.prototype, {
|
||||
typeof PredictiveEchoOverlay !== 'undefined' ? new PredictiveEchoOverlay(this.terminal) : null;
|
||||
this._predictiveEcho?.setPredictWhen((terminal) => window.CodemanTerminalInput.isCodexComposerRow(terminal));
|
||||
if (MobileDetection.isTouchDevice()) {
|
||||
this.terminal.onScroll(() => this._syncHistoryReloadButton());
|
||||
this.terminal.onCursorMove(() => this._syncMobileHelperTextareaToCursor());
|
||||
this.terminal.onRender(() => this._syncMobileHelperTextareaToCursor());
|
||||
// Keep the live content above the keyboard while the rows are held.
|
||||
@@ -4010,6 +4011,80 @@ Object.assign(CodemanApp.prototype, {
|
||||
return buffer.viewportY >= buffer.baseY - 2;
|
||||
},
|
||||
|
||||
/** Capture the first readable row and its neighbours without copying the buffer. */
|
||||
_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++;
|
||||
return {
|
||||
viewportY,
|
||||
rowsFromBottom: baseY - viewportY,
|
||||
offset: row - viewportY,
|
||||
signature: Array.from({ length: 3 }, (_, i) => buffer.getLine(row + i)?.translateToString(true).trim() || ''),
|
||||
};
|
||||
},
|
||||
|
||||
/** Restore the closest matching content, falling back to distance from live output. */
|
||||
_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;
|
||||
}
|
||||
const match = exactMatch ?? firstRowMatch;
|
||||
if (match !== null) target = clamp(match - anchor.offset);
|
||||
}
|
||||
this.terminal.scrollToLine(target);
|
||||
return target;
|
||||
},
|
||||
|
||||
/** Sole owner of the touch-only history reload control's visibility. */
|
||||
_syncHistoryReloadButton() {
|
||||
// Touch capability does not change at runtime and desktop never shows the
|
||||
// control, so non-touch pages skip the DOM work entirely.
|
||||
const touch = typeof MobileDetection !== 'undefined' && MobileDetection.isTouchDevice();
|
||||
if (!touch) return;
|
||||
const button = document.getElementById('historyReloadBtn');
|
||||
if (!button) return;
|
||||
const sessionId = this.activeSessionId;
|
||||
const session = this.sessions.get(sessionId);
|
||||
const visible = !!(touch && session && session.mode !== 'shell' &&
|
||||
!this.isTerminalAtBottom() && this._liveOutputSinceFullPull?.has(sessionId) &&
|
||||
!this._tilesOwnTerminal?.() && !this._fullHistoryRepullInFlight);
|
||||
if (button.hidden === visible) button.hidden = !visible;
|
||||
if (this._fullHistoryRepullInFlight) return;
|
||||
button.disabled = false;
|
||||
button.textContent = '↻ Reload history';
|
||||
button.onclick = () => {
|
||||
button.disabled = true;
|
||||
button.textContent = 'Loading…';
|
||||
return Promise.resolve(this._maybeRefetchFullHistory({ force: true, anchor: 'content' }))
|
||||
.finally(() => this._syncHistoryReloadButton());
|
||||
};
|
||||
},
|
||||
|
||||
/**
|
||||
* Re-take the sticky-scroll baseline from where the viewport now sits.
|
||||
*
|
||||
@@ -4054,13 +4129,11 @@ Object.assign(CodemanApp.prototype, {
|
||||
},
|
||||
|
||||
/**
|
||||
* Post-scroll companion to _noteTerminalUserScroll: hitting the TOP of the
|
||||
* buffer while scrolling up gives the app a chance to pull the rest of tmux's
|
||||
* scrollback (issue #205, see _maybeRefetchFullHistory). Shell sessions pull a
|
||||
* bounded window because their captures can be large; their banner button is
|
||||
* the unbounded path. Must be called AFTER scrollLines(), since the check is on
|
||||
* the resulting position, and it is deliberately not folded into
|
||||
* _noteTerminalUserScroll for exactly that reason.
|
||||
* After scrollLines(), repair on ANY upward gesture in a non-shell session
|
||||
* marked by live output since its last mux-full-history replay (#814), using
|
||||
* a content anchor to hold the reader's place. Unmarked sessions still pull
|
||||
* at the top (#205); shells pull only a bounded window there. The pull owns
|
||||
* cooldown/latch and downgrade guards.
|
||||
*
|
||||
* It is also what brings up the partial-history notice, and what retires it
|
||||
* once a downward scroll is back at live output (_setHistoryNoticeRevealed).
|
||||
@@ -4068,8 +4141,8 @@ Object.assign(CodemanApp.prototype, {
|
||||
* what the pull left rather than flashing the state it is about to replace.
|
||||
*/
|
||||
_maybeLoadMoreHistoryOnScroll(lines) {
|
||||
if (Array.isArray(this._earlyReplayTravel)) {
|
||||
this._earlyReplayTravel.push(lines);
|
||||
if (this._earlyReplayTravel?.sessionId === this.activeSessionId) {
|
||||
this._earlyReplayTravel.moves.push(lines);
|
||||
return;
|
||||
}
|
||||
if (lines > 0) {
|
||||
@@ -4078,39 +4151,22 @@ Object.assign(CodemanApp.prototype, {
|
||||
}
|
||||
if (lines === 0) return;
|
||||
const buffer = this.terminal?.buffer?.active;
|
||||
if (buffer?.viewportY !== 0) {
|
||||
const sessionId = this.activeSessionId;
|
||||
// tmux repaint bursts can leave a gap just above live output (#814).
|
||||
// Called after scrollLines: include this gesture's travel in the bottom check.
|
||||
if (
|
||||
lines < 0 &&
|
||||
sessionId &&
|
||||
this._liveOutputSinceFullPull?.has(sessionId) &&
|
||||
this.sessions.get(sessionId)?.mode !== 'shell' &&
|
||||
buffer?.viewportY >= buffer.baseY - 2 - Math.abs(lines) &&
|
||||
!this._fullHistoryRepullInFlight &&
|
||||
!this._isLoadingBuffer
|
||||
) {
|
||||
Promise.resolve(this._maybeRefetchFullHistory?.({ anchor: 'bottom' }))
|
||||
.catch(() => {})
|
||||
.then(() => {
|
||||
// Travel during the replay is swallowed above, so a gesture that
|
||||
// reached the top meanwhile still owes the notice its reveal.
|
||||
if (this.activeSessionId === sessionId && this.terminal?.buffer?.active?.viewportY === 0) {
|
||||
this._setHistoryNoticeRevealed?.(sessionId);
|
||||
}
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
// An earlier frame of this gesture already started the pull; its own
|
||||
// completion reveals the notice, so do not flash the pre-pull state now.
|
||||
if (this._fullHistoryRepullInFlight || this._isLoadingBuffer) return;
|
||||
const reachedTop = buffer?.viewportY === 0;
|
||||
const sessionId = this.activeSessionId;
|
||||
Promise.resolve(this._maybeRefetchFullHistory?.())
|
||||
const repair = sessionId && this._liveOutputSinceFullPull?.has(sessionId) &&
|
||||
this.sessions.get(sessionId)?.mode !== 'shell';
|
||||
if (!repair && buffer?.viewportY !== 0) return;
|
||||
// An earlier frame already started a pull and owns the notice reveal.
|
||||
if (this._fullHistoryRepullInFlight || this._isLoadingBuffer) return;
|
||||
Promise.resolve(repair
|
||||
? this._maybeRefetchFullHistory?.({ anchor: 'content' })
|
||||
: this._maybeRefetchFullHistory?.())
|
||||
.catch(() => {})
|
||||
.then(() => {
|
||||
if (sessionId && this.activeSessionId === sessionId) this._setHistoryNoticeRevealed?.(sessionId);
|
||||
if (sessionId && this.activeSessionId === sessionId &&
|
||||
(reachedTop || this.terminal?.buffer?.active?.viewportY === 0)) {
|
||||
this._setHistoryNoticeRevealed?.(sessionId);
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
@@ -4735,9 +4791,14 @@ Object.assign(CodemanApp.prototype, {
|
||||
});
|
||||
// Only live writes can open a new tmux repaint gap; replays cannot (#814).
|
||||
if (writeChunk.length && flushSessionId && !this._isLoadingBuffer) {
|
||||
(this._liveOutputSinceFullPull ||= new Set()).add(flushSessionId);
|
||||
const marked = (this._liveOutputSinceFullPull ||= new Set());
|
||||
const newlyMarked = !marked.has(flushSessionId);
|
||||
marked.add(flushSessionId);
|
||||
const generations = (this._liveOutputGen ||= new Map());
|
||||
generations.set(flushSessionId, (generations.get(flushSessionId) || 0) + 1);
|
||||
// Visibility only changes here when the mark appears; scrolling is
|
||||
// covered by the touch-only onScroll hook.
|
||||
if (newlyMarked) this._syncHistoryReloadButton?.();
|
||||
}
|
||||
} catch (err) {
|
||||
this._terminalWriteInFlight = false;
|
||||
@@ -5079,6 +5140,11 @@ Object.assign(CodemanApp.prototype, {
|
||||
this.batchTerminalWrite(entry.data);
|
||||
}
|
||||
}
|
||||
const recoverySession = this._pendingDroppedOutputRecovery;
|
||||
this._pendingDroppedOutputRecovery = null;
|
||||
if (recoverySession && recoverySession === this.activeSessionId) {
|
||||
this._scheduleDroppedOutputRecovery?.(recoverySession);
|
||||
}
|
||||
return true;
|
||||
},
|
||||
|
||||
|
||||
@@ -0,0 +1,451 @@
|
||||
/** Real xterm + trusted phone gestures recover tmux repaint gaps while reading (#814). */
|
||||
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
||||
import { chromium, type Browser, type BrowserContext, type Page } from 'playwright';
|
||||
import type { Terminal } from '@xterm/xterm';
|
||||
import { WebServer } from '../src/web/server.js';
|
||||
|
||||
type Anchor = { signature: string[]; offset: number; viewportY: number; rowsFromBottom: number };
|
||||
type HistoryApp = {
|
||||
terminal: Terminal & {
|
||||
_core?: { _renderService?: { dimensions?: { css?: { cell?: { height: number } } } } };
|
||||
};
|
||||
fitAddon: { proposeDimensions(): { cols: number; rows: number } | undefined };
|
||||
sessions: Map<string, object>;
|
||||
activeSessionId: string;
|
||||
hideWelcome(): void;
|
||||
_onSessionTerminal(event: { id: string; data: string }): void;
|
||||
_liveOutputSinceFullPull: Set<string>;
|
||||
_fullHistoryRepullInFlight: boolean;
|
||||
_isLoadingBuffer: boolean;
|
||||
pendingWrites: string[];
|
||||
_terminalWriteInFlight: boolean;
|
||||
_bufferLoadOwner: unknown;
|
||||
_loadBufferQueue: { data: string; at: number }[] | null;
|
||||
_selectGeneration: number;
|
||||
_initGeneration: number;
|
||||
terminalLoadStates: Map<string, unknown>;
|
||||
_terminalFontReady: Promise<void>;
|
||||
_resizeTimeout: number | null;
|
||||
_lastResizeDims: { cols: number; rows: number } | null;
|
||||
_syncStickyScrollBaseline(): void;
|
||||
_captureViewportAnchor(): Anchor;
|
||||
_syncHistoryReloadButton(): void;
|
||||
};
|
||||
type RepairWindow = Window & {
|
||||
app: HistoryApp;
|
||||
repairTest: { pulls: number; anchor: Anchor | null; inject: boolean };
|
||||
repairReadiness?: { cols: number; rows: number; frames: number };
|
||||
};
|
||||
|
||||
const SESSION = 'history-repair-browser';
|
||||
const MARKER = 'AFTER-CAPTURE-DURING-DOWNLOAD';
|
||||
let server: WebServer;
|
||||
let browser: Browser;
|
||||
let baseUrl: string;
|
||||
const pageEvents = new WeakMap<Page, string[]>();
|
||||
|
||||
async function setupState(page: Page) {
|
||||
return page.evaluate(() => {
|
||||
const app = (window as RepairWindow).app;
|
||||
const buffer = app?.terminal?.buffer.active;
|
||||
return {
|
||||
appLoaded: document.body.classList.contains('app-loaded'),
|
||||
baseY: buffer?.baseY,
|
||||
length: buffer?.length,
|
||||
viewportY: buffer?.viewportY,
|
||||
cols: app?.terminal?.cols,
|
||||
rows: app?.terminal?.rows,
|
||||
resizePending: Boolean(app?._resizeTimeout),
|
||||
lastResizeDims: app?._lastResizeDims,
|
||||
proposedDims: app?.fitAddon?.proposeDimensions(),
|
||||
cellHeight: app?.terminal?._core?._renderService?.dimensions?.css?.cell?.height,
|
||||
pendingWrites: app?.pendingWrites?.length,
|
||||
terminalWriteInFlight: app?._terminalWriteInFlight,
|
||||
isLoadingBuffer: app?._isLoadingBuffer,
|
||||
bufferLoadOwner: app?._bufferLoadOwner,
|
||||
loadBufferQueue: app?._loadBufferQueue?.length ?? 0,
|
||||
activeSessionId: app?.activeSessionId,
|
||||
selectGeneration: app?._selectGeneration,
|
||||
sessions: app?.sessions ? [...app.sessions.keys()] : [],
|
||||
initGeneration: app?._initGeneration,
|
||||
terminalLoadStates: app?.terminalLoadStates ? [...app.terminalLoadStates] : [],
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
async function failureDetails(page: Page, error: unknown): Promise<Error> {
|
||||
const setup = await setupState(page).catch(String);
|
||||
const buffer = await bufferState(page).catch(String);
|
||||
return new Error(JSON.stringify({ setup, buffer, events: pageEvents.get(page) }), { cause: error });
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
server = new WebServer(0, false, true);
|
||||
await server.start();
|
||||
baseUrl = `http://localhost:${server.boundPort}`;
|
||||
browser = await chromium.launch({ headless: true });
|
||||
}, 60_000);
|
||||
|
||||
afterAll(async () => {
|
||||
await browser?.close();
|
||||
await server?.stop();
|
||||
}, 30_000);
|
||||
|
||||
async function openTerminal(
|
||||
touch: boolean,
|
||||
viewport = touch ? { width: 390, height: 640 } : { width: 1280, height: 800 }
|
||||
): Promise<{ context: BrowserContext; page: Page }> {
|
||||
const context = await browser.newContext({
|
||||
hasTouch: touch,
|
||||
isMobile: touch,
|
||||
viewport,
|
||||
});
|
||||
const page = await context.newPage();
|
||||
const events: string[] = [];
|
||||
pageEvents.set(page, events);
|
||||
page.on('console', (message) => {
|
||||
events.push(`console.${message.type()}: ${message.text()}`);
|
||||
if (events.length > 100) events.shift();
|
||||
});
|
||||
page.on('pageerror', (error) => events.push(`pageerror: ${error.stack || error.message}`));
|
||||
try {
|
||||
await page.goto(baseUrl, { waitUntil: 'domcontentloaded' });
|
||||
await page.waitForFunction(() => document.body.classList.contains('app-loaded'));
|
||||
await page.waitForFunction(() => {
|
||||
const app = (window as RepairWindow).app;
|
||||
return app?.terminal && app._initGeneration > 0 && !app._isLoadingBuffer && app.terminalLoadStates.size === 0;
|
||||
});
|
||||
await page.evaluate(async (session) => {
|
||||
const app = (window as RepairWindow).app;
|
||||
// A client-only OMP session isolates the rendering path from real CLI/PTYS.
|
||||
// Opening it changes layout, so finish the real resize path BEFORE seeding.
|
||||
app.sessions.set(session, { id: session, mode: 'omp', status: 'idle', name: 'History repair' });
|
||||
app.activeSessionId = session;
|
||||
app.hideWelcome();
|
||||
await app._terminalFontReady;
|
||||
await document.fonts.ready;
|
||||
// Empty xterm can still carry fallback render metrics. Paint a glyph
|
||||
// before fitting, then clear it before the fixture's numbered output.
|
||||
const rendered = Promise.withResolvers<void>();
|
||||
const listener = app.terminal.onRender(() => {
|
||||
listener.dispose();
|
||||
rendered.resolve();
|
||||
});
|
||||
app.terminal.write('W');
|
||||
await rendered.promise;
|
||||
const { promise, resolve } = Promise.withResolvers<void>();
|
||||
app.terminal.write('\x1bc', resolve);
|
||||
await promise;
|
||||
window.dispatchEvent(new Event('resize'));
|
||||
}, SESSION);
|
||||
await page.waitForFunction(() => {
|
||||
const w = window as RepairWindow;
|
||||
const app = w.app;
|
||||
const { cols, rows } = app.terminal;
|
||||
const proposed = app.fitAddon.proposeDimensions();
|
||||
const cellHeight = app.terminal._core?._renderService?.dimensions?.css?.cell?.height || 0;
|
||||
if (
|
||||
cellHeight <= 0 ||
|
||||
proposed?.cols !== cols ||
|
||||
proposed?.rows !== rows ||
|
||||
app._resizeTimeout ||
|
||||
app._isLoadingBuffer ||
|
||||
app.terminalLoadStates.size ||
|
||||
app.pendingWrites.length ||
|
||||
app._terminalWriteInFlight ||
|
||||
app._lastResizeDims?.cols !== cols ||
|
||||
app._lastResizeDims?.rows !== rows
|
||||
) {
|
||||
w.repairReadiness = undefined;
|
||||
return false;
|
||||
}
|
||||
// Synchronous rAF polling: require the initial match plus two more frames.
|
||||
// An async predicate returns a truthy Promise, which Playwright won't retry.
|
||||
const previous = w.repairReadiness;
|
||||
const frames = previous?.cols === cols && previous.rows === rows ? previous.frames + 1 : 1;
|
||||
w.repairReadiness = { cols, rows, frames };
|
||||
return frames >= 3;
|
||||
});
|
||||
await page.evaluate(
|
||||
async ({ session, marker }) => {
|
||||
const w = window as RepairWindow;
|
||||
const app = w.app;
|
||||
// Startup resets and resize clears have already parsed at fitted geometry.
|
||||
w.repairTest = { pulls: 0, anchor: null, inject: false };
|
||||
const captureAnchor = app._captureViewportAnchor.bind(app);
|
||||
app._captureViewportAnchor = () => {
|
||||
const anchor = captureAnchor();
|
||||
w.repairTest.anchor = anchor;
|
||||
return anchor;
|
||||
};
|
||||
const realFetch = window.fetch.bind(window);
|
||||
window.fetch = ((input: RequestInfo | URL, init?: RequestInit) => {
|
||||
const url = String(typeof input === 'string' ? input : ((input as Request).url ?? input));
|
||||
if (!url.includes(`/api/sessions/${session}/terminal`)) return realFetch(input, init);
|
||||
if (!url.includes('full=1')) throw new Error(`Unexpected history request: ${url}`);
|
||||
w.repairTest.pulls++;
|
||||
return Promise.resolve({
|
||||
ok: true,
|
||||
status: 200,
|
||||
headers: new Headers(),
|
||||
json: async () => {
|
||||
// This is after headers and before replay, inside the real load window.
|
||||
if (w.repairTest.inject) app._onSessionTerminal({ id: session, data: `\r\n${marker}\r\n` });
|
||||
const terminalBuffer =
|
||||
Array.from({ length: 144 }, (_, i) => `NUMBER-${String(i).padStart(3, '0')}`).join('\r\n') + '\r\n';
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
terminalBuffer,
|
||||
source: 'mux-full-history',
|
||||
paneHistoryLines: 121,
|
||||
truncated: false,
|
||||
fullSize: terminalBuffer.length,
|
||||
retainedBytes: terminalBuffer.length,
|
||||
},
|
||||
};
|
||||
},
|
||||
}) as unknown as Promise<Response>;
|
||||
}) as typeof window.fetch;
|
||||
// All output still enters through the production terminal event path.
|
||||
app._onSessionTerminal({
|
||||
id: session,
|
||||
data: Array.from({ length: 60 }, (_, i) => `NUMBER-${String(i).padStart(3, '0')}\r\n`).join(''),
|
||||
});
|
||||
await new Promise<void>((resolve) => app.terminal.write('', resolve));
|
||||
},
|
||||
{ session: SESSION, marker: MARKER }
|
||||
);
|
||||
await page.waitForFunction(() => {
|
||||
const app = (window as RepairWindow).app;
|
||||
const buffer = app.terminal.buffer.active;
|
||||
return (
|
||||
buffer.length === 61 &&
|
||||
buffer.baseY === 61 - app.terminal.rows &&
|
||||
!app.pendingWrites.length &&
|
||||
!app._terminalWriteInFlight &&
|
||||
Array.from({ length: 60 }, (_, i) => buffer.getLine(i)?.translateToString(true)).every(
|
||||
(row, i) => row === `NUMBER-${String(i).padStart(3, '0')}`
|
||||
)
|
||||
);
|
||||
});
|
||||
// The initial 60 lines stand in for the last successful full-history replay.
|
||||
await page.evaluate((session) => {
|
||||
const app = (window as RepairWindow).app;
|
||||
app.terminal.scrollToBottom();
|
||||
app._syncStickyScrollBaseline();
|
||||
app._liveOutputSinceFullPull.delete(session);
|
||||
}, SESSION);
|
||||
} catch (error) {
|
||||
const state = await setupState(page).catch(String);
|
||||
await context.close();
|
||||
throw new Error(`Terminal setup failed: ${JSON.stringify({ state, events })}`, { cause: error });
|
||||
}
|
||||
return { context, page };
|
||||
}
|
||||
|
||||
/** Finger down scrolls history up; cancel at the endpoint to avoid momentum. */
|
||||
async function scrollHistoryByTouch(page: Page, distance: number): Promise<void> {
|
||||
const box = await page.locator('#terminalContainer').boundingBox();
|
||||
if (!box) throw new Error('Terminal container is not visible');
|
||||
const x = box.x + box.width / 2;
|
||||
const y = box.y + Math.min(80, box.height / 4);
|
||||
const cdp = await page.context().newCDPSession(page);
|
||||
const before = await page.evaluate(() => (window as RepairWindow).app.terminal.buffer.active.viewportY);
|
||||
try {
|
||||
await cdp.send('Input.dispatchTouchEvent', { type: 'touchStart', touchPoints: [{ x, y }] });
|
||||
await cdp.send('Input.dispatchTouchEvent', { type: 'touchMove', touchPoints: [{ x, y: y + distance }] });
|
||||
await page.waitForFunction((previous) => {
|
||||
const app = (window as RepairWindow).app;
|
||||
return app.terminal.buffer.active.viewportY !== previous || app._fullHistoryRepullInFlight;
|
||||
}, before);
|
||||
// A trusted cancellation ends the drag without xterm/app momentum changing
|
||||
// the reading position after the gesture or starting another top pull.
|
||||
await cdp.send('Input.dispatchTouchEvent', { type: 'touchCancel', touchPoints: [] });
|
||||
} finally {
|
||||
await cdp.detach();
|
||||
}
|
||||
}
|
||||
|
||||
async function burst(page: Page): Promise<void> {
|
||||
await page.evaluate((session) => {
|
||||
const app = (window as RepairWindow).app;
|
||||
// tmux scrolls a whole screen and repaints the last 24 rows. The numbered
|
||||
// rows 60..119 exist only in tmux and are deliberately absent from this stream.
|
||||
const repaint = Array.from({ length: 24 }, (_, row) => `\x1b[${row + 1};1H\x1b[2KNUMBER-${120 + row}`).join('');
|
||||
app._onSessionTerminal({ id: session, data: `\x1b[24S${repaint}` });
|
||||
}, SESSION);
|
||||
await page.waitForFunction((session) => (window as RepairWindow).app._liveOutputSinceFullPull.has(session), SESSION);
|
||||
}
|
||||
|
||||
async function bufferState(page: Page) {
|
||||
return page.evaluate((marker) => {
|
||||
const w = window as RepairWindow;
|
||||
const buffer = w.app.terminal.buffer.active;
|
||||
const rows = Array.from(
|
||||
{ length: buffer.length },
|
||||
(_, i) => buffer.getLine(i)?.translateToString(true).trim() || ''
|
||||
);
|
||||
const anchor = w.repairTest.anchor;
|
||||
return {
|
||||
numbers: rows.filter((row) => /^NUMBER-\d+$/.test(row)),
|
||||
markerHits: rows.filter((row) => row.includes(marker)).length,
|
||||
anchorOffset: anchor ? rows.indexOf(anchor.signature[0]) - buffer.viewportY : null,
|
||||
expectedOffset: anchor?.offset,
|
||||
pulls: w.repairTest.pulls,
|
||||
viewportY: buffer.viewportY,
|
||||
baseY: buffer.baseY,
|
||||
session: w.app.activeSessionId,
|
||||
length: buffer.length,
|
||||
pendingWrites: w.app.pendingWrites.length,
|
||||
terminalWriteInFlight: w.app._terminalWriteInFlight,
|
||||
bufferLoadOwner: w.app._bufferLoadOwner,
|
||||
loadBufferQueue: w.app._loadBufferQueue,
|
||||
selectGeneration: w.app._selectGeneration,
|
||||
initGeneration: w.app._initGeneration,
|
||||
sessions: [...w.app.sessions.keys()],
|
||||
marked: w.app._liveOutputSinceFullPull.has(w.app.activeSessionId),
|
||||
loading: w.app._isLoadingBuffer,
|
||||
inFlight: w.app._fullHistoryRepullInFlight,
|
||||
};
|
||||
}, MARKER);
|
||||
}
|
||||
|
||||
async function waitForRepair(page: Page): Promise<void> {
|
||||
await page.waitForFunction(() => {
|
||||
const w = window as RepairWindow;
|
||||
return (
|
||||
w.repairTest.pulls === 1 &&
|
||||
!w.app._fullHistoryRepullInFlight &&
|
||||
!w.app._isLoadingBuffer &&
|
||||
!w.app.pendingWrites.length &&
|
||||
!w.app._terminalWriteInFlight
|
||||
);
|
||||
});
|
||||
// xterm's parse marker is the completion signal for the production flush.
|
||||
await page.evaluate(async () => {
|
||||
const app = (window as RepairWindow).app;
|
||||
await new Promise<void>((resolve) => app.terminal.write('', resolve));
|
||||
});
|
||||
}
|
||||
|
||||
const allNumbers = Array.from({ length: 144 }, (_, i) => `NUMBER-${String(i).padStart(3, '0')}`);
|
||||
|
||||
describe('history gap repair on phones', () => {
|
||||
it('repairs from mid-history after a real upward scroll and holds the content anchor', async () => {
|
||||
const { context, page } = await openTerminal(true);
|
||||
try {
|
||||
await scrollHistoryByTouch(page, 100);
|
||||
const position = await page.evaluate(() => {
|
||||
const b = (window as RepairWindow).app.terminal.buffer.active;
|
||||
return { viewportY: b.viewportY, baseY: b.baseY };
|
||||
});
|
||||
expect(position.viewportY).toBeGreaterThan(0);
|
||||
expect(position.baseY - position.viewportY).toBeGreaterThan(5);
|
||||
await burst(page);
|
||||
expect((await bufferState(page)).numbers).not.toContain('NUMBER-090');
|
||||
await scrollHistoryByTouch(page, 40);
|
||||
await waitForRepair(page);
|
||||
const state = await bufferState(page);
|
||||
expect(state.numbers).toEqual(allNumbers);
|
||||
expect(state.anchorOffset).toBe(state.expectedOffset);
|
||||
expect(state.pulls).toBe(1);
|
||||
} catch (error) {
|
||||
throw await failureDetails(page, error);
|
||||
} finally {
|
||||
await context.close();
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
it('keeps output arriving during the capture download exactly once', async () => {
|
||||
const { context, page } = await openTerminal(true);
|
||||
try {
|
||||
await scrollHistoryByTouch(page, 100);
|
||||
await burst(page);
|
||||
await page.evaluate(() => {
|
||||
(window as RepairWindow).repairTest.inject = true;
|
||||
});
|
||||
await scrollHistoryByTouch(page, 40);
|
||||
await waitForRepair(page);
|
||||
const state = await bufferState(page);
|
||||
const detail = JSON.stringify({ state, events: pageEvents.get(page) });
|
||||
expect(state.markerHits, detail).toBe(1);
|
||||
expect(state.numbers, detail).toEqual(allNumbers);
|
||||
} catch (error) {
|
||||
throw await failureDetails(page, error);
|
||||
} finally {
|
||||
await context.close();
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
it('offers a touch reload while reading and tapping it recovers the missing rows', async () => {
|
||||
const { context, page } = await openTerminal(true);
|
||||
try {
|
||||
await scrollHistoryByTouch(page, 100);
|
||||
await burst(page);
|
||||
const button = page.getByRole('button', { name: 'Reload history' });
|
||||
await button.waitFor({ state: 'visible' });
|
||||
const box = await button.boundingBox();
|
||||
expect(box!.height).toBeGreaterThanOrEqual(44);
|
||||
expect(box!.width).toBeGreaterThanOrEqual(44);
|
||||
await button.tap();
|
||||
await waitForRepair(page);
|
||||
const state = await bufferState(page);
|
||||
expect(state.numbers).toEqual(allNumbers);
|
||||
expect(state.anchorOffset).toBe(state.expectedOffset);
|
||||
expect(await button.isVisible()).toBe(false);
|
||||
} catch (error) {
|
||||
throw await failureDetails(page, error);
|
||||
} finally {
|
||||
await context.close();
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
it('floats a 44px reload control on wide touch viewports without resizing the terminal', async () => {
|
||||
const { context, page } = await openTerminal(true, { width: 1280, height: 800 });
|
||||
try {
|
||||
await page.evaluate(() => {
|
||||
(window as RepairWindow).app.terminal.scrollToLine(10);
|
||||
});
|
||||
const dimensions = () =>
|
||||
page.evaluate(() => {
|
||||
const terminal = (window as RepairWindow).app.terminal;
|
||||
const box = document.getElementById('terminalContainer')!.getBoundingClientRect();
|
||||
return { width: box.width, height: box.height, cols: terminal.cols, rows: terminal.rows };
|
||||
});
|
||||
const before = await dimensions();
|
||||
expect(await page.locator('#historyReloadBtn').isVisible()).toBe(false);
|
||||
await burst(page);
|
||||
const button = page.getByRole('button', { name: 'Reload history' });
|
||||
await button.waitFor({ state: 'visible' });
|
||||
expect(await button.evaluate((element) => getComputedStyle(element).position)).toBe('absolute');
|
||||
const box = await button.boundingBox();
|
||||
expect(box!.height).toBeGreaterThanOrEqual(44);
|
||||
expect(box!.width).toBeGreaterThanOrEqual(44);
|
||||
expect(await dimensions()).toEqual(before);
|
||||
} catch (error) {
|
||||
throw await failureDetails(page, error);
|
||||
} finally {
|
||||
await context.close();
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
it('never shows the reload control in a non-touch context', async () => {
|
||||
const { context, page } = await openTerminal(false);
|
||||
try {
|
||||
await page.evaluate(() => {
|
||||
(window as RepairWindow).app.terminal.scrollToLine(10);
|
||||
});
|
||||
await burst(page);
|
||||
await page.evaluate(() => {
|
||||
(window as RepairWindow).app._syncHistoryReloadButton();
|
||||
});
|
||||
expect(await page.locator('#historyReloadBtn').isVisible()).toBe(false);
|
||||
expect((await bufferState(page)).pulls).toBe(0);
|
||||
} catch (error) {
|
||||
throw await failureDetails(page, error);
|
||||
} finally {
|
||||
await context.close();
|
||||
}
|
||||
}, 60_000);
|
||||
});
|
||||
@@ -121,6 +121,8 @@ function makeApp() {
|
||||
let resolvePull: (() => void) | null = null;
|
||||
const app = {
|
||||
activeSessionId: 's1' as string | null,
|
||||
sessions: new Map([['s1', { mode: 'omp' }]]),
|
||||
_liveOutputSinceFullPull: new Set<string>(),
|
||||
terminal: { buffer: { active: buffer } },
|
||||
// Each gesture's pull is held open until the test settles it.
|
||||
_maybeRefetchFullHistory: vi.fn(
|
||||
@@ -184,6 +186,29 @@ describe('partial-history notice: lazy reveal', () => {
|
||||
expect(loadButton(bar)?.textContent).toBe('Load full history');
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ viewportY: 0, revealed: true },
|
||||
{ viewportY: 200, revealed: false },
|
||||
])(
|
||||
'retains the initiating top state through a marked repair from row $viewportY',
|
||||
async ({ viewportY, revealed }) => {
|
||||
const { app, bar, buffer } = makeApp();
|
||||
app._setHistoryTruncation('s1', TAIL);
|
||||
app._liveOutputSinceFullPull.add('s1');
|
||||
app._maybeRefetchFullHistory.mockImplementation(async () => {
|
||||
app._setHistoryTruncation('s1', { ...TAIL, source: 'mux-full-history' });
|
||||
buffer.viewportY = 100; // The content anchor restored the old top below recovered rows.
|
||||
});
|
||||
buffer.viewportY = viewportY;
|
||||
app._maybeLoadMoreHistoryOnScroll(-5);
|
||||
for (let i = 0; i < 5; i++) await Promise.resolve();
|
||||
expect(app._maybeRefetchFullHistory).toHaveBeenCalledOnce();
|
||||
expect(app._maybeRefetchFullHistory).toHaveBeenCalledWith({ anchor: 'content' });
|
||||
expect(bar.hidden).toBe(!revealed);
|
||||
if (revealed) expect(loadButton(bar)?.textContent).toBe('Load full history');
|
||||
}
|
||||
);
|
||||
|
||||
it('a later frame of the same gesture does not flash the pre-pull state while the pull runs', async () => {
|
||||
const { app, bar, buffer } = makeApp();
|
||||
app._setHistoryTruncation('s1', TAIL);
|
||||
|
||||
@@ -49,7 +49,7 @@ function methodSource(source: string, method: string): string {
|
||||
}
|
||||
|
||||
/** Real terminal-ui.js mixin, for `_estimateReplayRows` / `_replayWouldShrinkBuffer`. */
|
||||
function loadTerminalMixin(): Record<string, unknown> {
|
||||
function loadTerminalMixin(globals: Record<string, unknown> = {}): Record<string, unknown> {
|
||||
const source = readFileSync(resolve(PUBLIC, 'terminal-ui.js'), 'utf8');
|
||||
const FakeCodemanApp = function () {} as unknown as { prototype: Record<string, unknown> };
|
||||
const context = vm.createContext({
|
||||
@@ -63,6 +63,7 @@ function loadTerminalMixin(): Record<string, unknown> {
|
||||
CodemanApp: FakeCodemanApp,
|
||||
window: { addEventListener: vi.fn(), removeEventListener: vi.fn() },
|
||||
document: { addEventListener: vi.fn() },
|
||||
...globals,
|
||||
});
|
||||
vm.runInContext(source, context);
|
||||
return FakeCodemanApp.prototype;
|
||||
@@ -75,6 +76,20 @@ function loadRefetch(): (this: unknown, opts?: { force?: boolean; anchor?: strin
|
||||
return vm.runInContext(`({ ${body} })._maybeRefetchFullHistory`, context);
|
||||
}
|
||||
|
||||
function loadAppMethod(name: string, globals: Record<string, unknown> = {}): Function {
|
||||
const source = readFileSync(resolve(PUBLIC, 'app.js'), 'utf8');
|
||||
return vm.runInContext(
|
||||
`({ ${methodSource(source, name)} }).${name}`,
|
||||
vm.createContext({
|
||||
performance,
|
||||
TERMINAL_TAIL_SIZE,
|
||||
TERMINAL_CHUNK_SIZE: 32 * 1024,
|
||||
_crashDiag: { log: vi.fn() },
|
||||
...globals,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
/** The REAL `_setHistoryTruncation`, so the banner state a pull leaves behind is what production would hold. */
|
||||
function loadSetHistoryTruncation(): (this: unknown, sessionId: string, payload?: Record<string, unknown>) => void {
|
||||
const app = readFileSync(resolve(PUBLIC, 'app.js'), 'utf8');
|
||||
@@ -125,6 +140,7 @@ function makeApp(
|
||||
_selectGeneration: 7,
|
||||
_fullHistoryRepullInFlight: false,
|
||||
_isLoadingBuffer: false,
|
||||
_loadBufferQueue: null as { at: number; data: string }[] | null,
|
||||
_fullHistoryRepullAt: new Map<string, number>(),
|
||||
_fullHistoryRepullUseless: new Set<string>(),
|
||||
_paneHistoryLines: new Map<string, number>(),
|
||||
@@ -134,12 +150,25 @@ function makeApp(
|
||||
rows: 30,
|
||||
// xterm's scrollback option; 0 leaves the browser-cap check out of a test.
|
||||
options: { scrollback },
|
||||
buffer: { active: { length: bufferRows, baseY: 0, viewportY: 0 } },
|
||||
scrollToLine: vi.fn(),
|
||||
buffer: { active: { length: bufferRows, baseY: 0, viewportY: 0, getLine: (_row: number) => undefined } },
|
||||
scrollToTop: vi.fn(),
|
||||
},
|
||||
_estimateReplayRows: mixin._estimateReplayRows,
|
||||
_replayWouldShrinkBuffer: mixin._replayWouldShrinkBuffer,
|
||||
_beginBufferLoad: mixin._beginBufferLoad,
|
||||
_finishBufferLoad: vi.fn(function (this: unknown, owner: string, opts?: object) {
|
||||
return (mixin._finishBufferLoad as Function).call(this, owner, opts);
|
||||
}),
|
||||
batchTerminalWrite: vi.fn(function (this: unknown, data: string) {
|
||||
return (mixin.batchTerminalWrite as Function).call(this, data);
|
||||
}),
|
||||
_captureViewportAnchor: mixin._captureViewportAnchor,
|
||||
_restoreViewportAnchor: mixin._restoreViewportAnchor,
|
||||
pendingWrites: [] as string[],
|
||||
_scheduleTerminalWriteFlush: vi.fn(),
|
||||
isTerminalAtBottom: () => true,
|
||||
_scheduleDroppedOutputRecovery: vi.fn(),
|
||||
_fetchTerminalCapture: vi.fn(async (url: string) => {
|
||||
urls.push(url);
|
||||
return {
|
||||
@@ -159,8 +188,11 @@ function makeApp(
|
||||
setHistoryTruncation.call(app, sessionId, p);
|
||||
}),
|
||||
_resetTerminalForReplay: vi.fn(),
|
||||
_bufferLoadFinishOpts: vi.fn(() => ({})),
|
||||
chunkedTerminalWrite: vi.fn(async () => ({ parsedAt: performance.now(), bufferLength: 400, completed: true })),
|
||||
_bufferLoadFinishOpts: loadAppMethod('_bufferLoadFinishOpts'),
|
||||
chunkedTerminalWrite: vi.fn(async (_buffer?: string, _size?: number, owner?: string, opts?: object) => {
|
||||
(mixin._finishBufferLoad as Function).call(app, owner, opts);
|
||||
return { parsedAt: performance.now(), bufferLength: 400, completed: true };
|
||||
}),
|
||||
_syncStickyScrollBaseline: vi.fn(),
|
||||
};
|
||||
return { app, urls };
|
||||
@@ -262,8 +294,7 @@ describe('early full-history recovery above live output (#814)', () => {
|
||||
const app = Object.assign(base, {
|
||||
_liveOutputSinceFullPull: new Set<string>(),
|
||||
_liveOutputGen: new Map<string, number>(),
|
||||
_earlyReplayTravel: null as number[] | null,
|
||||
pendingWrites: [] as string[],
|
||||
_earlyReplayTravel: null as { sessionId: string; moves: number[] } | null,
|
||||
_wasAtBottomBeforeWrite: false,
|
||||
_scheduleTerminalWriteFlush: vi.fn(),
|
||||
_restoreTerminalViewport: vi.fn(),
|
||||
@@ -285,10 +316,11 @@ describe('early full-history recovery above live output (#814)', () => {
|
||||
app.terminal.scrollToLine.mockImplementation((row: number) => {
|
||||
active.viewportY = row;
|
||||
});
|
||||
app.chunkedTerminalWrite.mockImplementation(async () => {
|
||||
app.chunkedTerminalWrite.mockImplementation(async (_buffer, _size, owner, opts) => {
|
||||
active.baseY = 370;
|
||||
active.viewportY = 370;
|
||||
active.length = 400;
|
||||
(mixin._finishBufferLoad as Function).call(app, owner, opts);
|
||||
return { parsedAt: performance.now(), bufferLength: 400, completed: true };
|
||||
});
|
||||
const liveOutput = () => {
|
||||
@@ -305,14 +337,12 @@ describe('early full-history recovery above live output (#814)', () => {
|
||||
const replay = app.chunkedTerminalWrite.getMockImplementation()!;
|
||||
const { promise: gate, resolve: release } = Promise.withResolvers<void>();
|
||||
const { promise: ready, resolve: started } = Promise.withResolvers<void>();
|
||||
app.chunkedTerminalWrite.mockImplementationOnce(async () => {
|
||||
app._isLoadingBuffer = true;
|
||||
app.chunkedTerminalWrite.mockImplementationOnce(async (...args) => {
|
||||
active.baseY = 0;
|
||||
active.viewportY = 0;
|
||||
started();
|
||||
await gate;
|
||||
const result = await replay();
|
||||
app._isLoadingBuffer = false;
|
||||
const result = await replay(...args);
|
||||
beforeComplete();
|
||||
return result;
|
||||
});
|
||||
@@ -326,6 +356,12 @@ describe('early full-history recovery above live output (#814)', () => {
|
||||
liveOutput();
|
||||
await scroll(-5);
|
||||
expect(urls).toEqual(['/api/sessions/s1/terminal?full=1']);
|
||||
expect(app.chunkedTerminalWrite).toHaveBeenCalledWith(
|
||||
expect.any(String),
|
||||
32 * 1024,
|
||||
expect.stringMatching(/^buffer-/),
|
||||
expect.objectContaining({ flushQueued: true })
|
||||
);
|
||||
expect(active.viewportY).toBe(365);
|
||||
expect(active.baseY - active.viewportY).toBe(5);
|
||||
expect(app._liveOutputSinceFullPull.has('s1')).toBe(false);
|
||||
@@ -359,20 +395,31 @@ describe('early full-history recovery above live output (#814)', () => {
|
||||
expect(app._earlyReplayTravel).toBeNull();
|
||||
});
|
||||
|
||||
it('keeps a session dirty when live output lands while the capture is still downloading', async () => {
|
||||
it('queues download-time output and replays it through batchTerminalWrite after the capture', async () => {
|
||||
const { app, urls, liveOutput, scroll } = makeScrollApp();
|
||||
liveOutput();
|
||||
const fetchCapture = app._fetchTerminalCapture.getMockImplementation()!;
|
||||
const { promise, resolve: release } = Promise.withResolvers<void>();
|
||||
app._fetchTerminalCapture.mockImplementationOnce(async (url: string) => {
|
||||
expect(app._isLoadingBuffer).toBe(true);
|
||||
const capture = await fetchCapture(url);
|
||||
// tmux has captured; this output is newer than the capture the replay writes.
|
||||
liveOutput();
|
||||
await promise;
|
||||
return capture;
|
||||
});
|
||||
await scroll(-5);
|
||||
const pull = scroll(-5);
|
||||
loadAppMethod('_onSessionTerminal').call(app, { id: 's1', data: 'download-time output' });
|
||||
expect(app._loadBufferQueue).toEqual([expect.objectContaining({ data: 'download-time output' })]);
|
||||
release();
|
||||
await pull;
|
||||
expect(urls).toHaveLength(1);
|
||||
expect(app.batchTerminalWrite).toHaveBeenCalledWith('download-time output');
|
||||
expect(app.pendingWrites).toContain('download-time output');
|
||||
expect(app._isLoadingBuffer).toBe(false);
|
||||
// Flushing the replayed queue marks the session again.
|
||||
(mixin.flushPendingWrites as Function).call(app);
|
||||
expect(app._liveOutputSinceFullPull.has('s1')).toBe(true);
|
||||
});
|
||||
|
||||
it('keeps live output flushed before the final restore dirty for the next early pull', async () => {
|
||||
const { app, active, urls, liveOutput, scroll, pauseReplay } = makeScrollApp();
|
||||
liveOutput();
|
||||
@@ -417,14 +464,17 @@ describe('early full-history recovery above live output (#814)', () => {
|
||||
expect(app._liveOutputSinceFullPull.size).toBe(0);
|
||||
});
|
||||
|
||||
it('does not pull early for downward travel or while already reading older rows', async () => {
|
||||
const { active, urls, liveOutput, scroll } = makeScrollApp();
|
||||
it('repairs while already reading mid-history, but never on downward travel', async () => {
|
||||
const { app, active, urls, liveOutput, scroll } = makeScrollApp();
|
||||
liveOutput();
|
||||
active.viewportY = 50;
|
||||
await scroll(-5);
|
||||
active.viewportY = 95;
|
||||
expect(urls).toHaveLength(1);
|
||||
expect(app._maybeRefetchFullHistory).toHaveBeenCalledWith({ anchor: 'content' });
|
||||
app._fullHistoryRepullAt.clear();
|
||||
liveOutput();
|
||||
await scroll(3);
|
||||
expect(urls).toEqual([]);
|
||||
expect(urls).toHaveLength(1);
|
||||
});
|
||||
|
||||
it.each(['_isLoadingBuffer', '_fullHistoryRepullInFlight'] as const)('respects the %s guard', async (guard) => {
|
||||
@@ -450,6 +500,144 @@ describe('early full-history recovery above live output (#814)', () => {
|
||||
expect(app._liveOutputSinceFullPull.has('s1')).toBe(true);
|
||||
expect(app._fullHistoryRepullUseless.has('s1')).toBe(true);
|
||||
});
|
||||
|
||||
it.each(['empty', 'tab-switch', 'downgrade', 'bounded-shell', 'rejection'])(
|
||||
'flushes download-time output on the %s non-replay path',
|
||||
async (exit) => {
|
||||
const { app } = makeApp(exit === 'bounded-shell' ? 'shell' : 'omp', {
|
||||
bufferRows: 200,
|
||||
capture: lines(400),
|
||||
});
|
||||
const { promise, resolve: release } = Promise.withResolvers<void>();
|
||||
app._fetchTerminalCapture.mockImplementationOnce(async () => {
|
||||
await promise;
|
||||
if (exit === 'rejection') throw new Error('offline');
|
||||
if (exit === 'tab-switch') app._selectGeneration++;
|
||||
return {
|
||||
headersAt: performance.now(),
|
||||
headers: { get: () => '' },
|
||||
json: { data: { terminalBuffer: exit === 'empty' ? '' : lines(10), source: 'mux-full-history' } },
|
||||
};
|
||||
});
|
||||
const pull = refetch.call(app);
|
||||
expect(app._isLoadingBuffer).toBe(true);
|
||||
loadAppMethod('_onSessionTerminal').call(app, { id: 's1', data: 'queued while fetching' });
|
||||
release();
|
||||
await pull;
|
||||
expect(app.chunkedTerminalWrite).not.toHaveBeenCalled();
|
||||
expect(app._finishBufferLoad).toHaveBeenCalledOnce();
|
||||
expect(app._finishBufferLoad).toHaveBeenCalledWith(expect.any(String), { flushQueued: true, since: 0 });
|
||||
expect(app.pendingWrites).toContain('queued while fetching');
|
||||
expect(app._isLoadingBuffer).toBe(false);
|
||||
}
|
||||
);
|
||||
|
||||
it('counts download-time output toward the 128 KiB dropped-output recovery cap', async () => {
|
||||
const { app } = makeApp('omp', { bufferRows: 30, capture: lines(400) });
|
||||
const { promise, resolve: release } = Promise.withResolvers<void>();
|
||||
app._fetchTerminalCapture.mockImplementationOnce(async () => {
|
||||
await promise;
|
||||
return {
|
||||
headersAt: performance.now(),
|
||||
headers: { get: () => '' },
|
||||
json: { data: { terminalBuffer: '', source: 'history' } },
|
||||
};
|
||||
});
|
||||
const pull = refetch.call(app);
|
||||
const onTerminal = loadAppMethod('_onSessionTerminal');
|
||||
onTerminal.call(app, { id: 's1', data: 'x'.repeat(70_000) });
|
||||
onTerminal.call(app, { id: 's1', data: 'y'.repeat(70_000) });
|
||||
expect(app._scheduleDroppedOutputRecovery).toHaveBeenCalledWith('s1', 0, 70_000);
|
||||
expect(app._loadBufferQueue).toHaveLength(1);
|
||||
release();
|
||||
await pull;
|
||||
});
|
||||
|
||||
it.each([false, true])(
|
||||
'defers real dropped-output recovery through a slow pull (timer already armed: %s)',
|
||||
async (armed) => {
|
||||
vi.useFakeTimers();
|
||||
const { promise, resolve: release } = Promise.withResolvers<void>();
|
||||
try {
|
||||
const { app } = makeApp('omp', { bufferRows: 30, capture: lines(400) });
|
||||
const retry = vi.fn(({ repainted, stillActive, attempt }) => !repainted && stillActive && attempt < 4);
|
||||
const schedule = loadAppMethod('_scheduleDroppedOutputRecovery', {
|
||||
setTimeout,
|
||||
window: { CodemanDroppedOutput: { DROP_RECOVERY_DELAY_MS: 2000, shouldRetryDroppedOutputRecovery: retry } },
|
||||
});
|
||||
const refresh = vi.fn(async () => true);
|
||||
Object.assign(app, {
|
||||
_scheduleDroppedOutputRecovery: (...args: unknown[]) => schedule.apply(app, args),
|
||||
_onSessionNeedsRefresh: refresh,
|
||||
});
|
||||
if (armed) schedule.call(app, 's1');
|
||||
const fetchCapture = app._fetchTerminalCapture.getMockImplementation()!;
|
||||
app._fetchTerminalCapture.mockImplementationOnce(async (url) => {
|
||||
await promise;
|
||||
return fetchCapture(url);
|
||||
});
|
||||
const pull = refetch.call(app);
|
||||
const onTerminal = loadAppMethod('_onSessionTerminal');
|
||||
onTerminal.call(app, { id: 's1', data: 'x'.repeat(70_000) });
|
||||
onTerminal.call(app, { id: 's1', data: 'y'.repeat(70_000) });
|
||||
await vi.advanceTimersByTimeAsync(20_000); // Longer than all five normal retry intervals.
|
||||
expect(app._isLoadingBuffer).toBe(true);
|
||||
expect(refresh).not.toHaveBeenCalled();
|
||||
expect(retry).not.toHaveBeenCalled();
|
||||
release();
|
||||
await pull;
|
||||
expect(app._isLoadingBuffer).toBe(false);
|
||||
await vi.advanceTimersByTimeAsync(2000);
|
||||
expect(refresh).toHaveBeenCalledOnce();
|
||||
expect(refresh).toHaveBeenCalledWith({ id: 's1' });
|
||||
expect(retry).toHaveBeenCalledWith(expect.objectContaining({ attempt: 0, repainted: true }));
|
||||
} finally {
|
||||
release();
|
||||
vi.useRealTimers();
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
it('does not resume a deferred recovery for a tab that is no longer active', () => {
|
||||
const { app } = makeApp('omp', { bufferRows: 30, capture: lines(400) });
|
||||
const owner = (app._beginBufferLoad as Function).call(app);
|
||||
Object.assign(app, { _pendingDroppedOutputRecovery: 's1', activeSessionId: 's2' });
|
||||
app._finishBufferLoad(owner);
|
||||
expect(app._scheduleDroppedOutputRecovery).not.toHaveBeenCalled();
|
||||
expect(Reflect.get(app, '_pendingDroppedOutputRecovery')).toBeNull();
|
||||
});
|
||||
|
||||
it.each(['mux-full-history', 'history'])('clears the scroll-pull mark only for a mux capture: %s', async (source) => {
|
||||
const { app, liveOutput, scroll } = makeScrollApp();
|
||||
liveOutput();
|
||||
const fetchCapture = app._fetchTerminalCapture.getMockImplementation()!;
|
||||
app._fetchTerminalCapture.mockImplementationOnce(async (url) => {
|
||||
const capture = await fetchCapture(url);
|
||||
capture.json.data.source = source;
|
||||
return capture;
|
||||
});
|
||||
await scroll(-5);
|
||||
expect(app._liveOutputSinceFullPull.has('s1')).toBe(source !== 'mux-full-history');
|
||||
});
|
||||
|
||||
it('does not swallow another tab’s travel or clear the old mark when replay is cancelled', async () => {
|
||||
const { app, active, liveOutput, scroll, pauseReplay } = makeScrollApp();
|
||||
liveOutput();
|
||||
const paused = pauseReplay();
|
||||
const pull = scroll(-5);
|
||||
await paused.ready;
|
||||
app.activeSessionId = 's2';
|
||||
app._selectGeneration++;
|
||||
active.baseY = 100;
|
||||
active.viewportY = 100;
|
||||
(mixin._maybeLoadMoreHistoryOnScroll as Function).call(app, 3);
|
||||
expect(app._setHistoryNoticeRevealed).toHaveBeenCalledWith(null);
|
||||
expect(app._earlyReplayTravel?.moves).toEqual([]);
|
||||
paused.release();
|
||||
await pull;
|
||||
expect(app._liveOutputSinceFullPull.has('s1')).toBe(true);
|
||||
expect(app._earlyReplayTravel).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('a skipped bounded window never damages the Load full history banner', () => {
|
||||
@@ -635,3 +823,190 @@ describe('an unloaded buffer is not held to an older downgrade refusal', () => {
|
||||
expect(app._fullHistoryRepullInFlight).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('content anchors hold the reader through a history repair', () => {
|
||||
function fixture(rows: string[], viewportY = 5) {
|
||||
let content = rows;
|
||||
const active = {
|
||||
viewportY,
|
||||
baseY: rows.length - 3,
|
||||
length: rows.length,
|
||||
getLine: vi.fn((row: number) =>
|
||||
content[row] === undefined
|
||||
? undefined
|
||||
: {
|
||||
translateToString: () => content[row],
|
||||
}
|
||||
),
|
||||
};
|
||||
const app = { terminal: { buffer: { active }, scrollToLine: vi.fn() } };
|
||||
const capture = () => (mixin._captureViewportAnchor as Function).call(app);
|
||||
const restore = (anchor: unknown, next: string[]) => {
|
||||
content = next;
|
||||
active.baseY = next.length - 3;
|
||||
active.length = next.length;
|
||||
return (mixin._restoreViewportAnchor as Function).call(app, anchor);
|
||||
};
|
||||
return { app, active, capture, restore };
|
||||
}
|
||||
|
||||
it('keeps a three-row signature at its viewport offset when rows are inserted below the reader', () => {
|
||||
const rows = Array.from({ length: 30 }, (_, i) => `row ${i}`);
|
||||
rows[5] = '';
|
||||
const { app, capture, restore } = fixture(rows);
|
||||
const anchor = capture();
|
||||
const target = restore(anchor, [...rows.slice(0, 12), ...Array(20).fill('recovered'), ...rows.slice(12)]);
|
||||
expect(target).toBe(5);
|
||||
expect(app.terminal.scrollToLine).toHaveBeenCalledWith(5);
|
||||
expect(anchor.viewportY).toBe(5);
|
||||
expect(anchor.offset).toBe(1);
|
||||
});
|
||||
|
||||
it('chooses the nearest exact signature over a nearer first-row-only match', () => {
|
||||
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);
|
||||
});
|
||||
|
||||
it('falls back to the nearest first row, then distance from the bottom when nothing matches', () => {
|
||||
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);
|
||||
});
|
||||
|
||||
it('keeps bottom distance within the bottom tolerance even if matching text exists', () => {
|
||||
const rows = Array.from({ length: 30 }, (_, i) => `row ${i}`);
|
||||
const { capture, restore } = fixture(rows, 26);
|
||||
expect(restore(capture(), [...rows, ...Array(10).fill('new')])).toBe(36);
|
||||
});
|
||||
|
||||
it.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 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);
|
||||
active.getLine.mockClear();
|
||||
expect(restore(anchor, next)).toBe(kind === 'first-row-only' ? 25_100 : 25_000);
|
||||
expect(active.getLine.mock.calls.length).toBeLessThanOrEqual(4005);
|
||||
});
|
||||
});
|
||||
|
||||
describe('touch history reload control', () => {
|
||||
function fixture({
|
||||
touch = true,
|
||||
mode = 'omp',
|
||||
bottom = false,
|
||||
marked = true,
|
||||
inFlight = false,
|
||||
tiles = false,
|
||||
active = true,
|
||||
} = {}) {
|
||||
const button = { hidden: true, disabled: false, textContent: '', onclick: null as (() => void) | null };
|
||||
const ui = loadTerminalMixin({
|
||||
MobileDetection: { isTouchDevice: () => touch },
|
||||
document: { addEventListener: vi.fn(), getElementById: () => button },
|
||||
});
|
||||
const app = {
|
||||
activeSessionId: active ? 's1' : null,
|
||||
sessions: new Map([['s1', { mode }]]),
|
||||
isTerminalAtBottom: () => bottom,
|
||||
_liveOutputSinceFullPull: new Set(marked ? ['s1'] : []),
|
||||
_fullHistoryRepullInFlight: inFlight,
|
||||
_tilesOwnTerminal: () => tiles,
|
||||
_maybeRefetchFullHistory: vi.fn(async (_opts: object) => {}),
|
||||
_syncHistoryReloadButton: () => (ui._syncHistoryReloadButton as Function).call(app),
|
||||
};
|
||||
return { app, button };
|
||||
}
|
||||
|
||||
it.each([
|
||||
{ opts: {}, visible: true },
|
||||
{ opts: { touch: false }, visible: false },
|
||||
{ opts: { mode: 'shell' }, visible: false },
|
||||
{ opts: { bottom: true }, visible: false },
|
||||
{ opts: { marked: false }, visible: false },
|
||||
{ opts: { inFlight: true }, visible: false },
|
||||
{ opts: { tiles: true }, visible: false },
|
||||
{ opts: { active: false }, visible: false },
|
||||
])('visibility is $visible for $opts', ({ opts, visible }) => {
|
||||
const { app, button } = fixture(opts);
|
||||
app._syncHistoryReloadButton();
|
||||
expect(button.hidden).toBe(!visible);
|
||||
});
|
||||
|
||||
it('forces a content-anchored pull on tap and resets the loading state on settle', async () => {
|
||||
const { app, button } = fixture();
|
||||
const { promise, resolve: release } = Promise.withResolvers<void>();
|
||||
app._maybeRefetchFullHistory.mockReturnValueOnce(promise);
|
||||
app._syncHistoryReloadButton();
|
||||
const tapped = button.onclick!();
|
||||
expect(app._maybeRefetchFullHistory).toHaveBeenCalledWith({ force: true, anchor: 'content' });
|
||||
expect(button.disabled).toBe(true);
|
||||
expect(button.textContent).toBe('Loading…');
|
||||
release();
|
||||
await tapped;
|
||||
expect(button.disabled).toBe(false);
|
||||
expect(button.textContent).toBe('↻ Reload history');
|
||||
});
|
||||
});
|
||||
|
||||
describe('selectSession only clears live-output marks for actual full mux captures', () => {
|
||||
it.each(['mux-full-history', 'history'])('checks the response source: %s', async (source) => {
|
||||
const errors = vi.fn();
|
||||
const select = loadAppMethod('selectSession', {
|
||||
console: { log: vi.fn(), error: errors },
|
||||
document: { querySelector: () => null },
|
||||
localStorage: { setItem: vi.fn(), getItem: () => null },
|
||||
requestIdleCallback: vi.fn(),
|
||||
});
|
||||
const { app } = makeApp('omp', { bufferRows: 30, capture: lines(60), payload: { source } });
|
||||
const methods = Object.fromEntries(
|
||||
[
|
||||
'_setTerminalLoadState',
|
||||
'_clearTerminalLoadState',
|
||||
'_cleanupPreviousSession',
|
||||
'_renderHistoryTruncationBanner',
|
||||
'_updateSseSubscription',
|
||||
'hideWelcome',
|
||||
'markIdleAlertSeen',
|
||||
'_updateActiveTabImmediate',
|
||||
'closeSessionSidebarOnHandheld',
|
||||
'renderSessionTabs',
|
||||
'_updateLocalEchoState',
|
||||
'syncTerminalGeometry',
|
||||
'_markTerminalBufferReconciled',
|
||||
'_connectWs',
|
||||
'scrollToLastNonEmptyLine',
|
||||
].map((name) => [name, vi.fn()])
|
||||
);
|
||||
Object.assign(app, methods, {
|
||||
activeSessionId: 's2',
|
||||
_fullHistoryLoaded: new Set(),
|
||||
_liveOutputSinceFullPull: new Set(['s1']),
|
||||
_liveOutputGen: new Map(),
|
||||
_shouldFocusTerminalForTabSwitch: () => false,
|
||||
_isStaleSelect: () => false,
|
||||
sendResize: async () => false,
|
||||
});
|
||||
Object.assign(app.terminal, { scrollToBottom: vi.fn() });
|
||||
await select.call(app, 's1');
|
||||
expect(errors).not.toHaveBeenCalled();
|
||||
expect(app.chunkedTerminalWrite).toHaveBeenCalledOnce();
|
||||
expect(Reflect.get(app, '_liveOutputSinceFullPull').has('s1')).toBe(source !== 'mux-full-history');
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user