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: preserve unknown entity references across song imports and chat (#9760)

Adam Eivy2ebebb046e33
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index 531d373314..6767350711 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -55,7 +55,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `universeStylePreset.js` | `universeStylePreset(universe, series)` re-exported from `server/lib/universeVisualStyle.js` — the style preset `composeStyledPrompt` layers on top, shared with the FableLoom visual-canon compiler so a series style override composes identically on both sides (#8442). |
| `universeRunTag.js` | `buildUniverseSectionRenderTag(universe, kindKey, entry)` — the durable `universeRun` job tag the canon-render call sites (UniverseCanonSection, NounsStage, Story Builder characters step) pass to `generateImage` so the server auto-files the render into the universe collection AND appends it to the entry's `imageRefs[]` (no client follow-up PATCH). |
| `autopilotMilestones.js` | Series-Autopilot milestone map. `buildAutopilotMilestones(plan, progress, {terminal})` folds the run's projected plan (the `start` frame) and its live progress snapshot (`progress` frames / the status route) into ordered rows with a `MILESTONE_STATUS` each — a furthest-index cursor, so a gate the run revisits can't un-finish the milestones after it; `summarizeAutopilotMilestones(rows)` rolls them into the header meter (a settled-but-unstepped milestone counts as complete); `describeAutopilotVerification(kind, verification)` renders what a gate actually validated — shared with the panel's `frameLabel`, since the milestone row and the activity log render the same telemetry; `isStoppedTerminal(terminal)` is the one definition of "the run stopped mid-plan"; `autopilotMarkerTerminal(status)` translates a persisted `autopilot.status` into the terminal frame type the fold reads, so a map rebuilt from the marker after a reload (#4140) flags the step a paused run stopped on. Also owns `AUTOPILOT_STEP_LABELS` / `autopilotStepLabel(kind)`, the one set of human labels for conductor step kinds (shared by the map and the panel's live status line). Used by `components/pipeline/AutopilotMilestones.jsx` + `AutopilotPanel.jsx`. |
-| `beeperMessageBody.js` | Beeper message bodies: `decodeHtmlEntities` (the five predefined entities plus ` `, mirroring `server/lib/xmlEntities.js`), `looksLikeHtmlBody`, `parseMessageBody(body)` → blocks of marked spans (`p`/`div`/`br`/`blockquote`/`strong`/`b`/`em`/`i`/`a[href]`, `null` when the body carries none of them) and `messagePreviewText(body)` for the one-line rail row. Some networks deliver HTML (Discord, Matrix) and the mirror stores it verbatim, so the thread and the preview parse it into a data model and render React elements — never `dangerouslySetInnerHTML`; a non-http(s) `href` degrades to plain text. |
+| `beeperMessageBody.js` | Beeper message bodies: `decodeHtmlEntities` (the five predefined entities plus ` `, using the shared `server/lib/xmlEntities.js` decoder), `looksLikeHtmlBody`, `parseMessageBody(body)` → blocks of marked spans (`p`/`div`/`br`/`blockquote`/`strong`/`b`/`em`/`i`/`a[href]`, `null` when the body carries none of them) and `messagePreviewText(body)` for the one-line rail row. Some networks deliver HTML (Discord, Matrix) and the mirror stores it verbatim, so the thread and the preview parse it into a data model and render React elements — never `dangerouslySetInnerHTML`; a non-http(s) `href` degrades to plain text. |
| `backupExcludes.js` | CLIENT MIRROR of the backup-exclude block in `server/lib/sharedSchemas.js` (#7241) — `anchorUserExclude` / `anchorUserExcludes` / `isSafeExcludePattern` / `EXCLUDE_PATTERN_MAX_LENGTH`. The Backup settings tab anchors a newly added exclude and renders the effective list with these, so the chip the user sees is the rsync filter the server will actually run instead of an unanchored pattern that matches at any depth. |
| `beatColors.js` | `BEAT_KIND_COLORS` + `getBeatKindColor(kind)` — per-kind display colors for reader-map emotional beats (kinds defined server-side in `storyArc.js`). Keeps every beat visualization consistent. |
| `beatGrid.js` | Music-video beat-quantized timeline arranger (#1854). `buildBeatGridPoints(audioAnalysis)` merges beats/downbeats/section edges into one ranked snap-point list; `snapTimeToGrid(timeSec, gridPoints, toleranceSec)` finds the nearest point within tolerance; `computeSceneSpans(scenes, durationSec)` lays out scenes without a persisted `startSec`/`endSec` contiguously as a display-only fallback; `computeDragSpan({kind, startSpan, deltaSec, gridPoints, ...})` resolves a timeline drag gesture (`'move'` or `'right'` — no `'left'`, since the render can only trim from a clip's own frame 0) into a new span; `shouldMarkBeatAligned({kind, snapped, wasPersisted})` gates the `beatAligned` flag so a reposition-only drag can't silently promote an unpersisted scene's placeholder fallback duration into a "saved exactly" render duration; `autoArrangeScenes(scenes, audioAnalysis)` proposes a full `{ sceneId, startSec, endSec, beatAligned }[]` arrangement by distributing scenes across song sections weighted by each section's `energy` (#1915). Used by `components/musicVideo/BeatTimeline.jsx` and `pages/MusicVideo.jsx`. |
@@ -264,7 +264,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `tribeCadence.js` | Re-export of `server/lib/tribeCadence.js` — the single authoritative Tribe care-cadence rules shared by the page, the Care dashboard widget, and the server. |
| `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); `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`). |
+| `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)` uses the shared `server/lib/xmlEntities.js` decoder (ordinary spaces for ` `) and 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) 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. |
diff --git a/client/src/lib/beeperMessageBody.js b/client/src/lib/beeperMessageBody.js
index 682a3063c9..24924b56c0 100644
--- a/client/src/lib/beeperMessageBody.js
+++ b/client/src/lib/beeperMessageBody.js
@@ -29,37 +29,16 @@
* own (the #59 fix).
*/
+import { decodeXmlEntities } from '../../../server/lib/xmlEntities.js';
import { isHttpUrl } from '../utils/urlNormalize.js';
-// Mirrors `server/lib/xmlEntities.js` `decodeXmlEntities` (also privately
-// mirrored by `client/src/lib/tabNotation.js`). Keep the three in sync.
-const NAMED_ENTITIES = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'" };
-// `decodeXmlEntities` takes an `extraEntities` map for exactly this case; the
-// client copy inlines its one extra rather than growing a parameter. `&nbsp;`
-// is routine in the HTML bodies below and decodes to U+00A0, written as an
-// escape so the source never carries an invisible non-breaking space.
-const HTML_ENTITIES = { ...NAMED_ENTITIES, nbsp: '\u00a0' };
-const ENTITY_RE = /&(#x[0-9a-fA-F]+|#[0-9]+|[a-zA-Z][a-zA-Z0-9]*);/g;
-
/**
* Beeper Desktop delivers entity-encoded text for some bridged networks, so the
* decode happens on the way OUT to the DOM. Everything decoded here is rendered
* as a text node, so decoding only changes which characters are shown — it can
* never introduce markup.
*/
-export const decodeHtmlEntities = (str) => {
- if (typeof str !== 'string' || str.indexOf('&') === -1) return str;
- return str.replace(ENTITY_RE, (match, code) => {
- if (code[0] === '#') {
- const cp = code[1] === 'x' || code[1] === 'X'
- ? parseInt(code.slice(2), 16)
- : parseInt(code.slice(1), 10);
- return cp >= 0 && cp <= 0x10ffff ? String.fromCodePoint(cp) : match;
- }
- // `Object.hasOwn` rather than `in`: `&constructor;` must stay literal.
- return Object.hasOwn(HTML_ENTITIES, code) ? HTML_ENTITIES[code] : match;
- });
-};
+export const decodeHtmlEntities = (str) => decodeXmlEntities(str, { nbsp: '\u00a0' });
// The tags that mean anything here. `div` joins the block set because Matrix
// bodies wrap lines in one; anything absent from both sets keeps its text and
diff --git a/client/src/lib/tabNotation.js b/client/src/lib/tabNotation.js
index d63be0a580..9b5eb41c48 100644
--- a/client/src/lib/tabNotation.js
+++ b/client/src/lib/tabNotation.js
@@ -1,3 +1,5 @@
+import { decodeXmlEntities } from '../../../server/lib/xmlEntities.js';
+
// PortOS tab/chord-sheet notation — pure, dependency-free helpers for the
// SongBook feature (/songbook): classify pasted guitar-tab / chord-sheet /
// ChordPro text line-by-line, extract ChordPro meta, clean up pasted content,
@@ -368,25 +370,7 @@ export const parseTabSheet = (text) => {
// Paste normalization
// ---------------------------------------------------------------------------
-// Mirrors server/lib/xmlEntities.js `decodeXmlEntities` (with `nbsp` as the
-// one extra entity) — keep the two in sync. Single-pass scan is double-decode-
-// safe: `&amp;lt;` decodes to `&lt;`, never `<`. Out-of-range numeric code
-// points are left untouched (String.fromCodePoint would throw a RangeError,
-// and this module must never throw on pasted garbage).
-const NAMED_ENTITIES = { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", nbsp: ' ' };
-
-const ENTITY_RE = /&(#x[0-9a-fA-F]+|#[0-9]+|[a-zA-Z][a-zA-Z0-9]*);/g;
-
-const decodeEntities = (s) =>
- s.replace(ENTITY_RE, (match, code) => {
- if (code[0] === '#') {
- const cp = code[1] === 'x' || code[1] === 'X'
- ? parseInt(code.slice(2), 16)
- : parseInt(code.slice(1), 10);
- return cp >= 0 && cp <= 0x10ffff ? String.fromCodePoint(cp) : match;
- }
- return NAMED_ENTITIES[code] ?? match;
- });
+const decodeEntities = (text) => decodeXmlEntities(text, { nbsp: ' ' });
// Expand tabs to 8-column stops (what <pre> renders), preserving alignment.
const detabLine = (line) => {
diff --git a/client/src/lib/tabNotation.test.js b/client/src/lib/tabNotation.test.js
index b9ac93cacb..f32b400f52 100644
--- a/client/src/lib/tabNotation.test.js
+++ b/client/src/lib/tabNotation.test.js
@@ -335,7 +335,7 @@ describe('normalizePastedTab', () => {
});
it('leaves unknown named entities untouched', () => {
- expect(normalizePastedTab('&bogus; C G')).toBe('&bogus; C G');
+ expect(normalizePastedTab('&bogus; &constructor; &toString; &hasOwnProperty; C G')).toBe('&bogus; &constructor; &toString; &hasOwnProperty; C G');
});
it('maps Unicode accidentals to ASCII so mixed lines classify and transpose', () => {
diff --git a/client/src/pages/SongBookImport.test.jsx b/client/src/pages/SongBookImport.test.jsx
index 621c39763e..d9ac164801 100644
--- a/client/src/pages/SongBookImport.test.jsx
+++ b/client/src/pages/SongBookImport.test.jsx
@@ -53,6 +53,16 @@ describe('SongBookImport', () => {
expect(body.content.text).toBe('&lt; C G Am');
});
+ it('preserves unknown references when saving pasted lyrics', async () => {
+ const text = 'C G\n&constructor; &toString; &hasOwnProperty;';
+ await renderPage();
+ fireEvent.change(screen.getByLabelText('Pasted tab content'), { target: { value: text } });
+ fireEvent.change(screen.getByLabelText('Title'), { target: { value: 'Example Song' } });
+ fireEvent.click(screen.getByRole('button', { name: 'Save song' }));
+ await waitFor(() => expect(api.createSong).toHaveBeenCalled());
+ expect(api.createSong.mock.calls[0][0].content.text).toBe(text);
+ });
+
it('the header Save action saves the draft and is gated on content (#6001)', async () => {
// The form's own Save sits below the textarea + preview — off-screen on a
// phone — so the header copy is the one that has to work above the fold.
diff --git a/server/lib/xmlEntities.js b/server/lib/xmlEntities.js
index 464d89cd53..01d756a7a1 100644
--- a/server/lib/xmlEntities.js
+++ b/server/lib/xmlEntities.js
@@ -19,8 +19,7 @@
* untouched rather than dropped or thrown on, so one malformed reference can't
* corrupt or abort the surrounding parse.
*
- * Mirrored client-side by the private `decodeEntities` in
- * `client/src/lib/tabNotation.js` (lib stays a leaf) — keep the two in sync.
+ * Imported directly by the SongBook paste and Beeper browser wrappers.
*/
const NAMED_ENTITIES = {
@@ -59,6 +58,6 @@ export function decodeXmlEntities(str, extraEntities) {
if (extraEntities && Object.prototype.hasOwnProperty.call(extraEntities, code)) {
return extraEntities[code];
}
- return NAMED_ENTITIES[code] ?? match;
+ return Object.hasOwn(NAMED_ENTITIES, code) ? NAMED_ENTITIES[code] : match;
});
}
diff --git a/server/lib/xmlEntities.test.js b/server/lib/xmlEntities.test.js
index a652218920..516c5d4c91 100644
--- a/server/lib/xmlEntities.test.js
+++ b/server/lib/xmlEntities.test.js
@@ -32,7 +32,7 @@ describe('decodeXmlEntities', () => {
});
it('leaves unknown named entities untouched', () => {
- expect(decodeXmlEntities('&bogus;')).toBe('&bogus;');
+ expect(decodeXmlEntities('&bogus; &constructor; &toString; &hasOwnProperty;')).toBe('&bogus; &constructor; &toString; &hasOwnProperty;');
expect(decodeXmlEntities('&nbsp;')).toBe('&nbsp;'); // not predefined without extras
});
diff --git a/server/services/brainSongbookImport.test.js b/server/services/brainSongbookImport.test.js
index c33c8bc379..f10e30fc96 100644
--- a/server/services/brainSongbookImport.test.js
+++ b/server/services/brainSongbookImport.test.js
@@ -108,6 +108,11 @@ describe('extractLargestPre', () => {
expect(extractLargestPre(html)).toBe('&#x110000; still a long enough sheet');
});
+ it('preserves unknown named references in URL-extracted lyrics', () => {
+ const text = 'C G\n&constructor; &toString; &hasOwnProperty;';
+ expect(extractLargestPre(`<pre>${text}</pre>`)).toBe(text);
+ });
+
it('strips inner markup tags', () => {
const html = '<pre><span class="chord">Am</span> example lyric line here</pre>';
expect(extractLargestPre(html)).toBe('Am example lyric line here');