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.
143 lines
4.7 KiB
TypeScript
143 lines
4.7 KiB
TypeScript
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');
|
|
}
|
|
} |