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-1023]): live vocal pitch tuner overlay while recording
Adam Eivyb1e732357ca7
diff --git a/client/src/components/songs/PitchTuner.jsx b/client/src/components/songs/PitchTuner.jsxnew file mode 100644index 0000000000..d1c035c784--- /dev/null+++ b/client/src/components/songs/PitchTuner.jsx@@ -0,0 +1,208 @@+/**+ * PitchTuner — live vocal tuner that shows the note you're singing and how+ * flat/sharp it is, in real time.+ *+ * Two modes, one component:+ * - **Attached** — when a live recording `stream` is passed in, the tuner taps+ * an AnalyserNode off that SAME mic stream (via `createStreamAnalyser`) so it+ * never opens a second getUserMedia (which would re-prompt / fight the+ * recorder). It mounts read-only inside the record panel and follows the take.+ * - **Standalone** — with no `stream`, it offers a "Tune" toggle that opens its+ * own mic just for tuning; nothing is recorded or saved. "Stop" closes it.+ *+ * The needle/note are colored by `tuningQuality` (green in-tune, yellow close,+ * red off) using `--port-*` tokens only. The AnalyserNode + the pitch tracker's+ * rAF loop are torn down on stop, on stream-change, and on unmount (the+ * deferred-work teardown rule in CLAUDE.md) so no audio graph or loop dangles.+ */++import { useCallback, useEffect, useRef, useState } from 'react';+import { Music2, Square } from 'lucide-react';+import toast from '../ui/Toast';+import { createStreamAnalyser } from '../../lib/audioRecorder.js';+import { createPitchTracker, tuningQuality } from '../../lib/pitchDetect.js';++// Map a tuning-quality level to its readout color token + needle fill.+const LEVEL_TONE = {+ 'in-tune': 'text-port-success',+ close: 'text-port-warning',+ off: 'text-port-error',+ none: 'text-gray-500',+};+const LEVEL_BAR = {+ 'in-tune': 'bg-port-success',+ close: 'bg-port-warning',+ off: 'bg-port-error',+ none: 'bg-port-border',+};++// Cents range the needle spans (a semitone is ±50¢; clamp so a wild glitch+// can't push the needle off the bar).+const CENTS_SPAN = 50;++// Format a detected note as "C♯4" using the same sharp/flat glyphs the score+// renderer uses, falling back to a dash while no pitch is detected.+const noteLabel = (note) => {+ if (!note) return '—';+ const glyph = note.accidental === '#' ? '♯'+ : note.accidental === 'b' ? '♭'+ : note.accidental || '';+ return `${note.letter}${glyph}${note.octave}`;+};++export default function PitchTuner({ stream = null, a4 = 440 }) {+ // `reading` is the latest tracker frame: { note, cents } (nulls when no pitch).+ const [reading, setReading] = useState({ note: null, cents: null });+ const [standaloneOn, setStandaloneOn] = useState(false);+ const trackerRef = useRef(null); // active pitch tracker { stop }+ const analyserRef = useRef(null); // active { close } stream-analyser graph+ const ownStreamRef = useRef(null); // standalone-mode mic stream we own + must stop+ const mountedRef = useRef(true);++ useEffect(() => {+ mountedRef.current = true;+ return () => { mountedRef.current = false; };+ }, []);++ // Tear down the tracker loop + analyser graph (but not the stream — see attach).+ const teardownTracker = useCallback(() => {+ if (trackerRef.current) { trackerRef.current.stop(); trackerRef.current = null; }+ if (analyserRef.current) { analyserRef.current.close(); analyserRef.current = null; }+ setReading({ note: null, cents: null });+ }, []);++ // Attach the tuner to a stream. Returns nothing; teardownTracker() detaches.+ const attach = useCallback((src) => {+ teardownTracker();+ if (!src) return;+ const graph = createStreamAnalyser(src);+ analyserRef.current = graph;+ trackerRef.current = createPitchTracker(graph.analyser, {+ a4,+ onUpdate: (u) => {+ if (!mountedRef.current) return; // navigation-away guard+ setReading({ note: u.note, cents: u.cents });+ },+ });+ }, [a4, teardownTracker]);++ // Recording stream changed (started/stopped): follow it in attached mode.+ // When it goes null we also drop any standalone session — the record panel+ // owns the tuner while a take is live.+ useEffect(() => {+ if (stream) {+ // A recording take takes over — drop any standalone mic we'd opened so it+ // doesn't leak, then follow the recording stream.+ setStandaloneOn(false);+ if (ownStreamRef.current) {+ ownStreamRef.current.getTracks().forEach((t) => t.stop());+ ownStreamRef.current = null;+ }+ attach(stream);+ } else if (!standaloneOn) {+ teardownTracker();+ }+ return () => { if (stream) teardownTracker(); };+ // standaloneOn intentionally omitted: toggling it is handled in its own paths.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [stream, attach, teardownTracker]);++ // Stop standalone tuning: tear down the tracker AND close the mic we opened.+ const stopStandalone = useCallback(() => {+ teardownTracker();+ if (ownStreamRef.current) {+ ownStreamRef.current.getTracks().forEach((t) => t.stop());+ ownStreamRef.current = null;+ }+ setStandaloneOn(false);+ }, [teardownTracker]);++ // Tear everything down on unmount.+ useEffect(() => () => {+ if (trackerRef.current) trackerRef.current.stop();+ if (analyserRef.current) analyserRef.current.close();+ if (ownStreamRef.current) ownStreamRef.current.getTracks().forEach((t) => t.stop());+ }, []);++ const startStandalone = useCallback(async () => {+ const src = await navigator.mediaDevices.getUserMedia({ audio: true }).catch((err) => {+ toast.error(err?.message || 'Microphone access denied');+ return null;+ });+ if (!src) return;+ if (!mountedRef.current) { src.getTracks().forEach((t) => t.stop()); return; }+ ownStreamRef.current = src;+ setStandaloneOn(true);+ attach(src);+ }, [attach]);++ const active = Boolean(stream) || standaloneOn;+ const quality = tuningQuality(reading.cents);+ // Needle position 0–100% across the bar; 50% is dead-center (in tune).+ const clamped = Number.isFinite(reading.cents)+ ? Math.max(-CENTS_SPAN, Math.min(CENTS_SPAN, reading.cents))+ : 0;+ const needlePct = 50 + (clamped / CENTS_SPAN) * 50;++ return (+ <div className="bg-port-card border border-port-border rounded-lg p-3">+ <div className="flex items-center justify-between gap-2 flex-wrap">+ <h3 className="flex items-center gap-2 text-sm font-semibold text-white">+ <Music2 size={15} className="text-port-accent" /> Tuner+ {stream && <span className="text-xs font-normal text-port-error">● live</span>}+ </h3>+ {/* Standalone toggle — only when NOT attached to a recording stream. */}+ {!stream && (+ standaloneOn ? (+ <button+ type="button"+ onClick={stopStandalone}+ className="flex items-center gap-1.5 px-3 py-1.5 text-xs rounded-lg bg-port-error text-white hover:bg-port-error/90"+ >+ <Square size={14} /> Stop+ </button>+ ) : (+ <button+ type="button"+ onClick={startStandalone}+ className="flex items-center gap-1.5 px-3 py-1.5 text-xs rounded-lg bg-port-accent text-white hover:bg-port-accent/90"+ title="Open the mic to tune — nothing is recorded"+ >+ <Music2 size={14} /> Tune+ </button>+ )+ )}+ </div>++ {/* Note + cents readout */}+ <div className="flex items-end justify-center gap-3 mt-3" aria-live="polite">+ <span className={`text-4xl font-bold tabular-nums leading-none ${LEVEL_TONE[quality.level]}`}>+ {noteLabel(reading.note)}+ </span>+ <span className={`text-sm pb-1 ${LEVEL_TONE[quality.level]}`}>+ {Number.isFinite(reading.cents) && reading.note+ ? `${reading.cents > 0 ? '+' : ''}${reading.cents}¢ · ${quality.label}`+ : active ? 'Listening…' : 'Idle'}+ </span>+ </div>++ {/* Cents needle: a center-anchored bar; the needle slides flat←→sharp. */}+ <div className="relative h-6 mt-3" aria-hidden="true">+ {/* track */}+ <div className="absolute inset-x-0 top-1/2 -translate-y-1/2 h-1 bg-port-border rounded-full" />+ {/* center (in-tune) mark */}+ <div className="absolute left-1/2 top-0 bottom-0 w-px bg-gray-500" />+ {/* needle */}+ <div+ className={`absolute top-1/2 -translate-y-1/2 -translate-x-1/2 w-1.5 h-5 rounded-full transition-all duration-75 ${LEVEL_BAR[quality.level]}`}+ style={{ left: `${needlePct}%`, opacity: reading.note ? 1 : 0.3 }}+ />+ </div>+ <div className="flex justify-between text-[10px] text-gray-600 mt-1" aria-hidden="true">+ <span>♭ flat</span>+ <span>in tune</span>+ <span>sharp ♯</span>+ </div>+ </div>+ );+}diff --git a/client/src/components/songs/PitchTuner.test.jsx b/client/src/components/songs/PitchTuner.test.jsxnew file mode 100644index 0000000000..8d35381117--- /dev/null+++ b/client/src/components/songs/PitchTuner.test.jsx@@ -0,0 +1,91 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { render, screen, fireEvent, waitFor } from '@testing-library/react';++// Web Audio doesn't exist in jsdom, so mock the two lib seams the tuner uses:+// `createStreamAnalyser` (graph off a stream) and `createPitchTracker` (the rAF+// loop). We assert the component attaches and tears both down correctly without+// needing a real AudioContext.+const analyserClose = vi.fn();+const trackerStop = vi.fn();+let lastOnUpdate = null;++vi.mock('../../lib/audioRecorder.js', () => ({+ createStreamAnalyser: vi.fn(() => ({ analyser: { id: 'analyser' }, context: {}, close: analyserClose })),+}));++vi.mock('../../lib/pitchDetect.js', async (importActual) => {+ const actual = await importActual(); // keep the real tuningQuality+ return {+ ...actual,+ createPitchTracker: vi.fn((analyser, opts) => {+ lastOnUpdate = opts.onUpdate;+ return { stop: trackerStop };+ }),+ };+});++import PitchTuner from './PitchTuner.jsx';+import { createStreamAnalyser } from '../../lib/audioRecorder.js';+import { createPitchTracker } from '../../lib/pitchDetect.js';++const fakeStream = () => ({ getTracks: () => [{ stop: vi.fn() }] });++describe('PitchTuner', () => {+ beforeEach(() => {+ analyserClose.mockClear();+ trackerStop.mockClear();+ createStreamAnalyser.mockClear();+ createPitchTracker.mockClear();+ lastOnUpdate = null;+ });++ it('attaches to a provided recording stream (no second getUserMedia)', () => {+ const stream = fakeStream();+ render(<PitchTuner stream={stream} />);+ expect(createStreamAnalyser).toHaveBeenCalledWith(stream);+ expect(createPitchTracker).toHaveBeenCalledTimes(1);+ // Attached mode shows the live badge and hides the standalone Tune button.+ expect(screen.getByText(/live/)).toBeTruthy();+ expect(screen.queryByText('Tune')).toBeNull();+ });++ it('renders the detected note + cents from a tracker update', async () => {+ render(<PitchTuner stream={fakeStream()} />);+ lastOnUpdate({ note: { letter: 'A', accidental: '', octave: 4 }, cents: 3 });+ await waitFor(() => expect(screen.getByText('A4')).toBeTruthy());+ expect(screen.getByText(/\+3¢ · In tune/)).toBeTruthy();+ });++ it('tears down tracker + analyser when the stream goes away', () => {+ const { rerender } = render(<PitchTuner stream={fakeStream()} />);+ expect(trackerStop).not.toHaveBeenCalled();+ rerender(<PitchTuner stream={null} />);+ expect(trackerStop).toHaveBeenCalled();+ expect(analyserClose).toHaveBeenCalled();+ });++ it('tears down on unmount', () => {+ const { unmount } = render(<PitchTuner stream={fakeStream()} />);+ unmount();+ expect(trackerStop).toHaveBeenCalled();+ expect(analyserClose).toHaveBeenCalled();+ });++ it('standalone mode opens its own mic on Tune and closes it on Stop', async () => {+ const ownTracks = [{ stop: vi.fn() }];+ const getUserMedia = vi.fn(() => Promise.resolve({ getTracks: () => ownTracks }));+ global.navigator.mediaDevices = { getUserMedia };++ render(<PitchTuner />); // no stream → standalone+ expect(screen.getByText('Tune')).toBeTruthy();++ fireEvent.click(screen.getByText('Tune'));+ await waitFor(() => expect(createPitchTracker).toHaveBeenCalled());+ expect(getUserMedia).toHaveBeenCalledWith({ audio: true });++ fireEvent.click(screen.getByText('Stop'));+ expect(trackerStop).toHaveBeenCalled();+ expect(analyserClose).toHaveBeenCalled();+ expect(ownTracks[0].stop).toHaveBeenCalled(); // the mic we opened is released+ });+});diff --git a/client/src/components/songs/SongRecordings.jsx b/client/src/components/songs/SongRecordings.jsxindex 1ee65170a5..b523a3fcdf 100644--- a/client/src/components/songs/SongRecordings.jsx+++ b/client/src/components/songs/SongRecordings.jsx@@ -21,6 +21,7 @@ import { createLayeredPlayer } from '../../lib/songPlayback';import { uploadFile, getUploadUrl } from '../../services/api';import { formatDurationMs } from '../../utils/formatters';import Metronome from './Metronome';+import PitchTuner from './PitchTuner';// Lower bound peak amplitude — below this the take is effectively silence// (dead mic / muted input), worth warning about before it joins the stack.@@ -38,6 +39,9 @@ export default function SongRecordings({ recordings = [], layers = [], onChange,const [saving, setSaving] = useState(false);const [playing, setPlaying] = useState(false);const [targetLayerId, setTargetLayerId] = useState('');+ // Live mic stream while recording — passed to the tuner so it taps the SAME+ // mic (no second getUserMedia). Null whenever a take isn't in flight.+ const [liveStream, setLiveStream] = useState(null);const handleRef = useRef(null); // active MediaRecorder handleconst playerRef = useRef(null); // active layered player@@ -61,6 +65,7 @@ export default function SongRecordings({ recordings = [], layers = [], onChange,});if (!handle) return;handleRef.current = handle;+ setLiveStream(handle.stream || null); // feed the tuner the recording micsetRecording(true);}, []);@@ -68,6 +73,7 @@ export default function SongRecordings({ recordings = [], layers = [], onChange,const handle = handleRef.current;if (!handle) return;handleRef.current = null;+ setLiveStream(null); // stream is being torn down with the takesetRecording(false);setSaving(true);const take = await handle.stop().catch((err) => {@@ -177,8 +183,11 @@ export default function SongRecordings({ recordings = [], layers = [], onChange,</p>{/* Tempo reference + count-in — the shared timing grid for recording. */}- <div className="mb-3">+ <div className="mb-3 grid grid-cols-1 lg:grid-cols-2 gap-3"><Metronome tempo={tempo} score={score} />+ {/* Live tuner — taps the recording mic while a take is live, else offers+ a standalone "just tune" mode that opens its own mic. */}+ <PitchTuner stream={liveStream} /></div>{/* Layer the next take targets (optional) */}diff --git a/client/src/lib/README.md b/client/src/lib/README.mdindex c310153dea..58a6d8dabe 100644--- a/client/src/lib/README.md+++ b/client/src/lib/README.md@@ -62,7 +62,7 @@ grep -i "what you want to do" client/src/lib/README.md| Module | Purpose ||---|---|| `applyManuscriptEdits.js` | `applyEditsToContent(content, edits, anchorQuote)` — PREVIEW-ONLY client mirror of the server's accept splice (`server/services/pipeline/manuscriptFix.js`): locate each `find` (nearest the anchor when recurring), drop overlaps, replace bottom-up. Powers the Manuscript editor's whole-manuscript impact preview. |-| `audioRecorder.js` | `startMemoRecording()` → `{ stop, cancel }` handle whose `stop()` resolves to `{ audioBase64, mimeType, peak, durationMs }` (16 kHz mono WAV, base64). Plus `blobToWav16k`, `encodePcmToWav`, `pickRecordingMimeType`, `arrayBufferToBase64`. Standalone one-shot memo capture for catalog voice ingest — NOT the live voice-agent recorder in `services/voiceClient.js`. |+| `audioRecorder.js` | `startMemoRecording()` → `{ stream, stop, cancel }` handle whose `stop()` resolves to `{ audioBase64, mimeType, peak, durationMs }` (16 kHz mono WAV, base64); the live `stream` lets a tuner tap the same mic. `createStreamAnalyser(stream, { fftSize })` → `{ analyser, context, close }` taps an `AnalyserNode` off an existing stream (no second getUserMedia). Plus `blobToWav16k`, `encodePcmToWav`, `pickRecordingMimeType`, `arrayBufferToBase64`. Standalone one-shot memo capture for catalog voice ingest — NOT the live voice-agent recorder in `services/voiceClient.js`. || `clientErrorReporter.js` | `reportClientError({ type, error?, message?, ... })` — POSTs window.onerror + unhandledrejection events to `/api/client-errors` with throttle + dedup. Wired from `main.jsx`; never call directly from React components. || `clinicianReport.js` | Pure builders for the MeatSpace clinician-export view (`/meatspace/export`). `buildClinicianReport({ tests, config })` → structured report model (blood panels grouped by category with reference ranges + out-of-range flags, plus a lifestyle summary); `reportToMarkdown(report)` → copy-paste markdown. Reuses the Blood tab's `REFERENCE_RANGES` / `getBloodValueStatus` so printed flags match the UI. Also exports `buildBloodTestModel`, `buildLifestyleModel`, `getCategoryForKey`, `formatRange`. || `clipboard.js` | `copyToClipboard`, `writeClipboardSilently`, `readClipboard` — safe across insecure-origin contexts. Use these instead of `navigator.clipboard.writeText` inline. |@@ -87,7 +87,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. |-| `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. |+| `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). || `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`. || `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/audioRecorder.js b/client/src/lib/audioRecorder.jsindex ed5f5cae8e..0225537c2c 100644--- a/client/src/lib/audioRecorder.js+++ b/client/src/lib/audioRecorder.js@@ -84,11 +84,38 @@ export function arrayBufferToBase64(buffer) {return btoa(binary);}+/**+ * Tap a live `AnalyserNode` off an existing `MediaStream` — for the live tuner,+ * which must read the SAME mic the recorder already opened rather than calling+ * getUserMedia a second time (a second stream prompts again / fights the first).+ * Returns `{ analyser, context, close }`; `close()` tears down the analyser graph+ * and AudioContext but leaves the stream alone (the recorder owns the stream's+ * lifetime). Caller MUST call `close()` on stop/unmount (deferred-work cleanup).+ */+export function createStreamAnalyser(stream, { fftSize = 2048 } = {}) {+ const context = new (window.AudioContext || window.webkitAudioContext)();+ const source = context.createMediaStreamSource(stream);+ const analyser = context.createAnalyser();+ analyser.fftSize = fftSize;+ source.connect(analyser); // no connection to destination — we only read frames+ return {+ analyser,+ context,+ close: () => {+ source.disconnect();+ analyser.disconnect();+ context.close().catch(() => {});+ },+ };+}+/*** Start recording from the default microphone. Returns a handle whose* `stop()` resolves to `{ audioBase64, peak, mimeType, durationMs }` — a- * 16 kHz mono WAV base64 string ready to POST. The caller is responsible for- * calling `stop()` (or `cancel()` to discard). Throws if mic access is denied.+ * 16 kHz mono WAV base64 string ready to POST. The handle also exposes the live+ * `stream` so an analyser (live tuner) can tap the same mic without opening a+ * second one. The caller is responsible for calling `stop()` (or `cancel()` to+ * discard). Throws if mic access is denied.*/export async function startMemoRecording() {const stream = await navigator.mediaDevices.getUserMedia({ audio: true });@@ -102,6 +129,7 @@ export async function startMemoRecording() {const teardown = () => stream.getTracks().forEach((t) => t.stop());return {+ stream,stop: () => new Promise((resolve, reject) => {recorder.onstop = async () => {teardown();diff --git a/client/src/lib/pitchDetect.js b/client/src/lib/pitchDetect.jsindex 3504fd517b..b925e96978 100644--- a/client/src/lib/pitchDetect.js+++ b/client/src/lib/pitchDetect.js@@ -77,6 +77,28 @@ export const noteToFrequency = (note, { a4 = 440 } = {}) => {return a4 * Math.pow(2, (midi - 69) / 12);};+// === Tuning quality (cents → bucket) ===================================++// Cents-deviation thresholds the tuner UI colors by. Within ±IN_TUNE_CENTS the+// note is "in tune" (green); within ±CLOSE_CENTS it's "close" (yellow);+// anything wider is "off" (red). Exported so the thresholds are a single shared+// constant the UI and its tests agree on, not magic numbers in a component.+export const IN_TUNE_CENTS = 5;+export const CLOSE_CENTS = 20;++// Classify a cents deviation into a tuning-quality bucket for the tuner readout.+// Pure + side-effect-free (no colors here — the component maps `level` to a+// `--port-*` token) so the thresholds are unit-testable. `label` carries the+// sharp/flat direction so the UI doesn't re-derive the sign. A non-finite cents+// (no pitch detected) returns the neutral `none` bucket.+export const tuningQuality = (cents) => {+ if (!Number.isFinite(cents)) return { level: 'none', label: '—' };+ const abs = Math.abs(cents);+ if (abs <= IN_TUNE_CENTS) return { level: 'in-tune', label: 'In tune' };+ if (abs <= CLOSE_CENTS) return { level: 'close', label: cents > 0 ? 'A little sharp' : 'A little flat' };+ return { level: 'off', label: cents > 0 ? 'Sharp' : 'Flat' };+};+// === Fundamental-frequency estimation ==================================// Estimate the fundamental frequency of a Float32 PCM frame via the McLeoddiff --git a/client/src/lib/pitchDetect.test.js b/client/src/lib/pitchDetect.test.jsindex b44f8937bd..93489d5ba4 100644--- a/client/src/lib/pitchDetect.test.js+++ b/client/src/lib/pitchDetect.test.js@@ -4,6 +4,9 @@ import {frequencyToNote,noteToFrequency,createPitchTracker,+ tuningQuality,+ IN_TUNE_CENTS,+ CLOSE_CENTS,} from './pitchDetect.js';const SAMPLE_RATE = 44100;@@ -97,6 +100,34 @@ describe('noteToFrequency', () => {});});+describe('tuningQuality', () => {+ it('returns the neutral bucket for a non-finite cents (no pitch)', () => {+ expect(tuningQuality(null)).toEqual({ level: 'none', label: '—' });+ expect(tuningQuality(NaN)).toEqual({ level: 'none', label: '—' });+ expect(tuningQuality(undefined)).toEqual({ level: 'none', label: '—' });+ });++ it('buckets dead-center and within the in-tune band as in-tune', () => {+ expect(tuningQuality(0).level).toBe('in-tune');+ expect(tuningQuality(IN_TUNE_CENTS).level).toBe('in-tune');+ expect(tuningQuality(-IN_TUNE_CENTS).level).toBe('in-tune');+ });++ it('buckets just past the in-tune band as close, with a direction label', () => {+ expect(tuningQuality(IN_TUNE_CENTS + 1).level).toBe('close');+ expect(tuningQuality(IN_TUNE_CENTS + 1).label).toMatch(/sharp/i);+ expect(tuningQuality(-(IN_TUNE_CENTS + 1)).label).toMatch(/flat/i);+ expect(tuningQuality(CLOSE_CENTS).level).toBe('close');+ });++ it('buckets beyond the close band as off, with a direction label', () => {+ expect(tuningQuality(CLOSE_CENTS + 1).level).toBe('off');+ expect(tuningQuality(CLOSE_CENTS + 1).label).toBe('Sharp');+ expect(tuningQuality(-(CLOSE_CENTS + 1)).level).toBe('off');+ expect(tuningQuality(-(CLOSE_CENTS + 1)).label).toBe('Flat');+ });+});+describe('detectFrequency', () => {it('recovers the fundamental of a pure sine across the vocal range', () => {for (const hz of [130.81, 261.63, 440, 587.33, 880]) {