HEL-898: preserve director v2 subtitle wiring verbatim on fc905fe
Co-authored-by: multica-agent <github@multica.ai>
This commit is contained in:
+31
-14
@@ -10,7 +10,7 @@ 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 { mergeTurns, OFF, recentRows, VoiceController, voiceLine, voiceStatus, WORDS, type VoiceView } from '../voice/session';
|
||||
import { loadTransport } from '../voice/livekit';
|
||||
import { newestId, serverId } from '../adapters/inbox';
|
||||
|
||||
@@ -19,6 +19,8 @@ const metricsFor = (width: number): Metrics => { const compact = document.docume
|
||||
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).
|
||||
@@ -68,7 +70,8 @@ export function ChatPanel({ state, onChange, onPresence, onVoice, onObservation,
|
||||
};
|
||||
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); };
|
||||
// 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;
|
||||
@@ -99,17 +102,27 @@ export function ChatPanel({ state, onChange, onPresence, onVoice, onObservation,
|
||||
// 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<ShownMessage[]>(() => {
|
||||
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' });
|
||||
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]);
|
||||
const turn = useMemo(() => groupTurns(shown).at(-1), [shown]);
|
||||
}, [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<HTMLDivElement>(null), lines = useRef<LineStage | null>(null), meter = useRef<HTMLElement>(null);
|
||||
const [metrics, setMetrics] = useState<Metrics>(() => metricsFor(Math.min(900, innerWidth * .88)));
|
||||
const pages = useMemo(() => pagesOf(turn, metrics), [turn, metrics]);
|
||||
@@ -126,7 +139,7 @@ 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: busy || voiceView.phase === 'thinking' || voiceView.phase === 'speaking', sheet: log || full };
|
||||
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)); }
|
||||
@@ -154,8 +167,12 @@ export function ChatPanel({ state, onChange, onPresence, onVoice, onObservation,
|
||||
const key = turn?.key || '';
|
||||
if (key === turnKey.current) return;
|
||||
turnKey.current = key; how.current = 'jump'; head.current = START; setAnchor(START);
|
||||
if (key && key === sentTurn.current) setFlowState(true);
|
||||
// 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());
|
||||
@@ -165,8 +182,8 @@ export function ChatPanel({ state, onChange, onPresence, onVoice, onObservation,
|
||||
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 && busy && mine.role === 'companion' ? '还在说' : '';
|
||||
lines.current?.mark({ text, waiting: atEnd && busy && 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]);
|
||||
|
||||
@@ -306,7 +323,7 @@ export function ChatPanel({ state, onChange, onPresence, onVoice, onObservation,
|
||||
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 = reply ? shown.filter(m => !m.live) : shown;
|
||||
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<HTMLElement>(null);
|
||||
@@ -327,7 +344,7 @@ export function ChatPanel({ state, onChange, onPresence, onVoice, onObservation,
|
||||
<div className="reader-bar">
|
||||
<button className="flow" aria-pressed={flow} onClick={() => setFlow(!flow)}><Icon name={flow ? 'pause' : 'play'}/><span>{flow ? '暂停' : '继续'}</span></button>
|
||||
<button className="icon" aria-label="上一句" disabled={cursor <= 0} onClick={() => back()}><Icon name="back"/></button>
|
||||
<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>
|
||||
<span className="count" aria-label={pages.length ? `第 ${cursor + 1} 句,共 ${pages.length} 句${talking ? ',还在说' : ''}` : '还没有对话'}><span>{pages.length ? `${cursor + 1} / ${pages.length}${talking ? '…' : ''}` : '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>}
|
||||
@@ -341,7 +358,7 @@ export function ChatPanel({ state, onChange, onPresence, onVoice, onObservation,
|
||||
</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>
|
||||
<div className="scroll" ref={logRef}><p className="guide">内容完整保留;关闭后回到刚才那一句,自动呈现会接着走。</p>{record.map(m => <article key={m.id} data-life={m.lifeIds.join(' ') || undefined} data-mid={m.id} data-role={m.role} className={`message ${m.status === 'failed' ? 'fail' : ''} ${(focusLife && m.lifeIds.includes(focusLife)) || focusIds.includes(m.id) ? 'hl' : ''}`}><div className="author"><i/>{m.role === 'user' ? '你' : name}{m.proactive && <span className="tagm">她主动说的</span>}</div><p>{m.text}</p>{m.status === 'failed' && <button className="btn-text" onClick={() => void send(m)}>没发出去 · 重试</button>}{m.status === 'cancelled' && <span className="incomplete">已取消</span>}{m.live === 'cancelled' && <span className="incomplete">已停止 · 这是未完成片段,未存入聊天记录</span>}</article>)}{reply && <article className="message" data-role="companion"><div className="author"><i/>{name}</div><p>{reply}</p><span className="incomplete">还在说…</span></article>}{herLine && !herLine.proactive && <article className="message" data-role="companion"><div className="author"><i/>{name}</div><p>{herLine.text}</p><span className="incomplete">{herOpen ? '还在说…' : '语音刚说完 · 正在读回聊天记录'}</span></article>}</div></aside>
|
||||
{full && fullMessage && <aside className="record full glass read" role="dialog" aria-modal="false" aria-labelledby="full-title"><header><div><p className="eyebrow">{fullMessage.role === 'user' ? '你' : name} · 全文</p><h2 id="full-title">这一段,慢慢看</h2></div><button className="btn-round sm" ref={fullClose} aria-label="关闭全文" onClick={() => setFull(false)}><Icon name="x"/></button></header>
|
||||
<div className="scroll"><p className="guide">整段完整可读。关闭后回到刚才那一句。</p><article className="message" data-role={fullMessage.role}><div className="author"><i/>{fullMessage.role === 'user' ? '你' : name}</div><p>{fullMessage.text}</p>{fullMessage.live === 'generating' && <span className="incomplete">还在说…</span>}{fullMessage.live === 'cancelled' && <span className="incomplete">这段回复已停止,内容未完成,未存入聊天记录。</span>}</article></div></aside>}
|
||||
{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>}
|
||||
|
||||
+116
-13
@@ -7,6 +7,7 @@
|
||||
// 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 type { ShownMessage } from '../chat/reading';
|
||||
import { api, toMessage, within, type MessagePage } from '../adapters/real';
|
||||
import { serverId } from '../adapters/inbox';
|
||||
|
||||
@@ -17,17 +18,38 @@ export interface VoiceView {
|
||||
heard: string;
|
||||
// Her line spoken after a failure (φ): heard, not part of the record.
|
||||
spoken: string;
|
||||
// What she is saying right now, shown on the stage where her text replies appear; never stored by the page.
|
||||
her: HerLine | null;
|
||||
// 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 }
|
||||
// One "she speaks" (an SDK speech): her reply to your voice turn, or a stored reach-out read aloud. `open` grows by
|
||||
// replacement (each interim is the whole text so far); `final` is the stored reply's exact text; `done` is closed and
|
||||
// stays only until the record (or the next turn) takes its place.
|
||||
export interface HerLine { speech: string; text: string; state: 'open' | 'final' | 'done'; turnId?: string; messageId?: number; proactive?: boolean }
|
||||
export const OFF: VoiceView = { phase: 'off', heard: '', spoken: '', her: null, notice: '', blocked: false };
|
||||
|
||||
// ── cg.subtitle contract v2 (docs/voice-subtitle-contract-v2.md). Anything that is not exactly v2 is dropped. ──
|
||||
const USER_KINDS = ['interim', 'user_final'] as const;
|
||||
const HER_KINDS = ['turn_start', 'assistant_interim', 'assistant_final', 'turn_end', 'turn_cancel', 'error', 'proactive_start', 'proactive_end', 'proactive_cancel'] as const;
|
||||
export type SubtitleKind = typeof USER_KINDS[number] | typeof HER_KINDS[number];
|
||||
export interface Subtitle { seq: number; kind: SubtitleKind; role: 'user' | 'assistant'; text: string; speech: string; turnId?: string; messageId?: number; reason?: string }
|
||||
const id = (v: unknown) => typeof v === 'string' && v.length > 0 && v.length <= 200 ? v : '';
|
||||
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 };
|
||||
if (!s || typeof s !== 'object' || Array.isArray(s) || s.v !== 2 || !Number.isSafeInteger(s.seq) || (s.seq as number) <= 0 || typeof s.text !== 'string') return null;
|
||||
const kind = s.kind as SubtitleKind, user = (USER_KINDS as readonly string[]).includes(kind);
|
||||
if (!user && !(HER_KINDS as readonly string[]).includes(kind)) return null;
|
||||
if (s.role !== (user ? 'user' : 'assistant')) return null;
|
||||
const out: Subtitle = { seq: s.seq as number, kind, role: user ? 'user' : 'assistant', text: s.text, speech: user ? '' : id(s.speech_id) };
|
||||
if (!user && !out.speech) return null;
|
||||
if (s.turn_id !== undefined && s.turn_id !== null) { if (!id(s.turn_id)) return null; out.turnId = s.turn_id as string; }
|
||||
if (kind === 'assistant_final' && !out.turnId) return null;
|
||||
if (kind.startsWith('proactive_')) { if (!Number.isSafeInteger(s.message_id) || (s.message_id as number) <= 0) return null; out.messageId = s.message_id as number; }
|
||||
if (typeof s.reason === 'string') out.reason = s.reason;
|
||||
return out;
|
||||
}
|
||||
|
||||
// ── What the controller needs from a real-time client. livekit.ts implements it with livekit-client; tests use fakes. ──
|
||||
@@ -77,7 +99,10 @@ export interface VoiceDeps {
|
||||
secure?: () => boolean;
|
||||
}
|
||||
|
||||
interface Live { gen: number; abort: AbortController; mic?: MicTrack; room?: VoiceRoom; session?: string; agent: boolean; stated: boolean; hushed: boolean; timer?: ReturnType<typeof setTimeout> }
|
||||
// seq: the highest subtitle sequence applied in this call (one worker job, one sequence). speech: her speech open now;
|
||||
// closed: speeches that ended, were cancelled or were superseded here; nothing for them is shown again.
|
||||
interface Live { gen: number; abort: AbortController; mic?: MicTrack; room?: VoiceRoom; session?: string; agent: boolean; stated: boolean; hushed: boolean; timer?: ReturnType<typeof setTimeout>; seq: number; speech: string; pro: boolean; message?: number; closed: string[] }
|
||||
const CLOSED_KEPT = 64;
|
||||
|
||||
const AGENT_PHASE: Record<string, VoicePhase> = { initializing: 'joining', listening: 'listening', thinking: 'thinking', speaking: 'speaking' };
|
||||
|
||||
@@ -127,7 +152,7 @@ export class VoiceController {
|
||||
// The generation is taken before anything is awaited, so a start that wakes up after a newer one never takes
|
||||
// the call over; the call it replaces is released first, as end() would.
|
||||
const prev = this.live;
|
||||
const gen = ++this.gen, live: Live = { gen, abort: new AbortController(), agent: false, stated: false, hushed: false };
|
||||
const gen = ++this.gen, live: Live = { gen, abort: new AbortController(), agent: false, stated: false, hushed: false, seq: 0, speech: '', pro: false, closed: [] };
|
||||
this.live = live;
|
||||
this.view = { ...OFF, phase: 'opening' }; this.deps.onView(this.view);
|
||||
const stale = () => gen !== this.gen;
|
||||
@@ -189,11 +214,11 @@ export class VoiceController {
|
||||
},
|
||||
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();
|
||||
// Replays, late frames of an older turn and frames that overtook each other all sit at or below the
|
||||
// highest sequence already applied in this call.
|
||||
const s = subtitle(payload); if (!s || s.seq <= live.seq) return;
|
||||
live.seq = s.seq;
|
||||
this.hear(live, s);
|
||||
},
|
||||
dropped: () => { if (!stale()) void fail(WORDS.dropped); },
|
||||
audioBlocked: blocked => this.show({ blocked }, gen),
|
||||
@@ -224,10 +249,73 @@ export class VoiceController {
|
||||
if (live) void this.teardown(live, true);
|
||||
}
|
||||
|
||||
// One subtitle that passed the sequence gate. Your draft and her line never share a slot: `heard` is yours, `her`
|
||||
// is hers. Her frames act only on the speech open now; a speech once closed here is never shown again.
|
||||
private hear(live: Live, s: Subtitle) {
|
||||
const gen = live.gen, cur = this.view.her, honest = (phase: VoicePhase) => live.stated ? {} : { phase };
|
||||
if (s.kind === 'interim') {
|
||||
// Your draft. Her open line is left to the server's cancel (an SDK barge-in decides, not every sound).
|
||||
this.show({ heard: s.text, spoken: '', ...honest('listening') }, gen);
|
||||
if (live.hushed && !live.stated) { live.hushed = false; live.room?.hush(false); }
|
||||
return;
|
||||
}
|
||||
if (s.kind === 'user_final') {
|
||||
// A new turn of yours: nothing of hers from before may stand after it.
|
||||
if (live.speech) this.close(live, live.speech);
|
||||
this.show({ heard: s.text, spoken: '', her: null, ...honest('thinking') }, gen); this.deps.onSpoke(); this.deps.onRecord();
|
||||
return;
|
||||
}
|
||||
const pro = s.kind.startsWith('proactive_');
|
||||
if (s.kind === 'turn_start' || s.kind === 'proactive_start') {
|
||||
if (live.closed.includes(s.speech) || live.speech === s.speech) return;
|
||||
if (live.speech) this.close(live, live.speech);
|
||||
live.speech = s.speech; live.pro = pro; live.message = s.messageId;
|
||||
// A reach-out arrives whole (its stored text); a reply starts empty and grows.
|
||||
this.show({ spoken: '', ...(pro ? { heard: '' } : {}), her: pro ? { speech: s.speech, text: s.text, state: 'open', messageId: s.messageId, proactive: true } : { speech: s.speech, text: '', state: 'open' }, ...honest(pro ? 'speaking' : 'thinking') }, gen);
|
||||
return;
|
||||
}
|
||||
if (s.speech !== live.speech || pro !== live.pro || (pro && s.messageId !== live.message)) return;
|
||||
const mine = cur?.speech === s.speech ? cur : null;
|
||||
switch (s.kind) {
|
||||
case 'assistant_interim':
|
||||
// Replace, never append: each interim is the whole reply so far.
|
||||
if (mine?.state === 'open' && mine.text !== s.text) this.show({ her: { ...mine, text: s.text } }, gen);
|
||||
return;
|
||||
case 'assistant_final':
|
||||
if (mine?.state !== 'open') return;
|
||||
// Her stored answer: your draft it answered has done its part (as before v2).
|
||||
this.show({ heard: '', her: { ...mine, text: s.text, state: 'final', turnId: s.turnId }, ...honest('listening') }, gen); this.deps.onRecord();
|
||||
return;
|
||||
case 'error':
|
||||
// φ: heard, not stored; her unfinished line goes at once. The cancel that follows closes the speech.
|
||||
this.show({ heard: '', spoken: s.text, ...(mine ? { her: null } : {}), ...honest('listening') }, gen); this.deps.onRecord();
|
||||
return;
|
||||
case 'turn_end': case 'proactive_end':
|
||||
this.close(live, s.speech);
|
||||
// A reply closed without its final never became her reply; a reach-out read to the end stays until the
|
||||
// record or the next turn takes its place.
|
||||
this.show({ ...(mine ? { her: mine.state === 'final' || pro ? { ...mine, state: 'done' as const } : null } : {}), ...honest('listening') }, gen);
|
||||
if (!pro) this.deps.onRecord();
|
||||
return;
|
||||
case 'turn_cancel': case 'proactive_cancel':
|
||||
this.close(live, s.speech);
|
||||
this.show({ ...(mine ? { her: null } : {}), ...honest('listening') }, gen);
|
||||
if (!pro) this.deps.onRecord();
|
||||
return;
|
||||
}
|
||||
}
|
||||
private close(live: Live, speech: string) {
|
||||
if (live.speech === speech) { live.speech = ''; live.pro = false; live.message = undefined; }
|
||||
if (!live.closed.includes(speech)) { live.closed.push(speech); if (live.closed.length > CLOSED_KEPT) live.closed.shift(); }
|
||||
}
|
||||
|
||||
// You sent text while she was answering by voice: the server cancels her voice turn; keep its last audio silent.
|
||||
// Her line goes at once, whatever state it was in: your words come next on the stage.
|
||||
hush() {
|
||||
const live = this.live;
|
||||
if (!live?.room || (this.view.phase !== 'speaking' && this.view.phase !== 'thinking')) return;
|
||||
const live = this.live; if (!live) return;
|
||||
if (live.speech) this.close(live, live.speech);
|
||||
if (this.view.her) this.show({ her: null }, live.gen);
|
||||
if (!live.room || (this.view.phase !== 'speaking' && this.view.phase !== 'thinking')) return;
|
||||
live.hushed = true; live.room.hush(true);
|
||||
this.show({ spoken: '' }, live.gen);
|
||||
}
|
||||
@@ -285,6 +373,21 @@ export function mergeTurns(known: Message[], rows: Message[]): Message[] | null
|
||||
}
|
||||
return next;
|
||||
}
|
||||
// Her voice line as the stage shows it, in the place her text reply would take; null once it has nothing to add.
|
||||
// `since` is how many record rows there were when this speech was first seen. It gives way to the record: her reply
|
||||
// once its own row (same turn) is there, a reach-out once its stored row is the newest line; a finished line also as
|
||||
// soon as anything else came into the record after it, so it never stands in front of a newer turn.
|
||||
export function voiceLine(her: HerLine | null, messages: Message[], since: number, incoming: Message[] = []): ShownMessage | null {
|
||||
if (!her || !her.text) return null;
|
||||
const own = (m: Message) => her.proactive ? m.id === String(her.messageId) : !!her.turnId && m.turnId === her.turnId;
|
||||
if (her.proactive ? messages.at(-1)?.id === String(her.messageId) : messages.some(m => m.role === 'companion' && own(m))) return null;
|
||||
if (her.state !== 'open' && messages.slice(since).some(m => !own(m))) return null;
|
||||
// A reach-out keeps its stored row's identity (id, turn), so the row taking over keeps the same lines on the stage.
|
||||
const row = her.proactive ? [...messages, ...incoming].find(own) : undefined;
|
||||
// Her reply still growing holds back its newest line, as a streamed text reply does.
|
||||
return { id: row?.id ?? `voice-${her.speech}`, role: 'companion', text: her.text, lifeIds: [], turnId: row ? row.turnId : her.turnId, ...(her.proactive ? { proactive: true } : {}), ...(her.state === 'open' && !her.proactive ? { live: 'generating' as const } : {}) };
|
||||
}
|
||||
|
||||
// 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[]> {
|
||||
|
||||
Reference in New Issue
Block a user