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
add SongBook: Brain-federated song repertoire with tabs, learning stages, and autoscroll play view
[._.]/ Adam Eivy380b1df1c72f
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 9cd39c310d..5b1c35e044 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -109,4 +109,6 @@- **[issue-2535] Paginate the remaining privacy + digital-twin list endpoints, completing the sweep.** The last unbounded index `GET`s flagged by #2535 — privacy `/vault`, `/orgs`, `/changes`, `/brokers`, `/broker-cases`, and digital-twin `/documents` — now opt into the shared `paginateArray` envelope exactly like the creative-catalog routes shipped in #2636: `isPaginationRequested(req.query)` gates a bounded `{ items, total, limit, offset }` response (`defaultLimit: 50`, `maxLimit: 500`) the moment a client passes `limit`/`offset`, while a param-less request returns the full array byte-for-byte, so no client change is required. Because the four privacy list-query schemas are `.strict()` (they'd reject unknown keys), a local `paginationQueryFields` fragment (`limit`/`offset` as passthrough strings — `parsePagination` does the parse+clamp) is spread into `privacyVaultListQuerySchema`, `privacyOrgListQuerySchema`, `privacyBrokerListQuerySchema`, and `privacyBrokerCaseListQuerySchema` in `privacyValidation.js`; the `/orgs` handler strips `limit`/`offset` before passing filters to `listOrgs` so pagination never leaks into the service query. New route tests cover the vault/orgs/changes/broker-cases envelopes (filters preserved) and the digital-twin documents envelope. This closes the remaining slice of #2535 (the CoS-tasks default-paginated shape and the creative-catalog/media routes shipped previously).- **[issue-2642] Require provider/runner provenance before excluding environmental failures from task learning.** Environmental-failure exclusion previously trusted `errorAnalysis.category` alone, but that category is produced by the `analyzeAgentFailure` regex sweep over the failed agent's output tail — so ordinary task output could be misclassified as an infra category (e.g. a failing test whose tail prints "rate limit" tripping the unscoped `/rate.?limit/`) and the run would be silently diverted out of the learning aggregates as an "outage." `analyzeAgentFailure` now stamps an `origin` provenance marker on every classification: `'provider'`/`'runner'` when the match carries a genuine structured signal (an `API Error: NNN` line, a Node error code like `ECONNREFUSED`, a provider token like `overloaded_error`/`not_found_error`, or the structural startup-failure), and `'output-scan'` when it comes only from a loose keyword alternative. Mixed patterns (e.g. `API Error: 429` vs a bare `rate limit`) gate the promotion through a per-pattern `structuredMarker` sub-pattern via the new pure `resolvePatternOrigin` helper. The exclusion gate in `recordTaskCompletion` (`server/services/taskLearning/metrics.js`) now runs through a pure `shouldDivertToEnvironmental(outcomeSuccess, category, origin)` that additionally requires `origin !== 'output-scan'`, so an output-scan false positive counts as a genuine failure while structured signals stay excluded. Back-compat is preserved: an `errorAnalysis` with no `origin` (older records / federated peers) keeps the category-only behavior, and the routing-side signature filter is unchanged (it already fails safe). New unit tests cover the provenance stamping across the classifiers and all three acceptance cases in the gate.- **[issue-2532] Finish thinning the Universe Builder route into focused feature lifecycles.** `pages/UniverseBuilder.jsx` is now a 9-line compatibility shell over the presentational editor, while draft hydration/persistence and canon-safe merges live in `useUniverseDraft`, AI expansion/refinement lives in `useUniverseExpand`, and bulk-render configuration plus per-entry job queues live in `useUniverseRender`. The existing Bible/Cast/Places/Objects panels moved out of the route module with their behavior and named exports preserved. New hook tests cover hydration, dirty saves, deletion-wins canon merges, locked expansion rows, all-trunk render selection, and backend guards; the full client suite remains green.+- **SongBook — a Brain repertoire for guitar tabs, chord sheets, and sheet music with learning-stage tracking and an autoscrolling play view.** New `/songbook` index (filter by stage/instrument/tag/search, all URL-addressable) and `/songbook/:id` full-bleed viewer: tab/chord/ChordPro content renders with highlighted chord tokens, section headers, and horizontally-scrollable tab staffs; an Ultimate-Guitar-style autoscroll (play/pause, speed slider, keyboard shortcuts, screen wake-lock) paces long charts, with non-destructive transpose and font-size controls persisted per song. Each song tracks a learning stage (`new → learning → learned → memorized`) flippable from the card or viewer. Songs import by paste (auto-cleanup of HTML remnants + format detection) or by URL — a server-side SSRF-guarded fetch with an Ultimate Guitar extractor and generic `<pre>`/plain-text fallbacks returns an editable draft, never auto-saving. Sheet-music/MIDI/image attachments upload per song: metadata (name, size, SHA-256) lives in the synced record while bytes stay machine-local under `data/brain/songbook/` (peers show "not on this machine"). Songs are a first-class Brain entity type (`data/brain/songs.json`), so they federate across machines with LWW sync, tombstone deletes, and reconcile coverage automatically — and they're reachable from ⌘K and voice nav (`nav.brain.songbook`). New pure `tabNotation` lib (line classification, ChordPro, transpose with column preservation, paste normalization) with extensive unit tests.+- **Fix the app-manager Git tab's "Clean N merged" button counting worktree-locked branches, so cleanup deleted zero and toasted "No merged branches to clean up".** `getBranches` marked a local branch `merged: true` from `git branch --merged` alone, but `deleteMergedBranches` (correctly) skips branches checked out in a worktree — `git branch -d` can't delete them. On any install with active CoS-agent/claim worktrees, those merged-but-locked branches inflated the button's count while yielding no deletions. `getBranches` now also returns a `worktree` flag (branch checked out in another worktree), the Git tab's `localMergedCount` counts only `merged && !worktree` so the button reflects what the server will actually delete, and locked branches render a `worktree` badge next to `merged` so the user sees why they linger. Server + client tests cover the count and badge.diff --git a/client/src/App.jsx b/client/src/App.jsxindex 19f1ff2e58..6e44c26c53 100644--- a/client/src/App.jsx+++ b/client/src/App.jsx@@ -59,6 +59,9 @@ const Authors = lazyWithReload(() => import('./pages/Authors'));const Music = lazyWithReload(() => import('./pages/Music'));const Catalog = lazyWithReload(() => import('./pages/Catalog'));const Rounds = lazyWithReload(() => import('./pages/Rounds'));+const SongBook = lazyWithReload(() => import('./pages/SongBook'));+const SongBookImport = lazyWithReload(() => import('./pages/SongBookImport'));+const SongBookViewer = lazyWithReload(() => import('./pages/SongBookViewer'));const RoundEditor = lazyWithReload(() => import('./pages/RoundEditor'));const RoundsGuide = lazyWithReload(() => import('./pages/RoundsGuide'));const CatalogIngest = lazyWithReload(() => import('./pages/CatalogIngest'));@@ -356,6 +359,11 @@ export default function App() {<Route path="rounds" element={<Rounds />} /><Route path="rounds/guide" element={<RoundsGuide />} /><Route path="rounds/:id" element={<RoundEditor />} />+ {/* SongBook: index + import are plain scrolling pages; the viewer+ (/songbook/:id) is full-bleed (see Layout.jsx isFullWidth). */}+ <Route path="songbook" element={<SongBook />} />+ <Route path="songbook/import" element={<SongBookImport />} />+ <Route path="songbook/:id" element={<SongBookViewer />} /><Route path="catalog" element={<Catalog />} /><Route path="catalog/ingest" element={<CatalogIngest />} /><Route path="catalog/:type/:id" element={<CatalogIngredient />} />diff --git a/client/src/components/Layout.jsx b/client/src/components/Layout.jsxindex 735ff05d55..f8a3e1d340 100644--- a/client/src/components/Layout.jsx+++ b/client/src/components/Layout.jsx@@ -58,6 +58,7 @@ import {Lightbulb,GitBranch,Link2,+ ListMusic,Database,Shield,Lock,@@ -156,6 +157,7 @@ const navItems = [{ to: '/brain/notes', label: 'Notes', icon: FileText },{ to: '/openclaw', label: 'OpenClaw', icon: MessagesSquare },{ to: '/rapid-reader', label: 'Rapid Reader', icon: Zap },+ { to: '/songbook', label: 'SongBook', icon: ListMusic },{ to: '/timeline', label: 'Timeline', icon: CalendarClock },{ to: '/tribe', label: 'Tribe', icon: Users },{ to: '/brain/trust', label: 'Trust', icon: Shield },@@ -1205,7 +1207,12 @@ export default function Layout() {// internal overflow-y-auto container). The trailing (?:\/|$) +// create(?:\/|$) lookahead also excludes the trailing-slash URL// /apps/create/ (React Router treats it as the same route).- /^\/apps\/(?!create(?:\/|$))[^/]+(?:\/|$)/.test(location.pathname);+ /^\/apps\/(?!create(?:\/|$))[^/]+(?:\/|$)/.test(location.pathname) ||+ // Only the SongBook VIEWER (/songbook/:id) is full-bleed and owns+ // its own scroll (autoscroll container); the /songbook index and+ // /songbook/import are plain scrolling pages — the import(?:\/|$)+ // lookahead mirrors the /apps/create exclusion above.+ /^\/songbook\/(?!import(?:\/|$))[^/]+(?:\/|$)/.test(location.pathname);return (<main id="main-content" className={`flex-1 min-h-0 print:overflow-visible print:min-h-0 ${isFullWidth ? 'relative overflow-hidden' : 'overflow-auto p-4 md:p-6'}`}><Outlet />diff --git a/client/src/components/songbook/TabSheetView.jsx b/client/src/components/songbook/TabSheetView.jsxnew file mode 100644index 0000000000..f27c896e53--- /dev/null+++ b/client/src/components/songbook/TabSheetView.jsx@@ -0,0 +1,114 @@+import { useMemo } from 'react';+import { parseTabSheet } from '../../lib/tabNotation.js';++/**+ * Rendered tab/chord sheet — the shared display surface for the SongBook+ * viewer's play mode, the editor's live preview, and the import preview.+ *+ * Takes the (already-transposed) sheet `text` and renders parseTabSheet's+ * classified lines:+ * - section → styled heading+ * - chords → monospace line with each chord token highlighted at its+ * original column (whitespace-pre keeps alignment)+ * - chordlyric → chord row built from col offsets rendered above the bare lyric+ * - tabstaff → consecutive staff lines grouped in one overflow-x-auto block+ * so a wide staff scrolls as a unit without wrapping+ * - lyric/text → plain monospace pre-wrap+ *+ * `fontSizeRem` scales the whole sheet (viewer font ± control).+ */++// Split a chords line into plain/chord segments using the parser's col offsets.+const chordLineSegments = (text, chords) => {+ const segments = [];+ let cursor = 0;+ for (const { name, col } of chords) {+ if (col > cursor) segments.push({ text: text.slice(cursor, col), chord: false });+ segments.push({ text: text.slice(col, col + name.length), chord: true });+ cursor = col + name.length;+ }+ if (cursor < text.length) segments.push({ text: text.slice(cursor), chord: false });+ return segments;+};++// Build the padded chord row for a chordlyric line: each chord name lands at+// its col offset into the lyric; names that would collide keep one space.+const buildChordRow = (chords) => {+ let row = '';+ for (const { name, col } of chords) {+ if (row.length < col) row += ' '.repeat(col - row.length);+ else if (row.length > 0) row += ' ';+ row += name;+ }+ return row;+};++const ChordsLine = ({ line }) => (+ <div className="whitespace-pre-wrap">+ {chordLineSegments(line.text, line.chords).map((seg, i) =>+ seg.chord+ ? <span key={i} className="text-port-accent font-semibold">{seg.text}</span>+ : <span key={i}>{seg.text}</span>)}+ </div>+);++const ChordLyricLine = ({ line }) => (+ <div className="overflow-x-auto">+ <div className="whitespace-pre text-port-accent font-semibold leading-tight">+ {buildChordRow(line.chords)}+ </div>+ <div className="whitespace-pre">{line.text || ' '}</div>+ </div>+);++export default function TabSheetView({ text, fontSizeRem = 0.875, className = '' }) {+ const { lines } = useMemo(() => parseTabSheet(text), [text]);++ // Group consecutive tabstaff lines into one horizontally-scrollable block so+ // the six strings of a staff scroll together.+ const blocks = useMemo(() => {+ const out = [];+ for (const line of lines) {+ const prev = out[out.length - 1];+ if (line.type === 'tabstaff' && prev?.type === 'tabstaff') prev.lines.push(line);+ else out.push({ type: line.type, lines: [line] });+ }+ return out;+ }, [lines]);++ return (+ <div className={`font-mono text-gray-200 ${className}`} style={{ fontSize: `${fontSizeRem}rem`, lineHeight: 1.5 }}>+ {blocks.map((block, bi) => {+ if (block.type === 'tabstaff') {+ return (+ <div key={bi} className="overflow-x-auto whitespace-pre text-gray-300 my-1">+ {block.lines.map((line, li) => <div key={li}>{line.text}</div>)}+ </div>+ );+ }+ const line = block.lines[0];+ switch (line.type) {+ case 'section':+ // {end_of_*} directives carry an empty label — render nothing visible.+ return line.label+ ? (+ <div key={bi} className="mt-4 mb-1 text-port-accent font-bold uppercase tracking-wide text-[0.85em]">+ {line.label}+ </div>+ )+ : <div key={bi} className="mb-1" />;+ case 'chords':+ return <ChordsLine key={bi} line={line} />;+ case 'chordlyric':+ return <ChordLyricLine key={bi} line={line} />;+ case 'blank':+ return <div key={bi}>{' '}</div>;+ case 'lyric':+ case 'text':+ default:+ return <div key={bi} className="whitespace-pre-wrap">{line.text}</div>;+ }+ })}+ </div>+ );+}diff --git a/client/src/components/songbook/TabSheetView.test.jsx b/client/src/components/songbook/TabSheetView.test.jsxnew file mode 100644index 0000000000..ab2f6fc4a0--- /dev/null+++ b/client/src/components/songbook/TabSheetView.test.jsx@@ -0,0 +1,61 @@+import { describe, it, expect } from 'vitest';+import { render, screen } from '@testing-library/react';+import TabSheetView from './TabSheetView.jsx';++// Invented placeholder content only (privacy convention) — nonsense lyrics.+const SAMPLE = `[Verse 1]+C G+Nonsense lyric line+e|--3--2--|+B|--0-----|+[C]Hello [G]world`;++describe('TabSheetView', () => {+ it('renders section labels as headings', () => {+ render(<TabSheetView text={SAMPLE} />);+ expect(screen.getByText('Verse 1')).toBeTruthy();+ });++ it('highlights chord tokens on chords lines', () => {+ const { container } = render(<TabSheetView text={SAMPLE} />);+ const highlighted = [...container.querySelectorAll('.text-port-accent.font-semibold')]+ .map((el) => el.textContent.trim());+ expect(highlighted).toContain('C');+ expect(highlighted).toContain('G');+ });++ it('renders the lyric line under the chords', () => {+ render(<TabSheetView text={SAMPLE} />);+ expect(screen.getByText('Nonsense lyric line')).toBeTruthy();+ });++ it('groups consecutive tabstaff lines into one horizontally-scrollable block', () => {+ const { container } = render(<TabSheetView text={SAMPLE} />);+ const staffBlocks = [...container.querySelectorAll('.overflow-x-auto')]+ .filter((el) => el.textContent.includes('e|--3--2--|'));+ expect(staffBlocks.length).toBe(1);+ // Both staff lines live in the same block so they scroll together.+ expect(staffBlocks[0].textContent).toContain('B|--0-----|');+ });++ it('renders chordlyric lines as a chord row above the bare lyric', () => {+ const { container } = render(<TabSheetView text={SAMPLE} />);+ // Bare lyric (brackets stripped)+ expect(screen.getByText('Hello world')).toBeTruthy();+ // Chord row: names padded out to their col offsets ("C" at 0, "G" at 6).+ const chordRow = [...container.querySelectorAll('.whitespace-pre')]+ .find((el) => /^C\s+G$/.test(el.textContent));+ expect(chordRow).toBeTruthy();+ expect(chordRow.textContent.indexOf('G')).toBe(6);+ });++ it('applies the font size scale', () => {+ const { container } = render(<TabSheetView text="plain words" fontSizeRem={1.25} />);+ expect(container.firstChild.style.fontSize).toBe('1.25rem');+ });++ it('renders empty text without crashing', () => {+ const { container } = render(<TabSheetView text="" />);+ expect(container.firstChild).toBeTruthy();+ });+});diff --git a/client/src/components/songbook/constants.js b/client/src/components/songbook/constants.jsnew file mode 100644index 0000000000..ac320c8da7--- /dev/null+++ b/client/src/components/songbook/constants.js@@ -0,0 +1,21 @@+// Shared SongBook constants — learning-stage progression, stage chip colors,+// and the instrument list (mirrors server/lib/brainValidation.js enums).++export const SONG_STAGES = [+ { id: 'new', label: 'New' },+ { id: 'learning', label: 'Learning' },+ { id: 'learned', label: 'Learned' },+ { id: 'memorized', label: 'Memorized' },+];++// Tailwind chip classes per stage (STATUS_COLORS style: bg tint + text + border).+export const SONG_STAGE_COLORS = {+ new: 'bg-gray-500/20 text-gray-400 border-gray-500/30',+ learning: 'bg-port-warning/20 text-port-warning border-port-warning/30',+ learned: 'bg-port-accent/20 text-port-accent border-port-accent/30',+ memorized: 'bg-port-success/20 text-port-success border-port-success/30',+};++export const INSTRUMENTS = ['guitar', 'piano', 'ukulele', 'bass', 'voice', 'other'];++export const SONG_FORMATS = ['chordpro', 'tab', 'plain'];diff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex 2c40fadd60..e757571323 100644--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@ -106,6 +106,8 @@ grep -i "what you want to do" client/src/hooks/README.md| `useSwipeNav` | Horizontal swipe prev/next. | Mobile swipe between siblings. || `useValidTab` | Resolve the active tab from the `:tab` URL param against a TABS list, falling back to a default on invalid/missing. | Any tabbed page whose tab lives in the URL — don't re-roll the `new Set(TABS.map(...))` guard. || `useAsyncAction` | `running` state + toast-on-error. | Buttons that await an async action. |+| `useAutoscroll` | rAF autoscroll for a scrollable container: advances `scrollTop` by `pxPerSec`, auto-stops at the bottom, pauses on user wheel/touchmove, live speed changes via ref. Returns `{ playing, toggle, stop, pxPerSec, setPxPerSec }`. | SongBook play view; any teleprompter-style surface. |+| `useWakeLock` | Holds a screen wake lock (`navigator.wakeLock`) while `active` is true; releases on unmount/inactive, re-acquires on visibilitychange; no-op where unsupported. | Hands-free surfaces that must keep the screen on (SongBook autoscroll). |## Storage & persistencediff --git a/client/src/hooks/index.js b/client/src/hooks/index.jsindex 960e15ed08..d9a9e6fb57 100644--- a/client/src/hooks/index.js+++ b/client/src/hooks/index.js@@ -9,6 +9,7 @@// === Default-exporting hooks (re-exported as named) ===export { default as useAnchorReveal } from './useAnchorReveal.js';+export { default as useAutoscroll } from './useAutoscroll.js';export { default as useCityAudio } from './useCityAudio.js';export { default as useAutoSizeTextarea } from './useAutoSizeTextarea.js';export { default as useChartColors } from './useChartColors.js';@@ -52,6 +53,7 @@ export { default as useUniverseExpand } from './useUniverseExpand.js';export { default as useUniverseGallery } from './useUniverseGallery.js';export { default as useUniverseRender } from './useUniverseRender.js';export { default as useVideoDownload } from './useVideoDownload.js';+export { default as useWakeLock } from './useWakeLock.js';export { default as useYoutubeTrackImport } from './useYoutubeTrackImport.js';export { default as useReferenceAudioImport } from './useReferenceAudioImport.js';export { default as useMidiTranscription } from './useMidiTranscription.js';diff --git a/client/src/hooks/useAutoscroll.js b/client/src/hooks/useAutoscroll.jsnew file mode 100644index 0000000000..959230566e--- /dev/null+++ b/client/src/hooks/useAutoscroll.js@@ -0,0 +1,75 @@+import { useCallback, useEffect, useRef, useState } from 'react';++/**+ * Smooth autoscroll for a scrollable container (SongBook play view, or any+ * "teleprompter" surface): a requestAnimationFrame loop advances+ * `container.scrollTop` by `pxPerSec`. Behavior contract:+ *+ * - Auto-stops (pauses) when the container reaches the bottom.+ * - A user wheel or touchmove on the container pauses playback — manual+ * scrolling always wins; the user resumes explicitly.+ * - Speed changes apply live (read through a ref) without restarting the loop.+ * - rAF is cancelled and listeners detach on pause/unmount; a `mountedRef`+ * guards the auto-stop setState so a frame that lands after unmount is inert.+ *+ * containerRef — ref to the scrollable element (must have overflow-y-auto).+ * Returns { playing, toggle, stop, pxPerSec, setPxPerSec }.+ */+export default function useAutoscroll(containerRef, { initialPxPerSec = 30 } = {}) {+ const [playing, setPlaying] = useState(false);+ const [pxPerSec, setPxPerSec] = useState(initialPxPerSec);+ const pxPerSecRef = useRef(pxPerSec);+ pxPerSecRef.current = pxPerSec;++ const mountedRef = useRef(true);+ useEffect(() => () => { mountedRef.current = false; }, []);++ useEffect(() => {+ if (!playing) return undefined;+ const el = containerRef.current;+ if (!el) return undefined;++ let rafId = null;+ let lastTs = null;+ // Fractional-pixel accumulator: scrollTop assignment can round on some+ // engines, so slow speeds (< 1px/frame) would otherwise never move.+ let carry = 0;++ const step = (ts) => {+ if (lastTs != null) {+ const dt = Math.min((ts - lastTs) / 1000, 0.5); // clamp tab-suspend gaps+ carry += pxPerSecRef.current * dt;+ const whole = Math.floor(carry);+ if (whole >= 1) {+ el.scrollTop += whole;+ carry -= whole;+ }+ // Bottom reached (±1px slack for fractional layout heights) → auto-stop.+ if (el.scrollTop >= el.scrollHeight - el.clientHeight - 1) {+ if (mountedRef.current) setPlaying(false);+ return;+ }+ }+ lastTs = ts;+ rafId = requestAnimationFrame(step);+ };++ // Manual scroll intent pauses playback; the passive flag keeps native+ // scrolling responsive (we never preventDefault).+ const pause = () => { if (mountedRef.current) setPlaying(false); };+ el.addEventListener('wheel', pause, { passive: true });+ el.addEventListener('touchmove', pause, { passive: true });++ rafId = requestAnimationFrame(step);+ return () => {+ if (rafId != null) cancelAnimationFrame(rafId);+ el.removeEventListener('wheel', pause);+ el.removeEventListener('touchmove', pause);+ };+ }, [playing, containerRef]);++ const toggle = useCallback(() => setPlaying((p) => !p), []);+ const stop = useCallback(() => setPlaying(false), []);++ return { playing, toggle, stop, pxPerSec, setPxPerSec };+}diff --git a/client/src/hooks/useAutoscroll.test.jsx b/client/src/hooks/useAutoscroll.test.jsxnew file mode 100644index 0000000000..c83fbbbe75--- /dev/null+++ b/client/src/hooks/useAutoscroll.test.jsx@@ -0,0 +1,102 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { renderHook, act } from '@testing-library/react';+import useAutoscroll from './useAutoscroll.js';++// Manual rAF pump — collect scheduled callbacks and flush them with explicit+// timestamps so scroll advancement is deterministic.+let rafCallbacks;+let cancelled;++const flush = (ts) => {+ const cbs = rafCallbacks;+ rafCallbacks = [];+ cbs.forEach((cb) => cb(ts));+};++const makeContainer = () => {+ const listeners = {};+ return {+ el: {+ scrollTop: 0,+ scrollHeight: 1000,+ clientHeight: 200,+ addEventListener: (ev, fn) => { listeners[ev] = fn; },+ removeEventListener: (ev) => { delete listeners[ev]; },+ },+ listeners,+ };+};++describe('useAutoscroll', () => {+ beforeEach(() => {+ rafCallbacks = [];+ cancelled = [];+ vi.stubGlobal('requestAnimationFrame', (cb) => { rafCallbacks.push(cb); return rafCallbacks.length; });+ vi.stubGlobal('cancelAnimationFrame', (id) => { cancelled.push(id); });+ });+ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it('advances scrollTop by pxPerSec while playing', () => {+ const { el } = makeContainer();+ const ref = { current: el };+ const { result } = renderHook(() => useAutoscroll(ref, { initialPxPerSec: 100 }));++ expect(result.current.playing).toBe(false);+ act(() => result.current.toggle());+ expect(result.current.playing).toBe(true);++ act(() => flush(0)); // first frame establishes lastTs+ act(() => flush(100)); // 0.1s at 100px/s → 10px+ act(() => flush(200)); // another 10px+ expect(el.scrollTop).toBe(20);+ });++ it('applies live speed changes without restarting the loop', () => {+ const { el } = makeContainer();+ const ref = { current: el };+ const { result } = renderHook(() => useAutoscroll(ref, { initialPxPerSec: 100 }));+ act(() => result.current.toggle());+ act(() => flush(0));+ act(() => result.current.setPxPerSec(200));+ act(() => flush(100)); // 0.1s at 200px/s → 20px+ expect(el.scrollTop).toBe(20);+ });++ it('auto-stops at the bottom', () => {+ const { el } = makeContainer();+ const ref = { current: el };+ const { result } = renderHook(() => useAutoscroll(ref, { initialPxPerSec: 100 }));+ act(() => result.current.toggle());+ el.scrollTop = 795; // bottom threshold = 1000 - 200 - 1 = 799+ act(() => flush(0));+ act(() => flush(100)); // +10px → 805 ≥ 799 → stop+ expect(result.current.playing).toBe(false);+ // No further frames scheduled after the stop path returned.+ expect(rafCallbacks.length).toBe(0);+ });++ it('pauses when the user wheels/touch-drags the container', () => {+ const { el, listeners } = makeContainer();+ const ref = { current: el };+ const { result } = renderHook(() => useAutoscroll(ref));+ act(() => result.current.toggle());+ expect(typeof listeners.wheel).toBe('function');+ expect(typeof listeners.touchmove).toBe('function');+ act(() => listeners.wheel());+ expect(result.current.playing).toBe(false);+ // Listeners detach while paused.+ expect(listeners.wheel).toBeUndefined();+ });++ it('cancels the rAF loop on unmount', () => {+ const { el } = makeContainer();+ const ref = { current: el };+ const { result, unmount } = renderHook(() => useAutoscroll(ref));+ act(() => result.current.toggle());+ expect(rafCallbacks.length).toBe(1);+ unmount();+ expect(cancelled.length).toBeGreaterThan(0);+ });+});diff --git a/client/src/hooks/useWakeLock.js b/client/src/hooks/useWakeLock.jsnew file mode 100644index 0000000000..59ca16ab6a--- /dev/null+++ b/client/src/hooks/useWakeLock.js@@ -0,0 +1,52 @@+import { useEffect, useRef } from 'react';++/**+ * Hold a screen wake lock (navigator.wakeLock) while `active` is true — keeps+ * the display on during hands-free surfaces like SongBook's autoscrolling play+ * view. No-op where the Wake Lock API is unsupported (older Safari, jsdom).+ *+ * The browser force-releases wake locks when the tab is hidden, so a+ * visibilitychange listener re-acquires on return while still active. A+ * generation counter makes a request that resolves after deactivation/unmount+ * release itself immediately instead of leaking a held lock.+ */+export default function useWakeLock(active) {+ const lockRef = useRef(null);+ const generationRef = useRef(0);++ useEffect(() => {+ const wakeLock = typeof navigator !== 'undefined' ? navigator.wakeLock : undefined;+ if (!active || !wakeLock?.request) return undefined;++ const generation = ++generationRef.current;++ const acquire = async () => {+ const lock = await wakeLock.request('screen').catch(() => null);+ if (!lock) return;+ // Deactivated (or re-activated) while the request was in flight — this+ // acquisition is stale; release it rather than adopting it.+ if (generationRef.current !== generation) {+ lock.release().catch(() => {});+ return;+ }+ lockRef.current = lock;+ };++ const onVisibility = () => {+ // The UA auto-released the lock when the tab hid; re-acquire on return.+ if (document.visibilityState === 'visible' && generationRef.current === generation) {+ acquire();+ }+ };++ acquire();+ document.addEventListener('visibilitychange', onVisibility);++ return () => {+ generationRef.current += 1; // invalidate any in-flight request+ document.removeEventListener('visibilitychange', onVisibility);+ lockRef.current?.release?.().catch(() => {});+ lockRef.current = null;+ };+ }, [active]);+}diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex 2c938b37d0..272560e8d6 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -131,6 +131,7 @@ grep -i "what you want to do" client/src/lib/README.md| `tribeCadence.js` | Mirror of `server/lib/tribeCadence.js` — the single authoritative Tribe care-cadence rules shared by the page, the Care dashboard widget, and the proactive alert: `cadenceStatus(entity)` → `{ state, daysRemaining, daysOverdue }`, `daysSinceDate(dateStr)`, `DEFAULT_CADENCE_DAYS`, `SOON_WINDOW_DAYS`. A cross-boundary contract test asserts it never drifts from the server copy. || `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); `CHORD_TOKEN_RE` exported for reuse. Forgiving — never throws, unknown lines classify as `text`. NOT the lead-sheet parser (`scoreNotation.js`). || `terminalTheme.js` | Pure xterm.js palette builder for the Shell terminal. `buildTerminalTheme({ bg, fg, accent, card, error, success, warning }, mode)` assembles the xterm `theme` object — base ANSI colors from the active theme's CSS vars, the rest from mode-tuned literals (`ANSI_NIGHT` bright/pastel for dark backgrounds, `ANSI_DAY` darkened/saturated so colored CLI output stays legible on daytime themes). `parseCssColorToHex(raw, fallback)` normalizes both the `15 15 15` triple form and the `rgb(7 7 7 / 0.86)` function form (used by `--port-terminal-*` tokens) to `#rrggbb`, dropping alpha. No DOM reads — `Shell.jsx` resolves CSS vars and re-applies on theme switch. || `universeBuilderShared.js` | Shared constants + pure category/trunk/composite helpers for the Universe Builder page and its extracted tab/editor components (#2374): `TRUNK_TABS`/`TRUNK_BY_ID`/`TRUNK_BY_KIND`, `TAB_*` + `BUCKET_CANON`, `CATEGORY_LABELS`, `DEFAULT_RENDER_OPTS`, `COMPOSITE_BOARD_KINDS`; and helpers `groupBucketsByKind`, `normalizeCategoryKey`, `humanizeCategory`, `ensureDraftCategories`, `getCategoryKeys`, `compositeKindLabel`. No React state — safe to import from the page or any tab component without a cycle. || `universeBuilderCounts.js` | Pure prompt-count helpers for the Universe Builder render buttons (#2374), mirroring the server's compile/skip rules so inline counts match what `/render` will enqueue: `totalVariationCount`, `canonEntryHasContent`, `countCanonWithContent`, `renderPromptCount`, `scopedPromptCount`. The server `compilePrompts`/`synthesizeCanonPrompt` copy is authoritative — keep in sync. |diff --git a/client/src/lib/index.js b/client/src/lib/index.jsindex 4d3469674c..e18b79d375 100644--- a/client/src/lib/index.js+++ b/client/src/lib/index.js@@ -98,6 +98,7 @@ export * from './songPlayback.js';export * from './songProgress.js';export * from './streakGlyph.js';export * from './syncCounts.js';+export * from './tabNotation.js';export * from './terminalTheme.js';export * from './tribe.js';export * from './tribeCadence.js';diff --git a/client/src/lib/tabNotation.js b/client/src/lib/tabNotation.jsnew file mode 100644index 0000000000..f7235571d4--- /dev/null+++ b/client/src/lib/tabNotation.js@@ -0,0 +1,379 @@+// 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,+// and transpose chord symbols. Modeled on scoreNotation.js: forgiving (never+// throws — unknown lines classify as 'text', problems collect into errors[]),+// pure (no React, no browser APIs — these tests also run in node env in CI).+//+// NOT the lead-sheet parser (scoreNotation.js) and NOT the SMF parser+// (midiNotes.js) — this module understands the loose text formats people paste+// from tab sites: chords-over-lyrics, monospace tab staffs, and ChordPro.+//+// API (contract the SongBook UI builds against):+// detectFormat(text) → 'chordpro' | 'tab' | 'plain'+// parseTabSheet(text) → { lines: [Line], meta, errors }+// normalizePastedTab(text) → cleaned text+// transposeChordName(name, n) → transposed chord symbol+// transposeText(text, n) → text with chord lines transposed in place+// CHORD_TOKEN_RE → anchored single-token chord matcher+//+// Line = { type, text, chords?, label? } where type is one of:+// 'section' — [Verse 1], {start_of_chorus}/{soc}, or a bare "Chorus:" line+// 'chords' — a line that is ≥~80% chord tokens (C, Am7, F#m7b5, G/B, N.C.)+// 'lyric' — a plain line directly under a 'chords' line+// 'tabstaff' — monospace tab staff (e|--3--2--| ; string-letter prefixed)+// 'chordlyric' — ChordPro inline [C]lyric; text is the bare lyric, chords+// carry col offsets into it+// 'blank' — whitespace-only+// 'text' — everything else (incl. {directive} lines; meta directives+// still populate meta)++// ---------------------------------------------------------------------------+// Chord tokens+// ---------------------------------------------------------------------------++// Anchored matcher for ONE chord symbol (test whitespace-split tokens against+// it). Root A–G + optional #/b, then any run of quality/extension parts, then+// an optional /bass. Deliberate anti-word choices: roots are uppercase-only,+// bare ASCII `o` (diminished shorthand) requires a following digit so "Go" /+// "Do" / "No" never match, and there is no bare `-` quality so hyphenated+// lyric fragments stay words. "N.C." (no chord) is accepted as-is.+export const CHORD_TOKEN_RE = new RegExp(+ '^(?:N\\.?C\\.?|[A-G][#b]?' ++ '(?:6/9|maj|min|dim|aug|sus|add|M|m|\\+|°|ø|o(?=\\d)|\\d{1,2}|[#b]\\d{1,2}|' ++ '\\(\\s*(?:maj|add|sus|dim|aug|[#b])?\\d{1,2}\\s*\\))*' ++ '(?:/[A-G][#b]?)?)$',+);++// Length cap keeps the alternation-star from chewing on long pasted garbage.+const isChordToken = (token) => token.length > 0 && token.length <= 12 && CHORD_TOKEN_RE.test(token);++// A chord token that could ALSO plausibly be an English word: a bare root+// letter ("A"). Everything else that matches CHORD_TOKEN_RE (accidental,+// quality, slash, N.C.) is treated as unambiguous — a lone "Am" line is far+// more often the chord than the word, and word usage ("Am I…") brings other+// tokens that fail the density gate anyway.+const isAmbiguousChordToken = (token) => /^[A-G]$/.test(token);++// Rhythm/bar noise commonly interleaved on chord lines — ignored by the+// density calculation rather than counted against it.+const FILLER_TOKEN_RE = /^(?:\|+|\/+|%|-+|\.+|,|[([]?x\d{1,2}[)\]]?)$/i;++// Classify one whitespace-delimited token from a candidate chord line.+// '(Am)' counts as a chord (name Am, col offset +1 past the paren).+const chordTokenInfo = (token, col) => {+ if (isChordToken(token)) return { kind: 'chord', name: token, col };+ const paren = /^\((.+)\)$/.exec(token);+ if (paren && isChordToken(paren[1])) return { kind: 'chord', name: paren[1], col: col + 1 };+ if (FILLER_TOKEN_RE.test(token)) return { kind: 'filler' };+ return { kind: 'other' };+};++// ---------------------------------------------------------------------------+// Line classification+// ---------------------------------------------------------------------------++const META_DIRECTIVE_RE = /^\s*\{\s*(title|t|artist|subtitle|st|key|capo)\s*:\s*([^}]*?)\s*\}\s*$/i;+const CHORDPRO_SECTION_RE =+ /^\s*\{\s*(start_of_\w+|end_of_\w+|soc|eoc|sov|eov|sob|eob|sot|eot)\s*(?::\s*([^}]*?)\s*)?\}\s*$/i;+const GENERIC_DIRECTIVE_RE = /^\s*\{\s*[A-Za-z_]+\s*(?::[^}]*)?\}\s*$/;+const BRACKET_SECTION_RE = /^\s*\[([^\]]+)\]\s*$/;+const WORD_SECTION_RE =+ /^\s*(intro|verse|chorus|pre[- ]?chorus|bridge|outro|solo|interlude|instrumental|refrain|coda)(\s+\d+)?\s*:?\s*$/i;+const META_ALIASES = { t: 'title', subtitle: 'artist', st: 'artist' };++const capitalize = (s) => (s ? s[0].toUpperCase() + s.slice(1) : s);++// Short ChordPro section codes → [start|end, kind].+const CHORDPRO_SHORT = {+ soc: ['start', 'chorus'], eoc: ['end', 'chorus'],+ sov: ['start', 'verse'], eov: ['end', 'verse'],+ sob: ['start', 'bridge'], eob: ['end', 'bridge'],+ sot: ['start', 'tab'], eot: ['end', 'tab'],+};++// Tab staff detection. Two shapes:+// (a) string-letter prefix straight into a bar: `e|--3--2--|`, `D|-0-`, `B:`+// (b) bar-first staffs with no string name: `|--3--5--|`+// The body charset is dashes/digits/bars plus tab technique glyphs+// (h p b r s t x v ~ / \ ^ * < > = . :) — deliberately NO uppercase letters+// (except X for dead notes), so chord lines with bars ("C | G | Am") fall+// through to the chords classifier.+const TAB_BODY_RE = /^[\s\-0-9|/\\hpbrstxvX~.^*()<>=:]*$/;+const isTabstaffLine = (line) => {+ const t = line.trimEnd();+ if (!t.trim()) return false;+ const prefix = /^\s*[A-Ga-g][#b]?\s*[|:]/.exec(t);+ const dashes = (t.match(/-/g) || []).length;+ if (prefix) return dashes >= 2 && TAB_BODY_RE.test(t.slice(prefix[0].length));+ return t.includes('|') && dashes >= 3 && TAB_BODY_RE.test(t);+};++// ChordPro inline [C]lyric → { text: bare lyric, chords: [{ name, col }] } or+// null when the line has no chord-token brackets. Non-chord brackets ([x2],+// [weird]) stay literal in the lyric text.+const parseChordLyric = (line) => {+ const chords = [];+ let bare = '';+ let last = 0;+ const re = /\[([^\]]*)\]/g;+ let m;+ while ((m = re.exec(line))) {+ bare += line.slice(last, m.index);+ if (isChordToken(m[1])) chords.push({ name: m[1], col: bare.length });+ else bare += m[0];+ last = m.index + m[0].length;+ }+ bare += line.slice(last);+ return chords.length ? { text: bare, chords } : null;+};++// A 'chords' line: ≥1 chord token, chord density ≥ 80% among non-filler+// tokens, and either 2+ chord tokens or at least one unambiguous one — so a+// lone "A" line stays text ("A day in the life" already fails on density).+const parseChordsLine = (line) => {+ const chords = [];+ let other = 0;+ const re = /\S+/g;+ let m;+ while ((m = re.exec(line))) {+ const info = chordTokenInfo(m[0], m.index);+ if (info.kind === 'chord') chords.push({ name: info.name, col: info.col });+ else if (info.kind === 'other') other += 1;+ }+ if (!chords.length) return null;+ if (chords.length / (chords.length + other) < 0.8) return null;+ if (chords.length < 2 && chords.every((c) => isAmbiguousChordToken(c.name))) return null;+ return chords;+};++// Classify one raw line (context-free — the lyric-under-chords promotion is a+// post-pass in parseTabSheet). Returns { type, text, chords?, label?, meta?,+// error?, chordpro? } — meta/error/chordpro are internal and stripped from the+// public parse result.+const classifyLine = (raw) => {+ const line = String(raw ?? '');+ if (!line.trim()) return { type: 'blank', text: line };++ const meta = META_DIRECTIVE_RE.exec(line);+ if (meta) {+ const key = META_ALIASES[meta[1].toLowerCase()] || meta[1].toLowerCase();+ const value = meta[2];+ if (key === 'capo') {+ if (/^\d{1,2}$/.test(value)) return { type: 'text', text: line, meta: { capo: Number(value) }, chordpro: true };+ return { type: 'text', text: line, error: `invalid capo value "${value}"`, chordpro: true };+ }+ return { type: 'text', text: line, meta: { [key]: value }, chordpro: true };+ }++ const cpSection = CHORDPRO_SECTION_RE.exec(line);+ if (cpSection) {+ const code = cpSection[1].toLowerCase();+ const custom = (cpSection[2] || '').trim();+ const [phase, kind] = CHORDPRO_SHORT[code] || [code.startsWith('end_of_') ? 'end' : 'start', code.replace(/^(start|end)_of_/, '').replace(/_/g, ' ')];+ const label = phase === 'end' ? '' : custom || capitalize(kind);+ return { type: 'section', text: line, label, chordpro: true };+ }++ if (GENERIC_DIRECTIVE_RE.test(line)) return { type: 'text', text: line, chordpro: true };++ const bracket = BRACKET_SECTION_RE.exec(line);+ if (bracket && !isChordToken(bracket[1].trim())) {+ return { type: 'section', text: line, label: bracket[1].trim() };+ }++ const word = WORD_SECTION_RE.exec(line);+ if (word) return { type: 'section', text: line, label: line.trim().replace(/:\s*$/, '') };++ if (isTabstaffLine(line)) return { type: 'tabstaff', text: line };++ const chordLyric = parseChordLyric(line);+ if (chordLyric) return { type: 'chordlyric', text: chordLyric.text, chords: chordLyric.chords, chordpro: true };++ const chords = parseChordsLine(line);+ if (chords) return { type: 'chords', text: line, chords };++ return { type: 'text', text: line };+};++// ---------------------------------------------------------------------------+// Public parsing API+// ---------------------------------------------------------------------------++// 'chordpro' when any ChordPro machinery appears ({directives} or inline+// [C]lyric chords); else 'tab' when the sheet has tab staffs or chord lines+// (monospace rendering matters); else 'plain'.+export const detectFormat = (text) => {+ let sawSheet = false;+ for (const raw of String(text ?? '').split(/\r?\n/)) {+ const c = classifyLine(raw);+ if (c.chordpro) return 'chordpro';+ if (c.type === 'tabstaff' || c.type === 'chords') sawSheet = true;+ }+ return sawSheet ? 'tab' : 'plain';+};++// Parse a full sheet into classified lines + ChordPro meta ({title:}/{t:},+// {artist:}/{subtitle:}/{st:}, {key:}, {capo:} — first occurrence wins) ++// collected (never thrown) errors. lines is 1:1 with the input lines.+export const parseTabSheet = (text) => {+ const meta = {};+ const errors = [];+ const classified = String(text ?? '').split(/\r?\n/).map((raw) => classifyLine(raw));++ for (const line of classified) {+ if (line.meta) {+ for (const [key, value] of Object.entries(line.meta)) {+ if (!(key in meta)) meta[key] = value;+ }+ }+ if (line.error) errors.push(line.error);+ }++ // Promote the plain line directly under a chords line to 'lyric' — the+ // classic chords-over-lyrics pairing. Only the immediately-following line+ // (no blank between) qualifies; standalone prose stays 'text'.+ const lines = classified.map(({ type, text: lineText, chords, label }, i) => {+ const promoted = type === 'text' && classified[i - 1]?.type === 'chords' ? 'lyric' : type;+ const out = { type: promoted, text: lineText };+ if (chords) out.chords = chords;+ if (label !== undefined) out.label = label;+ return out;+ });++ return { lines, meta, errors };+};++// ---------------------------------------------------------------------------+// Paste normalization+// ---------------------------------------------------------------------------++const NAMED_ENTITIES = { lt: '<', gt: '>', quot: '"', apos: "'", nbsp: ' ' };++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, '&');++// Expand tabs to 8-column stops (what <pre> renders), preserving alignment.+const detabLine = (line) => {+ if (!line.includes('\t')) return line;+ let out = '';+ for (const ch of line) {+ if (ch === '\t') out += ' '.repeat(8 - (out.length % 8));+ else out += ch;+ }+ return out;+};++// Clean up pasted content: CRLF/CR → LF, <br>/<p>/<div> boundaries → newlines,+// strip real HTML tags (a tag must start with a letter, so tab harmonics like+// e|--<7>--| survive), decode common entities, expand tabs, trim trailing+// whitespace per line, collapse runs of 3+ blank lines to 2, and trim+// leading/trailing blank lines.+export const normalizePastedTab = (text) => {+ if (typeof text !== 'string' || !text) return '';+ const cleaned = decodeEntities(+ text+ .replace(/\r\n?/g, '\n')+ .replace(/<(?:br|p|div)(?:\s[^>]*)?\/?>/gi, '\n')+ .replace(/<\/?[A-Za-z][A-Za-z0-9-]*(?:\s[^>]*)?\/?>/g, ''),+ );+ return cleaned+ .split('\n')+ .map((line) => detabLine(line).replace(/\s+$/, ''))+ .join('\n')+ .replace(/\n{4,}/g, '\n\n\n')+ .replace(/^\n+/, '')+ .replace(/\n+$/, '');+};++// ---------------------------------------------------------------------------+// Transposition+// ---------------------------------------------------------------------------++const NOTE_TO_PC = {+ C: 0, 'C#': 1, Db: 1, D: 2, 'D#': 3, Eb: 3, E: 4, Fb: 4, 'E#': 5, F: 5,+ 'F#': 6, Gb: 6, G: 7, 'G#': 8, Ab: 8, A: 9, 'A#': 10, Bb: 10, B: 11, Cb: 11, 'B#': 0,+};+const SHARP_NAMES = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B'];+const FLAT_NAMES = ['C', 'Db', 'D', 'Eb', 'E', 'F', 'Gb', 'G', 'Ab', 'A', 'Bb', 'B'];+// Conventional mixed spelling for roots with no source accidental to honor —+// the names guitarists actually write (C# D Eb E F F# G Ab A Bb B).+const DEFAULT_NAMES = ['C', 'C#', 'D', 'Eb', 'E', 'F', 'F#', 'G', 'Ab', 'A', 'Bb', 'B'];++const spellPitchClass = (pc, pref) =>+ (pref === 'b' ? FLAT_NAMES : pref === '#' ? SHARP_NAMES : DEFAULT_NAMES)[pc];++// Transpose one chord symbol by n semitones (wraps mod 12; negative fine).+// The source accidental steers spelling: a flat-spelled chord stays in flats,+// sharp stays in sharps, naturals use the conventional mixed table. Slash+// basses transpose with the chord (their own accidental wins, else the+// root's). "N.C." and anything that isn't a chord token pass through+// unchanged — forgiving, never throws.+export const transposeChordName = (name, n) => {+ const raw = String(name ?? '');+ if (!Number.isFinite(n)) return raw;+ if (/^N\.?C\.?$/.test(raw)) return raw;+ if (!isChordToken(raw)) return raw;+ const m = /^([A-G])([#b]?)(.*)$/.exec(raw);+ if (!m) return raw;+ const shift = ((Math.trunc(n) % 12) + 12) % 12;+ const pref = m[2];+ let quality = m[3];+ let bassOut = '';+ const slash = /^(.*)\/([A-G])([#b]?)$/.exec(quality);+ if (slash) {+ quality = slash[1];+ const bassPc = (NOTE_TO_PC[slash[2] + slash[3]] + shift) % 12;+ bassOut = `/${spellPitchClass(bassPc, slash[3] || pref)}`;+ }+ const rootPc = (NOTE_TO_PC[m[1] + pref] + shift) % 12;+ return spellPitchClass(rootPc, pref) + quality + bassOut;+};++const transposeToken = (token, n) => {+ if (isChordToken(token)) return transposeChordName(token, n);+ const paren = /^\((.+)\)$/.exec(token);+ if (paren && isChordToken(paren[1])) return `(${transposeChordName(paren[1], n)})`;+ return token;+};++// Rebuild a chords line with each token transposed, keeping every token at+// its original column where possible: shorter names pad back out with spaces,+// longer names eat the following gap. When a grown name would collide with+// the next token, a single separating space is kept (the rest of the line+// shifts by the overflow).+const transposeChordLine = (line, n) => {+ let out = '';+ const re = /\S+/g;+ let m;+ while ((m = re.exec(line))) {+ if (out.length < m.index) out += ' '.repeat(m.index - out.length);+ else if (out.length > 0) out += ' ';+ out += transposeToken(m[0], n);+ }+ return out;+};++// Transpose every chord token on 'chords' and 'chordlyric' lines; all other+// lines (lyrics, tab staffs, sections, prose) pass through untouched. Line+// endings normalize to \n. Never mutates or throws.+export const transposeText = (text, n) => {+ if (!Number.isFinite(n)) return String(text ?? '');+ return String(text ?? '')+ .split(/\r?\n/)+ .map((raw) => {+ const c = classifyLine(raw);+ if (c.type === 'chords') return transposeChordLine(raw, Math.trunc(n));+ if (c.type === 'chordlyric') {+ return raw.replace(/\[([^\]]*)\]/g, (all, inner) =>+ isChordToken(inner) ? `[${transposeChordName(inner, n)}]` : all,+ );+ }+ return raw;+ })+ .join('\n');+};diff --git a/client/src/lib/tabNotation.test.js b/client/src/lib/tabNotation.test.jsnew file mode 100644index 0000000000..858f0a196f--- /dev/null+++ b/client/src/lib/tabNotation.test.js@@ -0,0 +1,428 @@+import { describe, it, expect } from 'vitest';+import {+ CHORD_TOKEN_RE,+ detectFormat,+ parseTabSheet,+ normalizePastedTab,+ transposeChordName,+ transposeText,+} from './tabNotation.js';++// All fixture content is invented ("Example Song" by "The Placeholders") —+// never real lyrics or real records.++describe('CHORD_TOKEN_RE', () => {+ const CHORDS = [+ 'C', 'A', 'G7', 'Am', 'Am7', 'Bm', 'F#', 'Bb', 'F#m', 'Bbm7',+ 'Cmaj7', 'Cmin7', 'CM7', 'Cm7b5', 'F#m7b5', 'C7#9', 'Cdim', 'Cdim7',+ 'Caug', 'C+', 'Asus', 'Asus2', 'Dsus4', 'Cadd9', 'Gadd9', 'C6', 'C9',+ 'C11', 'C13', 'C6/9', 'G/B', 'D/F#', 'Eb/Bb', 'Am7/G', 'Co7', 'C°', 'Cø7',+ 'B7sus4', 'C(b5)', 'Cm(maj7)', 'N.C.', 'NC',+ ];+ it.each(CHORDS)('matches %s', (token) => {+ expect(CHORD_TOKEN_RE.test(token)).toBe(true);+ });++ const WORDS = [+ 'day', 'the', 'life', 'Amen', 'Ambient', 'Bad', 'Dad', 'Go', 'Do', 'No',+ 'Hey', 'Chorus', 'maj7', 'H', 'A-round', 'Bass', 'Edge', 'Gone', 'Fine',+ 'Am7x', 'C/H', 'lantern', 'a',+ ];+ it.each(WORDS)('does not match %s', (token) => {+ expect(CHORD_TOKEN_RE.test(token)).toBe(false);+ });+});++describe('parseTabSheet — line classification', () => {+ const types = (text) => parseTabSheet(text).lines.map((l) => l.type);++ it('classifies a full invented sheet', () => {+ const sheet = [+ '[Verse 1]',+ 'C G Am',+ 'Paper boats on a cardboard sea',+ '',+ 'e|--3--2--0-------|',+ 'B|------3--1------|',+ 'Just some spoken stage notes here',+ ].join('\n');+ expect(types(sheet)).toEqual([+ 'section', 'chords', 'lyric', 'blank', 'tabstaff', 'tabstaff', 'text',+ ]);+ });++ it('extracts chord names and columns from a chords line', () => {+ const { lines } = parseTabSheet('C G7 Am');+ expect(lines[0].type).toBe('chords');+ expect(lines[0].chords).toEqual([+ { name: 'C', col: 0 },+ { name: 'G7', col: 9 },+ { name: 'Am', col: 18 },+ ]);+ });++ it('accepts bar separators and repeat markers as filler on chord lines', () => {+ const { lines } = parseTabSheet('| C | G | Am | (x2)');+ expect(lines[0].type).toBe('chords');+ expect(lines[0].chords.map((c) => c.name)).toEqual(['C', 'G', 'Am']);+ });++ it('counts parenthesized chords with an offset col', () => {+ const { lines } = parseTabSheet('C (Am7) G');+ expect(lines[0].chords).toEqual([+ { name: 'C', col: 0 },+ { name: 'Am7', col: 3 },+ { name: 'G', col: 8 },+ ]);+ });++ it('does NOT classify "A day in the life" style lyrics as chords', () => {+ expect(types('A day in the life')).toEqual(['text']);+ expect(types('Amber waves and gray tin skies')).toEqual(['text']);+ expect(types('Be Good Every Day')).toEqual(['text']);+ });++ it('treats a lone bare "A" line as text, but unambiguous singles as chords', () => {+ expect(types('A')).toEqual(['text']);+ expect(types('Am')).toEqual(['chords']);+ expect(types('F#')).toEqual(['chords']);+ expect(types('Am7')).toEqual(['chords']);+ });++ it('classifies 2+ bare-letter tokens as chords', () => {+ expect(types('A D A E')).toEqual(['chords']);+ });++ it('rejects lines below the 80% chord density gate', () => {+ expect(types('C G and then repeat forever')).toEqual(['text']);+ expect(types('C Am F G repeat')).toEqual(['chords']); // 4/5 = 80%+ });++ it('promotes only the line directly under a chords line to lyric', () => {+ const sheet = 'C G\nFirst invented line\nSecond invented line';+ expect(types(sheet)).toEqual(['chords', 'lyric', 'text']);+ });++ it('does not promote across a blank line', () => {+ expect(types('C G\n\nInvented line')).toEqual(['chords', 'blank', 'text']);+ });+});++describe('parseTabSheet — sections', () => {+ const first = (text) => parseTabSheet(text).lines[0];++ it('bracket headers become sections with a label', () => {+ expect(first('[Verse 1]')).toEqual({ type: 'section', text: '[Verse 1]', label: 'Verse 1' });+ expect(first('[Pre-Chorus]').type).toBe('section');+ expect(first('[Intro]').label).toBe('Intro');+ });++ it('a whole-line bracketed chord is chordlyric, not a section', () => {+ const line = first('[Am]');+ expect(line.type).toBe('chordlyric');+ expect(line.chords).toEqual([{ name: 'Am', col: 0 }]);+ });++ it('ChordPro long and short section directives', () => {+ expect(first('{start_of_chorus}')).toMatchObject({ type: 'section', label: 'Chorus' });+ expect(first('{soc}')).toMatchObject({ type: 'section', label: 'Chorus' });+ expect(first('{sov}')).toMatchObject({ type: 'section', label: 'Verse' });+ expect(first('{sot}')).toMatchObject({ type: 'section', label: 'Tab' });+ expect(first('{start_of_verse: Verse 2}')).toMatchObject({ type: 'section', label: 'Verse 2' });+ });++ it('ChordPro end directives are sections with an empty label', () => {+ expect(first('{end_of_chorus}')).toMatchObject({ type: 'section', label: '' });+ expect(first('{eoc}')).toMatchObject({ type: 'section', label: '' });+ });++ it('bare section words with optional number/colon', () => {+ expect(first('Chorus').type).toBe('section');+ expect(first('Verse 2:')).toMatchObject({ type: 'section', label: 'Verse 2' });+ expect(first('CHORUS:').type).toBe('section');+ });++ it('unknown {directives} are text, not sections', () => {+ expect(first('{comment: play softly}').type).toBe('text');+ });+});++describe('parseTabSheet — tab staffs', () => {+ const type = (line) => parseTabSheet(line).lines[0].type;++ it('recognizes string-letter-prefixed staffs on all six strings', () => {+ for (const staff of [+ 'e|--3--2--0-------|',+ 'B|------3--1------|',+ 'G|----0-----0-----|',+ 'D|-0--------------|',+ 'A|----------------|',+ 'E|----------------|',+ ]) {+ expect(type(staff), staff).toBe('tabstaff');+ }+ });++ it('recognizes bar-first staffs and technique glyphs', () => {+ expect(type('|--3h5p3--7/9--12\\10--|')).toBe('tabstaff');+ expect(type('e|--<7>--x--~~--|')).toBe('tabstaff');+ expect(type('C#|--4--6--|')).toBe('tabstaff');+ });++ it('does not classify chord lines with bars as tabstaff', () => {+ expect(type('C | G | Am')).toBe('chords');+ });++ it('does not classify divider lines as tabstaff', () => {+ expect(type('----------------')).toBe('text');+ });+});++describe('parseTabSheet — chordlyric', () => {+ it('extracts chords with col offsets into the bare lyric', () => {+ const { lines } = parseTabSheet('[C]Twinkle [G]little [Am]lamp');+ expect(lines[0].type).toBe('chordlyric');+ expect(lines[0].text).toBe('Twinkle little lamp');+ expect(lines[0].chords).toEqual([+ { name: 'C', col: 0 },+ { name: 'G', col: 8 },+ { name: 'Am', col: 15 },+ ]);+ });++ it('mid-word chords land at the right column', () => {+ const { lines } = parseTabSheet('Won[C]der[G]ful');+ expect(lines[0].text).toBe('Wonderful');+ expect(lines[0].chords).toEqual([+ { name: 'C', col: 3 },+ { name: 'G', col: 6 },+ ]);+ });++ it('non-chord brackets stay literal in the lyric', () => {+ const { lines } = parseTabSheet('[C]La la [weird] la');+ expect(lines[0].text).toBe('La la [weird] la');+ expect(lines[0].chords).toEqual([{ name: 'C', col: 0 }]);+ });+});++describe('parseTabSheet — meta + errors', () => {+ it('extracts ChordPro meta directives', () => {+ const { meta } = parseTabSheet(+ '{title: Example Song}\n{artist: The Placeholders}\n{key: G}\n{capo: 2}',+ );+ expect(meta).toEqual({ title: 'Example Song', artist: 'The Placeholders', key: 'G', capo: 2 });+ });++ it('supports the short aliases {t:} and {st:}', () => {+ const { meta } = parseTabSheet('{t: Example Song}\n{st: The Placeholders}');+ expect(meta).toEqual({ title: 'Example Song', artist: 'The Placeholders' });+ });++ it('first occurrence wins for duplicate directives', () => {+ const { meta } = parseTabSheet('{title: Example Song}\n{title: Other Title}');+ expect(meta.title).toBe('Example Song');+ });++ it('collects invalid capo values as errors without throwing', () => {+ const { meta, errors } = parseTabSheet('{capo: banana}\n{title: Example Song}');+ expect(meta.capo).toBeUndefined();+ expect(meta.title).toBe('Example Song');+ expect(errors).toEqual(['invalid capo value "banana"']);+ });++ it('never throws on junk input and keeps lines 1:1', () => {+ expect(parseTabSheet(null)).toEqual({ lines: [{ type: 'blank', text: '' }], meta: {}, errors: [] });+ expect(parseTabSheet(undefined).errors).toEqual([]);+ expect(parseTabSheet('a\nb\nc').lines).toHaveLength(3);+ });+});++describe('detectFormat', () => {+ it('chordpro via directives', () => {+ expect(detectFormat('{title: Example Song}\nC G Am')).toBe('chordpro');+ expect(detectFormat('{soc}\nla la\n{eoc}')).toBe('chordpro');+ });++ it('chordpro via inline chord brackets', () => {+ expect(detectFormat('[C]Hum a [G]made-up tune')).toBe('chordpro');+ });++ it('chordpro wins even when tab staffs appear first', () => {+ expect(detectFormat('e|--3--|\n{capo: 1}')).toBe('chordpro');+ });++ it('tab via staff lines or chord lines', () => {+ expect(detectFormat('e|--3--2--|\nB|--1--3--|')).toBe('tab');+ expect(detectFormat('C G Am\nInvented lyric line')).toBe('tab');+ });++ it('plain for prose', () => {+ expect(detectFormat('Just a note the user typed about a song.')).toBe('plain');+ expect(detectFormat('')).toBe('plain');+ expect(detectFormat(undefined)).toBe('plain');+ });+});++describe('normalizePastedTab', () => {+ it('normalizes CRLF and bare CR to LF', () => {+ expect(normalizePastedTab('a\r\nb\rc')).toBe('a\nb\nc');+ });++ it('strips HTML tags and converts breaks to newlines', () => {+ expect(normalizePastedTab('<span class="c">C G</span><br>la la')).toBe('C G\nla la');+ expect(normalizePastedTab('<div>C</div><p>G</p>')).toBe('C\nG');+ });++ it('preserves tab harmonics angle brackets', () => {+ expect(normalizePastedTab('e|--<7>--|')).toBe('e|--<7>--|');+ });++ it('decodes common HTML entities', () => {+ expect(normalizePastedTab('& <3 'tis "x" AB')).toBe(+ '& <3 \'tis "x" AB',+ );+ expect(normalizePastedTab('C G')).toBe('C G');+ });++ it('does not double-decode &lt;', () => {+ expect(normalizePastedTab('&lt;')).toBe('<');+ });++ it('expands tabs to 8-column stops', () => {+ expect(normalizePastedTab('C\tG')).toBe('C G');+ expect(normalizePastedTab('Am7\tD')).toBe('Am7 D');+ });++ it('collapses 3+ blank lines to 2 and trims edges', () => {+ expect(normalizePastedTab('a\n\n\n\n\nb')).toBe('a\n\n\nb');+ expect(normalizePastedTab('a\n\nb')).toBe('a\n\nb');+ expect(normalizePastedTab('\n\na\n\n')).toBe('a');+ });++ it('trims trailing whitespace per line', () => {+ expect(normalizePastedTab('C \nlyric ')).toBe('C\nlyric');+ });++ it('returns empty string for non-string input', () => {+ expect(normalizePastedTab(null)).toBe('');+ expect(normalizePastedTab(undefined)).toBe('');+ expect(normalizePastedTab(42)).toBe('');+ });+});++describe('transposeChordName', () => {+ it('transposes basic chords', () => {+ expect(transposeChordName('Am7', 2)).toBe('Bm7');+ expect(transposeChordName('C', 7)).toBe('G');+ expect(transposeChordName('G', 5)).toBe('C');+ });++ it('wraps around the octave in both directions', () => {+ expect(transposeChordName('B7', 1)).toBe('C7');+ expect(transposeChordName('C', -1)).toBe('B');+ expect(transposeChordName('Am7', 14)).toBe('Bm7');+ expect(transposeChordName('Am7', -10)).toBe('Bm7');+ expect(transposeChordName('C#m', 12)).toBe('C#m');+ expect(transposeChordName('Db', 0)).toBe('Db');+ });++ it('transposes slash chords, bass included', () => {+ expect(transposeChordName('G/B', 2)).toBe('A/C#');+ expect(transposeChordName('D/F#', 2)).toBe('E/G#');+ expect(transposeChordName('Eb/Bb', 2)).toBe('F/C');+ expect(transposeChordName('Am7/G', -2)).toBe('Gm7/F');+ });++ it('preserves the extension text verbatim', () => {+ expect(transposeChordName('F#m7b5', 1)).toBe('Gm7b5');+ expect(transposeChordName('C7#9', 2)).toBe('D7#9');+ expect(transposeChordName('Cadd9', 2)).toBe('Dadd9');+ expect(transposeChordName('C6/9', 2)).toBe('D6/9');+ });++ it('spells with flats when the source used flats, sharps when sharps', () => {+ expect(transposeChordName('Bb', 1)).toBe('B');+ expect(transposeChordName('Bb', 3)).toBe('Db');+ expect(transposeChordName('F#', 2)).toBe('G#');+ expect(transposeChordName('Eb', -2)).toBe('Db');+ });++ it('uses conventional mixed spelling from natural roots', () => {+ expect(transposeChordName('A', 1)).toBe('Bb');+ expect(transposeChordName('C', 1)).toBe('C#');+ expect(transposeChordName('D', 1)).toBe('Eb');+ expect(transposeChordName('F', 1)).toBe('F#');+ expect(transposeChordName('G', 1)).toBe('Ab');+ });++ it('passes through N.C. and non-chords unchanged', () => {+ expect(transposeChordName('N.C.', 5)).toBe('N.C.');+ expect(transposeChordName('hello', 3)).toBe('hello');+ expect(transposeChordName('Amen', 2)).toBe('Amen');+ expect(transposeChordName('', 2)).toBe('');+ expect(transposeChordName(null, 2)).toBe('');+ expect(transposeChordName('C', NaN)).toBe('C');+ });+});++describe('transposeText', () => {+ it('transposes chord lines and leaves lyric/text lines alone', () => {+ const input = 'C G7\nLantern light on a tin-can sea';+ expect(transposeText(input, 2)).toBe('D A7\nLantern light on a tin-can sea');+ });++ it('leaves lyric lines starting with chord-shaped words untouched', () => {+ const input = 'A day in the life of a paper boat';+ expect(transposeText(input, 2)).toBe(input);+ });++ it('leaves tab staffs and section headers untouched', () => {+ const input = '[Verse 1]\ne|--3--2--0--|';+ expect(transposeText(input, 3)).toBe(input);+ });++ it('preserves columns when names keep their length', () => {+ expect(transposeText('C G Am', 2)).toBe('D A Bm');+ });++ it('pads after shrinking names so following chords keep their columns', () => {+ expect(transposeText('C#m F#', -1)).toBe('Cm F');+ expect(transposeText('Bbm7 C', 2)).toBe('Cm7 D');+ });++ it('eats trailing spaces when names grow so following chords keep their columns', () => {+ expect(transposeText('E7 A', 1)).toBe('F7 Bb');+ expect(transposeText('A Bb', 2)).toBe('B C');+ });++ it('keeps a single separating space when a grown name would collide', () => {+ expect(transposeText('Am7b5 G', 1)).toBe('Bbm7b5 Ab');+ });++ it('transposes chordlyric bracket chords in place', () => {+ expect(transposeText('[C]Hum a [G]made-up [Am]tune', 2)).toBe('[D]Hum a [A]made-up [Bm]tune');+ });++ it('leaves non-chord brackets alone on chordlyric lines', () => {+ expect(transposeText('[C]La la [weird] la', 2)).toBe('[D]La la [weird] la');+ });++ it('transposes parenthesized and slash chords on chord lines', () => {+ expect(transposeText('C (Am7) G/B', 2)).toBe('D (Bm7) A/C#');+ });++ it('is identity at n = 0 for chord content', () => {+ const input = 'C G/B Am7\n[C]la [G]la';+ expect(transposeText(input, 0)).toBe(input);+ });++ it('round-trips: +n then -n restores enharmonic pitch classes', () => {+ expect(transposeText(transposeText('C Em G/B', 3), -3)).toBe('C Em G/B');+ });++ it('never throws on junk input', () => {+ expect(transposeText(null, 2)).toBe('');+ expect(transposeText('C G', NaN)).toBe('C G');+ });+});diff --git a/client/src/pages/SongBook.jsx b/client/src/pages/SongBook.jsxnew file mode 100644index 0000000000..d521981367--- /dev/null+++ b/client/src/pages/SongBook.jsx@@ -0,0 +1,260 @@+/**+ * SongBook index — /songbook.+ *+ * Repertoire tracker: every song the user knows or is learning (guitar tabs,+ * chord sheets, sheet music) with a learning stage (new → learning → learned →+ * memorized). A plain padded+scrolling page (NOT full-width, like /rounds);+ * 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.+ */++import { useEffect, useMemo, useState, useCallback } from 'react';+import { useNavigate, useSearchParams, Link } from 'react-router-dom';+import { ListMusic, Plus, Trash2, Download, Search, X } from 'lucide-react';+import toast from '../components/ui/Toast';+import PageHeader from '../components/PageHeader';+import EmptyState from '../components/EmptyState';+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);++export default function SongBook() {+ const navigate = useNavigate();+ const [searchParams, setSearchParams] = useSearchParams();+ const stageFilter = searchParams.get('stage') || '';+ const instrumentFilter = searchParams.get('instrument') || '';+ const tagFilter = searchParams.get('tag') || '';+ const q = searchParams.get('q') || '';++ const setParam = useCallback((key, value) => {+ setSearchParams((prev) => {+ const next = new URLSearchParams(prev);+ if (value) next.set(key, value);+ else next.delete(key);+ return next;+ }, { replace: true });+ }, [setSearchParams]);++ const [songs, setSongs] = useState([]);+ const [loading, setLoading] = useState(true);+ const [title, setTitle] = useState('');+ const { isConfirming, requestDelete, cancelDelete, confirmDelete } = useConfirmDelete();++ useEffect(() => {+ listSongs({ silent: true })+ .then((data) => setSongs(Array.isArray(data?.songs) ? data.songs : []))+ .catch((err) => toast.error(err?.message || 'Failed to load songs'))+ .finally(() => setLoading(false));+ }, []);++ const [create, creating] = useAsyncAction(async () => {+ const name = title.trim();+ if (!name) { toast.error('Give the song a title'); return null; }+ const song = await createSong({ title: name }, { silent: true });+ // A blank new song has nothing to read — open straight into edit mode.+ if (song?.id) navigate(`/songbook/${song.id}?mode=edit`);+ return song;+ }, { errorMessage: 'Failed to create song' });++ const onDelete = useCallback((song) => confirmDelete(() =>+ deleteSong(song.id, { silent: true })+ .then(() => setSongs((prev) => prev.filter((s) => s.id !== song.id)))+ .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).+ const onStageChange = useCallback((id, stage) => {+ patchSongStage(id, stage)+ .then((updated) => setSongs((prev) => prev.map((s) => (s.id === id ? { ...s, ...updated } : s))))+ .catch(() => {});+ }, []);++ const filtered = useMemo(() => {+ const needle = q.trim().toLowerCase();+ return songs.filter((s) => {+ if (stageFilter && s.stage !== stageFilter) return false;+ if (instrumentFilter && s.instrument !== instrumentFilter) return false;+ if (tagFilter && !(Array.isArray(s.tags) && s.tags.includes(tagFilter))) return false;+ if (needle && !(`${s.title} ${s.artist}`.toLowerCase().includes(needle))) return false;+ return true;+ });+ }, [songs, stageFilter, instrumentFilter, tagFilter, q]);++ const selectClass = 'bg-port-bg border border-port-border rounded-lg px-2 py-2 text-sm text-white focus:border-port-accent focus:outline-none';++ return (+ <div>+ <PageHeader+ icon={ListMusic}+ title="SongBook"+ subtitle="Songs you're learning — tabs, chord sheets, and sheet music"+ className="border-b-0 px-0 sm:px-0 py-0 sm:py-1 mb-3"+ actions={(+ <Link+ to="/songbook/import"+ className="flex items-center gap-2 px-3 py-2 text-sm rounded-lg border border-port-border text-gray-300 hover:text-white hover:bg-port-border/50"+ >+ <Download size={16} />+ Import+ </Link>+ )}+ />++ {/* Create row */}+ <form+ onSubmit={(e) => { e.preventDefault(); create(); }}+ 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>+ <input+ id="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"+ />+ </div>+ <button+ type="submit"+ disabled={creating}+ className="flex items-center justify-center gap-2 px-4 py-2 text-sm rounded-lg bg-port-accent text-white hover:bg-port-accent/90 disabled:opacity-50"+ >+ <Plus size={16} />+ New Song+ </button>+ </form>++ {/* Filters (URL-backed) */}+ <div className="flex flex-wrap items-center gap-2 mb-4">+ <div className="relative flex-1 min-w-[160px] max-w-xs">+ <Search size={14} className="absolute left-2.5 top-1/2 -translate-y-1/2 text-gray-500" aria-hidden="true" />+ <input+ type="search"+ value={q}+ onChange={(e) => setParam('q', e.target.value)}+ placeholder="Search title/artist…"+ aria-label="Search songs"+ className="w-full bg-port-bg border border-port-border rounded-lg pl-8 pr-3 py-2 text-sm text-white focus:border-port-accent focus:outline-none"+ />+ </div>+ <select+ value={stageFilter}+ onChange={(e) => setParam('stage', e.target.value)}+ aria-label="Filter by stage"+ className={selectClass}+ >+ <option value="">All stages</option>+ {SONG_STAGES.map((s) => <option key={s.id} value={s.id}>{s.label}</option>)}+ </select>+ <select+ value={instrumentFilter}+ onChange={(e) => setParam('instrument', e.target.value)}+ aria-label="Filter by instrument"+ className={selectClass}+ >+ <option value="">All instruments</option>+ {INSTRUMENTS.map((i) => <option key={i} value={i}>{capitalize(i)}</option>)}+ </select>+ {tagFilter && (+ <button+ type="button"+ onClick={() => setParam('tag', '')}+ className="flex items-center gap-1 px-2 py-1 rounded-full text-xs bg-port-accent/10 text-port-accent border border-port-accent/20 hover:bg-port-accent/20"+ aria-label={`Clear tag filter ${tagFilter}`}+ >+ #{tagFilter}+ <X size={12} />+ </button>+ )}+ </div>++ {/* Grid */}+ {loading ? (+ <p className="text-sm text-gray-500">Loading songs…</p>+ ) : filtered.length === 0 ? (+ songs.length === 0 ? (+ <EmptyState+ icon={ListMusic}+ title="No songs yet"+ message="Add the first song you're learning — create one above, or import a tab from a URL or paste."+ actionTo="/songbook/import"+ actionLabel="Import a song"+ />+ ) : (+ <p className="text-sm text-gray-500">No songs match the current filters.</p>+ )+ ) : (+ <ul className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3">+ {filtered.map((song) => (+ <li+ key={song.id}+ className="group bg-port-card border border-port-border rounded-lg flex items-start gap-3 px-4 py-3 hover:border-port-accent/50"+ >+ <Link to={`/songbook/${song.id}`} className="flex-1 min-w-0">+ <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.updatedAt && <span>Edited {timeAgo(song.updatedAt)}</span>}+ </div>+ {Array.isArray(song.tags) && song.tags.length > 0 && (+ <div className="flex flex-wrap gap-1 mt-1.5">+ {song.tags.map((tag) => (+ <button+ key={tag}+ type="button"+ onClick={(e) => { e.preventDefault(); setParam('tag', tag); }}+ className="px-1.5 py-0.5 rounded-full text-[10px] bg-port-bg text-gray-400 border border-port-border hover:text-port-accent hover:border-port-accent/40"+ >+ #{tag}+ </button>+ ))}+ </div>+ )}+ </Link>+ <div className="flex flex-col items-end gap-2 shrink-0">+ <select+ value={song.stage || 'new'}+ onChange={(e) => onStageChange(song.id, e.target.value)}+ aria-label={`Stage for ${song.title}`}+ className={`text-xs rounded-full border px-2 py-1 focus:outline-none ${SONG_STAGE_COLORS[song.stage] || SONG_STAGE_COLORS.new}`}+ >+ {SONG_STAGES.map((s) => <option key={s.id} value={s.id} className="bg-port-card text-white">{s.label}</option>)}+ </select>+ {isConfirming(song.id) ? (+ <ConfirmButtonPair+ prompt="Delete?"+ ariaLabel={`Confirm delete ${song.title}`}+ onConfirm={() => onDelete(song)}+ onCancel={cancelDelete}+ />+ ) : (+ <button+ type="button"+ onClick={() => requestDelete(song.id)}+ className="p-1.5 text-gray-500 hover:text-port-error"+ aria-label={`Delete ${song.title}`}+ title="Delete song"+ >+ <Trash2 size={15} />+ </button>+ )}+ </div>+ </li>+ ))}+ </ul>+ )}+ </div>+ );+}diff --git a/client/src/pages/SongBook.test.jsx b/client/src/pages/SongBook.test.jsxnew file mode 100644index 0000000000..b5f05f9931--- /dev/null+++ b/client/src/pages/SongBook.test.jsx@@ -0,0 +1,94 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { render, screen, fireEvent, waitFor } from '@testing-library/react';+import { MemoryRouter, Routes, Route } from 'react-router-dom';++// Mock the api barrel (RoundEditor.test.jsx harness style).+const api = vi.hoisted(() => ({+ listSongs: vi.fn(),+ createSong: vi.fn(),+ deleteSong: vi.fn(),+ patchSongStage: vi.fn(),+}));+vi.mock('../services/api', () => api);+vi.mock('../components/ui/Toast', () => ({ default: { error: vi.fn(), success: vi.fn() } }));++import SongBook from './SongBook.jsx';++// Invented fixture data only (privacy convention).+const song = (id, title, extra = {}) => ({+ id,+ title,+ artist: 'The Placeholders',+ instrument: 'guitar',+ stage: 'new',+ tags: ['campfire'],+ key: '',+ capo: 0,+ tuning: '',+ sourceUrl: '',+ content: { format: 'tab', text: '' },+ notes: '',+ attachments: [],+ createdAt: '2026-01-01T00:00:00.000Z',+ updatedAt: '2026-01-01T00:00:00.000Z',+ ...extra,+});++const renderPage = (path = '/songbook') => render(+ <MemoryRouter initialEntries={[path]}>+ <Routes><Route path="/songbook" element={<SongBook />} /></Routes>+ </MemoryRouter>,+);++describe('SongBook index', () => {+ beforeEach(() => {+ api.listSongs.mockReset().mockResolvedValue({ songs: [song('s1', 'Example Song')] });+ api.patchSongStage.mockReset();+ api.deleteSong.mockReset();+ api.createSong.mockReset();+ });++ it('renders the loaded songs', async () => {+ renderPage();+ expect(await screen.findByText('Example Song')).toBeTruthy();+ 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' }));+ 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');+ 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);+ });++ it('deletes a song after inline confirmation and removes its card', async () => {+ api.deleteSong.mockResolvedValue({ id: 's1' });+ renderPage();+ await screen.findByText('Example Song');+ fireEvent.click(screen.getByLabelText('Delete Example Song'));+ fireEvent.click(screen.getByRole('button', { name: 'Delete' }));+ expect(api.deleteSong).toHaveBeenCalledWith('s1', { silent: true });+ await waitFor(() => expect(screen.queryByText('Example Song')).toBeNull());+ });++ it('filters by stage from the URL search param', async () => {+ api.listSongs.mockResolvedValue({+ songs: [song('s1', 'Example Song'), song('s2', 'Other Tune', { stage: 'memorized' })],+ });+ renderPage('/songbook?stage=memorized');+ expect(await screen.findByText('Other Tune')).toBeTruthy();+ expect(screen.queryByText('Example Song')).toBeNull();+ });++ it('shows the teaching empty state when there are no songs', async () => {+ api.listSongs.mockResolvedValue({ songs: [] });+ renderPage();+ expect(await screen.findByText('No songs yet')).toBeTruthy();+ expect(screen.getByText('Import a song')).toBeTruthy();+ });+});diff --git a/client/src/pages/SongBookImport.jsx b/client/src/pages/SongBookImport.jsxnew file mode 100644index 0000000000..967e7246b9--- /dev/null+++ b/client/src/pages/SongBookImport.jsx@@ -0,0 +1,290 @@+/**+ * SongBook import — /songbook/import (plain padded page, NOT full-width).+ *+ * Two URL-param-driven tabs (?tab=paste|url, TabPills):+ * - PASTE: font-mono textarea (+ clipboard Paste / Sample / Clear buttons).+ * Content runs through normalizePastedTab; detectFormat + parseTabSheet+ * drive a live preview (the same TabSheetView the viewer renders) and+ * prefill title/artist/key/capo from ChordPro meta.+ * - URL: input validated with isUrl; Fetch POSTs to the server-side extractor+ * which returns a draft ({ title, artist, content, sourceUrl }) — nothing is+ * stored until the user reviews and Saves.+ *+ * Below either tab: a draft form (title/artist/instrument/stage/tags) → Save →+ * createSong → navigate to the new song's viewer.+ */++import { useMemo, useState, useCallback } from 'react';+import { useNavigate, useSearchParams, 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 { useAsyncAction } from '../hooks/useAsyncAction';+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]+e|--0--2--3--2--0------|+B|--------------3--1--0|++[Verse 1]+C G Am F+Placeholder words in every line+C G F+Nothing here is a real song++[Chorus]+F G C+La la la, la la la`;++// Server import error codes → user-actionable messages (we own the error UI+// here, so the API call passes { silent: true }).+const IMPORT_ERROR_MESSAGES = {+ UNSAFE_URL: 'That URL can\'t be fetched — only public http(s) addresses are allowed.',+ SONG_IMPORT_FETCH_FAILED: 'Couldn\'t fetch that page — check the URL or try copy/pasting the tab instead.',+ SONG_IMPORT_EMPTY: 'No tab or chord content found on that page — try copy/pasting the tab instead.',+};++const TABS = [+ { id: 'paste', label: 'Paste', icon: FileText },+ { 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]);++ // Paste tab state+ const [pasted, setPasted] = useState('');+ const normalized = useMemo(() => normalizePastedTab(pasted), [pasted]);+ const pasteMeta = useMemo(() => (normalized ? parseTabSheet(normalized).meta : {}), [normalized]);++ // URL tab state+ const [url, setUrl] = useState('');+ const [fetched, setFetched] = useState(null); // server draft: { title, artist, content, sourceUrl }++ // Shared draft form+ const [title, setTitle] = useState('');+ const [artist, setArtist] = useState('');+ const [instrument, setInstrument] = useState('guitar');+ const [stage, setStage] = useState('new');+ const [tags, setTags] = useState('');++ const applyMetaDefaults = useCallback((meta) => {+ // Prefill only untouched fields — never clobber what the user typed.+ if (meta?.title) setTitle((cur) => cur || meta.title);+ if (meta?.artist) setArtist((cur) => cur || meta.artist);+ }, []);++ const onPasteButton = useCallback(async () => {+ const text = await readClipboard();+ if (text == null) { toast.error('Clipboard unavailable — paste into the box instead'); return; }+ const clean = normalizePastedTab(text);+ setPasted(clean);+ applyMetaDefaults(parseTabSheet(clean).meta);+ }, [applyMetaDefaults]);++ const [fetchUrl, fetching] = useAsyncAction(async () => {+ const normalizedUrl = normalizeUrl(url);+ if (!normalizedUrl || !isUrl(normalizedUrl)) { toast.error('Enter a valid URL'); return null; }+ const data = await importSongFromUrl(normalizedUrl, { silent: true }).catch((err) => {+ toast.error(IMPORT_ERROR_MESSAGES[err?.code] || err?.message || 'Import failed');+ return null;+ });+ const draft = data?.draft;+ if (!draft) return null;+ 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 [save, saving] = useAsyncAction(async () => {+ const name = title.trim();+ if (!name) { toast.error('Give the song a title'); return null; }+ if (!contentText.trim()) { toast.error('Nothing to save — paste or fetch a tab first'); return null; }+ const body = {+ title: name,+ artist: artist.trim(),+ instrument,+ stage,+ tags: tags.split(',').map((t) => t.trim()).filter(Boolean),+ content: { format: contentFormat, text: contentText },+ };+ if (tab === 'url' && fetched?.sourceUrl) body.sourceUrl = fetched.sourceUrl;+ if (tab === 'paste') {+ if (pasteMeta.key) body.key = pasteMeta.key;+ if (Number.isInteger(pasteMeta.capo)) body.capo = pasteMeta.capo;+ }+ const song = await createSong(body, { silent: true });+ if (song?.id) navigate(`/songbook/${song.id}`);+ return song;+ }, { errorMessage: 'Failed to save song' });++ return (+ <div>+ <PageHeader+ icon={ListMusic}+ title="Import Song"+ subtitle="Paste a tab or fetch one from a URL, review, then save"+ className="border-b-0 px-0 sm:px-0 py-0 sm:py-1 mb-3"+ actions={(+ <Link to="/songbook" className={btnClass}>+ <ArrowLeft size={15} />+ SongBook+ </Link>+ )}+ />++ <TabPills tabs={TABS} activeTab={tab} onChange={setTab} size="sm" ariaLabel="Import source" className="mb-4" />++ {tab === 'paste' ? (+ <div className="mb-4">+ <div className="flex flex-wrap items-center gap-2 mb-2">+ <button type="button" onClick={onPasteButton} className={btnClass}>+ <ClipboardPaste size={14} />+ Paste+ </button>+ <button type="button" onClick={() => { setPasted(SAMPLE_TAB); }} className={btnClass}>+ <Wand2 size={14} />+ Sample+ </button>+ <button type="button" onClick={() => setPasted('')} disabled={!pasted} className={btnClass}>+ <Eraser size={14} />+ Clear+ </button>+ {normalized && (+ <span className="text-xs text-gray-500 ml-auto">+ Detected format: <span className="text-port-accent">{contentFormat}</span>+ </span>+ )}+ </div>+ <label htmlFor="import-paste" className="sr-only">Pasted tab content</label>+ <textarea+ id="import-paste"+ value={pasted}+ onChange={(e) => setPasted(e.target.value)}+ onBlur={() => applyMetaDefaults(pasteMeta)}+ placeholder="Paste a guitar tab, chord sheet, or ChordPro file here…"+ spellCheck={false}+ rows={12}+ className={`${inputClass} font-mono whitespace-pre resize-y`}+ />+ </div>+ ) : (+ <div className="mb-4">+ <form+ onSubmit={(e) => { e.preventDefault(); fetchUrl(); }}+ className="flex flex-col sm:flex-row gap-2 sm:items-end"+ >+ <div className="flex-1">+ <label htmlFor="import-url" className={labelClass}>Tab / chord-sheet URL</label>+ <input+ id="import-url"+ type="text"+ value={url}+ onChange={(e) => setUrl(e.target.value)}+ placeholder="https://example.com/tabs/example-song"+ className={inputClass}+ />+ </div>+ <button+ type="submit"+ disabled={fetching || !isUrl(normalizeUrl(url) || '')}+ className="flex items-center justify-center gap-2 px-4 py-2 text-sm rounded-lg bg-port-accent text-white hover:bg-port-accent/90 disabled:opacity-50"+ >+ <Globe size={15} />+ {fetching ? 'Fetching…' : 'Fetch'}+ </button>+ </form>+ {fetched && (+ <p className="text-xs text-gray-500 mt-2">+ Fetched <span className="text-gray-300">{fetched.title || 'untitled'}</span>+ {fetched.artist ? <> by <span className="text-gray-300">{fetched.artist}</span></> : null}+ {' — '}format <span className="text-port-accent">{contentFormat}</span>. Review below, then save.+ </p>+ )}+ </div>+ )}++ {/* Live preview (shared renderer with the viewer) */}+ {contentText && (+ <div className="mb-4">+ <div className="text-xs text-gray-400 mb-1">Preview</div>+ <div className="bg-port-card border border-port-border rounded-lg p-3 max-h-[50vh] overflow-y-auto overflow-x-auto">+ <TabSheetView text={contentText} />+ </div>+ </div>+ )}++ {/* Draft form */}+ <form+ onSubmit={(e) => { e.preventDefault(); save(); }}+ className="bg-port-card border border-port-border rounded-lg p-4 grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-5 gap-3 items-end"+ >+ <div className="lg:col-span-1">+ <label htmlFor="import-title" className={labelClass}>Title</label>+ <input id="import-title" type="text" value={title} onChange={(e) => setTitle(e.target.value)} placeholder="e.g. Example Song" className={inputClass} />+ </div>+ <div>+ <label htmlFor="import-artist" className={labelClass}>Artist</label>+ <input id="import-artist" type="text" value={artist} onChange={(e) => setArtist(e.target.value)} placeholder="e.g. The Placeholders" className={inputClass} />+ </div>+ <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>)}+ </select>+ </div>+ <div>+ <label htmlFor="import-stage" className={labelClass}>Stage</label>+ <select id="import-stage" value={stage} onChange={(e) => setStage(e.target.value)} className={inputClass}>+ {SONG_STAGES.map((s) => <option key={s.id} value={s.id}>{s.label}</option>)}+ </select>+ </div>+ <div>+ <label htmlFor="import-tags" className={labelClass}>Tags (comma-separated)</label>+ <input id="import-tags" type="text" value={tags} onChange={(e) => setTags(e.target.value)} placeholder="e.g. campfire" className={inputClass} />+ </div>+ <div className="sm:col-span-2 lg:col-span-5">+ <button+ type="submit"+ disabled={saving || !contentText.trim()}+ className="flex items-center justify-center gap-2 px-4 py-2 text-sm rounded-lg bg-port-accent text-white hover:bg-port-accent/90 disabled:opacity-50"+ >+ <Save size={15} />+ {saving ? 'Saving…' : 'Save song'}+ </button>+ </div>+ </form>+ </div>+ );+}diff --git a/client/src/pages/SongBookViewer.jsx b/client/src/pages/SongBookViewer.jsxnew file mode 100644index 0000000000..92c69a3854--- /dev/null+++ b/client/src/pages/SongBookViewer.jsx@@ -0,0 +1,600 @@+/**+ * SongBook viewer — /songbook/:id.+ *+ * Full-bleed page (Layout.jsx isFullWidth matches /songbook/:id): flex-col+ * h-full shell with a shrink-0 header + controls bar and a flex-1+ * overflow-y-auto body the page owns (the autoscroll container).+ *+ * Two URL-param-driven modes (linkable-routes convention):+ * - PLAY (default): the rendered sheet (TabSheetView) with an+ * Ultimate-Guitar-style controls bar — autoscroll play/pause + speed,+ * transpose ± (render-time transposeText, never mutates stored text; offset+ * persisted per song via safeStorage), font size ±, stage select, capo/key/+ * tuning badges, source link — plus the attachments section (synced meta,+ * machine-local bytes → "not on this machine" when absent).+ * - EDIT (?mode=edit): metadata form + font-mono content textarea with format+ * select and live preview. Saves are explicit (single PUT). The whole+ * `content` object is always sent — the server fills nested content+ * defaults, so `{ content: { text } }` alone would reset format to 'tab'.+ *+ * Keyboard (play mode): space play/pause, +/- speed, [ ] transpose, 0 top.+ * A screen wake lock holds while autoscroll plays (useWakeLock).+ */++import { useState, useEffect, useMemo, useRef, useCallback } from 'react';+import { useParams, useNavigate, useSearchParams, Link } from 'react-router-dom';+import {+ ListMusic, ArrowLeft, Save, Trash2, Pencil, Eye, Play, Pause, Plus, Minus,+ ExternalLink, Paperclip, Upload, FileX2,+} from 'lucide-react';+import toast from '../components/ui/Toast';+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 { useAsyncAction } from '../hooks/useAsyncAction';+import { useConfirmDelete } from '../hooks/useConfirmDelete';+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 { readFileAsBase64, ATTACHMENT_MAX_FILE_SIZE } from '../utils/fileUpload';+import {+ getSong, updateSong, patchSongStage, 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;+const FONT_MAX = 1.75;+const FONT_STEP = 0.125;+const SPEED_MIN = 5;+const SPEED_MAX = 150;++// Song record → flat editable draft (tags joined for the text input).+const toDraft = (song) => ({+ title: song.title || '',+ artist: song.artist || '',+ instrument: song.instrument || 'guitar',+ stage: song.stage || 'new',+ key: song.key || '',+ capo: song.capo ?? 0,+ tuning: song.tuning || '',+ tags: Array.isArray(song.tags) ? song.tags.join(', ') : '',+ sourceUrl: song.sourceUrl || '',+ notes: song.notes || '',+ format: song.content?.format || 'tab',+ text: song.content?.text || '',+});++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]);++ const [song, setSong] = useState(null);+ const [loading, setLoading] = useState(true);+ const [notFound, setNotFound] = useState(false);+ const [draft, setDraft] = useState(null);+ // null = not fetched yet, [] = fetched-and-empty (sentinel convention).+ const [attachments, setAttachments] = useState(null);+ const { isConfirming, requestDelete, cancelDelete, confirmDelete } = useConfirmDelete();++ useEffect(() => {+ let cancelled = false;+ setSong(null);+ setDraft(null);+ setAttachments(null);+ setNotFound(false);+ setLoading(true);+ getSong(id, { silent: true })+ .then((s) => {+ if (cancelled) return;+ setSong(s);+ setDraft(toDraft(s));+ })+ .catch(() => { if (!cancelled) setNotFound(true); })+ .finally(() => { if (!cancelled) setLoading(false); });+ listSongAttachments(id, { silent: true })+ .then((list) => { if (!cancelled) setAttachments(Array.isArray(list) ? list : []); })+ .catch(() => { if (!cancelled) setAttachments([]); });+ return () => { cancelled = true; };+ }, [id]);++ // --- Transpose: render-time only, persisted per song via safeStorage.+ const [transpose, setTransposeState] = useState(0);+ useEffect(() => {+ const n = Number(safeReadStorage(`songbook:transpose:${id}`));+ setTransposeState(Number.isFinite(n) ? Math.max(TRANSPOSE_MIN, Math.min(TRANSPOSE_MAX, Math.trunc(n))) : 0);+ }, [id]);+ const setTranspose = useCallback((n) => {+ const clamped = Math.max(TRANSPOSE_MIN, Math.min(TRANSPOSE_MAX, n));+ setTransposeState(clamped);+ safeWriteStorage(`songbook:transpose:${id}`, String(clamped));+ }, [id]);++ // --- Font size (rem scale), persisted globally — a comfortable reading size+ // carries across songs.+ const [fontSize, setFontSizeState] = useState(() => {+ const n = Number(safeReadStorage('songbook:fontSize'));+ return Number.isFinite(n) && n >= FONT_MIN && n <= FONT_MAX ? n : 0.875;+ });+ const setFontSize = useCallback((n) => {+ const clamped = Math.max(FONT_MIN, Math.min(FONT_MAX, n));+ setFontSizeState(clamped);+ safeWriteStorage('songbook:fontSize', String(clamped));+ }, []);++ // --- Autoscroll + wake lock+ const scrollRef = useRef(null);+ const { playing, toggle, stop, pxPerSec, setPxPerSec } = useAutoscroll(scrollRef);+ useWakeLock(playing);++ const scrollToTop = useCallback(() => {+ stop();+ if (scrollRef.current) scrollRef.current.scrollTop = 0;+ }, [stop]);++ useKeyboardShortcuts(!editing && !!song, {+ ' ': toggle,+ '+': () => setPxPerSec((v) => Math.min(SPEED_MAX, v + 5)),+ '=': () => setPxPerSec((v) => Math.min(SPEED_MAX, v + 5)),+ '-': () => setPxPerSec((v) => Math.max(SPEED_MIN, v - 5)),+ '[': () => setTranspose(transpose - 1),+ ']': () => setTranspose(transpose + 1),+ '0': scrollToTop,+ });++ const renderedText = useMemo(() => {+ const text = song?.content?.text || '';+ return transpose ? transposeText(text, transpose) : text;+ }, [song, transpose]);++ // --- Mutations+ const onStageChange = useCallback((stage) => {+ // Helper toast owns the error UI (no custom catch toast → no silent).+ patchSongStage(id, stage)+ .then((updated) => {+ setSong(updated);+ setDraft((prev) => (prev ? { ...prev, stage: updated.stage } : prev));+ })+ .catch(() => {});+ }, [id]);++ const [save, saving] = useAsyncAction(async () => {+ const title = draft.title.trim();+ if (!title) { toast.error('Title is required'); return null; }+ const capo = Math.max(0, Math.min(12, Math.trunc(Number(draft.capo) || 0)));+ // Always the WHOLE content object — a partial { text } would reset format.+ const updated = await updateSong(id, {+ title,+ artist: draft.artist.trim(),+ instrument: draft.instrument,+ stage: draft.stage,+ key: draft.key.trim(),+ capo,+ tuning: draft.tuning.trim(),+ tags: parseTags(draft.tags),+ sourceUrl: draft.sourceUrl.trim(),+ notes: draft.notes,+ content: { format: draft.format, text: draft.text },+ }, { silent: true });+ setSong(updated);+ setDraft(toDraft(updated));+ toast.success('Song saved');+ return updated;+ }, { errorMessage: 'Failed to save song' });++ const onDeleteSong = useCallback(() => confirmDelete(() =>+ deleteSong(id, { silent: true })+ .then(() => navigate('/songbook'))+ .catch((err) => toast.error(err?.message || 'Failed to delete song')),+ ), [confirmDelete, id, navigate]);++ // --- Attachments+ const fileInputRef = useRef(null);+ const [uploadFiles, uploading] = useAsyncAction(async (files) => {+ for (const file of Array.from(files)) {+ if (file.size > ATTACHMENT_MAX_FILE_SIZE) {+ toast.error(`"${file.name}" exceeds ${Math.round(ATTACHMENT_MAX_FILE_SIZE / 1024 / 1024)}MB limit`);+ continue;+ }+ const data = await readFileAsBase64(file);+ const res = await uploadSongAttachment(id, { filename: file.name, data }, { silent: true });+ if (res?.attachment) {+ setAttachments((prev) => [...(prev || []), { ...res.attachment, present: true }]);+ }+ }+ }, { errorMessage: 'Upload failed' });++ const onDeleteAttachment = useCallback((filename) => confirmDelete(() =>+ deleteSongAttachment(id, filename, { silent: true })+ .then((res) => {+ // Server returns the updated meta list; carry over local present flags.+ setAttachments((prev) => (res?.attachments || []).map((meta) => ({+ ...meta,+ present: prev?.find((a) => a.filename === meta.filename)?.present ?? false,+ })));+ })+ .catch((err) => toast.error(err?.message || 'Failed to delete attachment')),+ ), [confirmDelete, id]);++ // --- Render states+ if (notFound) {+ return (+ <div className="flex flex-col h-full items-center justify-center text-center p-6">+ <ListMusic size={32} className="text-gray-600 mb-3" />+ <h2 className="text-white font-semibold mb-1">Song not found</h2>+ <p className="text-gray-400 text-sm mb-4">It may have been deleted, or the link is stale.</p>+ <Link to="/songbook" className="px-4 py-2 rounded-lg text-sm bg-port-accent/10 text-port-accent hover:bg-port-accent/20">+ Back to SongBook+ </Link>+ </div>+ );+ }++ if (loading || !song) {+ return <p className="p-6 text-sm text-gray-500">Loading song…</p>;+ }++ const stageClass = SONG_STAGE_COLORS[song.stage] || SONG_STAGE_COLORS.new;++ return (+ <div className="flex flex-col h-full">+ <PageHeader+ icon={ListMusic}+ title={song.title}+ 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">+ <ArrowLeft size={15} />+ <span className="hidden sm:inline">All songs</span>+ </Link>+ {editing ? (+ <>+ <button+ type="button"+ onClick={() => save()}+ disabled={saving}+ className="flex items-center gap-1.5 px-3 py-2 text-sm rounded-lg bg-port-accent text-white hover:bg-port-accent/90 disabled:opacity-50"+ >+ <Save size={15} />+ {saving ? 'Saving…' : 'Save'}+ </button>+ <button+ type="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"+ >+ <Eye size={15} />+ View+ </button>+ </>+ ) : (+ <button+ type="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"+ >+ <Pencil size={15} />+ Edit+ </button>+ )}+ {isConfirming('song') ? (+ <ConfirmButtonPair+ prompt="Delete?"+ ariaLabel={`Confirm delete ${song.title}`}+ onConfirm={onDeleteSong}+ onCancel={cancelDelete}+ />+ ) : (+ <button+ type="button"+ onClick={() => requestDelete('song')}+ className="p-2 text-gray-500 hover:text-port-error"+ aria-label={`Delete ${song.title}`}+ title="Delete song"+ >+ <Trash2 size={16} />+ </button>+ )}+ </>+ )}+ />++ {editing ? (+ /* ============================== EDIT MODE ============================== */+ <div className="flex-1 overflow-y-auto p-4">+ <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3 mb-4">+ <div>+ <label htmlFor="song-edit-title" className={labelClass}>Title</label>+ <input id="song-edit-title" type="text" value={draft.title} onChange={(e) => setDraft({ ...draft, title: e.target.value })} className={inputClass} />+ </div>+ <div>+ <label htmlFor="song-edit-artist" className={labelClass}>Artist</label>+ <input id="song-edit-artist" type="text" value={draft.artist} onChange={(e) => setDraft({ ...draft, artist: e.target.value })} className={inputClass} />+ </div>+ <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>)}+ </select>+ </div>+ <div>+ <label htmlFor="song-edit-stage" className={labelClass}>Stage</label>+ <select id="song-edit-stage" value={draft.stage} onChange={(e) => setDraft({ ...draft, stage: e.target.value })} className={inputClass}>+ {SONG_STAGES.map((s) => <option key={s.id} value={s.id}>{s.label}</option>)}+ </select>+ </div>+ <div>+ <label htmlFor="song-edit-key" className={labelClass}>Key</label>+ <input id="song-edit-key" type="text" value={draft.key} onChange={(e) => setDraft({ ...draft, key: e.target.value })} placeholder="e.g. Am" className={inputClass} />+ </div>+ <div>+ <label htmlFor="song-edit-capo" className={labelClass}>Capo</label>+ <input id="song-edit-capo" type="number" min="0" max="12" value={draft.capo} onChange={(e) => setDraft({ ...draft, capo: e.target.value })} className={inputClass} />+ </div>+ <div>+ <label htmlFor="song-edit-tuning" className={labelClass}>Tuning</label>+ <input id="song-edit-tuning" type="text" value={draft.tuning} onChange={(e) => setDraft({ ...draft, tuning: e.target.value })} placeholder="e.g. Drop D" className={inputClass} />+ </div>+ <div>+ <label htmlFor="song-edit-tags" className={labelClass}>Tags (comma-separated)</label>+ <input id="song-edit-tags" type="text" value={draft.tags} onChange={(e) => setDraft({ ...draft, tags: e.target.value })} placeholder="e.g. campfire, fingerstyle" className={inputClass} />+ </div>+ <div className="sm:col-span-2">+ <label htmlFor="song-edit-source" className={labelClass}>Source URL</label>+ <input id="song-edit-source" type="text" value={draft.sourceUrl} onChange={(e) => setDraft({ ...draft, sourceUrl: e.target.value })} placeholder="https://…" className={inputClass} />+ </div>+ <div className="sm:col-span-2">+ <label htmlFor="song-edit-notes" className={labelClass}>Notes</label>+ <AutoSizeTextarea+ id="song-edit-notes"+ value={draft.notes}+ onChange={(e) => setDraft({ ...draft, notes: e.target.value })}+ placeholder="Practice notes, tricky passages…"+ className={`${inputClass} min-h-[42px]`}+ />+ </div>+ </div>++ <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">+ <div>+ <div className="flex items-center justify-between mb-1">+ <label htmlFor="song-edit-text" className="text-xs text-gray-400">Content</label>+ <div className="flex items-center gap-2">+ <label htmlFor="song-edit-format" className="text-xs text-gray-500">Format</label>+ <select+ id="song-edit-format"+ value={draft.format}+ onChange={(e) => setDraft({ ...draft, format: e.target.value })}+ className="bg-port-bg border border-port-border rounded px-2 py-1 text-xs text-white focus:border-port-accent focus:outline-none"+ >+ {SONG_FORMATS.map((f) => <option key={f} value={f}>{f}</option>)}+ </select>+ </div>+ </div>+ <AutoSizeTextarea+ id="song-edit-text"+ value={draft.text}+ onChange={(e) => setDraft({ ...draft, text: e.target.value })}+ placeholder={'[Verse 1]\nC G\nExample lyrics here…'}+ spellCheck={false}+ className={`${inputClass} font-mono min-h-[280px] whitespace-pre`}+ />+ </div>+ <div>+ <div className="text-xs text-gray-400 mb-1">Preview</div>+ <div className="bg-port-card border border-port-border rounded-lg p-3 overflow-x-auto">+ <TabSheetView text={draft.text} fontSizeRem={fontSize} />+ </div>+ </div>+ </div>+ </div>+ ) : (+ /* ============================== PLAY MODE ============================== */+ <>+ <div className="shrink-0 border-b border-port-border bg-port-card/60 px-3 py-2 flex flex-wrap items-center gap-x-4 gap-y-2">+ {/* Autoscroll */}+ <div className="flex items-center gap-2">+ <button+ type="button"+ onClick={toggle}+ className={`${ctrlBtnClass} ${playing ? 'text-port-accent border-port-accent/50' : ''}`}+ aria-label={playing ? 'Pause autoscroll' : 'Play autoscroll'}+ title={playing ? 'Pause autoscroll (space)' : 'Play autoscroll (space)'}+ >+ {playing ? <Pause size={18} /> : <Play size={18} />}+ </button>+ <label htmlFor="song-speed" className="sr-only">Autoscroll speed</label>+ <input+ id="song-speed"+ type="range"+ min={SPEED_MIN}+ max={SPEED_MAX}+ value={pxPerSec}+ onChange={(e) => setPxPerSec(Number(e.target.value))}+ className="w-24 sm:w-32 accent-port-accent"+ title="Autoscroll speed (+/-)"+ />+ </div>++ {/* Transpose */}+ <div className="flex items-center gap-1" role="group" aria-label="Transpose">+ <button type="button" onClick={() => setTranspose(transpose - 1)} className={ctrlBtnClass} aria-label="Transpose down" title="Transpose down ([)">+ <Minus size={16} />+ </button>+ <span className="min-w-[3.5rem] text-center text-sm text-gray-300 font-mono" title="Transpose (semitones)">+ {transpose > 0 ? `+${transpose}` : transpose}+ </span>+ <button type="button" onClick={() => setTranspose(transpose + 1)} className={ctrlBtnClass} aria-label="Transpose up" title="Transpose up (])">+ <Plus size={16} />+ </button>+ </div>++ {/* Font size */}+ <div className="flex items-center gap-1" role="group" aria-label="Font size">+ <button type="button" onClick={() => setFontSize(fontSize - FONT_STEP)} className={`${ctrlBtnClass} text-xs font-bold`} aria-label="Smaller text">+ A−+ </button>+ <button type="button" onClick={() => setFontSize(fontSize + FONT_STEP)} className={`${ctrlBtnClass} text-sm font-bold`} aria-label="Larger text">+ A++ </button>+ </div>++ {/* Stage */}+ <div>+ <label htmlFor="song-stage" className="sr-only">Learning stage</label>+ <select+ id="song-stage"+ value={song.stage || 'new'}+ onChange={(e) => onStageChange(e.target.value)}+ className={`text-xs rounded-full border px-2 py-2 min-h-[44px] focus:outline-none ${stageClass}`}+ >+ {SONG_STAGES.map((s) => <option key={s.id} value={s.id} className="bg-port-card text-white">{s.label}</option>)}+ </select>+ </div>++ {/* Badges + source */}+ <div className="flex flex-wrap items-center gap-2 text-xs text-gray-400 ml-auto">+ {song.key && <span className="px-2 py-1 rounded-full bg-port-bg border border-port-border">Key {song.key}</span>}+ {song.capo > 0 && <span className="px-2 py-1 rounded-full bg-port-bg border border-port-border">Capo {song.capo}</span>}+ {song.tuning && <span className="px-2 py-1 rounded-full bg-port-bg border border-port-border">{song.tuning}</span>}+ {isHttpUrl(song.sourceUrl) && (+ <a+ href={song.sourceUrl}+ target="_blank"+ rel="noopener noreferrer"+ className="flex items-center gap-1 px-2 py-1 rounded-full bg-port-bg border border-port-border text-port-accent hover:border-port-accent/50"+ >+ <ExternalLink size={12} />+ Source+ </a>+ )}+ </div>+ </div>++ <div ref={scrollRef} className="flex-1 overflow-y-auto px-4 py-4">+ {song.content?.text ? (+ <TabSheetView text={renderedText} fontSizeRem={fontSize} className="max-w-4xl" />+ ) : (+ <p className="text-sm text-gray-500">+ No sheet content yet — <button type="button" onClick={() => setMode('edit')} className="text-port-accent hover:underline">add some in Edit mode</button>.+ </p>+ )}++ {song.notes && (+ <div className="mt-6 max-w-4xl text-sm text-gray-400 whitespace-pre-wrap border-t border-port-border pt-3">+ {song.notes}+ </div>+ )}++ {/* Attachments */}+ <div className="mt-8 max-w-4xl border-t border-port-border pt-4 pb-16">+ <div className="flex items-center justify-between mb-2">+ <h2 className="flex items-center gap-2 text-sm font-semibold text-white">+ <Paperclip size={14} className="text-gray-500" />+ Attachments+ </h2>+ <div>+ <input+ ref={fileInputRef}+ type="file"+ multiple+ className="hidden"+ aria-label="Upload attachment"+ onChange={(e) => { if (e.target.files?.length) uploadFiles(e.target.files); e.target.value = ''; }}+ />+ <button+ type="button"+ onClick={() => fileInputRef.current?.click()}+ disabled={uploading}+ className="flex items-center gap-1.5 px-3 py-2 text-xs rounded-lg border border-port-border text-gray-300 hover:text-white hover:bg-port-border/50 disabled:opacity-50"+ >+ <Upload size={13} />+ {uploading ? 'Uploading…' : 'Upload'}+ </button>+ </div>+ </div>+ {attachments === null ? (+ <p className="text-xs text-gray-500">Loading attachments…</p>+ ) : attachments.length === 0 ? (+ <p className="text-xs text-gray-500">No attachments — upload sheet-music PDFs, images, or MIDI files.</p>+ ) : (+ <ul className="space-y-1">+ {attachments.map((att) => (+ <li key={att.filename} className="flex items-center gap-3 px-3 py-2 bg-port-card border border-port-border rounded-lg text-sm">+ {att.present ? (+ <a+ href={songAttachmentUrl(id, att.filename)}+ target="_blank"+ rel="noopener noreferrer"+ className="flex-1 min-w-0 truncate text-port-accent hover:underline"+ title={att.label || att.filename}+ >+ {att.label || att.filename}+ </a>+ ) : (+ <span className="flex-1 min-w-0 flex items-center gap-2 truncate text-gray-500" title={att.label || att.filename}>+ <FileX2 size={13} className="shrink-0" />+ <span className="truncate">{att.label || att.filename}</span>+ <span className="shrink-0 text-[10px] uppercase tracking-wide text-gray-600 border border-port-border rounded-full px-1.5 py-0.5">not on this machine</span>+ </span>+ )}+ {att.size != null && <span className="shrink-0 text-xs text-gray-500">{formatBytes(att.size)}</span>}+ {isConfirming(att.filename) ? (+ <ConfirmButtonPair+ prompt="Delete?"+ className="shrink-0"+ ariaLabel={`Confirm delete ${att.label || att.filename}`}+ onConfirm={() => onDeleteAttachment(att.filename)}+ onCancel={cancelDelete}+ />+ ) : (+ <button+ type="button"+ onClick={() => requestDelete(att.filename)}+ className="p-1.5 shrink-0 text-gray-500 hover:text-port-error"+ aria-label={`Delete attachment ${att.label || att.filename}`}+ >+ <Trash2 size={14} />+ </button>+ )}+ </li>+ ))}+ </ul>+ )}+ </div>+ </div>+ </>+ )}+ </div>+ );+}diff --git a/client/src/pages/SongBookViewer.test.jsx b/client/src/pages/SongBookViewer.test.jsxnew file mode 100644index 0000000000..faa5dab917--- /dev/null+++ b/client/src/pages/SongBookViewer.test.jsx@@ -0,0 +1,120 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { render, screen, fireEvent, waitFor } from '@testing-library/react';+import { MemoryRouter, Routes, Route } from 'react-router-dom';++// Mock the api barrel (RoundEditor.test.jsx harness style).+const api = vi.hoisted(() => ({+ getSong: vi.fn(),+ updateSong: vi.fn(),+ patchSongStage: vi.fn(),+ deleteSong: vi.fn(),+ listSongAttachments: vi.fn(),+ uploadSongAttachment: vi.fn(),+ deleteSongAttachment: vi.fn(),+ songAttachmentUrl: (id, filename) => `/api/brain/songbook/${id}/attachments/${filename}`,+}));+vi.mock('../services/api', () => api);+vi.mock('../components/ui/Toast', () => ({ default: { error: vi.fn(), success: vi.fn() } }));++import SongBookViewer from './SongBookViewer.jsx';++// Invented fixture data only (privacy convention) — nonsense sheet content.+const SHEET = `[Chorus]+C G Am F+Nonsense words here`;++const song = (extra = {}) => ({+ id: 'abc',+ title: 'Example Song',+ artist: 'The Placeholders',+ instrument: 'guitar',+ stage: 'new',+ tags: [],+ key: 'C',+ capo: 2,+ tuning: '',+ sourceUrl: '',+ content: { format: 'tab', text: SHEET },+ scrollDurationSec: null,+ notes: '',+ attachments: [],+ createdAt: '2026-01-01T00:00:00.000Z',+ updatedAt: '2026-01-01T00:00:00.000Z',+ ...extra,+});++const renderPage = (path = '/songbook/abc') => render(+ <MemoryRouter initialEntries={[path]}>+ <Routes><Route path="/songbook/:id" element={<SongBookViewer />} /></Routes>+ </MemoryRouter>,+);++describe('SongBookViewer', () => {+ beforeEach(() => {+ api.getSong.mockReset().mockResolvedValue(song());+ api.listSongAttachments.mockReset().mockResolvedValue([]);+ api.patchSongStage.mockReset();+ api.updateSong.mockReset();+ api.deleteSong.mockReset();+ globalThis.localStorage?.clear?.();+ });++ it('renders the parsed sheet in play mode', async () => {+ renderPage();+ expect(await screen.findByText('Example Song')).toBeTruthy();+ // Section header + lyric line from parseTabSheet.+ expect(await screen.findByText('Chorus')).toBeTruthy();+ expect(screen.getByText('Nonsense words here')).toBeTruthy();+ // Meta badges+ expect(screen.getByText('Key C')).toBeTruthy();+ expect(screen.getByText('Capo 2')).toBeTruthy();+ // Attachments settle to the empty message (no act warnings left pending).+ expect(await screen.findByText(/No attachments/)).toBeTruthy();+ });++ it('shows the not-found fallback for a stale id', async () => {+ api.getSong.mockRejectedValue(Object.assign(new Error('Song not found'), { status: 404 }));+ api.listSongAttachments.mockRejectedValue(new Error('Song not found'));+ renderPage();+ expect(await screen.findByText('Song not found')).toBeTruthy();+ 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' }));+ renderPage();+ const select = await screen.findByLabelText('Learning stage');+ fireEvent.change(select, { target: { value: 'learned' } });+ expect(api.patchSongStage).toHaveBeenCalledWith('abc', 'learned');+ await waitFor(() => expect(screen.getByLabelText('Learning stage').value).toBe('learned'));+ });++ it('marks synced-but-absent attachments as not on this machine', async () => {+ api.listSongAttachments.mockResolvedValue([+ { filename: 'aaaa1111-sheet.pdf', label: 'Sheet music', mime: 'application/pdf', size: 1024, sha256: 'x', present: false },+ { filename: 'bbbb2222-local.pdf', label: 'Local copy', mime: 'application/pdf', size: 2048, sha256: 'y', present: true },+ ]);+ renderPage();+ expect(await screen.findByText('not on this machine')).toBeTruthy();+ // The present attachment is a link to the serve URL; the absent one is not.+ const link = screen.getByRole('link', { name: 'Local copy' });+ expect(link.getAttribute('href')).toBe('/api/brain/songbook/abc/attachments/bbbb2222-local.pdf');+ expect(screen.queryByRole('link', { name: /Sheet music/ })).toBeNull();+ });++ it('renders the edit form in ?mode=edit and saves the whole content object', async () => {+ api.updateSong.mockImplementation((id, patch) => Promise.resolve(song({ ...patch })));+ renderPage('/songbook/abc?mode=edit');+ const titleInput = await screen.findByLabelText('Title');+ expect(titleInput.value).toBe('Example Song');+ fireEvent.change(titleInput, { target: { value: 'Renamed Song' } });+ fireEvent.click(screen.getByRole('button', { name: 'Save' }));+ await waitFor(() => expect(api.updateSong).toHaveBeenCalled());+ const [, patch] = api.updateSong.mock.calls[0];+ expect(patch.title).toBe('Renamed Song');+ // The WHOLE content object goes in the PUT (format would otherwise reset).+ expect(patch.content).toEqual({ format: 'tab', text: SHEET });+ // attachments is server-managed — never sent.+ expect('attachments' in patch).toBe(false);+ });+});diff --git a/client/src/services/README.md b/client/src/services/README.mdindex 71818d4c06..9e775132af 100644--- a/client/src/services/README.md+++ b/client/src/services/README.md@@ -105,6 +105,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire| `apiWritersRoom.js` | Writers Room (folders + works + drafts, live continuation + render-preview reservation, scene-image attach). || `apiSharing.js` | Share buckets + federation sync. || `apiRounds.js` | Rounds workbench CRUD (a cappella round writing + arranging voice layers + learning tracking). |+| `apiSongbook.js` | SongBook repertoire tracker (`/songbook` — Brain `songs` entity): song CRUD + stage PATCH, URL import draft, and attachments (base64 upload, present-flag list, raw serve URL via `songAttachmentUrl`). || `apiPeerSync.js` | Per-record peer sync subscriptions (universe + series → other PortOS instances over Tailnet). || `apiSyncReview.js` | Sync hygiene: duplicate-record detection + smart merge (universe/series) and the non-blocking edit-conflict journal (list/resolve). Surfaced in Sharing → Duplicates / Conflicts. |diff --git a/client/src/services/api.js b/client/src/services/api.jsindex 7930563f18..03acda67c3 100644--- a/client/src/services/api.js+++ b/client/src/services/api.js@@ -63,6 +63,7 @@ export * from './apiMusic.js';export * from './apiPipeline.js';export * from './apiSharing.js';export * from './apiRounds.js';+export * from './apiSongbook.js';export * from './apiPeerSync.js';export * from './apiSyncReview.js';export * from './apiCreativeDirector.js';diff --git a/client/src/services/apiSongbook.js b/client/src/services/apiSongbook.jsnew file mode 100644index 0000000000..c4f8dcdb2a--- /dev/null+++ b/client/src/services/apiSongbook.js@@ -0,0 +1,61 @@+import { request } from './apiCore.js';++// SongBook API surface (Brain repertoire tracker — guitar tabs / chord sheets /+// sheet music at /songbook). Every helper takes an optional `options` arg so+// callers with their own `.catch` toast can pass `{ silent: true }` to avoid a+// double-toast (project convention). Path params are URL-encoded.+//+// Server contract notes (server/routes/brainSongbook.js):+// - POST / and POST /:id/attachments return 201 with the created record /+// `{ attachment }` in the body.+// - PUT is a defaults-free partial, BUT a nested `content` object fills inner+// defaults — callers must always send the WHOLE content object+// ({ format, text }), never `{ content: { text } }` alone (format would+// reset to 'tab'). Never send `attachments` (server-managed; stripped).+// - DELETE /:id/attachments/:filename returns+// `{ success, filename, attachments }` — `attachments` is the updated meta+// list, usable directly for reactive state.+// - GET /:id/attachments entries carry `present: boolean` (bytes exist on this+// machine); serving an absent file 404s with code NOT_ON_THIS_MACHINE.++const enc = encodeURIComponent;++export const listSongs = (options) => request('/brain/songbook', options);++export const getSong = (id, options) => request(`/brain/songbook/${enc(id)}`, options);++export const createSong = (body = {}, options) =>+ request('/brain/songbook', { method: 'POST', body: JSON.stringify(body), ...options });++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 });++// Fetch + extract a draft from a tab/chord-sheet URL → { draft: { title,+// artist, content: { format, text }, sourceUrl } }. Nothing is stored — the+// user reviews and saves explicitly. Error codes: 400 UNSAFE_URL,+// 502 SONG_IMPORT_FETCH_FAILED, 422 SONG_IMPORT_EMPTY.+export const importSongFromUrl = (url, options) =>+ request('/brain/songbook/import/url', { method: 'POST', body: JSON.stringify({ url }), ...options });++// → [{ filename, label, mime, size, sha256, present }] (present = bytes local)+export const listSongAttachments = (id, options) =>+ request(`/brain/songbook/${enc(id)}/attachments`, options);++// body: { filename, data (base64), label? } → { attachment } (201)+export const uploadSongAttachment = (id, body, options) =>+ request(`/brain/songbook/${enc(id)}/attachments`, { method: 'POST', body: JSON.stringify(body), ...options });++// → { success, filename, attachments } — attachments is the updated meta list.+export const deleteSongAttachment = (id, filename, options) =>+ request(`/brain/songbook/${enc(id)}/attachments/${enc(filename)}`, { method: 'DELETE', ...options });++// Raw URL for opening/serving an attachment's bytes (href/src, not fetch).+export const songAttachmentUrl = (id, filename) =>+ `/api/brain/songbook/${enc(id)}/attachments/${enc(filename)}`;diff --git a/data.reference/brain/songs.json b/data.reference/brain/songs.jsonnew file mode 100644index 0000000000..79802cb55a--- /dev/null+++ b/data.reference/brain/songs.json@@ -0,0 +1,3 @@+{+ "records": {}+}diff --git a/docs/plans/2026-07-15-songbook.md b/docs/plans/2026-07-15-songbook.mdnew file mode 100644index 0000000000..1d5016aec6--- /dev/null+++ b/docs/plans/2026-07-15-songbook.md@@ -0,0 +1,213 @@+# SongBook — guitar tabs, chord sheets & sheet music in the Brain++Date: 2026-07-15. Status: approved design, implemented on `feature/songbook`.++## What it is++A repertoire tracker inside the Brain: songs the user knows or is learning (guitar+tabs, chord/lyric sheets, piano sheet music), each with a learning stage+(`new → learning → learned → memorized`), plus an Ultimate-Guitar-style playback+view with adjustable autoscroll, transpose, and font sizing. Content arrives by+paste (auto-formatted) or by URL import (server-side fetch + extraction).++## Storage: Brain entity type `songs` (NOT a new data store)++Songs enroll in the existing Brain entity store — add `'songs'` to+`BRAIN_ENTITY_TYPES`, `FILES`, and the caches map in+`server/services/brainStorage.js`. That single enrollment derives: sync-log+appends, LWW peer sync, tombstone deletes + GC, reconcile checksum coverage, and+`originInstanceId` backfill. Older peers skip the unknown type gracefully+(`applyRemoteChanges` skips unknown types), so no schema-version bump is needed.+This is deliberately NOT a fresh `data/*.json` store (STORAGE.md anti-pattern) —+it joins an existing storage system, and it is NOT db-primary because the user's+"Brain" domain is file-primary with its own federation pipeline and songs should+sync across machines like every other brain record.++- Records persist to `data/brain/songs.json` (`{ records: { id: record } }`).+- Seed file: `data.reference/brain/songs.json` with `{ "records": {} }`.+- All writes go through brainStorage's generic API (`create/update/remove/getAll/getById`)+ — never write the JSON directly. Deletes are tombstones (brainStorage.remove).+- Attachments (PDF sheet music, images, MIDI): **metadata in the synced record**+ (identical on all peers, so the reconcile checksum stays clean); **bytes+ machine-local** under `data/brain/songbook/` (`<uuid>-<sanitized-name>`).+ Peers that lack the file render "not on this machine". `data/brain/` is already+ covered by backup; do NOT add excludes.++## Record schema (Zod in `server/lib/brainValidation.js`)++```js+songStageEnum = z.enum(['new', 'learning', 'learned', 'memorized'])+songInstrumentEnum = z.enum(['guitar', 'piano', 'ukulele', 'bass', 'voice', 'other'])+songContentFormatEnum = z.enum(['chordpro', 'tab', 'plain'])++songInputSchema = {+ title: z.string().trim().min(1).max(300),+ artist: z.string().trim().max(300).optional().default(''),+ instrument: songInstrumentEnum.optional().default('guitar'),+ stage: songStageEnum.optional().default('new'),+ tags: z.array(z.string().trim().min(1).max(50)).max(50).optional().default([]),+ key: z.string().trim().max(20).optional().default(''),+ capo: z.number().int().min(0).max(12).optional().default(0),+ tuning: z.string().trim().max(40).optional().default(''),+ sourceUrl: z.string().trim().max(2000).optional().default(''),+ content: 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(''),+}+// songRecordSchema = input + server-managed fields:+// attachments: [{ filename, label, mime, size, sha256 }] (default [])+// + brainStorage-stamped id/createdAt/updatedAt/originInstanceId+```++`attachments` is server-managed (mutated only by the attachment endpoints) — the+PUT handler must ignore/strip client-supplied `attachments`.++## Server API (sub-router `server/routes/brainSongbook.js`, mounted from the `server/routes/brain.js` barrel at `/songbook` → full paths `/api/brain/songbook/...`)++- `GET /` → `{ songs: [...] }` (tombstones excluded — brainStorage does this)+- `GET /:id` → record or 404 ServerError+- `POST /` — validateRequest(songInputSchema) → created record+- `PUT /:id` — validateRequest(songInputSchema.partial()), strips `attachments`, → updated record+- `PATCH /:id/stage` — `{ stage: songStageEnum }` → updated record (cheap chip-flip path)+- `DELETE /:id` → `{ id }` (tombstone)+- `POST /import/url` — `{ url: z.string().url() }` → `{ draft: { title, artist, content: { format, text }, sourceUrl } }`+ Synchronous (no SSE). Service `server/services/brainSongbookImport.js`.+- `POST /:id/attachments` — `{ filename, data (base64), label? }`, 50MB cap,+ extension allowlist (crib `server/routes/attachments.js`: sanitizeFilename,+ isPathInsideDir, `<uuid>-<name>`), writes bytes + sha256, appends meta to record+ → `{ attachment }`+- `GET /:id/attachments` → `[{ ...meta, present: boolean }]` (present = bytes exist locally)+- `GET /:id/attachments/:filename` → serves file (nosniff; attachment disposition for risky MIME)+- `DELETE /:id/attachments/:filename` → removes meta from record + deletes local bytes++Conventions: asyncHandler everywhere, no try/catch, ServerError for 404s,+schemas in `server/lib/brainValidation.js` (namespace-exported in the lib barrel —+watch the collision-detector test).++## URL import service (`server/services/brainSongbookImport.js`)++1. `assertPublicHttpUrl` + text fetch via `server/lib/safeUrlFetch.js`.+2. Extractors, first match wins:+ a. **Ultimate Guitar**: the page embeds JSON in `<div class="js-store" data-content="...">`+ — HTML-entity-decode, JSON.parse, read `store.page.data.tab_view.wiki_tab.content`+ (tab text with `[ch]...[/ch]` / `[tab]...[/tab]` markers — strip markers) and+ `store.page.data.tab.song_name / artist_name`. Defensive optional-chaining; any+ shape drift falls through to (b).+ b. **Generic `<pre>` block**: largest `<pre>` in the page (regex, no cheerio),+ entity-decoded.+ c. **Fallback**: strip tags → plain text; if the result has no chord-like or+ tab-like lines (server keeps a tiny line-classifier mirror or just length+ heuristics), still return it as `format: 'plain'`.+3. Title/artist fallback: `<title>` tag parsing (`"X by Y" / "X - Y"` patterns).+4. Never store on import — return a draft; the client shows a review/edit screen+ and the user saves explicitly. Emoji-prefixed single-line logs.++## Client parser (`client/src/lib/tabNotation.js` — pure leaf, modeled on `scoreNotation.js`)++```js+detectFormat(text) // → 'chordpro' | 'tab' | 'plain'+parseTabSheet(text) // → { lines: [Line], meta: { title?, artist?, key?, capo? }, errors: [] }+// Line = { type: 'section'|'chords'|'lyric'|'tabstaff'|'chordlyric'|'blank'|'text', text, chords?: [{ name, col }] }+// 'section' — [Verse 1], [Chorus], {start_of_chorus} etc.+// 'chords' — a line that is ≥~80% chord tokens/whitespace (C, Am7, F#m7b5, G/B, N.C.)+// 'tabstaff' — monospace tab staff lines (e|--3--2--| ; also B/G/D/A/E-prefixed)+// 'chordlyric'— ChordPro inline [C]lyric syntax, chords carry col offsets into the bare lyric+normalizePastedTab(text) // strip HTML remnants/entities, normalize \r\n, collapse 3+ blank lines, detab+transposeChordName(name, n) // 'Am7' + 2 → 'Bm7'; handles slash chords, prefers keys' natural spelling+transposeText(text, n) // transpose every chord token in chords/chordlyric lines, preserving column alignment where possible+CHORD_TOKEN_RE // exported for reuse/tests+```++Forgiving parser: never throws; unknown lines classify as `'text'`; errors collect+into `errors[]`. Barrel + README row + colocated tests (lib tests also run in node+env in CI — `vi.stubGlobal` any browser API).++## Client pages & wiring++- `client/src/services/apiSongbook.js` (template: `apiRounds.js`; trailing+ `options` param on every helper) + `export * from './apiSongbook.js'` in+ `api.js` + README row.+- `client/src/pages/SongBook.jsx` — index at `/songbook`. Card grid+ (Rounds.jsx template), filters in URL search params (`?stage=&instrument=&tag=&q=`,+ Catalog.jsx template), stage chips with a `SONG_STAGE_COLORS` map (constants in+ `client/src/components/songbook/constants.js`), quick stage-flip on cards+ (PATCH + reactive local-state update), New Song / Import buttons,+ EmptyState when empty, useConfirmDelete + ConfirmButtonPair for delete.+ NOT in `isFullWidth`.+- `client/src/pages/SongBookViewer.jsx` — `/songbook/:id`, full-bleed+ (RoundEditor template: `flex flex-col h-full`, shrink-0 header, `flex-1+ overflow-y-auto` body it owns). Modes via search params: `?mode=edit` (editor+ textarea `font-mono` + live preview) vs default play view.+ - **Play view**: rendered sheet from `parseTabSheet` — section headers styled,+ chord tokens highlighted (`text-port-accent font-semibold`), tab staffs in a+ per-block `overflow-x-auto` `font-mono` container, ChordPro chord-over-lyric+ rendering. Controls bar: play/pause autoscroll, speed slider, transpose ±+ (renders `transposeText` result, never mutates stored text; persists+ `transpose` offset per song via safeStorage), font size ±, stage select,+ capo/key/tuning badges, attachment list (opens/serves via API; "not on this+ machine" state), sourceUrl link.+ - **Autoscroll** (`client/src/components/songbook/useAutoscroll.js` or hook in+ hooks/ with barrel+README): rAF loop advancing `container.scrollTop` at px/s;+ only meaningful when content overflows. Speed slider maps to px/s; if+ `scrollDurationSec` set, a "fit to duration" preset computes px/s from+ scrollHeight. Pauses at bottom; user wheel/touch drag pauses autoscroll+ (resume button). Keyboard via `useKeyboardShortcuts`: space = play/pause,+ `+/-` = speed, `[`/`]` = transpose, `0` = top. New `useWakeLock` hook+ (navigator.wakeLock, released on unmount/visibility loss) keeps the screen on+ while scrolling — check `client/eslint.config.js` browserGlobals if lint+ complains.+ - Not-found fallback for stale ids; delete navigates back to `/songbook`.+- **Import flow** — `/songbook/import` (also full-bleed exempt? keep it simple:+ padded page, NOT in isFullWidth — use the trailing-slash regex carefully:+ `startsWith('/songbook/')` would catch `/songbook/import`, so viewer full-bleed+ must exempt import, e.g. regex like the apps pattern, or make import a mode of+ the index page at `/songbook?import=1`… **Decision: import lives at+ `/songbook/import`, and the isFullWidth check is+ `/^\/songbook\/(?!import$)[^/]+/.test(pathname)`**, mirroring the apps-create+ exclusion at Layout.jsx:1208). Two tabs (TabPills): Paste (textarea ++ readClipboard Paste button + live `detectFormat`/`normalizePastedTab` preview)+ and From URL (input validated with `isUrl`, plain POST via useAsyncAction).+ Both produce a draft → editable title/artist/instrument/tags/stage form →+ Save → POST → navigate to `/songbook/:id`.+- Routing (`App.jsx`): `songbook`, `songbook/import`, `songbook/:id` — all+ `lazyWithReload`.+- Sidebar (`Layout.jsx`): Brain section child `{ to: '/songbook', label: 'SongBook' }`+ alphabetical (between Rapid Reader and Timeline), distinct lucide icon+ (e.g. `BookAudio` or `ListMusic` — Music/Mic taken).+- Nav manifest (`server/lib/navManifest.js`):+ `{ id: 'nav.brain.songbook', path: '/songbook', label: 'SongBook', section: 'Brain',+ aliases: ['songbook', 'song-book', 'tabs', 'chords', 'guitar-tabs'],+ keywords: ['guitar', 'tab', 'tablature', 'chord chart', 'lyrics', 'sheet music', 'repertoire', 'autoscroll'] }`+ — avoid `songs`/`song` (already aliased to nav.create.rounds; first-declared wins).++## Tests++- Server: `brainSongbook` route tests (crib brain route tests — CRUD, stage patch,+ attachment strip on PUT, 404s), `brainSongbookImport.test.js` (UG js-store+ fixture — INVENTED fixture data, never a real scrape dump; `<pre>` fallback;+ entity decoding; title/artist fallback), brainStorage enrollment sanity+ (songs type appears in getSummary / sync log round-trip if cheap).+- Client: `tabNotation.test.js` (chord-line detection incl. false positives like+ the lyric "A Boy Named Sue" line starting with A; tab staff detection; ChordPro;+ transpose incl. slash chords and column preservation; normalize). Component+ tests: SongBook index (api-barrel mock, RoundEditor.test.jsx harness style),+ viewer render + stage flip.+- Run: `cd server && npm test`, `cd client && npm test` (worktree symlinks+ node_modules from the primary checkout).++## Privacy++No real song data, hostnames, or live-instance records in fixtures/docs/commits —+invent fixture tabs (e.g. "Example Song" by "The Placeholders").++## Explicitly deferred (PLAN.md items if not done)++- Practice/spaced-rep integration (`songProgress.js` / SM-2 in meatspacePostMemory) —+ stage field is manual v1.+- Linking a song to existing Rounds/Tracks/MIDI records (cross-links field).+- 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.diff --git a/server/lib/brainValidation.js b/server/lib/brainValidation.jsindex 0a3648bbb7..ea61f08d99 100644--- a/server/lib/brainValidation.js+++ b/server/lib/brainValidation.js@@ -548,3 +548,73 @@ export const brainDigestRunSchema = z.object({providerOverride: z.string().optional(),modelOverride: z.string().optional()});++// =============================================================================+// SONGBOOK SCHEMAS (Brain entity type `songs` — guitar tabs / chord sheets)+// =============================================================================++// Learning stage for a repertoire song+export const songStageEnum = z.enum(['new', 'learning', 'learned', 'memorized']);++// Instrument the sheet is written for+export const songInstrumentEnum = z.enum(['guitar', 'piano', 'ukulele', 'bass', 'voice', 'other']);++// 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+export const songInputSchema = z.object({+ title: z.string().trim().min(1).max(300),+ artist: z.string().trim().max(300).optional().default(''),+ instrument: songInstrumentEnum.optional().default('guitar'),+ stage: songStageEnum.optional().default('new'),+ tags: z.array(z.string().trim().min(1).max(50)).max(50).optional().default([]),+ key: z.string().trim().max(20).optional().default(''),+ capo: z.number().int().min(0).max(12).optional().default(0),+ tuning: z.string().trim().max(40).optional().default(''),+ sourceUrl: z.string().trim().max(2000).optional().default(''),+ content: 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/url+export const songImportUrlSchema = z.object({+ url: z.string().url().max(2000)+});++// POST /api/brain/songbook/:id/attachments — base64 upload body+export const songAttachmentUploadSchema = z.object({+ filename: z.string().min(1).max(300),+ data: z.string().min(1),+ label: z.string().max(300).optional().default('')+});diff --git a/server/lib/fileUtils.js b/server/lib/fileUtils.jsindex 47da1be593..9552e9c538 100644--- a/server/lib/fileUtils.js+++ b/server/lib/fileUtils.js@@ -129,6 +129,10 @@ export const PATHS = {// archive JSON lives one level up (data/brain/imports/<source>/) and is NOT// served — only this assets subtree is.brainImportAssets: join(INSTALL_ROOT, 'data/brain/imports/assets'),+ // SongBook attachment BYTES (PDF sheet music, images, MIDI). Machine-local —+ // only the metadata syncs inside the brain `songs` record; peers lacking a+ // file render "not on this machine". Covered by backup via data/brain/.+ brainSongbook: join(INSTALL_ROOT, 'data/brain/songbook'),slashdo: join(CODE_ROOT, 'lib/slashdo')};@@ -799,6 +803,8 @@ export const EXTENSION_MIME_MAP = {'.wav': 'audio/wav','.ogg': 'audio/ogg','.m4a': 'audio/mp4',+ '.mid': 'audio/midi',+ '.midi': 'audio/midi',// Video'.mp4': 'video/mp4','.webm': 'video/webm',diff --git a/server/lib/navManifest.js b/server/lib/navManifest.jsindex f17ada4b59..259f0c01bd 100644--- a/server/lib/navManifest.js+++ b/server/lib/navManifest.js@@ -67,6 +67,8 @@ export const NAV_COMMANDS = [{ id: 'nav.brain.memory', path: '/brain/memory', label: 'Memory', section: 'Brain', aliases: ['brain-memory', 'memory'] },{ id: 'nav.brain.notes', path: '/brain/notes', label: 'Notes', section: 'Brain', aliases: ['brain-notes', 'notes'] },{ id: 'nav.rapid-reader', path: '/rapid-reader', label: 'Rapid Reader', section: 'Brain', aliases: ['rapid-reader', 'speed-reader', 'rsvp', 'spritz'], keywords: ['speed reading', 'rapid reading', 'rsvp', 'spritz', 'word per minute', 'wpm', 'focal'] },+ // No 'songs'/'song' aliases — those already resolve to nav.create.rounds (first-declared wins).+ { id: 'nav.brain.songbook', path: '/songbook', label: 'SongBook', section: 'Brain', aliases: ['songbook', 'song-book', 'tabs', 'chords', 'guitar-tabs'], keywords: ['guitar', 'tab', 'tablature', 'chord chart', 'lyrics', 'sheet music', 'repertoire', 'autoscroll'] },{ id: 'nav.brain.trust', path: '/brain/trust', label: 'Trust', section: 'Brain', aliases: ['brain-trust'] },{ id: 'nav.calendar.agenda', path: '/calendar/agenda', label: 'Agenda', section: 'Calendar', aliases: ['calendar', 'agenda'] },diff --git a/server/routes/brain.js b/server/routes/brain.jsindex 92e0d28f39..d6b364e87b 100644--- a/server/routes/brain.js+++ b/server/routes/brain.js@@ -15,6 +15,7 @@ import linkRoutes from './brainLinks.js';import graphRoutes from './brainGraph.js';import syncRoutes from './brainSync.js';import dailyLogRoutes from './brainDailyLog.js';+import songbookRoutes from './brainSongbook.js';const router = Router();@@ -26,5 +27,6 @@ router.use(linkRoutes);router.use(graphRoutes);router.use(syncRoutes);router.use(dailyLogRoutes);+router.use('/songbook', songbookRoutes);export default router;diff --git a/server/routes/brainSongbook.js b/server/routes/brainSongbook.jsnew file mode 100644index 0000000000..6a73c05e16--- /dev/null+++ b/server/routes/brainSongbook.js@@ -0,0 +1,237 @@+/**+ * Brain SongBook Routes+ *+ * Repertoire tracker (guitar tabs / chord sheets / sheet music) stored as the+ * Brain entity type `songs` — all writes go through brainStorage's generic API+ * so records ride the sync-log / LWW / tombstone federation pipeline.+ *+ * Mounted from the brain barrel at /songbook → /api/brain/songbook/...+ *+ * Attachments: METADATA lives in the synced record (identical on all peers);+ * BYTES are machine-local under data/brain/songbook/ (<uuid8>-<sanitized-name>).+ * The list endpoint reports `present: boolean` per attachment so peers lacking+ * the file can render "not on this machine".+ */++import { Router } from 'express';+import { writeFile, 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,+} from '../lib/fileUtils.js';++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);+ if (!song) {+ throw new ServerError('Song not found', { status: 404, code: 'NOT_FOUND' });+ }+ return song;+}++// 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) {+ const safeFilename = sanitizeFilename(rawFilename);+ const filepath = resolve(songbookDir(), safeFilename);+ if (!isPathInsideDir(songbookDir(), filepath)) {+ throw new ServerError('Invalid filename', { status: 400, code: 'INVALID_FILENAME' });+ }+ const meta = (Array.isArray(song.attachments) ? song.attachments : [])+ .find((a) => a.filename === safeFilename);+ if (!meta) {+ throw new ServerError('Attachment not found', { status: 404, code: 'NOT_FOUND' });+ }+ return { meta, safeFilename, filepath };+}++// =============================================================================+// IMPORT (before /:id routes so 'import' is never treated as an id)+// =============================================================================++// POST /import/url — fetch + extract a draft; nothing is stored.+router.post('/import/url', asyncHandler(async (req, res) => {+ const { url } = validateRequest(songImportUrlSchema, req.body);+ const draft = await importSongFromUrl(url);+ res.json({ draft });+}));++// =============================================================================+// SONG CRUD+// =============================================================================++router.get('/', asyncHandler(async (req, res) => {+ const songs = await brainStorage.getAll('songs');+ res.json({ songs });+}));++router.get('/:id', asyncHandler(async (req, res) => {+ const song = await getSongOr404(req.params.id);+ res.json(song);+}));++router.post('/', asyncHandler(async (req, res) => {+ const data = validateRequest(songInputSchema, req.body);+ // `attachments` is server-managed — always born empty, mutated only by the+ // attachment endpoints below.+ const song = await brainStorage.create('songs', { ...data, attachments: [] });+ res.status(201).json(song);+}));++router.put('/:id', asyncHandler(async (req, res) => {+ // partialWithoutDefaults (not .partial()) so an omitted field is genuinely+ // absent instead of resetting to its default (see zodCompat.js). The schema+ // 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' });+ }+ res.json(song);+}));++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' });+ }+ res.json({ id: req.params.id });+}));++// =============================================================================+// ATTACHMENTS+// =============================================================================++// POST /:id/attachments — base64 upload; writes bytes + appends meta to record+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 attachment = {+ filename: fname,+ label,+ mime: getMimeType(getFileExtension(fname)),+ size: buffer.length,+ sha256: createHash('sha256').update(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)`);+ res.status(201).json({ attachment });+}));++// GET /:id/attachments — synced meta + machine-local presence+router.get('/:id/attachments', asyncHandler(async (req, res) => {+ const song = await getSongOr404(req.params.id);+ const metas = Array.isArray(song.attachments) ? song.attachments : [];+ const attachments = await Promise.all(metas.map(async (meta) => ({+ ...meta,+ present: await pathExists(join(songbookDir(), meta.filename)),+ })));+ res.json(attachments);+}));++// GET /:id/attachments/:filename — serve the local bytes+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);+}));++// DELETE /:id/attachments/:filename — remove meta from record + local bytes+router.delete('/:id/attachments/:filename', asyncHandler(async (req, res) => {+ const song = await getSongOr404(req.params.id);+ const { safeFilename, filepath } = resolveAttachment(song, req.params.filename);++ const updated = await brainStorage.update('songs', song.id, {+ attachments: song.attachments.filter((a) => a.filename !== safeFilename),+ });++ // Bytes may legitimately be absent on this machine (meta synced from a peer).+ if (await pathExists(filepath)) {+ await unlink(filepath);+ }++ console.log(`🗑️ Song attachment deleted: ${safeFilename}`);+ res.json({ success: true, filename: safeFilename, attachments: updated.attachments });+}));++export default router;diff --git a/server/routes/brainSongbook.test.js b/server/routes/brainSongbook.test.jsnew file mode 100644index 0000000000..5fe20557dd--- /dev/null+++ b/server/routes/brainSongbook.test.js@@ -0,0 +1,397 @@+import { describe, it, expect, vi, beforeEach, afterAll } from 'vitest';+import express from 'express';+import { mkdtempSync, rmSync, existsSync, writeFileSync, mkdirSync, readFileSync } from 'fs';+import { tmpdir } from 'os';+import { join } from 'path';+import { createHash } from 'crypto';+import { request } from '../lib/testHelper.js';+import { errorMiddleware } from '../lib/errorHandler.js';+import { makePathsProxy } from '../lib/mockPathsDataRoot.js';++// Redirect the attachment bytes directory at a per-suite temp dir. `var` ++// function declaration are hoisted (no TDZ) so the hoisted vi.mock factory can+// call getTempRoot() safely.+var tempRoot; // eslint-disable-line no-var+function getTempRoot() {+ if (!tempRoot) tempRoot = mkdtempSync(join(tmpdir(), 'songbook-route-test-'));+ return tempRoot;+}+const songbookDir = () => join(getTempRoot(), 'brain', 'songbook');++vi.mock('../lib/fileUtils.js', async () => {+ const actual = await vi.importActual('../lib/fileUtils.js');+ return makePathsProxy(actual, {+ dataRoot: () => getTempRoot(),+ extraOverrides: (root) => ({ brainSongbook: join(root, 'brain', 'songbook') }),+ });+});++vi.mock('../services/brainStorage.js', () => ({+ getAll: vi.fn(),+ getById: vi.fn(),+ create: vi.fn(),+ update: vi.fn(),+ remove: vi.fn(),+}));++vi.mock('../services/brainSongbookImport.js', () => ({+ importSongFromUrl: vi.fn(),+}));++import * as brainStorage from '../services/brainStorage.js';+import { importSongFromUrl } from '../services/brainSongbookImport.js';+import songbookRoutes from './brainSongbook.js';++afterAll(() => { if (tempRoot) rmSync(tempRoot, { recursive: true, force: true }); });++const SONG_ID = '11111111-1111-4111-8111-111111111111';++const buildApp = () => {+ const app = express();+ app.use(express.json({ limit: '55mb' }));+ app.use('/api/brain/songbook', songbookRoutes);+ app.use(errorMiddleware);+ return app;+};++const baseSong = (overrides = {}) => ({+ id: SONG_ID,+ title: 'Example Song',+ artist: 'The Placeholders',+ instrument: 'guitar',+ stage: 'new',+ tags: [],+ key: '',+ capo: 0,+ tuning: '',+ sourceUrl: '',+ content: { format: 'tab', text: 'e|--0--|' },+ scrollDurationSec: null,+ notes: '',+ attachments: [],+ createdAt: '2026-07-01T00:00:00.000Z',+ updatedAt: '2026-07-01T00:00:00.000Z',+ ...overrides,+});++describe('Brain SongBook routes', () => {+ let app;++ beforeEach(() => {+ vi.clearAllMocks();+ app = buildApp();+ });++ // ===========================================================================+ // CRUD+ // ===========================================================================++ describe('GET /api/brain/songbook', () => {+ it('returns { songs } from the entity store', async () => {+ brainStorage.getAll.mockResolvedValue([baseSong()]);+ const res = await request(app).get('/api/brain/songbook');+ expect(res.status).toBe(200);+ expect(res.body.songs).toHaveLength(1);+ expect(brainStorage.getAll).toHaveBeenCalledWith('songs');+ });+ });++ describe('GET /api/brain/songbook/:id', () => {+ it('returns the song', async () => {+ brainStorage.getById.mockResolvedValue(baseSong());+ const res = await request(app).get(`/api/brain/songbook/${SONG_ID}`);+ expect(res.status).toBe(200);+ expect(res.body.title).toBe('Example Song');+ expect(brainStorage.getById).toHaveBeenCalledWith('songs', SONG_ID);+ });++ it('404s for an unknown id', async () => {+ brainStorage.getById.mockResolvedValue(null);+ const res = await request(app).get('/api/brain/songbook/nope');+ expect(res.status).toBe(404);+ });+ });++ describe('POST /api/brain/songbook', () => {+ it('creates with schema defaults applied and attachments born empty', async () => {+ brainStorage.create.mockImplementation(async (type, data) => ({ id: SONG_ID, ...data }));+ const res = await request(app)+ .post('/api/brain/songbook')+ .send({ title: 'Example Song' });+ expect(res.status).toBe(201);+ expect(brainStorage.create).toHaveBeenCalledWith('songs', expect.objectContaining({+ title: 'Example Song',+ artist: '',+ instrument: 'guitar',+ stage: 'new',+ capo: 0,+ content: { format: 'tab', text: '' },+ scrollDurationSec: null,+ attachments: [],+ }));+ });++ it('ignores client-supplied attachments on create', async () => {+ brainStorage.create.mockImplementation(async (type, data) => ({ id: SONG_ID, ...data }));+ await request(app)+ .post('/api/brain/songbook')+ .send({ title: 'X', attachments: [{ filename: 'evil.txt' }] });+ expect(brainStorage.create).toHaveBeenCalledWith('songs',+ expect.objectContaining({ attachments: [] }));+ });++ it('400s when title is missing', async () => {+ const res = await request(app).post('/api/brain/songbook').send({ artist: 'X' });+ expect(res.status).toBe(400);+ expect(brainStorage.create).not.toHaveBeenCalled();+ });++ it('400s on an invalid stage', async () => {+ const res = await request(app)+ .post('/api/brain/songbook')+ .send({ title: 'X', stage: 'mastered' });+ expect(res.status).toBe(400);+ });+ });++ describe('PUT /api/brain/songbook/:id', () => {+ it('updates only the sent fields (no default injection)', 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);+ // Exactly the sent field — an omitted title/capo/etc. must not reset to defaults.+ expect(brainStorage.update).toHaveBeenCalledWith('songs', SONG_ID, { stage: 'learning' });+ });++ it('strips client-supplied attachments', async () => {+ brainStorage.update.mockResolvedValue(baseSong());+ await request(app)+ .put(`/api/brain/songbook/${SONG_ID}`)+ .send({ title: 'New Title', attachments: [{ filename: 'forged.pdf', mime: 'application/pdf', size: 1, sha256: 'x'.repeat(64) }] });+ expect(brainStorage.update).toHaveBeenCalledWith('songs', SONG_ID, { title: 'New Title' });+ });++ it('404s when the song is missing', async () => {+ brainStorage.update.mockResolvedValue(null);+ const res = await request(app)+ .put(`/api/brain/songbook/${SONG_ID}`)+ .send({ title: 'X' });+ expect(res.status).toBe(404);+ });+ });++ 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);+ const res = await request(app).delete(`/api/brain/songbook/${SONG_ID}`);+ expect(res.status).toBe(200);+ expect(res.body).toEqual({ id: SONG_ID });+ expect(brainStorage.remove).toHaveBeenCalledWith('songs', SONG_ID);+ });++ it('404s when already gone', async () => {+ brainStorage.remove.mockResolvedValue(false);+ const res = await request(app).delete(`/api/brain/songbook/${SONG_ID}`);+ expect(res.status).toBe(404);+ });+ });++ // ===========================================================================+ // IMPORT+ // ===========================================================================++ describe('POST /api/brain/songbook/import/url', () => {+ it('returns the extracted draft', async () => {+ const draft = {+ title: 'Example Song',+ artist: 'The Placeholders',+ content: { format: 'tab', text: 'e|--0--|' },+ sourceUrl: 'https://www.example.com/tab/1',+ };+ importSongFromUrl.mockResolvedValue(draft);+ const res = await request(app)+ .post('/api/brain/songbook/import/url')+ .send({ url: 'https://www.example.com/tab/1' });+ expect(res.status).toBe(200);+ expect(res.body.draft).toEqual(draft);+ expect(importSongFromUrl).toHaveBeenCalledWith('https://www.example.com/tab/1');+ });++ it('400s on a non-URL', async () => {+ const res = await request(app)+ .post('/api/brain/songbook/import/url')+ .send({ url: 'not a url' });+ expect(res.status).toBe(400);+ expect(importSongFromUrl).not.toHaveBeenCalled();+ });+ });++ // ===========================================================================+ // ATTACHMENTS+ // ===========================================================================++ describe('POST /api/brain/songbook/:id/attachments', () => {+ it('writes bytes, hashes them, and appends meta to the record', async () => {+ const song = baseSong();+ brainStorage.getById.mockResolvedValue(song);+ brainStorage.update.mockImplementation(async (type, id, fields) => ({ ...song, ...fields }));++ const payload = Buffer.from('invented sheet music');+ const res = await request(app)+ .post(`/api/brain/songbook/${SONG_ID}/attachments`)+ .send({ filename: 'sheet.txt', data: payload.toString('base64'), label: 'Lead sheet' });++ expect(res.status).toBe(201);+ const { attachment } = res.body;+ expect(attachment.filename).toMatch(/^[0-9a-f]{8}-sheet\.txt$/);+ expect(attachment.label).toBe('Lead sheet');+ expect(attachment.mime).toBe('text/plain');+ expect(attachment.size).toBe(payload.length);+ expect(attachment.sha256).toBe(createHash('sha256').update(payload).digest('hex'));++ // Bytes landed in the machine-local songbook dir+ const filepath = join(songbookDir(), attachment.filename);+ expect(existsSync(filepath)).toBe(true);+ expect(readFileSync(filepath, 'utf-8')).toBe('invented sheet music');++ // Meta appended via the entity store (federates with the record)+ expect(brainStorage.update).toHaveBeenCalledWith('songs', SONG_ID, {+ attachments: [attachment],+ });+ });++ it('accepts MIDI files (songbook-specific allowlist extension)', async () => {+ brainStorage.getById.mockResolvedValue(baseSong());+ brainStorage.update.mockImplementation(async (type, id, fields) => ({ ...baseSong(), ...fields }));+ const res = await request(app)+ .post(`/api/brain/songbook/${SONG_ID}/attachments`)+ .send({ filename: 'melody.mid', data: Buffer.from('MThd').toString('base64') });+ expect(res.status).toBe(201);+ expect(res.body.attachment.mime).toBe('audio/midi');+ });++ it('rejects disallowed extensions', async () => {+ brainStorage.getById.mockResolvedValue(baseSong());+ const res = await request(app)+ .post(`/api/brain/songbook/${SONG_ID}/attachments`)+ .send({ filename: 'app.exe', data: Buffer.from('nope').toString('base64') });+ expect(res.status).toBe(400);+ expect(brainStorage.update).not.toHaveBeenCalled();+ });++ it('404s when the song is missing', async () => {+ brainStorage.getById.mockResolvedValue(null);+ const res = await request(app)+ .post(`/api/brain/songbook/${SONG_ID}/attachments`)+ .send({ filename: 'sheet.txt', data: Buffer.from('x').toString('base64') });+ expect(res.status).toBe(404);+ });+ });++ describe('GET /api/brain/songbook/:id/attachments', () => {+ it('reports present:true only for bytes that exist locally', async () => {+ mkdirSync(songbookDir(), { recursive: true });+ writeFileSync(join(songbookDir(), 'aaaaaaaa-here.txt'), 'local bytes');+ const song = baseSong({+ attachments: [+ { filename: 'aaaaaaaa-here.txt', label: '', mime: 'text/plain', size: 11, sha256: 'a'.repeat(64) },+ { filename: 'bbbbbbbb-elsewhere.pdf', label: '', mime: 'application/pdf', size: 5, sha256: 'b'.repeat(64) },+ ],+ });+ brainStorage.getById.mockResolvedValue(song);++ const res = await request(app).get(`/api/brain/songbook/${SONG_ID}/attachments`);+ expect(res.status).toBe(200);+ expect(res.body).toHaveLength(2);+ expect(res.body[0]).toMatchObject({ filename: 'aaaaaaaa-here.txt', present: true });+ expect(res.body[1]).toMatchObject({ filename: 'bbbbbbbb-elsewhere.pdf', present: false });+ });+ });++ describe('GET /api/brain/songbook/:id/attachments/:filename', () => {+ it('serves local bytes with nosniff', async () => {+ mkdirSync(songbookDir(), { recursive: true });+ writeFileSync(join(songbookDir(), 'cccccccc-serve.txt'), 'serve me');+ brainStorage.getById.mockResolvedValue(baseSong({+ attachments: [{ filename: 'cccccccc-serve.txt', label: '', mime: 'text/plain', size: 8, sha256: 'c'.repeat(64) }],+ }));++ const res = await request(app).get(`/api/brain/songbook/${SONG_ID}/attachments/cccccccc-serve.txt`);+ expect(res.status).toBe(200);+ expect(res.headers['x-content-type-options']).toBe('nosniff');+ expect(res.text).toBe('serve me');+ });++ it('404s for a filename not on the record (even if a file exists)', async () => {+ mkdirSync(songbookDir(), { recursive: true });+ writeFileSync(join(songbookDir(), 'dddddddd-orphan.txt'), 'orphan');+ brainStorage.getById.mockResolvedValue(baseSong({ attachments: [] }));+ const res = await request(app).get(`/api/brain/songbook/${SONG_ID}/attachments/dddddddd-orphan.txt`);+ expect(res.status).toBe(404);+ });++ it('404s with NOT_ON_THIS_MACHINE when meta is synced but bytes are absent', async () => {+ brainStorage.getById.mockResolvedValue(baseSong({+ attachments: [{ filename: 'eeeeeeee-remote.pdf', label: '', mime: 'application/pdf', size: 5, sha256: 'e'.repeat(64) }],+ }));+ const res = await request(app).get(`/api/brain/songbook/${SONG_ID}/attachments/eeeeeeee-remote.pdf`);+ expect(res.status).toBe(404);+ expect(JSON.stringify(res.body)).toContain('NOT_ON_THIS_MACHINE');+ });+ });++ describe('DELETE /api/brain/songbook/:id/attachments/:filename', () => {+ it('removes the meta from the record and deletes local bytes', async () => {+ mkdirSync(songbookDir(), { recursive: true });+ const filepath = join(songbookDir(), 'ffffffff-gone.txt');+ writeFileSync(filepath, 'delete me');+ const meta = { filename: 'ffffffff-gone.txt', label: '', mime: 'text/plain', size: 9, sha256: 'f'.repeat(64) };+ const song = baseSong({ attachments: [meta] });+ brainStorage.getById.mockResolvedValue(song);+ brainStorage.update.mockImplementation(async (type, id, fields) => ({ ...song, ...fields }));++ const res = await request(app).delete(`/api/brain/songbook/${SONG_ID}/attachments/ffffffff-gone.txt`);+ expect(res.status).toBe(200);+ expect(res.body).toMatchObject({ success: true, filename: 'ffffffff-gone.txt', attachments: [] });+ expect(brainStorage.update).toHaveBeenCalledWith('songs', SONG_ID, { attachments: [] });+ expect(existsSync(filepath)).toBe(false);+ });++ it('404s for a meta not on the record', async () => {+ brainStorage.getById.mockResolvedValue(baseSong({ attachments: [] }));+ const res = await request(app).delete(`/api/brain/songbook/${SONG_ID}/attachments/nope.txt`);+ expect(res.status).toBe(404);+ expect(brainStorage.update).not.toHaveBeenCalled();+ });+ });+});diff --git a/server/services/brainSongbookImport.js b/server/services/brainSongbookImport.jsnew file mode 100644index 0000000000..8100f6c0ad--- /dev/null+++ b/server/services/brainSongbookImport.js@@ -0,0 +1,200 @@+/**+ * SongBook URL Import Service+ *+ * Fetches a user-supplied URL (SSRF-guarded via safeUrlFetch) and extracts a+ * song DRAFT — { title, artist, content: { format, text }, sourceUrl } — for+ * the client's review/edit screen. Nothing is stored here; the user saves the+ * draft explicitly via POST /api/brain/songbook.+ *+ * Extractors, first match wins:+ * 1. Ultimate Guitar js-store JSON (defensive — any shape drift falls through)+ * 2. Largest <pre> block in the page (tab sites overwhelmingly use <pre>)+ * 3. Strip-tags plain-text fallback (always yields something on a real page)+ *+ * All extraction functions are pure and exported for testing.+ */++import { fetchPublicText } from '../lib/safeUrlFetch.js';+import { safeJSONParse } from '../lib/fileUtils.js';+import { ServerError } from '../lib/errorHandler.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, '&');+}++/**+ * Strip Ultimate-Guitar chord/tab markers ([ch]C[/ch], [tab]...[/tab]) from+ * wiki_tab content, leaving the plain monospace sheet.+ */+export function stripUgMarkers(text) {+ if (typeof text !== 'string') return '';+ return text.replace(/\[\/?(?:ch|tab)\]/gi, '');+}++// Normalize line endings and trim outer blank space; collapse 3+ blank lines.+const normalizeSheetText = (text) =>+ text.replace(/\r\n?/g, '\n').replace(/\n{3,}/g, '\n\n').trim();++/**+ * Ultimate Guitar extractor. UG pages embed their whole page state as+ * HTML-entity-encoded JSON in <div class="js-store" data-content="...">.+ * The tab text lives at page.data.tab_view.wiki_tab.content and the song/artist+ * names at page.data.tab.{song_name,artist_name}. Everything is optional-chained+ * so ANY shape drift returns null and the caller falls through to the next+ * extractor. Returns { text, title, artist } or null.+ */+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);+ // 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;+ if (typeof content !== 'string' || !content.trim()) return null;+ return {+ text: normalizeSheetText(stripUgMarkers(content)),+ title: typeof data?.tab?.song_name === 'string' ? data.tab.song_name.trim() : '',+ artist: typeof data?.tab?.artist_name === 'string' ? data.tab.artist_name.trim() : '',+ };+}++// A <pre> shorter than this is navigation/code chrome, not a song sheet —+// fall through to the plain-text extractor instead of returning a stub.+const MIN_PRE_CHARS = 20;++/**+ * Generic tab-site extractor: the largest <pre> block in the page (regex, no+ * DOM library), inner tags stripped, entities decoded. Returns string or null.+ */+export function extractLargestPre(html) {+ if (typeof html !== 'string') return null;+ let largest = '';+ const re = /<pre\b[^>]*>([\s\S]*?)<\/pre>/gi;+ 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, '')));+ 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+ .replace(/\s*\((?:ver\.?|version)\s*\d*\)\s*$/i, '')+ .replace(/\s+(?:chords|tabs?|guitar tabs?|bass tabs?|ukulele)$/i, '')+ .trim();+ return cleaned || s.trim();+};++/**+ * Title/artist fallback from the page <title>: strips site suffixes after+ * '|' / '@', then tries "X by Y" and "X - Y" patterns. Returns+ * { title, artist } with '' for anything unresolvable.+ */+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();+ if (!raw) return { title: '', artist: '' };+ const by = /^(.+?)\s+by\s+(.+)$/i.exec(raw);+ if (by) return { title: cleanTitlePart(by[1]), artist: by[2].trim() };+ const dash = /^(.+?)\s+[-–—]\s+(.+)$/.exec(raw);+ if (dash) return { title: cleanTitlePart(dash[1]), artist: dash[2].trim() };+ return { title: cleanTitlePart(raw), artist: '' };+}++/**+ * Pure orchestration: run the extractor cascade over fetched HTML and build+ * the draft. Exported for testing without network mocks.+ */+export function buildDraftFromHtml(html, url) {+ const fallback = parseTitleArtist(html);++ const ug = extractUltimateGuitarStore(html);+ if (ug) {+ return {+ title: ug.title || fallback.title,+ artist: ug.artist || fallback.artist,+ content: { format: 'tab', text: ug.text.slice(0, MAX_CONTENT_CHARS) },+ sourceUrl: url,+ };+ }++ const pre = extractLargestPre(html);+ if (pre) {+ return {+ title: fallback.title,+ artist: fallback.artist,+ content: { format: 'tab', text: pre.slice(0, MAX_CONTENT_CHARS) },+ sourceUrl: url,+ };+ }++ return {+ title: fallback.title,+ artist: fallback.artist,+ content: { format: 'plain', text: stripHtmlToText(html).slice(0, MAX_CONTENT_CHARS) },+ sourceUrl: url,+ };+}++/**+ * Fetch a URL and extract a song draft. Throws ServerError on unsafe URLs+ * (400, via safeUrlFetch), fetch failures (502), or content-free pages (422).+ */+export async function importSongFromUrl(url) {+ const html = await fetchPublicText(url, {+ timeoutMs: 20000,+ headers: { 'User-Agent': 'Mozilla/5.0 (compatible; PortOS-SongBook/1.0)' },+ });+ if (html === null) {+ throw new ServerError('Could not fetch that URL (network error, non-2xx response, or blocked redirect)', {+ status: 502,+ code: 'SONG_IMPORT_FETCH_FAILED',+ });+ }+ const draft = buildDraftFromHtml(html, url);+ if (!draft.content.text) {+ throw new ServerError('No song content found at that URL', {+ status: 422,+ code: 'SONG_IMPORT_EMPTY',+ });+ }+ console.log(`🎸 SongBook import: ${draft.content.format} draft (${draft.content.text.length} chars) from ${new URL(url).hostname}`);+ return draft;+}diff --git a/server/services/brainSongbookImport.test.js b/server/services/brainSongbookImport.test.jsnew file mode 100644index 0000000000..be2425fc46--- /dev/null+++ b/server/services/brainSongbookImport.test.js@@ -0,0 +1,221 @@+/**+ * SongBook import extractor tests.+ *+ * All fixtures are INVENTED ("Example Song" by "The Placeholders") — never+ * real scraped page content, and no real URLs beyond example.com.+ */+import { describe, it, expect, vi, beforeEach } from 'vitest';++vi.mock('../lib/safeUrlFetch.js', () => ({+ fetchPublicText: vi.fn(),+}));++import { fetchPublicText } from '../lib/safeUrlFetch.js';+import {+ decodeHtmlEntities,+ stripUgMarkers,+ extractUltimateGuitarStore,+ extractLargestPre,+ stripHtmlToText,+ parseTitleArtist,+ buildDraftFromHtml,+ importSongFromUrl,+} from './brainSongbookImport.js';++// Build an invented UG-shaped page: js-store div with entity-encoded JSON.+const encodeAttr = (s) => s.replace(/&/g, '&').replace(/"/g, '"').replace(/</g, '<').replace(/>/g, '>');++const UG_CONTENT = '[tab][ch]C[/ch] [ch]G[/ch]\nExample lyric line one[/tab]\n[tab][ch]Am[/ch] [ch]F[/ch]\nExample lyric line two[/tab]';++const buildUgHtml = (storeJson, title = 'EXAMPLE SONG CHORDS by The Placeholders @ Ultimate-Guitar.Com') =>+ `<html><head><title>${title}</title></head><body>` ++ `<div class="js-store" data-content="${encodeAttr(JSON.stringify(storeJson))}"></div>` ++ '</body></html>';++const UG_STORE = {+ store: {+ page: {+ data: {+ tab: { song_name: 'Example Song', artist_name: 'The Placeholders' },+ tab_view: { wiki_tab: { content: UG_CONTENT } },+ },+ },+ },+};++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');+ });+});++describe('extractUltimateGuitarStore', () => {+ it('extracts content + song/artist names from the js-store JSON', () => {+ const result = extractUltimateGuitarStore(buildUgHtml(UG_STORE));+ expect(result).not.toBeNull();+ expect(result.title).toBe('Example Song');+ expect(result.artist).toBe('The Placeholders');+ expect(result.text).toContain('C G');+ expect(result.text).toContain('Example lyric line one');+ expect(result.text).not.toContain('[ch]');+ expect(result.text).not.toContain('[tab]');+ });++ it('tolerates the shape without the top-level store key', () => {+ const result = extractUltimateGuitarStore(buildUgHtml(UG_STORE.store));+ expect(result?.title).toBe('Example Song');+ });++ it('returns null when there is no js-store div', () => {+ expect(extractUltimateGuitarStore('<html><body><p>nothing</p></body></html>')).toBeNull();+ });++ it('returns null on shape drift (missing wiki_tab)', () => {+ const drifted = { store: { page: { data: { tab: { song_name: 'X' } } } } };+ expect(extractUltimateGuitarStore(buildUgHtml(drifted))).toBeNull();+ });++ it('returns null on malformed JSON in data-content', () => {+ const html = '<div class="js-store" data-content="{not json"></div>';+ expect(extractUltimateGuitarStore(html)).toBeNull();+ });++ it('returns null when content is present but empty', () => {+ const empty = { store: { page: { data: { tab_view: { wiki_tab: { content: ' ' } } } } } };+ expect(extractUltimateGuitarStore(buildUgHtml(empty))).toBeNull();+ });+});++describe('extractLargestPre', () => {+ it('picks the largest <pre> and decodes entities', () => {+ const html = '<pre>short but long enough tab</pre>' ++ '<pre class="tab">e|--0--2--3--|\nB|--1--1--0--|\nG & D strings</pre>';+ const result = extractLargestPre(html);+ expect(result).toContain('e|--0--2--3--|');+ expect(result).toContain('G & D strings');+ });++ 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');+ });++ it('returns null when the only <pre> is too small to be a sheet', () => {+ expect(extractLargestPre('<pre>x = 1;</pre>')).toBeNull();+ });++ it('returns null with no <pre> at all', () => {+ expect(extractLargestPre('<p>hello</p>')).toBeNull();+ });+});++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>';+ expect(parseTitleArtist(html)).toEqual({ title: 'EXAMPLE SONG', artist: 'The Placeholders' });+ });++ it('parses "X - Y" titles', () => {+ expect(parseTitleArtist('<title>Example Song - The Placeholders | TabSite</title>'))+ .toEqual({ title: 'Example Song', artist: 'The Placeholders' });+ });++ it('returns empty fields when there is no title tag', () => {+ expect(parseTitleArtist('<html></html>')).toEqual({ title: '', artist: '' });+ });+});++describe('buildDraftFromHtml', () => {+ const URL = 'https://www.example.com/tab/example-song-1';++ it('prefers the UG extractor and stamps sourceUrl', () => {+ const draft = buildDraftFromHtml(buildUgHtml(UG_STORE), URL);+ expect(draft.title).toBe('Example Song');+ expect(draft.artist).toBe('The Placeholders');+ expect(draft.content.format).toBe('tab');+ expect(draft.content.text).toContain('Example lyric line one');+ expect(draft.sourceUrl).toBe(URL);+ });++ it('falls back to the largest <pre> with title/artist from <title>', () => {+ const html = '<html><head><title>Example Song by The Placeholders</title></head>' ++ '<body><pre>e|--0--2--3--| example tab staff</pre></body></html>';+ const draft = buildDraftFromHtml(html, URL);+ expect(draft.content.format).toBe('tab');+ expect(draft.content.text).toContain('e|--0--2--3--|');+ expect(draft.title).toBe('Example Song');+ expect(draft.artist).toBe('The Placeholders');+ });++ it('falls through UG shape drift to the <pre> extractor', () => {+ const drifted = { store: { page: { data: {} } } };+ const html = buildUgHtml(drifted).replace('</body>', '<pre>Am F C G — example progression sheet</pre></body>');+ const draft = buildDraftFromHtml(html, URL);+ expect(draft.content.format).toBe('tab');+ expect(draft.content.text).toContain('example progression sheet');+ });++ 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 draft = buildDraftFromHtml(html, URL);+ expect(draft.content.format).toBe('plain');+ expect(draft.content.text).toBe('Just some lyric text on a plain page');+ });+});++describe('importSongFromUrl', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('fetches via safeUrlFetch and returns the draft', async () => {+ fetchPublicText.mockResolvedValue(buildUgHtml(UG_STORE));+ const draft = await importSongFromUrl('https://www.example.com/tab/1');+ expect(fetchPublicText).toHaveBeenCalledWith('https://www.example.com/tab/1', expect.objectContaining({+ timeoutMs: expect.any(Number),+ }));+ expect(draft.title).toBe('Example Song');+ expect(draft.sourceUrl).toBe('https://www.example.com/tab/1');+ });++ it('throws 502 when the fetch fails closed (null)', async () => {+ fetchPublicText.mockResolvedValue(null);+ await expect(importSongFromUrl('https://www.example.com/tab/1'))+ .rejects.toMatchObject({ status: 502, code: 'SONG_IMPORT_FETCH_FAILED' });+ });++ it('throws 422 when the page yields no content at all', async () => {+ fetchPublicText.mockResolvedValue('<html><head><title>Empty</title></head><body></body></html>');+ await expect(importSongFromUrl('https://www.example.com/tab/1'))+ .rejects.toMatchObject({ status: 422, code: 'SONG_IMPORT_EMPTY' });+ });+});diff --git a/server/services/brainStorage.js b/server/services/brainStorage.jsindex 4526923991..1a3a205b56 100644--- a/server/services/brainStorage.js+++ b/server/services/brainStorage.js@@ -47,7 +47,7 @@ const DATA_DIR = PATHS.brain;// backfill all cover them with no per-type branching.export const BRAIN_ENTITY_TYPES = Object.freeze(['people', 'projects', 'ideas', 'admin', 'memories', 'links', 'buckets',- 'journals', 'inbox',+ 'journals', 'inbox', 'songs',]);// A tombstone is a deleted-record marker kept IN PLACE in `data.records[id]`@@ -92,6 +92,10 @@ const FILES = {// from the old inbox_log.jsonl to inbox.json (migration 081).journals: join(DATA_DIR, 'journals.json'),inbox: join(DATA_DIR, 'inbox.json'),+ // SongBook repertoire records (guitar tabs / chord sheets / sheet music).+ // Attachment BYTES live machine-local under data/brain/songbook/ (see+ // routes/brainSongbook.js); only the metadata rides in the synced record.+ songs: join(DATA_DIR, 'songs.json'),digests: join(DATA_DIR, 'digests.jsonl'),reviews: join(DATA_DIR, 'reviews.jsonl')};@@ -111,6 +115,7 @@ const caches = {buckets: { data: null, timestamp: 0 },journals: { data: null, timestamp: 0 },inbox: { data: null, timestamp: 0 },+ songs: { data: null, timestamp: 0 },digests: { data: null, timestamp: 0 },reviews: { data: null, timestamp: 0 }};diff --git a/server/services/brainStorage.test.js b/server/services/brainStorage.test.jsindex cd517c1452..27a5aaee7b 100644--- a/server/services/brainStorage.test.js+++ b/server/services/brainStorage.test.js@@ -238,6 +238,32 @@ describe('memory recency ordering', () => {});});+describe('songs entity enrollment (SongBook)', () => {+ it('lists songs in BRAIN_ENTITY_TYPES so sync/GC/backfill all cover it', () => {+ expect(brainStorage.BRAIN_ENTITY_TYPES).toContain('songs');+ });++ it('round-trips create/getAll/getById/remove through the generic entity API', async () => {+ const created = await brainStorage.create('songs', {+ title: 'Example Song',+ artist: 'The Placeholders',+ stage: 'new',+ attachments: [],+ });+ expect(created.id).toBeDefined();+ expect(created.originInstanceId).toBe('local-instance');++ const all = await brainStorage.getAll('songs');+ expect(all.find((s) => s.id === created.id)).toMatchObject({ title: 'Example Song' });++ expect(await brainStorage.remove('songs', created.id)).toBe(true);+ expect(await brainStorage.getById('songs', created.id)).toBeNull();+ // Tombstone retained in place (not hard-deleted) for LWW convergence.+ const raw = await rawRecord('songs', created.id);+ expect(raw._deleted).toBe(true);+ });+});+// Read the raw stored record (including tombstones) by bypassing the read filter.async function rawRecord(type, id) {const { readFile } = await import('fs/promises');