import { newId } from '../domain/id'; import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react'; import type { DemoState, Message } from '../domain/model'; import { RealChatAdapter } from '../adapters/real'; import { confirmReceipt, receiptMatches } from '../adapters/receipt'; import { DemoAdapter, TurnGate } from '../adapters/demo'; import { publicView } from '../domain/privacy'; import { Icon, Modal } from '../shared/ui'; 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, voiceLine, 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 }; }; const typingTarget = (el: Element | null) => !!el && (el.matches('textarea,input,select,[contenteditable="true"]')); const NO_IDS: string[] = [], NO_MESSAGES: Message[] = []; // Marks "your next turn is one you said by voice" until its row is read back and its turn key is known. const SPOKEN = '\u0000spoken'; export function ChatPanel({ state, onChange, onPresence, onVoice, onObservation, onRecord, offline, fail, log, setLog, focusLife, focusIds = NO_IDS, real = false, onReceipt, incoming = NO_MESSAGES, onAdmit }: { real?: boolean; // Real only: the server accepted a complete-receipt confirmation (the life it may unlock is decided later). onReceipt?: () => void; // Real only: her own messages that reached the open page while you are here, not yet on the stage. incoming?: Message[]; onAdmit?: (ids: string[]) => void; state: DemoState; onChange: (messages: Message[]) => void; onPresence: (p: string) => void; onVoice: (v: boolean) => void; onObservation: (s: string) => void; // A reading sheet (full text or the whole record) is open: she stays across the table, the room dims a little. onRecord: (open: boolean) => void; offline: boolean; fail: boolean; log: boolean; setLog: (b: boolean) => void; focusLife: string; // Real only: exact message ids to open the record at (a memory's server-given sources), apart from life ids. focusIds?: string[]; }) { const draftKey = real ? 'cg.real.draft' : 'cg.draft', readKey = real ? 'cg.real.reading' : 'cg.reading'; const [draft, setDraft] = useState(() => { try { return sessionStorage.getItem(draftKey) || ''; } catch { return ''; } }), [reply, setReply] = useState(''), [busy, setBusy] = useState(false), [voice, setVoice] = useState(false), [permission, setPermission] = useState<'' | 'mic' | 'vision'>(''), [notice, setNotice] = useState(''), [flash, setFlash] = useState(''), [denied, setDenied] = useState(false), [vision, setVision] = useState(false); const gate = useRef(new TurnGate()), adapter = useRef(real ? new RealChatAdapter(epoch => { gate.current.epoch = epoch; }) : new DemoAdapter()), live = useRef(state.messages), logRef = useRef(null), voiceController = useRef(null); const [activeTurn, setActiveTurn] = useState(''), [interrupted, setInterrupted] = useState<{ text: string; turn: string } | null>(null); const replyLive = useRef(''), turnLive = useRef(''), sentTurn = useRef(''); live.current = state.messages; 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(OFF), [voiceOff, setVoiceOff] = useState(''); const voiceCtl = useRef(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 | 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. // Like sending, it starts a new turn that comes in by itself, even if you had paused reading. spoke.current = () => { if (busyNow.current) stop(true); sentTurn.current = SPOKEN; if (!flow) setFlash('新的一轮会自动呈现,随时可以暂停'); }; 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. const view = useMemo(() => real ? state : publicView(state), [state, real]); // What she says by voice takes the place her text reply would take (HEL-898). It is shown, never stored: once the // record holds it (same turn, or the same stored reach-out as the newest line) the row takes over under the same // line keys; a finished line also gives way as soon as anything else comes into the record after it. const her = real ? voiceView.her : null, herBase = useRef({ speech: '', at: 0 }); if (her && herBase.current.speech !== her.speech) herBase.current = { speech: her.speech, at: view.messages.length }; const herLine = useMemo(() => reply ? null : voiceLine(her, view.messages, herBase.current.at, incoming), [her, reply, view.messages, incoming]); const herOpen = !!herLine && her?.state === 'open', talking = busy || herOpen; // The cut-off part of a stopped reply stays with its own turn (it is shown, never stored). const shown = useMemo(() => { const list: ShownMessage[] = [...view.messages]; if (reply) list.push({ id: 'live-reply', role: 'companion', text: reply, lifeIds: [], turnId: activeTurn, live: 'generating' }); else { if (interrupted) { const at = list.map(m => m.turnId).lastIndexOf(interrupted.turn); list.splice(at < 0 ? list.length : at + 1, 0, { id: 'cut-reply', role: 'companion', text: interrupted.text, lifeIds: [], turnId: interrupted.turn, live: 'cancelled' }); } if (herLine) list.push(herLine); } return list; }, [view.messages, reply, activeTurn, interrupted, herLine]); const turn = useMemo(() => groupTurns(shown).at(-1), [shown]), opener = useRef(''); opener.current = turn?.items[0]?.role || ''; const stageRef = useRef(null), lines = useRef(null), meter = useRef(null); const [metrics, setMetrics] = useState(() => metricsFor(Math.min(900, innerWidth * .88))); const pages = useMemo(() => pagesOf(turn, metrics), [turn, metrics]); // Reading position is kept as a place in the text (not a line number), so re-chunking never loses it. const restored = useRef<{ turn: string; anchor: Anchor; flow: boolean } | null>((() => { try { return JSON.parse(sessionStorage.getItem(readKey) || 'null'); } catch { return null; } })()); const resume = restored.current && turn && restored.current.turn === turn.key ? restored.current : null; const [anchor, setAnchor] = useState(resume?.anchor || START), [flow, setFlowState] = useState(resume ? resume.flow : true), [full, setFull] = useState(false); const head = useRef(resume?.anchor || START), how = useRef('jump'), turnKey = useRef(turn?.key || ''); const cursor = cursorAt(pages, anchor), page = pages[cursor], atEnd = cursor >= pages.length - 1; const headIndex = cursorAt(pages, head.current); if (cursor > headIndex) head.current = anchor; const held = useRef(new Set()), clock = useRef(new ReadingClock()); const reading = useRef({ pages, cursor, flow }); reading.current = { pages, cursor, flow }; // 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: talking || 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(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]); useEffect(() => { try { if (turn) sessionStorage.setItem(readKey, JSON.stringify({ turn: turn.key, anchor, flow })); } catch { /* Position remains in memory. */ } }, [turn, anchor, flow, readKey]); useEffect(() => { if (offline) { gate.current.resync(); setBusy(false); setReply(''); setVoice(false); onVoice(false); voiceController.current?.abort(); } }, [offline, onVoice]); useEffect(() => { if (!vision) return; onObservation('模拟 · 刚刚看到,未采集影像'); const t = setTimeout(() => onObservation('模拟 · 已过期,不再当作眼前'), 30000); return () => clearTimeout(t); }, [vision, onObservation]); useEffect(() => { if (!flash) return; const t = setTimeout(() => setFlash(''), 2600); return () => clearTimeout(t); }, [flash]); useEffect(() => { onRecord(log || full); }, [log, full, onRecord]); useEffect(() => () => onRecord(false), [onRecord]); useEffect(() => { if (log) { const el = focusLife ? logRef.current?.querySelector(`[data-life~="${CSS.escape(focusLife)}"]`) : focusIds.length ? logRef.current?.querySelector(`[data-mid="${CSS.escape(focusIds[0])}"]`) : null; if (el) el.scrollIntoView({ block: 'center' }); else if (logRef.current) logRef.current.scrollTop = logRef.current.scrollHeight; } }, [log, focusLife, focusIds, view.messages.length]); // ── Stage ── useLayoutEffect(() => { if (stageRef.current) lines.current = new LineStage(stageRef.current); return () => { lines.current = null; }; }, []); useLayoutEffect(() => { const el = stageRef.current; if (!el) return; const measure = () => setMetrics(m => { const next = metricsFor(el.clientWidth || m.width); if (next.width === m.width && next.font === m.font && next.compact === m.compact) return m; how.current = 'jump'; return next; }); const ro = new ResizeObserver(measure), vv = window.visualViewport; ro.observe(el); addEventListener('resize', measure); vv?.addEventListener('resize', measure); measure(); return () => { ro.disconnect(); removeEventListener('resize', measure); vv?.removeEventListener('resize', measure); }; }, []); // A new turn (you sent something, or she spoke on her own) starts at its first line. useLayoutEffect(() => { const key = turn?.key || ''; if (key === turnKey.current) return; turnKey.current = key; how.current = 'jump'; head.current = START; setAnchor(START); // Your own new turn (sent, or said by voice: its server turn id is only known once the row is read back). if (key && (key === sentTurn.current || (sentTurn.current === SPOKEN && opener.current === 'user'))) { sentTurn.current = key; setFlowState(true); } }, [turn?.key]); // 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('|'); useLayoutEffect(() => { lines.current?.present(pages, cursor, how.current, name, !motionOff()); how.current = 'advance'; // eslint-disable-next-line react-hooks/exhaustive-deps -- re-present only when the visible lines change }, [signature, cursor]); useLayoutEffect(() => { if (!page) return; const mine = page.message, cancelled = mine.live === 'cancelled' || (mine.status === 'cancelled' && mine.role === 'companion'); const text = cancelled && page.last ? '未完成 · 已取消' : mine.role === 'user' && mine.status === 'failed' ? '没发出去' : mine.role === 'user' && mine.status === 'cancelled' && atEnd ? '本轮已取消' : atEnd && talking && mine.role === 'companion' ? '还在说' : ''; lines.current?.mark({ text, waiting: atEnd && talking && mine.role === 'companion' }); }); useEffect(() => { lines.current?.rename(name); }, [name]); // ── Reading clock. Holds (hover, selection, open sheets, hidden page) freeze it without changing your choice. ── useEffect(() => { let raf = 0; const c = clock.current, away = () => c.pause(); const tick = (now: number) => { const { pages: list, cursor: at, flow: on } = reading.current, w = waiting.current; const running = on && !held.current.size && !document.hidden, done = c.tick(now, list[at], running); if (done && at < list.length - 1) { how.current = 'advance'; setAnchor(anchorOf(list, at + 1) || START); } else if (w.count && !w.busy && !w.sheet && running && at >= list.length - 1 && (done || !list.length)) { w.count = 0; admit.current(); } if (meter.current) meter.current.style.transform = `scaleX(${c.progress})`; raf = requestAnimationFrame(tick); }; raf = requestAnimationFrame(tick); document.addEventListener('visibilitychange', away); return () => { cancelAnimationFrame(raf); document.removeEventListener('visibilitychange', away); }; }, []); const [holding, setHolding] = useState(false); const hold = useCallback((why: string, on: boolean) => { if (on) held.current.add(why); else held.current.delete(why); setHolding(held.current.size > 0); }, []); useEffect(() => { hold('sheet', log || full); }, [log, full, hold]); useEffect(() => { const selection = () => { const s = getSelection(); hold('select', !!(s && String(s).length && stageRef.current?.contains(s.anchorNode))); }; document.addEventListener('selectionchange', selection); return () => document.removeEventListener('selectionchange', selection); }, [hold]); const goTo = (index: number, mode: PresentHow) => { const to = Math.max(0, Math.min(index, pages.length - 1)); if (to === cursor) return; how.current = mode; clock.current.forget(); setAnchor(anchorOf(pages, to) || START); }; const setFlow = (on: boolean, quiet = false) => { setFlowState(on); clock.current.restart(); if (!quiet) setFlash(on ? '继续自动呈现' : '已暂停 · 可以慢慢回看'); }; const back = (instant = false) => { if (flow) setFlow(false, true); goTo(cursor - 1, instant ? 'instant' : 'jump'); }; const forward = (instant = false) => goTo(cursor + 1, instant ? 'instant' : 'advance'); const toLatest = () => { how.current = 'jump'; setAnchor(head.current); setFlow(true, true); }; // Keyboard review lands at once (no slide, no replayed ink). Sheets and dialogs own their keys. const keys = useRef({ back, forward, toggle: () => setFlow(!flow) }); keys.current = { back, forward, toggle: () => setFlow(!flow) }; useEffect(() => { const key = (e: KeyboardEvent) => { if (e.defaultPrevented || e.altKey || e.ctrlKey || e.metaKey || typingTarget(document.activeElement) || document.querySelector('.modal.open') || document.documentElement.dataset.mode !== 'talk') return; if (e.key === 'ArrowLeft') { snap(); keys.current.back(true); } else if (e.key === 'ArrowRight') { snap(); keys.current.forward(true); } else if (e.key === ' ' && (document.activeElement === document.body || !document.activeElement)) { e.preventDefault(); keys.current.toggle(); } }; addEventListener('keydown', key); return () => removeEventListener('keydown', key); }, []); // Esc closes the full-text sheet first (one layer at a time) and returns focus to the button that opened it. const fullButton = useRef(null), historyButton = useRef(null), fullClose = useRef(null), logClose = useRef(null); useEffect(() => { if (!full) return; fullClose.current?.focus({ preventScroll: true }); const key = (e: KeyboardEvent) => { if (e.key !== 'Escape' || document.querySelector('.modal.open')) return; e.stopImmediatePropagation(); e.preventDefault(); setFull(false); }; document.addEventListener('keydown', key, true); return () => { document.removeEventListener('keydown', key, true); const back = fullButton.current; if (back && !back.closest('[inert]')) back.focus({ preventScroll: true }); }; }, [full]); const logWasOpen = useRef(log); useEffect(() => { if (log) logClose.current?.focus({ preventScroll: true }); else if (logWasOpen.current && document.activeElement && (document.activeElement === document.body || document.activeElement.closest('.record'))) historyButton.current?.focus({ preventScroll: true }); logWasOpen.current = log; }, [log]); async function send(retry?: Message) { 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; change(retry ? live.current.map(m => m.id === retry.id ? msg : m) : [...live.current, msg]); if (!retry) setDraft(''); setActiveTurn(turnId); turnLive.current = turnId; setBusy(true); onPresence('在想'); setNotice(''); if (!flow) setFlash('新的一轮会自动呈现,随时可以暂停'); try { await adapter.current.send(text, turnId, gate.current.epoch, signal, event => { if (!gate.current.accepts(event)) return; if (event.t === 'chat.delta') { replyLive.current += event.delta; setInterrupted(null); setReply(replyLive.current); onPresence('在说话'); } else if (event.t === 'chat.final') { // Receipt only for this gated, un-aborted, fully parsed final whose own text hashes to receipt.text_hash. const said = event.utterance.text, receipt = real && !signal.aborted && receiptMatches(event.receipt, turnId, said) ? event.receipt : null; // With a receipt the reply carries its server id, so a replayed turn replaces rather than duplicates it // and life records can point back at it. const replyId = receipt ? String(receipt.message_id) : newId(); change([...live.current.filter(m => m.id !== replyId).map(m => m.id === msg.id ? { ...m, status: 'sent' as const } : m), { id: replyId, role: 'companion', text: said, lifeIds: [], turnId }]); // The full text is kept above; only now is receipt confirmed. accepted means received, not published. if (receipt) void confirmReceipt(receipt, turnId, said).then(outcome => { if (outcome === 'accepted') onReceipt?.(); }); replyLive.current = ''; setInterrupted(null); setReply(''); if (real) setDraft(current => current === text ? '' : current); setBusy(false); 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 }); replyLive.current = ''; setReply(''); setDraft(text); setNotice(real && (e instanceof TypeError || e instanceof SyntaxError) ? '连接中断了,你写的话还在,可以重试。' : (e as Error).message); onPresence('在你面前'); } } 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}刚又说了一句 · 读完这段呈现` : '') : ''; const status = notice || flash || (busy ? (reply ? `${name}正在回应…` : `${name}在想…`) : queued || (!pages.length ? '你们还没有说过话。' : real ? '' : '演示回复 · 未连接真实模型')); const unread = pages.length - 1 - cursor, single = pages.length <= 1 && !busy, fullMessage = page?.message; const textarea = useRef(null); useLayoutEffect(() => { const t = textarea.current; if (!t) return; t.style.height = 'auto'; t.style.height = Math.min(t.scrollHeight, 88) + 'px'; }, [draft]); const typing = (on: boolean) => document.documentElement.classList.toggle('typing', on); useEffect(() => () => { document.documentElement.classList.remove('typing'); }, []); const record = shown.filter(m => m !== herLine && (!reply || !m.live)); // While a reading sheet is open the table words are out of reach (the sheet holds them all); layout effect so the // focus hand-back after closing never lands on an inert button. const conversation = useRef(null); useLayoutEffect(() => { conversation.current?.toggleAttribute('inert', log || full); }, [log, full]); return <>
{real && voiceOn &&
{voiceLabel} {voiceView.spoken ? {name}:{voiceView.spoken}未记入聊天 : voiceView.heard && 「{voiceView.heard}」} {voiceView.blocked && }
} {!real && voice &&
{busy ? '她在想(模拟)' : '在听你说(模拟,无收音)'}
}