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: open pitch-analysis mics with browser audio processing off (#5303)

[._.]/ Adam Eivy31aa2dceaf5d
diff --git a/client/src/components/songs/MicProcessingHint.jsx b/client/src/components/songs/MicProcessingHint.jsx
new file mode 100644
index 0000000000..829a4f828a
--- /dev/null
+++ b/client/src/components/songs/MicProcessingHint.jsx
@@ -0,0 +1,27 @@
+/**
+ * MicProcessingHint — one-line warning shown when the browser kept its speech
+ * processing chain on despite a pitch-analysis mic asking for it off (Safari
+ * and Firefox both do, for some stages). Renders nothing when every stage was
+ * honored, and nothing when the browser doesn't report what it applied — an
+ * unknown stage is not evidence of a problem.
+ */
+
+import { AlertTriangle } from 'lucide-react';
+import { hasUnwantedProcessing } from '../../lib/audioRecorder.js';
+
+const LABELS = {
+ echoCancellation: 'echo cancellation',
+ noiseSuppression: 'noise suppression',
+ autoGainControl: 'automatic gain control',
+};
+
+export default function MicProcessingHint({ processing = null }) {
+ if (!hasUnwantedProcessing(processing)) return null;
+ const on = Object.keys(LABELS).filter((key) => processing[key] === true).map((key) => LABELS[key]);
+ return (
+ <p className="flex items-start gap-1.5 mt-2 text-xs text-port-warning">
+ <AlertTriangle size={13} className="shrink-0 mt-0.5" />
+ <span>Browser audio processing is on ({on.join(', ')}) — pitch readings may drift.</span>
+ </p>
+ );
+}
diff --git a/client/src/components/songs/PitchTuner.jsx b/client/src/components/songs/PitchTuner.jsx
index 598ba0cfb7..9de71de7b5 100644
--- a/client/src/components/songs/PitchTuner.jsx
+++ b/client/src/components/songs/PitchTuner.jsx
@@ -19,9 +19,10 @@
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 { createStreamAnalyser, openAnalysisMic, readAppliedProcessing } from '../../lib/audioRecorder.js';
import { createPitchTracker, tuningQuality } from '../../lib/pitchDetect.js';
import useMounted from '../../hooks/useMounted';
+import MicProcessingHint from './MicProcessingHint.jsx';
// Map a tuning-quality level to its readout color token + needle fill.
const LEVEL_TONE = {
@@ -58,6 +59,10 @@ export default function PitchTuner({ stream = null, a4 = 440 }) {
// "still that note" rather than a fresh detection.
const [reading, setReading] = useState({ note: null, cents: null, held: false });
const [standaloneOn, setStandaloneOn] = useState(false);
+ // What the browser ACTUALLY applied to whichever mic we are reading — the own
+ // standalone stream, or the recorder's (which is opened speech-tuned on
+ // purpose, so an attached tuner honestly reports the drift).
+ const [micProcessing, setMicProcessing] = useState(null);
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
@@ -68,12 +73,14 @@ export default function PitchTuner({ stream = null, a4 = 440 }) {
if (trackerRef.current) { trackerRef.current.stop(); trackerRef.current = null; }
if (analyserRef.current) { analyserRef.current.close(); analyserRef.current = null; }
setReading({ note: null, cents: null, held: false });
+ setMicProcessing(null);
}, []);
// Attach the tuner to a stream. Returns nothing; teardownTracker() detaches.
const attach = useCallback((src) => {
teardownTracker();
if (!src) return;
+ setMicProcessing(readAppliedProcessing(src));
const graph = createStreamAnalyser(src);
analyserRef.current = graph;
trackerRef.current = createPitchTracker(graph.analyser, {
@@ -136,11 +143,12 @@ export default function PitchTuner({ stream = null, a4 = 440 }) {
// ownStreamRef, leaking the first). The button hides once standaloneOn flips,
// but a fast double event can re-enter before the re-render.
if (standaloneOn || trackerRef.current) return;
- const src = await navigator.mediaDevices.getUserMedia({ audio: true }).catch((err) => {
+ const opened = await openAnalysisMic().catch((err) => {
toast.error(err?.message || 'Microphone access denied');
return null;
});
- if (!src) return;
+ if (!opened) return;
+ const { stream: src } = opened;
if (!mountedRef.current) { src.getTracks().forEach((t) => t.stop()); return; }
ownStreamRef.current = src;
setStandaloneOn(true);
@@ -219,6 +227,7 @@ export default function PitchTuner({ stream = null, a4 = 440 }) {
<span>in tune</span>
<span>sharp ♯</span>
</div>
+ {active && <MicProcessingHint processing={micProcessing} />}
</div>
);
}
diff --git a/client/src/components/songs/PitchTuner.test.jsx b/client/src/components/songs/PitchTuner.test.jsx
index 80e615d338..030837392e 100644
--- a/client/src/components/songs/PitchTuner.test.jsx
+++ b/client/src/components/songs/PitchTuner.test.jsx
@@ -9,9 +9,13 @@ 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/audioRecorder.js', async (importActual) => {
+ const actual = await importActual(); // keep the real openAnalysisMic / getSettings read-back
+ return {
+ ...actual,
+ createStreamAnalyser: vi.fn(() => ({ analyser: { id: 'analyser' }, context: {}, close: analyserClose })),
+ };
+});
vi.mock('../../lib/pitchDetect.js', async (importActual) => {
const actual = await importActual(); // keep the real tuningQuality
@@ -98,11 +102,32 @@ describe('PitchTuner', () => {
fireEvent.click(screen.getByText('Tune'));
await waitFor(() => expect(createPitchTracker).toHaveBeenCalled());
- expect(getUserMedia).toHaveBeenCalledWith({ audio: true });
+ // Pitch analysis opens the mic with the browser processing chain requested
+ // off — AGC/NS/AEC all corrupt the signal the tracker reads.
+ expect(getUserMedia).toHaveBeenCalledWith({
+ audio: { echoCancellation: false, noiseSuppression: false, autoGainControl: false },
+ });
fireEvent.click(screen.getByText('Stop'));
expect(trackerStop).toHaveBeenCalled();
expect(analyserClose).toHaveBeenCalled();
expect(ownTracks[0].stop).toHaveBeenCalled(); // the mic we opened is released
});
+
+ it('warns when the browser kept its processing chain on, and stays quiet otherwise', async () => {
+ const withSettings = (settings) => ({
+ getTracks: () => [{ stop: vi.fn(), getSettings: () => settings }],
+ });
+
+ // Honored constraints (plus an unreported stage) → no warning.
+ const clean = render(<PitchTuner stream={withSettings({ echoCancellation: false, noiseSuppression: false })} />);
+ expect(screen.queryByText(/Browser audio processing is on/)).toBeNull();
+ clean.unmount();
+
+ // AGC survived the request → the readout says why the reading may drift.
+ render(<PitchTuner stream={withSettings({ autoGainControl: true, noiseSuppression: false })} />);
+ await waitFor(() => expect(
+ screen.getByText(/Browser audio processing is on \(automatic gain control\)/),
+ ).toBeTruthy());
+ });
});
diff --git a/client/src/components/songs/SingToVerify.jsx b/client/src/components/songs/SingToVerify.jsx
index 84db2306f8..713e837429 100644
--- a/client/src/components/songs/SingToVerify.jsx
+++ b/client/src/components/songs/SingToVerify.jsx
@@ -7,6 +7,7 @@ import useSingToVerify, {
} from '../../hooks/useSingToVerify.js';
import { GRADE } from '../../lib/colorMatch.js';
import { parseScore, replaceNotePitch } from '../../lib/scoreNotation.js';
+import MicProcessingHint from './MicProcessingHint.jsx';
import ScoreSheet from './ScoreSheet.jsx';
const pitchLabel = (pitch) =>
@@ -21,6 +22,7 @@ export default function SingToVerify({ value = '', tempo = null, onChange }) {
beat,
rows,
error,
+ micProcessing,
start,
stop,
cancel,
@@ -119,6 +121,7 @@ export default function SingToVerify({ value = '', tempo = null, onChange }) {
</div>
{error && <p className="mt-2 text-xs text-port-error">{error}</p>}
+ <MicProcessingHint processing={micProcessing} />
{rows.length > 0 && !recording && (
<div className="mt-3 space-y-3">
diff --git a/client/src/components/songs/SongTraining.jsx b/client/src/components/songs/SongTraining.jsx
index f3ff03f9d2..b3037505c8 100644
--- a/client/src/components/songs/SongTraining.jsx
+++ b/client/src/components/songs/SongTraining.jsx
@@ -22,6 +22,7 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { GraduationCap, Play, Square, Repeat, CheckCircle2, Circle, Target } from 'lucide-react';
import toast from '../ui/Toast';
+import { openAnalysisMic } from '../../lib/audioRecorder.js';
import { scoreHasMusic } from '../../lib/scoreNotation.js';
import {
WHOLE_SONG_SCOPE,
@@ -103,11 +104,12 @@ export default function SongTraining({
const handleStart = useCallback(async () => {
if (running || stream) return;
- const src = await navigator.mediaDevices.getUserMedia({ audio: true }).catch((err) => {
+ const opened = await openAnalysisMic().catch((err) => {
toast.error(err?.message || 'Microphone access denied');
return null;
});
- if (!src) return;
+ if (!opened) return;
+ const { stream: src } = opened;
if (!mountedRef.current) { src.getTracks().forEach((t) => t.stop()); return; }
streamRef.current = src;
setStream(src);
diff --git a/client/src/hooks/useSingToScore.js b/client/src/hooks/useSingToScore.js
index eba01280ae..b72606ebad 100644
--- a/client/src/hooks/useSingToScore.js
+++ b/client/src/hooks/useSingToScore.js
@@ -13,7 +13,7 @@
// in AGENTS.md) so nothing dangles after navigation-away.
import { useCallback, useEffect, useRef, useState } from 'react';
-import { createStreamAnalyser } from '../lib/audioRecorder.js';
+import { createStreamAnalyser, openAnalysisMic } from '../lib/audioRecorder.js';
import { createPitchTracker } from '../lib/pitchDetect.js';
import { createMetronome, clampBpm, timeSignatureFromScore, DEFAULT_BPM } from '../lib/metronome.js';
import { transcribePitchTrack } from '../lib/singToScore.js';
@@ -145,14 +145,15 @@ export default function useSingToScore({ tempo, score = '', musicKey = 'C' } = {
// handed back on every path that never reaches teardown() (the unmount bail
// below is belt-and-suspenders: the hook already releases on unmount).
claimSession();
- const src = await getUserMedia({ audio: true }).catch((err) => {
+ const opened = await openAnalysisMic({ getUserMedia }).catch((err) => {
if (settleStart(requestGeneration)) {
releaseSession();
if (mountedRef.current) setError(err?.message || 'Microphone access denied');
}
return null;
});
- if (!src) return;
+ if (!opened) return;
+ const src = opened.stream;
if (!mountedRef.current || !isCurrent(requestGeneration)) {
src.getTracks().forEach((track) => track.stop());
if (isCurrent(requestGeneration)) releaseSession();
diff --git a/client/src/hooks/useSingToScore.test.js b/client/src/hooks/useSingToScore.test.js
index 83c3492942..46321ec857 100644
--- a/client/src/hooks/useSingToScore.test.js
+++ b/client/src/hooks/useSingToScore.test.js
@@ -12,9 +12,13 @@ let trackerOnUpdate = null;
let metroOpts = null;
const { transcribeMock } = vi.hoisted(() => ({ transcribeMock: vi.fn(() => '| C4q |') }));
-vi.mock('../lib/audioRecorder.js', () => ({
- createStreamAnalyser: vi.fn(() => ({ analyser: { fftSize: 2048 }, context: {}, close: analyserClose })),
-}));
+vi.mock('../lib/audioRecorder.js', async (importActual) => {
+ const actual = await importActual(); // keep the real openAnalysisMic / getSettings read-back
+ return {
+ ...actual,
+ createStreamAnalyser: vi.fn(() => ({ analyser: { fftSize: 2048 }, context: {}, close: analyserClose })),
+ };
+});
vi.mock('../lib/pitchDetect.js', () => ({
createPitchTracker: vi.fn((_analyser, opts) => { trackerOnUpdate = opts.onUpdate; return { stop: trackerStop }; }),
diff --git a/client/src/hooks/useSingToVerify.js b/client/src/hooks/useSingToVerify.js
index a923a94004..2e6e792b68 100644
--- a/client/src/hooks/useSingToVerify.js
+++ b/client/src/hooks/useSingToVerify.js
@@ -2,7 +2,7 @@
// existing score, without changing the score until the user accepts pitches.
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
-import { createStreamAnalyser } from '../lib/audioRecorder.js';
+import { createStreamAnalyser, openAnalysisMic } from '../lib/audioRecorder.js';
import { createMetronome, clampBpm, DEFAULT_BPM } from '../lib/metronome.js';
import { createPitchTracker } from '../lib/pitchDetect.js';
import { parseScore } from '../lib/scoreNotation.js';
@@ -23,6 +23,9 @@ export default function useSingToVerify({ score: scoreText = '', tempo } = {}) {
const [beat, setBeat] = useState(null);
const [rows, setRows] = useState([]);
const [error, setError] = useState(null);
+ // What the browser actually applied to the capture stream — a stage left on
+ // despite ANALYSIS_AUDIO_CONSTRAINTS is why a Safari/Firefox comparison drifts.
+ const [micProcessing, setMicProcessing] = useState(null);
const score = useMemo(() => parseScore(scoreText), [scoreText]);
const mountedRef = useMounted();
@@ -108,14 +111,15 @@ export default function useSingToVerify({ score: scoreText = '', tempo } = {}) {
// newer start()'s own claim now owns the slot, so releasing from a
// superseded request would drop THAT claim instead of ours.
claimSession();
- const stream = await getUserMedia({ audio: true }).catch((err) => {
+ const opened = await openAnalysisMic({ getUserMedia }).catch((err) => {
if (settleStart(requestGeneration)) {
releaseSession();
if (mountedRef.current) setError(err?.message || 'Microphone access denied');
}
return null;
});
- if (!stream) return;
+ if (!opened) return;
+ const { stream, processing } = opened;
if (!mountedRef.current || !isCurrent(requestGeneration)) {
stream.getTracks().forEach((track) => track.stop());
if (isCurrent(requestGeneration)) releaseSession();
@@ -123,6 +127,7 @@ export default function useSingToVerify({ score: scoreText = '', tempo } = {}) {
}
settleStart(requestGeneration);
streamRef.current = stream;
+ setMicProcessing(processing);
const graph = createStreamAnalyser(stream);
analyserRef.current = graph;
@@ -187,5 +192,5 @@ export default function useSingToVerify({ score: scoreText = '', tempo } = {}) {
cancelRef.current = cancel;
useEffect(() => () => cancelRef.current(), []);
- return { phase, beat, rows, error, start, stop, cancel, reset, toggleAccept, acceptAll };
+ return { phase, beat, rows, error, micProcessing, start, stop, cancel, reset, toggleAccept, acceptAll };
}
diff --git a/client/src/hooks/useSingToVerify.test.js b/client/src/hooks/useSingToVerify.test.js
index 7cc34621ef..eb66f296d1 100644
--- a/client/src/hooks/useSingToVerify.test.js
+++ b/client/src/hooks/useSingToVerify.test.js
@@ -10,9 +10,13 @@ let metronomeOptions = null;
let clock = 1000;
const { alignMock } = vi.hoisted(() => ({ alignMock: vi.fn(() => [{ index: 0, accepted: false }]) }));
-vi.mock('../lib/audioRecorder.js', () => ({
- createStreamAnalyser: vi.fn(() => ({ analyser: {}, close: analyserClose })),
-}));
+vi.mock('../lib/audioRecorder.js', async (importActual) => {
+ const actual = await importActual(); // keep the real openAnalysisMic / getSettings read-back
+ return {
+ ...actual,
+ createStreamAnalyser: vi.fn(() => ({ analyser: {}, close: analyserClose })),
+ };
+});
vi.mock('../lib/pitchDetect.js', () => ({
createPitchTracker: vi.fn((_analyser, options) => {
@@ -86,6 +90,45 @@ describe('useSingToVerify', () => {
expect(result.current.rows).toEqual([{ index: 0, accepted: false }]);
});
+ it('opens the mic with browser processing off and reports what actually stuck', async () => {
+ // Safari honors the AEC request but keeps AGC on — the exact case the
+ // report exists for, since the tuner cannot tell from the samples alone.
+ const settings = { echoCancellation: false, noiseSuppression: false, autoGainControl: true };
+ navigator.mediaDevices.getUserMedia = vi.fn(async () => ({
+ getTracks: () => [{ stop: trackStop, getSettings: () => settings }],
+ }));
+ const { result } = renderHook(() => useSingToVerify({
+ tempo: 120,
+ score: 'time: 4/4\n| C4q |',
+ }));
+
+ await act(async () => { await result.current.start(1); });
+
+ expect(navigator.mediaDevices.getUserMedia).toHaveBeenCalledWith({
+ audio: { echoCancellation: false, noiseSuppression: false, autoGainControl: false },
+ });
+ expect(result.current.micProcessing).toEqual(settings);
+ });
+
+ it('reports an unknown processing stage as null rather than as honored', async () => {
+ // Firefox omits keys it does not implement. Collapsing absent into false
+ // would let it claim clean audio it never promised.
+ navigator.mediaDevices.getUserMedia = vi.fn(async () => ({
+ getTracks: () => [{ stop: trackStop, getSettings: () => ({ echoCancellation: false }) }],
+ }));
+ const { result } = renderHook(() => useSingToVerify({
+ tempo: 120,
+ score: 'time: 4/4\n| C4q |',
+ }));
+
+ await act(async () => { await result.current.start(1); });
+
+ expect(result.current.micProcessing).toEqual({
+ echoCancellation: false,
+ noiseSuppression: null,
+ autoGainControl: null,
+ });
+ });
it('tears down mic stream, analyser, tracker, and metronome on unmount', async () => {
const { result, unmount } = renderHook(() => useSingToVerify({
tempo: 120,
diff --git a/client/src/lib/README.md b/client/src/lib/README.md
index c37012bb03..ce39e06832 100644
--- a/client/src/lib/README.md
+++ b/client/src/lib/README.md
@@ -99,7 +99,7 @@ grep -i "what you want to do" client/src/lib/README.md
| `appIdentity.js` | `PORTOS_APP_ID` — stable id of the baseline PortOS app (mirrors `server/lib/appIdentity.js`). Dependency-free so a module reachable from a node-env server test (e.g. `components/apps/constants.js`) can identify PortOS without importing `services/apiCore.js`, which pulls in React via `ui/Toast`. `apiCore.js` re-exports it, so `import { PORTOS_APP_ID } from '../services/api'` still works. |
| `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. |
| `assessmentTuningNotice.js` | `tuningNoticeChip(entry)` — the short form of how a measured local-model assessment says its launch configuration did NOT take effect. `tuningApplied === false` covers two opposite cases and `tuningKey` separates them: a TUNED run whose knobs never reached the daemon (`tuning not applied`), versus an UNTUNED run PortOS could not put back on backend defaults (`not at defaults`) — #4759. Shared by `ModelThroughputReport.jsx`'s table cell and `LocalModelAssessments.jsx`'s result toast; the long form is the server's exclusion reason in `getAssessmentReport`. |
-| `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`. |
+| `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`. **`openAnalysisMic({ getUserMedia })`** → `{ stream, processing }` is the ONE way a pitch-analysis surface opens a mic: it requests `ANALYSIS_AUDIO_CONSTRAINTS` (echo cancellation / noise suppression / AGC off — plain booleans, never `{ exact }`, so a browser that can't honor one still opens the mic) and reads `track.getSettings()` back so the UI can say what actually stuck. `readAppliedProcessing(stream)` reports each stage as `true` / `false` / `null` (browser didn't say — never collapse unknown into off) and `hasUnwantedProcessing(p)` gates the warning. Memo capture deliberately keeps the speech-tuned defaults; Whisper wants them. |
| `bareUrl.js` | `parseBareUrl(text)` — the normalized URL when a capture's entire text is a URL, else null. Client mirror of the authoritative `server/lib/bareUrl.js` (parity enforced by `server/lib/bareUrl.mirror.test.js`), so the brain capture boxes preview the exact filing decision the server will make. Use this — not the looser `utils/urlNormalize.js` `isUrl` — anywhere the answer must match the server. |
| `youtubeUrl.js` | `isYoutubeVideoUrl(text)` / `youtubeVideoId(url)` — single-video YouTube URL detection. Client mirror of `YOUTUBE_INGEST_URL_RE` in `server/services/youtubeIngest.js` (behavioral parity pinned by `server/lib/youtubeUrl.mirror.test.js`); deliberately excludes playlists and channels. Quick Capture uses it to swap to the ingest submit path and reveal the ingest options panel. Also `INGEST_OPTIONS` — the single table of the three ingest artifacts (`key` / `settingKey` / `fallback` / `label` / `hint`) — plus `defaultIngestOptions()` and `ingestOptionsFromSettings(settings)`. Everything that enumerates the switches derives from that table; add an artifact there, not at each call site. |
| `boundedMap.js` | `evictOldest(map, max, onEvict?)` — evict oldest-first (`map.keys().next().value`) until a Map is within `max`, with an optional per-evicted-key teardown callback for a companion timer map; `ORPHAN_BUFFER_MAX` (64), the shared cap for the orphan-event race-buffers. The one home for the "stash an unmatched event in a `jobId → …` Map, evict the oldest on overflow" idiom shared by `useSceneRenderLifecycle`, `useImageGenQueue`, and `clientErrorReporter`. |
diff --git a/client/src/lib/audioRecorder.js b/client/src/lib/audioRecorder.js
index 3e8a1deb02..9c0114da0b 100644
--- a/client/src/lib/audioRecorder.js
+++ b/client/src/lib/audioRecorder.js
@@ -168,3 +168,63 @@ export async function startMemoRecording() {
cancel: () => { teardown(); try { recorder.stop(); } catch { /* already stopped */ } },
};
}
+
+/**
+ * Constraints every PITCH-ANALYSIS mic opens with. The browser's default
+ * capture chain is tuned for speech intelligibility, not signal analysis: AGC
+ * rides the level the tuner's clarity gate reads, noise suppression chews
+ * sustained vowels and soft onsets, and echo cancellation can gate the mic
+ * outright while a reference melody plays back. Plain booleans, NOT `{ exact }`
+ * — a browser that can't honor one must still open the mic rather than fail
+ * closed; `openAnalysisMic` reports back what actually stuck.
+ *
+ * Deliberately NOT applied to `startMemoRecording` — that capture feeds Whisper
+ * transcription, where the speech-tuned chain helps.
+ */
+export const ANALYSIS_AUDIO_CONSTRAINTS = Object.freeze({
+ echoCancellation: false,
+ noiseSuppression: false,
+ autoGainControl: false,
+});
+
+const PROCESSING_KEYS = ['echoCancellation', 'noiseSuppression', 'autoGainControl'];
+
+/**
+ * Read back which processing stages the browser ACTUALLY applied to a capture
+ * stream. Each key is `true` (on despite the constraint), `false` (honored), or
+ * `null` when the browser doesn't report it — Firefox omits keys from
+ * `getSettings()`, and unknown must not collapse into "off" or every such
+ * browser would silently claim clean audio.
+ */
+export function readAppliedProcessing(stream) {
+ const track = stream?.getAudioTracks?.()?.[0] ?? stream?.getTracks?.()?.[0];
+ const settings = track?.getSettings?.();
+ return Object.fromEntries(PROCESSING_KEYS.map((key) => [
+ key,
+ typeof settings?.[key] === 'boolean' ? settings[key] : null,
+ ]));
+}
+
+/** True only when a stage is KNOWN to still be on — `null` (unknown) never warns. */
+export function hasUnwantedProcessing(processing) {
+ return PROCESSING_KEYS.some((key) => processing?.[key] === true);
+}
+
+/**
+ * Open a microphone for pitch/signal analysis with the browser's processing
+ * chain requested off, and report what it actually applied. Returns
+ * `{ stream, processing }`; rejects exactly like `getUserMedia` does, so call
+ * sites keep their existing `.catch()` + re-entrancy guards.
+ *
+ * Pass `getUserMedia` when the caller already resolved (and null-checked) it —
+ * reaching through `navigator.mediaDevices` throws synchronously on an insecure
+ * origin, and the capture hooks must do that check before claiming the audio
+ * session.
+ */
+export async function openAnalysisMic({ getUserMedia } = {}) {
+ const open = getUserMedia
+ || navigator.mediaDevices?.getUserMedia?.bind(navigator.mediaDevices);
+ if (!open) throw new Error('Microphone access requires a secure browser connection');
+ const stream = await open({ audio: { ...ANALYSIS_AUDIO_CONSTRAINTS } });
+ return { stream, processing: readAppliedProcessing(stream) };
+}
diff --git a/client/src/lib/audioRecorder.test.js b/client/src/lib/audioRecorder.test.js
new file mode 100644
index 0000000000..e25263e4ce
--- /dev/null
+++ b/client/src/lib/audioRecorder.test.js
@@ -0,0 +1,75 @@
+// The analysis-mic helper: what it asks the browser for, and how honestly it
+// reports what the browser actually did. The rest of audioRecorder.js is Web
+// Audio / MediaRecorder plumbing exercised through its component callers.
+
+import { describe, it, expect, vi } from 'vitest';
+import {
+ ANALYSIS_AUDIO_CONSTRAINTS,
+ hasUnwantedProcessing,
+ openAnalysisMic,
+ readAppliedProcessing,
+} from './audioRecorder.js';
+
+const streamWith = (settings) => ({
+ getAudioTracks: () => [settings === undefined ? {} : { getSettings: () => settings }],
+});
+
+describe('openAnalysisMic', () => {
+ it('requests the processing chain off with plain booleans, never { exact }', async () => {
+ const getUserMedia = vi.fn(async () => streamWith({}));
+ await openAnalysisMic({ getUserMedia });
+ expect(getUserMedia).toHaveBeenCalledWith({
+ audio: { echoCancellation: false, noiseSuppression: false, autoGainControl: false },
+ });
+ // `{ exact }` would make a browser that can't honor a stage fail the whole
+ // request instead of opening a usable (if processed) mic.
+ expect(Object.values(ANALYSIS_AUDIO_CONSTRAINTS).every((v) => v === false)).toBe(true);
+ });
+
+ it('returns the stream alongside the settings the browser actually applied', async () => {
+ const stream = streamWith({ echoCancellation: false, noiseSuppression: true, autoGainControl: true });
+ const { stream: opened, processing } = await openAnalysisMic({ getUserMedia: async () => stream });
+ expect(opened).toBe(stream);
+ expect(processing).toEqual({
+ echoCancellation: false,
+ noiseSuppression: true,
+ autoGainControl: true,
+ });
+ });
+
+ it('rejects like getUserMedia does, so callers keep their own catch/guards', async () => {
+ const getUserMedia = vi.fn(async () => { throw new Error('Permission denied'); });
+ await expect(openAnalysisMic({ getUserMedia })).rejects.toThrow('Permission denied');
+ });
+});
+
+describe('readAppliedProcessing', () => {
+ it('reports an unsupported getSettings as unknown, not as honored', () => {
+ // A browser (or a jsdom stub) with no getSettings tells us nothing — every
+ // stage must read null, or the UI would claim clean audio it can't verify.
+ expect(readAppliedProcessing(streamWith(undefined))).toEqual({
+ echoCancellation: null,
+ noiseSuppression: null,
+ autoGainControl: null,
+ });
+ expect(readAppliedProcessing(null)).toEqual({
+ echoCancellation: null,
+ noiseSuppression: null,
+ autoGainControl: null,
+ });
+ });
+
+ it('falls back to getTracks when the stream has no getAudioTracks', () => {
+ const stream = { getTracks: () => [{ getSettings: () => ({ autoGainControl: true }) }] };
+ expect(readAppliedProcessing(stream).autoGainControl).toBe(true);
+ });
+});
+
+describe('hasUnwantedProcessing', () => {
+ it('warns only on a stage KNOWN to be on', () => {
+ expect(hasUnwantedProcessing({ echoCancellation: false, noiseSuppression: false, autoGainControl: false })).toBe(false);
+ expect(hasUnwantedProcessing({ echoCancellation: null, noiseSuppression: null, autoGainControl: null })).toBe(false);
+ expect(hasUnwantedProcessing(null)).toBe(false);
+ expect(hasUnwantedProcessing({ echoCancellation: null, noiseSuppression: true, autoGainControl: null })).toBe(true);
+ });
+});