HEL-908 R1/R2 rework (HEL-909 review): whole-turn reasoning gate + cg.interrupt data channel

R1 — reasoning separation truly closed. The streaming hold leaked wholesale
on real token arrival (review A1: 'private reasoning '*20 beyond the 128-char
bound, no sentence ender; review A2: a Chinese sentence ender released the
hold) AND the adapter consumed the stray closer, so the app-level turn split
could never recover — the previous 'persistence and receipt always clean'
claim was false and is retracted. Per the engineering ruling the adapter now
has two explicit endpoint modes (GOV-006, no heuristics, no new engine):
buffer_turn (TurnReasoningGate) emits NOTHING during generation, splits the
whole turn at stream end and only then delivers the clean visible text; it
is set explicitly for all tiers in config/models.yaml (first visible text
waits for the full generation; cancelled/timed-out turns emit nothing and
end exactly as before — recorded and test-pinned, low latency NOT claimed).
stream (default, backward compatible) keeps explicit-tag/field semantics and
passes stray closers through unmodified so the turn-level split keeps its
signal. Both review strings and the recorded id=12 stream replay clean at
every chunk size through the real adapter and the real app into chat.delta,
the archive and the receipt; normal zh/en preserved byte-for-byte; unclosed
explicit thinking still fails honestly.

R2 — an authoritative interrupt when the LLM already finalized and TTS is
still playing (review evidence C: zero interrupts, old audio played out).
The page's existing hush() entry (ChatPanel untouched) now also publishes
{"v":1} on the room's own reliable data channel topic cg.interrupt
(fire-and-forget: a dropped publish never blocks or breaks the text send);
the worker subscribes data_received, validates topic/sender/payload and
calls session.interrupt(force=True) — the SDK's own programmatic interrupt,
force confirmed against the installed 1.8.8 source (non-force raises
RuntimeError on allow_interruptions=False speech). Failures log loudly; the
listener is unloaded via add_shutdown_callback; the server-cancel path in
llm_chat_api also interrupts with force and logs failures.

Verification (offline, zero real requests): real-SDK harness 8/8 including a
real SpeechHandle with a genuinely pending playout wait released by the
cg.interrupt message after a clean chat.final (evidence-C shape) plus the
full validation matrix; .venv311 full suite 480 passed / 8 skipped (2
test_r3 failures pre-exist at 5625de6); web npm ci from the existing lock,
typecheck 0 errors, lint 0 errors + 1 pre-existing warning, vitest 148/148,
build ok; ruff clean; check_requirements vs origin/main and b8ec832 with the
corrected handoff.

