193 lines
17 KiB
JavaScript
193 lines
17 KiB
JavaScript
// HEL-879 unified review: the ACTUAL worker's v2 frames (web/tests/fixtures/hel879, generated on
|
|
// the .12 real SDK by scripts/gen_hel879_unified_frames.py) replayed through the current page.
|
|
// Headless Chromium over CDP against tests/hel878_mock.mjs + tests/fake-livekit.js (no WebRTC, no
|
|
// model, no TTS; fake audio device as the microphone). Everything on the subtitle side is the
|
|
// worker's own output — turn ids, speech ids, seqs, kinds; the mock's record rows are keyed to the
|
|
// fixture turn ids so the stage takeover is exercised end to end. Usage:
|
|
// node tests/hel879_unified_shots.mjs <chromium-binary> <outDir> [port]
|
|
import { spawn } from 'node:child_process';
|
|
import { mkdirSync, writeFileSync, readFileSync } from 'node:fs';
|
|
import { join } from 'node:path';
|
|
import { tmpdir } from 'node:os';
|
|
|
|
const [chrome, out, portArg] = process.argv.slice(2);
|
|
const port = Number(portArg || 8879), base = `http://127.0.0.1:${port}`, cdpPort = 9499;
|
|
mkdirSync(out, { recursive: true });
|
|
// The mock rides along (child of this run, killed at the end): one self-contained command.
|
|
const mock = spawn(process.execPath, [new URL('./hel878_mock.mjs', import.meta.url).pathname, String(port)], { stdio: 'ignore' });
|
|
await new Promise((ok, ko) => { const t = setTimeout(() => ok(undefined), 3000); mock.once('spawn', () => setTimeout(ok, 400)); });
|
|
const profile = join(tmpdir(), `hel879-unified-${Date.now()}`);
|
|
const browser = spawn(chrome, ['--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 ? ` — ${detail}` : ''}`); };
|
|
const ctl = async path => (await fetch(`${base}${path}`)).json();
|
|
const shot = async name => { const { data } = await cdp('Page.captureScreenshot', { format: 'png' }); writeFileSync(join(out, `${name}.png`), Buffer.from(data, 'base64')); };
|
|
const frames = async (name, ms) => { const list = []; const end = Date.now() + ms; while (Date.now() < end) { const { data } = await cdp('Page.captureScreenshot', { format: 'jpeg', quality: 70 }); list.push(data); } list.forEach((d, i) => writeFileSync(join(out, `${name}-${String(i).padStart(2, '0')}.jpg`), Buffer.from(d, 'base64'))); return list.length; };
|
|
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.click(); return true; })()`);
|
|
const type = t => js(`(() => { const el = document.querySelector('textarea'); const set = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value').set; set.call(el, ${JSON.stringify(t)}); el.dispatchEvent(new Event('input', { bubbles: true })); return true; })()`);
|
|
const until = async (fn, ms = 4000) => { const end = Date.now() + ms; while (Date.now() < end) { if (await fn()) return true; await sleep(100); } return false; };
|
|
const stage = () => js(`document.querySelector('.conversation .stage')?.innerText || ''`);
|
|
const said = () => js(`document.querySelector('.conversation .sr')?.textContent || ''`);
|
|
const row = () => js(`document.querySelector('.voice-row.real')?.innerText || ''`);
|
|
const phase = () => js(`document.querySelector('.voice-row.real')?.dataset.phase || 'off'`);
|
|
const lk = expr => js(`window.__lk ? (${expr}) : null`);
|
|
const say = frame => lk(`__lk.say(${JSON.stringify(frame)})`);
|
|
const state = s => lk(`__lk.state(${JSON.stringify(s)})`);
|
|
const exists = sel => js(`!!document.querySelector(${JSON.stringify(sel)})`);
|
|
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 }); }
|
|
async function boot(theme) {
|
|
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(1600);
|
|
}
|
|
async function startVoice() {
|
|
await click('.voice-button'); await until(() => exists('.modal.open'));
|
|
await click('.modal.open .btn-primary', '开始语音');
|
|
await until(async () => (await phase()) === 'joining');
|
|
await until(async () => (await lk('__lk.rooms.at(-1)?.state')) === 'connected');
|
|
await lk('__lk.join()'); await sleep(250);
|
|
}
|
|
// The actual worker fixtures + the sidecar that carries their turn ids / receipts.
|
|
const load = name => readFileSync(new URL(`./fixtures/hel879/${name}.jsonl`, import.meta.url), 'utf8').split('\n').filter(l => l.trim()).map(l => JSON.parse(l));
|
|
const sidecar = JSON.parse(readFileSync(new URL('./fixtures/hel879/sidecar.json', import.meta.url), 'utf8'));
|
|
const of = (frames, kind, nth = 0) => frames.filter(f => f.kind === kind)[nth];
|
|
const sayAll = async frames => { for (const f of frames) await say(f); };
|
|
const calls = async () => ctl('/__log');
|
|
const rows = async () => ctl('/__rows');
|
|
await cdp('Page.enable'); await cdp('Runtime.enable'); await cdp('Network.enable');
|
|
|
|
// ── The full run on moon/desktop: every worker scenario through the real page. ──
|
|
await view('desktop'); await boot('moon'); await click('.nav-item', '交谈'); await sleep(1400);
|
|
await startVoice(); await calls();
|
|
|
|
// 1. Normal turn (worker-normal.jsonl): her words grow on the stage before anything is stored.
|
|
const normal = load('worker-normal'), turn = sidecar.scenarios.normal.turn_id;
|
|
await ctl(`/__voice-turn?stage=user&turn=${encodeURIComponent(turn)}&text=${encodeURIComponent('你在听吗')}`);
|
|
await sayAll(normal.filter(f => f.seq <= 2)); await state('thinking');
|
|
for (const f of normal.filter(f => f.kind === 'turn_start' || f.kind === 'assistant_interim')) {
|
|
await say(f); await state('speaking');
|
|
if (f.text.length > 8) { await until(async () => (await stage()).includes(f.text.slice(0, 6)), 6000); await frames(`w-normal-grow-${f.seq}`, 350); }
|
|
}
|
|
check('worker frames: her reply grows on the stage while she speaks, before it is stored', (await stage()).includes('在听呢') && (await rows()).every(r => r.role !== 'companion' || r.turn_id !== turn), (await stage()));
|
|
check('worker frames: your final is your line, her words never in the voice line', !(await row()).includes('在听呢'), await row());
|
|
await shot('w1-her-words-growing');
|
|
// The stored row takes over: same turn id, exactly once, stage keeps its place.
|
|
await ctl(`/__voice-turn?stage=reply&turn=${encodeURIComponent(turn)}&text=${encodeURIComponent('在听呢,你刚才说到一半的那件事我还在想。')}`);
|
|
await sayAll(normal.filter(f => f.kind === 'assistant_final' || f.kind === 'turn_end')); await state('listening'); await sleep(900);
|
|
await click('.log-btn'); await sleep(700);
|
|
const record1 = await js(`document.querySelector('.log-panel .scroll')?.innerText || ''`);
|
|
check('worker frames: the stored row (same turn id) takes over exactly once — re-read, never written by the page', record1.split('在听呢,你刚才说到一半的那件事我还在想。').length - 1 === 1, record1.slice(-140).replace(/\n/g, ' '));
|
|
await shot('w2-record-after-final');
|
|
await click('.log-panel .btn-round'); await sleep(400); await click('.read-all'); await sleep(400); await click('.record.full .btn-round'); await sleep(300);
|
|
|
|
// 2. Barge-in (worker-interrupt.jsonl): the cut turn never gets a final; the next turn lands clean.
|
|
const it = load('worker-interrupt'), cutTurn = sidecar.scenarios.interrupt.turn_ids.cut, nextTurn = sidecar.scenarios.interrupt.turn_ids.next;
|
|
await ctl(`/__voice-turn?stage=user&turn=${encodeURIComponent(cutTurn)}&text=${encodeURIComponent('讲讲你下午做了什么')}`);
|
|
await sayAll(it.slice(0, 4)); await state('speaking');
|
|
await until(async () => (await stage()).includes('白鹭'), 6000);
|
|
await shot('w3-before-cut');
|
|
await sayAll(it.slice(4, 5)); await state('listening'); await ctl(`/__voice-turn?stage=cancel&turn=${encodeURIComponent(cutTurn)}`); await sleep(250);
|
|
check('worker frames: interrupted — her unfinished line is gone at once, no final exists for the cut turn', !(await stage()).includes('白鹭') && it.filter(f => f.kind === 'assistant_final' && f.speech_id === of(it, 'turn_cancel').speech_id).length === 0, await stage());
|
|
// Late frames of the cut speech (fresh seqs, dead speech) change nothing.
|
|
const cutSpeech = of(it, 'turn_cancel').speech_id;
|
|
await say({ v: 2, seq: 90, kind: 'assistant_interim', role: 'assistant', speech_id: cutSpeech, text: '白鹭又飞回来了' });
|
|
await say({ v: 2, seq: 91, kind: 'assistant_final', role: 'assistant', speech_id: cutSpeech, turn_id: 'late', text: '白鹭又飞回来了。' });
|
|
await sleep(350);
|
|
check('worker frames: late frames of the cut speech stay out', !(await stage()).includes('飞回来'));
|
|
// The next clean turn of the same recording lands with its own receipt.
|
|
await ctl(`/__voice-turn?stage=user&turn=${encodeURIComponent(nextTurn)}&text=${encodeURIComponent('那后来呢')}`);
|
|
await ctl(`/__voice-turn?stage=reply&turn=${encodeURIComponent(nextTurn)}&text=${encodeURIComponent('后来我在桥上站了一会儿,风把水面吹皱了。')}`);
|
|
await sayAll(it.slice(5)); await state('speaking'); await until(async () => (await stage()).includes('桥上'), 6000); await state('listening'); await sleep(700);
|
|
await click('.log-btn'); await sleep(600);
|
|
const record2 = await js(`document.querySelector('.log-panel .scroll')?.innerText || ''`);
|
|
check('worker frames: the next turn lands clean (one stored row of its own)', record2.includes('风把水面吹皱了') && record2.split('风把水面吹皱了').length - 1 === 1, record2.slice(-120).replace(/\n/g, ' '));
|
|
await click('.log-panel .btn-round'); await sleep(300);
|
|
|
|
// 3. phi (worker-phi.jsonl): her failed line is heard, not stored.
|
|
const phi = load('worker-phi');
|
|
await ctl(`/__voice-turn?stage=user&turn=${encodeURIComponent(sidecar.scenarios.phi.turn_id)}&text=${encodeURIComponent('说说那件事吧')}`);
|
|
await sayAll(phi); await state('speaking'); await sleep(300); await state('listening'); await sleep(300);
|
|
check('worker frames: phi is heard in the voice line, not stored as her reply', (await row()).includes('说不出来话') && !(await stage()).includes('说不出来话'), await row());
|
|
await shot('w4-phi-heard');
|
|
await sleep(600);
|
|
|
|
// 4. No legal receipt (worker-no_receipt.jsonl): cancel only, nothing on the stage.
|
|
const nr = load('worker-no_receipt');
|
|
await ctl(`/__voice-turn?stage=user&turn=${encodeURIComponent(sidecar.scenarios.no_receipt.turn_id)}&text=${encodeURIComponent('再讲讲那座桥')}`);
|
|
await sayAll(nr.filter(f => f.kind !== 'turn_cancel')); await state('speaking');
|
|
await until(async () => (await stage()).includes('水声很好听'), 6000);
|
|
await say(of(nr, 'turn_cancel')); await state('listening'); await sleep(300);
|
|
check('worker frames: no legal receipt — the page never shows a final (cancel only)', !(await stage()).includes('水声很好听') && nr.every(f => f.kind !== 'assistant_final'), await stage());
|
|
|
|
// 5. Proactive (worker-proactive.jsonl): start DURING playout, end/cancel with the row's own id.
|
|
await ctl(`/__proactive?id=301&text=${encodeURIComponent('刚才路过花店,想起你说过喜欢白色的洋桔梗。')}`); await calls();
|
|
const pro = load('worker-proactive');
|
|
await say(of(pro.filter(f => f.message_id === 301), 'proactive_start')); await state('speaking'); await sleep(600);
|
|
check('worker frames: reach-out read aloud is shown word for word while she speaks it', (await stage()).includes('洋桔梗'), await stage());
|
|
await shot('w5-reach-out');
|
|
await say(of(pro.filter(f => f.message_id === 301), 'proactive_end')); await state('listening'); await sleep(400);
|
|
// The interrupted variant clears without a trace and the page wrote nothing.
|
|
const before = await calls();
|
|
await say(pro.filter(f => f.message_id === 302)[0]); await state('speaking'); await sleep(250);
|
|
await say(pro.filter(f => f.message_id === 302)[1]); await state('listening'); await sleep(250);
|
|
const after = await calls();
|
|
check('worker frames: an interrupted reach-out clears; the page still wrote nothing (no receipt, no read mark)', !after.some(l => !l.startsWith('GET ')), after.join(' | '));
|
|
|
|
// 6. Text takes over while she speaks (the worker's own next turn): typed words come next.
|
|
const nt = load('worker-normal'), nt2 = { ...normal[2], seq: 100, speech_id: 'speech_text_takeover' };
|
|
await say(nt2); await state('speaking'); await sleep(200);
|
|
await type('先等等,我打字跟你说'); await js(`document.querySelector('.send').click(), true`); await sleep(400);
|
|
check('text over voice: her worker line is gone at once, your typed words are on the stage', !(await stage()).includes('在听呢,') && (await stage()).includes('先等等'), await stage());
|
|
await until(async () => !(await exists('.reader-bar .stop')), 9000); await state('listening'); await sleep(400);
|
|
|
|
// 7. The room drops mid-sentence: everything clears with the call; starting again works.
|
|
await say({ v: 2, seq: 120, kind: 'turn_start', role: 'assistant', speech_id: 'speech_drop', text: '' });
|
|
await say({ v: 2, seq: 121, kind: 'assistant_interim', role: 'assistant', speech_id: 'speech_drop', text: '晚安,明天见。' }); await state('speaking');
|
|
await until(async () => (await stage()).includes('晚安'), 6000);
|
|
await lk('__lk.drop()'); await sleep(400);
|
|
check('dropped mid-sentence: her line and the call clear together', !(await stage()).includes('晚安') && (await phase()) === 'off', await stage());
|
|
await shot('w6-after-drop');
|
|
await startVoice(); await calls();
|
|
const fresh = { v: 2, seq: 1, kind: 'turn_start', role: 'assistant', speech_id: 'speech_fresh', text: '' };
|
|
const freshText = { v: 2, seq: 2, kind: 'assistant_interim', role: 'assistant', speech_id: 'speech_fresh', text: '又见面了。' };
|
|
await say(fresh); await say(freshText); await state('speaking');
|
|
await until(async () => (await stage()).includes('又见面了'), 6000);
|
|
check('a new call is a new room and a new sequence: her words flow again, nothing of the old call remains', (await stage()).includes('又见面了') && !(await stage()).includes('晚安'), await stage());
|
|
await shot('w7-reopened');
|
|
await click('.voice-row.real .voice-end'); await sleep(300);
|
|
|
|
// ── Second theme + phone: the same worker frames on the approved visuals. ──
|
|
for (const [theme, v, tag] of [['fog', 'desktop', 'fog'], ['moon', 'phone', 'phone']]) {
|
|
await view(v); await boot(theme); await click('.nav-item', '交谈'); await sleep(1400); await startVoice(); await calls();
|
|
const t = load('worker-normal'), tid = sidecar.scenarios.normal.turn_id;
|
|
await ctl(`/__voice-turn?stage=user&turn=${encodeURIComponent(tid)}&text=${encodeURIComponent('你在听吗')}`);
|
|
await sayAll(t.filter(f => f.seq <= 2));
|
|
await say(of(t, 'turn_start')); await state('speaking');
|
|
for (const f of t.filter(f => f.kind === 'assistant_interim')) { await say(f); await sleep(260); }
|
|
check(`${tag}: worker frames grow her reply on the approved ${theme} ${v} layout`, await until(async () => (await stage()).includes('在听呢,你刚才说到一半的那件事'), 8000), await stage());
|
|
if (tag === 'phone') await frames('phone-growing', 700);
|
|
await shot(`${tag}-her-words-growing`);
|
|
await ctl(`/__voice-turn?stage=reply&turn=${encodeURIComponent(tid)}&text=${encodeURIComponent('在听呢,你刚才说到一半的那件事我还在想。')}`);
|
|
await sayAll(t.filter(f => f.kind === 'assistant_final' || f.kind === 'turn_end')); await state('listening'); await sleep(800);
|
|
await click('.log-btn'); await sleep(600);
|
|
const rec = await js(`document.querySelector('.log-panel .scroll')?.innerText || ''`);
|
|
check(`${tag}: the stored row takes over once on ${theme} ${v}`, rec.split('在听呢,你刚才说到一半的那件事我还在想。').length - 1 === 1, '');
|
|
await click('.log-panel .btn-round'); await sleep(300);
|
|
await click('.voice-row.real .voice-end'); await sleep(300);
|
|
}
|
|
|
|
ws.close(); browser.kill(); mock.kill();
|
|
const failed = results.filter(r => !r).length;
|
|
console.log(`${results.length - failed}/${results.length} passed`);
|
|
process.exit(failed ? 1 : 0);
|