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

stop voice dictation from garbling shell input by forwarding edits as a diff

[._.]/ Adam Eivy5d7ba134c9fa
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 90cf5d8fee..2ff861cb04 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -1,5 +1,6 @@
## Fixed
+- Voice dictation into the Shell terminal no longer garbles what you said. Apple dictation streams progressively refined guesses and rewrites what it already typed ("determin" → "determine" → "determines"); the terminal forwarded every insertion but none of the matching deletions, so a dictated sentence arrived at the prompt as an accumulating pile-up ("ddedeterdetermindeterminedetermines if any code…"). Dictation edits are now translated into the deletions and insertions a terminal understands, so the prompt shows the sentence you dictated.
- Tapping the notifications bell on a phone now opens a panel that stays on screen. It was anchored to the bell — which sits mid-screen in the sidebar — so the panel ran off the right edge, clipping notification titles and putting every per-item dismiss button and the mark-all/clear-all controls out of reach with nothing to scroll to them.
- The notification panel's "+N more notifications" line is now a "Show N more" button, so the notifications past the first ten can be read and dismissed instead of being permanently unreachable.
- Notification dismiss and "Mark read" buttons are now full-size, always-visible tap targets on touch devices — they were sized to their bare icon, and the dismiss button was only revealed on hover, which a phone has no way to do.
diff --git a/client/src/hooks/useShellSession.js b/client/src/hooks/useShellSession.js
index bf7368f1f8..6a228937f5 100644
--- a/client/src/hooks/useShellSession.js
+++ b/client/src/hooks/useShellSession.js
@@ -8,6 +8,7 @@ import '@xterm/xterm/css/xterm.css';
import { useSocket } from './useSocket';
import { useThemeContext } from '../components/ThemeContext';
import { buildTerminalTheme, parseCssColorToHex } from '../lib/terminalTheme';
+import { attachDictationBridge } from '../lib/terminalDictation';
import { readFileAsBase64 } from '../utils/fileUpload';
import * as api from '../services/api';
import toast from '../components/ui/Toast';
@@ -313,15 +314,31 @@ export function useShellSession({ isFullscreen } = {}) {
useEffect(() => {
if (!termInstanceRef.current || !socket) return;
- const disposable = termInstanceRef.current.onData((data) => {
- // Drop keystrokes during a pending start/attach so they don't land in the previous
- // session — the terminal has already been cleared and "Attaching…" is showing.
+ // Drop keystrokes during a pending start/attach so they don't land in the previous
+ // session — the terminal has already been cleared and "Attaching…" is showing.
+ const send = (data) => {
if (sessionIdRef.current && !pendingAttachRef.current.target) {
socket.emit('shell:input', { sessionId: sessionIdRef.current, data });
}
+ };
+
+ const disposable = termInstanceRef.current.onData(send);
+
+ // Voice dictation (iOS mic key, macOS Fn Fn) streams progressively refined
+ // guesses and rewrites what it already typed. xterm forwards each insertion
+ // and ignores the matching deletions, so the PTY accumulates the garble
+ // ("determin" + "determine" + "determines"…). The bridge intercepts the
+ // hidden textarea and forwards a diff (DELs + additions) instead.
+ const detachDictation = attachDictationBridge({
+ container: terminalRef.current,
+ textarea: termInstanceRef.current.textarea,
+ sendData: send,
});
- return () => disposable.dispose();
+ return () => {
+ disposable.dispose();
+ detachDictation();
+ };
}, [socket]);
const clearActiveSession = useCallback(() => {
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 35c2a8db7d..ecbdc09495 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -168,6 +168,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `streakGlyph.js` | `streakGlyph(streak)` — the single POST streak emoji (✨ / ⚡ / 🔥 by day count) shared by the POST launcher, Morse trainer, daily widget, and dashboard streak widget. |
| `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({ container, textarea, sendData })` binds capture-phase listeners on the terminal container — ahead of xterm's own textarea listeners — and forwards a diff instead: `DEL` per dropped character, then the added text. Paths that reach the PTY some other way (a keystroke xterm handles itself, paste, blur, composition end) resync the mirror without emitting. `diffToTerminalInput(mirror, next, floor)` is the pure diff, where `floor` is the prefix we did not write and must never rewind through; `commonPrefixLength(a, b)` and `DEL` are exported for callers/tests. 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. |
| `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. |
| `threejsRig.js` | `summarizeThreejsArticulation(spec)` → `{ articulationReady, jointCount, socketCount, attachmentCount, jointsByPartId }` — client mirror of the readiness rule in `server/lib/threejsModelRig.js`, used by the Three.js Models preview, which is handed a bare spec rather than the record's stored report (and gets none at all for a model generated before rig readiness shipped). A spec with no `articulation` key reads as a static assembly; a graph is ready only when it carries more than a lone root and every child joint names a pivot socket. `jointsByPartId` is null-prototype so a provider-authored part id cannot resolve to an inherited function. |
diff --git a/client/src/lib/index.js b/client/src/lib/index.js
index f44ba9d5ed..a7e16f749f 100644
--- a/client/src/lib/index.js
+++ b/client/src/lib/index.js
@@ -134,6 +134,7 @@ export * from './spriteWalkUnlock.js';
export * from './streakGlyph.js';
export * from './syncCounts.js';
export * from './tabNotation.js';
+export * from './terminalDictation.js';
export * from './terminalTheme.js';
export * from './threejsExplode.js';
export * from './threejsRig.js';
diff --git a/client/src/lib/terminalDictation.js b/client/src/lib/terminalDictation.js
new file mode 100644
index 0000000000..75c5227a9e
--- /dev/null
+++ b/client/src/lib/terminalDictation.js
@@ -0,0 +1,144 @@
+// Dictation/IME bridge for the xterm.js terminal.
+//
+// ── The bug this fixes ─────────────────────────────────────────────────────────
+// Apple dictation (iOS "mic" key, macOS Fn Fn) does not emit one final phrase —
+// it streams progressively refined guesses and REPLACES what it previously wrote
+// in the focused field. In a normal <textarea> that is invisible: the field's
+// value goes "dde" → "deter" → "determin" → "determines", each edit replacing the
+// last. xterm.js, though, is a character STREAM: its hidden textarea listener
+// (`CoreBrowserTerminal#_inputEvent`) forwards `inputType: 'insertText'` events
+// verbatim and ignores every deletion event, because a terminal has no notion of
+// "replace what I just sent". So each refinement is appended to the PTY and the
+// user gets the accumulated garble:
+//
+// ddedeterdetermindeterminedetermines ifdetermines if any code…
+//
+// ── The fix ────────────────────────────────────────────────────────────────────
+// Intercept textarea input events in the capture phase (on an ancestor, so we run
+// BEFORE xterm's own textarea listener) and forward a DIFF instead of the raw
+// insertion: DEL (0x7f) for each character the field dropped, then whatever it
+// gained. The textarea keeps accumulating exactly as the OS intends, and the PTY
+// sees the same edits a real text field would apply.
+//
+// Resync points (a keystroke xterm handles itself, blur, paste, composition end)
+// reset the mirror without emitting anything, because those paths send to the PTY
+// through xterm and may clear the textarea out from under us.
+
+// 0x7f — what a terminal expects for "erase the previous character".
+export const DEL = '\x7f';
+
+// Input events whose effect we translate into terminal input ourselves. Anything
+// outside this list (paste, undo, composition text, line breaks) is already
+// handled by xterm or the keydown path, so it only resyncs our mirror.
+const OWNED_INPUT_TYPES = new Set([
+ 'insertText',
+ 'insertReplacementText',
+ 'deleteContentBackward',
+ 'deleteContentForward',
+ 'deleteWordBackward',
+ 'deleteWordForward',
+ 'deleteSoftLineBackward',
+ 'deleteSoftLineForward',
+]);
+
+export const commonPrefixLength = (a, b) => {
+ const max = Math.min(a.length, b.length);
+ let i = 0;
+ while (i < max && a[i] === b[i]) i++;
+ return i;
+};
+
+/**
+ * Translate a text-field edit into terminal input.
+ *
+ * @param {string} mirror what the field held when we last forwarded it
+ * @param {string} next what the field holds now
+ * @param {number} floor how much of `mirror` predates our tracking. Characters
+ * below the floor reached the PTY some other way (typed keystrokes, a paste),
+ * so we must never emit DELs for them — rewinding there would eat text we
+ * didn't write. Diverging below the floor is only reachable by interleaving
+ * physical edits with dictation mid-phrase; we retype from the floor instead,
+ * which can duplicate a few characters but never deletes someone else's.
+ * @returns {string} the bytes to send to the PTY ('' when nothing changed)
+ */
+export const diffToTerminalInput = (mirror, next, floor = 0) => {
+ const common = commonPrefixLength(mirror, next);
+ if (common === mirror.length && common === next.length) return '';
+ const safeFloor = Math.max(0, Math.min(floor, mirror.length));
+ const rewindTo = Math.max(common, safeFloor);
+ return DEL.repeat(mirror.length - rewindTo) + next.slice(rewindTo);
+};
+
+/**
+ * Wire the dictation bridge onto a live xterm instance's hidden textarea.
+ *
+ * @param {object} params
+ * @param {HTMLElement} params.container — an ANCESTOR of the textarea (the element
+ * passed to `term.open()`). Listeners bind here in the capture phase so they run
+ * before xterm's own textarea listeners and can stop the event from reaching them.
+ * @param {HTMLTextAreaElement} params.textarea — `term.textarea`
+ * @param {(data: string) => void} params.sendData — forwards to the PTY
+ * @returns {() => void} dispose
+ */
+export const attachDictationBridge = ({ container, textarea, sendData }) => {
+ if (!container || !textarea || typeof sendData !== 'function') return () => {};
+
+ // What the textarea held the last time we reconciled it with the PTY.
+ let mirror = textarea.value || '';
+ // Length of `mirror` we did not put into the PTY ourselves — see diffToTerminalInput.
+ let floor = mirror.length;
+ let resyncTimer = null;
+
+ const resyncNow = () => {
+ resyncTimer = null;
+ mirror = textarea.value || '';
+ floor = mirror.length;
+ };
+
+ // Deferred: xterm's own handler runs after ours and may clear the textarea
+ // (Enter and Ctrl-C do), so read the field only once it has had its turn.
+ const scheduleResync = () => {
+ if (resyncTimer != null) return;
+ resyncTimer = setTimeout(resyncNow, 0);
+ };
+
+ const handleKeyDown = (ev) => {
+ // 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.
+ if (ev.keyCode === 229 || ev.isComposing) return;
+ scheduleResync();
+ };
+
+ const handleInput = (ev) => {
+ if (ev.target !== textarea) return;
+ // A real composition (IME candidate window) is xterm's CompositionHelper's job;
+ // it forwards the committed text on compositionend.
+ if (ev.isComposing) return;
+ const inputType = ev.inputType;
+ if (inputType && !OWNED_INPUT_TYPES.has(inputType)) {
+ resyncNow();
+ return;
+ }
+ // Ours: stop the event before xterm's textarea listener can append the raw
+ // insertion on top of what we're about to reconcile.
+ ev.stopPropagation();
+ const next = textarea.value || '';
+ const data = diffToTerminalInput(mirror, next, floor);
+ mirror = next;
+ if (data) sendData(data);
+ };
+
+ container.addEventListener('keydown', handleKeyDown, true);
+ container.addEventListener('input', handleInput, true);
+ // blur/compositionend don't bubble, but capture-phase listeners still see them.
+ container.addEventListener('blur', scheduleResync, true);
+ container.addEventListener('compositionend', scheduleResync, true);
+
+ return () => {
+ if (resyncTimer != null) clearTimeout(resyncTimer);
+ container.removeEventListener('keydown', handleKeyDown, true);
+ container.removeEventListener('input', handleInput, true);
+ container.removeEventListener('blur', scheduleResync, true);
+ container.removeEventListener('compositionend', scheduleResync, true);
+ };
+};
diff --git a/client/src/lib/terminalDictation.test.js b/client/src/lib/terminalDictation.test.js
new file mode 100644
index 0000000000..e9327c1bc6
--- /dev/null
+++ b/client/src/lib/terminalDictation.test.js
@@ -0,0 +1,189 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { DEL, commonPrefixLength, diffToTerminalInput, attachDictationBridge } from './terminalDictation.js';
+
+describe('commonPrefixLength', () => {
+ it('counts the shared leading characters', () => {
+ expect(commonPrefixLength('determin', 'determines')).toBe(8);
+ expect(commonPrefixLength('abc', 'abc')).toBe(3);
+ expect(commonPrefixLength('abc', 'xyz')).toBe(0);
+ expect(commonPrefixLength('', 'abc')).toBe(0);
+ });
+});
+
+describe('diffToTerminalInput', () => {
+ it('emits nothing when the field did not change', () => {
+ expect(diffToTerminalInput('hello', 'hello')).toBe('');
+ });
+
+ it('emits only the appended text when the field grew', () => {
+ expect(diffToTerminalInput('determin', 'determines')).toBe('es');
+ });
+
+ it('erases the replaced tail before retyping it', () => {
+ // The dictation case: the field replaced "termine" with "termines".
+ expect(diffToTerminalInput('determine', 'determined')).toBe('d');
+ expect(diffToTerminalInput('their', 'there')).toBe(`${DEL}${DEL}re`);
+ });
+
+ it('emits pure deletions when the field shrank', () => {
+ expect(diffToTerminalInput('hello', 'hell')).toBe(DEL);
+ expect(diffToTerminalInput('hello', '')).toBe(DEL.repeat(5));
+ });
+
+ it('never rewinds below the floor — it retypes instead of eating prior text', () => {
+ // 'ls ' reached the PTY as keystrokes (floor 3); only 'foo' is ours.
+ expect(diffToTerminalInput('ls foo', 'ls bar', 3)).toBe(`${DEL.repeat(3)}bar`);
+ // Divergence below the floor: retype from the floor, delete nothing under it.
+ expect(diffToTerminalInput('ls foo', 'xx bar', 3)).toBe(`${DEL.repeat(3)}bar`);
+ });
+
+ it('clamps a floor longer than the mirror', () => {
+ expect(diffToTerminalInput('ab', 'abc', 99)).toBe('c');
+ });
+});
+
+describe('attachDictationBridge', () => {
+ let container;
+ let textarea;
+ let sent;
+ let dispose;
+
+ const fireInput = (inputType) => {
+ const ev = new Event('input', { bubbles: true });
+ // jsdom has no InputEvent#inputType on a plain Event — set it explicitly.
+ Object.defineProperty(ev, 'inputType', { value: inputType });
+ textarea.dispatchEvent(ev);
+ return ev;
+ };
+
+ // Stands in for xterm's own textarea listener, which appends the raw insertion.
+ const attachXtermStub = () => {
+ const spy = vi.fn();
+ textarea.addEventListener('input', spy, true);
+ return spy;
+ };
+
+ beforeEach(() => {
+ vi.useFakeTimers();
+ container = document.createElement('div');
+ textarea = document.createElement('textarea');
+ container.appendChild(textarea);
+ document.body.appendChild(container);
+ sent = [];
+ dispose = attachDictationBridge({ container, textarea, sendData: (d) => sent.push(d) });
+ });
+
+ afterEach(() => {
+ dispose();
+ container.remove();
+ vi.useRealTimers();
+ });
+
+ it('is a no-op when wired with missing pieces', () => {
+ expect(attachDictationBridge({})()).toBeUndefined();
+ expect(attachDictationBridge({ container, textarea })()).toBeUndefined();
+ });
+
+ it('forwards a streaming dictation phrase without duplicating it', () => {
+ // Exactly the reported failure: Apple dictation rewrites its own guess.
+ for (const partial of ['dde', 'deter', 'determin', 'determine', 'determines', 'determines if any code']) {
+ textarea.value = partial;
+ fireInput('insertText');
+ }
+ // Replaying the emitted stream through a terminal-ish reducer must reproduce
+ // the field's final value — not the accumulated garble.
+ const rendered = sent.join('').split('').reduce((acc, ch) => (ch === DEL ? acc.slice(0, -1) : acc + ch), '');
+ expect(rendered).toBe('determines if any code');
+ });
+
+ it('stops the event before xterm can append the raw insertion', () => {
+ const xterm = attachXtermStub();
+ textarea.value = 'hi';
+ fireInput('insertText');
+ expect(xterm).not.toHaveBeenCalled();
+ expect(sent).toEqual(['hi']);
+ });
+
+ it('translates a dictation replacement into erase + retype', () => {
+ textarea.value = 'their';
+ fireInput('insertText');
+ textarea.value = 'there';
+ fireInput('insertReplacementText');
+ expect(sent).toEqual(['their', `${DEL}${DEL}re`]);
+ });
+
+ it('forwards soft-keyboard deletions', () => {
+ textarea.value = 'abc';
+ fireInput('insertText');
+ textarea.value = 'ab';
+ fireInput('deleteContentBackward');
+ expect(sent).toEqual(['abc', DEL]);
+ });
+
+ it('leaves unowned input types to xterm and resyncs the mirror', () => {
+ const xterm = attachXtermStub();
+ textarea.value = 'pasted';
+ fireInput('insertFromPaste');
+ expect(sent).toEqual([]);
+ expect(xterm).toHaveBeenCalledTimes(1);
+ // The paste is now part of the untouchable floor: a later dictation appends
+ // rather than erasing text xterm already sent.
+ textarea.value = 'pasted more';
+ fireInput('insertText');
+ expect(sent).toEqual([' more']);
+ });
+
+ it('ignores input that belongs to an in-progress composition', () => {
+ const xterm = attachXtermStub();
+ const ev = new Event('input', { bubbles: true });
+ Object.defineProperty(ev, 'inputType', { value: 'insertCompositionText' });
+ Object.defineProperty(ev, 'isComposing', { value: true });
+ textarea.value = 'か';
+ textarea.dispatchEvent(ev);
+ expect(sent).toEqual([]);
+ expect(xterm).toHaveBeenCalledTimes(1);
+ });
+
+ it('resyncs after a keystroke xterm handles itself', () => {
+ textarea.value = 'abc';
+ fireInput('insertText');
+ // Enter: xterm sends CR and clears the textarea.
+ textarea.dispatchEvent(new KeyboardEvent('keydown', { keyCode: 13, bubbles: true }));
+ textarea.value = '';
+ vi.runAllTimers();
+ // Next dictation starts from a clean mirror — no phantom DELs for 'abc'.
+ textarea.value = 'next';
+ fireInput('insertText');
+ expect(sent).toEqual(['abc', 'next']);
+ });
+
+ it('does not resync on the composition keycode soft keyboards report', () => {
+ textarea.dispatchEvent(new KeyboardEvent('keydown', { keyCode: 229, bubbles: true }));
+ textarea.value = 'ab';
+ fireInput('insertText');
+ vi.runAllTimers();
+ textarea.value = 'abc';
+ fireInput('insertText');
+ expect(sent).toEqual(['ab', 'c']);
+ });
+
+ it('resyncs on blur, which clears xterm\'s textarea', () => {
+ textarea.value = 'abc';
+ fireInput('insertText');
+ textarea.dispatchEvent(new FocusEvent('blur'));
+ textarea.value = '';
+ vi.runAllTimers();
+ textarea.value = 'fresh';
+ fireInput('insertText');
+ expect(sent).toEqual(['abc', 'fresh']);
+ });
+
+ it('detaches every listener on dispose', () => {
+ dispose();
+ const xterm = attachXtermStub();
+ textarea.value = 'after';
+ fireInput('insertText');
+ expect(sent).toEqual([]);
+ expect(xterm).toHaveBeenCalledTimes(1);
+ });
+});