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
songs: add reference-tone melody playback + playhead to the sheet-music view
[._.]/ Adam Eivy4054e2551dd0
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex aa37deeda4..622e83eae9 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -10,6 +10,7 @@- **Scheduled "Refresh local-LLM catalog" task** — a new built-in CoS schedule that periodically researches the current best local models per category and opens a PR refreshing PortOS's bundled suggested-models catalog (`server/lib/localLlmCatalog.js`) and the editorial model ranking, so the in-app install picker and recommendations don't go stale. It no-ops on any repo lacking the catalog file, so it only does work when enabled on the PortOS app itself. Off by default; weekly when enabled, and it only opens a PR when the catalog is actually out of date.- **Manuscript editorial review: "Start fresh" re-run mode** — re-running the editorial pass in the manuscript editor previously always *merged*, leaving every prior open note in place even when a later pass no longer flagged it. A new "Start fresh" checkbox next to "Run editorial review" reconciles the open list against the latest pass: open notes it still finds stay open, open notes it no longer finds are auto-dismissed, and genuinely-new findings are added. Your accepted and dismissed decisions are left untouched. Clearing is done by moving notes to dismissed (never by deleting them), so the change syncs correctly across federated machines instead of being resurrected by a peer. Merge stays the default.- **Manuscript editor: editorial feedback is now shown in-context, not just in a sidebar** — instead of scrolling a disconnected list of notes, each editorial comment is highlighted directly on the text it points to. A header toggle switches between two modes: **Live** (Grammarly-style — the manuscript stays fully editable and each anchored note shows as a severity-toned underline; click the underlined text or its tag to pop the note's card right there with Generate-fix / Accept / Dismiss) and **Review** (a read-through where the prose is annotated and clicking a highlight expands the note inline, with a per-section Edit toggle to drop into free editing). The right sidebar becomes a filterable index (by severity, with open / accepted / dismissed groups and a "located in text" count) that scrolls to and opens any note. The editor now focuses **one issue at a time** with a deep-linkable tab strip (`…/manuscript/<issueNumber>`, each tab badged with its open-note count) instead of one page-length scroll of every issue. Suggested edits can be reviewed as a **side-by-side before/after diff** (default) or the prior stacked inline diff, and a new **Impact preview** shows, per affected issue, how accepting the selected fixes changes the whole manuscript before you commit to them (a single fix can span multiple issues). Notes whose anchor text no longer matches the draft degrade gracefully — they stay listed in the sidebar with no in-text highlight rather than disappearing.+- **Songs: hear the written melody (reference-tone playback + playhead)** — the sheet-music view now has a **Play melody** control that synthesizes the notated tune so you can hear how a part goes before you sing it — the written-notation companion to the recorded-take round-stack playback. Each note is played as a soft triangle-wave reference tone on the same shared audio clock the recording mixer uses (no MIDI.js / Tone.js — Web Audio oscillators only), with pitch and rhythm read from the score (A4=440, durations honoring the time signature). The currently-sounding notehead lights up in the theme accent as a moving playhead so the audio and the staff stay in sync, and a **Tempo** field lets you slow it down (defaults to the song's marked tempo). Play / pause / stop, and audio tears down cleanly when you navigate away.- **Songs: a sheet-music view & editor** — each song can now carry real sheet music, rendered as an engraved staff (treble or bass clef, key & time signature, notes with stems/flags/dots, accidentals, ledger lines, rests, chord symbols above and lyrics beneath). It's drawn entirely in-house — no third-party music-notation library — from a small, readable text format ("PortOS lead-sheet notation": `clef:` / `key:` / `time:` / `tempo:` headers, then measures of `[chord] pitch+duration (lyric)` like `[C] E4q(If) G4q(you)`). The **Edit** tab gives you a textarea with a live-updating staff preview, a collapsible format guide, and per-measure beat-count feedback; the **View** tab shows the rendered score full-width above the lyrics. The built-in "500 Miles" now ships with its verse melody, chords, and lyrics as a worked example you can edit and learn from.- **Songs: built-in singing rounds + a round-stack (quodlibet) view** — four traditional rounds now ship as built-in songs — **Hey Ho Nobody Home**, **Ah Poor Bird** (with an alternate "Oh poor bird, why art thou…" lyric set), **Rose Rose Rose Red**, and **Zum Gali Gali** — each with its melody in sheet music, lyrics, and canon-entry voice layers. Songs can now declare the partners they're sung with: the first three are the classic *quodlibet* — they share one minor chord cycle and can be sung at the same time. In **Edit**, a "Sings with" picker links partner songs; in **View**, a **Stack parts** toggle (linkable as `?stack=1`) renders every partner's melody and lyrics stacked as simultaneous parts and plays their recorded takes layered together on one audio clock. Existing installs receive the four rounds via a migration; the links round-trip and are restorable via "Refresh from template."- **Songs: a read/perform view, built-in defaults, and reference videos** — the song page now has a **View / Edit** toggle (mode lives in the URL, so each view is linkable). **View** is a clean, desktop-wide performance layout — lyrics rendered in full with no cramped sub-scrolling boxes, sections laid out side-by-side to use the screen and cut vertical scrolling, with the recorder kept front-and-centre for playing/recording; **Edit** is the existing workbench, now wider with a two-column lyric grid. Shipped example songs are tagged **Built-in default** (a badge in the Songs list and a banner in the editor) with a **Refresh from template** button that restores the latest bundled lyrics, arrangement, and references while preserving your own recordings and learned progress — so an install that already has an older copy of a default song can renew it on demand. Songs can also carry **reference material**: paste a link to a performance or tutorial, and TikTok video links play inline as embeds in the View tab (other links render as link cards). The built-in "500 Miles" ships with TikTok reference performances and its full set of lyrics.diff --git a/client/src/components/songs/ScoreSheet.jsx b/client/src/components/songs/ScoreSheet.jsxindex 2b1ddcd918..74996ee8d3 100644--- a/client/src/components/songs/ScoreSheet.jsx+++ b/client/src/components/songs/ScoreSheet.jsx@@ -19,8 +19,9 @@* missing music font degrades only the clef glyph, never the staff.*/-import { useMemo } from 'react';+import { useMemo, useState, useRef, useEffect, useId } from 'react';import { parseScore } from '../../lib/scoreNotation.js';+import { createScorePlayer, DEFAULT_BPM } from '../../lib/scorePlayback.js';// --- Geometry (all in internal SVG units; the <svg> scales via viewBox) ------const WIDTH = 720; // internal coordinate width — viewBox scales to fit@@ -59,6 +60,9 @@ const STAFF_BLOCK = 4 * GAP; // the five staff lines span four gaps// fill="…"/stroke="…" attributes. Staff lines sit at a dimmed muted tone so the// noteheads (full text colour) read as the foreground in both themes.const INK = 'rgb(var(--port-text))';+// The currently-sounding note (playhead) is painted in the theme accent so it+// reads as the foreground against the neutral-ink staff, in both day and dark.+const ACTIVE = 'rgb(var(--port-accent))';const STAFF = 'rgb(var(--port-text-muted) / 0.55)';const CHORD = 'rgb(var(--port-accent))';const LYRIC = 'rgb(var(--port-text-muted))';@@ -131,9 +135,64 @@ const rowLyricOffset = (row, bottomLineStep) => {return Math.max(LYRIC_MIN_BELOW_STAFF, belowStaffPx + LYRIC_BELOW_NOTE);};-export default function ScoreSheet({ text, className = '' }) {+export default function ScoreSheet({ text, className = '', controls = true, activeNoteIndex = null }) {const score = useMemo(() => parseScore(text), [text]);+ // --- Reference-tone playback (synthesize the written melody) ---------------+ // The player lives in scorePlayback.js (pure schedule + a lookahead oscillator+ // scheduler); this component only owns the transport UI + the playhead index.+ // Hooks run unconditionally, before the no-music early return below.+ const uid = useId();+ const playerRef = useRef(null);+ const [isPlaying, setIsPlaying] = useState(false);+ const [activeIdx, setActiveIdx] = useState(-1);+ const scoreBpm = Number.isFinite(score.tempo) && score.tempo > 0 ? score.tempo : DEFAULT_BPM;+ const [tempo, setTempo] = useState(scoreBpm);++ // A changed score (live editing, switching songs) invalidates the player and+ // resets the transport; tempo re-syncs to the new score's marking.+ useEffect(() => {+ if (playerRef.current) { playerRef.current.stop(); playerRef.current = null; }+ setIsPlaying(false);+ setActiveIdx(-1);+ setTempo(scoreBpm);+ }, [score, scoreBpm]);++ // Tear down any live oscillators + lookahead interval on unmount.+ useEffect(() => () => {+ if (playerRef.current) { playerRef.current.stop(); playerRef.current = null; }+ }, []);++ // Tempo edits take effect on the running (or next) player.+ useEffect(() => { if (playerRef.current) playerRef.current.setTempo(tempo); }, [tempo]);++ const ensurePlayer = () => {+ if (!playerRef.current) {+ playerRef.current = createScorePlayer(score, {+ bpm: tempo,+ onNote: (i) => setActiveIdx(i == null ? -1 : i),+ onEnded: () => { setIsPlaying(false); setActiveIdx(-1); },+ });+ }+ return playerRef.current;+ };++ const togglePlay = () => {+ const player = ensurePlayer();+ if (isPlaying) { player.pause(); setIsPlaying(false); return; }+ setIsPlaying(true);+ Promise.resolve(player.play()).catch(() => setIsPlaying(false));+ };++ const handleStop = () => {+ if (playerRef.current) playerRef.current.stop();+ setIsPlaying(false);+ setActiveIdx(-1);+ };++ // A passed `activeNoteIndex` (controlled use / tests) wins over internal play.+ const highlight = activeNoteIndex == null ? activeIdx : activeNoteIndex;+const { rows, height } = useMemo(() => {const packed = packRows(score.measures, score.keySig.count);const blStep = BOTTOM_LINE_STEP[score.clef] ?? BOTTOM_LINE_STEP.treble;@@ -156,6 +215,10 @@ export default function ScoreSheet({ text, className = '' }) {const middleLineStep = bottomLineStep + 4;const els = [];+ // Global note index across the whole score, in the same order scorePlayback's+ // buildSchedule walks it — so `highlight` (the now-sounding note) lines up with+ // the correct notehead for the playhead.+ let noteCounter = 0;rows.forEach((row, ri) => {const rowTop = row.top;const staffTop = rowTop + ROW_TOP_PAD;@@ -222,10 +285,12 @@ export default function ScoreSheet({ text, className = '' }) {const cx = cursor + slot / 2;cursor += slot;const key = `m${index}-n${ni}`;+ const ink = noteCounter === highlight ? ACTIVE : INK;+ noteCounter += 1;if (note.rest) {- els.push(...renderRest(note, cx, yForStep, bottomLineStep, key));+ els.push(...renderRest(note, cx, yForStep, bottomLineStep, key, ink));} else {- els.push(...renderNote(note, cx, yForStep, bottomLineStep, middleLineStep, key));+ els.push(...renderNote(note, cx, yForStep, bottomLineStep, middleLineStep, key, ink));}if (note.chord) {els.push(<text key={`${key}-ch`} x={cx} y={chordY} fontSize={12} fontWeight="600" style={fillStyle(CHORD)} textAnchor="middle" fontFamily="ui-sans-serif, system-ui, sans-serif">{note.chord}</text>);@@ -240,21 +305,62 @@ export default function ScoreSheet({ text, className = '' }) {});return (- <svg- className={className}- viewBox={`0 0 ${WIDTH} ${height}`}- width="100%"- role="img"- aria-label="Sheet music notation"- style={{ height: 'auto', display: 'block' }}- >- {els}- </svg>+ <div className="w-full">+ {controls && (+ <div className="flex flex-wrap items-center gap-2 mb-2 text-xs text-gray-400">+ <button+ type="button"+ onClick={togglePlay}+ aria-label={isPlaying ? 'Pause melody' : 'Play melody'}+ className="flex items-center gap-1 rounded-md border border-port-border bg-port-card px-2 py-1 text-white hover:border-port-accent transition-colors"+ >+ <span aria-hidden="true">{isPlaying ? '⏸' : '▶'}</span>+ <span className="hidden sm:inline">{isPlaying ? 'Pause' : 'Play melody'}</span>+ </button>+ <button+ type="button"+ onClick={handleStop}+ aria-label="Stop melody"+ disabled={!isPlaying && activeIdx < 0}+ className="flex items-center gap-1 rounded-md border border-port-border bg-port-card px-2 py-1 text-white hover:border-port-accent transition-colors disabled:opacity-40 disabled:hover:border-port-border"+ >+ <span aria-hidden="true">⏹</span>+ <span className="hidden sm:inline">Stop</span>+ </button>+ <label htmlFor={`${uid}-tempo`} className="ml-auto flex items-center gap-1">+ <span>Tempo</span>+ <input+ id={`${uid}-tempo`}+ type="number"+ min={20}+ max={300}+ value={tempo}+ onChange={(e) => {+ const next = Number(e.target.value);+ if (Number.isFinite(next) && next > 0) setTempo(next);+ }}+ className="w-16 rounded-md border border-port-border bg-port-card px-2 py-1 text-white"+ />+ <span>BPM</span>+ </label>+ </div>+ )}+ <svg+ className={className}+ viewBox={`0 0 ${WIDTH} ${height}`}+ width="100%"+ role="img"+ aria-label="Sheet music notation"+ style={{ height: 'auto', display: 'block' }}+ >+ {els}+ </svg>+ </div>);}// --- Per-note drawing --------------------------------------------------------function renderNote(note, cx, yForStep, bottomLineStep, middleLineStep, key) {+function renderNote(note, cx, yForStep, bottomLineStep, middleLineStep, key, ink = INK) {const out = [];const step = note.step;const y = yForStep(step);@@ -278,7 +384,7 @@ function renderNote(note, cx, yForStep, bottomLineStep, middleLineStep, key) {// Accidental glyph, left of the head.if (note.pitch.accidental && ACCIDENTAL_GLYPH[note.pitch.accidental]) {- out.push(<text key={`${key}-acc`} x={cx - NOTE_RX - 6} y={y + 5} fontSize={16} style={fillStyle(INK)} textAnchor="middle" fontFamily={MUSIC_FONT}>{ACCIDENTAL_GLYPH[note.pitch.accidental]}</text>);+ out.push(<text key={`${key}-acc`} x={cx - NOTE_RX - 6} y={y + 5} fontSize={16} style={fillStyle(ink)} textAnchor="middle" fontFamily={MUSIC_FONT}>{ACCIDENTAL_GLYPH[note.pitch.accidental]}</text>);}// Notehead — open for half/whole, solid otherwise. A slight rotation gives@@ -286,21 +392,21 @@ function renderNote(note, cx, yForStep, bottomLineStep, middleLineStep, key) {out.push(<ellipse key={`${key}-head`} cx={cx} cy={y} rx={NOTE_RX} ry={NOTE_RY}transform={`rotate(-18 ${cx} ${y})`}- style={{ fill: filled ? INK : "none", stroke: INK }} strokeWidth={filled ? 0 : 1.4} />,+ style={{ fill: filled ? ink : "none", stroke: ink }} strokeWidth={filled ? 0 : 1.4} />,);// Stem + flags (whole notes have neither).if (note.duration.stem) {const stemX = up ? cx + NOTE_RX - 0.6 : cx - NOTE_RX + 0.6;const stemEndY = up ? y - STEM_LEN : y + STEM_LEN;- out.push(<line key={`${key}-stem`} x1={stemX} y1={y} x2={stemX} y2={stemEndY} style={strokeStyle(INK)} strokeWidth={1.3} />);+ out.push(<line key={`${key}-stem`} x1={stemX} y1={y} x2={stemX} y2={stemEndY} style={strokeStyle(ink)} strokeWidth={1.3} />);for (let f = 0; f < note.duration.flags; f += 1) {const fy = up ? stemEndY + f * FLAG_GAP : stemEndY - f * FLAG_GAP;const dir = up ? 1 : -1;out.push(<path key={`${key}-flag${f}`}d={`M ${stemX} ${fy} Q ${stemX + 11} ${fy + dir * 5} ${stemX + 8} ${fy + dir * 16}`}- style={{ fill: "none", stroke: INK }} strokeWidth={1.6} strokeLinecap="round" />,+ style={{ fill: "none", stroke: ink }} strokeWidth={1.6} strokeLinecap="round" />,);}}@@ -311,7 +417,7 @@ function renderNote(note, cx, yForStep, bottomLineStep, middleLineStep, key) {const onLine = ((step - bottomLineStep) % 2 + 2) % 2 === 0;const dy = onLine ? y - STEP : y;for (let d = 0; d < note.duration.dots; d += 1) {- out.push(<circle key={`${key}-dot${d}`} cx={cx + NOTE_RX + 4 + d * 4} cy={dy} r={1.5} style={fillStyle(INK)} />);+ out.push(<circle key={`${key}-dot${d}`} cx={cx + NOTE_RX + 4 + d * 4} cy={dy} r={1.5} style={fillStyle(ink)} />);}}return out;@@ -320,29 +426,29 @@ function renderNote(note, cx, yForStep, bottomLineStep, middleLineStep, key) {// --- Per-rest drawing -------------------------------------------------------// Rests are drawn from primitives (not Unicode) so they render identically on// every platform. Positions are relative to the middle staff line.-function renderRest(note, cx, yForStep, bottomLineStep, key) {+function renderRest(note, cx, yForStep, bottomLineStep, key, ink = INK) {const code = note.duration.code;const midLine = yForStep(bottomLineStep + 4);const secondTop = yForStep(bottomLineStep + 6); // 2nd line from top (whole rest hangs here)const out = [];if (code === 'w') {- out.push(<rect key={`${key}-r`} x={cx - 5} y={secondTop} width={10} height={GAP * 0.4} style={fillStyle(INK)} />);+ out.push(<rect key={`${key}-r`} x={cx - 5} y={secondTop} width={10} height={GAP * 0.4} style={fillStyle(ink)} />);} else if (code === 'h') {- out.push(<rect key={`${key}-r`} x={cx - 5} y={midLine - GAP * 0.4} width={10} height={GAP * 0.4} style={fillStyle(INK)} />);+ out.push(<rect key={`${key}-r`} x={cx - 5} y={midLine - GAP * 0.4} width={10} height={GAP * 0.4} style={fillStyle(ink)} />);} else if (code === 'q') {// Stylized quarter rest — a zig-zag down the middle of the staff.const top = yForStep(bottomLineStep + 6);out.push(<path key={`${key}-r`}d={`M ${cx - 3} ${top} L ${cx + 3} ${top + GAP} L ${cx - 2.5} ${top + GAP * 1.7} Q ${cx + 4} ${top + GAP * 2.2} ${cx + 1} ${top + GAP * 3}`}- style={{ fill: "none", stroke: INK }} strokeWidth={1.8} strokeLinecap="round" strokeLinejoin="round" />,+ style={{ fill: "none", stroke: ink }} strokeWidth={1.8} strokeLinecap="round" strokeLinejoin="round" />,);} else {// Eighth / sixteenth / 32nd rest — a diagonal stroke with one blob per flag.const top = yForStep(bottomLineStep + 5);- out.push(<line key={`${key}-rstroke`} x1={cx + 3} y1={top} x2={cx - 3} y2={top + GAP * 2} style={strokeStyle(INK)} strokeWidth={1.4} />);+ out.push(<line key={`${key}-rstroke`} x1={cx + 3} y1={top} x2={cx - 3} y2={top + GAP * 2} style={strokeStyle(ink)} strokeWidth={1.4} />);for (let f = 0; f < (note.duration.flags || 1); f += 1) {- out.push(<circle key={`${key}-rb${f}`} cx={cx + 2} cy={top + f * GAP * 0.9} r={2} style={fillStyle(INK)} />);+ out.push(<circle key={`${key}-rb${f}`} cx={cx + 2} cy={top + f * GAP * 0.9} r={2} style={fillStyle(ink)} />);}}return out;diff --git a/client/src/components/songs/ScoreSheet.test.jsx b/client/src/components/songs/ScoreSheet.test.jsxindex c25fb0ed12..5afb7cb1d9 100644--- a/client/src/components/songs/ScoreSheet.test.jsx+++ b/client/src/components/songs/ScoreSheet.test.jsx@@ -100,4 +100,31 @@ describe('ScoreSheet renderer', () => {expect(html).not.toMatch(/NaN/);expect(count(html, 'ellipse')).toBe(2);});++ it('renders a melody playback control with a labelled tempo input', () => {+ const html = renderToStaticMarkup(<ScoreSheet text={FIVE_HUNDRED_MILES} />);+ expect(html).toContain('aria-label="Play melody"');+ expect(html).toContain('aria-label="Stop melody"');+ expect(html).toMatch(/<input[^>]*type="number"/); // tempo input+ // The tempo input is label-associated (htmlFor/id), not just visually styled.+ const id = /<input[^>]*\bid="([^"]+)"/.exec(html)?.[1];+ expect(id).toBeTruthy();+ expect(html).toContain(`for="${id}"`);+ });++ it('omits the playback control when controls=false', () => {+ const html = renderToStaticMarkup(<ScoreSheet text={FIVE_HUNDRED_MILES} controls={false} />);+ expect(html).not.toContain('aria-label="Play melody"');+ });++ it('highlights the notehead at activeNoteIndex in the theme accent (playhead)', () => {+ const plain = renderToStaticMarkup(<ScoreSheet text={FIVE_HUNDRED_MILES} controls={false} />);+ // With no playhead, no notehead is painted in the accent colour.+ expect(plain).not.toMatch(/<ellipse[^>]*fill:rgb\(var\(--port-accent\)\)/);+ // The first note (a filled quarter) lights up when it is the active note.+ const lit = renderToStaticMarkup(+ <ScoreSheet text={FIVE_HUNDRED_MILES} controls={false} activeNoteIndex={0} />,+ );+ expect(lit).toMatch(/<ellipse[^>]*fill:rgb\(var\(--port-accent\)\)/);+ });});diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex 19f796e202..4eef0dea63 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -89,6 +89,7 @@ grep -i "what you want to do" client/src/lib/README.md| `cityPlaybackFrame.js` | Map a recorded CyberCity snapshot frame onto the prop shape CityScene/CityHud consume for the timeline scrubber (`mergeFrameIntoCityProps`, `buildPlaybackApps`, `buildPlaybackAgentMap`, `isPlayableFrame`). Honors `schemaVersion` and the capture-side null sentinels; returns only snapshot-backed props so unfed landmarks stay live. || `universeBuilderExpand.js` | `mergeExpandIntoDraft(draft, result)` — pure merge of a Universe Builder draft with the LLM expand-API response (lock honoring, category/sheet merge with `kind` precedence, canon dedupe by name/slugline/alias). Also exports `mergeVariations`, `mergeCanonByName`, and `extractPreservedFromDraft` for callers that need the building blocks (per-category Generate, save-time refetch+merge). || `scoreNotation.js` | Parser for the PortOS lead-sheet notation — a dependency-free text format for melody + chords + lyrics that the `<ScoreSheet>` SVG renderer draws (no abcjs / VexFlow / OSMD). `parseScore(text)` → `{ clef, key, keySig, time, tempo, measures, errors }`; plus `parsePitch`, `diatonicStep`, `durationBeats`, `keySignature`, `DURATIONS`, and `scoreHasMusic(text)`. Forgiving: bad tokens collect into `errors` and are skipped, never thrown. Pure — the renderer only does geometry. |+| `scorePlayback.js` | Melody synth playback for the lead-sheet notation — companion to `songPlayback.js` (which stacks recorded vocal takes), this synthesizes the WRITTEN melody as soft `OscillatorNode` reference tones on a lazy shared `AudioContext` (no MIDI.js / Tone.js). `buildSchedule(score, bpm?)` is the pure notes→`{ freq, startSec, durSec }` mapping (A4=440, quarter-beat = `(60/bpm)·(beatValue/4)` so it honors the time signature); `noteToFrequency`/`midiToFreq`/`pitchToMidi` convert pitches; `createScorePlayer(score, { bpm, onNote, onEnded })` plays/pauses/stops with a lookahead scheduler and emits the now-sounding note index for the `<ScoreSheet>` playhead. || `songCraft.js` | Canonical a cappella song-craft reference data rendered by the Songs Guide (`/songs/guide`) and reused by the Song editor: `RHYTHM_SHAPES` / `DIRGE_RHYTHM_SHAPES` (dirge & ballad pulse feels with BPM bands), `VOICE_LAYERS` (foundation-first harmony build ladder), `LEARNING_STEPS` (practice sequence), `NOTATION_HELP` (lead-sheet/notation primers), `SOLFEGE_DEGREES` + `solfegeForDegree(n)`, and `rhythmShapeLabel(id)` (human-readable "Slow 4/4 ballad · dirge (56–76 BPM)" label shared by the editor's picker and read view). Pure data; pickers and docs read the same source so they can't drift. || `songPlayback.js` | `createLayeredPlayer(takes)` — decode N recorded vocal takes and start them together on one shared `AudioContext` so they stack into a layered a cappella performance (sample-aligned, per-layer mute). Used by the Song editor's recording mixer. || `wrSceneCursor.js` | Resolve which script scene the editor caret sits in (`sceneAtCursor`, `sceneAnchorIndex`) — inverse of WorkEditor's jump-to-scene text search; drives the live render preview's "scene at cursor" target. |diff --git a/client/src/lib/index.js b/client/src/lib/index.jsindex 261195d11b..b897ff1ae2 100644--- a/client/src/lib/index.js+++ b/client/src/lib/index.js@@ -56,6 +56,7 @@ export * from './voiceLabel.js';// === Page-scoped pure helpers ===export * from './cityPlaybackFrame.js';export * from './scoreNotation.js';+export * from './scorePlayback.js';export * from './songCraft.js';export * from './songPlayback.js';export * from './universeBuilderExpand.js';diff --git a/client/src/lib/scorePlayback.js b/client/src/lib/scorePlayback.jsnew file mode 100644index 0000000000..d176aac982--- /dev/null+++ b/client/src/lib/scorePlayback.js@@ -0,0 +1,271 @@+// Melody synth playback for the lead-sheet notation — turns a parsed score+// (see scoreNotation.js) into a soft "reference tone" you can hear before you+// sing it. Companion to songPlayback.js: that mixer stacks RECORDED vocal takes,+// this one synthesizes the WRITTEN melody as oscillator tones so a singer can+// preview the intended pitch line.+//+// No third-party audio/MIDI library — Web Audio OscillatorNodes only, mirroring+// the lazy shared-AudioContext + lookahead-scheduler idiom in songPlayback.js.+// The schedule-building math (notes → { freq, startSec, durSec }) is a pure+// function so it can be unit-tested without Web Audio; the player wires that+// schedule onto the audio clock and emits a per-note "now sounding" callback so+// the UI can move a playhead. Pure (no React) — ScoreSheet wraps it in a hook.++// --- Pitch → frequency ------------------------------------------------------+// Equal-tempered, A4 = 440 Hz. MIDI 69 == A4, so f = 440 · 2^((midi−69)/12).+const PITCH_CLASS = { C: 0, D: 2, E: 4, F: 5, G: 7, A: 9, B: 11 };+const ACCIDENTAL_SHIFT = { '': 0, '#': 1, '##': 2, b: -1, bb: -2, n: 0 };++// MIDI note number for a parsed pitch ({ letter, accidental, octave }). C4 = 60,+// A4 = 69. Returns null for anything that isn't a pitch.+export const pitchToMidi = (pitch) => {+ if (!pitch) return null;+ const pc = PITCH_CLASS[String(pitch.letter || '').toUpperCase()];+ const shift = ACCIDENTAL_SHIFT[pitch.accidental || ''];+ if (pc == null || shift == null || !Number.isFinite(pitch.octave)) return null;+ return (pitch.octave + 1) * 12 + pc + shift;+};++// Frequency (Hz) for a MIDI note number. A4 (69) → 440.+export const midiToFreq = (midi) => (Number.isFinite(midi) ? 440 * Math.pow(2, (midi - 69) / 12) : null);++// Frequency (Hz) for a parsed pitch, or null when it isn't a pitch.+export const noteToFrequency = (pitch) => {+ const midi = pitchToMidi(pitch);+ return midi == null ? null : midiToFreq(midi);+};++// --- Schedule building (pure) -----------------------------------------------+// Walk the parsed score in render order (measures → notes) and assign each note+// a global index, an onset, and a duration in seconds. The note index matches+// the order <ScoreSheet> flattens notes, so the player's onNote(index) lines up+// with the rendered notehead for the playhead highlight.+//+// Timing: scoreNotation durations are in QUARTER-NOTE beats. The score's tempo+// counts beats where one beat = the time-signature denominator note, so a+// quarter-note beat lasts (60/bpm)·(beatValue/4) seconds. That makes 4/4 read as+// quarter=bpm and 6/8 read as eighth=bpm (the conventional interpretation),+// using the time signature rather than ignoring it.+export const DEFAULT_BPM = 90;++export const buildSchedule = (score, bpmOverride) => {+ const beatValue = score?.time?.beatValue || 4;+ const bpm = Number.isFinite(bpmOverride) && bpmOverride > 0+ ? bpmOverride+ : (Number.isFinite(score?.tempo) && score.tempo > 0 ? score.tempo : DEFAULT_BPM);+ const secPerQuarter = (60 / bpm) * (beatValue / 4);++ const events = [];+ let beat = 0;+ let index = 0;+ for (const measure of score?.measures || []) {+ for (const note of measure.notes || []) {+ const durBeats = note.duration?.beats || 0;+ events.push({+ index,+ rest: !!note.rest,+ freq: note.rest ? null : noteToFrequency(note.pitch),+ startBeat: beat,+ durBeats,+ startSec: beat * secPerQuarter,+ durSec: durBeats * secPerQuarter,+ });+ beat += durBeats;+ index += 1;+ }+ }+ return { events, bpm, secPerQuarter, totalSec: beat * secPerQuarter };+};++// --- Audio context ----------------------------------------------------------+// Lazily create + reuse one AudioContext (browsers cap the count). Resumed on+// demand because autoplay policy starts it suspended until a user gesture.+let sharedCtx = null;+const ctx = () => {+ if (!sharedCtx) {+ const Ctor = window.AudioContext || window.webkitAudioContext;+ sharedCtx = new Ctor();+ }+ return sharedCtx;+};++// Guard a UI callback that fires from a setInterval tick — an uncaught throw+// there has no request boundary to bubble to and would leave the scheduler+// interval orphaned. (CLAUDE.md: wrap non-request-lifecycle callbacks.)+const safeCall = (cb, ...args) => {+ if (typeof cb !== 'function') return;+ try { cb(...args); }+ catch (err) { console.error(`🎹 score playback callback failed: ${err.message}`); }+};++const LEAD = 0.08; // seconds of lead-in before beat 0 sounds+const LOOKAHEAD_MS = 25; // how often the scheduler wakes+const SCHEDULE_AHEAD = 0.12; // seconds of audio scheduled past "now"++/**+ * Build a melody player over a parsed score.+ *+ * @param {object} score — output of `parseScore`.+ * @param {object} [options]+ * @param {number} [options.bpm] — tempo override (else score.tempo, else 90).+ * @param {(index:number|null)=>void} [options.onNote] — called with the index of+ * the now-sounding note (null when playback ends / stops) so the UI can move a+ * playhead.+ * @param {()=>void} [options.onEnded] — called once when the melody finishes.+ * @returns {{ play, pause, stop, isPlaying, setTempo, schedule }}+ */+export const createScorePlayer = (score, options = {}) => {+ const { onNote, onEnded } = options;+ let bpm = Number.isFinite(options.bpm) && options.bpm > 0 ? options.bpm : null;+ let schedule = buildSchedule(score, bpm);++ let playing = false;+ let interval = null;+ let startTime = 0; // ctx time at which beat 0 plays+ let offsetSec = 0; // resume position (seconds into the score)+ let nextScheduleIdx = 0; // next event to hand to the oscillator scheduler+ let nextNotifyIdx = 0; // next event to fire onNote for+ let lastNotified = -1;+ let nodes = []; // live { osc, gain } for teardown++ const stopNodes = () => {+ for (const n of nodes) {+ n.osc.onended = null;+ try { n.osc.stop(); } catch { /* already stopped */ }+ }+ nodes = [];+ };++ const clearTick = () => {+ if (interval != null) { clearInterval(interval); interval = null; }+ };++ // Schedule one tone with a short attack/release gain envelope so it doesn't+ // click. Triangle wave reads as a soft reference tone.+ const scheduleTone = (freq, startAt, durSec) => {+ const c = ctx();+ const osc = c.createOscillator();+ const gain = c.createGain();+ osc.type = 'triangle';+ osc.frequency.setValueAtTime(freq, startAt);++ const peak = 0.18;+ const attack = Math.min(0.012, durSec * 0.25);+ const release = Math.min(0.07, durSec * 0.4);+ const end = startAt + durSec;+ const sustainEnd = Math.max(startAt + attack, end - release);+ gain.gain.setValueAtTime(0.0001, startAt);+ gain.gain.exponentialRampToValueAtTime(peak, startAt + attack);+ gain.gain.setValueAtTime(peak, sustainEnd);+ gain.gain.exponentialRampToValueAtTime(0.0001, end);++ osc.connect(gain).connect(c.destination);+ osc.start(startAt);+ osc.stop(end + 0.03);+ const entry = { osc, gain };+ osc.onended = () => { nodes = nodes.filter((n) => n !== entry); };+ nodes.push(entry);+ };++ // One scheduler tick: hand any due tones to the audio clock, fire the playhead+ // callback for the latest note that has started, and finish at the end.+ const tick = () => {+ const now = ctx().currentTime;+ const events = schedule.events;++ while (nextScheduleIdx < events.length) {+ const ev = events[nextScheduleIdx];+ const at = startTime + ev.startSec;+ if (at > now + SCHEDULE_AHEAD) break;+ if (!ev.rest && ev.freq) scheduleTone(ev.freq, Math.max(at, now), ev.durSec);+ nextScheduleIdx += 1;+ }++ let newest = -1;+ while (nextNotifyIdx < events.length && startTime + events[nextNotifyIdx].startSec <= now) {+ newest = events[nextNotifyIdx].index;+ nextNotifyIdx += 1;+ }+ if (newest >= 0 && newest !== lastNotified) {+ lastNotified = newest;+ safeCall(onNote, newest);+ }++ if (now - startTime >= schedule.totalSec) finish();+ };++ // Natural end — reset to the top and notify.+ function finish() {+ clearTick();+ stopNodes();+ playing = false;+ offsetSec = 0;+ nextScheduleIdx = 0;+ nextNotifyIdx = 0;+ lastNotified = -1;+ safeCall(onNote, null);+ safeCall(onEnded);+ }++ // Position the schedule/notify cursors at a resume offset — the first event+ // still sounding at (or starting after) `offset`. Both cursors share this+ // point so the note under the playhead at resume is (re)scheduled AND+ // (re)notified, and a fresh play from 0 still notifies note 0.+ const seekCursors = (offset) => {+ const events = schedule.events;+ let idx = events.findIndex((e) => e.startSec + e.durSec > offset + 1e-6);+ if (idx < 0) idx = events.length;+ nextScheduleIdx = idx;+ nextNotifyIdx = idx;+ };++ const play = async () => {+ if (playing) return;+ const c = ctx();+ if (c.state === 'suspended' && c.resume) await c.resume();+ if (!schedule.events.length || schedule.totalSec <= 0) { safeCall(onEnded); return; }++ schedule = buildSchedule(score, bpm); // pick up a tempo change made while idle+ playing = true;+ lastNotified = -1;+ startTime = c.currentTime + LEAD - offsetSec;+ seekCursors(offsetSec);+ tick(); // schedule the immediate window now so playback starts promptly+ interval = setInterval(tick, LOOKAHEAD_MS);+ };++ // Pause — stop sounding, remember position, keep the cursor for resume.+ const pause = () => {+ if (!playing) return;+ offsetSec = Math.min(Math.max(0, ctx().currentTime - startTime), schedule.totalSec);+ clearTick();+ stopNodes();+ playing = false;+ };++ // Stop — full teardown back to the top, clears the playhead.+ const stop = () => {+ clearTick();+ stopNodes();+ playing = false;+ offsetSec = 0;+ nextScheduleIdx = 0;+ nextNotifyIdx = 0;+ lastNotified = -1;+ safeCall(onNote, null);+ };++ const setTempo = (nextBpm) => {+ bpm = Number.isFinite(nextBpm) && nextBpm > 0 ? nextBpm : null;+ if (!playing) schedule = buildSchedule(score, bpm);+ };++ return {+ play,+ pause,+ stop,+ isPlaying: () => playing,+ setTempo,+ schedule: () => schedule,+ };+};diff --git a/client/src/lib/scorePlayback.test.js b/client/src/lib/scorePlayback.test.jsnew file mode 100644index 0000000000..47fe6575ae--- /dev/null+++ b/client/src/lib/scorePlayback.test.js@@ -0,0 +1,166 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { parseScore, parsePitch } from './scoreNotation.js';+import {+ buildSchedule,+ midiToFreq,+ pitchToMidi,+ noteToFrequency,+ createScorePlayer,+ DEFAULT_BPM,+} from './scorePlayback.js';++// --- Pitch → frequency ------------------------------------------------------+describe('pitch → frequency', () => {+ it('maps A4 to exactly 440 Hz (the tuning reference)', () => {+ expect(pitchToMidi(parsePitch('A4'))).toBe(69);+ expect(midiToFreq(69)).toBe(440);+ expect(noteToFrequency(parsePitch('A4'))).toBe(440);+ });++ it('maps middle C (C4) to MIDI 60 ≈ 261.63 Hz', () => {+ expect(pitchToMidi(parsePitch('C4'))).toBe(60);+ expect(noteToFrequency(parsePitch('C4'))).toBeCloseTo(261.626, 2);+ });++ it('applies accidentals as semitone shifts (F#4 = MIDI 66)', () => {+ expect(pitchToMidi(parsePitch('F#4'))).toBe(66);+ expect(noteToFrequency(parsePitch('F#4'))).toBeCloseTo(369.994, 2);+ expect(pitchToMidi(parsePitch('Bb3'))).toBe(58);+ });++ it('octaves double the frequency (A5 = 880)', () => {+ expect(noteToFrequency(parsePitch('A5'))).toBe(880);+ expect(noteToFrequency(parsePitch('A3'))).toBe(220);+ });++ it('returns null for non-pitches', () => {+ expect(noteToFrequency(null)).toBeNull();+ expect(pitchToMidi(undefined)).toBeNull();+ });+});++// --- Schedule building (pure) ----------------------------------------------+describe('buildSchedule', () => {+ it('schedules one event per note with correct onsets, durations and frequencies', () => {+ const score = parseScore('time: 4/4\ntempo: 120\n| C4q D4q E4h |');+ const { events, totalSec, secPerQuarter } = buildSchedule(score);+ // tempo 120, quarter-beat = (60/120)·(4/4) = 0.5 s.+ expect(secPerQuarter).toBeCloseTo(0.5, 6);+ expect(events.map((e) => e.index)).toEqual([0, 1, 2]);+ expect(events.map((e) => e.startSec)).toEqual([0, 0.5, 1.0]);+ expect(events.map((e) => e.durSec)).toEqual([0.5, 0.5, 1.0]);+ expect(events[0].freq).toBeCloseTo(261.626, 2); // C4+ expect(events[1].freq).toBeCloseTo(293.665, 2); // D4+ expect(events[2].freq).toBeCloseTo(329.628, 2); // E4+ expect(totalSec).toBeCloseTo(2.0, 6);+ });++ it('advances time through rests but carries no frequency', () => {+ const score = parseScore('time: 4/4\ntempo: 60\n| C4q rq C4h |');+ const { events, totalSec } = buildSchedule(score);+ expect(events).toHaveLength(3);+ expect(events[1].rest).toBe(true);+ expect(events[1].freq).toBeNull();+ expect(events[1].startSec).toBeCloseTo(1.0, 6); // after the first quarter (60 bpm → 1 s)+ expect(events[2].startSec).toBeCloseTo(2.0, 6); // after the rest+ expect(totalSec).toBeCloseTo(4.0, 6);+ });++ it('honors the time signature denominator (6/8 counts the eighth as the beat)', () => {+ const score = parseScore('time: 6/8\ntempo: 120\n| C4e D4e E4e |');+ const { events, secPerQuarter } = buildSchedule(score);+ // beatValue 8: quarter-beat = (60/120)·(8/4) = 1.0 s, so an eighth = 0.5 s.+ expect(secPerQuarter).toBeCloseTo(1.0, 6);+ expect(events.map((e) => e.durSec)).toEqual([0.5, 0.5, 0.5]);+ expect(events.map((e) => e.startSec)).toEqual([0, 0.5, 1.0]);+ });++ it('falls back to the score tempo, then DEFAULT_BPM, then a bpm override', () => {+ const noTempo = parseScore('time: 4/4\n| C4q |');+ expect(buildSchedule(noTempo).bpm).toBe(DEFAULT_BPM);+ const withTempo = parseScore('time: 4/4\ntempo: 68\n| C4q |');+ expect(buildSchedule(withTempo).bpm).toBe(68);+ expect(buildSchedule(withTempo, 140).bpm).toBe(140); // override wins+ });+});++// --- Player (stubbed Web Audio) --------------------------------------------+// jsdom has no Web Audio. A minimal fake AudioContext records created+// oscillators and exposes a controllable clock so we can drive the lookahead+// scheduler deterministically with fake timers.+const audio = { now: 0, oscillators: [] };+const fakeParam = () => ({ setValueAtTime: () => {}, exponentialRampToValueAtTime: () => {} });+function FakeAudioContext() {+ return {+ state: 'running',+ resume: () => Promise.resolve(),+ get currentTime() { return audio.now; },+ destination: { id: 'destination' },+ createOscillator() {+ const osc = {+ type: '', frequency: fakeParam(), onended: null, started: null, stopped: null,+ connect: (t) => t, start(t) { this.started = t; }, stop(t) { this.stopped = t; },+ };+ audio.oscillators.push(osc);+ return osc;+ },+ createGain() { return { gain: fakeParam(), connect: (t) => t }; },+ };+}++const drive = (toSec) => {+ for (let t = 0; t <= toSec; t += 0.1) { audio.now = Number(t.toFixed(3)); vi.advanceTimersByTime(100); }+};++describe('createScorePlayer', () => {+ beforeEach(() => {+ audio.now = 0;+ audio.oscillators = [];+ window.AudioContext = FakeAudioContext;+ vi.useFakeTimers();+ });+ afterEach(() => { vi.useRealTimers(); });++ const SCORE = parseScore('time: 4/4\ntempo: 120\n| C4q D4q E4q rq |');++ it('schedules an oscillator per pitched note (rests make no tone)', async () => {+ const player = createScorePlayer(SCORE, { bpm: 120 });+ await player.play();+ drive(3); // run past totalSec (2 s) so every note schedules+ expect(audio.oscillators).toHaveLength(3); // C, D, E — the rest is silent+ player.stop();+ });++ it('emits the now-sounding note index, then null at the end', async () => {+ const seen = [];+ const ended = vi.fn();+ const player = createScorePlayer(SCORE, { bpm: 120, onNote: (i) => seen.push(i), onEnded: ended });+ await player.play();+ drive(3);+ expect(seen).toContain(0);+ expect(seen).toContain(2);+ expect(seen[seen.length - 1]).toBeNull(); // playhead cleared at finish+ expect(ended).toHaveBeenCalledTimes(1);+ });++ it('stop() cancels the lookahead interval and stops live nodes', async () => {+ const player = createScorePlayer(SCORE, { bpm: 120 });+ await player.play();+ expect(audio.oscillators.length).toBeGreaterThan(0);+ const first = audio.oscillators[0];+ const scheduledSoFar = audio.oscillators.length;+ player.stop();+ expect(first.stopped).not.toBeNull(); // the live node was stopped+ drive(3); // interval is cleared → no further notes get scheduled+ expect(audio.oscillators).toHaveLength(scheduledSoFar);+ expect(player.isPlaying()).toBe(false);+ });++ it('does nothing (and reports ended) for a score with no notes', async () => {+ const ended = vi.fn();+ const player = createScorePlayer(parseScore('time: 4/4\n| |'), { onEnded: ended });+ await player.play();+ expect(audio.oscillators).toHaveLength(0);+ expect(ended).toHaveBeenCalled();+ });+});