Compare commits
2
Commits
a26c597d4f
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
102ce9b909 | ||
|
|
3dddf1f12b |
@@ -6,7 +6,7 @@ import { AuthService } from '../services/auth/auth.service';
|
|||||||
import { VoiceStreamService } from '../services/voice-stream/voice-stream.service';
|
import { VoiceStreamService } from '../services/voice-stream/voice-stream.service';
|
||||||
import { ThemeService } from '../services/theme/theme.service';
|
import { ThemeService } from '../services/theme/theme.service';
|
||||||
|
|
||||||
/** Settings remain discoverable; document-management operations require admin authority. */
|
/** Navigation outside the assistant: document management is admin-only per the contract. */
|
||||||
const BASE_NAV_ITEMS: NavItem[] = [
|
const BASE_NAV_ITEMS: NavItem[] = [
|
||||||
{ icon: 'M12 5v14M5 12h14', label: 'چت جدید', route: '/' },
|
{ icon: 'M12 5v14M5 12h14', label: 'چت جدید', route: '/' },
|
||||||
{ icon: 'M4 4v16h16M8 20V11M12.5 20V6M17 20V9', label: 'گزارشات', route: '/reports' },
|
{ icon: 'M4 4v16h16M8 20V11M12.5 20V6M17 20V9', label: 'گزارشات', route: '/reports' },
|
||||||
@@ -53,8 +53,11 @@ export class LayoutComponent {
|
|||||||
|
|
||||||
/** The signed-in identity exactly as the server reported it. */
|
/** The signed-in identity exactly as the server reported it. */
|
||||||
readonly userName = computed(() => this.authService.currentUserSubject.value?.username ?? '');
|
readonly userName = computed(() => this.authService.currentUserSubject.value?.username ?? '');
|
||||||
/** The settings page handles role-specific controls; the server authorizes each operation. */
|
/** Hiding a nav entry is only cosmetic: every request is still authorized server-side. */
|
||||||
readonly navItems = signal<NavItem[]>(BASE_NAV_ITEMS);
|
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');
|
||||||
|
});
|
||||||
|
|
||||||
onProfile(): void {
|
onProfile(): void {
|
||||||
this.sidebarOpen.set(false);
|
this.sidebarOpen.set(false);
|
||||||
|
|||||||
@@ -330,8 +330,4 @@
|
|||||||
transition: none !important;
|
transition: none !important;
|
||||||
animation: 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,20 +37,6 @@
|
|||||||
|
|
||||||
<!-- composer: call bar (while a call runs) + the chat input -->
|
<!-- composer: call bar (while a call runs) + the chat input -->
|
||||||
<div class="composer">
|
<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()) {
|
@if (jumpVisible()) {
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
|
|||||||
@@ -17,7 +17,6 @@ import { Subscription } from 'rxjs';
|
|||||||
import { AiChatInputComponent } from '../../shared/ui/ai-chat-input/ai-chat-input.component';
|
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 { VoiceStreamPanelComponent } from '../../shared/ui/voice-stream-panel/voice-stream-panel.component';
|
||||||
import { VoiceTranscriptComponent } from '../../shared/ui/voice-transcript/voice-transcript.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 { VoiceStreamService } from '../../services/voice-stream/voice-stream.service';
|
||||||
import { ThemeService } from '../../services/theme/theme.service';
|
import { ThemeService } from '../../services/theme/theme.service';
|
||||||
|
|
||||||
@@ -61,16 +60,6 @@ export class HomePage implements OnInit, OnDestroy {
|
|||||||
readonly hasMessages = signal(false);
|
readonly hasMessages = signal(false);
|
||||||
readonly callOpen = this.voiceStream.isOpen;
|
readonly callOpen = this.voiceStream.isOpen;
|
||||||
readonly voiceMessages = this.voiceStream.messages;
|
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. */
|
/** Anything on screen that belongs in the chat column: text sent, a live call, or a finished call's transcript. */
|
||||||
readonly hasConversation = computed(
|
readonly hasConversation = computed(
|
||||||
@@ -94,7 +83,6 @@ export class HomePage implements OnInit, OnDestroy {
|
|||||||
private routerSubscription?: Subscription;
|
private routerSubscription?: Subscription;
|
||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
void this.voiceStream.loadProviders();
|
|
||||||
this.routerSubscription = this.router.events
|
this.routerSubscription = this.router.events
|
||||||
.pipe(filter((event) => event instanceof NavigationEnd))
|
.pipe(filter((event) => event instanceof NavigationEnd))
|
||||||
.subscribe((event: NavigationEnd) => {
|
.subscribe((event: NavigationEnd) => {
|
||||||
|
|||||||
@@ -484,7 +484,8 @@
|
|||||||
.documents-table th,
|
.documents-table th,
|
||||||
.documents-table td {
|
.documents-table td {
|
||||||
padding: 0.6rem 0.75rem;
|
padding: 0.6rem 0.75rem;
|
||||||
text-align: right;
|
/* Every column — labels and row content alike — is centred in the RTL table. */
|
||||||
|
text-align: center;
|
||||||
vertical-align: top;
|
vertical-align: top;
|
||||||
border-bottom: 1px solid var(--color-card-border);
|
border-bottom: 1px solid var(--color-card-border);
|
||||||
/* Fixed layout fits the card; wrap long tokens so a cell never widens the table. */
|
/* Fixed layout fits the card; wrap long tokens so a cell never widens the table. */
|
||||||
@@ -509,6 +510,7 @@
|
|||||||
*/
|
*/
|
||||||
.documents-actions {
|
.documents-actions {
|
||||||
align-items: flex-start;
|
align-items: flex-start;
|
||||||
|
justify-content: center;
|
||||||
flex-wrap: wrap;
|
flex-wrap: wrap;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -555,8 +555,8 @@
|
|||||||
</td>
|
</td>
|
||||||
<td class="px-3 py-2.5 align-top">
|
<td class="px-3 py-2.5 align-top">
|
||||||
@if (doc.status === 'ready' && !isReviewNeeded(doc) && isAdmin()) {
|
@if (doc.status === 'ready' && !isReviewNeeded(doc) && isAdmin()) {
|
||||||
@if (togglingDocId() === doc.id) {
|
@if (togglingDocId() === doc.id) {
|
||||||
<div class="flex items-center gap-1.5 text-xs text-[var(--text-muted)]">
|
<div class="flex items-center justify-center gap-1.5 text-xs text-[var(--text-muted)]">
|
||||||
<svg
|
<svg
|
||||||
class="w-3 h-3 animate-spin"
|
class="w-3 h-3 animate-spin"
|
||||||
viewBox="0 0 24 24"
|
viewBox="0 0 24 24"
|
||||||
|
|||||||
@@ -166,6 +166,26 @@ describe('SettingsPage — document filters', () => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('centres the documents table headers and row cells', () => {
|
||||||
|
// Regression: headers and cells both inherited the `text-align: right` of the
|
||||||
|
// RTL table, leaving the whole table visually skewed to one side.
|
||||||
|
const fixture = TestBed.createComponent(SettingsPage);
|
||||||
|
fixture.detectChanges();
|
||||||
|
const el = fixture.nativeElement as HTMLElement;
|
||||||
|
|
||||||
|
const headers = Array.from(el.querySelectorAll('.documents-table thead th'));
|
||||||
|
expect(headers.length).toBe(6);
|
||||||
|
for (const header of headers) {
|
||||||
|
expect(getComputedStyle(header).textAlign).toBe('center');
|
||||||
|
}
|
||||||
|
|
||||||
|
const cells = Array.from(el.querySelectorAll('.documents-table tbody td'));
|
||||||
|
expect(cells.length).toBe(6);
|
||||||
|
for (const cell of cells) {
|
||||||
|
expect(getComputedStyle(cell).textAlign).toBe('center');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
it('confirms before removing: the bin button opens a modal, cancel keeps the doc, confirm shows the MVP notice', () => {
|
it('confirms before removing: the bin button opens a modal, cancel keeps the doc, confirm shows the MVP notice', () => {
|
||||||
const fixture = TestBed.createComponent(SettingsPage);
|
const fixture = TestBed.createComponent(SettingsPage);
|
||||||
fixture.detectChanges();
|
fixture.detectChanges();
|
||||||
|
|||||||
@@ -120,7 +120,6 @@ describe('DocumentsService (backend handoff contract)', () => {
|
|||||||
|
|
||||||
const req = httpMock.expectOne('/api/v1/documents/doc-1/retry');
|
const req = httpMock.expectOne('/api/v1/documents/doc-1/retry');
|
||||||
expect(req.request.method).toBe('POST');
|
expect(req.request.method).toBe('POST');
|
||||||
expect(req.request.serializeBody()).toBeNull();
|
|
||||||
expect(req.request.headers.get('Idempotency-Key')).toBe('key-retry-1');
|
expect(req.request.headers.get('Idempotency-Key')).toBe('key-retry-1');
|
||||||
req.flush({ job_id: 'job-1', status: 'queued' }, { status: 202, statusText: 'Accepted' });
|
req.flush({ job_id: 'job-1', status: 'queued' }, { status: 202, statusText: 'Accepted' });
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -152,7 +152,7 @@ export class DocumentsService {
|
|||||||
): Observable<RetryResult> {
|
): Observable<RetryResult> {
|
||||||
return this.http.postRaw<RetryResult>(
|
return this.http.postRaw<RetryResult>(
|
||||||
`${API}/documents/${encodeURIComponent(documentId)}/retry`,
|
`${API}/documents/${encodeURIComponent(documentId)}/retry`,
|
||||||
null,
|
{},
|
||||||
{ headers: this.idempotencyHeaders(idempotencyKey), skipToast: true },
|
{ headers: this.idempotencyHeaders(idempotencyKey), skipToast: true },
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -25,10 +25,6 @@ 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 {
|
export interface MeResponse {
|
||||||
user: { id: string; username: string; role: string; organization_id: string };
|
user: { id: string; username: string; role: string; organization_id: string };
|
||||||
csrf_token: string;
|
csrf_token: string;
|
||||||
@@ -59,7 +55,6 @@ export interface ConversationResponse {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export interface VoiceSessionResponse {
|
export interface VoiceSessionResponse {
|
||||||
provider?: VoiceProvider;
|
|
||||||
session_id: string;
|
session_id: string;
|
||||||
conversation_id: string;
|
conversation_id: string;
|
||||||
status: string;
|
status: string;
|
||||||
@@ -89,12 +84,8 @@ export class VoiceApiService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** F01: capabilities (the UI must check `voice` before offering a call). */
|
/** F01: capabilities (the UI must check `voice` before offering a call). */
|
||||||
configuration(provider?: VoiceProvider): Promise<ConfigurationResponse> {
|
configuration(): Promise<ConfigurationResponse> {
|
||||||
return this.send(this.http.get<ConfigurationResponse>(this.url('/configuration') + (provider ? '?provider=' + encodeURIComponent(provider) : ''), this.readOptions()));
|
return this.send(this.http.get<ConfigurationResponse>(this.url('/configuration'), 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. */
|
/** C01: only `mode: "voice"` exists in the MVP. `clientRequestId` makes replays return the same conversation. */
|
||||||
@@ -113,12 +104,11 @@ export class VoiceApiService {
|
|||||||
csrf: string,
|
csrf: string,
|
||||||
conversationId: string,
|
conversationId: string,
|
||||||
clientRequestId: string,
|
clientRequestId: string,
|
||||||
provider?: VoiceProvider,
|
|
||||||
): Promise<VoiceSessionResponse> {
|
): Promise<VoiceSessionResponse> {
|
||||||
return this.send(
|
return this.send(
|
||||||
this.http.post<VoiceSessionResponse>(
|
this.http.post<VoiceSessionResponse>(
|
||||||
this.url('/voice/sessions'),
|
this.url('/voice/sessions'),
|
||||||
{ conversation_id: conversationId, client_request_id: clientRequestId, ...(provider ? { provider } : {}) },
|
{ conversation_id: conversationId, client_request_id: clientRequestId },
|
||||||
this.writeOptions(csrf),
|
this.writeOptions(csrf),
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -56,7 +56,6 @@ type TransportMock = Omit<VoiceTransport, 'connect' | 'sendAudio' | 'sendControl
|
|||||||
describe('VoiceStreamService (backend handoff contract)', () => {
|
describe('VoiceStreamService (backend handoff contract)', () => {
|
||||||
let service: VoiceStreamService;
|
let service: VoiceStreamService;
|
||||||
let api: {
|
let api: {
|
||||||
providers: ReturnType<typeof vi.fn>;
|
|
||||||
me: ReturnType<typeof vi.fn>;
|
me: ReturnType<typeof vi.fn>;
|
||||||
configuration: ReturnType<typeof vi.fn>;
|
configuration: ReturnType<typeof vi.fn>;
|
||||||
createConversation: ReturnType<typeof vi.fn>;
|
createConversation: ReturnType<typeof vi.fn>;
|
||||||
@@ -84,10 +83,6 @@ describe('VoiceStreamService (backend handoff contract)', () => {
|
|||||||
engineClear = vi.fn();
|
engineClear = vi.fn();
|
||||||
|
|
||||||
api = {
|
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),
|
me: vi.fn().mockResolvedValue(ME),
|
||||||
configuration: vi.fn().mockResolvedValue(CONFIG),
|
configuration: vi.fn().mockResolvedValue(CONFIG),
|
||||||
createConversation: vi.fn().mockResolvedValue(CONVERSATION),
|
createConversation: vi.fn().mockResolvedValue(CONVERSATION),
|
||||||
@@ -1072,49 +1067,4 @@ describe('VoiceStreamService (backend handoff contract)', () => {
|
|||||||
expect(service.state()).toBe('LISTENING'); // completed turns finish immediately
|
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 { Subject } from 'rxjs';
|
||||||
import { MicrophoneError } from '../microphone/microphone.service';
|
import { MicrophoneError } from '../microphone/microphone.service';
|
||||||
import { uuid } from '../../shared/utils/uuid';
|
import { uuid } from '../../shared/utils/uuid';
|
||||||
import { VoiceApiError, VoiceApiService, VoiceSessionResponse, VoiceProvider, VoiceProviderOption } from './voice-api.service';
|
import { VoiceApiError, VoiceApiService, VoiceSessionResponse } from './voice-api.service';
|
||||||
import { VoiceAudioEngine, VoiceEngineError } from './voice-audio-engine.service';
|
import { VoiceAudioEngine, VoiceEngineError } from './voice-audio-engine.service';
|
||||||
import { VOICE_TRANSPORT_FACTORY, VoiceTransport } from './voice-transport';
|
import { VOICE_TRANSPORT_FACTORY, VoiceTransport } from './voice-transport';
|
||||||
import {
|
import {
|
||||||
@@ -127,10 +127,6 @@ export class VoiceStreamService {
|
|||||||
private readonly createTransport = inject(VOICE_TRANSPORT_FACTORY);
|
private readonly createTransport = inject(VOICE_TRANSPORT_FACTORY);
|
||||||
private readonly cues = inject(VoiceCueService);
|
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 state = signal<VoiceStreamState>('IDLE');
|
||||||
readonly connection = signal<VoiceConnection>('disconnected');
|
readonly connection = signal<VoiceConnection>('disconnected');
|
||||||
readonly messages = signal<VoiceMessage[]>([]);
|
readonly messages = signal<VoiceMessage[]>([]);
|
||||||
@@ -181,7 +177,6 @@ export class VoiceStreamService {
|
|||||||
|
|
||||||
constructor() {
|
constructor() {
|
||||||
this.attempt = loadPersistedAttempt();
|
this.attempt = loadPersistedAttempt();
|
||||||
this.selectedProvider.set(this.attempt?.provider ?? null);
|
|
||||||
// A reload during a call leaves an un-reconciled reservation: reconcile with the
|
// 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
|
// 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.
|
// never auto-resumed — the user starts a fresh conversation explicitly.
|
||||||
@@ -193,59 +188,7 @@ export class VoiceStreamService {
|
|||||||
|
|
||||||
// ---- public API -----------------------------------------------------------
|
// ---- 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> {
|
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.isOpen()) return this.failure('cancelled', '');
|
||||||
if (!this.isSupported) return this.failure('unsupported', MESSAGES.unsupported);
|
if (!this.isSupported) return this.failure('unsupported', MESSAGES.unsupported);
|
||||||
|
|
||||||
@@ -271,7 +214,7 @@ export class VoiceStreamService {
|
|||||||
this.connection.set('connecting');
|
this.connection.set('connecting');
|
||||||
|
|
||||||
// Reuse a persisted attempt (ambiguous outcome of a previous try); otherwise create one.
|
// Reuse a persisted attempt (ambiguous outcome of a previous try); otherwise create one.
|
||||||
if (!this.attempt) this.attempt = newCreationAttempt(this.selectedProvider());
|
if (!this.attempt) this.attempt = newCreationAttempt();
|
||||||
persistAttempt(this.attempt);
|
persistAttempt(this.attempt);
|
||||||
|
|
||||||
// 1) microphone + worklets (needs the user gesture; shows the permission prompt)
|
// 1) microphone + worklets (needs the user gesture; shows the permission prompt)
|
||||||
@@ -299,7 +242,7 @@ export class VoiceStreamService {
|
|||||||
const me = await this.api.me();
|
const me = await this.api.me();
|
||||||
if (stale()) return this.failure('cancelled', '');
|
if (stale()) return this.failure('cancelled', '');
|
||||||
|
|
||||||
const configuration = await this.api.configuration(this.attempt?.provider);
|
const configuration = await this.api.configuration();
|
||||||
if (stale()) return this.failure('cancelled', '');
|
if (stale()) return this.failure('cancelled', '');
|
||||||
if (!configuration.capabilities.voice) {
|
if (!configuration.capabilities.voice) {
|
||||||
return this.abortStart(session, { reason: 'unavailable', message: MESSAGES.voiceDisabled });
|
return this.abortStart(session, { reason: 'unavailable', message: MESSAGES.voiceDisabled });
|
||||||
@@ -1261,7 +1204,7 @@ export class VoiceStreamService {
|
|||||||
* replay — never new ids, never a blind retry of an unknown state.
|
* replay — never new ids, never a blind retry of an unknown state.
|
||||||
*/
|
*/
|
||||||
private async reserve(csrf: string, title: string): Promise<VoiceSessionResponse> {
|
private async reserve(csrf: string, title: string): Promise<VoiceSessionResponse> {
|
||||||
const attempt = this.attempt ?? newCreationAttempt(this.selectedProvider());
|
const attempt = this.attempt ?? newCreationAttempt();
|
||||||
this.attempt = attempt;
|
this.attempt = attempt;
|
||||||
|
|
||||||
let activeCsrf = csrf;
|
let activeCsrf = csrf;
|
||||||
@@ -1295,7 +1238,6 @@ export class VoiceStreamService {
|
|||||||
activeCsrf,
|
activeCsrf,
|
||||||
attempt.conversationId!,
|
attempt.conversationId!,
|
||||||
attempt.sessionRequestId,
|
attempt.sessionRequestId,
|
||||||
attempt.provider,
|
|
||||||
);
|
);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
const refreshed = await this.refreshAfterCsrfFailure(err);
|
const refreshed = await this.refreshAfterCsrfFailure(err);
|
||||||
@@ -1312,7 +1254,6 @@ export class VoiceStreamService {
|
|||||||
activeCsrf,
|
activeCsrf,
|
||||||
attempt.conversationId!,
|
attempt.conversationId!,
|
||||||
attempt.sessionRequestId,
|
attempt.sessionRequestId,
|
||||||
attempt.provider,
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
} else if (err instanceof VoiceApiError && err.code === 'LIVE_SESSION_BUSY') {
|
} else if (err instanceof VoiceApiError && err.code === 'LIVE_SESSION_BUSY') {
|
||||||
@@ -1417,14 +1358,12 @@ interface VoiceCreationAttempt {
|
|||||||
conversationId: string | null;
|
conversationId: string | null;
|
||||||
sessionId: string | null;
|
sessionId: string | null;
|
||||||
streamPath: string | null;
|
streamPath: string | null;
|
||||||
provider?: VoiceProvider;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const ATTEMPT_STORAGE_KEY = 'voice_creation_attempt';
|
const ATTEMPT_STORAGE_KEY = 'voice_creation_attempt';
|
||||||
|
|
||||||
function newCreationAttempt(provider: VoiceProvider | null = null): VoiceCreationAttempt {
|
function newCreationAttempt(): VoiceCreationAttempt {
|
||||||
return {
|
return {
|
||||||
...(provider ? { provider } : {}),
|
|
||||||
conversationRequestId: uuid(),
|
conversationRequestId: uuid(),
|
||||||
sessionRequestId: uuid(),
|
sessionRequestId: uuid(),
|
||||||
conversationId: null,
|
conversationId: null,
|
||||||
|
|||||||
Reference in New Issue
Block a user