Files
CyberGril/web/tests/hel900_custom_voice.test.ts
T

202 lines
15 KiB
TypeScript

// HEL-900: custom voice wiring against docs/voice-custom-contract-HEL899.md §2, fully offline (fake fetch, fake decoder,
// fake microphone and recorder). Nothing here reaches a real ASR/TTS or a real microphone.
import { afterEach, describe, expect, it, vi } from 'vitest';
import { applyVoice, encodeWav, listVoices, previewVoice, Recorder, registerVoice, SAY, toReference, VoiceError, wavInfo, type Decoded, type MediaParts, type RecView } from '../src/voice/custom';
const tone = (seconds: number, rate: number, channels = 1, amp = 0.3): Decoded => {
const length = Math.round(seconds * rate), data = Array.from({ length: channels }, () => Float32Array.from({ length }, (_, i) => amp * Math.sin(i / 7)));
return { sampleRate: rate, length, numberOfChannels: channels, getChannelData: c => data[c] };
};
const json = (status: number, body: unknown) => new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } });
const wavBytes = (seconds: number, rate = 24000) => encodeWav(new Float32Array(Math.round(seconds * rate)).fill(0.1), rate);
const never = new AbortController().signal;
afterEach(() => { vi.unstubAllGlobals(); vi.useRealTimers(); });
describe('reference audio becomes the WAV the server accepts', () => {
it('writes PCM 16-bit mono with a header the server can parse', () => {
const info = wavInfo(encodeWav(new Float32Array(16000 * 3), 16000));
expect(info).toEqual({ rate: 16000, channels: 1, bits: 16, seconds: 3 });
});
it('does not take a WebM (or anything else) for a WAV', () => {
const webm = new Uint8Array([0x1a, 0x45, 0xdf, 0xa3, ...new Array(60).fill(0)]).buffer;
expect(wavInfo(webm)).toBeNull();
expect(wavInfo(new ArrayBuffer(10))).toBeNull();
});
it('decodes, mixes down and resamples a 48 kHz stereo take to 16 kHz mono', async () => {
const ref = await toReference(new Blob([new Uint8Array(8)]), async () => tone(3, 48000, 2));
expect(ref.wav.type).toBe('audio/wav');
const info = wavInfo(await ref.wav.arrayBuffer())!;
expect(info.rate).toBe(16000); expect(info.channels).toBe(1); expect(info.bits).toBe(16);
expect(info.seconds).toBeCloseTo(3, 1); expect(ref.seconds).toBeCloseTo(3, 1);
});
it('refuses what the server would refuse, before sending anything', async () => {
await expect(toReference(new Blob([new Uint8Array(8)]), async () => tone(1.5, 16000))).rejects.toThrow(SAY.tooShort);
await expect(toReference(new Blob([new Uint8Array(8)]), async () => tone(4, 16000, 1, 0))).rejects.toThrow(SAY.silent);
await expect(toReference(new Blob([new Uint8Array(8)]), async () => { throw new Error('EncodingError'); })).rejects.toThrow(SAY.undecodable);
await expect(toReference({ size: 60 * 1024 * 1024 } as Blob, async () => tone(4, 16000))).rejects.toThrow(SAY.fileTooBig);
// 15 MB of 16 kHz WAV is about 491 s.
await expect(toReference(new Blob([new Uint8Array(8)]), async () => tone(500, 16000))).rejects.toThrow(SAY.tooBig);
});
});
describe('API contract §2', () => {
it('lists voices, honest about an unconfigured or older server', async () => {
const ok = vi.fn(async () => json(200, { configured: true, voices: [{ id: 'rain', label: 'rain', source: 'builtin', selected: false, previewed: false, registered_at: null }, { id: 'cg-9f2c1a77', label: '她的声音', source: 'custom', selected: true, previewed: true, registered_at: 1 }, { id: '<bad>', label: 'x', source: 'custom' }], selection: { voice: 'cg-9f2c1a77', label: '她的声音', updated_at: 2 } }));
const list = await listVoices(never, ok as typeof fetch);
expect(ok).toHaveBeenCalledWith('/api/voice/voices', expect.anything());
expect(list.configured && list.voices.map(v => v.id)).toEqual(['rain', 'cg-9f2c1a77']);
expect(list.configured && list.selection).toEqual({ voice: 'cg-9f2c1a77', label: '她的声音', updated_at: 2 });
expect(await listVoices(never, (async () => json(200, { configured: false, voices: [], selection: null })) as typeof fetch)).toEqual({ configured: false });
await expect(listVoices(never, (async () => json(404, { detail: 'Not Found' })) as typeof fetch)).rejects.toMatchObject({ status: 404, message: SAY.noRoute });
await expect(listVoices(never, (async () => json(503, { detail: '音色登记服务这会儿不在,稍后再试试。' })) as typeof fetch)).rejects.toMatchObject({ status: 503, message: '音色登记服务这会儿不在,稍后再试试。' });
});
it('registers the raw WAV bytes with its parameters in the query string', async () => {
const wav = new Blob([wavBytes(3, 16000)], { type: 'audio/wav' });
const f = vi.fn(async (_url: string, _init?: RequestInit) => json(201, { id: 'cg-1234abcd', label: '轻一点', prompt_text: '你好呀', prompt_text_source: 'user', prompt_wav: '/x', registered_at: 1 }));
const done = await registerVoice(wav, { label: ' 轻一点 ', text: '你好呀', allowAsr: true }, never, f as unknown as typeof fetch);
const [url, init] = f.mock.calls[0];
const q = new URL(url, 'http://x').searchParams;
expect(url.startsWith('/api/voice/voices?')).toBe(true);
expect([q.get('label'), q.get('prompt_text'), q.get('allow_asr')]).toEqual(['轻一点', '你好呀', 'false']);
expect(init!.method).toBe('POST'); expect(init!.body).toBe(wav); expect((init!.headers as Record<string, string>)['Content-Type']).toBe('audio/wav');
expect(done).toEqual({ id: 'cg-1234abcd', label: '轻一点', prompt_text: '你好呀', prompt_text_source: 'user' });
});
it('asks for transcription only when you left the text empty and allowed it', async () => {
const f = vi.fn(async (_url: string) => json(201, { id: 'cg-1', label: 'cg-1', prompt_text: '转写的', prompt_text_source: 'asr' }));
await registerVoice(new Blob([wavBytes(3)]), { label: '', text: ' ', allowAsr: true }, never, f as unknown as typeof fetch);
await registerVoice(new Blob([wavBytes(3)]), { label: '', text: '', allowAsr: false }, never, f as unknown as typeof fetch);
expect(f.mock.calls.map(([u]) => new URL(u, 'http://x').searchParams.get('allow_asr'))).toEqual(['true', 'false']);
});
it('passes the server refusal through and keeps nothing half-done', async () => {
const detail = '请填写这段音频的参考文字,或明确选择让系统转写(会用到语音识别)。';
await expect(registerVoice(new Blob([wavBytes(3)]), { label: '', text: '', allowAsr: false }, never, (async () => json(422, { detail })) as typeof fetch)).rejects.toMatchObject({ status: 422, message: detail });
await expect(registerVoice(new Blob([wavBytes(3)]), { label: '', text: 'x', allowAsr: false }, never, (async () => { throw new TypeError('Failed to fetch'); }) as typeof fetch)).rejects.toThrow(SAY.unreachable);
});
it('sends nothing while the browser is offline', async () => {
vi.stubGlobal('navigator', { onLine: false });
const f = vi.fn();
await expect(registerVoice(new Blob([wavBytes(3)]), { label: '', text: 'x', allowAsr: false }, never, f as unknown as typeof fetch)).rejects.toThrow(SAY.offline);
await expect(previewVoice('rain', '', never, f as unknown as typeof fetch)).rejects.toThrow(SAY.offline);
expect(f).not.toHaveBeenCalled();
});
it('plays only a real WAV from a fresh preview, and sends the default text only when you gave none', async () => {
const f = vi.fn(async (_u: string, _i?: RequestInit) => new Response(wavBytes(1.2), { status: 200, headers: { 'Content-Type': 'audio/wav' } }));
const blob = await previewVoice('cg-1', '', never, f as unknown as typeof fetch);
expect(wavInfo(await blob.arrayBuffer())?.rate).toBe(24000);
expect(JSON.parse(String(f.mock.calls[0][1]!.body))).toEqual({ voice: 'cg-1' });
await previewVoice('cg-1', ' 晚安 ', never, f as unknown as typeof fetch);
expect(JSON.parse(String(f.mock.calls[1][1]!.body))).toEqual({ voice: 'cg-1', text: '晚安' });
await expect(previewVoice('cg-1', '', never, (async () => new Response('<html>oops</html>', { status: 200 })) as typeof fetch)).rejects.toThrow(SAY.badPreview);
await expect(previewVoice('ghost', '', never, (async () => json(404, { detail: '这个声音现在不在列表里。' })) as typeof fetch)).rejects.toMatchObject({ status: 404 });
await expect(previewVoice('cg-1', '', never, (async () => json(503, { detail: '她的声音服务这会儿不在,稍后再试试。' })) as typeof fetch)).rejects.toThrow('她的声音服务这会儿不在');
});
it('a late preview answer for a cancelled request is not returned as a result', async () => {
const c = new AbortController();
const f = (async (_u: string, init?: RequestInit) => new Promise<Response>((_, reject) => init!.signal!.addEventListener('abort', () => reject(new DOMException('aborted', 'AbortError'))))) as typeof fetch;
const p = previewVoice('cg-1', '', c.signal, f);
c.abort();
await expect(p).rejects.toMatchObject({ name: 'AbortError' });
});
it('applies, and says plainly when a custom voice was not previewed', async () => {
const f = vi.fn(async () => json(200, { voice: 'cg-1', label: '轻一点', updated_at: 5 }));
expect(await applyVoice('cg-1', never, f as unknown as typeof fetch)).toEqual({ voice: 'cg-1', label: '轻一点', updated_at: 5 });
await expect(applyVoice('cg-2', never, (async () => json(409, { detail: '这个声音还没有试听过,先试听再给她用。' })) as typeof fetch)).rejects.toMatchObject({ status: 409, message: '这个声音还没有试听过,先试听再给她用。' });
await expect(applyVoice('cg-2', never, (async () => json(503, { detail: '她的音色状态这会儿写不进,这次没有换成功。' })) as typeof fetch)).rejects.toMatchObject({ status: 503 });
// An answer for some other voice is not taken as "applied".
await expect(applyVoice('cg-2', never, f as unknown as typeof fetch)).rejects.toBeInstanceOf(VoiceError);
});
});
// ── Recorder with a fake microphone and MediaRecorder ──
class FakeTrack extends EventTarget { stopped = false; stop() { this.stopped = true; } }
function fakeMedia(opts: { deny?: string; secure?: boolean } = {}) {
const tracks: FakeTrack[] = [];
let release: (s: MediaStream) => void = () => {};
const recorders: FakeRecorder[] = [];
class FakeRecorder {
state: 'inactive' | 'recording' = 'inactive'; mimeType = 'audio/webm;codecs=opus';
ondataavailable: ((e: { data: Blob }) => void) | null = null; onstop: (() => void) | null = null; onerror: (() => void) | null = null;
start() { this.state = 'recording'; }
stop() { if (this.state === 'inactive') return; this.state = 'inactive'; this.ondataavailable?.({ data: new Blob([new Uint8Array(100)], { type: this.mimeType }) }); queueMicrotask(() => this.onstop?.()); }
}
let asked = 0;
const media: MediaParts = {
secure: () => opts.secure !== false,
getUserMedia: c => {
asked++;
expect(c.video).toBe(false);
if (opts.deny) return Promise.reject(Object.assign(new Error('no'), { name: opts.deny }));
return new Promise(resolve => { release = resolve; });
},
recorder: () => { const r = new FakeRecorder(); recorders.push(r); return r as unknown as MediaRecorder; },
};
const grant = () => { const t = new FakeTrack(); tracks.push(t); release({ getTracks: () => tracks, getAudioTracks: () => tracks } as unknown as MediaStream); };
return { media, grant, tracks, recorders, asked: () => asked };
}
function harness(m: ReturnType<typeof fakeMedia>, max = 20) {
let t = 0;
const views: RecView[] = [], done: Blob[] = [], fails: string[] = [];
const r = new Recorder({ view: v => views.push(v), done: b => done.push(b), fail: s => fails.push(s) }, m.media, max, () => t);
return { r, views, done, fails, advance: (ms: number) => { t += ms; vi.advanceTimersByTime(ms); } };
}
const tick = () => new Promise(r => setTimeout(r, 0));
describe('recording is only on your tap and always lets the microphone go', () => {
it('opens nothing until started; stop keeps the take and closes the microphone', async () => {
const m = fakeMedia(), h = harness(m);
expect(m.asked()).toBe(0);
const started = h.r.start(); m.grant(); await started;
expect(h.r.view.phase).toBe('recording');
h.r.stop();
expect(m.tracks.every(t => t.stopped)).toBe(true);
await tick();
expect(h.done).toHaveLength(1); expect(h.done[0].type).toContain('webm');
expect(h.r.view.phase).toBe('converting');
h.r.settled(); expect(h.r.view.phase).toBe('idle');
});
it('cancel throws the take away and frees the microphone; nothing is handed over later', async () => {
const m = fakeMedia(), h = harness(m);
const started = h.r.start(); m.grant(); await started;
h.r.cancel(); await tick();
expect(m.tracks.every(t => t.stopped)).toBe(true);
expect(h.done).toHaveLength(0); expect(h.r.view.phase).toBe('idle');
});
it('a microphone granted after you cancelled (or left) is closed at once, never used', async () => {
const m = fakeMedia(), h = harness(m);
const started = h.r.start(); h.r.cancel(); m.grant(); await started;
expect(m.tracks[0].stopped).toBe(true);
expect(m.recorders).toHaveLength(0); expect(h.r.view.phase).toBe('idle');
});
it('stops by itself at the length limit', async () => {
vi.useFakeTimers();
const m = fakeMedia(), h = harness(m, 20);
const started = h.r.start(); m.grant(); await started;
h.advance(20200);
expect(m.tracks.every(t => t.stopped)).toBe(true);
await vi.runAllTimersAsync();
expect(h.done).toHaveLength(1);
});
it('a microphone that goes away mid-take ends it honestly', async () => {
const m = fakeMedia(), h = harness(m);
const started = h.r.start(); m.grant(); await started;
m.tracks[0].dispatchEvent(new Event('ended'));
expect(h.fails).toEqual([SAY.micGone]); expect(h.r.view.phase).toBe('idle'); expect(m.recorders[0].state).toBe('inactive');
});
it('a refused permission or an insecure page says why and opens nothing', async () => {
const denied = fakeMedia({ deny: 'NotAllowedError' }), h1 = harness(denied);
await h1.r.start();
expect(h1.fails).toEqual([SAY.denied]); expect(h1.r.view.phase).toBe('idle');
const busy = fakeMedia({ deny: 'NotReadableError' }), h2 = harness(busy);
await h2.r.start(); expect(h2.fails).toEqual([SAY.micBusy]);
const insecure = fakeMedia({ secure: false }), h3 = harness(insecure);
await h3.r.start();
expect(h3.fails).toEqual([SAY.insecure]); expect(insecure.asked()).toBe(0);
});
it('a second tap while recording does not open a second microphone', async () => {
const m = fakeMedia(), h = harness(m);
const started = h.r.start(); await h.r.start(); m.grant(); await started;
expect(m.asked()).toBe(1);
h.r.cancel();
});
});