feat(voice): enhance audio stream lifecycle with sent_bytes validation and ref-attributed idle tracking
This commit is contained in:
@@ -27,9 +27,9 @@
|
|||||||
*
|
*
|
||||||
* Messages in: { type: 'push', pcm: ArrayBuffer (Int16 mono), sampleRate, audioRef }
|
* Messages in: { type: 'push', pcm: ArrayBuffer (Int16 mono), sampleRate, audioRef }
|
||||||
* { type: 'clear' } barge-in: drop everything immediately
|
* { type: 'clear' } barge-in: drop everything immediately
|
||||||
* { type: 'flush' } end of turn: emit the tail, play what is left, then idle
|
* { type: 'flush', audioRef } end of turn: emit the tail, play what is left, then idle
|
||||||
* Messages out: { type: 'progress', audioRef, playedMs }
|
* Messages out: { type: 'progress', audioRef, playedMs }
|
||||||
* { type: 'idle' } buffer ran dry after playing
|
* { type: 'idle', audioRef } buffer ran dry after playing
|
||||||
* { type: 'overflow' } bounded queue filled — caller fails the session safely
|
* { type: 'overflow' } bounded queue filled — caller fails the session safely
|
||||||
*/
|
*/
|
||||||
const BOUND_BYTES = 96000; // contract cap on outstanding SOURCE PCM16
|
const BOUND_BYTES = 96000; // contract cap on outstanding SOURCE PCM16
|
||||||
@@ -74,7 +74,7 @@ class PcmPlaybackProcessor extends AudioWorkletProcessor {
|
|||||||
if (!m) return;
|
if (!m) return;
|
||||||
if (m.type === 'push') this.push(new Int16Array(m.pcm), m.sampleRate, m.audioRef || null);
|
if (m.type === 'push') this.push(new Int16Array(m.pcm), m.sampleRate, m.audioRef || null);
|
||||||
else if (m.type === 'clear') this.clear();
|
else if (m.type === 'clear') this.clear();
|
||||||
else if (m.type === 'flush') this.flush();
|
else if (m.type === 'flush') this.flush(m.audioRef);
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -110,12 +110,12 @@ class PcmPlaybackProcessor extends AudioWorkletProcessor {
|
|||||||
this.playingRef = null;
|
this.playingRef = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
flush() {
|
flush(audioRef = this.pendingRef) {
|
||||||
this.finalizeTail(); // emit the deferred tail so every admitted sample becomes output
|
this.finalizeTail(); // emit the deferred tail so every admitted sample becomes output
|
||||||
if (this.count === 0) {
|
if (this.count === 0) {
|
||||||
this.started = false;
|
this.started = false;
|
||||||
this.reportFinal();
|
this.reportFinal();
|
||||||
this.port.postMessage({ type: 'idle' });
|
this.port.postMessage({ type: 'idle', audioRef: audioRef || this.pendingRef });
|
||||||
} else {
|
} else {
|
||||||
this.started = true; // play the remaining audio + tail without waiting for the prebuffer
|
this.started = true; // play the remaining audio + tail without waiting for the prebuffer
|
||||||
}
|
}
|
||||||
@@ -260,7 +260,7 @@ class PcmPlaybackProcessor extends AudioWorkletProcessor {
|
|||||||
this.queuedSource = 0;
|
this.queuedSource = 0;
|
||||||
this.started = false;
|
this.started = false;
|
||||||
this.reportFinal();
|
this.reportFinal();
|
||||||
this.port.postMessage({ type: 'idle' });
|
this.port.postMessage({ type: 'idle', audioRef: this.pendingRef });
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
ch0.fill(0);
|
ch0.fill(0);
|
||||||
|
|||||||
@@ -182,7 +182,9 @@ describe('pcm-playback.worklet', () => {
|
|||||||
drain(proc);
|
drain(proc);
|
||||||
expect(proc.refPlayedOut.get('aud-1')).toBe((rate * 1001) / 1000);
|
expect(proc.refPlayedOut.get('aud-1')).toBe((rate * 1001) / 1000);
|
||||||
expect(playedFor(proc, 'aud-1')).toBe(1001);
|
expect(playedFor(proc, 'aud-1')).toBe(1001);
|
||||||
const values = proc.out.filter((m) => m.audioRef === 'aud-1').map((m) => m.playedMs ?? 0);
|
const values = proc.out
|
||||||
|
.filter((m) => m.type === 'progress' && m.audioRef === 'aud-1')
|
||||||
|
.map((m) => m.playedMs ?? 0);
|
||||||
expect(values).toEqual([...values].sort((a, b) => a - b));
|
expect(values).toEqual([...values].sort((a, b) => a - b));
|
||||||
expect(values.every((ms) => ms <= 1001)).toBe(true);
|
expect(values.every((ms) => ms <= 1001)).toBe(true);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ export interface VoiceEngineHandlers {
|
|||||||
/** One PCM16 frame (config.inputSampleRate, config.frameMs). Runs outside Angular's zone. */
|
/** One PCM16 frame (config.inputSampleRate, config.frameMs). Runs outside Angular's zone. */
|
||||||
onFrame(pcm: ArrayBuffer, rms: number): void;
|
onFrame(pcm: ArrayBuffer, rms: number): void;
|
||||||
/** The playback buffer ran dry (or `flushPlayback()` found it empty). */
|
/** The playback buffer ran dry (or `flushPlayback()` found it empty). */
|
||||||
onPlaybackIdle(): void;
|
onPlaybackIdle(audioRef?: string | null): void;
|
||||||
/** The microphone track ended unexpectedly. */
|
/** The microphone track ended unexpectedly. */
|
||||||
onMicEnded(): void;
|
onMicEnded(): void;
|
||||||
/**
|
/**
|
||||||
@@ -131,7 +131,7 @@ export class VoiceAudioEngine {
|
|||||||
) => {
|
) => {
|
||||||
switch (event.data?.type) {
|
switch (event.data?.type) {
|
||||||
case 'idle':
|
case 'idle':
|
||||||
handlers.onPlaybackIdle();
|
handlers.onPlaybackIdle(event.data.audioRef);
|
||||||
break;
|
break;
|
||||||
case 'progress':
|
case 'progress':
|
||||||
if (event.data.audioRef) {
|
if (event.data.audioRef) {
|
||||||
@@ -185,8 +185,8 @@ export class VoiceAudioEngine {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/** End of turn: play the remaining audio, then report idle. */
|
/** End of turn: play the remaining audio, then report idle. */
|
||||||
flushPlayback(): void {
|
flushPlayback(audioRef?: string | null): void {
|
||||||
this.playback?.port.postMessage({ type: 'flush' });
|
this.playback?.port.postMessage({ type: 'flush', audioRef });
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---- mic / meters ----------------------------------------------------------
|
// ---- mic / meters ----------------------------------------------------------
|
||||||
|
|||||||
@@ -40,14 +40,20 @@ describe('voice-event.validator', () => {
|
|||||||
expect(
|
expect(
|
||||||
parseVoiceServerEvent(JSON.stringify({ ...ANSWER_LIMITED, reason: 'output_length_limit' })),
|
parseVoiceServerEvent(JSON.stringify({ ...ANSWER_LIMITED, reason: 'output_length_limit' })),
|
||||||
).toBeNull();
|
).toBeNull();
|
||||||
expect(parseVoiceServerEvent(JSON.stringify({ ...ANSWER_LIMITED, reason: 'token_limit' }))).toBeNull();
|
expect(
|
||||||
expect(parseVoiceServerEvent(JSON.stringify({ type: 'answer_limited', turn_ref: 't1' }))).toBeNull();
|
parseVoiceServerEvent(JSON.stringify({ ...ANSWER_LIMITED, reason: 'token_limit' })),
|
||||||
|
).toBeNull();
|
||||||
|
expect(
|
||||||
|
parseVoiceServerEvent(JSON.stringify({ type: 'answer_limited', turn_ref: 't1' })),
|
||||||
|
).toBeNull();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('rejects answer_limited without a valid turn_ref', () => {
|
it('rejects answer_limited without a valid turn_ref', () => {
|
||||||
expect(parseVoiceServerEvent(JSON.stringify({ ...ANSWER_LIMITED, turn_ref: '' }))).toBeNull();
|
expect(parseVoiceServerEvent(JSON.stringify({ ...ANSWER_LIMITED, turn_ref: '' }))).toBeNull();
|
||||||
expect(parseVoiceServerEvent(JSON.stringify({ ...ANSWER_LIMITED, turn_ref: 7 }))).toBeNull();
|
expect(parseVoiceServerEvent(JSON.stringify({ ...ANSWER_LIMITED, turn_ref: 7 }))).toBeNull();
|
||||||
expect(parseVoiceServerEvent('{"type":"answer_limited","reason":"output_token_limit"}')).toBeNull();
|
expect(
|
||||||
|
parseVoiceServerEvent('{"type":"answer_limited","reason":"output_token_limit"}'),
|
||||||
|
).toBeNull();
|
||||||
});
|
});
|
||||||
|
|
||||||
it('only advertises the contract reason and statuses', () => {
|
it('only advertises the contract reason and statuses', () => {
|
||||||
@@ -58,12 +64,24 @@ describe('voice-event.validator', () => {
|
|||||||
|
|
||||||
describe('transcript frames', () => {
|
describe('transcript frames', () => {
|
||||||
it('accepts a limited assistant transcript', () => {
|
it('accepts a limited assistant transcript', () => {
|
||||||
const frame = { type: 'transcript', turn_ref: 't1', role: 'assistant', text: 'پاسخ', status: 'limited' };
|
const frame = {
|
||||||
|
type: 'transcript',
|
||||||
|
turn_ref: 't1',
|
||||||
|
role: 'assistant',
|
||||||
|
text: 'پاسخ',
|
||||||
|
status: 'limited',
|
||||||
|
};
|
||||||
expect(parseVoiceServerEvent(JSON.stringify(frame))).toEqual(frame);
|
expect(parseVoiceServerEvent(JSON.stringify(frame))).toEqual(frame);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('rejects a limited USER transcript (limited is assistant-only)', () => {
|
it('rejects a limited USER transcript (limited is assistant-only)', () => {
|
||||||
const frame = { type: 'transcript', turn_ref: 't1', role: 'user', text: 'ادامه بده', status: 'limited' };
|
const frame = {
|
||||||
|
type: 'transcript',
|
||||||
|
turn_ref: 't1',
|
||||||
|
role: 'user',
|
||||||
|
text: 'ادامه بده',
|
||||||
|
status: 'limited',
|
||||||
|
};
|
||||||
expect(parseVoiceServerEvent(JSON.stringify(frame))).toBeNull();
|
expect(parseVoiceServerEvent(JSON.stringify(frame))).toBeNull();
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -80,12 +98,25 @@ describe('voice-event.validator', () => {
|
|||||||
const base = { type: 'transcript', turn_ref: 't1', role: 'assistant', text: 'متن' };
|
const base = { type: 'transcript', turn_ref: 't1', role: 'assistant', text: 'متن' };
|
||||||
expect(parseVoiceServerEvent(JSON.stringify({ ...base, status: 'capped' }))).toBeNull();
|
expect(parseVoiceServerEvent(JSON.stringify({ ...base, status: 'capped' }))).toBeNull();
|
||||||
expect(parseVoiceServerEvent(JSON.stringify({ ...base, status: 5 }))).toBeNull();
|
expect(parseVoiceServerEvent(JSON.stringify({ ...base, status: 5 }))).toBeNull();
|
||||||
expect(parseVoiceServerEvent(JSON.stringify({ ...base, status: 'limited', text: 3 }))).toBeNull();
|
expect(
|
||||||
expect(parseVoiceServerEvent(JSON.stringify({ ...base, status: 'limited', role: 'system' }))).toBeNull();
|
parseVoiceServerEvent(JSON.stringify({ ...base, status: 'limited', text: 3 })),
|
||||||
expect(parseVoiceServerEvent(JSON.stringify({ ...base, status: 'limited', turn_ref: '' }))).toBeNull();
|
).toBeNull();
|
||||||
|
expect(
|
||||||
|
parseVoiceServerEvent(JSON.stringify({ ...base, status: 'limited', role: 'system' })),
|
||||||
|
).toBeNull();
|
||||||
|
expect(
|
||||||
|
parseVoiceServerEvent(JSON.stringify({ ...base, status: 'limited', turn_ref: '' })),
|
||||||
|
).toBeNull();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('accepts bounded audio_ended sent_bytes and rejects malformed counters', () => {
|
||||||
|
const frame = { type: 'audio_ended', audio_ref: 'aud-1', turn_ref: 'turn-1', sent_bytes: 9600 };
|
||||||
|
expect(parseVoiceServerEvent(JSON.stringify(frame))).toEqual(frame);
|
||||||
|
for (const sent_bytes of [-1, 1.5, '9600', Number.MAX_SAFE_INTEGER + 1]) {
|
||||||
|
expect(parseVoiceServerEvent(JSON.stringify({ ...frame, sent_bytes }))).toBeNull();
|
||||||
|
}
|
||||||
|
});
|
||||||
describe('existing events keep passing (older backends)', () => {
|
describe('existing events keep passing (older backends)', () => {
|
||||||
it('accepts every known event type with a valid payload', () => {
|
it('accepts every known event type with a valid payload', () => {
|
||||||
const frames: VoiceServerEvent[] = [
|
const frames: VoiceServerEvent[] = [
|
||||||
@@ -131,9 +162,7 @@ describe('voice-event.validator', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it('defaults a missing error retryable flag to false instead of dropping the frame', () => {
|
it('defaults a missing error retryable flag to false instead of dropping the frame', () => {
|
||||||
const parsed = parseVoiceServerEvent(
|
const parsed = parseVoiceServerEvent('{"type":"error","error":{"code":"X","message":"y"}}');
|
||||||
'{"type":"error","error":{"code":"X","message":"y"}}',
|
|
||||||
);
|
|
||||||
expect(parsed).toEqual({
|
expect(parsed).toEqual({
|
||||||
type: 'error',
|
type: 'error',
|
||||||
error: { code: 'X', message: 'y', retryable: false },
|
error: { code: 'X', message: 'y', retryable: false },
|
||||||
@@ -145,7 +174,11 @@ describe('voice-event.validator', () => {
|
|||||||
it('drops unknown event types instead of forwarding them', () => {
|
it('drops unknown event types instead of forwarding them', () => {
|
||||||
expect(parseVoiceServerEvent('{"type":"response.create"}')).toBeNull();
|
expect(parseVoiceServerEvent('{"type":"response.create"}')).toBeNull();
|
||||||
expect(parseVoiceServerEvent('{"type":"continue"}')).toBeNull();
|
expect(parseVoiceServerEvent('{"type":"continue"}')).toBeNull();
|
||||||
expect(parseVoiceServerEvent('{"type":"answer_limited2","turn_ref":"t1","reason":"output_token_limit"}')).toBeNull();
|
expect(
|
||||||
|
parseVoiceServerEvent(
|
||||||
|
'{"type":"answer_limited2","turn_ref":"t1","reason":"output_token_limit"}',
|
||||||
|
),
|
||||||
|
).toBeNull();
|
||||||
expect(parseVoiceServerEvent('{"type":42}')).toBeNull();
|
expect(parseVoiceServerEvent('{"type":42}')).toBeNull();
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -160,13 +193,19 @@ describe('voice-event.validator', () => {
|
|||||||
it('drops frames with a broken audio/session/interruption payload', () => {
|
it('drops frames with a broken audio/session/interruption payload', () => {
|
||||||
expect(parseVoiceServerEvent('{"type":"audio_started"}')).toBeNull();
|
expect(parseVoiceServerEvent('{"type":"audio_started"}')).toBeNull();
|
||||||
expect(parseVoiceServerEvent('{"type":"audio_started","audio_ref":""}')).toBeNull();
|
expect(parseVoiceServerEvent('{"type":"audio_started","audio_ref":""}')).toBeNull();
|
||||||
expect(parseVoiceServerEvent('{"type":"turn_interrupted","turn_ref":"t1","cancelled_tool_call_ids":[1]}')).toBeNull();
|
expect(
|
||||||
|
parseVoiceServerEvent(
|
||||||
|
'{"type":"turn_interrupted","turn_ref":"t1","cancelled_tool_call_ids":[1]}',
|
||||||
|
),
|
||||||
|
).toBeNull();
|
||||||
expect(
|
expect(
|
||||||
parseVoiceServerEvent(
|
parseVoiceServerEvent(
|
||||||
'{"type":"session_ready","session_id":"s","input_audio":{"encoding":"pcm_s16le","sample_rate":24000,"channels":1}}',
|
'{"type":"session_ready","session_id":"s","input_audio":{"encoding":"pcm_s16le","sample_rate":24000,"channels":1}}',
|
||||||
),
|
),
|
||||||
).toBeNull();
|
).toBeNull();
|
||||||
expect(parseVoiceServerEvent('{"type":"sources","turn_ref":"t1","sources":"none"}')).toBeNull();
|
expect(
|
||||||
|
parseVoiceServerEvent('{"type":"sources","turn_ref":"t1","sources":"none"}'),
|
||||||
|
).toBeNull();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -120,7 +120,10 @@ function isVoiceServerEvent(value: unknown): value is VoiceServerEvent {
|
|||||||
case 'audio_ended':
|
case 'audio_ended':
|
||||||
return (
|
return (
|
||||||
isApplicationReference(value['audio_ref']) &&
|
isApplicationReference(value['audio_ref']) &&
|
||||||
(value['turn_ref'] === undefined || isApplicationReference(value['turn_ref']))
|
(value['turn_ref'] === undefined || isApplicationReference(value['turn_ref'])) &&
|
||||||
|
(value['type'] !== 'audio_ended' ||
|
||||||
|
value['sent_bytes'] === undefined ||
|
||||||
|
(Number.isSafeInteger(value['sent_bytes']) && (value['sent_bytes'] as number) >= 0))
|
||||||
);
|
);
|
||||||
|
|
||||||
case 'turn_interrupted':
|
case 'turn_interrupted':
|
||||||
|
|||||||
@@ -10,7 +10,11 @@ import { VoiceStreamService } from './voice-stream.service';
|
|||||||
import { VOICE_TRANSPORT_FACTORY, VoiceTransport, VoiceTransportHandlers } from './voice-transport';
|
import { VOICE_TRANSPORT_FACTORY, VoiceTransport, VoiceTransportHandlers } from './voice-transport';
|
||||||
import { PlaybackProgressMessage, VoiceServerEvent } from './voice-stream.types';
|
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 = {
|
const CONFIG = {
|
||||||
revision: 1,
|
revision: 1,
|
||||||
assistant_name: 'دستیار',
|
assistant_name: 'دستیار',
|
||||||
@@ -34,7 +38,8 @@ const READY_EVENT: VoiceServerEvent = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const OVERFLOW_MESSAGE = 'حجم صدای در حال پخش از محدودهٔ مجاز گذشت و گفتگو بهطور ایمن پایان یافت.';
|
const OVERFLOW_MESSAGE = 'حجم صدای در حال پخش از محدودهٔ مجاز گذشت و گفتگو بهطور ایمن پایان یافت.';
|
||||||
const SEND_OVERFLOW_MESSAGE = 'حجم صدای ارسالی از محدودهٔ مجاز گذشت و گفتگو بهطور ایمن پایان یافت.';
|
const SEND_OVERFLOW_MESSAGE =
|
||||||
|
'حجم صدای ارسالی از محدودهٔ مجاز گذشت و گفتگو بهطور ایمن پایان یافت.';
|
||||||
|
|
||||||
/** Flush pending microtasks/timers so the service reaches a stable await point. */
|
/** Flush pending microtasks/timers so the service reaches a stable await point. */
|
||||||
const flush = (): Promise<void> => new Promise((resolve) => setTimeout(resolve, 5));
|
const flush = (): Promise<void> => new Promise((resolve) => setTimeout(resolve, 5));
|
||||||
@@ -96,7 +101,9 @@ describe('VoiceStreamService (backend handoff contract)', () => {
|
|||||||
return Promise.resolve();
|
return Promise.resolve();
|
||||||
}),
|
}),
|
||||||
sendAudio: vi.fn(),
|
sendAudio: vi.fn(),
|
||||||
sendControl: vi.fn().mockImplementation((message: PlaybackProgressMessage) => controls.push(message)),
|
sendControl: vi
|
||||||
|
.fn()
|
||||||
|
.mockImplementation((message: PlaybackProgressMessage) => controls.push(message)),
|
||||||
close: vi.fn(),
|
close: vi.fn(),
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -138,7 +145,9 @@ describe('VoiceStreamService (backend handoff contract)', () => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function firstEndedError(): Promise<string | undefined> {
|
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 () => {
|
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 },
|
output_audio: { encoding: 'pcm_s16le', sample_rate: 24000, channels: 1 },
|
||||||
});
|
});
|
||||||
const result = await started;
|
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 () => {
|
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 () => {
|
it('reports the final real played progress when the turn is interrupted', async () => {
|
||||||
await startConnected();
|
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' });
|
transportHandlers?.onEvent({ type: 'audio_started', audio_ref: 'aud-2' });
|
||||||
engineHandlers?.onPlaybackProgress('aud-2', 300);
|
engineHandlers?.onPlaybackProgress('aud-2', 300);
|
||||||
controls = [];
|
controls = [];
|
||||||
@@ -235,9 +254,7 @@ describe('VoiceStreamService (backend handoff contract)', () => {
|
|||||||
// The worklet answers `clear` with its final cumulative report for the ref.
|
// The worklet answers `clear` with its final cumulative report for the ref.
|
||||||
engineHandlers?.onPlaybackProgress('aud-2', 780);
|
engineHandlers?.onPlaybackProgress('aud-2', 780);
|
||||||
|
|
||||||
expect(controls).toEqual([
|
expect(controls).toEqual([{ type: 'playback_progress', audio_ref: 'aud-2', played_ms: 780 }]);
|
||||||
{ type: 'playback_progress', audio_ref: 'aud-2', played_ms: 780 },
|
|
||||||
]);
|
|
||||||
expect(service.messages().find((m) => m.id === 'turn-1:assistant')?.interrupted).toBe(true);
|
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);
|
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 () => {
|
it('drains on audio_ended so the ref reaches its true final progress (not solely on transcript)', async () => {
|
||||||
await startConnected();
|
await startConnected();
|
||||||
transportHandlers?.onEvent({ type: 'audio_started', audio_ref: 'aud-1' });
|
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' });
|
transportHandlers?.onEvent({ type: 'audio_ended', audio_ref: 'aud-1' });
|
||||||
expect(engineFlush).toHaveBeenCalledTimes(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({
|
transportHandlers?.onEvent({
|
||||||
type: 'transcript',
|
type: 'transcript',
|
||||||
turn_ref: 'turn-1',
|
turn_ref: 'turn-1',
|
||||||
@@ -343,7 +410,7 @@ describe('VoiceStreamService (backend handoff contract)', () => {
|
|||||||
text: '…',
|
text: '…',
|
||||||
status: 'completed',
|
status: 'completed',
|
||||||
});
|
});
|
||||||
expect(engineFlush).toHaveBeenCalledTimes(2);
|
expect(engineFlush).toHaveBeenCalledTimes(1);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('requires a fresh conversation after CONTEXT_REVOKED and drops the old attempt', async () => {
|
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 },
|
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(sessionStorage.getItem('voice_creation_attempt')).toBeNull();
|
||||||
expect(service.connection()).toBe('disconnected');
|
expect(service.connection()).toBe('disconnected');
|
||||||
});
|
});
|
||||||
@@ -398,9 +467,27 @@ describe('VoiceStreamService (backend handoff contract)', () => {
|
|||||||
it('marks partial then completed transcripts final', async () => {
|
it('marks partial then completed transcripts final', async () => {
|
||||||
await startConnected();
|
await startConnected();
|
||||||
|
|
||||||
transportHandlers?.onEvent({ type: 'transcript', turn_ref: 't1', role: 'assistant', text: 'سلام', status: 'partial' });
|
transportHandlers?.onEvent({
|
||||||
transportHandlers?.onEvent({ type: 'transcript', turn_ref: 't1', role: 'assistant', text: 'سلام و خوب', status: 'partial' });
|
type: 'transcript',
|
||||||
transportHandlers?.onEvent({ type: 'transcript', turn_ref: 't1', role: 'assistant', text: 'سلام و خوب', status: 'completed' });
|
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');
|
const assistant = service.messages().find((m) => m.id === 't1:assistant');
|
||||||
expect(assistant?.text).toBe('سلام و خوب');
|
expect(assistant?.text).toBe('سلام و خوب');
|
||||||
@@ -411,8 +498,20 @@ describe('VoiceStreamService (backend handoff contract)', () => {
|
|||||||
await startConnected();
|
await startConnected();
|
||||||
|
|
||||||
// The server streams assistant partials before the user transcript for the same turn.
|
// 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({
|
||||||
transportHandlers?.onEvent({ type: 'transcript', turn_ref: 'turn-1', role: 'user', text: 'سلام', status: 'completed' });
|
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 list = service.messages();
|
||||||
const userIndex = list.findIndex((m) => m.id === 'turn-1:user');
|
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 () => {
|
it('keeps user→assistant order and stable turn order across turns', async () => {
|
||||||
await startConnected();
|
await startConnected();
|
||||||
|
|
||||||
transportHandlers?.onEvent({ type: 'transcript', turn_ref: 't1', role: 'user', text: 'سوال ۱', status: 'completed' });
|
transportHandlers?.onEvent({
|
||||||
transportHandlers?.onEvent({ type: 'transcript', turn_ref: 't1', role: 'assistant', text: 'پاسخ ۱', status: 'completed' });
|
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
|
// turn 2's assistant lands before its user transcript
|
||||||
transportHandlers?.onEvent({ type: 'transcript', turn_ref: 't2', role: 'assistant', text: 'پاسخ ۲', status: 'partial' });
|
transportHandlers?.onEvent({
|
||||||
transportHandlers?.onEvent({ type: 'transcript', turn_ref: 't2', role: 'user', text: 'سوال ۲', status: 'completed' });
|
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([
|
expect(service.messages().map((m) => m.id)).toEqual([
|
||||||
't1:user',
|
't1:user',
|
||||||
@@ -445,9 +568,17 @@ describe('VoiceStreamService (backend handoff contract)', () => {
|
|||||||
transportHandlers?.onEvent({
|
transportHandlers?.onEvent({
|
||||||
type: 'sources',
|
type: 'sources',
|
||||||
turn_ref: 't1',
|
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']);
|
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 () => {
|
it('preserves repeated legitimate partial words (no content-based dedup)', async () => {
|
||||||
await startConnected();
|
await startConnected();
|
||||||
|
|
||||||
transportHandlers?.onEvent({ type: 'transcript', turn_ref: 't1', role: 'assistant', text: 'بله', status: 'partial' });
|
transportHandlers?.onEvent({
|
||||||
transportHandlers?.onEvent({ type: 'transcript', turn_ref: 't1', role: 'assistant', text: ' بله', status: 'partial' });
|
type: 'transcript',
|
||||||
transportHandlers?.onEvent({ type: 'transcript', turn_ref: 't1', role: 'assistant', text: ' بله', status: 'partial' });
|
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('بله بله بله');
|
expect(service.messages()[0].text).toBe('بله بله بله');
|
||||||
});
|
});
|
||||||
@@ -701,7 +850,11 @@ describe('VoiceStreamService (backend handoff contract)', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const list = service.messages();
|
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')?.text).toBe('سوال اول');
|
||||||
expect(list.find((m) => m.id === 'turn-1:user')?.limited).toBeFalsy();
|
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-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 () => {
|
it('cannot let an old session marker contaminate a new session', async () => {
|
||||||
await startConnected(); // session A
|
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 service.close();
|
||||||
|
|
||||||
await startConnected(); // session B
|
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.
|
// The worklet answers `clear` with its final cumulative report for the ref.
|
||||||
engineHandlers?.onPlaybackProgress('aud-2', 780);
|
engineHandlers?.onPlaybackProgress('aud-2', 780);
|
||||||
|
|
||||||
expect(controls).toEqual([
|
expect(controls).toEqual([{ type: 'playback_progress', audio_ref: 'aud-2', played_ms: 780 }]);
|
||||||
{ type: 'playback_progress', audio_ref: 'aud-2', played_ms: 780 },
|
|
||||||
]);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
it('never auto-continues, fabricates a control message or recreates the session', async () => {
|
it('never auto-continues, fabricates a control message or recreates the session', async () => {
|
||||||
|
|||||||
@@ -27,8 +27,7 @@ export type VoiceStartFailure =
|
|||||||
| 'overflow';
|
| 'overflow';
|
||||||
|
|
||||||
export type VoiceStartResult =
|
export type VoiceStartResult =
|
||||||
| { ok: true }
|
{ ok: true } | { ok: false; reason: VoiceStartFailure; message: string };
|
||||||
| { ok: false; reason: VoiceStartFailure; message: string };
|
|
||||||
|
|
||||||
type TranscriptEvent = Extract<VoiceServerEvent, { type: 'transcript' }>;
|
type TranscriptEvent = Extract<VoiceServerEvent, { type: 'transcript' }>;
|
||||||
type SourcesEvent = Extract<VoiceServerEvent, { type: 'sources' }>;
|
type SourcesEvent = Extract<VoiceServerEvent, { type: 'sources' }>;
|
||||||
@@ -58,7 +57,8 @@ interface TeardownOptions {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const MESSAGES = {
|
const MESSAGES = {
|
||||||
unsupported: 'گفتگوی صوتی در این مرورگر پشتیبانی نمیشود (اتصال امن HTTPS و مرورگر جدید لازم است).',
|
unsupported:
|
||||||
|
'گفتگوی صوتی در این مرورگر پشتیبانی نمیشود (اتصال امن HTTPS و مرورگر جدید لازم است).',
|
||||||
micDenied: 'دسترسی به میکروفون رد شد. اجازهی دسترسی را در تنظیمات مرورگر فعال کنید.',
|
micDenied: 'دسترسی به میکروفون رد شد. اجازهی دسترسی را در تنظیمات مرورگر فعال کنید.',
|
||||||
micUnavailable: 'میکروفونی پیدا نشد یا در حال استفادهی برنامهی دیگری است.',
|
micUnavailable: 'میکروفونی پیدا نشد یا در حال استفادهی برنامهی دیگری است.',
|
||||||
micLost: 'اتصال میکروفون قطع شد و گفتگو پایان یافت.',
|
micLost: 'اتصال میکروفون قطع شد و گفتگو پایان یافت.',
|
||||||
@@ -147,7 +147,6 @@ export class VoiceStreamService {
|
|||||||
private cleanupPromise: Promise<void> | null = null;
|
private cleanupPromise: Promise<void> | null = null;
|
||||||
private session = 0;
|
private session = 0;
|
||||||
private streaming = false;
|
private streaming = false;
|
||||||
private turnEnded = false;
|
|
||||||
private audioGenerationDone = false; // server finished sending this audio_ref's frames
|
private audioGenerationDone = false; // server finished sending this audio_ref's frames
|
||||||
private interruptTimer: ReturnType<typeof setTimeout> | null = null;
|
private interruptTimer: ReturnType<typeof setTimeout> | null = null;
|
||||||
private settleTimer: ReturnType<typeof setTimeout> | null = null;
|
private settleTimer: ReturnType<typeof setTimeout> | null = null;
|
||||||
@@ -164,6 +163,10 @@ export class VoiceStreamService {
|
|||||||
/** Latest cumulative played_ms actually consumed by the worklet, per server audio_ref. */
|
/** Latest cumulative played_ms actually consumed by the worklet, per server audio_ref. */
|
||||||
private readonly playedMsByRef = new Map<string, number>();
|
private readonly playedMsByRef = new Map<string, number>();
|
||||||
private currentAudioRef: string | null = null;
|
private currentAudioRef: string | null = null;
|
||||||
|
private readonly seenAudioRefs = new Set<string>();
|
||||||
|
private currentAudioTurnRef: string | null = null;
|
||||||
|
private currentAudioReceivedBytes = 0;
|
||||||
|
private currentAudioSentBytes: number | null = null;
|
||||||
private progressWaiters: Array<() => void> = [];
|
private progressWaiters: Array<() => void> = [];
|
||||||
/** Turns whose answer the server marked limited (bounded; marker may precede its row). */
|
/** Turns whose answer the server marked limited (bounded; marker may precede its row). */
|
||||||
private readonly limitedTurns = new Set<string>();
|
private readonly limitedTurns = new Set<string>();
|
||||||
@@ -202,6 +205,7 @@ export class VoiceStreamService {
|
|||||||
this.lastConversationId = null;
|
this.lastConversationId = null;
|
||||||
this.currentAudioRef = null;
|
this.currentAudioRef = null;
|
||||||
this.playedMsByRef.clear();
|
this.playedMsByRef.clear();
|
||||||
|
this.seenAudioRefs.clear();
|
||||||
this.state.set('IDLE');
|
this.state.set('IDLE');
|
||||||
this.connection.set('connecting');
|
this.connection.set('connecting');
|
||||||
|
|
||||||
@@ -213,11 +217,12 @@ export class VoiceStreamService {
|
|||||||
try {
|
try {
|
||||||
await this.engine.start({
|
await this.engine.start({
|
||||||
onFrame: (pcm) => this.onMicFrame(pcm),
|
onFrame: (pcm) => this.onMicFrame(pcm),
|
||||||
onPlaybackIdle: () => this.ngZone.run(() => this.onPlaybackIdle()),
|
onPlaybackIdle: (audioRef) => this.ngZone.run(() => this.onPlaybackIdle(audioRef)),
|
||||||
onMicEnded: () => this.ngZone.run(() => this.failSession(MESSAGES.micLost, session)),
|
onMicEnded: () => this.ngZone.run(() => this.failSession(MESSAGES.micLost, session)),
|
||||||
onPlaybackProgress: (audioRef, playedMs) =>
|
onPlaybackProgress: (audioRef, playedMs) =>
|
||||||
this.ngZone.run(() => this.onPlaybackProgress(audioRef, playedMs)),
|
this.ngZone.run(() => this.onPlaybackProgress(audioRef, playedMs)),
|
||||||
onPlaybackOverflow: () => this.ngZone.run(() => this.failSession(MESSAGES.overflow, session)),
|
onPlaybackOverflow: () =>
|
||||||
|
this.ngZone.run(() => this.failSession(MESSAGES.overflow, session)),
|
||||||
});
|
});
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
return this.abortStart(session, this.mapEngineError(err));
|
return this.abortStart(session, this.mapEngineError(err));
|
||||||
@@ -271,12 +276,17 @@ export class VoiceStreamService {
|
|||||||
onEvent: (event) => this.ngZone.run(() => this.onServerEvent(event, session)),
|
onEvent: (event) => this.ngZone.run(() => this.onServerEvent(event, session)),
|
||||||
onAudio: (chunk) => this.onServerAudio(chunk, session),
|
onAudio: (chunk) => this.onServerAudio(chunk, session),
|
||||||
onClose: (info) =>
|
onClose: (info) =>
|
||||||
this.ngZone.run(() => this.failSession(MESSAGES.disconnected, session, this.describeSocketClose(info))),
|
this.ngZone.run(() =>
|
||||||
|
this.failSession(MESSAGES.disconnected, session, this.describeSocketClose(info)),
|
||||||
|
),
|
||||||
onOverflow: (which) =>
|
onOverflow: (which) =>
|
||||||
this.ngZone.run(() =>
|
this.ngZone.run(() =>
|
||||||
// Playback queue overflow and capture/send overflow are different faults with
|
// Playback queue overflow and capture/send overflow are different faults with
|
||||||
// different causes; give each its own message instead of one shared string.
|
// different causes; give each its own message instead of one shared string.
|
||||||
this.failSession(which === 'send' ? MESSAGES.sendOverflow : MESSAGES.overflow, session),
|
this.failSession(
|
||||||
|
which === 'send' ? MESSAGES.sendOverflow : MESSAGES.overflow,
|
||||||
|
session,
|
||||||
|
),
|
||||||
),
|
),
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
@@ -361,7 +371,10 @@ export class VoiceStreamService {
|
|||||||
if (this.isOpen() || this.attempt !== attempt) return true;
|
if (this.isOpen() || this.attempt !== attempt) return true;
|
||||||
let sessionId = attempt.sessionId;
|
let sessionId = attempt.sessionId;
|
||||||
if (!sessionId) {
|
if (!sessionId) {
|
||||||
const existing = await this.api.getVoiceSessionByRequest(me.csrf_token, attempt.sessionRequestId);
|
const existing = await this.api.getVoiceSessionByRequest(
|
||||||
|
me.csrf_token,
|
||||||
|
attempt.sessionRequestId,
|
||||||
|
);
|
||||||
sessionId = existing?.session_id ?? null;
|
sessionId = existing?.session_id ?? null;
|
||||||
}
|
}
|
||||||
if (this.isOpen() || this.attempt !== attempt) return true;
|
if (this.isOpen() || this.attempt !== attempt) return true;
|
||||||
@@ -418,6 +431,7 @@ export class VoiceStreamService {
|
|||||||
|
|
||||||
private onServerAudio(chunk: ArrayBuffer, session: number): void {
|
private onServerAudio(chunk: ArrayBuffer, session: number): void {
|
||||||
if (session !== this.session || !this.streaming) return;
|
if (session !== this.session || !this.streaming) return;
|
||||||
|
this.currentAudioReceivedBytes += chunk.byteLength;
|
||||||
this.engine.enqueuePlayback(chunk, this.currentAudioRef);
|
this.engine.enqueuePlayback(chunk, this.currentAudioRef);
|
||||||
this.clearSettleTimer();
|
this.clearSettleTimer();
|
||||||
|
|
||||||
@@ -511,8 +525,18 @@ export class VoiceStreamService {
|
|||||||
break;
|
break;
|
||||||
|
|
||||||
case 'audio_started':
|
case 'audio_started':
|
||||||
|
if (
|
||||||
|
this.seenAudioRefs.has(event.audio_ref) ||
|
||||||
|
(event.turn_ref && this.interruptedTurns.has(event.turn_ref))
|
||||||
|
)
|
||||||
|
break;
|
||||||
|
this.seenAudioRefs.add(event.audio_ref);
|
||||||
this.currentAudioRef = event.audio_ref;
|
this.currentAudioRef = event.audio_ref;
|
||||||
|
this.currentAudioTurnRef = event.turn_ref ?? null;
|
||||||
|
this.currentAudioReceivedBytes = 0;
|
||||||
|
this.currentAudioSentBytes = null;
|
||||||
this.audioGenerationDone = false; // frames for this ref are now streaming in
|
this.audioGenerationDone = false; // frames for this ref are now streaming in
|
||||||
|
this.clearSettleTimer();
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case 'audio_ended':
|
case 'audio_ended':
|
||||||
@@ -520,8 +544,23 @@ export class VoiceStreamService {
|
|||||||
// the ref's FINAL playback progress reaches its true duration (no phantom outstanding
|
// the ref's FINAL playback progress reaches its true duration (no phantom outstanding
|
||||||
// sample the backend would read as a stall). This drives the drain on generation
|
// sample the backend would read as a stall). This drives the drain on generation
|
||||||
// completion, cooperating with — not depending solely on — the completed transcript.
|
// completion, cooperating with — not depending solely on — the completed transcript.
|
||||||
|
if (
|
||||||
|
event.audio_ref !== this.currentAudioRef ||
|
||||||
|
this.audioGenerationDone ||
|
||||||
|
(event.turn_ref &&
|
||||||
|
this.currentAudioTurnRef &&
|
||||||
|
event.turn_ref !== this.currentAudioTurnRef)
|
||||||
|
)
|
||||||
|
break;
|
||||||
this.audioGenerationDone = true;
|
this.audioGenerationDone = true;
|
||||||
this.engine.flushPlayback();
|
this.currentAudioSentBytes = event.sent_bytes ?? null;
|
||||||
|
if (event.sent_bytes !== undefined && event.sent_bytes !== this.currentAudioReceivedBytes) {
|
||||||
|
console.warn('Voice audio delivery mismatch', {
|
||||||
|
sentBytes: event.sent_bytes,
|
||||||
|
receivedBytes: this.currentAudioReceivedBytes,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
this.engine.flushPlayback(this.currentAudioRef);
|
||||||
break;
|
break;
|
||||||
|
|
||||||
case 'turn_interrupted':
|
case 'turn_interrupted':
|
||||||
@@ -556,13 +595,7 @@ export class VoiceStreamService {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (event.status === 'completed') {
|
if (event.status === 'completed') return;
|
||||||
// All text for this turn is out. Drain the queue only once generation has ended
|
|
||||||
// (audio_ended); otherwise the tail would be finalized while audio is still streamed.
|
|
||||||
this.turnEnded = true;
|
|
||||||
if (this.audioGenerationDone) this.engine.flushPlayback();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (event.status === 'limited') {
|
if (event.status === 'limited') {
|
||||||
// An answer state, not a playback or session event: the limited transcript does
|
// An answer state, not a playback or session event: the limited transcript does
|
||||||
@@ -596,7 +629,7 @@ export class VoiceStreamService {
|
|||||||
* bounded settle the drain path uses.
|
* bounded settle the drain path uses.
|
||||||
*/
|
*/
|
||||||
private scheduleLimitedSettle(): void {
|
private scheduleLimitedSettle(): void {
|
||||||
if (this.state() !== 'PROCESSING' || this.settleTimer) return;
|
if (this.state() !== 'PROCESSING' || this.currentAudioRef || this.settleTimer) return;
|
||||||
this.settleTimer = setTimeout(() => {
|
this.settleTimer = setTimeout(() => {
|
||||||
this.settleTimer = null;
|
this.settleTimer = null;
|
||||||
if (this.state() === 'PROCESSING') this.finishTurn();
|
if (this.state() === 'PROCESSING') this.finishTurn();
|
||||||
@@ -605,8 +638,16 @@ export class VoiceStreamService {
|
|||||||
|
|
||||||
/** Server-side barge-in: the user spoke over the assistant. */
|
/** Server-side barge-in: the user spoke over the assistant. */
|
||||||
private onTurnInterrupted(turnRef: string): void {
|
private onTurnInterrupted(turnRef: string): void {
|
||||||
|
if (this.currentAudioTurnRef && this.currentAudioTurnRef !== turnRef) {
|
||||||
|
this.markInterrupted(turnRef);
|
||||||
|
return;
|
||||||
|
}
|
||||||
this.engine.clearPlayback(); // the worklet posts the final progress for the active ref
|
this.engine.clearPlayback(); // the worklet posts the final progress for the active ref
|
||||||
this.turnEnded = false;
|
if (!this.currentAudioTurnRef || this.currentAudioTurnRef === turnRef) {
|
||||||
|
this.currentAudioRef = null;
|
||||||
|
this.currentAudioTurnRef = null;
|
||||||
|
this.audioGenerationDone = false;
|
||||||
|
}
|
||||||
this.clearSettleTimer();
|
this.clearSettleTimer();
|
||||||
this.markInterrupted(turnRef);
|
this.markInterrupted(turnRef);
|
||||||
|
|
||||||
@@ -646,7 +687,6 @@ export class VoiceStreamService {
|
|||||||
|
|
||||||
// The session survives a retryable failure (e.g. SEARCH_TIMEOUT): drop the failed turn and keep listening.
|
// The session survives a retryable failure (e.g. SEARCH_TIMEOUT): drop the failed turn and keep listening.
|
||||||
this.engine.clearPlayback();
|
this.engine.clearPlayback();
|
||||||
this.turnEnded = false;
|
|
||||||
this.clearSettleTimer();
|
this.clearSettleTimer();
|
||||||
this.finalizeAssistant();
|
this.finalizeAssistant();
|
||||||
if (this.state() === 'PROCESSING' || this.state() === 'SPEAKING') this.state.set('LISTENING');
|
if (this.state() === 'PROCESSING' || this.state() === 'SPEAKING') this.state.set('LISTENING');
|
||||||
@@ -655,29 +695,28 @@ export class VoiceStreamService {
|
|||||||
|
|
||||||
// ---- end of an assistant turn ----------------------------------------------
|
// ---- end of an assistant turn ----------------------------------------------
|
||||||
|
|
||||||
private onPlaybackIdle(): void {
|
private onPlaybackIdle(audioRef?: string | null): void {
|
||||||
const state = this.state();
|
if (audioRef && audioRef !== this.currentAudioRef) return;
|
||||||
if (state !== 'SPEAKING' && state !== 'PROCESSING') return;
|
if (this.state() !== 'SPEAKING' && this.state() !== 'PROCESSING') return;
|
||||||
|
// A dry queue while generation is open is an underrun, not the end of a turn.
|
||||||
if (this.turnEnded) {
|
if (this.audioGenerationDone && this.currentAudioRef) {
|
||||||
|
const sent = this.currentAudioSentBytes;
|
||||||
|
const playedMs = this.playedMsByRef.get(this.currentAudioRef) ?? 0;
|
||||||
|
// played_ms is floored; less than one millisecond (48 bytes) may remain in that unit.
|
||||||
|
if (sent !== null && Math.abs(sent - playedMs * 48) >= 48) {
|
||||||
|
console.warn('Voice audio playback mismatch', { sentBytes: sent, playedMs });
|
||||||
|
}
|
||||||
this.finishTurn();
|
this.finishTurn();
|
||||||
} else if (state === 'SPEAKING') {
|
|
||||||
// The buffer drained but no `completed` transcript arrived (yet). If no more audio comes, the turn is over.
|
|
||||||
this.clearSettleTimer();
|
|
||||||
this.settleTimer = setTimeout(() => {
|
|
||||||
this.settleTimer = null;
|
|
||||||
if (this.state() === 'SPEAKING') this.finishTurn();
|
|
||||||
}, this.config.settleMs);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private finishTurn(): void {
|
private finishTurn(): void {
|
||||||
this.turnEnded = false;
|
this.audioGenerationDone = false;
|
||||||
|
this.currentAudioRef = null;
|
||||||
|
this.currentAudioTurnRef = null;
|
||||||
this.clearSettleTimer();
|
this.clearSettleTimer();
|
||||||
this.finalizeAssistant();
|
|
||||||
this.state.set('LISTENING');
|
this.state.set('LISTENING');
|
||||||
}
|
}
|
||||||
|
|
||||||
// ---- transcript ------------------------------------------------------------
|
// ---- transcript ------------------------------------------------------------
|
||||||
|
|
||||||
private upsertTranscript(event: TranscriptEvent): void {
|
private upsertTranscript(event: TranscriptEvent): void {
|
||||||
@@ -688,9 +727,7 @@ export class VoiceStreamService {
|
|||||||
// `limited` is valid only for assistant rows (the transport rejects the rest), and a
|
// `limited` is valid only for assistant rows (the transport rejects the rest), and a
|
||||||
// user transcript of a limited turn stays a plain user row.
|
// user transcript of a limited turn stays a plain user row.
|
||||||
const attachLimited =
|
const attachLimited =
|
||||||
event.role === 'assistant' &&
|
event.role === 'assistant' && !interrupted && (limited || this.isLimitedTurn(event.turn_ref));
|
||||||
!interrupted &&
|
|
||||||
(limited || this.isLimitedTurn(event.turn_ref));
|
|
||||||
|
|
||||||
// A turn the server already interrupted cannot be restored by late assistant text
|
// A turn the server already interrupted cannot be restored by late assistant text
|
||||||
// (partial, completed or limited). The interrupted transcript itself still passes:
|
// (partial, completed or limited). The interrupted transcript itself still passes:
|
||||||
@@ -802,7 +839,9 @@ export class VoiceStreamService {
|
|||||||
// not seen yet sorts after all existing ones.
|
// not seen yet sorts after all existing ones.
|
||||||
const turns: string[] = [];
|
const turns: string[] = [];
|
||||||
for (const m of list) if (!turns.includes(m.turnRef)) turns.push(m.turnRef);
|
for (const m of list) if (!turns.includes(m.turnRef)) turns.push(m.turnRef);
|
||||||
const turnRank = turns.includes(message.turnRef) ? turns.indexOf(message.turnRef) : turns.length;
|
const turnRank = turns.includes(message.turnRef)
|
||||||
|
? turns.indexOf(message.turnRef)
|
||||||
|
: turns.length;
|
||||||
|
|
||||||
for (let i = 0; i < list.length; i++) {
|
for (let i = 0; i < list.length; i++) {
|
||||||
const existingTurn = turns.indexOf(list[i].turnRef);
|
const existingTurn = turns.indexOf(list[i].turnRef);
|
||||||
@@ -925,7 +964,8 @@ export class VoiceStreamService {
|
|||||||
// Start-only failure: release immediately (unmount-style) and best-effort V04 for any
|
// Start-only failure: release immediately (unmount-style) and best-effort V04 for any
|
||||||
// reservation that was made. Keep the attempt when it was an ambiguous reserve so the
|
// reservation that was made. Keep the attempt when it was an ambiguous reserve so the
|
||||||
// next start() reconciles it with the same ids instead of duplicating.
|
// next start() reconciles it with the same ids instead of duplicating.
|
||||||
if (session === this.session) void this.teardown({ ordered: false, closeRemote: true, keepAttempt });
|
if (session === this.session)
|
||||||
|
void this.teardown({ ordered: false, closeRemote: true, keepAttempt });
|
||||||
return this.failure(failure.reason, failure.message);
|
return this.failure(failure.reason, failure.message);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -993,7 +1033,10 @@ export class VoiceStreamService {
|
|||||||
// 2) supersede the session, then V04 /close (bounded), then 3) release.
|
// 2) supersede the session, then V04 /close (bounded), then 3) release.
|
||||||
invalidate();
|
invalidate();
|
||||||
if (options.closeRemote !== false && remote) {
|
if (options.closeRemote !== false && remote) {
|
||||||
await this.withTimeout(this.api.closeVoiceSession(remote.csrf, remote.sessionId), CLOSE_WAIT_MS);
|
await this.withTimeout(
|
||||||
|
this.api.closeVoiceSession(remote.csrf, remote.sessionId),
|
||||||
|
CLOSE_WAIT_MS,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
/* the session may already be closed/expired (e.g. 409 LIVE_SESSION_UNUSABLE) */
|
/* the session may already be closed/expired (e.g. 409 LIVE_SESSION_UNUSABLE) */
|
||||||
@@ -1071,7 +1114,6 @@ export class VoiceStreamService {
|
|||||||
};
|
};
|
||||||
|
|
||||||
private resetTurnFlags(): void {
|
private resetTurnFlags(): void {
|
||||||
this.turnEnded = false;
|
|
||||||
this.audioGenerationDone = false;
|
this.audioGenerationDone = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1224,7 +1266,8 @@ export class VoiceStreamService {
|
|||||||
|
|
||||||
private mapEngineError(err: unknown): { reason: VoiceStartFailure; message: string } {
|
private mapEngineError(err: unknown): { reason: VoiceStartFailure; message: string } {
|
||||||
if (err instanceof MicrophoneError) {
|
if (err instanceof MicrophoneError) {
|
||||||
if (err.code === 'unsupported') return { reason: 'unsupported', message: MESSAGES.unsupported };
|
if (err.code === 'unsupported')
|
||||||
|
return { reason: 'unsupported', message: MESSAGES.unsupported };
|
||||||
return {
|
return {
|
||||||
reason: 'mic',
|
reason: 'mic',
|
||||||
message: err.code === 'denied' ? MESSAGES.micDenied : MESSAGES.micUnavailable,
|
message: err.code === 'denied' ? MESSAGES.micDenied : MESSAGES.micUnavailable,
|
||||||
|
|||||||
@@ -72,7 +72,7 @@ export type VoiceServerEvent =
|
|||||||
}
|
}
|
||||||
| { type: 'sources'; turn_ref: string; tool_call_id?: string; sources: VoiceSource[] }
|
| { type: 'sources'; turn_ref: string; tool_call_id?: string; sources: VoiceSource[] }
|
||||||
| { type: 'audio_started'; audio_ref: string; turn_ref?: string }
|
| { type: 'audio_started'; audio_ref: string; turn_ref?: string }
|
||||||
| { type: 'audio_ended'; audio_ref: string; turn_ref?: string }
|
| { type: 'audio_ended'; audio_ref: string; turn_ref?: string; sent_bytes?: number }
|
||||||
| { type: 'turn_interrupted'; turn_ref: string; cancelled_tool_call_ids?: string[] }
|
| { type: 'turn_interrupted'; turn_ref: string; cancelled_tool_call_ids?: string[] }
|
||||||
/**
|
/**
|
||||||
* The assistant answer hit the backend's output-token limit. This is an ANSWER
|
* The assistant answer hit the backend's output-token limit. This is an ANSWER
|
||||||
@@ -153,7 +153,7 @@ export interface VoiceStreamConfig {
|
|||||||
outputSampleRate: number;
|
outputSampleRate: number;
|
||||||
frameMs: number;
|
frameMs: number;
|
||||||
connectTimeoutMs: number;
|
connectTimeoutMs: number;
|
||||||
/** After playback drains without a `completed` assistant transcript, wait this long, then return to LISTENING. */
|
/** Fallback only for a limited response with no audio reference. */
|
||||||
settleMs: number;
|
settleMs: number;
|
||||||
/** Folder (relative to <base href>) holding the two *.worklet.js files, served from the UI origin. */
|
/** Folder (relative to <base href>) holding the two *.worklet.js files, served from the UI origin. */
|
||||||
workletBasePath: string;
|
workletBasePath: string;
|
||||||
|
|||||||
Reference in New Issue
Block a user