HEL-898: preserve director v2 subtitle wiring verbatim on fc905fe
Co-authored-by: multica-agent <github@multica.ai>
This commit is contained in:
@@ -26,7 +26,8 @@
|
||||
return true;
|
||||
};
|
||||
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; };
|
||||
lk.say = obj => { const room = lk.rooms.at(-1); room.emit(RoomEvent.DataReceived, new TextEncoder().encode(JSON.stringify(obj)), undefined, 0, 'cg.subtitle'); 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; };
|
||||
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) {
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// answered with tests/fake-livekit.js (a scripted stand-in, no WebRTC); the real vendored build stays reachable at
|
||||
// /__real-sdk.js for the API-surface check only. Synthetic data only: no model, no LiveKit, no TTS, no network.
|
||||
// Usage: node tests/hel878_mock.mjs <port>. Control GETs: /__voice?configured=&tts=, /__refuse/<code|0>,
|
||||
// /__voice-turn?stage=user|reply|cancel&text=, /__cut, /__sessions, /__log, /__rows.
|
||||
// /__voice-turn?stage=user|reply|cancel&text=, /__proactive?text=, /__cut, /__sessions, /__log, /__rows.
|
||||
import { createServer } from 'node:http';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { extname, join, normalize } from 'node:path';
|
||||
@@ -41,6 +41,8 @@ createServer(async (req, res) => {
|
||||
if (stage === 'cancel') rows.forEach(r => { if (r.turn_id === `voice-${voiceTurn}`) r.status = 'cancelled'; });
|
||||
return send(res, 200, { turn: voiceTurn });
|
||||
}
|
||||
// A reach-out the life runtime stored (HEL-898): the worker may read it aloud; the page sees it through the inbox.
|
||||
if (p === '/__proactive') { const id = add({ role: 'companion', text: url.searchParams.get('text') || '', turn_id: `pro-${rows.length + 1}`, proactive: true }); return send(res, 200, { id }); }
|
||||
// A voice turn took the server's turn gate: the text stream in flight ends without a final; its row is cancelled.
|
||||
if (p === '/__cut') { const s = textStream; textStream = null; if (s) { rows.forEach(r => { if (r.turn_id === s.turn_id && r.role === 'user') r.status = 'cancelled'; }); s.cut = true; s.res.end(); } return send(res, 200, { cut: !!s }); }
|
||||
if (p === '/__real-sdk.js') return send(res, 200, await readFile(join(dist, 'vendor/livekit-client-2.22.4.umd.min.js')), 'text/javascript');
|
||||
|
||||
@@ -114,7 +114,7 @@ check('speaking: her name, and that you can cut in by speaking', (await row()).i
|
||||
await frames('m2-voice-speaking', 900);
|
||||
await shot('08-moon-desktop-voice-speaking');
|
||||
await ctl('/__voice-turn?stage=reply&text=' + encodeURIComponent('是橘色的那只吗?它最近总在桥下晒太阳。'));
|
||||
await lk(`__lk.say({ kind: 'assistant_final', role: 'assistant', text: '是橘色的那只吗?它最近总在桥下晒太阳。' })`); await lk(`__lk.state('listening')`);
|
||||
await lk(`__lk.say({ kind: 'turn_start', role: 'assistant', text: '', speech_id: 'sp-878-1' })`); await lk(`__lk.say({ kind: 'assistant_final', role: 'assistant', text: '是橘色的那只吗?它最近总在桥下晒太阳。', speech_id: 'sp-878-1', turn_id: 'voice-1' })`); await lk(`__lk.say({ kind: 'turn_end', role: 'assistant', text: '', speech_id: 'sp-878-1', turn_id: 'voice-1' })`); await lk(`__lk.state('listening')`);
|
||||
await until(async () => (await said()).includes('晒太阳'), 6000);
|
||||
check('her spoken answer reaches the stage once it is in the record', (await said()).includes('晒太阳'), await said());
|
||||
await shot('09-moon-desktop-voice-reply-on-stage');
|
||||
@@ -125,7 +125,7 @@ await shot('10-moon-desktop-voice-record');
|
||||
await click('.log-panel .btn-round'); await sleep(400);
|
||||
|
||||
// ── 6. φ: her failure line is heard and shown, never recorded. ──
|
||||
await lk(`__lk.say({ kind: 'error', role: 'assistant', text: '我刚刚没接上话,你再说一遍好吗?' })`); await sleep(400);
|
||||
await lk(`__lk.say({ kind: 'turn_start', role: 'assistant', text: '', speech_id: 'sp-878-phi' })`); await lk(`__lk.say({ kind: 'error', role: 'assistant', text: '我刚刚没接上话,你再说一遍好吗?', speech_id: 'sp-878-phi' })`); await lk(`__lk.say({ kind: 'turn_cancel', role: 'assistant', text: '', speech_id: 'sp-878-phi', reason: 'error_phi' })`); await sleep(400);
|
||||
check('φ line shown as heard, marked not recorded; not in the record', (await row()).includes('没接上话') && (await row()).includes('未记入聊天') && !(await ctl('/__rows')).some(r => r.text.includes('没接上话')));
|
||||
await shot('11-moon-desktop-voice-phi');
|
||||
|
||||
|
||||
@@ -0,0 +1,172 @@
|
||||
// HEL-898 browser check: her words while she speaks (cg.subtitle contract v2) on the approved conversation. Drives
|
||||
// headless Edge over CDP against tests/hel878_mock.mjs, with tests/fake-livekit.js in place of the LiveKit client and
|
||||
// Chromium's fake audio device in place of a microphone: no model, no TTS, no real call. Frames are the worker's v2
|
||||
// envelopes (docs/voice-subtitle-contract-v2.md). Usage: node tests/hel898_shots.mjs <edge.exe> <outDir> [port].
|
||||
import { spawn } from 'node:child_process';
|
||||
import { mkdirSync, writeFileSync, rmSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { tmpdir } from 'node:os';
|
||||
|
||||
const [edge, out, portArg] = process.argv.slice(2);
|
||||
const port = Number(portArg || 8878), base = `http://127.0.0.1:${port}`, cdpPort = 9498;
|
||||
mkdirSync(out, { recursive: true });
|
||||
const profile = join(tmpdir(), `hel898-edge-${Date.now()}`);
|
||||
const browser = spawn(edge, ['--headless=new', `--remote-debugging-port=${cdpPort}`, `--user-data-dir=${profile}`, '--no-first-run', '--hide-scrollbars', '--force-color-profile=srgb', '--use-fake-device-for-media-stream', '--use-fake-ui-for-media-stream', '--autoplay-policy=no-user-gesture-required', 'about:blank'], { stdio: 'ignore' });
|
||||
const sleep = ms => new Promise(r => setTimeout(r, ms));
|
||||
let targets;
|
||||
for (let i = 0; i < 60 && !targets; i++) { try { targets = await (await fetch(`http://127.0.0.1:${cdpPort}/json`)).json(); } catch { await sleep(250); } }
|
||||
const ws = new WebSocket(targets.find(t => t.type === 'page').webSocketDebuggerUrl);
|
||||
await new Promise(r => ws.addEventListener('open', r, { once: true }));
|
||||
let id = 0; const waiting = new Map();
|
||||
ws.addEventListener('message', ({ data }) => { const m = JSON.parse(data); if (m.id && waiting.has(m.id)) { const { ok, ko } = waiting.get(m.id); waiting.delete(m.id); m.error ? ko(new Error(m.error.message)) : ok(m.result); } });
|
||||
const cdp = (method, params = {}) => new Promise((ok, ko) => { const n = ++id; waiting.set(n, { ok, ko }); ws.send(JSON.stringify({ id: n, method, params })); });
|
||||
const js = async expr => { const r = await cdp('Runtime.evaluate', { expression: expr, returnByValue: true, awaitPromise: true }); if (r.exceptionDetails) throw new Error(r.exceptionDetails.exception?.description || 'js error'); return r.result.value; };
|
||||
const results = [];
|
||||
const check = (name, ok, detail = '') => { results.push(ok); console.log(`${ok ? 'PASS' : 'FAIL'} ${name}${detail ? ` — ${detail}` : ''}`); };
|
||||
const ctl = async path => (await fetch(`${base}${path}`)).json();
|
||||
const shot = async name => { const { data } = await cdp('Page.captureScreenshot', { format: 'png' }); writeFileSync(join(out, `${name}.png`), Buffer.from(data, 'base64')); };
|
||||
const frames = async (name, ms) => { const list = []; const end = Date.now() + ms; while (Date.now() < end) { const { data } = await cdp('Page.captureScreenshot', { format: 'jpeg', quality: 70 }); list.push(data); } list.forEach((d, i) => writeFileSync(join(out, `${name}-${String(i).padStart(2, '0')}.jpg`), Buffer.from(d, 'base64'))); return list.length; };
|
||||
const click = async (selector, text = '') => js(`(() => { const el = [...document.querySelectorAll(${JSON.stringify(selector)})].find(e => e.offsetParent !== null && e.textContent.includes(${JSON.stringify(text)})); if (!el) return false; el.click(); return true; })()`);
|
||||
const text = sel => js(`[...document.querySelectorAll(${JSON.stringify(sel)})].map(e => e.innerText).join('\\n')`);
|
||||
const exists = sel => js(`!!document.querySelector(${JSON.stringify(sel)})`);
|
||||
// The stage's own text (every line now on it) and the line read out to assistive tech.
|
||||
const stage = () => js(`document.querySelector('.conversation .stage')?.innerText || ''`);
|
||||
const said = () => js(`document.querySelector('.conversation .sr')?.textContent || ''`);
|
||||
const row = () => js(`document.querySelector('.voice-row.real')?.innerText || ''`);
|
||||
const phase = () => js(`document.querySelector('.voice-row.real')?.dataset.phase || 'off'`);
|
||||
const lk = expr => js(`window.__lk ? (${expr}) : null`);
|
||||
const say = frame => lk(`__lk.say(${JSON.stringify(frame)})`);
|
||||
const her = (kind, speech, extra = {}) => say({ kind, role: 'assistant', text: '', speech_id: speech, ...extra });
|
||||
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 views = { desktop: { width: 1440, height: 900, deviceScaleFactor: 1, mobile: false }, phone: { width: 390, height: 844, deviceScaleFactor: 2, mobile: true } };
|
||||
async function view(v) { await cdp('Emulation.setDeviceMetricsOverride', views[v]); await cdp('Emulation.setTouchEmulationEnabled', { enabled: views[v].mobile, maxTouchPoints: 5 }); }
|
||||
async function boot(theme) {
|
||||
await cdp('Page.navigate', { url: `${base}/` }); await sleep(500);
|
||||
await js(`localStorage.setItem('cg.theme', ${JSON.stringify(theme)}); sessionStorage.clear(); true`);
|
||||
await cdp('Page.navigate', { url: `${base}/` }); await sleep(1600);
|
||||
}
|
||||
async function startVoice() {
|
||||
await click('.voice-button'); await until(() => exists('.modal.open'));
|
||||
await click('.modal.open .btn-primary', '开始语音');
|
||||
await until(async () => (await phase()) === 'joining');
|
||||
await until(async () => (await lk('__lk.rooms.at(-1)?.state')) === 'connected');
|
||||
await lk('__lk.join()'); await sleep(200);
|
||||
}
|
||||
const calls = async () => ctl('/__log');
|
||||
// One voice turn of yours as the worker leaves it: the stored row, then user_final; waits for it on the stage.
|
||||
const youSay = async words => {
|
||||
const { turn } = await ctl('/__voice-turn?stage=user&text=' + encodeURIComponent(words));
|
||||
await say({ kind: 'user_final', role: 'user', text: words }); await lk(`__lk.state('thinking')`);
|
||||
await until(async () => (await stage()).includes(words.slice(0, 4)), 6000);
|
||||
return turn;
|
||||
};
|
||||
const rows = async () => ctl('/__rows');
|
||||
await cdp('Page.enable'); await cdp('Runtime.enable'); await cdp('Network.enable');
|
||||
|
||||
const REPLY = '是橘色的那只吗?它最近总在桥下晒太阳,尾巴一甩一甩的,好像整座桥都是它的。你下次路过可以叫它一声,它会回头看你。';
|
||||
const STEPS = ['是橘色的那只吗?它最近总在桥下晒太阳,', '是橘色的那只吗?它最近总在桥下晒太阳,尾巴一甩一甩的,好像整座桥都是它的。', `${REPLY}`];
|
||||
|
||||
for (const [theme, v] of [['moon', 'desktop'], ['fog', 'desktop'], ['moon', 'phone'], ['fog', 'phone']]) {
|
||||
const tag = `${theme}-${v}`;
|
||||
await view(v); await boot(theme); await click('.nav-item', '交谈'); await sleep(1400);
|
||||
await startVoice(); await calls();
|
||||
|
||||
// ── 1. A voice turn: your draft and final, then her words growing on the stage before anything is stored. ──
|
||||
await say({ kind: 'interim', role: 'user', text: '今天下班的路上' }); await sleep(200);
|
||||
const prior = (await rows()).filter(r => r.text === REPLY).length;
|
||||
const turn = await youSay('今天下班的路上看到一只猫');
|
||||
await her('turn_start', `a-${tag}`); await lk(`__lk.state('speaking')`);
|
||||
const shots = [];
|
||||
for (const [i, step] of STEPS.entries()) {
|
||||
await her('assistant_interim', `a-${tag}`, { text: step });
|
||||
shots.push(frames(`${tag}-m1-growing-${i}`, 450));
|
||||
await shots.at(-1);
|
||||
}
|
||||
await until(async () => (await stage()).includes('晒太阳'), 8000);
|
||||
check(`${tag}: her reply shows on the stage while she speaks, before it is stored`, (await stage()).includes('晒太阳') && (await rows()).filter(r => r.text === REPLY).length === prior, await stage());
|
||||
check(`${tag}: your draft stays in the voice line, her words never there`, !(await row()).includes('晒太阳'), await row());
|
||||
await shot(`${tag}-01-her-words-growing`);
|
||||
|
||||
// ── 2. Pause and look back while she is still speaking: reading holds, nothing jumps. ──
|
||||
await click('.reader-bar .flow'); await sleep(300);
|
||||
check(`${tag}: pause while she speaks`, await exists('.conversation.reading-paused'));
|
||||
await click('.reader-bar .icon[aria-label="上一句"]'); await sleep(400);
|
||||
await shot(`${tag}-02-paused-looking-back`);
|
||||
await ctl('/__voice-turn?stage=reply&text=' + encodeURIComponent(REPLY));
|
||||
await her('assistant_final', `a-${tag}`, { text: REPLY, turn_id: `voice-${turn}` }); await her('turn_end', `a-${tag}`, { turn_id: `voice-${turn}` }); await lk(`__lk.state('listening')`);
|
||||
await sleep(900);
|
||||
await click('.reader-bar .latest'); await sleep(2500);
|
||||
await click('.log-btn'); await sleep(700);
|
||||
const rec = await text('.log-panel .scroll');
|
||||
check(`${tag}: once stored, the record holds her reply exactly once (re-read, not written by the page)`, rec.split(REPLY).length - 1 === prior + 1, rec.slice(-160).replace(/\n/g, ' '));
|
||||
await shot(`${tag}-03-record-after-final`);
|
||||
await click('.log-panel .btn-round'); await sleep(400);
|
||||
await click('.read-all'); await sleep(500); await shot(`${tag}-04-full-text`); await click('.record.full .btn-round'); await sleep(300);
|
||||
|
||||
// ── 3. Interrupted: no final; her line goes at once; late frames of the cut turn change nothing. ──
|
||||
// Paused reading, then you speak: like sending, your new turn and her answer come in by themselves.
|
||||
await click('.reader-bar .flow'); await sleep(200);
|
||||
check(`${tag}: paused before speaking`, await exists('.conversation.reading-paused'));
|
||||
await youSay('你今天去哪儿了');
|
||||
check(`${tag}: speaking resumes reading for the new turn`, !(await exists('.conversation.reading-paused')));
|
||||
await her('turn_start', `b-${tag}`); await lk(`__lk.state('speaking')`);
|
||||
await her('assistant_interim', `b-${tag}`, { text: '对了,我今天下午去了河边,看到一群白鹭从水面上飞过去了。它们飞得很低,' });
|
||||
check(`${tag}: second reply growing`, await until(async () => (await stage()).includes('白鹭'), 8000), await stage());
|
||||
await shot(`${tag}-05-before-cut`);
|
||||
await say({ kind: 'interim', role: 'user', text: '等一下' });
|
||||
await her('turn_cancel', `b-${tag}`, { reason: 'interrupted' }); await lk(`__lk.state('listening')`); await ctl('/__voice-turn?stage=cancel');
|
||||
await sleep(150);
|
||||
check(`${tag}: interrupted: her unfinished line is gone at once`, !(await stage()).includes('白鹭'), await stage());
|
||||
await her('assistant_interim', `b-${tag}`, { text: '对了,我今天下午去了河边,看到一群白鹭从水面上飞过去了。它们飞得很低,真好看。' });
|
||||
await her('assistant_final', `b-${tag}`, { text: '对了,我今天下午去了河边,看到一群白鹭从水面上飞过去了。它们飞得很低,真好看。', turn_id: 'late' });
|
||||
await sleep(400);
|
||||
check(`${tag}: late frames of the cut turn stay out`, !(await stage()).includes('白鹭'));
|
||||
await shot(`${tag}-06-after-cut`);
|
||||
|
||||
// ── 4. Text takes over while she speaks: her line goes, your typed words come next. ──
|
||||
await youSay('我们聊点别的吧');
|
||||
await her('turn_start', `c-${tag}`); await lk(`__lk.state('speaking')`);
|
||||
await her('assistant_interim', `c-${tag}`, { text: '那我们换个话题吧,你今天晚饭吃了什么,好不好吃?我今天' });
|
||||
check(`${tag}: her line before you type`, await until(async () => (await stage()).includes('换个话题'), 8000), await stage());
|
||||
await type('先等等,我打字说'); await js(`document.querySelector('.send').click(), true`); await sleep(400);
|
||||
check(`${tag}: text over voice: her line is gone, your words are on the stage`, !(await stage()).includes('换个话题') && (await stage()).includes('先等等'), await stage());
|
||||
await until(async () => !(await exists('.reader-bar .stop')), 9000); await lk(`__lk.state('listening')`); await sleep(400);
|
||||
|
||||
// ── 5. A stored reach-out read aloud: its own text in her place, no request, no read mark, interruptible. ──
|
||||
const { id: pro } = await ctl('/__proactive?text=' + encodeURIComponent('刚才路过花店,想起你说过喜欢白色的洋桔梗。'));
|
||||
await calls();
|
||||
await say({ kind: 'proactive_start', role: 'assistant', text: '刚才路过花店,想起你说过喜欢白色的洋桔梗。', speech_id: `p-${tag}`, message_id: pro }); await lk(`__lk.state('speaking')`);
|
||||
await sleep(1500);
|
||||
check(`${tag}: reach-out shown in her place, word for word`, (await stage()).includes('洋桔梗'), await stage());
|
||||
await shot(`${tag}-07-reach-out`);
|
||||
await say({ kind: 'interim', role: 'user', text: '是吗' });
|
||||
await say({ kind: 'proactive_cancel', role: 'assistant', text: '', speech_id: `p-${tag}`, message_id: pro, reason: 'interrupted' }); await lk(`__lk.state('listening')`);
|
||||
await sleep(200);
|
||||
const after = await calls();
|
||||
check(`${tag}: reach-out cut: cleared; the page wrote nothing (no receipt, no read mark, no message)`, !after.some(l => !l.startsWith('GET ')) , after.join(' | '));
|
||||
|
||||
// ── 6. Hanging up mid-sentence clears her line with the call. ──
|
||||
await youSay('我先去睡了');
|
||||
await her('turn_start', `d-${tag}`); await her('assistant_interim', `d-${tag}`, { text: '晚安,明天见。今天说了好多好多话,你要早点睡哦。我会在窗边等你,' });
|
||||
check(`${tag}: her line before hanging up`, await until(async () => (await stage()).includes('早点睡'), 8000), await stage());
|
||||
await click('.voice-row.real .voice-end'); await sleep(400);
|
||||
check(`${tag}: hung up: her line gone, voice off`, !(await stage()).includes('早点睡') && (await phase()) === 'off', await stage());
|
||||
await shot(`${tag}-08-ended`);
|
||||
}
|
||||
|
||||
// ── 7. Reduced motion: her words still arrive, without animated entrances. ──
|
||||
await view('desktop'); await cdp('Emulation.setEmulatedMedia', { features: [{ name: 'prefers-reduced-motion', value: 'reduce' }] });
|
||||
await boot('moon'); await click('.nav-item', '交谈'); await sleep(1400); await startVoice();
|
||||
await youSay('慢一点说给我听');
|
||||
await her('turn_start', 'rm'); await lk(`__lk.state('speaking')`);
|
||||
for (const step of STEPS) { await her('assistant_interim', 'rm', { text: step }); await sleep(300); }
|
||||
check('reduced motion: her words arrive', await until(async () => (await stage()).includes('晒太阳'), 8000), await stage());
|
||||
await frames('reduced-motion-growing', 600);
|
||||
await click('.voice-row.real .voice-end'); await sleep(300);
|
||||
|
||||
ws.close(); browser.kill();
|
||||
try { rmSync(profile, { recursive: true, force: true }); } catch { /* Edge may still hold the profile. */ }
|
||||
const failed = results.filter(r => !r).length;
|
||||
console.log(`${results.length - failed}/${results.length} passed`);
|
||||
process.exit(failed ? 1 : 0);
|
||||
+209
-12
@@ -1,7 +1,13 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { mergeTurns, recentRows, VoiceController, voiceStatus, WORDS, type MicTrack, type RoomEvents, type VoiceRoom, type VoiceView } from '../src/voice/session';
|
||||
import { mergeTurns, recentRows, VoiceController, voiceLine, voiceStatus, WORDS, type HerLine, type MicTrack, type RoomEvents, type VoiceRoom, type VoiceView } from '../src/voice/session';
|
||||
import { groupTurns, pagesOf, type ShownMessage } from '../src/chat/reading';
|
||||
import type { ServerMessage } from '../src/adapters/real';
|
||||
import type { Message } from '../src/domain/model';
|
||||
import { readFileSync } from 'node:fs';
|
||||
|
||||
// The backend's recorded cg.subtitle frames (contract v2, docs/rework/hel879/subtitle-samples, generated offline).
|
||||
type Frame = Record<string, unknown> & { seq: number };
|
||||
const sample = (name: string): Frame[] => readFileSync(new URL(`../../docs/rework/hel879/subtitle-samples/${name}.jsonl`, import.meta.url), 'utf8').split('\n').filter(l => l.trim()).map(l => JSON.parse(l));
|
||||
|
||||
// Fake transport and media objects: no LiveKit, no microphone, no network. The fake server follows the HEL-877 voice
|
||||
// router (src/cybergril/voice/router.py): GET /api/voice/status, POST /api/voice/session -> 201 grant, DELETE
|
||||
@@ -176,7 +182,7 @@ describe('lifecycle', () => {
|
||||
const r = await connected(), old = r.transport.rooms[0];
|
||||
await r.c.end(); r.record.mockClear();
|
||||
const seen = r.views.length;
|
||||
old.on.agentState('speaking'); old.on.subtitle({ kind: 'user_final', role: 'user', text: '旧的话' }); old.on.agentJoined(); old.on.dropped(); old.on.audioBlocked(true);
|
||||
old.on.agentState('speaking'); old.on.subtitle({ v: 2, seq: 1, kind: 'user_final', role: 'user', text: '旧的话' }); old.on.subtitle({ v: 2, seq: 2, kind: 'turn_start', role: 'assistant', text: '', speech_id: 'old' }); old.on.agentJoined(); old.on.dropped(); old.on.audioBlocked(true);
|
||||
r.transport.mics[0].ended?.();
|
||||
await flush();
|
||||
expect(r.views.length).toBe(seen);
|
||||
@@ -243,10 +249,12 @@ describe('lifecycle', () => {
|
||||
});
|
||||
it('never confirms a receipt or posts chat itself: the worker owns both', async () => {
|
||||
const r = await connected(), room = r.transport.rooms[0];
|
||||
room.on.subtitle({ kind: 'user_final', role: 'user', text: '今天好冷' });
|
||||
room.on.subtitle({ kind: 'assistant_final', role: 'assistant', text: '那多穿一件。' });
|
||||
for (const line of sample('normal-turn')) room.on.subtitle(line);
|
||||
for (const line of sample('proactive')) room.on.subtitle({ ...line, seq: line.seq + 100 });
|
||||
await r.c.end();
|
||||
expect(r.server.calls.some(c => c.url.startsWith('/api/chat'))).toBe(false);
|
||||
// No receipt, no read mark, no message write: the page only talks to the voice routes.
|
||||
expect(r.server.calls.every(c => c.url.startsWith('/api/voice/'))).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -338,24 +346,32 @@ describe('a late end of an older call', () => {
|
||||
});
|
||||
});
|
||||
|
||||
// A v2 frame as the worker's SubtitleBus emits it (src/cybergril/voice/seam.py).
|
||||
const frame = (seq: number, kind: string, extra: Record<string, unknown> = {}) => ({ v: 2, seq, kind, role: kind === 'interim' || kind === 'user_final' ? 'user' : 'assistant', text: '', ...extra });
|
||||
describe('subtitles and the two channels', () => {
|
||||
it('interim is a draft; user_final cancels a text reply and asks for the record; φ is heard but not recorded', async () => {
|
||||
const r = await connected(), room = r.transport.rooms[0];
|
||||
room.on.subtitle({ kind: 'interim', role: 'user', text: '今天' });
|
||||
room.on.subtitle(frame(1, 'interim', { text: '今天' }));
|
||||
expect(r.view().heard).toBe('今天'); expect(r.record).not.toHaveBeenCalled();
|
||||
room.on.subtitle({ kind: 'user_final', role: 'user', text: '今天好冷' });
|
||||
room.on.subtitle(frame(2, 'user_final', { text: '今天好冷' }));
|
||||
expect(r.spoke).toHaveBeenCalledTimes(1); expect(r.record).toHaveBeenCalledTimes(1);
|
||||
room.on.subtitle({ kind: 'error', role: 'assistant', text: '我刚才走神了,你再说一遍?' });
|
||||
expect(r.view().spoken).toBe('我刚才走神了,你再说一遍?');
|
||||
room.on.subtitle({ kind: 'assistant_final', role: 'assistant', text: '那多穿一件。' });
|
||||
expect(r.view()).toMatchObject({ heard: '', spoken: '' });
|
||||
room.on.subtitle(frame(3, 'turn_start', { speech_id: 'a' }));
|
||||
room.on.subtitle(frame(4, 'assistant_interim', { speech_id: 'a', text: '我刚' }));
|
||||
room.on.subtitle(frame(5, 'error', { speech_id: 'a', text: '我刚才走神了,你再说一遍?' }));
|
||||
expect(r.view()).toMatchObject({ spoken: '我刚才走神了,你再说一遍?', her: null });
|
||||
room.on.subtitle(frame(6, 'turn_cancel', { speech_id: 'a', reason: 'error_phi' }));
|
||||
expect(r.view()).toMatchObject({ spoken: '我刚才走神了,你再说一遍?', her: null });
|
||||
room.on.subtitle(frame(7, 'assistant_interim', { speech_id: 'a', text: '我刚才走神了' })); // after its cancel
|
||||
expect(r.view().her).toBeNull();
|
||||
room.on.subtitle({ kind: 'bogus', text: 1 }); room.on.subtitle(null);
|
||||
expect(r.record).toHaveBeenCalledTimes(3);
|
||||
expect(r.server.calls.some(c => c.url.startsWith('/api/chat') || c.url.startsWith('/api/messages'))).toBe(false);
|
||||
});
|
||||
it('without the agent state attribute, subtitles still move the state honestly', async () => {
|
||||
const r = await connected(), room = r.transport.rooms[0];
|
||||
room.on.subtitle({ kind: 'user_final', role: 'user', text: '在吗' }); expect(r.view().phase).toBe('thinking');
|
||||
room.on.subtitle({ kind: 'assistant_final', role: 'assistant', text: '在。' }); expect(r.view().phase).toBe('listening');
|
||||
room.on.subtitle(frame(1, 'user_final', { text: '在吗' })); expect(r.view().phase).toBe('thinking');
|
||||
room.on.subtitle(frame(2, 'turn_start', { speech_id: 'a' })); expect(r.view().phase).toBe('thinking');
|
||||
room.on.subtitle(frame(3, 'assistant_final', { speech_id: 'a', turn_id: 't', text: '在。' })); expect(r.view().phase).toBe('listening');
|
||||
});
|
||||
it('typing over her spoken answer silences what is left of it until she is listening again', async () => {
|
||||
const r = await connected(), room = r.transport.rooms[0];
|
||||
@@ -367,6 +383,187 @@ describe('subtitles and the two channels', () => {
|
||||
});
|
||||
});
|
||||
|
||||
// HEL-898: her words while she speaks (contract v2). The page shows them; it never stores, confirms or marks them.
|
||||
describe('her voice line (cg.subtitle v2)', () => {
|
||||
const play = (room: Room, frames: Frame[], after?: (f: Frame) => void) => { for (const f of frames) { room.on.subtitle(f); after?.(f); } };
|
||||
it('rejects anything that is not exactly a v2 frame', async () => {
|
||||
const r = await connected(), room = r.transport.rooms[0], seen = r.views.length;
|
||||
const bad = [
|
||||
{ kind: 'user_final', role: 'user', text: 'v1 没有信封' },
|
||||
{ ...frame(1, 'user_final', { text: '版本不对' }), v: 3 },
|
||||
{ ...frame(1, 'user_final', { text: '序号不对' }), seq: 0 },
|
||||
{ ...frame(1, 'user_final', { text: '序号不对' }), seq: 1.5 },
|
||||
{ ...frame(1, 'user_final', { text: '序号不对' }), seq: '1' },
|
||||
frame(1, 'turn_start'), // no speech_id
|
||||
{ ...frame(1, 'turn_start', { speech_id: 'a' }), role: 'user' }, // her kind, your role
|
||||
{ ...frame(1, 'interim', { text: '草稿' }), role: 'assistant' }, // your kind, her role
|
||||
frame(1, 'assistant_final', { speech_id: 'a', text: '无归属' }), // final without turn_id
|
||||
frame(1, 'proactive_start', { speech_id: 'p', text: '无行号' }), // reach-out without message_id
|
||||
frame(1, 'proactive_start', { speech_id: 'p', text: '行号不对', message_id: '17' }),
|
||||
frame(1, 'assistant_text', { speech_id: 'a', text: '未知种类' }),
|
||||
[frame(1, 'user_final', { text: '数组' })],
|
||||
];
|
||||
for (const b of bad) room.on.subtitle(b);
|
||||
expect(r.views.length).toBe(seen); expect(r.record).not.toHaveBeenCalled(); expect(r.spoke).not.toHaveBeenCalled();
|
||||
// A rejected frame does not move the sequence: the first good one still lands.
|
||||
room.on.subtitle(frame(1, 'interim', { text: '好的' })); expect(r.view().heard).toBe('好的');
|
||||
});
|
||||
it('normal turn: your draft and final, her growing reply replaced in place, then her stored final', async () => {
|
||||
const r = await connected(), room = r.transport.rooms[0], frames = sample('normal-turn');
|
||||
const steps: (VoiceView['her'] | string)[] = [];
|
||||
play(room, frames, () => steps.push(r.view().her ? { ...r.view().her! } : r.view().heard));
|
||||
expect(steps).toEqual([
|
||||
'你在听的', '你在听吗?',
|
||||
{ speech: 'speech_normal', text: '', state: 'open' },
|
||||
{ speech: 'speech_normal', text: '在听呢,', state: 'open' },
|
||||
{ speech: 'speech_normal', text: '在听呢,在听呢,你刚才说到一半的那件事我还在想。', state: 'open' },
|
||||
{ speech: 'speech_normal', text: '在听呢,你刚才说到一半的那件事我还在想。', state: 'final', turnId: '0e2f-demo-turn' },
|
||||
{ speech: 'speech_normal', text: '在听呢,你刚才说到一半的那件事我还在想。', state: 'done', turnId: '0e2f-demo-turn' },
|
||||
]);
|
||||
expect(r.view().heard).toBe(''); // her stored answer retires the draft it answered
|
||||
// Her words never land in your draft slot, and yours never in hers.
|
||||
expect(r.views.every(v => !v.her || !v.heard.includes('在听呢'))).toBe(true);
|
||||
expect(r.spoke).toHaveBeenCalledTimes(1);
|
||||
expect(r.record).toHaveBeenCalledTimes(3); // your final, her final, her turn's end: re-read, never written
|
||||
// The whole recording replayed (same seq) changes nothing.
|
||||
const seen = r.views.length; play(room, frames);
|
||||
expect(r.views.length).toBe(seen);
|
||||
// Your next turn: her finished line does not stay in front of it.
|
||||
room.on.subtitle(frame(8, 'interim', { text: '那' })); expect(r.view().her?.state).toBe('done');
|
||||
room.on.subtitle(frame(9, 'user_final', { text: '那你想到了吗' })); expect(r.view().her).toBeNull();
|
||||
});
|
||||
it('interrupted: no final, her line goes at once, its late frames never reach the new turn', async () => {
|
||||
const r = await connected(), room = r.transport.rooms[0], frames = sample('interrupt');
|
||||
play(room, frames.slice(0, 2));
|
||||
expect(r.view().her).toMatchObject({ speech: 'speech_cut', text: '我正想跟你说,今天下午', state: 'open' });
|
||||
play(room, frames.slice(2, 3));
|
||||
expect(r.view().her).toBeNull();
|
||||
// Late increments of the cut turn, even with a higher seq, and a replay of its start.
|
||||
room.on.subtitle(frame(4, 'assistant_interim', { speech_id: 'speech_cut', text: '我正想跟你说,今天下午去了' }));
|
||||
room.on.subtitle(frame(5, 'assistant_final', { speech_id: 'speech_cut', turn_id: 'old', text: '我正想跟你说,今天下午去了河边。' }));
|
||||
room.on.subtitle(frame(6, 'turn_start', { speech_id: 'speech_cut' }));
|
||||
expect(r.view().her).toBeNull();
|
||||
play(room, frames.slice(3).map(f => ({ ...f, seq: f.seq + 10 })));
|
||||
expect(r.view()).toMatchObject({ heard: '', her: { speech: 'speech_next', text: '好,你先说。', state: 'done', turnId: '0e2f-demo-next' } });
|
||||
});
|
||||
it('frames that overtook each other: a lower seq is stale; an older speech never touches or closes the new one', async () => {
|
||||
const r = await connected(), room = r.transport.rooms[0];
|
||||
room.on.subtitle(frame(1, 'turn_start', { speech_id: 'a' }));
|
||||
room.on.subtitle(frame(3, 'assistant_interim', { speech_id: 'a', text: '一二三' }));
|
||||
room.on.subtitle(frame(2, 'assistant_interim', { speech_id: 'a', text: '一二' })); // overtaken: dropped
|
||||
expect(r.view().her?.text).toBe('一二三');
|
||||
// Two handles: b starts while a is still open (queued then generated). a is closed here by b.
|
||||
room.on.subtitle(frame(4, 'turn_start', { speech_id: 'b' }));
|
||||
room.on.subtitle(frame(5, 'assistant_interim', { speech_id: 'a', text: '一二三四' }));
|
||||
room.on.subtitle(frame(6, 'turn_end', { speech_id: 'a', turn_id: 'ta' }));
|
||||
room.on.subtitle(frame(7, 'turn_cancel', { speech_id: 'a', reason: 'interrupted' }));
|
||||
room.on.subtitle(frame(8, 'proactive_cancel', { speech_id: 'b', message_id: 3, reason: 'interrupted' })); // wrong family
|
||||
expect(r.view().her).toEqual({ speech: 'b', text: '', state: 'open' });
|
||||
room.on.subtitle(frame(9, 'assistant_interim', { speech_id: 'b', text: '好' }));
|
||||
room.on.subtitle(frame(10, 'turn_end', { speech_id: 'b', turn_id: 'tb' })); // closed without final
|
||||
expect(r.view().her).toBeNull();
|
||||
room.on.subtitle(frame(11, 'assistant_final', { speech_id: 'b', turn_id: 'tb', text: '好。' }));
|
||||
expect(r.view().her).toBeNull();
|
||||
});
|
||||
it('reach-out read aloud: shown whole with its stored message id, interruptible, nothing marked or stored', async () => {
|
||||
const r = await connected(), room = r.transport.rooms[0], frames = sample('proactive');
|
||||
play(room, frames.slice(0, 1));
|
||||
expect(r.view()).toMatchObject({ phase: 'speaking', her: { speech: 'speech_pro1', text: '我看到一句很适合现在的话,先念给你听。', state: 'open', messageId: 17, proactive: true } });
|
||||
room.on.subtitle(frame(2, 'proactive_end', { speech_id: 'speech_pro1', message_id: 99 })); // another row's end
|
||||
expect(r.view().her?.state).toBe('open');
|
||||
play(room, frames.slice(1, 2).map(f => ({ ...f, seq: 3 })));
|
||||
expect(r.view().her).toMatchObject({ messageId: 17, state: 'done' });
|
||||
play(room, frames.slice(2).map(f => ({ ...f, seq: f.seq + 10 })));
|
||||
expect(r.view().her).toBeNull();
|
||||
// Reaching out is not a turn of yours: no "you spoke", no record write, no request at all.
|
||||
expect(r.spoke).not.toHaveBeenCalled(); expect(r.record).not.toHaveBeenCalled();
|
||||
expect(r.server.calls.filter(c => !c.url.startsWith('/api/voice/'))).toEqual([]);
|
||||
});
|
||||
it('a reach-out cut by your voice: the cancel clears it, your words follow', async () => {
|
||||
const r = await connected(), room = r.transport.rooms[0];
|
||||
room.on.subtitle(frame(1, 'proactive_start', { speech_id: 'p', message_id: 18, text: '还有一件事想告诉你——' }));
|
||||
room.on.subtitle(frame(2, 'interim', { text: '等等' }));
|
||||
expect(r.view()).toMatchObject({ heard: '等等', her: { speech: 'p', state: 'open' } });
|
||||
room.on.subtitle(frame(3, 'proactive_cancel', { speech_id: 'p', message_id: 18, reason: 'interrupted' }));
|
||||
expect(r.view()).toMatchObject({ heard: '等等', her: null });
|
||||
});
|
||||
it('text taking over, hanging up and starting again each clear her line at once', async () => {
|
||||
const r = await connected(), room = r.transport.rooms[0];
|
||||
room.on.agentState('speaking');
|
||||
room.on.subtitle(frame(1, 'turn_start', { speech_id: 'a' }));
|
||||
room.on.subtitle(frame(2, 'assistant_interim', { speech_id: 'a', text: '那我们' }));
|
||||
r.c.hush();
|
||||
expect(r.view().her).toBeNull(); expect(room.hushed).toEqual([true]);
|
||||
room.on.subtitle(frame(3, 'assistant_interim', { speech_id: 'a', text: '那我们明天' }));
|
||||
expect(r.view().her).toBeNull();
|
||||
// A finished line is cleared by text too: your typed line comes next on the stage.
|
||||
room.on.subtitle(frame(4, 'turn_start', { speech_id: 'b' }));
|
||||
room.on.subtitle(frame(5, 'assistant_interim', { speech_id: 'b', text: '好。' }));
|
||||
room.on.subtitle(frame(6, 'assistant_final', { speech_id: 'b', turn_id: 'tb', text: '好。' }));
|
||||
room.on.subtitle(frame(7, 'turn_end', { speech_id: 'b', turn_id: 'tb' }));
|
||||
expect(r.view().her?.state).toBe('done');
|
||||
r.c.hush(); expect(r.view().her).toBeNull();
|
||||
// Hanging up mid-sentence.
|
||||
room.on.subtitle(frame(8, 'turn_start', { speech_id: 'c' }));
|
||||
room.on.subtitle(frame(9, 'assistant_interim', { speech_id: 'c', text: '嗯' }));
|
||||
await r.c.end(); expect(r.view().her).toBeNull();
|
||||
room.on.subtitle(frame(10, 'assistant_interim', { speech_id: 'c', text: '嗯,晚安' }));
|
||||
expect(r.view().her).toBeNull();
|
||||
// A new call is a new worker job: its sequence starts again; the old room's frames stay dead.
|
||||
await r.c.start(); const next = r.transport.rooms[1]; next.on.agentJoined();
|
||||
next.on.subtitle(frame(1, 'turn_start', { speech_id: 'n' }));
|
||||
next.on.subtitle(frame(2, 'assistant_interim', { speech_id: 'n', text: '又见面了' }));
|
||||
room.on.subtitle(frame(11, 'turn_start', { speech_id: 'z' }));
|
||||
room.on.subtitle(frame(12, 'assistant_interim', { speech_id: 'n', text: '旧房间' }));
|
||||
expect(r.view().her).toEqual({ speech: 'n', text: '又见面了', state: 'open' });
|
||||
await r.c.end();
|
||||
});
|
||||
it('the room dropping mid-sentence clears her line with the call', async () => {
|
||||
const r = await connected(), room = r.transport.rooms[0];
|
||||
room.on.subtitle(frame(1, 'turn_start', { speech_id: 'a' }));
|
||||
room.on.subtitle(frame(2, 'assistant_interim', { speech_id: 'a', text: '我' }));
|
||||
room.on.dropped(); await flush();
|
||||
expect(r.view()).toMatchObject({ phase: 'off', her: null, notice: WORDS.dropped });
|
||||
});
|
||||
});
|
||||
|
||||
describe('her voice line on the stage', () => {
|
||||
const M = (id: number, role: Message['role'], text: string, turnId?: string, extra: Partial<Message> = {}): Message => ({ id: String(id), role, text, lifeIds: [], turnId, status: 'sent', ...extra });
|
||||
const metrics = { width: 900, font: 23, compact: false };
|
||||
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 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(stage([you, growing])).toEqual(['T:0:0=你在听吗?', 'T:1:0=在听呢,你刚才说到一半的那件事我一直还在心里想着。']);
|
||||
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=后来呢?']);
|
||||
const stored = [you, M(5, 'companion', done.text, 'T')];
|
||||
expect(voiceLine(done, stored, 1)).toBeNull();
|
||||
expect(stage(stored)).toEqual(shown);
|
||||
});
|
||||
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();
|
||||
expect(voiceLine({ ...done, state: 'open' }, [you, M(6, 'user', '还有', 'U')], 1)).not.toBeNull();
|
||||
expect(voiceLine({ ...done, text: '' }, [you], 1)).toBeNull();
|
||||
});
|
||||
it('a reach-out read aloud keeps its stored row identity and gives way when that row is the newest line', () => {
|
||||
const line: HerLine = { speech: 'p', text: '我看到一句很适合现在的话,先念给你听。', state: 'open', messageId: 17, proactive: true };
|
||||
const row = M(17, 'companion', line.text, 'R', { proactive: true });
|
||||
const before = [you, M(5, 'companion', '在。', 'T')];
|
||||
const waiting = voiceLine(line, before, 2, [row])!;
|
||||
expect(waiting).toMatchObject({ id: '17', turnId: 'R', proactive: true }); expect(waiting.live).toBeUndefined();
|
||||
expect(stage([...before, waiting])).toEqual(stage([...before, row]));
|
||||
expect(voiceLine({ ...line, state: 'done' }, [...before, row], 2)).toBeNull();
|
||||
// Not on the page at all: shown under its own key; nothing is created for the record.
|
||||
expect(voiceLine(line, before, 2)).toMatchObject({ id: 'voice-p', proactive: true });
|
||||
});
|
||||
});
|
||||
|
||||
describe('record re-read', () => {
|
||||
const msg = (id: number, role: Message['role'], turnId: string, extra: Partial<Message> = {}): Message => ({ id: String(id), role, text: `${role}${id}`, lifeIds: [], turnId, status: 'sent', ...extra });
|
||||
it('adds voice turns once, in id order; leaves reach-outs to the inbox and text turns to the stream', () => {
|
||||
|
||||
Reference in New Issue
Block a user