1363 lines
54 KiB
TypeScript
1363 lines
54 KiB
TypeScript
import { Injectable, NgZone, computed, inject, signal } from '@angular/core';
|
|
import { Subject } from 'rxjs';
|
|
import { MicrophoneError } from '../microphone/microphone.service';
|
|
import { uuid } from '../../shared/utils/uuid';
|
|
import { VoiceApiError, VoiceApiService, VoiceSessionResponse } from './voice-api.service';
|
|
import { VoiceAudioEngine, VoiceEngineError } from './voice-audio-engine.service';
|
|
import { VOICE_TRANSPORT_FACTORY, VoiceTransport } from './voice-transport';
|
|
import {
|
|
VOICE_STREAM_CONFIG,
|
|
VoiceConnection,
|
|
VoiceMessage,
|
|
VoiceServerEvent,
|
|
VoiceSessionEnd,
|
|
VoiceStreamState,
|
|
} from './voice-stream.types';
|
|
import { VoiceCueService } from './voice-cue.service';
|
|
|
|
export type VoiceStartFailure =
|
|
| 'cancelled'
|
|
| 'unsupported'
|
|
| 'mic'
|
|
| 'engine'
|
|
| 'auth'
|
|
| 'unavailable'
|
|
| 'api'
|
|
| 'connect'
|
|
| 'overflow';
|
|
|
|
export type VoiceStartResult =
|
|
{ ok: true } | { ok: false; reason: VoiceStartFailure; message: string };
|
|
|
|
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: 'دسترسی به میکروفون رد شد. اجازهی دسترسی را در تنظیمات مرورگر فعال کنید.',
|
|
micUnavailable: 'میکروفونی پیدا نشد یا در حال استفادهی برنامهی دیگری است.',
|
|
micLost: 'اتصال میکروفون قطع شد و گفتگو پایان یافت.',
|
|
engine: 'راهاندازی پردازشگر صوتی ناموفق بود. صفحه را دوباره بارگذاری کنید.',
|
|
auth: 'نشست شما منقضی شده است. دوباره وارد شوید.',
|
|
voiceDisabled: 'گفتگوی صوتی برای این سامانه فعال نیست.',
|
|
rateLimited: 'تعداد درخواستها زیاد است. کمی بعد دوباره تلاش کنید.',
|
|
unavailable: 'سرویس موقتاً در دسترس نیست. کمی بعد دوباره تلاش کنید.',
|
|
sessionUnusable: 'نشست صوتی بسته شده است. گفتگوی جدیدی شروع کنید.',
|
|
api: 'شروع گفتگوی صوتی ناموفق بود. دوباره تلاش کنید.',
|
|
connect: 'اتصال به سرور صوتی برقرار نشد. دوباره تلاش کنید.',
|
|
badFormat: 'فرمت صدای سرور با برنامه سازگار نیست.',
|
|
overflow: 'حجم صدای در حال پخش از محدودهٔ مجاز گذشت و گفتگو بهطور ایمن پایان یافت.',
|
|
sendOverflow: 'حجم صدای ارسالی از محدودهٔ مجاز گذشت و گفتگو بهطور ایمن پایان یافت.',
|
|
disconnected: 'ارتباط با سرور قطع شد و گفتگو پایان یافت.',
|
|
server: 'سرور گفتگوی صوتی با خطا مواجه شد.',
|
|
contextRevoked: 'محتوای دانش تغییر کرده و مکالمهٔ قبلی دیگر معتبر نیست. گفتگوی جدیدی شروع کنید.',
|
|
stale: 'مکالمهٔ قبلی منقضی شده است. گفتگوی جدیدی شروع کنید.',
|
|
conversationTitle: 'گفتگوی صوتی',
|
|
} as const;
|
|
|
|
/** How long INTERRUPTED stays visible before returning to LISTENING. */
|
|
const INTERRUPTED_FLASH_MS = 150;
|
|
/** How long a retryable server error stays on screen. */
|
|
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;
|
|
/**
|
|
* Bounded per-turn answer-state memory (turns the server marked `answer_limited`, and
|
|
* turns it interrupted). A marker can arrive before its transcript row exists, so the
|
|
* record must survive until the row lands — but a long call must not grow it forever,
|
|
* so the oldest entries are dropped past this cap.
|
|
*/
|
|
const TURN_STATE_MEMORY = 50;
|
|
|
|
/**
|
|
* One live voice call against the backend handoff contract (§7–§9):
|
|
*
|
|
* mic ─▶ engine ─▶ PCM16 24 kHz frames ─▶ WSS ─▶ server
|
|
* server ─▶ session_ready / user_speech_started / transcript / sources /
|
|
* audio_started / audio_ended / turn_interrupted / answer_limited /
|
|
* error (JSON)
|
|
* ─▶ PCM16 24 kHz audio (binary) ─▶ engine playback
|
|
* client ─▶ playback_progress (the only JSON control message, cumulative played_ms)
|
|
*
|
|
* Start: mic permission → GET /me (CSRF) → POST /conversations → POST /voice/sessions
|
|
* → WSS stream_path → `session_ready`.
|
|
* End: final playback progress → V04 close → close the socket, stop the audio.
|
|
*
|
|
* Barge-in is decided by the server: it sends `turn_interrupted` and the client flushes
|
|
* playback. The contract has no other client→server JSON message.
|
|
*
|
|
* Ambiguous C01/V01 outcomes (timeout / network) are reconciled with the SAME
|
|
* `client_request_id` pair — replayed via V03 or the identical request — never with new
|
|
* ids, so a second conversation/session is never created. The attempt is kept in
|
|
* sessionStorage (ids and paths only, no secrets) so a reload can reconcile first.
|
|
*/
|
|
@Injectable({ providedIn: 'root' })
|
|
export class VoiceStreamService {
|
|
private readonly ngZone = inject(NgZone);
|
|
private readonly engine = inject(VoiceAudioEngine);
|
|
private readonly api = inject(VoiceApiService);
|
|
private readonly config = inject(VOICE_STREAM_CONFIG);
|
|
private readonly createTransport = inject(VOICE_TRANSPORT_FACTORY);
|
|
private readonly cues = inject(VoiceCueService);
|
|
|
|
readonly state = signal<VoiceStreamState>('IDLE');
|
|
readonly connection = signal<VoiceConnection>('disconnected');
|
|
readonly messages = signal<VoiceMessage[]>([]);
|
|
readonly muted = signal(false);
|
|
/** Non-fatal, retryable server error to show as a banner (e.g. SEARCH_TIMEOUT). */
|
|
readonly streamError = signal<string | null>(null);
|
|
|
|
/** true from the moment start() is called until the call is over. */
|
|
readonly isOpen = computed(() => this.connection() !== 'disconnected');
|
|
readonly isSupported = this.engine.isSupported && typeof WebSocket !== 'undefined';
|
|
|
|
/** Emits once for every call that reached `connected` (normal end or failure). */
|
|
readonly sessionEnded$ = new Subject<VoiceSessionEnd>();
|
|
|
|
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 audioGenerationDone = false; // server finished sending this audio_ref's frames
|
|
private interruptTimer: ReturnType<typeof setTimeout> | null = null;
|
|
private settleTimer: ReturnType<typeof setTimeout> | null = null;
|
|
private errorTimer: ReturnType<typeof setTimeout> | null = null;
|
|
private readyWaiter: {
|
|
resolve: () => void;
|
|
reject: (error: Error) => void;
|
|
timer: ReturnType<typeof setTimeout>;
|
|
} | null = null;
|
|
private lastConversationId: string | null = null;
|
|
|
|
/** Creation attempt: stable client request ids + the ids/paths the server returned. */
|
|
private attempt: VoiceCreationAttempt | null = null;
|
|
/** 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>();
|
|
/** Turns the server interrupted (bounded; late assistant text must not restore them). */
|
|
private readonly interruptedTurns = new Set<string>();
|
|
|
|
constructor() {
|
|
this.attempt = loadPersistedAttempt();
|
|
// A reload during a call leaves an un-reconciled reservation: reconcile with the
|
|
// server first (V02/V03), close what is still open, and drop the attempt. Media is
|
|
// never auto-resumed — the user starts a fresh conversation explicitly.
|
|
if (this.attempt) void this.recover();
|
|
|
|
// Leaving the page releases mic/worklet/AudioContext/WebSocket immediately.
|
|
window.addEventListener('pagehide', this.onPageLeave);
|
|
}
|
|
|
|
// ---- public API -----------------------------------------------------------
|
|
|
|
async start(options: { title?: string } = {}): Promise<VoiceStartResult> {
|
|
if (this.isOpen()) return this.failure('cancelled', '');
|
|
if (!this.isSupported) return this.failure('unsupported', MESSAGES.unsupported);
|
|
|
|
const session = ++this.session;
|
|
const stale = (): boolean => session !== this.session;
|
|
|
|
this.messages.set([]);
|
|
this.muted.set(false);
|
|
this.clearError();
|
|
this.cleanupPromise = null;
|
|
this.resetTurnFlags();
|
|
// Per-session answer state: a new session can never inherit the previous one's
|
|
// limited/interrupted turn markers.
|
|
this.limitedTurns.clear();
|
|
this.interruptedTurns.clear();
|
|
this.lastConversationId = null;
|
|
this.currentAudioRef = null;
|
|
this.playedMsByRef.clear();
|
|
this.seenAudioRefs.clear();
|
|
this.state.set('IDLE');
|
|
this.connection.set('connecting');
|
|
|
|
// Reuse a persisted attempt (ambiguous outcome of a previous try); otherwise create one.
|
|
if (!this.attempt) this.attempt = newCreationAttempt();
|
|
persistAttempt(this.attempt);
|
|
|
|
// 1) microphone + worklets (needs the user gesture; shows the permission prompt)
|
|
try {
|
|
await this.engine.start({
|
|
onFrame: (pcm) => this.onMicFrame(pcm),
|
|
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)),
|
|
});
|
|
} catch (err) {
|
|
return this.abortStart(session, this.mapEngineError(err));
|
|
}
|
|
if (stale()) {
|
|
if (!this.isOpen()) this.engine.stop();
|
|
return this.failure('cancelled', '');
|
|
}
|
|
|
|
// 2) REST: identity/CSRF → capabilities → conversation → voice session
|
|
let voiceSession: VoiceSessionResponse;
|
|
try {
|
|
const me = await this.api.me();
|
|
if (stale()) return this.failure('cancelled', '');
|
|
|
|
const configuration = await this.api.configuration();
|
|
if (stale()) return this.failure('cancelled', '');
|
|
if (!configuration.capabilities.voice) {
|
|
return this.abortStart(session, { reason: 'unavailable', message: MESSAGES.voiceDisabled });
|
|
}
|
|
|
|
voiceSession = await this.reserve(me.csrf_token, options.title ?? MESSAGES.conversationTitle);
|
|
if (stale()) {
|
|
this.closeRemote({ sessionId: voiceSession.session_id, csrf: me.csrf_token });
|
|
this.attempt = null;
|
|
clearPersistedAttempt();
|
|
return this.failure('cancelled', '');
|
|
}
|
|
} catch (err) {
|
|
if (stale()) return this.failure('cancelled', '');
|
|
// An ambiguous reserve outcome (timeout / network / 5xx) keeps the attempt: the
|
|
// next start reconciles it with the same client_request_ids instead of creating a
|
|
// second conversation/session. A definitive failure (4xx) drops it.
|
|
const keepAttempt = err instanceof VoiceApiError && this.isAmbiguous(err);
|
|
return this.abortStart(session, this.mapApiError(err), keepAttempt);
|
|
}
|
|
|
|
this.remote = {
|
|
sessionId: voiceSession.session_id,
|
|
conversationId: voiceSession.conversation_id,
|
|
csrf: this.lastCsrf,
|
|
};
|
|
this.lastConversationId = voiceSession.conversation_id;
|
|
|
|
// 3) WebSocket (created outside the zone so socket events don't trigger change detection)
|
|
const transport = this.createTransport(this.api.streamUrl(voiceSession.stream_path));
|
|
this.transport = transport;
|
|
try {
|
|
await this.ngZone.runOutsideAngular(() =>
|
|
transport.connect({
|
|
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)),
|
|
),
|
|
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 {
|
|
if (stale()) return this.failure('cancelled', '');
|
|
return this.abortStart(session, { reason: 'connect', message: MESSAGES.connect });
|
|
}
|
|
if (stale()) return this.failure('cancelled', '');
|
|
|
|
// 4) wait for `session_ready` (the server pushes it; the client sends no handshake)
|
|
try {
|
|
await new Promise<void>((resolve, reject) => {
|
|
const timer = setTimeout(
|
|
() => reject(new Error('ready-timeout')),
|
|
this.config.connectTimeoutMs,
|
|
);
|
|
this.readyWaiter = { resolve, reject, timer };
|
|
});
|
|
} catch (err) {
|
|
if (stale()) return this.failure('cancelled', '');
|
|
const badFormat = err instanceof Error && err.message === 'format';
|
|
return this.abortStart(session, {
|
|
reason: 'connect',
|
|
message: badFormat ? MESSAGES.badFormat : MESSAGES.connect,
|
|
});
|
|
}
|
|
if (stale()) return this.failure('cancelled', '');
|
|
|
|
this.connection.set('connected');
|
|
this.state.set('LISTENING');
|
|
this.streaming = true;
|
|
// "You can speak now" — once per session, not per turn (a turn cue would be noise).
|
|
this.cues.playReady();
|
|
return { ok: true };
|
|
}
|
|
|
|
/** User ends the call. Safe to call at any time. */
|
|
end(): void {
|
|
void this.close();
|
|
}
|
|
|
|
/**
|
|
* 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; 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,
|
|
});
|
|
}
|
|
|
|
/**
|
|
* After media/context loss the user starts a brand-new conversation: the old
|
|
* reservation is closed (V04) and its creation attempt is dropped, so the next
|
|
* `start()` mints fresh client request ids. An ambiguous attempt that was never
|
|
* connected is still reconciled with the same ids — never duplicated.
|
|
*/
|
|
async freshSession(title?: string): Promise<VoiceStartResult> {
|
|
await this.close();
|
|
return this.start({ title });
|
|
}
|
|
|
|
/**
|
|
* Reconcile a persisted creation attempt with the server (V02/V03) and close whatever
|
|
* reservation is still open. Media is never resumed automatically: recovery is not a
|
|
* seamless reconnect. Returns whether an attempt existed.
|
|
*/
|
|
async recover(): Promise<boolean> {
|
|
const attempt = this.attempt;
|
|
if (!attempt) return false;
|
|
try {
|
|
const me = await this.api.me();
|
|
// A call may have started while the request was in flight: never close its session.
|
|
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,
|
|
);
|
|
sessionId = existing?.session_id ?? null;
|
|
}
|
|
if (this.isOpen() || this.attempt !== attempt) return true;
|
|
if (sessionId) {
|
|
await this.api.closeVoiceSession(me.csrf_token, sessionId).catch(() => undefined);
|
|
}
|
|
} catch {
|
|
/* the attempt is stale either way: drop it below */
|
|
}
|
|
if (!this.isOpen() && this.attempt === attempt) {
|
|
this.attempt = null;
|
|
clearPersistedAttempt();
|
|
}
|
|
return true;
|
|
}
|
|
|
|
/** V02: status + safe diagnostics of the current reservation (for the UI, no secrets). */
|
|
async poll(): Promise<unknown> {
|
|
const remote = this.remote;
|
|
if (!remote) return null;
|
|
return this.api.pollVoiceSession(remote.csrf, remote.sessionId);
|
|
}
|
|
|
|
toggleMute(): void {
|
|
const next = !this.muted();
|
|
this.muted.set(next);
|
|
this.engine.setMuted(next); // frames keep flowing (silent), so the server never sees a gap
|
|
}
|
|
|
|
/** Level (0..1) the orb should follow: assistant audio while speaking, otherwise the mic. */
|
|
orbLevel(): number {
|
|
if (this.state() === 'SPEAKING') return this.engine.outputLevel();
|
|
return this.muted() ? 0 : this.engine.inputLevel();
|
|
}
|
|
|
|
dismissError(): void {
|
|
this.clearError();
|
|
}
|
|
|
|
/** Component teardown: release a live call without emitting events. */
|
|
dispose(): void {
|
|
this.rejectReady();
|
|
if (!this.isOpen()) return; // keep an ambiguous attempt for reconciliation
|
|
void this.teardown({ ordered: false, closeRemote: true, emitEnded: false });
|
|
}
|
|
|
|
// ---- audio from the microphone (outside the zone) --------------------------
|
|
|
|
private onMicFrame(pcm: ArrayBuffer): void {
|
|
if (this.streaming) this.transport?.sendAudio(pcm);
|
|
}
|
|
|
|
// ---- audio from the server (outside the zone) -----------------------------
|
|
|
|
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();
|
|
|
|
if (this.state() !== 'SPEAKING') {
|
|
this.ngZone.run(() => {
|
|
if (this.interruptTimer) {
|
|
clearTimeout(this.interruptTimer);
|
|
this.interruptTimer = null;
|
|
}
|
|
this.state.set('SPEAKING');
|
|
});
|
|
}
|
|
}
|
|
|
|
// ---- playback progress ------------------------------------------------------
|
|
|
|
private onPlaybackProgress(audioRef: string, playedMs: number): void {
|
|
if (playedMs <= 0) return;
|
|
// Keep the latest cumulative value per ref; the final report is sent from here too.
|
|
this.playedMsByRef.set(audioRef, playedMs);
|
|
this.sendPlaybackProgress(audioRef, playedMs);
|
|
this.resolveProgressWaiters();
|
|
}
|
|
|
|
/**
|
|
* The only client→server JSON control message: cumulative REAL played milliseconds
|
|
* for a server audio_ref, computed by the worklet from consumed samples.
|
|
*/
|
|
private sendPlaybackProgress(audioRef: string, playedMs: number): void {
|
|
const transport = this.transport;
|
|
if (!transport || playedMs <= 0) return;
|
|
transport.sendControl({ type: 'playback_progress', audio_ref: audioRef, played_ms: playedMs });
|
|
}
|
|
|
|
/**
|
|
* Before closing a call, ask the worklet for the final played report of the active ref
|
|
* (barge-in drops the queue, so the last 250 ms cadence may be stale).
|
|
*/
|
|
private reportFinalProgress(): Promise<void> {
|
|
const ref = this.currentAudioRef;
|
|
const transport = this.transport;
|
|
if (!ref || !transport || this.connection() !== 'connected') return Promise.resolve();
|
|
|
|
this.engine.clearPlayback(); // worklet answers with its final cumulative report
|
|
return new Promise<void>((resolve) => {
|
|
const done = (): void => {
|
|
clearTimeout(timer);
|
|
resolve();
|
|
};
|
|
const timer = setTimeout(done, FINAL_PROGRESS_WAIT_MS);
|
|
this.progressWaiters.push(done);
|
|
});
|
|
}
|
|
|
|
private resolveProgressWaiters(): void {
|
|
const waiters = this.progressWaiters;
|
|
this.progressWaiters = [];
|
|
waiters.forEach((waiter) => waiter());
|
|
}
|
|
|
|
// ---- JSON events from the server -------------------------------------------
|
|
|
|
private onServerEvent(event: VoiceServerEvent, session: number): void {
|
|
if (session !== this.session) return;
|
|
|
|
switch (event.type) {
|
|
case 'session_ready': {
|
|
const { input_audio: input, output_audio: output } = event;
|
|
const compatible =
|
|
input.encoding === 'pcm_s16le' &&
|
|
output.encoding === 'pcm_s16le' &&
|
|
input.channels === 1 &&
|
|
output.channels === 1 &&
|
|
input.sample_rate === this.config.inputSampleRate &&
|
|
output.sample_rate === this.config.outputSampleRate;
|
|
if (compatible) this.resolveReady();
|
|
else this.rejectReady(new Error('format'));
|
|
break;
|
|
}
|
|
|
|
case 'user_speech_started':
|
|
// A new server turn started; the transcript/sources of older turns stay untouched.
|
|
break;
|
|
|
|
case 'transcript':
|
|
this.onTranscript(event);
|
|
break;
|
|
|
|
case 'sources':
|
|
this.upsertSources(event);
|
|
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':
|
|
// Generation finished: emit the worklet's deferred tail and drain what is buffered so
|
|
// 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.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':
|
|
this.onTurnInterrupted(event.turn_ref);
|
|
break;
|
|
|
|
case 'answer_limited':
|
|
// Answer state only — see onAnswerLimited: no cleanup, no socket/mic/playback
|
|
// side effects, no automatic continuation.
|
|
this.onAnswerLimited(event.turn_ref);
|
|
break;
|
|
|
|
case 'error':
|
|
this.onServerError(event, session);
|
|
break;
|
|
}
|
|
}
|
|
|
|
private onTranscript(event: TranscriptEvent): void {
|
|
this.upsertTranscript(event);
|
|
|
|
if (event.status === 'interrupted') {
|
|
this.onTurnInterrupted(event.turn_ref);
|
|
return;
|
|
}
|
|
|
|
if (event.role === 'user') {
|
|
// The user finished their sentence; the assistant is working on it.
|
|
if (event.status === 'completed' && this.state() === 'LISTENING') {
|
|
this.state.set('PROCESSING');
|
|
}
|
|
return;
|
|
}
|
|
|
|
if (event.status === 'completed') return;
|
|
|
|
if (event.status === 'limited') {
|
|
// An answer state, not a playback or session event: the limited transcript does
|
|
// NOT seal the audio reference, so generated audio keeps playing until audio_ended
|
|
// and the real queue drain finish it. Only the "thinking" state needs a bounded
|
|
// fallback, for a limited answer that produced no audio to drain.
|
|
this.scheduleLimitedSettle();
|
|
}
|
|
}
|
|
|
|
/**
|
|
* `answer_limited`: the assistant answer reached the backend's output-token limit.
|
|
*
|
|
* This is an ANSWER state — not an error and not a session-lifecycle event. It must
|
|
* not close or reconnect the socket, stop the microphone, flush or mute playback,
|
|
* reset `audio_ref`/`played_ms`, mark the session failed, mark playback finished, ask
|
|
* the backend to close, or request another answer automatically. The audio already
|
|
* generated keeps playing; the user asks for more ("ادامه بده") as a genuine new
|
|
* microphone turn.
|
|
*/
|
|
private onAnswerLimited(turnRef: string): void {
|
|
this.rememberLimitedTurn(turnRef);
|
|
this.markLimited(turnRef);
|
|
this.scheduleLimitedSettle();
|
|
}
|
|
|
|
/**
|
|
* Never leave the UI permanently "thinking" after a limited answer: when audio is
|
|
* queued the state is SPEAKING and the normal drain path returns to LISTENING, but a
|
|
* limited answer can arrive with no outstanding audio at all — then schedule the same
|
|
* bounded settle the drain path uses.
|
|
*/
|
|
private scheduleLimitedSettle(): void {
|
|
if (this.state() !== 'PROCESSING' || this.currentAudioRef || this.settleTimer) return;
|
|
this.settleTimer = setTimeout(() => {
|
|
this.settleTimer = null;
|
|
if (this.state() === 'PROCESSING') this.finishTurn();
|
|
}, this.config.settleMs);
|
|
}
|
|
|
|
/** 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
|
|
if (!this.currentAudioTurnRef || this.currentAudioTurnRef === turnRef) {
|
|
this.currentAudioRef = null;
|
|
this.currentAudioTurnRef = null;
|
|
this.audioGenerationDone = false;
|
|
}
|
|
this.clearSettleTimer();
|
|
this.markInterrupted(turnRef);
|
|
|
|
const state = this.state();
|
|
if (state === 'SPEAKING' || state === 'PROCESSING') {
|
|
this.state.set('INTERRUPTED');
|
|
if (this.interruptTimer) clearTimeout(this.interruptTimer);
|
|
this.interruptTimer = setTimeout(() => {
|
|
this.interruptTimer = null;
|
|
if (this.state() === 'INTERRUPTED') this.state.set('LISTENING');
|
|
}, INTERRUPTED_FLASH_MS);
|
|
}
|
|
}
|
|
|
|
private onServerError(event: ErrorEvent, session: number): void {
|
|
const { message, retryable, code } = event.error;
|
|
// 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).
|
|
if (code === 'CONTEXT_REVOKED' || code === 'CONVERSATION_STALE') {
|
|
this.failSession(MESSAGES.contextRevoked, session);
|
|
return;
|
|
}
|
|
if (code === 'LIVE_SESSION_UNUSABLE' || code === 'SESSION_CLOSED') {
|
|
this.failSession(MESSAGES.sessionUnusable, session);
|
|
return;
|
|
}
|
|
|
|
if (!retryable) {
|
|
this.failSession(message || MESSAGES.server, session, `server error ${code}`);
|
|
return;
|
|
}
|
|
|
|
// The session survives a retryable failure (e.g. SEARCH_TIMEOUT): drop the failed turn and keep listening.
|
|
this.engine.clearPlayback();
|
|
this.clearSettleTimer();
|
|
this.finalizeAssistant();
|
|
if (this.state() === 'PROCESSING' || this.state() === 'SPEAKING') this.state.set('LISTENING');
|
|
this.showError(message || MESSAGES.server);
|
|
}
|
|
|
|
// ---- end of an assistant turn ----------------------------------------------
|
|
|
|
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();
|
|
}
|
|
}
|
|
|
|
private finishTurn(): void {
|
|
this.audioGenerationDone = false;
|
|
this.currentAudioRef = null;
|
|
this.currentAudioTurnRef = null;
|
|
this.clearSettleTimer();
|
|
this.state.set('LISTENING');
|
|
}
|
|
// ---- transcript ------------------------------------------------------------
|
|
|
|
private upsertTranscript(event: TranscriptEvent): void {
|
|
const id = `${event.turn_ref}:${event.role}`;
|
|
const final = event.status !== 'partial';
|
|
const interrupted = event.status === 'interrupted';
|
|
const limited = event.status === 'limited';
|
|
// `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));
|
|
|
|
// A turn the server already interrupted cannot be restored by late assistant text
|
|
// (partial, completed or limited). The interrupted transcript itself still passes:
|
|
// it carries the final text of the cut-off answer.
|
|
if (event.role === 'assistant' && !interrupted && this.interruptedTurns.has(event.turn_ref)) {
|
|
return;
|
|
}
|
|
|
|
this.messages.update((list) => {
|
|
const index = list.findIndex((m) => m.id === id);
|
|
if (index === -1) {
|
|
// A `limited` transcript is kept even with empty text: the row carries the
|
|
// answer state and the UI shows the unavailable-text presentation for it —
|
|
// spoken text is never manufactured.
|
|
if (!event.text.trim() && !limited) return list;
|
|
return this.insertTranscript(list, {
|
|
id,
|
|
turnRef: event.turn_ref,
|
|
role: event.role,
|
|
text: event.text,
|
|
final,
|
|
interrupted: interrupted || undefined,
|
|
limited: attachLimited || undefined,
|
|
});
|
|
}
|
|
|
|
const current = list[index];
|
|
if (current.interrupted && !interrupted) return list; // late partial for a cut-off message
|
|
// A late `partial` must not extend an answer that is already final (completed or
|
|
// limited): the answer would silently revert to growing partial text.
|
|
if (current.final && event.status === 'partial' && event.role === 'assistant') return list;
|
|
const copy = [...list];
|
|
copy[index] = {
|
|
...current,
|
|
text: this.mergeTranscriptText(current.text, event),
|
|
final: current.final || final,
|
|
interrupted: current.interrupted || interrupted || undefined,
|
|
// Monotonic: once an answer is limited, a delayed completed/partial transcript
|
|
// cannot downgrade it back.
|
|
limited: current.limited || attachLimited || undefined,
|
|
};
|
|
return copy;
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Transcript text semantics (contract):
|
|
* - `partial` is a DELTA: it is appended as-is, with its own spacing. Identical
|
|
* deltas are legitimately repeated words and are never deduplicated by content.
|
|
* - `completed` and `limited` are FINAL SNAPSHOTS: they replace the accumulated
|
|
* text exactly, so the last partial accumulation is never kept alongside them.
|
|
*/
|
|
private mergeTranscriptText(previous: string, event: TranscriptEvent): string {
|
|
const next = event.text;
|
|
if (!next) return previous;
|
|
if (event.status === 'partial') return previous + next;
|
|
return next;
|
|
}
|
|
|
|
private upsertSources(event: SourcesEvent): void {
|
|
const id = `${event.turn_ref}:assistant`;
|
|
this.messages.update((list) => {
|
|
const index = list.findIndex((m) => m.id === id);
|
|
const current: VoiceMessage =
|
|
index === -1
|
|
? {
|
|
id,
|
|
turnRef: event.turn_ref,
|
|
role: 'assistant',
|
|
text: '',
|
|
final: false,
|
|
// A sources row for a turn the server already marked limited shows the
|
|
// limited indication with the unavailable-text presentation — unless the
|
|
// turn was interrupted, which takes precedence.
|
|
limited: this.isLimitedTurn(event.turn_ref) || undefined,
|
|
}
|
|
: list[index];
|
|
|
|
const sources = [...(current.sources ?? [])];
|
|
for (const source of event.sources) {
|
|
// `available: false` means the excerpt is no longer valid: keep the reference for
|
|
// the turn but hide its excerpt instead of showing revoked text.
|
|
const normalized = source.available === false ? { ...source, excerpt: undefined } : source;
|
|
const existing = sources.findIndex(
|
|
(s) => s.source_ref === normalized.source_ref && s.chunk_id === normalized.chunk_id,
|
|
);
|
|
if (existing === -1) sources.push(normalized);
|
|
else sources[existing] = normalized;
|
|
}
|
|
|
|
const next = { ...current, sources };
|
|
if (index === -1) return this.insertTranscript(list, next);
|
|
const copy = [...list];
|
|
copy[index] = next;
|
|
return copy;
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Inserts a new transcript bubble so the invariant always holds: WITHIN a turn the user
|
|
* request precedes the AI response, and turns keep their first-seen order. This matters when
|
|
* an assistant partial/response for a turn arrives before that turn's user transcript (the
|
|
* server streams transcripts per role and does not guarantee the user text lands first) —
|
|
* a plain append would then show the AI answer above the user's question.
|
|
*/
|
|
private insertTranscript(list: VoiceMessage[], message: VoiceMessage): VoiceMessage[] {
|
|
const roleRank = message.role === 'user' ? 0 : 1;
|
|
// Stable turn order = the order turns first appear in the current list; a turn we have
|
|
// 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;
|
|
|
|
for (let i = 0; i < list.length; i++) {
|
|
const existingTurn = turns.indexOf(list[i].turnRef);
|
|
const existingRank = list[i].role === 'user' ? 0 : 1;
|
|
const comesAfter =
|
|
existingTurn > turnRank || (existingTurn === turnRank && existingRank > roleRank);
|
|
if (comesAfter) return [...list.slice(0, i), message, ...list.slice(i)];
|
|
}
|
|
return [...list, message];
|
|
}
|
|
|
|
private markInterrupted(turnRef: string): void {
|
|
this.rememberInterruptedTurn(turnRef);
|
|
const id = `${turnRef}:assistant`;
|
|
this.messages.update((list) => {
|
|
const index = list.findIndex((m) => m.id === id);
|
|
if (index === -1 || list[index].interrupted) return list;
|
|
const copy = [...list];
|
|
// Interruption takes precedence over a limited marker on the same answer: the row
|
|
// is presented as cut off, not as a completed-capped answer.
|
|
copy[index] = { ...copy[index], final: true, interrupted: true };
|
|
return copy;
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Flag the assistant answer of `turnRef` as limited. When the row does not exist yet
|
|
* (the marker arrived before any transcript text) the bounded `limitedTurns` record
|
|
* carries the state until the row is created — no text is ever invented here.
|
|
*/
|
|
private markLimited(turnRef: string): void {
|
|
const id = `${turnRef}:assistant`;
|
|
this.messages.update((list) => {
|
|
const index = list.findIndex((m) => m.id === id);
|
|
// No row yet (the bounded record carries the state), already limited, or
|
|
// interrupted (interruption takes precedence): nothing to change.
|
|
if (index === -1 || list[index].limited || list[index].interrupted) return list;
|
|
const copy = [...list];
|
|
copy[index] = { ...copy[index], limited: true };
|
|
return copy;
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Whether the server marked `turnRef`'s answer limited. Interrupted turns answer
|
|
* `false`: the interruption takes precedence over the limited state everywhere this
|
|
* predicate is used (transcript rows, sources rows and the marker application), so
|
|
* the answer is always presented as cut off rather than capped.
|
|
*/
|
|
private isLimitedTurn(turnRef: string): boolean {
|
|
return this.limitedTurns.has(turnRef) && !this.interruptedTurns.has(turnRef);
|
|
}
|
|
|
|
/** Bounded memory of limited turns; repeated markers are idempotent. */
|
|
private rememberLimitedTurn(turnRef: string): void {
|
|
this.limitedTurns.add(turnRef);
|
|
this.evictOldest(this.limitedTurns);
|
|
}
|
|
|
|
/** Bounded memory of interrupted turns, so late assistant text cannot restore them. */
|
|
private rememberInterruptedTurn(turnRef: string): void {
|
|
this.interruptedTurns.add(turnRef);
|
|
this.evictOldest(this.interruptedTurns);
|
|
}
|
|
|
|
private evictOldest(turns: Set<string>): void {
|
|
while (turns.size > TURN_STATE_MEMORY) {
|
|
const oldest = turns.values().next().value;
|
|
if (oldest === undefined) break;
|
|
turns.delete(oldest);
|
|
}
|
|
}
|
|
|
|
private finalizeAssistant(): void {
|
|
this.messages.update((list) =>
|
|
list.some((m) => m.role === 'assistant' && !m.final)
|
|
? list.map((m) => (m.role === 'assistant' && !m.final ? { ...m, final: true } : m))
|
|
: list,
|
|
);
|
|
}
|
|
|
|
private finalizeAll(): void {
|
|
this.messages.update((list) =>
|
|
list.some((m) => !m.final) ? list.map((m) => (m.final ? m : { ...m, final: true })) : list,
|
|
);
|
|
}
|
|
|
|
// ---- lifecycle -------------------------------------------------------------
|
|
|
|
/**
|
|
* 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()` 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(
|
|
session: number,
|
|
failure: { reason: VoiceStartFailure; message: string },
|
|
keepAttempt = false,
|
|
): VoiceStartResult {
|
|
// 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);
|
|
}
|
|
|
|
/**
|
|
* 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;
|
|
|
|
// "Call finished" — once per connected session, before local resources (including the
|
|
// engine AudioContext) are released; every end path funnels through this single-flight
|
|
// cleanup, so ordered and unordered teardown both trigger it exactly once.
|
|
if (wasConnected) {
|
|
this.cues.playEnd();
|
|
}
|
|
|
|
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;
|
|
// The markers describe this session's turns only: drop them so a later session
|
|
// starts clean even if a late frame slipped through.
|
|
this.limitedTurns.clear();
|
|
this.interruptedTurns.clear();
|
|
};
|
|
|
|
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();
|
|
|
|
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();
|
|
}
|
|
|
|
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 */
|
|
});
|
|
}
|
|
|
|
private onPageLeave = (): void => {
|
|
if (!this.isOpen()) return;
|
|
// 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.
|
|
void this.teardown({ ordered: false, closeRemote: true, keepAttempt: true, emitEnded: false });
|
|
};
|
|
|
|
private resetTurnFlags(): void {
|
|
this.audioGenerationDone = false;
|
|
}
|
|
|
|
private clearSettleTimer(): void {
|
|
if (this.settleTimer) {
|
|
clearTimeout(this.settleTimer);
|
|
this.settleTimer = null;
|
|
}
|
|
}
|
|
|
|
private showError(message: string): void {
|
|
this.clearError();
|
|
this.streamError.set(message);
|
|
this.errorTimer = setTimeout(() => this.clearError(), ERROR_BANNER_MS);
|
|
}
|
|
|
|
private clearError(): void {
|
|
if (this.errorTimer) {
|
|
clearTimeout(this.errorTimer);
|
|
this.errorTimer = null;
|
|
}
|
|
if (this.streamError() !== null) this.streamError.set(null);
|
|
}
|
|
|
|
private resolveReady(): void {
|
|
const waiter = this.readyWaiter;
|
|
this.readyWaiter = null;
|
|
if (!waiter) return;
|
|
clearTimeout(waiter.timer);
|
|
waiter.resolve();
|
|
}
|
|
|
|
private rejectReady(error: Error = new Error('cancelled')): void {
|
|
const waiter = this.readyWaiter;
|
|
this.readyWaiter = null;
|
|
if (!waiter) return;
|
|
clearTimeout(waiter.timer);
|
|
waiter.reject(error);
|
|
}
|
|
|
|
// ---- creation attempt / reservation -----------------------------------------
|
|
|
|
/** CSRF of the most recent `/me`; refreshed per attempt. */
|
|
private lastCsrf = '';
|
|
|
|
/**
|
|
* C01 then V01 with the attempt's stable client request ids. Ambiguous outcomes
|
|
* (timeout / network) are reconciled with the SAME ids: V03 first, then an identical
|
|
* replay — never new ids, never a blind retry of an unknown state.
|
|
*/
|
|
private async reserve(csrf: string, title: string): Promise<VoiceSessionResponse> {
|
|
const attempt = this.attempt ?? newCreationAttempt();
|
|
this.attempt = attempt;
|
|
|
|
let activeCsrf = csrf;
|
|
if (!attempt.conversationId) {
|
|
try {
|
|
const conversation = await this.api.createConversation(
|
|
activeCsrf,
|
|
title,
|
|
attempt.conversationRequestId,
|
|
);
|
|
attempt.conversationId = conversation.id;
|
|
} catch (err) {
|
|
const refreshed = await this.refreshAfterCsrfFailure(err);
|
|
activeCsrf = refreshed ?? activeCsrf;
|
|
if (!this.isAmbiguous(err) && !refreshed) throw err;
|
|
// Replay the identical request: C01 is idempotent on client_request_id.
|
|
const conversation = await this.api.createConversation(
|
|
activeCsrf,
|
|
title,
|
|
attempt.conversationRequestId,
|
|
);
|
|
attempt.conversationId = conversation.id;
|
|
}
|
|
persistAttempt(attempt);
|
|
}
|
|
|
|
if (!attempt.sessionId || !attempt.streamPath) {
|
|
let voiceSession: VoiceSessionResponse | null = null;
|
|
try {
|
|
voiceSession = await this.api.createVoiceSession(
|
|
activeCsrf,
|
|
attempt.conversationId!,
|
|
attempt.sessionRequestId,
|
|
);
|
|
} catch (err) {
|
|
const refreshed = await this.refreshAfterCsrfFailure(err);
|
|
activeCsrf = refreshed ?? activeCsrf;
|
|
if (this.isAmbiguous(err) || refreshed) {
|
|
// Did the ambiguous V01 create a reservation? Reconcile before replaying.
|
|
const existing = await this.api
|
|
.getVoiceSessionByRequest(activeCsrf, attempt.sessionRequestId)
|
|
.catch(() => null);
|
|
if (existing?.stream_path) {
|
|
voiceSession = existing;
|
|
} else {
|
|
voiceSession = await this.api.createVoiceSession(
|
|
activeCsrf,
|
|
attempt.conversationId!,
|
|
attempt.sessionRequestId,
|
|
);
|
|
}
|
|
} else if (err instanceof VoiceApiError && err.code === 'LIVE_SESSION_BUSY') {
|
|
// A session already exists for this request: reconcile instead of a second one.
|
|
const existing = await this.api
|
|
.getVoiceSessionByRequest(activeCsrf, attempt.sessionRequestId)
|
|
.catch(() => null);
|
|
if (existing?.stream_path) voiceSession = existing;
|
|
else throw err;
|
|
} else {
|
|
throw err;
|
|
}
|
|
}
|
|
attempt.sessionId = voiceSession!.session_id;
|
|
attempt.streamPath = voiceSession!.stream_path;
|
|
persistAttempt(attempt);
|
|
}
|
|
|
|
this.lastCsrf = activeCsrf;
|
|
this.lastConversationId = attempt.conversationId;
|
|
return {
|
|
session_id: attempt.sessionId!,
|
|
conversation_id: attempt.conversationId!,
|
|
status: 'connecting',
|
|
stream_path: attempt.streamPath!,
|
|
expires_at: '',
|
|
poll_url: '',
|
|
};
|
|
}
|
|
|
|
/** 403 CSRF_INVALID → read a fresh token from `/me` and allow one identical replay. */
|
|
private async refreshAfterCsrfFailure(err: unknown): Promise<string | null> {
|
|
if (!(err instanceof VoiceApiError) || err.code !== 'CSRF_INVALID') return null;
|
|
try {
|
|
const me = await this.api.me();
|
|
return me.csrf_token;
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
/** Timeout / network / 5xx: the outcome is unknown, so reconcile instead of assuming. */
|
|
private isAmbiguous(err: unknown): boolean {
|
|
if (!(err instanceof VoiceApiError)) return true;
|
|
return err.status === 0 || err.status === 408 || err.status >= 500;
|
|
}
|
|
|
|
// ---- error mapping ---------------------------------------------------------
|
|
|
|
private mapEngineError(err: unknown): { reason: VoiceStartFailure; message: string } {
|
|
if (err instanceof MicrophoneError) {
|
|
if (err.code === 'unsupported')
|
|
return { reason: 'unsupported', message: MESSAGES.unsupported };
|
|
return {
|
|
reason: 'mic',
|
|
message: err.code === 'denied' ? MESSAGES.micDenied : MESSAGES.micUnavailable,
|
|
};
|
|
}
|
|
if (err instanceof VoiceEngineError && err.code === 'unsupported') {
|
|
return { reason: 'unsupported', message: MESSAGES.unsupported };
|
|
}
|
|
return { reason: 'engine', message: MESSAGES.engine };
|
|
}
|
|
|
|
/** Maps the contract's error codes (handoff §10) to a user-facing Persian message. */
|
|
private mapApiError(err: unknown): { reason: VoiceStartFailure; message: string } {
|
|
if (!(err instanceof VoiceApiError)) return { reason: 'api', message: MESSAGES.api };
|
|
|
|
switch (err.code) {
|
|
case 'AUTH_REQUIRED':
|
|
return { reason: 'auth', message: MESSAGES.auth };
|
|
case 'CSRF_INVALID':
|
|
return { reason: 'auth', message: MESSAGES.auth };
|
|
case 'RATE_LIMITED':
|
|
return { reason: 'api', message: MESSAGES.rateLimited };
|
|
case 'CALIBRATION_REQUIRED':
|
|
case 'DEPENDENCY_UNAVAILABLE':
|
|
return { reason: 'unavailable', message: MESSAGES.unavailable };
|
|
case 'LIVE_SESSION_UNUSABLE':
|
|
case 'CONTEXT_REVOKED':
|
|
case 'CONVERSATION_STALE':
|
|
return { reason: 'api', message: MESSAGES.stale };
|
|
case 'NETWORK':
|
|
return { reason: 'connect', message: MESSAGES.connect };
|
|
default:
|
|
return { reason: 'api', message: MESSAGES.api };
|
|
}
|
|
}
|
|
|
|
private failure(reason: VoiceStartFailure, message: string): VoiceStartResult {
|
|
return { ok: false, reason, message };
|
|
}
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Creation-attempt persistence (ids and paths only — never cookies, CSRF or audio)
|
|
// ---------------------------------------------------------------------------
|
|
|
|
interface VoiceCreationAttempt {
|
|
conversationRequestId: string;
|
|
sessionRequestId: string;
|
|
conversationId: string | null;
|
|
sessionId: string | null;
|
|
streamPath: string | null;
|
|
}
|
|
|
|
const ATTEMPT_STORAGE_KEY = 'voice_creation_attempt';
|
|
|
|
function newCreationAttempt(): VoiceCreationAttempt {
|
|
return {
|
|
conversationRequestId: uuid(),
|
|
sessionRequestId: uuid(),
|
|
conversationId: null,
|
|
sessionId: null,
|
|
streamPath: null,
|
|
};
|
|
}
|
|
|
|
function loadPersistedAttempt(): VoiceCreationAttempt | null {
|
|
try {
|
|
const raw = sessionStorage.getItem(ATTEMPT_STORAGE_KEY);
|
|
if (!raw) return null;
|
|
const parsed = JSON.parse(raw) as VoiceCreationAttempt;
|
|
if (!parsed?.conversationRequestId || !parsed?.sessionRequestId) return null;
|
|
return parsed;
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
function persistAttempt(attempt: VoiceCreationAttempt): void {
|
|
try {
|
|
sessionStorage.setItem(ATTEMPT_STORAGE_KEY, JSON.stringify(attempt));
|
|
} catch {
|
|
/* storage unavailable (private mode): the attempt lives in memory only */
|
|
}
|
|
}
|
|
|
|
function clearPersistedAttempt(): void {
|
|
try {
|
|
sessionStorage.removeItem(ATTEMPT_STORAGE_KEY);
|
|
} catch {
|
|
/* storage unavailable: nothing to clear */
|
|
}
|
|
}
|