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
refactor([issue-2477]): apply simplify-pass findings to the MIDI roll
[._.]/ Adam Eivyf0800e99b94f
diff --git a/client/src/components/songs/MidiPianoRoll.jsx b/client/src/components/songs/MidiPianoRoll.jsxindex 76770768a5..bbdc35a414 100644--- a/client/src/components/songs/MidiPianoRoll.jsx+++ b/client/src/components/songs/MidiPianoRoll.jsx@@ -1,8 +1,9 @@import { useCallback, useEffect, useRef, useState } from 'react';import { midiNoteName, isBlackKey } from '../../lib/pianoKeyboard';import { chordNoteNames } from '../../lib/midiChords';+import { roundRect, layerColor } from '../../lib/canvasRoll.js';import { formatTimecode } from '../../utils/formatters';-import { layerColor } from './PianoRoll.jsx';+import useCanvasDprSize from '../../hooks/useCanvasDprSize.js';// DAW-style horizontal piano-roll for inspecting a transcribed `.mid` file// (time × pitch grid) — NOT the Synthesia falling-note <PianoRoll>, which is@@ -12,7 +13,10 @@ import { layerColor } from './PianoRoll.jsx';// The canvas is virtualized — it stays the container's width and pans by a// scroll offset (a full-duration canvas at high zoom would blow past browser// canvas size limits). Pan/scrub state lives in refs and redraws directly so-// dragging never churns React renders; only the hover tooltip is state.+// dragging never churns React renders; hover state holds only the hovered+// note/chord IDENTITY (it drives the highlight repaint) while the tooltip's+// x/y position is mutated straight onto the DOM node — a mousemove within one+// note repaints nothing.const GUTTER_W = 44; // left pitch gutterconst RULER_H = 18; // top time ruler@@ -24,30 +28,27 @@ const GRID_LINE = 'rgba(255,255,255,0.05)';const C_LINE = 'rgba(255,255,255,0.14)';const TEXT_DIM = '#71717a';const NOTE_RADIUS = 2;+const TOOLTIP_W = 170; // clamp so the tooltip never overflows the right edge-// Zoom is a multiplier over fit-to-width (1 = whole file visible).+// Zoom is a multiplier over fit-to-width (1 = whole file visible). ZOOM_STEP+// is the shared discrete step for toolbar buttons and +/- keys — wheel/pinch+// use finer continuous factors.export const MIN_ZOOM = 1;export const MAX_ZOOM = 64;+export const ZOOM_STEP = 1.5;export const clampZoom = (z) => Math.min(MAX_ZOOM, Math.max(MIN_ZOOM, z));-const roundRect = (ctx, x, y, w, h, r) => {- const rr = Math.max(0, Math.min(r, w / 2, h / 2));- if (ctx.roundRect) { ctx.beginPath(); ctx.roundRect(x, y, w, h, rr); return; }- ctx.beginPath();- ctx.moveTo(x + rr, y);- ctx.arcTo(x + w, y, x + w, y + h, rr);- ctx.arcTo(x + w, y + h, x, y + h, rr);- ctx.arcTo(x, y + h, x, y, rr);- ctx.arcTo(x, y, x + w, y, rr);- ctx.closePath();-};-// Ruler tick step that keeps labels ≥ ~70px apart at the current zoom.const tickStep = (pps) => {const steps = [0.25, 0.5, 1, 2, 5, 10, 15, 30, 60, 120];return steps.find((s) => s * pps >= 70) || 300;};+const tooltipStyle = (x, y, width) => ({+ left: `${Math.min(x + 10, Math.max(0, width - TOOLTIP_W))}px`,+ top: `${Math.max(0, y - 24)}px`,+});+/*** @param {object} props* @param {object} props.data — view-model from parseMidiFile.@@ -60,17 +61,21 @@ const tickStep = (pps) => {export default function MidiPianoRoll({ data, chords, showChords, zoom, onZoomChange, height }) {const wrapRef = useRef(null);const canvasRef = useRef(null);- const widthRef = useRef(0);const scrollSecRef = useRef(0);const playheadSecRef = useRef(0);const pointersRef = useRef(new Map()); // pointerId → { x, y, moved }const pinchRef = useRef(null); // { startDist, startZoom }- const [hover, setHover] = useState(null); // { kind:'note'|'chord', x, y, ... }+ const tooltipRef = useRef(null);+ const tooltipPosRef = useRef({ x: 0, y: 0 });+ // Identity only ({ kind, note } | { kind, chord }) — drives the highlight+ // repaint; position updates never touch state.+ const [hover, setHover] = useState(null);const zoomRef = useRef(zoom);zoomRef.current = zoom;const duration = Math.max(data?.durationSec || 0, 0.001);const chordLaneH = showChords && chords?.length ? CHORD_H : 0;+ const multiTrack = (data?.tracks?.length || 1) > 1;// Pitch rows: pad one semitone each side, widen to at least an octave.let lowMidi = Math.max(0, (data?.minMidi ?? 60) - 1);@@ -78,7 +83,7 @@ export default function MidiPianoRoll({ data, chords, showChords, zoom, onZoomChif (highMidi - lowMidi < 11) {const pad = Math.ceil((11 - (highMidi - lowMidi)) / 2);lowMidi = Math.max(0, lowMidi - pad);- highMidi = Math.min(127, highMidi + 11 - (highMidi - lowMidi));+ highMidi = Math.min(127, lowMidi + 11);}const rowCount = highMidi - lowMidi + 1;@@ -94,11 +99,6 @@ export default function MidiPianoRoll({ data, chords, showChords, zoom, onZoomChreturn { width, gridW, pps, gridTop, gridH, rowH, maxScroll };}, [duration, chordLaneH, height, rowCount]);- const noteColor = useCallback((n) => {- const multiTrack = (data?.tracks?.length || 1) > 1;- return multiTrack ? layerColor(n.track) : ACCENT;- }, [data]);-const draw = useCallback(() => {const canvas = canvasRef.current;const { width, gridW, pps, gridTop, gridH, rowH, maxScroll } = geometry();@@ -115,15 +115,17 @@ export default function MidiPianoRoll({ data, chords, showChords, zoom, onZoomChctx.fillStyle = BG;ctx.fillRect(0, 0, width, height);- // Horizontal pitch rows — every semitone faint, every C stronger.+ // 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) {- ctx.fillStyle = isBlackKey(m) ? 'rgba(255,255,255,0.02)' : 'transparent';- if (isBlackKey(m)) ctx.fillRect(GUTTER_W, y, gridW, rowH);+ if (isBlackKey(m)) {+ ctx.fillStyle = 'rgba(255,255,255,0.02)';+ ctx.fillRect(GUTTER_W, y, gridW, rowH);+ }ctx.fillStyle = GRID_LINE;ctx.fillRect(GUTTER_W, y + rowH, gridW, 1);}@@ -168,6 +170,8 @@ export default function MidiPianoRoll({ data, chords, showChords, zoom, onZoomCh}// 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();@@ -175,16 +179,19 @@ export default function MidiPianoRoll({ data, chords, showChords, zoom, onZoomChctx.rect(GUTTER_W, gridTop, gridW, gridH);ctx.clip();ctx.textAlign = 'left';- (data?.notes || []).forEach((n) => {+ const notes = data?.notes || [];+ for (let i = 0; i < notes.length; i += 1) {+ const n = notes[i];+ if (n.startSec > viewEnd) break;const end = n.startSec + n.durationSec;- if (end < scroll || n.startSec > viewEnd) return;- if (n.midi < lowMidi || n.midi > highMidi) return;+ 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 = noteColor(n);+ 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;@@ -203,7 +210,7 @@ export default function MidiPianoRoll({ data, chords, showChords, zoom, onZoomChctx.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));}- });+ }ctx.restore();// Playhead (static scrub position in v1 — click to move).@@ -238,38 +245,28 @@ export default function MidiPianoRoll({ data, chords, showChords, zoom, onZoomChctx.fillStyle = 'rgba(255,255,255,0.15)';ctx.fillRect(barX, height - 3, barW, 2);}- }, [data, chords, chordLaneH, geometry, height, highMidi, lowMidi, hover, noteColor]);+ }, [data, chords, chordLaneH, geometry, height, highMidi, lowMidi, hover, multiTrack, duration]);const drawRef = useRef(draw);drawRef.current = draw;- // DPR-aware canvas sizing + redraw on container resize (PianoRoll pattern).- useEffect(() => {- const el = wrapRef.current;- if (!el) return undefined;- const resize = () => {- const w = Math.floor(el.clientWidth);- if (!w) return;- widthRef.current = w;- const canvas = canvasRef.current;- if (!canvas) return;- const dpr = (typeof window !== 'undefined' && window.devicePixelRatio) || 1;- canvas.width = Math.round(w * dpr);- canvas.height = Math.round(height * dpr);- canvas.style.width = `${w}px`;- canvas.style.height = `${height}px`;- const ctx = canvas.getContext('2d');- if (ctx) ctx.setTransform(dpr, 0, 0, dpr, 0, 0);- drawRef.current();- };- resize();- const ro = new ResizeObserver(resize);- ro.observe(el);- return () => ro.disconnect();- }, [height]);+ // DPR-aware canvas sizing + redraw on container resize (shared hook).+ const widthRef = useCanvasDprSize(wrapRef, canvasRef, height, drawRef);useEffect(() => { draw(); }, [draw, zoom]);+ // Coalesce pan-driven repaints to one per animation frame — wheel/pointer+ // events can fire faster than the display presents.+ const rafRef = useRef(0);+ const scheduleDraw = useCallback(() => {+ if (rafRef.current) return;+ rafRef.current = requestAnimationFrame(() => {+ rafRef.current = 0;+ drawRef.current();+ });+ }, []);+ useEffect(() => () => cancelAnimationFrame(rafRef.current), []);+const canvasPos = (e) => {const rect = canvasRef.current.getBoundingClientRect();return { x: e.clientX - rect.left, y: e.clientY - rect.top };@@ -282,29 +279,52 @@ export default function MidiPianoRoll({ data, chords, showChords, zoom, onZoomChconst sec = scroll + (x - GUTTER_W) / pps;if (chordLaneH && y >= RULER_H && y < RULER_H + chordLaneH) {const chord = (chords || []).find((c) => sec >= c.startSec && sec <= c.endSec);- return chord ? { kind: 'chord', chord, x, y } : null;+ return chord ? { kind: 'chord', chord } : null;}if (y < gridTop) return null;const midi = highMidi - Math.floor((y - gridTop) / rowH);- // Iterate back-to-front so the top-drawn (later) note wins the hit.+ // Iterate back-to-front so the top-drawn (later) note wins the hit; the+ // 2/pps term keeps min-width (2px) bars hittable.const notes = data?.notes || [];for (let i = notes.length - 1; i >= 0; i -= 1) {const n = notes[i];if (n.midi !== midi) continue;- const w = Math.max(2, n.durationSec * pps);- if (sec >= n.startSec && sec <= n.startSec + Math.max(n.durationSec, w / pps)) {- return { kind: 'note', note: n, x, y };+ if (sec >= n.startSec && sec <= n.startSec + Math.max(n.durationSec, 2 / pps)) {+ return { kind: 'note', note: n };}}return null;}, [chords, chordLaneH, data, geometry, highMidi]);+ // Update tooltip position without re-rendering: stash in a ref and mutate+ // the DOM node directly when it's mounted.+ const moveTooltip = useCallback((x, y) => {+ tooltipPosRef.current = { x, y };+ const el = tooltipRef.current;+ if (el) Object.assign(el.style, tooltipStyle(x, y, widthRef.current || 0));+ }, [widthRef]);++ // Set hover identity only when it actually changed — same note/chord under+ // the cursor returns prev, so React bails out and the canvas doesn't repaint.+ const setHoverIdentity = useCallback((hit) => {+ setHover((prev) => {+ if (!hit && !prev) return prev;+ if (hit && prev && hit.kind === prev.kind+ && (hit.kind === 'note' ? hit.note.id === prev.note.id : hit.chord === prev.chord)) {+ return prev;+ }+ return hit;+ });+ }, []);+const applyZoomAnchored = useCallback((factor, anchorX) => {const { pps } = geometry();const next = clampZoom(zoomRef.current * factor);if (next === zoomRef.current) return;const anchorSec = scrollSecRef.current + (Math.max(anchorX, GUTTER_W) - GUTTER_W) / pps;const nextPps = (pps / zoomRef.current) * next;+ // Mutate scroll BEFORE notifying the parent: the zoom prop change triggers+ // the redraw effect, which clamps and paints with the adjusted scroll.scrollSecRef.current = anchorSec - (Math.max(anchorX, GUTTER_W) - GUTTER_W) / nextPps;onZoomChange(next);}, [geometry, onZoomChange]);@@ -318,8 +338,8 @@ export default function MidiPianoRoll({ data, chords, showChords, zoom, onZoomChconst { pps } = geometry();const delta = Math.abs(e.deltaX) > Math.abs(e.deltaY) ? e.deltaX : e.deltaY;scrollSecRef.current += delta / pps;- draw();- }, [applyZoomAnchored, draw, geometry]);+ scheduleDraw();+ }, [applyZoomAnchored, geometry, scheduleDraw]);// React attaches wheel listeners passively — preventDefault needs a native// non-passive listener or the page scrolls/zooms along with the roll.@@ -357,21 +377,15 @@ export default function MidiPianoRoll({ data, chords, showChords, zoom, onZoomChif (Math.abs(dx) > 2 || tracked.moved) {scrollSecRef.current -= dx / pps;pointersRef.current.set(e.pointerId, { ...pos, moved: true });- setHover(null);- draw();+ setHoverIdentity(null);+ scheduleDraw();return;}}- // Plain hover (mouse) — tooltip hit-test.- const hit = hitTest(pos.x, pos.y);- setHover((prev) => {- if (!hit && !prev) return prev;- if (hit && prev && hit.kind === prev.kind- && (hit.kind === 'note' ? hit.note.id === prev.note.id : hit.chord === prev.chord)) {- return { ...prev, x: pos.x, y: pos.y };- }- return hit;- });+ // Plain hover (mouse) — tooltip hit-test. Position always tracks the+ // cursor; identity state only changes when a different note/chord is hit.+ moveTooltip(pos.x, pos.y);+ setHoverIdentity(hitTest(pos.x, pos.y));};const handlePointerUp = (e) => {@@ -383,13 +397,14 @@ export default function MidiPianoRoll({ data, chords, showChords, zoom, onZoomChconst pos = canvasPos(e);const hit = hitTest(pos.x, pos.y);if (hit) {- setHover(hit);+ moveTooltip(pos.x, pos.y);+ setHoverIdentity(hit);return;}const { pps, gridTop } = geometry();if (pos.x >= GUTTER_W && pos.y >= gridTop) {playheadSecRef.current = scrollSecRef.current + (pos.x - GUTTER_W) / pps;- setHover(null);+ setHoverIdentity(null);draw();}};@@ -407,22 +422,22 @@ export default function MidiPianoRoll({ data, chords, showChords, zoom, onZoomChdraw();} else if (e.key === '+' || e.key === '=') {e.preventDefault();- onZoomChange(clampZoom(zoomRef.current * 1.5));+ onZoomChange(clampZoom(zoomRef.current * ZOOM_STEP));} else if (e.key === '-') {e.preventDefault();- onZoomChange(clampZoom(zoomRef.current / 1.5));+ onZoomChange(clampZoom(zoomRef.current / ZOOM_STEP));} else if (e.key === '0') {e.preventDefault();scrollSecRef.current = 0;onZoomChange(MIN_ZOOM);draw(); // zoom may already be at MIN_ZOOM — the scroll reset still needs a repaint} else if (e.key === 'Escape') {- setHover(null);+ setHoverIdentity(null);}};const tooltip = hover && (hover.kind === 'note'- ? `${hover.note.name} · ${formatTimecode(hover.note.startSec)} · ${Math.round(hover.note.durationSec * 1000)}ms · v=${Math.round((hover.note.velocity ?? 0) * 127)}${(data?.tracks?.length || 1) > 1 ? ` · track ${hover.note.track}` : ''}`+ ? `${hover.note.name} · ${formatTimecode(hover.note.startSec)} · ${Math.round(hover.note.durationSec * 1000)}ms · v=${Math.round((hover.note.velocity ?? 0) * 127)}${multiTrack ? ` · track ${hover.note.track}` : ''}`: `${hover.chord.label} · ${chordNoteNames(hover.chord.midis)}`);return (@@ -436,16 +451,14 @@ export default function MidiPianoRoll({ data, chords, showChords, zoom, onZoomChonPointerDown={handlePointerDown}onPointerMove={handlePointerMove}onPointerUp={handlePointerUp}- onPointerLeave={() => { pointersRef.current.clear(); pinchRef.current = null; setHover(null); }}+ onPointerLeave={() => { pointersRef.current.clear(); pinchRef.current = null; setHoverIdentity(null); }}onKeyDown={handleKeyDown}/>{tooltip && (<div+ ref={tooltipRef}className="pointer-events-none absolute z-10 px-1.5 py-0.5 rounded bg-black/90 border border-port-border text-[10px] text-gray-200 whitespace-nowrap"- style={{- left: Math.min(hover.x + 10, Math.max(0, (widthRef.current || 0) - 170)),- top: Math.max(0, hover.y - 24),- }}+ style={tooltipStyle(tooltipPosRef.current.x, tooltipPosRef.current.y, widthRef.current || 0)}>{tooltip}</div>diff --git a/client/src/components/songs/MidiVisualization.jsx b/client/src/components/songs/MidiVisualization.jsxindex ddb686b6c5..973f38a6e3 100644--- a/client/src/components/songs/MidiVisualization.jsx+++ b/client/src/components/songs/MidiVisualization.jsx@@ -3,9 +3,9 @@ import { ChevronDown, ChevronRight, Download, Loader2, Maximize2, Minimize2, Zooimport useMidiNotes from '../../hooks/useMidiNotes';import { detectChordWindows } from '../../lib/midiChords';import { midiNoteName } from '../../lib/pianoKeyboard';+import { layerColor } from '../../lib/canvasRoll.js';import { formatTimecode } from '../../utils/formatters';-import MidiPianoRoll, { MIN_ZOOM, clampZoom } from './MidiPianoRoll.jsx';-import { layerColor } from './PianoRoll.jsx';+import MidiPianoRoll, { MIN_ZOOM, ZOOM_STEP, clampZoom } from './MidiPianoRoll.jsx';// Chrome around <MidiPianoRoll>: loads + parses the .mid (useMidiNotes),// detects chords, and wraps the roll in a collapsible panel with a toolbar@@ -16,6 +16,20 @@ import { layerColor } from './PianoRoll.jsx';const COMPACT_H = 200;const EXPANDED_H = 380;+// Chord windows keyed by the parsed view-model's identity: useMidiNotes caches+// view-models per URL, so a collapse/expand remount reuses the same object and+// skips the re-sweep — the chord cache rides the parse cache's lifetime.+const chordCache = new WeakMap();+const chordsFor = (data) => {+ if (!data) return [];+ let chords = chordCache.get(data);+ if (!chords) {+ chords = detectChordWindows(data.notes);+ chordCache.set(data, chords);+ }+ return chords;+};+/*** @param {object} props* @param {string} props.url — resolved URL of the transcribed .mid file.@@ -29,7 +43,7 @@ export default function MidiVisualization({ url, filename, model }) {const [showChords, setShowChords] = useState(true);const { status, data, error, reload } = useMidiNotes(open ? url : null);- const chords = useMemo(() => (data ? detectChordWindows(data.notes) : []), [data]);+ const chords = useMemo(() => chordsFor(data), [data]);if (!url) return null;@@ -53,11 +67,11 @@ 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={() => setZoom((z) => clampZoom(z / 1.5))} aria-label="Zoom out"+ <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} /></button>- <button type="button" onClick={() => setZoom((z) => clampZoom(z * 1.5))} aria-label="Zoom in"+ <button type="button" onClick={() => setZoom((z) => clampZoom(z * ZOOM_STEP))} aria-label="Zoom in"className="p-1 rounded text-gray-400 hover:text-white hover:bg-port-border/50" title="Zoom in (+)"><ZoomIn size={13} /></button>@@ -92,17 +106,21 @@ export default function MidiVisualization({ url, filename, model }) {</div>{open && (<div className="px-2 pb-2">- {status === 'loading' && (- <div className="flex items-center justify-center gap-2 rounded-lg bg-[#0c0c0e] text-xs text-gray-400" style={{ height: COMPACT_H }}>- <Loader2 size={14} className="animate-spin" /> Parsing MIDI…- </div>- )}- {status === 'error' && (- <div className="flex items-center justify-center gap-2 rounded-lg bg-[#0c0c0e] text-xs text-port-error" style={{ height: COMPACT_H }}>- <span>{error}</span>- <button type="button" onClick={reload} className="px-1.5 py-0.5 rounded border border-port-border text-gray-300 hover:text-white">- Retry- </button>+ {(status === 'loading' || status === 'error') && (+ <div+ className={`flex items-center justify-center gap-2 rounded-lg bg-[#0c0c0e] text-xs ${status === 'error' ? 'text-port-error' : 'text-gray-400'}`}+ style={{ height: COMPACT_H }}+ >+ {status === 'loading' ? (+ <><Loader2 size={14} className="animate-spin" /> Parsing MIDI…</>+ ) : (+ <>+ <span>{error}</span>+ <button type="button" onClick={reload} className="px-1.5 py-0.5 rounded border border-port-border text-gray-300 hover:text-white">+ Retry+ </button>+ </>+ )}</div>)}{status === 'ready' && data && (diff --git a/client/src/components/songs/PianoRoll.jsx b/client/src/components/songs/PianoRoll.jsxindex 504cf1ff1b..8d5a75b4d8 100644--- a/client/src/components/songs/PianoRoll.jsx+++ b/client/src/components/songs/PianoRoll.jsx@@ -7,6 +7,8 @@ import {midiNoteName,BLACK_KEY_HEIGHT_RATIO,} from '../../lib/pianoKeyboard';+import { roundRect } from '../../lib/canvasRoll.js';+import useCanvasDprSize from '../../hooks/useCanvasDprSize.js';// Synthesia-style piano-roll visualizer for the song system's layered MIDI// player. Renders every selected lead-sheet part as colored notes falling onto@@ -20,10 +22,9 @@ import {// sample-aligned with the audio rather than running its own timer.// Per-layer colors, assigned by part index in the parent so the keyboard, the-// falling notes and the layer checkboxes all agree. Bright, distinct hues that-// read on the near-black canvas.-const LAYER_COLORS = ['#3b82f6', '#22c55e', '#f59e0b', '#ec4899', '#a855f7', '#06b6d4', '#ef4444', '#14b8a6'];-export const layerColor = (index) => LAYER_COLORS[((index % LAYER_COLORS.length) + LAYER_COLORS.length) % LAYER_COLORS.length];+// falling notes and the layer checkboxes all agree. Re-exported from the+// shared canvas-roll palette so <MidiPianoRoll> and legends use the same hues.+export { layerColor } from '../../lib/canvasRoll.js';const VISIBLE_SECONDS = 3.4; // how far ahead the falling notes are shown (fall speed)const KEYBOARD_HEIGHT = 64; // px of keyboard at the bottom@@ -36,18 +37,6 @@ const HIT_LINE = '#3b82f6';const GRID_LINE = 'rgba(255,255,255,0.05)';const BG = '#0c0c0e';-const roundRect = (ctx, x, y, w, h, r) => {- const rr = Math.max(0, Math.min(r, w / 2, h / 2));- if (ctx.roundRect) { ctx.beginPath(); ctx.roundRect(x, y, w, h, rr); return; }- ctx.beginPath();- ctx.moveTo(x + rr, y);- ctx.arcTo(x + w, y, x + w, y + h, rr);- ctx.arcTo(x + w, y + h, x, y + h, rr);- ctx.arcTo(x, y + h, x, y, rr);- ctx.arcTo(x, y, x + w, y, rr);- ctx.closePath();-};-/*** @param {object} props* @param {Array<{id:string,label:string,color:string,score:string}>} props.parts@@ -62,7 +51,6 @@ const roundRect = (ctx, x, y, w, h, r) => {export default function PianoRoll({ parts, tempo, getPosition, playing, height = 300 }) {const wrapRef = useRef(null);const canvasRef = useRef(null);- const widthRef = useRef(0);// Keep the latest getPosition without making it a draw() dependency (the parent// hands a fresh closure each render; the rAF loop should not restart for that).const getPositionRef = useRef(getPosition);@@ -179,29 +167,7 @@ export default function PianoRoll({ parts, tempo, getPosition, playing, height =drawRef.current = draw;// Size the canvas to the container (devicePixelRatio-aware) and redraw.- useEffect(() => {- const el = wrapRef.current;- if (!el) return undefined;- const resize = () => {- const w = Math.floor(el.clientWidth);- if (!w) return;- widthRef.current = w;- const canvas = canvasRef.current;- if (!canvas) return;- const dpr = (typeof window !== 'undefined' && window.devicePixelRatio) || 1;- canvas.width = Math.round(w * dpr);- canvas.height = Math.round(height * dpr);- canvas.style.width = `${w}px`;- canvas.style.height = `${height}px`;- const ctx = canvas.getContext('2d');- if (ctx) ctx.setTransform(dpr, 0, 0, dpr, 0, 0);- drawRef.current();- };- resize();- const ro = new ResizeObserver(resize);- ro.observe(el);- return () => ro.disconnect();- }, [height]);+ const widthRef = useCanvasDprSize(wrapRef, canvasRef, height, drawRef);// rAF clock: animate the fall while playing, otherwise draw a single frame.useEffect(() => {diff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex 28d3779c15..ea0f2a3158 100644--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@ -158,4 +158,5 @@ grep -i "what you want to do" client/src/hooks/README.md| `useVideoDownload` | One full-video-download job slot (#1946): start/cancel + SSE progress + terminal-frame handling via `POST /api/devtools/video-download`. Returns `{ active, percent, stage, start(url), cancel }`; `onComplete(video)` fires with the finished video-history entry. | The Dev Tools Video Downloader page. || `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. || `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). |diff --git a/client/src/hooks/index.js b/client/src/hooks/index.jsindex 1ea87a99bb..ec45e7a2a6 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 useCanvasDprSize } from './useCanvasDprSize.js';// === Mixed (both default and named) — surface both ===export { default as useAsyncAction } from './useAsyncAction.js';diff --git a/client/src/hooks/useCanvasDprSize.js b/client/src/hooks/useCanvasDprSize.jsnew file mode 100644index 0000000000..34de6a2659--- /dev/null+++ b/client/src/hooks/useCanvasDprSize.js@@ -0,0 +1,43 @@+import { useEffect, useRef } from 'react';++// DevicePixelRatio-aware canvas sizing shared by the piano-roll renderers+// (<PianoRoll>, <MidiPianoRoll>). Sizes the canvas bitmap to the container+// width × the given CSS height at the device pixel ratio, keeps the CSS size+// in plain px, applies the DPR transform, and redraws — on mount and on every+// container resize (ResizeObserver).+//+// `drawRef` is a ref to the latest draw() (not the function itself) so the+// observer is created once per height and never torn down just because the+// draw closure was recreated.+//+// Returns a ref holding the current CSS width — the draw code reads it+// instead of measuring the DOM per frame.+export default function useCanvasDprSize(wrapRef, canvasRef, height, drawRef) {+ const widthRef = useRef(0);++ useEffect(() => {+ const el = wrapRef.current;+ if (!el) return undefined;+ const resize = () => {+ const w = Math.floor(el.clientWidth);+ if (!w) return;+ widthRef.current = w;+ const canvas = canvasRef.current;+ if (!canvas) return;+ const dpr = (typeof window !== 'undefined' && window.devicePixelRatio) || 1;+ canvas.width = Math.round(w * dpr);+ canvas.height = Math.round(height * dpr);+ canvas.style.width = `${w}px`;+ canvas.style.height = `${height}px`;+ const ctx = canvas.getContext('2d');+ if (ctx) ctx.setTransform(dpr, 0, 0, dpr, 0, 0);+ drawRef.current();+ };+ resize();+ const ro = new ResizeObserver(resize);+ ro.observe(el);+ return () => ro.disconnect();+ }, [height, wrapRef, canvasRef, drawRef]);++ return widthRef;+}diff --git a/client/src/hooks/useMidiNotes.js b/client/src/hooks/useMidiNotes.jsindex 597ae344c4..d0c38ca66e 100644--- a/client/src/hooks/useMidiNotes.js+++ b/client/src/hooks/useMidiNotes.js@@ -9,7 +9,20 @@ import { parseMidiFile } from '../lib/midiNotes.js';// url → parsed view-model. Parsed models are small (notes only, no raw bytes);// null is never cached ("not fetched" and "cached-empty" must stay distinct).+// LRU-capped so a long session browsing many transcriptions doesn't+// accumulate unbounded parsed note lists on the heap.+const CACHE_MAX = 16;const cache = new Map();+const cachePut = (url, data) => {+ cache.delete(url); // re-insert so Map iteration order is least-recent first+ cache.set(url, data);+ if (cache.size > CACHE_MAX) cache.delete(cache.keys().next().value);+};+const cacheGet = (url) => {+ const data = cache.get(url);+ if (data !== undefined) cachePut(url, data); // refresh recency+ return data;+};/** Test-only: clear the module-level parse cache between cases. */export const __clearMidiNotesCache = () => cache.clear();@@ -30,8 +43,9 @@ export default function useMidiNotes(url) {setState({ status: 'idle', data: null, error: null });return;}- if (!force && cache.has(targetUrl)) {- setState({ status: 'ready', data: cache.get(targetUrl), error: null });+ const cached = force ? undefined : cacheGet(targetUrl);+ if (cached !== undefined) {+ setState({ status: 'ready', data: cached, error: null });return;}setState({ status: 'loading', data: null, error: null });@@ -42,7 +56,7 @@ export default function useMidiNotes(url) {}).then((buf) => {const data = parseMidiFile(buf);- cache.set(targetUrl, data);+ cachePut(targetUrl, data);if (generationRef.current === generation) setState({ status: 'ready', data, error: null });}).catch((err) => {diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex bd3b42264b..02e87abbc6 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -107,6 +107,7 @@ grep -i "what you want to do" client/src/lib/README.md| Module | Purpose ||---|---|| `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. || `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). |@@ -116,7 +117,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`). |-| `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), and the `BLACK_KEY_RATIO`/`BLACK_KEY_HEIGHT_RATIO` constants. Pairs with `scorePlayback`'s per-note `midi` field. |+| `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. || `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→`{ midi, freq, startSec, durSec }` mapping (A4=440, quarter-beat = `(60/bpm)·(beatValue/4)` so it honors the time signature; `midi` feeds the `<PianoRoll>` key mapping); `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; `createMultiScorePlayer(parts, { bpm, onNote, onEnded })` synthesizes several parts (melody + checked harmony) together on one master bus (level backs off as voices stack) with a per-part `onNote(partId, index)` playhead, plus `position()`/`duration()` (score-seconds) for the continuous piano-roll visualizer. |diff --git a/client/src/lib/canvasRoll.js b/client/src/lib/canvasRoll.jsnew file mode 100644index 0000000000..36464f6ea3--- /dev/null+++ b/client/src/lib/canvasRoll.js@@ -0,0 +1,22 @@+// Shared canvas helpers for the two piano-roll renderers — the Synthesia+// falling-note <PianoRoll> (score playback) and the DAW-style <MidiPianoRoll>+// (transcribed .mid inspection, #2477). Pure canvas math/palette, no React.++// Per-layer/track colors, assigned by index so keyboards, note bars, and+// legends all agree. Bright, distinct hues that read on the near-black canvas.+const LAYER_COLORS = ['#3b82f6', '#22c55e', '#f59e0b', '#ec4899', '#a855f7', '#06b6d4', '#ef4444', '#14b8a6'];+export const layerColor = (index) => LAYER_COLORS[((index % LAYER_COLORS.length) + LAYER_COLORS.length) % LAYER_COLORS.length];++// Rounded-rect path with a feature-detect for ctx.roundRect (arcTo fallback+// for older canvas implementations). Callers fill()/stroke() the path.+export const roundRect = (ctx, x, y, w, h, r) => {+ const rr = Math.max(0, Math.min(r, w / 2, h / 2));+ if (ctx.roundRect) { ctx.beginPath(); ctx.roundRect(x, y, w, h, rr); return; }+ ctx.beginPath();+ ctx.moveTo(x + rr, y);+ ctx.arcTo(x + w, y, x + w, y + h, rr);+ ctx.arcTo(x + w, y + h, x, y + h, rr);+ ctx.arcTo(x, y + h, x, y, rr);+ ctx.arcTo(x, y, x + w, y, rr);+ ctx.closePath();+};diff --git a/client/src/lib/index.js b/client/src/lib/index.jsindex f15db4af0a..e38bf28f98 100644--- a/client/src/lib/index.js+++ b/client/src/lib/index.js@@ -77,6 +77,7 @@ export * from './voiceLabel.js';// === Page-scoped pure helpers ===export * from './cityPlaybackFrame.js';+export * from './canvasRoll.js';export * from './colorMatch.js';export * from './editorialChecks.js';export * from './editorialHealth.js';diff --git a/client/src/lib/midiChords.js b/client/src/lib/midiChords.jsindex 74a81a2f9f..7222d5478d 100644--- a/client/src/lib/midiChords.js+++ b/client/src/lib/midiChords.js@@ -4,9 +4,7 @@// chord symbol (Cmaj7, Am, G/B, …) — or, when no dictionary shape matches,// the sorted pitch-class names (never a wrong guess). No canvas/React.-import { midiNoteName } from './pianoKeyboard.js';--const PITCH_CLASS_NAMES = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B'];+import { midiNoteName, pitchClass as pc, PITCH_CLASS_NAMES } from './pianoKeyboard.js';// Minimum overlap for a window to count as an intentional chord rather than a// passing-note smear (see issue #2477 — 40–80ms band; midpoint chosen).@@ -29,7 +27,6 @@ const CHORD_SHAPES = [{ intervals: [0, 5, 7], suffix: 'sus4' },];-const pc = (midi) => ((midi % 12) + 12) % 12;const sameSet = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]);/**@@ -62,14 +59,12 @@ export const nameChord = (pcs, bassPc) => {* simultaneously-sounding pitch classes stays constant and has ≥2 members.** @param {Array<{midi:number,startSec:number,durationSec:number}>} notes —- * normalized notes from parseMidiFile (any order).- * @param {object} [opts]- * @param {number} [opts.minWindowSec=MIN_CHORD_WINDOW_SEC] — windows shorter- * than this are dropped as passing-note noise.+ * normalized notes from parseMidiFile (any order). Windows shorter than+ * MIN_CHORD_WINDOW_SEC are dropped as passing-note noise.* @returns {Array<{startSec:number,endSec:number,label:string,midis:number[]}>}* consecutive windows with the same label are merged.*/-export const detectChordWindows = (notes, { minWindowSec = MIN_CHORD_WINDOW_SEC } = {}) => {+export const detectChordWindows = (notes) => {const edges = [];(notes || []).forEach((n) => {if (!Number.isFinite(n.midi) || !Number.isFinite(n.startSec)) return;@@ -82,17 +77,16 @@ export const detectChordWindows = (notes, { minWindowSec = MIN_CHORD_WINDOW_SECconst sounding = new Map(); // midi → active count (handles overlapping same-pitch notes)const windows = [];- let spanStart = null;- let spanMidis = null;+ // Open span: the sounding-set is immutable while a span is open, so the+ // sorted midis and their comparison key are computed once at open time.+ let span = null; // { startSec, key, midis: number[] (sorted) }const closeSpan = (t) => {- if (spanStart == null) return;- if (t - spanStart >= minWindowSec) {- const midis = [...spanMidis].sort((a, b) => a - b);- const label = nameChord(midis.map(pc), pc(midis[0]));- if (label) windows.push({ startSec: spanStart, endSec: t, label, midis });+ if (!span) return;+ if (t - span.startSec >= MIN_CHORD_WINDOW_SEC) {+ const label = nameChord(span.midis.map(pc), pc(span.midis[0]));+ if (label) windows.push({ startSec: span.startSec, endSec: t, label, midis: span.midis });}- spanStart = null;- spanMidis = null;+ span = null;};let i = 0;@@ -106,15 +100,12 @@ export const detectChordWindows = (notes, { minWindowSec = MIN_CHORD_WINDOW_SECelse sounding.delete(e.midi);i += 1;}- const midis = [...sounding.keys()];- const pcs = new Set(midis.map(pc));- if (pcs.size >= 2) {- const key = midis.sort((a, b) => a - b).join(',');- const prevKey = spanMidis ? [...spanMidis].sort((a, b) => a - b).join(',') : null;- if (key !== prevKey) {+ const midis = [...sounding.keys()].sort((a, b) => a - b);+ if (new Set(midis.map(pc)).size >= 2) {+ const key = midis.join(',');+ if (key !== span?.key) {closeSpan(t);- spanStart = t;- spanMidis = new Set(midis);+ span = { startSec: t, key, midis };}} else {closeSpan(t);diff --git a/client/src/lib/pianoKeyboard.js b/client/src/lib/pianoKeyboard.jsindex c9b4d81ff7..1c9a366002 100644--- a/client/src/lib/pianoKeyboard.js+++ b/client/src/lib/pianoKeyboard.js@@ -8,10 +8,14 @@// Pitch classes (semitone within an octave) that map to WHITE keys. Everything// else is a black key.const WHITE_PITCH_CLASSES = new Set([0, 2, 4, 5, 7, 9, 11]);-const NOTE_NAMES = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B'];++// Canonical sharps-spelling pitch-class name table — the single source for+// note/chord naming (referenceAnalysis.js re-exports it; midiChords.js+// consumes it). A spelling change here must not fork per consumer.+export const PITCH_CLASS_NAMES = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B'];// Positive modulo so negative MIDI numbers (below C-1) still classify correctly.-const pitchClass = (midi) => ((midi % 12) + 12) % 12;+export const pitchClass = (midi) => ((midi % 12) + 12) % 12;// True when this MIDI note is a black (sharp/flat) key.export const isBlackKey = (midi) => !WHITE_PITCH_CLASSES.has(pitchClass(midi));@@ -19,7 +23,7 @@ export const isBlackKey = (midi) => !WHITE_PITCH_CLASSES.has(pitchClass(midi));// Scientific note name for a MIDI number (sharps spelling). MIDI 60 → "C4".export const midiNoteName = (midi) => {if (!Number.isFinite(midi)) return '';- return `${NOTE_NAMES[pitchClass(midi)]}${Math.floor(midi / 12) - 1}`;+ return `${PITCH_CLASS_NAMES[pitchClass(midi)]}${Math.floor(midi / 12) - 1}`;};// Black-key width as a fraction of a white-key width (real pianos ≈ 0.6).diff --git a/client/src/lib/referenceAnalysis.js b/client/src/lib/referenceAnalysis.jsindex 15c78994e3..3228ace9c9 100644--- a/client/src/lib/referenceAnalysis.js+++ b/client/src/lib/referenceAnalysis.js@@ -444,8 +444,10 @@ const LETTER_PC = { C: 0, D: 2, E: 4, F: 5, G: 7, A: 9, B: 11 };const ACCIDENTAL_SHIFT = { '': 0, n: 0, '#': 1, '##': 2, b: -1, bb: -2 };// Display names for pitch classes (sharp spelling — labels only; the score-// text itself is already spelled from the key signature).-export const PITCH_CLASS_NAMES = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B'];+// text itself is already spelled from the key signature). Re-export of the+// canonical table in pianoKeyboard.js so note and chord labels can't drift+// apart (#2477 promoted the shared constant).+export { PITCH_CLASS_NAMES } from './pianoKeyboard.js';// Pitch class (0–11) of a parsed note's pitch, or null when unmappable.const notePitchClass = (pitch) => {diff --git a/client/src/pages/MusicVideo.jsx b/client/src/pages/MusicVideo.jsxindex 24599ba9f0..17a872ea3b 100644--- a/client/src/pages/MusicVideo.jsx+++ b/client/src/pages/MusicVideo.jsx@@ -745,6 +745,7 @@ export default function MusicVideo() {const audioFile = projectAudioFilename(selected);if (!audioFile) return null;const audioUrl = trackAudioUrl(audioFile);+ const midiFile = selected.midiTranscription?.filename;return (<div className="mt-2 flex flex-col gap-2"><div className="flex flex-wrap items-center gap-2">@@ -754,18 +755,15 @@ export default function MusicVideo() {className="flex items-center gap-1 bg-port-bg border border-port-border rounded px-2 py-1 text-xs hover:bg-port-border/40"><Download size={13} /> Download audio</a>- {selected.midiTranscription?.filename && (- <a href={trackAudioUrl(selected.midiTranscription.filename)} download- title={`Download the MIDI transcription (MuScriptor ${selected.midiTranscription.model || ''})`}- className="flex items-center gap-1 bg-port-bg border border-port-border rounded px-2 py-1 text-xs text-port-accent hover:bg-port-border/40">- <Music size={13} /> Download MIDI- </a>- )}</div>- {selected.midiTranscription?.filename && (+ {/* The visualization panel owns the MIDI download button, so no+ separate Download-MIDI anchor here (#2477). Served from the+ music dir (same static route as the master audio) so the+ federated .mid resolves on peers too. */}+ {midiFile && (<MidiVisualization- url={trackAudioUrl(selected.midiTranscription.filename)}- filename={selected.midiTranscription.filename}+ url={trackAudioUrl(midiFile)}+ filename={midiFile}model={selected.midiTranscription.model}/>)}