// 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 [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);