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-1092]): persist per-take pitch analysis end-to-end
Adam Eivy93e8937c8490
diff --git a/client/src/components/songs/ColorMatch.jsx b/client/src/components/songs/ColorMatch.jsxindex 6b3eb99b55..1247fada89 100644--- a/client/src/components/songs/ColorMatch.jsx+++ b/client/src/components/songs/ColorMatch.jsx@@ -1,23 +1,24 @@/*** ColorMatch — sing the written melody and watch the score grade you in real- * time. While a vocal take is recording, this panel walks the notated score in- * tempo (after a one-bar metronome count-in) and colors each notehead by how- * accurately it was sung — green (in tune), yellow (close), red (off or missed)- * — then shows a per-take accuracy score for training.+ * time. While a vocal take is recording, the parent (`SongRecordings`) walks the+ * notated score in tempo (after a one-bar metronome count-in) and feeds this+ * panel the per-note grades; it colors each notehead by how accurately it was+ * sung — green (in tune), yellow (close), red (off or missed) — then shows a+ * per-take accuracy score for training.*- * It is a thin shell over `useColorMatch` (which owns the timing/grading) and- * the pure <ScoreSheet> renderer (which just paints the `noteColors` it's- * handed). The grading mic is the SAME stream the recorder opened — no second- * getUserMedia. With no live take, the panel shows a hint to start recording.+ * Presentational: the grading lives in `useColorMatch`, lifted into+ * `SongRecordings` so the recorder can attach the finished take's pitch trace ++ * accuracy to the saved recording (#1092). This component only paints the+ * `noteColors`/`summary` it's handed onto the pure <ScoreSheet> renderer. With+ * no live take and no prior summary, it shows a hint to start recording.** Colors and copy use `--port-*` theme tokens only; the layout is* mobile-responsive (the controls wrap above the staff).*/-import { useEffect, useMemo } from 'react';+import { useMemo } from 'react';import { Target } from 'lucide-react';-import { parseScore, scoreHasMusic } from '../../lib/scoreNotation.js';-import useColorMatch from '../../hooks/useColorMatch.js';+import { scoreHasMusic } from '../../lib/scoreNotation.js';import ScoreSheet from './ScoreSheet.jsx';// Summary bucket → readout color token, matching the notehead grades.@@ -28,25 +29,16 @@ const BUCKET_TONE = {missed: 'text-port-error',};-export default function ColorMatch({ score = '', stream = null, tempo = null }) {+export default function ColorMatch({+ score = '',+ stream = null,+ running = false,+ countingIn = false,+ noteColors = null,+ summary = null,+ activeIndex = null,+}) {const hasMusic = useMemo(() => scoreHasMusic(score), [score]);- const parsed = useMemo(() => parseScore(score), [score]);- const bpm = Number.isFinite(tempo) && tempo > 0 ? tempo : null;-- const { running, countingIn, noteColors, summary, activeIndex, start } = useColorMatch({- score: parsed,- stream,- bpm,- });-- // Auto-arm: the moment a take starts (stream appears) and the score has notes,- // begin a color-match run so the singer is graded as they record. Stop when the- // take ends. The hook also stops itself when the stream vanishes mid-run.- useEffect(() => {- if (stream && hasMusic && !running) start();- // start/stop are stable from the hook; we only react to stream/hasMusic.- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [stream, hasMusic]);if (!hasMusic) return null;diff --git a/client/src/components/songs/SongRecordings.jsx b/client/src/components/songs/SongRecordings.jsxindex 7b7da46671..5408acb52a 100644--- a/client/src/components/songs/SongRecordings.jsx+++ b/client/src/components/songs/SongRecordings.jsx@@ -14,12 +14,15 @@*/import { useEffect, useRef, useState, useCallback, useMemo } from 'react';-import { Mic, Square, Play, Trash2, Volume2, VolumeX, Loader2 } from 'lucide-react';+import { Mic, Square, Play, Trash2, Volume2, VolumeX, Loader2, Target } from 'lucide-react';import toast from '../ui/Toast';import { startMemoRecording } from '../../lib/audioRecorder';import { createLayeredPlayer } from '../../lib/songPlayback';import { uploadFile, getUploadUrl } from '../../services/api';import { formatDurationMs } from '../../utils/formatters';+import { parseScore, scoreHasMusic } from '../../lib/scoreNotation';+import { buildColorMatchTimeline, gradesFromPerNote } from '../../lib/colorMatch';+import useColorMatch from '../../hooks/useColorMatch';import Metronome from './Metronome';import PitchTuner from './PitchTuner';import ColorMatch from './ColorMatch';@@ -46,6 +49,33 @@ export default function SongRecordings({ recordings = [], layers = [], onChange,const handleRef = useRef(null); // active MediaRecorder handleconst playerRef = useRef(null); // active layered player+ // Live color-match grading is owned HERE (not inside <ColorMatch>) so the+ // finished take's pitch trace + accuracy can be attached to the saved+ // recording (#1092). The hook taps the SAME recording stream; ColorMatch is a+ // presentational view of its noteColors/summary.+ const hasMusic = useMemo(() => scoreHasMusic(score), [score]);+ const parsedScore = useMemo(() => parseScore(score), [score]);+ const bpm = Number.isFinite(tempo) && tempo > 0 ? tempo : null;+ const {+ running: matchRunning, countingIn, noteColors, summary, activeIndex,+ start: startMatch, stop: stopMatch,+ } = useColorMatch({ score: parsedScore, stream: liveStream, bpm });++ // Auto-arm grading the moment a take starts (stream appears) and the score has+ // notes — mirrors the old <ColorMatch> self-arm, now lifted up. The take's+ // stopRecording explicitly stops grading to harvest the trace, so we only+ // need to start here. The hook also self-stops if the stream vanishes.+ useEffect(() => {+ if (liveStream && hasMusic && !matchRunning) startMatch();+ // start is stable; react only to stream/hasMusic (the arm trigger).+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [liveStream, hasMusic]);++ // A persisted take selected for review — repaints its saved grades onto the+ // staff from disk (no re-grading). Null when no take is being reviewed or a+ // live take is grading (the live run owns the staff then).+ const [reviewId, setReviewId] = useState(null);+// Tear down any live player/recorder on unmount so a navigation-away can't// leave the mic open or audio playing into the void.useEffect(() => () => {@@ -59,6 +89,7 @@ export default function SongRecordings({ recordings = [], layers = [], onChange,}, [layers]);const startRecording = useCallback(async () => {+ setReviewId(null); // a fresh take takes over the staff from any saved-take reviewif (playerRef.current) { playerRef.current.stop(); setPlaying(false); }const handle = await startMemoRecording().catch((err) => {toast.error(err?.message || 'Microphone access denied');@@ -74,6 +105,10 @@ export default function SongRecordings({ recordings = [], layers = [], onChange,const handle = handleRef.current;if (!handle) return;handleRef.current = null;+ // Stop grading FIRST (while the analyser graph is still alive) to harvest the+ // finished take's pitch trace + accuracy summary, THEN drop the stream. stop()+ // returns null if grading wasn't running (no score / unmounted).+ const analysis = stopMatch();setLiveStream(null); // stream is being torn down with the takesetRecording(false);setSaving(true);@@ -96,26 +131,48 @@ export default function SongRecordings({ recordings = [], layers = [], onChange,setSaving(false);if (!result?.filename) return;- const next = [- ...recordings,- {- id: tempRecordingId(),- layerId: targetLayerId,- label: targetLayerId ? layerLabel(targetLayerId) : 'Take',- filename: result.filename,- durationMs: take.durationMs || 0,- peak: take.peak || 0,- muted: false,- },- ];- onChange(next);+ const entry = {+ id: tempRecordingId(),+ layerId: targetLayerId,+ label: targetLayerId ? layerLabel(targetLayerId) : 'Take',+ filename: result.filename,+ durationMs: take.durationMs || 0,+ peak: take.peak || 0,+ muted: false,+ };+ // Attach the captured pitch analysis when the take was graded against a score+ // (#1092). Only persist a trace/summary that actually has content — a take+ // sung with no score (or that graded zero notes) carries no analysis, and the+ // server omits empty fields anyway. The server re-sanitizes + bounds both.+ if (analysis?.pitchTrack?.length) entry.pitchTrack = analysis.pitchTrack;+ if (analysis?.summary?.graded > 0) entry.accuracy = analysis.summary;++ onChange([...recordings, entry]);toast.success('Take recorded — Save the song to keep it');- }, [recordings, targetLayerId, layerLabel, onChange]);+ }, [recordings, targetLayerId, layerLabel, onChange, stopMatch]);const removeRecording = useCallback((id) => {+ setReviewId((cur) => (cur === id ? null : cur));onChange(recordings.filter((r) => r.id !== id));}, [recordings, onChange]);+ // The take being reviewed (if it still exists and carries saved accuracy).+ const reviewTake = useMemo(+ () => recordings.find((r) => r.id === reviewId && r.accuracy?.perNote?.length) || null,+ [recordings, reviewId],+ );+ // Repaint the reviewed take's SAVED grades onto the staff — read from disk via+ // gradesFromPerNote, never re-graded from audio (the migration's purpose).+ const reviewColors = useMemo(() => {+ if (!reviewTake) return null;+ const timeline = buildColorMatchTimeline(parsedScore, { bpm });+ return gradesFromPerNote(timeline, reviewTake.accuracy.perNote);+ }, [reviewTake, parsedScore, bpm]);++ const toggleReview = useCallback((id) => {+ setReviewId((cur) => (cur === id ? null : id));+ }, []);+const toggleMute = useCallback((id) => {onChange(recordings.map((r) => (r.id === id ? { ...r, muted: !r.muted } : r)));}, [recordings, onChange]);@@ -192,10 +249,20 @@ export default function SongRecordings({ recordings = [], layers = [], onChange,</div>{/* Color-match — walks the written score in tempo while recording and- grades each note by sung accuracy. Only shows when the song has a+ grades each note by sung accuracy. While a live take grades, it shows+ the live run; otherwise it can replay a saved take's grading (selected+ via the "Review" button on a recording). Only shows when the song has anotated melody to sing against. */}<div className="mb-3">- <ColorMatch score={score} stream={liveStream} tempo={tempo} />+ <ColorMatch+ score={score}+ stream={liveStream}+ running={matchRunning}+ countingIn={countingIn}+ noteColors={reviewTake && !matchRunning ? reviewColors : noteColors}+ summary={reviewTake && !matchRunning ? reviewTake.accuracy : summary}+ activeIndex={matchRunning ? activeIndex : null}+ /></div>{/* Layer the next take targets (optional) */}@@ -233,6 +300,14 @@ export default function SongRecordings({ recordings = [], layers = [], onChange,<div className="flex items-center gap-2 min-w-0"><span className="text-sm text-white truncate">{r.label || 'Take'}</span>{r.durationMs > 0 && <span className="text-xs text-gray-500 shrink-0">{formatDurationMs(r.durationMs)}</span>}+ {r.accuracy?.graded > 0 && (+ <span+ className={`text-xs shrink-0 font-medium ${r.accuracy.percentInTune >= 80 ? 'text-port-success' : r.accuracy.percentInTune >= 50 ? 'text-port-warning' : 'text-port-error'}`}+ title={`${r.accuracy.percentInTune}% in tune over ${r.accuracy.graded} ${r.accuracy.graded === 1 ? 'note' : 'notes'}`}+ >+ {r.accuracy.percentInTune}%+ </span>+ )}</div>{layers.length > 0 && (<select@@ -246,6 +321,20 @@ export default function SongRecordings({ recordings = [], layers = [], onChange,</select>)}</div>+ {/* Review the saved grading on the staff (no re-grading from audio).+ Only when the take carries per-note grades and nothing is live. */}+ {hasMusic && r.accuracy?.perNote?.length > 0 && !matchRunning && (+ <button+ type="button"+ onClick={() => toggleReview(r.id)}+ aria-pressed={reviewId === r.id}+ title={reviewId === r.id ? 'Hide saved grading' : 'Show this take’s grading on the staff'}+ className={`p-1 shrink-0 ${reviewId === r.id ? 'text-port-accent' : 'text-gray-500 hover:text-port-accent'}`}+ aria-label="Review take grading"+ >+ <Target size={15} />+ </button>+ )}{/* Solo listen to one take */}<audio controls preload="none" src={getUploadUrl(r.filename)} className="h-8 max-w-[160px] hidden sm:block" /><button type="button" onClick={() => removeRecording(r.id)} className="p-1.5 text-gray-500 hover:text-port-error shrink-0" aria-label="Remove take">diff --git a/client/src/components/songs/SongRecordings.test.jsx b/client/src/components/songs/SongRecordings.test.jsxnew file mode 100644index 0000000000..f00c057034--- /dev/null+++ b/client/src/components/songs/SongRecordings.test.jsx@@ -0,0 +1,126 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { render, screen, fireEvent, waitFor } from '@testing-library/react';++// SongRecordings owns the color-match grading (#1092) so it can attach the+// finished take's pitch trace + accuracy to the saved recording. We mock the+// three seams that need a mic / Web Audio (none exist in jsdom):+// - useColorMatch: the grading hook. stop() returns the analysis to attach.+// - audioRecorder.startMemoRecording: the WAV recorder.+// - services/api: the upload + url helpers.+// The pure grading math is covered in colorMatch.test.js; here we pin the+// wiring: stop() is harvested before the stream drops, and its analysis lands+// on the new recording entry.++const matchStart = vi.fn();+let matchStopResult = null;+const matchStop = vi.fn(() => matchStopResult);+let hookState = { running: false, countingIn: false, noteColors: {}, summary: null, activeIndex: null };++vi.mock('../../hooks/useColorMatch', () => ({+ __esModule: true,+ default: () => ({ ...hookState, start: matchStart, stop: matchStop }),+}));++const takeResult = { audioBase64: 'data', durationMs: 1200, peak: 0.5 };+const handleStop = vi.fn(() => Promise.resolve(takeResult));+vi.mock('../../lib/audioRecorder', () => ({+ startMemoRecording: vi.fn(() => Promise.resolve({+ stream: { getTracks: () => [{ stop: vi.fn() }] },+ stop: handleStop,+ cancel: vi.fn(),+ })),+}));++vi.mock('../../lib/songPlayback', () => ({+ createLayeredPlayer: vi.fn(() => ({ play: vi.fn(() => Promise.resolve()), stop: vi.fn(), onEnded: vi.fn() })),+}));++const uploadFile = vi.fn(() => Promise.resolve({ filename: 'vocal-test.wav' }));+vi.mock('../../services/api', () => ({+ uploadFile: (...a) => uploadFile(...a),+ getUploadUrl: (f) => `/api/uploads/${f}`,+}));++vi.mock('../ui/Toast', () => ({ default: { success: vi.fn(), error: vi.fn() } }));++// PitchTuner taps Web Audio (createStreamAnalyser) on a live stream — stub it;+// it has its own test. ColorMatch stays real (it's pure now) so we exercise the+// lifted grading state it renders.+vi.mock('./PitchTuner', () => ({ default: () => null }));++import SongRecordings from './SongRecordings.jsx';++// A short score so scoreHasMusic() is true and grading auto-arms.+const SCORE = ['time: 4/4', 'tempo: 120', '| C4q D4q E4q F4q |'].join('\n');++describe('SongRecordings — pitch analysis wiring (#1092)', () => {+ beforeEach(() => {+ matchStart.mockClear();+ matchStop.mockClear();+ handleStop.mockClear();+ uploadFile.mockClear();+ matchStopResult = null;+ hookState = { running: false, countingIn: false, noteColors: {}, summary: null, activeIndex: null };+ });++ it('attaches the captured pitchTrack + accuracy to the new take on stop', async () => {+ matchStopResult = {+ summary: { graded: 4, counts: { 'in-tune': 3, close: 1, off: 0, missed: 0 }, percentInTune: 75, perNote: ['in-tune', 'in-tune', 'in-tune', 'close'] },+ pitchTrack: [{ tMs: 0, hz: 261.6, cents: 2, clarity: 0.95 }, { tMs: 50, hz: 293.7, cents: -3, clarity: 0.9 }],+ };+ const onChange = vi.fn();+ render(<SongRecordings recordings={[]} score={SCORE} tempo={120} onChange={onChange} />);++ fireEvent.click(screen.getByRole('button', { name: /record take/i }));+ await waitFor(() => expect(screen.getByRole('button', { name: /stop & save/i })).toBeTruthy());+ fireEvent.click(screen.getByRole('button', { name: /stop & save/i }));++ await waitFor(() => expect(onChange).toHaveBeenCalled());+ // Grading was stopped to harvest the analysis.+ expect(matchStop).toHaveBeenCalled();+ const next = onChange.mock.calls.at(-1)[0];+ expect(next).toHaveLength(1);+ expect(next[0].filename).toBe('vocal-test.wav');+ expect(next[0].accuracy).toEqual(matchStopResult.summary);+ expect(next[0].pitchTrack).toEqual(matchStopResult.pitchTrack);+ });++ it('omits analysis when grading produced no graded notes', async () => {+ matchStopResult = {+ summary: { graded: 0, counts: { 'in-tune': 0, close: 0, off: 0, missed: 0 }, percentInTune: 0, perNote: [] },+ pitchTrack: [],+ };+ const onChange = vi.fn();+ render(<SongRecordings recordings={[]} score={SCORE} tempo={120} onChange={onChange} />);++ fireEvent.click(screen.getByRole('button', { name: /record take/i }));+ await waitFor(() => expect(screen.getByRole('button', { name: /stop & save/i })).toBeTruthy());+ fireEvent.click(screen.getByRole('button', { name: /stop & save/i }));++ await waitFor(() => expect(onChange).toHaveBeenCalled());+ const next = onChange.mock.calls.at(-1)[0];+ expect(next[0]).not.toHaveProperty('accuracy');+ expect(next[0]).not.toHaveProperty('pitchTrack');+ });++ it('shows a saved take’s accuracy badge and a Review button to replay its grading', () => {+ const recordings = [{+ id: 'rec-1', label: 'Take', filename: 'a.wav', durationMs: 1000, peak: 0.4, muted: false,+ accuracy: { graded: 4, counts: { 'in-tune': 3, close: 1, off: 0, missed: 0 }, percentInTune: 75, perNote: ['in-tune', 'in-tune', 'in-tune', 'close'] },+ }];+ render(<SongRecordings recordings={recordings} score={SCORE} tempo={120} onChange={vi.fn()} />);+ // Badge shows the persisted percent (read from disk, not recomputed).+ expect(screen.getByText('75%')).toBeTruthy();+ // Review button is present and toggles aria-pressed.+ const review = screen.getByRole('button', { name: /review take grading/i });+ expect(review.getAttribute('aria-pressed')).toBe('false');+ fireEvent.click(review);+ expect(review.getAttribute('aria-pressed')).toBe('true');+ });++ it('does not offer Review for a legacy take with no per-note grades', () => {+ const recordings = [{ id: 'rec-1', label: 'Take', filename: 'a.wav', durationMs: 1000, peak: 0.4, muted: false }];+ render(<SongRecordings recordings={recordings} score={SCORE} tempo={120} onChange={vi.fn()} />);+ expect(screen.queryByRole('button', { name: /review take grading/i })).toBeNull();+ });+});diff --git a/client/src/hooks/useColorMatch.js b/client/src/hooks/useColorMatch.jsindex d5296c2b3e..78733ca7a1 100644--- a/client/src/hooks/useColorMatch.js+++ b/client/src/hooks/useColorMatch.js@@ -24,11 +24,22 @@ import {buildColorMatchTimeline,noteAtTime,gradeNote,+ centsBetween,summarizeAccuracy,GRADE,} from '../lib/colorMatch.js';import useMounted from './useMounted.js';+// Downsample the per-frame pitch readout into a trace at ~20 samples/sec. The+// rAF loop runs at ~60fps; storing every frame would triple the persisted trace+// for no extra fidelity (a sung note is far slower than 16 ms). One sample per+// 50 ms keeps the saved tuner trace replay-accurate while small (a 30 s take is+// ~600 samples, well under the server's PITCH_TRACK_MAX bound).+const TRACE_SAMPLE_MS = 50;+// Defensive client-side cap mirroring the server's PITCH_TRACK_MAX so a runaway+// take can't grow an unbounded array in memory before the server clamps it.+const TRACE_MAX_SAMPLES = 4000;+// Rank grades so a note keeps the BEST attempt it was hit with across the frames// it's active — a singer who slides into pitch shouldn't be graded on the wobble// they started with. Higher rank = better.@@ -58,11 +69,16 @@ export default function useColorMatch({ score, stream, bpm = null, countInBars =const analyserRef = useRef(null);const timelineRef = useRef(null);const startAudioTimeRef = useRef(null); // metronome audio time of the first music beat- const pitchRef = useRef({ hz: null }); // latest tracked pitch, read each rAF frame+ const pitchRef = useRef({ hz: null, clarity: null }); // latest tracked pitch, read each rAF frameconst gradesRef = useRef({}); // mutable accumulator; flushed to stateconst cursorRef = useRef(0); // lower-bound index hint for noteAtTimeconst maxReachedRef = useRef(-1); // furthest note.index the timeline walkedconst rafRef = useRef(null);+ // Downsampled tuner trace ({ tMs, hz, cents, clarity }[]) accumulated across+ // the run and returned by stop() so the recorder can persist it on the take.+ // `lastTraceMs` throttles to one sample per TRACE_SAMPLE_MS (see grade()).+ const traceRef = useRef([]);+ const lastTraceMsRef = useRef(-Infinity);// Tear down the audio graph, tracker, metronome, and rAF loop. Idempotent.const teardown = useCallback(() => {@@ -74,16 +90,19 @@ export default function useColorMatch({ score, stream, bpm = null, countInBars =if (trackerRef.current) { trackerRef.current.stop(); trackerRef.current = null; }if (analyserRef.current) { analyserRef.current.close(); analyserRef.current = null; }startAudioTimeRef.current = null;- pitchRef.current = { hz: null };+ pitchRef.current = { hz: null, clarity: null };cursorRef.current = 0;}, []);// Stop a session: finalize the accuracy summary from whatever was graded, then// tear the audio graph down. Keeps the painted `noteColors` so the singer sees- // their last result.+ // their last result. Returns the finished take analysis `{ summary, pitchTrack }`+ // so a caller (the recorder) can attach it to the saved take; an unmounted stop+ // returns null. The trace is snapshotted BEFORE teardown wipes the run refs.const stop = useCallback(() => {+ const pitchTrack = traceRef.current.slice();teardown();- if (!mountedRef.current) return;+ if (!mountedRef.current) return null;// Fill MISSED for every note the timeline WALKED PAST (index <= maxReached)// that never received a usable grade — so a note the singer skipped counts// against the take. Notes never reached on an early stop stay absent, so@@ -100,10 +119,12 @@ export default function useColorMatch({ score, stream, bpm = null, countInBars =gradesRef.current = filled;setNoteColors(filled);}- setSummary(summarizeAccuracy(gradesRef.current));+ const finalSummary = summarizeAccuracy(gradesRef.current);+ setSummary(finalSummary);setRunning(false);setCountingIn(false);setActiveIndex(null);+ return { summary: finalSummary, pitchTrack };}, [teardown, mountedRef]);// One animation frame while grading: read elapsed time off the metronome's@@ -136,6 +157,22 @@ export default function useColorMatch({ score, stream, bpm = null, countInBars =} else {setActiveIndex((cur) => (cur === null ? cur : null));}+ // Downsample the live pitch into the persisted trace: at most one sample per+ // TRACE_SAMPLE_MS, capped at TRACE_MAX_SAMPLES (the server clamps too). `cents`+ // is measured against the active note's target when one is being sung, else+ // null (a sample in a rest still records hz so the replay isn't gappy).+ if (elapsedMs - lastTraceMsRef.current >= TRACE_SAMPLE_MS+ && traceRef.current.length < TRACE_MAX_SAMPLES) {+ lastTraceMsRef.current = elapsedMs;+ const { hz, clarity } = pitchRef.current;+ const cents = hit ? centsBetween(hz, hit.note.targetHz) : null;+ traceRef.current.push({+ tMs: Math.round(elapsedMs),+ hz: Number.isFinite(hz) ? hz : null,+ cents: Number.isFinite(cents) ? Math.round(cents) : null,+ clarity: Number.isFinite(clarity) ? clarity : null,+ });+ }rafRef.current = requestAnimationFrame(grade);}, [stop]);@@ -149,6 +186,8 @@ export default function useColorMatch({ score, stream, bpm = null, countInBars =gradesRef.current = {};cursorRef.current = 0;maxReachedRef.current = -1;+ traceRef.current = [];+ lastTraceMsRef.current = -Infinity;timelineRef.current = timeline;setNoteColors({});setSummary(null);@@ -162,7 +201,9 @@ export default function useColorMatch({ score, stream, bpm = null, countInBars =analyserRef.current = graph;trackerRef.current = createPitchTracker(graph.analyser, {a4,- onUpdate: (u) => { pitchRef.current = { hz: u.hz }; },+ // Keep hz + clarity — grade() reads hz for scoring and samples both+ // (plus cents-from-target) into the persisted tuner trace.+ onUpdate: (u) => { pitchRef.current = { hz: u.hz, clarity: u.clarity ?? null }; },});const ts = timeSignatureFromScore(score);diff --git a/client/src/lib/colorMatch.js b/client/src/lib/colorMatch.jsindex 90b7a43723..24885e8036 100644--- a/client/src/lib/colorMatch.js+++ b/client/src/lib/colorMatch.js@@ -122,19 +122,49 @@ export const noteAtTime = (timeline, tMs, fromIdx = 0) => {return null;};+// Flatten a grade map/array into the ordered list of GRADED grades. PENDING+// (un-sung) notes are dropped so a stopped-early take isn't penalized for notes+// it never reached. A map is walked in ASCENDING note-index order so the result+// lines up note-for-note with the score (the renderer's global note index); an+// array is taken in its given order. Shared by `summarizeAccuracy` so the+// `perNote` it persists and the counts it derives come from one ordered pass.+const orderedGrades = (grades) => {+ if (Array.isArray(grades)) return grades.filter((g) => g && g !== GRADE.PENDING);+ return Object.entries(grades || {})+ .sort((a, b) => Number(a[0]) - Number(b[0]))+ .map(([, g]) => g)+ .filter((g) => g && g !== GRADE.PENDING);+};+// Aggregate per-note grades into a take summary for training mode. `grades` is a// map (or array) of noteIndex → GRADE for the notes that were walked. Counts a// note "in tune" only for GRADE.IN_TUNE; `percentInTune` is over the GRADED// notes (PENDING/un-sung notes are excluded so a stopped-early take isn't-// penalized for notes it never reached). Returns counts per bucket + the-// percentage, all derived — no side effects.+// penalized for notes it never reached). Returns counts per bucket, the+// percentage, AND `perNote` — the ordered grade list the persisted-take shape+// stores (mirrors server `sanitizeAccuracy`, so a saved take round-trips its+// grading). All derived — no side effects.export const summarizeAccuracy = (grades) => {- const values = Array.isArray(grades)- ? grades.filter((g) => g && g !== GRADE.PENDING)- : Object.values(grades || {}).filter((g) => g && g !== GRADE.PENDING);+ const perNote = orderedGrades(grades);const counts = { 'in-tune': 0, close: 0, off: 0, missed: 0 };- for (const g of values) if (g in counts) counts[g] += 1;- const graded = values.length;+ for (const g of perNote) if (g in counts) counts[g] += 1;+ const graded = perNote.length;const percentInTune = graded > 0 ? Math.round((counts['in-tune'] / graded) * 100) : 0;- return { graded, counts, percentInTune };+ return { graded, counts, percentInTune, perNote };+};++// Reconstruct a noteIndex → GRADE map from a take's persisted `perNote` list and+// its timeline, WITHOUT re-grading audio. `perNote` (from summarizeAccuracy) is+// the graded notes in ascending global-note-index order, rests excluded and+// un-reached notes absent — exactly the order `buildColorMatchTimeline` walks its+// notes — so the i-th persisted grade belongs to the i-th timeline note. Used to+// repaint the staff from a saved take on song open so the grading is read from+// disk, not recomputed from the mic (#1092). Returns an empty map for an empty+// list (a take with no graded notes paints no colors).+export const gradesFromPerNote = (timeline, perNote = []) => {+ const notes = timeline?.notes || [];+ const map = {};+ const n = Math.min(notes.length, perNote.length);+ for (let i = 0; i < n; i += 1) map[notes[i].index] = perNote[i];+ return map;};diff --git a/client/src/lib/colorMatch.test.js b/client/src/lib/colorMatch.test.jsindex 19a3e857f9..68bc1579db 100644--- a/client/src/lib/colorMatch.test.js+++ b/client/src/lib/colorMatch.test.js@@ -7,6 +7,7 @@ import {gradeNote,centsBetween,summarizeAccuracy,+ gradesFromPerNote,GRADE,MATCH_IN_TUNE_CENTS,MATCH_CLOSE_CENTS,@@ -173,4 +174,55 @@ describe('summarizeAccuracy', () => {expect(s.graded).toBe(3);expect(s.percentInTune).toBe(0);});++ // #1092: the summary now carries `perNote` — the ordered grade list the+ // persisted take stores (mirrors server sanitizeAccuracy). It must be in+ // ASCENDING note-index order so a saved take lines up with the score, and+ // exclude PENDING (un-sung) notes just like the counts do.+ it('emits perNote in ascending note-index order, excluding pending', () => {+ // Deliberately out of insertion order to prove the sort, with a PENDING hole.+ const grades = { 2: GRADE.OFF, 0: GRADE.IN_TUNE, 3: GRADE.PENDING, 1: GRADE.CLOSE };+ const s = summarizeAccuracy(grades);+ expect(s.perNote).toEqual([GRADE.IN_TUNE, GRADE.CLOSE, GRADE.OFF]);+ expect(s.graded).toBe(3);+ });++ it('perNote preserves an array input order verbatim', () => {+ expect(summarizeAccuracy([GRADE.OFF, GRADE.IN_TUNE]).perNote).toEqual([GRADE.OFF, GRADE.IN_TUNE]);+ });++ it('emits an empty perNote for a take with no graded notes', () => {+ expect(summarizeAccuracy({}).perNote).toEqual([]);+ });+});++describe('gradesFromPerNote', () => {+ // The persisted-take round trip: a saved `perNote` list repaints onto the+ // staff by mapping each grade to the timeline note at the same ordinal — rests+ // are excluded from both the timeline notes and perNote, so they align.+ const tl = buildColorMatchTimeline(parseScore('time: 4/4\ntempo: 120\n| C4q rq D4q E4q |'));++ it('maps each saved grade to the timeline note at the same ordinal (rests skipped)', () => {+ // Timeline notes are at global indices 0, 2, 3 (index 1 is the rest).+ const map = gradesFromPerNote(tl, [GRADE.IN_TUNE, GRADE.CLOSE, GRADE.OFF]);+ expect(map).toEqual({ 0: GRADE.IN_TUNE, 2: GRADE.CLOSE, 3: GRADE.OFF });+ });++ it('round-trips with summarizeAccuracy.perNote', () => {+ const graded = { 0: GRADE.IN_TUNE, 2: GRADE.MISSED, 3: GRADE.OFF };+ const { perNote } = summarizeAccuracy(graded);+ expect(gradesFromPerNote(tl, perNote)).toEqual(graded);+ });++ it('tolerates a perNote shorter or longer than the timeline', () => {+ expect(gradesFromPerNote(tl, [GRADE.IN_TUNE])).toEqual({ 0: GRADE.IN_TUNE });+ // Extra grades past the last timeline note are ignored (no index to bind to).+ const over = gradesFromPerNote(tl, [GRADE.IN_TUNE, GRADE.OFF, GRADE.OFF, GRADE.CLOSE, GRADE.OFF]);+ expect(over).toEqual({ 0: GRADE.IN_TUNE, 2: GRADE.OFF, 3: GRADE.OFF });+ });++ it('returns an empty map for an empty perNote', () => {+ expect(gradesFromPerNote(tl, [])).toEqual({});+ expect(gradesFromPerNote(tl)).toEqual({});+ });});