HEL-878: preserve original author continuous voice wiring

Co-authored-by: multica-agent <github@multica.ai>
This commit is contained in:
2026-10-27 02:35:37 +08:00
co-authored by multica-agent
parent bf234570c0
commit b95ce798b4
13 changed files with 1234 additions and 11 deletions
+90 -8
View File
@@ -10,6 +10,9 @@ import { snap } from '../shared/motion';
import { motionOff } from '../stage/roomScene';
import { LineStage, type PresentHow } from './lineStage';
import { anchorOf, cursorAt, groupTurns, pagesOf, ReadingClock, type Anchor, type Metrics, type ShownMessage } from './reading';
import { mergeTurns, OFF, recentRows, VoiceController, voiceStatus, WORDS, type VoiceView } from '../voice/session';
import { loadTransport } from '../voice/livekit';
import { newestId, serverId } from '../adapters/inbox';
const START: Anchor = { mi: 0, offset: 0 };
const metricsFor = (width: number): Metrics => { const compact = document.documentElement.classList.contains('compact'); return { width, font: compact ? 16 : innerWidth <= 720 ? 18 : 23, compact }; };
@@ -47,6 +50,51 @@ export function ChatPanel({ state, onChange, onPresence, onVoice, onObservation,
const name = state.identity.name;
const change = (messages: Message[]) => { live.current = messages; onChange(messages); };
// ── Real voice (R5). The controller owns the call; this panel shows its state and keeps the record in step. ──
const [voiceView, setVoiceView] = useState<VoiceView>(OFF), [voiceOff, setVoiceOff] = useState('');
const voiceCtl = useRef<VoiceController | null>(null), busyNow = useRef(busy); busyNow.current = busy;
// Your voice turn and her spoken answer reach the record only as server rows (subtitles carry no message id).
// Rows still pending on the page are read again until they settle.
const recordSync = useRef({ running: false, again: false, timer: 0 as ReturnType<typeof setTimeout> | 0 });
const reread = useRef(() => {});
reread.current = () => {
const sync = recordSync.current;
if (sync.running) { sync.again = true; return; }
sync.running = true; sync.again = false;
const pending = live.current.filter(m => m.status === 'pending').map(serverId).filter(Boolean);
const since = Math.min(newestId(live.current), ...pending.map(id => id - 1));
recentRows(since, new AbortController().signal).then(rows => { const next = mergeTurns(live.current, rows); if (next) change(next); }, () => { /* The next turn or the inbox read tries again. */ })
.finally(() => { sync.running = false; if (sync.again) reread.current(); });
};
const spoke = useRef(() => {});
// Speaking cancels a text reply still streaming (the server's turn gate already did); it is kept as a cut fragment.
spoke.current = () => { if (busyNow.current) stop(true); };
useEffect(() => {
if (!real) return;
const sync = recordSync.current;
const c = new VoiceController({ transport: loadTransport, onView: setVoiceView, onSpoke: () => spoke.current(), onRecord: () => { clearTimeout(sync.timer); sync.timer = setTimeout(() => reread.current(), 250); } });
voiceCtl.current = c;
const gone = () => c.unload(), offline = () => { if (c.active) void c.end(WORDS.offline); }, online = () => void c.settle();
addEventListener('pagehide', gone); addEventListener('offline', offline); addEventListener('online', online); online();
// Leaving the conversation (nav, Esc, 结束交谈) unmounts this panel: the call ends with it.
return () => { removeEventListener('pagehide', gone); removeEventListener('offline', offline); removeEventListener('online', online); voiceCtl.current = null; void c.end(); };
}, [real]);
// The switch reads the server's honest state once on arrival; it never opens a room or touches the microphone.
useEffect(() => {
if (!real) return;
const c = new AbortController();
voiceStatus(c.signal).then(s => setVoiceOff(s.available ? '' : s.reason), () => {});
return () => c.abort();
}, [real]);
const voiceOn = real ? voiceView.phase !== 'off' : voice;
const voiceLabel = { off: '', opening: '正在接通…', joining: `在等${name}接起…`, listening: '在听你说', thinking: `${name}在想`, speaking: `${name}在说 · 开口就能打断` }[voiceView.phase];
useEffect(() => {
if (!real) return;
onVoice(voiceView.phase !== 'off');
if (voiceView.phase !== 'off') onPresence(voiceLabel);
else if (voiceView.notice) { onPresence('在你面前'); setNotice(voiceView.notice); }
}, [real, voiceView.phase, voiceView.notice, voiceLabel, onVoice, onPresence]);
// ── What the stage shows: the newest turn of the (already privacy-filtered) record, plus the live reply. ──
// Real messages are trimmed by the server before transmission; their lifeIds point at records this page has not
// necessarily loaded, so the demo's local filter would wrongly hide them.
@@ -78,10 +126,10 @@ export function ChatPanel({ state, onChange, onPresence, onVoice, onObservation,
// Her own message that arrives while you are here waits its turn: never while she is answering you, a sheet is
// open, you paused or went back, or the line on screen has not had its time. Then it comes in as a new turn.
const waiting = useRef({ count: 0, busy: false, sheet: false }), admit = useRef(() => {});
waiting.current = { count: incoming.length, busy, sheet: log || full };
waiting.current = { count: incoming.length, busy: busy || voiceView.phase === 'thinking' || voiceView.phase === 'speaking', sheet: log || full };
admit.current = () => { const add = incoming.filter(m => !live.current.some(k => k.id === m.id)); onAdmit?.(incoming.map(m => m.id)); if (add.length) change([...live.current, ...add]); };
function stop() { gate.current.cancel(); if (replyLive.current) setInterrupted({ text: replyLive.current, turn: turnLive.current }); replyLive.current = ''; setBusy(false); setReply(''); onPresence('停下来了'); change(live.current.map(m => m.status === 'pending' ? { ...m, status: 'cancelled' } : m)); }
function stop(quiet = false) { gate.current.cancel(); if (replyLive.current) setInterrupted({ text: replyLive.current, turn: turnLive.current }); replyLive.current = ''; setBusy(false); setReply(''); if (!quiet) onPresence('停下来了'); change(live.current.map(m => m.status === 'pending' ? { ...m, status: 'cancelled' } : m)); }
function endVoice() { stop(); voiceController.current?.abort(); setVoice(false); onVoice(false); onPresence('在你面前'); }
useEffect(() => { const current = gate.current; return () => { current.cancel(); if (real) onChange(live.current.map(m => m.status === 'pending' ? { ...m, status: 'cancelled' } : m)); voiceController.current?.abort(); onVoice(false); onObservation(''); }; }, [onVoice, onObservation, onChange, real]);
useEffect(() => { try { sessionStorage.setItem(draftKey, draft); } catch { /* Draft remains in memory. */ } }, [draft, draftKey]);
@@ -184,6 +232,8 @@ export function ChatPanel({ state, onChange, onPresence, onVoice, onObservation,
if (!retry && real) retry = [...live.current].reverse().find(m => m.role === 'user' && m.status === 'failed' && m.text === draft.trim());
const text = retry?.text || draft.trim(); if (!text || offline) return;
stop();
// Typing over her spoken answer: the server cancels that voice turn; what is left of its audio stays silent.
voiceCtl.current?.hush();
const turnId = retry?.turnId || newId(), signal = gate.current.begin(turnId);
const msg: Message = { id: retry?.id || newId(), role: 'user', text, lifeIds: [], turnId, status: 'pending' };
sentTurn.current = turnId;
@@ -207,12 +257,26 @@ export function ChatPanel({ state, onChange, onPresence, onVoice, onObservation,
replyLive.current = ''; setInterrupted(null); setReply('');
if (real) setDraft(current => current === text ? '' : current);
setBusy(false);
onPresence(voice ? '在听你说(模拟)' : '在你面前');
onPresence(real ? (voiceCtl.current?.active ? '在听你说' : '在你面前') : voice ? '在听你说(模拟)' : '在你面前');
}
}, fail);
}
catch (e) {
if (signal.aborted) return;
// A stream that ends without its final is not always a broken connection: a newer turn (your voice, or
// another page) takes the server's turn gate and cancels this one. The server's record says which.
if (real) {
const row = await recentRows(0, new AbortController().signal, 1).then(rows => rows.find(m => m.role === 'user' && m.turnId === turnId), () => undefined);
if (signal.aborted) return;
if (row?.status === 'cancelled') {
gate.current.cancel();
if (replyLive.current) setInterrupted({ text: replyLive.current, turn: turnId });
replyLive.current = ''; setReply(''); setBusy(false);
change(live.current.map(m => m.id === msg.id ? { ...m, status: 'cancelled' } : m));
if (!voiceCtl.current?.active) onPresence('在你面前');
return;
}
}
change(live.current.map(m => m.id === msg.id ? { ...m, status: 'failed' } : m));
setBusy(false);
if (replyLive.current) setInterrupted({ text: replyLive.current, turn: turnId });
@@ -222,7 +286,17 @@ export function ChatPanel({ state, onChange, onPresence, onVoice, onObservation,
onPresence('在你面前');
}
}
const setVoiceMode = () => { if (real) { setNotice('语音尚未接通,文字仍可使用。'); return; } if (voice) { endVoice(); return; } setPermission('mic'); };
const setVoiceMode = () => {
if (real) {
const c = voiceCtl.current; if (!c) return;
if (c.active) { void c.end(); setNotice('语音已结束,麦克风已关闭。'); return; }
// Ask the server again: its state may have changed since the page opened (no room, no microphone yet).
setNotice('');
voiceStatus(AbortSignal.timeout(8000)).then(s => { setVoiceOff(s.available ? '' : s.reason); if (s.available) { setDenied(false); setPermission('mic'); } else setNotice(s.reason); }, () => setNotice(WORDS.unknown));
return;
}
if (voice) { endVoice(); return; } setPermission('mic');
};
const lastUser = [...view.messages].reverse().find(m => m.role === 'user');
// Only says why her new words wait when it is your own reading that holds them; otherwise they simply come in.
const queued = incoming.length && !busy ? (!flow ? `${name}刚又说了一句 · 继续后呈现` : !atEnd ? `${name}刚又说了一句 · 读完这段呈现` : '') : '';
@@ -239,7 +313,14 @@ export function ChatPanel({ state, onChange, onPresence, onVoice, onObservation,
useLayoutEffect(() => { conversation.current?.toggleAttribute('inert', log || full); }, [log, full]);
return <><section ref={conversation} className={`conversation ${single ? 'single-page' : ''} ${flow ? '' : 'reading-paused'} ${holding && flow ? 'reading-held' : ''}`} aria-label="当前对话">
{voice && <div className="voice-row"><span className="voice-wave" aria-hidden="true"><i/><i/><i/><i/></span><span>{busy ? '她在想(模拟)' : '在听你说(模拟,无收音)'}</span><button onClick={() => { stop(); setNotice(fail ? '刚才没听清,你再说一遍?(模拟识别失败)' : '她停下来了,在等你。'); }}>打断她</button><button onClick={endVoice}>结束语音</button></div>}
{real && voiceOn && <div className="voice-row real" data-phase={voiceView.phase} role="status" aria-live="polite">
<span className="voice-wave" aria-hidden="true"><i/><i/><i/><i/></span>
<span className="voice-state">{voiceLabel}</span>
{voiceView.spoken ? <span className="voice-heard said" title={voiceView.spoken}>{name}:{voiceView.spoken}<em>未记入聊天</em></span> : voiceView.heard && <span className="voice-heard" title={voiceView.heard}>「{voiceView.heard}」</span>}
{voiceView.blocked && <button onClick={() => void voiceCtl.current?.resumeAudio()}>点一下听{name}的声音</button>}
<button className="voice-end" onClick={() => { void voiceCtl.current?.end(); setNotice('语音已结束,麦克风已关闭。'); }}>结束语音</button>
</div>}
{!real && voice && <div className="voice-row"><span className="voice-wave" aria-hidden="true"><i/><i/><i/><i/></span><span>{busy ? '她在想(模拟)' : '在听你说(模拟,无收音)'}</span><button onClick={() => { stop(); setNotice(fail ? '刚才没听清,你再说一遍?(模拟识别失败)' : '她停下来了,在等你。'); }}>打断她</button><button onClick={endVoice}>结束语音</button></div>}
<div className="stage" ref={stageRef} aria-hidden="true" onPointerEnter={e => { if (e.pointerType === 'mouse') hold('hover', true); }} onPointerLeave={() => hold('hover', false)}/>
<p className="sr" aria-live="polite" aria-atomic="true">{page ? `${page.message.role === 'user' ? '你' : name}:${page.text}` : ''}</p>
{status && <div className="talk-status" role="status"><span>{status}</span>{lastUser?.status === 'failed' && !busy && <button className="retry" onClick={() => void send(lastUser)}>重试</button>}</div>}
@@ -249,20 +330,21 @@ export function ChatPanel({ state, onChange, onPresence, onVoice, onObservation,
<span className="count" aria-label={pages.length ? `第 ${cursor + 1} 句,共 ${pages.length} 句${busy ? ',还在说' : ''}` : '还没有对话'}><span>{pages.length ? `${cursor + 1} / ${pages.length}${busy ? '…' : ''}` : '0 / 0'}</span><i ref={meter}/></span>
<button className="icon" aria-label="下一句" disabled={atEnd} onClick={() => forward()}><Icon name="next"/></button>
<button className="read-all" ref={fullButton} disabled={!page} onClick={() => setFull(true)}>全文</button>
{busy && <button className="stop" onClick={stop}>停止回复</button>}
{busy && <button className="stop" onClick={() => stop()}>停止回复</button>}
{!flow && cursor < cursorAt(pages, head.current) && <button className="latest" onClick={toLatest}><Icon name="down"/><span>{unread > 0 ? `回到读到的地方 · 后面还有 ${unread} 句` : '回到读到的地方'}</span></button>}
</div>
<div className="composer"><button className={`round log-btn ${log ? 'on' : ''}`} ref={historyButton} aria-label="完整记录" aria-expanded={log} onClick={() => setLog(!log)}><Icon name="lines"/></button>
<textarea ref={textarea} aria-label="想和她说的话" rows={1} maxLength={4000} value={draft} placeholder="想和她说点什么…" onFocus={() => typing(true)} onBlur={() => typing(false)} onChange={e => setDraft(e.target.value)} onKeyDown={e => { if (e.key === 'Enter' && !e.shiftKey && !e.nativeEvent.isComposing && e.keyCode !== 229) { e.preventDefault(); void send(); } }}/>
<button className={`round cam ${vision ? 'on' : ''}`} aria-label={real ? '视觉观察尚未接通' : '视觉观察(模拟)'} onClick={() => { if (real) { setNotice('视觉尚未接通,不采集影像。'); return; } if (vision) { setVision(false); onObservation('窗户关上了'); } else setPermission('vision'); }}><Icon name="eye"/></button>
<button className="round send" disabled={!draft.trim() || offline} aria-label="发送" onClick={() => void send()}><Icon name="up"/></button>
<button className={`voice-button ${denied ? 'denied' : ''}`} aria-label={real ? '语音尚未接通' : voice ? '停止语音' : '开始模拟语音'} disabled={offline} onClick={setVoiceMode}><Icon name={voice ? 'stop' : 'mic'}/></button>
<button className={`voice-button ${denied || (real && voiceOff && !voiceOn) ? 'denied' : ''} ${real && voiceOn ? 'on' : ''}`} aria-label={real ? voiceOn ? '结束语音' : voiceOff ? `语音不可用:${voiceOff}` : '开始语音' : voice ? '停止语音' : '开始模拟语音'} aria-pressed={real ? voiceOn : undefined} disabled={offline} onClick={setVoiceMode}><Icon name={voiceOn ? 'stop' : 'mic'}/></button>
</div>
</section>
<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>}</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>}
{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>}
{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>}
</>;
}