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
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { renderHook, act } from '@testing-library/react';
// Mock every Web Audio / mic seam the hook touches so it runs in jsdom. We
// capture the metronome + tracker callbacks so the test can drive the count-in
// → recording → transcribe lifecycle deterministically.
const analyserClose = vi.fn();
const trackerStop = vi.fn();
const metronomeStop = vi.fn();
const trackStop = vi.fn();
let trackerOnUpdate = null;
let metroOpts = null;
const { transcribeMock } = vi.hoisted(() => ({ transcribeMock: vi.fn(() => '| C4q |') }));
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 }; }),
}));
vi.mock('../lib/metronome.js', async (importActual) => {
const actual = await importActual();
return {
...actual,
createMetronome: vi.fn((opts) => {
metroOpts = opts;
return { start: vi.fn(async () => {}), stop: metronomeStop };
}),
};
});
vi.mock('../lib/singToScore.js', () => ({ transcribePitchTrack: transcribeMock }));
import useSingToScore, { SING_IDLE, SING_COUNT_IN, SING_RECORDING } from './useSingToScore.js';
const fakeStream = () => ({ getTracks: () => [{ stop: trackStop }] });
describe('useSingToScore', () => {
beforeEach(() => {
analyserClose.mockClear();
trackerStop.mockClear();
metronomeStop.mockClear();
trackStop.mockClear();
transcribeMock.mockClear();
trackerOnUpdate = null;
metroOpts = null;
global.navigator.mediaDevices = { getUserMedia: vi.fn(async () => fakeStream()) };
// Safari 16.4+ only — jsdom has no `navigator.audioSession`, so the iOS
// session tests below stub the shape the arbiter writes to.
global.navigator.audioSession = { type: 'auto' };
global.performance = { now: () => 1000 };
});
afterEach(() => { vi.clearAllMocks(); delete global.navigator.audioSession; });
it('walks idle → count-in → recording → idle and transcribes on stop', async () => {
const { result } = renderHook(() => useSingToScore({ tempo: 120, score: 'time: 4/4', musicKey: 'C' }));
expect(result.current.phase).toBe(SING_IDLE);
await act(async () => { await result.current.start(); });
expect(result.current.phase).toBe(SING_COUNT_IN);
// Count-in completes → recording starts and the capture clock anchors.
act(() => { metroOpts.onCountInComplete({ beat: 1 }); });
expect(result.current.phase).toBe(SING_RECORDING);
// A clear frame is captured into the track.
act(() => { trackerOnUpdate({ hz: 261.6, clarity: 0.95 }); });
act(() => { result.current.stop(); });
expect(result.current.phase).toBe(SING_IDLE);
expect(transcribeMock).toHaveBeenCalledTimes(1);
// The accumulated track (one frame) is passed to the transcriber.
expect(transcribeMock.mock.calls[0][0]).toHaveLength(1);
expect(result.current.result).toBe('| C4q |');
});
it('does not capture frames during the count-in', async () => {
const { result } = renderHook(() => useSingToScore({ tempo: 120, score: 'time: 4/4' }));
await act(async () => { await result.current.start(); });
// Frame arrives before count-in completes — must be ignored.
act(() => { trackerOnUpdate?.({ hz: 440, clarity: 0.95 }); });
act(() => { metroOpts.onCountInComplete({ beat: 1 }); });
act(() => { result.current.stop(); });
expect(transcribeMock.mock.calls[0][0]).toHaveLength(0);
});
it('surfaces a mic-denied error and stays idle', async () => {
global.navigator.mediaDevices.getUserMedia = vi.fn(async () => { throw new Error('Permission denied'); });
const { result } = renderHook(() => useSingToScore({ tempo: 120 }));
await act(async () => { await result.current.start(); });
expect(result.current.phase).toBe(SING_IDLE);
expect(result.current.error).toBe('Permission denied');
global.navigator.mediaDevices.getUserMedia = vi.fn(async () => fakeStream());
await act(async () => { await result.current.start(); });
expect(result.current.phase).toBe(SING_COUNT_IN);
});
it('tears down mic, analyser, tracker, and metronome on unmount', async () => {
const { result, unmount } = renderHook(() => useSingToScore({ tempo: 120, score: 'time: 4/4' }));
await act(async () => { await result.current.start(); });
unmount();
expect(metronomeStop).toHaveBeenCalled();
expect(trackerStop).toHaveBeenCalled();
expect(analyserClose).toHaveBeenCalled();
expect(trackStop).toHaveBeenCalled();
});
it('allows only one microphone request while permission is pending', async () => {
let resolveStream;
navigator.mediaDevices.getUserMedia = vi.fn(() => new Promise((resolve) => {
resolveStream = resolve;
}));
const { result } = renderHook(() => useSingToScore({ tempo: 120, score: 'time: 4/4' }));
let firstStart;
act(() => {
firstStart = result.current.start();
result.current.start();
});
expect(navigator.mediaDevices.getUserMedia).toHaveBeenCalledTimes(1);
await act(async () => {
resolveStream(fakeStream());
await firstStart;
});
expect(result.current.phase).toBe(SING_COUNT_IN);
});
it('stops a permission-pending stream when capture is cancelled', async () => {
let resolveStream;
navigator.mediaDevices.getUserMedia = vi.fn(() => new Promise((resolve) => {
resolveStream = resolve;
}));
const { result, unmount } = renderHook(() => useSingToScore({ tempo: 120, score: 'time: 4/4' }));
let startPromise;
act(() => { startPromise = result.current.start(); });
unmount();
await act(async () => {
resolveStream(fakeStream());
await startPromise;
});
expect(trackStop).toHaveBeenCalledOnce();
});
it('ignores a permission rejection that arrives after capture was already cancelled', async () => {
let rejectStream;
navigator.mediaDevices.getUserMedia = vi.fn(() => new Promise((_resolve, reject) => {
rejectStream = reject;
}));
const { result, unmount } = renderHook(() => useSingToScore({ tempo: 120, score: 'time: 4/4' }));
let startPromise;
act(() => { startPromise = result.current.start(); });
unmount();
// The pending getUserMedia request rejects only after cancel() already
// tore this attempt down (generation bumped). The stale-generation branch
// in the catch handler must swallow this quietly — no error surfaced, no
// stream to stop, no double release.
await act(async () => {
rejectStream(new Error('Permission denied'));
await startPromise.catch(() => {});
});
expect(result.current.error).toBeNull();
expect(trackStop).not.toHaveBeenCalled();
});
// `playback` REFUSES capture on iOS, and the transport-driven players declare
// it document-wide, so this hook has to claim `play-and-record` around its own
// getUserMedia rather than relying on nothing else having claimed first (#4131).
describe('iOS audio session', () => {
it('claims play-and-record for the mic window and hands it back on stop', async () => {
const { result } = renderHook(() => useSingToScore({ tempo: 120, score: 'time: 4/4' }));
await act(async () => { await result.current.start(); });
expect(navigator.audioSession.type).toBe('play-and-record');
act(() => { result.current.stop(); });
expect(navigator.audioSession.type).toBe('auto');
});
it('hands the session back when the mic is denied', async () => {
global.navigator.mediaDevices.getUserMedia = vi.fn(async () => { throw new Error('Permission denied'); });
const { result } = renderHook(() => useSingToScore({ tempo: 120 }));
await act(async () => { await result.current.start(); });
// A denied mic never reaches teardown(), so the claim has to be released
// on the rejection path or the page stays pinned record-capable.
expect(navigator.audioSession.type).toBe('auto');
});
it('hands the session back on unmount mid-capture', async () => {
const { result, unmount } = renderHook(() => useSingToScore({ tempo: 120, score: 'time: 4/4' }));
await act(async () => { await result.current.start(); });
unmount();
expect(navigator.audioSession.type).toBe('auto');
});
});
});