HEL-900: preserve visual director custom voice frontend unchanged
Co-authored-by: multica-agent <github@multica.ai>
This commit is contained in:
@@ -0,0 +1,201 @@
|
||||
// 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();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,120 @@
|
||||
// HEL-900 isolated contract mock for her own voice (docs/voice-custom-contract-HEL899.md §2). Serves web/dist plus the
|
||||
// minimum real-app API (companion, messages, health) and the five custom-voice endpoints, answering exactly as the
|
||||
// HEL-899 router does. Synthetic data only: no voice panel, no ASR, no TTS, no network beyond 127.0.0.1. The preview is
|
||||
// a generated tone wrapped as 24 kHz mono WAV, not a voice. Usage: node tests/hel900_mock.mjs <port>.
|
||||
// Control GETs: /__mode?list=ok|off|none|down, /__fail?register=&preview=&apply= (status code, `net`, `bad`, `slow`),
|
||||
// /__reset, /__log (drains), /__uploads, /__pid.
|
||||
import { createServer } from 'node:http';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { extname, join, normalize } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const dist = fileURLToPath(new URL('../dist/', import.meta.url));
|
||||
const port = Number(process.argv[2] || 8900);
|
||||
const identity = { id: '1', name: '栖', birth: '2000-03-14', hour: '子', relation: '朋友', nickname: '', boundary: '', color: { pillars: { year: '庚辰', month: '己卯', day: '丙午', hour: '戊子' }, traits: '合成测试档案' } };
|
||||
const BUILTIN = ['bailu', 'bajie', 'default', 'female_soft', 'haimianbaobao', 'jiaojiao', 'male_warm', 'nezha', 'rain', 'sunwukong', 'xiaoyun'];
|
||||
const log = [], uploads = [], gaveUp = [];
|
||||
let mode = 'ok', fail = {}, custom = new Map(), previewed = new Set(), selection = { voice: null, label: '', updated_at: null }, made = 0;
|
||||
const reset = () => { mode = 'ok'; fail = {}; custom = new Map(); previewed = new Set(); selection = { voice: null, label: '', updated_at: null }; made = 0; log.splice(0); uploads.splice(0); };
|
||||
const send = (res, status, body, type = 'application/json; charset=utf-8') => { res.writeHead(status, { 'Content-Type': type, 'Cache-Control': 'no-store' }); res.end(typeof body === 'string' || Buffer.isBuffer(body) ? body : JSON.stringify(body)); };
|
||||
const sleep = ms => new Promise(r => setTimeout(r, ms));
|
||||
const body = async req => { const parts = []; for await (const c of req) parts.push(c); return Buffer.concat(parts); };
|
||||
function wavInfo(b) {
|
||||
if (b.length < 44 || b.toString('ascii', 0, 4) !== 'RIFF' || b.toString('ascii', 8, 12) !== 'WAVE') return null;
|
||||
let at = 12, fmt = null;
|
||||
while (at + 8 <= b.length) {
|
||||
const id = b.toString('ascii', at, at + 4), size = b.readUInt32LE(at + 4);
|
||||
if (id === 'fmt ') fmt = { channels: b.readUInt16LE(at + 10), rate: b.readUInt32LE(at + 12), bits: b.readUInt16LE(at + 22) };
|
||||
if (id === 'data') return fmt && { ...fmt, seconds: Math.min(size, b.length - at - 8) / (fmt.rate * fmt.channels * fmt.bits / 8) };
|
||||
at += 8 + size + (size & 1);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
function tone(seconds = 1.6, rate = 24000) {
|
||||
const n = Math.round(seconds * rate), b = Buffer.alloc(44 + n * 2);
|
||||
b.write('RIFF', 0); b.writeUInt32LE(36 + n * 2, 4); b.write('WAVE', 8); b.write('fmt ', 12); b.writeUInt32LE(16, 16); b.writeUInt16LE(1, 20); b.writeUInt16LE(1, 22);
|
||||
b.writeUInt32LE(rate, 24); b.writeUInt32LE(rate * 2, 28); b.writeUInt16LE(2, 32); b.writeUInt16LE(16, 34); b.write('data', 36); b.writeUInt32LE(n * 2, 40);
|
||||
for (let i = 0; i < n; i++) b.writeInt16LE(Math.round(Math.sin(i / 9) * 6000 * Math.min(1, i / 2000, (n - i) / 2000)), 44 + i * 2);
|
||||
return b;
|
||||
}
|
||||
const known = id => BUILTIN.includes(id) || custom.has(id);
|
||||
const item = id => { const r = custom.get(id); return { id, label: r ? r.label : id, source: id.startsWith('cg-') ? 'custom' : 'builtin', selected: selection.voice === id, previewed: previewed.has(id), registered_at: r ? r.registered_at : null, prompt_text: r ? r.prompt_text : null, prompt_wav: r ? `/opt/voice-agent/cosyvoice/voice_samples/${id}.wav` : null }; };
|
||||
// A failure set with /__fail applies once, then the endpoint behaves again (a retry can succeed).
|
||||
const take = kind => { const f = fail[kind]; delete fail[kind]; return f; };
|
||||
const failed = async (res, f, detail) => {
|
||||
if (f === 'net') { res.destroy(); return true; }
|
||||
if (/^\d+$/.test(String(f))) { send(res, Number(f), { detail }); return true; }
|
||||
return false;
|
||||
};
|
||||
|
||||
// A request the page aborts (leaving, switching voice) must not take the mock down with it.
|
||||
const handle = async (req, res) => {
|
||||
const url = new URL(req.url, 'http://x'), p = url.pathname;
|
||||
if (p.startsWith('/api/')) log.push(`${req.method} ${p}${url.search}`);
|
||||
if (p === '/__pid') return send(res, 200, { pid: process.pid, mock: 'hel900' });
|
||||
if (p === '/__log') return send(res, 200, log.splice(0));
|
||||
if (p === '/__uploads') return send(res, 200, uploads);
|
||||
if (p === '/__gaveup') return send(res, 200, gaveUp);
|
||||
if (p === '/__reset') { reset(); return send(res, 200, { ok: true }); }
|
||||
if (p === '/__mode') { mode = url.searchParams.get('list') || 'ok'; return send(res, 200, { mode }); }
|
||||
if (p === '/__fail') { fail = Object.fromEntries(url.searchParams); return send(res, 200, fail); }
|
||||
if (p === '/__state') return send(res, 200, { selection, previewed: [...previewed], custom: [...custom.keys()] });
|
||||
if (p === '/api/health') return send(res, 200, { ok: true, epoch: 3, llm: { ok: true, model: 'mock' }, backend: { life: true, persona: true, receipt: true, web_connected: true }, life_runtime: { state: 'running', timezone: 'Asia/Shanghai', budget_warning: false, budget_stopped: false, last: null }, capabilities: { text: true, proactive: true, voice: true, memory: true } });
|
||||
if (p === '/api/companion') return send(res, 200, identity);
|
||||
if (p === '/api/messages') return send(res, 200, { messages: [], next_before: null, epoch: 3 });
|
||||
if (p === '/api/persona') return send(res, 200, { state: 'ready', interpretation: null, seeds: [], growth: [] });
|
||||
if (p === '/api/life' || p === '/api/memories') return send(res, 200, { events: [], memories: [], next_before: null, epoch: 3 });
|
||||
if (p === '/api/voice/status') return send(res, 200, { configured: true, tts_ok: true, agent_name: 'cybergril-voice-agent', voice: true });
|
||||
|
||||
if (p === '/api/voice/voices' && req.method === 'GET') {
|
||||
if (mode === 'none') return send(res, 404, { detail: 'Not Found' });
|
||||
if (mode === 'off') return send(res, 200, { configured: false, voices: [], selection: null });
|
||||
if (mode === 'down') return send(res, 503, { detail: '音色登记服务这会儿不在,稍后再试试。' });
|
||||
return send(res, 200, { configured: true, voices: [...BUILTIN, ...custom.keys()].map(item), selection: { ...selection } });
|
||||
}
|
||||
if (p === '/api/voice/voices' && req.method === 'POST') {
|
||||
const data = await body(req), q = url.searchParams, info = wavInfo(data);
|
||||
uploads.push({ type: req.headers['content-type'], bytes: data.length, magic: data.toString('ascii', 0, 4), wave: data.toString('ascii', 8, 12), info, label: q.get('label'), prompt_text: q.get('prompt_text'), allow_asr: q.get('allow_asr') });
|
||||
const f = take('register');
|
||||
if (f === 'slow') await sleep(2500);
|
||||
else if (await failed(res, f, f === '503' || f === 503 ? '音色登记服务这会儿不在,稍后再试。' : '登记没有成功。')) return;
|
||||
if (!info) return send(res, 422, { detail: '只支持 WAV 格式的参考音频。' });
|
||||
if (data.length > 15 * 1024 * 1024) return send(res, 422, { detail: '文件过大(>15MB),请录 5–20 秒的一段。' });
|
||||
if (info.seconds < 2) return send(res, 422, { detail: '参考音频太短(至少 2 秒),请录 5–20 秒。' });
|
||||
const text = (q.get('prompt_text') || '').trim(), asr = q.get('allow_asr') === 'true';
|
||||
if (!text && !asr) return send(res, 422, { detail: '请填写这段音频的参考文字,或明确选择让系统转写(会用到语音识别)。' });
|
||||
const id = `cg-${(0x9f2c1a70 + ++made).toString(16)}`, label = (q.get('label') || '').trim() || id;
|
||||
const record = { id, label, prompt_text: text || '(模拟转写)今天天气很好,我们出去走走吧。', prompt_text_source: text ? 'user' : 'asr', prompt_wav: `/opt/voice-agent/cosyvoice/voice_samples/${id}.wav`, registered_at: Date.now() };
|
||||
custom.set(id, record);
|
||||
return send(res, 201, record);
|
||||
}
|
||||
if (p === '/api/voice/preview' && req.method === 'POST') {
|
||||
const { voice, text } = JSON.parse((await body(req)).toString() || '{}');
|
||||
log.push(` preview ${voice} ${text ? `"${text}"` : '(default)'}`);
|
||||
const f = take('preview');
|
||||
if (!voice) return send(res, 422, { detail: '请指定要试听的声音。' });
|
||||
if (!known(voice)) return send(res, 404, { detail: '这个声音现在不在列表里。' });
|
||||
if (f === 'slow') await sleep(2500);
|
||||
else if (f === 'bad') return send(res, 200, '<html>not audio</html>', 'text/html');
|
||||
else if (await failed(res, f, '她的声音服务这会儿不在,稍后再试试。')) return;
|
||||
previewed.add(voice);
|
||||
return send(res, 200, tone(), 'audio/wav');
|
||||
}
|
||||
if (p === '/api/voice/selection' && req.method === 'GET') return send(res, 200, { ...selection });
|
||||
if (p === '/api/voice/selection' && req.method === 'POST') {
|
||||
const { voice } = JSON.parse((await body(req)).toString() || '{}');
|
||||
const f = take('apply');
|
||||
if (await failed(res, f, f === '409' ? '这个声音还没有试听过,先试听再给她用。' : '她的音色状态这会儿写不进,这次没有换成功。')) return;
|
||||
if (!known(voice)) return send(res, 404, { detail: '这个声音现在不在列表里。' });
|
||||
if (voice.startsWith('cg-') && !previewed.has(voice)) return send(res, 409, { detail: '这个声音还没有试听过,先试听再给她用。' });
|
||||
selection = { voice, label: custom.get(voice)?.label || voice, updated_at: Date.now() };
|
||||
return send(res, 200, { ...selection });
|
||||
}
|
||||
if (p.startsWith('/api/')) return send(res, 404, { detail: 'Not Found' });
|
||||
const file = normalize(join(dist, p === '/' ? 'index.html' : p));
|
||||
if (!file.startsWith(normalize(dist))) return send(res, 403, 'no', 'text/plain');
|
||||
try { send(res, 200, await readFile(file), { '.js': 'text/javascript', '.css': 'text/css', '.html': 'text/html; charset=utf-8', '.svg': 'image/svg+xml', '.png': 'image/png', '.jpg': 'image/jpeg', '.webp': 'image/webp' }[extname(file)] || 'application/octet-stream'); }
|
||||
catch { send(res, 200, await readFile(join(dist, 'index.html')), 'text/html; charset=utf-8'); }
|
||||
};
|
||||
createServer((req, res) => { handle(req, res).catch(e => { gaveUp.push(`${req.method} ${req.url}`); console.log(`client gave up: ${req.method} ${req.url} (${e.code || e.message})`); try { res.destroy(); } catch { /* gone */ } }); }).on('error', e => { console.error(`hel900 mock could not listen on ${port}: ${e.code || e.message}`); process.exit(2); })
|
||||
.listen(port, '127.0.0.1', () => console.log(`hel900 mock on ${port} pid ${process.pid}`));
|
||||
@@ -0,0 +1,208 @@
|
||||
// HEL-900 browser check: 她的声音 in settings — reference (file or recording) → fresh preview → apply. Drives headless
|
||||
// Edge over CDP against tests/hel900_mock.mjs; Chromium's fake audio device stands in for a microphone (a beep, not a
|
||||
// person), the preview is a generated tone. No voice panel, ASR, TTS or real clone is involved.
|
||||
// Usage: node tests/hel900_shots.mjs <edge.exe> <outDir> [port].
|
||||
import { spawn } from 'node:child_process';
|
||||
import { mkdirSync, writeFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { tmpdir } from 'node:os';
|
||||
|
||||
const [edge, out, portArg] = process.argv.slice(2);
|
||||
const port = Number(portArg || 8900), base = `http://127.0.0.1:${port}`, cdpPort = 9500;
|
||||
mkdirSync(out, { recursive: true });
|
||||
const profile = join(tmpdir(), `hel900-edge-${Date.now()}`);
|
||||
const browser = spawn(edge, ['--headless=new', `--remote-debugging-port=${cdpPort}`, `--user-data-dir=${profile}`, '--no-first-run', '--hide-scrollbars', '--force-color-profile=srgb', '--use-fake-device-for-media-stream', '--use-fake-ui-for-media-stream', '--autoplay-policy=no-user-gesture-required', 'about:blank'], { stdio: 'ignore' });
|
||||
const sleep = ms => new Promise(r => setTimeout(r, ms));
|
||||
let targets;
|
||||
for (let i = 0; i < 60 && !targets; i++) { try { targets = await (await fetch(`http://127.0.0.1:${cdpPort}/json`)).json(); } catch { await sleep(250); } }
|
||||
const ws = new WebSocket(targets.find(t => t.type === 'page').webSocketDebuggerUrl);
|
||||
await new Promise(r => ws.addEventListener('open', r, { once: true }));
|
||||
let id = 0; const waiting = new Map();
|
||||
ws.addEventListener('message', ({ data }) => { const m = JSON.parse(data); if (m.id && waiting.has(m.id)) { const { ok, ko } = waiting.get(m.id); waiting.delete(m.id); m.error ? ko(new Error(m.error.message)) : ok(m.result); } });
|
||||
const cdp = (method, params = {}) => new Promise((ok, ko) => { const n = ++id; waiting.set(n, { ok, ko }); ws.send(JSON.stringify({ id: n, method, params })); });
|
||||
const js = async expr => { const r = await cdp('Runtime.evaluate', { expression: expr, returnByValue: true, awaitPromise: true }); if (r.exceptionDetails) throw new Error(r.exceptionDetails.exception?.description || 'js error'); return r.result.value; };
|
||||
const results = [];
|
||||
const check = (name, ok, detail = '') => { results.push(ok); console.log(`${ok ? 'PASS' : 'FAIL'} ${name}${detail && !ok ? ` — ${String(detail).slice(0, 300)}` : ''}`); };
|
||||
const ctl = async path => (await fetch(`${base}${path}`)).json();
|
||||
const shot = async name => { const { data } = await cdp('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false }); writeFileSync(join(out, `${name}.png`), Buffer.from(data, 'base64')); };
|
||||
const click = async (selector, text = '') => js(`(() => { const el = [...document.querySelectorAll(${JSON.stringify(selector)})].find(e => e.offsetParent !== null && e.textContent.includes(${JSON.stringify(text)})); if (!el) return false; el.scrollIntoView({ block: 'center' }); el.click(); return true; })()`);
|
||||
const exists = sel => js(`(() => { const e = document.querySelector(${JSON.stringify(sel)}); return !!e && e.offsetParent !== null; })()`);
|
||||
const text = sel => js(`[...document.querySelectorAll(${JSON.stringify(sel)})].filter(e => e.offsetParent !== null).map(e => e.innerText).join('\\n')`);
|
||||
const disabled = (sel, label) => js(`(() => { const el = [...document.querySelectorAll(${JSON.stringify(sel)})].find(e => e.offsetParent !== null && e.textContent.includes(${JSON.stringify(label)})); return el ? el.disabled : null; })()`);
|
||||
const until = async (fn, ms = 6000) => { const end = Date.now() + ms; while (Date.now() < end) { if (await fn()) return true; await sleep(100); } return false; };
|
||||
const fill = (sel, value) => js(`(() => { const el = [...document.querySelectorAll(${JSON.stringify(sel)})].find(e => e.offsetParent !== null); if (!el) return false; const proto = el.tagName === 'TEXTAREA' ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype; Object.getOwnPropertyDescriptor(proto, 'value').set.call(el, ${JSON.stringify(value)}); el.dispatchEvent(new Event('input', { bubbles: true })); return true; })()`);
|
||||
const live = () => js('window.__live()');
|
||||
const status = () => text('.voice-sec .status');
|
||||
const views = { desktop: { width: 1440, height: 900, deviceScaleFactor: 1, mobile: false }, phone: { width: 390, height: 844, deviceScaleFactor: 2, mobile: true } };
|
||||
async function view(v) { await cdp('Emulation.setDeviceMetricsOverride', views[v]); await cdp('Emulation.setTouchEmulationEnabled', { enabled: views[v].mobile, maxTouchPoints: 5 }); }
|
||||
// Counts every microphone track the page ever got, so "released" means readyState 'ended' on all of them.
|
||||
const PROBE = `(() => { const md = navigator.mediaDevices; if (!md) return; const orig = md.getUserMedia.bind(md); window.__tracks = []; window.__gum = []; window.__deny = '';
|
||||
md.getUserMedia = async c => { window.__gum.push(JSON.stringify(c)); if (window.__deny) throw new DOMException('denied', window.__deny); const s = await orig(c); s.getTracks().forEach(t => window.__tracks.push(t)); return s; };
|
||||
window.__live = () => window.__tracks.filter(t => t.readyState === 'live').length; })();`;
|
||||
async function boot(theme) {
|
||||
await ctl('/__reset');
|
||||
await cdp('Page.navigate', { url: `${base}/` }); await sleep(500);
|
||||
await js(`localStorage.setItem('cg.theme', ${JSON.stringify(theme)}); sessionStorage.clear(); true`);
|
||||
await cdp('Page.navigate', { url: `${base}/` }); await sleep(1500);
|
||||
}
|
||||
async function openVoice() {
|
||||
await click('.nav-item', '设置'); await sleep(700);
|
||||
await click('.snav button', '她的声音');
|
||||
return until(() => exists('.voice-sec') || exists('.pane-manage .off-card'), 6000);
|
||||
}
|
||||
async function record(seconds = 3.5) {
|
||||
await click('.voice-sec .seg button', '现在录一段');
|
||||
await click('.voice-sec .rec button', '开始录音');
|
||||
await until(async () => (await text('.voice-sec .rec')).includes('正在录音'));
|
||||
await sleep(seconds * 1000);
|
||||
}
|
||||
async function stopRecording() { await click('.voice-sec .rec button', '停止'); return until(() => exists('.voice-sec .take .pill'), 8000); }
|
||||
const wav = (seconds, rate = 22050, channels = 2) => {
|
||||
const n = Math.round(seconds * rate), b = Buffer.alloc(44 + n * 2 * channels);
|
||||
b.write('RIFF', 0); b.writeUInt32LE(36 + n * 2 * channels, 4); b.write('WAVE', 8); b.write('fmt ', 12); b.writeUInt32LE(16, 16); b.writeUInt16LE(1, 20); b.writeUInt16LE(channels, 22);
|
||||
b.writeUInt32LE(rate, 24); b.writeUInt32LE(rate * 2 * channels, 28); b.writeUInt16LE(2 * channels, 32); b.writeUInt16LE(16, 34); b.write('data', 36); b.writeUInt32LE(n * 2 * channels, 40);
|
||||
for (let i = 0; i < n * channels; i++) b.writeInt16LE(Math.round(Math.sin(i / 11) * 5000), 44 + i * 2);
|
||||
return b;
|
||||
};
|
||||
const files = join(tmpdir(), `hel900-files-${Date.now()}`); mkdirSync(files, { recursive: true });
|
||||
writeFileSync(join(files, 'reference-22k-stereo.wav'), wav(6));
|
||||
writeFileSync(join(files, 'renamed-webm.wav'), Buffer.concat([Buffer.from([0x1a, 0x45, 0xdf, 0xa3]), Buffer.alloc(4000, 7)]));
|
||||
async function upload(name) {
|
||||
const { result } = await cdp('Runtime.evaluate', { expression: `[...document.querySelectorAll('.voice-sec input[type=file]')].find(e => e.offsetParent !== null)` });
|
||||
await cdp('DOM.setFileInputFiles', { files: [join(files, name)], objectId: result.objectId });
|
||||
}
|
||||
|
||||
await cdp('Page.enable'); await cdp('Runtime.enable'); await cdp('Network.enable'); await cdp('DOM.enable');
|
||||
await cdp('Page.addScriptToEvaluateOnNewDocument', { source: PROBE });
|
||||
check('mock is this hel900 mock', (await ctl('/__pid')).mock === 'hel900');
|
||||
|
||||
// ── Main path, both themes × desktop/phone ──
|
||||
for (const [theme, v] of [['moon', 'desktop'], ['fog', 'desktop'], ['moon', 'phone'], ['fog', 'phone']]) {
|
||||
const tag = `${theme}-${v}`;
|
||||
await view(v); await boot(theme);
|
||||
check(`${tag}: no microphone before anything is tapped`, (await js('window.__gum.length')) === 0);
|
||||
await openVoice(); await until(() => exists('.voice-sec .voice-list'));
|
||||
const first = await ctl('/__log');
|
||||
check(`${tag}: opening the section only reads the list`, first.every(l => !l.includes('POST')) && first.some(l => l.includes('GET /api/voice/voices')), first.join(' | '));
|
||||
check(`${tag}: says when a change takes effect`, (await text('.voice-sec .kv')).includes('下一次通话'));
|
||||
await shot(`${tag}-01-section`);
|
||||
|
||||
await record(3.2);
|
||||
check(`${tag}: recording state is explicit and the microphone is live`, (await live()) === 1 && (await text('.voice-sec .rec')).includes('麦克风开着'));
|
||||
check(`${tag}: audio only, never the camera`, (await js('window.__gum.at(-1)')).includes('"video":false'));
|
||||
await shot(`${tag}-02-recording`);
|
||||
await sleep(800);
|
||||
check(`${tag}: stopping keeps the take and releases the microphone`, await stopRecording() && (await live()) === 0);
|
||||
check(`${tag}: the take is labelled as your reference, not her voice`, (await text('.voice-sec .take h4')).includes('不是栖的声音'));
|
||||
check(`${tag}: register needs reference text or an explicit transcription opt-in`, (await disabled('.voice-sec .take button', '登记这段声音')) === true);
|
||||
await fill('.voice-sec .take input.input', '轻一点的她'); await fill('.voice-sec .take textarea', '今天天气很好,我们出去走走吧。');
|
||||
await shot(`${tag}-03-take`);
|
||||
await click('.voice-sec .take button', '登记这段声音');
|
||||
await until(async () => (await text('.voice-sec .voice-list')).includes('轻一点的她'));
|
||||
const up = (await ctl('/__uploads')).at(-1);
|
||||
check(`${tag}: the upload is real PCM WAV (16 kHz mono 16-bit), raw body + query`, up && up.type === 'audio/wav' && up.magic === 'RIFF' && up.wave === 'WAVE' && up.info?.rate === 16000 && up.info?.channels === 1 && up.info?.bits === 16 && up.info.seconds >= 3 && up.allow_asr === 'false' && up.prompt_text === '今天天气很好,我们出去走走吧。', JSON.stringify(up));
|
||||
check(`${tag}: the new voice is chosen for a preview; apply waits for it`, (await text('.voice-sec .audition h4')).includes('轻一点的她') && (await disabled('.voice-sec .audition button', '给栖用这个声音')) === true);
|
||||
await shot(`${tag}-04-registered`);
|
||||
await click('.voice-sec .audition button', '生成试听');
|
||||
check(`${tag}: a fresh preview plays and only then can be applied`, await until(() => exists('.voice-sec .sample.ready')) && (await disabled('.voice-sec .audition button', '给栖用这个声音')) === false);
|
||||
check(`${tag}: the preview is labelled as her synthesized voice, not your reference`, (await text('.voice-sec .sample figcaption')).includes('不是参考原声'));
|
||||
check(`${tag}: the preview actually plays in the page`, await until(() => js(`(() => { const a = document.querySelector('.voice-sec .sample audio'); return !!a && (a.currentTime > 0 || !a.paused); })()`)));
|
||||
await sleep(600);
|
||||
await shot(`${tag}-05-preview`);
|
||||
await click('.voice-sec .audition button', '给栖用这个声音');
|
||||
await until(async () => (await text('.voice-sec .kv')).includes('轻一点的她'));
|
||||
const st = await ctl('/__state');
|
||||
check(`${tag}: applied — current voice shown, from the next call`, st.selection.voice?.startsWith('cg-') && (await text('.voice-sec .audition')).includes('她现在就用这个') && (await status()).includes('已经接通的通话不会中途换声'), await status());
|
||||
await shot(`${tag}-06-applied`);
|
||||
check(`${tag}: no object URL or microphone left after closing settings`, await (async () => { await click('.pane-manage button[aria-label="关闭设置"]'); await sleep(400); return (await live()) === 0 && !(await exists('.voice-sec')); })());
|
||||
}
|
||||
|
||||
// ── Edge cases (desktop, moon; the phone fog run repeats the recording ones) ──
|
||||
await view('desktop'); await boot('moon'); await openVoice(); await until(() => exists('.voice-sec .voice-list'));
|
||||
// File path: a real WAV from disk (22 kHz stereo) is re-encoded; a WebM renamed .wav is refused before upload.
|
||||
await upload('renamed-webm.wav');
|
||||
check('file: a renamed non-WAV is refused in the browser, nothing uploaded', await until(async () => (await status()).includes('解不开')) && (await ctl('/__uploads')).length === 0, await status());
|
||||
await upload('reference-22k-stereo.wav');
|
||||
check('file: a 22 kHz stereo WAV becomes 16 kHz mono', await until(() => exists('.voice-sec .take .pill')) && (await text('.voice-sec .take')).includes('16kHz 单声道'));
|
||||
await shot('edge-01-file-take');
|
||||
// Explicit transcription opt-in.
|
||||
await click('.voice-sec .take .switch-row input');
|
||||
check('asr: opting in enables register with empty text', (await disabled('.voice-sec .take button', '登记这段声音')) === false);
|
||||
// Offline: nothing is sent; the take and the form stay.
|
||||
await cdp('Network.emulateNetworkConditions', { offline: true, latency: 0, downloadThroughput: -1, uploadThroughput: -1 });
|
||||
await click('.voice-sec .take button', '登记这段声音');
|
||||
check('offline: says so, keeps the take, sends nothing', await until(async () => (await status()).includes('网络断开')) && (await exists('.voice-sec .take .pill')) && (await ctl('/__uploads')).length === 0, await status());
|
||||
await shot('edge-02-offline');
|
||||
await cdp('Network.emulateNetworkConditions', { offline: false, latency: 0, downloadThroughput: -1, uploadThroughput: -1 });
|
||||
// Server down once (503): message, take kept; the retry succeeds and carries allow_asr=true.
|
||||
await ctl('/__fail?register=503');
|
||||
await click('.voice-sec .take button', '登记这段声音');
|
||||
check('503: honest message, take still there for a retry', await until(async () => (await status()).includes('音色登记服务')) && await exists('.voice-sec .take .pill'), await status());
|
||||
await shot('edge-03-register-503');
|
||||
await js(`(() => { const b = [...document.querySelectorAll('.voice-sec .take button')].find(e => e.textContent.includes('登记这段声音')); b.click(); b.click(); return true; })()`);
|
||||
await until(async () => (await text('.voice-sec .voice-list')).includes('cg-'));
|
||||
const ups = await ctl('/__uploads');
|
||||
check('double tap registers once; transcription only on explicit opt-in', ups.length === 2 && ups.at(-1).allow_asr === 'true' && ups.at(-1).prompt_text === '', JSON.stringify(ups.map(u => u.allow_asr)));
|
||||
check('asr: the transcribed text is shown back', (await status()).includes('服务器转写'), await status());
|
||||
// Late preview: A is slow, you switch to B; A's sample never shows up as B's (nor at all).
|
||||
await ctl('/__fail?preview=slow');
|
||||
await click('.voice-sec .audition button', '生成试听');
|
||||
await sleep(300);
|
||||
await click('.voice-sec details.voice-builtin summary'); await sleep(200);
|
||||
await click('.voice-sec .voice-builtin button', 'rain');
|
||||
await sleep(3000);
|
||||
check('late: an older preview arriving after switching is dropped', (await text('.voice-sec .audition h4')).includes('rain') && !(await exists('.voice-sec .sample')) && (await disabled('.voice-sec .audition button', '给栖用这个声音')) === true);
|
||||
await shot('edge-04-late-dropped');
|
||||
// A preview that is not audio is refused, never played.
|
||||
await ctl('/__fail?preview=bad');
|
||||
await click('.voice-sec .audition button', '生成试听');
|
||||
check('bad preview: refused, nothing playable shown', await until(async () => (await status()).includes('不是可播放')) && !(await exists('.voice-sec .sample .pill')), await status());
|
||||
// TTS down.
|
||||
await ctl('/__fail?preview=503');
|
||||
await click('.voice-sec .audition button', '生成试听');
|
||||
check('preview 503: honest message', await until(async () => (await status()).includes('声音服务这会儿不在')), await status());
|
||||
// 409 from the server even after a preview here (another device, a restart): said plainly, nothing changes.
|
||||
await click('.voice-sec .audition button', '生成试听'); await until(() => exists('.voice-sec .sample.ready'));
|
||||
await ctl('/__fail?apply=409');
|
||||
await click('.voice-sec .audition button', '给栖用这个声音');
|
||||
check('apply 409: message, selection unchanged', await until(async () => (await status()).includes('还没有试听过')) && (await ctl('/__state')).selection.voice === null, await status());
|
||||
await shot('edge-05-apply-409');
|
||||
// Recording: cancel, leave mid-take, denied permission.
|
||||
await record(1.2);
|
||||
await click('.voice-sec .rec button', '取消');
|
||||
check('cancel: microphone released, take discarded', (await live()) === 0 && (await status()).includes('已取消'));
|
||||
await record(1.2);
|
||||
await click('.snav button', '城市'); await sleep(300);
|
||||
check('leaving the section mid-take releases the microphone', (await live()) === 0);
|
||||
await click('.snav button', '她的声音'); await sleep(300);
|
||||
check('coming back says the take was dropped', (await status()).includes('离开了这里'), await status());
|
||||
await js(`window.__deny = 'NotAllowedError'; true`);
|
||||
await click('.voice-sec .rec button', '开始录音');
|
||||
check('denied: says why, nothing recording', await until(async () => (await status()).includes('没有拿到麦克风权限')) && (await live()) === 0, await status());
|
||||
await js(`window.__deny = ''; true`);
|
||||
await shot('edge-06-denied');
|
||||
// Unsaved take: closing settings asks first.
|
||||
await record(2.6); await stopRecording();
|
||||
await click('.pane-manage button[aria-label="关闭设置"]');
|
||||
check('an unregistered take guards leaving', await until(() => exists('.modal.open')) && (await text('.modal.open')).includes('未保存'));
|
||||
await shot('edge-07-leave-guard');
|
||||
await click('.modal.open button', '放弃修改并离开'); await sleep(400);
|
||||
check('after leaving, nothing of the section remains', (await live()) === 0 && !(await exists('.voice-sec')));
|
||||
// Server states for the list.
|
||||
for (const [mode, words, name] of [['off', '还没有在这台服务上配置', 'unconfigured'], ['none', '还没有自定义声音的通路', 'no-route'], ['down', '一时没读出来', 'panel-down']]) {
|
||||
await ctl(`/__mode?list=${mode}`);
|
||||
await cdp('Page.navigate', { url: `${base}/` }); await sleep(1300); await openVoice();
|
||||
check(`list ${name}: honest card, no microphone, no 'adjustable' tag`, (await text('.pane-manage .sec-body')).includes(words) && (await js('window.__gum.length')) === 0 && !(await text('.pane-manage .sec-h')).includes('可以调整'));
|
||||
await shot(`edge-08-${name}`);
|
||||
}
|
||||
await ctl('/__mode?list=ok');
|
||||
await click('.pane-manage .off-card button', '再试一次');
|
||||
check('panel back: retry shows the list', await until(() => exists('.voice-sec .voice-list')));
|
||||
for (const theme of ['moon', 'fog']) { await view('phone'); await boot(theme); await openVoice(); await until(() => exists('.voice-sec .voice-list')); await ctl('/__mode?list=down'); await cdp('Page.navigate', { url: `${base}/` }); await sleep(1300); await openVoice(); await shot(`phone-${theme}-panel-down`); await ctl('/__mode?list=ok'); }
|
||||
|
||||
const gave = await ctl('/__gaveup');
|
||||
check('no registration or apply was ever cut off by the page itself', !gave.some(l => l.startsWith('POST /api/voice/voices') || l.startsWith('POST /api/voice/selection')), gave.join(' | '));
|
||||
const passed = results.filter(Boolean).length;
|
||||
console.log(`\n${passed}/${results.length} passed`);
|
||||
browser.kill();
|
||||
process.exit(passed === results.length ? 0 : 1);
|
||||
Reference in New Issue
Block a user