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
@@ -27,8 +27,7 @@ export type VoiceStartFailure =
| 'overflow';
export type VoiceStartResult =
| { ok: true }
| { ok: false; reason: VoiceStartFailure; message: string };
{ ok: true } | { ok: false; reason: VoiceStartFailure; message: string };
type TranscriptEvent = Extract<VoiceServerEvent, { type: 'transcript' }>;
type SourcesEvent = Extract<VoiceServerEvent, { type: 'sources' }>;
@@ -58,7 +57,8 @@ interface TeardownOptions {
}
const MESSAGES = {
unsupported: 'گفتگوی صوتی در این مرورگر پشتیبانی نمی‌شود (اتصال امن HTTPS و مرورگر جدید لازم است).',
unsupported:
'گفتگوی صوتی در این مرورگر پشتیبانی نمی‌شود (اتصال امن HTTPS و مرورگر جدید لازم است).',
micDenied: 'دسترسی به میکروفون رد شد. اجازه‌ی دسترسی را در تنظیمات مرورگر فعال کنید.',
micUnavailable: 'میکروفونی پیدا نشد یا در حال استفاده‌ی برنامه‌ی دیگری است.',
micLost: 'اتصال میکروفون قطع شد و گفتگو پایان یافت.',
@@ -147,7 +147,6 @@ export class VoiceStreamService {
private cleanupPromise: Promise<void> | null = null;
private session = 0;
private streaming = false;
private turnEnded = false;
private audioGenerationDone = false; // server finished sending this audio_ref's frames
private interruptTimer: 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. */
private readonly playedMsByRef = new Map<string, number>();
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> = [];
/** Turns whose answer the server marked limited (bounded; marker may precede its row). */
private readonly limitedTurns = new Set<string>();
@@ -202,6 +205,7 @@ export class VoiceStreamService {
this.lastConversationId = null;
this.currentAudioRef = null;
this.playedMsByRef.clear();
this.seenAudioRefs.clear();
this.state.set('IDLE');
this.connection.set('connecting');
@@ -213,11 +217,12 @@ export class VoiceStreamService {
try {
await this.engine.start({
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)),
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) {
return this.abortStart(session, this.mapEngineError(err));
@@ -271,12 +276,17 @@ export class VoiceStreamService {
onEvent: (event) => this.ngZone.run(() => this.onServerEvent(event, session)),
onAudio: (chunk) => this.onServerAudio(chunk, session),
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) =>
this.ngZone.run(() =>
// Playback queue overflow and capture/send overflow are different faults with
// 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;
let sessionId = attempt.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;
}
if (this.isOpen() || this.attempt !== attempt) return true;
@@ -418,6 +431,7 @@ export class VoiceStreamService {
private onServerAudio(chunk: ArrayBuffer, session: number): void {
if (session !== this.session || !this.streaming) return;
this.currentAudioReceivedBytes += chunk.byteLength;
this.engine.enqueuePlayback(chunk, this.currentAudioRef);
this.clearSettleTimer();
@@ -511,8 +525,18 @@ export class VoiceStreamService {
break;
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.currentAudioTurnRef = event.turn_ref ?? null;
this.currentAudioReceivedBytes = 0;
this.currentAudioSentBytes = null;
this.audioGenerationDone = false; // frames for this ref are now streaming in
this.clearSettleTimer();
break;
case 'audio_ended':
@@ -520,8 +544,23 @@ export class VoiceStreamService {
// 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
// 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.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;
case 'turn_interrupted':
@@ -556,13 +595,7 @@ export class VoiceStreamService {
return;
}
if (event.status === 'completed') {
// 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 === 'completed') return;
if (event.status === 'limited') {
// 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.
*/
private scheduleLimitedSettle(): void {
if (this.state() !== 'PROCESSING' || this.settleTimer) return;
if (this.state() !== 'PROCESSING' || this.currentAudioRef || this.settleTimer) return;
this.settleTimer = setTimeout(() => {
this.settleTimer = null;
if (this.state() === 'PROCESSING') this.finishTurn();
@@ -605,8 +638,16 @@ export class VoiceStreamService {
/** Server-side barge-in: the user spoke over the assistant. */
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.turnEnded = false;
if (!this.currentAudioTurnRef || this.currentAudioTurnRef === turnRef) {
this.currentAudioRef = null;
this.currentAudioTurnRef = null;
this.audioGenerationDone = false;
}
this.clearSettleTimer();
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.
this.engine.clearPlayback();
this.turnEnded = false;
this.clearSettleTimer();
this.finalizeAssistant();
if (this.state() === 'PROCESSING' || this.state() === 'SPEAKING') this.state.set('LISTENING');
@@ -655,29 +695,28 @@ export class VoiceStreamService {
// ---- end of an assistant turn ----------------------------------------------
private onPlaybackIdle(): void {
const state = this.state();
if (state !== 'SPEAKING' && state !== 'PROCESSING') return;
if (this.turnEnded) {
private onPlaybackIdle(audioRef?: string | null): void {
if (audioRef && audioRef !== this.currentAudioRef) 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.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();
} 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 {
this.turnEnded = false;
this.audioGenerationDone = false;
this.currentAudioRef = null;
this.currentAudioTurnRef = null;
this.clearSettleTimer();
this.finalizeAssistant();
this.state.set('LISTENING');
}
// ---- transcript ------------------------------------------------------------
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
// user transcript of a limited turn stays a plain user row.
const attachLimited =
event.role === 'assistant' &&
!interrupted &&
(limited || this.isLimitedTurn(event.turn_ref));
event.role === 'assistant' && !interrupted && (limited || this.isLimitedTurn(event.turn_ref));
// A turn the server already interrupted cannot be restored by late assistant text
// (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.
const turns: string[] = [];
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++) {
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
// 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.
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);
}
@@ -993,7 +1033,10 @@ export class VoiceStreamService {
// 2) supersede the session, then V04 /close (bounded), then 3) release.
invalidate();
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 {
/* the session may already be closed/expired (e.g. 409 LIVE_SESSION_UNUSABLE) */
@@ -1071,7 +1114,6 @@ export class VoiceStreamService {
};
private resetTurnFlags(): void {
this.turnEnded = false;
this.audioGenerationDone = false;
}
@@ -1224,7 +1266,8 @@ export class VoiceStreamService {
private mapEngineError(err: unknown): { reason: VoiceStartFailure; message: string } {
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 {
reason: 'mic',
message: err.code === 'denied' ? MESSAGES.micDenied : MESSAGES.micUnavailable,