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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: add momentum to mobile shell scrollback
[._.]/ Adam Eivyb191d6870a71
diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex c00d302c41..dbe15605ad 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -229,7 +229,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, 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, while apps that explicitly enable terminal mouse tracking keep xterm’s native wheel path. `attachTerminalTouchScroll(terminal)` (→ detach fn) reserves one-finger panning while preserving pinch zoom; mouse-aware apps receive row-granular wheel events at the touch coordinates, and only apps without wheel support fall back to page keys. `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`. |+| `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, while apps that explicitly enable terminal mouse tracking keep xterm’s native wheel path. `attachTerminalTouchScroll(terminal)` (→ detach fn) reserves one-finger panning while preserving pinch zoom and adds bounded flick momentum to normal shell scrollback; mouse-aware apps receive row-granular wheel events at the touch coordinates, and only apps without wheel support fall back to page keys. `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. || `textUtils.js` | `escapeRegExp(value)` and `countWords(text)` re-exported from `server/lib/textUtils.js` — the two members the bundle has callers for (the Writers Room editor and exercise panel and the autobiography tab count words with the same `\S+` rule the server stores). Named exports rather than `export *`, so the file stays the list of what the browser actually uses. || `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. |diff --git a/client/src/lib/terminalScroll.js b/client/src/lib/terminalScroll.jsindex 6eb3c66489..9bece907a6 100644--- a/client/src/lib/terminalScroll.js+++ b/client/src/lib/terminalScroll.js@@ -88,10 +88,14 @@ const wheelDeltaLines = (event, rowHeightPx) => {};const wheelScrollResetters = new WeakMap();+const touchScrollResetters = new WeakMap();-/** Clear fractional wheel state before a reused terminal starts a new session. */+/** Clear pending scroll gestures before a reused terminal starts a new session. */export const resetTerminalWheelScroll = (terminal) => {- if (terminal && typeof terminal === 'object') wheelScrollResetters.get(terminal)?.();+ if (terminal && typeof terminal === 'object') {+ wheelScrollResetters.get(terminal)?.();+ touchScrollResetters.get(terminal)?.();+ }};/**@@ -201,22 +205,76 @@ export const attachTerminalTouchScroll = (terminal) => {let lastY = null;let accumPx = 0;let geometry = null;+ let lastMoveAt = 0;+ let velocity = 0;+ let momentumFrame = null;++ const stopMomentum = () => {+ if (momentumFrame !== null) cancelAnimationFrame(momentumFrame);+ momentumFrame = null;+ };- const end = () => { lastY = null; accumPx = 0; geometry = null; };+ const end = () => {+ stopMomentum();+ lastY = null;+ accumPx = 0;+ geometry = null;+ velocity = 0;+ };++ const onEnd = () => {+ // Only local scrollback can coast safely. Sending delayed keys or mouse+ // reports could operate a different TUI after the finger has left the screen.+ const buffer = terminal.buffer?.active;+ if (lastY === null || isAltBuffer(terminal)+ || terminal.modes?.mouseTrackingMode !== 'none'+ || performance.now() - lastMoveAt > 80 || Math.abs(velocity) < 0.1) return end();+ lastY = null;+ let previousFrameAt = performance.now();+ const coast = (now) => {+ momentumFrame = null;+ if (terminal.buffer?.active !== buffer || isAltBuffer(terminal)+ || terminal.modes?.mouseTrackingMode !== 'none') return end();+ const elapsed = now - previousFrameAt;+ // A suspended tab must not replay a flick when it becomes visible again.+ if (elapsed > 80) return end();+ previousFrameAt = now;+ accumPx += velocity * elapsed;+ velocity *= Math.exp(-elapsed / 180);+ const { steps, remainderPx } = planTouchScrollSteps(accumPx, geometry.rowHeightPx);+ accumPx = remainderPx;+ if (steps) {+ const before = buffer.viewportY;+ terminal.scrollLines(steps);+ if (buffer.viewportY === before) return end();+ }+ if (Math.abs(velocity) < 0.1) return end();+ momentumFrame = requestAnimationFrame(coast);+ };+ momentumFrame = requestAnimationFrame(coast);+ };const onStart = (ev) => {+ end();// 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);+ lastMoveAt = performance.now();};const onMove = (ev) => {if (lastY == null) return;if (ev.touches?.length !== 1) return end();const y = ev.touches[0].clientY;- accumPx += lastY - y;+ const now = performance.now();+ const delta = lastY - y;+ const elapsed = now - lastMoveAt;+ // Cap release speed so a sparse event stream cannot fling thousands of rows.+ velocity = elapsed > 0 ? Math.max(-3, Math.min(3, delta / elapsed)) : 0;+ lastMoveAt = now;+ accumPx += delta;lastY = y;// Cancel even sub-row movement: it still belongs to this terminal gesture.if (ev.cancelable) ev.preventDefault();@@ -251,17 +309,21 @@ export const attachTerminalTouchScroll = (terminal) => {}};+ touchScrollResetters.set(terminal, end);el.addEventListener('touchstart', onStart, { passive: true });el.addEventListener('touchmove', onMove, { passive: false });- el.addEventListener('touchend', end, { passive: true });+ el.addEventListener('touchend', onEnd, { passive: true });+ el.addEventListener('wheel', stopMomentum, { passive: true });el.addEventListener('touchcancel', end, { passive: true });return () => {end();+ if (touchScrollResetters.get(terminal) === end) touchScrollResetters.delete(terminal);el.style.touchAction = previousTouchAction;el.removeEventListener('touchstart', onStart);el.removeEventListener('touchmove', onMove);- el.removeEventListener('touchend', end);+ el.removeEventListener('touchend', onEnd);+ el.removeEventListener('wheel', stopMomentum);el.removeEventListener('touchcancel', end);};};diff --git a/client/src/lib/terminalScroll.test.js b/client/src/lib/terminalScroll.test.jsindex 80532a3f15..d9d4f33fb5 100644--- a/client/src/lib/terminalScroll.test.js+++ b/client/src/lib/terminalScroll.test.js@@ -36,7 +36,7 @@ const touchEvent = (type, touches) => {return ev;};-afterEach(() => { document.body.innerHTML = ''; });+afterEach(() => { vi.useRealTimers(); document.body.innerHTML = ''; });describe('measureTerminalGeometry', () => {it('derives the row height from the rendered screen, not the outer container', () => {@@ -372,6 +372,51 @@ describe('attachTerminalTouchScroll', () => {detach();});+ it('coasts a shell flick and stops at the scrollback boundary', () => {+ vi.useFakeTimers();+ const term = makeTerminal({ alt: false });+ term.buffer.active.viewportY = 20;+ term.scrollLines.mockImplementation(lines => {+ term.buffer.active.viewportY = Math.max(0, term.buffer.active.viewportY + lines);+ });+ const detach = attachTerminalTouchScroll(term);+ term.element.dispatchEvent(touchEvent('touchstart', [300]));+ vi.advanceTimersByTime(20);+ term.element.dispatchEvent(touchEvent('touchmove', [340]));+ expect(term.buffer.active.viewportY).toBe(18);+ term.element.dispatchEvent(touchEvent('touchend', []));+ vi.advanceTimersByTime(48);+ expect(term.buffer.active.viewportY).toBeLessThan(18);+ vi.advanceTimersByTime(2000);+ const settled = term.scrollLines.mock.calls.length;+ vi.advanceTimersByTime(2000);+ expect(term.scrollLines).toHaveBeenCalledTimes(settled);+ detach();+ vi.useRealTimers();+ });++ it.each(['touchstart', 'touchcancel', 'wheel', 'detach', 'buffer', 'session reset'])('cancels a shell flick on %s', action => {+ vi.useFakeTimers();+ const term = makeTerminal({ alt: false });+ term.buffer.active.viewportY = 100;+ term.scrollLines.mockImplementation(lines => { term.buffer.active.viewportY += lines; });+ const detach = attachTerminalTouchScroll(term);+ term.element.dispatchEvent(touchEvent('touchstart', [300]));+ vi.advanceTimersByTime(20);+ term.element.dispatchEvent(touchEvent('touchmove', [340]));+ term.element.dispatchEvent(touchEvent('touchend', []));+ if (action === 'session reset') resetTerminalWheelScroll(term);+ else if (action === 'detach') detach();+ else if (action === 'buffer') term.buffer.active = { type: 'alternate' };+ else if (action === 'wheel') term.element.dispatchEvent(new WheelEvent('wheel'));+ else term.element.dispatchEvent(touchEvent(action, action === 'touchstart' ? [340] : []));+ vi.advanceTimersByTime(1000);+ expect(term.scrollLines).toHaveBeenCalledTimes(1);+ expect(term.input).not.toHaveBeenCalled();+ detach();+ vi.useRealTimers();+ });+it('detaches every listener', () => {const term = makeTerminal();const detach = attachTerminalTouchScroll(term);