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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
simplify SongBook: shared upload/serve + htmlToText helpers, drop redundant surface
[._.]/ Adam Eivy38ee29753d4a
diff --git a/PLAN.md b/PLAN.mdindex e2157602a7..e569068174 100644--- a/PLAN.md+++ b/PLAN.md@@ -15,3 +15,29 @@ This file no longer tracks individual tasks (so it stops generating mergeconflicts as work proceeds). Speculative ideas now live as `future`-labeledissues rather than a list here, so they can each be promoted, refined, or closedindependently.++### SongBook follow-ups++Deferred from the SongBook feature's post-review cleanup (see+`docs/plans/2026-07-15-songbook.md`) — to be promoted to labeled GitHub issues+by `/do:replan --issues`:++- [ ] "Fit to duration" autoscroll preset: re-add an optional `scrollDurationSec`+ field to `songInputSchema` (`server/lib/brainValidation.js`) plus a preset+ button in `client/src/pages/SongBookViewer.jsx` that computes `pxPerSec` from+ the scroll container's `scrollHeight / scrollDurationSec`. Dropped from v1 as+ speculative — no UI consumed the field.+- [ ] Consolidate `server/routes/uploads.js` onto the shared `saveBase64Upload`+ / `serveLocalFile` helpers in `server/lib/fileUtils.js` (added for+ `routes/attachments.js` + `routes/brainSongbook.js`). Left out of the SongBook+ pass because uploads.js has a different response shape and uses the full+ `EXTENSION_MIME_MAP` rather than an allowlist.+- [ ] SongBook practice/spaced-rep integration (SM-2 style, cf.+ `meatspacePostMemory`) — the `stage` field on `songs` records is manual in v1+ (`server/lib/brainValidation.js` `songStageEnum`).+- [ ] Link songs to existing Rounds/Tracks/MIDI records — a cross-links field on+ the `songs` record + UI in `client/src/pages/SongBookViewer.jsx`.+- [ ] Chord diagrams / fretboard rendering and MIDI/score preview embedding in+ the SongBook viewer (`client/src/components/songbook/TabSheetView.jsx`).+- [ ] Brain memory-bridge/graph enrollment for `songs` records (nav/⌘K already+ works via the nav manifest; this is the knowledge-graph side).diff --git a/client/src/components/songbook/TabSheetView.jsx b/client/src/components/songbook/TabSheetView.jsxindex f27c896e53..c895f1c60c 100644--- a/client/src/components/songbook/TabSheetView.jsx+++ b/client/src/components/songbook/TabSheetView.jsx@@ -1,4 +1,4 @@-import { useMemo } from 'react';+import { memo, useMemo } from 'react';import { parseTabSheet } from '../../lib/tabNotation.js';/**@@ -61,7 +61,7 @@ const ChordLyricLine = ({ line }) => (</div>);-export default function TabSheetView({ text, fontSizeRem = 0.875, className = '' }) {+function TabSheetView({ text, fontSizeRem = 0.875, className = '' }) {const { lines } = useMemo(() => parseTabSheet(text), [text]);// Group consecutive tabstaff lines into one horizontally-scrollable block so@@ -112,3 +112,7 @@ export default function TabSheetView({ text, fontSizeRem = 0.875, className = ''</div>);}++// Props are all primitives, so memo makes re-renders of a host page (stage+// flips, autoscroll ticks) skip the full sheet re-render.+export default memo(TabSheetView);diff --git a/client/src/components/songbook/constants.js b/client/src/components/songbook/constants.jsindex ac320c8da7..6b7d7ad6a2 100644--- a/client/src/components/songbook/constants.js+++ b/client/src/components/songbook/constants.js@@ -16,6 +16,23 @@ export const SONG_STAGE_COLORS = {memorized: 'bg-port-success/20 text-port-success border-port-success/30',};-export const INSTRUMENTS = ['guitar', 'piano', 'ukulele', 'bass', 'voice', 'other'];+export const INSTRUMENTS = [+ { id: 'guitar', label: 'Guitar' },+ { id: 'piano', label: 'Piano' },+ { id: 'ukulele', label: 'Ukulele' },+ { id: 'bass', label: 'Bass' },+ { id: 'voice', label: 'Voice' },+ { id: 'other', label: 'Other' },+];++// Display label for a stored instrument id (unknown ids render as-is).+export const instrumentLabel = (id) => INSTRUMENTS.find((i) => i.id === id)?.label || id;export const SONG_FORMATS = ['chordpro', 'tab', 'plain'];++// Shared form/button recipes for the SongBook pages (index, import, viewer) —+// kept here so the three pages don't drift on styling.+export const inputClass = 'w-full bg-port-bg border border-port-border rounded-lg px-3 py-2 text-sm text-white focus:border-port-accent focus:outline-none';+export const labelClass = 'block text-xs text-gray-400 mb-1';+// Secondary button (bordered, subtle hover; disabled fades).+export const btnClass = 'flex items-center gap-1.5 px-3 py-2 text-sm rounded-lg border border-port-border text-gray-300 hover:text-white hover:bg-port-border/50 disabled:opacity-50';diff --git a/client/src/lib/tabNotation.js b/client/src/lib/tabNotation.jsindex f7235571d4..30620f96de 100644--- a/client/src/lib/tabNotation.js+++ b/client/src/lib/tabNotation.js@@ -248,14 +248,25 @@ export const parseTabSheet = (text) => {// Paste normalization// ----------------------------------------------------------------------------const NAMED_ENTITIES = { lt: '<', gt: '>', quot: '"', apos: "'", nbsp: ' ' };+// 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: `&lt;` decodes to `<`, 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(/&(lt|gt|quot|apos|nbsp);/gi, (_, name) => NAMED_ENTITIES[name.toLowerCase()])- .replace(/&#x([0-9a-f]+);/gi, (_, hex) => String.fromCodePoint(parseInt(hex, 16)))- .replace(/&#(\d+);/g, (_, dec) => String.fromCodePoint(Number(dec)))- .replace(/&/gi, '&');+ 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;+ });// 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.jsindex 858f0a196f..2b2864543e 100644--- a/client/src/lib/tabNotation.test.js+++ b/client/src/lib/tabNotation.test.js@@ -289,6 +289,15 @@ describe('normalizePastedTab', () => {expect(normalizePastedTab('&lt;')).toBe('<');});+ it('leaves out-of-range numeric entities untouched instead of throwing (mirrors decodeXmlEntities)', () => {+ expect(normalizePastedTab('� ok')).toBe('� ok');+ expect(normalizePastedTab('� ok')).toBe('� ok');+ });++ it('leaves unknown named entities untouched', () => {+ expect(normalizePastedTab('&bogus; C G')).toBe('&bogus; C G');+ });+it('expands tabs to 8-column stops', () => {expect(normalizePastedTab('C\tG')).toBe('C G');expect(normalizePastedTab('Am7\tD')).toBe('Am7 D');diff --git a/client/src/pages/RoundEditor.jsx b/client/src/pages/RoundEditor.jsxindex 6614599a6c..4679198a47 100644--- a/client/src/pages/RoundEditor.jsx+++ b/client/src/pages/RoundEditor.jsx@@ -43,6 +43,7 @@ import ScoreSheet from '../components/songs/ScoreSheet';import PianoRoll, { layerColor } from '../components/songs/PianoRoll';import RoundStack from '../components/songs/RoundStack';import { scoreHasMusic, parseScore } from '../lib/scoreNotation';+import { isHttpUrl } from '../utils/urlNormalize';import { createMultiScorePlayer, DEFAULT_BPM } from '../lib/scorePlayback';import { harmonyPartOrder } from '../lib/songCraft';@@ -64,10 +65,6 @@ const tiktokVideoId = (url) => {return m ? m[1] : null;};const tiktokEmbedSrc = (id) => `https://www.tiktok.com/player/v1/${id}`;-// Only http(s) URLs are safe to render as a clickable link — reject-// javascript:/data: and other schemes so a stored reference can't smuggle a-// script into an href.-const isHttpUrl = (url) => /^https?:\/\//i.test(url || '');// In-session-only id for a freshly-added section/layer, used purely as a React// key until the row is saved. Counter-based (not Math.random, which isdiff --git a/client/src/pages/SongBook.jsx b/client/src/pages/SongBook.jsxindex d521981367..98f21ddc6c 100644--- a/client/src/pages/SongBook.jsx+++ b/client/src/pages/SongBook.jsx@@ -7,8 +7,8 @@* the play/edit viewer lives at /songbook/:id and import at /songbook/import.** Filters live in URL search params (?stage=&instrument=&tag=&q=) so a- * filtered view is linkable (Catalog.jsx pattern). Stage flips PATCH the cheap- * /stage endpoint and update local state reactively — no refetch.+ * filtered view is linkable (Catalog.jsx pattern). Stage flips PUT just the+ * stage field and update local state reactively — no refetch.*/import { useEffect, useMemo, useState, useCallback } from 'react';@@ -21,10 +21,10 @@ import ConfirmButtonPair from '../components/ui/ConfirmButtonPair';import { timeAgo } from '../utils/formatters';import { useAsyncAction } from '../hooks/useAsyncAction';import { useConfirmDelete } from '../hooks/useConfirmDelete';-import { listSongs, createSong, deleteSong, patchSongStage } from '../services/api';-import { SONG_STAGES, SONG_STAGE_COLORS, INSTRUMENTS } from '../components/songbook/constants';--const capitalize = (s) => (s ? s[0].toUpperCase() + s.slice(1) : s);+import { listSongs, createSong, deleteSong, updateSong } from '../services/api';+import {+ SONG_STAGES, SONG_STAGE_COLORS, INSTRUMENTS, instrumentLabel, inputClass, labelClass,+} from '../components/songbook/constants';export default function SongBook() {const navigate = useNavigate();@@ -70,10 +70,11 @@ export default function SongBook() {.catch((err) => toast.error(err?.message || 'Failed to delete song')),), [confirmDelete]);- // Stage flip: PATCH then merge the server record into local state. No custom- // catch toast — the request helper owns the error toast (single layer).+ // Stage flip: PUT just the stage (defaults-free partial) then merge the+ // server record into local state. No custom catch toast — the request+ // helper owns the error toast (single layer).const onStageChange = useCallback((id, stage) => {- patchSongStage(id, stage)+ updateSong(id, { stage }).then((updated) => setSongs((prev) => prev.map((s) => (s.id === id ? { ...s, ...updated } : s)))).catch(() => {});}, []);@@ -115,14 +116,14 @@ export default function SongBook() {className="bg-port-card border border-port-border rounded-lg p-4 mb-4 flex flex-col sm:flex-row gap-3 sm:items-end"><div className="flex-1">- <label htmlFor="song-title" className="block text-xs text-gray-400 mb-1">Title</label>+ <label htmlFor="song-title" className={labelClass}>Title</label><inputid="song-title"type="text"value={title}onChange={(e) => setTitle(e.target.value)}placeholder="e.g. Example Song"- className="w-full bg-port-bg border border-port-border rounded-lg px-3 py-2 text-sm text-white focus:border-port-accent focus:outline-none"+ className={inputClass}/></div><button@@ -164,7 +165,7 @@ export default function SongBook() {className={selectClass}><option value="">All instruments</option>- {INSTRUMENTS.map((i) => <option key={i} value={i}>{capitalize(i)}</option>)}+ {INSTRUMENTS.map((i) => <option key={i.id} value={i.id}>{i.label}</option>)}</select>{tagFilter && (<button@@ -205,7 +206,7 @@ export default function SongBook() {<div className="text-white font-medium truncate" title={song.title}>{song.title}</div><div className="flex flex-wrap gap-x-3 gap-y-0.5 text-xs text-gray-500 mt-1">{song.artist && <span className="text-gray-400">{song.artist}</span>}- {song.instrument && <span>{capitalize(song.instrument)}</span>}+ {song.instrument && <span>{instrumentLabel(song.instrument)}</span>}{song.updatedAt && <span>Edited {timeAgo(song.updatedAt)}</span>}</div>{Array.isArray(song.tags) && song.tags.length > 0 && (diff --git a/client/src/pages/SongBook.test.jsx b/client/src/pages/SongBook.test.jsxindex b5f05f9931..1bf9bf7ae5 100644--- a/client/src/pages/SongBook.test.jsx+++ b/client/src/pages/SongBook.test.jsx@@ -7,7 +7,7 @@ const api = vi.hoisted(() => ({listSongs: vi.fn(),createSong: vi.fn(),deleteSong: vi.fn(),- patchSongStage: vi.fn(),+ updateSong: vi.fn(),}));vi.mock('../services/api', () => api);vi.mock('../components/ui/Toast', () => ({ default: { error: vi.fn(), success: vi.fn() } }));@@ -43,7 +43,7 @@ const renderPage = (path = '/songbook') => render(describe('SongBook index', () => {beforeEach(() => {api.listSongs.mockReset().mockResolvedValue({ songs: [song('s1', 'Example Song')] });- api.patchSongStage.mockReset();+ api.updateSong.mockReset();api.deleteSong.mockReset();api.createSong.mockReset();});@@ -54,13 +54,13 @@ describe('SongBook index', () => {expect(screen.getByText('The Placeholders')).toBeTruthy();});- it('flips a song stage via patchSongStage and updates local state reactively', async () => {- api.patchSongStage.mockResolvedValue(song('s1', 'Example Song', { stage: 'learning' }));+ it('flips a song stage via a partial updateSong and updates local state reactively', async () => {+ api.updateSong.mockResolvedValue(song('s1', 'Example Song', { stage: 'learning' }));renderPage();const select = await screen.findByLabelText('Stage for Example Song');expect(select.value).toBe('new');fireEvent.change(select, { target: { value: 'learning' } });- expect(api.patchSongStage).toHaveBeenCalledWith('s1', 'learning');+ expect(api.updateSong).toHaveBeenCalledWith('s1', { stage: 'learning' });await waitFor(() => expect(screen.getByLabelText('Stage for Example Song').value).toBe('learning'));// Reactive local-state update — no refetch of the list.expect(api.listSongs).toHaveBeenCalledTimes(1);diff --git a/client/src/pages/SongBookImport.jsx b/client/src/pages/SongBookImport.jsxindex 967e7246b9..5e39abc8ed 100644--- a/client/src/pages/SongBookImport.jsx+++ b/client/src/pages/SongBookImport.jsx@@ -15,21 +15,22 @@*/import { useMemo, useState, useCallback } from 'react';-import { useNavigate, useSearchParams, Link } from 'react-router-dom';+import { useNavigate, Link } from 'react-router-dom';import { ListMusic, ArrowLeft, ClipboardPaste, Eraser, Wand2, Globe, FileText, Save } from 'lucide-react';import toast from '../components/ui/Toast';import PageHeader from '../components/PageHeader';import TabPills from '../components/ui/TabPills';import TabSheetView from '../components/songbook/TabSheetView';-import { SONG_STAGES, INSTRUMENTS } from '../components/songbook/constants';+import {+ SONG_STAGES, INSTRUMENTS, inputClass, labelClass, btnClass,+} from '../components/songbook/constants';import { useAsyncAction } from '../hooks/useAsyncAction';+import useDrawerTab from '../hooks/useDrawerTab';import { createSong, importSongFromUrl } from '../services/api';import { normalizePastedTab, detectFormat, parseTabSheet } from '../lib/tabNotation.js';import { readClipboard } from '../lib/clipboard.js';import { isUrl, normalizeUrl } from '../utils/urlNormalize';-const capitalize = (s) => (s ? s[0].toUpperCase() + s.slice(1) : s);-// Invented placeholder sheet — demonstrates sections, chord lines, and a tab// staff without any real song data (privacy convention).const SAMPLE_TAB = `[Intro]@@ -59,23 +60,10 @@ const TABS = [{ id: 'url', label: 'From URL', icon: Globe },];-const inputClass = 'w-full bg-port-bg border border-port-border rounded-lg px-3 py-2 text-sm text-white focus:border-port-accent focus:outline-none';-const labelClass = 'block text-xs text-gray-400 mb-1';-const btnClass = 'flex items-center gap-1.5 px-3 py-2 text-sm rounded-lg border border-port-border text-gray-300 hover:text-white hover:bg-port-border/50 disabled:opacity-50';-export default function SongBookImport() {const navigate = useNavigate();- const [searchParams, setSearchParams] = useSearchParams();- const rawTab = searchParams.get('tab');- const tab = TABS.some((t) => t.id === rawTab) ? rawTab : 'paste';- const setTab = useCallback((next) => {- setSearchParams((prev) => {- const p = new URLSearchParams(prev);- if (next === 'paste') p.delete('tab');- else p.set('tab', next);- return p;- }, { replace: true });- }, [setSearchParams]);+ // URL-backed tab state (default omitted from the URL, replace-history writes).+ const [tab, setTab] = useDrawerTab('tab', 'paste', ['paste', 'url']);// Paste tab stateconst [pasted, setPasted] = useState('');@@ -107,6 +95,8 @@ export default function SongBookImport() {applyMetaDefaults(parseTabSheet(clean).meta);}, [applyMetaDefaults]);+ // Error mapping lives in the .catch alone — it swallows every rejection, so+ // a useAsyncAction errorMessage layer could never fire (single toast layer).const [fetchUrl, fetching] = useAsyncAction(async () => {const normalizedUrl = normalizeUrl(url);if (!normalizedUrl || !isUrl(normalizedUrl)) { toast.error('Enter a valid URL'); return null; }@@ -119,13 +109,17 @@ export default function SongBookImport() {setFetched(draft);applyMetaDefaults(draft);return draft;- }, { errorMessage: 'Import failed' });+ });// The active tab's content → what Save will store.const contentText = tab === 'url' ? (fetched?.content?.text || '') : normalized;- const contentFormat = tab === 'url'- ? (fetched?.content?.format || detectFormat(contentText))- : detectFormat(normalized);+ const fetchedFormat = fetched?.content?.format;+ // Memoized on its real inputs so detectFormat (a full line-classifier pass)+ // doesn't re-run on every unrelated keystroke (title/artist/tags).+ const contentFormat = useMemo(+ () => (tab === 'url' && fetchedFormat) || detectFormat(contentText),+ [tab, fetchedFormat, contentText],+ );const [save, saving] = useAsyncAction(async () => {const name = title.trim();@@ -261,7 +255,7 @@ export default function SongBookImport() {<div><label htmlFor="import-instrument" className={labelClass}>Instrument</label><select id="import-instrument" value={instrument} onChange={(e) => setInstrument(e.target.value)} className={inputClass}>- {INSTRUMENTS.map((i) => <option key={i} value={i}>{capitalize(i)}</option>)}+ {INSTRUMENTS.map((i) => <option key={i.id} value={i.id}>{i.label}</option>)}</select></div><div>diff --git a/client/src/pages/SongBookViewer.jsx b/client/src/pages/SongBookViewer.jsxindex 92c69a3854..2417c38f3e 100644--- a/client/src/pages/SongBookViewer.jsx+++ b/client/src/pages/SongBookViewer.jsx@@ -22,7 +22,7 @@*/import { useState, useEffect, useMemo, useRef, useCallback } from 'react';-import { useParams, useNavigate, useSearchParams, Link } from 'react-router-dom';+import { useParams, useNavigate, Link } from 'react-router-dom';import {ListMusic, ArrowLeft, Save, Trash2, Pencil, Eye, Play, Pause, Plus, Minus,ExternalLink, Paperclip, Upload, FileX2,@@ -32,23 +32,26 @@ import PageHeader from '../components/PageHeader';import ConfirmButtonPair from '../components/ui/ConfirmButtonPair';import AutoSizeTextarea from '../components/ui/AutoSizeTextarea';import TabSheetView from '../components/songbook/TabSheetView';-import { SONG_STAGES, SONG_STAGE_COLORS, INSTRUMENTS, SONG_FORMATS } from '../components/songbook/constants';+import {+ SONG_STAGES, SONG_STAGE_COLORS, INSTRUMENTS, SONG_FORMATS,+ inputClass, labelClass, btnClass,+} from '../components/songbook/constants';import { useAsyncAction } from '../hooks/useAsyncAction';import { useConfirmDelete } from '../hooks/useConfirmDelete';+import useDrawerTab from '../hooks/useDrawerTab';import useKeyboardShortcuts from '../hooks/useKeyboardShortcuts';import useAutoscroll from '../hooks/useAutoscroll';import useWakeLock from '../hooks/useWakeLock';import { transposeText } from '../lib/tabNotation.js';import { safeReadStorage, safeWriteStorage } from '../lib/safeStorage.js';import { formatBytes } from '../utils/formatters';+import { isHttpUrl } from '../utils/urlNormalize';import { readFileAsBase64, ATTACHMENT_MAX_FILE_SIZE } from '../utils/fileUpload';import {- getSong, updateSong, patchSongStage, deleteSong,+ getSong, updateSong, deleteSong,listSongAttachments, uploadSongAttachment, deleteSongAttachment, songAttachmentUrl,} from '../services/api';-const capitalize = (s) => (s ? s[0].toUpperCase() + s.slice(1) : s);-const TRANSPOSE_MIN = -11;const TRANSPOSE_MAX = 11;const FONT_MIN = 0.625;@@ -75,28 +78,15 @@ const toDraft = (song) => ({const parseTags = (raw) => raw.split(',').map((t) => t.trim()).filter(Boolean);-// Only http(s) URLs are safe to render as a clickable link — reject-// javascript:/data: schemes so a stored sourceUrl can't smuggle a script.-const isHttpUrl = (url) => /^https?:\/\//i.test(url || '');--const inputClass = 'w-full bg-port-bg border border-port-border rounded-lg px-3 py-2 text-sm text-white focus:border-port-accent focus:outline-none';-const labelClass = 'block text-xs text-gray-400 mb-1';// 44px minimum touch targets on the controls bar (mobile-friendly).const ctrlBtnClass = 'flex items-center justify-center min-w-[44px] min-h-[44px] rounded-lg border border-port-border text-gray-300 hover:text-white hover:bg-port-border/50';export default function SongBookViewer() {const { id } = useParams();const navigate = useNavigate();- const [searchParams, setSearchParams] = useSearchParams();- const editing = searchParams.get('mode') === 'edit';- const setMode = useCallback((mode) => {- setSearchParams((prev) => {- const next = new URLSearchParams(prev);- if (mode === 'edit') next.set('mode', 'edit');- else next.delete('mode');- return next;- }, { replace: true });- }, [setSearchParams]);+ // URL-backed mode (default 'play' omitted from the URL, replace-history writes).+ const [mode, setMode] = useDrawerTab('mode', 'play', ['play', 'edit']);+ const editing = mode === 'edit';const [song, setSong] = useState(null);const [loading, setLoading] = useState(true);@@ -171,15 +161,19 @@ export default function SongBookViewer() {'0': scrollToTop,});- const renderedText = useMemo(() => {- const text = song?.content?.text || '';- return transpose ? transposeText(text, transpose) : text;- }, [song, transpose]);+ // Keyed on the content STRING (not the song object) so unrelated record+ // updates (stage flips, attachment meta) don't re-run the transpose pass.+ const contentText = song?.content?.text || '';+ const renderedText = useMemo(+ () => (transpose ? transposeText(contentText, transpose) : contentText),+ [contentText, transpose],+ );// --- Mutationsconst onStageChange = useCallback((stage) => {- // Helper toast owns the error UI (no custom catch toast → no silent).- patchSongStage(id, stage)+ // PUT just the stage (defaults-free partial). Helper toast owns the error+ // UI (no custom catch toast → no silent).+ updateSong(id, { stage }).then((updated) => {setSong(updated);setDraft((prev) => (prev ? { ...prev, stage: updated.stage } : prev));@@ -273,7 +267,7 @@ export default function SongBookViewer() {subtitle={song.artist || undefined}actions={(<>- <Link to="/songbook" className="flex items-center gap-1.5 px-3 py-2 text-sm rounded-lg border border-port-border text-gray-300 hover:text-white hover:bg-port-border/50">+ <Link to="/songbook" className={btnClass}><ArrowLeft size={15} /><span className="hidden sm:inline">All songs</span></Link>@@ -291,7 +285,7 @@ export default function SongBookViewer() {<buttontype="button"onClick={() => setMode('play')}- className="flex items-center gap-1.5 px-3 py-2 text-sm rounded-lg border border-port-border text-gray-300 hover:text-white hover:bg-port-border/50"+ className={btnClass}><Eye size={15} />View@@ -301,7 +295,7 @@ export default function SongBookViewer() {<buttontype="button"onClick={() => setMode('edit')}- className="flex items-center gap-1.5 px-3 py-2 text-sm rounded-lg border border-port-border text-gray-300 hover:text-white hover:bg-port-border/50"+ className={btnClass}><Pencil size={15} />Edit@@ -344,7 +338,7 @@ export default function SongBookViewer() {<div><label htmlFor="song-edit-instrument" className={labelClass}>Instrument</label><select id="song-edit-instrument" value={draft.instrument} onChange={(e) => setDraft({ ...draft, instrument: e.target.value })} className={inputClass}>- {INSTRUMENTS.map((i) => <option key={i} value={i}>{capitalize(i)}</option>)}+ {INSTRUMENTS.map((i) => <option key={i.id} value={i.id}>{i.label}</option>)}</select></div><div>diff --git a/client/src/pages/SongBookViewer.test.jsx b/client/src/pages/SongBookViewer.test.jsxindex faa5dab917..472a6c91f0 100644--- a/client/src/pages/SongBookViewer.test.jsx+++ b/client/src/pages/SongBookViewer.test.jsx@@ -6,7 +6,6 @@ import { MemoryRouter, Routes, Route } from 'react-router-dom';const api = vi.hoisted(() => ({getSong: vi.fn(),updateSong: vi.fn(),- patchSongStage: vi.fn(),deleteSong: vi.fn(),listSongAttachments: vi.fn(),uploadSongAttachment: vi.fn(),@@ -35,7 +34,6 @@ const song = (extra = {}) => ({tuning: '',sourceUrl: '',content: { format: 'tab', text: SHEET },- scrollDurationSec: null,notes: '',attachments: [],createdAt: '2026-01-01T00:00:00.000Z',@@ -53,7 +51,6 @@ describe('SongBookViewer', () => {beforeEach(() => {api.getSong.mockReset().mockResolvedValue(song());api.listSongAttachments.mockReset().mockResolvedValue([]);- api.patchSongStage.mockReset();api.updateSong.mockReset();api.deleteSong.mockReset();globalThis.localStorage?.clear?.();@@ -80,12 +77,12 @@ describe('SongBookViewer', () => {expect(screen.getByText('Back to SongBook')).toBeTruthy();});- it('flips the stage via patchSongStage and merges the server record', async () => {- api.patchSongStage.mockResolvedValue(song({ stage: 'learned' }));+ it('flips the stage via a partial updateSong and merges the server record', async () => {+ api.updateSong.mockResolvedValue(song({ stage: 'learned' }));renderPage();const select = await screen.findByLabelText('Learning stage');fireEvent.change(select, { target: { value: 'learned' } });- expect(api.patchSongStage).toHaveBeenCalledWith('abc', 'learned');+ expect(api.updateSong).toHaveBeenCalledWith('abc', { stage: 'learned' });await waitFor(() => expect(screen.getByLabelText('Learning stage').value).toBe('learned'));});diff --git a/client/src/services/apiSongbook.js b/client/src/services/apiSongbook.jsindex c4f8dcdb2a..199f7074fe 100644--- a/client/src/services/apiSongbook.js+++ b/client/src/services/apiSongbook.js@@ -27,13 +27,11 @@ export const getSong = (id, options) => request(`/brain/songbook/${enc(id)}`, opexport const createSong = (body = {}, options) =>request('/brain/songbook', { method: 'POST', body: JSON.stringify(body), ...options });+// Defaults-free partial PUT — also the stage chip-flip path+// (`updateSong(id, { stage })`).export const updateSong = (id, patch, options) =>request(`/brain/songbook/${enc(id)}`, { method: 'PUT', body: JSON.stringify(patch), ...options });-// Cheap chip-flip path — PATCH only the learning stage.-export const patchSongStage = (id, stage, options) =>- request(`/brain/songbook/${enc(id)}/stage`, { method: 'PATCH', body: JSON.stringify({ stage }), ...options });-export const deleteSong = (id, options) =>request(`/brain/songbook/${enc(id)}`, { method: 'DELETE', ...options });diff --git a/client/src/utils/README.md b/client/src/utils/README.mdindex 3fd4bd2aff..a97088499f 100644--- a/client/src/utils/README.md+++ b/client/src/utils/README.md@@ -33,7 +33,7 @@ grep -i "what you want to do" client/src/utils/README.md| `coalesce` | Trailing-edge coalescer: wraps a function so rapid calls collapse into one deferred invocation. || `easing` | `smoothstep` interpolation easing curve. || `hashString` | Deterministic string → 32-bit hash (stable colors, keys, seeds). |-| `urlNormalize` | `isUrl` detection and `normalizeUrl` (optional git/`requireDot` modes). |+| `urlNormalize` | `isUrl` detection, `normalizeUrl` (optional git/`requireDot` modes), and `isHttpUrl` (explicit http(s) only — safe-href check). || `platform` | `isMac` detection and `modKey` (⌘/Ctrl) for keyboard-shortcut display. || `navWorkingSet` | Recent/pinned nav persistence (`recordVisit`, `togglePin`, `isPinned`) plus `resolveRecentNavEntries` for mapping stored deep links back to their longest matching nav-manifest entry. || `providers` | AI-provider type predicates and helpers (`isCliProvider`, `isApiProvider`, `isCodexProvider`, `filterSelectableModels`, `getProviderTimeout`, configured-default sentinels, and the claude/codex thinking-effort levels — `effortLevelsForProvider`, mirror of server `providerModels.js`). |diff --git a/client/src/utils/urlNormalize.js b/client/src/utils/urlNormalize.jsindex 9f96961c69..dc7b409edd 100644--- a/client/src/utils/urlNormalize.js+++ b/client/src/utils/urlNormalize.js@@ -14,6 +14,16 @@const URL_SCHEME_PATTERN = /^(https?:\/\/|git@)/i;const DOMAIN_PATTERN = /^\S+\.\S+$/;+/**+ * True when a stored/user value is an explicit http(s) URL — the only scheme+ * safe to render as a clickable link (rejects javascript:/data: so a stored+ * URL can't smuggle a script into an href).+ *+ * @param {string} url+ * @returns {boolean}+ */+export const isHttpUrl = (url) => /^https?:\/\//i.test(url || '');+/*** Detect whether a raw string should be treated as a URL/link rather than* free text. Mirrors QuickBrainCapture's detection: an explicit schemediff --git a/docs/plans/2026-07-15-songbook.md b/docs/plans/2026-07-15-songbook.mdindex 1d5016aec6..3b6673ae3d 100644--- a/docs/plans/2026-07-15-songbook.md+++ b/docs/plans/2026-07-15-songbook.md@@ -211,3 +211,24 @@ invent fixture tabs (e.g. "Example Song" by "The Placeholders").- Chord diagrams / fretboard rendering; MIDI/score preview embedding in the viewer.- Voice/palette actions (nav entry alone gives ⌘K + voice nav).- Brain memory-bridge/graph enrollment for songs.++## Post-review amendments (2026-07-15)++Applied after the 4-angle code review of `feature/songbook`; the sections above+are kept as the original design record.++- **`PATCH /:id/stage` removed.** The dedicated stage endpoint (and+ `songStagePatchSchema` / client `patchSongStage`) duplicated what the+ defaults-free partial `PUT /:id` already does — stage flips now go through+ `updateSong(id, { stage })`.+- **`scrollDurationSec` dropped from `songInputSchema`.** Speculative in v1+ (nothing consumed it). The "fit to duration" autoscroll preset that would+ re-add it is parked in PLAN.md under "SongBook follow-ups".+- **`songAttachmentSchema` / `songRecordSchema` deleted** — dead exports;+ attachment metadata stays server-managed with no client-suppliable schema.+- **Shared helpers extracted:** entity decoding via `decodeXmlEntities`+ (`server/lib/xmlEntities.js`, mirrored by `tabNotation.js`'s private+ decoder), strip-tags via `server/lib/htmlToText.js` (also adopted by the+ Gmail sync), and the attachment upload/serve pipeline via+ `saveBase64Upload` / `serveLocalFile` in `server/lib/fileUtils.js` with a+ curated `SONGBOOK_ATTACHMENT_EXTENSIONS` allowlist.diff --git a/server/lib/README.md b/server/lib/README.mdindex 7d21b9cbc0..6536bb0557 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -125,7 +125,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `conflictJournal.js` | Non-blocking edit-conflict journal for cross-install LWW merges. `maybeJournalBeforeOverwrite({kind,id,local,remote,source})` (call right before a merge overwrite) archives the losing local version when a true 3-way divergence is detected (`detectConflict` via per-record `syncBaseHash` + `contentHashForRecord`), then advances the base hash; `flushBaseHashes()` persists the batched base-hash side store; `withBaseHashFlushBatch(fn)` defers every interior flush so an await-separated multi-record push loop (peer:online convergence) collapses N `sync_base_hashes.json` rewrites into one terminal write (re-entrant; flushes in `finally`). `deleteSyncBaseHash(kind,id)` evicts a record's base hash when its tombstone is hard-pruned (called from every `pruneTombstoned*` path — universe/series/issue/collection) so the side store doesn't grow without bound; `pruneOrphanedBaseHashes(resolves)` is the backstop sweep (`resolves(kind,id) => bool`; unknown kinds kept) that drops keys whose record no longer resolves, wired into the tombstone GC sweep. `conflictJournalStore()` is the `pending`/`resolved` entry store (discard resolves an entry; DELETE hard-removes it — there is no `dismissed` status). Local-only — never crosses the wire. || `schemaVersions.js` | Cross-instance sync version contract. `PORTOS_SCHEMA_VERSIONS` (frozen map of `{ category: layoutVersion }`), `RECORD_KIND_SCHEMA_CATEGORIES` (frozen map of federated record kind → the schema categories it writes), `buildPortosMeta()` (envelope for every outbound sync payload), `compareSchemaVersions(sender, receiver)` returning `{ ahead, behind, compatible }`, `scopeVersionDiff(diff, categories)` (restrict that diff to the categories a specific transfer touches), and `formatVersionGap()` for UI/log lines. Receivers gate `applyIncomingPush` / share-bucket import / snapshot apply per-category on the scoped comparator result so an upgraded sender can't corrupt a downstream peer — and a bump to one category doesn't sever sync of the others. || `dataRoot.js` | Data-root resolution + worktree-checkout detection (#1947). `resolveInstallRoot(fallbackRoot)` prefers the `PORTOS_DATA_ROOT` env var (pinned at real launch in `ecosystem.config.cjs`) over an `import.meta.url`-derived fallback, so a process booted from inside a CoS agent git worktree still resolves `data/`/`data.reference/` to the real install instead of the worktree's empty tree. `isWorktreeRoot(rootDir)` is the boot-migration backstop — true when `rootDir` lives under `data/cos/worktrees/` (keyed on the path segment only, so a fresh install's empty `data/` isn't a false positive). `DATA_ROOT_ENV` is the env-var name constant. Consumed by `fileUtils.js` (`PATHS`), `server/index.js`, and `scripts/run-migrations.js`. |-| `fileUtils.js` | `PATHS` constants, `atomicWrite`, `tryReadFile`, `pathExists` (async `existsSync` replacement for request/hot paths), `safeJSONParse`, `expandHome` (`~/foo` → absolute), `sleep(ms)`, `sanitizeFilename`, `importFileToUploads(tempPath, name)` (land a server-produced temp file in `PATHS.uploads` with `/api/uploads` naming), JSONL append/read/write helpers, dir scans, hashes, JSON helpers. Most paths/file work goes through here. |+| `fileUtils.js` | `PATHS` constants, `atomicWrite`, `tryReadFile`, `pathExists` (async `existsSync` replacement for request/hot paths), `safeJSONParse`, `expandHome` (`~/foo` → absolute), `sleep(ms)`, `sanitizeFilename`, `importFileToUploads(tempPath, name)` (land a server-produced temp file in `PATHS.uploads` with `/api/uploads` naming), `saveBase64Upload(dir, { filename, data }, { allowedExtensions, maxBytes })` + `serveLocalFile(res, dir, filename, opts?)` (shared attachment upload/serve pipeline — allowlist, size cap, `<uuid8>-name`, containment guard, nosniff/disposition), extension allowlists (`ATTACHMENT_ALLOWED_EXTENSIONS`, `SONGBOOK_ATTACHMENT_EXTENSIONS`), JSONL append/read/write helpers, dir scans, hashes, JSON helpers. Most paths/file work goes through here. || `boundedStateMap.js` | `createBoundedStateMap({ maxSize, ttlMs })` — a `Map` that self-evicts so a per-key state cache can't grow one entry per key forever. Lazy TTL + LRU eviction on `get`/`set` (no timers); `get` doubles as the LRU touch. Used by the moltbook/moltworld rate-limiters to bound their per-agent state. || `createKeyCachedQueue.js` | Per-KEY serialized async work queue (sibling to `fileWriteQueue.js`'s single tail). `createKeyCachedQueue()` returns `queue(key, work)` that chains each `work` thunk onto the prior in-flight promise for that `key` — same-key work runs one-after-another (later sees earlier's committed result), different keys run concurrently. Self-pruning tail Map; `work` runs on both fulfil and reject so one failure can't stall the chain; carries `.clear()` for test reset. Used by the media-job completion hooks (writers-room / catalog / music-video scene-image attach) to serialize per-record. || `createNewestWinsGuard.js` | Newest-render-wins ordering guard for out-of-order async completions. `createNewestWinsGuard()` returns `{ isStale(key, at), mark(key, at), clear() }` — tracks the newest applied `queuedAt` per slot `key` so an older render completing after a newer one is dropped (`isStale` true) instead of clobbering the newer frame. ISO timestamps compare as strings; absent `at` is never stale. Used by `createMediaJobImageHook`'s opt-in guard and the catalog hook's portrait slot. |@@ -198,6 +198,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| Module | Purpose ||---|---|+| `htmlToText.js` | Shared HTML → plain-text converter. `htmlToText(html, { extraEntities?, paragraphBreak?, collapseSpaces? })` — strips script/style/head/noscript blocks, converts `<br>`/block closes to newlines, strips remaining tags, decodes entities via `decodeXmlEntities`, collapses 3+ newlines, trims. Options preserve caller-specific output (Gmail: `paragraphBreak: '\n\n'` + `collapseSpaces`; SongBook import: defaults — space runs preserved for tab alignment). || `jsonExtract.js` | Pull JSON blocks out of LLM responses. || `taskParser.js` | Parse `TASKS.md` format. || `xmlEntities.js` | Shared dependency-free XML/HTML entity decoder. `decodeXmlEntities(str, extraEntities?)` — single-pass (double-decode-safe) decode of the five predefined named entities + decimal/hex numeric refs, with an optional caller-supplied extra-entity map (e.g. `{ nbsp: ' ', zwnj: '' }`). Unknown/out-of-range refs left untouched. Used by the Apple Health XML parser, Claude changelog feed, Pinterest RSS, generic feeds, and Gmail HTML-to-text. |diff --git a/server/lib/brainValidation.js b/server/lib/brainValidation.jsindex ea61f08d99..7f9842f140 100644--- a/server/lib/brainValidation.js+++ b/server/lib/brainValidation.js@@ -562,17 +562,10 @@ export const songInstrumentEnum = z.enum(['guitar', 'piano', 'ukulele', 'bass',// Content notation format (drives the client-side parser/renderer)export const songContentFormatEnum = z.enum(['chordpro', 'tab', 'plain']);-// Attachment metadata — synced in the record; the BYTES are machine-local-// under data/brain/songbook/ (peers lacking the file show "not on this machine").-export const songAttachmentSchema = z.object({- filename: z.string().min(1).max(300),- label: z.string().max(300).optional().default(''),- mime: z.string().max(100),- size: z.number().int().min(0),- sha256: z.string().length(64)-});--// Create/Update Song input schema+// Create/Update Song input schema. Attachment metadata ({ filename, label,+// mime, size, sha256 }) is server-managed — synced in the record, mutated only+// by the attachment endpoints, never client-suppliable (no schema key here, so+// Zod's unknown-key stripping drops it).export const songInputSchema = z.object({title: z.string().trim().min(1).max(300),artist: z.string().trim().max(300).optional().default(''),@@ -587,26 +580,9 @@ export const songInputSchema = z.object({format: songContentFormatEnum.optional().default('tab'),text: z.string().max(200000).optional().default('')}).optional().default({ format: 'tab', text: '' }),- scrollDurationSec: z.number().int().min(15).max(3600).nullable().optional().default(null),notes: z.string().max(5000).optional().default('')});-// Full Song record — input plus server-managed fields. `attachments` is-// mutated ONLY by the attachment endpoints (PUT strips client-supplied values);-// id/createdAt/updatedAt/originInstanceId are stamped by brainStorage.-export const songRecordSchema = songInputSchema.extend({- id: z.string().guid(),- attachments: z.array(songAttachmentSchema).optional().default([]),- originInstanceId: z.string().optional(),- createdAt: z.string().datetime(),- updatedAt: z.string().datetime()-});--// PATCH /api/brain/songbook/:id/stage — cheap chip-flip path-export const songStagePatchSchema = z.object({- stage: songStageEnum-});-// POST /api/brain/songbook/import/urlexport const songImportUrlSchema = z.object({url: z.string().url().max(2000)diff --git a/server/lib/fileUtils.js b/server/lib/fileUtils.jsindex 9552e9c538..1baa622c07 100644--- a/server/lib/fileUtils.js+++ b/server/lib/fileUtils.js@@ -852,6 +852,18 @@ export const ATTACHMENT_ALLOWED_EXTENSIONS = new Set(['.zip', '.tar', '.gz',]);+/**+ * Curated allowlist for SongBook attachments (sheet-music PDFs, scans, MIDI,+ * practice audio). Deliberately NOT a superset of ATTACHMENT_ALLOWED_EXTENSIONS+ * — code/archive/config types make no sense on a song record, while MIDI and+ * audio (which the CoS attachment set excludes) are core sheet-music formats.+ */+export const SONGBOOK_ATTACHMENT_EXTENSIONS = new Set([+ '.pdf', '.png', '.jpg', '.jpeg', '.gif', '.webp', '.svg',+ '.txt', '.md',+ '.mid', '.midi', '.mp3', '.wav', '.m4a', '.ogg',+]);+/*** Look up the MIME type for a file extension (including the leading dot, e.g.* ".png"). Returns 'application/octet-stream' for unknown extensions.@@ -957,6 +969,88 @@ export async function importFileToUploads(tempPath, originalName) {return importFileToDir(tempPath, originalName, PATHS.uploads);}+/**+ * Persist a base64-encoded upload into `dir` with the shared attachment+ * pipeline: extension allowlist → base64 decode → size cap → ensureDir →+ * `<uuid8>-<sanitized-name>` naming → containment guard → write.+ *+ * Throws ServerError with the exact status/code/message contract the+ * attachment routes established (`INVALID_FILE_TYPE`, `FILE_TOO_LARGE`,+ * `INVALID_FILENAME` — all 400), so refactored routes keep their pinned+ * responses. Consolidates `routes/attachments.js` and+ * `routes/brainSongbook.js` (uploads.js has a different shape — see PLAN.md).+ *+ * @param {string} dir - Destination directory (created if missing).+ * @param {{ filename: string, data: string }} upload - Original filename ++ * base64 payload (validated as present by the calling route).+ * @param {{ allowedExtensions: Set<string>, maxBytes: number }} opts+ * @returns {Promise<{ id: string, filename: string, filePath: string,+ * buffer: Buffer, size: number, mime: string }>} `id` is the full UUID whose+ * first 8 chars prefix `filename`.+ */+export async function saveBase64Upload(dir, { filename, data }, { allowedExtensions, maxBytes }) {+ const ext = getFileExtension(filename);+ if (!ext || !allowedExtensions.has(ext)) {+ const allowedList = [...allowedExtensions].join(', ');+ throw new ServerError(`File type not allowed. Supported: ${allowedList}`, { status: 400, code: 'INVALID_FILE_TYPE' });+ }++ const buffer = Buffer.from(data, 'base64');+ if (buffer.length > maxBytes) {+ throw new ServerError(`File exceeds maximum size of ${maxBytes / 1024 / 1024}MB`, { status: 400, code: 'FILE_TOO_LARGE' });+ }++ await ensureDir(dir);++ // Unique uuid prefix avoids collisions; sanitize kills traversal characters.+ const id = randomUUID();+ const fname = `${id.slice(0, 8)}-${sanitizeFilename(filename)}`;+ const filePath = join(dir, fname);+ // Double-check the path is within the destination dir (defense in depth).+ if (!isPathInsideDir(dir, filePath)) {+ throw new ServerError('Invalid filename', { status: 400, code: 'INVALID_FILENAME' });+ }++ await writeFile(filePath, buffer);++ return { id, filename: fname, filePath, buffer, size: buffer.length, mime: getMimeType(getFileExtension(fname)) };+}++/**+ * Serve a machine-local file from `dir` by user-supplied filename with the+ * shared safety pipeline: sanitize → containment guard (400+ * `INVALID_FILENAME`) → existence check (404, message/code parametrized via+ * `missingError` so routes keep their contracts) → `X-Content-Type-Options:+ * nosniff` → attachment disposition for RISKY_MIME_TYPES → `res.sendFile`.+ *+ * Mirrors the exact serving behavior of `routes/attachments.js`.+ *+ * @param {import('express').Response} res+ * @param {string} dir - The containing directory.+ * @param {string} filename - Raw user-supplied filename.+ * @param {{ missingError?: { message: string, code: string } }} [opts]+ */+export async function serveLocalFile(res, dir, filename, { missingError } = {}) {+ const safeFilename = sanitizeFilename(filename);+ const filePath = resolvePath(dir, safeFilename);++ if (!isPathInsideDir(dir, filePath)) {+ throw new ServerError('Invalid filename', { status: 400, code: 'INVALID_FILENAME' });+ }++ if (!(await pathExists(filePath))) {+ const { message = 'Attachment not found', code = 'NOT_FOUND' } = missingError || {};+ throw new ServerError(message, { status: 404, code });+ }++ const mimeType = getMimeType(getFileExtension(safeFilename));+ res.set('X-Content-Type-Options', 'nosniff');+ if (RISKY_MIME_TYPES.has(mimeType)) {+ res.set('Content-Disposition', `attachment; filename="${safeFilename}"`);+ }+ res.type(mimeType).sendFile(filePath);+}+/*** Validate a user-supplied filename is a safe basename with one of the* allowed extensions — refuses path-traversal, null bytes, separators, anddiff --git a/server/lib/htmlToText.js b/server/lib/htmlToText.jsnew file mode 100644index 0000000000..1681756841--- /dev/null+++ b/server/lib/htmlToText.js@@ -0,0 +1,51 @@+/**+ * Shared HTML → readable plain text converter.+ *+ * A single dependency-free strip-tags pipeline for the places PortOS turns+ * fetched/synced HTML into text (Gmail message bodies, SongBook URL imports).+ * Replaces the near-identical private copies that lived in+ * `services/messageGmailSync.js` and `services/brainSongbookImport.js`.+ *+ * Pipeline: drop <script>/<style>/<head>/<noscript> blocks wholesale, convert+ * <br> and block-element closes to newlines, strip every remaining tag, decode+ * entities via the shared `decodeXmlEntities`, normalize line endings, collapse+ * runs of 3+ newlines to a blank line, and trim.+ *+ * Options exist only to preserve each caller's historical observable output:+ * - `extraEntities` — merged on top of `{ nbsp: ' ' }` (Gmail adds+ * `{ zwnj: '' }` for mail-specific zero-width chars).+ * - `paragraphBreak` — what `</p>` becomes. Default `'\n'` (SongBook —+ * tab sheets want tight lines); Gmail passes `'\n\n'`+ * so paragraphs keep a blank line between them.+ * - `collapseSpaces` — collapse runs of spaces/tabs to one space. Default+ * false — NEVER enable for tab/chord sheets, whose+ * column alignment is meaningful. Gmail enables it.+ */++import { decodeXmlEntities } from './xmlEntities.js';++/**+ * Convert an HTML document/fragment to plain text.+ *+ * @param {string} html - Raw HTML. Non-strings return ''.+ * @param {object} [options]+ * @param {Object<string,string>} [options.extraEntities] - Extra named entities+ * merged on top of `{ nbsp: ' ' }` and the predefined five.+ * @param {string} [options.paragraphBreak='\n'] - Replacement for `</p>`.+ * @param {boolean} [options.collapseSpaces=false] - Collapse space/tab runs.+ * @returns {string} Readable plain text, trimmed.+ */+export function htmlToText(html, { extraEntities, paragraphBreak = '\n', collapseSpaces = false } = {}) {+ if (typeof html !== 'string') return '';+ const stripped = html+ .replace(/<(script|style|head|noscript)\b[\s\S]*?<\/\1>/gi, '')+ .replace(/<br\s*\/?>/gi, '\n')+ .replace(/<\/p>/gi, paragraphBreak)+ .replace(/<\/(div|li|tr|h[1-6])>/gi, '\n')+ .replace(/<[^>]+>/g, '');+ let text = decodeXmlEntities(stripped, { nbsp: ' ', ...extraEntities })+ .replace(/\r\n?/g, '\n')+ .replace(/\n{3,}/g, '\n\n');+ if (collapseSpaces) text = text.replace(/[ \t]+/g, ' ');+ return text.trim();+}diff --git a/server/lib/htmlToText.test.js b/server/lib/htmlToText.test.jsnew file mode 100644index 0000000000..cd602476ea--- /dev/null+++ b/server/lib/htmlToText.test.js@@ -0,0 +1,52 @@+import { describe, it, expect } from 'vitest';+import { htmlToText } from './htmlToText.js';++describe('htmlToText', () => {+ it('drops script/style/head/noscript blocks and strips tags', () => {+ const html = '<html><head><title>x</title><style>.a{}</style></head><body>' ++ '<script>var a = 1;</script><noscript>enable js</noscript><p>Hello</p></body></html>';+ const text = htmlToText(html);+ expect(text).toBe('Hello');+ expect(text).not.toContain('var a');+ expect(text).not.toContain('enable js');+ });++ it('converts <br> and block closes to newlines', () => {+ expect(htmlToText('a<br>b</div>c</li>d</tr>e</h2>f')).toBe('a\nb\nc\nd\ne\nf');+ });++ it('uses a single newline for </p> by default', () => {+ expect(htmlToText('<p>one</p><p>two</p>')).toBe('one\ntwo');+ });++ it('honors paragraphBreak for </p> (Gmail keeps blank lines)', () => {+ expect(htmlToText('<p>one</p><p>two</p>', { paragraphBreak: '\n\n' })).toBe('one\n\ntwo');+ });++ it('decodes entities including nbsp and caller extras', () => {+ expect(htmlToText('C G & AB')).toBe('C G & AB');+ expect(htmlToText('a‌b', { extraEntities: { zwnj: '' } })).toBe('ab');+ });++ it('leaves out-of-range numeric entities untouched (never throws)', () => {+ expect(htmlToText('� ok')).toBe('� ok');+ });++ it('preserves inner space runs by default (tab-sheet alignment)', () => {+ expect(htmlToText('<pre>C G</pre>')).toBe('C G');+ });++ it('collapses space/tab runs when collapseSpaces is set', () => {+ expect(htmlToText('a \t b', { collapseSpaces: true })).toBe('a b');+ });++ it('normalizes CRLF and collapses 3+ newlines, then trims', () => {+ expect(htmlToText('\n\na\r\n\r\n\r\nb\n\n')).toBe('a\n\nb');+ });++ it('returns "" for non-strings', () => {+ expect(htmlToText(null)).toBe('');+ expect(htmlToText(undefined)).toBe('');+ expect(htmlToText(42)).toBe('');+ });+});diff --git a/server/lib/index.js b/server/lib/index.jsindex e7177cf366..f0e6440e4c 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -178,6 +178,7 @@ export * from './rrfRanking.js';export * from './vectorMath.js';// === Extraction & parsing ===+export * from './htmlToText.js';export * from './jsonExtract.js';export * from './taskParser.js';export * from './xmlEntities.js';diff --git a/server/lib/navManifest.test.js b/server/lib/navManifest.test.jsindex b7acb9bc5f..3dca30bb20 100644--- a/server/lib/navManifest.test.js+++ b/server/lib/navManifest.test.js@@ -312,6 +312,7 @@ const NAV_COVERAGE_OPT_OUT = new Map([['/apps/create', 'create-app form, reached via the "New App" button on /apps'],['/feature-agents/create', 'create-agent form, reached via the "New Agent" button'],['/login', 'auth gate — surfaced only when settings.secrets.auth is enabled, reached via 401 redirect'],+ ['/songbook/import', 'import-song form, reached via the "Import" button on /songbook'],['/universes/new', 'create-mode sentinel for the Universe Builder editor'],]);diff --git a/server/lib/xmlEntities.js b/server/lib/xmlEntities.jsindex dba9fab6b5..464d89cd53 100644--- a/server/lib/xmlEntities.js+++ b/server/lib/xmlEntities.js@@ -18,6 +18,9 @@* emitted. Unknown entities and out-of-range numeric code points are left* 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.*/const NAMED_ENTITIES = {diff --git a/server/routes/attachments.js b/server/routes/attachments.jsindex 36c690131a..1338fb30be 100644--- a/server/routes/attachments.js+++ b/server/routes/attachments.js@@ -4,13 +4,12 @@*/import { Router } from 'express';-import { writeFile, unlink, readdir, stat } from 'fs/promises';+import { unlink, readdir, stat } from 'fs/promises';import { join, resolve } from 'path';-import { v4 as uuidv4 } from '../lib/uuid.js';import { asyncHandler, ServerError } from '../lib/errorHandler.js';import {- ensureDir, pathExists, PATHS, RISKY_MIME_TYPES,- sanitizeFilename, getFileExtension, getMimeType, ATTACHMENT_ALLOWED_EXTENSIONS, isPathInsideDir,+ pathExists, PATHS, sanitizeFilename, getFileExtension, getMimeType,+ ATTACHMENT_ALLOWED_EXTENSIONS, isPathInsideDir, saveBase64Upload, serveLocalFile,} from '../lib/fileUtils.js';const ATTACHMENTS_DIR = PATHS.cosAttachments;@@ -20,15 +19,6 @@ const router = Router();// Max file size: 50MB (larger than screenshots to accommodate documents)const MAX_FILE_SIZE = 50 * 1024 * 1024;-/**- * Validate file extension is allowed for attachments.- * Uses the strict ATTACHMENT_ALLOWED_EXTENSIONS allowlist from fileUtils.- */-function isAllowedExtension(filename) {- const ext = getFileExtension(filename);- return ext && ATTACHMENT_ALLOWED_EXTENSIONS.has(ext);-}-// POST /api/attachments - Upload a file attachment (base64)router.post('/', asyncHandler(async (req, res) => {const { data, filename } = req.body;@@ -41,76 +31,28 @@ router.post('/', asyncHandler(async (req, res) => {throw new ServerError('filename is required', { status: 400, code: 'VALIDATION_ERROR' });}- // Validate extension- if (!isAllowedExtension(filename)) {- const allowedList = [...ATTACHMENT_ALLOWED_EXTENSIONS].join(', ');- throw new ServerError(`File type not allowed. Supported: ${allowedList}`, { status: 400, code: 'INVALID_FILE_TYPE' });- }-- // Decode base64 and validate size- const buffer = Buffer.from(data, 'base64');- if (buffer.length > MAX_FILE_SIZE) {- throw new ServerError(`File exceeds maximum size of ${MAX_FILE_SIZE / 1024 / 1024}MB`, { status: 400, code: 'FILE_TOO_LARGE' });- }-- // Ensure attachments directory exists (ensureDir is idempotent — mkdir- // recursive — so no existence pre-check is needed on this upload path).- await ensureDir(ATTACHMENTS_DIR);-- const id = uuidv4();- const safeName = sanitizeFilename(filename);- const ext = getFileExtension(safeName);- // Create unique filename with UUID prefix to avoid collisions- const fname = `${id.slice(0, 8)}-${safeName}`;- const filepath = join(ATTACHMENTS_DIR, fname);-- // Double-check path is within attachments directory (defense in depth)- if (!isPathInsideDir(ATTACHMENTS_DIR, filepath)) {- throw new ServerError('Invalid filename', { status: 400, code: 'INVALID_FILENAME' });- }-- await writeFile(filepath, buffer);-- const mimeType = getMimeType(ext);+ // Shared pipeline: allowlist → decode → size cap → `<uuid8>-name` → write.+ const saved = await saveBase64Upload(ATTACHMENTS_DIR, { filename, data }, {+ allowedExtensions: ATTACHMENT_ALLOWED_EXTENSIONS,+ maxBytes: MAX_FILE_SIZE,+ });- console.log(`📎 Attachment saved: ${fname} (${buffer.length} bytes, ${mimeType})`);+ console.log(`📎 Attachment saved: ${saved.filename} (${saved.size} bytes, ${saved.mime})`);res.json({- id,- filename: fname,+ id: saved.id,+ filename: saved.filename,originalName: filename,// API-relative URL only — never the absolute FS path (leaks install layout).- path: `/api/attachments/${encodeURIComponent(fname)}`,- size: buffer.length,- mimeType+ path: `/api/attachments/${encodeURIComponent(saved.filename)}`,+ size: saved.size,+ mimeType: saved.mime});}));// GET /api/attachments/:filename - Serve an attachmentrouter.get('/:filename', asyncHandler(async (req, res) => {- const { filename } = req.params;- // Sanitize filename to prevent path traversal- const safeFilename = sanitizeFilename(filename);- const filepath = resolve(ATTACHMENTS_DIR, safeFilename);-- // Verify the resolved path is within attachments directory- if (!isPathInsideDir(ATTACHMENTS_DIR, filepath)) {- throw new ServerError('Invalid filename', { status: 400, code: 'INVALID_FILENAME' });- }-- if (!(await pathExists(filepath))) {- throw new ServerError('Attachment not found', { status: 404, code: 'NOT_FOUND' });- }-- const ext = getFileExtension(safeFilename);- const mimeType = getMimeType(ext);-- res.set('X-Content-Type-Options', 'nosniff');- if (RISKY_MIME_TYPES.has(mimeType)) {- res.set('Content-Disposition', `attachment; filename="${safeFilename}"`);- }-- res.type(mimeType).sendFile(filepath);+ await serveLocalFile(res, ATTACHMENTS_DIR, req.params.filename);}));// DELETE /api/attachments/:filename - Delete an attachmentdiff --git a/server/routes/brainSongbook.js b/server/routes/brainSongbook.jsindex 6a73c05e16..7e881fab6f 100644--- a/server/routes/brainSongbook.js+++ b/server/routes/brainSongbook.js@@ -14,24 +14,22 @@*/import { Router } from 'express';-import { writeFile, unlink } from 'fs/promises';+import { unlink } from 'fs/promises';import { join, resolve } from 'path';import { createHash } from 'crypto';-import { v4 as uuidv4 } from '../lib/uuid.js';import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { validateRequest } from '../lib/validation.js';import { partialWithoutDefaults } from '../lib/zodCompat.js';import {songInputSchema,- songStagePatchSchema,songImportUrlSchema,songAttachmentUploadSchema,} from '../lib/brainValidation.js';import * as brainStorage from '../services/brainStorage.js';import { importSongFromUrl } from '../services/brainSongbookImport.js';import {- ensureDir, pathExists, PATHS, RISKY_MIME_TYPES,- sanitizeFilename, getFileExtension, getMimeType, ATTACHMENT_ALLOWED_EXTENSIONS, isPathInsideDir,+ pathExists, PATHS, sanitizeFilename, isPathInsideDir,+ SONGBOOK_ATTACHMENT_EXTENSIONS, saveBase64Upload, serveLocalFile,} from '../lib/fileUtils.js';const router = Router();@@ -39,27 +37,22 @@ const router = Router();// Max attachment size: 50MB (matches routes/attachments.js — sheet-music PDFs)const MAX_ATTACHMENT_SIZE = 50 * 1024 * 1024;-// The shared attachment allowlist plus MIDI — sheet music commonly ships as-// .mid/.midi, which the CoS attachment set deliberately excludes.-const SONG_ATTACHMENT_EXTENSIONS = new Set([...ATTACHMENT_ALLOWED_EXTENSIONS, '.mid', '.midi']);-// Read lazily (not captured at module load) so test PATHS mocks with// per-suite temp roots resolve correctly.const songbookDir = () => PATHS.brainSongbook;-const isAllowedExtension = (filename) => {- const ext = getFileExtension(filename);- return !!ext && SONG_ATTACHMENT_EXTENSIONS.has(ext);-};--async function getSongOr404(id) {- const song = await brainStorage.getById('songs', id);+// 404 unless the storage layer returned a record (or a truthy delete result).+function requireSong(song) {if (!song) {throw new ServerError('Song not found', { status: 404, code: 'NOT_FOUND' });}return song;}+async function getSongOr404(id) {+ return requireSong(await brainStorage.getById('songs', id));+}+// Locate an attachment's meta on a song + its vetted local filepath. Throws// 400 on a traversal-shaped filename and 404 when the meta isn't on the record.function resolveAttachment(song, rawFilename) {@@ -115,19 +108,7 @@ router.put('/:id', asyncHandler(async (req, res) => {// has no `attachments` key, so Zod's unknown-key stripping drops any// client-supplied attachments — the record's server-managed list survives.const data = validateRequest(partialWithoutDefaults(songInputSchema), req.body);- const song = await brainStorage.update('songs', req.params.id, data);- if (!song) {- throw new ServerError('Song not found', { status: 404, code: 'NOT_FOUND' });- }- res.json(song);-}));--router.patch('/:id/stage', asyncHandler(async (req, res) => {- const { stage } = validateRequest(songStagePatchSchema, req.body);- const song = await brainStorage.update('songs', req.params.id, { stage });- if (!song) {- throw new ServerError('Song not found', { status: 404, code: 'NOT_FOUND' });- }+ const song = requireSong(await brainStorage.update('songs', req.params.id, data));res.json(song);}));@@ -135,10 +116,7 @@ router.delete('/:id', asyncHandler(async (req, res) => {// Tombstone delete (brainStorage.remove) so the deletion federates. Local// attachment bytes are left in place — peers may still hold the meta, and// orphaned bytes are harmless machine-local files.- const deleted = await brainStorage.remove('songs', req.params.id);- if (!deleted) {- throw new ServerError('Song not found', { status: 404, code: 'NOT_FOUND' });- }+ requireSong(await brainStorage.remove('songs', req.params.id));res.json({ id: req.params.id });}));@@ -151,39 +129,23 @@ router.post('/:id/attachments', asyncHandler(async (req, res) => {const song = await getSongOr404(req.params.id);const { filename, data, label } = validateRequest(songAttachmentUploadSchema, req.body);- if (!isAllowedExtension(filename)) {- const allowedList = [...SONG_ATTACHMENT_EXTENSIONS].join(', ');- throw new ServerError(`File type not allowed. Supported: ${allowedList}`, { status: 400, code: 'INVALID_FILE_TYPE' });- }-- const buffer = Buffer.from(data, 'base64');- if (buffer.length > MAX_ATTACHMENT_SIZE) {- throw new ServerError(`File exceeds maximum size of ${MAX_ATTACHMENT_SIZE / 1024 / 1024}MB`, { status: 400, code: 'FILE_TOO_LARGE' });- }-- await ensureDir(songbookDir());-- // Unique uuid prefix avoids collisions; sanitize kills traversal characters.- const fname = `${uuidv4().slice(0, 8)}-${sanitizeFilename(filename)}`;- const filepath = join(songbookDir(), fname);- if (!isPathInsideDir(songbookDir(), filepath)) {- throw new ServerError('Invalid filename', { status: 400, code: 'INVALID_FILENAME' });- }-- await writeFile(filepath, buffer);+ const saved = await saveBase64Upload(songbookDir(), { filename, data }, {+ allowedExtensions: SONGBOOK_ATTACHMENT_EXTENSIONS,+ maxBytes: MAX_ATTACHMENT_SIZE,+ });const attachment = {- filename: fname,+ filename: saved.filename,label,- mime: getMimeType(getFileExtension(fname)),- size: buffer.length,- sha256: createHash('sha256').update(buffer).digest('hex'),+ mime: saved.mime,+ size: saved.size,+ sha256: createHash('sha256').update(saved.buffer).digest('hex'),};await brainStorage.update('songs', song.id, {attachments: [...(Array.isArray(song.attachments) ? song.attachments : []), attachment],});- console.log(`🎸 Song attachment saved: ${fname} (${buffer.length} bytes)`);+ console.log(`🎸 Song attachment saved: ${saved.filename} (${saved.size} bytes)`);res.status(201).json({ attachment });}));@@ -198,22 +160,15 @@ router.get('/:id/attachments', asyncHandler(async (req, res) => {res.json(attachments);}));-// GET /:id/attachments/:filename — serve the local bytes+// GET /:id/attachments/:filename — serve the local bytes. resolveAttachment+// runs first so a filename not on the record 404s even when a file exists;+// the shared server then handles the meta-synced-but-bytes-absent case.router.get('/:id/attachments/:filename', asyncHandler(async (req, res) => {const song = await getSongOr404(req.params.id);- const { safeFilename, filepath } = resolveAttachment(song, req.params.filename);-- if (!(await pathExists(filepath))) {- // Meta is synced but the bytes never landed on this machine.- throw new ServerError('Attachment file is not on this machine', { status: 404, code: 'NOT_ON_THIS_MACHINE' });- }-- const mimeType = getMimeType(getFileExtension(safeFilename));- res.set('X-Content-Type-Options', 'nosniff');- if (RISKY_MIME_TYPES.has(mimeType)) {- res.set('Content-Disposition', `attachment; filename="${safeFilename}"`);- }- res.type(mimeType).sendFile(filepath);+ resolveAttachment(song, req.params.filename);+ await serveLocalFile(res, songbookDir(), req.params.filename, {+ missingError: { message: 'Attachment file is not on this machine', code: 'NOT_ON_THIS_MACHINE' },+ });}));// DELETE /:id/attachments/:filename — remove meta from record + local bytesdiff --git a/server/routes/brainSongbook.test.js b/server/routes/brainSongbook.test.jsindex 5fe20557dd..0d8a8198f9 100644--- a/server/routes/brainSongbook.test.js+++ b/server/routes/brainSongbook.test.js@@ -66,7 +66,6 @@ const baseSong = (overrides = {}) => ({tuning: '',sourceUrl: '',content: { format: 'tab', text: 'e|--0--|' },- scrollDurationSec: null,notes: '',attachments: [],createdAt: '2026-07-01T00:00:00.000Z',@@ -126,7 +125,6 @@ describe('Brain SongBook routes', () => {stage: 'new',capo: 0,content: { format: 'tab', text: '' },- scrollDurationSec: null,attachments: [],}));});@@ -155,16 +153,25 @@ describe('Brain SongBook routes', () => {});describe('PUT /api/brain/songbook/:id', () => {- it('updates only the sent fields (no default injection)', async () => {+ it('updates only the sent fields (no default injection) — the stage-flip path', async () => {brainStorage.update.mockResolvedValue(baseSong({ stage: 'learning' }));const res = await request(app).put(`/api/brain/songbook/${SONG_ID}`).send({ stage: 'learning' });expect(res.status).toBe(200);+ expect(res.body.stage).toBe('learning');// Exactly the sent field — an omitted title/capo/etc. must not reset to defaults.expect(brainStorage.update).toHaveBeenCalledWith('songs', SONG_ID, { stage: 'learning' });});+ it('400s on an invalid stage', async () => {+ const res = await request(app)+ .put(`/api/brain/songbook/${SONG_ID}`)+ .send({ stage: 'perfected' });+ expect(res.status).toBe(400);+ expect(brainStorage.update).not.toHaveBeenCalled();+ });+it('strips client-supplied attachments', async () => {brainStorage.update.mockResolvedValue(baseSong());await request(app)@@ -182,34 +189,6 @@ describe('Brain SongBook routes', () => {});});- describe('PATCH /api/brain/songbook/:id/stage', () => {- it('flips the stage', async () => {- brainStorage.update.mockResolvedValue(baseSong({ stage: 'memorized' }));- const res = await request(app)- .patch(`/api/brain/songbook/${SONG_ID}/stage`)- .send({ stage: 'memorized' });- expect(res.status).toBe(200);- expect(res.body.stage).toBe('memorized');- expect(brainStorage.update).toHaveBeenCalledWith('songs', SONG_ID, { stage: 'memorized' });- });-- it('400s on an invalid stage', async () => {- const res = await request(app)- .patch(`/api/brain/songbook/${SONG_ID}/stage`)- .send({ stage: 'perfected' });- expect(res.status).toBe(400);- expect(brainStorage.update).not.toHaveBeenCalled();- });-- it('404s when the song is missing', async () => {- brainStorage.update.mockResolvedValue(null);- const res = await request(app)- .patch(`/api/brain/songbook/${SONG_ID}/stage`)- .send({ stage: 'learning' });- expect(res.status).toBe(404);- });- });-describe('DELETE /api/brain/songbook/:id', () => {it('tombstones and returns { id }', async () => {brainStorage.remove.mockResolvedValue(true);diff --git a/server/services/brainSongbookImport.js b/server/services/brainSongbookImport.jsindex 8100f6c0ad..cf18c64924 100644--- a/server/services/brainSongbookImport.js+++ b/server/services/brainSongbookImport.js@@ -17,31 +17,17 @@import { fetchPublicText } from '../lib/safeUrlFetch.js';import { safeJSONParse } from '../lib/fileUtils.js';import { ServerError } from '../lib/errorHandler.js';+import { decodeXmlEntities } from '../lib/xmlEntities.js';+import { htmlToText } from '../lib/htmlToText.js';// Matches songInputSchema's content.text max — clamp instead of failing the// draft so an oversized page still yields something editable.const MAX_CONTENT_CHARS = 200000;-const NAMED_ENTITIES = { lt: '<', gt: '>', quot: '"', apos: "'", nbsp: ' ' };--// Guarded String.fromCodePoint — out-of-range numeric entities decode to ''-// instead of throwing (the parser must never throw on hostile/garbled HTML).-const safeCodePoint = (n) =>- (Number.isInteger(n) && n >= 0 && n <= 0x10ffff ? String.fromCodePoint(n) : '');--/**- * Decode the HTML entities that matter for tab pages (named basics + numeric).- * `&` decodes LAST so double-encoded sequences ("&lt;") don't- * double-decode into markup.- */-export function decodeHtmlEntities(str) {- if (typeof str !== 'string') return '';- return str- .replace(/&#x([0-9a-f]+);/gi, (_, hex) => safeCodePoint(parseInt(hex, 16)))- .replace(/&#(\d+);/g, (_, dec) => safeCodePoint(Number(dec)))- .replace(/&(lt|gt|quot|apos|nbsp);/gi, (_, name) => NAMED_ENTITIES[name.toLowerCase()])- .replace(/&/gi, '&');-}+// Shared entity decoder (single-pass, double-decode-safe, out-of-range numeric+// refs left untouched — never throws on hostile/garbled HTML). ` ` is the+// one non-predefined entity tab pages routinely carry.+const decodeEntities = (str) => decodeXmlEntities(str, { nbsp: ' ' });/*** Strip Ultimate-Guitar chord/tab markers ([ch]C[/ch], [tab]...[/tab]) from@@ -68,7 +54,7 @@ export function extractUltimateGuitarStore(html) {if (typeof html !== 'string') return null;const match = /<div[^>]*class="[^"]*js-store[^"]*"[^>]*data-content="([^"]*)"/i.exec(html);if (!match) return null;- const parsed = safeJSONParse(decodeHtmlEntities(match[1]), null);+ const parsed = safeJSONParse(decodeEntities(match[1]), null);// Observed shape nests under a top-level `store` key; tolerate both.const data = parsed?.store?.page?.data ?? parsed?.page?.data;const content = data?.tab_view?.wiki_tab?.content;@@ -95,24 +81,10 @@ export function extractLargestPre(html) {for (let m = re.exec(html); m; m = re.exec(html)) {if (m[1].length > largest.length) largest = m[1];}- const text = normalizeSheetText(decodeHtmlEntities(largest.replace(/<[^>]+>/g, '')));+ const text = normalizeSheetText(decodeEntities(largest.replace(/<[^>]+>/g, '')));return text.length >= MIN_PRE_CHARS ? text : null;}-/**- * Last-resort extractor: strip scripts/styles/tags to plain text. Always- * returns a string (possibly empty).- */-export function stripHtmlToText(html) {- if (typeof html !== 'string') return '';- const text = html- .replace(/<(script|style|head|noscript)\b[\s\S]*?<\/\1>/gi, '')- .replace(/<br\s*\/?>/gi, '\n')- .replace(/<\/(p|div|li|tr|h[1-6])>/gi, '\n')- .replace(/<[^>]+>/g, '');- return normalizeSheetText(decodeHtmlEntities(text));-}-// Strip "(ver 2)" suffixes and trailing sheet-type keywords from a <title>-derived song name.const cleanTitlePart = (s) => {const cleaned = s@@ -129,7 +101,7 @@ const cleanTitlePart = (s) => {*/export function parseTitleArtist(html) {const match = /<title[^>]*>([\s\S]*?)<\/title>/i.exec(typeof html === 'string' ? html : '');- const raw = decodeHtmlEntities(match?.[1] ?? '').split(/[|@]/)[0].replace(/\s+/g, ' ').trim();+ const raw = decodeEntities(match?.[1] ?? '').split(/[|@]/)[0].replace(/\s+/g, ' ').trim();if (!raw) return { title: '', artist: '' };const by = /^(.+?)\s+by\s+(.+)$/i.exec(raw);if (by) return { title: cleanTitlePart(by[1]), artist: by[2].trim() };@@ -165,10 +137,12 @@ export function buildDraftFromHtml(html, url) {};}+ // Last resort: shared strip-tags plain text (space runs preserved — the+ // default htmlToText options — in case the page held aligned sheet text).return {title: fallback.title,artist: fallback.artist,- content: { format: 'plain', text: stripHtmlToText(html).slice(0, MAX_CONTENT_CHARS) },+ content: { format: 'plain', text: htmlToText(html).slice(0, MAX_CONTENT_CHARS) },sourceUrl: url,};}diff --git a/server/services/brainSongbookImport.test.js b/server/services/brainSongbookImport.test.jsindex be2425fc46..8225ef8dde 100644--- a/server/services/brainSongbookImport.test.js+++ b/server/services/brainSongbookImport.test.js@@ -12,11 +12,9 @@ vi.mock('../lib/safeUrlFetch.js', () => ({import { fetchPublicText } from '../lib/safeUrlFetch.js';import {- decodeHtmlEntities,stripUgMarkers,extractUltimateGuitarStore,extractLargestPre,- stripHtmlToText,parseTitleArtist,buildDraftFromHtml,importSongFromUrl,@@ -43,24 +41,6 @@ const UG_STORE = {},};-describe('decodeHtmlEntities', () => {- it('decodes named, decimal, and hex entities', () => {- expect(decodeHtmlEntities('<b> "hi" 'x' A')).toBe('<b> "hi" \'x\' A');- });-- it('decodes & last so double-encoded text stays literal', () => {- expect(decodeHtmlEntities('&lt;')).toBe('<');- });-- it('never throws on out-of-range numeric entities', () => {- expect(decodeHtmlEntities('� ok')).toBe(' ok');- });-- it('returns "" for non-strings', () => {- expect(decodeHtmlEntities(null)).toBe('');- });-});-describe('stripUgMarkers', () => {it('strips [ch]/[tab] markers but keeps the sheet text', () => {expect(stripUgMarkers('[tab][ch]Am[/ch] hello[/tab]')).toBe('Am hello');@@ -113,6 +93,16 @@ describe('extractLargestPre', () => {expect(result).toContain('G & D strings');});+ it('decodes named, decimal, and hex entities without double-decoding', () => {+ const html = '<pre><b> "hi" 'x' A &lt; and padding</pre>';+ expect(extractLargestPre(html)).toBe('<b> "hi" \'x\' A < and padding');+ });++ it('leaves out-of-range numeric entities untouched (never throws)', () => {+ const html = '<pre>� still a long enough sheet</pre>';+ expect(extractLargestPre(html)).toBe('� still a long enough sheet');+ });+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');@@ -127,16 +117,6 @@ describe('extractLargestPre', () => {});});-describe('stripHtmlToText', () => {- it('drops scripts/styles and converts block ends to newlines', () => {- const html = '<html><head><style>.x{}</style></head><body>' +- '<script>var a = 1;</script><p>Verse one line</p><p>Verse two line</p></body></html>';- const text = stripHtmlToText(html);- expect(text).toBe('Verse one line\nVerse two line');- expect(text).not.toContain('var a');- });-});-describe('parseTitleArtist', () => {it('parses "X CHORDS by Y @ site" titles', () => {const html = '<title>EXAMPLE SONG CHORDS (ver 2) by The Placeholders @ Ultimate-Guitar.Com</title>';@@ -184,11 +164,12 @@ describe('buildDraftFromHtml', () => {});it('falls back to plain tag-stripped text when nothing else matches', () => {- const html = '<html><head><title>Example Song - The Placeholders</title></head>' +- '<body><p>Just some lyric text on a plain page</p></body></html>';+ const html = '<html><head><title>Example Song - The Placeholders</title><style>.x{}</style></head>' ++ '<body><script>var a = 1;</script><p>Just some lyric text on a plain page</p></body></html>';const draft = buildDraftFromHtml(html, URL);expect(draft.content.format).toBe('plain');expect(draft.content.text).toBe('Just some lyric text on a plain page');+ expect(draft.content.text).not.toContain('var a');});});diff --git a/server/services/messageGmailSync.js b/server/services/messageGmailSync.jsindex 4881bc736c..389d36f72a 100644--- a/server/services/messageGmailSync.js+++ b/server/services/messageGmailSync.js@@ -7,7 +7,7 @@ import { gmail } from '@googleapis/gmail';import { v4 as uuidv4 } from '../lib/uuid.js';import crypto from 'crypto';import { getAuthenticatedClient } from './googleAuth.js';-import { decodeXmlEntities } from '../lib/xmlEntities.js';+import { htmlToText as sharedHtmlToText } from '../lib/htmlToText.js';function makeExternalId(gmailId) {return 'api-gmail-' + crypto.createHash('md5').update(gmailId).digest('hex').slice(0, 12);@@ -25,25 +25,13 @@ function decodeBase64Url(str) {}/**- * Convert HTML to readable plain text by stripping style/script/head blocks, then tags.+ * Convert HTML to readable plain text via the shared strip-tags pipeline.+ * Mail-specific options: `‌` decodes to nothing, `</p>` keeps a blank+ * line between paragraphs, and space/tab runs collapse (email HTML is+ * whitespace-noisy and carries no meaningful column alignment).*/function htmlToText(html) {- const stripped = html- .replace(/<head\b[^>]*>[\s\S]*?<\/head>/gi, '')- .replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi, '')- .replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi, '')- .replace(/<br\s*\/?>/gi, '\n')- .replace(/<\/p>/gi, '\n\n')- .replace(/<\/div>/gi, '\n')- .replace(/<\/tr>/gi, '\n')- .replace(/<\/li>/gi, '\n')- .replace(/<[^>]*>/g, '');- // Shared decoder handles the named + numeric entities; ` `/`‌` are- // mail-specific so they're passed as extra entities (space / zero-width strip).- return decodeXmlEntities(stripped, { nbsp: ' ', zwnj: '' })- .replace(/\n{3,}/g, '\n\n')- .replace(/[ \t]+/g, ' ')- .trim();+ return sharedHtmlToText(html, { extraEntities: { zwnj: '' }, paragraphBreak: '\n\n', collapseSpaces: true });}/**