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

address review (agy): keep the dictation mirror honest and stop splitting surrogate pairs

[._.]/ Adam Eivy6af21cbc9d20
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 3fb24e9779..a15f581cee 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(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`. |
+| `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`. |
| `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 ea7f8fce93..2145707b80 100644
--- a/client/src/lib/terminalDictation.js
+++ b/client/src/lib/terminalDictation.js
@@ -49,28 +49,40 @@ const isOwnedInput = (inputType) => (
|| inputType.startsWith('delete')
);
+const isHighSurrogate = (code) => code >= 0xd800 && code <= 0xdbff;
+
const commonPrefixLength = (a, b) => {
const max = Math.min(a.length, b.length);
let i = 0;
while (i < max && a.charCodeAt(i) === b.charCodeAt(i)) i++;
- return i;
+ // Never split a surrogate pair: cutting between the halves of an astral
+ // character (swapping 😀 for 😂 shares the high surrogate) would send a lone
+ // surrogate, which serializes to U+FFFD instead of the emoji.
+ return i > 0 && isHighSurrogate(a.charCodeAt(i - 1)) ? i - 1 : i;
};
/**
- * Translate a text-field edit into terminal input.
+ * Plan the terminal input for a text-field edit.
*
- * @param {string} mirror what the field held when we last forwarded it
+ * @param {string} mirror what the PTY holds from this field
* @param {string} next what the field holds now
* @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)
+ * @returns {{data: string, committed: string}} `data` is the bytes to send ('' when
+ * nothing changed); `committed` is what the PTY holds once they're applied. The
+ * two differ from `next` only when `floor` blocked a full rewind — the caller
+ * must track `committed`, not `next`, or every later diff is computed against a
+ * baseline the PTY never had.
*/
-export const diffToTerminalInput = (mirror, next, floor = 0) => {
+export const planFieldEdit = (mirror, next, floor = 0) => {
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;
+ return {
+ // Pure append is the common case — skip building an empty DEL run for it.
+ data: rewindTo === mirror.length ? tail : TERMINAL_DEL.repeat(mirror.length - rewindTo) + tail,
+ committed: mirror.slice(0, rewindTo) + tail,
+ };
};
/**
@@ -89,9 +101,10 @@ export const attachDictationBridge = (terminal, sendData) => {
const textarea = terminal?.textarea;
if (!container || !textarea || typeof sendData !== 'function') return () => {};
- // What the textarea held the last time we reconciled it with the PTY.
+ // What the PTY holds from this field. Usually equal to the textarea's value —
+ // it diverges only when `floor` blocked a full rewind (see planFieldEdit).
let mirror = textarea.value;
- // Length of `mirror` we did not put into the PTY ourselves — see diffToTerminalInput.
+ // Length of `mirror` we did not put into the PTY ourselves — see planFieldEdit.
let floor = mirror.length;
let resyncTimer = null;
@@ -132,13 +145,22 @@ export const attachDictationBridge = (terminal, sendData) => {
// 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);
+ // We are reconciling the field right now, so a resync armed by the keystroke
+ // that produced this event would only re-read the same value — and pin `floor`
+ // to the whole phrase, silently blocking every later correction from rewinding.
+ if (resyncTimer != null) {
+ clearTimeout(resyncTimer);
+ resyncTimer = null;
+ }
+ const { data, committed } = planFieldEdit(mirror, textarea.value, 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;
+ // `committed`, not the field's value: when `floor` blocked a full rewind the
+ // PTY holds the un-rewound prefix, and claiming otherwise desyncs every
+ // later diff.
+ mirror = committed;
};
// blur/compositionend don't bubble, but capture-phase listeners still see them.
diff --git a/client/src/lib/terminalDictation.test.js b/client/src/lib/terminalDictation.test.js
index 0330e57690..317548f38e 100644
--- a/client/src/lib/terminalDictation.test.js
+++ b/client/src/lib/terminalDictation.test.js
@@ -1,6 +1,6 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { Terminal } from '@xterm/xterm';
-import { TERMINAL_DEL as DEL, diffToTerminalInput, attachDictationBridge } from './terminalDictation.js';
+import { TERMINAL_DEL as DEL, planFieldEdit, attachDictationBridge } from './terminalDictation.js';
// 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
@@ -10,31 +10,51 @@ const render = (chunks) => chunks.join('').split('').reduce(
'',
);
-describe('diffToTerminalInput', () => {
+describe('planFieldEdit', () => {
+ const data = (...args) => planFieldEdit(...args).data;
+
it('emits nothing when the field did not change', () => {
- expect(diffToTerminalInput('hello', 'hello')).toBe('');
+ expect(data('hello', 'hello')).toBe('');
});
it('emits only the appended text when the field grew', () => {
- expect(diffToTerminalInput('determin', 'determines')).toBe('es');
+ expect(data('determin', 'determines')).toBe('es');
});
it('erases the replaced tail before retyping it', () => {
- expect(diffToTerminalInput('their', 'there')).toBe(`${DEL}${DEL}re`);
+ expect(data('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));
+ expect(data('hello', 'hell')).toBe(DEL);
+ expect(data('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`);
+ expect(data('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`);
+ expect(data('ls foo', 'xx bar', 3)).toBe(`${DEL.repeat(3)}bar`);
// A floor past the end of the mirror clamps instead of emitting a negative run.
- expect(diffToTerminalInput('ab', 'abc', 99)).toBe('c');
+ expect(data('ab', 'abc', 99)).toBe('c');
+ });
+
+ it('reports what the PTY holds, which is not the field when the floor blocked a rewind', () => {
+ // Normally the PTY ends up holding exactly what the field shows.
+ expect(planFieldEdit('their', 'there').committed).toBe('there');
+ // But 'ls ' is below the floor and was never rewound, so the PTY holds
+ // 'ls bar' even though the field reads 'xx bar'. Tracking the field here
+ // would make every later diff rewind against a baseline that never existed.
+ expect(planFieldEdit('ls foo', 'xx bar', 3).committed).toBe('ls bar');
+ });
+
+ it('does not split a surrogate pair', () => {
+ // 😀 and 😂 share a high surrogate; cutting between the halves would send a
+ // lone surrogate, which serializes to U+FFFD instead of the emoji.
+ const plan = planFieldEdit('hi 😀', 'hi 😂');
+ expect(plan.data).toBe(`${DEL.repeat(2)}😂`);
+ expect(plan.committed).toBe('hi 😂');
+ expect([...plan.data].every((ch) => ch.charCodeAt(0) < 0xd800 || ch.codePointAt(0) > 0xffff)).toBe(true);
});
});
@@ -196,6 +216,24 @@ describe('attachDictationBridge', () => {
expect(sent).toEqual(['abc', 'fresh']);
});
+ it('cancels a pending resync when it reconciles the field itself', () => {
+ // A keystroke xterm handled arms a resync; the dictation event that follows
+ // reconciles the field first. If the stale timer still fired it would pin the
+ // floor to the whole phrase and silently swallow every later correction.
+ textarea.value = 'their';
+ fireInput('insertText');
+ // Field is non-empty now, so this keystroke really does arm a resync.
+ textarea.dispatchEvent(new KeyboardEvent('keydown', { keyCode: 32, bubbles: true }));
+ textarea.value = 'there';
+ fireInput('insertReplacementText');
+ vi.runAllTimers();
+ // A stale resync would have pinned floor to 'there'.length, and this
+ // correction would emit nothing at all.
+ textarea.value = 'their';
+ fireInput('insertReplacementText');
+ expect(sent).toEqual(['their', `${DEL}${DEL}re`, `${DEL}${DEL}ir`]);
+ });
+
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 }));