From a4926e49f12d33cdd8c4c2db1d44ac51636201ad Mon Sep 17 00:00:00 2001 From: Aamer Akhter Date: Mon, 5 Oct 2026 21:23:03 -0400 Subject: [PATCH] fix(terminal): keep the page-key fallback out of swipes, pinches, wheel notches and dialogs Review follow-up for the hollow-pane PageUp/PageDown fallback (_maybePageCliTranscript): - A mostly horizontal wheel swipe (both deltas present, |deltaX| > |deltaY|) is consumed without paging. The touch path already locks its axis. - A pinch (wheel events with ctrlKey, as Chrome reports one) is consumed without paging. - Only a trackpad-sized opening event (under 2 rows) pages at once. A wheel notch (100 px, 4 rows) accumulates toward half a screen as before, so five slow notches send one PageUp again instead of five. A debt from a pre-paid page still dies with its gesture; plain wheel travel carries across notches. - Nothing pages while the active tab's alert is 'action' (a pending permission_prompt or elicitation_dialog), so a page key never reaches an open dialog's selector. Docs: the invariants paragraph now says which Codex versions were seen drawing on the alt screen (0.157.1, 0.160) and that 0.147.0 still draws inline, without claiming a cutoff. --- docs/architecture-invariants.md | 2 +- src/web/public/terminal-ui.js | 35 ++++++++++-- test/terminal-scroll-routing.test.ts | 79 +++++++++++++++++++++++++--- 3 files changed, 103 insertions(+), 13 deletions(-) diff --git a/docs/architecture-invariants.md b/docs/architecture-invariants.md index 4095c418..219adcd1 100644 --- a/docs/architecture-invariants.md +++ b/docs/architecture-invariants.md @@ -225,7 +225,7 @@ Further detail: the `: ` form (`w3-myapp: fix the login redirect` **Wheel/touch forwarding is NOT gated on viewport-at-bottom** (#205, `terminal-ui.js:_shouldForwardWheelToApp`): for sessions verified to scroll their own transcript on SGR wheel reports (claude ≥ 2.1.187 while `cliMouseTracking` is true, i.e. fullscreen; version via the local/docker/remote `--version` probes), the plain wheel AND touch drags forward as coalesced SGR reports (`_forwardScrollToApp` → `_sendSyntheticSgrWheel`, 40ms batches, 5-tick cap, 512-byte queue bound). It used to gate on the viewport being at the bottom so both scrollbacks stayed reachable, but a repaint-mode CLI keeps NO terminal scrollback of its own — xterm's buffer holds only replayed repaint frames, so local scrolling drags the CLI's pinned prompt box up the screen over stale frames; and `scrollToLastNonEmptyLine()` routinely parked the viewport off-bottom, silently pinning the wheel to local. Forwarding now snaps the viewport home first (SGR coordinates address the LIVE screen — a report computed from a scrolled-up viewport would hit-test the wrong row). Local scrollback remains on Shift+wheel and the `terminalWheelLocalScrollback` opt-out (both also cover touch via the shared gate; touch has no Shift, so the setting is its only local pin). `_wheelScrollLines()` normalizes `deltaMode` (Firefox fires LINE deltas ≈3/notch — read as pixels that rounded to 0 and fell to the ±1 fallback, ~4× too slow; PAGE deltas scale by `terminal.rows`) while keeping the #154 Shift-axis trap (macOS trackpads put Shift+scroll magnitude on deltaX). Tests: `test/terminal-touch-tap.test.ts`. -**A false gate on a hollow pane must not mean a DEAD gesture** (#205 round 2, `_maybePageCliTranscript`): every way `_shouldForwardWheelToApp()` returns false leaves a repaint-mode pane scrolling a buffer that has nothing in it (`baseY === 0`) — the version probe came back empty, the CLI really is older than 2.1.187, the `cliMouseTracking` flag is unset (inline claude, or fullscreen right after a server restart), or the user turned on `terminalWheelLocalScrollback`. **opencode is the fifth case, and the gate is false there by design**: its TUI runs on the ALTERNATE SCREEN (1.18.31 measured: tmux `alternate_on=1`, `history_size=0`), so the buffer is hollow, and it IGNORES SGR wheel reports entirely (six `\x1b[<64;…M` reports against an idle pane left the capture byte-identical) while still paging its transcript on PageUp/PageDown (`messages_page_up/down`) — so paging is the only gesture that can reach it, and without it the wheel was silently dead in every opencode tab. The 1.12.0 retest reported exactly that shape for Claude: a wheel that did nothing at all while Fn+Up (PageUp) paged back through intact text, which is the proof that the CLI's own history and the PTY input path were both fine. So under the guard (`_localScrollbackIsHollow()`: the `transcriptPageKeys` capability, gate false, `baseY === 0`) wheel and touch travel is translated into coalesced `\x1b[5~` / `\x1b[6~` through the same 40ms queue as the SGR reports, at half a screen of travel per page key (the key jumps a whole screen; a 1:1 mapping was unusably slow with a discrete wheel). ⚠️ The first event of a gesture pages AT ONCE and the travel it skipped is owed back by the rest of the gesture (one page per half screen still); a >150 ms pause, a direction change or a tab switch starts a new gesture. Waiting for half a screen first meant an ordinary trackpad flick (well under 19 rows on a 38-row pane) sent nothing at all. ⚠️ Which modes page is the registry's `capabilities.transcriptPageKeys`, published as `window.__codemanTranscriptPageKeys`, never an id check in terminal-ui.js. Codex is on it although it is never forwarded the wheel: newer codex (measured 0.157.1 locally, 0.160 remote) draws on tmux's alternate screen, which the full strip hides from xterm, so its pane is hollow too, and PageUp pages its transcript while SGR wheel reports still do nothing. This is the page-key fallback, NOT wheel forwarding, and an older inline codex keeps real local history (`baseY > 0`) so the guard never fires for it. `shell`/`pi` own real terminal scrollback and are never paged, and gemini/antigravity/grok/deepseek/omp page-key behaviour is unverified (`docs/scrollback-fix-plan.md`). ⚠️ Shift is excluded on purpose — it is the explicit "give me local scrollback" gesture and must keep that meaning. ⚠️ `terminalWheelLocalScrollback` is deliberately NOT scoped away from repaint-mode CLIs even though it is a footgun there: that would silently override an explicit user choice, so the fallback catches it instead. **Server-side counterpart**: `getClaudeCliVersion()` caches SUCCESS for the process lifetime but must never cache FAILURE — it used to, so one timed-out or PATH-starved probe at the first Claude session start disabled wheel-forwarding for every Claude session until the server restarted (a dead wheel on phone, tablet and laptop at once, the signature of a server-side cause). Failures now retry with a 1/2/4…15min backoff; the policy is the pure `resolveClaudeCliVersion()`. **Tiles** (a grid tile, the split's Pane B: `TerminalTile`) page the wheel through these same gates, called with the tile's own terminal and session (`_localScrollbackIsHollow(target)`, `_shouldForwardWheelToApp(ev, target)`) and the pure `CodemanTerminalInput.pageKeysForTravel`, so the mode rule stays in terminal-ui.js alone. ⚠️ A tile's `baseY` is rarely 0 even when hollow: its first capture is taken at the PTY's previous, taller size and its row-shrinking fits push rows up, so it passes `localRows` with those rows discounted (`TerminalTile._localRows`). ⚠️ So a tile can be hollow with its viewport still up in those rows (Shift+PageUp, a scrollbar drag, a wheel during the first replay), and it pages only while `_terminalViewportAtBottom(tile.terminal)` holds: otherwise every wheel, wheel-down included, was paged and swallowed, the stale rows stayed on screen and the click report (which refuses an off-bottom viewport) went dead too. Off the bottom the wheel stays xterm's, so a wheel-down brings the viewport home. The primary pane needs no such gate: hollow there means `baseY === 0`, which is always at the bottom. Tiles have no touch path and do not forward SGR wheel (tile-grid-plan follow-up 4). Tests: `test/terminal-scroll-routing.test.ts`, `test/terminal-tile-scroll.test.ts`, `test/claude-cli-version-cache.test.ts`. +**A false gate on a hollow pane must not mean a DEAD gesture** (#205 round 2, `_maybePageCliTranscript`): every way `_shouldForwardWheelToApp()` returns false leaves a repaint-mode pane scrolling a buffer that has nothing in it (`baseY === 0`) — the version probe came back empty, the CLI really is older than 2.1.187, the `cliMouseTracking` flag is unset (inline claude, or fullscreen right after a server restart), or the user turned on `terminalWheelLocalScrollback`. **opencode is the fifth case, and the gate is false there by design**: its TUI runs on the ALTERNATE SCREEN (1.18.31 measured: tmux `alternate_on=1`, `history_size=0`), so the buffer is hollow, and it IGNORES SGR wheel reports entirely (six `\x1b[<64;…M` reports against an idle pane left the capture byte-identical) while still paging its transcript on PageUp/PageDown (`messages_page_up/down`) — so paging is the only gesture that can reach it, and without it the wheel was silently dead in every opencode tab. The 1.12.0 retest reported exactly that shape for Claude: a wheel that did nothing at all while Fn+Up (PageUp) paged back through intact text, which is the proof that the CLI's own history and the PTY input path were both fine. So under the guard (`_localScrollbackIsHollow()`: the `transcriptPageKeys` capability, gate false, `baseY === 0`) wheel and touch travel is translated into coalesced `\x1b[5~` / `\x1b[6~` through the same 40ms queue as the SGR reports, at half a screen of travel per page key (the key jumps a whole screen; a 1:1 mapping was unusably slow with a discrete wheel). ⚠️ The first event of a trackpad-sized gesture (opening under 2 rows) pages AT ONCE and the travel it skipped is owed back by the rest of the gesture (one page per half screen still); a >150 ms pause, a direction change or a tab switch starts a new gesture. Waiting for half a screen first meant an ordinary trackpad flick (well under 19 rows on a 38-row pane) sent nothing at all. A larger opening event is a mouse-wheel notch (100 px is 4 rows) and accumulates as before, or slow notches, each its own gesture past the gap, would page a full screen apiece. ⚠️ Three gestures are consumed WITHOUT paging: a pinch (`ctrlKey`, Chrome's trackpad-pinch wheel events), a mostly horizontal swipe (both deltas present and `|deltaX| > |deltaY|`; the touch path locks its own axis first), and anything while the pane's own session has the alert `'action'` (a pending `permission_prompt` or `elicitation_dialog`, `updateTabAlertFromHooks` in app.js), so a page key never lands in an open dialog's selector. ⚠️ Which modes page is the registry's `capabilities.transcriptPageKeys`, published as `window.__codemanTranscriptPageKeys`, never an id check in terminal-ui.js. Codex is on it although it is never forwarded the wheel: newer codex draws on tmux's alternate screen, which the full strip hides from xterm, so its pane is hollow too, and PageUp pages its transcript while SGR wheel reports still do nothing. Which version made the switch is not pinned down: alt-screen drawing was observed on 0.157.1 (local) and 0.160 (remote), while 0.147.0 still draws inline; nothing between 0.147.0 and 0.157.1 has been checked. This is the page-key fallback, NOT wheel forwarding, and an older inline codex keeps real local history (`baseY > 0`) so the guard never fires for it. `shell`/`pi` own real terminal scrollback and are never paged, and gemini/antigravity/grok/deepseek/omp page-key behaviour is unverified (`docs/scrollback-fix-plan.md`). ⚠️ Shift is excluded on purpose — it is the explicit "give me local scrollback" gesture and must keep that meaning. ⚠️ `terminalWheelLocalScrollback` is deliberately NOT scoped away from repaint-mode CLIs even though it is a footgun there: that would silently override an explicit user choice, so the fallback catches it instead. **Server-side counterpart**: `getClaudeCliVersion()` caches SUCCESS for the process lifetime but must never cache FAILURE — it used to, so one timed-out or PATH-starved probe at the first Claude session start disabled wheel-forwarding for every Claude session until the server restarted (a dead wheel on phone, tablet and laptop at once, the signature of a server-side cause). Failures now retry with a 1/2/4…15min backoff; the policy is the pure `resolveClaudeCliVersion()`. **Tiles** (a grid tile, the split's Pane B: `TerminalTile`) page the wheel through these same gates, called with the tile's own terminal and session (`_localScrollbackIsHollow(target)`, `_shouldForwardWheelToApp(ev, target)`) and the pure `CodemanTerminalInput.pageKeysForTravel`, so the mode rule stays in terminal-ui.js alone. ⚠️ A tile's `baseY` is rarely 0 even when hollow: its first capture is taken at the PTY's previous, taller size and its row-shrinking fits push rows up, so it passes `localRows` with those rows discounted (`TerminalTile._localRows`). ⚠️ So a tile can be hollow with its viewport still up in those rows (Shift+PageUp, a scrollbar drag, a wheel during the first replay), and it pages only while `_terminalViewportAtBottom(tile.terminal)` holds: otherwise every wheel, wheel-down included, was paged and swallowed, the stale rows stayed on screen and the click report (which refuses an off-bottom viewport) went dead too. Off the bottom the wheel stays xterm's, so a wheel-down brings the viewport home. The primary pane needs no such gate: hollow there means `baseY === 0`, which is always at the bottom. Tiles have no touch path and do not forward SGR wheel (tile-grid-plan follow-up 4). Tests: `test/terminal-scroll-routing.test.ts`, `test/terminal-tile-scroll.test.ts`, `test/claude-cli-version-cache.test.ts`. **Why the wheel went where it went is LOGGED** (`_logScrollRouting`): one console line per session per distinct decision — `[scroll] <id> → forward-sgr|page-keys|local-scrollback|repull-refused-downgrade (mode=…, cliVersion=…, localScrollbackOptOut=…, mouseTracking=…, localScrollbackRows=…)`. #205 ran two rounds of remote guesswork over questions this line answers directly; keep it when touching the routing. diff --git a/src/web/public/terminal-ui.js b/src/web/public/terminal-ui.js index 4d2150ea..9d939a90 100644 --- a/src/web/public/terminal-ui.js +++ b/src/web/public/terminal-ui.js @@ -96,8 +96,12 @@ // starts a NEW gesture, and the first event of a gesture pages at once rather // than waiting for half a screen of travel (a trackpad flick never got there). const PAGE_KEY_GESTURE_GAP_MS = 150; - // ...but not for sub-row jitter (0.1 row, ~2px). + // ...but not for sub-row jitter (0.1 row, ~2px)... const PAGE_KEY_MIN_START_ROWS = 0.1; + // ...and only for a trackpad-sized opening event. A mouse-wheel notch (100px, + // 4 rows) accumulates toward half a screen as before; paging at once on it made + // slow notches, each its own gesture past the gap, page a full screen apiece. + const PAGE_KEY_IMMEDIATE_MAX_ROWS = 2; // Wheel delta → scroll lines (fractional), for a terminal `rows` tall. The // body of the primary pane's _wheelScrollLinesFloat (see its comment for the @@ -269,6 +273,7 @@ pageKeysForTravel, PAGE_KEY_GESTURE_GAP_MS, PAGE_KEY_MIN_START_ROWS, + PAGE_KEY_IMMEDIATE_MAX_ROWS, TUI_PROMPT_DEFAULT_ROWS_FROM_BOTTOM, MOBILE_KEYBOARD_DISMISS_EXEMPT_SELECTOR, MOBILE_KEYBOARD_DISMISS_TAP_SLOP, @@ -5736,12 +5741,21 @@ Object.assign(CodemanApp.prototype, { * scrollback is never touched. Shift is excluded on purpose: it is the explicit * "give me local scrollback" gesture and must keep that meaning. * - * The FIRST event of a gesture pages at once. Waiting for half a screen of + * The FIRST event of a trackpad-sized gesture (opening under + * PAGE_KEY_IMMEDIATE_MAX_ROWS) pages at once. Waiting for half a screen of * travel (19 rows, ~475px on a 38-row pane) meant an ordinary trackpad flick * never sent a key at all. That page is pre-paid: the travel it skipped is * owed back by the rest of the gesture, so the rate stays one page per * `perPage` rows. A pause (PAGE_KEY_GESTURE_GAP_MS), a direction change or a - * tab switch starts a new gesture. + * tab switch starts a new gesture. A larger opening event is a wheel notch and + * accumulates as before, so slow notches still page once per `perPage` rows. + * + * Consumed WITHOUT paging: a pinch (`ctrlKey`, how Chrome reports a trackpad + * pinch), a mostly horizontal swipe (both deltas present, |deltaX| > |deltaY|; + * the touch path locks its own axis before it gets here), and any gesture while + * the session has an open dialog (tab alert 'action', set by a pending + * permission_prompt or elicitation_dialog), so a page key never reaches its + * selector. * * @returns true when the gesture was consumed here (the caller must not also * scroll locally). @@ -5755,11 +5769,17 @@ Object.assign(CodemanApp.prototype, { _maybePageCliTranscript(ev, lines) { if (!lines || ev?.shiftKey || !this.activeSessionId) return false; if (!this._localScrollbackIsHollow()) return false; + if (ev?.ctrlKey) return true; // pinch + const dx = Math.abs(ev?.deltaX || 0); + const dy = Math.abs(ev?.deltaY || 0); + if (dx && dy && dx > dy) return true; // mostly horizontal swipe + if (this.tabAlerts?.get(this.activeSessionId) === 'action') return true; // dialog up // Leftover travel belongs to the tab it was made on. if (this._pageKeySession !== this.activeSessionId) { this._pageKeySession = this.activeSessionId; this._pageKeyPending = 0; this._pageKeyLastAt = undefined; + this._pageKeyPrepaid = false; } const tuning = window.CodemanTerminalInput; const perPage = Math.max(2, Math.round((this.terminal?.rows || 24) * tuning.PAGE_KEY_SCREEN_FRACTION)); @@ -5772,9 +5792,14 @@ Object.assign(CodemanApp.prototype, { this._pageKeyLastAt = now; this._pageKeyDir = dir; if (gestureStart) { - this._pageKeyPending = 0; - if (Math.abs(lines) >= tuning.PAGE_KEY_MIN_START_ROWS && Math.abs(lines) < perPage) { + // A debt left by an earlier pre-paid page dies with its gesture; plain + // wheel travel keeps accumulating across notches. + if (this._pageKeyPrepaid) this._pageKeyPending = 0; + this._pageKeyPrepaid = false; + const size = Math.abs(lines); + if (size >= tuning.PAGE_KEY_MIN_START_ROWS && size < Math.min(perPage, tuning.PAGE_KEY_IMMEDIATE_MAX_ROWS)) { // Pre-pay one page; the skipped travel is owed back (pending carries the opposite sign). + this._pageKeyPrepaid = true; this._pageKeyPending = lines - dir * perPage; this._queueScrollBytes(dir < 0 ? tuning.KEY_PAGE_UP : tuning.KEY_PAGE_DOWN); this._logScrollRouting('page-keys'); diff --git a/test/terminal-scroll-routing.test.ts b/test/terminal-scroll-routing.test.ts index fca7d5e0..ea7ffa33 100644 --- a/test/terminal-scroll-routing.test.ts +++ b/test/terminal-scroll-routing.test.ts @@ -172,14 +172,15 @@ describe('PageUp/PageDown fallback for a hollow local buffer (issue #205 round 2 it('answers the first event of a gesture at once and owes the travel back', () => { const { app, sent } = hollowApp(); - // A trackpad flick is far less than half a screen (18 rows here). It used to - // send nothing at all, so a session that always lands here looked dead. - expect(app._maybePageCliTranscript({ shiftKey: false }, -10)).toBe(true); + // A trackpad flick opens with a small delta and stays far short of half a + // screen (18 rows here). It used to send nothing at all, so a session that + // always lands here looked dead. + expect(app._maybePageCliTranscript({ shiftKey: false }, -1)).toBe(true); app._flushWheelSgrQueue(); expect(sent).toEqual([{ id: 'sess-1', data: '\x1b[5~' }]); // The pre-paid page is owed back: the rest of this page's travel sends nothing… - app._maybePageCliTranscript({ shiftKey: false }, -8); + app._maybePageCliTranscript({ shiftKey: false }, -17); app._flushWheelSgrQueue(); expect(sent).toHaveLength(1); @@ -200,15 +201,79 @@ describe('PageUp/PageDown fallback for a hollow local buffer (issue #205 round 2 let now = 1_000; clock.now = () => now; - app._maybePageCliTranscript({ shiftKey: false }, -2); // first event: one PageUp - app._maybePageCliTranscript({ shiftKey: false }, 2); // reversal: one PageDown at once + app._maybePageCliTranscript({ shiftKey: false }, -1); // first event: one PageUp + app._maybePageCliTranscript({ shiftKey: false }, 1); // reversal: one PageDown at once now += 1_000; - app._maybePageCliTranscript({ shiftKey: false }, 2); // after a pause: another at once + app._maybePageCliTranscript({ shiftKey: false }, 1); // after a pause: another at once app._maybePageCliTranscript({ shiftKey: false }, 0.05); // sub-row jitter in the same gesture: nothing app._flushWheelSgrQueue(); expect(sent).toEqual([{ id: 'sess-1', data: '\x1b[5~\x1b[6~\x1b[6~' }]); }); + it('lets wheel notches accumulate instead of paging a full screen on each one', () => { + // A 100 px notch is 4 rows. Only a trackpad-sized opening event (under 2 rows) + // pages at once; a notch adds up toward half a screen as it always did, so + // slow notches (each one its own gesture by the 150 ms gap) still page once + // per 18 rows here, not once per notch. + for (const gapMs of [250, 40]) { + const { app, sent, clock } = hollowApp(); + let now = 1_000; + clock.now = () => now; + for (let i = 0; i < 5; i++) { + expect(app._maybePageCliTranscript({ shiftKey: false, deltaY: -100 }, -4)).toBe(true); + now += gapMs; + } + app._flushWheelSgrQueue(); + expect(sent).toEqual([{ id: 'sess-1', data: '\x1b[5~' }]); + } + }); + + it('consumes a mostly horizontal swipe without paging', () => { + const { app, sent } = hollowApp(); + + // A sideways trackpad swipe carries a little vertical drift (3 px is 0.12 rows, + // above the jitter floor). It must not page the transcript. + for (let i = 0; i < 6; i++) { + expect(app._maybePageCliTranscript({ shiftKey: false, deltaX: 60, deltaY: 3 }, 0.12)).toBe(true); + } + app._flushWheelSgrQueue(); + expect(sent).toEqual([]); + + // A mostly vertical swipe with some sideways drift still pages. + app._maybePageCliTranscript({ shiftKey: false, deltaX: 3, deltaY: -25 }, -1); + app._flushWheelSgrQueue(); + expect(sent).toEqual([{ id: 'sess-1', data: '\x1b[5~' }]); + }); + + it('consumes a trackpad pinch without paging', () => { + const { app, sent } = hollowApp(); + + // Chrome reports a pinch as wheel events with ctrlKey set. + for (let i = 0; i < 4; i++) { + expect(app._maybePageCliTranscript({ shiftKey: false, ctrlKey: true, deltaY: 4 }, 0.16)).toBe(true); + } + app._flushWheelSgrQueue(); + expect(sent).toEqual([]); + }); + + it('does not page while the session is showing a dialog', () => { + const { app, sent } = hollowApp(); + // 'action' is set while a permission_prompt or elicitation_dialog is pending + // (updateTabAlertFromHooks in app.js). Page keys must not reach that selector. + app.tabAlerts = new Map([['sess-1', 'action']]); + + expect(app._maybePageCliTranscript({ shiftKey: false }, -1)).toBe(true); + expect(app._maybePageCliTranscript({ shiftKey: false }, -40)).toBe(true); + app._flushWheelSgrQueue(); + expect(sent).toEqual([]); + + // Once the dialog is answered (an idle alert, or none) paging resumes. + app.tabAlerts.set('sess-1', 'idle'); + app._maybePageCliTranscript({ shiftKey: false }, 1); + app._flushWheelSgrQueue(); + expect(sent).toEqual([{ id: 'sess-1', data: '\x1b[6~' }]); + }); + it('does not page on sub-row jitter that opens a gesture', () => { const { app, sent } = hollowApp();