Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a26c597d4f | ||
|
|
815191588c |
@@ -6,7 +6,7 @@ import { AuthService } from '../services/auth/auth.service';
|
||||
import { VoiceStreamService } from '../services/voice-stream/voice-stream.service';
|
||||
import { ThemeService } from '../services/theme/theme.service';
|
||||
|
||||
/** Navigation outside the assistant: document management is admin-only per the contract. */
|
||||
/** Settings remain discoverable; document-management operations require admin authority. */
|
||||
const BASE_NAV_ITEMS: NavItem[] = [
|
||||
{ icon: 'M12 5v14M5 12h14', label: 'چت جدید', route: '/' },
|
||||
{ icon: 'M4 4v16h16M8 20V11M12.5 20V6M17 20V9', label: 'گزارشات', route: '/reports' },
|
||||
@@ -53,11 +53,8 @@ export class LayoutComponent {
|
||||
|
||||
/** The signed-in identity exactly as the server reported it. */
|
||||
readonly userName = computed(() => this.authService.currentUserSubject.value?.username ?? '');
|
||||
/** Hiding a nav entry is only cosmetic: every request is still authorized server-side. */
|
||||
readonly navItems = computed<NavItem[]>(() => {
|
||||
const isAdmin = this.authService.currentUserSubject.value?.role === 'admin';
|
||||
return isAdmin ? BASE_NAV_ITEMS : BASE_NAV_ITEMS.filter((item) => item.route !== '/settings');
|
||||
});
|
||||
/** The settings page handles role-specific controls; the server authorizes each operation. */
|
||||
readonly navItems = signal<NavItem[]>(BASE_NAV_ITEMS);
|
||||
|
||||
onProfile(): void {
|
||||
this.sidebarOpen.set(false);
|
||||
|
||||
@@ -330,4 +330,8 @@
|
||||
transition: none !important;
|
||||
animation: none !important;
|
||||
}
|
||||
}
|
||||
}
|
||||
.voice-provider-choice { display: flex; flex-wrap: wrap; align-items: center; gap: .5rem; padding: .5rem 1rem; font-size: .85rem; }
|
||||
.voice-provider-choice select { font: inherit; color: inherit; background: var(--surface-color, transparent); border: 1px solid currentColor; border-radius: .5rem; padding: .3rem .6rem; }
|
||||
.voice-provider-choice small { opacity: .75; }
|
||||
.voice-provider-error { margin: .25rem 1rem; font-size: .8rem; }
|
||||
|
||||
@@ -37,6 +37,20 @@
|
||||
|
||||
<!-- composer: call bar (while a call runs) + the chat input -->
|
||||
<div class="composer">
|
||||
@if (providerOptions().length) {
|
||||
<div class="voice-provider-choice" dir="rtl">
|
||||
<label for="voice-provider">ارائهدهندهٔ صدا</label>
|
||||
<select id="voice-provider" [value]="selectedProvider() ?? ''" [disabled]="providerSwitching()" (change)="onProviderChange($event)">
|
||||
@if (!selectedProvider()) { <option value="">پیشفرض سرویس</option> }
|
||||
@for (provider of providerOptions(); track provider.id) {
|
||||
<option [value]="provider.id" [disabled]="!provider.can_start">{{ provider.label }}{{ provider.can_start ? '' : ' — فعلاً در دسترس نیست' }}</option>
|
||||
}
|
||||
</select>
|
||||
@if (callOpen()) { <small>تغییر ارائهدهنده تماس فعلی را پایان میدهد.</small> }
|
||||
</div>
|
||||
}
|
||||
@if (providerChoiceError()) { <p class="voice-provider-error" role="status">{{ providerChoiceError() }}</p> }
|
||||
|
||||
@if (jumpVisible()) {
|
||||
<button
|
||||
type="button"
|
||||
|
||||
@@ -17,6 +17,7 @@ import { Subscription } from 'rxjs';
|
||||
import { AiChatInputComponent } from '../../shared/ui/ai-chat-input/ai-chat-input.component';
|
||||
import { VoiceStreamPanelComponent } from '../../shared/ui/voice-stream-panel/voice-stream-panel.component';
|
||||
import { VoiceTranscriptComponent } from '../../shared/ui/voice-transcript/voice-transcript.component';
|
||||
import { VoiceProvider } from '../../services/voice-stream/voice-api.service';
|
||||
import { VoiceStreamService } from '../../services/voice-stream/voice-stream.service';
|
||||
import { ThemeService } from '../../services/theme/theme.service';
|
||||
|
||||
@@ -60,6 +61,16 @@ export class HomePage implements OnInit, OnDestroy {
|
||||
readonly hasMessages = signal(false);
|
||||
readonly callOpen = this.voiceStream.isOpen;
|
||||
readonly voiceMessages = this.voiceStream.messages;
|
||||
readonly providerOptions = this.voiceStream.providerOptions;
|
||||
readonly selectedProvider = this.voiceStream.selectedProvider;
|
||||
readonly providerSwitching = this.voiceStream.providerSwitching;
|
||||
readonly providerChoiceError = this.voiceStream.providerChoiceError;
|
||||
|
||||
async onProviderChange(event: Event): Promise<void> {
|
||||
const select = event.target as HTMLSelectElement;
|
||||
await this.voiceStream.selectProvider(select.value as VoiceProvider);
|
||||
select.value = this.selectedProvider() ?? "";
|
||||
}
|
||||
|
||||
/** Anything on screen that belongs in the chat column: text sent, a live call, or a finished call's transcript. */
|
||||
readonly hasConversation = computed(
|
||||
@@ -83,6 +94,7 @@ export class HomePage implements OnInit, OnDestroy {
|
||||
private routerSubscription?: Subscription;
|
||||
|
||||
constructor() {
|
||||
void this.voiceStream.loadProviders();
|
||||
this.routerSubscription = this.router.events
|
||||
.pipe(filter((event) => event instanceof NavigationEnd))
|
||||
.subscribe((event: NavigationEnd) => {
|
||||
|
||||
@@ -120,6 +120,7 @@ describe('DocumentsService (backend handoff contract)', () => {
|
||||
|
||||
const req = httpMock.expectOne('/api/v1/documents/doc-1/retry');
|
||||
expect(req.request.method).toBe('POST');
|
||||
expect(req.request.serializeBody()).toBeNull();
|
||||
expect(req.request.headers.get('Idempotency-Key')).toBe('key-retry-1');
|
||||
req.flush({ job_id: 'job-1', status: 'queued' }, { status: 202, statusText: 'Accepted' });
|
||||
});
|
||||
|
||||
@@ -152,7 +152,7 @@ export class DocumentsService {
|
||||
): Observable<RetryResult> {
|
||||
return this.http.postRaw<RetryResult>(
|
||||
`${API}/documents/${encodeURIComponent(documentId)}/retry`,
|
||||
{},
|
||||
null,
|
||||
{ headers: this.idempotencyHeaders(idempotencyKey), skipToast: true },
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
Reference in New Issue
Block a user