HEL-903: preserve visual author voice status, call voice and recovery fixes

Co-authored-by: multica-agent <github@multica.ai>
This commit is contained in:
总管
2026-10-28 01:10:48 +08:00
co-authored by multica-agent
parent b09a907747
commit 51669aae6d
11 changed files with 656 additions and 24 deletions
+1 -1
View File
@@ -62,7 +62,7 @@ describe('her worker leaves while the room stays open (real adapter, SDK event n
room.say({ v: 2, seq: 3, kind: 'assistant_interim', role: 'assistant', text: '在听呢。', speech_id: 'sp' });
expect(r.view()).toMatchObject({ phase: 'thinking', her: { speech: 'sp', text: '在听呢。', state: 'open' } });
room.leave(worker.identity); await flush();
expect(r.view()).toEqual({ phase: 'off', heard: '', spoken: '', her: null, notice: WORDS.agentLeft, blocked: false });
expect(r.view()).toEqual({ phase: 'off', heard: '', spoken: '', her: null, notice: WORDS.agentLeft, blocked: false, voice: null });
expect(mics[0].stopped).toBeGreaterThan(0);
expect(room.disconnects).toBe(1);
expect(deletes(r.calls)).toEqual(['DELETE /api/voice/session/s1']);
+130
View File
@@ -0,0 +1,130 @@
// HEL-903 isolated contract mock: the HEL-878 voice session (fake LiveKit via tests/fake-livekit.js) and the HEL-900
// custom-voice endpoints in one process, answering as src/cybergril/voice/router.py does at b09a907 — the session
// answer carries `voice` (selection if still listed, else "default"), /api/voice/status carries configured/tts_ok.
// Adds the failures this card handles: a registration the panel filed while the answer was lost (500 / dropped).
// Synthetic data only: no voice panel, ASR, TTS, LiveKit or network beyond 127.0.0.1.
// Usage: node tests/hel903_mock.mjs <port>. Control GETs: /__status?mode=ok|down|off|none|500|net,
// /__session-voice?v=<id>|omit|(empty: as the server), /__fail?register=503|500|net|commit500|commitnet,
// /__select?voice=<id> (another device applies a voice), /__reset, /__log (drains), /__uploads, /__state, /__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)), fake = fileURLToPath(new URL('./fake-livekit.js', import.meta.url));
const port = Number(process.argv[2] || 8903);
const T0 = Date.UTC(2026, 9, 27, 12, 0);
const identity = { id: '1', name: '栖', birth: '2000-03-14', hour: '子', relation: '朋友', nickname: '', boundary: '', color: { pillars: { year: '庚辰', month: '己卯', day: '丙午', hour: '戊子' }, traits: '合成测试档案' } };
const BUILTIN = ['bailu', 'default', 'female_soft', 'male_warm', 'rain', 'xiaoyun'];
const log = [], uploads = [], sessions = new Map();
let statusMode = 'ok', sessionVoice = '', fail = {}, custom = new Map(), orphans = new Set(), previewed = new Set(), selection = { voice: null, label: '', updated_at: null }, made = 0, rooms = 0;
const reset = () => { statusMode = 'ok'; sessionVoice = ''; fail = {}; custom = new Map(); orphans = new Set(); previewed = new Set(); selection = { voice: null, label: '', updated_at: null }; made = 0; log.splice(0); uploads.splice(0); sessions.clear(); };
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 listed = () => [...BUILTIN, ...custom.keys(), ...orphans];
const known = id => listed().includes(id);
// An orphan is in the shared panel only: no CyberGril metadata, so the router lists it with label = 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 ? r.prompt_wav : null }; };
const take = kind => { const f = fail[kind]; delete fail[kind]; return f; };
const newId = () => `cg-${(0x5e7a0000 + ++made).toString(16)}`;
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: 'hel903' });
if (p === '/__log') return send(res, 200, log.splice(0));
if (p === '/__uploads') return send(res, 200, uploads);
if (p === '/__reset') { reset(); return send(res, 200, { ok: true }); }
if (p === '/__status') { statusMode = url.searchParams.get('mode') || 'ok'; return send(res, 200, { statusMode }); }
if (p === '/__session-voice') { sessionVoice = url.searchParams.get('v') || ''; return send(res, 200, { sessionVoice }); }
if (p === '/__fail') { fail = Object.fromEntries(url.searchParams); return send(res, 200, fail); }
if (p === '/__select') { const v = url.searchParams.get('voice'); selection = { voice: v, label: custom.get(v)?.label || v, updated_at: Date.now() }; return send(res, 200, selection); }
if (p === '/__state') return send(res, 200, { selection, custom: [...custom.keys()], orphans: [...orphans], open: [...sessions.keys()], rooms });
if (p.startsWith('/vendor/livekit-client')) return send(res, 200, await readFile(fake), 'text/javascript');
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: false, memory: true } });
if (p === '/api/companion') return send(res, 200, identity);
if (p === '/api/messages') return send(res, 200, { messages: [{ id: 1, ts: T0, role: 'user', text: '今天下雨了吗?', turn_id: 't1', status: 'sent', lifeIds: [] }, { id: 2, ts: T0 + 6e4, role: 'companion', text: '下了一点,窗台上还湿着。', turn_id: 't1', status: 'sent', lifeIds: [] }], 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') {
if (statusMode === 'none') return send(res, 404, { detail: 'Not Found' });
if (statusMode === '500') return send(res, 500, 'Internal Server Error', 'text/plain');
if (statusMode === 'net') { res.destroy(); return; }
if (statusMode === 'off') return send(res, 200, { configured: false, tts_ok: false, agent_name: null, voice: false });
return send(res, 200, { configured: true, tts_ok: statusMode === 'ok', agent_name: 'cybergril-voice-agent', voice: false, livekit_url: 'wss://lk.invalid' });
}
if (p === '/api/voice/session' && req.method === 'POST') {
if (statusMode !== 'ok') return send(res, 503, { detail: '她的声音服务这会儿不在,稍后再试试。' });
await sleep(120);
// As _capture_voice: a still-listed selection, else "default"; captured once, at opening.
const captured = selection.voice && known(selection.voice) ? selection.voice : 'default';
const id = `sess-${++rooms}`; sessions.set(id, captured);
const grant = { url: 'wss://lk.invalid', token: `token-${id}`, room: `cg-voice-${rooms}`, session_id: id, agent_name: 'cybergril-voice-agent', epoch: 3, expires_at: Date.now() + 2 * 3600e3, voice: sessionVoice && sessionVoice !== 'omit' ? sessionVoice : captured };
if (sessionVoice === 'omit') delete grant.voice;
return send(res, 201, grant);
}
if (p.startsWith('/api/voice/session/') && req.method === 'DELETE') { const id = decodeURIComponent(p.slice(19)); return sessions.delete(id) ? send(res, 200, { ended: true }) : send(res, 404, { detail: '这次通话已经不在了。' }); }
if (p === '/api/voice/voices' && req.method === 'GET') return send(res, 200, { configured: true, voices: listed().map(item), selection: { ...selection } });
if (p === '/api/voice/voices' && req.method === 'POST') {
const data = await body(req), q = url.searchParams, info = wavInfo(data), f = take('register');
uploads.push({ type: req.headers['content-type'], bytes: data.length, info, label: q.get('label'), prompt_text: q.get('prompt_text'), allow_asr: q.get('allow_asr'), fail: f || '' });
// The panel took it, then the local metadata write failed (HEL-902 §4: OSError → 500) or the answer was lost.
// `commitnet` cuts the answer mid-body (a reset before any byte would let Chromium silently resend the POST on a
// reused socket, which is not the case this card covers).
if (f === 'commit500' || f === 'commitnet') { const lost = newId(); orphans.add(lost); if (f === 'commitnet') { res.writeHead(201, { 'Content-Type': 'application/json; charset=utf-8', 'Content-Length': '400' }); res.write(`{"id":"${lost}","la`); setTimeout(() => res.destroy(), 50); return; } return send(res, 500, 'Internal Server Error', 'text/plain'); }
if (f === 'net') { res.destroy(); return; }
if (f === '503') return send(res, 503, { detail: '音色登记服务这会儿不在,稍后再试试。' });
if (f === '500') return send(res, 500, 'Internal Server Error', 'text/plain');
if (!info) return send(res, 422, { detail: '只支持 WAV 格式的参考音频。' });
const text = (q.get('prompt_text') || '').trim(), asr = q.get('allow_asr') === 'true';
if (!text && !asr) return send(res, 422, { detail: '请填写这段音频的参考文字,或明确选择让系统转写(会用到语音识别)。' });
const id = newId(), 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 } = JSON.parse((await body(req)).toString() || '{}');
if (!known(voice)) return send(res, 404, { detail: '这个声音现在不在列表里。' });
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() || '{}');
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 => { console.log(`client gave up: ${req.method} ${req.url} (${e.code || e.message})`); try { res.destroy(); } catch { /* gone */ } }); })
.on('error', e => { console.error(`hel903 mock could not listen on ${port}: ${e.code || e.message}`); process.exit(2); })
.listen(port, '127.0.0.1', () => console.log(`hel903 mock on ${port} pid ${process.pid}`));
+226
View File
@@ -0,0 +1,226 @@
// HEL-903 browser check: 外接服务 voice rows from /api/voice/status, 本次通话声音 on the call line, and recovery after a
// registration with no clear answer. Drives headless Edge over CDP against tests/hel903_mock.mjs, with
// tests/fake-livekit.js in place of the LiveKit client and Chromium's fake audio device in place of a microphone (a beep,
// not a person). No voice panel, ASR, TTS, LiveKit or real clone is involved.
// Usage: node tests/hel903_shots.mjs <edge.exe> <outDir> [port] [before]. `before` only takes the comparison shots
// (run it against a build of the code before this card; it asserts nothing about the new behaviour).
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, mode] = process.argv.slice(2);
const port = Number(portArg || 8903), base = `http://127.0.0.1:${port}`, cdpPort = 9503;
mkdirSync(out, { recursive: true });
const profile = join(tmpdir(), `hel903-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, label = '') => js(`(() => { const el = [...document.querySelectorAll(${JSON.stringify(selector)})].find(e => e.offsetParent !== null && e.textContent.includes(${JSON.stringify(label)})); 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 scrollTo = sel => js(`(() => { const e = document.querySelector(${JSON.stringify(sel)}); if (e) e.scrollIntoView({ block: 'center' }); return !!e; })()`);
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 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 }); }
const PROBE = `(() => { const md = navigator.mediaDevices; if (!md) return; const orig = md.getUserMedia.bind(md); window.__tracks = [];
md.getUserMedia = async c => { 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; })();`;
const live = () => js('window.__live ? window.__live() : 0');
async function boot(theme, path = '/') {
await ctl('/__reset');
await cdp('Page.navigate', { url: `${base}${path}` }); await sleep(500);
await js(`localStorage.setItem('cg.theme', ${JSON.stringify(theme)}); localStorage.removeItem('cg.voice.owed'); sessionStorage.clear(); true`);
await cdp('Page.navigate', { url: `${base}${path}` }); await sleep(1500);
}
async function settings(section) { if (!(await exists('.pane-manage.open'))) { await click('.nav-item', '设置'); await sleep(700); } await click('.snav button', section); await sleep(400); }
async function closeSettings() { await click('.pane-manage button[aria-label="关闭设置"]'); await sleep(500); if (await exists('.modal.open')) { await click('.modal.open button', '放弃修改并离开'); await sleep(400); } }
const svc = label => js(`(() => { const r = [...document.querySelectorAll('.svc')].find(e => e.offsetParent !== null && e.querySelector('.nm')?.firstChild?.textContent === ${JSON.stringify(label)}); return r ? r.querySelector('.nm small').innerText : null; })()`);
const wav = (seconds, rate = 22050) => {
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 / 11) * 5000), 44 + i * 2);
return b;
};
const files = join(tmpdir(), `hel903-files-${Date.now()}`); mkdirSync(files, { recursive: true });
writeFileSync(join(files, 'reference.wav'), wav(6));
async function upload() {
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, 'reference.wav')], objectId: result.objectId });
return until(() => exists('.voice-sec .take .pill'));
}
async function takeReady(label) { await upload(); await fill('.voice-sec .take input.input', label); await fill('.voice-sec .take textarea', '今天天气很好,我们出去走走吧。'); }
async function applyVoice(label) {
await takeReady(label);
await click('.voice-sec .take button', '登记这段声音');
await until(async () => (await text('.voice-sec .voice-list')).includes(label));
await click('.voice-sec .audition button', '生成试听'); await until(() => exists('.voice-sec .sample.ready'));
await click('.voice-sec .audition button', '给栖用这个声音');
return until(async () => (await text('.voice-sec .kv')).includes(label));
}
const phase = () => js(`document.querySelector('.voice-row.real')?.dataset.phase || 'off'`);
const pin = () => js(`document.querySelector('.voice-row.real .voice-pin')?.innerText || ''`);
async function startCall() {
await click('.voice-button'); await until(() => exists('.modal.open'));
await click('.modal.open .btn-primary', '开始语音');
await until(async () => (await phase()) === 'joining');
await until(() => js(`window.__lk?.rooms.at(-1)?.state === 'connected'`));
await js('window.__lk.join()'); await sleep(300);
}
async function endCall() { await click('.voice-row.real .voice-end', '结束语音'); await until(async () => (await phase()) === 'off'); await sleep(300); }
async function talk() { await click('.nav-item', '交谈'); await sleep(1400); }
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 hel903 mock', (await ctl('/__pid')).mock === 'hel903');
if (mode === 'before') {
// The same three places before this card: services rows, the call line, a registration that failed after filing.
await view('desktop'); await boot('moon');
await settings('外接服务'); await sleep(600); await shot('before-01-services');
await settings('她的声音'); await until(() => exists('.voice-sec .voice-list')); await applyVoice('轻一点的她');
await closeSettings(); await talk(); await startCall(); await shot('before-02-call'); await endCall();
await settings('她的声音'); await until(() => exists('.voice-sec .voice-list'));
await takeReady('第二个'); await ctl('/__fail?register=commit500'); await click('.voice-sec .take button', '登记这段声音'); await sleep(1200); await scrollTo('.voice-sec .take'); await shot('before-03-register-500');
browser.kill(); process.exit(0);
}
// ── 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);
// 1. 外接服务: read from /api/voice/status, never "尚未接通" and never "已接通" for voice.
await settings('外接服务');
await until(async () => (await svc('语音合成')) && !(await svc('语音合成')).includes('正在读取'));
const tts = await svc('语音合成'), asr = await svc('语音识别');
check(`${tag}: services — TTS row says configured + health probe reachable`, tts === '已配置 · 合成服务健康检查可连接', tts);
check(`${tag}: services — ASR row claims no probe it does not have`, asr.includes('没有单独的健康检查'), asr);
check(`${tag}: services — no voice row says "尚未接通" or "已接通"`, !/尚未接通|已接通/u.test(`${tts}${asr}`));
check(`${tag}: services — reading status opens no microphone`, (await live()) === 0 && (await js('window.__tracks.length')) === 0);
await scrollTo('.svc'); await shot(`${tag}-01-services`);
// 2. Apply a voice, then call: the call line shows the voice the session answer pinned.
await settings('她的声音'); await until(() => exists('.voice-sec .voice-list'));
check(`${tag}: a voice is applied through the existing flow`, await applyVoice('轻一点的她'));
check(`${tag}: settings still says a change takes effect at the next call`, (await text('.voice-sec .kv')).includes('下一次通话'));
await closeSettings(); await talk();
await startCall();
check(`${tag}: call line shows 本次通话 voice from the session answer`, (await pin()).includes('轻一点的她'), await pin());
// 3. Another device applies a different voice mid-call: this call keeps its own.
await ctl('/__select?voice=rain');
await js(`window.__lk.say({ kind: 'interim', role: 'user', text: '你听得到吗' })`); await sleep(300);
check(`${tag}: subtitles still show beside it`, (await text('.voice-row.real')).includes('你听得到吗'));
check(`${tag}: a choice made during the call does not change this call`, (await pin()).includes('轻一点的她'), await pin());
await shot(`${tag}-02-call-pinned`);
await endCall();
check(`${tag}: ending the call releases the microphone and drops the pin`, (await live()) === 0 && !(await exists('.voice-row.real .voice-pin')));
// 4. The next call takes the new choice.
await startCall();
check(`${tag}: the next call shows the new voice`, (await pin()).includes('rain'), await pin());
await shot(`${tag}-03-next-call`);
await endCall();
// 5. A registration filed by the panel whose answer was lost: say so, offer the list, find the numbered entry.
await settings('她的声音'); await until(() => exists('.voice-sec .voice-list'));
await takeReady('第二个');
await ctl('/__fail?register=commit500');
await click('.voice-sec .take button', '登记这段声音');
check(`${tag}: 500 after filing — says it may be registered and to refresh first`, await until(async () => (await text('.voice-sec .status')).includes('可能已经登记上了')) && (await text('.voice-sec .status')).includes('刷新列表'), await text('.voice-sec .status'));
check(`${tag}: offers 刷新列表 and words a second registration as a checked choice`, (await exists('.voice-sec .take')) && (await text('.voice-sec .take .take-acts')).includes('刷新列表') && (await text('.voice-sec .take .take-acts')).includes('确认没有,再登记'));
check(`${tag}: the list is not re-read or re-registered behind your back`, (await ctl('/__uploads')).length === 2);
await scrollTo('.voice-sec .take .take-acts'); await shot(`${tag}-04-register-unsure`);
await click('.voice-sec .take button', '刷新列表');
check(`${tag}: refreshing names the new numbered entry`, await until(async () => /列表里多了「cg-/u.test(await text('.voice-sec .status'))), await text('.voice-sec .status'));
check(`${tag}: the numbered entry is marked as missing local metadata`, (await text('.voice-sec .voice-list')).includes('只有编号,缺本地资料') && (await exists('.voice-sec .voice-idonly')));
check(`${tag}: after it is found the cautious button goes away`, !(await text('.voice-sec .take .take-acts')).includes('刷新列表'));
await scrollTo('.voice-sec .voice-idonly'); await shot(`${tag}-05-found-numbered`);
await closeSettings();
}
// ── Branches, desktop moon unless noted ──
await view('desktop'); await boot('moon');
for (const [m, tts, asr, name] of [
['down', '已配置 · 合成服务这会儿暂不可用', '没有单独的健康检查', 'down'],
['off', '未配置 · 这台服务没有语音配置', '未配置', 'off'],
['none', '这台服务没有语音状态接口', '这台服务没有语音状态接口', 'no-route'],
['500', '状态未知 · 这次没读到语音状态', '状态未知', 'unknown-500'],
['net', '状态未知 · 这次没读到语音状态', '状态未知', 'unknown-net'],
]) {
await ctl(`/__status?mode=${m}`);
await settings('外接服务'); await click('.svc button', '重新读取状态');
await until(async () => !((await svc('语音合成')) || '').includes('正在读取'));
const t = await svc('语音合成'), a = await svc('语音识别');
check(`status ${name}: TTS "${tts}"`, t === tts, t);
check(`status ${name}: ASR row honest`, a.includes(asr), a);
if (m === 'down' || m === 'off') { await scrollTo('.svc'); await shot(`branch-services-${name}`); }
}
await ctl('/__status?mode=ok');
await view('phone'); await boot('fog'); await ctl('/__status?mode=down'); await settings('外接服务'); await until(async () => (await svc('语音合成')) === '已配置 · 合成服务这会儿暂不可用'); await scrollTo('.svc'); await shot('branch-services-down-fog-phone'); await ctl('/__status?mode=ok');
await view('desktop'); await boot('moon');
// The session answer without a voice field (an older server): shown as not said, never guessed from settings.
await settings('她的声音'); await until(() => exists('.voice-sec .voice-list')); await applyVoice('轻一点的她');
await ctl('/__session-voice?v=omit'); await closeSettings(); await talk(); await startCall();
check('session without voice: "声音未说明", not the settings choice', (await pin()).includes('声音未说明') && !(await pin()).includes('轻一点的她'), await pin());
await shot('branch-call-voice-unknown');
await endCall();
await ctl('/__session-voice?v=default'); await startCall();
check('session voice "default": shown as 默认声音', (await pin()).includes('默认声音'), await pin());
await endCall(); await ctl('/__session-voice');
// A dropped answer after filing; a 503 before filing (refresh finds nothing; a checked retry then succeeds).
await settings('她的声音'); await until(() => exists('.voice-sec .voice-list'));
await takeReady('断线那次'); await ctl('/__fail?register=commitnet');
await click('.voice-sec .take button', '登记这段声音');
check('dropped answer: may be registered, refresh first', await until(async () => (await text('.voice-sec .status')).includes('可能已经登记上了')), await text('.voice-sec .status'));
await click('.voice-sec .take button', '刷新列表');
check('dropped answer: refresh finds the numbered entry', await until(async () => /列表里多了「cg-/u.test(await text('.voice-sec .status'))));
await click('.voice-sec .take button', '换一段');
await takeReady('面板不在'); await ctl('/__fail?register=503');
await click('.voice-sec .take button', '登记这段声音');
check('503: keeps the server words and adds the refresh advice', await until(async () => (await text('.voice-sec .status')).includes('音色登记服务')) && (await text('.voice-sec .status')).includes('刷新列表'), await text('.voice-sec .status'));
await click('.voice-sec .take button', '刷新列表');
check('503: refresh finds nothing new and says to wait before registering again', await until(async () => (await text('.voice-sec .status')).includes('暂时没有新出现的条目')), await text('.voice-sec .status'));
await shot('branch-register-503-none');
const before = (await ctl('/__uploads')).length;
await click('.voice-sec .take button', '确认没有,再登记');
check('503: the checked retry registers once and the take is gone', await until(async () => (await text('.voice-sec .voice-list')).includes('面板不在')) && (await ctl('/__uploads')).length === before + 1 && !(await exists('.voice-sec .take')));
// Recording regression: the microphone opens on a tap and closes on stop / cancel.
await click('.voice-sec .seg button', '现在录一段');
await click('.voice-sec .rec button', '开始录音');
await until(async () => (await text('.voice-sec .rec')).includes('正在录音'));
await sleep(2600);
check('recording: microphone live while recording', (await live()) === 1);
await click('.voice-sec .rec button', '停止');
check('recording: stop keeps the take and releases the microphone', await until(() => exists('.voice-sec .take .pill'), 8000) && (await live()) === 0);
await click('.voice-sec .take button', '换一段');
await click('.voice-sec .rec button', '开始录音'); await until(async () => (await text('.voice-sec .rec')).includes('正在录音'));
await click('.voice-sec .rec button', '取消');
check('recording: cancel releases the microphone', (await live()) === 0);
await closeSettings();
// Demo entry: nothing goes to any server from settings (services, her voice) or the conversation.
await boot('moon', '/?demo=1'); await ctl('/__log');
await settings('外接服务'); await sleep(500); await settings('她的声音'); await sleep(500); await closeSettings();
await click('.nav-item', '交谈'); await sleep(1200);
const demoLog = await ctl('/__log');
check('demo: zero /api requests from settings and the conversation', demoLog.length === 0, demoLog.join(' | '));
await settings('外接服务'); await shot('demo-services');
const passed = results.filter(Boolean).length;
console.log(`\n${passed}/${results.length} passed`);
browser.kill();
process.exit(passed === results.length ? 0 : 1);
+122
View File
@@ -0,0 +1,122 @@
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);
});
});