feat(voice): enhance streaming engine and improve system reliability

Improve the PCM playback worklet with robust resampling and buffer
management. Refactor the voice-stream service for better session
teardown and error handling. Fix authentication issues by enabling
credentials in HttpService and using relative URLs. Add Jalali date
support and an AI model configuration tab in settings. Enhance
diagnostics for voice transport and the audio engine.
This commit is contained in:
PeymanHonarjoo
2026-10-10 15:12:57 +03:30
parent ff7fcbc4bb
commit be17544f2d
30 changed files with 1379 additions and 390 deletions
@@ -33,9 +33,21 @@ const READY_EVENT: VoiceServerEvent = {
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: {
@@ -51,12 +63,15 @@ describe('VoiceStreamService (backend handoff contract)', () => {
let engineHandlers: VoiceEngineHandlers | null;
let transportHandlers: VoiceTransportHandlers | null;
let controls: PlaybackProgressMessage[];
let transportMock: TransportMock;
let engineStop: ReturnType<typeof vi.fn>;
beforeEach(() => {
sessionStorage.clear();
engineHandlers = null;
transportHandlers = null;
controls = [];
engineStop = vi.fn();
api = {
me: vi.fn().mockResolvedValue(ME),
@@ -69,7 +84,7 @@ describe('VoiceStreamService (backend handoff contract)', () => {
streamUrl: vi.fn().mockReturnValue('wss://ui.local/api/v1/voice/sessions/ses-1/stream'),
};
const transportMock: VoiceTransport & { handlers: VoiceTransportHandlers | null } = {
transportMock = {
handlers: null,
connect: vi.fn().mockImplementation((handlers: VoiceTransportHandlers) => {
transportHandlers = handlers;
@@ -95,7 +110,7 @@ describe('VoiceStreamService (backend handoff contract)', () => {
engineHandlers = handlers;
return Promise.resolve();
}),
stop: vi.fn(),
stop: engineStop,
setMuted: vi.fn(),
enqueuePlayback: vi.fn(),
clearPlayback: vi.fn(),
@@ -228,10 +243,73 @@ describe('VoiceStreamService (backend handoff contract)', () => {
engineHandlers?.onPlaybackOverflow();
expect(await ended).toBe('حجم صدای در حال پخش از محدودهٔ مجاز گذشت و گفتگو به‌طور ایمن پایان یافت.');
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('requires a fresh conversation after CONTEXT_REVOKED and drops the old attempt', async () => {
await startConnected();
const ended = firstEndedError();