import { Injectable, NgZone, computed, inject, signal } from '@angular/core'; import { Subject } from 'rxjs'; import { MicrophoneError } from '../microphone/microphone.service'; import { VoiceApiError, VoiceApiService, VoiceSessionResponse } 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'; import { VoiceCueService } from './voice-cue.service'; export type VoiceStartFailure = | 'cancelled' | 'unsupported' | 'mic' | 'engine' | 'auth' | 'unavailable' | 'api' | 'connect' | 'overflow'; export type VoiceStartResult = | { ok: true } | { ok: false; reason: VoiceStartFailure; message: string }; type TranscriptEvent = Extract; type SourcesEvent = Extract; type ErrorEvent = Extract; /** * Options for the single per-session cleanup (`teardown`). One cleanup runs per session and * is shared by overflow, server error, socket close, manual Stop, unmount and start aborts. */ interface TeardownOptions { /** User-facing (Persian) failure message carried on sessionEnded$. */ error?: string; /** Machine-readable cause (e.g. `ws close 1006`) carried on sessionEnded$. */ detail?: string; /** * Intentional stop: final progress → V04 → release, the order the contract requires. * `false` (default) releases local resources immediately and sends V04 best-effort — * used for unmount / start-abort / page-leave, where instant release matters more. */ ordered?: boolean; /** Send V04 /close for this session (default true). */ closeRemote?: boolean; /** Emit sessionEnded$ if the call reached connected (default true). */ emitEnded?: boolean; /** Keep the persisted creation attempt (ambiguous reserve / page-leave). Default false. */ keepAttempt?: boolean; } const MESSAGES = { unsupported: 'گفتگوی صوتی در این مرورگر پشتیبانی نمی‌شود (اتصال امن HTTPS و مرورگر جدید لازم است).', micDenied: 'دسترسی به میکروفون رد شد. اجازه‌ی دسترسی را در تنظیمات مرورگر فعال کنید.', micUnavailable: 'میکروفونی پیدا نشد یا در حال استفاده‌ی برنامه‌ی دیگری است.', micLost: 'اتصال میکروفون قطع شد و گفتگو پایان یافت.', engine: 'راه‌اندازی پردازشگر صوتی ناموفق بود. صفحه را دوباره بارگذاری کنید.', auth: 'نشست شما منقضی شده است. دوباره وارد شوید.', voiceDisabled: 'گفتگوی صوتی برای این سامانه فعال نیست.', rateLimited: 'تعداد درخواست‌ها زیاد است. کمی بعد دوباره تلاش کنید.', unavailable: 'سرویس موقتاً در دسترس نیست. کمی بعد دوباره تلاش کنید.', sessionUnusable: 'نشست صوتی بسته شده است. گفتگوی جدیدی شروع کنید.', api: 'شروع گفتگوی صوتی ناموفق بود. دوباره تلاش کنید.', connect: 'اتصال به سرور صوتی برقرار نشد. دوباره تلاش کنید.', badFormat: 'فرمت صدای سرور با برنامه سازگار نیست.', overflow: 'حجم صدای در حال پخش از محدودهٔ مجاز گذشت و گفتگو به‌طور ایمن پایان یافت.', sendOverflow: 'حجم صدای ارسالی از محدودهٔ مجاز گذشت و گفتگو به‌طور ایمن پایان یافت.', disconnected: 'ارتباط با سرور قطع شد و گفتگو پایان یافت.', server: 'سرور گفتگوی صوتی با خطا مواجه شد.', contextRevoked: 'محتوای دانش تغییر کرده و مکالمهٔ قبلی دیگر معتبر نیست. گفتگوی جدیدی شروع کنید.', stale: 'مکالمهٔ قبلی منقضی شده است. گفتگوی جدیدی شروع کنید.', 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; /** Longest wait for the worklet's final playback report when closing a call. */ const FINAL_PROGRESS_WAIT_MS = 300; /** Longest wait for V04 /close before releasing local resources anyway (the POST keeps running). */ const CLOSE_WAIT_MS = 3000; /** * One live voice call against the backend handoff contract (§7–§9): * * mic ─▶ engine ─▶ PCM16 24 kHz frames ─▶ WSS ─▶ server * server ─▶ session_ready / user_speech_started / transcript / sources / * audio_started / audio_ended / turn_interrupted / error (JSON) * ─▶ PCM16 24 kHz audio (binary) ─▶ engine playback * client ─▶ playback_progress (the only JSON control message, cumulative played_ms) * * Start: mic permission → GET /me (CSRF) → POST /conversations → POST /voice/sessions * → WSS stream_path → `session_ready`. * End: final playback progress → V04 close → close the socket, stop the audio. * * Barge-in is decided by the server: it sends `turn_interrupted` and the client flushes * playback. The contract has no other client→server JSON message. * * Ambiguous C01/V01 outcomes (timeout / network) are reconciled with the SAME * `client_request_id` pair — replayed via V03 or the identical request — never with new * ids, so a second conversation/session is never created. The attempt is kept in * sessionStorage (ids and paths only, no secrets) so a reload can reconcile first. */ @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); private readonly cues = inject(VoiceCueService); readonly state = signal('IDLE'); readonly connection = signal('disconnected'); readonly messages = signal([]); readonly muted = signal(false); /** Non-fatal, retryable server error to show as a banner (e.g. SEARCH_TIMEOUT). */ readonly streamError = signal(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(); private transport: VoiceTransport | null = null; private remote: { sessionId: string; conversationId: string; csrf: string } | null = null; /** Single-flight guard: at most one cleanup runs per active session (one /close each). */ private cleanupPromise: Promise | null = null; private session = 0; private streaming = false; private turnEnded = false; private audioGenerationDone = false; // server finished sending this audio_ref's frames private interruptTimer: ReturnType | null = null; private settleTimer: ReturnType | null = null; private errorTimer: ReturnType | null = null; private readyWaiter: { resolve: () => void; reject: (error: Error) => void; timer: ReturnType; } | null = null; private lastConversationId: string | null = null; /** Creation attempt: stable client request ids + the ids/paths the server returned. */ private attempt: VoiceCreationAttempt | null = null; /** Latest cumulative played_ms actually consumed by the worklet, per server audio_ref. */ private readonly playedMsByRef = new Map(); private currentAudioRef: string | null = null; private progressWaiters: Array<() => void> = []; constructor() { this.attempt = loadPersistedAttempt(); // A reload during a call leaves an un-reconciled reservation: reconcile with the // server first (V02/V03), close what is still open, and drop the attempt. Media is // never auto-resumed — the user starts a fresh conversation explicitly. if (this.attempt) void this.recover(); // Leaving the page releases mic/worklet/AudioContext/WebSocket immediately. window.addEventListener('pagehide', this.onPageLeave); } // ---- public API ----------------------------------------------------------- async start(options: { title?: string } = {}): Promise { 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.cleanupPromise = null; this.resetTurnFlags(); this.lastConversationId = null; this.currentAudioRef = null; this.playedMsByRef.clear(); this.state.set('IDLE'); this.connection.set('connecting'); // Reuse a persisted attempt (ambiguous outcome of a previous try); otherwise create one. if (!this.attempt) this.attempt = newCreationAttempt(); persistAttempt(this.attempt); // 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)), onPlaybackProgress: (audioRef, playedMs) => this.ngZone.run(() => this.onPlaybackProgress(audioRef, playedMs)), onPlaybackOverflow: () => this.ngZone.run(() => this.failSession(MESSAGES.overflow, session)), }); } catch (err) { return this.abortStart(session, this.mapEngineError(err)); } if (stale()) { if (!this.isOpen()) this.engine.stop(); return this.failure('cancelled', ''); } // 2) REST: identity/CSRF → capabilities → conversation → voice session let voiceSession: VoiceSessionResponse; 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 }); } voiceSession = await this.reserve(me.csrf_token, options.title ?? MESSAGES.conversationTitle); if (stale()) { this.closeRemote({ sessionId: voiceSession.session_id, csrf: me.csrf_token }); this.attempt = null; clearPersistedAttempt(); return this.failure('cancelled', ''); } } catch (err) { if (stale()) return this.failure('cancelled', ''); // An ambiguous reserve outcome (timeout / network / 5xx) keeps the attempt: the // next start reconciles it with the same client_request_ids instead of creating a // second conversation/session. A definitive failure (4xx) drops it. const keepAttempt = err instanceof VoiceApiError && this.isAmbiguous(err); return this.abortStart(session, this.mapApiError(err), keepAttempt); } this.remote = { sessionId: voiceSession.session_id, conversationId: voiceSession.conversation_id, csrf: this.lastCsrf, }; this.lastConversationId = voiceSession.conversation_id; // 3) WebSocket (created outside the zone so socket events don't trigger change detection) const transport = this.createTransport(this.api.streamUrl(voiceSession.stream_path)); 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: (info) => this.ngZone.run(() => this.failSession(MESSAGES.disconnected, session, this.describeSocketClose(info))), onOverflow: (which) => this.ngZone.run(() => // Playback queue overflow and capture/send overflow are different faults with // different causes; give each its own message instead of one shared string. this.failSession(which === 'send' ? MESSAGES.sendOverflow : MESSAGES.overflow, 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((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; // "You can speak now" — once per session, not per turn (a turn cue would be noise). this.cues.playReady(); return { ok: true }; } /** User ends the call. Safe to call at any time. */ end(): void { void this.close(); } /** * Intentional close: routes through the single per-session cleanup so final progress → * V04 /close → release happens exactly once and in the order the contract requires. * Concurrent callers (overflow / error / socket close / another Stop) reuse the same * cleanup and cannot send a second /close or a second teardown. */ async close(options: { error?: string; detail?: string } = {}): Promise { // Idle with no cleanup in flight: nothing to close. A persisted creation attempt from // an ambiguous reserve outcome is kept so the next start() reconciles it, not duplicates. if (this.connection() === 'disconnected' && !this.cleanupPromise) return; await this.teardown({ ordered: true, closeRemote: true, error: options.error, detail: options.detail, }); } /** * After media/context loss the user starts a brand-new conversation: the old * reservation is closed (V04) and its creation attempt is dropped, so the next * `start()` mints fresh client request ids. An ambiguous attempt that was never * connected is still reconciled with the same ids — never duplicated. */ async freshSession(title?: string): Promise { await this.close(); return this.start({ title }); } /** * Reconcile a persisted creation attempt with the server (V02/V03) and close whatever * reservation is still open. Media is never resumed automatically: recovery is not a * seamless reconnect. Returns whether an attempt existed. */ async recover(): Promise { const attempt = this.attempt; if (!attempt) return false; try { const me = await this.api.me(); // A call may have started while the request was in flight: never close its session. if (this.isOpen() || this.attempt !== attempt) return true; let sessionId = attempt.sessionId; if (!sessionId) { const existing = await this.api.getVoiceSessionByRequest(me.csrf_token, attempt.sessionRequestId); sessionId = existing?.session_id ?? null; } if (this.isOpen() || this.attempt !== attempt) return true; if (sessionId) { await this.api.closeVoiceSession(me.csrf_token, sessionId).catch(() => undefined); } } catch { /* the attempt is stale either way: drop it below */ } if (!this.isOpen() && this.attempt === attempt) { this.attempt = null; clearPersistedAttempt(); } return true; } /** V02: status + safe diagnostics of the current reservation (for the UI, no secrets). */ async poll(): Promise { const remote = this.remote; if (!remote) return null; return this.api.pollVoiceSession(remote.csrf, remote.sessionId); } 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 a live call without emitting events. */ dispose(): void { this.rejectReady(); if (!this.isOpen()) return; // keep an ambiguous attempt for reconciliation void this.teardown({ ordered: false, closeRemote: true, emitEnded: false }); } // ---- 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.currentAudioRef); this.clearSettleTimer(); if (this.state() !== 'SPEAKING') { this.ngZone.run(() => { if (this.interruptTimer) { clearTimeout(this.interruptTimer); this.interruptTimer = null; } this.state.set('SPEAKING'); }); } } // ---- playback progress ------------------------------------------------------ private onPlaybackProgress(audioRef: string, playedMs: number): void { if (playedMs <= 0) return; // Keep the latest cumulative value per ref; the final report is sent from here too. this.playedMsByRef.set(audioRef, playedMs); this.sendPlaybackProgress(audioRef, playedMs); this.resolveProgressWaiters(); } /** * The only client→server JSON control message: cumulative REAL played milliseconds * for a server audio_ref, computed by the worklet from consumed samples. */ private sendPlaybackProgress(audioRef: string, playedMs: number): void { const transport = this.transport; if (!transport || playedMs <= 0) return; transport.sendControl({ type: 'playback_progress', audio_ref: audioRef, played_ms: playedMs }); } /** * Before closing a call, ask the worklet for the final played report of the active ref * (barge-in drops the queue, so the last 250 ms cadence may be stale). */ private reportFinalProgress(): Promise { const ref = this.currentAudioRef; const transport = this.transport; if (!ref || !transport || this.connection() !== 'connected') return Promise.resolve(); this.engine.clearPlayback(); // worklet answers with its final cumulative report return new Promise((resolve) => { const done = (): void => { clearTimeout(timer); resolve(); }; const timer = setTimeout(done, FINAL_PROGRESS_WAIT_MS); this.progressWaiters.push(done); }); } private resolveProgressWaiters(): void { const waiters = this.progressWaiters; this.progressWaiters = []; waiters.forEach((waiter) => waiter()); } // ---- 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 'user_speech_started': // A new server turn started; the transcript/sources of older turns stay untouched. break; case 'transcript': this.onTranscript(event); break; case 'sources': this.upsertSources(event); break; case 'audio_started': this.currentAudioRef = event.audio_ref; this.audioGenerationDone = false; // frames for this ref are now streaming in break; case 'audio_ended': // Generation finished: emit the worklet's deferred tail and drain what is buffered so // the ref's FINAL playback progress reaches its true duration (no phantom outstanding // sample the backend would read as a stall). This drives the drain on generation // completion, cooperating with — not depending solely on — the completed transcript. this.audioGenerationDone = true; this.engine.flushPlayback(); 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. Drain the queue only once generation has ended // (audio_ended); otherwise the tail would be finalized while audio is still streamed. this.turnEnded = true; if (this.audioGenerationDone) this.engine.flushPlayback(); } } /** Server-side barge-in: the user spoke over the assistant. */ private onTurnInterrupted(turnRef: string): void { this.engine.clearPlayback(); // the worklet posts the final progress for the active ref 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; // The server's `error` frame is the direct cause of a session ending here: below it // drives failSession → V04 /close. `code` + `request_id` alone hide the message and // any extra details, so log the whole frame. console.warn('VoiceStreamService: server error frame', event.error); // The old conversation/session is no longer usable: the user must start a fresh one // (Gemini interruption can also require ending the session entirely). if (code === 'CONTEXT_REVOKED' || code === 'CONVERSATION_STALE') { this.failSession(MESSAGES.contextRevoked, session); return; } if (code === 'LIVE_SESSION_UNUSABLE' || code === 'SESSION_CLOSED') { this.failSession(MESSAGES.sessionUnusable, session); return; } if (!retryable) { this.failSession(message || MESSAGES.server, session, `server error ${code}`); 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 this.insertTranscript(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 contract 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) */ 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) { // `available: false` means the excerpt is no longer valid: keep the reference for // the turn but hide its excerpt instead of showing revoked text. const normalized = source.available === false ? { ...source, excerpt: undefined } : source; const existing = sources.findIndex( (s) => s.source_ref === normalized.source_ref && s.chunk_id === normalized.chunk_id, ); if (existing === -1) sources.push(normalized); else sources[existing] = normalized; } const next = { ...current, sources }; if (index === -1) return this.insertTranscript(list, next); const copy = [...list]; copy[index] = next; return copy; }); } /** * Inserts a new transcript bubble so the invariant always holds: WITHIN a turn the user * request precedes the AI response, and turns keep their first-seen order. This matters when * an assistant partial/response for a turn arrives before that turn's user transcript (the * server streams transcripts per role and does not guarantee the user text lands first) — * a plain append would then show the AI answer above the user's question. */ private insertTranscript(list: VoiceMessage[], message: VoiceMessage): VoiceMessage[] { const roleRank = message.role === 'user' ? 0 : 1; // Stable turn order = the order turns first appear in the current list; a turn we have // not seen yet sorts after all existing ones. const turns: string[] = []; for (const m of list) if (!turns.includes(m.turnRef)) turns.push(m.turnRef); const turnRank = turns.includes(message.turnRef) ? turns.indexOf(message.turnRef) : turns.length; for (let i = 0; i < list.length; i++) { const existingTurn = turns.indexOf(list[i].turnRef); const existingRank = list[i].role === 'user' ? 0 : 1; const comesAfter = existingTurn > turnRank || (existingTurn === turnRank && existingRank > roleRank); if (comesAfter) return [...list.slice(0, i), message, ...list.slice(i)]; } return [...list, message]; } 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 ------------------------------------------------------------- /** * The `CloseEvent` on the WebSocket carries the server's code and reason. Dropping it * (as this handler used to) leaves a generic "disconnected" banner and no clue why the * stream died, so the cause of an early disconnect cannot be diagnosed at all. * * Codes that matter in practice: 1000 = server ended the call normally, 1006 = the * connection dropped with no close frame (proxy/network), 1008/1009 = policy violation * (the server rejected a frame we sent), 1011 = server-side error. */ private describeSocketClose(info: { clean: boolean; code: number; reason: string }): string { const reason = info.reason ? ` reason="${info.reason}"` : ''; const detail = `ws close ${info.code}${info.clean ? ' (clean)' : ''}${reason}`; console.warn(`VoiceStreamService: socket closed — ${detail}`); return detail; } private failSession(message: string, session: number, detail?: string): void { if (session !== this.session || !this.isOpen()) return; // `close()` runs the ordered single-flight cleanup (final progress → V04 → release) // and emits sessionEnded$ exactly once, carrying the first meaningful failure. The // `session`/isOpen guard above drops stale callbacks so an old session never ends a // newer one. void this.close({ error: message, detail }); } private abortStart( session: number, failure: { reason: VoiceStartFailure; message: string }, keepAttempt = false, ): VoiceStartResult { // Start-only failure: release immediately (unmount-style) and best-effort V04 for any // reservation that was made. Keep the attempt when it was an ambiguous reserve so the // next start() reconciles it with the same ids instead of duplicating. if (session === this.session) void this.teardown({ ordered: false, closeRemote: true, keepAttempt }); return this.failure(failure.reason, failure.message); } /** * The ONE cleanup per session. Every end path funnels through here: overflow, server * error, socket close, manual Stop, unmount, page-leave and start-abort. It is * single-flight (`cleanupPromise`) so concurrent triggers share one pass — one /close and * one resource release — and it marks the session stopping before any await, so stale * callbacks cannot end a newer session. */ private teardown(options: TeardownOptions = {}): Promise { const existing = this.cleanupPromise; if (existing) return existing; // a cleanup for the active session is already running const promise = this.performTeardown(this.session, options).finally(() => { if (this.cleanupPromise === promise) this.cleanupPromise = null; }); this.cleanupPromise = promise; return promise; } private async performTeardown(session: number, options: TeardownOptions): Promise { const wasConnected = this.connection() === 'connected'; const conversationId = this.remote?.conversationId ?? this.lastConversationId; const remote = this.remote; const superseded = (): boolean => this.session !== session + 1; // Stop admitting new media BEFORE any await. this.streaming = false; // "Call finished" — once per connected session, before local resources (including the // engine AudioContext) are released; every end path funnels through this single-flight // cleanup, so ordered and unordered teardown both trigger it exactly once. if (wasConnected) { this.cues.playEnd(); } const release = (): void => { // A newer session may have taken over during an await: never touch its resources. if (superseded()) return; this.releaseLocal(options); }; /** Drop all pending async work and supersede this session, so late callbacks are stale. */ const invalidate = (): void => { if (this.session === session) this.session = session + 1; this.resetTurnFlags(); this.rejectReady(); this.resolveProgressWaiters(); this.clearSettleTimer(); if (this.interruptTimer) { clearTimeout(this.interruptTimer); this.interruptTimer = null; } this.currentAudioRef = null; }; if (options.ordered) { try { // 1) final playback progress (bounded) — still needs ref + connected transport. await this.reportFinalProgress(); // 2) supersede the session, then V04 /close (bounded), then 3) release. invalidate(); if (options.closeRemote !== false && remote) { await this.withTimeout(this.api.closeVoiceSession(remote.csrf, remote.sessionId), CLOSE_WAIT_MS); } } catch { /* the session may already be closed/expired (e.g. 409 LIVE_SESSION_UNUSABLE) */ } finally { if (options.ordered) this.finalizeAll(); release(); } } else { // Unmount / start-abort / page-leave: invalidate + release immediately, then send V04 // best-effort in the background (it may not finish while the page is unloading). invalidate(); release(); if (options.closeRemote !== false && remote) { this.api.closeVoiceSession(remote.csrf, remote.sessionId).catch(() => { /* already closed / expired: nothing to do */ }); } } if (options.ordered && options.emitEnded !== false && wasConnected && !superseded()) { this.sessionEnded$.next({ conversationId, messages: this.messages(), error: options.error, detail: options.detail, }); } } /** Cancellable wait: resolve when `work` settles or after `ms`, whichever is first. The underlying request is left to finish. */ private withTimeout(work: Promise, ms: number): Promise { let timer: ReturnType | undefined; const timedOut = new Promise((resolve) => { timer = setTimeout(() => resolve(undefined), ms); }); return Promise.race([work.catch((): undefined => undefined), timedOut]).finally(() => clearTimeout(timer), ); } /** Release mic, worklets, AudioContext, socket and timers. Runs even if V04 failed. */ private releaseLocal(options: TeardownOptions): void { const transport = this.transport; this.transport = null; transport?.close(); this.engine.stop(); this.remote = null; this.streaming = false; // The reservation is over: drop the attempt so the next start() mints fresh request ids — // unless an ambiguous reserve / page-leave still needs the same ids replayed/reconciled. if (!options.keepAttempt) { this.attempt = null; clearPersistedAttempt(); } this.clearError(); this.connection.set('disconnected'); this.state.set('IDLE'); this.muted.set(false); } /** Best-effort one-off V04 for a reservation produced by a start() that was just superseded. */ 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 onPageLeave = (): void => { if (!this.isOpen()) return; // The attempt id/path stay in sessionStorage on purpose: the next page load reconciles // it with V02/V03 (V04 may not complete while unloading) before anything else. void this.teardown({ ordered: false, closeRemote: true, keepAttempt: true, emitEnded: false }); }; private resetTurnFlags(): void { this.turnEnded = false; this.audioGenerationDone = 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); } // ---- creation attempt / reservation ----------------------------------------- /** CSRF of the most recent `/me`; refreshed per attempt. */ private lastCsrf = ''; /** * C01 then V01 with the attempt's stable client request ids. Ambiguous outcomes * (timeout / network) are reconciled with the SAME ids: V03 first, then an identical * replay — never new ids, never a blind retry of an unknown state. */ private async reserve(csrf: string, title: string): Promise { const attempt = this.attempt ?? newCreationAttempt(); this.attempt = attempt; let activeCsrf = csrf; if (!attempt.conversationId) { try { const conversation = await this.api.createConversation( activeCsrf, title, attempt.conversationRequestId, ); attempt.conversationId = conversation.id; } catch (err) { const refreshed = await this.refreshAfterCsrfFailure(err); activeCsrf = refreshed ?? activeCsrf; if (!this.isAmbiguous(err) && !refreshed) throw err; // Replay the identical request: C01 is idempotent on client_request_id. const conversation = await this.api.createConversation( activeCsrf, title, attempt.conversationRequestId, ); attempt.conversationId = conversation.id; } persistAttempt(attempt); } if (!attempt.sessionId || !attempt.streamPath) { let voiceSession: VoiceSessionResponse | null = null; try { voiceSession = await this.api.createVoiceSession( activeCsrf, attempt.conversationId!, attempt.sessionRequestId, ); } catch (err) { const refreshed = await this.refreshAfterCsrfFailure(err); activeCsrf = refreshed ?? activeCsrf; if (this.isAmbiguous(err) || refreshed) { // Did the ambiguous V01 create a reservation? Reconcile before replaying. const existing = await this.api .getVoiceSessionByRequest(activeCsrf, attempt.sessionRequestId) .catch(() => null); if (existing?.stream_path) { voiceSession = existing; } else { voiceSession = await this.api.createVoiceSession( activeCsrf, attempt.conversationId!, attempt.sessionRequestId, ); } } else if (err instanceof VoiceApiError && err.code === 'LIVE_SESSION_BUSY') { // A session already exists for this request: reconcile instead of a second one. const existing = await this.api .getVoiceSessionByRequest(activeCsrf, attempt.sessionRequestId) .catch(() => null); if (existing?.stream_path) voiceSession = existing; else throw err; } else { throw err; } } attempt.sessionId = voiceSession!.session_id; attempt.streamPath = voiceSession!.stream_path; persistAttempt(attempt); } this.lastCsrf = activeCsrf; this.lastConversationId = attempt.conversationId; return { session_id: attempt.sessionId!, conversation_id: attempt.conversationId!, status: 'connecting', stream_path: attempt.streamPath!, expires_at: '', poll_url: '', }; } /** 403 CSRF_INVALID → read a fresh token from `/me` and allow one identical replay. */ private async refreshAfterCsrfFailure(err: unknown): Promise { if (!(err instanceof VoiceApiError) || err.code !== 'CSRF_INVALID') return null; try { const me = await this.api.me(); return me.csrf_token; } catch { return null; } } /** Timeout / network / 5xx: the outcome is unknown, so reconcile instead of assuming. */ private isAmbiguous(err: unknown): boolean { if (!(err instanceof VoiceApiError)) return true; return err.status === 0 || err.status === 408 || err.status >= 500; } // ---- 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 contract's error codes (handoff §10) 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 'CSRF_INVALID': return { reason: 'auth', message: MESSAGES.auth }; case 'RATE_LIMITED': return { reason: 'api', message: MESSAGES.rateLimited }; case 'CALIBRATION_REQUIRED': case 'DEPENDENCY_UNAVAILABLE': return { reason: 'unavailable', message: MESSAGES.unavailable }; case 'LIVE_SESSION_UNUSABLE': case 'CONTEXT_REVOKED': case 'CONVERSATION_STALE': return { reason: 'api', message: MESSAGES.stale }; 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 }; } } // --------------------------------------------------------------------------- // Creation-attempt persistence (ids and paths only — never cookies, CSRF or audio) // --------------------------------------------------------------------------- interface VoiceCreationAttempt { conversationRequestId: string; sessionRequestId: string; conversationId: string | null; sessionId: string | null; streamPath: string | null; } const ATTEMPT_STORAGE_KEY = 'voice_creation_attempt'; function newCreationAttempt(): VoiceCreationAttempt { return { conversationRequestId: crypto.randomUUID(), sessionRequestId: crypto.randomUUID(), conversationId: null, sessionId: null, streamPath: null, }; } function loadPersistedAttempt(): VoiceCreationAttempt | null { try { const raw = sessionStorage.getItem(ATTEMPT_STORAGE_KEY); if (!raw) return null; const parsed = JSON.parse(raw) as VoiceCreationAttempt; if (!parsed?.conversationRequestId || !parsed?.sessionRequestId) return null; return parsed; } catch { return null; } } function persistAttempt(attempt: VoiceCreationAttempt): void { try { sessionStorage.setItem(ATTEMPT_STORAGE_KEY, JSON.stringify(attempt)); } catch { /* storage unavailable (private mode): the attempt lives in memory only */ } } function clearPersistedAttempt(): void { try { sessionStorage.removeItem(ATTEMPT_STORAGE_KEY); } catch { /* storage unavailable: nothing to clear */ } }