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:
Hadrien Kerlero committed 2026-11-22 02:43:56 +01:00
1 parent fd31315582
commit b890ef3302
10 files changed
+1050 -84

No files matched your search

+44 -24
View File
@@ -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
+1
View File
@@ -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"
+20
View File
@@ -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
View File
@@ -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;
},