feat(voice): enhance audio stream lifecycle with sent_bytes validation and ref-attributed idle tracking

This commit is contained in:
amirhosein mazaheri
2026-10-12 18:51:05 +03:30
parent 89c6bc6d44
commit 58c3c20933
8 changed files with 344 additions and 102 deletions
@@ -10,7 +10,11 @@ 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 ME = {
user: { id: 'u1', username: 'admin', role: 'admin', organization_id: 'o1' },
csrf_token: 'csrf-1',
expires_at: 'later',
};
const CONFIG = {
revision: 1,
assistant_name: 'دستیار',
@@ -34,7 +38,8 @@ const READY_EVENT: VoiceServerEvent = {
};
const OVERFLOW_MESSAGE = 'حجم صدای در حال پخش از محدودهٔ مجاز گذشت و گفتگو به‌طور ایمن پایان یافت.';
const SEND_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));
@@ -96,7 +101,9 @@ describe('VoiceStreamService (backend handoff contract)', () => {
return Promise.resolve();
}),
sendAudio: vi.fn(),
sendControl: vi.fn().mockImplementation((message: PlaybackProgressMessage) => controls.push(message)),
sendControl: vi
.fn()
.mockImplementation((message: PlaybackProgressMessage) => controls.push(message)),
close: vi.fn(),
};
@@ -138,7 +145,9 @@ describe('VoiceStreamService (backend handoff contract)', () => {
}
function firstEndedError(): Promise<string | undefined> {
return new Promise((resolve) => service.sessionEnded$.pipe(first()).subscribe((end) => resolve(end.error)));
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 () => {
@@ -166,7 +175,11 @@ describe('VoiceStreamService (backend handoff contract)', () => {
output_audio: { encoding: 'pcm_s16le', sample_rate: 24000, channels: 1 },
});
const result = await started;
expect(result).toEqual({ ok: false, reason: 'connect', message: 'فرمت صدای سرور با برنامه سازگار نیست.' });
expect(result).toEqual({
ok: false,
reason: 'connect',
message: 'فرمت صدای سرور با برنامه سازگار نیست.',
});
});
it('reconciles an ambiguous V01 through V03 instead of creating a second session', async () => {
@@ -226,7 +239,13 @@ describe('VoiceStreamService (backend handoff contract)', () => {
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: '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 = [];
@@ -235,9 +254,7 @@ describe('VoiceStreamService (backend handoff contract)', () => {
// 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(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);
});
@@ -314,6 +331,56 @@ describe('VoiceStreamService (backend handoff contract)', () => {
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' });
@@ -335,7 +402,7 @@ describe('VoiceStreamService (backend handoff contract)', () => {
transportHandlers?.onEvent({ type: 'audio_ended', audio_ref: 'aud-1' });
expect(engineFlush).toHaveBeenCalledTimes(1);
// Once generation is done, a late/second completed transcript re-flushes idempotently.
// A duplicate final transcript does not flush the sealed reference again.
transportHandlers?.onEvent({
type: 'transcript',
turn_ref: 'turn-1',
@@ -343,7 +410,7 @@ describe('VoiceStreamService (backend handoff contract)', () => {
text: '…',
status: 'completed',
});
expect(engineFlush).toHaveBeenCalledTimes(2);
expect(engineFlush).toHaveBeenCalledTimes(1);
});
it('requires a fresh conversation after CONTEXT_REVOKED and drops the old attempt', async () => {
@@ -355,7 +422,9 @@ describe('VoiceStreamService (backend handoff contract)', () => {
error: { code: 'CONTEXT_REVOKED', message: 'context revoked', retryable: false },
});
expect(await ended).toBe('محتوای دانش تغییر کرده و مکالمهٔ قبلی دیگر معتبر نیست. گفتگوی جدیدی شروع کنید.');
expect(await ended).toBe(
'محتوای دانش تغییر کرده و مکالمهٔ قبلی دیگر معتبر نیست. گفتگوی جدیدی شروع کنید.',
);
expect(sessionStorage.getItem('voice_creation_attempt')).toBeNull();
expect(service.connection()).toBe('disconnected');
});
@@ -398,9 +467,27 @@ describe('VoiceStreamService (backend handoff contract)', () => {
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' });
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('سلام و خوب');
@@ -411,8 +498,20 @@ describe('VoiceStreamService (backend handoff contract)', () => {
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' });
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');
@@ -424,11 +523,35 @@ describe('VoiceStreamService (backend handoff contract)', () => {
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' });
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' });
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',
@@ -445,9 +568,17 @@ describe('VoiceStreamService (backend handoff contract)', () => {
transportHandlers?.onEvent({
type: 'sources',
turn_ref: 't1',
sources: [{ source_ref: 's1', document_id: 'd1', chunk_id: 'c1', title: 'سند', excerpt: 'بند' }],
sources: [
{ source_ref: 's1', document_id: 'd1', chunk_id: 'c1', title: 'سند', excerpt: 'بند' },
],
});
transportHandlers?.onEvent({
type: 'transcript',
turn_ref: 't1',
role: 'user',
text: 'سلام',
status: 'completed',
});
transportHandlers?.onEvent({ type: 'transcript', turn_ref: 't1', role: 'user', text: 'سلام', status: 'completed' });
expect(service.messages().map((m) => m.id)).toEqual(['t1:user', 't1:assistant']);
});
@@ -549,9 +680,27 @@ describe('VoiceStreamService (backend handoff contract)', () => {
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' });
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('بله بله بله');
});
@@ -701,7 +850,11 @@ describe('VoiceStreamService (backend handoff contract)', () => {
});
const list = service.messages();
expect(list.map((m) => m.id)).toEqual(['turn-1:user', 'turn-1:assistant', 'turn-2:assistant']);
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);
@@ -710,7 +863,11 @@ describe('VoiceStreamService (backend handoff contract)', () => {
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' });
transportHandlers?.onEvent({
type: 'answer_limited',
turn_ref: 'shared-turn',
reason: 'output_token_limit',
});
await service.close();
await startConnected(); // session B
@@ -845,9 +1002,7 @@ describe('VoiceStreamService (backend handoff contract)', () => {
// 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(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 () => {