Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: scroll OpenCode history in the Shell

[._.]/ Adam Eivy3161734c0b46
diff --git a/client/src/hooks/useShellSession.js b/client/src/hooks/useShellSession.js
index 844bcd0408..8c3692f426 100644
--- a/client/src/hooks/useShellSession.js
+++ b/client/src/hooks/useShellSession.js
@@ -9,7 +9,7 @@ import { useSocket } from './useSocket';
import { useThemeContext } from '../components/ThemeContext';
import { buildTerminalTheme, parseCssColorToHex } from '../lib/terminalTheme';
import { attachDictationBridge } from '../lib/terminalDictation';
-import { attachTerminalTouchScroll, scrollTerminalPage } from '../lib/terminalScroll';
+import { attachTerminalTouchScroll, attachTerminalWheelScroll, scrollTerminalPage } from '../lib/terminalScroll';
import { readFileAsBase64 } from '../utils/fileUpload';
import * as api from '../services/api';
import toast from '../components/ui/Toast';
@@ -271,10 +271,14 @@ export function useShellSession({ isFullscreen } = {}) {
term.open(terminalRef.current);
// xterm binds no touch handlers of its own, so without this a swipe over the
- // terminal does nothing — see lib/terminalScroll.js. Attached here rather than in
- // its own effect: it has no reactive deps, so its lifetime is exactly the
- // terminal instance's (unlike the dictation bridge, which needs emitShellInput).
+ // terminal does nothing. Alternate-screen TUIs need the matching wheel capture so
+ // OpenCode's supported PageUp/PageDown bindings receive scroll gestures instead
+ // of unsupported mouse reports. See lib/terminalScroll.js. Attached here rather
+ // than in its own effect: neither handler has reactive deps, so both lifetimes are
+ // exactly the terminal instance's (unlike the dictation bridge, which needs
+ // emitShellInput).
const detachTouchScroll = attachTerminalTouchScroll(term);
+ const detachWheelScroll = attachTerminalWheelScroll(term);
requestAnimationFrame(() => {
fitAddon.fit();
@@ -285,6 +289,7 @@ export function useShellSession({ isFullscreen } = {}) {
return () => {
detachTouchScroll();
+ detachWheelScroll();
term.dispose();
termInstanceRef.current = null;
fitAddonRef.current = null;
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 0be5509781..522f94d37d 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -192,7 +192,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `tabNotation.js` | Guitar-tab / chord-sheet / ChordPro text parser for SongBook (`/songbook`). `parseTabSheet(text)` → `{ lines, meta, errors }` classifying each line (`section`/`chords`/`lyric`/`tabstaff`/`chordlyric`/`blank`/`text`) with chord names + column offsets, plus ChordPro meta (`{title:}`/`{artist:}`/`{key:}`/`{capo:}`); `detectFormat(text)` → `'chordpro' \| 'tab' \| 'plain'`; `normalizePastedTab(text)` cleans HTML remnants/entities, CRLF, tabs→spaces, blank-line runs; `transposeChordName(name, n)` / `transposeText(text, n)` transpose chord symbols (slash chords, sensible sharp/flat spelling, column-preserving on chord lines); `TAB_ARTICULATIONS` documents tab-staff technique characters for the viewer legend; `CHORD_TOKEN_RE` exported for reuse, plus `NOTE_TO_PC` / `spellPitchClass` exported minimally so `chordShapes.js` derives voicings from the same pitch-class tables. Forgiving — never throws, unknown lines classify as `text`. NOT the lead-sheet parser (`scoreNotation.js`). |
| `tailnetPeer.js` | `isTailnetPeer(peer)` — is this registered peer reachable ONLY over the tailnet? A faithful port of `server/lib/tailnetPeer.js` (MagicDNS `.ts.net`, the 100.64.0.0/10 CGNAT range with every octet range-checked, and the `fd7a:115c:a1e0::/48` ULA; an explicit non-tailnet `host` overrides a tailnet-looking `address`). FAIL-CLOSED — anything not positively recognized is not tailnet. Used to keep the unattended-render-routing picker from OFFERING a peer the server would refuse under ADR [federated visual prompts](../../../docs/decisions/2026-08-20-federated-visual-prompts.md) rule 5; the server stays authoritative and refuses such a route both on save and on every enqueue. Keep the table in `tailnetPeer.test.js` identical to the server suite’s. |
| `terminalDictation.js` | Voice-dictation/IME bridge for the Shell's xterm.js terminal. Apple dictation streams progressively refined guesses and *replaces* what it already typed; xterm forwards each insertion and drops the matching deletions, so the PTY accumulates a garble (`determin` + `determine` + `determines`…). `attachDictationBridge(terminal, sendData)` binds capture-phase listeners on `terminal.element` — ahead of xterm's own textarea listeners, which it stops — and forwards a diff instead: `TERMINAL_DEL` (`0x7f`) per dropped character, then the added text. `sendData` returns `false` to report a dropped send, which leaves the mirror where the PTY actually is. Paths that reach the PTY some other way (a keystroke xterm handles itself, paste, blur, composition end, screen-reader mode) resync the mirror without emitting. `planFieldEdit(mirror, next, floor)` → `{ data, committed }` is the pure core: `floor` is the prefix we did not write and must never rewind through, and `committed` (what the PTY holds afterward, which is *not* the field's value when the floor blocked a rewind) is what the caller must track. The prefix scan never splits a surrogate pair — cutting between the halves of an astral character would send a lone surrogate that serializes to `U+FFFD`. Wired in `useShellSession`; the test suite pins the seam against a real `Terminal`. |
-| `terminalScroll.js` | Scrolling the Shell terminal by touch, and inside a full-screen TUI. Two gaps, one primitive: xterm 6 binds **no touch handlers at all** (its viewport is VS Code’s `SmoothScrollableElement`, whose scroll extent is virtual — there is no oversized spacer for the browser to scroll natively), and a TUI’s ALTERNATE screen buffer additionally has no scrollback, so `scrollLines()` clamps to a no-op there. `attachTerminalTouchScroll(terminal)` (→ detach fn) makes a one-finger drag scroll in either buffer; `scrollTerminalLines(terminal, lines, geometry?)` / `scrollTerminalPage(terminal, direction)` drive it — via `scrollLines()` in the normal buffer, and in the alternate buffer by synthesizing `DOM_DELTA_LINE` wheel events on `terminal.element`, xterm’s only injection point (`attachCustomWheelEventHandler` intercepts, it cannot inject), so xterm’s own table picks SGR mouse report vs cursor key from the DEC modes the TUI set. `measureTerminalGeometry(terminal)` takes the one layout-forcing read per gesture (row height + screen centre); `planTouchScrollSteps(accumPx, rowHeightPx)` is the pure sub-row-remainder core. Wired in `useShellSession` (`scrollPage`) + the `SCROLL_KEYS` buttons in `components/shell/TerminalHotKeys.jsx`. |
+| `terminalScroll.js` | Scrolling the Shell terminal by touch, wheel, and page controls. xterm 6 binds **no touch handlers at all**, and a TUI’s ALTERNATE screen buffer has no terminal scrollback, so `scrollLines()` clamps to a no-op there. Normal shell scrollback uses `scrollLines()`; alternate-screen wheel gestures are captured before xterm’s mouse listener and translated to standard PageUp/PageDown input, which OpenCode supports for its message viewport. `attachTerminalTouchScroll(terminal)` (→ detach fn) makes a one-finger drag scroll in either buffer, `attachTerminalWheelScroll(terminal)` handles native wheel input, and `scrollTerminalPage(terminal, direction)` powers the `SCROLL_KEYS` buttons. `measureTerminalGeometry(terminal)` takes one layout read per gesture; `planTouchScrollSteps(accumPx, rowHeightPx)` is the pure sub-row-remainder core. Wired in `useShellSession`. |
| `terminalTheme.js` | Pure xterm.js palette builder for the Shell terminal. `buildTerminalTheme({ bg, fg, accent, card, error, success, warning }, mode)` assembles the xterm `theme` object — base ANSI colors from the active theme's CSS vars, the rest from mode-tuned literals (`ANSI_NIGHT` bright/pastel for dark backgrounds, `ANSI_DAY` darkened/saturated so colored CLI output stays legible on daytime themes). `parseCssColorToHex(raw, fallback)` normalizes both the `15 15 15` triple form and the `rgb(7 7 7 / 0.86)` function form (used by `--port-terminal-*` tokens) to `#rrggbb`, dropping alpha. No DOM reads — `Shell.jsx` resolves CSS vars and re-applies on theme switch. |
| `threejsAnimation.js` | Pure pose evaluator for the declarative clip contract in `server/lib/threejsModel.js`, used by the Three.js Models preview transport. `evaluateThreejsClipPose(clip, timeSeconds)` → `{ timeSeconds, pose, activeSequenceIds, activePartIds }` where `pose` is a null-prototype partId → `{ position?, rotationDegrees?, scale?, opacity?, visible? }` map: each part+channel resolves from the one sequence that owns the instant (the window containing it, else the most recent behind it, else the next ahead), `visible` steps at the window's end rather than interpolating, and a part no sequence drives is absent so the spec renders as authored. `collectThreejsCues(clip, from, to)` returns the data-only sound cues a play loop crossed in the half-open `[from, to)` interval — a scrub calls it never, which is what makes scrubbing silent. `listThreejsClips` / `listThreejsCues` / `resolveThreejsClip` / `getThreejsClipDuration` read a spec that may have no `animation` key at all. |
| `threejsEnvironment.js` | Image-based lighting for the procedural sculpt spec, used by the Three.js Models preview. `spec.lights` are punctual — they light a surface but give it nothing to REFLECT, so `metalness`, `transmission`, `clearcoat` and `iridescence` read off an environment or read off nothing, and a plausible conductor renders near-black without one. `createSculptEnvironmentTarget(renderer, preset)` builds a preset locally from three's own primitives and prefilters it through `PMREMGenerator` — `neutral` is three's bundled `RoomEnvironment`, `studio` a dark shell with three emissive softbox panels plus a floor bounce — returning null for `none`; the caller owns the render TARGET and disposes it (disposing only `.texture` leaks the framebuffer behind it). `THREEJS_RENDER_PROFILE` mirrors the server's colour-space/tone-map/exposure contract so the preview renders at what the export stamps on the model. Deliberately NOT drei's `<Environment preset=…>`, which fetches an HDR from a CDN: rendering a local model makes no outbound request. `resolveSculptEnvironment(spec)` is the client mirror of `resolveThreejsEnvironment` in `server/lib/threejsModel.js`, reading a spec with no `environment` key as the `none` it was actually authored against. |
diff --git a/client/src/lib/terminalScroll.js b/client/src/lib/terminalScroll.js
index 0b71dd6151..920c7ecd07 100644
--- a/client/src/lib/terminalScroll.js
+++ b/client/src/lib/terminalScroll.js
@@ -12,40 +12,44 @@
//
// • The ALTERNATE screen buffer that a TUI takes (a watched `claude`/`codex` run,
// `vim`, `less`, `htop`) has no scrollback by construction: `ybase` stays 0, so
-// `scrollLines()` and friends clamp to a no-op there. Scrolling an alt-screen
-// app means handing the scroll to the APP, which owns its own scroll region.
+// `scrollLines()` and friends clamp to a no-op there. OpenCode's TUI also does
+// not use terminal mouse-wheel reports for its message viewport; its supported
+// path is the terminal's PageUp/PageDown key bindings.
//
-// The primitive is a synthesized wheel event on `terminal.element`. That is not a
-// shortcut around xterm — it is the only injection point xterm offers
-// (`attachCustomWheelEventHandler` intercepts wheels, it cannot inject one), and
-// going through it lets xterm's own decision table pick what to emit: an SGR mouse
-// report when the TUI enabled wheel tracking, a cursor key ("alternate scroll") when
-// it did not. Deciding that here would mean duplicating protocol state the public
-// API doesn't expose — `modes` reports `mouseTrackingMode`, but not the encoding.
-// The normal buffer is the one case driven directly, through the real `scrollLines()`.
+// Normal-buffer scroll stays inside xterm through `scrollLines()`. In an alternate
+// buffer, wheel events are captured before xterm's mouse protocol listener and
+// translated to PageUp/PageDown escape sequences through `terminal.input()`. That
+// keeps the event from becoming unsupported application mouse input while still
+// letting the TUI own its conversation scroll region. The page buttons and touch
+// gestures use the same key path.
//
// Scrolling back PAST a TUI, into what the shell printed before it started, stays
// impossible while it holds the alternate screen. That is terminal semantics, not a
// gap here.
-// One dispatched wheel event is one scroll step, whatever delta it carries: both of
-// xterm's alternate-buffer paths emit exactly one report (a mouse event, or a single
-// cursor key) per wheel event and ignore the magnitude. N lines therefore means N
-// events — bounded so a fling or a huge `rows` can't become an unbounded loop.
-const MAX_WHEEL_STEPS = 64;
+// Used to bound a touch drag or a synthetic request instead of emitting an unbounded
+// sequence of page keys when a gesture has a very large delta.
+const MAX_SCROLL_STEPS = 64;
// Used when the terminal hasn't been laid out yet, so a swipe on a freshly-attached
// session still scrolls instead of silently accumulating pixels forever.
const FALLBACK_ROW_HEIGHT_PX = 18;
-// DOM_DELTA_LINE, not pixels: xterm's wheel accumulator divides a PIXEL delta by the
-// device cell height and additionally damps deltas under 50px, so a synthesized pixel
-// event is liable to round to zero steps and scroll nothing. A line delta is read as
-// whole lines with no accumulator.
-const WHEEL_DELTA_MODE_LINE = 1;
-
const isAltBuffer = (terminal) => terminal?.buffer?.active?.type === 'alternate';
+// These are the standard xterm sequences OpenCode binds to its message page
+// commands. Sending them through Terminal#input makes them flow through xterm's
+// existing onData bridge to the PTY, without needing to know the server session id.
+const PAGE_UP_SEQUENCE = '\x1b[5~';
+const PAGE_DOWN_SEQUENCE = '\x1b[6~';
+
+/** Send one standard terminal PageUp/PageDown key to an alternate-screen app. */
+export const sendTerminalPageKey = (terminal, direction) => {
+ if (!terminal || !direction || typeof terminal.input !== 'function') return false;
+ terminal.input(direction < 0 ? PAGE_UP_SEQUENCE : PAGE_DOWN_SEQUENCE, false);
+ return true;
+};
+
// `.xterm-screen` is the element that is exactly rows × cellHeight; the outer
// `.xterm` container can carry padding that would skew a row height taken from it.
const screenElement = (terminal) => {
@@ -54,36 +58,28 @@ const screenElement = (terminal) => {
};
/**
- * Measure the terminal once per gesture: the row height that turns drag pixels into
- * lines, and the screen's centre, which a synthesized wheel needs because xterm
- * resolves the event to a cell and drops any mouse report landing outside the screen.
- *
- * Hoisted out of the per-move path deliberately — both are layout-forcing reads, and
- * PortOS runs xterm's DOM renderer, so during a live TUI run layout is dirty every
- * frame and a read per `touchmove` costs a full style+layout flush of the row grid at
- * touch frequency. Neither value can change inside a drag we are preventDefault-ing.
+ * Measure the terminal once per gesture. This is a layout-forcing read, and PortOS
+ * runs xterm's DOM renderer, so reading on every touchmove costs a style+layout flush
+ * at touch frequency. The row height cannot change inside a gesture we consume.
*/
export const measureTerminalGeometry = (terminal) => {
const rect = screenElement(terminal)?.getBoundingClientRect();
const rows = terminal?.rows || 0;
return {
rowHeightPx: rect?.height > 0 && rows ? rect.height / rows : FALLBACK_ROW_HEIGHT_PX,
- clientX: rect ? rect.left + rect.width / 2 : 0,
- clientY: rect ? rect.top + rect.height / 2 : 0,
};
};
// A screenful, minus one row of overlap so the reader keeps a line of context — the
-// same convention a pager uses for Page Up/Down.
+// same convention a normal terminal's Page Up/Down control uses.
const terminalPageLines = (terminal) => Math.max(1, (terminal?.rows ?? 1) - 1);
/**
- * Scroll the terminal by `lines` (negative = toward older output). Pass `geometry`
- * from `measureTerminalGeometry` to reuse a gesture's measurement; omit it for
- * one-shot calls. Returns the lines actually applied, signed — which is the clamp-
- * aware count, not the request.
+ * Scroll the normal terminal buffer by `lines` (negative = toward older output).
+ * Alternate-screen apps have no terminal scrollback, so each requested logical
+ * step becomes the app's supported PageUp/PageDown key instead.
*/
-export const scrollTerminalLines = (terminal, lines, geometry) => {
+export const scrollTerminalLines = (terminal, lines) => {
const requested = Math.trunc(lines);
if (!terminal || !requested) return 0;
@@ -94,26 +90,42 @@ export const scrollTerminalLines = (terminal, lines, geometry) => {
return requested;
}
- const el = terminal.element;
- if (!el?.dispatchEvent || typeof WheelEvent === 'undefined') return 0;
- const up = requested < 0;
- const steps = Math.min(Math.abs(requested), MAX_WHEEL_STEPS);
- const { clientX, clientY } = geometry || measureTerminalGeometry(terminal);
- const init = {
- deltaY: up ? -1 : 1,
- deltaMode: WHEEL_DELTA_MODE_LINE,
- clientX,
- clientY,
- bubbles: true,
- cancelable: true,
- };
- for (let i = 0; i < steps; i++) el.dispatchEvent(new WheelEvent('wheel', init));
- return up ? -steps : steps;
+ const direction = requested < 0 ? -1 : 1;
+ const steps = Math.min(Math.abs(requested), MAX_SCROLL_STEPS);
+ let sent = 0;
+ while (sent < steps && sendTerminalPageKey(terminal, direction)) sent++;
+ return direction * sent;
};
/** Scroll one screenful. `direction` is -1 for up (older), 1 for down. */
-export const scrollTerminalPage = (terminal, direction) =>
- scrollTerminalLines(terminal, terminalPageLines(terminal) * (direction < 0 ? -1 : 1));
+export const scrollTerminalPage = (terminal, direction) => {
+ if (isAltBuffer(terminal)) {
+ return sendTerminalPageKey(terminal, direction) ? (direction < 0 ? -1 : 1) : 0;
+ }
+ return scrollTerminalLines(terminal, terminalPageLines(terminal) * (direction < 0 ? -1 : 1));
+};
+
+/**
+ * Capture native wheel input for alternate-screen apps that expose scrolling as
+ * keybindings instead of terminal mouse reports. Normal shell scrollback is left
+ * entirely to xterm's own viewport listener.
+ */
+export const attachTerminalWheelScroll = (terminal) => {
+ const el = terminal?.element;
+ if (!el?.addEventListener) return () => {};
+
+ const onWheel = (event) => {
+ if (!isAltBuffer(terminal) || !event.deltaY || event.shiftKey) return;
+ if (!sendTerminalPageKey(terminal, event.deltaY < 0 ? -1 : 1)) return;
+ if (event.cancelable) event.preventDefault();
+ // xterm's mouse listener is on the same terminal element. Stop it before it
+ // turns this wheel into an unsupported mouse report for the TUI.
+ event.stopImmediatePropagation();
+ };
+
+ el.addEventListener('wheel', onWheel, { capture: true, passive: false });
+ return () => el.removeEventListener('wheel', onWheel, { capture: true });
+};
/**
* Convert accumulated drag distance into whole scroll steps, keeping the sub-row
@@ -130,9 +142,8 @@ export const planTouchScrollSteps = (accumPx, rowHeightPx) => {
/**
* Make a one-finger drag scroll the terminal. Returns a detach function.
*
- * Buffer-agnostic on purpose: `scrollTerminalLines` already branches, and the gap
- * this closes (xterm 6 binds no touch handlers) is not specific to a TUI — an
- * ordinary shell's scrollback is just as unswipeable without it.
+ * Normal shell sessions scroll row-by-row. Alternate-screen TUIs use a half-viewport
+ * drag threshold because their PageUp/PageDown bindings move a page, not one row.
*/
export const attachTerminalTouchScroll = (terminal) => {
const el = terminal?.element;
@@ -158,13 +169,19 @@ export const attachTerminalTouchScroll = (terminal) => {
const y = ev.touches[0].clientY;
accumPx += lastY - y;
lastY = y;
- const { steps, remainderPx } = planTouchScrollSteps(accumPx, geometry.rowHeightPx);
+ // OpenCode's PageUp/PageDown bindings move the message viewport by a page,
+ // not by one terminal row. Wait for roughly half a viewport before sending a
+ // page key; normal shell scrollback remains row-granular.
+ const stepHeight = isAltBuffer(terminal)
+ ? Math.max(geometry.rowHeightPx, (terminal.rows || 1) * geometry.rowHeightPx / 2)
+ : geometry.rowHeightPx;
+ const { steps, remainderPx } = planTouchScrollSteps(accumPx, stepHeight);
if (!steps) return;
accumPx = remainderPx;
// Swallow the gesture only once it has resolved into a scroll — before that it
// may still be a tap, and a TUI with mouse tracking on wants the click.
if (ev.cancelable) ev.preventDefault();
- scrollTerminalLines(terminal, steps, geometry);
+ scrollTerminalLines(terminal, steps);
};
el.addEventListener('touchstart', onStart, { passive: true });
diff --git a/client/src/lib/terminalScroll.test.js b/client/src/lib/terminalScroll.test.js
index f42a755fc5..d9269074f9 100644
--- a/client/src/lib/terminalScroll.test.js
+++ b/client/src/lib/terminalScroll.test.js
@@ -1,17 +1,17 @@
import { describe, it, expect, vi, afterEach } from 'vitest';
import {
+ attachTerminalTouchScroll,
+ attachTerminalWheelScroll,
measureTerminalGeometry,
planTouchScrollSteps,
scrollTerminalLines,
scrollTerminalPage,
- attachTerminalTouchScroll,
+ sendTerminalPageKey,
} from './terminalScroll.js';
// A stand-in for the xterm instance carrying only what this module reads. The real
-// Terminal can't be driven here: xterm's own wheel handlers bail out when the render
-// service has no measured cell height (jsdom has no layout), which is why these tests
-// assert the SHAPE of the dispatched wheel event rather than what xterm does with it —
-// the contract this module owns is "emit what a real wheel emits".
+// Terminal is not needed here: these tests pin the event ownership and key sequence
+// that the Shell's xterm instance exposes to the PTY.
const makeTerminal = ({ alt = true, rows = 24, height = 480 } = {}) => {
const el = document.createElement('div');
const screen = document.createElement('div');
@@ -23,6 +23,7 @@ const makeTerminal = ({ alt = true, rows = 24, height = 480 } = {}) => {
element: el,
rows,
buffer: { active: { type: alt ? 'alternate' : 'normal' } },
+ input: vi.fn(),
scrollLines: vi.fn(),
};
};
@@ -33,28 +34,16 @@ const touchEvent = (type, touches) => {
return ev;
};
-// Returns the array the assertions read; every dispatched wheel lands in it.
-const captureWheels = (term) => {
- const wheels = [];
- term.element.addEventListener('wheel', (ev) => wheels.push(ev));
- return wheels;
-};
-
afterEach(() => { document.body.innerHTML = ''; });
describe('measureTerminalGeometry', () => {
it('derives the row height from the rendered screen, not the outer container', () => {
- expect(measureTerminalGeometry(makeTerminal({ rows: 24, height: 480 })).rowHeightPx).toBe(20);
+ expect(measureTerminalGeometry(makeTerminal({ rows: 24, height: 480 }))).toEqual({ rowHeightPx: 20 });
});
it('falls back to a nominal row height before the terminal has been laid out', () => {
- expect(measureTerminalGeometry(makeTerminal({ rows: 24, height: 0 })).rowHeightPx).toBe(18);
- expect(measureTerminalGeometry(null).rowHeightPx).toBe(18);
- });
-
- it('centres on the screen so a synthesized wheel resolves to a real cell', () => {
- // .xterm-screen rect is left 100 / width 800, top 50 / height 480.
- expect(measureTerminalGeometry(makeTerminal({ height: 480 }))).toMatchObject({ clientX: 500, clientY: 290 });
+ expect(measureTerminalGeometry(makeTerminal({ rows: 24, height: 0 }))).toEqual({ rowHeightPx: 18 });
+ expect(measureTerminalGeometry(null)).toEqual({ rowHeightPx: 18 });
});
});
@@ -74,76 +63,56 @@ describe('planTouchScrollSteps', () => {
});
});
+describe('alternate-screen page keys', () => {
+ it('sends standard PageUp/PageDown sequences through xterm input', () => {
+ const term = makeTerminal();
+ expect(sendTerminalPageKey(term, -1)).toBe(true);
+ expect(sendTerminalPageKey(term, 1)).toBe(true);
+ expect(term.input.mock.calls).toEqual([['\x1b[5~', false], ['\x1b[6~', false]]);
+ });
+
+ it('returns false when the terminal cannot accept input', () => {
+ expect(sendTerminalPageKey(null, -1)).toBe(false);
+ expect(sendTerminalPageKey({ input: null }, -1)).toBe(false);
+ expect(sendTerminalPageKey({ input: vi.fn() }, 0)).toBe(false);
+ });
+});
+
describe('scrollTerminalLines', () => {
it('uses the real scrollback API in the normal buffer', () => {
const term = makeTerminal({ alt: false });
- const wheels = captureWheels(term);
expect(scrollTerminalLines(term, -5)).toBe(-5);
expect(term.scrollLines).toHaveBeenCalledWith(-5);
- // The viewport's scroll extent is virtual, so a wheel event would move nothing.
- expect(wheels).toHaveLength(0);
+ expect(term.input).not.toHaveBeenCalled();
});
- it('dispatches one wheel event per line in the alternate buffer', () => {
+ it('uses the app page key for each alternate-buffer step', () => {
const term = makeTerminal();
- const wheels = captureWheels(term);
expect(scrollTerminalLines(term, -3)).toBe(-3);
- expect(term.scrollLines).not.toHaveBeenCalled();
- // One event == one scroll step whichever path xterm takes, so the magnitude is
- // fixed at one line and the COUNT carries the distance.
- expect(wheels.map((ev) => ev.deltaY)).toEqual([-1, -1, -1]);
- expect(wheels.every((ev) => ev.deltaMode === WheelEvent.DOM_DELTA_LINE)).toBe(true);
+ expect(term.input.mock.calls).toEqual([
+ ['\x1b[5~', false],
+ ['\x1b[5~', false],
+ ['\x1b[5~', false],
+ ]);
});
- it('scrolls down with a positive delta', () => {
+ it('bounds a large alternate-buffer request', () => {
const term = makeTerminal();
- const wheels = captureWheels(term);
- scrollTerminalLines(term, 2);
- expect(wheels.map((ev) => ev.deltaY)).toEqual([1, 1]);
- });
-
- it('positions the wheel inside the rendered screen so the mouse report is not dropped', () => {
- const term = makeTerminal({ height: 480 });
- const wheels = captureWheels(term);
- scrollTerminalLines(term, -1);
- expect(wheels[0].clientX).toBe(500);
- expect(wheels[0].clientY).toBe(290);
- });
-
- it('never sets shiftKey — xterm reads it as "scroll the browser, not the terminal"', () => {
- const term = makeTerminal();
- const wheels = captureWheels(term);
- scrollTerminalLines(term, -1);
- expect(wheels[0].shiftKey).toBe(false);
- });
-
- it('bounds a fling instead of dispatching an unbounded run of events', () => {
- const term = makeTerminal();
- const wheels = captureWheels(term);
expect(scrollTerminalLines(term, -5000)).toBe(-64);
- expect(wheels).toHaveLength(64);
- });
-
- it('reuses a supplied geometry instead of re-measuring', () => {
- const term = makeTerminal();
- const wheels = captureWheels(term);
- scrollTerminalLines(term, -1, { rowHeightPx: 20, clientX: 7, clientY: 9 });
- expect(wheels[0].clientX).toBe(7);
- expect(wheels[0].clientY).toBe(9);
+ expect(term.input).toHaveBeenCalledTimes(64);
});
it('is a no-op for zero, a fractional delta, or no terminal', () => {
const term = makeTerminal();
- const wheels = captureWheels(term);
expect(scrollTerminalLines(term, 0)).toBe(0);
expect(scrollTerminalLines(term, 0.4)).toBe(0);
expect(scrollTerminalLines(null, -3)).toBe(0);
- expect(wheels).toHaveLength(0);
+ expect(term.input).not.toHaveBeenCalled();
});
});
describe('scrollTerminalPage', () => {
- it('moves a screenful minus one row of overlap', () => {
+ it('moves a normal-buffer screenful minus one row of overlap', () => {
const term = makeTerminal({ alt: false, rows: 24 });
scrollTerminalPage(term, -1);
expect(term.scrollLines).toHaveBeenCalledWith(-23);
@@ -151,40 +120,102 @@ describe('scrollTerminalPage', () => {
expect(term.scrollLines).toHaveBeenCalledWith(23);
});
- it('still moves a line on a one-row terminal', () => {
+ it('uses one app page key in an alternate buffer', () => {
+ const term = makeTerminal({ rows: 24 });
+ expect(scrollTerminalPage(term, -1)).toBe(-1);
+ expect(term.input).toHaveBeenCalledWith('\x1b[5~', false);
+ });
+
+ it('still moves a line on a one-row normal terminal', () => {
const term = makeTerminal({ alt: false, rows: 1 });
scrollTerminalPage(term, -1);
expect(term.scrollLines).toHaveBeenCalledWith(-1);
});
});
+describe('attachTerminalWheelScroll', () => {
+ it('translates alternate-buffer wheel input before xterm can send mouse input', () => {
+ const term = makeTerminal();
+ const xtermListener = vi.fn();
+ term.element.addEventListener('wheel', xtermListener);
+ const detach = attachTerminalWheelScroll(term);
+ const event = new WheelEvent('wheel', { deltaY: -120, bubbles: true, cancelable: true });
+
+ term.element.dispatchEvent(event);
+
+ expect(term.input).toHaveBeenCalledWith('\x1b[5~', false);
+ expect(xtermListener).not.toHaveBeenCalled();
+ expect(event.defaultPrevented).toBe(true);
+ detach();
+ });
+
+ it('maps a downward wheel to PageDown', () => {
+ const term = makeTerminal();
+ const detach = attachTerminalWheelScroll(term);
+ term.element.dispatchEvent(new WheelEvent('wheel', { deltaY: 1, bubbles: true, cancelable: true }));
+ expect(term.input).toHaveBeenCalledWith('\x1b[6~', false);
+ detach();
+ });
+
+ it('leaves normal-buffer wheel input to xterm', () => {
+ const term = makeTerminal({ alt: false });
+ const xtermListener = vi.fn();
+ term.element.addEventListener('wheel', xtermListener);
+ const detach = attachTerminalWheelScroll(term);
+ const event = new WheelEvent('wheel', { deltaY: -120, bubbles: true, cancelable: true });
+ term.element.dispatchEvent(event);
+ expect(term.input).not.toHaveBeenCalled();
+ expect(xtermListener).toHaveBeenCalledTimes(1);
+ expect(event.defaultPrevented).toBe(false);
+ detach();
+ });
+
+ it('leaves shift-wheel input alone for browser horizontal-scroll behavior', () => {
+ const term = makeTerminal();
+ const xtermListener = vi.fn();
+ term.element.addEventListener('wheel', xtermListener);
+ const detach = attachTerminalWheelScroll(term);
+ const event = new WheelEvent('wheel', { deltaY: -120, shiftKey: true, bubbles: true, cancelable: true });
+ term.element.dispatchEvent(event);
+ expect(term.input).not.toHaveBeenCalled();
+ expect(xtermListener).toHaveBeenCalledTimes(1);
+ detach();
+ });
+
+ it('detaches the wheel listener', () => {
+ const term = makeTerminal();
+ const detach = attachTerminalWheelScroll(term);
+ detach();
+ term.element.dispatchEvent(new WheelEvent('wheel', { deltaY: -120, bubbles: true, cancelable: true }));
+ expect(term.input).not.toHaveBeenCalled();
+ });
+});
+
describe('attachTerminalTouchScroll', () => {
- it('scrolls the alternate buffer on a one-finger drag, and swallows the gesture', () => {
- const term = makeTerminal({ rows: 24, height: 480 }); // 20px rows
- const wheels = captureWheels(term);
+ it('scrolls an alternate buffer after a half-viewport drag', () => {
+ const term = makeTerminal({ rows: 24, height: 480 }); // 20px rows, 240px page threshold
const detach = attachTerminalTouchScroll(term);
term.element.dispatchEvent(touchEvent('touchstart', [300]));
- // Finger moves DOWN 60px → pull older output into view → three lines of scroll up.
- const move = touchEvent('touchmove', [360]);
+ // Finger moves DOWN 260px → pull older output into view.
+ const move = touchEvent('touchmove', [560]);
term.element.dispatchEvent(move);
- expect(wheels.map((ev) => ev.deltaY)).toEqual([-1, -1, -1]);
+ expect(term.input).toHaveBeenCalledWith('\x1b[5~', false);
expect(move.defaultPrevented).toBe(true);
detach();
});
- it('scrolls down when the finger moves up', () => {
+ it('scrolls down when the alternate-buffer finger moves up', () => {
const term = makeTerminal({ rows: 24, height: 480 });
- const wheels = captureWheels(term);
const detach = attachTerminalTouchScroll(term);
term.element.dispatchEvent(touchEvent('touchstart', [300]));
- term.element.dispatchEvent(touchEvent('touchmove', [260]));
- expect(wheels.map((ev) => ev.deltaY)).toEqual([1, 1]);
+ term.element.dispatchEvent(touchEvent('touchmove', [40]));
+ expect(term.input).toHaveBeenCalledWith('\x1b[6~', false);
detach();
});
- it('scrolls an ordinary shell session too — xterm 6 binds no touch handlers at all', () => {
+ it('scrolls an ordinary shell session row-by-row', () => {
const term = makeTerminal({ alt: false, rows: 24, height: 480 });
const detach = attachTerminalTouchScroll(term);
term.element.dispatchEvent(touchEvent('touchstart', [300]));
@@ -197,23 +228,21 @@ describe('attachTerminalTouchScroll', () => {
it('leaves a sub-row drag alone so a tap still reaches the TUI', () => {
const term = makeTerminal({ rows: 24, height: 480 });
- const wheels = captureWheels(term);
const detach = attachTerminalTouchScroll(term);
term.element.dispatchEvent(touchEvent('touchstart', [300]));
const move = touchEvent('touchmove', [305]);
term.element.dispatchEvent(move);
- expect(wheels).toHaveLength(0);
+ expect(term.input).not.toHaveBeenCalled();
expect(move.defaultPrevented).toBe(false);
detach();
});
- it('still scrolls when the terminal has not been laid out (fallback row height)', () => {
- const term = makeTerminal({ rows: 24, height: 0 });
- const wheels = captureWheels(term);
+ it('still scrolls an alternate buffer before layout is available', () => {
+ const term = makeTerminal({ rows: 24, height: 0 }); // 18px fallback, 216px threshold
const detach = attachTerminalTouchScroll(term);
term.element.dispatchEvent(touchEvent('touchstart', [300]));
- term.element.dispatchEvent(touchEvent('touchmove', [336])); // 36px / 18px rows
- expect(wheels).toHaveLength(2);
+ term.element.dispatchEvent(touchEvent('touchmove', [520]));
+ expect(term.input).toHaveBeenCalledWith('\x1b[5~', false);
detach();
});
@@ -229,39 +258,35 @@ describe('attachTerminalTouchScroll', () => {
});
it('ignores a two-finger gesture (pinch-zoom belongs to the browser)', () => {
- const term = makeTerminal({ rows: 24, height: 480 });
- const wheels = captureWheels(term);
+ const term = makeTerminal();
const detach = attachTerminalTouchScroll(term);
term.element.dispatchEvent(touchEvent('touchstart', [300, 400]));
term.element.dispatchEvent(touchEvent('touchmove', [200, 500]));
- expect(wheels).toHaveLength(0);
+ expect(term.input).not.toHaveBeenCalled();
detach();
});
it('does not carry drag distance across separate gestures', () => {
- const term = makeTerminal({ rows: 24, height: 480 });
- const wheels = captureWheels(term);
+ const term = makeTerminal({ alt: false, rows: 24, height: 480 });
const detach = attachTerminalTouchScroll(term);
term.element.dispatchEvent(touchEvent('touchstart', [300]));
term.element.dispatchEvent(touchEvent('touchmove', [315]));
term.element.dispatchEvent(touchEvent('touchend', []));
- expect(wheels).toHaveLength(0);
- // A fresh 15px drag totals 30px — over one 20px row — only if the first
- // gesture's remainder leaked through.
+ expect(term.scrollLines).not.toHaveBeenCalled();
+ // A fresh 15px drag must not combine with the first gesture's remainder.
term.element.dispatchEvent(touchEvent('touchstart', [300]));
term.element.dispatchEvent(touchEvent('touchmove', [315]));
- expect(wheels).toHaveLength(0);
+ expect(term.scrollLines).not.toHaveBeenCalled();
detach();
});
it('detaches every listener', () => {
- const term = makeTerminal({ rows: 24, height: 480 });
- const wheels = captureWheels(term);
+ const term = makeTerminal();
const detach = attachTerminalTouchScroll(term);
detach();
term.element.dispatchEvent(touchEvent('touchstart', [300]));
- term.element.dispatchEvent(touchEvent('touchmove', [400]));
- expect(wheels).toHaveLength(0);
+ term.element.dispatchEvent(touchEvent('touchmove', [600]));
+ expect(term.input).not.toHaveBeenCalled();
});
it('returns a safe no-op when the terminal has no element yet', () => {