HEL-898: preserve director v2 subtitle wiring verbatim on fc905fe

Co-authored-by: multica-agent <github@multica.ai>
This commit is contained in:
总管
2026-10-27 05:53:00 +08:00
co-authored by multica-agent
parent fc905fe6bd
commit 46ac0a7a20
8 changed files with 574 additions and 43 deletions
+116 -13
View File
@@ -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[]> {