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:
@@ -32,6 +32,29 @@ type TranscriptEvent = Extract<VoiceServerEvent, { type: 'transcript' }>;
|
||||
type SourcesEvent = Extract<VoiceServerEvent, { type: 'sources' }>;
|
||||
type ErrorEvent = Extract<VoiceServerEvent, { type: 'error' }>;
|
||||
|
||||
/**
|
||||
* Options for the single per-session cleanup (`teardown`). One cleanup runs per session and
|
||||
* is shared by overflow, server error, socket close, manual Stop, unmount and start aborts.
|
||||
*/
|
||||
interface TeardownOptions {
|
||||
/** User-facing (Persian) failure message carried on sessionEnded$. */
|
||||
error?: string;
|
||||
/** Machine-readable cause (e.g. `ws close 1006`) carried on sessionEnded$. */
|
||||
detail?: string;
|
||||
/**
|
||||
* Intentional stop: final progress → V04 → release, the order the contract requires.
|
||||
* `false` (default) releases local resources immediately and sends V04 best-effort —
|
||||
* used for unmount / start-abort / page-leave, where instant release matters more.
|
||||
*/
|
||||
ordered?: boolean;
|
||||
/** Send V04 /close for this session (default true). */
|
||||
closeRemote?: boolean;
|
||||
/** Emit sessionEnded$ if the call reached connected (default true). */
|
||||
emitEnded?: boolean;
|
||||
/** Keep the persisted creation attempt (ambiguous reserve / page-leave). Default false. */
|
||||
keepAttempt?: boolean;
|
||||
}
|
||||
|
||||
const MESSAGES = {
|
||||
unsupported: 'گفتگوی صوتی در این مرورگر پشتیبانی نمیشود (اتصال امن HTTPS و مرورگر جدید لازم است).',
|
||||
micDenied: 'دسترسی به میکروفون رد شد. اجازهی دسترسی را در تنظیمات مرورگر فعال کنید.',
|
||||
@@ -47,6 +70,7 @@ const MESSAGES = {
|
||||
connect: 'اتصال به سرور صوتی برقرار نشد. دوباره تلاش کنید.',
|
||||
badFormat: 'فرمت صدای سرور با برنامه سازگار نیست.',
|
||||
overflow: 'حجم صدای در حال پخش از محدودهٔ مجاز گذشت و گفتگو بهطور ایمن پایان یافت.',
|
||||
sendOverflow: 'حجم صدای ارسالی از محدودهٔ مجاز گذشت و گفتگو بهطور ایمن پایان یافت.',
|
||||
disconnected: 'ارتباط با سرور قطع شد و گفتگو پایان یافت.',
|
||||
server: 'سرور گفتگوی صوتی با خطا مواجه شد.',
|
||||
contextRevoked: 'محتوای دانش تغییر کرده و مکالمهٔ قبلی دیگر معتبر نیست. گفتگوی جدیدی شروع کنید.',
|
||||
@@ -60,6 +84,8 @@ const INTERRUPTED_FLASH_MS = 150;
|
||||
const ERROR_BANNER_MS = 6000;
|
||||
/** Longest wait for the worklet's final playback report when closing a call. */
|
||||
const FINAL_PROGRESS_WAIT_MS = 300;
|
||||
/** Longest wait for V04 /close before releasing local resources anyway (the POST keeps running). */
|
||||
const CLOSE_WAIT_MS = 3000;
|
||||
|
||||
/**
|
||||
* One live voice call against the backend handoff contract (§7–§9):
|
||||
@@ -106,6 +132,8 @@ export class VoiceStreamService {
|
||||
|
||||
private transport: VoiceTransport | null = null;
|
||||
private remote: { sessionId: string; conversationId: string; csrf: string } | null = null;
|
||||
/** Single-flight guard: at most one cleanup runs per active session (one /close each). */
|
||||
private cleanupPromise: Promise<void> | null = null;
|
||||
private session = 0;
|
||||
private streaming = false;
|
||||
private turnEnded = false;
|
||||
@@ -149,6 +177,7 @@ export class VoiceStreamService {
|
||||
this.messages.set([]);
|
||||
this.muted.set(false);
|
||||
this.clearError();
|
||||
this.cleanupPromise = null;
|
||||
this.resetTurnFlags();
|
||||
this.lastConversationId = null;
|
||||
this.currentAudioRef = null;
|
||||
@@ -221,8 +250,14 @@ export class VoiceStreamService {
|
||||
transport.connect({
|
||||
onEvent: (event) => this.ngZone.run(() => this.onServerEvent(event, session)),
|
||||
onAudio: (chunk) => this.onServerAudio(chunk, session),
|
||||
onClose: () => this.ngZone.run(() => this.failSession(MESSAGES.disconnected, session)),
|
||||
onOverflow: () => this.ngZone.run(() => this.failSession(MESSAGES.overflow, session)),
|
||||
onClose: (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),
|
||||
),
|
||||
}),
|
||||
);
|
||||
} catch {
|
||||
@@ -262,39 +297,21 @@ export class VoiceStreamService {
|
||||
}
|
||||
|
||||
/**
|
||||
* Intentional close: final playback progress for the active audio_ref, then V04, and
|
||||
* only then the socket/audio teardown — the order required by the contract.
|
||||
* Intentional close: routes through the single per-session cleanup so final progress →
|
||||
* V04 /close → release happens exactly once and in the order the contract requires.
|
||||
* Concurrent callers (overflow / error / socket close / another Stop) reuse the same
|
||||
* cleanup and cannot send a second /close or a second teardown.
|
||||
*/
|
||||
async close(options: { error?: string } = {}): Promise<void> {
|
||||
if (!this.isOpen()) {
|
||||
// Idle: nothing to close. A persisted creation attempt from an ambiguous reserve
|
||||
// outcome is kept so the next start() reconciles it instead of duplicating it.
|
||||
return;
|
||||
}
|
||||
const remote = this.remote;
|
||||
// 1) final, worklet-computed playback progress for the ref that is still playing
|
||||
await this.reportFinalProgress();
|
||||
// 2) V04 before the transport closes
|
||||
if (remote) {
|
||||
try {
|
||||
await this.api.closeVoiceSession(remote.csrf, remote.sessionId);
|
||||
} catch {
|
||||
/* the session may already be closed/expired (e.g. 409 LIVE_SESSION_UNUSABLE) */
|
||||
}
|
||||
}
|
||||
// 3) release mic, worklets, AudioContext and the WebSocket
|
||||
const wasConnected = this.connection() === 'connected';
|
||||
const conversationId = this.remote?.conversationId ?? this.lastConversationId;
|
||||
// Invalidate pending async work BEFORE resolving the session_ready waiter, so a
|
||||
// start() still waiting sees a cancelled session instead of a connect failure.
|
||||
this.session++;
|
||||
this.rejectReady();
|
||||
this.finalizeAll();
|
||||
const messages = this.messages();
|
||||
this.teardown();
|
||||
if (wasConnected) {
|
||||
this.sessionEnded$.next({ conversationId, messages, error: options.error });
|
||||
}
|
||||
async close(options: { error?: string; detail?: string } = {}): Promise<void> {
|
||||
// Idle with no cleanup in flight: nothing to close. A persisted creation attempt from
|
||||
// an ambiguous reserve outcome is kept so the next start() reconciles it, not duplicates.
|
||||
if (this.connection() === 'disconnected' && !this.cleanupPromise) return;
|
||||
await this.teardown({
|
||||
ordered: true,
|
||||
closeRemote: true,
|
||||
error: options.error,
|
||||
detail: options.detail,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -366,7 +383,7 @@ export class VoiceStreamService {
|
||||
dispose(): void {
|
||||
this.rejectReady();
|
||||
if (!this.isOpen()) return; // keep an ambiguous attempt for reconciliation
|
||||
this.teardown();
|
||||
void this.teardown({ ordered: false, closeRemote: true, emitEnded: false });
|
||||
}
|
||||
|
||||
// ---- audio from the microphone (outside the zone) --------------------------
|
||||
@@ -533,7 +550,10 @@ export class VoiceStreamService {
|
||||
|
||||
private onServerError(event: ErrorEvent, session: number): void {
|
||||
const { message, retryable, code } = event.error;
|
||||
console.warn('VoiceStreamService: server error', code, event.error.request_id);
|
||||
// The server's `error` frame is the direct cause of a session ending here: below it
|
||||
// drives failSession → V04 /close. `code` + `request_id` alone hide the message and
|
||||
// any extra details, so log the whole frame.
|
||||
console.warn('VoiceStreamService: server error frame', event.error);
|
||||
|
||||
// The old conversation/session is no longer usable: the user must start a fresh one
|
||||
// (Gemini interruption can also require ending the session entirely).
|
||||
@@ -547,7 +567,7 @@ export class VoiceStreamService {
|
||||
}
|
||||
|
||||
if (!retryable) {
|
||||
this.failSession(message || MESSAGES.server, session);
|
||||
this.failSession(message || MESSAGES.server, session, `server error ${code}`);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -693,11 +713,29 @@ export class VoiceStreamService {
|
||||
|
||||
// ---- lifecycle -------------------------------------------------------------
|
||||
|
||||
private failSession(message: string, session: number): void {
|
||||
/**
|
||||
* The `CloseEvent` on the WebSocket carries the server's code and reason. Dropping it
|
||||
* (as this handler used to) leaves a generic "disconnected" banner and no clue why the
|
||||
* stream died, so the cause of an early disconnect cannot be diagnosed at all.
|
||||
*
|
||||
* Codes that matter in practice: 1000 = server ended the call normally, 1006 = the
|
||||
* connection dropped with no close frame (proxy/network), 1008/1009 = policy violation
|
||||
* (the server rejected a frame we sent), 1011 = server-side error.
|
||||
*/
|
||||
private describeSocketClose(info: { clean: boolean; code: number; reason: string }): string {
|
||||
const reason = info.reason ? ` reason="${info.reason}"` : '';
|
||||
const detail = `ws close ${info.code}${info.clean ? ' (clean)' : ''}${reason}`;
|
||||
console.warn(`VoiceStreamService: socket closed — ${detail}`);
|
||||
return detail;
|
||||
}
|
||||
|
||||
private failSession(message: string, session: number, detail?: string): void {
|
||||
if (session !== this.session || !this.isOpen()) return;
|
||||
// `close()` performs the ordered teardown (final progress → V04 → transport) and
|
||||
// emits sessionEnded$ exactly once, carrying the failure message.
|
||||
void this.close({ error: message });
|
||||
// `close()` runs the ordered single-flight cleanup (final progress → V04 → release)
|
||||
// and emits sessionEnded$ exactly once, carrying the first meaningful failure. The
|
||||
// `session`/isOpen guard above drops stale callbacks so an old session never ends a
|
||||
// newer one.
|
||||
void this.close({ error: message, detail });
|
||||
}
|
||||
|
||||
private abortStart(
|
||||
@@ -705,44 +743,130 @@ export class VoiceStreamService {
|
||||
failure: { reason: VoiceStartFailure; message: string },
|
||||
keepAttempt = false,
|
||||
): VoiceStartResult {
|
||||
if (session === this.session) this.teardown({ keepAttempt });
|
||||
// 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 });
|
||||
return this.failure(failure.reason, failure.message);
|
||||
}
|
||||
|
||||
/** Releases every resource; idempotent. Invalidates all pending async work via `session`. */
|
||||
private teardown(options: { keepAttempt?: boolean } = {}): void {
|
||||
this.session++;
|
||||
/**
|
||||
* The ONE cleanup per session. Every end path funnels through here: overflow, server
|
||||
* error, socket close, manual Stop, unmount, page-leave and start-abort. It is
|
||||
* single-flight (`cleanupPromise`) so concurrent triggers share one pass — one /close and
|
||||
* one resource release — and it marks the session stopping before any await, so stale
|
||||
* callbacks cannot end a newer session.
|
||||
*/
|
||||
private teardown(options: TeardownOptions = {}): Promise<void> {
|
||||
const existing = this.cleanupPromise;
|
||||
if (existing) return existing; // a cleanup for the active session is already running
|
||||
const promise = this.performTeardown(this.session, options).finally(() => {
|
||||
if (this.cleanupPromise === promise) this.cleanupPromise = null;
|
||||
});
|
||||
this.cleanupPromise = promise;
|
||||
return promise;
|
||||
}
|
||||
|
||||
private async performTeardown(session: number, options: TeardownOptions): Promise<void> {
|
||||
const wasConnected = this.connection() === 'connected';
|
||||
const conversationId = this.remote?.conversationId ?? this.lastConversationId;
|
||||
const remote = this.remote;
|
||||
const superseded = (): boolean => this.session !== session + 1;
|
||||
|
||||
// Stop admitting new media BEFORE any await.
|
||||
this.streaming = false;
|
||||
this.resetTurnFlags();
|
||||
this.clearSettleTimer();
|
||||
this.clearError();
|
||||
this.resolveProgressWaiters();
|
||||
this.currentAudioRef = null;
|
||||
if (this.interruptTimer) {
|
||||
clearTimeout(this.interruptTimer);
|
||||
this.interruptTimer = null;
|
||||
|
||||
const release = (): void => {
|
||||
// A newer session may have taken over during an await: never touch its resources.
|
||||
if (superseded()) return;
|
||||
this.releaseLocal(options);
|
||||
};
|
||||
|
||||
/** Drop all pending async work and supersede this session, so late callbacks are stale. */
|
||||
const invalidate = (): void => {
|
||||
if (this.session === session) this.session = session + 1;
|
||||
this.resetTurnFlags();
|
||||
this.rejectReady();
|
||||
this.resolveProgressWaiters();
|
||||
this.clearSettleTimer();
|
||||
if (this.interruptTimer) {
|
||||
clearTimeout(this.interruptTimer);
|
||||
this.interruptTimer = null;
|
||||
}
|
||||
this.currentAudioRef = null;
|
||||
};
|
||||
|
||||
if (options.ordered) {
|
||||
try {
|
||||
// 1) final playback progress (bounded) — still needs ref + connected transport.
|
||||
await this.reportFinalProgress();
|
||||
// 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);
|
||||
}
|
||||
} catch {
|
||||
/* the session may already be closed/expired (e.g. 409 LIVE_SESSION_UNUSABLE) */
|
||||
} finally {
|
||||
if (options.ordered) this.finalizeAll();
|
||||
release();
|
||||
}
|
||||
} else {
|
||||
// Unmount / start-abort / page-leave: invalidate + release immediately, then send V04
|
||||
// best-effort in the background (it may not finish while the page is unloading).
|
||||
invalidate();
|
||||
release();
|
||||
if (options.closeRemote !== false && remote) {
|
||||
this.api.closeVoiceSession(remote.csrf, remote.sessionId).catch(() => {
|
||||
/* already closed / expired: nothing to do */
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (options.ordered && options.emitEnded !== false && wasConnected && !superseded()) {
|
||||
this.sessionEnded$.next({
|
||||
conversationId,
|
||||
messages: this.messages(),
|
||||
error: options.error,
|
||||
detail: options.detail,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/** Cancellable wait: resolve when `work` settles or after `ms`, whichever is first. The underlying request is left to finish. */
|
||||
private withTimeout<T>(work: Promise<T>, ms: number): Promise<T | undefined> {
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
const timedOut = new Promise<undefined>((resolve) => {
|
||||
timer = setTimeout(() => resolve(undefined), ms);
|
||||
});
|
||||
return Promise.race([work.catch((): undefined => undefined), timedOut]).finally(() =>
|
||||
clearTimeout(timer),
|
||||
);
|
||||
}
|
||||
|
||||
/** Release mic, worklets, AudioContext, socket and timers. Runs even if V04 failed. */
|
||||
private releaseLocal(options: TeardownOptions): void {
|
||||
const transport = this.transport;
|
||||
this.transport = null;
|
||||
transport?.close();
|
||||
this.engine.stop();
|
||||
|
||||
// The reservation is over: drop the attempt so the next start() mints fresh request ids —
|
||||
// unless an ambiguous reserve failure still needs the same ids replayed/reconciled.
|
||||
const remote = this.remote;
|
||||
this.remote = null;
|
||||
this.streaming = false;
|
||||
// The reservation is over: drop the attempt so the next start() mints fresh request ids —
|
||||
// unless an ambiguous reserve / page-leave still needs the same ids replayed/reconciled.
|
||||
if (!options.keepAttempt) {
|
||||
this.attempt = null;
|
||||
clearPersistedAttempt();
|
||||
}
|
||||
if (remote) this.closeRemote(remote);
|
||||
|
||||
this.clearError();
|
||||
this.connection.set('disconnected');
|
||||
this.state.set('IDLE');
|
||||
this.muted.set(false);
|
||||
}
|
||||
|
||||
/** Best-effort one-off V04 for a reservation produced by a start() that was just superseded. */
|
||||
private closeRemote(remote: { sessionId: string; csrf: string }): void {
|
||||
this.api.closeVoiceSession(remote.csrf, remote.sessionId).catch(() => {
|
||||
/* already closed / expired (e.g. 409 LIVE_SESSION_UNUSABLE): nothing to do */
|
||||
@@ -751,19 +875,9 @@ export class VoiceStreamService {
|
||||
|
||||
private onPageLeave = (): void => {
|
||||
if (!this.isOpen()) return;
|
||||
const transport = this.transport;
|
||||
const remote = this.remote;
|
||||
this.session++;
|
||||
this.streaming = false;
|
||||
this.transport = null;
|
||||
transport?.close();
|
||||
this.engine.stop();
|
||||
this.remote = null;
|
||||
if (remote) this.closeRemote(remote);
|
||||
// The attempt id/path stay in sessionStorage on purpose: the next page load reconciles
|
||||
// it with V02/V03 (V04 may not complete while unloading) before anything else.
|
||||
this.connection.set('disconnected');
|
||||
this.state.set('IDLE');
|
||||
void this.teardown({ ordered: false, closeRemote: true, keepAttempt: true, emitEnded: false });
|
||||
};
|
||||
|
||||
private resetTurnFlags(): void {
|
||||
|
||||
Reference in New Issue
Block a user