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
feat([issue-2490]): synth playback with moving playhead for the MIDI piano-roll
[._.]/ Adam Eivy9a154af3b09f
diff --git a/client/src/components/songs/MidiPianoRoll.jsx b/client/src/components/songs/MidiPianoRoll.jsxindex 02af45ccd6..53e9f9ef5d 100644--- a/client/src/components/songs/MidiPianoRoll.jsx+++ b/client/src/components/songs/MidiPianoRoll.jsx@@ -57,8 +57,16 @@ const tooltipStyle = (x, y, width) => ({* @param {number} props.zoom — fit-relative multiplier (MIN_ZOOM..MAX_ZOOM).* @param {(next:number)=>void} props.onZoomChange — wheel/pinch zoom.* @param {number} props.height — total canvas height in px.+ * @param {boolean} [props.playing] — drives the rAF playhead loop (synth preview).+ * @param {()=>number} [props.getPosition] — live playback position in seconds+ * (stable reference; reads the MIDI player's position()).+ * @param {(sec:number)=>void} [props.onSeek] — playhead moved by tap/arrow keys.+ * @param {()=>void} [props.onTogglePlay] — Space pressed (play/pause).*/-export default function MidiPianoRoll({ data, chords, showChords, zoom, onZoomChange, height }) {+export default function MidiPianoRoll({+ data, chords, showChords, zoom, onZoomChange, height,+ playing = false, getPosition, onSeek, onTogglePlay,+}) {const wrapRef = useRef(null);const canvasRef = useRef(null);const scrollSecRef = useRef(0);@@ -72,6 +80,12 @@ export default function MidiPianoRoll({ data, chords, showChords, zoom, onZoomChconst [hover, setHover] = useState(null);const zoomRef = useRef(zoom);zoomRef.current = zoom;+ // Latest playback props without making them draw()/effect dependencies —+ // the parent hands fresh closures each render; the rAF loop reads refs.+ const getPositionRef = useRef(getPosition);+ getPositionRef.current = getPosition;+ const playingRef = useRef(playing);+ playingRef.current = playing;const duration = Math.max(data?.durationSec || 0, 0.001);const chordLaneH = showChords && chords?.length ? CHORD_H : 0;@@ -215,19 +229,37 @@ export default function MidiPianoRoll({ data, chords, showChords, zoom, onZoomCh}ctx.restore();- // Playhead (static scrub position in v1 — click to move).+ // Playhead — scrub position when idle, live audio position while playing+ // (the rAF loop mutates playheadSecRef from getPosition() each frame).const px = timeToX(playheadSecRef.current);if (px >= GUTTER_W && px <= width) {ctx.fillStyle = ACCENT;ctx.fillRect(px - 1, RULER_H, 2, height - RULER_H);}+ // Sounding pitches (playing only) — light their gutter rows below. Notes+ // are start-sorted, so the scan early-breaks at the playhead.+ let soundingMidis = null;+ if (playingRef.current) {+ soundingMidis = new Set();+ const pos = playheadSecRef.current;+ for (let i = 0; i < notes.length; i += 1) {+ const n = notes[i];+ if (n.startSec > pos) break;+ if (pos < n.startSec + n.durationSec) soundingMidis.add(n.midi);+ }+ }+// Pitch gutter on top (opaque, so notes pan "under" it).ctx.fillStyle = GUTTER_BG;ctx.fillRect(0, gridTop, GUTTER_W, gridH);ctx.textAlign = 'right';for (let m = lowMidi; m <= highMidi; m += 1) {const y = midiToY(m);+ if (soundingMidis?.has(m)) {+ ctx.fillStyle = 'rgba(59,130,246,0.45)';+ ctx.fillRect(0, y, GUTTER_W, Math.max(1, rowH));+ }if (m % 12 === 0 && rowH >= 3) {ctx.fillStyle = TEXT_DIM;ctx.font = '9px ui-sans-serif, system-ui, sans-serif';@@ -257,6 +289,36 @@ export default function MidiPianoRoll({ data, chords, showChords, zoom, onZoomChuseEffect(() => { draw(); }, [draw, zoom]);+ // Playback rAF loop: while playing, read the live audio position into the+ // playhead ref, page the view to keep it visible, and repaint each frame.+ // On pause/stop the loop tears down and one static frame pins the playhead+ // where the audio stopped (position() reports the resume offset).+ useEffect(() => {+ if (!playing) {+ if (getPositionRef.current) {+ playheadSecRef.current = getPositionRef.current() ?? 0;+ drawRef.current();+ }+ return undefined;+ }+ let raf = 0;+ const loop = () => {+ playheadSecRef.current = getPositionRef.current?.() ?? 0;+ // Page-turn follow: when the playhead exits the visible window (or a+ // seek lands outside it), snap the view so it re-enters near the left.+ const { gridW, pps, maxScroll } = geometry();+ const view = gridW / pps;+ const pos = playheadSecRef.current;+ if (pos < scrollSecRef.current || pos > scrollSecRef.current + view) {+ scrollSecRef.current = Math.min(Math.max(0, pos - view * 0.1), maxScroll);+ }+ drawRef.current();+ raf = requestAnimationFrame(loop);+ };+ raf = requestAnimationFrame(loop);+ return () => cancelAnimationFrame(raf);+ }, [playing, geometry]);+// Coalesce pan-driven repaints to one per animation frame — wheel/pointer// events can fire faster than the display presents.const rafRef = useRef(0);@@ -409,6 +471,7 @@ export default function MidiPianoRoll({ data, chords, showChords, zoom, onZoomChconst { pps, gridTop } = geometry();if (pos.x >= GUTTER_W && pos.y >= gridTop) {playheadSecRef.current = scrollSecRef.current + (pos.x - GUTTER_W) / pps;+ onSeek?.(playheadSecRef.current);setHoverIdentity(null);draw();}@@ -423,8 +486,12 @@ export default function MidiPianoRoll({ data, chords, showChords, zoom, onZoomChscrollSecRef.current += dir * (gridW / pps) * 0.5;} else {playheadSecRef.current = Math.min(duration, Math.max(0, playheadSecRef.current + dir * (10 / pps)));+ onSeek?.(playheadSecRef.current);}draw();+ } else if (e.key === ' ' && onTogglePlay) {+ e.preventDefault(); // keep Space from scrolling the page+ onTogglePlay();} else if (e.key === '+' || e.key === '=') {e.preventDefault();onZoomChange(clampZoom(zoomRef.current * ZOOM_STEP));@@ -452,7 +519,7 @@ export default function MidiPianoRoll({ data, chords, showChords, zoom, onZoomChclassName="block w-full rounded-lg bg-[#0c0c0e] touch-none cursor-crosshair focus:outline-none focus:ring-1 focus:ring-port-accent"tabIndex={0}role="img"- aria-label={`MIDI piano roll: ${data?.notes?.length || 0} notes, ${midiNoteName(data?.minMidi ?? 60)} to ${midiNoteName(data?.maxMidi ?? 71)}, ${formatTimecode(duration)} long. Use plus and minus to zoom, arrow keys to move the playhead, shift plus arrows to pan.`}+ aria-label={`MIDI piano roll: ${data?.notes?.length || 0} notes, ${midiNoteName(data?.minMidi ?? 60)} to ${midiNoteName(data?.maxMidi ?? 71)}, ${formatTimecode(duration)} long. Use plus and minus to zoom, arrow keys to move the playhead, shift plus arrows to pan${onTogglePlay ? ', space to play or pause' : ''}.`}onPointerDown={handlePointerDown}onPointerMove={handlePointerMove}onPointerUp={handlePointerUp}diff --git a/client/src/components/songs/MidiVisualization.jsx b/client/src/components/songs/MidiVisualization.jsxindex 973f38a6e3..a72a07911b 100644--- a/client/src/components/songs/MidiVisualization.jsx+++ b/client/src/components/songs/MidiVisualization.jsx@@ -1,6 +1,7 @@import { useMemo, useState } from 'react';-import { ChevronDown, ChevronRight, Download, Loader2, Maximize2, Minimize2, ZoomIn, ZoomOut } from 'lucide-react';+import { ChevronDown, ChevronRight, Download, Loader2, Maximize2, Minimize2, Pause, Play, ZoomIn, ZoomOut } from 'lucide-react';import useMidiNotes from '../../hooks/useMidiNotes';+import useMidiPlayer from '../../hooks/useMidiPlayer';import { detectChordWindows } from '../../lib/midiChords';import { midiNoteName } from '../../lib/pianoKeyboard';import { layerColor } from '../../lib/canvasRoll.js';@@ -42,6 +43,9 @@ export default function MidiVisualization({ url, filename, model }) {const [zoom, setZoom] = useState(MIN_ZOOM);const [showChords, setShowChords] = useState(true);const { status, data, error, reload } = useMidiNotes(open ? url : null);+ // Synth preview (#2490) — collapsing the panel nulls `data`, which tears the+ // player down, so audio never outlives the visible roll.+ const { playing, toggle, seek, getPosition } = useMidiPlayer(data);const chords = useMemo(() => chordsFor(data), [data]);@@ -67,6 +71,16 @@ export default function MidiVisualization({ url, filename, model }) {{open && (<><span className="mx-1 h-4 w-px bg-port-border" aria-hidden="true" />+ <button+ type="button"+ onClick={toggle}+ disabled={status !== 'ready'}+ aria-label={playing ? 'Pause playback' : 'Play synth preview'}+ className="p-1 rounded text-port-accent hover:bg-port-border/50 disabled:opacity-40"+ title={playing ? 'Pause (space)' : 'Play a synth preview (space)'}+ >+ {playing ? <Pause size={13} /> : <Play size={13} />}+ </button><button type="button" onClick={() => setZoom((z) => clampZoom(z / ZOOM_STEP))} aria-label="Zoom out"className="p-1 rounded text-gray-400 hover:text-white hover:bg-port-border/50" title="Zoom out (-)"><ZoomOut size={13} />@@ -132,6 +146,10 @@ export default function MidiVisualization({ url, filename, model }) {zoom={zoom}onZoomChange={setZoom}height={expanded ? EXPANDED_H : COMPACT_H}+ playing={playing}+ getPosition={getPosition}+ onSeek={seek}+ onTogglePlay={toggle}/><p className="sr-only">MIDI transcription: {data.notes.length} notes across {data.tracks.length} track{data.tracks.length === 1 ? '' : 's'},diff --git a/client/src/components/songs/MidiVisualization.test.jsx b/client/src/components/songs/MidiVisualization.test.jsxindex 64f497ccc6..730478491a 100644--- a/client/src/components/songs/MidiVisualization.test.jsx+++ b/client/src/components/songs/MidiVisualization.test.jsx@@ -32,6 +32,23 @@ const makeCtx = () => ({fillStyle: '', strokeStyle: '', lineWidth: 1, font: '', textAlign: '', globalAlpha: 1,});+// jsdom has no Web Audio — minimal fake for the synth-preview player (same+// shape as midiPlayback.test.js, static clock is enough for UI wiring tests).+const fakeParam = () => ({ setValueAtTime: vi.fn(), exponentialRampToValueAtTime: vi.fn() });+function FakeAudioContext() {+ return {+ state: 'running',+ resume: () => Promise.resolve(),+ currentTime: 0,+ destination: {},+ createOscillator: () => ({+ type: '', frequency: fakeParam(), onended: null,+ connect: (t) => t, start: vi.fn(), stop: vi.fn(),+ }),+ createGain: () => ({ gain: fakeParam(), connect: (t) => t }),+ };+}+describe('<MidiVisualization>', () => {let ctx;beforeEach(() => {@@ -39,6 +56,7 @@ describe('<MidiVisualization>', () => {ctx = makeCtx();vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue(ctx);vi.stubGlobal('ResizeObserver', class { observe() {} disconnect() {} });+ vi.stubGlobal('AudioContext', FakeAudioContext);Object.defineProperty(HTMLElement.prototype, 'clientWidth', { configurable: true, get() { return 800; } });vi.stubGlobal('fetch', vi.fn(() => Promise.resolve({ok: true,@@ -103,4 +121,42 @@ describe('<MidiVisualization>', () => {fireEvent.click(screen.getByLabelText('Fit to width'));expect(ctx.clearRect).toHaveBeenCalled();});++ it('play button starts the synth preview and toggles to pause (#2490)', async () => {+ render(<MidiVisualization url="/uploads/test.mid" />);+ // Disabled until the parse is ready.+ expect(screen.getByLabelText('Play synth preview').disabled).toBe(true);+ await screen.findByText(/3 notes · /);+ const play = screen.getByLabelText('Play synth preview');+ expect(play.disabled).toBe(false);+ fireEvent.click(play);+ const pause = await screen.findByLabelText('Pause playback');+ fireEvent.click(pause);+ expect(await screen.findByLabelText('Play synth preview')).toBeTruthy();+ });++ it('Space on the focused roll toggles playback', async () => {+ render(<MidiVisualization url="/uploads/test.mid" />);+ await screen.findByText(/3 notes · /);+ const canvas = screen.getByRole('img');+ expect(canvas.getAttribute('aria-label')).toMatch(/space to play or pause/);+ fireEvent.keyDown(canvas, { key: ' ' });+ const pause = await screen.findByLabelText('Pause playback');+ fireEvent.keyDown(canvas, { key: ' ' });+ expect(await screen.findByLabelText('Play synth preview')).toBeTruthy();+ expect(pause).toBeTruthy();+ });++ it('collapsing the panel tears playback down with it', async () => {+ render(<MidiVisualization url="/uploads/test.mid" />);+ await screen.findByText(/3 notes · /);+ fireEvent.click(screen.getByLabelText('Play synth preview'));+ await screen.findByLabelText('Pause playback');+ fireEvent.click(screen.getByLabelText('Collapse MIDI visualization'));+ // Roll + transport gone; re-expanding comes back idle (not still "playing").+ expect(screen.queryByLabelText('Pause playback')).toBeNull();+ fireEvent.click(screen.getByLabelText('Expand MIDI visualization'));+ await screen.findByText(/3 notes · /);+ expect(screen.getByLabelText('Play synth preview')).toBeTruthy();+ });});diff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex ea0f2a3158..afda010b91 100644--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@ -160,3 +160,4 @@ grep -i "what you want to do" client/src/hooks/README.md| `useMidiTranscription` | One audio → MIDI transcription job slot (MuScriptor): start/cancel + SSE stage progress + terminal-frame handling, generic over the Rounds and Music Video API surfaces (pass `startRequest`/`eventsUrl`/`cancelRequest`). Returns `{ active, stage, stageLabel, context, start(context), cancel }` (`stageLabel` is the ready-to-render human label for the current STAGE — including a distinct "Downloading model…" for the first-use weight download, which also fires a one-time toast; `context` is the in-flight job's captured target, for per-target UI gates); `onComplete(frame, context)` fires with the terminal frame (`filename`, `model`, any server-merged extras). | The Rounds reference "Transcribe MIDI" control and the Music Video MIDI button. || `useCanvasDprSize` | DevicePixelRatio-aware canvas sizing shared by the piano-roll renderers (`<PianoRoll>`, `<MidiPianoRoll>`): sizes the bitmap to container-width × height at the DPR, applies the transform, and redraws via a `drawRef` on mount + every `ResizeObserver` resize (observer created once per height, never churned by draw-closure changes). Returns a ref holding the current CSS width so draw code doesn't measure the DOM per frame. | Both piano-roll canvases. || `useMidiNotes` | Fetch + parse a transcribed `.mid` file into the piano-roll view-model (`parseMidiFile` in `lib/midiNotes.js`), with a module-level per-URL cache so remounts (collapse, tab switches) don't refetch/reparse. Returns `{ status: 'idle'\|'loading'\|'ready'\|'error', data, error, reload }`; a generation counter drops stale in-flight responses on URL change/unmount. Plain `fetch` of the static file URL — errors surface inline, never as toasts (#2477). | `<MidiVisualization>` (Rounds ReferenceAnalysis + Music Video). |+| `useMidiPlayer` | React wrapper over `lib/midiPlayback.js` (#2490): one synth player per parsed MIDI view-model, torn down when the data changes/unmounts so oscillators never outlive the roll. Returns `{ playing, toggle, seek(sec), getPosition }` — `getPosition` is the stable ref the `<MidiPianoRoll>` rAF playhead reads; no AudioContext is touched until the first toggle. A resume failure resets `playing` instead of lying. | `<MidiVisualization>` (Rounds ReferenceAnalysis + Music Video). |diff --git a/client/src/hooks/index.js b/client/src/hooks/index.jsindex ec45e7a2a6..6b0e0bd0db 100644--- a/client/src/hooks/index.js+++ b/client/src/hooks/index.js@@ -51,6 +51,7 @@ export { default as useYoutubeTrackImport } from './useYoutubeTrackImport.js';export { default as useReferenceAudioImport } from './useReferenceAudioImport.js';export { default as useMidiTranscription } from './useMidiTranscription.js';export { default as useMidiNotes } from './useMidiNotes.js';+export { default as useMidiPlayer } from './useMidiPlayer.js';export { default as useCanvasDprSize } from './useCanvasDprSize.js';// === Mixed (both default and named) — surface both ===diff --git a/client/src/hooks/useMidiPlayer.js b/client/src/hooks/useMidiPlayer.jsnew file mode 100644index 0000000000..0ca64a1316--- /dev/null+++ b/client/src/hooks/useMidiPlayer.js@@ -0,0 +1,52 @@+import { useCallback, useEffect, useRef, useState } from 'react';+import { createMidiPlayer } from '../lib/midiPlayback.js';++// React wrapper over lib/midiPlayback.js for the MIDI visualization (#2490):+// owns one player per parsed view-model, exposes play/pause + seek + a stable+// getPosition for the <MidiPianoRoll> rAF playhead, and tears the player down+// when the data changes or the host unmounts so oscillators never outlive the+// file they preview. No audio is touched until the first toggle — the player+// only reaches for the AudioContext inside play().++/**+ * @param {object|null} data — parseMidiFile view-model (null while loading/collapsed).+ * @returns {{ playing:boolean, toggle:()=>void, seek:(sec:number)=>void,+ * getPosition:()=>number }}+ */+export default function useMidiPlayer(data) {+ const [playing, setPlaying] = useState(false);+ const playerRef = useRef(null);++ useEffect(() => {+ if (!data) return undefined;+ const player = createMidiPlayer(data, { onEnded: () => setPlaying(false) });+ playerRef.current = player;+ return () => {+ player.stop();+ if (playerRef.current === player) playerRef.current = null;+ setPlaying(false);+ };+ }, [data]);++ const toggle = useCallback(() => {+ const player = playerRef.current;+ if (!player) return;+ if (player.isPlaying()) {+ player.pause();+ setPlaying(false);+ } else {+ setPlaying(true);+ // play() resolves once playback has STARTED; a resume failure (autoplay+ // policy edge) lands here — reset the button instead of lying "playing".+ player.play().catch((err) => {+ console.error(`🎹 MIDI preview failed to start: ${err.message}`);+ setPlaying(false);+ });+ }+ }, []);++ const seek = useCallback((sec) => { playerRef.current?.seek(sec); }, []);+ const getPosition = useCallback(() => playerRef.current?.position() ?? 0, []);++ return { playing, toggle, seek, getPosition };+}diff --git a/client/src/hooks/useMidiPlayer.test.jsx b/client/src/hooks/useMidiPlayer.test.jsxnew file mode 100644index 0000000000..0031e94b5e--- /dev/null+++ b/client/src/hooks/useMidiPlayer.test.jsx@@ -0,0 +1,98 @@+import { renderHook, act } from '@testing-library/react';+import { describe, it, expect, vi, beforeEach } from 'vitest';+import useMidiPlayer from './useMidiPlayer.js';+import { createMidiPlayer } from '../lib/midiPlayback.js';++vi.mock('../lib/midiPlayback.js', () => ({ createMidiPlayer: vi.fn() }));++// One fake player per createMidiPlayer call, capturing the onEnded wiring.+const makeFakePlayer = () => {+ let playing = false;+ return {+ play: vi.fn(() => { playing = true; return Promise.resolve(); }),+ pause: vi.fn(() => { playing = false; }),+ stop: vi.fn(() => { playing = false; }),+ seek: vi.fn(),+ position: vi.fn(() => 1.25),+ duration: vi.fn(() => 10),+ isPlaying: () => playing,+ };+};++describe('useMidiPlayer', () => {+ let players;+ beforeEach(() => {+ players = [];+ createMidiPlayer.mockReset();+ createMidiPlayer.mockImplementation((data, opts) => {+ const p = { ...makeFakePlayer(), onEnded: opts?.onEnded, data };+ players.push(p);+ return p;+ });+ });++ const DATA = { durationSec: 10, notes: [{ midi: 60, startSec: 0, durationSec: 1 }] };++ it('is inert without data (no player, toggle is a no-op)', () => {+ const { result } = renderHook(() => useMidiPlayer(null));+ expect(createMidiPlayer).not.toHaveBeenCalled();+ act(() => result.current.toggle());+ expect(result.current.playing).toBe(false);+ expect(result.current.getPosition()).toBe(0);+ });++ it('toggle plays, then pauses; getPosition reads the player', async () => {+ const { result } = renderHook(() => useMidiPlayer(DATA));+ await act(async () => result.current.toggle());+ expect(players[0].play).toHaveBeenCalledTimes(1);+ expect(result.current.playing).toBe(true);+ expect(result.current.getPosition()).toBe(1.25);+ await act(async () => result.current.toggle());+ expect(players[0].pause).toHaveBeenCalledTimes(1);+ expect(result.current.playing).toBe(false);+ });++ it('resets the playing flag when the player reports ended', async () => {+ const { result } = renderHook(() => useMidiPlayer(DATA));+ await act(async () => result.current.toggle());+ expect(result.current.playing).toBe(true);+ act(() => players[0].onEnded());+ expect(result.current.playing).toBe(false);+ });++ it('tears the player down (stop) when the data changes, and builds a new one', async () => {+ const NEXT = { durationSec: 5, notes: [] };+ const { result, rerender } = renderHook(({ data }) => useMidiPlayer(data), {+ initialProps: { data: DATA },+ });+ await act(async () => result.current.toggle());+ rerender({ data: NEXT });+ expect(players[0].stop).toHaveBeenCalled();+ expect(result.current.playing).toBe(false);+ expect(createMidiPlayer).toHaveBeenCalledTimes(2);+ expect(players[1].data).toBe(NEXT);+ });++ it('stops the player on unmount', async () => {+ const { result, unmount } = renderHook(() => useMidiPlayer(DATA));+ await act(async () => result.current.toggle());+ unmount();+ expect(players[0].stop).toHaveBeenCalled();+ });++ it('resets the playing flag when play() rejects (autoplay policy edge)', async () => {+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});+ const { result } = renderHook(() => useMidiPlayer(DATA));+ players[0].play.mockImplementation(() => Promise.reject(new Error('denied')));+ await act(async () => { result.current.toggle(); });+ expect(result.current.playing).toBe(false);+ expect(consoleError).toHaveBeenCalled();+ consoleError.mockRestore();+ });++ it('seek forwards to the player', async () => {+ const { result } = renderHook(() => useMidiPlayer(DATA));+ act(() => result.current.seek(3.5));+ expect(players[0].seek).toHaveBeenCalledWith(3.5);+ });+});diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex 02e87abbc6..6e22fb439e 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -106,6 +106,7 @@ grep -i "what you want to do" client/src/lib/README.md| Module | Purpose ||---|---|+| `audioContext.js` | `getAudioContext()` — the ONE app-wide lazy Web Audio `AudioContext` singleton every playback feature shares (`songPlayback`, `scorePlayback`, `metronome`, `midiPlayback`). Browsers cap live contexts and one context = one sample clock, so simultaneous features stay aligned. Constructor resolved lazily (`window` → `globalThis`) so node-env test runs import cleanly; tests inject a fake via `vi.stubGlobal('AudioContext', …)` before first call. || `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. || `canvasRoll.js` | Shared canvas helpers for the two piano-roll renderers (`<PianoRoll>` falling-note + `<MidiPianoRoll>` DAW-style, #2477). `layerColor(index)` — the per-layer/track palette (8 hues, wraps both directions) used by note bars, keyboards, and legends; `roundRect(ctx, x, y, w, h, r)` — rounded-rect path with `ctx.roundRect` feature-detect and arcTo fallback. Pure canvas math/palette, no React. || `colorMatch.js` | Pure grading core for the song system's color-match training mode: `buildColorMatchTimeline(score, { bpm })` → `{ notes, totalMs, msPerQuarter, bpm }` (each note's target frequency + onset/offset window in ms, keyed by the same global note index the renderer flattens, timing mirroring `scorePlayback`); `gradeNote(hz, targetHz)` classifies a sung pitch against a target into `in-tune`/`close`/`off`/`missed` (octave-folded, thresholds `MATCH_IN_TUNE_CENTS`/`MATCH_CLOSE_CENTS`); `noteAtTime(timeline, tMs, fromIdx)` finds the active note for a rAF cursor; `summarizeAccuracy(grades)` → `{ graded, counts, percentInTune, perNote }` per-take summary (`perNote` is the ordered grade list a saved take persists, mirroring the server sanitizer); `gradesFromPerNote(timeline, perNote)` is its inverse — rebuilds the noteIndex→grade map to repaint a saved take's grading on open without re-grading audio; plus `centsBetween` and the `GRADE` enum. No React, no audio — the `useColorMatch` hook drives it. |@@ -117,6 +118,7 @@ grep -i "what you want to do" client/src/lib/README.md| `metronome.js` | Sample-accurate Web Audio metronome — the shared timing grid for the song system and first consumer of the song `tempo` field. `createMetronome({ bpm, beatsPerBar, countInBars, onBeat, onCountInComplete })` lookahead-schedules accented click tones on the shared `AudioContext` clock (same pattern as `songPlayback.js`), emits `{ beat, bar, accent, countIn, whenAudioTime }` per beat (the beat-clock callback color-match/sing-to-score subscribe to), and tears down all timers on `stop()`. Plus `clampBpm` (20–320), `secondsPerBeat`, `timeSignatureFromScore`, `beatDescriptor`. || `midiChords.js` | Chord detection for the MIDI visualization UI (#2477). `detectChordWindows(notes, { minWindowSec })` sweeps the normalized note list for maximal spans where ≥2 distinct pitch classes sound simultaneously → `[{ startSec, endSec, label, midis }]` (adjacent same-label windows merged); `nameChord(pcs, bassPc)` maps a pitch-class set to a compact symbol (maj/min/dim/aug triads, maj7/7/m7/m7b5/dim7, sus2/sus4/add9, slash-chord inversions) and falls back to sorted pitch-class names (`C E G#`) rather than guessing wrong; `chordNoteNames(midis)` for tooltips. Pure — no canvas/React. || `midiNotes.js` | Minimal Standard MIDI File parser + normalizer for the MIDI visualization UI (#2477) — in-tree, zero deps. `parseMidiFile(arrayBuffer)` parses SMF format 0/1 (running status, note-on vel-0-as-off, tempo map incl. mid-file changes, SMPTE division, track names) into the piano-roll view-model `{ durationSec, minMidi, maxMidi, notes:[{id,midi,startSec,durationSec,velocity,track,name}], tracks, tempos }`. Throws on non-MIDI bytes. Consumed by `useMidiNotes` → `<MidiPianoRoll>`. NOT the lead-sheet parser (`scoreNotation.js`). |+| `midiPlayback.js` | Synth preview of a transcribed `.mid` (#2490) — `createMidiPlayer(data, { onEnded })` plays the `parseMidiFile` view-model as velocity-scaled oscillator tones through a per-play master bus on the shared `AudioContext`, with the same lookahead-scheduler idiom + tone envelope (`scheduleTone`) as `scorePlayback.js`. Transport: `play`/`pause`/`stop`/`seek(sec)` (seek re-anchors a running transport and sounds the tails of notes sustaining across the seek point), `position()`/`duration()` for the `<MidiPianoRoll>` moving playhead. Pure (no React) — `useMidiPlayer` wraps it. || `pianoKeyboard.js` | Piano-keyboard geometry for the song system's Synthesia-style piano-roll visualizer (`<PianoRoll>`). Pure math, no canvas/React. `keyboardRange(midis, { minSemitones })` → `{ lowMidi, highMidi }` padded out to whole C–B octaves (min 2) so the keyboard always starts on a C / ends on a B and never collapses for a one-note part; `buildKeyboardLayout({ lowMidi, highMidi, width })` → `{ keys:[{midi,isBlack,x,w}], whiteWidth, blackWidth }` (white keys tiled edge-to-edge, black keys overlaid centered on the boundary, narrower); plus `isBlackKey(midi)`, `midiNoteName(midi)` (sharps spelling), `pitchClass(midi)` (positive modulo), the canonical `PITCH_CLASS_NAMES` table (re-exported by `referenceAnalysis.js`, consumed by `midiChords.js` — single source for note/chord spelling), and the `BLACK_KEY_RATIO`/`BLACK_KEY_HEIGHT_RATIO` constants. Pairs with `scorePlayback`'s per-note `midi` field. || `referenceAnalysis.js` | Reference-audio analysis for the Rounds workbench (#2106) — pure DSP + diff helpers behind the "analyze a reference's attached audio" view. `extractPitchTrack(samples, sampleRate, { startMs, endMs, hopMs })` frames decoded PCM through `detectFrequency` offline (faster than realtime) into the `[{ tMs, hz, clarity }]` shape `singToScore` consumes; `proposeSegmentScore(samples, sampleRate, { startMs, endMs, bpm, key })` runs the solo-segment pipeline (extract → `transcribePitchTrack` on the round's tempo/key grid) → `{ track, body, text }`; `buildScoreText({ key, tempo, body })` wraps a transcribed body in a lead-sheet header; `barPitchClasses(scoreText)` / `diffScoreBars(proposed, existing)` compare a proposed part against a stored scorePart per bar by octave-collapsed pitch-class sequence (drives the review diff highlighting). Stacked-mix extraction (#2121, spectral diff v2): `magnitudeSpectrum(frame, { fftSize })` (hand-rolled radix-2 FFT, Hann-windowed) / `averageMagnitudeSpectrum(samples, sampleRate, { startMs, endMs })` build a backing profile; `estimateSpectralF0(mag, sampleRate, fftSize)` picks the fundamental by weighted (1/k) harmonic sum (octave-robust); `extractSpectralDiffTrack(samples, sampleRate, { startMs, endMs, bgStartMs, bgEndMs })` subtracts the backing profile per frame and estimates f0 on the residual to recover a voice that never plays solo; `proposeStackedSegmentScore(...)` is its `proposeSegmentScore` counterpart. Zero LLM calls — pure local DSP. || `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. |diff --git a/client/src/lib/audioContext.js b/client/src/lib/audioContext.jsnew file mode 100644index 0000000000..b6eac24ea5--- /dev/null+++ b/client/src/lib/audioContext.js@@ -0,0 +1,30 @@+// The ONE app-wide Web Audio AudioContext, created lazily on first use.+// Browsers cap the number of live contexts (~6), and every playback feature+// sharing a single context also shares a single sample clock — so features+// that sound together (metronome + score synth, MIDI preview over a round)+// stay aligned for free. Consumed by songPlayback.js, scorePlayback.js,+// metronome.js, and midiPlayback.js — new audio features should import this+// instead of growing another module-level singleton.+//+// The constructor is resolved lazily and never touches a bare `window` at+// module load — the server's vitest run globs lib tests in the node+// environment (no jsdom), where `window` is undefined. Tests inject a fake+// via vi.stubGlobal('AudioContext', …) before the first call; the singleton+// then caches that fake for the life of the test file's module registry.++let sharedCtx = null;++/**+ * The shared AudioContext. Autoplay policies start it suspended until a user+ * gesture — callers resume() it on play, not here.+ */+export function getAudioContext() {+ if (!sharedCtx) {+ const Ctor =+ (typeof window !== 'undefined' && (window.AudioContext || window.webkitAudioContext)) ||+ globalThis.AudioContext ||+ globalThis.webkitAudioContext;+ sharedCtx = new Ctor();+ }+ return sharedCtx;+}diff --git a/client/src/lib/index.js b/client/src/lib/index.jsindex e38bf28f98..4d3469674c 100644--- a/client/src/lib/index.js+++ b/client/src/lib/index.js@@ -76,6 +76,7 @@ export * from './upsertByIdPrepend.js';export * from './voiceLabel.js';// === Page-scoped pure helpers ===+export * from './audioContext.js';export * from './cityPlaybackFrame.js';export * from './canvasRoll.js';export * from './colorMatch.js';@@ -85,6 +86,7 @@ export * from './lossSparkline.js';export * from './metronome.js';export * from './midiChords.js';export * from './midiNotes.js';+export * from './midiPlayback.js';export * from './pianoKeyboard.js';export * from './pitchDetect.js';export * from './referenceAnalysis.js';diff --git a/client/src/lib/metronome.js b/client/src/lib/metronome.jsindex 8a08998ca4..28c29ce5a7 100644--- a/client/src/lib/metronome.js+++ b/client/src/lib/metronome.js@@ -15,6 +15,7 @@// same grid. Pure-ish: no React; the <Metronome> component wraps it for UI.import { parseScore } from './scoreNotation.js';+import { getAudioContext as audioContext } from './audioContext.js';// BPM band — mirrors the server `tempo` validation (services/rounds.js// TEMPO_MIN / TEMPO_MAX, also enforced by the Zod schema in routes/rounds.js).@@ -27,24 +28,9 @@ const LOOKAHEAD_MS = 25; // how often the lookahead timer wakesconst SCHEDULE_AHEAD_S = 0.12; // how far ahead of `currentTime` we schedule audioconst START_LEAD_S = 0.1; // small lead before the first beat absorbs jitter-// Lazily create + reuse one AudioContext for the metronome's clicks. Browsers-// cap the number of contexts; reusing one keeps every click on the same clock.-let sharedCtx = null;-function audioContext() {- if (!sharedCtx) {- // Resolve the constructor lazily and never touch a bare `window` at module- // load — the server's vitest run globs this file's tests in the node- // environment (no jsdom), where `window` is undefined. Guard with- // `typeof window` and fall back to `globalThis` so the pure exports import- // cleanly and tests can inject a fake via globalThis.AudioContext.- const Ctor =- (typeof window !== 'undefined' && (window.AudioContext || window.webkitAudioContext)) ||- globalThis.AudioContext ||- globalThis.webkitAudioContext;- sharedCtx = new Ctor();- }- return sharedCtx;-}+// The app-wide shared AudioContext (imported at top from audioContext.js) —+// reusing one keeps every click on the same clock as the other playback+// features.// Clamp a BPM into the supported band. Returns null for non-numbers so a caller// can distinguish "no/invalid value" from a legitimately-clamped number.diff --git a/client/src/lib/midiPlayback.js b/client/src/lib/midiPlayback.jsnew file mode 100644index 0000000000..706fa1a8cf--- /dev/null+++ b/client/src/lib/midiPlayback.js@@ -0,0 +1,188 @@+// Synth preview of a transcribed MIDI file (#2490) — turns the parseMidiFile+// view-model (midiNotes.js) into audible oscillator tones with a live+// `position()` the <MidiPianoRoll> reads for its moving playhead. Companion to+// scorePlayback.js: that synthesizes the WRITTEN lead-sheet melody, this+// synthesizes the TRANSCRIBED .mid; both reuse the same lookahead-scheduler+// idiom, tone envelope (scheduleTone), and the one app-wide AudioContext.+// Pure (no React) — useMidiPlayer wraps it in a hook.++import { getAudioContext as ctx } from './audioContext.js';+import { scheduleTone, midiToFreq } from './scorePlayback.js';++// 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(`🎹 MIDI playback callback failed: ${err.message}`); }+};++const LEAD = 0.08; // seconds of lead-in before t=0 sounds+const LOOKAHEAD_MS = 25; // how often the scheduler wakes+const SCHEDULE_AHEAD = 0.12; // seconds of audio scheduled past "now"+const MIN_TONE_SEC = 0.05; // floor so zero/near-zero-length notes still tick+const TONE_PEAK = 0.16; // per-voice peak at full velocity (polyphonic sum)++// Velocity → per-tone gain peak. A floor keeps ppp notes audible; the master+// bus (fixed, below) keeps a dense chord from clipping the sum.+const peakFor = (velocity) => TONE_PEAK * (0.35 + 0.65 * (Number.isFinite(velocity) ? velocity : 0.8));+const MASTER_GAIN = 0.9;++/**+ * Build a synth player over a parsed MIDI view-model.+ *+ * @param {object} data — output of `parseMidiFile` ({ notes, durationSec });+ * notes are sorted by startSec, which the scheduler cursor relies on.+ * @param {object} [options]+ * @param {()=>void} [options.onEnded] — called once when playback reaches the end.+ * @returns {{ play, pause, stop, seek, isPlaying, position, duration }}+ */+export const createMidiPlayer = (data, options = {}) => {+ const { onEnded } = options;+ const notes = (data?.notes || []).filter((n) => Number.isFinite(n?.midi) && Number.isFinite(n?.startSec));+ const totalSec = Math.max(data?.durationSec || 0, 0);++ let playing = false;+ let interval = null;+ let startTime = 0; // ctx time at which t=0 plays+ let offsetSec = 0; // resume position (seconds into the file)+ let nextIdx = 0; // next note to hand to the oscillator scheduler+ let master = null; // per-play master bus GainNode+ let nodes = []; // live { osc, gain } for teardown+ // Bumped on every stop/pause; play() captures it before its `await ctx.resume()`+ // and bails if a teardown landed during that await (same guard as scorePlayback).+ let playToken = 0;++ 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; }+ };++ const playTone = (midi, startAt, durSec, velocity) => {+ const freq = midiToFreq(midi);+ if (!freq) return;+ const entry = scheduleTone(ctx(), freq, startAt, Math.max(durSec, MIN_TONE_SEC), master, peakFor(velocity));+ entry.osc.onended = () => { nodes = nodes.filter((n) => n !== entry); };+ nodes.push(entry);+ };++ // Position the scheduler cursor at the first note starting at/after `offset`,+ // and immediately sound the tails of notes already sustaining across it —+ // seeking into a held chord should be audible, not silent until the next+ // onset. Notes are start-sorted, so the tail scan can't early-break; it's a+ // one-time O(n) pass per seek/play, not per tick.+ const seekCursors = (offset, { soundTails } = {}) => {+ let idx = notes.findIndex((n) => n.startSec >= offset - 1e-6);+ if (idx < 0) idx = notes.length;+ nextIdx = idx;+ if (!soundTails) return;+ const now = ctx().currentTime;+ for (let i = 0; i < idx; i += 1) {+ const n = notes[i];+ const remaining = n.startSec + n.durationSec - offset;+ if (remaining > 1e-3) playTone(n.midi, now, remaining, n.velocity);+ }+ };++ // One scheduler tick: hand any due tones to the audio clock, finish at the end.+ const tick = () => {+ const now = ctx().currentTime;+ while (nextIdx < notes.length) {+ const n = notes[nextIdx];+ const at = startTime + n.startSec;+ if (at > now + SCHEDULE_AHEAD) break;+ playTone(n.midi, Math.max(at, now), n.durationSec, n.velocity);+ nextIdx += 1;+ }+ if (now - startTime >= totalSec) finish();+ };++ // Natural end — reset to the top and notify.+ function finish() {+ clearTick();+ stopNodes();+ master = null;+ playing = false;+ offsetSec = 0;+ nextIdx = 0;+ safeCall(onEnded);+ }++ const play = async () => {+ if (playing) return;+ const c = ctx();+ const token = ++playToken;+ if (c.state === 'suspended' && c.resume) await c.resume();+ if (token !== playToken) return; // a stop/pause landed during the resume await+ if (!notes.length || totalSec <= 0) { safeCall(onEnded); return; }++ master = c.createGain();+ master.gain.setValueAtTime(MASTER_GAIN, c.currentTime);+ master.connect(c.destination);++ playing = true;+ startTime = c.currentTime + LEAD - offsetSec;+ seekCursors(offsetSec, { soundTails: offsetSec > 0 });+ tick(); // schedule the immediate window now so playback starts promptly+ interval = setInterval(tick, LOOKAHEAD_MS);+ };++ // Pause — stop sounding, remember position for resume.+ const pause = () => {+ playToken++; // abort an in-flight play() still awaiting ctx.resume()+ if (!playing) return;+ offsetSec = Math.min(Math.max(0, ctx().currentTime - startTime), totalSec);+ clearTick();+ stopNodes();+ master = null;+ playing = false;+ };++ // Stop — full teardown back to the top.+ const stop = () => {+ playToken++; // abort an in-flight play() still awaiting ctx.resume()+ clearTick();+ stopNodes();+ master = null;+ playing = false;+ offsetSec = 0;+ nextIdx = 0;+ };++ // Jump to a position. While playing this re-anchors the running transport+ // (silences what's sounding, re-schedules from the new point); while idle it+ // just moves the resume offset so the next play() starts there.+ const seek = (sec) => {+ const clamped = Math.min(Math.max(0, Number.isFinite(sec) ? sec : 0), totalSec);+ if (!playing) { offsetSec = clamped; return; }+ stopNodes();+ startTime = ctx().currentTime - clamped;+ seekCursors(clamped, { soundTails: true });+ tick();+ };++ // Current playback head in file-seconds, for the moving playhead. During the+ // LEAD-in before t=0 sounds this is negative (down to −LEAD) — intentionally+ // not clamped, so the playhead doesn't jump ahead of the first audible note.+ const position = () => (playing+ ? Math.min(ctx().currentTime - startTime, totalSec)+ : offsetSec);++ return {+ play,+ pause,+ stop,+ seek,+ isPlaying: () => playing,+ position,+ duration: () => totalSec,+ };+};diff --git a/client/src/lib/midiPlayback.test.js b/client/src/lib/midiPlayback.test.jsnew file mode 100644index 0000000000..a18e05713f--- /dev/null+++ b/client/src/lib/midiPlayback.test.js@@ -0,0 +1,163 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { createMidiPlayer } from './midiPlayback.js';++// jsdom/node has no Web Audio. Same fake as scorePlayback.test.js: records+// created oscillators + gain envelopes and exposes a controllable clock so the+// lookahead scheduler can be driven deterministically with fake timers.+const audio = { now: 0, oscillators: [], gains: [] };+const fakeParam = () => {+ const values = [];+ return {+ values,+ setValueAtTime: (v) => values.push(v),+ exponentialRampToValueAtTime: (v) => values.push(v),+ };+};+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() {+ const gain = { gain: fakeParam(), connect: (t) => t };+ audio.gains.push(gain);+ return gain;+ },+ };+}++// Advance the audio clock RELATIVELY (unlike scorePlayback.test.js's absolute+// drive) — several cases here pause/seek and drive again, and an absolute+// drive would rewind currentTime.+const drive = (deltaSec) => {+ const target = audio.now + deltaSec;+ for (let t = audio.now + 0.1; t <= target + 1e-9; t += 0.1) {+ audio.now = Number(t.toFixed(3));+ vi.advanceTimersByTime(100);+ }+};++// C-E-G in sequence, then a long sustained C3 under the last note — 2 s total.+const DATA = {+ durationSec: 2,+ notes: [+ { id: 'a', midi: 60, startSec: 0, durationSec: 0.5, velocity: 1.0, track: 0 },+ { id: 'b', midi: 64, startSec: 0.5, durationSec: 0.5, velocity: 0.0, track: 0 },+ { id: 'c', midi: 48, startSec: 0.5, durationSec: 1.5, velocity: 0.8, track: 0 },+ { id: 'd', midi: 67, startSec: 1.0, durationSec: 1.0, velocity: 0.8, track: 0 },+ ],+};++describe('createMidiPlayer', () => {+ beforeEach(() => {+ audio.now = 0;+ audio.oscillators = [];+ audio.gains = [];+ vi.stubGlobal('AudioContext', FakeAudioContext);+ vi.useFakeTimers();+ });+ afterEach(() => { vi.useRealTimers(); vi.unstubAllGlobals(); });++ it('schedules an oscillator per note and finishes with onEnded + position reset', async () => {+ const ended = vi.fn();+ const player = createMidiPlayer(DATA, { onEnded: ended });+ await player.play();+ drive(3); // run past durationSec (2 s)+ expect(audio.oscillators).toHaveLength(4);+ expect(ended).toHaveBeenCalledTimes(1);+ expect(player.isPlaying()).toBe(false);+ expect(player.position()).toBe(0); // natural end resets to the top+ });++ it('scales the tone peak by velocity (louder note ramps to a higher gain)', async () => {+ const player = createMidiPlayer(DATA);+ await player.play();+ drive(1);+ // Per-tone gains follow the per-play master gain in creation order. The+ // envelope's peak value appears in the recorded param values.+ const [, loud, quiet] = audio.gains; // [master, note a (vel 1.0), note b (vel 0.0), ...]+ expect(Math.max(...loud.gain.values)).toBeGreaterThan(Math.max(...quiet.gain.values));+ player.stop();+ });++ it('pause remembers the position and play resumes from it', async () => {+ const player = createMidiPlayer(DATA);+ await player.play();+ drive(1.0);+ player.pause();+ expect(player.isPlaying()).toBe(false);+ const at = player.position();+ expect(at).toBeGreaterThan(0.5);+ const before = audio.oscillators.length;+ drive(2.0); // interval cleared — nothing further schedules+ expect(audio.oscillators).toHaveLength(before);+ await player.play();+ // Right after resume the position sits at the pause point minus the LEAD+ // pre-roll (position() is deliberately not clamped during the lead-in).+ expect(player.position()).toBeGreaterThan(at - 0.12);+ expect(player.position()).toBeLessThanOrEqual(at);+ player.stop();+ });++ it('stop() cancels the lookahead interval and silences live nodes', async () => {+ const player = createMidiPlayer(DATA);+ await player.play();+ const first = audio.oscillators[0];+ const scheduledSoFar = audio.oscillators.length;+ player.stop();+ expect(first.stopped).not.toBeNull();+ drive(3);+ expect(audio.oscillators).toHaveLength(scheduledSoFar);+ expect(player.position()).toBe(0);+ });++ it('seek while idle moves the resume point; play sounds the sustaining tails', async () => {+ const player = createMidiPlayer(DATA);+ player.seek(1.2); // mid-way through notes c (0.5–2.0) and d (1.0–2.0)+ expect(player.position()).toBeCloseTo(1.2, 6);+ await player.play();+ // Tails of c and d sound immediately even though their onsets are past.+ expect(audio.oscillators.length).toBeGreaterThanOrEqual(2);+ drive(0.1);+ // Notes a and b (fully before the seek point) never schedule.+ const freqs = audio.oscillators.flatMap((o) => o.frequency.values);+ expect(freqs.some((f) => Math.abs(f - 261.626) < 0.01)).toBe(false); // C4 (note a)+ player.stop();+ });++ it('seek while playing re-anchors the transport at the new position', async () => {+ const player = createMidiPlayer(DATA);+ await player.play();+ drive(0.3);+ player.seek(1.5);+ expect(player.position()).toBeCloseTo(1.5, 3);+ expect(player.isPlaying()).toBe(true);+ drive(1.0); // 0.5 s of playback left → natural finish+ expect(player.isPlaying()).toBe(false);+ });++ it('clamps a seek beyond the file to its duration', () => {+ const player = createMidiPlayer(DATA);+ player.seek(99);+ expect(player.position()).toBe(2);+ player.seek(-5);+ expect(player.position()).toBe(0);+ });++ it('reports ended immediately for an empty view-model', async () => {+ const ended = vi.fn();+ const player = createMidiPlayer({ durationSec: 0, notes: [] }, { onEnded: ended });+ await player.play();+ expect(audio.oscillators).toHaveLength(0);+ expect(ended).toHaveBeenCalledTimes(1);+ });+});diff --git a/client/src/lib/scorePlayback.js b/client/src/lib/scorePlayback.jsindex 38a506ce4e..53e6e8f95b 100644--- a/client/src/lib/scorePlayback.js+++ b/client/src/lib/scorePlayback.js@@ -11,6 +11,8 @@// 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.+import { getAudioContext as ctx } from './audioContext.js';+// --- 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 };@@ -79,18 +81,9 @@ export const buildSchedule = (score, bpmOverride) => {};// --- 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 = typeof window !== 'undefined'- ? (window.AudioContext || window.webkitAudioContext)- : (globalThis.AudioContext || globalThis.webkitAudioContext);- sharedCtx = new Ctor();- }- return sharedCtx;-};+// The app-wide shared AudioContext (imported at top from audioContext.js).+// Resumed on demand because autoplay policy starts it suspended until a user+// gesture.// 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@@ -110,8 +103,9 @@ const TONE_PEAK = 0.18; // per-voice gain peak for a single sounding tone// click. Triangle wave reads as a soft reference tone. Routed into `destination`// (the context output for the solo player; a per-part gain → master bus for the// multi-part player). Returns the live { osc, gain } so the caller can track it-// for teardown. Pure of any module state — both players share it.-const scheduleTone = (c, freq, startAt, durSec, destination, peak = TONE_PEAK) => {+// for teardown. Pure of any module state — both players here share it, and+// midiPlayback.js imports it so the MIDI preview sounds like the score synth.+export const scheduleTone = (c, freq, startAt, durSec, destination, peak = TONE_PEAK) => {const osc = c.createOscillator();const gain = c.createGain();osc.type = 'triangle';diff --git a/client/src/lib/songPlayback.js b/client/src/lib/songPlayback.jsindex 09b4ee1f2c..8947d47e71 100644--- a/client/src/lib/songPlayback.js+++ b/client/src/lib/songPlayback.js@@ -9,17 +9,10 @@// Pure-ish: no React. The Song editor wraps this in a small hook for UI state.// decodeAudioData is the only async dependency; callers handle rejection.-// Lazily create + reuse one AudioContext. Browsers cap the number of contexts,-// and reusing one keeps every layer on the same clock. Resumed on demand-// because autoplay policies start it suspended until a user gesture.-let sharedCtx = null;-function ctx() {- if (!sharedCtx) {- const Ctor = window.AudioContext || window.webkitAudioContext;- sharedCtx = new Ctor();- }- return sharedCtx;-}+// The app-wide shared AudioContext (see audioContext.js) — reusing one keeps+// every layer on the same clock. Resumed on demand because autoplay policies+// start it suspended until a user gesture.+import { getAudioContext as ctx } from './audioContext.js';// Decode one recording URL into an AudioBuffer. Cached per-URL on the returned// mixer (not globally) so a re-open re-fetches at most once per session.