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.
1121 lines
41 KiB
TypeScript
1121 lines
41 KiB
TypeScript
import { provideZonelessChangeDetection } from '@angular/core';
|
||
import { TestBed } from '@angular/core/testing';
|
||
import { provideHttpClient } from '@angular/common/http';
|
||
import { provideRouter } from '@angular/router';
|
||
import { first } from 'rxjs';
|
||
import { vi } from 'vitest';
|
||
import { VoiceApiError, VoiceApiService } from './voice-api.service';
|
||
import { VoiceAudioEngine, VoiceEngineHandlers } from './voice-audio-engine.service';
|
||
import { VoiceStreamService } from './voice-stream.service';
|
||
import { VOICE_TRANSPORT_FACTORY, VoiceTransport, VoiceTransportHandlers } from './voice-transport';
|
||
import { PlaybackProgressMessage, VoiceServerEvent } from './voice-stream.types';
|
||
|
||
const ME = {
|
||
user: { id: 'u1', username: 'admin', role: 'admin', organization_id: 'o1' },
|
||
csrf_token: 'csrf-1',
|
||
expires_at: 'later',
|
||
};
|
||
const CONFIG = {
|
||
revision: 1,
|
||
assistant_name: 'دستیار',
|
||
instruction: '',
|
||
capabilities: { text: true, voice: true, captions: true },
|
||
};
|
||
const CONVERSATION = { id: 'conv-1', mode: 'voice' as const, status: 'active' };
|
||
const SESSION = {
|
||
session_id: 'ses-1',
|
||
conversation_id: 'conv-1',
|
||
status: 'reserved',
|
||
stream_path: '/api/v1/voice/sessions/ses-1/stream',
|
||
expires_at: 'later',
|
||
poll_url: '/api/v1/voice/sessions/ses-1',
|
||
};
|
||
const READY_EVENT: VoiceServerEvent = {
|
||
type: 'session_ready',
|
||
session_id: 'ses-1',
|
||
input_audio: { encoding: 'pcm_s16le', sample_rate: 24000, channels: 1 },
|
||
output_audio: { encoding: 'pcm_s16le', sample_rate: 24000, channels: 1 },
|
||
};
|
||
|
||
const OVERFLOW_MESSAGE = 'حجم صدای در حال پخش از محدودهٔ مجاز گذشت و گفتگو بهطور ایمن پایان یافت.';
|
||
const SEND_OVERFLOW_MESSAGE =
|
||
'حجم صدای ارسالی از محدودهٔ مجاز گذشت و گفتگو بهطور ایمن پایان یافت.';
|
||
|
||
/** Flush pending microtasks/timers so the service reaches a stable await point. */
|
||
const flush = (): Promise<void> => new Promise((resolve) => setTimeout(resolve, 5));
|
||
|
||
type Mock = ReturnType<typeof vi.fn>;
|
||
type TransportMock = Omit<VoiceTransport, 'connect' | 'sendAudio' | 'sendControl' | 'close'> & {
|
||
handlers: VoiceTransportHandlers | null;
|
||
connect: Mock;
|
||
sendAudio: Mock;
|
||
sendControl: Mock;
|
||
close: Mock;
|
||
};
|
||
|
||
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>;
|
||
createVoiceSession: ReturnType<typeof vi.fn>;
|
||
getVoiceSessionByRequest: ReturnType<typeof vi.fn>;
|
||
pollVoiceSession: ReturnType<typeof vi.fn>;
|
||
closeVoiceSession: ReturnType<typeof vi.fn>;
|
||
streamUrl: ReturnType<typeof vi.fn>;
|
||
};
|
||
let engineHandlers: VoiceEngineHandlers | null;
|
||
let transportHandlers: VoiceTransportHandlers | null;
|
||
let controls: PlaybackProgressMessage[];
|
||
let transportMock: TransportMock;
|
||
let engineStop: ReturnType<typeof vi.fn>;
|
||
let engineFlush: Mock;
|
||
let engineClear: Mock;
|
||
|
||
beforeEach(() => {
|
||
sessionStorage.clear();
|
||
engineHandlers = null;
|
||
transportHandlers = null;
|
||
controls = [];
|
||
engineStop = vi.fn();
|
||
engineFlush = vi.fn();
|
||
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),
|
||
createVoiceSession: vi.fn().mockResolvedValue(SESSION),
|
||
getVoiceSessionByRequest: vi.fn().mockResolvedValue(null),
|
||
pollVoiceSession: vi.fn().mockResolvedValue({ session_id: 'ses-1', status: 'connected' }),
|
||
closeVoiceSession: vi.fn().mockResolvedValue(undefined),
|
||
streamUrl: vi.fn().mockReturnValue('wss://ui.local/api/v1/voice/sessions/ses-1/stream'),
|
||
};
|
||
|
||
transportMock = {
|
||
handlers: null,
|
||
connect: vi.fn().mockImplementation((handlers: VoiceTransportHandlers) => {
|
||
transportHandlers = handlers;
|
||
transportMock.handlers = handlers;
|
||
return Promise.resolve();
|
||
}),
|
||
sendAudio: vi.fn(),
|
||
sendControl: vi
|
||
.fn()
|
||
.mockImplementation((message: PlaybackProgressMessage) => controls.push(message)),
|
||
close: vi.fn(),
|
||
};
|
||
|
||
TestBed.configureTestingModule({
|
||
providers: [
|
||
provideZonelessChangeDetection(),
|
||
provideHttpClient(),
|
||
provideRouter([]),
|
||
{ provide: VoiceApiService, useValue: api },
|
||
{
|
||
provide: VoiceAudioEngine,
|
||
useValue: {
|
||
isSupported: true,
|
||
start: vi.fn().mockImplementation((handlers: VoiceEngineHandlers) => {
|
||
engineHandlers = handlers;
|
||
return Promise.resolve();
|
||
}),
|
||
stop: engineStop,
|
||
setMuted: vi.fn(),
|
||
enqueuePlayback: vi.fn(),
|
||
clearPlayback: engineClear,
|
||
flushPlayback: engineFlush,
|
||
inputLevel: () => 0,
|
||
outputLevel: () => 0,
|
||
},
|
||
},
|
||
{ provide: VOICE_TRANSPORT_FACTORY, useFactory: () => () => transportMock },
|
||
],
|
||
});
|
||
service = TestBed.inject(VoiceStreamService);
|
||
});
|
||
|
||
/** Drives a full start() up to `connected`, emitting the server `session_ready`. */
|
||
async function startConnected(): Promise<void> {
|
||
const started = service.start();
|
||
await flush();
|
||
transportHandlers?.onEvent(READY_EVENT);
|
||
await started;
|
||
}
|
||
|
||
function firstEndedError(): Promise<string | undefined> {
|
||
return new Promise((resolve) =>
|
||
service.sessionEnded$.pipe(first()).subscribe((end) => resolve(end.error)),
|
||
);
|
||
}
|
||
|
||
it('creates conversation then voice session with two separate client request ids', async () => {
|
||
await startConnected();
|
||
|
||
expect(api.createConversation).toHaveBeenCalledTimes(1);
|
||
const [, , conversationRequestId] = api.createConversation.mock.calls[0];
|
||
expect(conversationRequestId).toMatch(/^[0-9a-f-]{36}$/);
|
||
|
||
expect(api.createVoiceSession).toHaveBeenCalledTimes(1);
|
||
const [, conversationId, sessionRequestId] = api.createVoiceSession.mock.calls[0];
|
||
expect(conversationId).toBe('conv-1');
|
||
expect(sessionRequestId).not.toBe(conversationRequestId); // the two ids are independent
|
||
expect(service.connection()).toBe('connected');
|
||
expect(service.state()).toBe('LISTENING');
|
||
});
|
||
|
||
it('rejects a session_ready whose audio format breaks the 24 kHz mono PCM16LE contract', async () => {
|
||
const started = service.start();
|
||
await flush();
|
||
transportHandlers?.onEvent({
|
||
type: 'session_ready',
|
||
session_id: 'ses-1',
|
||
input_audio: { encoding: 'pcm_s16le', sample_rate: 16000, channels: 1 },
|
||
output_audio: { encoding: 'pcm_s16le', sample_rate: 24000, channels: 1 },
|
||
});
|
||
const result = await started;
|
||
expect(result).toEqual({
|
||
ok: false,
|
||
reason: 'connect',
|
||
message: 'فرمت صدای سرور با برنامه سازگار نیست.',
|
||
});
|
||
});
|
||
|
||
it('reconciles an ambiguous V01 through V03 instead of creating a second session', async () => {
|
||
api.createVoiceSession
|
||
.mockRejectedValueOnce(new VoiceApiError(0, 'TIMEOUT', 'timeout'))
|
||
.mockResolvedValue(SESSION);
|
||
api.getVoiceSessionByRequest.mockResolvedValue(SESSION);
|
||
|
||
await startConnected();
|
||
|
||
expect(api.getVoiceSessionByRequest).toHaveBeenCalledTimes(1);
|
||
const requestedId = api.getVoiceSessionByRequest.mock.calls[0][1];
|
||
expect(typeof requestedId).toBe('string');
|
||
expect(api.createVoiceSession).toHaveBeenCalledTimes(1); // no blind duplicate create
|
||
expect(service.connection()).toBe('connected');
|
||
});
|
||
|
||
it('replays V01 with the same client_request_id when reconciliation finds nothing', async () => {
|
||
api.createVoiceSession
|
||
.mockRejectedValueOnce(new VoiceApiError(0, 'TIMEOUT', 'timeout'))
|
||
.mockResolvedValue(SESSION);
|
||
api.getVoiceSessionByRequest.mockResolvedValue(null);
|
||
|
||
await startConnected();
|
||
|
||
expect(api.createVoiceSession).toHaveBeenCalledTimes(2);
|
||
const firstId = api.createVoiceSession.mock.calls[0][2];
|
||
const secondId = api.createVoiceSession.mock.calls[1][2];
|
||
expect(secondId).toBe(firstId); // same attempt, same payload
|
||
});
|
||
|
||
it('keeps the creation attempt after an ambiguous reserve so the next start() reconciles', async () => {
|
||
api.createConversation.mockRejectedValue(new VoiceApiError(0, 'TIMEOUT', 'timeout'));
|
||
|
||
const first = await service.start();
|
||
expect(first.ok).toBe(false);
|
||
expect(sessionStorage.getItem('voice_creation_attempt')).toBeTruthy();
|
||
// The replay used the same ids, never a fresh uuid.
|
||
const firstId = api.createConversation.mock.calls[0][2];
|
||
const secondId = api.createConversation.mock.calls[1][2];
|
||
expect(secondId).toBe(firstId);
|
||
});
|
||
|
||
it('sends playback_progress with the cumulative played_ms reported by the worklet', async () => {
|
||
await startConnected();
|
||
|
||
transportHandlers?.onEvent({ type: 'audio_started', audio_ref: 'aud-1' });
|
||
engineHandlers?.onPlaybackProgress('aud-1', 120);
|
||
engineHandlers?.onPlaybackProgress('aud-1', 900);
|
||
|
||
expect(controls).toEqual([
|
||
{ type: 'playback_progress', audio_ref: 'aud-1', played_ms: 120 },
|
||
{ type: 'playback_progress', audio_ref: 'aud-1', played_ms: 900 },
|
||
]);
|
||
});
|
||
|
||
it('reports the final real played progress when the turn is interrupted', async () => {
|
||
await startConnected();
|
||
|
||
transportHandlers?.onEvent({
|
||
type: 'transcript',
|
||
turn_ref: 'turn-1',
|
||
role: 'assistant',
|
||
text: 'پاسخ',
|
||
status: 'partial',
|
||
});
|
||
transportHandlers?.onEvent({ type: 'audio_started', audio_ref: 'aud-2' });
|
||
engineHandlers?.onPlaybackProgress('aud-2', 300);
|
||
controls = [];
|
||
|
||
transportHandlers?.onEvent({ type: 'turn_interrupted', turn_ref: 'turn-1' });
|
||
// The worklet answers `clear` with its final cumulative report for the ref.
|
||
engineHandlers?.onPlaybackProgress('aud-2', 780);
|
||
|
||
expect(controls).toEqual([{ type: 'playback_progress', audio_ref: 'aud-2', played_ms: 780 }]);
|
||
expect(service.messages().find((m) => m.id === 'turn-1:assistant')?.interrupted).toBe(true);
|
||
});
|
||
|
||
it('ends safely with a failure when the bounded playback queue overflows', async () => {
|
||
await startConnected();
|
||
const ended = firstEndedError();
|
||
|
||
engineHandlers?.onPlaybackOverflow();
|
||
|
||
expect(await ended).toBe(OVERFLOW_MESSAGE);
|
||
expect(service.connection()).toBe('disconnected');
|
||
});
|
||
|
||
it('uses a distinct message for capture/send overflow vs playback overflow', async () => {
|
||
await startConnected();
|
||
const ended = firstEndedError();
|
||
|
||
transportHandlers?.onOverflow('send');
|
||
|
||
expect(await ended).toBe(SEND_OVERFLOW_MESSAGE);
|
||
expect(await ended).not.toBe(OVERFLOW_MESSAGE);
|
||
expect(service.connection()).toBe('disconnected');
|
||
});
|
||
|
||
it('concurrent overflow + socket close + Stop send one /close and one teardown', async () => {
|
||
await startConnected();
|
||
const ended = firstEndedError();
|
||
|
||
// Several end triggers race for the same session (the reported live failure).
|
||
engineHandlers?.onPlaybackOverflow(); // 1st → overflow error
|
||
engineHandlers?.onPlaybackOverflow(); // duplicate
|
||
transportHandlers?.onClose({ clean: false, code: 1006, reason: '' }); // socket close
|
||
service.end(); // manual Stop
|
||
|
||
expect(await ended).toBe(OVERFLOW_MESSAGE); // first meaningful error preserved
|
||
expect(api.closeVoiceSession).toHaveBeenCalledTimes(1); // V04 sent exactly once
|
||
expect(transportMock.close).toHaveBeenCalledTimes(1); // socket released once
|
||
expect(engineStop).toHaveBeenCalledTimes(1); // audio graph released once
|
||
expect(service.connection()).toBe('disconnected');
|
||
});
|
||
|
||
it('releases local resources even when V04 /close fails', async () => {
|
||
await startConnected();
|
||
api.closeVoiceSession.mockRejectedValueOnce(new Error('V04 boom'));
|
||
|
||
await service.close();
|
||
|
||
expect(api.closeVoiceSession).toHaveBeenCalledTimes(1);
|
||
expect(transportMock.close).toHaveBeenCalledTimes(1);
|
||
expect(engineStop).toHaveBeenCalledTimes(1);
|
||
expect(service.connection()).toBe('disconnected');
|
||
expect(sessionStorage.getItem('voice_creation_attempt')).toBeNull();
|
||
});
|
||
|
||
it('ignores stale callbacks: an old session cannot close or affect a new one', async () => {
|
||
await startConnected(); // session A
|
||
await service.close();
|
||
api.closeVoiceSession.mockClear();
|
||
engineStop.mockClear();
|
||
transportMock.close.mockClear();
|
||
|
||
// Late callbacks captured for session A arrive after A already ended.
|
||
engineHandlers?.onPlaybackOverflow();
|
||
transportHandlers?.onClose({ clean: false, code: 1006, reason: '' });
|
||
await flush();
|
||
expect(api.closeVoiceSession).not.toHaveBeenCalled();
|
||
expect(service.connection()).toBe('disconnected');
|
||
|
||
// A brand-new session is independent and closes exactly once on its own.
|
||
await startConnected(); // session B
|
||
expect(service.connection()).toBe('connected');
|
||
api.closeVoiceSession.mockClear();
|
||
await service.close();
|
||
expect(api.closeVoiceSession).toHaveBeenCalledTimes(1);
|
||
});
|
||
|
||
it('keeps listening closed across an open-audio underrun and ignores a stale seal', async () => {
|
||
await startConnected();
|
||
transportHandlers?.onEvent({ type: 'audio_started', audio_ref: 'aud-1', turn_ref: 'turn-1' });
|
||
transportHandlers?.onAudio(new ArrayBuffer(9600));
|
||
engineHandlers?.onPlaybackIdle('aud-1');
|
||
|
||
vi.useFakeTimers();
|
||
try {
|
||
vi.advanceTimersByTime(2000);
|
||
} finally {
|
||
vi.useRealTimers();
|
||
}
|
||
expect(service.state()).toBe('SPEAKING');
|
||
|
||
transportHandlers?.onEvent({
|
||
type: 'transcript',
|
||
turn_ref: 'turn-1',
|
||
role: 'assistant',
|
||
text: 'complete text',
|
||
status: 'completed',
|
||
});
|
||
engineHandlers?.onPlaybackIdle('aud-1');
|
||
transportHandlers?.onEvent({ type: 'audio_ended', audio_ref: 'stale', turn_ref: 'turn-0' });
|
||
expect(service.state()).toBe('SPEAKING');
|
||
expect(engineFlush).not.toHaveBeenCalled();
|
||
|
||
transportHandlers?.onEvent({ type: 'audio_ended', audio_ref: 'aud-1', turn_ref: 'turn-1' });
|
||
engineHandlers?.onPlaybackIdle('stale');
|
||
expect(service.state()).toBe('SPEAKING');
|
||
engineHandlers?.onPlaybackIdle('aud-1');
|
||
expect(service.state()).toBe('LISTENING');
|
||
});
|
||
it('does not reset received bytes on a duplicate audio start', async () => {
|
||
await startConnected();
|
||
transportHandlers?.onEvent({ type: 'audio_started', audio_ref: 'aud-1', turn_ref: 'turn-1' });
|
||
transportHandlers?.onAudio(new ArrayBuffer(9600));
|
||
transportHandlers?.onEvent({ type: 'audio_started', audio_ref: 'aud-1', turn_ref: 'turn-1' });
|
||
const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
|
||
try {
|
||
transportHandlers?.onEvent({
|
||
type: 'audio_ended',
|
||
audio_ref: 'aud-1',
|
||
turn_ref: 'turn-1',
|
||
sent_bytes: 9600,
|
||
});
|
||
expect(warn).not.toHaveBeenCalledWith('Voice audio delivery mismatch', expect.anything());
|
||
} finally {
|
||
warn.mockRestore();
|
||
}
|
||
});
|
||
it('drains on audio_ended so the ref reaches its true final progress (not solely on transcript)', async () => {
|
||
await startConnected();
|
||
transportHandlers?.onEvent({ type: 'audio_started', audio_ref: 'aud-1' });
|
||
|
||
// A `completed` transcript that arrives BEFORE audio_ended must NOT flush the queue: the
|
||
// audio is still streaming, so finalizing the tail now would be premature.
|
||
transportHandlers?.onEvent({
|
||
type: 'transcript',
|
||
turn_ref: 'turn-1',
|
||
role: 'assistant',
|
||
text: '…',
|
||
status: 'completed',
|
||
});
|
||
expect(engineFlush).not.toHaveBeenCalled();
|
||
|
||
// audio_ended (generation complete) drives the drain: the worklet emits the deferred
|
||
// tail and plays out, so playback progress retires the whole ref before the backend's
|
||
// stall timeout — this is the fix for the premature LIVE_BUFFER_OVERFLOW termination.
|
||
transportHandlers?.onEvent({ type: 'audio_ended', audio_ref: 'aud-1' });
|
||
expect(engineFlush).toHaveBeenCalledTimes(1);
|
||
|
||
// A duplicate final transcript does not flush the sealed reference again.
|
||
transportHandlers?.onEvent({
|
||
type: 'transcript',
|
||
turn_ref: 'turn-1',
|
||
role: 'assistant',
|
||
text: '…',
|
||
status: 'completed',
|
||
});
|
||
expect(engineFlush).toHaveBeenCalledTimes(1);
|
||
});
|
||
|
||
it('requires a fresh conversation after CONTEXT_REVOKED and drops the old attempt', async () => {
|
||
await startConnected();
|
||
const ended = firstEndedError();
|
||
|
||
transportHandlers?.onEvent({
|
||
type: 'error',
|
||
error: { code: 'CONTEXT_REVOKED', message: 'context revoked', retryable: false },
|
||
});
|
||
|
||
expect(await ended).toBe(
|
||
'محتوای دانش تغییر کرده و مکالمهٔ قبلی دیگر معتبر نیست. گفتگوی جدیدی شروع کنید.',
|
||
);
|
||
expect(sessionStorage.getItem('voice_creation_attempt')).toBeNull();
|
||
expect(service.connection()).toBe('disconnected');
|
||
});
|
||
|
||
it('keeps a retryable server error non-fatal (the session stays usable)', async () => {
|
||
await startConnected();
|
||
|
||
transportHandlers?.onEvent({
|
||
type: 'error',
|
||
error: { code: 'SEARCH_TIMEOUT', message: 'جستوجو دیر شد', retryable: true },
|
||
});
|
||
|
||
expect(service.streamError()).toBe('جستوجو دیر شد');
|
||
expect(service.connection()).toBe('connected');
|
||
});
|
||
|
||
it('hides excerpts of sources the server marks unavailable', async () => {
|
||
await startConnected();
|
||
|
||
transportHandlers?.onEvent({
|
||
type: 'sources',
|
||
turn_ref: 'turn-9',
|
||
sources: [
|
||
{
|
||
source_ref: 'src-1',
|
||
document_id: 'doc-1',
|
||
chunk_id: 'chunk-1',
|
||
title: 'سند آزمون',
|
||
excerpt: 'متن منقضیشده',
|
||
available: false,
|
||
},
|
||
],
|
||
});
|
||
|
||
const assistant = service.messages().find((m) => m.id === 'turn-9:assistant');
|
||
expect(assistant?.sources?.[0].available).toBe(false);
|
||
expect(assistant?.sources?.[0].excerpt).toBeUndefined();
|
||
});
|
||
|
||
it('marks partial then completed transcripts final', async () => {
|
||
await startConnected();
|
||
|
||
transportHandlers?.onEvent({
|
||
type: 'transcript',
|
||
turn_ref: 't1',
|
||
role: 'assistant',
|
||
text: 'سلام',
|
||
status: 'partial',
|
||
});
|
||
transportHandlers?.onEvent({
|
||
type: 'transcript',
|
||
turn_ref: 't1',
|
||
role: 'assistant',
|
||
text: 'سلام و خوب',
|
||
status: 'partial',
|
||
});
|
||
transportHandlers?.onEvent({
|
||
type: 'transcript',
|
||
turn_ref: 't1',
|
||
role: 'assistant',
|
||
text: 'سلام و خوب',
|
||
status: 'completed',
|
||
});
|
||
|
||
const assistant = service.messages().find((m) => m.id === 't1:assistant');
|
||
expect(assistant?.text).toBe('سلام و خوب');
|
||
expect(assistant?.final).toBe(true);
|
||
});
|
||
|
||
it('orders a user request above its AI response even when the assistant transcript arrives first', async () => {
|
||
await startConnected();
|
||
|
||
// The server streams assistant partials before the user transcript for the same turn.
|
||
transportHandlers?.onEvent({
|
||
type: 'transcript',
|
||
turn_ref: 'turn-1',
|
||
role: 'assistant',
|
||
text: 'پاسخ فارسی',
|
||
status: 'partial',
|
||
});
|
||
transportHandlers?.onEvent({
|
||
type: 'transcript',
|
||
turn_ref: 'turn-1',
|
||
role: 'user',
|
||
text: 'سلام',
|
||
status: 'completed',
|
||
});
|
||
|
||
const list = service.messages();
|
||
const userIndex = list.findIndex((m) => m.id === 'turn-1:user');
|
||
const assistantIndex = list.findIndex((m) => m.id === 'turn-1:assistant');
|
||
expect(userIndex).toBeGreaterThanOrEqual(0);
|
||
expect(assistantIndex).toBeGreaterThan(userIndex);
|
||
});
|
||
|
||
it('keeps user→assistant order and stable turn order across turns', async () => {
|
||
await startConnected();
|
||
|
||
transportHandlers?.onEvent({
|
||
type: 'transcript',
|
||
turn_ref: 't1',
|
||
role: 'user',
|
||
text: 'سوال ۱',
|
||
status: 'completed',
|
||
});
|
||
transportHandlers?.onEvent({
|
||
type: 'transcript',
|
||
turn_ref: 't1',
|
||
role: 'assistant',
|
||
text: 'پاسخ ۱',
|
||
status: 'completed',
|
||
});
|
||
// turn 2's assistant lands before its user transcript
|
||
transportHandlers?.onEvent({
|
||
type: 'transcript',
|
||
turn_ref: 't2',
|
||
role: 'assistant',
|
||
text: 'پاسخ ۲',
|
||
status: 'partial',
|
||
});
|
||
transportHandlers?.onEvent({
|
||
type: 'transcript',
|
||
turn_ref: 't2',
|
||
role: 'user',
|
||
text: 'سوال ۲',
|
||
status: 'completed',
|
||
});
|
||
|
||
expect(service.messages().map((m) => m.id)).toEqual([
|
||
't1:user',
|
||
't1:assistant',
|
||
't2:user',
|
||
't2:assistant',
|
||
]);
|
||
});
|
||
|
||
it('keeps the user request above a sources-only assistant bubble of the same turn', async () => {
|
||
await startConnected();
|
||
|
||
// A `sources` frame can create the assistant bubble before the user transcript arrives.
|
||
transportHandlers?.onEvent({
|
||
type: 'sources',
|
||
turn_ref: 't1',
|
||
sources: [
|
||
{ source_ref: 's1', document_id: 'd1', chunk_id: 'c1', title: 'سند', excerpt: 'بند' },
|
||
],
|
||
});
|
||
transportHandlers?.onEvent({
|
||
type: 'transcript',
|
||
turn_ref: 't1',
|
||
role: 'user',
|
||
text: 'سلام',
|
||
status: 'completed',
|
||
});
|
||
|
||
expect(service.messages().map((m) => m.id)).toEqual(['t1:user', 't1:assistant']);
|
||
});
|
||
|
||
it('closes the reservation (V04) when the call ends on user request', async () => {
|
||
await startConnected();
|
||
await service.close();
|
||
|
||
expect(api.closeVoiceSession).toHaveBeenCalledWith('csrf-1', 'ses-1');
|
||
expect(sessionStorage.getItem('voice_creation_attempt')).toBeNull();
|
||
expect(service.connection()).toBe('disconnected');
|
||
});
|
||
|
||
describe('bounded answers (answer_limited)', () => {
|
||
const MARKER: VoiceServerEvent = {
|
||
type: 'answer_limited',
|
||
turn_ref: 'turn-1',
|
||
reason: 'output_token_limit',
|
||
};
|
||
|
||
it('keeps the marker as bounded metadata when it arrives before any transcript text', async () => {
|
||
await startConnected();
|
||
|
||
transportHandlers?.onEvent(MARKER);
|
||
|
||
// No transcript text is invented for the answer.
|
||
expect(service.messages()).toEqual([]);
|
||
expect(service.connection()).toBe('connected');
|
||
expect(service.state()).toBe('LISTENING');
|
||
});
|
||
|
||
it('attaches the marker to the row when the first transcript lands after it', async () => {
|
||
await startConnected();
|
||
|
||
transportHandlers?.onEvent(MARKER); // marker first, no text yet
|
||
transportHandlers?.onEvent({
|
||
type: 'transcript',
|
||
turn_ref: 'turn-1',
|
||
role: 'assistant',
|
||
text: 'پاسخ ',
|
||
status: 'partial',
|
||
});
|
||
transportHandlers?.onEvent({
|
||
type: 'transcript',
|
||
turn_ref: 'turn-1',
|
||
role: 'assistant',
|
||
text: 'پاسخ نهایی',
|
||
status: 'limited',
|
||
});
|
||
|
||
const assistant = service.messages().find((m) => m.id === 'turn-1:assistant');
|
||
expect(assistant?.text).toBe('پاسخ نهایی'); // final snapshot replaces the partial text
|
||
expect(assistant?.limited).toBe(true);
|
||
expect(assistant?.final).toBe(true);
|
||
});
|
||
|
||
it('keeps exact text and limited status when the limited transcript arrives before the marker', async () => {
|
||
await startConnected();
|
||
|
||
transportHandlers?.onEvent({
|
||
type: 'transcript',
|
||
turn_ref: 'turn-1',
|
||
role: 'assistant',
|
||
text: 'پاسخ کامل',
|
||
status: 'limited',
|
||
});
|
||
expect(service.messages()[0].limited).toBe(true); // the transcript alone marks the answer
|
||
|
||
transportHandlers?.onEvent(MARKER);
|
||
|
||
const assistant = service.messages().find((m) => m.id === 'turn-1:assistant');
|
||
expect(assistant?.text).toBe('پاسخ کامل');
|
||
expect(assistant?.limited).toBe(true);
|
||
});
|
||
|
||
it('treats repeated answer_limited markers as idempotent (no duplicate rows or notices)', async () => {
|
||
await startConnected();
|
||
|
||
transportHandlers?.onEvent({
|
||
type: 'transcript',
|
||
turn_ref: 'turn-1',
|
||
role: 'assistant',
|
||
text: 'پاسخ',
|
||
status: 'limited',
|
||
});
|
||
const before = service.messages();
|
||
|
||
transportHandlers?.onEvent(MARKER);
|
||
transportHandlers?.onEvent(MARKER);
|
||
transportHandlers?.onEvent(MARKER);
|
||
|
||
expect(service.messages()).toHaveLength(1);
|
||
expect(service.messages()).toBe(before); // no state write at all → no re-announcement
|
||
expect(service.messages()[0].text).toBe('پاسخ');
|
||
expect(service.streamError()).toBeNull(); // informational, never an error banner
|
||
expect(service.connection()).toBe('connected');
|
||
});
|
||
|
||
it('preserves repeated legitimate partial words (no content-based dedup)', async () => {
|
||
await startConnected();
|
||
|
||
transportHandlers?.onEvent({
|
||
type: 'transcript',
|
||
turn_ref: 't1',
|
||
role: 'assistant',
|
||
text: 'بله',
|
||
status: 'partial',
|
||
});
|
||
transportHandlers?.onEvent({
|
||
type: 'transcript',
|
||
turn_ref: 't1',
|
||
role: 'assistant',
|
||
text: ' بله',
|
||
status: 'partial',
|
||
});
|
||
transportHandlers?.onEvent({
|
||
type: 'transcript',
|
||
turn_ref: 't1',
|
||
role: 'assistant',
|
||
text: ' بله',
|
||
status: 'partial',
|
||
});
|
||
|
||
expect(service.messages()[0].text).toBe('بله بله بله');
|
||
});
|
||
|
||
it('does not downgrade a limited answer on delayed completed/partial events', async () => {
|
||
await startConnected();
|
||
|
||
transportHandlers?.onEvent({
|
||
type: 'transcript',
|
||
turn_ref: 't1',
|
||
role: 'assistant',
|
||
text: 'پاسخ محدود',
|
||
status: 'limited',
|
||
});
|
||
|
||
// Delayed frames for the same turn arrive after the final snapshot.
|
||
transportHandlers?.onEvent({
|
||
type: 'transcript',
|
||
turn_ref: 't1',
|
||
role: 'assistant',
|
||
text: 'پاسخ کاملتر',
|
||
status: 'completed',
|
||
});
|
||
transportHandlers?.onEvent({
|
||
type: 'transcript',
|
||
turn_ref: 't1',
|
||
role: 'assistant',
|
||
text: ' ادامه',
|
||
status: 'partial',
|
||
});
|
||
|
||
const assistant = service.messages().find((m) => m.id === 't1:assistant');
|
||
expect(assistant?.limited).toBe(true); // never reverts to completed/partial
|
||
expect(assistant?.final).toBe(true);
|
||
expect(assistant?.text).toBe('پاسخ کاملتر'); // the late partial did not extend it
|
||
});
|
||
|
||
it('lets turn_interrupted take precedence over limited and blocks late text', async () => {
|
||
await startConnected();
|
||
|
||
transportHandlers?.onEvent({
|
||
type: 'transcript',
|
||
turn_ref: 'turn-1',
|
||
role: 'assistant',
|
||
text: 'پاسخ ',
|
||
status: 'partial',
|
||
});
|
||
transportHandlers?.onEvent({
|
||
type: 'transcript',
|
||
turn_ref: 'turn-1',
|
||
role: 'assistant',
|
||
text: 'پاسخ نهایی',
|
||
status: 'limited',
|
||
});
|
||
transportHandlers?.onEvent(MARKER);
|
||
engineClear.mockClear();
|
||
|
||
transportHandlers?.onEvent({ type: 'turn_interrupted', turn_ref: 'turn-1' });
|
||
|
||
const assistant = service.messages().find((m) => m.id === 'turn-1:assistant');
|
||
expect(assistant?.interrupted).toBe(true); // interruption wins over the limited state
|
||
expect(engineClear).toHaveBeenCalledTimes(1); // the existing barge-in flush still runs
|
||
|
||
// Late assistant text cannot restore the interrupted answer.
|
||
transportHandlers?.onEvent({
|
||
type: 'transcript',
|
||
turn_ref: 'turn-1',
|
||
role: 'assistant',
|
||
text: 'متن دیرکرده',
|
||
status: 'limited',
|
||
});
|
||
transportHandlers?.onEvent({
|
||
type: 'transcript',
|
||
turn_ref: 'turn-1',
|
||
role: 'assistant',
|
||
text: 'ادامه',
|
||
status: 'partial',
|
||
});
|
||
|
||
const after = service.messages().find((m) => m.id === 'turn-1:assistant');
|
||
expect(after?.text).toBe('پاسخ نهایی');
|
||
expect(after?.interrupted).toBe(true);
|
||
});
|
||
|
||
it('does not mark an already interrupted answer as limited', async () => {
|
||
await startConnected();
|
||
|
||
transportHandlers?.onEvent({
|
||
type: 'transcript',
|
||
turn_ref: 'turn-1',
|
||
role: 'assistant',
|
||
text: 'پاسخ',
|
||
status: 'partial',
|
||
});
|
||
transportHandlers?.onEvent({ type: 'turn_interrupted', turn_ref: 'turn-1' });
|
||
transportHandlers?.onEvent(MARKER);
|
||
|
||
const assistant = service.messages().find((m) => m.id === 'turn-1:assistant');
|
||
expect(assistant?.interrupted).toBe(true);
|
||
expect(assistant?.limited).toBeFalsy();
|
||
});
|
||
|
||
it('does not mark a sources-only row of an interrupted turn as limited', async () => {
|
||
await startConnected();
|
||
|
||
// The turn is capped, then cut off before any transcript row exists, then its
|
||
// sources arrive: the row must not be presented as a limited answer.
|
||
transportHandlers?.onEvent(MARKER);
|
||
transportHandlers?.onEvent({ type: 'turn_interrupted', turn_ref: 'turn-1' });
|
||
transportHandlers?.onEvent({
|
||
type: 'sources',
|
||
turn_ref: 'turn-1',
|
||
sources: [{ source_ref: 'src-1', document_id: 'doc-1', chunk_id: 'chunk-1', title: 'سند' }],
|
||
});
|
||
|
||
const assistant = service.messages().find((m) => m.id === 'turn-1:assistant');
|
||
expect(assistant?.limited).toBeFalsy();
|
||
expect(assistant?.sources).toHaveLength(1);
|
||
});
|
||
|
||
it('keeps a delayed user transcript attached to its own turn, independent of assistant status', async () => {
|
||
await startConnected();
|
||
|
||
transportHandlers?.onEvent({ type: 'user_speech_started', turn_ref: 'turn-1' });
|
||
transportHandlers?.onEvent({
|
||
type: 'transcript',
|
||
turn_ref: 'turn-1',
|
||
role: 'assistant',
|
||
text: 'پاسخ اول',
|
||
status: 'limited',
|
||
});
|
||
// Turn 2 starts before turn 1's user transcript is finalized.
|
||
transportHandlers?.onEvent({ type: 'user_speech_started', turn_ref: 'turn-2' });
|
||
transportHandlers?.onEvent({
|
||
type: 'transcript',
|
||
turn_ref: 'turn-2',
|
||
role: 'assistant',
|
||
text: 'پاسخ دوم',
|
||
status: 'partial',
|
||
});
|
||
transportHandlers?.onEvent({
|
||
type: 'transcript',
|
||
turn_ref: 'turn-1',
|
||
role: 'user',
|
||
text: 'سوال اول',
|
||
status: 'completed',
|
||
});
|
||
|
||
const list = service.messages();
|
||
expect(list.map((m) => m.id)).toEqual([
|
||
'turn-1:user',
|
||
'turn-1:assistant',
|
||
'turn-2:assistant',
|
||
]);
|
||
expect(list.find((m) => m.id === 'turn-1:user')?.text).toBe('سوال اول');
|
||
expect(list.find((m) => m.id === 'turn-1:user')?.limited).toBeFalsy();
|
||
expect(list.find((m) => m.id === 'turn-1:assistant')?.limited).toBe(true);
|
||
expect(list.find((m) => m.id === 'turn-2:assistant')?.limited).toBeFalsy();
|
||
});
|
||
|
||
it('cannot let an old session marker contaminate a new session', async () => {
|
||
await startConnected(); // session A
|
||
transportHandlers?.onEvent({
|
||
type: 'answer_limited',
|
||
turn_ref: 'shared-turn',
|
||
reason: 'output_token_limit',
|
||
});
|
||
await service.close();
|
||
|
||
await startConnected(); // session B
|
||
|
||
transportHandlers?.onEvent({
|
||
type: 'transcript',
|
||
turn_ref: 'shared-turn',
|
||
role: 'assistant',
|
||
text: 'پاسخ تازه',
|
||
status: 'partial',
|
||
});
|
||
|
||
const assistant = service.messages().find((m) => m.id === 'shared-turn:assistant');
|
||
expect(assistant?.text).toBe('پاسخ تازه');
|
||
expect(assistant?.limited).toBeFalsy(); // session A's metadata did not leak
|
||
});
|
||
|
||
it('does not stop capture, close the socket, flush audio or reset playback progress', async () => {
|
||
await startConnected();
|
||
transportHandlers?.onEvent({ type: 'audio_started', audio_ref: 'aud-1' });
|
||
engineHandlers?.onPlaybackProgress('aud-1', 120);
|
||
controls = [];
|
||
engineFlush.mockClear();
|
||
engineClear.mockClear();
|
||
engineStop.mockClear();
|
||
transportMock.close.mockClear();
|
||
|
||
transportHandlers?.onEvent(MARKER);
|
||
transportHandlers?.onEvent({
|
||
type: 'transcript',
|
||
turn_ref: 'turn-1',
|
||
role: 'assistant',
|
||
text: 'پاسخ',
|
||
status: 'limited',
|
||
});
|
||
|
||
expect(engineFlush).not.toHaveBeenCalled(); // no flush/mute of playback
|
||
expect(engineClear).not.toHaveBeenCalled();
|
||
expect(engineStop).not.toHaveBeenCalled(); // microphone keeps capturing
|
||
expect(transportMock.close).not.toHaveBeenCalled(); // socket stays open
|
||
expect(api.closeVoiceSession).not.toHaveBeenCalled(); // no backend close request
|
||
expect(service.connection()).toBe('connected');
|
||
expect(service.state()).toBe('LISTENING');
|
||
|
||
// Capture keeps flowing and playback progress keeps being reported.
|
||
engineHandlers?.onFrame(new ArrayBuffer(9600), 0.5);
|
||
expect(transportMock.sendAudio).toHaveBeenCalledTimes(1);
|
||
engineHandlers?.onPlaybackProgress('aud-1', 300);
|
||
expect(controls).toEqual([{ type: 'playback_progress', audio_ref: 'aud-1', played_ms: 300 }]);
|
||
});
|
||
|
||
it('keeps buffered audio playing after the marker; audio_ended only seals generation', async () => {
|
||
await startConnected();
|
||
transportHandlers?.onEvent({ type: 'audio_started', audio_ref: 'aud-1' });
|
||
transportHandlers?.onAudio(new ArrayBuffer(9600)); // real binary audio
|
||
expect(service.state()).toBe('SPEAKING');
|
||
|
||
engineHandlers?.onPlaybackProgress('aud-1', 100);
|
||
controls = [];
|
||
engineFlush.mockClear();
|
||
|
||
transportHandlers?.onEvent(MARKER);
|
||
|
||
// Still playing: state unchanged, no flush, no clear, audio keeps arriving.
|
||
expect(service.state()).toBe('SPEAKING');
|
||
expect(engineFlush).not.toHaveBeenCalled();
|
||
expect(engineClear).not.toHaveBeenCalled();
|
||
transportHandlers?.onAudio(new ArrayBuffer(9600));
|
||
expect(engineStop).not.toHaveBeenCalled();
|
||
|
||
// audio_ended seals GENERATION (drain) — it is not actual playback completion:
|
||
// progress keeps being reported from what the worklet really plays.
|
||
transportHandlers?.onEvent({ type: 'audio_ended', audio_ref: 'aud-1' });
|
||
expect(engineFlush).toHaveBeenCalledTimes(1);
|
||
expect(service.state()).toBe('SPEAKING');
|
||
|
||
engineHandlers?.onPlaybackProgress('aud-1', 400);
|
||
expect(controls).toEqual([{ type: 'playback_progress', audio_ref: 'aud-1', played_ms: 400 }]);
|
||
|
||
// The turn only finishes when playback actually drains.
|
||
vi.useFakeTimers();
|
||
try {
|
||
engineHandlers?.onPlaybackIdle();
|
||
vi.advanceTimersByTime(900); // no completed transcript for this limited turn → settle
|
||
} finally {
|
||
vi.useRealTimers();
|
||
}
|
||
expect(service.state()).toBe('LISTENING');
|
||
});
|
||
|
||
it('does not leave the UI thinking when a limited answer produces no audio', async () => {
|
||
await startConnected();
|
||
transportHandlers?.onEvent({
|
||
type: 'transcript',
|
||
turn_ref: 'turn-1',
|
||
role: 'user',
|
||
text: 'سوال',
|
||
status: 'completed',
|
||
});
|
||
expect(service.state()).toBe('PROCESSING');
|
||
|
||
// The marker lands while no audio is outstanding at all.
|
||
vi.useFakeTimers();
|
||
try {
|
||
transportHandlers?.onEvent(MARKER);
|
||
vi.advanceTimersByTime(900); // the bounded settle fallback
|
||
} finally {
|
||
vi.useRealTimers();
|
||
}
|
||
expect(service.state()).toBe('LISTENING'); // usable again, session alive
|
||
expect(service.connection()).toBe('connected');
|
||
|
||
// The user can immediately speak a genuine continuation ("ادامه بده").
|
||
engineHandlers?.onFrame(new ArrayBuffer(9600), 0.5);
|
||
expect(transportMock.sendAudio).toHaveBeenCalledTimes(1);
|
||
});
|
||
|
||
it('reports the real final played progress when a limited answer is interrupted', async () => {
|
||
await startConnected();
|
||
transportHandlers?.onEvent({
|
||
type: 'transcript',
|
||
turn_ref: 'turn-1',
|
||
role: 'assistant',
|
||
text: 'پاسخ',
|
||
status: 'limited',
|
||
});
|
||
transportHandlers?.onEvent({ type: 'audio_started', audio_ref: 'aud-2' });
|
||
engineHandlers?.onPlaybackProgress('aud-2', 300);
|
||
controls = [];
|
||
|
||
transportHandlers?.onEvent({ type: 'turn_interrupted', turn_ref: 'turn-1' });
|
||
// The worklet answers `clear` with its final cumulative report for the ref.
|
||
engineHandlers?.onPlaybackProgress('aud-2', 780);
|
||
|
||
expect(controls).toEqual([{ type: 'playback_progress', audio_ref: 'aud-2', played_ms: 780 }]);
|
||
});
|
||
|
||
it('never auto-continues, fabricates a control message or recreates the session', async () => {
|
||
await startConnected();
|
||
controls = [];
|
||
|
||
transportHandlers?.onEvent(MARKER);
|
||
|
||
expect(controls).toEqual([]); // no continue/resume/response.create text command
|
||
expect(api.createVoiceSession).toHaveBeenCalledTimes(1); // no second reservation
|
||
expect(transportMock.connect).toHaveBeenCalledTimes(1); // no second socket
|
||
expect(api.closeVoiceSession).not.toHaveBeenCalled(); // no close request either
|
||
expect(service.connection()).toBe('connected'); // the session stays usable
|
||
});
|
||
|
||
it('still fails safely on a genuine error frame after a limited answer', async () => {
|
||
await startConnected();
|
||
const ended = firstEndedError();
|
||
|
||
transportHandlers?.onEvent(MARKER);
|
||
transportHandlers?.onEvent({
|
||
type: 'error',
|
||
error: { code: 'LIVE_BUFFER_OVERFLOW', message: 'overflow', retryable: false },
|
||
});
|
||
|
||
expect(await ended).toBe('overflow'); // a fatal error is NOT reinterpreted as limited
|
||
expect(api.closeVoiceSession).toHaveBeenCalledTimes(1);
|
||
expect(service.connection()).toBe('disconnected');
|
||
});
|
||
|
||
it('still fails safely on a real playback overflow after a limited answer', async () => {
|
||
await startConnected();
|
||
const ended = firstEndedError();
|
||
|
||
transportHandlers?.onEvent(MARKER);
|
||
engineHandlers?.onPlaybackOverflow();
|
||
|
||
expect(await ended).toBe(OVERFLOW_MESSAGE);
|
||
expect(service.connection()).toBe('disconnected');
|
||
});
|
||
|
||
it('keeps the ordinary completed-answer flow of an older backend intact', async () => {
|
||
await startConnected();
|
||
transportHandlers?.onEvent({ type: 'audio_started', audio_ref: 'aud-1' });
|
||
transportHandlers?.onAudio(new ArrayBuffer(9600));
|
||
transportHandlers?.onEvent({
|
||
type: 'transcript',
|
||
turn_ref: 'turn-1',
|
||
role: 'assistant',
|
||
text: 'پاسخ کامل',
|
||
status: 'completed',
|
||
});
|
||
transportHandlers?.onEvent({ type: 'audio_ended', audio_ref: 'aud-1' });
|
||
|
||
const assistant = service.messages().find((m) => m.id === 'turn-1:assistant');
|
||
expect(assistant?.text).toBe('پاسخ کامل');
|
||
expect(assistant?.limited).toBeFalsy();
|
||
expect(assistant?.final).toBe(true);
|
||
expect(engineFlush).toHaveBeenCalledTimes(1);
|
||
|
||
engineHandlers?.onPlaybackIdle();
|
||
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();
|
||
});
|
||
|
||
});
|