import { HttpClient, HttpErrorResponse, HttpHeaders } from '@angular/common/http'; import { Injectable, inject } from '@angular/core'; import { firstValueFrom, Observable } from 'rxjs'; import { uuid } from '../../shared/utils/uuid'; import { VOICE_STREAM_CONFIG, VoiceSessionStatus } from './voice-stream.types'; /** * The voice helper's HTTP deadline: a client timeout never means the server rolled back. * Generous on purpose — the UI runs against a remote backend through the dev-server proxy, * and the first call after a reload pays the proxy connection setup. */ const REQUEST_DEADLINE_MS = 15000; /** Error envelope from the contract: { 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 { revision: number; assistant_name: string; instruction: string; capabilities: { text: boolean; voice: boolean; captions: boolean; supported_upload_types?: string[]; max_upload_bytes?: number; max_pdf_pages?: number; }; } export interface ConversationResponse { id: string; mode: 'voice'; title?: string; status: string; access_epoch?: number; created_at?: string; } export interface VoiceSessionResponse { session_id: string; conversation_id: string; status: string; stream_path: string; expires_at: string; poll_url: string; } /** V02: status + safe diagnostics for a reserved/connected session. */ export interface VoiceSessionPollResponse extends VoiceSessionStatus { recent_tool_results?: unknown[]; } /** * Thin client for the endpoints the live voice call needs (A03, F01, C01, V01, V02, V03, V04). * Auth is the HttpOnly `rag_session` cookie (same-origin proxy); state-changing calls also need * `X-CSRF-Token`. C01/V01 are idempotent through their JSON `client_request_id`, never headers. */ @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 { return this.send(this.http.get(this.url('/me'), this.readOptions())); } /** F01: capabilities (the UI must check `voice` before offering a call). */ configuration(): Promise { return this.send(this.http.get(this.url('/configuration'), this.readOptions())); } /** C01: only `mode: "voice"` exists in the MVP. `clientRequestId` makes replays return the same conversation. */ createConversation(csrf: string, title: string, clientRequestId: string): Promise { return this.send( this.http.post( this.url('/conversations'), { client_request_id: clientRequestId, mode: 'voice', title }, this.writeOptions(csrf), ), ); } /** V01: reserves a live session; connect the WebSocket to the returned `stream_path`. */ createVoiceSession( csrf: string, conversationId: string, clientRequestId: string, ): Promise { return this.send( this.http.post( this.url('/voice/sessions'), { conversation_id: conversationId, client_request_id: clientRequestId }, this.writeOptions(csrf), ), ); } /** V02: status + safe diagnostics (no secrets). */ pollVoiceSession(csrf: string, sessionId: string): Promise { return this.send( this.http.get( this.url(`/voice/sessions/${encodeURIComponent(sessionId)}`), this.readOptions(), ), ); } /** * V03: reconcile a reservation by its C01/V01 `client_request_id` — used after an * ambiguous (timeout / network) reserve, or after a reload. Never opens a new provider * connection: `null` means the attempt was never reserved. */ getVoiceSessionByRequest(csrf: string, clientRequestId: string): Promise { return this.send( this.http .get( this.url(`/voice/sessions/by-request/${encodeURIComponent(clientRequestId)}`), this.readOptions(), ) .pipe(this.mapNotFoundToNull()), ); } /** V04: closes the session explicitly (no body). */ async closeVoiceSession(csrf: string, sessionId: string): Promise { await this.send( this.http.post( this.url(`/voice/sessions/${encodeURIComponent(sessionId)}/close`), {}, this.writeOptions(csrf), ), ); } /** `wss://…` URL for a V01 `stream_path` (same origin as the UI). */ 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 readOptions() { return { withCredentials: true, headers: new HttpHeaders({ 'X-Request-ID': uuid() }) }; } private writeOptions(csrf: string) { return { withCredentials: true, headers: new HttpHeaders({ 'X-CSRF-Token': csrf, 'X-Request-ID': uuid(), }), }; } private mapNotFoundToNull() { return (source: Observable): Observable => new Observable((observer) => { const sub = source.subscribe({ next: (value) => observer.next(value), error: (err: unknown) => { if (err instanceof HttpErrorResponse && err.status === 404) observer.next(null); else observer.error(err); observer.complete(); }, complete: () => observer.complete(), }); return () => sub.unsubscribe(); }); } private async send(request: Observable): Promise { try { return await firstValueFrom(this.withDeadline(request)); } catch (err) { throw this.toApiError(err); } } /** * A deadline that never aborts the request. * * `race()` is not usable here: when the timer wins, `race` unsubscribes the loser, so the * HttpClient would abort its XHR. An aborted XHR is reported by the browser as * "(canceled)" — with no status code at all — which is exactly what was observed for * `/api/v1/me`. It also makes a reserve ambiguous ("did the server create it?") instead of * letting it settle, which defeats the V03 reconciliation this flow is built around. * * Here the request subscription is deliberately kept alive: the UI still gets the timeout, * the XHR runs to completion, and a late response is simply discarded. */ private withDeadline(request: Observable): Observable { return new Observable((observer) => { let settled = false; const timer = setTimeout(() => { if (settled) return; settled = true; observer.error(new VoiceApiError(0, 'TIMEOUT', 'request-deadline')); }, REQUEST_DEADLINE_MS); request.subscribe({ next: (value) => { if (settled) return; settled = true; clearTimeout(timer); observer.next(value); }, error: (err: unknown) => { if (settled) return; settled = true; clearTimeout(timer); observer.error(this.toApiError(err)); }, complete: () => { if (settled) return; settled = true; clearTimeout(timer); observer.complete(); }, }); // Only the timer is torn down: the in-flight request is left to finish naturally. return () => clearTimeout(timer); }); } private toApiError(err: unknown): VoiceApiError { if (err instanceof VoiceApiError) return err; // deadline / already-normalized error if (err instanceof HttpErrorResponse) { const envelope = (err.error as { error?: Record } | 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'); } }