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
Merge remote-tracking branch 'origin/main' into next/issue-2490
[._.]/ Adam Eivy06fc0266ce5f
diff --cc .changelog/NEXT.mdindex ab8572fc13,a1891ba0f6..655b6435bb--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@@ -3,8 -3,8 +3,9 @@@## MIDI transcription- **[issue-2477] Visualize transcribed MIDI with an interactive piano-roll.** Rounds references and Music Video projects with a MuScriptor transcription now show a DAW-style time × pitch roll right below the audio controls — note bars with musical note names, a chord lane labeling simultaneous notes (Cmaj7, Am, slash inversions), hover/tap tooltips, zoom + pan + fit-to-width, click-to-scrub playhead, and a QA footer (note count, density, pitch range, duration, tempo, per-track legend). Collapsible and mobile-friendly; no external DAW needed to judge transcription quality.+- **[issue-2490] Hear a transcribed MIDI with a synth preview.** The MIDI piano-roll now has a play button (Space works too, with the roll focused): a soft synth renders the transcribed notes while a moving playhead tracks the audio across the roll, the view pages along to keep it visible, and the sounding pitches light up in the left gutter. Click anywhere in the grid (or use the arrow keys) to seek — playback jumps with the playhead, even mid-note into held chords. Works in both the Rounds reference analysis and Music Video surfaces; collapsing the panel stops playback.- **Music track pages show the MIDI piano-roll too.** A selected track on the Music → Tracks page now surfaces the newest MIDI transcription from any Music Video project linked to it, with the same interactive piano-roll and a link back to the source project.+ - **[issue-2491] MIDI piano-roll: cached-scene rendering, theme-aware colors, and cleanup.** The DAW-style roll now paints its grid + notes + gutter to a cached offscreen bitmap and just composites that (plus the playhead/hover overlay) on hover and scrub repaints — so a hover over a dense (10k-note) file no longer redraws every note bar. Both rolls follow the active theme's accent instead of a hardcoded blue (resolved via a shared `rollPalette` helper + `useCanvasRollPalette` hook, repainting on theme switch). Hit-testing indexes notes by pitch (one row scanned instead of every note), tick→seconds uses a binary search over tempo segments, and the ruler's M:SS tick labels use `formatDurationSec` (now correctly rendering a genuine zero as `0:00`).## Changeddiff --cc client/src/components/songs/MidiPianoRoll.jsxindex ace8dfccd7,c38f72e583..c5c758b247--- a/client/src/components/songs/MidiPianoRoll.jsx+++ b/client/src/components/songs/MidiPianoRoll.jsx@@@ -44,21 -43,6 +43,20 @@@ const tickStep = (pps) =>return steps.find((s) => s * pps >= 70) || 300;};+// First index in the start-sorted note list with startSec >= t. Subtracting+// the file's longest note duration from a window edge before searching gives+// the earliest index that can still overlap that edge — O(log n) instead of- // skip-scanning from note 0, which matters once the rAF playback loop makes- // drawing a 60fps hot path.++// scanning from note 0 in the 60fps playback loop's sounding-set sweep.+const lowerBound = (notes, t) => {+ let lo = 0;+ let hi = notes.length;+ while (lo < hi) {+ const mid = (lo + hi) >> 1;+ if (notes[mid].startSec < t) lo = mid + 1; else hi = mid;+ }+ return lo;+};+const tooltipStyle = (x, y, width) => ({left: `${Math.min(x + 10, Math.max(0, width - TOOLTIP_W))}px`,top: `${Math.max(0, y - 24)}px`,@@@ -95,25 -89,8 +111,25 @@@ export default function MidiPianoRoll(const [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;+ // Set of midis sounding this frame (null when idle) — written by the rAF- // playback loop, painted onto the pitch gutter by draw().++ // playback loop, painted onto the pitch gutter by the overlay pass.+ const soundingRef = useRef(null);+ // Whether the view should follow the moving playhead. An explicit user pan+ // (drag / wheel / shift+arrows) turns following off so the loop's page-snap+ // doesn't fight the pan frame-by-frame; it turns back on when the playhead+ // re-enters the view, on a seek, and on play.+ const followRef = useRef(true);const duration = Math.max(data?.durationSec || 0, 0.001);+ // Longest note in the file — the lookback window for lowerBound() scans.+ const maxDurSec = useMemo(+ () => (data?.notes || []).reduce((m, n) => Math.max(m, n.durationSec || 0), 0),+ [data],+ );const chordLaneH = showChords && chords?.length ? CHORD_H : 0;const multiTrack = (data?.tracks?.length || 1) > 1;@@@ -151,152 -142,239 +181,259 @@@const timeToX = (sec) => GUTTER_W + (sec - scroll) * pps;const midiToY = (m) => gridTop + (highMidi - m) * rowH;- ctx.clearRect(0, 0, width, height);- ctx.fillStyle = BG;- ctx.fillRect(0, 0, width, height);-- // Horizontal pitch rows — black-key rows tinted, every C stronger.- for (let m = lowMidi; m <= highMidi; m += 1) {- const y = midiToY(m);- if (m % 12 === 0) {- ctx.fillStyle = C_LINE;- ctx.fillRect(GUTTER_W, y + rowH, gridW, 1);- } else if (rowH >= 4) {- if (isBlackKey(m)) {- ctx.fillStyle = 'rgba(255,255,255,0.02)';- ctx.fillRect(GUTTER_W, y, gridW, rowH);+ // The full grid + notes + gutter is invariant under hover and playhead+ // moves, so paint it to an offscreen bitmap keyed on the values that DO+ // change it and reuse that bitmap for every other repaint. On a dense file+ // this turns a hover/scrub repaint from "redraw every note bar" into a+ // single drawImage() + a couple of overlay strokes.+ const paintScene = (octx) => {+ octx.clearRect(0, 0, width, height);+ octx.fillStyle = bg;+ octx.fillRect(0, 0, width, height);++ // Horizontal pitch rows — black-key rows tinted, every C stronger.+ for (let m = lowMidi; m <= highMidi; m += 1) {+ const y = midiToY(m);+ if (m % 12 === 0) {+ octx.fillStyle = C_LINE;+ octx.fillRect(GUTTER_W, y + rowH, gridW, 1);+ } else if (rowH >= 4) {+ if (isBlackKey(m)) {+ octx.fillStyle = 'rgba(255,255,255,0.02)';+ octx.fillRect(GUTTER_W, y, gridW, rowH);+ }+ octx.fillStyle = GRID_LINE;+ octx.fillRect(GUTTER_W, y + rowH, gridW, 1);}- ctx.fillStyle = GRID_LINE;- ctx.fillRect(GUTTER_W, y + rowH, gridW, 1);}- }- // Vertical time grid + ruler labels.- const step = tickStep(pps);- ctx.font = '9px ui-sans-serif, system-ui, sans-serif';- ctx.textAlign = 'left';- for (let t = Math.floor(scroll / step) * step; t <= viewEnd; t += step) {- if (t < 0) continue;- const x = timeToX(t);- if (x < GUTTER_W) continue;- ctx.fillStyle = GRID_LINE;- ctx.fillRect(x, gridTop, 1, gridH);- ctx.fillStyle = TEXT_DIM;- // Sub-second tick steps need the fractional digits or adjacent labels- // render identically ("0:03 0:03 0:03") right when fine timing matters.- ctx.fillText(step < 1 ? formatTimecode(t) : formatTimecode(t).replace(/\.\d+$/, ''), x + 3, RULER_H - 6);- }+ // Vertical time grid + ruler labels.+ const step = tickStep(pps);+ octx.font = '9px ui-sans-serif, system-ui, sans-serif';+ octx.textAlign = 'left';+ for (let t = Math.floor(scroll / step) * step; t <= viewEnd; t += step) {+ if (t < 0) continue;+ const x = timeToX(t);+ if (x < GUTTER_W) continue;+ octx.fillStyle = GRID_LINE;+ octx.fillRect(x, gridTop, 1, gridH);+ octx.fillStyle = TEXT_DIM;+ // Sub-second tick steps keep the fractional timecode (adjacent labels+ // would otherwise read "0:03 0:03 0:03"); whole-second steps use the+ // plain M:SS formatter.+ octx.fillText(step < 1 ? formatTimecode(t) : formatDurationSec(t), x + 3, RULER_H - 6);+ }- // Chord lane.- if (chordLaneH) {- ctx.fillStyle = 'rgba(255,255,255,0.03)';- ctx.fillRect(GUTTER_W, RULER_H, gridW, chordLaneH);- (chords || []).forEach((c) => {- if (c.endSec < scroll || c.startSec > viewEnd) return;- const x0 = Math.max(GUTTER_W, timeToX(c.startSec));- const x1 = Math.min(width, timeToX(c.endSec));- if (x1 - x0 < 2) return;- const isHover = hover?.kind === 'chord' && hover.chord === c;- ctx.fillStyle = isHover ? 'rgba(59,130,246,0.25)' : 'rgba(59,130,246,0.10)';- ctx.fillRect(x0, RULER_H + 1, x1 - x0 - 1, chordLaneH - 2);- // Sticky-left label, clipped to the window.- ctx.save();- ctx.beginPath();- ctx.rect(x0, RULER_H, x1 - x0, chordLaneH);- ctx.clip();- ctx.fillStyle = isHover ? '#dbeafe' : '#9ca3af';- ctx.font = '10px ui-sans-serif, system-ui, sans-serif';- ctx.fillText(c.label, x0 + 3, RULER_H + chordLaneH - 6);- ctx.restore();- });- }+ // Chord lane (dim — the hovered chord is brightened in the overlay pass).+ if (chordLaneH) {+ octx.fillStyle = 'rgba(255,255,255,0.03)';+ octx.fillRect(GUTTER_W, RULER_H, gridW, chordLaneH);+ (chords || []).forEach((c) => {+ if (c.endSec < scroll || c.startSec > viewEnd) return;+ const x0 = Math.max(GUTTER_W, timeToX(c.startSec));+ const x1 = Math.min(width, timeToX(c.endSec));+ if (x1 - x0 < 2) return;+ octx.fillStyle = `rgb(${accentRgb} / 0.10)`;+ octx.fillRect(x0, RULER_H + 1, x1 - x0 - 1, chordLaneH - 2);+ // Sticky-left label, clipped to the window.+ octx.save();+ octx.beginPath();+ octx.rect(x0, RULER_H, x1 - x0, chordLaneH);+ octx.clip();+ octx.fillStyle = '#9ca3af';+ octx.font = '10px ui-sans-serif, system-ui, sans-serif';+ octx.fillText(c.label, x0 + 3, RULER_H + chordLaneH - 6);+ octx.restore();+ });+ }- // Notes — only those intersecting the visible window, clipped to the grid.- // The list is sorted by startSec (parseMidiFile), so bail out of the loop- // at the first note past the right edge.- const hoverChordMidis = hover?.kind === 'chord' ? new Set(hover.chord.midis) : null;- const hoverChordSpan = hover?.kind === 'chord' ? hover.chord : null;- ctx.save();- ctx.beginPath();- ctx.rect(GUTTER_W, gridTop, gridW, gridH);- ctx.clip();- ctx.textAlign = 'left';- const notes = data?.notes || [];- for (let i = lowerBound(notes, scroll - maxDurSec); i < notes.length; i += 1) {- const n = notes[i];- if (n.startSec > viewEnd) break;- const end = n.startSec + n.durationSec;- if (end < scroll) continue;- if (n.midi < lowMidi || n.midi > highMidi) continue;- const x = timeToX(n.startSec);- const w = Math.max(2, n.durationSec * pps);- const y = midiToY(n.midi);- const h = Math.max(2, rowH - 1);- roundRect(ctx, x, y + 0.5, w, h, NOTE_RADIUS);- ctx.fillStyle = multiTrack ? layerColor(n.track) : ACCENT;- ctx.globalAlpha = 0.35 + 0.6 * (n.velocity ?? 0.8);- ctx.fill();- const isHoverNote = hover?.kind === 'note' && hover.note.id === n.id;- const inHoverChord = hoverChordMidis?.has(n.midi)- && hoverChordSpan && n.startSec < hoverChordSpan.endSec && end > hoverChordSpan.startSec;- if (isHoverNote || inHoverChord) {- ctx.globalAlpha = 1;- ctx.strokeStyle = '#ffffff';- ctx.lineWidth = 1;- ctx.stroke();+ // Notes — only those intersecting the visible window, clipped to the grid.- // The list is sorted by startSec (parseMidiFile), so bail out of the loop- // at the first note past the right edge.++ // The list is sorted by startSec (parseMidiFile), so start at the first++ // note that can still overlap the left edge and bail at the right edge.+ octx.save();+ octx.beginPath();+ octx.rect(GUTTER_W, gridTop, gridW, gridH);+ octx.clip();+ octx.textAlign = 'left';+ const notes = data?.notes || [];- for (let i = 0; i < notes.length; i += 1) {++ for (let i = lowerBound(notes, scroll - maxDurSec); i < notes.length; i += 1) {+ const n = notes[i];+ if (n.startSec > viewEnd) break;+ const end = n.startSec + n.durationSec;+ if (end < scroll) continue;+ if (n.midi < lowMidi || n.midi > highMidi) continue;+ const x = timeToX(n.startSec);+ const w = Math.max(2, n.durationSec * pps);+ const y = midiToY(n.midi);+ const h = Math.max(2, rowH - 1);+ roundRect(octx, x, y + 0.5, w, h, NOTE_RADIUS);+ octx.fillStyle = multiTrack ? layerColor(n.track) : accent;+ octx.globalAlpha = 0.35 + 0.6 * (n.velocity ?? 0.8);+ octx.fill();+ octx.globalAlpha = 1;+ // In-bar note name when it fits.+ if (w >= 28 && rowH >= 12) {+ octx.fillStyle = bg;+ octx.font = '9px ui-sans-serif, system-ui, sans-serif';+ octx.fillText(n.name || midiNoteName(n.midi), x + 3, y + h - Math.max(1, (h - 8) / 2));+ }}- ctx.globalAlpha = 1;- // In-bar note name when it fits.- if (w >= 28 && rowH >= 12) {- ctx.fillStyle = '#0c0c0e';- ctx.font = '9px ui-sans-serif, system-ui, sans-serif';- ctx.fillText(n.name || midiNoteName(n.midi), x + 3, y + h - Math.max(1, (h - 8) / 2));+ octx.restore();++ // Pitch gutter on top (opaque, so notes pan "under" it).+ octx.fillStyle = GUTTER_BG;+ octx.fillRect(0, gridTop, GUTTER_W, gridH);+ octx.textAlign = 'right';+ for (let m = lowMidi; m <= highMidi; m += 1) {+ const y = midiToY(m);+ if (m % 12 === 0 && rowH >= 3) {+ octx.fillStyle = TEXT_DIM;+ octx.font = '9px ui-sans-serif, system-ui, sans-serif';+ octx.fillText(midiNoteName(m), GUTTER_W - 4, y + rowH - 1);+ octx.fillStyle = C_LINE;+ octx.fillRect(0, y + rowH, GUTTER_W, 1);+ } else if (rowH >= 7) {+ octx.fillStyle = isBlackKey(m) ? 'rgba(255,255,255,0.05)' : 'rgba(255,255,255,0.10)';+ octx.fillRect(GUTTER_W - 8, y + 1, 5, Math.max(1, rowH - 2));+ }}- }- ctx.restore();-- // 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);- }+ // Scroll indicator along the bottom when zoomed in.+ if (maxScroll > 0) {+ const frac = gridW / (duration * pps);+ const barW = Math.max(24, gridW * frac);+ const barX = GUTTER_W + (scroll / maxScroll) * (gridW - barW);+ octx.fillStyle = 'rgba(255,255,255,0.15)';+ octx.fillRect(barX, height - 3, barW, 2);+ }+ };- // Sounding pitches (playing only) — computed once per frame by the rAF- // playback loop (null when idle); draw just paints the gutter rows.- const soundingMidis = soundingRef.current;-- // 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));+ // Live overlay: the hovered chord's bright box + label, hovered-note white- // strokes, and the playhead — everything that moves without invalidating- // the cached scene.++ // strokes, the playhead, and the sounding-pitch gutter lights — everything++ // that moves without invalidating the cached scene.+ const paintOverlay = (octx) => {+ if (hover?.kind === 'chord' && chordLaneH) {+ const c = hover.chord;+ if (!(c.endSec < scroll || c.startSec > viewEnd)) {+ const x0 = Math.max(GUTTER_W, timeToX(c.startSec));+ const x1 = Math.min(width, timeToX(c.endSec));+ if (x1 - x0 >= 2) {+ // Repaint the strip under the box so the brighter fill doesn't+ // composite on top of the baked dim box.+ octx.fillStyle = bg;+ octx.fillRect(x0, RULER_H, x1 - x0, chordLaneH);+ octx.fillStyle = 'rgba(255,255,255,0.03)';+ octx.fillRect(x0, RULER_H, x1 - x0, chordLaneH);+ octx.fillStyle = `rgb(${accentRgb} / 0.25)`;+ octx.fillRect(x0, RULER_H + 1, x1 - x0 - 1, chordLaneH - 2);+ octx.save();+ octx.beginPath();+ octx.rect(x0, RULER_H, x1 - x0, chordLaneH);+ octx.clip();+ octx.fillStyle = '#dbeafe';+ octx.font = '10px ui-sans-serif, system-ui, sans-serif';+ octx.fillText(c.label, x0 + 3, RULER_H + chordLaneH - 6);+ octx.restore();+ }+ }}- if (m % 12 === 0 && rowH >= 3) {- ctx.fillStyle = TEXT_DIM;- ctx.font = '9px ui-sans-serif, system-ui, sans-serif';- ctx.fillText(midiNoteName(m), GUTTER_W - 4, y + rowH - 1);- ctx.fillStyle = C_LINE;- ctx.fillRect(0, y + rowH, GUTTER_W, 1);- } else if (rowH >= 7) {- ctx.fillStyle = isBlackKey(m) ? 'rgba(255,255,255,0.05)' : 'rgba(255,255,255,0.10)';- ctx.fillRect(GUTTER_W - 8, y + 1, 5, Math.max(1, rowH - 2));++ // White outline on the hovered note (or every note in the hovered chord),+ // clipped to the grid so a stroke can't bleed over the gutter/ruler.+ if (hover) {+ octx.save();+ octx.beginPath();+ octx.rect(GUTTER_W, gridTop, gridW, gridH);+ octx.clip();+ octx.strokeStyle = '#ffffff';+ octx.lineWidth = 1;+ const strokeNote = (n) => {+ if (n.midi < lowMidi || n.midi > highMidi) return;+ const w = Math.max(2, n.durationSec * pps);+ const h = Math.max(2, rowH - 1);+ roundRect(octx, timeToX(n.startSec), midiToY(n.midi) + 0.5, w, h, NOTE_RADIUS);+ octx.stroke();+ };+ if (hover.kind === 'note') {+ strokeNote(hover.note);+ } else if (hover.kind === 'chord') {+ const span = hover.chord;+ span.midis.forEach((m) => {+ (notesByMidi.get(m) || []).forEach((n) => {+ const end = n.startSec + n.durationSec;+ if (n.startSec < span.endSec && end > span.startSec) strokeNote(n);+ });+ });+ }+ octx.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) {+ octx.fillStyle = accent;+ octx.fillRect(px - 1, RULER_H, 2, height - RULER_H);+ }++++ // Sounding pitches (synth preview, playing only) — the gutter is baked++ // opaque into the scene, so tint the row on top and re-draw its C label++ // so the octave anchor stays readable under the highlight.++ const soundingMidis = soundingRef.current;++ if (soundingMidis?.size) {++ for (const m of soundingMidis) {++ if (m < lowMidi || m > highMidi) continue;++ const y = midiToY(m);++ octx.fillStyle = `rgb(${accentRgb} / 0.35)`;++ octx.fillRect(0, y, GUTTER_W, Math.max(1, rowH));++ if (m % 12 === 0 && rowH >= 3) {++ octx.textAlign = 'right';++ octx.fillStyle = '#e5e7eb';++ octx.font = '9px ui-sans-serif, system-ui, sans-serif';++ octx.fillText(midiNoteName(m), GUTTER_W - 4, y + rowH - 1);++ }++ }++ }+ };++ // Rebuild the offscreen scene only when its signature changed; otherwise+ // reuse the cached bitmap. DPR is derived from the visible canvas's actual+ // backing store (set by useCanvasDprSize) rather than reading+ // window.devicePixelRatio directly — so the offscreen always matches the+ // visible canvas's resolution even if the DPR changes before the sizing hook+ // re-runs (a fresh-DPR scene composited into a stale-DPR canvas would blur).+ const fallbackDpr = (typeof window !== 'undefined' && window.devicePixelRatio) || 1;+ const backingW = canvas.width || Math.round(width * fallbackDpr);+ const backingH = canvas.height || Math.round(height * fallbackDpr);+ const dpr = backingW / width;+ const sig = {+ width, height, zoom: zoomRef.current, scroll, chordLaneH,+ lowMidi, highMidi, multiTrack, backingW, backingH,+ data, chords: chordLaneH ? chords : null, bg, accent, accentRgb,+ };+ const cached = sceneRef.current;+ if (!cached.canvas || !sceneSigEqual(cached.sig, sig)) {+ const off = cached.canvas+ || (typeof document !== 'undefined' ? document.createElement('canvas') : null);+ if (off) {+ // Only re-allocate (which clears + resets the transform) when the pixel+ // size actually changes; a pan/theme rebuild keeps the same buffer and+ // repaints over it (paintScene clears its own frame first).+ if (off.width !== backingW || off.height !== backingH) { off.width = backingW; off.height = backingH; }+ const octx = off.getContext('2d');+ if (octx) {+ octx.setTransform(dpr, 0, 0, dpr, 0, 0);+ paintScene(octx);+ }+ sceneRef.current = { canvas: off, sig };}}- // Scroll indicator along the bottom when zoomed in.- if (maxScroll > 0) {- const frac = gridW / (duration * pps);- const barW = Math.max(24, gridW * frac);- const barX = GUTTER_W + (scroll / maxScroll) * (gridW - barW);- ctx.fillStyle = 'rgba(255,255,255,0.15)';- ctx.fillRect(barX, height - 3, barW, 2);- }- }, [data, chords, chordLaneH, geometry, height, highMidi, lowMidi, hover, multiTrack, duration, maxDurSec]);++ ctx.clearRect(0, 0, width, height);+ const scene = sceneRef.current.canvas;+ if (scene) ctx.drawImage(scene, 0, 0, width, height);+ else paintScene(ctx); // no offscreen available (SSR) — paint direct+ paintOverlay(ctx);- }, [data, chords, chordLaneH, geometry, height, highMidi, lowMidi, hover, multiTrack, duration, notesByMidi]);++ }, [data, chords, chordLaneH, geometry, height, highMidi, lowMidi, hover, multiTrack, duration, notesByMidi, maxDurSec]);const drawRef = useRef(draw);drawRef.current = draw;@@@ -306,68 -388,6 +447,68 @@@useEffect(() => { draw(); }, [draw, zoom]);+ // Playback rAF loop: while playing, read the live audio position into the+ // playhead ref, page the view to keep it visible, compute the sounding+ // pitch set for the gutter, and repaint — but only when a frame is visually+ // different (playhead pixel, sounding set, or a page turn). At fit zoom the- // playhead moves well under a pixel per frame, so most frames skip the full- // canvas repaint. On pause/stop the loop tears down and one static frame++ // playhead moves well under a pixel per frame, so most frames skip the++ // repaint entirely. On pause/stop the loop tears down and one static frame+ // pins the playhead where the audio stopped.+ const wasPlayingRef = useRef(false);+ const lastFrameRef = useRef('');+ useEffect(() => {+ const notes = data?.notes || [];+ if (!playing) {+ soundingRef.current = null;+ if (wasPlayingRef.current) {+ wasPlayingRef.current = false;+ playheadSecRef.current = getPositionRef.current?.() ?? 0;+ drawRef.current();+ }+ return undefined;+ }+ wasPlayingRef.current = true;+ lastFrameRef.current = '';+ followRef.current = true; // pressing play re-follows the playhead+ let raf = 0;+ const loop = () => {+ const pos = getPositionRef.current?.() ?? 0;+ playheadSecRef.current = pos;+ // Page-turn follow: when the playhead exits the visible window, snap the+ // view so it re-enters near the left — but only while following (an+ // explicit user pan turns following off until the playhead re-enters).+ const { gridW, pps, maxScroll } = geometry();+ const view = gridW / pps;+ let paged = false;+ const visible = pos >= scrollSecRef.current && pos <= scrollSecRef.current + view;+ if (visible) {+ followRef.current = true;+ } else if (followRef.current) {+ scrollSecRef.current = Math.min(Math.max(0, pos - view * 0.1), maxScroll);+ paged = true;+ }+ // Sounding set — scan only the slice that can overlap the playhead.+ const sounding = new Set();+ for (let i = lowerBound(notes, pos - maxDurSec); i < notes.length; i += 1) {+ const n = notes[i];+ if (n.startSec > pos) break;+ if (pos < n.startSec + n.durationSec) sounding.add(n.midi);+ }+ // Signature = playhead pixel + exact sounding pitches (the set is+ // polyphony-sized, so the sort/join is cheap) — a size+sum digest would+ // miss contrary semitone motion at a sub-pixel playhead step.+ const frame = `${Math.round((pos - scrollSecRef.current) * pps)}:${[...sounding].sort((a, b) => a - b).join(',')}`;+ if (paged || frame !== lastFrameRef.current) {+ lastFrameRef.current = frame;+ soundingRef.current = sounding;+ drawRef.current();+ }+ raf = requestAnimationFrame(loop);+ };+ raf = requestAnimationFrame(loop);+ return () => cancelAnimationFrame(raf);+ }, [playing, geometry, data, maxDurSec]);+// Coalesce pan-driven repaints to one per animation frame — wheel/pointer// events can fire faster than the display presents.const rafRef = useRef(0);diff --cc client/src/components/songs/MidiPianoRoll.test.jsxindex 8fcb801449,e18b75f4ba..4ca1c94e8e--- a/client/src/components/songs/MidiPianoRoll.test.jsx+++ b/client/src/components/songs/MidiPianoRoll.test.jsx@@@ -2,11 -2,10 +2,13 @@@ import { render, cleanup, fireEvent } fimport { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import MidiPianoRoll from './MidiPianoRoll.jsx';- // Drives the playback rAF loop deterministically (#2490): requestAnimationFrame- // is stubbed to a manual queue so each pump() runs exactly one frame. The loop- // sets no React state — it mutates refs and paints the canvas — so assertions- // read the mocked 2d-context call counts/args.-+ // jsdom has no canvas/ResizeObserver and reports 0 widths — stub the minimum the+ // component needs so draw() runs and we can assert it painted. `drawImage` is+ // required because the roll composites a cached offscreen "scene" bitmap onto-// the visible canvas each repaint.++// the visible canvas each repaint. The playback describe below additionally++// stubs requestAnimationFrame to a manual queue so each pump() runs exactly one++// frame of the rAF loop (#2490) — the loop sets no React state, it mutates refs++// and paints, so assertions read the mocked 2d-context call counts/args.const makeCtx = () => ({clearRect: vi.fn(), fillRect: vi.fn(), strokeRect: vi.fn(), fillText: vi.fn(),save: vi.fn(), restore: vi.fn(), beginPath: vi.fn(), closePath: vi.fn(),@@@ -15,116 -14,52 +17,166 @@@fillStyle: '', strokeStyle: '', lineWidth: 1, font: '', textAlign: '', globalAlpha: 1,});+ const DATA = {+ durationSec: 2,+ minMidi: 60,+ maxMidi: 64,+ notes: [+ { id: '0:0', midi: 60, startSec: 0, durationSec: 0.5, velocity: 0.8, track: 0, name: 'C4' },+ { id: '0:1', midi: 64, startSec: 0.5, durationSec: 0.5, velocity: 0.7, track: 0, name: 'E4' },+ ],+ tracks: [{ index: 0, name: null, noteCount: 2 }],+ };++ describe('<MidiPianoRoll>', () => {+ let ctx;+ beforeEach(() => {+ ctx = makeCtx();+ vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue(ctx);+ vi.stubGlobal('ResizeObserver', class { observe() {} disconnect() {} });+ vi.stubGlobal('MutationObserver', class { observe() {} disconnect() {} });+ Object.defineProperty(HTMLElement.prototype, 'clientWidth', { configurable: true, get() { return 800; } });+ });+ afterEach(() => {+ cleanup();+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+ delete HTMLElement.prototype.clientWidth;+ });++ it('paints notes into an offscreen scene and composites it onto the canvas', () => {+ render(<MidiPianoRoll data={DATA} chords={[]} showChords={false} zoom={1} onZoomChange={() => {}} height={240} />);+ expect(ctx.setTransform).toHaveBeenCalled(); // offscreen scene built with a DPR transform+ expect(ctx.fill).toHaveBeenCalled(); // note bars drawn into the scene+ expect(ctx.drawImage).toHaveBeenCalled(); // cached scene composited to the visible canvas+ });++ it('renders the chord lane labels when showChords is set', () => {+ const chords = [{ startSec: 0, endSec: 1, label: 'Cmaj', midis: [60, 64, 67] }];+ render(<MidiPianoRoll data={DATA} chords={chords} showChords zoom={1} onZoomChange={() => {}} height={240} />);+ const labels = ctx.fillText.mock.calls.map((c) => c[0]);+ expect(labels).toContain('Cmaj');+ });++ it('renders an empty/default view-model without crashing', () => {+ const empty = { durationSec: 0, minMidi: 60, maxMidi: 71, notes: [], tracks: [] };+ expect(() => render(+ <MidiPianoRoll data={empty} chords={[]} showChords={false} zoom={1} onZoomChange={() => {}} height={240} />,+ )).not.toThrow();+ expect(ctx.drawImage).toHaveBeenCalled();+ });+ });+++// Long file + two-voice pitch handoff at t=5000 where the pair {60,64} → {61,63}+// keeps BOTH the set size and the midi sum constant — the case a size+sum+// repaint signature would miss.- const DATA = {++const PLAYBACK_DATA = {+ durationSec: 10000,+ minMidi: 60,+ maxMidi: 64,+ tracks: [{ index: 0 }],+ tempos: [],+ notes: [+ { id: 'a', midi: 60, startSec: 0, durationSec: 5000, velocity: 0.8, track: 0, name: 'C4' },+ { id: 'b', midi: 64, startSec: 0, durationSec: 5000, velocity: 0.8, track: 0, name: 'E4' },+ { id: 'c', midi: 61, startSec: 5000, durationSec: 5000, velocity: 0.8, track: 0, name: 'C#4' },+ { id: 'd', midi: 63, startSec: 5000, durationSec: 5000, velocity: 0.8, track: 0, name: 'D#4' },+ ],+};++describe('<MidiPianoRoll> playback rAF loop', () => {+ let ctx;+ let rafQueue;+ const pump = () => {+ const q = rafQueue;+ rafQueue = [];+ q.forEach((cb) => cb());+ };++ beforeEach(() => {+ ctx = makeCtx();+ rafQueue = [];+ vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue(ctx);+ vi.stubGlobal('ResizeObserver', class { observe() {} disconnect() {} });++ vi.stubGlobal('MutationObserver', class { observe() {} disconnect() {} });+ vi.stubGlobal('requestAnimationFrame', (cb) => { rafQueue.push(cb); return rafQueue.length; });+ vi.stubGlobal('cancelAnimationFrame', () => {});+ Object.defineProperty(HTMLElement.prototype, 'clientWidth', { configurable: true, get() { return 800; } });+ });+ afterEach(() => {+ cleanup();+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+ delete HTMLElement.prototype.clientWidth;+ });++ const renderRoll = (getPosition, { zoom = 1 } = {}) => render(+ <MidiPianoRoll- data={DATA}++ data={PLAYBACK_DATA}+ chords={[]}+ showChords={false}+ zoom={zoom}+ onZoomChange={() => {}}+ height={200}+ playing+ getPosition={getPosition}+ onSeek={() => {}}+ onTogglePlay={() => {}}+ />,+ );++ it('skips the full repaint on visually identical frames', () => {+ renderRoll(() => 100);+ pump(); // first loop frame paints+ const after1 = ctx.clearRect.mock.calls.length;+ pump();+ pump();+ pump();+ // Position, sounding set, and page state are all unchanged — every+ // subsequent frame skips the canvas repaint.+ expect(ctx.clearRect.mock.calls.length).toBe(after1);+ });++ it('repaints when the sounding pitches change even at constant set size, sum, and playhead pixel', () => {+ // At fit zoom, pps = (800-44)/10000 ≈ 0.0756 px/s — a 1.5 s step moves the+ // playhead well under a pixel, so only the pitch handoff distinguishes the+ // frames.+ let pos = 4999;+ renderRoll(() => pos);+ pump(); // paints with {60, 64} sounding+ const before = ctx.clearRect.mock.calls.length;+ pos = 5000.5; // same rounded playhead px; sounding set is now {61, 63}+ pump();- expect(ctx.clearRect.mock.calls.length).toBe(before + 1);++ expect(ctx.clearRect.mock.calls.length).toBeGreaterThan(before);+ });++ it('pages the view to follow a playhead that exits the visible window', () => {+ // zoom 8 → view ≈ 1250 s. Jumping to t=2000 must snap the window so the+ // playhead re-enters near the left (scroll ≈ 1875 s) — verified by the+ // ruler now labeling a tick inside the new window (t=1920 → "32:00").+ let pos = 0;+ renderRoll(() => pos, { zoom: 8 });+ pump();+ pos = 2000;+ pump();+ const labels = ctx.fillText.mock.calls.map((c) => c[0]);+ expect(labels).toContain('32:00');+ });++ it('stops chasing the playhead after an explicit wheel pan, until it re-enters the view', () => {+ let pos = 0;+ const { container } = renderRoll(() => pos, { zoom: 8 });+ const canvas = container.querySelector('canvas');+ pump();+ // User wheels the view far ahead of the playhead (deltaY pans horizontally).+ fireEvent.wheel(canvas, { deltaY: 3000 });+ pump(); // scheduleDraw repaint at the panned scroll+ pos = 2000; // playhead still far behind the panned window (scroll ≈ 4960)+ pump();+ const labels = ctx.fillText.mock.calls.map((c) => c[0]);- // No snap back: the pre-snap window at t≈2000 would label "34:00"; a- // followed snap would put scroll at 1875 (labels near 32:00). After the- // pan the window sits ≈4960 s in, so the ruler labels ≈"84:00"+.++ // No snap back: after the pan the window sits ≈4960 s in, so the ruler++ // labels ≈"84:00"+; a followed snap would relabel near 32:00.+ expect(labels).toContain('84:00');+ expect(labels).not.toContain('32:00');+ });+});diff --cc client/src/hooks/README.mdindex afda010b91,c8186f3cca..f7d3e0a43a--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@@ -159,5 -159,5 +159,6 @@@ grep -i "what you want to do" client/sr| `useReferenceAudioImport` | One round reference-audio-import job slot (#2120): start/cancel + SSE progress + terminal-frame handling via `POST /api/rounds/reference-audio/import`. Returns `{ active, percent, stage, start(url, context), cancel }`; `onComplete(filename, context)` fires with the uploads-dir filename to persist on the reference. Call once per surface that can independently kick off a download. | The reference-audio attach controls (`ReferenceAudioAttach`) — the "Download from URL" convenience. || `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. |+ | `useCanvasRollPalette` | Resolves the roll canvas palette (theme-following `--port-accent` + roll bg via `rollPalette`) into a ref, re-resolving on theme switch (`data-port-theme` MutationObserver) and repainting through a `drawRef`. Hands back a ref, not state, so a theme swap redraws the imperative canvas without a React re-render. | Both piano-roll canvases need theme-aware accent/bg colors that canvas `fillStyle` can't read from CSS vars. || `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 --cc client/src/hooks/index.jsindex 6b0e0bd0db,02014eae85..29ba960d0a--- a/client/src/hooks/index.js+++ b/client/src/hooks/index.js@@@ -51,8 -51,8 +51,9 @@@ export { default as useYoutubeTrackImpoexport { 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';+ export { default as useCanvasRollPalette } from './useCanvasRollPalette.js';// === Mixed (both default and named) — surface both ===export { default as useAsyncAction } from './useAsyncAction.js';diff --cc client/src/lib/README.mdindex a25096a4d5,f131477b3b..76a125a044--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@@ -106,9 -106,8 +106,9 @@@ grep -i "what you want to do" client/sr| 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. |+ | `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; `rollPalette()` — resolves the theme-following `{ bg, accent, accentRgb }` from `--port-accent` via `getComputedStyle` (canvas can't read CSS vars); `ROLL_BG` — the shared near-black bg literal. 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. || `pitchDetect.js` | Dependency-free vocal pitch-detection core for the song system (tuner / color-match / sing-to-score). `detectFrequency(frame, { sampleRate })` → `{ hz, clarity }` (McLeod NSDF; clarity gate rejects silence/noise); `frequencyToNote(hz, { a4 })` → `{ letter, accidental, octave, step, cents }` (cents ∈ [-50,+50], sharp positive; `step` reuses `scoreNotation`'s `diatonicStep` so detected notes align with the renderer); `noteToFrequency(note, { a4 })` inverse (color-match targets); `createPitchTracker(analyser, { onUpdate })` → `{ stop }` rAF/interval loop with median+EMA smoothing to kill octave jumps; `tuningQuality(cents)` → `{ level, label }` buckets a cents deviation into `in-tune`/`close`/`off`/`none` (thresholds `IN_TUNE_CENTS`/`CLOSE_CENTS`) for the tuner color readout. || `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). |