HEL-898: preserve director three-fix rework verbatim on b0dcb17
Co-authored-by: multica-agent <github@multica.ai>
This commit is contained in:
@@ -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,
|
||||
<aside className="record log-panel glass read" hidden={!log} role="dialog" aria-modal="false" aria-labelledby="record-title"><header><div><p className="eyebrow">{real ? '服务器聊天记录' : '完整记录 · 本机演示'}</p><h2 id="record-title">你们说过的话</h2></div><button className="btn-round sm" ref={logClose} aria-label="关闭记录" onClick={() => setLog(false)}><Icon name="x"/></button></header>
|
||||
<div className="scroll" ref={logRef}><p className="guide">内容完整保留;关闭后回到刚才那一句,自动呈现会接着走。</p>{record.map(m => <article key={m.id} data-life={m.lifeIds.join(' ') || undefined} data-mid={m.id} data-role={m.role} className={`message ${m.status === 'failed' ? 'fail' : ''} ${(focusLife && m.lifeIds.includes(focusLife)) || focusIds.includes(m.id) ? 'hl' : ''}`}><div className="author"><i/>{m.role === 'user' ? '你' : name}{m.proactive && <span className="tagm">她主动说的</span>}</div><p>{m.text}</p>{m.status === 'failed' && <button className="btn-text" onClick={() => void send(m)}>没发出去 · 重试</button>}{m.status === 'cancelled' && <span className="incomplete">已取消</span>}{m.live === 'cancelled' && <span className="incomplete">已停止 · 这是未完成片段,未存入聊天记录</span>}</article>)}{reply && <article className="message" data-role="companion"><div className="author"><i/>{name}</div><p>{reply}</p><span className="incomplete">还在说…</span></article>}{herLine && !herLine.proactive && <article className="message" data-role="companion"><div className="author"><i/>{name}</div><p>{herLine.text}</p><span className="incomplete">{herOpen ? '还在说…' : '语音刚说完 · 正在读回聊天记录'}</span></article>}</div></aside>
|
||||
{full && fullMessage && <aside className="record full glass read" role="dialog" aria-modal="false" aria-labelledby="full-title"><header><div><p className="eyebrow">{fullMessage.role === 'user' ? '你' : name} · 全文</p><h2 id="full-title">这一段,慢慢看</h2></div><button className="btn-round sm" ref={fullClose} aria-label="关闭全文" onClick={() => setFull(false)}><Icon name="x"/></button></header>
|
||||
<div className="scroll"><p className="guide">整段完整可读。关闭后回到刚才那一句。</p><article className="message" data-role={fullMessage.role}><div className="author"><i/>{fullMessage.role === 'user' ? '你' : name}</div><p>{fullMessage.text}</p>{fullMessage.live === 'generating' && <span className="incomplete">还在说…</span>}{fullMessage.live === 'cancelled' && <span className="incomplete">这段回复已停止,内容未完成,未存入聊天记录。</span>}</article></div></aside>}
|
||||
<div className="scroll"><p className="guide">整段完整可读。关闭后回到刚才那一句。</p><article className="message" data-role={fullMessage.role}><div className="author"><i/>{fullMessage.role === 'user' ? '你' : name}</div><p>{fullMessage.text}</p>{(fullMessage.live === 'generating' || fullMessage.live === 'speaking') && <span className="incomplete">还在说…</span>}{fullMessage.live === 'cancelled' && <span className="incomplete">这段回复已停止,内容未完成,未存入聊天记录。</span>}</article></div></aside>}
|
||||
{real && permission === 'mic' && <Modal title={`开始和${name}语音?`} onClose={() => { setPermission(''); setNotice('没有开启语音,文字仍可使用。'); }} confirm="开始语音" onConfirm={() => { setPermission(''); setNotice(''); void voiceCtl.current?.start(); }}>浏览器会请求麦克风权限。你的声音只送到这台服务器上{name}的语音服务,她用同一份记忆、同一段聊天回应你;你说的话和她的回答照常存进聊天记录。直接开口就能打断她。结束语音、离开交谈或关上页面时,麦克风立即关闭。<br/><small className="voice-note">语音通路还没有经过真机验收,效果可能不稳定。</small></Modal>}
|
||||
{!real && permission && <Modal title={permission === 'mic' ? '开启模拟语音?' : '打开模拟视觉窗?'} onClose={() => { 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(''); }}>本次仅模拟界面状态,不申请麦克风或摄像头权限,不采集声音或影像,也不向外接服务发送请求。</Modal>}
|
||||
</>;
|
||||
|
||||
@@ -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<HTMLElement>('.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;
|
||||
|
||||
+14
-5
@@ -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;
|
||||
}
|
||||
|
||||
@@ -20,7 +20,7 @@ interface LkRoom {
|
||||
}
|
||||
export interface Livekit {
|
||||
Room: new (options?: Record<string, unknown>) => 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<LkTrack>;
|
||||
@@ -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<string>(), joined = (p: LkParticipant) => { agents.add(p.identity); on.agentJoined(); };
|
||||
const players = () => [...holder.querySelectorAll<HTMLMediaElement>('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<string, string>, 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 }); },
|
||||
|
||||
@@ -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<typeof setTimeout>; 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<typeof setTimeout>; seq: number; speech: string; pro: boolean; message?: number; closed: Set<string> }
|
||||
|
||||
const AGENT_PHASE: Record<string, VoicePhase> = { 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
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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}`));
|
||||
|
||||
@@ -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 () => {
|
||||
|
||||
@@ -2,23 +2,47 @@
|
||||
// the .12 real SDK by scripts/gen_hel879_unified_frames.py) replayed through the current page.
|
||||
// Headless Chromium over CDP against tests/hel878_mock.mjs + tests/fake-livekit.js (no WebRTC, no
|
||||
// model, no TTS; fake audio device as the microphone). Everything on the subtitle side is the
|
||||
// worker's own output — turn ids, speech ids, seqs, kinds; the mock's record rows are keyed to the
|
||||
// worker's own output — turn ids, speech ids, kinds, texts; the mock's record rows are keyed to the
|
||||
// fixture turn ids so the stage takeover is exercised end to end. Usage:
|
||||
// node tests/hel879_unified_shots.mjs <chromium-binary> <outDir> [port]
|
||||
// node tests/hel879_unified_shots.mjs <chromium-binary> <outDir> [port] [cdpPort]
|
||||
//
|
||||
// Replay rules (HEL-898 f92a86f rework of this driver; the page is not changed by them):
|
||||
// - One call is one worker job is one strictly rising seq. The fixtures were recorded by separate worker jobs, each
|
||||
// from seq 1; replayed into one call they are RENUMBERED onto that call's sequence, in order. The original frames
|
||||
// are untouched in the fixtures; every renumbering is written to <outDir>/seq-renumbering.json.
|
||||
// - A new call (a new room) starts the sequence again at 1.
|
||||
// - Negatives (replays, late and out-of-order frames, retired speeches) are sent RAW, exactly as written, and each is
|
||||
// asserted to be refused by the page itself — the driver never repairs a bad frame and then claims the gate held.
|
||||
// - Each theme/viewport block starts from a reset record (/__reset), so the same fixture turn ids replayed per theme
|
||||
// never pile up in one record.
|
||||
// - The mock and CDP ports must be free before anything starts, and the mock must answer /__pid with the pid this
|
||||
// driver spawned: it never drives somebody else's service.
|
||||
import { spawn } from 'node:child_process';
|
||||
import { mkdirSync, writeFileSync, readFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { createConnection } from 'node:net';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const [chrome, out, portArg] = process.argv.slice(2);
|
||||
const port = Number(portArg || 8879), base = `http://127.0.0.1:${port}`, cdpPort = 9499;
|
||||
const [chrome, out, portArg, cdpArg] = process.argv.slice(2);
|
||||
const port = Number(portArg || 8879), base = `http://127.0.0.1:${port}`, cdpPort = Number(cdpArg || 9499);
|
||||
mkdirSync(out, { recursive: true });
|
||||
const sleep = ms => new Promise(r => setTimeout(r, ms));
|
||||
const busy = p => new Promise(ok => { const s = createConnection({ port: p, host: '127.0.0.1' }); s.once('connect', () => { s.destroy(); ok(true); }); s.once('error', () => ok(false)); });
|
||||
for (const [what, p] of [['mock', port], ['CDP', cdpPort]]) if (await busy(p)) { console.error(`port ${p} (${what}) is already in use: refusing to start over someone else's service`); process.exit(3); }
|
||||
// The mock rides along (child of this run, killed at the end): one self-contained command.
|
||||
const mock = spawn(process.execPath, [new URL('./hel878_mock.mjs', import.meta.url).pathname, String(port)], { stdio: 'ignore' });
|
||||
await new Promise((ok, ko) => { const t = setTimeout(() => ok(undefined), 3000); mock.once('spawn', () => setTimeout(ok, 400)); });
|
||||
const mock = spawn(process.execPath, [fileURLToPath(new URL('./hel878_mock.mjs', import.meta.url)), String(port)], { stdio: ['ignore', 'pipe', 'pipe'] });
|
||||
const listening = await new Promise(ok => {
|
||||
let said = ''; const t = setTimeout(() => ok(false), 8000);
|
||||
mock.stdout.on('data', d => { said += d; if (said.includes(`hel878 mock on ${port} pid ${mock.pid}`)) { clearTimeout(t); ok(true); } });
|
||||
mock.stderr.on('data', d => process.stderr.write(d));
|
||||
mock.once('exit', () => { clearTimeout(t); ok(false); });
|
||||
});
|
||||
const who = listening ? await fetch(`${base}/__pid`).then(r => r.json(), () => null) : null;
|
||||
if (!listening || who?.pid !== mock.pid) { console.error(`mock did not come up as pid ${mock.pid} on ${port} (answered: ${JSON.stringify(who)})`); mock.kill(); process.exit(3); }
|
||||
console.log(`mock pid ${mock.pid} listening on ${port}; CDP on ${cdpPort}`);
|
||||
const profile = join(tmpdir(), `hel879-unified-${Date.now()}`);
|
||||
const browser = spawn(chrome, ['--headless=new', `--remote-debugging-port=${cdpPort}`, `--user-data-dir=${profile}`, '--no-first-run', '--hide-scrollbars', '--force-color-profile=srgb', '--use-fake-device-for-media-stream', '--use-fake-ui-for-media-stream', '--autoplay-policy=no-user-gesture-required', 'about:blank'], { stdio: 'ignore' });
|
||||
const sleep = ms => new Promise(r => setTimeout(r, ms));
|
||||
let targets;
|
||||
for (let i = 0; i < 60 && !targets; i++) { try { targets = await (await fetch(`http://127.0.0.1:${cdpPort}/json`)).json(); } catch { await sleep(250); } }
|
||||
const ws = new WebSocket(targets.find(t => t.type === 'page').webSocketDebuggerUrl);
|
||||
@@ -28,164 +52,306 @@ ws.addEventListener('message', ({ data }) => { const m = JSON.parse(data); if (m
|
||||
const cdp = (method, params = {}) => new Promise((ok, ko) => { const n = ++id; waiting.set(n, { ok, ko }); ws.send(JSON.stringify({ id: n, method, params })); });
|
||||
const js = async expr => { const r = await cdp('Runtime.evaluate', { expression: expr, returnByValue: true, awaitPromise: true }); if (r.exceptionDetails) throw new Error(r.exceptionDetails.exception?.description || 'js error'); return r.result.value; };
|
||||
const results = [];
|
||||
const check = (name, ok, detail = '') => { results.push(ok); console.log(`${ok ? 'PASS' : 'FAIL'} ${name}${detail ? ` — ${detail}` : ''}`); };
|
||||
const check = (name, ok, detail = '') => { results.push(ok); console.log(`${ok ? 'PASS' : 'FAIL'} ${name}${detail ? ` — ${String(detail).replace(/\n/g, ' / ').slice(0, 220)}` : ''}`); };
|
||||
const ctl = async path => (await fetch(`${base}${path}`)).json();
|
||||
const shot = async name => { const { data } = await cdp('Page.captureScreenshot', { format: 'png' }); writeFileSync(join(out, `${name}.png`), Buffer.from(data, 'base64')); };
|
||||
const frames = async (name, ms) => { const list = []; const end = Date.now() + ms; while (Date.now() < end) { const { data } = await cdp('Page.captureScreenshot', { format: 'jpeg', quality: 70 }); list.push(data); } list.forEach((d, i) => writeFileSync(join(out, `${name}-${String(i).padStart(2, '0')}.jpg`), Buffer.from(d, 'base64'))); return list.length; };
|
||||
const click = async (selector, text = '') => js(`(() => { const el = [...document.querySelectorAll(${JSON.stringify(selector)})].find(e => e.offsetParent !== null && e.textContent.includes(${JSON.stringify(text)})); if (!el) return false; el.click(); return true; })()`);
|
||||
const type = t => js(`(() => { const el = document.querySelector('textarea'); const set = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value').set; set.call(el, ${JSON.stringify(t)}); el.dispatchEvent(new Event('input', { bubbles: true })); return true; })()`);
|
||||
const until = async (fn, ms = 4000) => { const end = Date.now() + ms; while (Date.now() < end) { if (await fn()) return true; await sleep(100); } return false; };
|
||||
const stage = () => js(`document.querySelector('.conversation .stage')?.innerText || ''`);
|
||||
const said = () => js(`document.querySelector('.conversation .sr')?.textContent || ''`);
|
||||
const status = () => js(`document.querySelector('.talk-status')?.innerText || ''`);
|
||||
const row = () => js(`document.querySelector('.voice-row.real')?.innerText || ''`);
|
||||
const phase = () => js(`document.querySelector('.voice-row.real')?.dataset.phase || 'off'`);
|
||||
const lk = expr => js(`window.__lk ? (${expr}) : null`);
|
||||
const say = frame => lk(`__lk.say(${JSON.stringify(frame)})`);
|
||||
const state = s => lk(`__lk.state(${JSON.stringify(s)})`);
|
||||
const exists = sel => js(`!!document.querySelector(${JSON.stringify(sel)})`);
|
||||
const views = { desktop: { width: 1440, height: 900, deviceScaleFactor: 1, mobile: false }, phone: { width: 390, height: 844, deviceScaleFactor: 2, mobile: true } };
|
||||
async function view(v) { await cdp('Emulation.setDeviceMetricsOverride', views[v]); await cdp('Emulation.setTouchEmulationEnabled', { enabled: views[v].mobile, maxTouchPoints: 5 }); }
|
||||
const reduce = on => cdp('Emulation.setEmulatedMedia', { features: [{ name: 'prefers-reduced-motion', value: on ? 'reduce' : 'no-preference' }] });
|
||||
async function boot(theme) {
|
||||
await ctl('/__reset');
|
||||
await cdp('Page.navigate', { url: `${base}/` }); await sleep(500);
|
||||
await js(`localStorage.setItem('cg.theme', ${JSON.stringify(theme)}); sessionStorage.clear(); true`);
|
||||
await js(`localStorage.clear(); localStorage.setItem('cg.theme', ${JSON.stringify(theme)}); sessionStorage.clear(); true`);
|
||||
await cdp('Page.navigate', { url: `${base}/` }); await sleep(1600);
|
||||
}
|
||||
|
||||
// ── Sequence of the call now open (see the replay rules above). ──
|
||||
const call = { id: 0, n: 0 }, renumbered = [];
|
||||
async function startVoice() {
|
||||
await click('.voice-button'); await until(() => exists('.modal.open'));
|
||||
await click('.modal.open .btn-primary', '开始语音');
|
||||
await until(async () => (await phase()) === 'joining');
|
||||
await until(async () => (await lk('__lk.rooms.at(-1)?.state')) === 'connected');
|
||||
await lk('__lk.join()'); await sleep(250);
|
||||
call.id++; call.n = 0;
|
||||
}
|
||||
const send = async (f, from) => { const sent = { ...f, seq: ++call.n }; renumbered.push({ call: call.id, from, orig_seq: f.seq, seq: sent.seq, kind: f.kind, speech_id: f.speech_id }); await lk(`__lk.say(${JSON.stringify(sent)})`); return sent; };
|
||||
const sendAll = async (frames, from) => { for (const f of frames) await send(f, from); };
|
||||
// Negatives: exactly as written. Returns nothing the page could use to "pass" — the page must refuse them itself.
|
||||
const raw = async f => { await lk(`__lk.say(${JSON.stringify(f)})`); call.n = Math.max(call.n, f.seq); };
|
||||
const fresh = (kind, speech, extra = {}) => ({ v: 2, seq: 0, kind, role: 'assistant', text: '', speech_id: speech, ...extra });
|
||||
|
||||
// The actual worker fixtures + the sidecar that carries their turn ids / receipts.
|
||||
const load = name => readFileSync(new URL(`./fixtures/hel879/${name}.jsonl`, import.meta.url), 'utf8').split('\n').filter(l => l.trim()).map(l => JSON.parse(l));
|
||||
const sidecar = JSON.parse(readFileSync(new URL('./fixtures/hel879/sidecar.json', import.meta.url), 'utf8'));
|
||||
const of = (frames, kind, nth = 0) => frames.filter(f => f.kind === kind)[nth];
|
||||
const sayAll = async frames => { for (const f of frames) await say(f); };
|
||||
const calls = async () => ctl('/__log');
|
||||
const rows = async () => ctl('/__rows');
|
||||
const herLine = `[...document.querySelectorAll('.conversation .stage .line[data-role=companion]:not(.leaving)')].at(-1)`;
|
||||
|
||||
// ── Real screencast → WebM. No ffmpeg here: the frames Chromium itself painted are re-played at their own timestamps
|
||||
// into the browser's MediaRecorder at the end of the run. Every frame is also kept as a JPEG with its timestamp. ──
|
||||
const recordings = [];
|
||||
async function record(name, fn) {
|
||||
const got = [];
|
||||
const onFrame = ({ data }) => { const m = JSON.parse(data); if (m.method !== 'Page.screencastFrame') return; got.push({ d: m.params.data, t: m.params.metadata.timestamp }); ws.send(JSON.stringify({ id: ++id, method: 'Page.screencastFrameAck', params: { sessionId: m.params.sessionId } })); };
|
||||
ws.addEventListener('message', onFrame);
|
||||
await cdp('Page.startScreencast', { format: 'jpeg', quality: 80, everyNthFrame: 1 });
|
||||
try { await fn(); await sleep(600); } finally { await cdp('Page.stopScreencast'); ws.removeEventListener('message', onFrame); }
|
||||
const dir = join(out, `${name}-frames`); mkdirSync(dir, { recursive: true });
|
||||
got.forEach((f, i) => writeFileSync(join(dir, `${String(i).padStart(3, '0')}.jpg`), Buffer.from(f.d, 'base64')));
|
||||
writeFileSync(join(dir, 'timing.json'), JSON.stringify(got.map((f, i) => ({ i, t: f.t }))));
|
||||
recordings.push({ name, frames: got });
|
||||
}
|
||||
async function encodeAll() {
|
||||
await cdp('Page.navigate', { url: 'about:blank' }); await sleep(300);
|
||||
for (const { name, frames: list } of recordings) {
|
||||
if (list.length < 2) { console.log(`video ${name}: only ${list.length} frame(s), not encoded`); continue; }
|
||||
await js(`window.__f = []; true`);
|
||||
for (let i = 0; i < list.length; i += 6) await js(`window.__f.push(...${JSON.stringify(list.slice(i, i + 6))}); true`);
|
||||
const b64 = await js(`(async () => {
|
||||
const f = window.__f, imgs = await Promise.all(f.map(x => new Promise(ok => { const i = new Image(); i.onload = () => ok(i); i.src = 'data:image/jpeg;base64,' + x.d; })));
|
||||
const c = document.createElement('canvas'); c.width = imgs[0].naturalWidth; c.height = imgs[0].naturalHeight; document.body.append(c);
|
||||
const g = c.getContext('2d'), rec = new MediaRecorder(c.captureStream(30), { mimeType: 'video/webm;codecs=vp8', videoBitsPerSecond: 5e6 }), parts = [];
|
||||
rec.ondataavailable = e => parts.push(e.data); g.drawImage(imgs[0], 0, 0); rec.start(200);
|
||||
for (let k = 0; k < imgs.length; k++) { g.drawImage(imgs[k], 0, 0); const gap = k + 1 < f.length ? (f[k + 1].t - f[k].t) * 1000 : 1000; await new Promise(r => setTimeout(r, Math.min(4000, Math.max(16, gap)))); }
|
||||
rec.stop(); await new Promise(r => { rec.onstop = r; });
|
||||
const bytes = new Uint8Array(await new Blob(parts, { type: 'video/webm' }).arrayBuffer()); let s = '';
|
||||
for (let i = 0; i < bytes.length; i += 0x8000) s += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
|
||||
c.remove(); return btoa(s);
|
||||
})()`);
|
||||
writeFileSync(join(out, `${name}.webm`), Buffer.from(b64, 'base64'));
|
||||
console.log(`video ${name}.webm: ${list.length} real frames, ${((list.at(-1).t - list[0].t)).toFixed(1)} s`);
|
||||
}
|
||||
}
|
||||
await cdp('Page.enable'); await cdp('Runtime.enable'); await cdp('Network.enable');
|
||||
|
||||
// ── The full run on moon/desktop: every worker scenario through the real page. ──
|
||||
await view('desktop'); await boot('moon'); await click('.nav-item', '交谈'); await sleep(1400);
|
||||
await view('desktop'); await reduce(false); await boot('moon'); await click('.nav-item', '交谈'); await sleep(1400);
|
||||
await startVoice(); await calls();
|
||||
|
||||
// 1. Normal turn (worker-normal.jsonl): her words grow on the stage before anything is stored.
|
||||
// 1. Normal turn (worker-normal.jsonl). Fix 3: her short reply is on the stage while she says it, not after the final.
|
||||
const normal = load('worker-normal'), turn = sidecar.scenarios.normal.turn_id;
|
||||
await ctl(`/__voice-turn?stage=user&turn=${encodeURIComponent(turn)}&text=${encodeURIComponent('你在听吗')}`);
|
||||
await sayAll(normal.filter(f => f.seq <= 2)); await state('thinking');
|
||||
for (const f of normal.filter(f => f.kind === 'turn_start' || f.kind === 'assistant_interim')) {
|
||||
await say(f); await state('speaking');
|
||||
if (f.text.length > 8) { await until(async () => (await stage()).includes(f.text.slice(0, 6)), 6000); await frames(`w-normal-grow-${f.seq}`, 350); }
|
||||
}
|
||||
check('worker frames: her reply grows on the stage while she speaks, before it is stored', (await stage()).includes('在听呢') && (await rows()).every(r => r.role !== 'companion' || r.turn_id !== turn), (await stage()));
|
||||
const interims = normal.filter(f => f.kind === 'assistant_interim');
|
||||
let beforeSentence = '', afterSentence = '', heldOn = '', storedThen = -1;
|
||||
await record('v1-moon-desktop-short-reply-while-speaking', async () => {
|
||||
await ctl(`/__voice-turn?stage=user&turn=${encodeURIComponent(turn)}&text=${encodeURIComponent('你在听吗')}`);
|
||||
await sendAll(normal.filter(f => f.seq <= 2), 'worker-normal'); await state('thinking'); await sleep(500);
|
||||
await send(of(normal, 'turn_start'), 'worker-normal'); await state('speaking');
|
||||
await send(interims[0], 'worker-normal'); await sleep(900);
|
||||
await send(interims[1], 'worker-normal'); await sleep(1600);
|
||||
beforeSentence = await stage();
|
||||
await send(interims[2], 'worker-normal');
|
||||
await until(async () => (await stage()).includes('我还在想'), 6000);
|
||||
afterSentence = await stage(); storedThen = (await rows()).filter(r => r.turn_id === turn && r.role === 'companion').length;
|
||||
await js(`window.__line = ${herLine}; true`);
|
||||
// She is still speaking it (the final comes only after playout): it stays there the whole time.
|
||||
await sleep(2600); heldOn = await stage();
|
||||
await shot('w1-her-words-growing');
|
||||
await ctl(`/__voice-turn?stage=reply&turn=${encodeURIComponent(turn)}&text=${encodeURIComponent('在听呢,你刚才说到一半的那件事我还在想。')}`);
|
||||
await sendAll(normal.filter(f => f.kind === 'assistant_final' || f.kind === 'turn_end'), 'worker-normal'); await state('listening'); await sleep(1200);
|
||||
});
|
||||
check('fix 3: while the sentence is still forming, her half-said words wait (one or two whole sentences, as before)', !beforeSentence.includes('你刚才说到一半'), beforeSentence);
|
||||
check('fix 3: her short reply is on the stage while she speaks it, before anything is stored', afterSentence.includes('在听呢,你刚才说到一半的那件事我还在想。') && storedThen === 0, `${afterSentence} (stored rows of hers then: ${storedThen})`);
|
||||
check('fix 3: it stays through the playout (seconds before the final)', heldOn.includes('我还在想'), heldOn);
|
||||
check('fix 3: her final and her stored row take over the very same line (no re-made line, no replayed ink)', await js(`window.__line === ${herLine} && window.__line.isConnected`), await stage());
|
||||
check('worker frames: your final is your line, her words never in the voice line', !(await row()).includes('在听呢'), await row());
|
||||
await shot('w1-her-words-growing');
|
||||
// The stored row takes over: same turn id, exactly once, stage keeps its place.
|
||||
await ctl(`/__voice-turn?stage=reply&turn=${encodeURIComponent(turn)}&text=${encodeURIComponent('在听呢,你刚才说到一半的那件事我还在想。')}`);
|
||||
await sayAll(normal.filter(f => f.kind === 'assistant_final' || f.kind === 'turn_end')); await state('listening'); await sleep(900);
|
||||
await click('.log-btn'); await sleep(700);
|
||||
const record1 = await js(`document.querySelector('.log-panel .scroll')?.innerText || ''`);
|
||||
check('worker frames: the stored row (same turn id) takes over exactly once — re-read, never written by the page', record1.split('在听呢,你刚才说到一半的那件事我还在想。').length - 1 === 1, record1.slice(-140).replace(/\n/g, ' '));
|
||||
check('worker frames: the stored row (same turn id) takes over exactly once — re-read, never written by the page', record1.split('在听呢,你刚才说到一半的那件事我还在想。').length - 1 === 1, record1.slice(-140));
|
||||
await shot('w2-record-after-final');
|
||||
await click('.log-panel .btn-round'); await sleep(400); await click('.read-all'); await sleep(400); await click('.record.full .btn-round'); await sleep(300);
|
||||
await click('.log-panel .btn-round'); await sleep(400);
|
||||
|
||||
// 1b. Fix 3, a short sentence the next one joins: the line grows in place; the words already there are not redone.
|
||||
await send(fresh('turn_start', 'speech_grow'), 'driver'); await state('speaking');
|
||||
await send(fresh('assistant_interim', 'speech_grow', { text: '嗯。' }), 'driver');
|
||||
await until(async () => (await stage()).includes('嗯。'), 6000);
|
||||
await js(`window.__line = ${herLine}; window.__first = window.__line.querySelector('p').firstChild; true`);
|
||||
await send(fresh('assistant_interim', 'speech_grow', { text: '嗯。我在这儿' }), 'driver'); await sleep(500);
|
||||
const growHeld = await js(`${herLine}.innerText`);
|
||||
await send(fresh('assistant_interim', 'speech_grow', { text: '嗯。我在这儿,一直都在。' }), 'driver'); await sleep(900);
|
||||
check('fix 3: the next sentence joins the same line in place (same node, first ink untouched; the unfinished part waited)', await js(`window.__line === ${herLine} && window.__line.querySelector('p').firstChild === window.__first && window.__line.innerText.includes('嗯。我在这儿,一直都在。')`) && !growHeld.includes('我在这儿'), await js(`${herLine}.innerText`));
|
||||
await send(fresh('turn_cancel', 'speech_grow', { reason: 'interrupted' }), 'driver'); await state('listening'); await sleep(400);
|
||||
|
||||
// 1c. Fix 3 negative: a long sentence still reads a line at a time; the part still being said waits.
|
||||
const long = '我下午去了河边,看到一群白鹭从水面上飞过去了,它们飞得很低,几乎贴着水,翅膀尖在水面上划出一道一道细细的白线,后来又绕回来落在对岸的芦苇里';
|
||||
await send(fresh('turn_start', 'speech_long'), 'driver'); await state('speaking');
|
||||
await send(fresh('assistant_interim', 'speech_long', { text: long }), 'driver');
|
||||
await until(async () => (await stage()).includes('白鹭'), 8000);
|
||||
const longStage = await stage();
|
||||
check('fix 3 negative: a long sentence shows its finished lines only, never the whole text at once', longStage.includes('白鹭') && !longStage.includes('芦苇里'), longStage);
|
||||
await send(fresh('turn_cancel', 'speech_long', { reason: 'interrupted' }), 'driver'); await state('listening'); await sleep(400);
|
||||
check('a cancelled reply leaves at once', !(await stage()).includes('白鹭'), await stage());
|
||||
await click('.read-all'); await sleep(400); await click('.record.full .btn-round'); await sleep(300);
|
||||
|
||||
// 2. Barge-in (worker-interrupt.jsonl): the cut turn never gets a final; the next turn lands clean.
|
||||
const it = load('worker-interrupt'), cutTurn = sidecar.scenarios.interrupt.turn_ids.cut, nextTurn = sidecar.scenarios.interrupt.turn_ids.next;
|
||||
await ctl(`/__voice-turn?stage=user&turn=${encodeURIComponent(cutTurn)}&text=${encodeURIComponent('讲讲你下午做了什么')}`);
|
||||
await sayAll(it.slice(0, 4)); await state('speaking');
|
||||
await until(async () => (await stage()).includes('白鹭'), 6000);
|
||||
await sendAll(it.slice(0, 4), 'worker-interrupt'); await state('speaking'); await sleep(1500);
|
||||
await shot('w3-before-cut');
|
||||
await sayAll(it.slice(4, 5)); await state('listening'); await ctl(`/__voice-turn?stage=cancel&turn=${encodeURIComponent(cutTurn)}`); await sleep(250);
|
||||
check('worker frames: interrupted — her unfinished line is gone at once, no final exists for the cut turn', !(await stage()).includes('白鹭') && it.filter(f => f.kind === 'assistant_final' && f.speech_id === of(it, 'turn_cancel').speech_id).length === 0, await stage());
|
||||
// Late frames of the cut speech (fresh seqs, dead speech) change nothing.
|
||||
const cutSpeech = of(it, 'turn_cancel').speech_id;
|
||||
await say({ v: 2, seq: 90, kind: 'assistant_interim', role: 'assistant', speech_id: cutSpeech, text: '白鹭又飞回来了' });
|
||||
await say({ v: 2, seq: 91, kind: 'assistant_final', role: 'assistant', speech_id: cutSpeech, turn_id: 'late', text: '白鹭又飞回来了。' });
|
||||
await sleep(350);
|
||||
check('worker frames: late frames of the cut speech stay out', !(await stage()).includes('飞回来'));
|
||||
// The next clean turn of the same recording lands with its own receipt.
|
||||
const sentInterim = renumbered.filter(x => x.from === 'worker-interrupt' && x.kind === 'assistant_interim').at(-1);
|
||||
await send(it[4], 'worker-interrupt'); await state('listening'); await ctl(`/__voice-turn?stage=cancel&turn=${encodeURIComponent(cutTurn)}`); await sleep(250);
|
||||
check('worker frames: interrupted — her unfinished line is gone at once, no final exists for the cut turn', !(await stage()).includes('白鹭') && it.filter(f => f.kind === 'assistant_final' && f.speech_id === cutSpeech).length === 0, await stage());
|
||||
// Negatives, RAW. (a) The cut speech's late frames with seqs ABOVE the high-water mark: only the speech gate stops them.
|
||||
const high = call.n;
|
||||
await raw({ v: 2, seq: high + 1, kind: 'assistant_interim', role: 'assistant', speech_id: cutSpeech, text: '白鹭又飞回来了。' });
|
||||
await raw({ v: 2, seq: high + 2, kind: 'assistant_final', role: 'assistant', speech_id: cutSpeech, turn_id: 'late', text: '白鹭又飞回来了。' });
|
||||
await sleep(400);
|
||||
check('negative (raw): late frames of the cut speech, fresh seqs — refused by the speech gate', !(await stage()).includes('飞回来'), await stage());
|
||||
// (b) A replay of a frame already applied (same seq) and an out-of-order lower seq for a new speech: the seq gate.
|
||||
await raw({ v: 2, seq: sentInterim.seq, kind: 'assistant_interim', role: 'assistant', speech_id: cutSpeech, text: '我下午去了河边。' });
|
||||
await raw({ v: 2, seq: high, kind: 'turn_start', role: 'assistant', speech_id: 'speech_late', text: '' });
|
||||
await raw({ v: 2, seq: high - 1, kind: 'assistant_interim', role: 'assistant', speech_id: 'speech_late', text: '乱序的旧话。' });
|
||||
await sleep(400);
|
||||
check('negative (raw): a replayed seq and out-of-order lower seqs — refused by the seq gate', !(await stage()).includes('乱序的旧话') && !(await stage()).includes('去了河边'), await stage());
|
||||
// The next clean turn of the same recording lands with its own receipt (renumbered past everything above).
|
||||
await ctl(`/__voice-turn?stage=user&turn=${encodeURIComponent(nextTurn)}&text=${encodeURIComponent('那后来呢')}`);
|
||||
await ctl(`/__voice-turn?stage=reply&turn=${encodeURIComponent(nextTurn)}&text=${encodeURIComponent('后来我在桥上站了一会儿,风把水面吹皱了。')}`);
|
||||
await sayAll(it.slice(5)); await state('speaking'); await until(async () => (await stage()).includes('桥上'), 6000); await state('listening'); await sleep(700);
|
||||
await sendAll(it.slice(5), 'worker-interrupt'); await state('speaking'); await until(async () => (await stage()).includes('桥上'), 6000); await state('listening'); await sleep(700);
|
||||
await click('.log-btn'); await sleep(600);
|
||||
const record2 = await js(`document.querySelector('.log-panel .scroll')?.innerText || ''`);
|
||||
check('worker frames: the next turn lands clean (one stored row of its own)', record2.includes('风把水面吹皱了') && record2.split('风把水面吹皱了').length - 1 === 1, record2.slice(-120).replace(/\n/g, ' '));
|
||||
check('worker frames: the next turn lands clean (one stored row of its own)', record2.split('风把水面吹皱了').length - 1 === 1, record2.slice(-120));
|
||||
await click('.log-panel .btn-round'); await sleep(300);
|
||||
|
||||
// 3. phi (worker-phi.jsonl): her failed line is heard, not stored.
|
||||
const phi = load('worker-phi');
|
||||
await ctl(`/__voice-turn?stage=user&turn=${encodeURIComponent(sidecar.scenarios.phi.turn_id)}&text=${encodeURIComponent('说说那件事吧')}`);
|
||||
await sayAll(phi); await state('speaking'); await sleep(300); await state('listening'); await sleep(300);
|
||||
await sendAll(phi, 'worker-phi'); await state('speaking'); await sleep(300); await state('listening'); await sleep(300);
|
||||
check('worker frames: phi is heard in the voice line, not stored as her reply', (await row()).includes('说不出来话') && !(await stage()).includes('说不出来话'), await row());
|
||||
await shot('w4-phi-heard');
|
||||
await sleep(600);
|
||||
|
||||
// 4. No legal receipt (worker-no_receipt.jsonl): cancel only, nothing on the stage.
|
||||
// 4. No legal receipt (worker-no_receipt.jsonl): cancel only, nothing of hers stays.
|
||||
const nr = load('worker-no_receipt');
|
||||
await ctl(`/__voice-turn?stage=user&turn=${encodeURIComponent(sidecar.scenarios.no_receipt.turn_id)}&text=${encodeURIComponent('再讲讲那座桥')}`);
|
||||
await sayAll(nr.filter(f => f.kind !== 'turn_cancel')); await state('speaking');
|
||||
await until(async () => (await stage()).includes('水声很好听'), 6000);
|
||||
await say(of(nr, 'turn_cancel')); await state('listening'); await sleep(300);
|
||||
check('worker frames: no legal receipt — the page never shows a final (cancel only)', !(await stage()).includes('水声很好听') && nr.every(f => f.kind !== 'assistant_final'), await stage());
|
||||
await sendAll(nr.filter(f => f.kind !== 'turn_cancel'), 'worker-no_receipt'); await state('speaking'); await sleep(1500);
|
||||
await send(of(nr, 'turn_cancel'), 'worker-no_receipt'); await state('listening'); await sleep(300);
|
||||
check('worker frames: no legal receipt — nothing of that reply stays (cancel only, never a final)', !(await stage()).includes('水声很好听') && nr.every(f => f.kind !== 'assistant_final'), await stage());
|
||||
|
||||
// 5. Proactive (worker-proactive.jsonl): start DURING playout, end/cancel with the row's own id.
|
||||
await ctl(`/__proactive?id=301&text=${encodeURIComponent('刚才路过花店,想起你说过喜欢白色的洋桔梗。')}`); await calls();
|
||||
const pro = load('worker-proactive');
|
||||
await say(of(pro.filter(f => f.message_id === 301), 'proactive_start')); await state('speaking'); await sleep(600);
|
||||
await send(of(pro.filter(f => f.message_id === 301), 'proactive_start'), 'worker-proactive'); await state('speaking'); await sleep(600);
|
||||
check('worker frames: reach-out read aloud is shown word for word while she speaks it', (await stage()).includes('洋桔梗'), await stage());
|
||||
await shot('w5-reach-out');
|
||||
await say(of(pro.filter(f => f.message_id === 301), 'proactive_end')); await state('listening'); await sleep(400);
|
||||
// The interrupted variant clears without a trace and the page wrote nothing.
|
||||
const before = await calls();
|
||||
await say(pro.filter(f => f.message_id === 302)[0]); await state('speaking'); await sleep(250);
|
||||
await say(pro.filter(f => f.message_id === 302)[1]); await state('listening'); await sleep(250);
|
||||
await send(of(pro.filter(f => f.message_id === 301), 'proactive_end'), 'worker-proactive'); await state('listening'); await sleep(400);
|
||||
await calls();
|
||||
await send(pro.filter(f => f.message_id === 302)[0], 'worker-proactive'); await state('speaking'); await sleep(250);
|
||||
await send(pro.filter(f => f.message_id === 302)[1], 'worker-proactive'); await state('listening'); await sleep(250);
|
||||
const after = await calls();
|
||||
check('worker frames: an interrupted reach-out clears; the page still wrote nothing (no receipt, no read mark)', !after.some(l => !l.startsWith('GET ')), after.join(' | '));
|
||||
|
||||
// 6. Text takes over while she speaks (the worker's own next turn): typed words come next.
|
||||
const nt = load('worker-normal'), nt2 = { ...normal[2], seq: 100, speech_id: 'speech_text_takeover' };
|
||||
await say(nt2); await state('speaking'); await sleep(200);
|
||||
await send({ ...normal[2], speech_id: 'speech_text_takeover' }, 'worker-normal (speech id renamed)');
|
||||
await send({ ...interims[2], speech_id: 'speech_text_takeover' }, 'worker-normal (speech id renamed)'); await state('speaking'); await sleep(200);
|
||||
await type('先等等,我打字跟你说'); await js(`document.querySelector('.send').click(), true`); await sleep(400);
|
||||
check('text over voice: her worker line is gone at once, your typed words are on the stage', !(await stage()).includes('在听呢,') && (await stage()).includes('先等等'), await stage());
|
||||
check('text over voice: her worker line is gone at once, your typed words are on the stage', !(await stage()).includes('我还在想') && (await stage()).includes('先等等'), await stage());
|
||||
await until(async () => !(await exists('.reader-bar .stop')), 9000); await state('listening'); await sleep(400);
|
||||
|
||||
// 7. The room drops mid-sentence: everything clears with the call; starting again works.
|
||||
await say({ v: 2, seq: 120, kind: 'turn_start', role: 'assistant', speech_id: 'speech_drop', text: '' });
|
||||
await say({ v: 2, seq: 121, kind: 'assistant_interim', role: 'assistant', speech_id: 'speech_drop', text: '晚安,明天见。' }); await state('speaking');
|
||||
// 7. Fix 2 in the page: the hand-built gate probes (66 later speeches, then speech_A again with fresh seqs), RAW,
|
||||
// in a call of their own (their seqs are their own, from 1).
|
||||
await click('.voice-row.real .voice-end'); await sleep(400);
|
||||
await startVoice();
|
||||
for (const f of load('adversarial-gates')) await raw(f);
|
||||
// Long enough for the reading flow to reach the newest line of this turn (the lines before it take their time).
|
||||
const back = await until(async () => /被挤出后的重放|迟到的旧稿/u.test(await stage()), 12000);
|
||||
check('fix 2 (raw probes): a long-retired speech re-sent with fresh seqs never comes back (watched 12 s)', !back, await stage());
|
||||
await raw({ v: 2, seq: call.n + 1, kind: 'turn_start', role: 'assistant', speech_id: 'speech_after_probe', text: '' });
|
||||
await raw({ v: 2, seq: call.n + 1, kind: 'assistant_interim', role: 'assistant', speech_id: 'speech_after_probe', text: '还在呢。' }); await state('speaking');
|
||||
check('fix 2: a new speech after the probes still comes in', await until(async () => (await stage()).includes('还在呢'), 15000), await stage());
|
||||
await state('listening');
|
||||
|
||||
// 8. The room drops mid-sentence: everything clears with the call; starting again works.
|
||||
await send(fresh('turn_start', 'speech_drop'), 'driver');
|
||||
await send(fresh('assistant_interim', 'speech_drop', { text: '晚安,明天见。' }), 'driver'); await state('speaking');
|
||||
await until(async () => (await stage()).includes('晚安'), 6000);
|
||||
await lk('__lk.drop()'); await sleep(400);
|
||||
check('dropped mid-sentence: her line and the call clear together', !(await stage()).includes('晚安') && (await phase()) === 'off', await stage());
|
||||
await shot('w6-after-drop');
|
||||
await startVoice(); await calls();
|
||||
const fresh = { v: 2, seq: 1, kind: 'turn_start', role: 'assistant', speech_id: 'speech_fresh', text: '' };
|
||||
const freshText = { v: 2, seq: 2, kind: 'assistant_interim', role: 'assistant', speech_id: 'speech_fresh', text: '又见面了。' };
|
||||
await say(fresh); await say(freshText); await state('speaking');
|
||||
await send(fresh('turn_start', 'speech_fresh'), 'driver'); await send(fresh('assistant_interim', 'speech_fresh', { text: '又见面了。' }), 'driver'); await state('speaking');
|
||||
await until(async () => (await stage()).includes('又见面了'), 6000);
|
||||
check('a new call is a new room and a new sequence: her words flow again, nothing of the old call remains', (await stage()).includes('又见面了') && !(await stage()).includes('晚安'), await stage());
|
||||
check('a new call is a new room and a new sequence (from 1): her words flow again, nothing of the old call remains', (await stage()).includes('又见面了') && !(await stage()).includes('晚安'), await stage());
|
||||
await shot('w7-reopened');
|
||||
await click('.voice-row.real .voice-end'); await sleep(300);
|
||||
await send(fresh('turn_end', 'speech_fresh'), 'driver'); await state('listening'); await sleep(300);
|
||||
|
||||
// ── Second theme + phone: the same worker frames on the approved visuals. ──
|
||||
for (const [theme, v, tag] of [['fog', 'desktop', 'fog'], ['moon', 'phone', 'phone']]) {
|
||||
await view(v); await boot(theme); await click('.nav-item', '交谈'); await sleep(1400); await startVoice(); await calls();
|
||||
// 9. Fix 1: her worker leaves while the room stays open.
|
||||
async function workerLeaves(tag) {
|
||||
await calls();
|
||||
await lk('__lk.guest()'); await sleep(200); await lk('__lk.guestLeave()'); await sleep(500);
|
||||
check(`${tag} fix 1 negative: someone else leaving does not hang up`, (await phase()) !== 'off' && !(await status()).includes('中断'), `${await phase()} ${await status()}`);
|
||||
const sid = (await ctl('/__sessions')).open.at(-1);
|
||||
let gone = '';
|
||||
await record(`v2-${tag}-worker-leaves`, async () => {
|
||||
await send(fresh('turn_start', `speech_${tag}_left`), 'driver'); await state('speaking');
|
||||
await send(fresh('assistant_interim', `speech_${tag}_left`, { text: '我先去看看窗外。' }), 'driver');
|
||||
await until(async () => (await stage()).includes('窗外'), 6000); await sleep(800);
|
||||
await lk('__lk.leave()');
|
||||
await until(async () => (await phase()) === 'off', 3000); await sleep(300); gone = await stage();
|
||||
await sleep(1500);
|
||||
});
|
||||
const mic = await lk(`__lk.mics.at(-1).readyState`), holder = await exists('[data-voice=her]'), log = await calls(), open = (await ctl('/__sessions')).open;
|
||||
check(`${tag} fix 1: the call ends at once — her line cleared, honest notice, microphone off, her audio gone`, (await phase()) === 'off' && !gone.includes('窗外') && (await status()).includes('她那边的语音中断了') && mic === 'ended' && !holder, `${await status()} mic=${mic} holder=${holder}`);
|
||||
check(`${tag} fix 1: this call's server room is deleted (once)`, log.filter(l => l === `DELETE /api/voice/session/${sid}`).length === 1 && !open.includes(sid), log.join(' | '));
|
||||
await shot(`${tag}-worker-left`);
|
||||
// Late events of that room (its own Disconnected, its worker "leaving" again) say nothing more.
|
||||
await lk('__lk.lateLeave(-1)'); await sleep(400);
|
||||
check(`${tag} fix 1: a late leave of that room changes nothing more (no second notice, no second DELETE)`, !(await calls()).some(l => l.startsWith('DELETE')), await status());
|
||||
}
|
||||
await workerLeaves('moon-desktop');
|
||||
// An old room's worker leaving late never ends the call that replaced it; your own hang-up adds no notice.
|
||||
await startVoice(); await calls();
|
||||
const oldRoom = await lk('__lk.rooms.length') - 2;
|
||||
await lk(`__lk.lateLeave(${oldRoom})`); await sleep(500);
|
||||
check('fix 1 negative: an old room\'s late worker leave does not end the new call', (await phase()) !== 'off' && !(await status()).includes('中断'), `${await phase()} ${await status()}`);
|
||||
const sid2 = (await ctl('/__sessions')).open.at(-1);
|
||||
await click('.voice-row.real .voice-end'); await sleep(500);
|
||||
await lk(`__lk.lateLeave(-1)`); await sleep(400);
|
||||
const endLog = await calls();
|
||||
check('fix 1 negative: your own hang-up — one DELETE, no "she left" notice', endLog.filter(l => l === `DELETE /api/voice/session/${sid2}`).length === 1 && !(await status()).includes('中断'), endLog.join(' | '));
|
||||
|
||||
// ── Second theme, phone, and reduced motion: the same worker frames and the three fixes on the approved visuals. ──
|
||||
for (const [theme, v, tag, still] of [['fog', 'desktop', 'fog-desktop', false], ['moon', 'phone', 'moon-phone', false], ['fog', 'phone', 'fog-phone', false], ['moon', 'desktop', 'reduced-motion', true]]) {
|
||||
await view(v); await reduce(still); await boot(theme); await click('.nav-item', '交谈'); await sleep(1400); await startVoice(); await calls();
|
||||
const t = load('worker-normal'), tid = sidecar.scenarios.normal.turn_id;
|
||||
await ctl(`/__voice-turn?stage=user&turn=${encodeURIComponent(tid)}&text=${encodeURIComponent('你在听吗')}`);
|
||||
await sayAll(t.filter(f => f.seq <= 2));
|
||||
await say(of(t, 'turn_start')); await state('speaking');
|
||||
for (const f of t.filter(f => f.kind === 'assistant_interim')) { await say(f); await sleep(260); }
|
||||
check(`${tag}: worker frames grow her reply on the approved ${theme} ${v} layout`, await until(async () => (await stage()).includes('在听呢,你刚才说到一半的那件事'), 8000), await stage());
|
||||
if (tag === 'phone') await frames('phone-growing', 700);
|
||||
let early = '';
|
||||
const run = async () => {
|
||||
await ctl(`/__voice-turn?stage=user&turn=${encodeURIComponent(tid)}&text=${encodeURIComponent('你在听吗')}`);
|
||||
await sendAll(t.filter(f => f.seq <= 2), 'worker-normal'); await state('thinking'); await sleep(400);
|
||||
await send(of(t, 'turn_start'), 'worker-normal'); await state('speaking');
|
||||
for (const f of t.filter(f => f.kind === 'assistant_interim')) { await send(f, 'worker-normal'); await sleep(500); }
|
||||
await until(async () => (await stage()).includes('我还在想'), 8000); early = await stage();
|
||||
stored = (await rows()).filter(r => r.role === 'companion' && r.turn_id === tid).length;
|
||||
await sleep(1800);
|
||||
};
|
||||
let stored = -1;
|
||||
if (tag === 'moon-phone' || tag === 'reduced-motion') await record(`v3-${tag}-short-reply-while-speaking`, run); else await run();
|
||||
check(`${tag}: her short reply is on the stage while she speaks it (before the final), approved ${theme} ${v}`, early.includes('在听呢,你刚才说到一半的那件事我还在想。') && stored === 0, early);
|
||||
if (still) check('reduced motion: her words arrive without ink or slide', !(await exists('.conversation .stage .ink')), '');
|
||||
await shot(`${tag}-her-words-growing`);
|
||||
await ctl(`/__voice-turn?stage=reply&turn=${encodeURIComponent(tid)}&text=${encodeURIComponent('在听呢,你刚才说到一半的那件事我还在想。')}`);
|
||||
await sayAll(t.filter(f => f.kind === 'assistant_final' || f.kind === 'turn_end')); await state('listening'); await sleep(800);
|
||||
await sendAll(t.filter(f => f.kind === 'assistant_final' || f.kind === 'turn_end'), 'worker-normal'); await state('listening'); await sleep(800);
|
||||
await click('.log-btn'); await sleep(600);
|
||||
const rec = await js(`document.querySelector('.log-panel .scroll')?.innerText || ''`);
|
||||
check(`${tag}: the stored row takes over once on ${theme} ${v}`, rec.split('在听呢,你刚才说到一半的那件事我还在想。').length - 1 === 1, '');
|
||||
check(`${tag}: the stored row takes over once on ${theme} ${v} (isolated record)`, rec.split('在听呢,你刚才说到一半的那件事我还在想。').length - 1 === 1, rec.slice(-120));
|
||||
await click('.log-panel .btn-round'); await sleep(300);
|
||||
await click('.voice-row.real .voice-end'); await sleep(300);
|
||||
await workerLeaves(tag);
|
||||
}
|
||||
|
||||
writeFileSync(join(out, 'seq-renumbering.json'), JSON.stringify(renumbered, null, 1));
|
||||
await reduce(false); await view('desktop');
|
||||
await encodeAll();
|
||||
ws.close(); browser.kill(); mock.kill();
|
||||
const failed = results.filter(r => !r).length;
|
||||
console.log(`${results.length - failed}/${results.length} passed`);
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { livekitTransport, type Livekit } from '../src/voice/livekit';
|
||||
import { VoiceController, WORDS, type MicTrack, type RoomEvents, type VoiceRoom, type VoiceView } from '../src/voice/session';
|
||||
|
||||
// HEL-898 (f92a86f review): her worker leaving a room that stays open. Driven through the real transport adapter
|
||||
// (src/voice/livekit.ts) with a scripted client that uses the vendored livekit-client 2.22.4 event names
|
||||
// (RoomEvent.ParticipantDisconnected = 'participantDisconnected', emitted as (participant, reason)); no WebRTC.
|
||||
const RoomEvent = { TrackSubscribed: 'trackSubscribed', TrackUnsubscribed: 'trackUnsubscribed', ParticipantConnected: 'participantConnected', ParticipantDisconnected: 'participantDisconnected', ParticipantAttributesChanged: 'participantAttributesChanged', DataReceived: 'dataReceived', Disconnected: 'disconnected', AudioPlaybackStatusChanged: 'audioPlaybackChanged' };
|
||||
const AGENT = 4;
|
||||
interface P { identity: string; kind?: number; attributes?: Record<string, string> }
|
||||
class FakeRoom {
|
||||
handlers: Record<string, ((...a: unknown[]) => void)[]> = {}; remoteParticipants = new Map<string, P>(); canPlaybackAudio = true; disconnects = 0; published: unknown[] = [];
|
||||
localParticipant = { publishTrack: async (t: unknown) => { this.published.push(t); } };
|
||||
constructor() { rooms.push(this); }
|
||||
on(e: string, cb: (...a: unknown[]) => void) { (this.handlers[e] ||= []).push(cb); return this; }
|
||||
emit(e: string, ...a: unknown[]) { (this.handlers[e] || []).forEach(cb => cb(...a)); }
|
||||
async connect() {}
|
||||
async disconnect() { this.disconnects++; [...this.remoteParticipants.values()].forEach(p => this.leave(p.identity)); this.emit(RoomEvent.Disconnected); }
|
||||
async startAudio() {}
|
||||
enter(p: P) { this.remoteParticipants.set(p.identity, p); this.emit(RoomEvent.ParticipantConnected, p); }
|
||||
// As the SDK does: the participant is removed from the map, then the event carries it and a reason.
|
||||
leave(identity: string) { const p = this.remoteParticipants.get(identity); if (!p) return; this.remoteParticipants.delete(identity); this.emit(RoomEvent.ParticipantDisconnected, p, 1); }
|
||||
say(frame: unknown) { this.emit(RoomEvent.DataReceived, new TextEncoder().encode(JSON.stringify(frame)), undefined, 0, 'cg.subtitle'); }
|
||||
}
|
||||
let rooms: FakeRoom[] = [], mics: { stopped: number }[] = [];
|
||||
const lk = {
|
||||
Room: FakeRoom, RoomEvent, Track: { Source: { Microphone: 'microphone' } }, ParticipantKind: { AGENT },
|
||||
async createLocalAudioTrack() { const m = { stopped: 0 }; mics.push(m); const mst = { stop: () => { m.stopped++; }, addEventListener() {} }; return { kind: 'audio', mediaStreamTrack: mst, attach: () => ({}), detach: () => [], stop: () => {} }; },
|
||||
} as unknown as Livekit;
|
||||
const worker: P = { identity: 'agent-AJ_1', kind: AGENT, attributes: { 'lk.agent.state': 'listening' } };
|
||||
|
||||
// The adapter keeps her audio in a hidden holder element; a node test has no DOM, so the few calls it makes are stubbed.
|
||||
beforeEach(() => {
|
||||
rooms = []; mics = [];
|
||||
const el = () => ({ hidden: false, dataset: {}, querySelectorAll: () => [], remove() {}, append() {} });
|
||||
vi.stubGlobal('document', { createElement: el, body: { append() {} } });
|
||||
});
|
||||
afterEach(() => { vi.unstubAllGlobals(); vi.restoreAllMocks(); });
|
||||
|
||||
function rig(deleteStatus = 200) {
|
||||
const calls: string[] = [], views: VoiceView[] = [], record = vi.fn();
|
||||
let status = deleteStatus, made = 0;
|
||||
const f = vi.fn(async (url: string, init: RequestInit = {}) => {
|
||||
const method = init.method || 'GET'; calls.push(`${method} ${url}`);
|
||||
if (url === '/api/voice/status') return new Response(JSON.stringify({ configured: true, tts_ok: true }));
|
||||
if (url === '/api/voice/session' && method === 'POST') { const id = `s${++made}`; return new Response(JSON.stringify({ url: 'wss://lk.test', token: `t-${id}`, room: `cg-voice-${id}`, session_id: id, epoch: 3, expires_at: 0 }), { status: 201 }); }
|
||||
if (method === 'DELETE') return new Response('{}', { status });
|
||||
return new Response('{}', { status: 404 });
|
||||
});
|
||||
const c = new VoiceController({ transport: async () => livekitTransport(lk), onView: v => views.push(v), onRecord: record, onSpoke: () => {}, fetch: f as unknown as typeof fetch, secure: () => true, agentWaitMs: 60000 });
|
||||
return { c, calls, views, view: () => views.at(-1)!, setDelete: (s: number) => { status = s; } };
|
||||
}
|
||||
const flush = async () => { for (let i = 0; i < 8; i++) await Promise.resolve(); await new Promise(r => setTimeout(r, 0)); };
|
||||
const deletes = (calls: string[]) => calls.filter(c => c.startsWith('DELETE'));
|
||||
|
||||
describe('her worker leaves while the room stays open (real adapter, SDK event names)', () => {
|
||||
it('ends the call honestly: her line, microphone, audio, room and server room all go at once', async () => {
|
||||
const r = rig(); await r.c.start(); const room = rooms[0];
|
||||
room.enter(worker);
|
||||
room.say({ v: 2, seq: 1, kind: 'user_final', role: 'user', text: '你在听吗' });
|
||||
room.say({ v: 2, seq: 2, kind: 'turn_start', role: 'assistant', text: '', speech_id: 'sp' });
|
||||
room.say({ v: 2, seq: 3, kind: 'assistant_interim', role: 'assistant', text: '在听呢。', speech_id: 'sp' });
|
||||
expect(r.view()).toMatchObject({ phase: 'thinking', her: { speech: 'sp', text: '在听呢。', state: 'open' } });
|
||||
room.leave(worker.identity); await flush();
|
||||
expect(r.view()).toEqual({ phase: 'off', heard: '', spoken: '', her: null, notice: WORDS.agentLeft, blocked: false });
|
||||
expect(mics[0].stopped).toBeGreaterThan(0);
|
||||
expect(room.disconnects).toBe(1);
|
||||
expect(deletes(r.calls)).toEqual(['DELETE /api/voice/session/s1']);
|
||||
// Nothing of that room is heard from again (its own Disconnected, late frames): one notice, one cleanup.
|
||||
room.say({ v: 2, seq: 9, kind: 'assistant_final', role: 'assistant', text: '晚到。', speech_id: 'sp', turn_id: 'T' });
|
||||
room.emit(RoomEvent.ParticipantDisconnected, worker, 1); await flush();
|
||||
expect(r.views.filter(v => v.notice === WORDS.agentLeft)).toHaveLength(1);
|
||||
expect(r.view().her).toBeNull();
|
||||
expect(deletes(r.calls)).toHaveLength(1);
|
||||
});
|
||||
it('a DELETE that could not get through is owed and sent again, as any failure', async () => {
|
||||
const r = rig(503); await r.c.start(); const room = rooms[0];
|
||||
room.enter(worker); room.leave(worker.identity); await flush();
|
||||
expect(r.view().notice).toBe(WORDS.agentLeft);
|
||||
r.setDelete(404); await r.c.settle();
|
||||
expect(deletes(r.calls)).toEqual(['DELETE /api/voice/session/s1', 'DELETE /api/voice/session/s1']);
|
||||
});
|
||||
it('anyone else leaving does not hang up; nor does a second worker leaving while hers stays', async () => {
|
||||
const r = rig(); await r.c.start(); const room = rooms[0];
|
||||
room.enter(worker); room.enter({ identity: 'guest-1', kind: 0, attributes: {} });
|
||||
room.leave('guest-1'); await flush();
|
||||
expect(r.view()).toMatchObject({ phase: 'listening', notice: '' });
|
||||
room.enter({ identity: 'agent-AJ_2', kind: AGENT, attributes: {} }); room.leave('agent-AJ_2'); await flush();
|
||||
expect(r.view()).toMatchObject({ phase: 'listening', notice: '' });
|
||||
expect(deletes(r.calls)).toHaveLength(0);
|
||||
await r.c.end();
|
||||
});
|
||||
it('your own hang-up says nothing more: the room closing takes her worker with it silently', async () => {
|
||||
const r = rig(); await r.c.start(); const room = rooms[0];
|
||||
room.enter(worker);
|
||||
await r.c.end(); await flush();
|
||||
expect(room.disconnects).toBe(1);
|
||||
expect(r.views.some(v => v.notice)).toBe(false);
|
||||
expect(deletes(r.calls)).toHaveLength(1);
|
||||
});
|
||||
it('an old room\'s worker leaving late never ends the new call', async () => {
|
||||
const r = rig(); await r.c.start(); const first = rooms[0]; first.enter(worker);
|
||||
await r.c.start(); const second = rooms[1]; second.enter({ ...worker, identity: 'agent-AJ_new' });
|
||||
// The first room was closed by the restart; its handlers stay registered, and fire late.
|
||||
first.emit(RoomEvent.ParticipantDisconnected, worker, 1); await flush();
|
||||
expect(r.view()).toMatchObject({ phase: 'listening', notice: '' });
|
||||
expect(deletes(r.calls)).toEqual(['DELETE /api/voice/session/s1']);
|
||||
await r.c.end();
|
||||
});
|
||||
});
|
||||
|
||||
describe('controller: agentLeft only for this call, only once she was there', () => {
|
||||
class Room implements VoiceRoom { closed = 0; on!: RoomEvents; async publish(_m: MicTrack) {} hush() {} async resumeAudio() {} async close() { this.closed++; } }
|
||||
const make = () => {
|
||||
const list: Room[] = [], views: VoiceView[] = [];
|
||||
const transport = { capture: async () => ({ stop() {}, onEnded() {} }), join: async (_u: string, _t: string, on: RoomEvents) => { const x = new Room(); x.on = on; list.push(x); return x; } };
|
||||
const f = vi.fn(async (url: string, init: RequestInit = {}) => url === '/api/voice/status' ? new Response('{"configured":true,"tts_ok":true}') : init.method === 'POST' ? new Response(JSON.stringify({ url: 'u', token: 't', room: 'r', session_id: `s${list.length + 1}`, epoch: 1, expires_at: 0 }), { status: 201 }) : new Response('{}'));
|
||||
const c = new VoiceController({ transport: async () => transport, onView: v => views.push(v), onRecord: () => {}, onSpoke: () => {}, fetch: f as unknown as typeof fetch, secure: () => true, agentWaitMs: 60000 });
|
||||
return { c, list, views, view: () => views.at(-1)! };
|
||||
};
|
||||
it('before her worker ever joined, a leave is not hers to report (the join wait says it honestly)', async () => {
|
||||
const r = make(); await r.c.start();
|
||||
r.list[0].on.agentLeft(); await flush();
|
||||
expect(r.view()).toMatchObject({ phase: 'joining', notice: '' });
|
||||
await r.c.end();
|
||||
});
|
||||
it('a stale call\'s agentLeft changes nothing in the new call', async () => {
|
||||
const r = make(); await r.c.start(); r.list[0].on.agentJoined();
|
||||
await r.c.end(); await r.c.start(); r.list[1].on.agentJoined();
|
||||
r.list[0].on.agentLeft(); await flush();
|
||||
expect(r.view()).toMatchObject({ phase: 'listening', notice: '' });
|
||||
expect(r.list[1].closed).toBe(0);
|
||||
r.list[1].on.agentLeft(); await flush();
|
||||
expect(r.view()).toMatchObject({ phase: 'off', notice: WORDS.agentLeft });
|
||||
expect(r.list[1].closed).toBe(1);
|
||||
});
|
||||
});
|
||||
+33
-3
@@ -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();
|
||||
|
||||
Reference in New Issue
Block a user