feat(voice): add session provider selection to the frontend

Pin provider choices to creation attempts, confirm session closure before switching and handle unavailable providers without fallback. Restore Settings navigation for non-admin users while preserving operation-level authorization.
This commit is contained in:
11linear11
2026-10-16 17:09:31 -04:00
parent 815191588c
commit a26c597d4f
7 changed files with 163 additions and 15 deletions
@@ -25,6 +25,10 @@ export class VoiceApiError extends Error {
}
}
export type VoiceProvider = 'openai' | 'local_s2s' | 'gemini';
export interface VoiceProviderOption { id: VoiceProvider; label: string; can_start: boolean; reason: string | null; }
export interface VoiceProvidersResponse { default_provider: VoiceProvider; connection_checked: boolean; providers: VoiceProviderOption[]; }
export interface MeResponse {
user: { id: string; username: string; role: string; organization_id: string };
csrf_token: string;
@@ -55,6 +59,7 @@ export interface ConversationResponse {
}
export interface VoiceSessionResponse {
provider?: VoiceProvider;
session_id: string;
conversation_id: string;
status: string;
@@ -84,8 +89,12 @@ export class VoiceApiService {
}
/** F01: capabilities (the UI must check `voice` before offering a call). */
configuration(): Promise<ConfigurationResponse> {
return this.send(this.http.get<ConfigurationResponse>(this.url('/configuration'), this.readOptions()));
configuration(provider?: VoiceProvider): Promise<ConfigurationResponse> {
return this.send(this.http.get<ConfigurationResponse>(this.url('/configuration') + (provider ? '?provider=' + encodeURIComponent(provider) : ''), this.readOptions()));
}
providers(): Promise<VoiceProvidersResponse> {
return this.send(this.http.get<VoiceProvidersResponse>(this.url('/voice/sessions/providers'), this.readOptions()));
}
/** C01: only `mode: "voice"` exists in the MVP. `clientRequestId` makes replays return the same conversation. */
@@ -104,11 +113,12 @@ export class VoiceApiService {
csrf: string,
conversationId: string,
clientRequestId: string,
provider?: VoiceProvider,
): Promise<VoiceSessionResponse> {
return this.send(
this.http.post<VoiceSessionResponse>(
this.url('/voice/sessions'),
{ conversation_id: conversationId, client_request_id: clientRequestId },
{ conversation_id: conversationId, client_request_id: clientRequestId, ...(provider ? { provider } : {}) },
this.writeOptions(csrf),
),
);
@@ -56,6 +56,7 @@ type TransportMock = Omit<VoiceTransport, 'connect' | 'sendAudio' | 'sendControl
describe('VoiceStreamService (backend handoff contract)', () => {
let service: VoiceStreamService;
let api: {
providers: ReturnType<typeof vi.fn>;
me: ReturnType<typeof vi.fn>;
configuration: ReturnType<typeof vi.fn>;
createConversation: ReturnType<typeof vi.fn>;
@@ -83,6 +84,10 @@ describe('VoiceStreamService (backend handoff contract)', () => {
engineClear = vi.fn();
api = {
providers: vi.fn().mockResolvedValue({ default_provider: 'openai', connection_checked: false, providers: [
{ id: 'openai', label: 'OpenAI', can_start: true, reason: null },
{ id: 'local_s2s', label: 'سیستم جدید', can_start: true, reason: null },
] }),
me: vi.fn().mockResolvedValue(ME),
configuration: vi.fn().mockResolvedValue(CONFIG),
createConversation: vi.fn().mockResolvedValue(CONVERSATION),
@@ -1067,4 +1072,49 @@ describe('VoiceStreamService (backend handoff contract)', () => {
expect(service.state()).toBe('LISTENING'); // completed turns finish immediately
});
});
it('pins the selected provider in each new creation attempt', async () => {
await service.loadProviders();
await startConnected();
expect(api.createVoiceSession.mock.calls[0][3]).toBe('openai');
api.pollVoiceSession.mockResolvedValue({ session_id: 'ses-1', status: 'closed' });
expect(await service.selectProvider('local_s2s')).toBe(true);
expect(service.isOpen()).toBe(false);
await startConnected();
expect(api.createVoiceSession.mock.calls[1][3]).toBe('local_s2s');
expect(api.createVoiceSession.mock.calls[1][2]).not.toBe(api.createVoiceSession.mock.calls[0][2]);
});
it('keeps provider and request ids when the previous close is unconfirmed', async () => {
await service.loadProviders();
await startConnected();
const previous = JSON.parse(sessionStorage.getItem('voice_creation_attempt')!);
api.pollVoiceSession.mockResolvedValue({ session_id: 'ses-1', status: 'connected' });
expect(await service.selectProvider('local_s2s')).toBe(false);
expect(service.selectedProvider()).toBe('openai');
expect(JSON.parse(sessionStorage.getItem('voice_creation_attempt')!)).toEqual(previous);
expect(service.providerChoiceError()).toBeTruthy();
api.pollVoiceSession.mockResolvedValue({ session_id: 'ses-1', status: 'closed' });
expect(await service.selectProvider('local_s2s')).toBe(true);
await startConnected();
expect(api.createVoiceSession.mock.calls[1][3]).toBe('local_s2s');
expect(api.createVoiceSession.mock.calls[1][2]).not.toBe(previous.sessionRequestId);
});
it('rejects unavailable choices without touching the current call', async () => {
await service.loadProviders();
await startConnected();
expect(await service.selectProvider('gemini')).toBe(false);
expect(service.isOpen()).toBe(true);
expect(api.closeVoiceSession).not.toHaveBeenCalled();
});
it('uses legacy default admission when an older backend has no provider discovery', async () => {
service.selectedProvider.set('openai');
api.providers.mockRejectedValue(new VoiceApiError(404, 'NOT_FOUND', 'missing'));
await service.loadProviders();
expect(service.selectedProvider()).toBeNull();
await startConnected();
expect(api.createVoiceSession.mock.calls[0][3]).toBeUndefined();
});
});
@@ -2,7 +2,7 @@ import { Injectable, NgZone, computed, inject, isDevMode, signal } from '@angula
import { Subject } from 'rxjs';
import { MicrophoneError } from '../microphone/microphone.service';
import { uuid } from '../../shared/utils/uuid';
import { VoiceApiError, VoiceApiService, VoiceSessionResponse } from './voice-api.service';
import { VoiceApiError, VoiceApiService, VoiceSessionResponse, VoiceProvider, VoiceProviderOption } from './voice-api.service';
import { VoiceAudioEngine, VoiceEngineError } from './voice-audio-engine.service';
import { VOICE_TRANSPORT_FACTORY, VoiceTransport } from './voice-transport';
import {
@@ -127,6 +127,10 @@ export class VoiceStreamService {
private readonly createTransport = inject(VOICE_TRANSPORT_FACTORY);
private readonly cues = inject(VoiceCueService);
readonly selectedProvider = signal<VoiceProvider | null>(null);
readonly providerOptions = signal<VoiceProviderOption[]>([]);
readonly providerChoiceError = signal('');
readonly providerSwitching = signal(false);
readonly state = signal<VoiceStreamState>('IDLE');
readonly connection = signal<VoiceConnection>('disconnected');
readonly messages = signal<VoiceMessage[]>([]);
@@ -177,6 +181,7 @@ export class VoiceStreamService {
constructor() {
this.attempt = loadPersistedAttempt();
this.selectedProvider.set(this.attempt?.provider ?? null);
// 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.
@@ -188,7 +193,59 @@ export class VoiceStreamService {
// ---- public API -----------------------------------------------------------
async loadProviders(): Promise<void> {
try {
const result = await this.api.providers();
this.providerOptions.set(result.providers.filter(row => row.id !== 'gemini' || row.can_start || row.id === result.default_provider));
this.providerChoiceError.set('');
if (!this.isOpen() && !this.attempt && !this.selectedProvider()) {
this.selectedProvider.set(result.default_provider);
}
} catch (err) {
if (err instanceof VoiceApiError && err.status === 404 && !this.attempt && !this.isOpen()) {
this.selectedProvider.set(null);
}
this.providerChoiceError.set('فهرست ارائه‌دهندگان دریافت نشد؛ انتخاب پیش‌فرض سرویس برقرار است.');
}
}
async selectProvider(provider: VoiceProvider): Promise<boolean> {
if (this.providerSwitching()) return false;
if (provider === this.selectedProvider()) return true;
if (!this.providerOptions().some(row => row.id === provider && row.can_start)) return false;
this.providerSwitching.set(true);
this.providerChoiceError.set('');
const previous = this.attempt;
try {
await this.close();
// Changing provider must never discard an ambiguous reservation or reuse
// its request ids with different arguments. Require a terminal server row.
if (previous) {
if (!previous.sessionId) throw new Error('Unresolved reservation');
const me = await this.api.me();
const status = await this.withTimeout(this.api.pollVoiceSession(me.csrf_token, previous.sessionId), CLOSE_WAIT_MS);
if (!status || !['closed', 'failed'].includes(status.status)) throw new Error('Close not confirmed');
}
if (previous && this.attempt === previous) {
this.attempt = null;
clearPersistedAttempt();
}
this.selectedProvider.set(provider);
return true;
} catch {
if (previous) { this.attempt = previous; persistAttempt(previous); }
this.providerChoiceError.set('پایان تماس قبلی تأیید نشد؛ ارائه‌دهنده تغییر نکرد.');
return false;
} finally {
this.providerSwitching.set(false);
}
}
async start(options: { title?: string } = {}): Promise<VoiceStartResult> {
if (this.providerSwitching()) return this.failure('cancelled', '');
if (this.attempt?.provider && this.selectedProvider() && this.attempt.provider !== this.selectedProvider()) {
return this.failure('api', 'ابتدا وضعیت تماس قبلی را مشخص کنید.');
}
if (this.isOpen()) return this.failure('cancelled', '');
if (!this.isSupported) return this.failure('unsupported', MESSAGES.unsupported);
@@ -214,7 +271,7 @@ export class VoiceStreamService {
this.connection.set('connecting');
// Reuse a persisted attempt (ambiguous outcome of a previous try); otherwise create one.
if (!this.attempt) this.attempt = newCreationAttempt();
if (!this.attempt) this.attempt = newCreationAttempt(this.selectedProvider());
persistAttempt(this.attempt);
// 1) microphone + worklets (needs the user gesture; shows the permission prompt)
@@ -242,7 +299,7 @@ export class VoiceStreamService {
const me = await this.api.me();
if (stale()) return this.failure('cancelled', '');
const configuration = await this.api.configuration();
const configuration = await this.api.configuration(this.attempt?.provider);
if (stale()) return this.failure('cancelled', '');
if (!configuration.capabilities.voice) {
return this.abortStart(session, { reason: 'unavailable', message: MESSAGES.voiceDisabled });
@@ -1204,7 +1261,7 @@ export class VoiceStreamService {
* replay — never new ids, never a blind retry of an unknown state.
*/
private async reserve(csrf: string, title: string): Promise<VoiceSessionResponse> {
const attempt = this.attempt ?? newCreationAttempt();
const attempt = this.attempt ?? newCreationAttempt(this.selectedProvider());
this.attempt = attempt;
let activeCsrf = csrf;
@@ -1238,6 +1295,7 @@ export class VoiceStreamService {
activeCsrf,
attempt.conversationId!,
attempt.sessionRequestId,
attempt.provider,
);
} catch (err) {
const refreshed = await this.refreshAfterCsrfFailure(err);
@@ -1254,6 +1312,7 @@ export class VoiceStreamService {
activeCsrf,
attempt.conversationId!,
attempt.sessionRequestId,
attempt.provider,
);
}
} else if (err instanceof VoiceApiError && err.code === 'LIVE_SESSION_BUSY') {
@@ -1358,12 +1417,14 @@ interface VoiceCreationAttempt {
conversationId: string | null;
sessionId: string | null;
streamPath: string | null;
provider?: VoiceProvider;
}
const ATTEMPT_STORAGE_KEY = 'voice_creation_attempt';
function newCreationAttempt(): VoiceCreationAttempt {
function newCreationAttempt(provider: VoiceProvider | null = null): VoiceCreationAttempt {
return {
...(provider ? { provider } : {}),
conversationRequestId: uuid(),
sessionRequestId: uuid(),
conversationId: null,