123 lines
8.5 KiB
TypeScript
123 lines
8.5 KiB
TypeScript
import { afterEach, describe, expect, it, vi } from 'vitest';
|
|
import { callVoiceOf, readVoiceStatus, VoiceController, type MicTrack, type RoomEvents, type VoiceRoom, type VoiceView } from '../src/voice/session';
|
|
import { callVoiceName, idOnly, registerVoice, SAY, VoiceError, type CustomVoice } from '../src/voice/custom';
|
|
|
|
// HEL-903 limited rework, offline only: fake fetch, fake room and microphone. No LiveKit, voice panel, ASR or TTS.
|
|
const gate = () => { let open!: () => void; const promise = new Promise<void>(r => { open = r; }); return { promise, open }; };
|
|
const flush = async (n = 8) => { for (let i = 0; i < n; i++) await Promise.resolve(); await new Promise(r => setTimeout(r, 0)); };
|
|
const signal = () => new AbortController().signal;
|
|
const reply = (body: unknown, status = 200) => new Response(typeof body === 'string' ? body : JSON.stringify(body), { status });
|
|
afterEach(() => { vi.unstubAllGlobals(); });
|
|
|
|
describe('外接服务 reads only what /api/voice/status can tell', () => {
|
|
const kind = (answer: () => Response | Promise<Response>) => readVoiceStatus(signal(), (async () => answer()) as unknown as typeof fetch);
|
|
it('tells not configured, reachable, down, no route and unreadable apart', async () => {
|
|
expect(await kind(() => reply({ configured: false, tts_ok: false, agent_name: null, voice: false }))).toBe('off');
|
|
expect(await kind(() => reply({ configured: true, tts_ok: true, voice: false }))).toBe('ok');
|
|
expect(await kind(() => reply({ configured: true, tts_ok: false, voice: false }))).toBe('down');
|
|
expect(await kind(() => reply({ detail: 'Not Found' }, 404))).toBe('none');
|
|
expect(await kind(() => reply('oops', 500))).toBe('unknown');
|
|
expect(await kind(() => reply('not json'))).toBe('unknown');
|
|
expect(await kind(() => { throw new TypeError('Failed to fetch'); })).toBe('unknown');
|
|
});
|
|
it('a configured flag alone is never "reachable"', async () => {
|
|
expect(await kind(() => reply({ configured: true }))).toBe('down');
|
|
});
|
|
});
|
|
|
|
// ── The call's own voice ──
|
|
class Mic implements MicTrack { stopped = 0; stop() { this.stopped++; } onEnded() {} }
|
|
class Room implements VoiceRoom { closed = 0; on!: RoomEvents; async publish() {} hush() {} async resumeAudio() {} async close() { this.closed++; } }
|
|
function rig() {
|
|
const views: VoiceView[] = [], rooms: Room[] = [], voices: unknown[] = [], gates: (ReturnType<typeof gate> | undefined)[] = [];
|
|
let made = 0;
|
|
const fetch = vi.fn(async (url: string, init: RequestInit = {}) => {
|
|
if (url === '/api/voice/status') return reply({ configured: true, tts_ok: true, voice: false });
|
|
if (url === '/api/voice/session' && init.method === 'POST') {
|
|
const n = made++, g = gates[n]; if (g) await g.promise;
|
|
const grant: Record<string, unknown> = { url: 'wss://lk.test', token: `t${n}`, room: `r${n}`, session_id: `s${n}`, epoch: 3, expires_at: 0 };
|
|
if (voices[n] !== undefined) grant.voice = voices[n];
|
|
return reply(grant, 201);
|
|
}
|
|
return reply({ ended: true });
|
|
});
|
|
const transport = { capture: async () => new Mic(), join: async (_u: string, _t: string, on: RoomEvents) => { const r = new Room(); r.on = on; rooms.push(r); return r; } };
|
|
const c = new VoiceController({ transport: async () => transport, onView: v => views.push(v), onRecord: () => {}, onSpoke: () => {}, fetch: fetch as unknown as typeof fetch, secure: () => true, agentWaitMs: 1000 });
|
|
return { c, views, rooms, voices, gates, view: () => views.at(-1)! };
|
|
}
|
|
|
|
describe('本次通话声音 comes from the session answer and stays for the call', () => {
|
|
it('shown from the granted room, unchanged through the call, gone when it ends', async () => {
|
|
const r = rig(); r.voices[0] = 'cg-1a2b3c4d';
|
|
await r.c.start();
|
|
expect(r.views.find(v => v.phase === 'opening')?.voice).toBeNull();
|
|
expect(r.view()).toMatchObject({ phase: 'joining', voice: { id: 'cg-1a2b3c4d' } });
|
|
r.rooms[0].on.agentJoined(); r.rooms[0].on.agentState('speaking'); r.rooms[0].on.agentState('listening');
|
|
expect(r.views.filter(v => v.phase !== 'opening').every(v => v.voice?.id === 'cg-1a2b3c4d')).toBe(true);
|
|
await r.c.end();
|
|
expect(r.view()).toMatchObject({ phase: 'off', voice: null });
|
|
});
|
|
it('a missing or odd field is "not said", never a guess', () => {
|
|
expect(callVoiceOf({})).toEqual({ id: null });
|
|
expect(callVoiceOf({ voice: '' })).toEqual({ id: null });
|
|
expect(callVoiceOf({ voice: 42 })).toEqual({ id: null });
|
|
expect(callVoiceOf({ voice: '<b>x</b>' })).toEqual({ id: null });
|
|
expect(callVoiceOf({ voice: 'default' })).toEqual({ id: 'default' });
|
|
});
|
|
it('an older call answering late never overwrites the newer call', async () => {
|
|
const r = rig(); r.voices[0] = 'old-voice'; r.voices[1] = 'cg-00000002'; r.gates[0] = gate();
|
|
const first = r.c.start(); await flush();
|
|
await r.c.start();
|
|
expect(r.view()).toMatchObject({ phase: 'joining', voice: { id: 'cg-00000002' } });
|
|
r.gates[0]!.open(); await first; await flush();
|
|
expect(r.view()).toMatchObject({ phase: 'joining', voice: { id: 'cg-00000002' } });
|
|
expect(r.views.some(v => v.voice?.id === 'old-voice')).toBe(false);
|
|
});
|
|
it('a failure after the room clears the voice with the call', async () => {
|
|
const r = rig(); r.voices[0] = 'rain';
|
|
await r.c.start(); r.rooms[0].on.agentJoined();
|
|
r.rooms[0].on.dropped(); await flush();
|
|
expect(r.view()).toMatchObject({ phase: 'off', voice: null });
|
|
});
|
|
it('names: its own label for that id only, the id otherwise, default and unknown in words', () => {
|
|
expect(callVoiceName('cg-1', { id: 'cg-1', label: '轻一点的她' })).toBe('轻一点的她');
|
|
expect(callVoiceName('cg-2', { id: 'cg-1', label: '轻一点的她' })).toBe('cg-2');
|
|
expect(callVoiceName('default', null)).toBe('默认声音');
|
|
expect(callVoiceName(null, null)).toBe('声音未说明');
|
|
});
|
|
});
|
|
|
|
describe('a registration with no clear answer says to look before registering again', () => {
|
|
const wav = new Blob([new Uint8Array(64)], { type: 'audio/wav' }), form = { label: 'x', text: '你好', allowAsr: false };
|
|
const attempt = async (answer: () => Response | Promise<Response>) => {
|
|
try { await registerVoice(wav, form, signal(), (async () => answer()) as unknown as typeof fetch); } catch (e) { return e as VoiceError; }
|
|
throw new Error('expected a failure');
|
|
};
|
|
it('500 / 503 / a dropped answer / an unreadable success may have been filed', async () => {
|
|
for (const e of [await attempt(() => reply({ detail: 'Internal Server Error' }, 500)), await attempt(() => reply({ detail: '音色登记服务这会儿不在,稍后再试试。' }, 503)), await attempt(() => { throw new TypeError('network'); }), await attempt(() => reply('', 201))]) {
|
|
expect(e).toBeInstanceOf(VoiceError);
|
|
expect(e.uncertain).toBe(true);
|
|
}
|
|
expect((await attempt(() => reply({ detail: '音色登记服务这会儿不在,稍后再试试。' }, 503))).message).toContain('音色登记服务');
|
|
});
|
|
it('a clear refusal (4xx) or a request never sent is not "maybe filed"', async () => {
|
|
expect((await attempt(() => reply({ detail: '参考音频太短(至少 2 秒),请录 5–20 秒。' }, 422))).uncertain).toBe(false);
|
|
expect((await attempt(() => reply({ detail: '还没有创建真实伴侣,语音也不会开始。' }, 409))).uncertain).toBe(false);
|
|
vi.stubGlobal('navigator', { onLine: false });
|
|
const offline = await attempt(() => reply({}, 201));
|
|
expect(offline.message).toBe(SAY.offline);
|
|
expect(offline.uncertain).toBe(false);
|
|
});
|
|
it('the advice points at refreshing the list and the numbered entries', () => {
|
|
expect(SAY.maybeRegistered).toContain('刷新列表');
|
|
expect(SAY.maybeRegistered).toContain('cg-');
|
|
expect(SAY.maybeRegistered).toContain('不用再登记');
|
|
});
|
|
it('an entry without local metadata is recognised as id-only', () => {
|
|
const v = (x: Partial<CustomVoice>): CustomVoice => ({ id: 'cg-9', label: 'cg-9', source: 'custom', selected: false, previewed: false, registered_at: null, ...x });
|
|
expect(idOnly(v({}))).toBe(true);
|
|
expect(idOnly(v({ label: '轻一点的她', registered_at: 1 }))).toBe(false);
|
|
expect(idOnly(v({ id: 'rain', label: 'rain', source: 'builtin' }))).toBe(false);
|
|
});
|
|
});
|