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
+3 -3
View File
@@ -79,7 +79,7 @@ export function RealApp() {
useEffect(() => { if (fresh && !unread.some(m => m.id === fresh.id)) setFresh(null); }, [fresh, unread]);
// Reply to her: one new message plays on the stage; several open the record at the first one you have not seen.
const openUnread = () => { setFresh(null); const first = unread[0]; leaveSettingsThen(() => { setArea('talk'); setFocusLife(''); setLog(unread.length > 1); setFocusIds(unread.length > 1 && first ? [first.id] : []); }); };
const ignoreVoice = useCallback(() => {}, []);
const ignoreVoice = useCallback(() => {}, []), [voiceOn, setVoiceOn] = useState(false);
// Status words follow the server, re-read when you open a page that shows them; a failed read keeps the last one.
const life = lifeStatus(health);
const refreshHealth = useCallback(() => { api<Health>('health').then(setHealth, () => {}); }, []);
@@ -100,12 +100,12 @@ export function RealApp() {
const lastReply = state ? [...state.messages].reverse().find(m => m.role === 'companion') : undefined;
const talking = area === 'talk' && !!state && !creating;
return <><Presenter real scene={{ mode: area === 'talk' ? 'talk' : 'daily', activity: '文字已接通', time_band: '', weather: '', outfit: '' }} space={space} theme={theme} instant={instant} observation="" now={state && !creating ? life.now : ''} lifeLabel={life.wired ? life.label : undefined} onApproach={() => navigate('talk')}/>
<header className="topbar"><div className="who"><i className="dot"/><span className="name" title={state?.identity.name}>{state?.identity.name || 'CyberGril'}</span>{talking && <span className="presence">{presence}</span>}<span className="state">{ready ? '真实档案 · 文字对话' : '连接真实服务'}</span></div><div className="env"><span className="chip glass weather">天气尚未接通</span><span className="theme-switch glass">{(['moon', 'fog'] as Theme[]).map(t => <button key={t} data-t={t} aria-label={t === 'moon' ? '靛蓝月光' : '蓝紫雾光'} aria-pressed={theme === t} onClick={() => setTheme(t)}><i/><span>{t === 'moon' ? '月光' : '雾光'}</span></button>)}</span>{talking && <button className="end-talk" onClick={() => navigate('now')}><Icon name="x"/><span>结束交谈</span></button>}</div></header>
<header className="topbar"><div className="who"><i className="dot"/><span className="name" title={state?.identity.name}>{state?.identity.name || 'CyberGril'}</span>{talking && <span className="presence">{presence}</span>}<span className="state">{!ready ? '连接真实服务' : talking && voiceOn ? '真实档案 · 语音(未经真机验收)' : '真实档案 · 文字对话'}</span></div><div className="env"><span className="chip glass weather">天气尚未接通</span><span className="theme-switch glass">{(['moon', 'fog'] as Theme[]).map(t => <button key={t} data-t={t} aria-label={t === 'moon' ? '靛蓝月光' : '蓝紫雾光'} aria-pressed={theme === t} onClick={() => setTheme(t)}><i/><span>{t === 'moon' ? '月光' : '雾光'}</span></button>)}</span>{talking && <button className="end-talk" onClick={() => navigate('now')}><Icon name="x"/><span>结束交谈</span></button>}</div></header>
{!ready ? <main className="entry"><div className="card glass"><h1>一扇亮着的窗。</h1><Status text={error || '正在读取服务器档案…'} error={!!error}/>{error && <><p>请检查真实服务是否可达。资料仍在服务器保存。</p><Button primary onClick={() => void initialize()}>重新连接</Button></>}</div></main> : <>
{creating && <CreationWizard real fail={false} onCreate={setState} onEnter={() => setCreating(false)}/>}
{!creating && state && <>
{area === 'now' && <main className="home"><div className="eyebrow">一扇亮着的窗</div><h1 className="whisper">慢慢说,我在这里。</h1><div className="meta"><span><Icon name="heart"/>{state.identity.relation} · 慢慢熟悉</span></div><button className="away" onClick={() => navigate('days')}>日子与回忆 · {life.label} <Icon name="next"/></button>{unread.length ? <button className="letter glass" onClick={openUnread}><span className="lh"><b>她留给你的</b><span>{unread.length > 1 ? `${unread.length} 句还没看` : '还没看'}</span></span><p>{unread[unread.length - 1].text}</p></button> : lastReply && <button className="letter glass read" onClick={() => { navigate('talk'); setLog(true); }}><span className="lh"><b>最近说过的话</b><span>打开完整记录</span></span><p>{lastReply.text}</p></button>}<div className="cta"><Button primary small={false} onClick={() => navigate('talk')}><Icon name="chat"/>和她说话</Button></div><p className="first-note">{memoryNote(health, life)}</p>{health && !health.llm.ok && <Status error text="模型暂时不可达,档案和历史仍可查看。"/>}</main>}
{area === 'talk' && <ChatPanel real state={state} onChange={changeMessages} onPresence={setPresence} onVoice={ignoreVoice} onObservation={ignoreVoice} onRecord={setRecord} offline={false} fail={false} log={log} setLog={setLog} focusLife={focusLife} focusIds={focusIds} onReceipt={acknowledged} incoming={incoming} onAdmit={admitted}/>}
{area === 'talk' && <ChatPanel real state={state} onChange={changeMessages} onPresence={setPresence} onVoice={setVoiceOn} onObservation={ignoreVoice} onRecord={setRecord} offline={false} fail={false} log={log} setLog={setLog} focusLife={focusLife} focusIds={focusIds} onReceipt={acknowledged} incoming={incoming} onAdmit={admitted}/>}
<LifePanel real state={state} open={area === 'days'} now={life.now} life={life} ackAt={ackAt} onClose={() => navigate('now')} onChat={openTold} onSaid={openSaid} onSettings={() => { navigate('settings'); setHerFocus(n => n + 1); }}/>
<ManagePanel real state={state} open={area === 'settings'} now={life.now} life={life} focus={herFocus} onClose={() => navigate('now')} onSave={setState} fail={false} theme={theme} setTheme={setTheme}/>
{/* Same card as the approved demo reach-out, now with her real words; it never opens the conversation by itself. */}
+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>}
</>;
}
+21
View File
@@ -389,6 +389,26 @@ body.offline .composer .send{opacity:.4;pointer-events:none}
.voice-row{display:flex;align-items:center;justify-content:center;gap:12px;font-size:12px;color:var(--text-2);margin-bottom:6px;text-shadow:0 1px 10px var(--pool)}.voice-row button{color:var(--accent);padding:4px 2px}
.voice-wave{display:inline-flex;gap:3px;align-items:center;height:14px}.voice-wave i{width:2px;height:100%;background:var(--accent);border-radius:2px;animation:r-wave 1.1s var(--ease-in-out) infinite}.voice-wave i:nth-child(2){animation-delay:.15s}.voice-wave i:nth-child(3){animation-delay:.3s}.voice-wave i:nth-child(4){animation-delay:.45s}
@keyframes r-wave{50%{transform:scaleY(.3)}}
/* Real voice (HEL-878): one quiet glass line above the stage, same width language as the composer. The wave says who
has the floor without relying on colour alone (the words beside it always name the state): your open-ring colour
while she listens, her lit accent while she speaks, a slow breath while connecting or thinking. */
.voice-row.real{max-width:min(640px,100%);min-height:34px;padding:0 6px 0 14px;border-radius:17px;gap:10px;background:color-mix(in srgb,var(--surface) 34%,transparent);border:1px solid var(--glass-line);-webkit-backdrop-filter:blur(16px);backdrop-filter:blur(16px);animation:voice-in 280ms var(--ease-out) both}
@keyframes voice-in{from{opacity:0;transform:translateY(6px)}}
.voice-row.real .voice-state{white-space:nowrap;color:var(--text-1);letter-spacing:.04em}
.voice-row.real .voice-heard{min-width:0;max-width:24em;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--user);opacity:.82}
.voice-row.real .voice-heard.said{color:var(--text-2)}
.voice-row.real .voice-heard em{font-style:normal;font-size:11px;color:var(--warn);margin-left:8px}
.voice-row.real button{white-space:nowrap;height:28px;padding:0 10px;border-radius:14px;transition:background-color 160ms var(--ease-out)}
.voice-row.real .voice-end{color:var(--text-1);box-shadow:inset 0 0 0 1px var(--glass-line)}
.voice-row.real .voice-wave i{transition:background-color var(--dur-ui) var(--ease-out),opacity var(--dur-ui) var(--ease-out)}
.voice-row[data-phase="opening"] .voice-wave i,.voice-row[data-phase="joining"] .voice-wave i,.voice-row[data-phase="thinking"] .voice-wave i{animation:r-breath 1.4s var(--ease-in-out) infinite;transform:scaleY(.35)}
.voice-row[data-phase="opening"] .voice-wave i,.voice-row[data-phase="joining"] .voice-wave i{background:var(--text-3)}
.voice-row[data-phase="listening"] .voice-wave i{background:var(--user);animation-duration:1.6s;opacity:.85}
.voice-row[data-phase="speaking"] .voice-wave i{box-shadow:0 0 6px var(--accent-glow)}
@keyframes r-breath{50%{opacity:.3}}
.voice-button.on{box-shadow:0 0 0 4px var(--accent-soft),0 0 18px var(--accent-glow)}
.voice-note{display:block;margin-top:10px;color:var(--warn);font-size:12px}
@media(hover:hover) and (pointer:fine){.voice-row.real button:hover{background:#ffffff0d}}
/* 完整记录与全文:房间里的阅读面,她仍在桌对面;不是模态框,导航始终可以直接切换 */
.record{position:fixed;z-index:20;top:calc(var(--view-top) + 84px);left:4vw;width:min(470px,36vw);height:calc(var(--view-h) - 150px - var(--safe-bottom));border-radius:26px;display:flex;flex-direction:column;overflow:hidden;box-shadow:0 25px 100px #02041270,inset 0 1px 0 #ffffff10;animation:sheet-in 240ms var(--ease-out)}
@@ -703,6 +723,7 @@ body.creating .create{opacity:1;pointer-events:auto}
.reader-bar .latest span{max-width:9em;overflow:hidden;text-overflow:ellipsis}
.composer{min-height:48px;padding:0 4px}.composer textarea{font-size:16px}
.composer .round{width:36px;height:36px}
.voice-row.real{width:100%;gap:8px;padding:0 4px 0 12px}.voice-row.real .voice-heard{flex:1;max-width:none}.voice-row.real button{height:34px}
.nav{padding:3px}
.nav-item{width:70px;height:40px}
+95
View File
@@ -0,0 +1,95 @@
// The existing LiveKit browser client (livekit-client 2.22.4, the same UMD build the .12 call page at :8090 serves from
// /static/). It is loaded from this site only when voice is switched on: the text and demo paths never fetch it.
// See web/VENDOR.md for its source and checksum.
import type { MicTrack, RoomEvents, VoiceRoom, VoiceTransport } from './session';
export const LIVEKIT_SRC = '/vendor/livekit-client-2.22.4.umd.min.js';
const SUBTITLES = 'cg.subtitle', AGENT_STATE = 'lk.agent.state';
// The few parts of the client used here (typed locally; the bundle carries no type package).
interface LkTrack { kind: string; mediaStreamTrack: MediaStreamTrack; attach(): HTMLMediaElement; detach(): HTMLMediaElement[]; stop(): void }
interface LkParticipant { identity: string; kind?: number; attributes?: Record<string, string> }
interface LkRoom {
on(event: string, cb: (...args: never[]) => void): LkRoom;
connect(url: string, token: string, options?: { autoSubscribe?: boolean }): Promise<void>;
disconnect(stopTracks?: boolean): Promise<void>;
startAudio(): Promise<void>;
canPlaybackAudio: boolean;
remoteParticipants: Map<string, LkParticipant>;
localParticipant: { publishTrack(track: LkTrack, options?: { source?: string }): Promise<unknown> };
}
export interface Livekit {
Room: new (options?: Record<string, unknown>) => LkRoom;
RoomEvent: Record<'TrackSubscribed' | 'TrackUnsubscribed' | 'ParticipantConnected' | 'ParticipantAttributesChanged' | 'DataReceived' | 'Disconnected' | 'AudioPlaybackStatusChanged', string>;
Track: { Source: { Microphone: string } };
ParticipantKind?: { AGENT?: number };
createLocalAudioTrack(options?: MediaTrackConstraints): Promise<LkTrack>;
}
declare global { interface Window { LivekitClient?: Livekit } }
let loading: Promise<Livekit> | null = null;
export function loadLivekit(src = LIVEKIT_SRC): Promise<Livekit> {
if (window.LivekitClient) return Promise.resolve(window.LivekitClient);
loading ??= new Promise<Livekit>((ok, ko) => {
const script = document.createElement('script');
script.src = src; script.async = true;
script.onload = () => window.LivekitClient ? ok(window.LivekitClient) : ko(new Error('livekit-client missing'));
script.onerror = () => { script.remove(); ko(new Error('livekit-client failed to load')); };
document.head.append(script);
}).catch(e => { loading = null; throw e; });
return loading;
}
const tracks = new WeakMap<MicTrack, LkTrack>();
export function livekitTransport(lk: Livekit): VoiceTransport {
const isAgent = (p: LkParticipant) => (lk.ParticipantKind?.AGENT !== undefined && p.kind === lk.ParticipantKind.AGENT) || AGENT_STATE in (p.attributes || {}) || p.identity.startsWith('agent-');
return {
async capture() {
// Same capture defaults as the :8090 call page: echo cancellation keeps her own voice out of the microphone.
const track = await lk.createLocalAudioTrack({ echoCancellation: true, noiseSuppression: true, autoGainControl: true });
const mic: MicTrack = { stop: () => { track.stop(); track.mediaStreamTrack.stop(); }, onEnded: cb => track.mediaStreamTrack.addEventListener('ended', cb, { once: true }) };
tracks.set(mic, track);
return mic;
},
async join(url, token, on: RoomEvents, signal) {
const room = new lk.Room({ adaptiveStream: true, dynacast: true });
// Her audio lives in one hidden holder; closing empties it, so nothing of an old call can keep playing.
const holder = document.createElement('div'), E = lk.RoomEvent;
holder.hidden = true; holder.dataset.voice = 'her'; document.body.append(holder);
let closing = false, hushed = false;
const players = () => [...holder.querySelectorAll<HTMLMediaElement>('audio,video')];
const close = async () => {
if (closing) return; closing = true;
players().forEach(el => { el.muted = true; el.pause(); el.srcObject = null; });
holder.remove();
await room.disconnect(true).catch(() => {});
};
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.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;
try { on.subtitle(JSON.parse(new TextDecoder().decode(payload))); } catch { /* A broken frame is dropped, never shown. */ }
}) as (...a: never[]) => void);
room.on(E.Disconnected, (() => { if (!closing) { void close(); on.dropped(); } }) as (...a: never[]) => void);
room.on(E.AudioPlaybackStatusChanged, (() => { if (!closing) on.audioBlocked(!room.canPlaybackAudio); }) as (...a: never[]) => void);
const abort = () => void close();
signal.addEventListener('abort', abort, { once: true });
try { await room.connect(url, token, { autoSubscribe: true }); }
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); });
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 }); },
hush(quiet) { hushed = quiet; players().forEach(el => { el.muted = quiet; }); },
resumeAudio: () => room.startAudio(),
close,
};
return voiceRoom;
},
};
}
export const loadTransport = async (): Promise<VoiceTransport> => livekitTransport(await loadLivekit());
+287
View File
@@ -0,0 +1,287 @@
// ── Continuous voice on the approved conversation (R5, HEL-878). ──
// The server opens a room and hands out a short join token (POST /api/voice/session, keys never reach the page); the
// browser joins with the existing LiveKit client and publishes the microphone. Her words are spoken by the dedicated
// worker, which goes through the same /api/chat as text; the page never confirms a receipt for voice (the worker does,
// only after real playout) and never turns subtitles into chat rows: the record is re-read from /api/messages.
//
// One rule holds the whole lifecycle together: every call starts a new generation, and anything that answers for an
// older generation (a late token, a late join, a late microphone, a late room event) is cleaned up, never shown.
import type { Message } from '../domain/model';
import { api, toMessage, within, type MessagePage } from '../adapters/real';
import { serverId } from '../adapters/inbox';
export type VoicePhase = 'off' | 'opening' | 'joining' | 'listening' | 'thinking' | 'speaking';
export interface VoiceView {
phase: VoicePhase;
// What the recogniser heard of you so far (a draft; it is replaced, never stored).
heard: string;
// Her line spoken after a failure (φ): heard, not part of the record.
spoken: string;
// Why voice is off or what went wrong; empty while it simply runs.
notice: string;
// The browser held her audio back until a tap (autoplay rules); `resume` lets it out.
blocked: boolean;
}
export const OFF: VoiceView = { phase: 'off', heard: '', spoken: '', notice: '', blocked: false };
export interface Subtitle { kind: 'interim' | 'user_final' | 'assistant_final' | 'error'; role: 'user' | 'assistant'; text: string }
export function subtitle(v: unknown): Subtitle | null {
const s = v as Record<string, unknown> | null;
if (!s || typeof s !== 'object' || typeof s.text !== 'string' || !['interim', 'user_final', 'assistant_final', 'error'].includes(s.kind as string)) return null;
return { kind: s.kind as Subtitle['kind'], role: s.role === 'assistant' ? 'assistant' : 'user', text: s.text };
}
// ── What the controller needs from a real-time client. livekit.ts implements it with livekit-client; tests use fakes. ──
export interface MicTrack { stop(): void; onEnded(cb: () => void): void }
export interface RoomEvents {
agentJoined(): void;
// The worker's own state attribute (lk.agent.state): initializing / listening / thinking / speaking.
agentState(state: string): void;
subtitle(payload: unknown): void;
// The room went away without us closing it (server ended it, network, kicked).
dropped(): void;
audioBlocked(blocked: boolean): void;
}
export interface VoiceRoom { publish(mic: MicTrack): Promise<void>; hush(on: boolean): void; resumeAudio(): Promise<void>; close(): Promise<void> }
export interface VoiceTransport { capture(): Promise<MicTrack>; join(url: string, token: string, on: RoomEvents, signal: AbortSignal): Promise<VoiceRoom> }
export interface VoiceAvailability { available: boolean; reason: string }
export interface SessionGrant { url: string; token: string; room: string; session_id: string; epoch: number; expires_at: number }
export const WORDS = {
notConfigured: '语音还没有在这台服务上配置,文字仍可使用。',
ttsDown: '她的声音服务这会儿不在,稍后再试试。文字仍可使用。',
noRoute: '这台服务还没有语音通路,文字仍可使用。',
unknown: '暂时读不到语音状态,文字仍可使用。',
insecure: '这个地址不是安全连接,浏览器不允许使用麦克风。需要从 HTTPS 入口打开。',
denied: '没有拿到麦克风权限,语音没有开始。文字仍可使用。',
noMic: '没有找到可用的麦克风,语音没有开始。',
micBusy: '麦克风被别的程序占用了,语音没有开始。',
client: '语音组件没有加载出来,文字仍可使用。',
unreachable: '通话服务暂时连不上,稍后再试试。',
noAgent: '她没有接上这次通话,麦克风已经关闭。文字仍可使用。',
dropped: '通话断开了,麦克风已经关闭。文字仍可使用。',
micGone: '麦克风被关掉了,语音已结束。',
offline: '网络断开了,语音已结束,麦克风已关闭。',
} as const;
export interface VoiceDeps {
transport: () => Promise<VoiceTransport>;
onView: (view: VoiceView) => void;
// The record may have changed (a voice turn began, ended or was cut): re-read /api/messages.
onRecord: () => void;
// You finished saying something by voice: a text reply still streaming has been cancelled by the server.
onSpoke: () => void;
fetch?: typeof fetch;
// How long the room may wait for her worker to join before giving up honestly.
agentWaitMs?: number;
secure?: () => boolean;
}
interface Live { gen: number; abort: AbortController; mic?: MicTrack; room?: VoiceRoom; session?: string; agent: boolean; stated: boolean; hushed: boolean; timer?: ReturnType<typeof setTimeout> }
const AGENT_PHASE: Record<string, VoicePhase> = { initializing: 'joining', listening: 'listening', thinking: 'thinking', speaking: 'speaking' };
export async function voiceStatus(signal: AbortSignal, f: typeof fetch = fetch): Promise<VoiceAvailability> {
let response: Response;
try { response = await f('/api/voice/status', { signal }); } catch (e) { if (signal.aborted) throw e; return { available: false, reason: WORDS.unknown }; }
// A server from before R5 has no such route: that is "not wired", not a failure.
if (response.status === 404 || response.status === 405) return { available: false, reason: WORDS.noRoute };
const data = await response.json().catch(() => null) as { configured?: unknown; tts_ok?: unknown } | null;
if (!response.ok || !data) return { available: false, reason: WORDS.unknown };
if (data.configured !== true) return { available: false, reason: WORDS.notConfigured };
if (data.tts_ok !== true) return { available: false, reason: WORDS.ttsDown };
return { available: true, reason: '' };
}
function micFailure(e: unknown, secure: boolean) {
const name = (e as { name?: string } | null)?.name || '';
if (!secure) return WORDS.insecure;
if (name === 'NotAllowedError' || name === 'SecurityError' || name === 'PermissionDeniedError') return WORDS.denied;
if (name === 'NotFoundError' || name === 'DevicesNotFoundError' || name === 'OverconstrainedError') return WORDS.noMic;
if (name === 'NotReadableError' || name === 'AbortError') return WORDS.micBusy;
return WORDS.denied;
}
const OWED = 'cg.voice.owed';
function owedSessions(): string[] {
try { const v = JSON.parse(localStorage.getItem(OWED) || '[]'); return Array.isArray(v) ? v.filter((s): s is string => typeof s === 'string' && !!s && s.length < 100) : []; } catch { return []; }
}
export class VoiceController {
private gen = 0;
private live: Live | null = null;
private view: VoiceView = OFF;
private f: typeof fetch;
constructor(private deps: VoiceDeps) { this.f = deps.fetch ?? ((...a) => fetch(...a)); }
get phase() { return this.view.phase; }
get active() { return this.live !== null; }
private show(next: Partial<VoiceView>, gen: number) {
if (gen !== this.gen) return;
this.view = { ...this.view, ...next };
this.deps.onView(this.view);
}
async start(): Promise<void> {
await this.end();
void this.settle();
const gen = ++this.gen, live: Live = { gen, abort: new AbortController(), agent: false, stated: false, hushed: false };
this.live = live;
this.view = { ...OFF, phase: 'opening' }; this.deps.onView(this.view);
const stale = () => gen !== this.gen;
const fail = async (notice: string) => { if (stale()) return; this.live = null; this.gen++; await this.teardown(live); this.view = { ...OFF, notice }; this.deps.onView(this.view); };
const secure = (this.deps.secure ?? (() => window.isSecureContext && !!navigator.mediaDevices?.getUserMedia))();
if (!secure) return fail(WORDS.insecure);
// 1. The honest switch: configured and her voice service reachable (no room, no microphone yet).
let status: VoiceAvailability;
try { status = await voiceStatus(live.abort.signal, this.f); } catch { return; }
if (stale()) return;
if (!status.available) return fail(status.reason);
// 2. The client, then the microphone. A refusal here opens nothing on the server.
let transport: VoiceTransport;
try { transport = await this.deps.transport(); } catch { return fail(WORDS.client); }
if (stale()) return;
let mic: MicTrack;
try { mic = await transport.capture(); } catch (e) { return fail(micFailure(e, true)); }
if (stale()) { mic.stop(); return; }
live.mic = mic;
mic.onEnded(() => { if (!stale()) void fail(WORDS.micGone); });
// 3. A room of her own for this call. This request is not cut short by ending: if it was already under way, its
// answer still owns a room on the server, so it is waited for and given back.
let response: Response, data: (SessionGrant & { detail?: unknown }) | null;
try {
response = await this.f('/api/voice/session', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{}', signal: AbortSignal.timeout(15000) });
data = await response.json().catch(() => null);
} catch { return fail(WORDS.unreachable); }
if (response.ok && typeof data?.session_id === 'string') live.session = data.session_id;
if (stale()) { await this.teardown(live); return; }
if (!response.ok || !data?.token || !data.url || !live.session) return fail(typeof data?.detail === 'string' && data.detail ? data.detail : WORDS.unreachable);
const grant = data;
// 4. Join and speak.
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); },
agentState: state => {
if (stale()) return;
const phase = AGENT_PHASE[state]; if (!phase) return;
live.stated = true;
if (phase !== 'joining' && !live.agent) events.agentJoined();
// After text took over, her old voice stays silent until she is back to listening.
if (live.hushed && phase !== 'speaking') { live.hushed = false; live.room?.hush(false); }
this.show({ phase, ...(phase === 'thinking' ? { spoken: '' } : {}) }, gen);
},
subtitle: payload => {
if (stale()) return;
const s = subtitle(payload); if (!s) return;
if (s.kind === 'interim') { this.show({ heard: s.text, spoken: '', ...(live.stated ? {} : { phase: 'listening' as const }) }, gen); if (live.hushed && !live.stated) { live.hushed = false; live.room?.hush(false); } return; }
if (s.kind === 'user_final') { this.show({ heard: s.text, spoken: '', ...(live.stated ? {} : { phase: 'thinking' as const }) }, gen); this.deps.onSpoke(); this.deps.onRecord(); return; }
if (s.kind === 'assistant_final') { this.show({ heard: '', spoken: '', ...(live.stated ? {} : { phase: 'listening' as const }) }, gen); this.deps.onRecord(); return; }
this.show({ heard: '', spoken: s.text, ...(live.stated ? {} : { phase: 'listening' as const }) }, gen); this.deps.onRecord();
},
dropped: () => { if (!stale()) void fail(WORDS.dropped); },
audioBlocked: blocked => this.show({ blocked }, gen),
};
let room: VoiceRoom;
try { room = await transport.join(grant.url, grant.token, events, live.abort.signal); } catch { return fail(WORDS.unreachable); }
if (stale()) { live.room = room; await this.teardown(live); return; }
live.room = room;
try { await room.publish(mic); } catch { return fail(WORDS.unreachable); }
if (stale()) { await this.teardown(live); return; }
if (!live.agent) live.timer = setTimeout(() => { if (!stale() && !live.agent) void fail(WORDS.noAgent); }, this.deps.agentWaitMs ?? 20000);
}
// Stop everything now: microphone first, then the room and its audio, then the server-side room. Safe to call twice.
async end(notice = ''): Promise<void> {
const live = this.live;
this.gen++; this.live = null;
const was = this.view.phase !== 'off' || this.view.notice !== notice;
this.view = { ...OFF, notice };
if (was) this.deps.onView(this.view);
if (live) { await this.teardown(live); this.deps.onRecord(); }
}
// Page is going away: same order, without waiting; the DELETE survives the unload.
unload() {
const live = this.live;
this.gen++; this.live = null; this.view = OFF;
if (live) void this.teardown(live, true);
}
// You sent text while she was answering by voice: the server cancels her voice turn; keep its last audio silent.
hush() {
const live = this.live;
if (!live?.room || (this.view.phase !== 'speaking' && this.view.phase !== 'thinking')) return;
live.hushed = true; live.room.hush(true);
this.show({ spoken: '' }, live.gen);
}
async resumeAudio() { const live = this.live; if (!live?.room) return; try { await live.room.resumeAudio(); this.show({ blocked: false }, live.gen); } catch { /* Still blocked; the tap stays offered. */ } }
private async teardown(live: Live, keepalive = false) {
live.abort.abort(); clearTimeout(live.timer);
try { live.mic?.stop(); } catch { /* Already stopped. */ }
const room = live.room; live.room = undefined;
const session = live.session; live.session = undefined;
const closing = room ? room.close().catch(() => {}) : Promise.resolve();
// The server deletes the room: her worker leaves and its job ends even if the page could not say goodbye itself.
// A DELETE that could not get through (offline) is kept and sent again when the network is back.
const ending = session ? this.release(session, keepalive) : Promise.resolve();
await Promise.all([closing, ending]);
}
// Kept in this browser (not only in memory), so leaving the conversation or reloading does not forget them. Until
// one gets through, the server side still ends on its own: the worker's job ends when the page's participant is
// gone from the room, and the session registry expires (runbook-hel877-voice §3.4/§3.5).
private owe(session: string, on: boolean) {
const list = new Set(owedSessions());
if (on) list.add(session); else list.delete(session);
try { if (list.size) localStorage.setItem(OWED, JSON.stringify([...list].slice(-20))); else localStorage.removeItem(OWED); } catch { /* Memory only for this visit. */ }
if (on) this.owed.add(session); else this.owed.delete(session);
}
private owed = new Set<string>();
private release(session: string, keepalive = false) {
// Noted before sending: if the page is gone before the answer, the next visit sends it again (404 = done).
this.owe(session, true);
return this.f(`/api/voice/session/${encodeURIComponent(session)}`, { method: 'DELETE', keepalive })
.then(r => { this.owe(session, !(r.ok || r.status === 404)); }, () => { this.owe(session, true); });
}
// Back online, arriving, or starting again: give back rooms an earlier end could not reach the server to delete.
async settle() { await Promise.all([...new Set([...this.owed, ...owedSessions()])].map(s => this.release(s))); }
}
// The record's view of voice: rows of your and her voice turns, re-read from the server. Her reach-outs (proactive)
// are left to the inbox reader so they keep their own entrance; text turns already on the page are matched by turn id.
export function mergeTurns(known: Message[], rows: Message[]): Message[] | null {
const byId = new Map(known.map((m, i) => [m.id, i])), turns = new Set(known.flatMap(m => m.turnId ? [`${m.role}:${m.turnId}`] : []));
let next: Message[] | null = null;
for (const m of [...rows].sort((a, b) => serverId(a) - serverId(b))) {
if (m.proactive || !serverId(m)) continue;
const at = byId.get(m.id);
if (at !== undefined) {
const old = (next ?? known)[at];
if (old.status !== m.status || old.text !== m.text) { next ??= [...known]; next[at] = { ...old, status: m.status, text: m.text }; }
continue;
}
if (m.turnId && turns.has(`${m.role}:${m.turnId}`)) continue;
next ??= [...known]; next.push(m); byId.set(m.id, next.length - 1); if (m.turnId) turns.add(`${m.role}:${m.turnId}`);
}
return next;
}
// Newest rows down to `since` (exclusive), at most `pages` pages of 50. Voice turns are few per read; a longer gap is
// left to the next re-read rather than read without bound.
export async function recentRows(since: number, signal: AbortSignal, pages = 4): Promise<Message[]> {
const rows: Message[] = [];
let before: number | null = null;
for (let i = 0; i < pages; i++) {
const page: MessagePage = await api(`messages?limit=50${before ? `&before=${before}` : ''}`, { signal: within(signal, 10000) });
const list = (Array.isArray(page.messages) ? page.messages : []).filter(m => Number.isSafeInteger(m?.id) && m.id > 0 && typeof m.text === 'string');
rows.push(...list.filter(m => m.id > since).map(toMessage));
if (list.some(m => m.id <= since) || !page.next_before || !Number.isSafeInteger(page.next_before)) break;
before = page.next_before;
}
return rows;
}