diff --git a/docs/requirements/handoff-HEL-898.json b/docs/requirements/handoff-HEL-898.json index 0c175fe..224db73 100644 --- a/docs/requirements/handoff-HEL-898.json +++ b/docs/requirements/handoff-HEL-898.json @@ -1,7 +1,7 @@ { "baseline_version": "1.11", - "read_commit": "3228b1e0d7f822b7030f945e285eac74126771aa", - "task": "HEL-898(HEL-879 接线卡,视觉总监本人编码):在已认可的交谈界面接上她的增量字幕(cg.subtitle 契约 v2)与语音内主动开口呈现,处理打断/文字接管/错误/挂断收尾;不另做聊天页、不改主题与整体动效", + "read_commit": "f92a86f5d8f839338311cdee08179049de34eb20", + "task": "HEL-898(HEL-879 接线卡,视觉总监本人编码):在已认可的交谈界面接上她的增量字幕(cg.subtitle 契约 v2)与语音内主动开口呈现,处理打断/文字接管/错误/挂断收尾;不另做聊天页、不改主题与整体动效;f92a86f 统一复核后的有限返修三项(worker 离场诚实收场、已退休 speech 不复活、短语音回复播放中可见)及回放基础设施", "requirement_ids": [ "CG-004", "CG-006", "CG-010", "CG-011", "CG-018", "CG-020", "VIS-001", "VIS-002", "VIS-003", "VIS-004", "VIS-005", "VIS-006", "VIS-007", "VIS-008", "VIS-009", "VIS-010", "VIS-011", "VIS-012", "VIS-013", @@ -10,7 +10,7 @@ "GOV-001", "GOV-002", "GOV-003", "GOV-004", "GOV-005", "GOV-006", "DEL-001" ], - "deliverable": "自总管输入包 3228b1e(INPUT-MANIFEST 逐文件 SHA-256)起的前端补丁,只动 web/src/voice/session.ts、web/src/chat/ChatPanel.tsx 与测试:1) session.ts 严格解析 v2 信封(v===2、正整数 seq、kind 白名单、角色与种类对应、她的事件必带 speech_id、assistant_final 必带 turn_id、proactive_* 必带正整数 message_id;不合格整条丢弃且不推进序号);每次通话(控制器代次)独立 seq 高水位,seq<=已应用即丢;按 speech 生命周期只接受当前打开的一轮,已关闭/被取代的 speech 不再显示,旧 speech 的高 seq 事件不能关闭新轮。VoiceView 新增 her(speech/text/state open|final|done/turnId/messageId/proactive),与用户 ASR 草稿 heard 分槽。2) turn_start 开轮,assistant_interim 整句替换,assistant_final 原子替换为落库文本并请页面回读 /api/messages,turn_end 关轮(无 final 的关轮按未成为正式回复即清),turn_cancel/error(φ)/user_final/文字接管 hush/结束/掉线/卸载/重开即时清;φ 原句仍在语音行以“未记入聊天”显示。3) proactive_start 以落库原文、同源 message_id 显示在她的位置,proactive_end 保留至记录或下一轮接替,proactive_cancel 即清;不发任何请求、不标已读、不开麦、不重 TTS、不进入正式记录。4) ChatPanel:她的语音行进入与文字回复相同的舞台槽位(当前一两句、自动续读、暂停/回看、全文),生长中沿用文字流的“最新一句先压住”规则,逐分片不重启动画;落库行到来时同一 turn 同一位置接替,行键不变不重放;被撤回的语音行以 instant 方式立即离场(不淡出);减少动态设置沿用既有逻辑。你用语音开始新一轮时与发送文字一致恢复自动呈现(原先暂停状态下她的回答不会进来)。5) 测试:voice.test.ts 改为 v2 帧并新增 11 项(录制样例三场景回放、信封负例、乱序/重放/迟到/双 handle、φ、主动开口及打断、文字接管/挂断/重开、舞台行键接替);fake-livekit.js 未带信封的帧自动套 v2;hel878_mock.mjs 增 /__proactive;hel878_shots.mjs 的她的 final 与 φ 改为 v2 生命周期;新增 hel898_shots.mjs(两主题×电脑/手机)", + "deliverable": "自总管输入包 3228b1e(INPUT-MANIFEST 逐文件 SHA-256)起的前端补丁,只动 web/src/voice/session.ts、web/src/chat/ChatPanel.tsx 与测试:1) session.ts 严格解析 v2 信封(v===2、正整数 seq、kind 白名单、角色与种类对应、她的事件必带 speech_id、assistant_final 必带 turn_id、proactive_* 必带正整数 message_id;不合格整条丢弃且不推进序号);每次通话(控制器代次)独立 seq 高水位,seq<=已应用即丢;按 speech 生命周期只接受当前打开的一轮,已关闭/被取代的 speech 不再显示,旧 speech 的高 seq 事件不能关闭新轮。VoiceView 新增 her(speech/text/state open|final|done/turnId/messageId/proactive),与用户 ASR 草稿 heard 分槽。2) turn_start 开轮,assistant_interim 整句替换,assistant_final 原子替换为落库文本并请页面回读 /api/messages,turn_end 关轮(无 final 的关轮按未成为正式回复即清),turn_cancel/error(φ)/user_final/文字接管 hush/结束/掉线/卸载/重开即时清;φ 原句仍在语音行以“未记入聊天”显示。3) proactive_start 以落库原文、同源 message_id 显示在她的位置,proactive_end 保留至记录或下一轮接替,proactive_cancel 即清;不发任何请求、不标已读、不开麦、不重 TTS、不进入正式记录。4) ChatPanel:她的语音行进入与文字回复相同的舞台槽位(当前一两句、自动续读、暂停/回看、全文),生长中沿用文字流的“最新一句先压住”规则,逐分片不重启动画;落库行到来时同一 turn 同一位置接替,行键不变不重放;被撤回的语音行以 instant 方式立即离场(不淡出);减少动态设置沿用既有逻辑。你用语音开始新一轮时与发送文字一致恢复自动呈现(原先暂停状态下她的回答不会进来)。5) 测试:voice.test.ts 改为 v2 帧并新增 11 项(录制样例三场景回放、信封负例、乱序/重放/迟到/双 handle、φ、主动开口及打断、文字接管/挂断/重开、舞台行键接替);fake-livekit.js 未带信封的帧自动套 v2;hel878_mock.mjs 增 /__proactive;hel878_shots.mjs 的她的 final 与 φ 改为 v2 生命周期;新增 hel898_shots.mjs(两主题×电脑/手机)。【f92a86f 有限返修,首轮读取 3228b1e;本轮输入包 166 文件 SHA-256 全符】1) livekit.ts 监听 RoomEvent.ParticipantDisconnected(vendor 2.22.4 原名 participantDisconnected,emit(participant, reason)),只在本房间她的 worker(按身份记住的 agent 或 isAgent)离开、且房内没有其他 agent 时报 agentLeft;房间关闭中不报。session.ts 的 RoomEvents 新增 agentLeft:仅当前代次且 agent 已接入时走既有 fail(清字幕/草稿、停麦、清播放、关房、DELETE 本次服务房,失败入欠账重试),中文提示 WORDS.agentLeft;普通参与者离场、旧房间迟到离场、用户主动挂断都不触发。2) 已关闭 speech 由 64 项窗口数组改为每次通话一个 Set,随通话代次释放;seq 严格门不变。3) 语音回复开放态改为 live=speaking:reading.pagesOf 对其最后一块只显示已成句部分(。!?!?… 及其后的收尾引号括号),未成句部分仍压住;文字流 live=generating 的规则不变。已显示的语音行之后只会在同键下增长(短句与下一句合并时):LineStage.grow 原位追加新字的既有墨迹,不重建行、不重放;减少动态时直接设文本。ChatPanel 签名对语音行计入文本,全文页“还在说…”也适用于 speaking;ReadingClock 对同键增长只延长停留时间。没有新布局或样式。4) 测试:hel879_frames 的 DOCUMENTED GAP 改为拒绝断言,并新增每通话独立用例;voice.test 新增短回复/长句/文字流不变用例;新增 hel898_agent_left.test.ts(真实 livekitTransport 适配器 + 脚本化 SDK 事件名,另有控制器负例);fake-livekit.js 增 ParticipantDisconnected/leave/lateLeave/guest;hel878_mock.mjs 增 /__pid、/__reset,监听失败即退出;hel879_unified_shots.mjs 修回放基础设施(端口空闲与 pid 确认、多段录制按当前通话单调重编号并写 seq-renumbering.json、新通话重置、每主题 /__reset 隔离、负例原样发送并断言拒绝),加三项正反例和 CDP screencast→WebM 录屏", "acceptance": [ "假 LiveKit 有序回放 normal-turn.jsonl:用户草稿→用户终稿→turn_start→两次增量(整句替换)→final(带 turn_id)→turn_end;她的字在舞台出现时 /__rows 尚无该回复;落库后记录中只出现一次(页面只回读,不写)", "interrupt.jsonl 与负例:turn_cancel 后她的未完成行立即离场;被取消轮之后的高 seq 增量/final/重复 turn_start 均不显示;整段录制重放不改变界面;双 handle 时旧 speech 的 turn_end/turn_cancel 不关闭新轮;无 final 的 turn_end 视为未成为正式回复并清除", @@ -18,7 +18,11 @@ "proactive.jsonl:原文一字不差显示在她的位置并保留落库行身份(id/turn),可被你的语音打断(proactive_cancel 即清);全程页面无任何非 GET 请求(无回执、无已读、无消息写入),不调用 onSpoke/onRecord", "文字接管、结束语音、掉线、新通话:她的行即时清;旧房间迟到帧被代次挡住;新通话序号从 1 重新开始并正常显示", "两主题(月光/雾光)电脑 1440×900 与手机 390×844 截图与连续帧:沿用已认可位置与组件,无新增组件或样式;减少动态设置下她的字照常出现、无入场动画", - "工程:tsc 0 错;eslint 0 错 1 条既有警告(ChatPanel fullButton ref,HEL-897 起即有);vitest 8 文件 99/99;vite build 通过;浏览器 hel898 61/61,HEL-878 回归 49/49;修前对照:新 voice.test.ts 在原 session.ts/ChatPanel 上 12 项失败" + "工程:tsc 0 错;eslint 0 错 1 条既有警告(ChatPanel fullButton ref,HEL-897 起即有);vitest 8 文件 99/99;vite build 通过;浏览器 hel898 61/61,HEL-878 回归 49/49;修前对照:新 voice.test.ts 在原 session.ts/ChatPanel 上 12 项失败", + "f92a86f 返修-1:worker 离场(房间仍开)时通话即时结束:她的行清除,提示“她那边的语音中断了……”,麦克风轨 ended,播放容器移除,本次 session DELETE 恰好一次;普通参与者离场不挂断;旧房间迟到离场不影响新通话;用户主动挂断只有一次 DELETE、没有离场提示;DELETE 失败入欠账并重试(单测)", + "f92a86f 返修-2:adversarial-gates 66 次挤出后,speech_A 以新 seq 重开/增量/终稿都被拒(单测与浏览器原样探针),之后新 speech 正常进入;新通话从 seq 1 开始,不受旧通话已退休 id 影响", + "f92a86f 返修-3:worker-normal 回放中“在听呢,”“…那件事”未成句时舞台不显示她的半句;第三个增量成句后、final 之前即显示整句,并在播放期间保持;final 与落库行接替为同一 DOM 行(不重建、不重放);短句与下一句合并时同节点原位增长、首字墨迹不动;长句只显示已完成的行、不整段铺满;文字流仍压住最新块", + "f92a86f 返修工程:tsc 0;eslint 0 错 1 条既有警告;vitest 10 文件 118/118;build 通过;修前对照 vitest 7 项失败;统一实际 worker 帧浏览器回放(moon/fog × 电脑/手机 + 减少动态)修后 53/53、修前 30/53(失败都落在三项及其连带);hel898_shots 61/61、hel878_shots 49/49;8 段 WebM 录屏取自真实 screencast 帧" ], "deferred": [ "真实通话未测:真实 LiveKit/WebRTC、真实 worker 与 SDK 回调时序、真机/Safari/iOS、可信 HTTPS+WSS、R5 连续三轮/1 秒打断/停麦无残音/有限预算,均仍由 HEL-797 主卡承接;本卡全部为假 LiveKit、假音频设备与 Chromium 无头 Edge", @@ -26,7 +30,9 @@ "后台并行小修(建房延迟后的清理唤醒、主动 say 的 start 发得过晚、无完整 receipt 错误发 final)由原总工在 HEL-879 处理;本卡按 v2 正确语义实现,最终后台 commit 出来后需按其统一复核(特别是 proactive_start 晚于音频开始时的呈现)", "已知边界:seq 按“一次 worker job 一个序列”实现;若同一房间内 worker 重连且序号归零,前端会按契约丢弃其帧直到超过旧高水位——需后台确认 job 与房间一一对应", "原版 Python 需求检查(scripts/check_requirements.py --base-ref origin/main,含本交接)未在本运行时执行(无 Python、无 git),须总管对实际目标分支复跑", - "D1 音色、cap=0、R6/R7、整体沉浸体验由主卡与白栖知决定;工程自测不是用户体验验收" + "D1 音色、cap=0、R6/R7、整体沉浸体验由主卡与白栖知决定;工程自测不是用户体验验收", + "f92a86f 返修:真实 SDK 下 worker 离场事件的时序(含网络重连期间 remoteParticipants 被清空但不发离场事件)只按 vendor 源码核对,未在真实房间验证", + "回放基础设施把多段录制重编号(原始帧保留在 fixtures,映射见 seq-renumbering.json),证明的是页面在“同一通话单调 seq”下的呈现与门,不证明 worker 跨 job 的 seq 行为" ], "requirement_changes": [], "verification": [ @@ -34,6 +40,8 @@ "工具:沿用本机既有离线工具链(HEL-834 留存 node v22.11.0;HEL-897 留存 web/node_modules,package-lock 哈希与本包一致,目录联接使用);未下载、未安装", "web:tsc --noEmit 0;eslint src 0 错 1 既有警告;vitest run 8 文件 99/99(原 88 + 新增);vite build 通过;日志随交付包", "浏览器:node tests/hel878_mock.mjs + node tests/hel898_shots.mjs(无头 Edge、脚本化 LiveKit 替身、Chromium 假音频设备)61/61;node tests/hel878_shots.mjs 回归 49/49;截图与连续帧随交付包", - "无模型、嵌入、ASR、TTS 请求,无真实麦克风采集,无部署、合并、服务或绑定改动;未改后台、总装分支或 PR#11" + "无模型、嵌入、ASR、TTS 请求,无真实麦克风采集,无部署、合并、服务或绑定改动;未改后台、总装分支或 PR#11", + "f92a86f 返修读取:卡内三项说明、HEL-898-统一复核返修输入-f92a86f.zip(166 文件 SHA-256 全符)、web/public/vendor/livekit-client-2.22.4.umd.min.js 中 RoomEvent.ParticipantDisconnected 的定义与 emit(participant, reason)、断开清理路径不发该事件;本包缺 docs/rework/hel879/subtitle-samples,测试运行时沿用 3228b1e 输入包同名文件(不入补丁)", + "f92a86f 返修浏览器:node tests/hel879_unified_shots.mjs 8879 9499(自带 mock,先确认端口空闲与 pid);hel898_shots/hel878_shots 由本运行自起 mock(核对 pid 后按 PID 停止)" ] } diff --git a/web/src/chat/ChatPanel.tsx b/web/src/chat/ChatPanel.tsx index e50f8bd..8267924 100644 --- a/web/src/chat/ChatPanel.tsx +++ b/web/src/chat/ChatPanel.tsx @@ -173,7 +173,8 @@ export function ChatPanel({ state, onChange, onPresence, onVoice, onObservation, // Her voice line withdrawn (cut, φ, text took over, you spoke, the call ended): it leaves at once, no fade. const hadLine = useRef(false); useLayoutEffect(() => { if (hadLine.current && !her) how.current = 'instant'; hadLine.current = !!herLine; }, [her, herLine]); - const signature = pages.map(p => p.key).join('|'); + // Her spoken line can take in her next sentence under the same key, so its words count there too. + const signature = pages.map(p => p.message.live === 'speaking' || p.message.id.startsWith('voice-') ? `${p.key}=${p.text}` : p.key).join('|'); useLayoutEffect(() => { lines.current?.present(pages, cursor, how.current, name, !motionOff()); how.current = 'advance'; @@ -360,7 +361,7 @@ export function ChatPanel({ state, onChange, onPresence, onVoice, onObservation, {full && fullMessage && } +

整段完整可读。关闭后回到刚才那一句。

{fullMessage.role === 'user' ? '你' : name}

{fullMessage.text}

{(fullMessage.live === 'generating' || fullMessage.live === 'speaking') && 还在说…}{fullMessage.live === 'cancelled' && 这段回复已停止,内容未完成,未存入聊天记录。}
} {real && permission === 'mic' && { setPermission(''); setNotice('没有开启语音,文字仍可使用。'); }} confirm="开始语音" onConfirm={() => { setPermission(''); setNotice(''); void voiceCtl.current?.start(); }}>浏览器会请求麦克风权限。你的声音只送到这台服务器上{name}的语音服务,她用同一份记忆、同一段聊天回应你;你说的话和她的回答照常存进聊天记录。直接开口就能打断她。结束语音、离开交谈或关上页面时,麦克风立即关闭。
语音通路还没有经过真机验收,效果可能不稳定。
} {!real && permission && { setPermission(''); setDenied(true); setNotice('没有开启。真实服务尚未接通,文字仍可使用。'); }} confirm="开始模拟" onConfirm={() => { if (permission === 'mic') { setDenied(false); setVoice(true); onVoice(true); voiceController.current = new AbortController(); onPresence('在听你说(模拟)'); setNotice('模拟语音没有收音,可继续用文字输入。'); } else { if (fail) { onObservation('模拟 · 看不清,视觉服务未接通'); setNotice('模拟观察失败,文字仍可使用。'); } else setVision(true); } setPermission(''); }}>本次仅模拟界面状态,不申请麦克风或摄像头权限,不采集声音或影像,也不向外接服务发送请求。} ; diff --git a/web/src/chat/lineStage.ts b/web/src/chat/lineStage.ts index 8b8cf81..a1cbc0a 100644 --- a/web/src/chat/lineStage.ts +++ b/web/src/chat/lineStage.ts @@ -14,6 +14,7 @@ export class LineStage { const el = document.createElement('div'); el.className = 'line' + (current ? ' is-current' : ' is-prev'); el.dataset.role = page.message.role; el.dataset.key = page.key; + if (page.message.live === 'speaking') el.dataset.spoken = '1'; const who = document.createElement('span'); who.className = 'by'; const dot = document.createElement('i'), label = document.createElement('b'), state = document.createElement('em'); label.textContent = page.message.role === 'user' ? '你' : name; label.title = label.textContent; state.className = 'state'; @@ -38,6 +39,15 @@ export class LineStage { { duration: quick ? 240 : 520, easing: EASE, fill: 'forwards' }).finished.then(() => node.remove()).catch(() => node.remove()); } clear() { this.stage.replaceChildren(); } + // Her spoken line took in the sentence she said next: the words already there stay as they are and only the new + // ones ink in after them (no motion: they just appear). Anything that is not a plain continuation is set at once. + private grow(node: HTMLElement, text: string, animate: boolean) { + const p = node.querySelector('p'); if (!p) return; + const was = p.textContent || ''; if (was === text) return; + if (!animate || !text.startsWith(was)) { p.className = ''; p.textContent = text; return; } + if (p.className !== 'ink') { p.append(text.slice(was.length)); return; } + graphemes(text.slice(was.length)).forEach((c, i) => { const s = document.createElement('span'); s.style.setProperty('--i', String(Math.min(i, 48))); s.textContent = c; p.append(s); }); + } // Shows the current page with the one before it. Returns early when the same lines are already on screen, so // a growing stream, a status change or a re-render never replays anything. present(pages: Page[], cursor: number, how: PresentHow, name: string, animate: boolean) { @@ -46,6 +56,8 @@ export class LineStage { const prev = pages[cursor - 1], want = [prev, page].filter((p): p is Page => !!p); const have = [...stage.querySelectorAll('.line:not(.leaving)')], keys = have.map(n => n.dataset.key); const inkFor = (p: Page) => p === page && animate && p.message.role === 'companion' && !this.inked.has(p.key); + // A line first shown while she was saying it keeps growing under its key (her final, then her stored row). + for (const p of want) { const n = have.find(x => x.dataset.key === p.key && x.dataset.spoken); if (n) this.grow(n, p.text, animate); } if (how === 'instant' || !animate) { // Keyboard review and reduced motion: show the target lines as they are — no slide, no re-played ink. if (keys.join() === want.map(p => p.key).join() && how !== 'instant') return; diff --git a/web/src/chat/reading.ts b/web/src/chat/reading.ts index cbd7b7f..a010c07 100644 --- a/web/src/chat/reading.ts +++ b/web/src/chat/reading.ts @@ -2,8 +2,8 @@ import type { Message } from '../domain/model'; // Reading logic carried over from the verified HEL-793/795 prototype (PR#8) and HEL-799 (approved 01a16810), moved // onto the real message flow: replies are shown one or two lines at a time and flow on by themselves. -// A message as the stage sees it: stored messages plus, at most, the reply still being written or cut off. -export interface ShownMessage extends Message { live?: 'generating' | 'cancelled' } +// A message as the stage sees it: stored messages plus, at most, the reply still being written, spoken or cut off. +export interface ShownMessage extends Message { live?: 'generating' | 'speaking' | 'cancelled' } export interface Turn { key: string; items: ShownMessage[] } export interface Page { key: string; text: string; index: number; last: boolean; mi: number; message: ShownMessage } export interface Metrics { width: number; font: number; compact: boolean } @@ -42,16 +42,23 @@ export function chunks(text: string, { width, font, compact }: Metrics): string[ return out; } +// The finished sentences at the start of a line (with their closing marks); '' while the first is still forming. +const SAID = /^[\s\S]*[。!?!?…][」』))”’"]*/u; +export const said = (line: string) => SAID.exec(line)?.[0] ?? ''; + export function pagesOf(turn: Turn | undefined, metrics: Metrics): Page[] { const list: Page[] = []; if (!turn) return list; turn.items.forEach((message, mi) => { - const parts = chunks(message.text, metrics); + const parts = chunks(message.text, metrics), shown = parts.slice(); // The newest chunk of a reply still being written is held back (it may still grow or merge with the next // sentence), so a line never changes or re-animates after it has appeared. - const held = message.live === 'generating' && parts.length ? 1 : 0; + if (message.live === 'generating') shown.pop(); + // Her reply while she speaks it: the newest chunk shows the sentences she has already finished. It may still + // take the next short sentence in (it only ever grows, see LineStage.grow); the words still forming wait. + else if (message.live === 'speaking' && shown.length) { const done = said(shown.pop()!); if (done) shown.push(done); } // Keys follow the turn and position, not the message id, so a streamed reply keeps its lines when it is stored. - for (let index = 0; index < parts.length - held; index++) list.push({ key: `${turn.key}:${mi}:${index}`, text: parts[index], index, last: index === parts.length - 1, mi, message }); + shown.forEach((text, index) => list.push({ key: `${turn.key}:${mi}:${index}`, text, index, last: index === parts.length - 1, mi, message })); }); return list; } @@ -75,6 +82,8 @@ export class ReadingClock { const dt = this.last ? Math.min(STALL, Math.max(0, now - this.last)) : 0; this.last = now; if (!page) return false; if (page.key !== this.key) { this.key = page.key; this.dwell = 0; this.total = dwellFor(page); } + // A spoken line that took in her next sentence gets the extra time it now needs (never less). + else this.total = Math.max(this.total, dwellFor(page)); if (running && this.dwell < this.total) this.dwell = Math.min(this.total, this.dwell + dt); return running && this.dwell >= this.total; } diff --git a/web/src/voice/livekit.ts b/web/src/voice/livekit.ts index d70de37..1bda044 100644 --- a/web/src/voice/livekit.ts +++ b/web/src/voice/livekit.ts @@ -20,7 +20,7 @@ interface LkRoom { } export interface Livekit { Room: new (options?: Record) => LkRoom; - RoomEvent: Record<'TrackSubscribed' | 'TrackUnsubscribed' | 'ParticipantConnected' | 'ParticipantAttributesChanged' | 'DataReceived' | 'Disconnected' | 'AudioPlaybackStatusChanged', string>; + RoomEvent: Record<'TrackSubscribed' | 'TrackUnsubscribed' | 'ParticipantConnected' | 'ParticipantDisconnected' | 'ParticipantAttributesChanged' | 'DataReceived' | 'Disconnected' | 'AudioPlaybackStatusChanged', string>; Track: { Source: { Microphone: string } }; ParticipantKind?: { AGENT?: number }; createLocalAudioTrack(options?: MediaTrackConstraints): Promise; @@ -57,6 +57,8 @@ export function livekitTransport(lk: Livekit): VoiceTransport { const holder = document.createElement('div'), E = lk.RoomEvent; holder.hidden = true; holder.dataset.voice = 'her'; document.body.append(holder); let closing = false, hushed = false; + // Her worker as seen in this room (by identity), so its leaving is recognised even if its attributes are gone. + const agents = new Set(), joined = (p: LkParticipant) => { agents.add(p.identity); on.agentJoined(); }; const players = () => [...holder.querySelectorAll('audio,video')]; const close = async () => { if (closing) return; closing = true; @@ -66,7 +68,13 @@ export function livekitTransport(lk: Livekit): VoiceTransport { }; room.on(E.TrackSubscribed, ((track: LkTrack) => { if (closing || track.kind !== 'audio') return; const el = track.attach(); el.muted = hushed; holder.append(el); }) as (...a: never[]) => void); room.on(E.TrackUnsubscribed, ((track: LkTrack) => { track.detach().forEach(el => el.remove()); }) as (...a: never[]) => void); - room.on(E.ParticipantConnected, ((p: LkParticipant) => { if (!closing && isAgent(p)) on.agentJoined(); }) as (...a: never[]) => void); + room.on(E.ParticipantConnected, ((p: LkParticipant) => { if (!closing && isAgent(p)) joined(p); }) as (...a: never[]) => void); + // Only her worker leaving ends the call (anyone else coming and going does not); our own closing says nothing. + room.on(E.ParticipantDisconnected, ((p: LkParticipant) => { + if (closing || !(agents.has(p.identity) || isAgent(p))) return; + agents.delete(p.identity); + if (![...room.remoteParticipants.values()].some(o => o.identity !== p.identity && isAgent(o))) on.agentLeft(); + }) as (...a: never[]) => void); room.on(E.ParticipantAttributesChanged, ((changed: Record, p: LkParticipant) => { if (!closing && AGENT_STATE in changed && isAgent(p)) on.agentState(changed[AGENT_STATE]); }) as (...a: never[]) => void); room.on(E.DataReceived, ((payload: Uint8Array, _p: unknown, _kind: unknown, topic?: string) => { if (closing || topic !== SUBTITLES) return; @@ -80,7 +88,7 @@ export function livekitTransport(lk: Livekit): VoiceTransport { catch (e) { await close(); throw e; } if (signal.aborted) { await close(); throw new DOMException('ended', 'AbortError'); } signal.removeEventListener('abort', abort); - room.remoteParticipants.forEach(p => { if (!isAgent(p)) return; on.agentJoined(); const state = p.attributes?.[AGENT_STATE]; if (state) on.agentState(state); }); + room.remoteParticipants.forEach(p => { if (!isAgent(p)) return; joined(p); const state = p.attributes?.[AGENT_STATE]; if (state) on.agentState(state); }); void room.startAudio().catch(() => {}).then(() => { if (!closing && !room.canPlaybackAudio) on.audioBlocked(true); }); const voiceRoom: VoiceRoom = { async publish(mic) { const track = tracks.get(mic); if (!track) throw new Error('unknown microphone'); await room.localParticipant.publishTrack(track, { source: lk.Track.Source.Microphone }); }, diff --git a/web/src/voice/session.ts b/web/src/voice/session.ts index 590556c..5b34bc6 100644 --- a/web/src/voice/session.ts +++ b/web/src/voice/session.ts @@ -56,6 +56,8 @@ export function subtitle(v: unknown): Subtitle | null { export interface MicTrack { stop(): void; onEnded(cb: () => void): void } export interface RoomEvents { agentJoined(): void; + // Her worker left the room while it stays open (its job ended or crashed): nobody is answering any more. + agentLeft(): void; // The worker's own state attribute (lk.agent.state): initializing / listening / thinking / speaking. agentState(state: string): void; subtitle(payload: unknown): void; @@ -81,6 +83,7 @@ export const WORDS = { client: '语音组件没有加载出来,文字仍可使用。', unreachable: '通话服务暂时连不上,稍后再试试。', noAgent: '她没有接上这次通话,麦克风已经关闭。文字仍可使用。', + agentLeft: '她那边的语音中断了,这次通话已结束,麦克风已经关闭。文字仍可使用。', dropped: '通话断开了,麦克风已经关闭。文字仍可使用。', micGone: '麦克风被关掉了,语音已结束。', offline: '网络断开了,语音已结束,麦克风已关闭。', @@ -100,9 +103,9 @@ export interface VoiceDeps { } // seq: the highest subtitle sequence applied in this call (one worker job, one sequence). speech: her speech open now; -// closed: speeches that ended, were cancelled or were superseded here; nothing for them is shown again. -interface Live { gen: number; abort: AbortController; mic?: MicTrack; room?: VoiceRoom; session?: string; agent: boolean; stated: boolean; hushed: boolean; timer?: ReturnType; seq: number; speech: string; pro: boolean; message?: number; closed: string[] } -const CLOSED_KEPT = 64; +// closed: speeches that ended, were cancelled or were superseded in this call; nothing for them is shown again. It is +// kept for the whole call (no window a long call could push a retired speech out of) and goes with the call. +interface Live { gen: number; abort: AbortController; mic?: MicTrack; room?: VoiceRoom; session?: string; agent: boolean; stated: boolean; hushed: boolean; timer?: ReturnType; seq: number; speech: string; pro: boolean; message?: number; closed: Set } const AGENT_PHASE: Record = { initializing: 'joining', listening: 'listening', thinking: 'thinking', speaking: 'speaking' }; @@ -152,7 +155,7 @@ export class VoiceController { // The generation is taken before anything is awaited, so a start that wakes up after a newer one never takes // the call over; the call it replaces is released first, as end() would. const prev = this.live; - const gen = ++this.gen, live: Live = { gen, abort: new AbortController(), agent: false, stated: false, hushed: false, seq: 0, speech: '', pro: false, closed: [] }; + const gen = ++this.gen, live: Live = { gen, abort: new AbortController(), agent: false, stated: false, hushed: false, seq: 0, speech: '', pro: false, closed: new Set() }; this.live = live; this.view = { ...OFF, phase: 'opening' }; this.deps.onView(this.view); const stale = () => gen !== this.gen; @@ -203,6 +206,9 @@ export class VoiceController { this.show({ phase: 'joining' }, gen); const events: RoomEvents = { agentJoined: () => { if (stale() || live.agent) return; live.agent = true; clearTimeout(live.timer); if (!live.stated) this.show({ phase: 'listening' }, gen); }, + // Her worker gone with the room still open: no one would ever answer, so the call ends honestly, exactly as a + // failure does (her line, microphone, her audio, room and server room all go; an unsent DELETE is owed). + agentLeft: () => { if (!stale() && live.agent) void fail(WORDS.agentLeft); }, agentState: state => { if (stale()) return; const phase = AGENT_PHASE[state]; if (!phase) return; @@ -267,7 +273,7 @@ export class VoiceController { } const pro = s.kind.startsWith('proactive_'); if (s.kind === 'turn_start' || s.kind === 'proactive_start') { - if (live.closed.includes(s.speech) || live.speech === s.speech) return; + if (live.closed.has(s.speech) || live.speech === s.speech) return; if (live.speech) this.close(live, live.speech); live.speech = s.speech; live.pro = pro; live.message = s.messageId; // A reach-out arrives whole (its stored text); a reply starts empty and grows. @@ -306,7 +312,7 @@ export class VoiceController { } private close(live: Live, speech: string) { if (live.speech === speech) { live.speech = ''; live.pro = false; live.message = undefined; } - if (!live.closed.includes(speech)) { live.closed.push(speech); if (live.closed.length > CLOSED_KEPT) live.closed.shift(); } + live.closed.add(speech); } // You sent text while she was answering by voice: the server cancels her voice turn; keep its last audio silent. @@ -384,8 +390,8 @@ export function voiceLine(her: HerLine | null, messages: Message[], since: numbe if (her.state !== 'open' && messages.slice(since).some(m => !own(m))) return null; // A reach-out keeps its stored row's identity (id, turn), so the row taking over keeps the same lines on the stage. const row = her.proactive ? [...messages, ...incoming].find(own) : undefined; - // Her reply still growing holds back its newest line, as a streamed text reply does. - return { id: row?.id ?? `voice-${her.speech}`, role: 'companion', text: her.text, lifeIds: [], turnId: row ? row.turnId : her.turnId, ...(her.proactive ? { proactive: true } : {}), ...(her.state === 'open' && !her.proactive ? { live: 'generating' as const } : {}) }; + // Her reply while she says it: every sentence she has finished is on the stage, only the one still forming waits. + return { id: row?.id ?? `voice-${her.speech}`, role: 'companion', text: her.text, lifeIds: [], turnId: row ? row.turnId : her.turnId, ...(her.proactive ? { proactive: true } : {}), ...(her.state === 'open' && !her.proactive ? { live: 'speaking' as const } : {}) }; } // Newest rows down to `since` (exclusive), at most `pages` pages of 50. Voice turns are few per read; a longer gap is diff --git a/web/tests/fake-livekit.js b/web/tests/fake-livekit.js index bdfa08d..76f3d93 100644 --- a/web/tests/fake-livekit.js +++ b/web/tests/fake-livekit.js @@ -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) { diff --git a/web/tests/hel878_mock.mjs b/web/tests/hel878_mock.mjs index 287dc75..0f7dcf5 100644 --- a/web/tests/hel878_mock.mjs +++ b/web/tests/hel878_mock.mjs @@ -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}`)); diff --git a/web/tests/hel879_frames.test.ts b/web/tests/hel879_frames.test.ts index f76efdd..30c026b 100644 --- a/web/tests/hel879_frames.test.ts +++ b/web/tests/hel879_frames.test.ts @@ -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 () => { diff --git a/web/tests/hel879_unified_shots.mjs b/web/tests/hel879_unified_shots.mjs index b8cef5d..34724c8 100644 --- a/web/tests/hel879_unified_shots.mjs +++ b/web/tests/hel879_unified_shots.mjs @@ -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 [port] +// node tests/hel879_unified_shots.mjs [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 /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`); diff --git a/web/tests/hel898_agent_left.test.ts b/web/tests/hel898_agent_left.test.ts new file mode 100644 index 0000000..daacaa0 --- /dev/null +++ b/web/tests/hel898_agent_left.test.ts @@ -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 } +class FakeRoom { + handlers: Record void)[]> = {}; remoteParticipants = new Map(); 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); + }); +}); diff --git a/web/tests/voice.test.ts b/web/tests/voice.test.ts index eb0067c..e33d0ae 100644 --- a/web/tests/voice.test.ts +++ b/web/tests/voice.test.ts @@ -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();