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: deliver iOS/macOS dictation to the Shell terminal again

[._.]/ Adam Eivyd746a331f5da
diff --git a/client/src/components/shell/createShellTerminal.js b/client/src/components/shell/createShellTerminal.js
index 4fba31f3b4..132f763d82 100644
--- a/client/src/components/shell/createShellTerminal.js
+++ b/client/src/components/shell/createShellTerminal.js
@@ -43,9 +43,10 @@ export const createShellTerminal = (container, options = {}) => {
// Screen-reader mode is what makes xterm build its .xterm-accessibility
// live region — without it every rendered row stays aria-hidden and a
// screen-reader user focusing the terminal hears an empty textarea. It
- // also relaxes _keyDown's blanket preventDefault on resolved keys, which
- // the dictation bridge (lib/terminalDictation.js) is already written to
- // defer to.
+ // also relaxes _keyDown's blanket preventDefault on resolved keys and
+ // makes xterm ignore every textarea insertText event — so dictation (which
+ // fires no key events) reaches the PTY only through the dictation bridge
+ // (lib/terminalDictation.js), which accounts for both.
screenReaderMode: true,
...options,
});
diff --git a/client/src/hooks/useItermSession.js b/client/src/hooks/useItermSession.js
index 1efcbb4aad..e2c90e766e 100644
--- a/client/src/hooks/useItermSession.js
+++ b/client/src/hooks/useItermSession.js
@@ -7,6 +7,7 @@ import {
readTerminalTheme,
TERMINAL_SCROLLBACK_LINES,
} from '../components/shell/createShellTerminal';
+import { attachDictationBridge } from '../lib/terminalDictation';
export const ITERM_SHELL_PATH = '/shell/iterm';
@@ -86,11 +87,18 @@ export function useItermSession({ itermSessionId, enabled = true } = {}) {
}, [socket]);
// Keystrokes typed into the terminal go to the viewed iTerm2 session verbatim.
+ // Dictation takes the bridge (lib/terminalDictation.js): the terminal runs in
+ // screen-reader mode, where xterm drops the insertText events dictation fires.
useEffect(() => {
const term = termRef.current;
if (!term) return undefined;
- const disposable = term.onData((data) => emitInput(data, { focus: false }));
- return () => disposable.dispose();
+ const send = (data) => emitInput(data, { focus: false });
+ const disposable = term.onData(send);
+ const detachDictation = attachDictationBridge(term, send);
+ return () => {
+ detachDictation();
+ disposable.dispose();
+ };
}, [emitInput, enabled]);
// List subscription + event wiring.
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index fd352d74ec..b14f780dff 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -252,7 +252,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); `chordLineSegments`, `pairedLineChunks`, and `chordLyricRows` build aligned, word-wrapping chord/lyric display rows; `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`. |
+| `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) resync the mirror without emitting. In screen-reader mode xterm drops every `insertText` event and leaves handled keydowns uncancelled, so the bridge is the only path dictation has to the PTY and a live keydown counts as xterm's keystroke, like a keypress. `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`. |
| `terminalFit.js` | In-tree xterm sizing helper. `fitTerminal(terminal)` measures the parent and terminal CSS box, accounts for padding and the overview-ruler scrollbar, clamps the calculated geometry to at least 2 columns × 1 row, and resizes only when the dimensions change. |
| `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. |
diff --git a/client/src/lib/terminalDictation.js b/client/src/lib/terminalDictation.js
index c986d95696..5ac123bbfb 100644
--- a/client/src/lib/terminalDictation.js
+++ b/client/src/lib/terminalDictation.js
@@ -41,6 +41,13 @@
// xterm's: it counts as a resync point, not ours to forward, and the event goes
// through untouched.
//
+// Screen-reader mode widens the seam to keydown. There xterm sends a resolved key
+// from `_keyDown` and deliberately does NOT cancel it (so the textarea keeps the
+// text for the screen reader to announce) — lowercase letters, digits, Backspace
+// all land in the field and fire `input` for bytes the PTY already has. So in that
+// mode a live keydown latches the same way a keypress does. Outside it, a handled
+// keydown is cancelled and never reaches the field.
+//
// We mirror `_keyPressHandled` and only that flag. xterm's `_inputEvent` also gates
// on `_keyDownSeen` and clears an `_unprocessedDeadKey`; the omissions are
// deliberate, because our own resync points already cover both — the keydown resync
@@ -133,8 +140,9 @@ export const attachDictationBridge = (terminal, sendData) => {
// Length of `mirror` we did not put into the PTY ourselves — see planFieldEdit.
let floor = mirror.length;
let resyncTimer = null;
- // Set on `keypress`, consumed by the next event — see "The keypress seam" above.
- let keyPressSeen = false;
+ // Set on `keypress` (and, in screen-reader mode, on keydown), consumed by the next
+ // event — see "The keypress seam" above.
+ let keyStrokeSeen = false;
const cancelResync = () => {
clearTimeout(resyncTimer);
@@ -157,16 +165,18 @@ export const attachDictationBridge = (terminal, sendData) => {
};
const handleKeyDown = (ev) => {
- // Whatever this keystroke inserts is xterm's only if a keypress follows it.
- keyPressSeen = false;
+ // Whatever this keystroke inserts is xterm's only if a keypress follows it —
+ // or, in screen-reader mode, already, because xterm sent it from keydown.
+ keyStrokeSeen = false;
// 229 is the "composition character" every soft keyboard/IME reports — those
// keystrokes land in the textarea and are ours to diff, not a resync point.
// They fire no keypress either, which is what keeps them ours below.
if (ev.keyCode === 229 || ev.isComposing) return;
+ if (terminal.options?.screenReaderMode) keyStrokeSeen = true;
scheduleResync();
};
- const handleKeyPress = () => { keyPressSeen = true; };
+ const handleKeyPress = () => { keyStrokeSeen = true; };
// The insertion a keypress produces can fail to arrive (the browser consumes the
// combination itself, focus leaves mid-keystroke). Disarm on keyup — as xterm's
@@ -175,10 +185,10 @@ export const attachDictationBridge = (terminal, sendData) => {
// all, so waiting for another keydown to clear it would swallow a dictated phrase.
// `input` fires during the keypress default action, long before keyup, so this
// never races the consume.
- const disarmKeyPress = () => { keyPressSeen = false; };
+ const disarmKeyStroke = () => { keyStrokeSeen = false; };
const handleBlur = () => {
- disarmKeyPress();
+ disarmKeyStroke();
scheduleResync();
};
@@ -188,17 +198,14 @@ export const attachDictationBridge = (terminal, sendData) => {
// keypress seam"). Take the insertion into the floor so a later correction can't
// rewind through it, and leave the event alone. Consumed ahead of the guards
// below so the latch is strictly one-shot.
- if (keyPressSeen) {
- disarmKeyPress();
+ if (keyStrokeSeen) {
+ disarmKeyStroke();
resyncNow();
return;
}
// A real composition (IME candidate window) is xterm's CompositionHelper's job;
// it forwards the committed text on compositionend.
if (ev.isComposing) return;
- // Screen-reader mode is the one configuration where xterm deliberately lets
- // these events through so the textarea can be read out — stay out of the way.
- if (terminal.options?.screenReaderMode) return;
if (!isOwnedInput(ev.inputType)) {
resyncNow();
return;
@@ -225,7 +232,7 @@ export const attachDictationBridge = (terminal, sendData) => {
const listeners = [
['keydown', handleKeyDown],
['keypress', handleKeyPress],
- ['keyup', disarmKeyPress],
+ ['keyup', disarmKeyStroke],
['input', handleInput],
['blur', handleBlur],
['compositionend', scheduleResync],
diff --git a/client/src/lib/terminalDictation.test.js b/client/src/lib/terminalDictation.test.js
index 25d7383211..e2101137c6 100644
--- a/client/src/lib/terminalDictation.test.js
+++ b/client/src/lib/terminalDictation.test.js
@@ -171,13 +171,28 @@ describe('attachDictationBridge', () => {
expect(xterm).toHaveBeenCalledTimes(1);
});
- it('stays out of the way in screen-reader mode', () => {
- const xterm = attachXtermStub();
+ it('forwards dictation in screen-reader mode', () => {
+ // xterm ignores every insertText in this mode, so the bridge is the only
+ // path a dictated phrase has to the PTY.
terminal.options.screenReaderMode = true;
textarea.value = 'abc';
fireInput('insertText');
+ expect(sent).toEqual(['abc']);
+ });
+
+ it('leaves a keydown-sent insertion to xterm in screen-reader mode', () => {
+ // xterm sends the key from keydown without cancelling it, so the browser
+ // then inserts it into the field — no keypress involved.
+ terminal.options.screenReaderMode = true;
+ fireKey('keydown', 65);
+ textarea.value = 'a';
+ fireInput('insertText');
+ fireKey('keyup', 65);
+ fireKey('keydown', 8);
+ textarea.value = '';
+ fireInput('deleteContentBackward');
+ fireKey('keyup', 8);
expect(sent).toEqual([]);
- expect(xterm).toHaveBeenCalledTimes(1);
});
it('does not claim text the sink reports as dropped', () => {
@@ -379,6 +394,32 @@ describe('attachDictationBridge against a real xterm Terminal', () => {
expect(sent).toEqual(['T', ' ', 'X', ' ']);
});
+ // The Shell page runs xterm in screen-reader mode (createShellTerminal), where
+ // xterm drops every insertText event: dictation, which fires no key events,
+ // never reached the PTY at all. If an upgrade starts forwarding these, the
+ // first assertion fails and the bridge would double-send in this mode.
+ it('delivers dictation in screen-reader mode, where xterm alone drops it', () => {
+ terminal.options.screenReaderMode = true;
+ const sent = [];
+ terminal.onData((d) => sent.push(d));
+ dictate(['hello']);
+ expect(sent).toEqual([]);
+
+ terminal.textarea.value = '';
+ const dispose = attachDictationBridge(terminal, (d) => { sent.push(d); });
+ dictate(['dde', 'deter', 'determines']);
+ // A lowercase key xterm sends from keydown without cancelling it: the browser
+ // then inserts it into the field, and it must not go out twice.
+ const { textarea } = terminal;
+ textarea.dispatchEvent(new KeyboardEvent('keydown', { key: 'x', keyCode: 88, bubbles: true }));
+ textarea.value += 'x';
+ textarea.dispatchEvent(new InputEvent('input', { inputType: 'insertText', data: 'x', bubbles: true }));
+ textarea.dispatchEvent(new KeyboardEvent('keyup', { key: 'x', keyCode: 88, bubbles: true }));
+ dispose();
+
+ expect(render(sent)).toBe('determinesx');
+ });
+
it('sends the dictated phrase once, not the accumulated garble', () => {
const sent = [];
// onData is where xterm's own textarea handling would surface, so anything it