HEL-898: preserve director three-fix rework verbatim on b0dcb17

Co-authored-by: multica-agent <github@multica.ai>
This commit is contained in:
总管
2026-10-27 07:09:23 +08:00
co-authored by multica-agent
parent b0dcb17e1a
commit 9254c17316
12 changed files with 527 additions and 115 deletions
+9 -1
View File
@@ -3,7 +3,7 @@
// createLocalAudioTrack); no WebRTC, no signalling. The microphone is a real MediaStreamTrack from the browser's fake
// device (--use-fake-device-for-media-stream), so stopping it can be observed. window.__lk drives her side.
(() => {
const RoomEvent = { TrackSubscribed: 'trackSubscribed', TrackUnsubscribed: 'trackUnsubscribed', ParticipantConnected: 'participantConnected', ParticipantAttributesChanged: 'participantAttributesChanged', DataReceived: 'dataReceived', Disconnected: 'disconnected', AudioPlaybackStatusChanged: 'audioPlaybackChanged' };
const RoomEvent = { TrackSubscribed: 'trackSubscribed', TrackUnsubscribed: 'trackUnsubscribed', ParticipantConnected: 'participantConnected', ParticipantDisconnected: 'participantDisconnected', ParticipantAttributesChanged: 'participantAttributesChanged', DataReceived: 'dataReceived', Disconnected: 'disconnected', AudioPlaybackStatusChanged: 'audioPlaybackChanged' };
const lk = window.__lk = { rooms: [], connects: [], published: [], mics: [], connectDelay: 200 };
class Room {
constructor() { this.handlers = {}; this.remoteParticipants = new Map(); this.canPlaybackAudio = true; this.state = 'new'; const self = this; this.localParticipant = { tracks: [], async publishTrack(t) { if (self.state !== 'connected') throw new Error('not connected'); self.localParticipant.tracks.push(t); lk.published.push(t); } }; lk.rooms.push(this); }
@@ -28,6 +28,14 @@
lk.state = s => { const room = lk.rooms.at(-1), p = [...room.remoteParticipants.values()][0]; if (!p) return false; p.attributes['lk.agent.state'] = s; room.emit(RoomEvent.ParticipantAttributesChanged, { 'lk.agent.state': s }, p); return true; };
// Frames without an envelope get the worker's v2 one (next seq of this room); explicit frames are sent as given.
lk.say = obj => { const room = lk.rooms.at(-1), frame = 'v' in obj ? obj : { v: 2, seq: (room.seq || 0) + 1, ...obj }; if (Number.isSafeInteger(frame.seq)) room.seq = Math.max(room.seq || 0, frame.seq); room.emit(RoomEvent.DataReceived, new TextEncoder().encode(JSON.stringify(frame)), undefined, 0, 'cg.subtitle'); return true; };
// HEL-898 (f92a86f): someone leaves while the room stays connected, as the SDK reports it (removed from the map,
// then ParticipantDisconnected(participant, reason)). leave() is her worker; guest()/guestLeave() anyone else.
// `room` picks an older room (index into lk.rooms) for late events.
const part = (room, identity) => { const p = room.remoteParticipants.get(identity); if (!p) return false; room.remoteParticipants.delete(identity); room.emit(RoomEvent.ParticipantDisconnected, p, 1); return true; };
lk.leave = (at = -1) => { const room = lk.rooms.at(at), p = [...room.remoteParticipants.values()].find(x => x.kind === 4); return p ? part(room, p.identity) : false; };
lk.lateLeave = at => { const room = lk.rooms.at(at); room.emit(RoomEvent.ParticipantDisconnected, { identity: 'agent-AJ_fake', kind: 4, attributes: {} }, 1); return true; };
lk.guest = () => { const room = live(), p = { identity: 'guest-1', kind: 0, attributes: {} }; room.remoteParticipants.set(p.identity, p); room.emit(RoomEvent.ParticipantConnected, p); return true; };
lk.guestLeave = () => part(live(), 'guest-1');
lk.drop = () => { const room = live(); room.state = 'gone'; room.emit(RoomEvent.Disconnected); return true; };
lk.block = () => { const room = live(); room.canPlaybackAudio = false; room.emit(RoomEvent.AudioPlaybackStatusChanged); return true; };
async function createLocalAudioTrack(constraints) {
+11 -3
View File
@@ -18,8 +18,11 @@ const identity = { id: '1', name: '栖', birth: '2000-03-14', hour: '子', relat
const epoch = 3, log = [], rows = [], sessions = new Map(), held = new Map();
let voice = { configured: true, tts: true }, refuse = 0, made = 0, voiceTurn = 0, textStream = null;
const add = row => { const id = rows.length + 1; rows.push({ id, ts: T0 + id * 60e3, status: 'sent', lifeIds: [], ...row }); return id; };
add({ role: 'user', text: '下雨天的时候,你会想听什么?', turn_id: '00000000-0000-4000-8000-000000000001' });
add({ role: 'companion', text: '会想把窗开一条缝,听雨落在铁皮檐上。你呢,今天累不累?', turn_id: '00000000-0000-4000-8000-000000000001' });
const seed = () => {
add({ role: 'user', text: '下雨天的时候,你会想听什么?', turn_id: '00000000-0000-4000-8000-000000000001' });
add({ role: 'companion', text: '会想把窗开一条缝,听雨落在铁皮檐上。你呢,今天累不累?', turn_id: '00000000-0000-4000-8000-000000000001' });
};
seed();
const dto = r => ({ id: r.id, ts: r.ts, role: r.role, text: r.text, turn_id: r.turn_id, status: r.status, lifeIds: r.lifeIds, ...(r.proactive ? { proactive: true } : {}) });
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));
@@ -29,6 +32,10 @@ createServer(async (req, res) => {
const url = new URL(req.url, 'http://x'), p = url.pathname;
if (!p.startsWith('/__') && !p.startsWith('/assets/') && !p.startsWith('/vendor/')) log.push(`${req.method} ${p}${url.search}`);
if (p === '/__log') return send(res, 200, log.splice(0));
// HEL-898 (f92a86f): which process answers (a driver checks it started THIS mock, not someone else's service on
// the port), and a clean record for an isolated scenario (same fixture turn ids replayed per theme).
if (p === '/__pid') return send(res, 200, { pid: process.pid, mock: 'hel878' });
if (p === '/__reset') { rows.splice(0); log.splice(0); sessions.clear(); held.clear(); voiceTurn = 0; textStream = null; seed(); return send(res, 200, { rows: rows.length }); }
if (p === '/__rows') return send(res, 200, rows.map(dto));
if (p === '/__sessions') return send(res, 200, { open: [...sessions.keys()], made });
if (p === '/__voice') { voice = { configured: url.searchParams.get('configured') !== '0', tts: url.searchParams.get('tts') !== '0' }; return send(res, 200, voice); }
@@ -96,4 +103,5 @@ createServer(async (req, res) => {
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'); }
}).listen(port, '127.0.0.1', () => console.log(`hel878 mock on ${port}`));
}).on('error', e => { console.error(`hel878 mock could not listen on ${port}: ${e.code || e.message}`); process.exit(2); })
.listen(port, '127.0.0.1', () => console.log(`hel878 mock on ${port} pid ${process.pid}`));
+28 -9
View File
@@ -164,22 +164,41 @@ describe('page guards against bad frames (adversarial, hand-built)', () => {
expect(r.view().her).toMatchObject({ speech: 'speech_A', state: 'done', turnId: 'gate-turn-1' });
});
it('DOCUMENTED GAP: after 64+ later closures a retired speech falls out of the window and a duplicate start with a fresh seq re-enters', async () => {
it('a retired speech stays retired for the whole call, however many speeches closed after it (was: re-entered after 64)', async () => {
const r = await connected(), room = r.transport.rooms[0];
const frames = load('adversarial-gates');
// Up to the end of the 66 squeeze speeches: speech_A is long closed (and by now pushed
// out of the 64-entry window); nothing of it is on the page.
// Up to the end of the 66 squeeze speeches: speech_A is long closed; nothing of it is on the page.
const dupStart = frames.filter(f => f.kind === 'turn_start' && f.speech_id === 'speech_A').at(-1)!;
play(room, frames.filter(f => f.seq < dupStart.seq));
expect(r.view().her).toBeNull();
expect(dupStart.seq).toBeGreaterThan(140);
// The current worker never re-emits a speech id (each SDK speech gets a fresh id and
// interim.begin runs once per stream), so this needs a misbehaving/second source —
// but if it happens, the page DOES re-open the long-retired speech...
// The current worker never re-emits a speech id (each SDK speech gets a fresh id and interim.begin runs once
// per stream), so this needs a misbehaving/second source — a low-cost guard, not a fix of a worker fault.
// Its fresh seqs pass the sequence gate; the retired speech id does not.
const views = r.views.length;
play(room, frames.filter(f => f.seq >= dupStart.seq));
expect(r.view().her).toMatchObject({ speech: 'speech_A', state: 'done', turnId: 'gate-turn-1' });
// ...whose replayed line stands as her words again.
expect(r.view().her?.text).toBe('被挤出后的重放终稿');
expect(r.view().her).toBeNull();
expect(r.views.slice(views).some(v => v.her || v.phase !== 'listening')).toBe(false);
// The seq gate is still strict on its own: nothing at or below the high-water mark gets in.
const high = frames.at(-1)!.seq;
room.on.subtitle({ v: 2, seq: high, kind: 'turn_start', role: 'assistant', text: '', speech_id: 'speech_new' });
expect(r.view().her).toBeNull();
room.on.subtitle({ v: 2, seq: high + 1, kind: 'turn_start', role: 'assistant', text: '', speech_id: 'speech_new' });
expect(r.view().her).toEqual({ speech: 'speech_new', text: '', state: 'open' });
});
it('the retired set is per call: a new call starts clean, and an old call\'s retired ids never leak or block', async () => {
const r = await connected(), room = r.transport.rooms[0];
play(room, load('adversarial-gates'));
await r.c.end();
await r.c.start(); const next = r.transport.rooms[1]; next.on.agentJoined();
// A new worker job: its own sequence from 1. A speech id the old call retired is not this call's business.
next.on.subtitle({ v: 2, seq: 1, kind: 'turn_start', role: 'assistant', text: '', speech_id: 'speech_A' });
next.on.subtitle({ v: 2, seq: 2, kind: 'assistant_interim', role: 'assistant', text: '新的一通。', speech_id: 'speech_A' });
expect(r.view().her).toEqual({ speech: 'speech_A', text: '新的一通。', state: 'open' });
// The old room, however late, moves nothing.
room.on.subtitle({ v: 2, seq: 9999, kind: 'turn_cancel', role: 'assistant', text: '', speech_id: 'speech_A' });
expect(r.view().her?.state).toBe('open');
await r.c.end();
});
it('your interim leaves her open line to the server\'s cancel; your final closes it at once', async () => {
+241 -75
View File
@@ -2,23 +2,47 @@
// 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
// 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]
// 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] = process.argv.slice(2);
const port = Number(portArg || 8879), base = `http://127.0.0.1:${port}`, cdpPort = 9499;
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, [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 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' });
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);
@@ -28,164 +52,306 @@ ws.addEventListener('message', ({ data }) => { const m = JSON.parse(data); if (m
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 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 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 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 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 }); }
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.setItem('cg.theme', ${JSON.stringify(theme)}); sessionStorage.clear(); true`);
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 sayAll = async frames => { for (const f of frames) await say(f); };
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 boot('moon'); await click('.nav-item', '交谈'); await sleep(1400);
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): her words grow on the stage before anything is stored.
// 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;
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()));
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 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, ' '));
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); await click('.read-all'); await sleep(400); await click('.record.full .btn-round'); await sleep(300);
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 sayAll(it.slice(0, 4)); await state('speaking');
await until(async () => (await stage()).includes('白鹭'), 6000);
await sendAll(it.slice(0, 4), 'worker-interrupt'); await state('speaking'); await sleep(1500);
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.
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 sayAll(it.slice(5)); await state('speaking'); await until(async () => (await stage()).includes('桥上'), 6000); await state('listening'); await sleep(700);
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.includes('风把水面吹皱了') && record2.split('风把水面吹皱了').length - 1 === 1, record2.slice(-120).replace(/\n/g, ' '));
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 sayAll(phi); await state('speaking'); await sleep(300); await state('listening'); await sleep(300);
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 on the stage.
// 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 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());
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 say(of(pro.filter(f => f.message_id === 301), 'proactive_start')); await state('speaking'); await sleep(600);
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 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);
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.
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 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());
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');
// 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();
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 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: her words flow again, nothing of the old call remains', (await stage()).includes('又见面了') && !(await stage()).includes('晚安'), await stage());
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 click('.voice-row.real .voice-end'); await sleep(300);
await send(fresh('turn_end', 'speech_fresh'), 'driver'); await state('listening'); 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();
// 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;
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);
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 sayAll(t.filter(f => f.kind === 'assistant_final' || f.kind === 'turn_end')); await state('listening'); await sleep(800);
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}`, rec.split('在听呢,你刚才说到一半的那件事我还在想。').length - 1 === 1, '');
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 click('.voice-row.real .voice-end'); 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`);
+137
View File
@@ -0,0 +1,137 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { livekitTransport, type Livekit } from '../src/voice/livekit';
import { VoiceController, WORDS, type MicTrack, type RoomEvents, type VoiceRoom, type VoiceView } from '../src/voice/session';
// HEL-898 (f92a86f review): her worker leaving a room that stays open. Driven through the real transport adapter
// (src/voice/livekit.ts) with a scripted client that uses the vendored livekit-client 2.22.4 event names
// (RoomEvent.ParticipantDisconnected = 'participantDisconnected', emitted as (participant, reason)); no WebRTC.
const RoomEvent = { TrackSubscribed: 'trackSubscribed', TrackUnsubscribed: 'trackUnsubscribed', ParticipantConnected: 'participantConnected', ParticipantDisconnected: 'participantDisconnected', ParticipantAttributesChanged: 'participantAttributesChanged', DataReceived: 'dataReceived', Disconnected: 'disconnected', AudioPlaybackStatusChanged: 'audioPlaybackChanged' };
const AGENT = 4;
interface P { identity: string; kind?: number; attributes?: Record<string, string> }
class FakeRoom {
handlers: Record<string, ((...a: unknown[]) => void)[]> = {}; remoteParticipants = new Map<string, P>(); canPlaybackAudio = true; disconnects = 0; published: unknown[] = [];
localParticipant = { publishTrack: async (t: unknown) => { this.published.push(t); } };
constructor() { rooms.push(this); }
on(e: string, cb: (...a: unknown[]) => void) { (this.handlers[e] ||= []).push(cb); return this; }
emit(e: string, ...a: unknown[]) { (this.handlers[e] || []).forEach(cb => cb(...a)); }
async connect() {}
async disconnect() { this.disconnects++; [...this.remoteParticipants.values()].forEach(p => this.leave(p.identity)); this.emit(RoomEvent.Disconnected); }
async startAudio() {}
enter(p: P) { this.remoteParticipants.set(p.identity, p); this.emit(RoomEvent.ParticipantConnected, p); }
// As the SDK does: the participant is removed from the map, then the event carries it and a reason.
leave(identity: string) { const p = this.remoteParticipants.get(identity); if (!p) return; this.remoteParticipants.delete(identity); this.emit(RoomEvent.ParticipantDisconnected, p, 1); }
say(frame: unknown) { this.emit(RoomEvent.DataReceived, new TextEncoder().encode(JSON.stringify(frame)), undefined, 0, 'cg.subtitle'); }
}
let rooms: FakeRoom[] = [], mics: { stopped: number }[] = [];
const lk = {
Room: FakeRoom, RoomEvent, Track: { Source: { Microphone: 'microphone' } }, ParticipantKind: { AGENT },
async createLocalAudioTrack() { const m = { stopped: 0 }; mics.push(m); const mst = { stop: () => { m.stopped++; }, addEventListener() {} }; return { kind: 'audio', mediaStreamTrack: mst, attach: () => ({}), detach: () => [], stop: () => {} }; },
} as unknown as Livekit;
const worker: P = { identity: 'agent-AJ_1', kind: AGENT, attributes: { 'lk.agent.state': 'listening' } };
// The adapter keeps her audio in a hidden holder element; a node test has no DOM, so the few calls it makes are stubbed.
beforeEach(() => {
rooms = []; mics = [];
const el = () => ({ hidden: false, dataset: {}, querySelectorAll: () => [], remove() {}, append() {} });
vi.stubGlobal('document', { createElement: el, body: { append() {} } });
});
afterEach(() => { vi.unstubAllGlobals(); vi.restoreAllMocks(); });
function rig(deleteStatus = 200) {
const calls: string[] = [], views: VoiceView[] = [], record = vi.fn();
let status = deleteStatus, made = 0;
const f = vi.fn(async (url: string, init: RequestInit = {}) => {
const method = init.method || 'GET'; calls.push(`${method} ${url}`);
if (url === '/api/voice/status') return new Response(JSON.stringify({ configured: true, tts_ok: true }));
if (url === '/api/voice/session' && method === 'POST') { const id = `s${++made}`; return new Response(JSON.stringify({ url: 'wss://lk.test', token: `t-${id}`, room: `cg-voice-${id}`, session_id: id, epoch: 3, expires_at: 0 }), { status: 201 }); }
if (method === 'DELETE') return new Response('{}', { status });
return new Response('{}', { status: 404 });
});
const c = new VoiceController({ transport: async () => livekitTransport(lk), onView: v => views.push(v), onRecord: record, onSpoke: () => {}, fetch: f as unknown as typeof fetch, secure: () => true, agentWaitMs: 60000 });
return { c, calls, views, view: () => views.at(-1)!, setDelete: (s: number) => { status = s; } };
}
const flush = async () => { for (let i = 0; i < 8; i++) await Promise.resolve(); await new Promise(r => setTimeout(r, 0)); };
const deletes = (calls: string[]) => calls.filter(c => c.startsWith('DELETE'));
describe('her worker leaves while the room stays open (real adapter, SDK event names)', () => {
it('ends the call honestly: her line, microphone, audio, room and server room all go at once', async () => {
const r = rig(); await r.c.start(); const room = rooms[0];
room.enter(worker);
room.say({ v: 2, seq: 1, kind: 'user_final', role: 'user', text: '你在听吗' });
room.say({ v: 2, seq: 2, kind: 'turn_start', role: 'assistant', text: '', speech_id: 'sp' });
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(mics[0].stopped).toBeGreaterThan(0);
expect(room.disconnects).toBe(1);
expect(deletes(r.calls)).toEqual(['DELETE /api/voice/session/s1']);
// Nothing of that room is heard from again (its own Disconnected, late frames): one notice, one cleanup.
room.say({ v: 2, seq: 9, kind: 'assistant_final', role: 'assistant', text: '晚到。', speech_id: 'sp', turn_id: 'T' });
room.emit(RoomEvent.ParticipantDisconnected, worker, 1); await flush();
expect(r.views.filter(v => v.notice === WORDS.agentLeft)).toHaveLength(1);
expect(r.view().her).toBeNull();
expect(deletes(r.calls)).toHaveLength(1);
});
it('a DELETE that could not get through is owed and sent again, as any failure', async () => {
const r = rig(503); await r.c.start(); const room = rooms[0];
room.enter(worker); room.leave(worker.identity); await flush();
expect(r.view().notice).toBe(WORDS.agentLeft);
r.setDelete(404); await r.c.settle();
expect(deletes(r.calls)).toEqual(['DELETE /api/voice/session/s1', 'DELETE /api/voice/session/s1']);
});
it('anyone else leaving does not hang up; nor does a second worker leaving while hers stays', async () => {
const r = rig(); await r.c.start(); const room = rooms[0];
room.enter(worker); room.enter({ identity: 'guest-1', kind: 0, attributes: {} });
room.leave('guest-1'); await flush();
expect(r.view()).toMatchObject({ phase: 'listening', notice: '' });
room.enter({ identity: 'agent-AJ_2', kind: AGENT, attributes: {} }); room.leave('agent-AJ_2'); await flush();
expect(r.view()).toMatchObject({ phase: 'listening', notice: '' });
expect(deletes(r.calls)).toHaveLength(0);
await r.c.end();
});
it('your own hang-up says nothing more: the room closing takes her worker with it silently', async () => {
const r = rig(); await r.c.start(); const room = rooms[0];
room.enter(worker);
await r.c.end(); await flush();
expect(room.disconnects).toBe(1);
expect(r.views.some(v => v.notice)).toBe(false);
expect(deletes(r.calls)).toHaveLength(1);
});
it('an old room\'s worker leaving late never ends the new call', async () => {
const r = rig(); await r.c.start(); const first = rooms[0]; first.enter(worker);
await r.c.start(); const second = rooms[1]; second.enter({ ...worker, identity: 'agent-AJ_new' });
// The first room was closed by the restart; its handlers stay registered, and fire late.
first.emit(RoomEvent.ParticipantDisconnected, worker, 1); await flush();
expect(r.view()).toMatchObject({ phase: 'listening', notice: '' });
expect(deletes(r.calls)).toEqual(['DELETE /api/voice/session/s1']);
await r.c.end();
});
});
describe('controller: agentLeft only for this call, only once she was there', () => {
class Room implements VoiceRoom { closed = 0; on!: RoomEvents; async publish(_m: MicTrack) {} hush() {} async resumeAudio() {} async close() { this.closed++; } }
const make = () => {
const list: Room[] = [], views: VoiceView[] = [];
const transport = { capture: async () => ({ stop() {}, onEnded() {} }), join: async (_u: string, _t: string, on: RoomEvents) => { const x = new Room(); x.on = on; list.push(x); return x; } };
const f = vi.fn(async (url: string, init: RequestInit = {}) => url === '/api/voice/status' ? new Response('{"configured":true,"tts_ok":true}') : init.method === 'POST' ? new Response(JSON.stringify({ url: 'u', token: 't', room: 'r', session_id: `s${list.length + 1}`, epoch: 1, expires_at: 0 }), { status: 201 }) : new Response('{}'));
const c = new VoiceController({ transport: async () => transport, onView: v => views.push(v), onRecord: () => {}, onSpoke: () => {}, fetch: f as unknown as typeof fetch, secure: () => true, agentWaitMs: 60000 });
return { c, list, views, view: () => views.at(-1)! };
};
it('before her worker ever joined, a leave is not hers to report (the join wait says it honestly)', async () => {
const r = make(); await r.c.start();
r.list[0].on.agentLeft(); await flush();
expect(r.view()).toMatchObject({ phase: 'joining', notice: '' });
await r.c.end();
});
it('a stale call\'s agentLeft changes nothing in the new call', async () => {
const r = make(); await r.c.start(); r.list[0].on.agentJoined();
await r.c.end(); await r.c.start(); r.list[1].on.agentJoined();
r.list[0].on.agentLeft(); await flush();
expect(r.view()).toMatchObject({ phase: 'listening', notice: '' });
expect(r.list[1].closed).toBe(0);
r.list[1].on.agentLeft(); await flush();
expect(r.view()).toMatchObject({ phase: 'off', notice: WORDS.agentLeft });
expect(r.list[1].closed).toBe(1);
});
});
+33 -3
View File
@@ -533,11 +533,13 @@ describe('her voice line on the stage', () => {
const stage = (list: ShownMessage[]) => pagesOf(groupTurns(list).at(-1), metrics).map(p => `${p.key}=${p.text}`);
const you = M(4, 'user', '你在听吗?', 'T');
it('grows in her slot after your voice turn; the stored row takes over under the same line keys', () => {
const open: HerLine = { speech: 's', text: '在听呢,你刚才说到一半的那件事我一直还在心里想着。后来呢?', state: 'open' };
const open: HerLine = { speech: 's', text: '在听呢,你刚才说到一半的那件事我一直还在心里想着。后来', state: 'open' };
const growing = voiceLine(open, [you], 1)!;
expect(growing).toMatchObject({ role: 'companion', live: 'generating' });
// The newest line of a reply still growing is held back, as in a streamed text reply.
expect(growing).toMatchObject({ role: 'companion', live: 'speaking' });
// While she speaks, the sentence still forming waits; what she has finished is there.
expect(stage([you, growing])).toEqual(['T:0:0=你在听吗?', 'T:1:0=在听呢,你刚才说到一半的那件事我一直还在心里想着。']);
open.text += '呢?';
expect(stage([you, voiceLine(open, [you], 1)!])).toEqual(['T:0:0=你在听吗?', 'T:1:0=在听呢,你刚才说到一半的那件事我一直还在心里想着。', 'T:1:1=后来呢?']);
const done: HerLine = { ...open, state: 'done', turnId: 'T' };
const shown = stage([you, voiceLine(done, [you], 1)!]);
expect(shown).toEqual(['T:0:0=你在听吗?', 'T:1:0=在听呢,你刚才说到一半的那件事我一直还在心里想着。', 'T:1:1=后来呢?']);
@@ -545,6 +547,34 @@ describe('her voice line on the stage', () => {
expect(voiceLine(done, stored, 1)).toBeNull();
expect(stage(stored)).toEqual(shown);
});
it('a short spoken reply is on the stage while she says it, not only once it is stored (HEL-898 f92a86f)', () => {
const at = (text: string) => stage([you, voiceLine({ speech: 's', text, state: 'open' }, [you], 1)!]);
// worker-normal.jsonl, interim by interim: nothing of hers until a sentence is finished, then the whole of it.
expect(at('在听呢,')).toEqual(['T:0:0=你在听吗?']);
expect(at('在听呢,你刚才说到一半的那件事')).toEqual(['T:0:0=你在听吗?']);
expect(at('在听呢,你刚才说到一半的那件事我还在想。')).toEqual(['T:0:0=你在听吗?', 'T:1:0=在听呢,你刚才说到一半的那件事我还在想。']);
// Her final and her stored row keep exactly that line under that key: nothing moves when it is stored.
expect(stage([you, voiceLine({ speech: 's', text: '在听呢,你刚才说到一半的那件事我还在想。', state: 'final', turnId: 'T' }, [you], 1)!])).toEqual(at('在听呢,你刚才说到一半的那件事我还在想。'));
expect(stage([you, M(5, 'companion', '在听呢,你刚才说到一半的那件事我还在想。', 'T')])).toEqual(at('在听呢,你刚才说到一半的那件事我还在想。'));
// A very short sentence shows at once; the next one joins the same line (it only ever grows, never shrinks).
expect(at('嗯。')).toEqual(['T:0:0=你在听吗?', 'T:1:0=嗯。']);
expect(at('嗯。我在')).toEqual(['T:0:0=你在听吗?', 'T:1:0=嗯。']);
expect(at('嗯。我在。')).toEqual(['T:0:0=你在听吗?', 'T:1:0=嗯。我在。']);
expect(at('“好啊。”')).toEqual(['T:0:0=你在听吗?', 'T:1:0=“好啊。”']);
});
it('a long spoken reply still reads one or two sentences at a time; a text stream keeps holding its newest line', () => {
const long = '我下午去了河边,看到一群白鹭从水面上飞过去了,它们飞得很低,几乎贴着水,翅膀尖在水面上划出一道一道细细的白线,后来又绕回来落在对岸的芦苇里';
const lines = stage([you, voiceLine({ speech: 's', text: long, state: 'open' }, [you], 1)!]).slice(1);
// Every finished line of a long sentence is shown; the part still being said waits; no line is the whole text.
expect(lines.length).toBeGreaterThan(0);
expect(lines.every(l => l.length - 'T:1:0='.length <= 60)).toBe(true);
expect(lines.join('')).not.toContain('芦苇里');
const full = stage([you, voiceLine({ speech: 's', text: long + '。', state: 'final', turnId: 'T' }, [you], 1)!]).slice(1);
expect(full.slice(0, lines.length)).toEqual(lines);
// The text chat's own rule is untouched: a streamed reply holds back its newest chunk even when it is a sentence.
const typed = pagesOf(groupTurns([you, { ...M(9, 'companion', '在听呢,你刚才说到一半的那件事我还在想。', 'T'), live: 'generating' }]).at(-1), metrics);
expect(typed.map(p => p.text)).toEqual(['你在听吗?']);
});
it('a finished line never stands in front of a newer turn; an open one waits for its own end', () => {
const done: HerLine = { speech: 's', text: '好。', state: 'done', turnId: 'T' };
expect(voiceLine(done, [you, M(6, 'user', '还有', 'U')], 1)).toBeNull();