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
perf(songs): cache the MidiPianoRoll scene + theme-aware roll palette (#2491)
Adam Eivy53b5beeacffe
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 876992125c..a1891ba0f6 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -4,6 +4,7 @@- **[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.- **Music track pages show the MIDI piano-roll too.** A selected track on the Music → Tracks page now surfaces the newest MIDI transcription from any Music Video project linked to it, with the same interactive piano-roll and a link back to the source project.+- **[issue-2491] MIDI piano-roll: cached-scene rendering, theme-aware colors, and cleanup.** The DAW-style roll now paints its grid + notes + gutter to a cached offscreen bitmap and just composites that (plus the playhead/hover overlay) on hover and scrub repaints — so a hover over a dense (10k-note) file no longer redraws every note bar. Both rolls follow the active theme's accent instead of a hardcoded blue (resolved via a shared `rollPalette` helper + `useCanvasRollPalette` hook, repainting on theme switch). Hit-testing indexes notes by pitch (one row scanned instead of every note), tick→seconds uses a binary search over tempo segments, and the ruler's M:SS tick labels use `formatDurationSec` (now correctly rendering a genuine zero as `0:00`).## Changeddiff --git a/client/src/components/songs/MidiPianoRoll.jsx b/client/src/components/songs/MidiPianoRoll.jsxindex 02af45ccd6..3e4aa4d94b 100644--- a/client/src/components/songs/MidiPianoRoll.jsx+++ b/client/src/components/songs/MidiPianoRoll.jsx@@ -1,9 +1,10 @@-import { useCallback, useEffect, useRef, useState } from 'react';+import { useCallback, useEffect, useMemo, 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 { formatTimecode, formatDurationSec } from '../../utils/formatters';import useCanvasDprSize from '../../hooks/useCanvasDprSize.js';+import useCanvasRollPalette from '../../hooks/useCanvasRollPalette.js';// DAW-style horizontal piano-roll for inspecting a transcribed `.mid` file// (time × pitch grid) — NOT the Synthesia falling-note <PianoRoll>, which is@@ -21,9 +22,7 @@ import useCanvasDprSize from '../../hooks/useCanvasDprSize.js';const GUTTER_W = 44; // left pitch gutterconst RULER_H = 18; // top time rulerconst 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';@@ -49,6 +48,17 @@ const tooltipStyle = (x, y, width) => ({top: `${Math.max(0, y - 24)}px`,});+// Shallow-compare two offscreen-scene signatures. `data`/`chords` compare by+// reference (a new parse is a new object); everything else by value. Any+// mismatch means the cached bitmap is stale and the scene must be repainted.+const sceneSigEqual = (a, b) => !!a && !!b+ && a.width === b.width && a.height === b.height && a.zoom === b.zoom+ && a.scroll === b.scroll && a.chordLaneH === b.chordLaneH+ && a.lowMidi === b.lowMidi && a.highMidi === b.highMidi+ && a.multiTrack === b.multiTrack && a.dpr === b.dpr+ && a.data === b.data && a.chords === b.chords+ && a.bg === b.bg && a.accent === b.accent && a.accentRgb === b.accentRgb;+/*** @param {object} props* @param {object} props.data — view-model from parseMidiFile.@@ -67,6 +77,12 @@ export default function MidiPianoRoll({ data, chords, showChords, zoom, onZoomChconst pinchRef = useRef(null); // { startDist, startZoom }const tooltipRef = useRef(null);const tooltipPosRef = useRef({ x: 0, y: 0 });+ // Cached offscreen "scene" (grid + notes + gutter, no playhead/hover) keyed+ // on everything that changes it — reused across hover/playhead repaints so a+ // mouse move over a 10k-note file drawImage()s the bitmap instead of redrawing+ // every note bar. Rebuilt only when the sig actually changes (pan/zoom/resize/+ // data/theme).+ const sceneRef = useRef({ canvas: null, sig: null });// Identity only ({ kind, note } | { kind, chord }) — drives the highlight// repaint; position updates never touch state.const [hover, setHover] = useState(null);@@ -87,6 +103,18 @@ export default function MidiPianoRoll({ data, chords, showChords, zoom, onZoomCh}const rowCount = highMidi - lowMidi + 1;+ // Notes bucketed by pitch (sorted-by-startSec preserved from parseMidiFile),+ // so hit-testing scans one row instead of every note (~88× fewer) and chord+ // hover strokes look up members by midi.+ const notesByMidi = useMemo(() => {+ const map = new Map();+ (data?.notes || []).forEach((n) => {+ const arr = map.get(n.midi);+ if (arr) arr.push(n); else map.set(n.midi, [n]);+ });+ return map;+ }, [data]);+const geometry = useCallback(() => {const width = widthRef.current;const gridW = Math.max(1, width - GUTTER_W);@@ -101,157 +129,254 @@ export default function MidiPianoRoll({ data, chords, showChords, zoom, onZoomChconst draw = useCallback(() => {const canvas = canvasRef.current;- const { width, gridW, pps, gridTop, gridH, rowH, maxScroll } = geometry();+ const geo = geometry();+ const { width, gridW, pps, gridTop, gridH, rowH, maxScroll } = geo;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 { bg, accent, accentRgb } = paletteRef.current;const timeToX = (sec) => GUTTER_W + (sec - scroll) * pps;const midiToY = (m) => gridTop + (highMidi - m) * rowH;- ctx.clearRect(0, 0, width, height);- ctx.fillStyle = BG;- ctx.fillRect(0, 0, width, height);-- // Horizontal pitch rows — black-key rows tinted, every C stronger.- for (let m = lowMidi; m <= highMidi; m += 1) {- const y = midiToY(m);- if (m % 12 === 0) {- ctx.fillStyle = C_LINE;- ctx.fillRect(GUTTER_W, y + rowH, gridW, 1);- } else if (rowH >= 4) {- if (isBlackKey(m)) {- ctx.fillStyle = 'rgba(255,255,255,0.02)';- ctx.fillRect(GUTTER_W, y, gridW, rowH);+ // The full grid + notes + gutter is invariant under hover and playhead+ // moves, so paint it to an offscreen bitmap keyed on the values that DO+ // change it and reuse that bitmap for every other repaint. On a dense file+ // this turns a hover/scrub repaint from "redraw every note bar" into a+ // single drawImage() + a couple of overlay strokes.+ const paintScene = (octx) => {+ octx.clearRect(0, 0, width, height);+ octx.fillStyle = bg;+ octx.fillRect(0, 0, width, height);++ // Horizontal pitch rows — black-key rows tinted, every C stronger.+ for (let m = lowMidi; m <= highMidi; m += 1) {+ const y = midiToY(m);+ if (m % 12 === 0) {+ octx.fillStyle = C_LINE;+ octx.fillRect(GUTTER_W, y + rowH, gridW, 1);+ } else if (rowH >= 4) {+ if (isBlackKey(m)) {+ octx.fillStyle = 'rgba(255,255,255,0.02)';+ octx.fillRect(GUTTER_W, y, gridW, rowH);+ }+ octx.fillStyle = GRID_LINE;+ octx.fillRect(GUTTER_W, y + rowH, gridW, 1);}- ctx.fillStyle = GRID_LINE;- ctx.fillRect(GUTTER_W, y + rowH, gridW, 1);}- }- // Vertical time grid + ruler labels.- const step = tickStep(pps);- ctx.font = '9px ui-sans-serif, system-ui, sans-serif';- ctx.textAlign = 'left';- for (let t = Math.floor(scroll / step) * step; t <= viewEnd; t += step) {- if (t < 0) continue;- const x = timeToX(t);- if (x < GUTTER_W) continue;- ctx.fillStyle = GRID_LINE;- ctx.fillRect(x, gridTop, 1, gridH);- ctx.fillStyle = TEXT_DIM;- // Sub-second tick steps need the fractional digits or adjacent labels- // render identically ("0:03 0:03 0:03") right when fine timing matters.- ctx.fillText(step < 1 ? formatTimecode(t) : formatTimecode(t).replace(/\.\d+$/, ''), x + 3, RULER_H - 6);- }+ // Vertical time grid + ruler labels.+ const step = tickStep(pps);+ octx.font = '9px ui-sans-serif, system-ui, sans-serif';+ octx.textAlign = 'left';+ for (let t = Math.floor(scroll / step) * step; t <= viewEnd; t += step) {+ if (t < 0) continue;+ const x = timeToX(t);+ if (x < GUTTER_W) continue;+ octx.fillStyle = GRID_LINE;+ octx.fillRect(x, gridTop, 1, gridH);+ octx.fillStyle = TEXT_DIM;+ // Sub-second tick steps keep the fractional timecode (adjacent labels+ // would otherwise read "0:03 0:03 0:03"); whole-second steps use the+ // plain M:SS formatter.+ octx.fillText(step < 1 ? formatTimecode(t) : formatDurationSec(t), x + 3, RULER_H - 6);+ }- // Chord lane.- if (chordLaneH) {- ctx.fillStyle = 'rgba(255,255,255,0.03)';- ctx.fillRect(GUTTER_W, RULER_H, gridW, chordLaneH);- (chords || []).forEach((c) => {- if (c.endSec < scroll || c.startSec > viewEnd) return;- const x0 = Math.max(GUTTER_W, timeToX(c.startSec));- const x1 = Math.min(width, timeToX(c.endSec));- if (x1 - x0 < 2) return;- const isHover = hover?.kind === 'chord' && hover.chord === c;- ctx.fillStyle = isHover ? 'rgba(59,130,246,0.25)' : 'rgba(59,130,246,0.10)';- ctx.fillRect(x0, RULER_H + 1, x1 - x0 - 1, chordLaneH - 2);- // Sticky-left label, clipped to the window.- ctx.save();- ctx.beginPath();- ctx.rect(x0, RULER_H, x1 - x0, chordLaneH);- ctx.clip();- ctx.fillStyle = isHover ? '#dbeafe' : '#9ca3af';- ctx.font = '10px ui-sans-serif, system-ui, sans-serif';- ctx.fillText(c.label, x0 + 3, RULER_H + chordLaneH - 6);- ctx.restore();- });- }+ // Chord lane (dim — the hovered chord is brightened in the overlay pass).+ if (chordLaneH) {+ octx.fillStyle = 'rgba(255,255,255,0.03)';+ octx.fillRect(GUTTER_W, RULER_H, gridW, chordLaneH);+ (chords || []).forEach((c) => {+ if (c.endSec < scroll || c.startSec > viewEnd) return;+ const x0 = Math.max(GUTTER_W, timeToX(c.startSec));+ const x1 = Math.min(width, timeToX(c.endSec));+ if (x1 - x0 < 2) return;+ octx.fillStyle = `rgb(${accentRgb} / 0.10)`;+ octx.fillRect(x0, RULER_H + 1, x1 - x0 - 1, chordLaneH - 2);+ // Sticky-left label, clipped to the window.+ octx.save();+ octx.beginPath();+ octx.rect(x0, RULER_H, x1 - x0, chordLaneH);+ octx.clip();+ octx.fillStyle = '#9ca3af';+ octx.font = '10px ui-sans-serif, system-ui, sans-serif';+ octx.fillText(c.label, x0 + 3, RULER_H + chordLaneH - 6);+ octx.restore();+ });+ }- // Notes — only those intersecting the visible window, clipped to the grid.- // The list is sorted by startSec (parseMidiFile), so bail out of the loop- // at the first note past the right edge.- const hoverChordMidis = hover?.kind === 'chord' ? new Set(hover.chord.midis) : null;- const hoverChordSpan = hover?.kind === 'chord' ? hover.chord : null;- ctx.save();- ctx.beginPath();- ctx.rect(GUTTER_W, gridTop, gridW, gridH);- ctx.clip();- ctx.textAlign = 'left';- const notes = data?.notes || [];- for (let i = 0; i < notes.length; i += 1) {- const n = notes[i];- if (n.startSec > viewEnd) break;- const end = n.startSec + n.durationSec;- if (end < scroll) continue;- if (n.midi < lowMidi || n.midi > highMidi) continue;- const x = timeToX(n.startSec);- const w = Math.max(2, n.durationSec * pps);- const y = midiToY(n.midi);- const h = Math.max(2, rowH - 1);- roundRect(ctx, x, y + 0.5, w, h, NOTE_RADIUS);- ctx.fillStyle = multiTrack ? layerColor(n.track) : ACCENT;- ctx.globalAlpha = 0.35 + 0.6 * (n.velocity ?? 0.8);- ctx.fill();- const isHoverNote = hover?.kind === 'note' && hover.note.id === n.id;- const inHoverChord = hoverChordMidis?.has(n.midi)- && hoverChordSpan && n.startSec < hoverChordSpan.endSec && end > hoverChordSpan.startSec;- if (isHoverNote || inHoverChord) {- ctx.globalAlpha = 1;- ctx.strokeStyle = '#ffffff';- ctx.lineWidth = 1;- ctx.stroke();+ // Notes — only those intersecting the visible window, clipped to the grid.+ // The list is sorted by startSec (parseMidiFile), so bail out of the loop+ // at the first note past the right edge.+ octx.save();+ octx.beginPath();+ octx.rect(GUTTER_W, gridTop, gridW, gridH);+ octx.clip();+ octx.textAlign = 'left';+ const notes = data?.notes || [];+ for (let i = 0; i < notes.length; i += 1) {+ const n = notes[i];+ if (n.startSec > viewEnd) break;+ const end = n.startSec + n.durationSec;+ if (end < scroll) continue;+ if (n.midi < lowMidi || n.midi > highMidi) continue;+ const x = timeToX(n.startSec);+ const w = Math.max(2, n.durationSec * pps);+ const y = midiToY(n.midi);+ const h = Math.max(2, rowH - 1);+ roundRect(octx, x, y + 0.5, w, h, NOTE_RADIUS);+ octx.fillStyle = multiTrack ? layerColor(n.track) : accent;+ octx.globalAlpha = 0.35 + 0.6 * (n.velocity ?? 0.8);+ octx.fill();+ octx.globalAlpha = 1;+ // In-bar note name when it fits.+ if (w >= 28 && rowH >= 12) {+ octx.fillStyle = bg;+ octx.font = '9px ui-sans-serif, system-ui, sans-serif';+ octx.fillText(n.name || midiNoteName(n.midi), x + 3, y + h - Math.max(1, (h - 8) / 2));+ }}- ctx.globalAlpha = 1;- // In-bar note name when it fits.- if (w >= 28 && rowH >= 12) {- ctx.fillStyle = '#0c0c0e';- ctx.font = '9px ui-sans-serif, system-ui, sans-serif';- ctx.fillText(n.name || midiNoteName(n.midi), x + 3, y + h - Math.max(1, (h - 8) / 2));+ octx.restore();++ // Pitch gutter on top (opaque, so notes pan "under" it).+ octx.fillStyle = GUTTER_BG;+ octx.fillRect(0, gridTop, GUTTER_W, gridH);+ octx.textAlign = 'right';+ for (let m = lowMidi; m <= highMidi; m += 1) {+ const y = midiToY(m);+ if (m % 12 === 0 && rowH >= 3) {+ octx.fillStyle = TEXT_DIM;+ octx.font = '9px ui-sans-serif, system-ui, sans-serif';+ octx.fillText(midiNoteName(m), GUTTER_W - 4, y + rowH - 1);+ octx.fillStyle = C_LINE;+ octx.fillRect(0, y + rowH, GUTTER_W, 1);+ } else if (rowH >= 7) {+ octx.fillStyle = isBlackKey(m) ? 'rgba(255,255,255,0.05)' : 'rgba(255,255,255,0.10)';+ octx.fillRect(GUTTER_W - 8, y + 1, 5, Math.max(1, rowH - 2));+ }+ }+ // Scroll indicator along the bottom when zoomed in.+ if (maxScroll > 0) {+ const frac = gridW / (duration * pps);+ const barW = Math.max(24, gridW * frac);+ const barX = GUTTER_W + (scroll / maxScroll) * (gridW - barW);+ octx.fillStyle = 'rgba(255,255,255,0.15)';+ octx.fillRect(barX, height - 3, barW, 2);+ }+ };++ // Live overlay: the hovered chord's bright box + label, hovered-note white+ // strokes, and the playhead — everything that moves without invalidating+ // the cached scene.+ const paintOverlay = (octx) => {+ if (hover?.kind === 'chord' && chordLaneH) {+ const c = hover.chord;+ if (!(c.endSec < scroll || c.startSec > viewEnd)) {+ const x0 = Math.max(GUTTER_W, timeToX(c.startSec));+ const x1 = Math.min(width, timeToX(c.endSec));+ if (x1 - x0 >= 2) {+ // Repaint the strip under the box so the brighter fill doesn't+ // composite on top of the baked dim box.+ octx.fillStyle = bg;+ octx.fillRect(x0, RULER_H, x1 - x0, chordLaneH);+ octx.fillStyle = 'rgba(255,255,255,0.03)';+ octx.fillRect(x0, RULER_H, x1 - x0, chordLaneH);+ octx.fillStyle = `rgb(${accentRgb} / 0.25)`;+ octx.fillRect(x0, RULER_H + 1, x1 - x0 - 1, chordLaneH - 2);+ octx.save();+ octx.beginPath();+ octx.rect(x0, RULER_H, x1 - x0, chordLaneH);+ octx.clip();+ octx.fillStyle = '#dbeafe';+ octx.font = '10px ui-sans-serif, system-ui, sans-serif';+ octx.fillText(c.label, x0 + 3, RULER_H + chordLaneH - 6);+ octx.restore();+ }+ }}- }- 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);- }+ // White outline on the hovered note (or every note in the hovered chord),+ // clipped to the grid so a stroke can't bleed over the gutter/ruler.+ if (hover) {+ octx.save();+ octx.beginPath();+ octx.rect(GUTTER_W, gridTop, gridW, gridH);+ octx.clip();+ octx.strokeStyle = '#ffffff';+ octx.lineWidth = 1;+ const strokeNote = (n) => {+ if (n.midi < lowMidi || n.midi > highMidi) return;+ const w = Math.max(2, n.durationSec * pps);+ const h = Math.max(2, rowH - 1);+ roundRect(octx, timeToX(n.startSec), midiToY(n.midi) + 0.5, w, h, NOTE_RADIUS);+ octx.stroke();+ };+ if (hover.kind === 'note') {+ strokeNote(hover.note);+ } else if (hover.kind === 'chord') {+ const span = hover.chord;+ span.midis.forEach((m) => {+ (notesByMidi.get(m) || []).forEach((n) => {+ const end = n.startSec + n.durationSec;+ if (n.startSec < span.endSec && end > span.startSec) strokeNote(n);+ });+ });+ }+ octx.restore();+ }- // 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));+ // Playhead (static scrub position in v1 — click to move).+ const px = timeToX(playheadSecRef.current);+ if (px >= GUTTER_W && px <= width) {+ octx.fillStyle = accent;+ octx.fillRect(px - 1, RULER_H, 2, height - RULER_H);+ }+ };++ // Rebuild the offscreen scene only when its signature changed; otherwise+ // reuse the cached bitmap.+ const dpr = (typeof window !== 'undefined' && window.devicePixelRatio) || 1;+ const sig = {+ width, height, zoom: zoomRef.current, scroll, chordLaneH,+ lowMidi, highMidi, multiTrack, dpr,+ data, chords: chordLaneH ? chords : null, bg, accent, accentRgb,+ };+ const cached = sceneRef.current;+ if (!cached.canvas || !sceneSigEqual(cached.sig, sig)) {+ const off = cached.canvas+ || (typeof document !== 'undefined' ? document.createElement('canvas') : null);+ if (off) {+ // Only re-allocate (which clears + resets the transform) when the pixel+ // size actually changes; a pan/theme rebuild keeps the same buffer and+ // repaints over it (paintScene clears its own frame first).+ const pxW = Math.round(width * dpr);+ const pxH = Math.round(height * dpr);+ if (off.width !== pxW || off.height !== pxH) { off.width = pxW; off.height = pxH; }+ const octx = off.getContext('2d');+ if (octx) {+ octx.setTransform(dpr, 0, 0, dpr, 0, 0);+ paintScene(octx);+ }+ sceneRef.current = { canvas: off, sig };}}- // Scroll indicator along the bottom when zoomed in.- if (maxScroll > 0) {- const frac = gridW / (duration * pps);- const barW = Math.max(24, gridW * frac);- const barX = GUTTER_W + (scroll / maxScroll) * (gridW - barW);- ctx.fillStyle = 'rgba(255,255,255,0.15)';- ctx.fillRect(barX, height - 3, barW, 2);- }- }, [data, chords, chordLaneH, geometry, height, highMidi, lowMidi, hover, multiTrack, duration]);++ ctx.clearRect(0, 0, width, height);+ const scene = sceneRef.current.canvas;+ if (scene) ctx.drawImage(scene, 0, 0, width, height);+ else paintScene(ctx); // no offscreen available (SSR) — paint direct+ paintOverlay(ctx);+ }, [data, chords, chordLaneH, geometry, height, highMidi, lowMidi, hover, multiTrack, duration, notesByMidi]);const drawRef = useRef(draw);drawRef.current = draw;+ // Theme-following canvas palette (accent + bg) read inside draw() via the+ // ref; re-resolves and repaints on theme switch.+ const paletteRef = useCanvasRollPalette(drawRef);+// DPR-aware canvas sizing + redraw on container resize (shared hook).const widthRef = useCanvasDprSize(wrapRef, canvasRef, height, drawRef);@@ -285,18 +410,19 @@ export default function MidiPianoRoll({ data, chords, showChords, zoom, onZoomCh}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; the+ // Only the notes on this pitch row (index by midi) instead of every note;+ // 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 row = notesByMidi.get(midi);+ if (!row) return null;+ for (let i = row.length - 1; i >= 0; i -= 1) {+ const n = row[i];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]);+ }, [chords, chordLaneH, geometry, highMidi, notesByMidi]);// Update tooltip position without re-rendering: stash in a ref and mutate// the DOM node directly when it's mounted.diff --git a/client/src/components/songs/MidiPianoRoll.test.jsx b/client/src/components/songs/MidiPianoRoll.test.jsxnew file mode 100644index 0000000000..e18b75f4ba--- /dev/null+++ b/client/src/components/songs/MidiPianoRoll.test.jsx@@ -0,0 +1,65 @@+import { render, cleanup } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import MidiPianoRoll from './MidiPianoRoll.jsx';++// jsdom has no canvas/ResizeObserver and reports 0 widths — stub the minimum the+// component needs so draw() runs and we can assert it painted. `drawImage` is+// required because the roll composites a cached offscreen "scene" bitmap onto+// the visible canvas each repaint.+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(), drawImage: vi.fn(),+ fillStyle: '', strokeStyle: '', lineWidth: 1, font: '', textAlign: '', globalAlpha: 1,+});++const DATA = {+ durationSec: 2,+ minMidi: 60,+ maxMidi: 64,+ notes: [+ { id: '0:0', midi: 60, startSec: 0, durationSec: 0.5, velocity: 0.8, track: 0, name: 'C4' },+ { id: '0:1', midi: 64, startSec: 0.5, durationSec: 0.5, velocity: 0.7, track: 0, name: 'E4' },+ ],+ tracks: [{ index: 0, name: null, noteCount: 2 }],+};++describe('<MidiPianoRoll>', () => {+ let ctx;+ beforeEach(() => {+ ctx = makeCtx();+ vi.spyOn(HTMLCanvasElement.prototype, 'getContext').mockReturnValue(ctx);+ vi.stubGlobal('ResizeObserver', class { observe() {} disconnect() {} });+ vi.stubGlobal('MutationObserver', class { observe() {} disconnect() {} });+ Object.defineProperty(HTMLElement.prototype, 'clientWidth', { configurable: true, get() { return 800; } });+ });+ afterEach(() => {+ cleanup();+ vi.restoreAllMocks();+ vi.unstubAllGlobals();+ delete HTMLElement.prototype.clientWidth;+ });++ it('paints notes into an offscreen scene and composites it onto the canvas', () => {+ render(<MidiPianoRoll data={DATA} chords={[]} showChords={false} zoom={1} onZoomChange={() => {}} height={240} />);+ expect(ctx.setTransform).toHaveBeenCalled(); // offscreen scene built with a DPR transform+ expect(ctx.fill).toHaveBeenCalled(); // note bars drawn into the scene+ expect(ctx.drawImage).toHaveBeenCalled(); // cached scene composited to the visible canvas+ });++ it('renders the chord lane labels when showChords is set', () => {+ const chords = [{ startSec: 0, endSec: 1, label: 'Cmaj', midis: [60, 64, 67] }];+ render(<MidiPianoRoll data={DATA} chords={chords} showChords zoom={1} onZoomChange={() => {}} height={240} />);+ const labels = ctx.fillText.mock.calls.map((c) => c[0]);+ expect(labels).toContain('Cmaj');+ });++ it('renders an empty/default view-model without crashing', () => {+ const empty = { durationSec: 0, minMidi: 60, maxMidi: 71, notes: [], tracks: [] };+ expect(() => render(+ <MidiPianoRoll data={empty} chords={[]} showChords={false} zoom={1} onZoomChange={() => {}} height={240} />,+ )).not.toThrow();+ expect(ctx.drawImage).toHaveBeenCalled();+ });+});diff --git a/client/src/components/songs/MidiVisualization.test.jsx b/client/src/components/songs/MidiVisualization.test.jsxindex 64f497ccc6..d400395302 100644--- a/client/src/components/songs/MidiVisualization.test.jsx+++ b/client/src/components/songs/MidiVisualization.test.jsx@@ -28,7 +28,7 @@ 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(),+ moveTo: vi.fn(), arcTo: vi.fn(), setTransform: vi.fn(), drawImage: vi.fn(),fillStyle: '', strokeStyle: '', lineWidth: 1, font: '', textAlign: '', globalAlpha: 1,});diff --git a/client/src/components/songs/PianoRoll.jsx b/client/src/components/songs/PianoRoll.jsxindex 8d5a75b4d8..638971a132 100644--- a/client/src/components/songs/PianoRoll.jsx+++ b/client/src/components/songs/PianoRoll.jsx@@ -9,6 +9,7 @@ import {} from '../../lib/pianoKeyboard';import { roundRect } from '../../lib/canvasRoll.js';import useCanvasDprSize from '../../hooks/useCanvasDprSize.js';+import useCanvasRollPalette from '../../hooks/useCanvasRollPalette.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@@ -33,9 +34,7 @@ const WHITE_KEY_FILL = '#e7e7ea';const WHITE_KEY_EDGE = '#9a9aa2';const BLACK_KEY_FILL = '#1b1b20';const BLACK_KEY_EDGE = '#000000';-const HIT_LINE = '#3b82f6';const GRID_LINE = 'rgba(255,255,255,0.05)';-const BG = '#0c0c0e';/*** @param {object} props@@ -79,6 +78,7 @@ export default function PianoRoll({ parts, tempo, getPosition, playing, height =if (!canvas || !width) return;const ctx = canvas.getContext('2d');if (!ctx) return;+ const { bg, accent } = paletteRef.current;// Keep the negative LEAD-in pre-roll intact (only guard non-finite) so a// falling note reaches the hit line exactly when its audio starts.@@ -94,7 +94,7 @@ export default function PianoRoll({ parts, tempo, getPosition, playing, height =const keyByMidi = new Map(layout.keys.map((k) => [k.midi, k]));ctx.clearRect(0, 0, width, height);- ctx.fillStyle = BG;+ ctx.fillStyle = bg;ctx.fillRect(0, 0, width, hitLineY);// Faint vertical octave gridlines (on every C) to anchor the eye.@@ -128,7 +128,7 @@ export default function PianoRoll({ parts, tempo, getPosition, playing, height =ctx.restore();// Hit line.- ctx.fillStyle = HIT_LINE;+ ctx.fillStyle = accent;ctx.fillRect(0, hitLineY - 1, width, 2);// Keyboard — white keys first, then black overlaid. Active keys glow in the@@ -143,7 +143,7 @@ export default function PianoRoll({ parts, tempo, getPosition, playing, height =ctx.strokeRect(k.x + 0.5, hitLineY + 0.5, k.w - 1, kbH - 1);// Octave label on each C.if (k.midi % 12 === 0 && k.w > 14) {- ctx.fillStyle = lit ? '#0c0c0e' : '#71717a';+ ctx.fillStyle = lit ? bg : '#71717a';ctx.font = '9px ui-sans-serif, system-ui, sans-serif';ctx.textAlign = 'center';ctx.fillText(midiNoteName(k.midi), k.x + k.w / 2, hitLineY + kbH - 5);@@ -166,6 +166,10 @@ export default function PianoRoll({ parts, tempo, getPosition, playing, height =const drawRef = useRef(draw);drawRef.current = draw;+ // Theme-following canvas palette (bg + accent hit line), read inside draw()+ // via the ref; re-resolves and repaints on theme switch.+ const paletteRef = useCanvasRollPalette(drawRef);+// Size the canvas to the container (devicePixelRatio-aware) and redraw.const widthRef = useCanvasDprSize(wrapRef, canvasRef, height, drawRef);diff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex ea0f2a3158..c8186f3cca 100644--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@ -159,4 +159,5 @@ grep -i "what you want to do" client/src/hooks/README.md| `useReferenceAudioImport` | One round reference-audio-import job slot (#2120): start/cancel + SSE progress + terminal-frame handling via `POST /api/rounds/reference-audio/import`. Returns `{ active, percent, stage, start(url, context), cancel }`; `onComplete(filename, context)` fires with the uploads-dir filename to persist on the reference. Call once per surface that can independently kick off a download. | The reference-audio attach controls (`ReferenceAudioAttach`) — the "Download from URL" convenience. || `useMidiTranscription` | One audio → MIDI transcription job slot (MuScriptor): start/cancel + SSE stage progress + terminal-frame handling, generic over the Rounds and Music Video API surfaces (pass `startRequest`/`eventsUrl`/`cancelRequest`). Returns `{ active, stage, stageLabel, context, start(context), cancel }` (`stageLabel` is the ready-to-render human label for the current STAGE — including a distinct "Downloading model…" for the first-use weight download, which also fires a one-time toast; `context` is the in-flight job's captured target, for per-target UI gates); `onComplete(frame, context)` fires with the terminal frame (`filename`, `model`, any server-merged extras). | The Rounds reference "Transcribe MIDI" control and the Music Video MIDI button. || `useCanvasDprSize` | DevicePixelRatio-aware canvas sizing shared by the piano-roll renderers (`<PianoRoll>`, `<MidiPianoRoll>`): sizes the bitmap to container-width × height at the DPR, applies the transform, and redraws via a `drawRef` on mount + every `ResizeObserver` resize (observer created once per height, never churned by draw-closure changes). Returns a ref holding the current CSS width so draw code doesn't measure the DOM per frame. | Both piano-roll canvases. |+| `useCanvasRollPalette` | Resolves the roll canvas palette (theme-following `--port-accent` + roll bg via `rollPalette`) into a ref, re-resolving on theme switch (`data-port-theme` MutationObserver) and repainting through a `drawRef`. Hands back a ref, not state, so a theme swap redraws the imperative canvas without a React re-render. | Both piano-roll canvases need theme-aware accent/bg colors that canvas `fillStyle` can't read from CSS vars. || `useMidiNotes` | Fetch + parse a transcribed `.mid` file into the piano-roll view-model (`parseMidiFile` in `lib/midiNotes.js`), with a module-level per-URL cache so remounts (collapse, tab switches) don't refetch/reparse. Returns `{ status: 'idle'\|'loading'\|'ready'\|'error', data, error, reload }`; a generation counter drops stale in-flight responses on URL change/unmount. Plain `fetch` of the static file URL — errors surface inline, never as toasts (#2477). | `<MidiVisualization>` (Rounds ReferenceAnalysis + Music Video). |diff --git a/client/src/hooks/index.js b/client/src/hooks/index.jsindex ec45e7a2a6..02014eae85 100644--- a/client/src/hooks/index.js+++ b/client/src/hooks/index.js@@ -52,6 +52,7 @@ export { default as useReferenceAudioImport } from './useReferenceAudioImport.jsexport { default as useMidiTranscription } from './useMidiTranscription.js';export { default as useMidiNotes } from './useMidiNotes.js';export { default as useCanvasDprSize } from './useCanvasDprSize.js';+export { default as useCanvasRollPalette } from './useCanvasRollPalette.js';// === Mixed (both default and named) — surface both ===export { default as useAsyncAction } from './useAsyncAction.js';diff --git a/client/src/hooks/useCanvasRollPalette.js b/client/src/hooks/useCanvasRollPalette.jsnew file mode 100644index 0000000000..cd06340533--- /dev/null+++ b/client/src/hooks/useCanvasRollPalette.js@@ -0,0 +1,22 @@+import { useEffect, useRef } from 'react';+import { rollPalette } from '../lib/canvasRoll.js';++// Resolves the piano-roll canvas palette (theme-following accent + roll bg)+// once, then re-resolves on theme switch and triggers a redraw. Canvas+// `fillStyle` can't read CSS custom properties, so the imperative roll draws+// read the resolved strings from the returned ref inside draw() instead of+// hardcoding hex. Mirrors `useChartColors`'s `data-port-theme` MutationObserver+// (set by `useTheme` on <html>), but hands back a ref — not React state — so a+// theme switch repaints the canvas without forcing a component re-render.+export default function useCanvasRollPalette(drawRef) {+ const paletteRef = useRef(rollPalette());+ useEffect(() => {+ const apply = () => { paletteRef.current = rollPalette(); drawRef.current?.(); };+ apply();+ if (typeof MutationObserver !== 'function') return undefined;+ const observer = new MutationObserver(apply);+ observer.observe(document.documentElement, { attributes: true, attributeFilter: ['data-port-theme'] });+ return () => observer.disconnect();+ }, [drawRef]);+ return paletteRef;+}diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex 02e87abbc6..f131477b3b 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -107,7 +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. |+| `canvasRoll.js` | Shared canvas helpers for the two piano-roll renderers (`<PianoRoll>` falling-note + `<MidiPianoRoll>` DAW-style, #2477). `layerColor(index)` — the per-layer/track palette (8 hues, wraps both directions) used by note bars, keyboards, and legends; `roundRect(ctx, x, y, w, h, r)` — rounded-rect path with `ctx.roundRect` feature-detect and arcTo fallback; `rollPalette()` — resolves the theme-following `{ bg, accent, accentRgb }` from `--port-accent` via `getComputedStyle` (canvas can't read CSS vars); `ROLL_BG` — the shared near-black bg literal. Pure canvas math/palette, no React. || `colorMatch.js` | Pure grading core for the song system's color-match training mode: `buildColorMatchTimeline(score, { bpm })` → `{ notes, totalMs, msPerQuarter, bpm }` (each note's target frequency + onset/offset window in ms, keyed by the same global note index the renderer flattens, timing mirroring `scorePlayback`); `gradeNote(hz, targetHz)` classifies a sung pitch against a target into `in-tune`/`close`/`off`/`missed` (octave-folded, thresholds `MATCH_IN_TUNE_CENTS`/`MATCH_CLOSE_CENTS`); `noteAtTime(timeline, tMs, fromIdx)` finds the active note for a rAF cursor; `summarizeAccuracy(grades)` → `{ graded, counts, percentInTune, perNote }` per-take summary (`perNote` is the ordered grade list a saved take persists, mirroring the server sanitizer); `gradesFromPerNote(timeline, perNote)` is its inverse — rebuilds the noteIndex→grade map to repaint a saved take's grading on open without re-grading audio; plus `centsBetween` and the `GRADE` enum. No React, no audio — the `useColorMatch` hook drives it. || `pitchDetect.js` | Dependency-free vocal pitch-detection core for the song system (tuner / color-match / sing-to-score). `detectFrequency(frame, { sampleRate })` → `{ hz, clarity }` (McLeod NSDF; clarity gate rejects silence/noise); `frequencyToNote(hz, { a4 })` → `{ letter, accidental, octave, step, cents }` (cents ∈ [-50,+50], sharp positive; `step` reuses `scoreNotation`'s `diatonicStep` so detected notes align with the renderer); `noteToFrequency(note, { a4 })` inverse (color-match targets); `createPitchTracker(analyser, { onUpdate })` → `{ stop }` rAF/interval loop with median+EMA smoothing to kill octave jumps; `tuningQuality(cents)` → `{ level, label }` buckets a cents deviation into `in-tune`/`close`/`off`/`none` (thresholds `IN_TUNE_CENTS`/`CLOSE_CENTS`) for the tuner color readout. || `universeBuilderExpand.js` | `mergeExpandIntoDraft(draft, result)` — pure merge of a Universe Builder draft with the LLM expand-API response (lock honoring, category/sheet merge with `kind` precedence, canon dedupe by name/slugline/alias). Also exports `mergeVariations`, `mergeCanonByName`, and `extractPreservedFromDraft` for callers that need the building blocks (per-category Generate, save-time refetch+merge). |diff --git a/client/src/lib/canvasRoll.js b/client/src/lib/canvasRoll.jsindex 36464f6ea3..8a1d8c93b6 100644--- a/client/src/lib/canvasRoll.js+++ b/client/src/lib/canvasRoll.js@@ -7,6 +7,31 @@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];+// Roll canvas background — a near-black intentionally darker than `--port-bg`+// (#0f0f0f) so the note bars pop. Single source for the literal both rolls+// (and their wrapper `bg-[#0c0c0e]` fallback) previously duplicated inline.+export const ROLL_BG = '#0c0c0e';+const ACCENT_FALLBACK_RGB = '59 130 246'; // Classic Midnight --port-accent++/**+ * Resolve the roll canvas palette from the active theme. Canvas `fillStyle`+ * can't read CSS custom properties, so we read `--port-accent` once via+ * `getComputedStyle` (mirroring `useChartColors`) and hand back concrete+ * strings. `accentRgb` is the raw space-separated triple so callers can build+ * alpha tints (`rgb(${accentRgb} / 0.25)`); `accent` is the ready-to-use solid.+ * Falls back to the Classic Midnight accent in non-browser/test environments.+ * @returns {{ bg:string, accent:string, accentRgb:string }}+ */+export const rollPalette = () => {+ let accentRgb = ACCENT_FALLBACK_RGB;+ if (typeof window !== 'undefined' && typeof getComputedStyle === 'function') {+ const parts = getComputedStyle(document.documentElement)+ .getPropertyValue('--port-accent').trim().split(/\s+/).filter(Boolean);+ if (parts.length >= 3) accentRgb = `${parts[0]} ${parts[1]} ${parts[2]}`;+ }+ return { bg: ROLL_BG, accent: `rgb(${accentRgb})`, accentRgb };+};+// 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) => {diff --git a/client/src/lib/canvasRoll.test.js b/client/src/lib/canvasRoll.test.jsnew file mode 100644index 0000000000..00efa358c2--- /dev/null+++ b/client/src/lib/canvasRoll.test.js@@ -0,0 +1,52 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import { layerColor, roundRect, rollPalette, ROLL_BG } from './canvasRoll.js';++describe('layerColor', () => {+ it('cycles through the palette and wraps at both ends', () => {+ expect(layerColor(0)).not.toBe(layerColor(1));+ expect(layerColor(8)).toBe(layerColor(0)); // 8-hue palette wraps+ expect(layerColor(-1)).toBe(layerColor(7)); // negative wraps positively+ });+});++describe('roundRect', () => {+ it('uses the native ctx.roundRect when available', () => {+ const ctx = { roundRect: vi.fn(), beginPath: vi.fn() };+ roundRect(ctx, 0, 0, 20, 10, 3);+ expect(ctx.roundRect).toHaveBeenCalledWith(0, 0, 20, 10, 3);+ });++ it('falls back to an arcTo path when ctx.roundRect is missing', () => {+ const ctx = { beginPath: vi.fn(), moveTo: vi.fn(), arcTo: vi.fn(), closePath: vi.fn() };+ roundRect(ctx, 0, 0, 20, 10, 3);+ expect(ctx.arcTo).toHaveBeenCalledTimes(4);+ expect(ctx.closePath).toHaveBeenCalled();+ });++ it('clamps the radius so it never exceeds half the smaller side', () => {+ const ctx = { roundRect: vi.fn(), beginPath: vi.fn() };+ roundRect(ctx, 0, 0, 8, 4, 100);+ expect(ctx.roundRect).toHaveBeenCalledWith(0, 0, 8, 4, 2); // min(100, 4, 2) = 2+ });+});++describe('rollPalette', () => {+ afterEach(() => vi.restoreAllMocks());++ it('resolves --port-accent from the theme into concrete strings', () => {+ vi.spyOn(window, 'getComputedStyle').mockReturnValue({+ getPropertyValue: (name) => (name === '--port-accent' ? ' 168 85 247 ' : ''),+ });+ const p = rollPalette();+ expect(p.bg).toBe(ROLL_BG);+ expect(p.accentRgb).toBe('168 85 247');+ expect(p.accent).toBe('rgb(168 85 247)');+ });++ it('falls back to the Classic Midnight accent when the var is missing', () => {+ vi.spyOn(window, 'getComputedStyle').mockReturnValue({ getPropertyValue: () => '' });+ const p = rollPalette();+ expect(p.accent).toBe('rgb(59 130 246)');+ expect(p.accentRgb).toBe('59 130 246');+ });+});diff --git a/client/src/lib/midiNotes.js b/client/src/lib/midiNotes.jsindex 03bb6dbdd2..a3a55453e8 100644--- a/client/src/lib/midiNotes.js+++ b/client/src/lib/midiNotes.js@@ -137,9 +137,19 @@ const buildTickToSec = (division, tempoEvents) => {curUs = c.usPerQuarter;segments.push({ tick: curTick, sec: curSec, usPerQuarter: curUs });});+ const DEFAULT_BASE = { tick: 0, sec: 0, usPerQuarter: DEFAULT_TEMPO_US };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];+ // Binary-search the last segment whose tick ≤ the query tick (segments are+ // sorted ascending). Falls back to the SMF default tempo for ticks before+ // the first tempo change. O(log segments) instead of a per-note linear scan+ // — only material for tempo-automation-dense files, but free to get right.+ let lo = 0;+ let hi = segments.length - 1;+ let base = DEFAULT_BASE;+ while (lo <= hi) {+ const mid = (lo + hi) >> 1;+ if (segments[mid].tick <= tick) { base = segments[mid]; lo = mid + 1; } else { hi = mid - 1; }+ }return base.sec + ((tick - base.tick) * base.usPerQuarter) / (ppq * 1e6);};};diff --git a/client/src/lib/midiNotes.test.js b/client/src/lib/midiNotes.test.jsindex 7d4d65e8f7..8ede5897a8 100644--- a/client/src/lib/midiNotes.test.js+++ b/client/src/lib/midiNotes.test.js@@ -81,6 +81,27 @@ describe('parseMidiFile', () => {expect(vm.tempos.map((t) => t.bpm)).toEqual([120, 240]);});+ it('resolves tick→seconds across several tempo segments (binary-search picks the right one)', () => {+ const bytes = smf([track([+ tempoEv(0, 500000), // tick 0 → 120 BPM (0.5s/beat)+ noteOn(0, 60), noteOff(PPQ, 60), // tick 0..480 → 0.00s+ tempoEv(0, 250000), // tick 480 → 240 BPM (0.25s/beat)+ noteOn(0, 62), noteOff(PPQ, 62), // tick 480..960 → 0.50s+ tempoEv(0, 1000000), // tick 960 → 60 BPM (1.0s/beat)+ noteOn(0, 64), noteOff(PPQ, 64), // tick 960..1440 → 0.75s, lasts 1.0s+ noteOn(0, 65), noteOff(PPQ, 65), // tick 1440..1920 → 1.75s+ endOfTrack(),+ ])]);+ const vm = parseMidiFile(bytes);+ const at = (midi) => vm.notes.find((n) => n.midi === midi);+ expect(at(60).startSec).toBeCloseTo(0.0, 5);+ expect(at(62).startSec).toBeCloseTo(0.5, 5);+ expect(at(64).startSec).toBeCloseTo(0.75, 5);+ expect(at(64).durationSec).toBeCloseTo(1.0, 5);+ expect(at(65).startSec).toBeCloseTo(1.75, 5); // last segment (60 BPM) applied+ expect(vm.tempos.map((t) => t.bpm)).toEqual([120, 240, 60]);+ });+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([diff --git a/client/src/utils/formatters.js b/client/src/utils/formatters.jsindex fd6d967729..27529dfca7 100644--- a/client/src/utils/formatters.js+++ b/client/src/utils/formatters.js@@ -210,10 +210,12 @@ export function formatDateTime(value) {/*** Format a number of seconds as M:SS (e.g. 75 → "1:15"). For coarse durations- * like a stitched video's runtime. Returns `'—'` for missing/invalid input.+ * like a stitched video's runtime or a piano-roll ruler tick. Returns `'—'`+ * for missing/invalid/negative input; a genuine zero renders as `"0:00"` (not+ * `'—'`) so callers can distinguish "unknown" from "zero seconds".*/export function formatDurationSec(seconds) {- if (!seconds || !Number.isFinite(seconds)) return '—';+ if (!Number.isFinite(seconds) || seconds < 0) return '—';const m = Math.floor(seconds / 60);const s = Math.floor(seconds % 60);return `${m}:${String(s).padStart(2, '0')}`;diff --git a/client/src/utils/formatters.test.js b/client/src/utils/formatters.test.jsindex a49948cd12..b1a1d0dc0a 100644--- a/client/src/utils/formatters.test.js+++ b/client/src/utils/formatters.test.js@@ -1,9 +1,30 @@import { describe, it, expect } from 'vitest';import {formatContextLength, formatDurationMin, formatDurationMs, formatEventDateTime, timeAgo,- formatCooldown, parseSizeGb, recommendedRamGb, parseTimeoutMs,+ formatCooldown, parseSizeGb, recommendedRamGb, parseTimeoutMs, formatDurationSec,} from './formatters.js';+describe('formatDurationSec', () => {+ it('formats seconds as M:SS with a zero-padded seconds field', () => {+ expect(formatDurationSec(75)).toBe('1:15');+ expect(formatDurationSec(5)).toBe('0:05');+ expect(formatDurationSec(600)).toBe('10:00');+ });++ it('renders a genuine zero as "0:00" (not the unknown dash)', () => {+ // Distinguishes "zero seconds" from "unknown" — the ruler and totals rely+ // on 0 → "0:00" rather than the old truthiness collapse to "—".+ expect(formatDurationSec(0)).toBe('0:00');+ });++ it('returns the unknown dash for missing/invalid/negative input', () => {+ expect(formatDurationSec(null)).toBe('—');+ expect(formatDurationSec(undefined)).toBe('—');+ expect(formatDurationSec(NaN)).toBe('—');+ expect(formatDurationSec(-3)).toBe('—');+ });+});+describe('formatContextLength', () => {it('formats common context windows compactly', () => {expect(formatContextLength(4096)).toBe('4K ctx');