Co-authored-by: multica-agent <github@multica.ai>
This commit is contained in:
xiaomo
2026-10-28 22:21:16 +08:00
co-authored by multica-agent
parent b8ec832f35
commit 958c6962fb
23 changed files with 844 additions and 379 deletions
+9 -2
View File
@@ -4,7 +4,7 @@
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';
const SUBTITLES = 'cg.subtitle', INTERRUPT = 'cg.interrupt', 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 }
@@ -16,7 +16,7 @@ interface LkRoom {
startAudio(): Promise<void>;
canPlaybackAudio: boolean;
remoteParticipants: Map<string, LkParticipant>;
localParticipant: { publishTrack(track: LkTrack, options?: { source?: string }): Promise<unknown> };
localParticipant: { publishTrack(track: LkTrack, options?: { source?: string }): Promise<unknown>; publishData(data: Uint8Array, options?: { reliable?: boolean; topic?: string }): Promise<void> };
}
export interface Livekit {
Room: new (options?: Record<string, unknown>) => LkRoom;
@@ -93,6 +93,13 @@ export function livekitTransport(lk: Livekit): VoiceTransport {
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; }); },
// HEL-909 R2: same-call interrupt for her worker (reliable, exact topic, payload {"v":1}).
// Fire-and-forget by contract: a failed or dropped publish must never break the text
// send that triggered it — the local mute above and the server's turn gate still hold.
interrupt() {
if (closing) return;
try { void room.localParticipant.publishData(new TextEncoder().encode('{"v":1}'), { reliable: true, topic: INTERRUPT }).catch(() => {}); } catch { /* transport already closed: nothing of this call can still be playing. */ }
},
resumeAudio: () => room.startAudio(),
close,
};
+9 -1
View File
@@ -69,7 +69,10 @@ export interface RoomEvents {
dropped(): void;
audioBlocked(blocked: boolean): void;
}
export interface VoiceRoom { publish(mic: MicTrack): Promise<void>; hush(on: boolean): void; resumeAudio(): Promise<void>; close(): Promise<void> }
// interrupt(): HEL-909 R2 — ask HER worker (over the room's own data channel, reliable)
// to stop any speech still playing. The call is one-way and never throws: it only
// supplements the local mute; the text send itself must never be blocked by it.
export interface VoiceRoom { publish(mic: MicTrack): Promise<void>; hush(on: boolean): void; interrupt(): 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 }
@@ -338,6 +341,11 @@ export class VoiceController {
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);
// HEL-909 R2: also tell the worker itself — when her turn already finished
// generating (server has no active turn to cancel) only the worker can stop
// the speech still playing. Fire-and-forget by contract: interrupt() never
// throws and never delays the text send.
live.room.interrupt();
this.show({ spoken: '' }, live.gen);
}
+1
View File
@@ -18,6 +18,7 @@ class Room implements VoiceRoom {
closed = 0; published: MicTrack[] = []; hushed: boolean[] = []; on!: RoomEvents;
async publish(mic: MicTrack) { this.published.push(mic); }
hush(on: boolean) { this.hushed.push(on); }
interrupt() {}
async resumeAudio() {}
async close() { this.closed++; }
}
+1 -1
View File
@@ -110,7 +110,7 @@ describe('her worker leaves while the room stays open (real adapter, SDK event n
});
describe('controller: agentLeft only for this call, only once she was there', () => {
class Room implements VoiceRoom { closed = 0; on!: RoomEvents; async publish(_m: MicTrack) {} hush() {} async resumeAudio() {} async close() { this.closed++; } }
class Room implements VoiceRoom { closed = 0; on!: RoomEvents; async publish(_m: MicTrack) {} hush() {} interrupt() {} async resumeAudio() {} async close() { this.closed++; } }
const make = () => {
const list: Room[] = [], views: VoiceView[] = [];
const transport = { capture: async () => ({ stop() {}, onEnded() {} }), join: async (_u: string, _t: string, on: RoomEvents) => { const x = new Room(); x.on = on; list.push(x); return x; } };
+1 -1
View File
@@ -27,7 +27,7 @@ describe('外接服务 reads only what /api/voice/status can tell', () => {
// ── The call's own voice ──
class Mic implements MicTrack { stopped = 0; stop() { this.stopped++; } onEnded() {} }
class Room implements VoiceRoom { closed = 0; on!: RoomEvents; async publish() {} hush() {} async resumeAudio() {} async close() { this.closed++; } }
class Room implements VoiceRoom { closed = 0; on!: RoomEvents; async publish() {} hush() {} interrupt() {} async resumeAudio() {} async close() { this.closed++; } }
function rig() {
const views: VoiceView[] = [], rooms: Room[] = [], voices: unknown[] = [], gates: (ReturnType<typeof gate> | undefined)[] = [];
let made = 0;
+1 -1
View File
@@ -22,7 +22,7 @@ test('old room disconnect cleanup cannot overwrite a newly opened call', async (
capture: async () => ({ stop() {}, onEnded() {} }),
join: async (_url, _token, callbacks) => {
events.push(callbacks);
return { publish: async () => {}, close: async () => {}, hush() {}, resumeAudio: async () => {} };
return { publish: async () => {}, close: async () => {}, hush() {}, interrupt() {}, resumeAudio: async () => {} };
},
}),
});
+4 -1
View File
@@ -16,9 +16,10 @@ const gate = () => { let open!: () => void; const promise = new Promise<void>(r
const flush = async (n = 8) => { for (let i = 0; i < n; i++) await Promise.resolve(); await new Promise(r => setTimeout(r, 0)); };
class Mic implements MicTrack { stopped = 0; ended?: () => void; stop() { this.stopped++; } onEnded(cb: () => void) { this.ended = cb; } }
class Room implements VoiceRoom {
closed = 0; published: MicTrack[] = []; hushed: boolean[] = []; on!: RoomEvents;
closed = 0; published: MicTrack[] = []; hushed: boolean[] = []; interrupted = 0; on!: RoomEvents;
async publish(mic: MicTrack) { this.published.push(mic); }
hush(on: boolean) { this.hushed.push(on); }
interrupt() { this.interrupted++; }
async resumeAudio() {}
async close() { this.closed++; }
}
@@ -376,8 +377,10 @@ describe('subtitles and the two channels', () => {
it('typing over her spoken answer silences what is left of it until she is listening again', async () => {
const r = await connected(), room = r.transport.rooms[0];
r.c.hush(); expect(room.hushed).toEqual([]); // listening: nothing to silence
expect(room.interrupted).toBe(0); // nor anything to tell her worker
room.on.agentState('speaking'); r.c.hush();
expect(room.hushed).toEqual([true]);
expect(room.interrupted).toBe(1); // HEL-909 R2: the worker is told too
room.on.agentState('speaking'); expect(room.hushed).toEqual([true]);
room.on.agentState('listening'); expect(room.hushed).toEqual([true, false]);
});