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

make the Shell terminal scrollable by touch, and scrollable at all inside a TUI

[._.]/ Adam Eivyf5d865333676
diff --git a/client/src/components/shell/TerminalHotKeys.jsx b/client/src/components/shell/TerminalHotKeys.jsx
index 1ac6ee24be..f81fe16056 100644
--- a/client/src/components/shell/TerminalHotKeys.jsx
+++ b/client/src/components/shell/TerminalHotKeys.jsx
@@ -1,4 +1,4 @@
-import { OctagonX, ChevronsLeft, ClipboardPaste, ArrowUp, ArrowDown, ArrowLeft, ArrowRight, CornerDownLeft } from 'lucide-react';
+import { OctagonX, ChevronsLeft, ClipboardPaste, ArrowUp, ArrowDown, ArrowLeft, ArrowRight, CornerDownLeft, ChevronsUp, ChevronsDown } from 'lucide-react';
import ShellImageDrop from './ShellImageDrop';
// Hot buttons for arrow / Enter entry — handy on touch devices and for driving TUI
@@ -15,6 +15,16 @@ export const NAV_KEYS = [
{ label: 'Enter', Icon: CornerDownLeft, seq: '\r' },
];
+// Scrolling the VIEW is deliberately separate from the arrow keys above: an arrow
+// drives whatever the focused app does with a cursor key (history, menu selection),
+// while these move what you are looking at. They are the only pointer-free way to
+// scroll at all — xterm 6 binds no touch handlers, and a TUI's alternate screen has
+// no scrollback either. Mechanism in `lib/terminalScroll.js`.
+export const SCROLL_KEYS = [
+ { label: 'Scroll up', Icon: ChevronsUp, direction: -1 },
+ { label: 'Scroll down', Icon: ChevronsDown, direction: 1 },
+];
+
// Touch-friendly TUI-driving controls shared by the inline quick-commands toolbar
// and the fullscreen control bar: Ctrl+B/C, Paste (+ fallback paste input), Photo,
// and the arrow / Enter hot buttons. The Ctrl+B/C / Paste text labels collapse
@@ -22,7 +32,7 @@ export const NAV_KEYS = [
//
// `popoverPlacement` is which way the Photo composer opens — 'above' for the
// fullscreen bar, which is pinned to the bottom of the viewport.
-export default function TerminalHotKeys({ sendCtrlB, sendCtrlC, handlePaste, sendNavKey, showPasteInput, setShowPasteInput, pasteInputRef, handlePasteInputEvent, sendImage, popoverPlacement = 'below' }) {
+export default function TerminalHotKeys({ sendCtrlB, sendCtrlC, handlePaste, sendNavKey, scrollPage, showPasteInput, setShowPasteInput, pasteInputRef, handlePasteInputEvent, sendImage, popoverPlacement = 'below' }) {
return (
<>
<button
@@ -65,6 +75,18 @@ export default function TerminalHotKeys({ sendCtrlB, sendCtrlC, handlePaste, sen
)}
<ShellImageDrop onSend={sendImage} placement={popoverPlacement} />
<div className="w-px h-6 bg-port-border shrink-0" />
+ {SCROLL_KEYS.map((key) => (
+ <button
+ key={key.label}
+ onClick={() => scrollPage(key.direction)}
+ className="flex items-center justify-center px-2.5 py-1.5 bg-port-card hover:bg-port-border text-gray-300 hover:text-white rounded text-xs font-mono transition-colors border border-port-border min-h-[40px] min-w-[40px] shrink-0"
+ title={`${key.label} one screen`}
+ aria-label={`${key.label} one screen`}
+ >
+ <key.Icon size={14} />
+ </button>
+ ))}
+ <div className="w-px h-6 bg-port-border shrink-0" />
{/* Arrow / Enter hot buttons — touch-friendly TUI nav + shell history */}
{NAV_KEYS.map((key) => (
<button
diff --git a/client/src/hooks/useShellSession.js b/client/src/hooks/useShellSession.js
index 8c1c647e93..9fb25cf4f1 100644
--- a/client/src/hooks/useShellSession.js
+++ b/client/src/hooks/useShellSession.js
@@ -9,6 +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 { readFileAsBase64 } from '../utils/fileUpload';
import * as api from '../services/api';
import toast from '../components/ui/Toast';
@@ -223,6 +224,13 @@ export function useShellSession({ isFullscreen } = {}) {
emitShellInput(`\x1b${appCursor ? 'O' : '['}${key.code}`, { focus: false });
}, [emitShellInput]);
+ // Scroll the VIEW by one screenful — distinct from the arrow keys above, which
+ // drive whatever the TUI does with a cursor key. `direction` is -1 for up, 1 for
+ // down; lib/terminalScroll.js owns why this can't just be term.scrollPages().
+ const scrollPage = useCallback((direction) => {
+ scrollTerminalPage(termInstanceRef.current, direction);
+ }, []);
+
// Initialize terminal once
useEffect(() => {
if (!terminalRef.current || termInstanceRef.current) return;
@@ -245,6 +253,12 @@ 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).
+ const detachTouchScroll = attachTerminalTouchScroll(term);
+
requestAnimationFrame(() => {
fitAddon.fit();
});
@@ -253,6 +267,7 @@ export function useShellSession({ isFullscreen } = {}) {
fitAddonRef.current = fitAddon;
return () => {
+ detachTouchScroll();
term.dispose();
termInstanceRef.current = null;
fitAddonRef.current = null;
@@ -866,6 +881,7 @@ export function useShellSession({ isFullscreen } = {}) {
sendCtrlB,
sendCtrlC,
sendNavKey,
+ scrollPage,
restartSession,
stopSession,
startNewSession,
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index f3df429083..97623f6b34 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -178,6 +178,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `syncCounts.js` | Directional pending-sync counts for the Instances federation cards. `directionalCounts({ localMax, peerMax, ourCursor, peerCursorForUs })` → `{ toPull, toPush }` (each a non-negative Number, or `null` when unknown) from monotonic change-log seqs; `diffSeq(ahead, behind)` is the BigInt-safe clamp-at-zero subtraction (handles numeric strings past `MAX_SAFE_INTEGER`); `describeDirectional({ toPull, toPush })` renders the plain-language `{ state, text }` ("in sync" / "N to pull · M to push" / "checking…"). No React — `SyncStatusBadge` drives it. |
| `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`). |
| `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`. |
| `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. |
| `threejsExplode.js` | Disassembly + part-picking maths for the procedural sculpt spec, shared by the Three.js Models preview so explode and the picker agree on what "a part" is. `computeExplodeLayout(parts, amount)` → `{ offsets, meshOffsets, unitIds, growth }`: separation is a layout **scale about the model centre** (≈2× at full explode) plus a base clearance for parts sitting at the centre — never a uniform outward push, which slides the arrangement without opening gaps — where `offsets` add to a unit's own `position` and `meshOffsets` apply to a group around a container's own geometry (moving its group instead would drag its child units along), and `growth` measures how much the layout actually grew so the camera re-fits on real change. `buildPartSelectionIndex(parts)` → `{ owners, ancestry, names }` for click resolution, subtree highlight, and the selection label. All maps are null-prototype — part ids are provider-authored and `idSchema` accepts `toString`. `isReliefPart` / `isContainerPart` expose the shared part definition: a part flagged `explodeWithParent` is surface relief that rides its parent and resolves selection up to it (unless it has no parent to ride), every other geometry-bearing part is both a movable unit and a selectable component, a part whose descendants carry geometry is additionally descended through, and a part with no geometry in its subtree moves nothing. |
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
index 1fcc4e321c..c934faca87 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -143,6 +143,7 @@ export * from './streakGlyph.js';
export * from './syncCounts.js';
export * from './tabNotation.js';
export * from './terminalDictation.js';
+export * from './terminalScroll.js';
export * from './terminalTheme.js';
export * from './threejsAnimation.js';
export * from './threejsExplode.js';
diff --git a/client/src/lib/terminalScroll.js b/client/src/lib/terminalScroll.js
new file mode 100644
index 0000000000..0b71dd6151
--- /dev/null
+++ b/client/src/lib/terminalScroll.js
@@ -0,0 +1,181 @@
+// Scrolling the Shell terminal — by touch at all, and inside a full-screen TUI.
+//
+// Two separate gaps land on one primitive, which is why one module covers both:
+//
+// • xterm.js 6 has NO touch input path. Its viewport is VS Code's
+// SmoothScrollableElement: the scroll extent is virtual (there is no oversized
+// spacer element for the browser to scroll natively — the `.xterm-scroll-area`
+// of earlier versions is gone), and the only inputs it binds are `wheel` and
+// scrollbar drags; the vendored `Gesture` helper is never given a target. So a
+// swipe over the terminal does nothing at all, in ANY session. On a phone —
+// where watched agent runs are mostly read — that is the entire scroll story.
+//
+// • 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.
+//
+// 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()`.
+//
+// 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 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';
+
+// `.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) => {
+ const el = terminal?.element;
+ return el ? el.querySelector('.xterm-screen') || el : null;
+};
+
+/**
+ * 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.
+ */
+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.
+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.
+ */
+export const scrollTerminalLines = (terminal, lines, geometry) => {
+ const requested = Math.trunc(lines);
+ if (!terminal || !requested) return 0;
+
+ // Normal buffer: the scrollback is real and only the real API moves it — the
+ // viewport is virtual, so there is no native scroller a wheel event could drive.
+ if (!isAltBuffer(terminal)) {
+ terminal.scrollLines?.(requested);
+ 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;
+};
+
+/** 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));
+
+/**
+ * Convert accumulated drag distance into whole scroll steps, keeping the sub-row
+ * remainder so a slow drag adds up instead of being truncated away every frame.
+ * `accumPx` is positive when the finger moved UP (content scrolls down), matching the
+ * sign convention of `scrollTerminalLines`.
+ */
+export const planTouchScrollSteps = (accumPx, rowHeightPx) => {
+ if (!(rowHeightPx > 0)) return { steps: 0, remainderPx: accumPx };
+ const steps = Math.trunc(accumPx / rowHeightPx);
+ return { steps, remainderPx: accumPx - steps * 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.
+ */
+export const attachTerminalTouchScroll = (terminal) => {
+ const el = terminal?.element;
+ if (!el?.addEventListener) return () => {};
+
+ let lastY = null;
+ let accumPx = 0;
+ let geometry = null;
+
+ const end = () => { lastY = null; accumPx = 0; geometry = null; };
+
+ const onStart = (ev) => {
+ // Two fingers is a pinch-zoom, which belongs to the browser.
+ if (ev.touches?.length !== 1) return end();
+ lastY = ev.touches[0].clientY;
+ accumPx = 0;
+ geometry = measureTerminalGeometry(terminal);
+ };
+
+ const onMove = (ev) => {
+ if (lastY == null) return;
+ if (ev.touches?.length !== 1) return end();
+ const y = ev.touches[0].clientY;
+ accumPx += lastY - y;
+ lastY = y;
+ const { steps, remainderPx } = planTouchScrollSteps(accumPx, geometry.rowHeightPx);
+ 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);
+ };
+
+ el.addEventListener('touchstart', onStart, { passive: true });
+ el.addEventListener('touchmove', onMove, { passive: false });
+ el.addEventListener('touchend', end, { passive: true });
+ el.addEventListener('touchcancel', end, { passive: true });
+
+ return () => {
+ el.removeEventListener('touchstart', onStart);
+ el.removeEventListener('touchmove', onMove);
+ el.removeEventListener('touchend', end);
+ el.removeEventListener('touchcancel', end);
+ };
+};
diff --git a/client/src/lib/terminalScroll.test.js b/client/src/lib/terminalScroll.test.js
new file mode 100644
index 0000000000..f42a755fc5
--- /dev/null
+++ b/client/src/lib/terminalScroll.test.js
@@ -0,0 +1,271 @@
+import { describe, it, expect, vi, afterEach } from 'vitest';
+import {
+ measureTerminalGeometry,
+ planTouchScrollSteps,
+ scrollTerminalLines,
+ scrollTerminalPage,
+ attachTerminalTouchScroll,
+} 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".
+const makeTerminal = ({ alt = true, rows = 24, height = 480 } = {}) => {
+ const el = document.createElement('div');
+ const screen = document.createElement('div');
+ screen.className = 'xterm-screen';
+ el.appendChild(screen);
+ document.body.appendChild(el);
+ screen.getBoundingClientRect = () => ({ left: 100, top: 50, width: 800, height, right: 900, bottom: 50 + height });
+ return {
+ element: el,
+ rows,
+ buffer: { active: { type: alt ? 'alternate' : 'normal' } },
+ scrollLines: vi.fn(),
+ };
+};
+
+const touchEvent = (type, touches) => {
+ const ev = new Event(type, { bubbles: true, cancelable: true });
+ ev.touches = touches.map((clientY) => ({ clientY }));
+ 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);
+ });
+
+ 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 });
+ });
+});
+
+describe('planTouchScrollSteps', () => {
+ it('holds back a sub-row drag and carries the remainder into the next one', () => {
+ expect(planTouchScrollSteps(8, 20)).toEqual({ steps: 0, remainderPx: 8 });
+ expect(planTouchScrollSteps(24, 20)).toEqual({ steps: 1, remainderPx: 4 });
+ });
+
+ it('truncates toward zero in both directions', () => {
+ expect(planTouchScrollSteps(-45, 20)).toEqual({ steps: -2, remainderPx: -5 });
+ expect(planTouchScrollSteps(45, 20)).toEqual({ steps: 2, remainderPx: 5 });
+ });
+
+ it('is inert without a usable row height', () => {
+ expect(planTouchScrollSteps(120, 0)).toEqual({ steps: 0, remainderPx: 120 });
+ });
+});
+
+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);
+ });
+
+ it('dispatches one wheel event per line in the alternate buffer', () => {
+ 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);
+ });
+
+ it('scrolls down with a positive delta', () => {
+ 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);
+ });
+
+ 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);
+ });
+});
+
+describe('scrollTerminalPage', () => {
+ it('moves a screenful minus one row of overlap', () => {
+ const term = makeTerminal({ alt: false, rows: 24 });
+ scrollTerminalPage(term, -1);
+ expect(term.scrollLines).toHaveBeenCalledWith(-23);
+ scrollTerminalPage(term, 1);
+ expect(term.scrollLines).toHaveBeenCalledWith(23);
+ });
+
+ it('still moves a line on a one-row terminal', () => {
+ const term = makeTerminal({ alt: false, rows: 1 });
+ scrollTerminalPage(term, -1);
+ expect(term.scrollLines).toHaveBeenCalledWith(-1);
+ });
+});
+
+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);
+ 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]);
+ term.element.dispatchEvent(move);
+
+ expect(wheels.map((ev) => ev.deltaY)).toEqual([-1, -1, -1]);
+ expect(move.defaultPrevented).toBe(true);
+ detach();
+ });
+
+ it('scrolls down when the 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]);
+ detach();
+ });
+
+ it('scrolls an ordinary shell session too — xterm 6 binds no touch handlers at all', () => {
+ const term = makeTerminal({ alt: false, rows: 24, height: 480 });
+ const detach = attachTerminalTouchScroll(term);
+ term.element.dispatchEvent(touchEvent('touchstart', [300]));
+ const move = touchEvent('touchmove', [360]);
+ term.element.dispatchEvent(move);
+ expect(term.scrollLines).toHaveBeenCalledWith(-3);
+ expect(move.defaultPrevented).toBe(true);
+ detach();
+ });
+
+ 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(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);
+ const detach = attachTerminalTouchScroll(term);
+ term.element.dispatchEvent(touchEvent('touchstart', [300]));
+ term.element.dispatchEvent(touchEvent('touchmove', [336])); // 36px / 18px rows
+ expect(wheels).toHaveLength(2);
+ detach();
+ });
+
+ it('measures once per gesture rather than on every move', () => {
+ const term = makeTerminal({ rows: 24, height: 480 });
+ const screen = term.element.querySelector('.xterm-screen');
+ const detach = attachTerminalTouchScroll(term);
+ term.element.dispatchEvent(touchEvent('touchstart', [300]));
+ const measure = vi.spyOn(screen, 'getBoundingClientRect');
+ for (let y = 320; y <= 500; y += 20) term.element.dispatchEvent(touchEvent('touchmove', [y]));
+ expect(measure).not.toHaveBeenCalled();
+ detach();
+ });
+
+ it('ignores a two-finger gesture (pinch-zoom belongs to the browser)', () => {
+ const term = makeTerminal({ rows: 24, height: 480 });
+ const wheels = captureWheels(term);
+ const detach = attachTerminalTouchScroll(term);
+ term.element.dispatchEvent(touchEvent('touchstart', [300, 400]));
+ term.element.dispatchEvent(touchEvent('touchmove', [200, 500]));
+ expect(wheels).toHaveLength(0);
+ detach();
+ });
+
+ it('does not carry drag distance across separate gestures', () => {
+ 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', [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.
+ term.element.dispatchEvent(touchEvent('touchstart', [300]));
+ term.element.dispatchEvent(touchEvent('touchmove', [315]));
+ expect(wheels).toHaveLength(0);
+ detach();
+ });
+
+ it('detaches every listener', () => {
+ const term = makeTerminal({ rows: 24, height: 480 });
+ const wheels = captureWheels(term);
+ const detach = attachTerminalTouchScroll(term);
+ detach();
+ term.element.dispatchEvent(touchEvent('touchstart', [300]));
+ term.element.dispatchEvent(touchEvent('touchmove', [400]));
+ expect(wheels).toHaveLength(0);
+ });
+
+ it('returns a safe no-op when the terminal has no element yet', () => {
+ expect(() => attachTerminalTouchScroll(null)()).not.toThrow();
+ expect(() => attachTerminalTouchScroll({})()).not.toThrow();
+ });
+});
diff --git a/client/src/pages/Shell.jsx b/client/src/pages/Shell.jsx
index 0bf7a7b55f..6c92fa2e27 100644
--- a/client/src/pages/Shell.jsx
+++ b/client/src/pages/Shell.jsx
@@ -45,6 +45,7 @@ export default function Shell() {
sendCtrlB,
sendCtrlC,
sendNavKey,
+ scrollPage,
restartSession,
stopSession,
startNewSession,
@@ -208,6 +209,7 @@ export default function Shell() {
sendCtrlC={sendCtrlC}
handlePaste={handlePaste}
sendNavKey={sendNavKey}
+ scrollPage={scrollPage}
showPasteInput={showPasteInput}
setShowPasteInput={setShowPasteInput}
pasteInputRef={pasteInputRef}
@@ -291,6 +293,7 @@ export default function Shell() {
sendCtrlC={sendCtrlC}
handlePaste={handlePaste}
sendNavKey={sendNavKey}
+ scrollPage={scrollPage}
showPasteInput={showPasteInput}
setShowPasteInput={setShowPasteInput}
pasteInputRef={pasteInputRef}