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; /** 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 { return new Promise((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); }, }, );