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-2477]): add interactive piano-roll MIDI visualization for MuScriptor transcriptions
[._.]/ Adam Eivy0f1c17444d28
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 3c60ddb9b7..6bf7541f88 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -1,5 +1,9 @@# Unreleased Changes+## 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.+## Changed- **Elements Song study mode drops a redundant result field.** The Flash Cards study results tracked both `element` and `symbol` on each record even though they hold identical values; the review UI now reads the single `element` field, removing the duplicate.diff --git a/client/src/components/songs/MidiPianoRoll.jsx b/client/src/components/songs/MidiPianoRoll.jsxnew file mode 100644index 0000000000..76770768a5--- /dev/null+++ b/client/src/components/songs/MidiPianoRoll.jsx@@ -0,0 +1,455 @@+import { useCallback, useEffect, useRef, useState } from 'react';+import { midiNoteName, isBlackKey } from '../../lib/pianoKeyboard';+import { chordNoteNames } from '../../lib/midiChords';+import { formatTimecode } from '../../utils/formatters';+import { layerColor } from './PianoRoll.jsx';++// DAW-style horizontal piano-roll for inspecting a transcribed `.mid` file+// (time × pitch grid) — NOT the Synthesia falling-note <PianoRoll>, which is+// score-playback pedagogy. Presentational: gets the parsed view-model from+// midiNotes.js via props and only draws + handles pointer/keyboard input.+//+// 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.++const GUTTER_W = 44; // left pitch gutter+const RULER_H = 18; // top time ruler+const CHORD_H = 20; // chord lane strip (when shown)+const BG = '#0c0c0e';+const GUTTER_BG = '#131316';+const ACCENT = '#3b82f6';+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;++// Zoom is a multiplier over fit-to-width (1 = whole file visible).+export const MIN_ZOOM = 1;+export const MAX_ZOOM = 64;+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;+};++/**+ * @param {object} props+ * @param {object} props.data — view-model from parseMidiFile.+ * @param {Array} props.chords — windows from detectChordWindows.+ * @param {boolean} props.showChords+ * @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.+ */+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 zoomRef = useRef(zoom);+ zoomRef.current = zoom;++ const duration = Math.max(data?.durationSec || 0, 0.001);+ const chordLaneH = showChords && chords?.length ? CHORD_H : 0;++ // Pitch rows: pad one semitone each side, widen to at least an octave.+ let lowMidi = Math.max(0, (data?.minMidi ?? 60) - 1);+ let highMidi = Math.min(127, (data?.maxMidi ?? 71) + 1);+ if (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));+ }+ const rowCount = highMidi - lowMidi + 1;++ const geometry = useCallback(() => {+ const width = widthRef.current;+ const gridW = Math.max(1, width - GUTTER_W);+ const fitPps = gridW / duration;+ const pps = fitPps * zoomRef.current;+ const gridTop = RULER_H + chordLaneH;+ const gridH = Math.max(1, height - gridTop);+ const rowH = gridH / rowCount;+ const maxScroll = Math.max(0, duration - gridW / pps);+ return { 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();+ if (!canvas || !width) return;+ const ctx = canvas.getContext('2d');+ if (!ctx) return;+ scrollSecRef.current = Math.min(Math.max(0, scrollSecRef.current), maxScroll);+ const scroll = scrollSecRef.current;+ const viewEnd = scroll + gridW / pps;+ 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 — every semitone faint, 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);+ 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;+ ctx.fillText(formatTimecode(t).replace(/\.\d+$/, ''), 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();+ });+ }++ // Notes — only those intersecting the visible window, clipped to the grid.+ 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';+ (data?.notes || []).forEach((n) => {+ const end = n.startSec + n.durationSec;+ if (end < scroll || n.startSec > viewEnd) return;+ if (n.midi < lowMidi || n.midi > highMidi) return;+ 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.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();+ }+ 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));+ }+ });+ ctx.restore();++ // Playhead (static scrub position in v1 — click to move).+ const px = timeToX(playheadSecRef.current);+ if (px >= GUTTER_W && px <= width) {+ ctx.fillStyle = ACCENT;+ ctx.fillRect(px - 1, RULER_H, 2, height - RULER_H);+ }++ // 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 (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));+ }+ }+ // 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, noteColor]);++ 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]);++ useEffect(() => { draw(); }, [draw, zoom]);++ const canvasPos = (e) => {+ const rect = canvasRef.current.getBoundingClientRect();+ return { x: e.clientX - rect.left, y: e.clientY - rect.top };+ };++ const hitTest = useCallback((x, y) => {+ const { gridW, pps, gridTop, rowH } = geometry();+ const scroll = scrollSecRef.current;+ if (x < GUTTER_W || x > GUTTER_W + gridW) return null;+ const 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;+ }+ 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.+ 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 };+ }+ }+ return null;+ }, [chords, chordLaneH, data, geometry, highMidi]);++ 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;+ scrollSecRef.current = anchorSec - (Math.max(anchorX, GUTTER_W) - GUTTER_W) / nextPps;+ onZoomChange(next);+ }, [geometry, onZoomChange]);++ const handleWheel = useCallback((e) => {+ e.preventDefault();+ if (e.ctrlKey || e.metaKey) {+ applyZoomAnchored(e.deltaY < 0 ? 1.25 : 0.8, canvasPos(e).x);+ return;+ }+ const { pps } = geometry();+ const delta = Math.abs(e.deltaX) > Math.abs(e.deltaY) ? e.deltaX : e.deltaY;+ scrollSecRef.current += delta / pps;+ draw();+ }, [applyZoomAnchored, draw, geometry]);++ // React attaches wheel listeners passively — preventDefault needs a native+ // non-passive listener or the page scrolls/zooms along with the roll.+ useEffect(() => {+ const canvas = canvasRef.current;+ if (!canvas) return undefined;+ canvas.addEventListener('wheel', handleWheel, { passive: false });+ return () => canvas.removeEventListener('wheel', handleWheel);+ }, [handleWheel]);++ const handlePointerDown = (e) => {+ canvasRef.current.setPointerCapture?.(e.pointerId);+ pointersRef.current.set(e.pointerId, { ...canvasPos(e), moved: false });+ if (pointersRef.current.size === 2) {+ const [a, b] = [...pointersRef.current.values()];+ pinchRef.current = { startDist: Math.abs(a.x - b.x) || 1, startZoom: zoomRef.current };+ }+ };++ const handlePointerMove = (e) => {+ const pos = canvasPos(e);+ const tracked = pointersRef.current.get(e.pointerId);+ if (tracked) {+ // Pinch zoom (two pointers) or drag pan (one pointer).+ if (pointersRef.current.size === 2 && pinchRef.current) {+ pointersRef.current.set(e.pointerId, { ...pos, moved: true });+ const [a, b] = [...pointersRef.current.values()];+ const dist = Math.abs(a.x - b.x) || 1;+ const next = clampZoom(pinchRef.current.startZoom * (dist / pinchRef.current.startDist));+ if (next !== zoomRef.current) onZoomChange(next);+ return;+ }+ const { pps } = geometry();+ const dx = pos.x - tracked.x;+ if (Math.abs(dx) > 2 || tracked.moved) {+ scrollSecRef.current -= dx / pps;+ pointersRef.current.set(e.pointerId, { ...pos, moved: true });+ setHover(null);+ draw();+ 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;+ });+ };++ const handlePointerUp = (e) => {+ const tracked = pointersRef.current.get(e.pointerId);+ pointersRef.current.delete(e.pointerId);+ if (pointersRef.current.size < 2) pinchRef.current = null;+ if (!tracked || tracked.moved) return;+ // A tap/click: on a note → tooltip (touch fallback); else → scrub playhead.+ const pos = canvasPos(e);+ const hit = hitTest(pos.x, pos.y);+ if (hit) {+ setHover(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);+ draw();+ }+ };++ const handleKeyDown = (e) => {+ const { pps, gridW } = geometry();+ if (e.key === 'ArrowLeft' || e.key === 'ArrowRight') {+ e.preventDefault();+ const dir = e.key === 'ArrowLeft' ? -1 : 1;+ if (e.shiftKey) {+ scrollSecRef.current += dir * (gridW / pps) * 0.5;+ } else {+ playheadSecRef.current = Math.min(duration, Math.max(0, playheadSecRef.current + dir * (10 / pps)));+ }+ draw();+ } else if (e.key === '+' || e.key === '=') {+ e.preventDefault();+ onZoomChange(clampZoom(zoomRef.current * 1.5));+ } else if (e.key === '-') {+ e.preventDefault();+ onZoomChange(clampZoom(zoomRef.current / 1.5));+ } 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);+ }+ };++ 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.chord.label} · ${chordNoteNames(hover.chord.midis)}`);++ return (+ <div ref={wrapRef} className="relative w-full">+ <canvas+ ref={canvasRef}+ className="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.`}+ onPointerDown={handlePointerDown}+ onPointerMove={handlePointerMove}+ onPointerUp={handlePointerUp}+ onPointerLeave={() => { pointersRef.current.clear(); pinchRef.current = null; setHover(null); }}+ onKeyDown={handleKeyDown}+ />+ {tooltip && (+ <div+ 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),+ }}+ >+ {tooltip}+ </div>+ )}+ </div>+ );+}diff --git a/client/src/components/songs/MidiVisualization.jsx b/client/src/components/songs/MidiVisualization.jsxnew file mode 100644index 0000000000..ddb686b6c5--- /dev/null+++ b/client/src/components/songs/MidiVisualization.jsx@@ -0,0 +1,146 @@+import { useMemo, useState } from 'react';+import { ChevronDown, ChevronRight, Download, Loader2, Maximize2, Minimize2, ZoomIn, ZoomOut } from 'lucide-react';+import useMidiNotes from '../../hooks/useMidiNotes';+import { detectChordWindows } from '../../lib/midiChords';+import { midiNoteName } from '../../lib/pianoKeyboard';+import { formatTimecode } from '../../utils/formatters';+import MidiPianoRoll, { MIN_ZOOM, clampZoom } from './MidiPianoRoll.jsx';+import { layerColor } from './PianoRoll.jsx';++// Chrome around <MidiPianoRoll>: loads + parses the .mid (useMidiNotes),+// detects chords, and wraps the roll in a collapsible panel with a toolbar+// (zoom/fit/chords/download) and a QA stats footer. Shared by the Rounds+// ReferenceAnalysis and Music Video surfaces — mount this, never a second+// copy of the roll wiring.++const COMPACT_H = 200;+const EXPANDED_H = 380;++/**+ * @param {object} props+ * @param {string} props.url — resolved URL of the transcribed .mid file.+ * @param {string} [props.filename] — download name for the MIDI link.+ * @param {string} [props.model] — MuScriptor model label for the footer.+ */+export default function MidiVisualization({ url, filename, model }) {+ const [open, setOpen] = useState(true);+ const [expanded, setExpanded] = useState(false);+ const [zoom, setZoom] = useState(MIN_ZOOM);+ const [showChords, setShowChords] = useState(true);+ const { status, data, error, reload } = useMidiNotes(open ? url : null);++ const chords = useMemo(() => (data ? detectChordWindows(data.notes) : []), [data]);++ if (!url) return null;++ const multiTrack = (data?.tracks?.length || 0) > 1;+ const density = data && data.durationSec > 0 ? data.notes.length / data.durationSec : 0;+ const densityLabel = density > 8 ? 'dense polyphony' : density > 3 ? 'moderate density' : 'sparse';++ return (+ <div className="w-full rounded-lg border border-port-border bg-port-card/50">+ <div className="flex flex-wrap items-center gap-1.5 px-2 py-1.5">+ <button+ type="button"+ onClick={() => setOpen((v) => !v)}+ aria-expanded={open}+ aria-label={open ? 'Collapse MIDI visualization' : 'Expand MIDI visualization'}+ className="flex items-center gap-1 text-xs text-gray-300 hover:text-white"+ >+ {open ? <ChevronDown size={14} /> : <ChevronRight size={14} />}+ <span className="font-medium">MIDI</span>+ </button>+ {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"+ 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"+ className="p-1 rounded text-gray-400 hover:text-white hover:bg-port-border/50" title="Zoom in (+)">+ <ZoomIn size={13} />+ </button>+ <button type="button" onClick={() => setZoom(MIN_ZOOM)} aria-label="Fit to width"+ className="px-1.5 py-0.5 text-[10px] rounded border border-port-border text-gray-400 hover:text-white" title="Fit the whole file (0)">+ Fit+ </button>+ {chords.length > 0 && (+ <button+ type="button"+ onClick={() => setShowChords((v) => !v)}+ aria-pressed={showChords}+ className={`px-1.5 py-0.5 text-[10px] rounded border ${showChords ? 'border-port-accent text-port-accent' : 'border-port-border text-gray-400 hover:text-white'}`}+ title="Toggle the chord lane"+ >+ Chords+ </button>+ )}+ <span className="flex-1" />+ <button type="button" onClick={() => setExpanded((v) => !v)}+ aria-label={expanded ? 'Compact height' : 'Expanded height'}+ className="p-1 rounded text-gray-400 hover:text-white hover:bg-port-border/50"+ title={expanded ? 'Compact height' : 'Expanded height'}>+ {expanded ? <Minimize2 size={13} /> : <Maximize2 size={13} />}+ </button>+ <a href={url} download={filename || true} aria-label="Download MIDI file"+ className="p-1 rounded text-port-accent hover:bg-port-border/50" title="Download the .mid file">+ <Download size={13} />+ </a>+ </>+ )}+ </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>+ </div>+ )}+ {status === 'ready' && data && (+ <>+ <MidiPianoRoll+ data={data}+ chords={chords}+ showChords={showChords}+ zoom={zoom}+ onZoomChange={setZoom}+ height={expanded ? EXPANDED_H : COMPACT_H}+ />+ <p className="sr-only">+ MIDI transcription: {data.notes.length} notes across {data.tracks.length} track{data.tracks.length === 1 ? '' : 's'},+ pitch range {midiNoteName(data.minMidi)} to {midiNoteName(data.maxMidi)}, duration {formatTimecode(data.durationSec)}.+ {chords.length > 0 && ` Detected chords include ${chords.slice(0, 8).map((c) => c.label).join(', ')}.`}+ </p>+ <div className="mt-1 flex flex-wrap items-center gap-x-3 gap-y-0.5 text-[10px] text-port-text-muted">+ <span>{`${data.notes.length} notes · ${densityLabel}`}</span>+ <span>{`${midiNoteName(data.minMidi)}–${midiNoteName(data.maxMidi)}`}</span>+ <span>{formatTimecode(data.durationSec)}</span>+ {data.tempos.length > 0 && <span>{`${data.tempos[0].bpm} BPM`}</span>}+ {model && <span>{`MuScriptor ${model}`}</span>}+ {multiTrack && (+ <span className="flex items-center gap-1.5">+ {data.tracks.map((t) => (+ <span key={t.index} className="flex items-center gap-0.5">+ <span className="inline-block w-2 h-2 rounded-sm" style={{ background: layerColor(t.index) }} aria-hidden="true" />+ {t.name || `Track ${t.index}`}+ </span>+ ))}+ </span>+ )}+ </div>+ </>+ )}+ </div>+ )}+ </div>+ );+}diff --git a/client/src/components/songs/MidiVisualization.test.jsx b/client/src/components/songs/MidiVisualization.test.jsxnew file mode 100644index 0000000000..64f497ccc6--- /dev/null+++ b/client/src/components/songs/MidiVisualization.test.jsx@@ -0,0 +1,106 @@+import { render, screen, cleanup, fireEvent } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import MidiVisualization from './MidiVisualization.jsx';+import { __clearMidiNotesCache } from '../../hooks/useMidiNotes.js';++// Tiny hand-built SMF fixture: a sustained C-major triad (C4 E4 G4) for one+// quarter at the default 120 BPM. Same builder approach as midiNotes.test.js.+const buildTriadMidi = () => {+ const str = (s) => [...s].map((c) => c.charCodeAt(0));+ const u32 = (v) => [(v >> 24) & 0xff, (v >> 16) & 0xff, (v >> 8) & 0xff, v & 0xff];+ const u16 = (v) => [(v >> 8) & 0xff, v & 0xff];+ const body = [+ 0, 0x90, 60, 100, 0, 0x90, 64, 100, 0, 0x90, 67, 100,+ 0x83, 0x60, 0x80, 60, 0, // delta 480 (varlen 0x83 0x60), then note-offs+ 0, 0x80, 64, 0,+ 0, 0x80, 67, 0,+ 0, 0xff, 0x2f, 0x00,+ ];+ return new Uint8Array([+ ...str('MThd'), ...u32(6), ...u16(0), ...u16(1), ...u16(480),+ ...str('MTrk'), ...u32(body.length), ...body,+ ]);+};++// jsdom has no canvas/ResizeObserver and reports 0 widths — stub the minimum+// (same pattern as PianoRoll.test.jsx).+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(),+ rect: vi.fn(), clip: vi.fn(), roundRect: vi.fn(), fill: vi.fn(), stroke: vi.fn(),+ moveTo: vi.fn(), arcTo: vi.fn(), setTransform: vi.fn(),+ fillStyle: '', strokeStyle: '', lineWidth: 1, font: '', textAlign: '', globalAlpha: 1,+});++describe('<MidiVisualization>', () => {+ let ctx;+ beforeEach(() => {+ __clearMidiNotesCache();+ ctx = makeCtx();+ vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue(ctx);+ vi.stubGlobal('ResizeObserver', class { observe() {} disconnect() {} });+ Object.defineProperty(HTMLElement.prototype, 'clientWidth', { configurable: true, get() { return 800; } });+ vi.stubGlobal('fetch', vi.fn(() => Promise.resolve({+ ok: true,+ arrayBuffer: () => Promise.resolve(buildTriadMidi().buffer),+ })));+ });+ afterEach(() => {+ cleanup();+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+ delete HTMLElement.prototype.clientWidth;+ });++ it('renders nothing without a url', () => {+ const { container } = render(<MidiVisualization url="" />);+ expect(container.firstChild).toBeNull();+ expect(fetch).not.toHaveBeenCalled();+ });++ it('loads, parses, and paints the roll with footer stats and sr summary', async () => {+ render(<MidiVisualization url="/uploads/test.mid" filename="test.mid" model="medium" />);+ // Loading state first, then the parsed roll.+ expect(screen.getByText(/Parsing MIDI/)).toBeTruthy();+ await screen.findByText(/3 notes · /);+ expect(ctx.fill).toHaveBeenCalled(); // note bars painted+ expect(screen.getByText(/C4–G4/)).toBeTruthy();+ expect(screen.getByText(/MuScriptor medium/)).toBeTruthy();+ // Chord lane detected the triad — toggle button present and sr summary names it.+ expect(screen.getByRole('button', { name: /chord/i })).toBeTruthy();+ expect(screen.getByText(/Detected chords include C\b/)).toBeTruthy();+ // Download link points at the file.+ const link = screen.getByLabelText('Download MIDI file');+ expect(link.getAttribute('href')).toBe('/uploads/test.mid');+ });++ it('shows an inline error with retry when the file fails to parse', async () => {+ fetch.mockImplementation(() => Promise.resolve({+ ok: true,+ arrayBuffer: () => Promise.resolve(new Uint8Array([1, 2, 3, 4]).buffer),+ }));+ render(<MidiVisualization url="/uploads/bad.mid" />);+ await screen.findByText(/Not a MIDI file/);+ expect(screen.getByRole('button', { name: /retry/i })).toBeTruthy();+ });++ it('collapses and re-expands without refetching (module cache)', async () => {+ render(<MidiVisualization url="/uploads/test.mid" />);+ await screen.findByText(/3 notes · /);+ expect(fetch).toHaveBeenCalledTimes(1);+ fireEvent.click(screen.getByLabelText('Collapse MIDI visualization'));+ expect(screen.queryByText(/3 notes · /)).toBeNull();+ fireEvent.click(screen.getByLabelText('Expand MIDI visualization'));+ await screen.findByText(/3 notes · /);+ expect(fetch).toHaveBeenCalledTimes(1); // served from the parse cache+ });++ it('zoom controls are real labeled buttons', async () => {+ render(<MidiVisualization url="/uploads/test.mid" />);+ await screen.findByText(/3 notes · /);+ fireEvent.click(screen.getByLabelText('Zoom in'));+ fireEvent.click(screen.getByLabelText('Zoom out'));+ fireEvent.click(screen.getByLabelText('Fit to width'));+ expect(ctx.clearRect).toHaveBeenCalled();+ });+});diff --git a/client/src/components/songs/ReferenceAnalysis.jsx b/client/src/components/songs/ReferenceAnalysis.jsxindex 8ce29bbe43..d2c40c0e89 100644--- a/client/src/components/songs/ReferenceAnalysis.jsx+++ b/client/src/components/songs/ReferenceAnalysis.jsx@@ -38,6 +38,7 @@ import useReferenceAudioImport from '../../hooks/useReferenceAudioImport.js';import useMidiTranscription from '../../hooks/useMidiTranscription.js';import MidiInstallModal from '../install/MidiInstallModal.jsx';import MidiGatedModal from '../install/MidiGatedModal.jsx';+import MidiVisualization from './MidiVisualization.jsx';import { startMemoRecording, arrayBufferToBase64 } from '../../lib/audioRecorder';import { proposeSegmentScore, proposeStackedSegmentScore, diffScoreBars, PITCH_CLASS_NAMES } from '../../lib/referenceAnalysis';import { scoreHasMusic, parseScore } from '../../lib/scoreNotation';@@ -175,6 +176,7 @@ export function ReferenceAudioAttach({ reference, onUpdate }) {if (reference.audioFilename) {return (+ <div className="flex flex-col gap-2"><div className="flex flex-wrap items-center gap-2"><MidiInstallModal {...midiJob.installGate} /><MidiGatedModal {...midiJob.gatedGate} />@@ -246,6 +248,10 @@ export function ReferenceAudioAttach({ reference, onUpdate }) {<X size={13} /> Remove audio</button></div>+ {reference.midiFilename && (+ <MidiVisualization url={getUploadUrl(reference.midiFilename)} filename={reference.midiFilename} />+ )}+ </div>);}diff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex 2af124d5d4..28d3779c15 100644--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@ -158,3 +158,4 @@ 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. |+| `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 1f2042b23e..1ea87a99bb 100644--- a/client/src/hooks/index.js+++ b/client/src/hooks/index.js@@ -50,6 +50,7 @@ export { default as useVideoDownload } from './useVideoDownload.js';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';// === Mixed (both default and named) — surface both ===export { default as useAsyncAction } from './useAsyncAction.js';diff --git a/client/src/hooks/useMidiNotes.js b/client/src/hooks/useMidiNotes.jsnew file mode 100644index 0000000000..597ae344c4--- /dev/null+++ b/client/src/hooks/useMidiNotes.js@@ -0,0 +1,65 @@+import { useCallback, useEffect, useRef, useState } from 'react';+import { parseMidiFile } from '../lib/midiNotes.js';++// Fetch + parse a `.mid` file into the piano-roll view-model, with a+// module-level cache so re-mounting a visualization (tab switches, collapse)+// doesn't refetch or reparse. Fetches directly (static file URL, same as the+// <audio> elements beside it) — no api request() layer, so errors surface as+// the hook's inline `error` state, never a toast.++// 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).+const cache = new Map();++/** Test-only: clear the module-level parse cache between cases. */+export const __clearMidiNotesCache = () => cache.clear();++/**+ * @param {string|null} url — resolved URL of the .mid file (null/'' renders idle).+ * @returns {{ status:'idle'|'loading'|'ready'|'error', data:object|null,+ * error:string|null, reload:()=>void }}+ */+export default function useMidiNotes(url) {+ const [state, setState] = useState({ status: 'idle', data: null, error: null });+ const generationRef = useRef(0);++ const load = useCallback((targetUrl, { force = false } = {}) => {+ generationRef.current += 1;+ const generation = generationRef.current;+ if (!targetUrl) {+ setState({ status: 'idle', data: null, error: null });+ return;+ }+ if (!force && cache.has(targetUrl)) {+ setState({ status: 'ready', data: cache.get(targetUrl), error: null });+ return;+ }+ setState({ status: 'loading', data: null, error: null });+ fetch(targetUrl)+ .then((res) => {+ if (!res.ok) throw new Error(`Failed to load MIDI (${res.status})`);+ return res.arrayBuffer();+ })+ .then((buf) => {+ const data = parseMidiFile(buf);+ cache.set(targetUrl, data);+ if (generationRef.current === generation) setState({ status: 'ready', data, error: null });+ })+ .catch((err) => {+ if (generationRef.current === generation) {+ setState({ status: 'error', data: null, error: err?.message || 'Failed to parse MIDI' });+ }+ });+ }, []);++ useEffect(() => {+ load(url);+ // Invalidate in-flight responses on unmount/url change so a stale parse+ // can't land on a different file's state.+ return () => { generationRef.current += 1; };+ }, [url, load]);++ const reload = useCallback(() => load(url, { force: true }), [url, load]);++ return { ...state, reload };+}diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex 9cfc31b1a1..bd3b42264b 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -114,6 +114,8 @@ grep -i "what you want to do" client/src/lib/README.md| `editorialHealth.js` | Pure presentation helpers for the editorial health panel (`/pipeline/editorial-checks`, #1316): `scoreBand(score)` bands a 0–100 health score into a label + Tailwind tone; `deltaDisplay(delta)` formats the revision-to-revision score change (arrow + tone); `sparklineGeometry(points, box)` projects the trend's score points into SVG polyline coords; `orderedCategories(openByCategory)` sorts the per-category open-finding breakdown; `orderedChecks(openByCheck, labelFor)` sorts the per-check breakdown resolving each id to its catalog label (#1597); `checkCountSeries(points, checkId)` extracts one check's count series across the trend points; `countSparklineGeometry(values, box)` projects a non-negative count series into SVG polyline coords normalized to its own max (per-check finding-count sparkline); `diffCountMaps(current, previous)` lists the buckets whose open-finding count changed between two snapshots (#1630); `snapshotDiff(point, previous)` builds a trend snapshot's drill-down (its own breakdown + per-severity/category/check diff vs the prior revision, null-aware for pre-#1597 per-check telemetry, #1630); plus the `SEVERITY_ORDER`/`SEVERITY_LABELS` and `READINESS_GATE_LABELS`/`READINESS_GATE_ORDER` tables. No React/window — the panel and its tests share them. || `lossSparkline.js` | `lossSparklineGeometry(series, box)` — projects an unbounded training-loss series (`{step,loss}[]`) into SVG polyline coords, normalized to its own min/max (unlike `editorialHealth.sparklineGeometry`'s fixed 0–100 axis). Returns `{ points, coords, last, min, max }`. Drives the Render Queue's training-row loss curve (#1408). No React. || `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. || `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/index.js b/client/src/lib/index.jsindex e6ce7b58a5..f15db4af0a 100644--- a/client/src/lib/index.js+++ b/client/src/lib/index.js@@ -82,6 +82,8 @@ export * from './editorialChecks.js';export * from './editorialHealth.js';export * from './lossSparkline.js';export * from './metronome.js';+export * from './midiChords.js';+export * from './midiNotes.js';export * from './pianoKeyboard.js';export * from './pitchDetect.js';export * from './referenceAnalysis.js';diff --git a/client/src/lib/midiChords.js b/client/src/lib/midiChords.jsnew file mode 100644index 0000000000..74a81a2f9f--- /dev/null+++ b/client/src/lib/midiChords.js@@ -0,0 +1,140 @@+// Chord detection for the MIDI visualization UI. Pure helpers: given the+// normalized note list from midiNotes.js, find time windows where ≥2 distinct+// pitch classes sound simultaneously and label each window with a compact+// 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'];++// 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).+export const MIN_CHORD_WINDOW_SEC = 0.06;++// Interval sets (semitones above the root, root included as 0), most-specific+// first so a maj7 isn't reported as its embedded triad.+const CHORD_SHAPES = [+ { intervals: [0, 4, 7, 11], suffix: 'maj7' },+ { intervals: [0, 4, 7, 10], suffix: '7' },+ { intervals: [0, 3, 7, 10], suffix: 'm7' },+ { intervals: [0, 3, 6, 10], suffix: 'm7b5' },+ { intervals: [0, 3, 6, 9], suffix: 'dim7' },+ { intervals: [0, 2, 4, 7], suffix: 'add9' },+ { intervals: [0, 4, 7], suffix: '' },+ { intervals: [0, 3, 7], suffix: 'm' },+ { intervals: [0, 3, 6], suffix: 'dim' },+ { intervals: [0, 4, 8], suffix: 'aug' },+ { intervals: [0, 2, 7], suffix: 'sus2' },+ { 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]);++/**+ * Name a set of pitch classes as a chord symbol.+ *+ * @param {number[]} pcs — distinct pitch classes (0–11).+ * @param {number} bassPc — pitch class of the lowest sounding note.+ * @returns {string} chord symbol (`Cmaj7`, `Am`, `C/E`), or space-joined+ * pitch-class names (`C E G#`) when no shape matches, or '' for <2 pcs.+ */+export const nameChord = (pcs, bassPc) => {+ const unique = [...new Set(pcs)].sort((a, b) => a - b);+ if (unique.length < 2) return '';+ // Try every pitch class as the root; prefer the bass note as root so+ // inversions come out as slash chords rather than a different quality.+ const roots = [bassPc, ...unique.filter((p) => p !== bassPc)];+ for (const root of roots) {+ const intervals = unique.map((p) => (p - root + 12) % 12).sort((a, b) => a - b);+ const shape = CHORD_SHAPES.find((s) => sameSet(s.intervals, intervals));+ if (shape) {+ const name = `${PITCH_CLASS_NAMES[root]}${shape.suffix}`;+ return root === bassPc ? name : `${name}/${PITCH_CLASS_NAMES[bassPc]}`;+ }+ }+ return unique.map((p) => PITCH_CLASS_NAMES[p]).join(' ');+};++/**+ * Sweep the note list for chord windows — maximal spans where the set of+ * 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.+ * @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 } = {}) => {+ const edges = [];+ (notes || []).forEach((n) => {+ if (!Number.isFinite(n.midi) || !Number.isFinite(n.startSec)) return;+ edges.push({ t: n.startSec, midi: n.midi, on: true });+ edges.push({ t: n.startSec + Math.max(n.durationSec || 0, 0.001), midi: n.midi, on: false });+ });+ if (!edges.length) return [];+ // Offs before ons at the same instant so back-to-back notes don't merge.+ edges.sort((a, b) => a.t - b.t || (a.on === b.on ? 0 : a.on ? 1 : -1));++ const sounding = new Map(); // midi → active count (handles overlapping same-pitch notes)+ const windows = [];+ let spanStart = null;+ let spanMidis = null;+ 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 });+ }+ spanStart = null;+ spanMidis = null;+ };++ let i = 0;+ while (i < edges.length) {+ const t = edges[i].t;+ // Apply every edge at this timestamp before re-evaluating the set.+ while (i < edges.length && edges[i].t === t) {+ const e = edges[i];+ const count = (sounding.get(e.midi) || 0) + (e.on ? 1 : -1);+ if (count > 0) sounding.set(e.midi, count);+ else 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) {+ closeSpan(t);+ spanStart = t;+ spanMidis = new Set(midis);+ }+ } else {+ closeSpan(t);+ }+ }+ closeSpan(edges[edges.length - 1].t);++ // Merge adjacent windows that resolved to the same label (retriggered chords).+ const merged = [];+ windows.forEach((w) => {+ const last = merged[merged.length - 1];+ if (last && last.label === w.label && w.startSec - last.endSec < 0.05) {+ last.endSec = w.endSec;+ last.midis = [...new Set([...last.midis, ...w.midis])].sort((a, b) => a - b);+ } else {+ merged.push({ ...w });+ }+ });+ return merged;+};++/** Human-readable pitch names for a chord window's tooltip (`C4 E4 G4`). */+export const chordNoteNames = (midis) => (midis || []).map((m) => midiNoteName(m)).join(' ');diff --git a/client/src/lib/midiChords.test.js b/client/src/lib/midiChords.test.jsnew file mode 100644index 0000000000..1d93c1a3b4--- /dev/null+++ b/client/src/lib/midiChords.test.js@@ -0,0 +1,97 @@+import { describe, expect, it } from 'vitest';+import { detectChordWindows, nameChord, chordNoteNames } from './midiChords.js';++const note = (midi, startSec, durationSec) => ({ midi, startSec, durationSec });++describe('nameChord', () => {+ it('names root-position triads and sevenths', () => {+ expect(nameChord([0, 4, 7], 0)).toBe('C'); // C E G+ expect(nameChord([9, 0, 4], 9)).toBe('Am'); // A C E+ expect(nameChord([0, 4, 7, 11], 0)).toBe('Cmaj7');+ expect(nameChord([7, 11, 2, 5], 7)).toBe('G7');+ expect(nameChord([9, 0, 4, 7], 9)).toBe('Am7');+ expect(nameChord([11, 2, 5, 9], 11)).toBe('Bm7b5');+ expect(nameChord([0, 3, 6, 9], 0)).toBe('Cdim7');+ expect(nameChord([0, 3, 6], 0)).toBe('Cdim');+ expect(nameChord([0, 4, 8], 0)).toBe('Caug');+ });++ it('names suspensions and add9', () => {+ expect(nameChord([0, 2, 7], 0)).toBe('Csus2');+ expect(nameChord([0, 5, 7], 0)).toBe('Csus4');+ expect(nameChord([0, 2, 4, 7], 0)).toBe('Cadd9');+ });++ it('reports inversions as slash chords', () => {+ expect(nameChord([0, 4, 7], 4)).toBe('C/E'); // first inversion+ expect(nameChord([0, 4, 7], 7)).toBe('C/G'); // second inversion+ });++ it('falls back to pitch-class names for unmatched clusters, never a wrong guess', () => {+ expect(nameChord([0, 1, 2], 0)).toBe('C C# D');+ expect(nameChord([0, 4, 8, 11, 2], 0)).toBe('C D E G# B');+ });++ it('returns empty for fewer than two pitch classes', () => {+ expect(nameChord([0], 0)).toBe('');+ expect(nameChord([0, 12 + 0].map((m) => m % 12), 0)).toBe(''); // octave doubling, one pc+ });+});++describe('detectChordWindows', () => {+ it('detects a sustained triad as one labeled window', () => {+ const windows = detectChordWindows([+ note(60, 0, 1), note(64, 0, 1), note(67, 0, 1),+ ]);+ expect(windows).toHaveLength(1);+ expect(windows[0]).toMatchObject({ label: 'C', midis: [60, 64, 67] });+ expect(windows[0].startSec).toBeCloseTo(0, 5);+ expect(windows[0].endSec).toBeCloseTo(1, 5);+ });++ it('ignores overlaps shorter than the minimum window', () => {+ // 30ms passing-note overlap — below the 60ms default → no chord.+ expect(detectChordWindows([note(60, 0, 0.5), note(62, 0.47, 0.5)])).toEqual([]);+ // The same shape with a 200ms overlap IS a window.+ expect(detectChordWindows([note(60, 0, 0.5), note(62, 0.3, 0.5)])).toHaveLength(1);+ });++ it('produces no windows for a monophonic melody', () => {+ expect(detectChordWindows([note(60, 0, 0.5), note(62, 0.5, 0.5), note(64, 1, 0.5)])).toEqual([]);+ });++ it('octave doublings of one pitch class are not a chord', () => {+ expect(detectChordWindows([note(60, 0, 1), note(72, 0, 1)])).toEqual([]);+ });++ it('merges retriggered instances of the same chord', () => {+ const windows = detectChordWindows([+ note(60, 0, 0.5), note(64, 0, 0.5), note(67, 0, 0.5),+ note(60, 0.52, 0.5), note(64, 0.52, 0.5), note(67, 0.52, 0.5),+ ]);+ expect(windows).toHaveLength(1);+ expect(windows[0].label).toBe('C');+ expect(windows[0].endSec).toBeCloseTo(1.02, 5);+ });++ it('splits when the sounding set changes to a different chord', () => {+ const windows = detectChordWindows([+ note(60, 0, 1), note(64, 0, 1), note(67, 0, 1), // C+ note(57, 1, 1), note(60, 1, 1), note(64, 1, 1), // Am+ ]);+ expect(windows.map((w) => w.label)).toEqual(['C', 'Am']);+ });++ it('handles empty and malformed input', () => {+ expect(detectChordWindows([])).toEqual([]);+ expect(detectChordWindows(null)).toEqual([]);+ expect(detectChordWindows([{ midi: NaN, startSec: 0, durationSec: 1 }])).toEqual([]);+ });+});++describe('chordNoteNames', () => {+ it('renders midi numbers as note names', () => {+ expect(chordNoteNames([60, 64, 67])).toBe('C4 E4 G4');+ expect(chordNoteNames([])).toBe('');+ });+});diff --git a/client/src/lib/midiNotes.js b/client/src/lib/midiNotes.jsnew file mode 100644index 0000000000..e95ead91a6--- /dev/null+++ b/client/src/lib/midiNotes.js@@ -0,0 +1,241 @@+// Minimal Standard MIDI File (SMF) parser + normalizer for the MIDI+// visualization UI (<MidiVisualization> / <MidiPianoRoll>). Parses format 0/1+// files down to the events the piano-roll needs — note-on/off, tempo map,+// track names — and normalizes them into a stable view-model with absolute+// seconds. Pure byte math, no canvas/React/fetch, so it's unit-testable with+// hand-built fixture bytes. Intentionally in-tree (no MIDI dependency): the+// roll only needs notes + tempo, not CC lanes or sysex payloads.+//+// View-model shape (consumed by useMidiNotes → MidiPianoRoll):+// {+// durationSec, minMidi, maxMidi,+// notes: [{ id, midi, startSec, durationSec, velocity, track, name }],+// tracks: [{ index, name?, noteCount }],+// tempos: [{ timeSec, bpm }],+// }++import { midiNoteName } from './pianoKeyboard.js';++const DEFAULT_TEMPO_US = 500000; // 120 BPM — the SMF default until a Set Tempo event++/** Read a big-endian uint of `bytes` length at `pos`. */+const readUint = (view, pos, bytes) => {+ let v = 0;+ for (let i = 0; i < bytes; i += 1) v = (v << 8) | view.getUint8(pos + i);+ return v >>> 0;+};++/** Read a MIDI variable-length quantity. Returns { value, next }. */+const readVarLen = (view, pos, end) => {+ let value = 0;+ let p = pos;+ for (let i = 0; i < 4 && p < end; i += 1) {+ const byte = view.getUint8(p);+ p += 1;+ value = (value << 7) | (byte & 0x7f);+ if ((byte & 0x80) === 0) return { value, next: p };+ }+ return { value, next: p };+};++const textDecoder = typeof TextDecoder !== 'undefined' ? new TextDecoder('utf-8', { fatal: false }) : null;+const decodeText = (view, pos, len) => {+ if (!textDecoder) return '';+ return textDecoder.decode(new Uint8Array(view.buffer, view.byteOffset + pos, len)).trim();+};++/**+ * Parse one MTrk chunk body into raw tick-timed events.+ * Handles running status, note-on velocity 0 as note-off, and skips+ * sysex/meta payloads it doesn't care about.+ */+const parseTrackEvents = (view, start, end) => {+ const events = []; // { tick, type: 'on'|'off'|'tempo'|'name', ... }+ let pos = start;+ let tick = 0;+ let runningStatus = 0;+ while (pos < end) {+ const delta = readVarLen(view, pos, end);+ tick += delta.value;+ pos = delta.next;+ if (pos >= end) break;++ let status = view.getUint8(pos);+ if (status & 0x80) {+ pos += 1;+ } else {+ // Running status: reuse the previous channel-message status byte.+ if (!(runningStatus & 0x80)) break; // malformed — bail out of this track+ status = runningStatus;+ }++ if (status === 0xff) {+ // Meta event: type byte + varlen payload.+ const metaType = view.getUint8(pos);+ const len = readVarLen(view, pos + 1, end);+ const dataPos = len.next;+ if (metaType === 0x51 && len.value >= 3) {+ events.push({ tick, type: 'tempo', usPerQuarter: readUint(view, dataPos, 3) });+ } else if (metaType === 0x03 && len.value > 0) {+ events.push({ tick, type: 'name', name: decodeText(view, dataPos, len.value) });+ } else if (metaType === 0x2f) {+ pos = dataPos + len.value;+ break; // End of Track+ }+ pos = dataPos + len.value;+ runningStatus = 0; // meta/sysex cancel running status+ continue;+ }+ if (status === 0xf0 || status === 0xf7) {+ const len = readVarLen(view, pos, end);+ pos = len.next + len.value;+ runningStatus = 0;+ continue;+ }++ runningStatus = status;+ const kind = status & 0xf0;+ const dataLen = kind === 0xc0 || kind === 0xd0 ? 1 : 2;+ if (pos + dataLen > end) break;+ if (kind === 0x90 || kind === 0x80) {+ const midi = view.getUint8(pos);+ const velocity = view.getUint8(pos + 1);+ if (kind === 0x90 && velocity > 0) events.push({ tick, type: 'on', midi, velocity });+ else events.push({ tick, type: 'off', midi });+ }+ pos += dataLen;+ }+ return events;+};++/**+ * Build a tick→seconds converter from the file's tempo events.+ * PPQ division uses the piecewise tempo map; SMPTE division is a fixed+ * seconds-per-tick and ignores tempo events entirely (per the SMF spec).+ */+const buildTickToSec = (division, tempoEvents) => {+ if (division & 0x8000) {+ // SMPTE: high byte is negative frames/sec, low byte is ticks/frame.+ const fps = 256 - ((division >> 8) & 0xff); // two's complement of the negative byte+ const ticksPerFrame = division & 0xff;+ const secPerTick = 1 / (fps * ticksPerFrame || 1);+ return (tick) => tick * secPerTick;+ }+ const ppq = division || 480;+ // Piecewise segments: seconds accumulated up to each tempo change.+ const changes = [...tempoEvents].sort((a, b) => a.tick - b.tick);+ const segments = [];+ let curTick = 0;+ let curSec = 0;+ let curUs = DEFAULT_TEMPO_US;+ changes.forEach((c) => {+ if (c.tick > curTick) {+ curSec += ((c.tick - curTick) * curUs) / (ppq * 1e6);+ curTick = c.tick;+ }+ curUs = c.usPerQuarter;+ segments.push({ tick: curTick, sec: curSec, usPerQuarter: curUs });+ });+ return (tick) => {+ let base = { tick: 0, sec: 0, usPerQuarter: DEFAULT_TEMPO_US };+ for (let i = 0; i < segments.length && segments[i].tick <= tick; i += 1) base = segments[i];+ return base.sec + ((tick - base.tick) * base.usPerQuarter) / (ppq * 1e6);+ };+};++/**+ * Parse an SMF file into the piano-roll view-model.+ *+ * @param {ArrayBuffer|Uint8Array} buffer — raw `.mid` bytes.+ * @returns {{ durationSec:number, minMidi:number, maxMidi:number,+ * notes:Array<{id:string,midi:number,startSec:number,durationSec:number,velocity:number,track:number,name:string}>,+ * tracks:Array<{index:number,name:string|null,noteCount:number}>,+ * tempos:Array<{timeSec:number,bpm:number}> }}+ * @throws {Error} when the buffer is not a parseable SMF file.+ */+export const parseMidiFile = (buffer) => {+ const bytes = buffer instanceof Uint8Array ? buffer : new Uint8Array(buffer);+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);+ if (bytes.length < 14 || readUint(view, 0, 4) !== 0x4d546864) {+ throw new Error('Not a MIDI file (missing MThd header)');+ }+ const headerLen = readUint(view, 4, 4);+ const trackCount = readUint(view, 10, 2);+ const division = readUint(view, 12, 2);++ // Walk the MTrk chunks (skip unknown chunk types per the spec).+ const rawTracks = [];+ let pos = 8 + headerLen;+ while (pos + 8 <= bytes.length && rawTracks.length < trackCount) {+ const chunkType = readUint(view, pos, 4);+ const chunkLen = readUint(view, pos + 4, 4);+ const bodyStart = pos + 8;+ const bodyEnd = Math.min(bodyStart + chunkLen, bytes.length);+ if (chunkType === 0x4d54726b) rawTracks.push(parseTrackEvents(view, bodyStart, bodyEnd));+ pos = bodyStart + chunkLen;+ }+ if (!rawTracks.length) throw new Error('MIDI file has no tracks');++ const tempoEvents = rawTracks.flat().filter((e) => e.type === 'tempo');+ const tickToSec = buildTickToSec(division, tempoEvents);++ const notes = [];+ const tracks = [];+ rawTracks.forEach((events, trackIndex) => {+ const open = new Map(); // midi → { startTick, velocity } (last-on wins per pitch)+ let name = null;+ let noteCount = 0;+ events.forEach((ev) => {+ if (ev.type === 'name' && !name) name = ev.name;+ if (ev.type === 'on') {+ // Retrigger of an already-open pitch closes the previous note first.+ const prev = open.get(ev.midi);+ if (prev) pushNote(prev, ev.tick);+ open.set(ev.midi, { midi: ev.midi, startTick: ev.tick, velocity: ev.velocity });+ } else if (ev.type === 'off') {+ const prev = open.get(ev.midi);+ if (prev) { pushNote(prev, ev.tick); open.delete(ev.midi); }+ }+ });+ // Notes left open at end-of-track get a minimal duration instead of vanishing.+ open.forEach((prev) => pushNote(prev, prev.startTick + 1));++ function pushNote(prev, endTick) {+ const startSec = tickToSec(prev.startTick);+ const endSec = tickToSec(Math.max(endTick, prev.startTick + 1));+ notes.push({+ id: `${trackIndex}:${notes.length}`,+ midi: prev.midi,+ startSec,+ durationSec: Math.max(endSec - startSec, 0.001),+ velocity: prev.velocity / 127,+ track: trackIndex,+ name: midiNoteName(prev.midi),+ });+ noteCount += 1;+ }+ tracks.push({ index: trackIndex, name, noteCount });+ });++ notes.sort((a, b) => a.startSec - b.startSec || a.midi - b.midi);+ let durationSec = 0;+ let minMidi = 127;+ let maxMidi = 0;+ notes.forEach((n) => {+ durationSec = Math.max(durationSec, n.startSec + n.durationSec);+ minMidi = Math.min(minMidi, n.midi);+ maxMidi = Math.max(maxMidi, n.midi);+ });+ if (!notes.length) { minMidi = 60; maxMidi = 71; }++ return {+ durationSec,+ minMidi,+ maxMidi,+ notes,+ tracks: tracks.filter((t) => t.noteCount > 0 || tracks.length === 1),+ tempos: tempoEvents+ .sort((a, b) => a.tick - b.tick)+ .map((e) => ({ timeSec: tickToSec(e.tick), bpm: Math.round(60e6 / e.usPerQuarter) })),+ };+};diff --git a/client/src/lib/midiNotes.test.js b/client/src/lib/midiNotes.test.jsnew file mode 100644index 0000000000..f237e73cf6--- /dev/null+++ b/client/src/lib/midiNotes.test.js@@ -0,0 +1,136 @@+import { describe, expect, it } from 'vitest';+import { parseMidiFile } from './midiNotes.js';++// Hand-built SMF fixtures — tiny byte arrays, no real transcriptions+// (Sensitive Data rule: never commit personal project data as fixtures).++const PPQ = 480;++/** Encode a MIDI variable-length quantity. */+const varLen = (value) => {+ const bytes = [value & 0x7f];+ let v = value >> 7;+ while (v > 0) {+ bytes.unshift((v & 0x7f) | 0x80);+ v >>= 7;+ }+ return bytes;+};++const str = (s) => [...s].map((c) => c.charCodeAt(0));+const u32 = (v) => [(v >> 24) & 0xff, (v >> 16) & 0xff, (v >> 8) & 0xff, v & 0xff];+const u16 = (v) => [(v >> 8) & 0xff, v & 0xff];++const track = (events) => {+ const body = events.flat();+ return [...str('MTrk'), ...u32(body.length), ...body];+};++const smf = (tracks, { format = 1, division = PPQ } = {}) => new Uint8Array([+ ...str('MThd'), ...u32(6), ...u16(format), ...u16(tracks.length), ...u16(division),+ ...tracks.flat(),+]);++const noteOn = (delta, midi, vel = 100, ch = 0) => [...varLen(delta), 0x90 | ch, midi, vel];+const noteOff = (delta, midi, ch = 0) => [...varLen(delta), 0x80 | ch, midi, 0];+const tempoEv = (delta, usPerQuarter) => [...varLen(delta), 0xff, 0x51, 0x03,+ (usPerQuarter >> 16) & 0xff, (usPerQuarter >> 8) & 0xff, usPerQuarter & 0xff];+const trackNameEv = (delta, name) => [...varLen(delta), 0xff, 0x03, name.length, ...str(name)];+const endOfTrack = (delta = 0) => [...varLen(delta), 0xff, 0x2f, 0x00];++describe('parseMidiFile', () => {+ it('rejects non-MIDI bytes', () => {+ expect(() => parseMidiFile(new Uint8Array([1, 2, 3, 4]))).toThrow(/MThd/);+ expect(() => parseMidiFile(new Uint8Array(str('RIFFxxxxWAVE')).buffer)).toThrow(/MThd/);+ });++ it('parses notes with default-tempo timing (120 BPM → one beat = 0.5s)', () => {+ const bytes = smf([track([+ noteOn(0, 60),+ noteOff(PPQ, 60), // C4 for one quarter+ noteOn(0, 64, 64),+ noteOff(PPQ * 2, 64), // E4 for a half note+ endOfTrack(),+ ])]);+ const vm = parseMidiFile(bytes);+ expect(vm.notes).toHaveLength(2);+ const [c4, e4] = vm.notes;+ expect(c4).toMatchObject({ midi: 60, name: 'C4', track: 0 });+ expect(c4.startSec).toBeCloseTo(0, 5);+ expect(c4.durationSec).toBeCloseTo(0.5, 5);+ expect(e4.startSec).toBeCloseTo(0.5, 5);+ expect(e4.durationSec).toBeCloseTo(1.0, 5);+ expect(e4.velocity).toBeCloseTo(64 / 127, 5);+ expect(vm.durationSec).toBeCloseTo(1.5, 5);+ expect(vm.minMidi).toBe(60);+ expect(vm.maxMidi).toBe(64);+ });++ it('applies mid-file tempo changes to later notes only', () => {+ const bytes = smf([track([+ tempoEv(0, 500000), // 120 BPM+ noteOn(0, 60), noteOff(PPQ, 60), // 0.0–0.5s+ tempoEv(0, 250000), // 240 BPM from tick 480+ noteOn(0, 62), noteOff(PPQ, 62), // starts 0.5s, lasts 0.25s+ endOfTrack(),+ ])]);+ const vm = parseMidiFile(bytes);+ const d4 = vm.notes.find((n) => n.midi === 62);+ expect(d4.startSec).toBeCloseTo(0.5, 5);+ expect(d4.durationSec).toBeCloseTo(0.25, 5);+ expect(vm.tempos.map((t) => t.bpm)).toEqual([120, 240]);+ });++ it('treats note-on velocity 0 as note-off and supports running status', () => {+ // After the first 0x90, subsequent events omit the status byte entirely.+ const bytes = smf([track([+ [...varLen(0), 0x90, 60, 100],+ [...varLen(PPQ), 60, 0], // running status: vel-0 note-on = off+ [...varLen(0), 64, 80], // running status: new note-on+ [...varLen(PPQ), 64, 0],+ endOfTrack(),+ ])]);+ const vm = parseMidiFile(bytes);+ expect(vm.notes).toHaveLength(2);+ expect(vm.notes[0].durationSec).toBeCloseTo(0.5, 5);+ expect(vm.notes[1].startSec).toBeCloseTo(0.5, 5);+ });++ it('separates tracks, keeps names, and counts notes per track', () => {+ const bytes = smf([+ track([tempoEv(0, 500000), endOfTrack()]), // conductor track — no notes+ track([trackNameEv(0, 'Piano'), noteOn(0, 60), noteOff(PPQ, 60), endOfTrack()]),+ track([trackNameEv(0, 'Bass'), noteOn(0, 40), noteOff(PPQ, 40), endOfTrack()]),+ ]);+ const vm = parseMidiFile(bytes);+ expect(vm.tracks.map((t) => t.name)).toEqual(['Piano', 'Bass']);+ expect(vm.tracks.every((t) => t.noteCount === 1)).toBe(true);+ expect(new Set(vm.notes.map((n) => n.track)).size).toBe(2);+ });++ it('closes notes left open at end-of-track instead of dropping them', () => {+ const bytes = smf([track([noteOn(0, 72), endOfTrack(PPQ)])]);+ const vm = parseMidiFile(bytes);+ expect(vm.notes).toHaveLength(1);+ expect(vm.notes[0].durationSec).toBeGreaterThan(0);+ });++ it('skips sysex and unknown meta events without derailing note parsing', () => {+ const bytes = smf([track([+ [...varLen(0), 0xf0, 3, 1, 2, 0xf7], // sysex, length 3+ [...varLen(0), 0xff, 0x58, 4, 4, 2, 24, 8], // time signature meta+ noteOn(0, 60), noteOff(PPQ, 60),+ endOfTrack(),+ ])]);+ expect(parseMidiFile(bytes).notes).toHaveLength(1);+ });++ it('handles an empty note list without NaN ranges', () => {+ const bytes = smf([track([endOfTrack()])]);+ const vm = parseMidiFile(bytes);+ expect(vm.notes).toHaveLength(0);+ expect(vm.durationSec).toBe(0);+ expect(Number.isFinite(vm.minMidi)).toBe(true);+ expect(Number.isFinite(vm.maxMidi)).toBe(true);+ });+});diff --git a/client/src/pages/MusicVideo.jsx b/client/src/pages/MusicVideo.jsxindex 0c61dfbc51..24599ba9f0 100644--- a/client/src/pages/MusicVideo.jsx+++ b/client/src/pages/MusicVideo.jsx@@ -24,6 +24,7 @@ import {import useMidiTranscription from '../hooks/useMidiTranscription.js';import MidiInstallModal from '../components/install/MidiInstallModal.jsx';import MidiGatedModal from '../components/install/MidiGatedModal.jsx';+import MidiVisualization from '../components/songs/MidiVisualization.jsx';import { generateImage } from '../services/apiSystem.js';import { generateVideo } from '../services/apiImageVideo.js';import { listTracks, trackAudioUrl } from '../services/apiTracks.js';@@ -745,19 +746,28 @@ export default function MusicVideo() {if (!audioFile) return null;const audioUrl = trackAudioUrl(audioFile);return (- <div className="mt-2 flex flex-wrap items-center gap-2">- <audio src={audioUrl} controls preload="metadata" className="h-8 max-w-full" aria-label="Preview track audio" />- <a href={audioUrl} download={audioFile}- title="Download the audio track"- 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+ <div className="mt-2 flex flex-col gap-2">+ <div className="flex flex-wrap items-center gap-2">+ <audio src={audioUrl} controls preload="metadata" className="h-8 max-w-full" aria-label="Preview track audio" />+ <a href={audioUrl} download={audioFile}+ title="Download the audio track"+ 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 && (+ <MidiVisualization+ url={trackAudioUrl(selected.midiTranscription.filename)}+ filename={selected.midiTranscription.filename}+ model={selected.midiTranscription.model}+ />)}</div>);diff --git a/client/src/pages/MusicVideo.test.jsx b/client/src/pages/MusicVideo.test.jsxindex 6ad72ceace..1181a810af 100644--- a/client/src/pages/MusicVideo.test.jsx+++ b/client/src/pages/MusicVideo.test.jsx@@ -219,10 +219,12 @@ describe('MusicVideo audio → MIDI transcription (MuScriptor)', () => {it('shows the MIDI download link once the project carries a transcription pointer', async () => {listTracks.mockResolvedValue([{ id: 't1', title: 'Neon Song', audioFilename: 'neon.mp3' }]);await openProject({ ...PROJECT_WITH_CLIP, midiTranscription: { filename: 'neon-midi.mid', model: 'medium' } });- const dl = await screen.findByRole('link', { name: /Download MIDI/i });- // Served from the music dir (same static route as the master audio) so the- // federated .mid resolves on peers too.- expect(dl.getAttribute('href')).toBe('/data/music/neon-midi.mid');+ // Two links now: the download button and the MidiVisualization panel's+ // download icon (#2477) — both serve from the music dir (same static route+ // as the master audio) so the federated .mid resolves on peers too.+ const links = await screen.findAllByRole('link', { name: /Download MIDI/i });+ expect(links.length).toBeGreaterThanOrEqual(1);+ links.forEach((dl) => expect(dl.getAttribute('href')).toBe('/data/music/neon-midi.mid'));});});