feat(voice): implement real-time voice-to-voice streaming engine

Introduce a complete low-level audio processing and streaming pipeline
for live voice conversations.

- Implement `VoiceAudioEngine` using `AudioWorklet` for low-latency
  PCM16 capture and playback.
- Add `pcm-capture` and `pcm-playback` worklets for high-performance
  audio processing outside the main thread.
- Implement `VoiceStreamService` to manage the voice-to-voice state
  machine (LISTENING, PROCESSING, SPEAKING, INTERRUPTED).
- Add `VoiceApiService` for managing conversation and session lifecycle
  via REST and WebSocket.
- Create `VoiceStreamPanelComponent` to display real-time transcripts,
  status indicators, and the animated voice orb.
- Integrate voice streaming into the `AiChatInputComponent` with
  support for seamless UI transitions between text and voice modes.
This commit is contained in:
PeymanHonarjoo
2026-10-08 12:52:29 +03:30
parent 447849289e
commit f6ce43453a
15 changed files with 2152 additions and 49 deletions
@@ -0,0 +1,143 @@
import { HttpClient, HttpErrorResponse, HttpHeaders } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import { firstValueFrom, Observable } from 'rxjs';
import { VOICE_STREAM_CONFIG } from './voice-stream.types';
/** Error envelope from the catalog: { error: { code, message, request_id, retryable, details } }. */
export class VoiceApiError extends Error {
constructor(
readonly status: number,
readonly code: string,
message: string,
readonly retryable = false,
readonly requestId?: string,
) {
super(message);
this.name = 'VoiceApiError';
}
}
export interface MeResponse {
user: { id: string; username: string; role: string; organization_id: string };
csrf_token: string;
expires_at: string;
}
export interface ConfigurationResponse {
capabilities: { text: boolean; voice: boolean; captions: boolean };
}
export interface ConversationResponse {
id: string;
mode: 'voice';
title: string;
status: string;
}
export interface VoiceSessionResponse {
session_id: string;
conversation_id: string;
status: string;
stream_path: string;
expires_at: string;
poll_url: string;
}
/**
* Thin client for the endpoints the live voice call needs (A03, F01, C01, V01, V04).
* Uses HttpClient so the app's existing interceptors (401 → login redirect, etc.) still apply.
* Auth is the HttpOnly `rag_session` cookie; state-changing calls also need `X-CSRF-Token`.
*/
@Injectable({ providedIn: 'root' })
export class VoiceApiService {
private readonly http = inject(HttpClient);
private readonly config = inject(VOICE_STREAM_CONFIG);
/** A03: identity + a fresh CSRF token. 401 AUTH_REQUIRED when not logged in. */
me(): Promise<MeResponse> {
return this.send(this.http.get<MeResponse>(this.url('/me'), { withCredentials: true }));
}
/** F01: capabilities (the UI must check `voice` before offering a call). */
configuration(): Promise<ConfigurationResponse> {
return this.send(
this.http.get<ConfigurationResponse>(this.url('/configuration'), { withCredentials: true }),
);
}
/** C01: only `mode: "voice"` exists in the MVP. */
createConversation(csrf: string, title: string): Promise<ConversationResponse> {
return this.send(
this.http.post<ConversationResponse>(
this.url('/conversations'),
{ client_request_id: crypto.randomUUID(), mode: 'voice', title },
this.options(csrf),
),
);
}
/** V01: reserves a live session; connect the WebSocket to the returned `stream_path`. */
createVoiceSession(csrf: string, conversationId: string): Promise<VoiceSessionResponse> {
return this.send(
this.http.post<VoiceSessionResponse>(
this.url('/voice/sessions'),
{ conversation_id: conversationId, client_request_id: crypto.randomUUID() },
this.options(csrf),
),
);
}
/** V04: closes the session (idempotent from the UI's point of view). */
async closeVoiceSession(csrf: string, sessionId: string): Promise<void> {
await this.send(
this.http.post<unknown>(
this.url(`/voice/sessions/${encodeURIComponent(sessionId)}/close`),
{},
this.options(csrf),
),
);
}
/** `wss://…` URL for a V01 `stream_path`. */
streamUrl(streamPath: string): string {
const base = this.config.apiOrigin || window.location.origin;
const url = new URL(streamPath, base);
url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:';
return url.toString();
}
// ---------------------------------------------------------------------------
private url(path: string): string {
return `${this.config.apiOrigin}${this.config.apiBase}${path}`;
}
private options(csrf: string) {
return {
withCredentials: true,
headers: new HttpHeaders({ 'X-CSRF-Token': csrf, 'X-Request-ID': crypto.randomUUID() }),
};
}
private async send<T>(request: Observable<T>): Promise<T> {
try {
return await firstValueFrom(request);
} catch (err) {
throw this.toApiError(err);
}
}
private toApiError(err: unknown): VoiceApiError {
if (err instanceof HttpErrorResponse) {
const envelope = (err.error as { error?: Record<string, unknown> } | null)?.error;
return new VoiceApiError(
err.status,
typeof envelope?.['code'] === 'string' ? envelope['code'] : err.status === 0 ? 'NETWORK' : 'UNKNOWN',
typeof envelope?.['message'] === 'string' ? envelope['message'] : err.message,
envelope?.['retryable'] === true,
typeof envelope?.['request_id'] === 'string' ? envelope['request_id'] : undefined,
);
}
return new VoiceApiError(0, 'UNKNOWN', err instanceof Error ? err.message : 'unknown error');
}
}
@@ -0,0 +1,192 @@
import { Injectable, NgZone, inject } from '@angular/core';
import { MicrophoneService } from '../microphone/microphone.service';
import { VOICE_STREAM_CONFIG } from './voice-stream.types';
export interface VoiceEngineHandlers {
/** One PCM16 frame (config.inputSampleRate, config.frameMs). Runs outside Angular's zone. */
onFrame(pcm: ArrayBuffer, rms: number): void;
/** The playback buffer ran dry (or `flushPlayback()` found it empty). */
onPlaybackIdle(): void;
/** The microphone track ended unexpectedly. */
onMicEnded(): void;
}
export class VoiceEngineError extends Error {
constructor(readonly code: 'unsupported' | 'worklet-failed') {
super(code);
this.name = 'VoiceEngineError';
}
}
/**
* Low-level audio for the call:
* mic → [pcm-capture worklet] → PCM16 frames → (service → transport)
* (transport → service) → PCM16 chunks → [pcm-playback worklet] → speakers
* Everything here runs outside Angular's zone; frames arrive ~50×/s and must not trigger change detection.
*/
@Injectable({ providedIn: 'root' })
export class VoiceAudioEngine {
private readonly ngZone = inject(NgZone);
private readonly mic = inject(MicrophoneService);
private readonly config = inject(VOICE_STREAM_CONFIG);
private ctx: AudioContext | null = null;
private source: MediaStreamAudioSourceNode | null = null;
private capture: AudioWorkletNode | null = null;
private playback: AudioWorkletNode | null = null;
private sink: GainNode | null = null;
private analyser: AnalyserNode | null = null;
private analyserData: Uint8Array<ArrayBuffer> | null = null;
private stream: MediaStream | null = null;
private inputRms = 0;
get isSupported(): boolean {
return (
this.mic.isSupported &&
typeof AudioContext !== 'undefined' &&
typeof AudioWorkletNode !== 'undefined'
);
}
/** Requests the mic, loads the worklets and starts capturing. Throws MicrophoneError / VoiceEngineError. */
async start(handlers: VoiceEngineHandlers): Promise<void> {
if (!this.isSupported) throw new VoiceEngineError('unsupported');
this.stop();
const stream = await this.mic.request(handlers.onMicEnded, {
echoCancellation: true,
noiseSuppression: true,
autoGainControl: true,
channelCount: 1,
});
this.stream = stream;
try {
await this.ngZone.runOutsideAngular(() => this.buildGraph(stream, handlers));
} catch (err) {
this.stop();
throw err instanceof Error && err.name === 'MicrophoneError' ? err : new VoiceEngineError('worklet-failed');
}
}
private async buildGraph(stream: MediaStream, handlers: VoiceEngineHandlers): Promise<void> {
const cfg = this.config;
const ctx = new AudioContext({ latencyHint: 'interactive' });
this.ctx = ctx;
const base = cfg.workletBasePath.replace(/\/$/, '');
await ctx.audioWorklet.addModule(`${base}/pcm-capture.worklet.js`);
await ctx.audioWorklet.addModule(`${base}/pcm-playback.worklet.js`);
if (ctx.state === 'suspended') await ctx.resume();
// capture: mic → worklet → (silent sink so the graph is pulled)
this.source = ctx.createMediaStreamSource(stream);
this.capture = new AudioWorkletNode(ctx, 'pcm-capture', {
numberOfInputs: 1,
numberOfOutputs: 1,
outputChannelCount: [1],
processorOptions: {
targetRate: cfg.inputSampleRate,
frameSamples: Math.round((cfg.inputSampleRate * cfg.frameMs) / 1000),
},
});
this.capture.port.onmessage = (event: MessageEvent<{ pcm: ArrayBuffer; rms: number }>) => {
this.inputRms = event.data.rms;
handlers.onFrame(event.data.pcm, event.data.rms);
};
this.sink = ctx.createGain();
this.sink.gain.value = 0; // never play the mic back
this.source.connect(this.capture);
this.capture.connect(this.sink);
this.sink.connect(ctx.destination);
// playback: worklet → analyser (output level) → speakers
this.playback = new AudioWorkletNode(ctx, 'pcm-playback', {
numberOfInputs: 0,
numberOfOutputs: 1,
outputChannelCount: [1],
});
this.playback.port.onmessage = (event: MessageEvent<{ type: string }>) => {
if (event.data?.type === 'idle') handlers.onPlaybackIdle();
};
this.analyser = ctx.createAnalyser();
this.analyser.fftSize = 1024;
this.analyser.smoothingTimeConstant = 0.6;
this.analyserData = new Uint8Array(this.analyser.fftSize);
this.playback.connect(this.analyser);
this.analyser.connect(ctx.destination);
}
// ---- playback --------------------------------------------------------------
/** Queues a PCM16 mono chunk at config.outputSampleRate. Ownership of the buffer moves to the worklet. */
enqueuePlayback(chunk: ArrayBuffer): void {
if (!this.playback) return;
const buffer = chunk.byteLength % 2 === 0 ? chunk : chunk.slice(0, chunk.byteLength - 1);
this.playback.port.postMessage(
{ type: 'push', pcm: buffer, sampleRate: this.config.outputSampleRate },
[buffer],
);
}
/** Barge-in: drop all queued audio immediately. */
clearPlayback(): void {
this.playback?.port.postMessage({ type: 'clear' });
}
/** End of turn: play the remaining audio, then report idle. */
flushPlayback(): void {
this.playback?.port.postMessage({ type: 'flush' });
}
// ---- mic / meters ----------------------------------------------------------
setMuted(muted: boolean): void {
this.stream?.getAudioTracks().forEach((track) => (track.enabled = !muted));
}
/** Mic level 0..1 (for the orb). */
inputLevel(): number {
return Math.min(1, this.inputRms * 6);
}
/** Assistant playback level 0..1 (for the orb). */
outputLevel(): number {
if (!this.analyser || !this.analyserData) return 0;
this.analyser.getByteTimeDomainData(this.analyserData);
let sum = 0;
for (let i = 0; i < this.analyserData.length; i++) {
const v = (this.analyserData[i] - 128) / 128;
sum += v * v;
}
return Math.min(1, Math.sqrt(sum / this.analyserData.length) * 5);
}
// ---- cleanup ---------------------------------------------------------------
stop(): void {
if (this.capture) this.capture.port.onmessage = null;
if (this.playback) this.playback.port.onmessage = null;
this.source?.disconnect();
this.capture?.disconnect();
this.sink?.disconnect();
this.playback?.disconnect();
this.analyser?.disconnect();
if (this.ctx && this.ctx.state !== 'closed') {
this.ctx.close().catch(() => undefined);
}
this.mic.release(this.stream);
this.ctx = null;
this.source = null;
this.capture = null;
this.playback = null;
this.sink = null;
this.analyser = null;
this.analyserData = null;
this.stream = null;
this.inputRms = 0;
}
}
@@ -0,0 +1,631 @@
import { Injectable, NgZone, computed, inject, signal } from '@angular/core';
import { Subject } from 'rxjs';
import { MicrophoneError } from '../microphone/microphone.service';
import { VoiceApiError, VoiceApiService } from './voice-api.service';
import { VoiceAudioEngine, VoiceEngineError } from './voice-audio-engine.service';
import { VOICE_TRANSPORT_FACTORY, VoiceTransport } from './voice-transport';
import {
VOICE_STREAM_CONFIG,
VoiceConnection,
VoiceMessage,
VoiceServerEvent,
VoiceSessionEnd,
VoiceStreamState,
} from './voice-stream.types';
export type VoiceStartFailure =
| 'cancelled'
| 'unsupported'
| 'mic'
| 'engine'
| 'auth'
| 'unavailable'
| 'api'
| 'connect';
export type VoiceStartResult =
| { ok: true }
| { ok: false; reason: VoiceStartFailure; message: string };
type TranscriptEvent = Extract<VoiceServerEvent, { type: 'transcript' }>;
type SourcesEvent = Extract<VoiceServerEvent, { type: 'sources' }>;
type ErrorEvent = Extract<VoiceServerEvent, { type: 'error' }>;
const MESSAGES = {
unsupported: 'گفتگوی صوتی در این مرورگر پشتیبانی نمی‌شود (اتصال امن HTTPS و مرورگر جدید لازم است).',
micDenied: 'دسترسی به میکروفون رد شد. اجازه‌ی دسترسی را در تنظیمات مرورگر فعال کنید.',
micUnavailable: 'میکروفونی پیدا نشد یا در حال استفاده‌ی برنامه‌ی دیگری است.',
micLost: 'اتصال میکروفون قطع شد و گفتگو پایان یافت.',
engine: 'راه‌اندازی پردازشگر صوتی ناموفق بود. صفحه را دوباره بارگذاری کنید.',
auth: 'نشست شما منقضی شده است. دوباره وارد شوید.',
voiceDisabled: 'گفتگوی صوتی برای این سامانه فعال نیست.',
rateLimited: 'تعداد درخواست‌ها زیاد است. کمی بعد دوباره تلاش کنید.',
unavailable: 'سرویس موقتاً در دسترس نیست. کمی بعد دوباره تلاش کنید.',
sessionUnusable: 'نشست صوتی بسته شده است. گفتگوی جدیدی شروع کنید.',
api: 'شروع گفتگوی صوتی ناموفق بود. دوباره تلاش کنید.',
connect: 'اتصال به سرور صوتی برقرار نشد. دوباره تلاش کنید.',
badFormat: 'فرمت صدای سرور با برنامه سازگار نیست.',
disconnected: 'ارتباط با سرور قطع شد و گفتگو پایان یافت.',
server: 'سرور گفتگوی صوتی با خطا مواجه شد.',
conversationTitle: 'گفتگوی صوتی',
} as const;
/** How long INTERRUPTED stays visible before returning to LISTENING. */
const INTERRUPTED_FLASH_MS = 150;
/** How long a retryable server error stays on screen. */
const ERROR_BANNER_MS = 6000;
/**
* One live voice call against the MVP API (mvp_ui_api_catalog.md §6):
*
* mic ─▶ engine ─▶ PCM16 16 kHz frames ─▶ WSS ─▶ server
* server ─▶ session_ready / transcript / sources / turn_interrupted / error (JSON)
* ─▶ PCM16 24 kHz audio (binary) ─▶ engine playback
*
* Start: mic permission → GET /me (CSRF) → GET /configuration (voice enabled?)
* → POST /conversations → POST /voice/sessions → WSS stream_path → `session_ready`.
* End: close the socket, stop audio, POST /voice/sessions/{id}/close.
*
* Barge-in is decided by the server: it sends `turn_interrupted` and the client flushes playback.
* (The contract has no client→server interrupt message.)
*/
@Injectable({ providedIn: 'root' })
export class VoiceStreamService {
private readonly ngZone = inject(NgZone);
private readonly engine = inject(VoiceAudioEngine);
private readonly api = inject(VoiceApiService);
private readonly config = inject(VOICE_STREAM_CONFIG);
private readonly createTransport = inject(VOICE_TRANSPORT_FACTORY);
readonly state = signal<VoiceStreamState>('IDLE');
readonly connection = signal<VoiceConnection>('disconnected');
readonly messages = signal<VoiceMessage[]>([]);
readonly muted = signal(false);
/** Non-fatal, retryable server error to show as a banner (e.g. SEARCH_TIMEOUT). */
readonly streamError = signal<string | null>(null);
/** true from the moment start() is called until the call is over. */
readonly isOpen = computed(() => this.connection() !== 'disconnected');
readonly isSupported = this.engine.isSupported && typeof WebSocket !== 'undefined';
/** Emits once for every call that reached `connected` (normal end or failure). */
readonly sessionEnded$ = new Subject<VoiceSessionEnd>();
private transport: VoiceTransport | null = null;
private remote: { sessionId: string; conversationId: string; csrf: string } | null = null;
private session = 0;
private streaming = false;
private turnEnded = false;
private interruptTimer: ReturnType<typeof setTimeout> | null = null;
private settleTimer: ReturnType<typeof setTimeout> | null = null;
private errorTimer: ReturnType<typeof setTimeout> | null = null;
private readyWaiter: {
resolve: () => void;
reject: (error: Error) => void;
timer: ReturnType<typeof setTimeout>;
} | null = null;
private lastConversationId: string | null = null;
// ---- public API -----------------------------------------------------------
async start(options: { title?: string } = {}): Promise<VoiceStartResult> {
if (this.isOpen()) return this.failure('cancelled', '');
if (!this.isSupported) return this.failure('unsupported', MESSAGES.unsupported);
const session = ++this.session;
const stale = (): boolean => session !== this.session;
this.messages.set([]);
this.muted.set(false);
this.clearError();
this.resetTurnFlags();
this.lastConversationId = null;
this.state.set('IDLE');
this.connection.set('connecting');
// 1) microphone + worklets (needs the user gesture; shows the permission prompt)
try {
await this.engine.start({
onFrame: (pcm) => this.onMicFrame(pcm),
onPlaybackIdle: () => this.ngZone.run(() => this.onPlaybackIdle()),
onMicEnded: () => this.ngZone.run(() => this.failSession(MESSAGES.micLost, session)),
});
} catch (err) {
return this.abortStart(session, this.mapEngineError(err));
}
if (stale()) {
// Cancelled while the permission prompt / worklets were loading: release what was just opened.
if (!this.isOpen()) this.engine.stop();
return this.failure('cancelled', '');
}
// 2) REST: identity/CSRF → capabilities → conversation → voice session
let streamPath: string;
try {
const me = await this.api.me();
if (stale()) return this.failure('cancelled', '');
const configuration = await this.api.configuration();
if (stale()) return this.failure('cancelled', '');
if (!configuration.capabilities.voice) {
return this.abortStart(session, { reason: 'unavailable', message: MESSAGES.voiceDisabled });
}
const conversation = await this.api.createConversation(me.csrf_token, MESSAGES.conversationTitle);
if (stale()) return this.failure('cancelled', '');
const voiceSession = await this.api.createVoiceSession(me.csrf_token, conversation.id);
const remote = {
sessionId: voiceSession.session_id,
conversationId: conversation.id,
csrf: me.csrf_token,
};
if (stale()) {
this.closeRemote(remote); // cancelled after the server already reserved the session
return this.failure('cancelled', '');
}
this.remote = remote;
this.lastConversationId = conversation.id;
streamPath = voiceSession.stream_path;
} catch (err) {
if (stale()) return this.failure('cancelled', '');
return this.abortStart(session, this.mapApiError(err));
}
// 3) WebSocket (created outside the zone so socket events don't trigger change detection)
const transport = this.createTransport(this.api.streamUrl(streamPath));
this.transport = transport;
try {
await this.ngZone.runOutsideAngular(() =>
transport.connect({
onEvent: (event) => this.ngZone.run(() => this.onServerEvent(event, session)),
onAudio: (chunk) => this.onServerAudio(chunk, session),
onClose: () => this.ngZone.run(() => this.failSession(MESSAGES.disconnected, session)),
}),
);
} catch {
if (stale()) return this.failure('cancelled', '');
return this.abortStart(session, { reason: 'connect', message: MESSAGES.connect });
}
if (stale()) return this.failure('cancelled', '');
// 4) wait for `session_ready` (the server pushes it; the client sends no handshake)
try {
await new Promise<void>((resolve, reject) => {
const timer = setTimeout(
() => reject(new Error('ready-timeout')),
this.config.connectTimeoutMs,
);
this.readyWaiter = { resolve, reject, timer };
});
} catch (err) {
if (stale()) return this.failure('cancelled', '');
const badFormat = err instanceof Error && err.message === 'format';
return this.abortStart(session, {
reason: 'connect',
message: badFormat ? MESSAGES.badFormat : MESSAGES.connect,
});
}
if (stale()) return this.failure('cancelled', '');
this.connection.set('connected');
this.state.set('LISTENING');
this.streaming = true;
return { ok: true };
}
/** User ends the call. Safe to call at any time. */
end(): void {
if (!this.isOpen()) return;
this.finishSession();
}
toggleMute(): void {
const next = !this.muted();
this.muted.set(next);
this.engine.setMuted(next); // frames keep flowing (silent), so the server never sees a gap
}
/** Level (0..1) the orb should follow: assistant audio while speaking, otherwise the mic. */
orbLevel(): number {
if (this.state() === 'SPEAKING') return this.engine.outputLevel();
return this.muted() ? 0 : this.engine.inputLevel();
}
dismissError(): void {
this.clearError();
}
/** Component teardown: release everything without emitting events. */
dispose(): void {
this.rejectReady();
this.teardown();
}
// ---- audio from the microphone (outside the zone) --------------------------
private onMicFrame(pcm: ArrayBuffer): void {
if (this.streaming) this.transport?.sendAudio(pcm);
}
// ---- audio from the server (outside the zone) ------------------------------
private onServerAudio(chunk: ArrayBuffer, session: number): void {
if (session !== this.session || !this.streaming) return;
this.engine.enqueuePlayback(chunk);
this.clearSettleTimer();
if (this.state() !== 'SPEAKING') {
this.ngZone.run(() => {
if (this.interruptTimer) {
clearTimeout(this.interruptTimer);
this.interruptTimer = null;
}
this.state.set('SPEAKING');
});
}
}
// ---- JSON events from the server -------------------------------------------
private onServerEvent(event: VoiceServerEvent, session: number): void {
if (session !== this.session) return;
switch (event.type) {
case 'session_ready': {
const { input_audio: input, output_audio: output } = event;
const compatible =
input.encoding === 'pcm_s16le' &&
output.encoding === 'pcm_s16le' &&
input.channels === 1 &&
output.channels === 1 &&
input.sample_rate === this.config.inputSampleRate &&
output.sample_rate === this.config.outputSampleRate;
if (compatible) this.resolveReady();
else this.rejectReady(new Error('format'));
break;
}
case 'transcript':
this.onTranscript(event);
break;
case 'sources':
this.upsertSources(event);
break;
case 'turn_interrupted':
this.onTurnInterrupted(event.turn_ref);
break;
case 'error':
this.onServerError(event, session);
break;
}
}
private onTranscript(event: TranscriptEvent): void {
this.upsertTranscript(event);
if (event.status === 'interrupted') {
this.onTurnInterrupted(event.turn_ref);
return;
}
if (event.role === 'user') {
// The user finished their sentence; the assistant is working on it.
if (event.status === 'completed' && this.state() === 'LISTENING') {
this.state.set('PROCESSING');
}
return;
}
if (event.status === 'completed') {
// All text for this turn is out. Play what is buffered, then return to LISTENING.
this.turnEnded = true;
this.engine.flushPlayback();
}
}
/** Server-side barge-in: the user spoke over the assistant. */
private onTurnInterrupted(turnRef: string): void {
this.engine.clearPlayback(); // empty the playback queue immediately
this.turnEnded = false;
this.clearSettleTimer();
this.markInterrupted(turnRef);
const state = this.state();
if (state === 'SPEAKING' || state === 'PROCESSING') {
this.state.set('INTERRUPTED');
if (this.interruptTimer) clearTimeout(this.interruptTimer);
this.interruptTimer = setTimeout(() => {
this.interruptTimer = null;
if (this.state() === 'INTERRUPTED') this.state.set('LISTENING');
}, INTERRUPTED_FLASH_MS);
}
}
private onServerError(event: ErrorEvent, session: number): void {
const { message, retryable, code } = event.error;
console.warn('VoiceStreamService: server error', code, event.error.request_id);
if (!retryable) {
this.failSession(message || MESSAGES.server, session);
return;
}
// The session survives a retryable failure (e.g. SEARCH_TIMEOUT): drop the failed turn and keep listening.
this.engine.clearPlayback();
this.turnEnded = false;
this.clearSettleTimer();
this.finalizeAssistant();
if (this.state() === 'PROCESSING' || this.state() === 'SPEAKING') this.state.set('LISTENING');
this.showError(message || MESSAGES.server);
}
// ---- end of an assistant turn ----------------------------------------------
private onPlaybackIdle(): void {
const state = this.state();
if (state !== 'SPEAKING' && state !== 'PROCESSING') return;
if (this.turnEnded) {
this.finishTurn();
} else if (state === 'SPEAKING') {
// The buffer drained but no `completed` transcript arrived (yet). If no more audio comes, the turn is over.
this.clearSettleTimer();
this.settleTimer = setTimeout(() => {
this.settleTimer = null;
if (this.state() === 'SPEAKING') this.finishTurn();
}, this.config.settleMs);
}
}
private finishTurn(): void {
this.turnEnded = false;
this.clearSettleTimer();
this.finalizeAssistant();
this.state.set('LISTENING');
}
// ---- transcript ------------------------------------------------------------
private upsertTranscript(event: TranscriptEvent): void {
const id = `${event.turn_ref}:${event.role}`;
const final = event.status !== 'partial';
const interrupted = event.status === 'interrupted';
this.messages.update((list) => {
const index = list.findIndex((m) => m.id === id);
if (index === -1) {
if (!event.text.trim()) return list;
return [
...list,
{
id,
turnRef: event.turn_ref,
role: event.role,
text: event.text,
final,
interrupted: interrupted || undefined,
},
];
}
const current = list[index];
if (current.interrupted && !interrupted) return list; // late partial for a cut-off message
const copy = [...list];
copy[index] = {
...current,
text: this.mergeTranscriptText(current.text, event),
final: current.final || final,
interrupted: current.interrupted || interrupted || undefined,
};
return copy;
});
}
/**
* The catalog does not say whether a `partial` carries the full text so far or only the new fragment,
* so both are handled:
* - `completed` with text → the final full text replaces whatever was accumulated
* - text that starts with what we already have → cumulative, replace
* - anything else → a fragment, append as-is (fragments carry their own spacing)
* If the backend turns out to use only one style, this is the single place to simplify.
*/
private mergeTranscriptText(previous: string, event: TranscriptEvent): string {
const next = event.text;
if (!next) return previous;
if (!previous || event.status === 'completed') return next;
if (next.startsWith(previous)) return next;
return previous + next;
}
private upsertSources(event: SourcesEvent): void {
const id = `${event.turn_ref}:assistant`;
this.messages.update((list) => {
const index = list.findIndex((m) => m.id === id);
const current: VoiceMessage =
index === -1
? { id, turnRef: event.turn_ref, role: 'assistant', text: '', final: false }
: list[index];
const sources = [...(current.sources ?? [])];
for (const source of event.sources) {
if (!sources.some((s) => s.source_ref === source.source_ref && s.chunk_id === source.chunk_id)) {
sources.push(source);
}
}
const next = { ...current, sources };
if (index === -1) return [...list, next];
const copy = [...list];
copy[index] = next;
return copy;
});
}
private markInterrupted(turnRef: string): void {
const id = `${turnRef}:assistant`;
this.messages.update((list) => {
const index = list.findIndex((m) => m.id === id);
if (index === -1 || list[index].interrupted) return list;
const copy = [...list];
copy[index] = { ...copy[index], final: true, interrupted: true };
return copy;
});
}
private finalizeAssistant(): void {
this.messages.update((list) =>
list.some((m) => m.role === 'assistant' && !m.final)
? list.map((m) => (m.role === 'assistant' && !m.final ? { ...m, final: true } : m))
: list,
);
}
private finalizeAll(): void {
this.messages.update((list) =>
list.some((m) => !m.final) ? list.map((m) => (m.final ? m : { ...m, final: true })) : list,
);
}
// ---- lifecycle -------------------------------------------------------------
private failSession(message: string, session: number): void {
if (session !== this.session || !this.isOpen()) return;
this.finishSession(message);
}
private finishSession(error?: string): void {
const wasConnected = this.connection() === 'connected';
const conversationId = this.remote?.conversationId ?? this.lastConversationId;
this.rejectReady();
this.finalizeAll();
const messages = this.messages();
this.teardown();
if (wasConnected) this.sessionEnded$.next({ conversationId, messages, error });
}
private abortStart(
session: number,
failure: { reason: VoiceStartFailure; message: string },
): VoiceStartResult {
if (session === this.session) this.teardown();
return this.failure(failure.reason, failure.message);
}
/** Releases every resource; idempotent. Invalidates all pending async work via `session`. */
private teardown(): void {
this.session++;
this.streaming = false;
this.resetTurnFlags();
this.clearSettleTimer();
this.clearError();
if (this.interruptTimer) {
clearTimeout(this.interruptTimer);
this.interruptTimer = null;
}
const transport = this.transport;
this.transport = null;
transport?.close();
this.engine.stop();
// V04: tell the server the session is over (best effort).
const remote = this.remote;
this.remote = null;
if (remote) this.closeRemote(remote);
this.connection.set('disconnected');
this.state.set('IDLE');
this.muted.set(false);
}
private closeRemote(remote: { sessionId: string; csrf: string }): void {
this.api.closeVoiceSession(remote.csrf, remote.sessionId).catch(() => {
/* already closed / expired (e.g. 409 LIVE_SESSION_UNUSABLE): nothing to do */
});
}
private resetTurnFlags(): void {
this.turnEnded = false;
}
private clearSettleTimer(): void {
if (this.settleTimer) {
clearTimeout(this.settleTimer);
this.settleTimer = null;
}
}
private showError(message: string): void {
this.clearError();
this.streamError.set(message);
this.errorTimer = setTimeout(() => this.clearError(), ERROR_BANNER_MS);
}
private clearError(): void {
if (this.errorTimer) {
clearTimeout(this.errorTimer);
this.errorTimer = null;
}
if (this.streamError() !== null) this.streamError.set(null);
}
private resolveReady(): void {
const waiter = this.readyWaiter;
this.readyWaiter = null;
if (!waiter) return;
clearTimeout(waiter.timer);
waiter.resolve();
}
private rejectReady(error: Error = new Error('cancelled')): void {
const waiter = this.readyWaiter;
this.readyWaiter = null;
if (!waiter) return;
clearTimeout(waiter.timer);
waiter.reject(error);
}
// ---- error mapping ---------------------------------------------------------
private mapEngineError(err: unknown): { reason: VoiceStartFailure; message: string } {
if (err instanceof MicrophoneError) {
if (err.code === 'unsupported') return { reason: 'unsupported', message: MESSAGES.unsupported };
return {
reason: 'mic',
message: err.code === 'denied' ? MESSAGES.micDenied : MESSAGES.micUnavailable,
};
}
if (err instanceof VoiceEngineError && err.code === 'unsupported') {
return { reason: 'unsupported', message: MESSAGES.unsupported };
}
return { reason: 'engine', message: MESSAGES.engine };
}
/** Maps the catalog's error codes (§7) to a user-facing Persian message. */
private mapApiError(err: unknown): { reason: VoiceStartFailure; message: string } {
if (!(err instanceof VoiceApiError)) return { reason: 'api', message: MESSAGES.api };
switch (err.code) {
case 'AUTH_REQUIRED':
return { reason: 'auth', message: MESSAGES.auth };
case 'RATE_LIMITED':
return { reason: 'api', message: MESSAGES.rateLimited };
case 'DEPENDENCY_UNAVAILABLE':
return { reason: 'unavailable', message: MESSAGES.unavailable };
case 'LIVE_SESSION_UNUSABLE':
return { reason: 'api', message: MESSAGES.sessionUnusable };
case 'NETWORK':
return { reason: 'connect', message: MESSAGES.connect };
default:
return { reason: 'api', message: MESSAGES.api };
}
}
private failure(reason: VoiceStartFailure, message: string): VoiceStartResult {
return { ok: false, reason, message };
}
}
@@ -0,0 +1,114 @@
import { InjectionToken } from '@angular/core';
/**
* Voice-to-voice state machine.
* The server sends no explicit state events, so the client derives them:
* LISTENING after session_ready, and after an assistant turn has finished playing
* PROCESSING user transcript `completed`, assistant audio has not started yet
* SPEAKING assistant audio is arriving / playing
* INTERRUPTED transient (~150 ms) after the server's `turn_interrupted`, then LISTENING
*/
export type VoiceStreamState = 'IDLE' | 'LISTENING' | 'PROCESSING' | 'SPEAKING' | 'INTERRUPTED';
export type VoiceConnection = 'disconnected' | 'connecting' | 'connected';
// ---------------------------------------------------------------------------
// Backend contract: mvp_ui_api_catalog.md (§6, "Live Voice Conversations & WSS")
// ---------------------------------------------------------------------------
export interface VoiceSource {
source_ref: string;
document_id: string;
chunk_id: string;
title: string;
excerpt?: string;
location?: { page?: number; section?: string };
available?: boolean;
}
export interface VoiceAudioFormat {
encoding: string;
sample_rate: number;
channels: number;
}
export type TranscriptStatus = 'partial' | 'completed' | 'interrupted';
export type VoiceServerEvent =
| {
type: 'session_ready';
session_id: string;
input_audio: VoiceAudioFormat;
output_audio: VoiceAudioFormat;
}
| {
type: 'transcript';
turn_ref: string;
role: 'user' | 'assistant';
/**
* Full text so far OR a new fragment: the catalog does not say which, so
* `VoiceStreamService.mergeTranscriptText` accepts both (`completed` always carries the final text).
*/
text: string;
status: TranscriptStatus;
}
| { type: 'sources'; turn_ref: string; tool_call_id: string; sources: VoiceSource[] }
| { type: 'turn_interrupted'; turn_ref: string; cancelled_tool_call_ids: string[] }
| {
type: 'error';
turn_ref?: string;
error: { code: string; message: string; request_id?: string; retryable: boolean };
};
export interface VoiceMessage {
/** `${turn_ref}:${role}` */
id: string;
turnRef: string;
role: 'user' | 'assistant';
text: string;
/** false while the text is still being recognized / generated */
final: boolean;
/** assistant message cut short by the user speaking over it */
interrupted?: boolean;
/** retrieved documents that back this answer */
sources?: VoiceSource[];
}
export interface VoiceSessionEnd {
conversationId: string | null;
messages: VoiceMessage[];
/** User-facing (Persian) message when the session ended because of a failure. */
error?: string;
}
export interface VoiceStreamConfig {
/** API prefix. */
apiBase: string;
/** Origin of the API; '' = same origin as the app (required for the `rag_session` cookie handshake). */
apiOrigin: string;
/** Fixed by the contract: 16 kHz up, 24 kHz down, mono PCM16. */
inputSampleRate: number;
outputSampleRate: number;
frameMs: number;
connectTimeoutMs: number;
/** After playback drains without a `completed` assistant transcript, wait this long, then return to LISTENING. */
settleMs: number;
/** Folder (relative to <base href>) holding the two *.worklet.js files. */
workletBasePath: string;
}
export const DEFAULT_VOICE_STREAM_CONFIG: VoiceStreamConfig = {
apiBase: '/api/v1',
apiOrigin: '',
inputSampleRate: 16000,
outputSampleRate: 24000,
frameMs: 20,
connectTimeoutMs: 8000,
settleMs: 700,
workletBasePath: 'assets/worklets',
};
/** Override in app.config.ts: `{ provide: VOICE_STREAM_CONFIG, useValue: { ...DEFAULT_VOICE_STREAM_CONFIG, apiOrigin: 'https://api.example.com' } }` */
export const VOICE_STREAM_CONFIG = new InjectionToken<VoiceStreamConfig>('VOICE_STREAM_CONFIG', {
providedIn: 'root',
factory: () => DEFAULT_VOICE_STREAM_CONFIG,
});
@@ -0,0 +1,117 @@
import { InjectionToken, inject } from '@angular/core';
import { VOICE_STREAM_CONFIG, VoiceServerEvent } from './voice-stream.types';
export interface VoiceTransportHandlers {
onEvent(event: VoiceServerEvent): void;
onAudio(chunk: ArrayBuffer): void;
/** Only called for closes the client did not ask for. */
onClose(info: { clean: boolean; code: number; reason: string }): void;
}
export interface VoiceTransport {
connect(handlers: VoiceTransportHandlers): Promise<void>;
/** PCM16 mono 16 kHz frame. */
sendAudio(frame: ArrayBuffer): void;
close(): void;
}
/** Drop mic frames instead of queueing when the socket is this far behind (~0.5 MB ≈ 16 s of audio). */
const MAX_BUFFERED_BYTES = 512 * 1024;
/**
* Plain WebSocket. Authentication is the `rag_session` cookie sent automatically on the handshake,
* so the page must be served from the same site as the API. The contract has no client→server
* JSON messages: the client only sends binary audio frames.
*/
export class WebSocketVoiceTransport implements VoiceTransport {
private ws: WebSocket | null = null;
private closedByClient = false;
constructor(
private readonly url: string,
private readonly connectTimeoutMs: number,
) {}
connect(handlers: VoiceTransportHandlers): Promise<void> {
return new Promise<void>((resolve, reject) => {
const ws = new WebSocket(this.url);
ws.binaryType = 'arraybuffer';
this.ws = ws;
let opened = false;
const timer = setTimeout(() => {
reject(new Error('connect-timeout'));
this.close();
}, this.connectTimeoutMs);
ws.onopen = () => {
opened = true;
clearTimeout(timer);
resolve();
};
ws.onmessage = (event: MessageEvent) => {
if (typeof event.data === 'string') {
try {
handlers.onEvent(JSON.parse(event.data) as VoiceServerEvent);
} catch {
/* ignore malformed control frames */
}
} else if (event.data instanceof ArrayBuffer) {
handlers.onAudio(event.data);
}
};
ws.onerror = () => {
if (!opened) {
clearTimeout(timer);
reject(new Error('connect-failed'));
}
};
ws.onclose = (event: CloseEvent) => {
clearTimeout(timer);
if (!opened) {
reject(new Error('connect-failed'));
return;
}
if (!this.closedByClient) {
handlers.onClose({ clean: event.wasClean, code: event.code, reason: event.reason });
}
};
});
}
sendAudio(frame: ArrayBuffer): void {
const ws = this.ws;
if (ws?.readyState === WebSocket.OPEN && ws.bufferedAmount < MAX_BUFFERED_BYTES) {
ws.send(frame);
}
}
close(): void {
this.closedByClient = true;
const ws = this.ws;
this.ws = null;
if (!ws) return;
ws.onmessage = null;
ws.onerror = null;
try {
ws.close(1000);
} catch {
/* already closed */
}
}
}
/** Replace in tests, or to plug a different transport. */
export const VOICE_TRANSPORT_FACTORY = new InjectionToken<(url: string) => VoiceTransport>(
'VOICE_TRANSPORT_FACTORY',
{
providedIn: 'root',
factory: () => {
const config = inject(VOICE_STREAM_CONFIG);
return (url: string) => new WebSocketVoiceTransport(url, config.connectTimeoutMs);
},
},
);