Skip to content

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

fix([issue-1092]): only arm take grading when a run actually starts

Adam Eivy3d453a7cdea2
diff --git a/client/src/components/songs/SongRecordings.jsx b/client/src/components/songs/SongRecordings.jsx
index b5da8cc187..f8db008d36 100644
--- a/client/src/components/songs/SongRecordings.jsx
+++ b/client/src/components/songs/SongRecordings.jsx
@@ -73,8 +73,12 @@ export default function SongRecordings({ recordings = [], layers = [], onChange,
// 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.
+ // We mark this take "armed" ONLY when startMatch() reports it actually began a
+ // run — a rest-only score makes hasMusic true but the hook bails (zero gradable
+ // notes) without resetting its accumulators, so a falsely-armed take would
+ // harvest the previous take's stale analysis.
useEffect(() => {
- if (liveStream && hasMusic && !matchRunning) { armedThisTakeRef.current = true; startMatch(); }
+ if (liveStream && hasMusic && !matchRunning && startMatch()) armedThisTakeRef.current = true;
// start is stable; react only to stream/hasMusic (the arm trigger).
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [liveStream, hasMusic]);
diff --git a/client/src/components/songs/SongRecordings.test.jsx b/client/src/components/songs/SongRecordings.test.jsx
index 971065929a..7bc0f83aba 100644
--- a/client/src/components/songs/SongRecordings.test.jsx
+++ b/client/src/components/songs/SongRecordings.test.jsx
@@ -11,7 +11,11 @@ import { render, screen, fireEvent, waitFor } from '@testing-library/react';
// wiring: stop() is harvested before the stream drops, and its analysis lands
// on the new recording entry.
-const matchStart = vi.fn();
+// startMatch returns true when a grading run actually armed (mirrors the real
+// hook: false on no-stream / rest-only / already-running). The owner gates
+// "armed for this take" on that, so the default success case returns true.
+let matchStartResult = true;
+const matchStart = vi.fn(() => matchStartResult);
let matchStopResult = null;
const matchStop = vi.fn(() => matchStopResult);
let hookState = { running: false, countingIn: false, noteColors: {}, summary: null, activeIndex: null };
@@ -59,6 +63,7 @@ describe('SongRecordings — pitch analysis wiring (#1092)', () => {
matchStop.mockClear();
handleStop.mockClear();
uploadFile.mockClear();
+ matchStartResult = true;
matchStopResult = null;
hookState = { running: false, countingIn: false, noteColors: {}, summary: null, activeIndex: null };
});
@@ -131,6 +136,33 @@ describe('SongRecordings — pitch analysis wiring (#1092)', () => {
rerender(<SongRecordings recordings={next} score="" tempo={120} onChange={onChange} />);
});
+ it('does not arm (or harvest) when the score has notation but no gradable notes', async () => {
+ // Regression (codex iteration 2): a rest-only score makes scoreHasMusic()
+ // true, so the auto-arm effect runs — but the hook's start() bails (zero
+ // gradable notes) WITHOUT resetting its accumulators. The owner must trust
+ // startMatch()'s return value: a false arm means no harvest, so a rest-only
+ // take can't inherit the prior take's analysis.
+ matchStartResult = false; // hook reports it didn't actually start a run
+ matchStopResult = {
+ summary: { graded: 4, counts: { 'in-tune': 4, close: 0, off: 0, missed: 0 }, percentInTune: 100, perNote: ['in-tune', 'in-tune', 'in-tune', 'in-tune'] },
+ pitchTrack: [{ tMs: 0, hz: 261.6, cents: 0, clarity: 0.99 }],
+ };
+ const onChange = vi.fn();
+ // A score with a measure (scoreHasMusic true) but only a rest.
+ const restOnly = ['time: 4/4', 'tempo: 120', '| rw |'].join('\n');
+ render(<SongRecordings recordings={[]} score={restOnly} 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());
+ expect(matchStop).not.toHaveBeenCalled(); // unarmed → no harvest attempt
+ 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,
diff --git a/client/src/hooks/useColorMatch.js b/client/src/hooks/useColorMatch.js
index 78733ca7a1..20886fe9dd 100644
--- a/client/src/hooks/useColorMatch.js
+++ b/client/src/hooks/useColorMatch.js
@@ -176,11 +176,15 @@ export default function useColorMatch({ score, stream, bpm = null, countInBars =
rafRef.current = requestAnimationFrame(grade);
}, [stop]);
- // Start a session: requires a live mic stream and a score with notes.
+ // Start a session: requires a live mic stream and a score with at least one
+ // gradable (non-rest) note. Returns true when a run actually armed (the
+ // accumulators were reset and grading began), false when it bailed early —
+ // callers gate "this take is being graded" on that so a rest-only / no-stream
+ // score can't leave a take falsely armed (which would harvest stale analysis).
const start = useCallback(() => {
- if (!stream || running) return;
+ if (!stream || running) return false;
const timeline = buildColorMatchTimeline(score, { bpm, a4 });
- if (!timeline.notes.length) return;
+ if (!timeline.notes.length) return false;
teardown();
gradesRef.current = {};
@@ -230,6 +234,7 @@ export default function useColorMatch({ score, stream, bpm = null, countInBars =
});
metronomeRef.current = metro;
Promise.resolve(metro.start()).catch(() => { if (mountedRef.current) stop(); });
+ return true;
}, [stream, running, score, bpm, a4, countInBars, teardown, grade, stop, mountedRef]);
// A vanished stream (recording stopped) or score change ends an active session.
diff --git a/client/src/hooks/useColorMatch.test.jsx b/client/src/hooks/useColorMatch.test.jsx
new file mode 100644
index 0000000000..4a8368221c
--- /dev/null
+++ b/client/src/hooks/useColorMatch.test.jsx
@@ -0,0 +1,102 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { renderHook, act } from '@testing-library/react';
+import { parseScore } from '../lib/scoreNotation.js';
+
+// useColorMatch owns the metronome + pitch tracker + rAF grading loop, none of
+// which exist in jsdom. We mock the three Web-Audio seams and assert the parts
+// that #1092 made load-bearing: start()'s boolean "did a run actually arm?"
+// contract (the owner gates take-harvest on it) and stop()'s analysis return.
+const trackerStop = vi.fn();
+const analyserClose = vi.fn();
+const metronomeStop = vi.fn();
+let lastMetronome = null;
+
+vi.mock('../lib/audioRecorder.js', () => ({
+ createStreamAnalyser: vi.fn(() => ({ analyser: { fftSize: 2048 }, context: { currentTime: 0, sampleRate: 44100 }, close: analyserClose })),
+}));
+vi.mock('../lib/pitchDetect.js', async (importActual) => {
+ const actual = await importActual();
+ return { ...actual, createPitchTracker: vi.fn(() => ({ stop: trackerStop })) };
+});
+vi.mock('../lib/metronome.js', async (importActual) => {
+ const actual = await importActual();
+ return {
+ ...actual,
+ createMetronome: vi.fn((opts) => {
+ lastMetronome = opts;
+ // Resolve start() but never fire onCountInComplete — we only exercise the
+ // arm/stop bookkeeping, not the rAF grading loop.
+ return { start: vi.fn(() => Promise.resolve()), stop: metronomeStop };
+ }),
+ };
+});
+
+import useColorMatch from './useColorMatch.js';
+
+const stream = () => ({ getTracks: () => [{ stop: vi.fn() }] });
+const FOUR = parseScore(['time: 4/4', 'tempo: 120', '| C4q D4q E4q F4q |'].join('\n'));
+const REST_ONLY = parseScore(['time: 4/4', 'tempo: 120', '| rw |'].join('\n'));
+
+describe('useColorMatch — start()/stop() contract (#1092)', () => {
+ beforeEach(() => {
+ trackerStop.mockClear();
+ analyserClose.mockClear();
+ metronomeStop.mockClear();
+ lastMetronome = null;
+ });
+
+ it('start() returns false with no stream', () => {
+ const { result } = renderHook(() => useColorMatch({ score: FOUR, stream: null, bpm: 120 }));
+ let armed;
+ act(() => { armed = result.current.start(); });
+ expect(armed).toBe(false);
+ expect(result.current.running).toBe(false);
+ });
+
+ it('start() returns false for a rest-only score (no gradable notes)', () => {
+ const { result } = renderHook(() => useColorMatch({ score: REST_ONLY, stream: stream(), bpm: 120 }));
+ let armed;
+ act(() => { armed = result.current.start(); });
+ expect(armed).toBe(false);
+ expect(result.current.running).toBe(false);
+ });
+
+ it('start() returns true and begins a run for a gradable score', () => {
+ const { result } = renderHook(() => useColorMatch({ score: FOUR, stream: stream(), bpm: 120 }));
+ let armed;
+ act(() => { armed = result.current.start(); });
+ expect(armed).toBe(true);
+ expect(result.current.running).toBe(true);
+ });
+
+ it('start() returns false when already running (no double-arm)', () => {
+ const { result } = renderHook(() => useColorMatch({ score: FOUR, stream: stream(), bpm: 120 }));
+ act(() => { result.current.start(); });
+ let again;
+ act(() => { again = result.current.start(); });
+ expect(again).toBe(false);
+ });
+
+ it('stop() returns { summary, pitchTrack } after a run and clears running', () => {
+ const { result } = renderHook(() => useColorMatch({ score: FOUR, stream: stream(), bpm: 120 }));
+ act(() => { result.current.start(); });
+ let analysis;
+ act(() => { analysis = result.current.stop(); });
+ expect(analysis).toMatchObject({
+ summary: expect.objectContaining({ graded: expect.any(Number), perNote: expect.any(Array) }),
+ pitchTrack: expect.any(Array),
+ });
+ expect(result.current.running).toBe(false);
+ // No grading frames ran (onCountInComplete never fired), so nothing graded.
+ expect(analysis.summary.graded).toBe(0);
+ expect(analysis.pitchTrack).toEqual([]);
+ });
+
+ it('stop() returns null after unmount (no state write into the void)', () => {
+ const { result, unmount } = renderHook(() => useColorMatch({ score: FOUR, stream: stream(), bpm: 120 }));
+ act(() => { result.current.start(); });
+ const { stop } = result.current;
+ unmount();
+ expect(stop()).toBeNull();
+ });
+});