Files
CyberGril/web/tests/hel879_unified_shots.mjs
T

359 lines
32 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, kinds, texts; 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] [cdpPort]
//
// Replay rules (HEL-898 f92a86f rework of this driver; the page is not changed by them):
// - One call is one worker job is one strictly rising seq. The fixtures were recorded by separate worker jobs, each
// from seq 1; replayed into one call they are RENUMBERED onto that call's sequence, in order. The original frames
// are untouched in the fixtures; every renumbering is written to <outDir>/seq-renumbering.json.
// - A new call (a new room) starts the sequence again at 1.
// - Negatives (replays, late and out-of-order frames, retired speeches) are sent RAW, exactly as written, and each is
// asserted to be refused by the page itself — the driver never repairs a bad frame and then claims the gate held.
// - Each theme/viewport block starts from a reset record (/__reset), so the same fixture turn ids replayed per theme
// never pile up in one record.
// - The mock and CDP ports must be free before anything starts, and the mock must answer /__pid with the pid this
// driver spawned: it never drives somebody else's service.
import { spawn } from 'node:child_process';
import { mkdirSync, writeFileSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
import { tmpdir } from 'node:os';
import { createConnection } from 'node:net';
import { fileURLToPath } from 'node:url';
const [chrome, out, portArg, cdpArg] = process.argv.slice(2);
const port = Number(portArg || 8879), base = `http://127.0.0.1:${port}`, cdpPort = Number(cdpArg || 9499);
mkdirSync(out, { recursive: true });
const sleep = ms => new Promise(r => setTimeout(r, ms));
const busy = p => new Promise(ok => { const s = createConnection({ port: p, host: '127.0.0.1' }); s.once('connect', () => { s.destroy(); ok(true); }); s.once('error', () => ok(false)); });
for (const [what, p] of [['mock', port], ['CDP', cdpPort]]) if (await busy(p)) { console.error(`port ${p} (${what}) is already in use: refusing to start over someone else's service`); process.exit(3); }
// The mock rides along (child of this run, killed at the end): one self-contained command.
const mock = spawn(process.execPath, [fileURLToPath(new URL('./hel878_mock.mjs', import.meta.url)), String(port)], { stdio: ['ignore', 'pipe', 'pipe'] });
const listening = await new Promise(ok => {
let said = ''; const t = setTimeout(() => ok(false), 8000);
mock.stdout.on('data', d => { said += d; if (said.includes(`hel878 mock on ${port} pid ${mock.pid}`)) { clearTimeout(t); ok(true); } });
mock.stderr.on('data', d => process.stderr.write(d));
mock.once('exit', () => { clearTimeout(t); ok(false); });
});
const who = listening ? await fetch(`${base}/__pid`).then(r => r.json(), () => null) : null;
if (!listening || who?.pid !== mock.pid) { console.error(`mock did not come up as pid ${mock.pid} on ${port} (answered: ${JSON.stringify(who)})`); mock.kill(); process.exit(3); }
console.log(`mock pid ${mock.pid} listening on ${port}; CDP on ${cdpPort}`);
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' });
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 ? ` — ${String(detail).replace(/\n/g, ' / ').slice(0, 220)}` : ''}`); };
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 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 status = () => js(`document.querySelector('.talk-status')?.innerText || ''`);
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 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 }); }
const reduce = on => cdp('Emulation.setEmulatedMedia', { features: [{ name: 'prefers-reduced-motion', value: on ? 'reduce' : 'no-preference' }] });
async function boot(theme) {
await ctl('/__reset');
await cdp('Page.navigate', { url: `${base}/` }); await sleep(500);
await js(`localStorage.clear(); localStorage.setItem('cg.theme', ${JSON.stringify(theme)}); sessionStorage.clear(); true`);
await cdp('Page.navigate', { url: `${base}/` }); await sleep(1600);
}
// ── Sequence of the call now open (see the replay rules above). ──
const call = { id: 0, n: 0 }, renumbered = [];
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);
call.id++; call.n = 0;
}
const send = async (f, from) => { const sent = { ...f, seq: ++call.n }; renumbered.push({ call: call.id, from, orig_seq: f.seq, seq: sent.seq, kind: f.kind, speech_id: f.speech_id }); await lk(`__lk.say(${JSON.stringify(sent)})`); return sent; };
const sendAll = async (frames, from) => { for (const f of frames) await send(f, from); };
// Negatives: exactly as written. Returns nothing the page could use to "pass" — the page must refuse them itself.
const raw = async f => { await lk(`__lk.say(${JSON.stringify(f)})`); call.n = Math.max(call.n, f.seq); };
const fresh = (kind, speech, extra = {}) => ({ v: 2, seq: 0, kind, role: 'assistant', text: '', speech_id: speech, ...extra });
// 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 calls = async () => ctl('/__log');
const rows = async () => ctl('/__rows');
const herLine = `[...document.querySelectorAll('.conversation .stage .line[data-role=companion]:not(.leaving)')].at(-1)`;
// ── Real screencast → WebM. No ffmpeg here: the frames Chromium itself painted are re-played at their own timestamps
// into the browser's MediaRecorder at the end of the run. Every frame is also kept as a JPEG with its timestamp. ──
const recordings = [];
async function record(name, fn) {
const got = [];
const onFrame = ({ data }) => { const m = JSON.parse(data); if (m.method !== 'Page.screencastFrame') return; got.push({ d: m.params.data, t: m.params.metadata.timestamp }); ws.send(JSON.stringify({ id: ++id, method: 'Page.screencastFrameAck', params: { sessionId: m.params.sessionId } })); };
ws.addEventListener('message', onFrame);
await cdp('Page.startScreencast', { format: 'jpeg', quality: 80, everyNthFrame: 1 });
try { await fn(); await sleep(600); } finally { await cdp('Page.stopScreencast'); ws.removeEventListener('message', onFrame); }
const dir = join(out, `${name}-frames`); mkdirSync(dir, { recursive: true });
got.forEach((f, i) => writeFileSync(join(dir, `${String(i).padStart(3, '0')}.jpg`), Buffer.from(f.d, 'base64')));
writeFileSync(join(dir, 'timing.json'), JSON.stringify(got.map((f, i) => ({ i, t: f.t }))));
recordings.push({ name, frames: got });
}
async function encodeAll() {
await cdp('Page.navigate', { url: 'about:blank' }); await sleep(300);
for (const { name, frames: list } of recordings) {
if (list.length < 2) { console.log(`video ${name}: only ${list.length} frame(s), not encoded`); continue; }
await js(`window.__f = []; true`);
for (let i = 0; i < list.length; i += 6) await js(`window.__f.push(...${JSON.stringify(list.slice(i, i + 6))}); true`);
const b64 = await js(`(async () => {
const f = window.__f, imgs = await Promise.all(f.map(x => new Promise(ok => { const i = new Image(); i.onload = () => ok(i); i.src = 'data:image/jpeg;base64,' + x.d; })));
const c = document.createElement('canvas'); c.width = imgs[0].naturalWidth; c.height = imgs[0].naturalHeight; document.body.append(c);
const g = c.getContext('2d'), rec = new MediaRecorder(c.captureStream(30), { mimeType: 'video/webm;codecs=vp8', videoBitsPerSecond: 5e6 }), parts = [];
rec.ondataavailable = e => parts.push(e.data); g.drawImage(imgs[0], 0, 0); rec.start(200);
for (let k = 0; k < imgs.length; k++) { g.drawImage(imgs[k], 0, 0); const gap = k + 1 < f.length ? (f[k + 1].t - f[k].t) * 1000 : 1000; await new Promise(r => setTimeout(r, Math.min(4000, Math.max(16, gap)))); }
rec.stop(); await new Promise(r => { rec.onstop = r; });
const bytes = new Uint8Array(await new Blob(parts, { type: 'video/webm' }).arrayBuffer()); let s = '';
for (let i = 0; i < bytes.length; i += 0x8000) s += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
c.remove(); return btoa(s);
})()`);
writeFileSync(join(out, `${name}.webm`), Buffer.from(b64, 'base64'));
console.log(`video ${name}.webm: ${list.length} real frames, ${((list.at(-1).t - list[0].t)).toFixed(1)} s`);
}
}
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 reduce(false); await boot('moon'); await click('.nav-item', '交谈'); await sleep(1400);
await startVoice(); await calls();
// 1. Normal turn (worker-normal.jsonl). Fix 3: her short reply is on the stage while she says it, not after the final.
const normal = load('worker-normal'), turn = sidecar.scenarios.normal.turn_id;
const interims = normal.filter(f => f.kind === 'assistant_interim');
let beforeSentence = '', afterSentence = '', heldOn = '', storedThen = -1;
await record('v1-moon-desktop-short-reply-while-speaking', async () => {
await ctl(`/__voice-turn?stage=user&turn=${encodeURIComponent(turn)}&text=${encodeURIComponent('你在听吗')}`);
await sendAll(normal.filter(f => f.seq <= 2), 'worker-normal'); await state('thinking'); await sleep(500);
await send(of(normal, 'turn_start'), 'worker-normal'); await state('speaking');
await send(interims[0], 'worker-normal'); await sleep(900);
await send(interims[1], 'worker-normal'); await sleep(1600);
beforeSentence = await stage();
await send(interims[2], 'worker-normal');
await until(async () => (await stage()).includes('我还在想'), 6000);
afterSentence = await stage(); storedThen = (await rows()).filter(r => r.turn_id === turn && r.role === 'companion').length;
await js(`window.__line = ${herLine}; true`);
// She is still speaking it (the final comes only after playout): it stays there the whole time.
await sleep(2600); heldOn = await stage();
await shot('w1-her-words-growing');
await ctl(`/__voice-turn?stage=reply&turn=${encodeURIComponent(turn)}&text=${encodeURIComponent('在听呢,你刚才说到一半的那件事我还在想。')}`);
await sendAll(normal.filter(f => f.kind === 'assistant_final' || f.kind === 'turn_end'), 'worker-normal'); await state('listening'); await sleep(1200);
});
check('fix 3: while the sentence is still forming, her half-said words wait (one or two whole sentences, as before)', !beforeSentence.includes('你刚才说到一半'), beforeSentence);
check('fix 3: her short reply is on the stage while she speaks it, before anything is stored', afterSentence.includes('在听呢,你刚才说到一半的那件事我还在想。') && storedThen === 0, `${afterSentence} (stored rows of hers then: ${storedThen})`);
check('fix 3: it stays through the playout (seconds before the final)', heldOn.includes('我还在想'), heldOn);
check('fix 3: her final and her stored row take over the very same line (no re-made line, no replayed ink)', await js(`window.__line === ${herLine} && window.__line.isConnected`), await stage());
check('worker frames: your final is your line, her words never in the voice line', !(await row()).includes('在听呢'), await row());
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));
await shot('w2-record-after-final');
await click('.log-panel .btn-round'); await sleep(400);
// 1b. Fix 3, a short sentence the next one joins: the line grows in place; the words already there are not redone.
await send(fresh('turn_start', 'speech_grow'), 'driver'); await state('speaking');
await send(fresh('assistant_interim', 'speech_grow', { text: '嗯。' }), 'driver');
await until(async () => (await stage()).includes('嗯。'), 6000);
await js(`window.__line = ${herLine}; window.__first = window.__line.querySelector('p').firstChild; true`);
await send(fresh('assistant_interim', 'speech_grow', { text: '嗯。我在这儿' }), 'driver'); await sleep(500);
const growHeld = await js(`${herLine}.innerText`);
await send(fresh('assistant_interim', 'speech_grow', { text: '嗯。我在这儿,一直都在。' }), 'driver'); await sleep(900);
check('fix 3: the next sentence joins the same line in place (same node, first ink untouched; the unfinished part waited)', await js(`window.__line === ${herLine} && window.__line.querySelector('p').firstChild === window.__first && window.__line.innerText.includes('嗯。我在这儿,一直都在。')`) && !growHeld.includes('我在这儿'), await js(`${herLine}.innerText`));
await send(fresh('turn_cancel', 'speech_grow', { reason: 'interrupted' }), 'driver'); await state('listening'); await sleep(400);
// 1c. Fix 3 negative: a long sentence still reads a line at a time; the part still being said waits.
const long = '我下午去了河边,看到一群白鹭从水面上飞过去了,它们飞得很低,几乎贴着水,翅膀尖在水面上划出一道一道细细的白线,后来又绕回来落在对岸的芦苇里';
await send(fresh('turn_start', 'speech_long'), 'driver'); await state('speaking');
await send(fresh('assistant_interim', 'speech_long', { text: long }), 'driver');
await until(async () => (await stage()).includes('白鹭'), 8000);
const longStage = await stage();
check('fix 3 negative: a long sentence shows its finished lines only, never the whole text at once', longStage.includes('白鹭') && !longStage.includes('芦苇里'), longStage);
await send(fresh('turn_cancel', 'speech_long', { reason: 'interrupted' }), 'driver'); await state('listening'); await sleep(400);
check('a cancelled reply leaves at once', !(await stage()).includes('白鹭'), await stage());
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 sendAll(it.slice(0, 4), 'worker-interrupt'); await state('speaking'); await sleep(1500);
await shot('w3-before-cut');
const cutSpeech = of(it, 'turn_cancel').speech_id;
const sentInterim = renumbered.filter(x => x.from === 'worker-interrupt' && x.kind === 'assistant_interim').at(-1);
await send(it[4], 'worker-interrupt'); 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 === cutSpeech).length === 0, await stage());
// Negatives, RAW. (a) The cut speech's late frames with seqs ABOVE the high-water mark: only the speech gate stops them.
const high = call.n;
await raw({ v: 2, seq: high + 1, kind: 'assistant_interim', role: 'assistant', speech_id: cutSpeech, text: '白鹭又飞回来了。' });
await raw({ v: 2, seq: high + 2, kind: 'assistant_final', role: 'assistant', speech_id: cutSpeech, turn_id: 'late', text: '白鹭又飞回来了。' });
await sleep(400);
check('negative (raw): late frames of the cut speech, fresh seqs — refused by the speech gate', !(await stage()).includes('飞回来'), await stage());
// (b) A replay of a frame already applied (same seq) and an out-of-order lower seq for a new speech: the seq gate.
await raw({ v: 2, seq: sentInterim.seq, kind: 'assistant_interim', role: 'assistant', speech_id: cutSpeech, text: '我下午去了河边。' });
await raw({ v: 2, seq: high, kind: 'turn_start', role: 'assistant', speech_id: 'speech_late', text: '' });
await raw({ v: 2, seq: high - 1, kind: 'assistant_interim', role: 'assistant', speech_id: 'speech_late', text: '乱序的旧话。' });
await sleep(400);
check('negative (raw): a replayed seq and out-of-order lower seqs — refused by the seq gate', !(await stage()).includes('乱序的旧话') && !(await stage()).includes('去了河边'), await stage());
// The next clean turn of the same recording lands with its own receipt (renumbered past everything above).
await ctl(`/__voice-turn?stage=user&turn=${encodeURIComponent(nextTurn)}&text=${encodeURIComponent('那后来呢')}`);
await ctl(`/__voice-turn?stage=reply&turn=${encodeURIComponent(nextTurn)}&text=${encodeURIComponent('后来我在桥上站了一会儿,风把水面吹皱了。')}`);
await sendAll(it.slice(5), 'worker-interrupt'); 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.split('风把水面吹皱了').length - 1 === 1, record2.slice(-120));
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 sendAll(phi, 'worker-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 of hers stays.
const nr = load('worker-no_receipt');
await ctl(`/__voice-turn?stage=user&turn=${encodeURIComponent(sidecar.scenarios.no_receipt.turn_id)}&text=${encodeURIComponent('再讲讲那座桥')}`);
await sendAll(nr.filter(f => f.kind !== 'turn_cancel'), 'worker-no_receipt'); await state('speaking'); await sleep(1500);
await send(of(nr, 'turn_cancel'), 'worker-no_receipt'); await state('listening'); await sleep(300);
check('worker frames: no legal receipt — nothing of that reply stays (cancel only, never a final)', !(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 send(of(pro.filter(f => f.message_id === 301), 'proactive_start'), 'worker-proactive'); 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 send(of(pro.filter(f => f.message_id === 301), 'proactive_end'), 'worker-proactive'); await state('listening'); await sleep(400);
await calls();
await send(pro.filter(f => f.message_id === 302)[0], 'worker-proactive'); await state('speaking'); await sleep(250);
await send(pro.filter(f => f.message_id === 302)[1], 'worker-proactive'); 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.
await send({ ...normal[2], speech_id: 'speech_text_takeover' }, 'worker-normal (speech id renamed)');
await send({ ...interims[2], speech_id: 'speech_text_takeover' }, 'worker-normal (speech id renamed)'); 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. Fix 2 in the page: the hand-built gate probes (66 later speeches, then speech_A again with fresh seqs), RAW,
// in a call of their own (their seqs are their own, from 1).
await click('.voice-row.real .voice-end'); await sleep(400);
await startVoice();
for (const f of load('adversarial-gates')) await raw(f);
// Long enough for the reading flow to reach the newest line of this turn (the lines before it take their time).
const back = await until(async () => /被挤出后的重放|迟到的旧稿/u.test(await stage()), 12000);
check('fix 2 (raw probes): a long-retired speech re-sent with fresh seqs never comes back (watched 12 s)', !back, await stage());
await raw({ v: 2, seq: call.n + 1, kind: 'turn_start', role: 'assistant', speech_id: 'speech_after_probe', text: '' });
await raw({ v: 2, seq: call.n + 1, kind: 'assistant_interim', role: 'assistant', speech_id: 'speech_after_probe', text: '还在呢。' }); await state('speaking');
check('fix 2: a new speech after the probes still comes in', await until(async () => (await stage()).includes('还在呢'), 15000), await stage());
await state('listening');
// 8. The room drops mid-sentence: everything clears with the call; starting again works.
await send(fresh('turn_start', 'speech_drop'), 'driver');
await send(fresh('assistant_interim', 'speech_drop', { text: '晚安,明天见。' }), 'driver'); 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();
await send(fresh('turn_start', 'speech_fresh'), 'driver'); await send(fresh('assistant_interim', 'speech_fresh', { text: '又见面了。' }), 'driver'); await state('speaking');
await until(async () => (await stage()).includes('又见面了'), 6000);
check('a new call is a new room and a new sequence (from 1): her words flow again, nothing of the old call remains', (await stage()).includes('又见面了') && !(await stage()).includes('晚安'), await stage());
await shot('w7-reopened');
await send(fresh('turn_end', 'speech_fresh'), 'driver'); await state('listening'); await sleep(300);
// 9. Fix 1: her worker leaves while the room stays open.
async function workerLeaves(tag) {
await calls();
await lk('__lk.guest()'); await sleep(200); await lk('__lk.guestLeave()'); await sleep(500);
check(`${tag} fix 1 negative: someone else leaving does not hang up`, (await phase()) !== 'off' && !(await status()).includes('中断'), `${await phase()} ${await status()}`);
const sid = (await ctl('/__sessions')).open.at(-1);
let gone = '';
await record(`v2-${tag}-worker-leaves`, async () => {
await send(fresh('turn_start', `speech_${tag}_left`), 'driver'); await state('speaking');
await send(fresh('assistant_interim', `speech_${tag}_left`, { text: '我先去看看窗外。' }), 'driver');
await until(async () => (await stage()).includes('窗外'), 6000); await sleep(800);
await lk('__lk.leave()');
await until(async () => (await phase()) === 'off', 3000); await sleep(300); gone = await stage();
await sleep(1500);
});
const mic = await lk(`__lk.mics.at(-1).readyState`), holder = await exists('[data-voice=her]'), log = await calls(), open = (await ctl('/__sessions')).open;
check(`${tag} fix 1: the call ends at once — her line cleared, honest notice, microphone off, her audio gone`, (await phase()) === 'off' && !gone.includes('窗外') && (await status()).includes('她那边的语音中断了') && mic === 'ended' && !holder, `${await status()} mic=${mic} holder=${holder}`);
check(`${tag} fix 1: this call's server room is deleted (once)`, log.filter(l => l === `DELETE /api/voice/session/${sid}`).length === 1 && !open.includes(sid), log.join(' | '));
await shot(`${tag}-worker-left`);
// Late events of that room (its own Disconnected, its worker "leaving" again) say nothing more.
await lk('__lk.lateLeave(-1)'); await sleep(400);
check(`${tag} fix 1: a late leave of that room changes nothing more (no second notice, no second DELETE)`, !(await calls()).some(l => l.startsWith('DELETE')), await status());
}
await workerLeaves('moon-desktop');
// An old room's worker leaving late never ends the call that replaced it; your own hang-up adds no notice.
await startVoice(); await calls();
const oldRoom = await lk('__lk.rooms.length') - 2;
await lk(`__lk.lateLeave(${oldRoom})`); await sleep(500);
check('fix 1 negative: an old room\'s late worker leave does not end the new call', (await phase()) !== 'off' && !(await status()).includes('中断'), `${await phase()} ${await status()}`);
const sid2 = (await ctl('/__sessions')).open.at(-1);
await click('.voice-row.real .voice-end'); await sleep(500);
await lk(`__lk.lateLeave(-1)`); await sleep(400);
const endLog = await calls();
check('fix 1 negative: your own hang-up — one DELETE, no "she left" notice', endLog.filter(l => l === `DELETE /api/voice/session/${sid2}`).length === 1 && !(await status()).includes('中断'), endLog.join(' | '));
// ── Second theme, phone, and reduced motion: the same worker frames and the three fixes on the approved visuals. ──
for (const [theme, v, tag, still] of [['fog', 'desktop', 'fog-desktop', false], ['moon', 'phone', 'moon-phone', false], ['fog', 'phone', 'fog-phone', false], ['moon', 'desktop', 'reduced-motion', true]]) {
await view(v); await reduce(still); 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;
let early = '';
const run = async () => {
await ctl(`/__voice-turn?stage=user&turn=${encodeURIComponent(tid)}&text=${encodeURIComponent('你在听吗')}`);
await sendAll(t.filter(f => f.seq <= 2), 'worker-normal'); await state('thinking'); await sleep(400);
await send(of(t, 'turn_start'), 'worker-normal'); await state('speaking');
for (const f of t.filter(f => f.kind === 'assistant_interim')) { await send(f, 'worker-normal'); await sleep(500); }
await until(async () => (await stage()).includes('我还在想'), 8000); early = await stage();
stored = (await rows()).filter(r => r.role === 'companion' && r.turn_id === tid).length;
await sleep(1800);
};
let stored = -1;
if (tag === 'moon-phone' || tag === 'reduced-motion') await record(`v3-${tag}-short-reply-while-speaking`, run); else await run();
check(`${tag}: her short reply is on the stage while she speaks it (before the final), approved ${theme} ${v}`, early.includes('在听呢,你刚才说到一半的那件事我还在想。') && stored === 0, early);
if (still) check('reduced motion: her words arrive without ink or slide', !(await exists('.conversation .stage .ink')), '');
await shot(`${tag}-her-words-growing`);
await ctl(`/__voice-turn?stage=reply&turn=${encodeURIComponent(tid)}&text=${encodeURIComponent('在听呢,你刚才说到一半的那件事我还在想。')}`);
await sendAll(t.filter(f => f.kind === 'assistant_final' || f.kind === 'turn_end'), 'worker-normal'); 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} (isolated record)`, rec.split('在听呢,你刚才说到一半的那件事我还在想。').length - 1 === 1, rec.slice(-120));
await click('.log-panel .btn-round'); await sleep(300);
await workerLeaves(tag);
}
writeFileSync(join(out, 'seq-renumbering.json'), JSON.stringify(renumbered, null, 1));
await reduce(false); await view('desktop');
await encodeAll();
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);