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

tighten the dictation bridge: reuse emitShellInput, take the terminal, pin the seam

[._.]/ Adam Eivy75c41bde70d1
diff --git a/client/src/hooks/useShellSession.js b/client/src/hooks/useShellSession.js
index 6a228937f5..81f17e08f8 100644
--- a/client/src/hooks/useShellSession.js
+++ b/client/src/hooks/useShellSession.js
@@ -148,12 +148,15 @@ export function useShellSession({ isFullscreen } = {}) {
// focus:false skips returning keyboard focus to the terminal after sending — used by
// the nav-key hot buttons so repeated arrow taps on touch devices don't keep re-summoning
// the on-screen keyboard (input is delivered over the socket regardless of focus).
+ // Returns whether the data actually went out — the dictation bridge needs to know,
+ // since it tracks what the PTY has received to compute its next correction.
const emitShellInput = useCallback((data, { focus = true } = {}) => {
- if (!socket || !sessionIdRef.current) return;
+ if (!socket || !sessionIdRef.current) return false;
// Don't fire quick-commands into the prior session while a switch/start is mid-flight.
- if (pendingAttachRef.current.target) return;
+ if (pendingAttachRef.current.target) return false;
socket.emit('shell:input', { sessionId: sessionIdRef.current, data });
if (focus) termInstanceRef.current?.focus();
+ return true;
}, [socket]);
// Send a photo (plus an optional message) to whatever is running in the active
@@ -310,17 +313,13 @@ export function useShellSession({ isFullscreen } = {}) {
};
}, [refitTerminal]);
- // Handle terminal input
+ // Handle terminal input. emitShellInput already owns the "don't land keystrokes in
+ // the session we're leaving" guard (the terminal has been cleared and "Attaching…"
+ // is showing), so both input paths go through it rather than re-deriving it.
+ // focus:false — typing is already focused, and the bridge must not steal focus.
useEffect(() => {
- if (!termInstanceRef.current || !socket) return;
-
- // 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 });
- }
- };
+ if (!termInstanceRef.current) return;
+ const send = (data) => emitShellInput(data, { focus: false });
const disposable = termInstanceRef.current.onData(send);
@@ -328,18 +327,20 @@ export function useShellSession({ isFullscreen } = {}) {
// 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,
- });
-
+ // hidden textarea and forwards a diff (DELs + additions) instead. It sends
+ // straight to `send` rather than looping back through `terminal.input()`:
+ // onData's only consumer IS this emit, and the round trip would throw away
+ // the delivered/dropped signal the bridge needs to track the PTY.
+ const detachDictation = attachDictationBridge(termInstanceRef.current, send);
+
+ // Detach the DOM listeners first — at unmount the terminal-init effect's
+ // cleanup has already disposed the terminal, so nothing here should depend
+ // on xterm's disposable running successfully.
return () => {
- disposable.dispose();
detachDictation();
+ disposable.dispose();
};
- }, [socket]);
+ }, [emitShellInput]);
const clearActiveSession = useCallback(() => {
sessionIdRef.current = null;
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index ecbdc09495..3fb24e9779 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -168,7 +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`. |
+| `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. `diffToTerminalInput(mirror, next, floor)` is the pure diff, where `floor` is the prefix we did not write and must never rewind through. Wired in `useShellSession`; the test suite pins the seam against a real `Terminal`. |
| `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/terminalDictation.js b/client/src/lib/terminalDictation.js
index 75c5227a9e..ea7f8fce93 100644
--- a/client/src/lib/terminalDictation.js
+++ b/client/src/lib/terminalDictation.js
@@ -14,37 +14,45 @@
// 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.
+// Intercept textarea input events in the capture phase (on `terminal.element`, so
+// we run BEFORE xterm's own listener on the textarea inside it) 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.
+//
+// ── Boundaries ─────────────────────────────────────────────────────────────────
+// Corrections are streamed live, which assumes the far end treats 0x7f as "erase
+// the previous character" — true at a shell prompt and in the line editors of the
+// TUIs this page drives. In a full-screen app that binds DEL to something else, a
+// mid-phrase correction is as approximate as a human backspacing would be; live
+// echo is worth more here than a settle-then-send buffer that hides the words the
+// user is speaking. Because we stop the event before xterm sees it, xterm never
+// clears the textarea mid-phrase either, so the mirror grows for as long as the
+// dictation does (bounded by the next resync — Enter, Ctrl-C, or blur).
// 0x7f — what a terminal expects for "erase the previous character".
-export const DEL = '\x7f';
+export const TERMINAL_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',
-]);
+// Input events whose effect we translate into terminal input ourselves: text the
+// field gained, and every flavour of text it dropped. Anything else (paste, undo,
+// composition text, line breaks) is already handled by xterm or the keydown path
+// and only resyncs our mirror — an unknown future `insert*` type must fall through
+// to xterm rather than being double-sent by both of us.
+const isOwnedInput = (inputType) => (
+ !inputType
+ || inputType === 'insertText'
+ || inputType === 'insertReplacementText'
+ || inputType.startsWith('delete')
+);
-export const commonPrefixLength = (a, b) => {
+const commonPrefixLength = (a, b) => {
const max = Math.min(a.length, b.length);
let i = 0;
- while (i < max && a[i] === b[i]) i++;
+ while (i < max && a.charCodeAt(i) === b.charCodeAt(i)) i++;
return i;
};
@@ -53,52 +61,52 @@ export const commonPrefixLength = (a, b) => {
*
* @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.
+ * @param {number} floor how much of `mirror` reached the PTY some other way
+ * (typed keystrokes, a paste). We retype from the floor rather than rewinding
+ * through it, so a correction can never erase text we didn't write.
* @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);
+ const rewindTo = Math.min(mirror.length, Math.max(commonPrefixLength(mirror, next), floor));
+ const tail = next.slice(rewindTo);
+ // Pure append is the common case — skip building an empty DEL run for it.
+ return rewindTo === mirror.length ? tail : TERMINAL_DEL.repeat(mirror.length - rewindTo) + tail;
};
/**
- * Wire the dictation bridge onto a live xterm instance's hidden textarea.
+ * Wire the dictation bridge onto a live xterm instance.
*
- * @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
+ * @param {object} terminal — an xterm `Terminal`. Only its public surface is used:
+ * `element` (the container it mounted into, and an ancestor of `textarea`, so
+ * capture-phase listeners there run before xterm's own), `textarea`, `options`.
+ * @param {(data: string) => boolean|void} sendData — forwards to the PTY. Return
+ * `false` to report the data was dropped (e.g. mid session-switch); the mirror
+ * then treats it as text we didn't write instead of claiming the PTY has it.
* @returns {() => void} dispose
*/
-export const attachDictationBridge = ({ container, textarea, sendData }) => {
+export const attachDictationBridge = (terminal, sendData) => {
+ const container = terminal?.element;
+ const textarea = terminal?.textarea;
if (!container || !textarea || typeof sendData !== 'function') return () => {};
// What the textarea held the last time we reconciled it with the PTY.
- let mirror = textarea.value || '';
+ 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 || '';
+ 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;
+ // Physical typing is the hot path and leaves nothing to reconcile — xterm
+ // cancels those keydowns, so the textarea stays as empty as the mirror.
+ if (resyncTimer != null || (mirror === '' && textarea.value === '')) return;
resyncTimer = setTimeout(resyncNow, 0);
};
@@ -114,31 +122,36 @@ export const attachDictationBridge = ({ container, textarea, sendData }) => {
// 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)) {
+ // 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;
}
// 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 next = textarea.value;
const data = diffToTerminalInput(mirror, next, floor);
+ // A refused send leaves the PTY exactly as it was, so leave the mirror there
+ // too — the next refinement then re-diffs against what the PTY really has
+ // instead of erasing characters that never arrived.
+ if (data && sendData(data) === false) return;
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);
+ const listeners = [
+ ['keydown', handleKeyDown],
+ ['input', handleInput],
+ ['blur', scheduleResync],
+ ['compositionend', scheduleResync],
+ ];
+ for (const [type, handler] of listeners) container.addEventListener(type, handler, 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);
+ clearTimeout(resyncTimer);
+ for (const [type, handler] of listeners) container.removeEventListener(type, handler, true);
};
};
diff --git a/client/src/lib/terminalDictation.test.js b/client/src/lib/terminalDictation.test.js
index e9327c1bc6..0330e57690 100644
--- a/client/src/lib/terminalDictation.test.js
+++ b/client/src/lib/terminalDictation.test.js
@@ -1,14 +1,14 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
-import { DEL, commonPrefixLength, diffToTerminalInput, attachDictationBridge } from './terminalDictation.js';
+import { Terminal } from '@xterm/xterm';
+import { TERMINAL_DEL as DEL, 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);
- });
-});
+// Replay an emitted terminal-input stream the way a line editor would, so a test
+// can assert "the prompt ends up holding what was dictated" rather than pinning
+// the exact byte sequence that gets it there.
+const render = (chunks) => chunks.join('').split('').reduce(
+ (acc, ch) => (ch === DEL ? acc.slice(0, -1) : acc + ch),
+ '',
+);
describe('diffToTerminalInput', () => {
it('emits nothing when the field did not change', () => {
@@ -20,8 +20,6 @@ describe('diffToTerminalInput', () => {
});
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`);
});
@@ -35,9 +33,7 @@ describe('diffToTerminalInput', () => {
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', () => {
+ // A floor past the end of the mirror clamps instead of emitting a negative run.
expect(diffToTerminalInput('ab', 'abc', 99)).toBe('c');
});
});
@@ -45,21 +41,20 @@ describe('diffToTerminalInput', () => {
describe('attachDictationBridge', () => {
let container;
let textarea;
+ let terminal;
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;
+ // Faithful to what a browser dispatches: dictation/soft-keyboard edits arrive
+ // as InputEvents carrying inputType, and the field value is already updated.
+ const fireInput = (inputType, data = null) => {
+ textarea.dispatchEvent(new InputEvent('input', { inputType, data, bubbles: true }));
};
// Stands in for xterm's own textarea listener, which appends the raw insertion.
const attachXtermStub = () => {
const spy = vi.fn();
- textarea.addEventListener('input', spy, true);
+ textarea.addEventListener('input', spy);
return spy;
};
@@ -69,8 +64,9 @@ describe('attachDictationBridge', () => {
textarea = document.createElement('textarea');
container.appendChild(textarea);
document.body.appendChild(container);
+ terminal = { element: container, textarea, options: {} };
sent = [];
- dispose = attachDictationBridge({ container, textarea, sendData: (d) => sent.push(d) });
+ dispose = attachDictationBridge(terminal, (d) => { sent.push(d); });
});
afterEach(() => {
@@ -79,9 +75,9 @@ describe('attachDictationBridge', () => {
vi.useRealTimers();
});
- it('is a no-op when wired with missing pieces', () => {
- expect(attachDictationBridge({})()).toBeUndefined();
- expect(attachDictationBridge({ container, textarea })()).toBeUndefined();
+ it('does not attach or throw when the terminal has no DOM yet', () => {
+ expect(() => attachDictationBridge({}, () => {})()).not.toThrow();
+ expect(() => attachDictationBridge(terminal, null)()).not.toThrow();
});
it('forwards a streaming dictation phrase without duplicating it', () => {
@@ -90,10 +86,7 @@ describe('attachDictationBridge', () => {
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');
+ expect(render(sent)).toBe('determines if any code');
});
it('stops the event before xterm can append the raw insertion', () => {
@@ -117,7 +110,9 @@ describe('attachDictationBridge', () => {
fireInput('insertText');
textarea.value = 'ab';
fireInput('deleteContentBackward');
- expect(sent).toEqual(['abc', DEL]);
+ textarea.value = '';
+ fireInput('deleteWordBackward');
+ expect(sent).toEqual(['abc', DEL, DEL.repeat(2)]);
});
it('leaves unowned input types to xterm and resyncs the mirror', () => {
@@ -135,15 +130,38 @@ describe('attachDictationBridge', () => {
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);
+ textarea.dispatchEvent(new InputEvent('input', {
+ inputType: 'insertCompositionText', data: 'か', isComposing: true, bubbles: true,
+ }));
expect(sent).toEqual([]);
expect(xterm).toHaveBeenCalledTimes(1);
});
+ it('stays out of the way in screen-reader mode', () => {
+ const xterm = attachXtermStub();
+ terminal.options.screenReaderMode = true;
+ textarea.value = 'abc';
+ fireInput('insertText');
+ expect(sent).toEqual([]);
+ expect(xterm).toHaveBeenCalledTimes(1);
+ });
+
+ it('does not claim text the sink reports as dropped', () => {
+ dispose();
+ let delivered = false;
+ dispose = attachDictationBridge(terminal, (d) => { if (delivered) sent.push(d); return delivered; });
+ // Mid session-switch: the emit is refused, so the PTY never saw 'abc'.
+ textarea.value = 'abc';
+ fireInput('insertText');
+ delivered = true;
+ // Once sends land again the whole phrase goes out — no DELs for characters
+ // that never arrived, and no silently swallowed words.
+ textarea.value = 'abd';
+ fireInput('insertReplacementText');
+ expect(sent).toEqual(['abd']);
+ });
+
it('resyncs after a keystroke xterm handles itself', () => {
textarea.value = 'abc';
fireInput('insertText');
@@ -178,6 +196,13 @@ describe('attachDictationBridge', () => {
expect(sent).toEqual(['abc', 'fresh']);
});
+ it('arms no timer while typing leaves nothing to reconcile', () => {
+ const timer = vi.spyOn(globalThis, 'setTimeout');
+ textarea.dispatchEvent(new KeyboardEvent('keydown', { keyCode: 65, bubbles: true }));
+ expect(timer).not.toHaveBeenCalled();
+ timer.mockRestore();
+ });
+
it('detaches every listener on dispose', () => {
dispose();
const xterm = attachXtermStub();
@@ -187,3 +212,61 @@ describe('attachDictationBridge', () => {
expect(xterm).toHaveBeenCalledTimes(1);
});
});
+
+// The bridge's whole seam is "our capture-phase listener on terminal.element runs
+// before xterm's own listener on the textarea inside it". The stub above can't
+// prove that — only a real Terminal can, and this is what fails loudly if an
+// xterm upgrade moves or re-phases that listener.
+describe('attachDictationBridge against a real xterm Terminal', () => {
+ let container;
+ let terminal;
+
+ beforeEach(() => {
+ // xterm reads the device pixel ratio on open(); jsdom ships no matchMedia.
+ window.matchMedia = vi.fn(() => ({ matches: false, addListener() {}, removeListener() {} }));
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ terminal = new Terminal({ allowProposedApi: true });
+ terminal.open(container);
+ });
+
+ afterEach(() => {
+ terminal.dispose();
+ container.remove();
+ delete window.matchMedia;
+ });
+
+ // Each refinement replaces the field's whole contents, which is what Apple
+ // dictation does — `data` carries the text the field gained, exactly the value
+ // xterm's own handler forwards verbatim.
+ const dictate = (partials) => {
+ for (const partial of partials) {
+ terminal.textarea.value = partial;
+ terminal.textarea.dispatchEvent(new InputEvent('input', {
+ inputType: 'insertText', data: partial, bubbles: true,
+ }));
+ }
+ };
+
+ // The bug, pinned upstream. If a future @xterm/xterm starts reconciling these
+ // events itself this fails — at which point the bridge is double-handling and
+ // should go, rather than quietly fighting xterm for the same input.
+ it('garbles the phrase when xterm handles the events alone', () => {
+ const sent = [];
+ terminal.onData((d) => sent.push(d));
+ dictate(['dde', 'deter', 'determin', 'determine', 'determines']);
+ expect(sent.join('')).toBe('ddedeterdetermindeterminedetermines');
+ });
+
+ 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
+ // forwards behind our back shows up here too.
+ terminal.onData((d) => sent.push(d));
+ const dispose = attachDictationBridge(terminal, (d) => { sent.push(d); });
+ dictate(['dde', 'deter', 'determin', 'determine', 'determines']);
+ dispose();
+
+ expect(render(sent)).toBe('determines');
+ });
+});