build(ui): expand application shell and implement administrative dashboard pages
This commit significantly expands the application's routing, navigation, and administrative capabilities. It introduces several new functional modules and refines the core layout for a more professional, dashboard-oriented experience. - **Routing & Navigation**: - Added routes for `wallboard`, `call-center`, `call-center/calls`, and `chat-questions`. - Updated `SidebarComponent` to include all new navigation items. - Enhanced `LayoutComponent` with dynamic navigation based on user roles (admin vs. user). - **New Administrative Pages**: - `WallboardPage`: Implements a real-time KPI dashboard with call activity trends and outcome distributions. - `CallCenterPage`: Provides a symbolic interface for managing call center connectivity and synchronization. - `CallCenterCallsPage`: Implements a call history retrieval interface with filtering capabilities. - `ChatQuestionsPage`: Adds a module for reviewing user questions from web and mobile channels. - **Core Infrastructure & Refinement**: - Updated `AppConfig` to include an `APP_INITIALIZER` for validating user identity via `AuthService` on startup. - Refined `HomeComponent` layout to a "Claude-style" continuous chat column. - Implemented global themed scrollbars and integrated the 'Lahze' font family. - Added `proxy.conf.json` and updated `angular.json` to support local backend development. - **Documentation**: - Added comprehensive API handoff guides for frontend-backend connection and MVP API catalog.
This commit is contained in:
@@ -1,7 +1,7 @@
|
||||
import { Injectable, NgZone, computed, inject, signal } from '@angular/core';
|
||||
import { Subject } from 'rxjs';
|
||||
import { MicrophoneError } from '../microphone/microphone.service';
|
||||
import { VoiceApiError, VoiceApiService } from './voice-api.service';
|
||||
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 {
|
||||
@@ -21,7 +21,8 @@ export type VoiceStartFailure =
|
||||
| 'auth'
|
||||
| 'unavailable'
|
||||
| 'api'
|
||||
| 'connect';
|
||||
| 'connect'
|
||||
| 'overflow';
|
||||
|
||||
export type VoiceStartResult =
|
||||
| { ok: true }
|
||||
@@ -45,8 +46,11 @@ const MESSAGES = {
|
||||
api: 'شروع گفتگوی صوتی ناموفق بود. دوباره تلاش کنید.',
|
||||
connect: 'اتصال به سرور صوتی برقرار نشد. دوباره تلاش کنید.',
|
||||
badFormat: 'فرمت صدای سرور با برنامه سازگار نیست.',
|
||||
overflow: 'حجم صدای در حال پخش از محدودهٔ مجاز گذشت و گفتگو بهطور ایمن پایان یافت.',
|
||||
disconnected: 'ارتباط با سرور قطع شد و گفتگو پایان یافت.',
|
||||
server: 'سرور گفتگوی صوتی با خطا مواجه شد.',
|
||||
contextRevoked: 'محتوای دانش تغییر کرده و مکالمهٔ قبلی دیگر معتبر نیست. گفتگوی جدیدی شروع کنید.',
|
||||
stale: 'مکالمهٔ قبلی منقضی شده است. گفتگوی جدیدی شروع کنید.',
|
||||
conversationTitle: 'گفتگوی صوتی',
|
||||
} as const;
|
||||
|
||||
@@ -54,20 +58,29 @@ const MESSAGES = {
|
||||
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;
|
||||
|
||||
/**
|
||||
* One live voice call against the MVP API (mvp_ui_api_catalog.md §6):
|
||||
* One live voice call against the backend handoff contract (§7–§9):
|
||||
*
|
||||
* mic ─▶ engine ─▶ PCM16 16 kHz frames ─▶ WSS ─▶ server
|
||||
* server ─▶ session_ready / transcript / sources / turn_interrupted / error (JSON)
|
||||
* mic ─▶ engine ─▶ PCM16 24 kHz frames ─▶ WSS ─▶ server
|
||||
* server ─▶ session_ready / user_speech_started / transcript / sources /
|
||||
* audio_started / audio_ended / turn_interrupted / 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) → GET /configuration (voice enabled?)
|
||||
* → POST /conversations → POST /voice/sessions → WSS stream_path → `session_ready`.
|
||||
* End: close the socket, stop audio, POST /voice/sessions/{id}/close.
|
||||
* 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 client→server interrupt message.)
|
||||
* 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 {
|
||||
@@ -106,6 +119,24 @@ export class VoiceStreamService {
|
||||
} | 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 progressWaiters: Array<() => void> = [];
|
||||
|
||||
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> {
|
||||
@@ -120,27 +151,35 @@ export class VoiceStreamService {
|
||||
this.clearError();
|
||||
this.resetTurnFlags();
|
||||
this.lastConversationId = null;
|
||||
this.currentAudioRef = null;
|
||||
this.playedMsByRef.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: () => this.ngZone.run(() => this.onPlaybackIdle()),
|
||||
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()) {
|
||||
// Cancelled while the permission prompt / worklets were loading: release what was just opened.
|
||||
if (!this.isOpen()) this.engine.stop();
|
||||
return this.failure('cancelled', '');
|
||||
}
|
||||
|
||||
// 2) REST: identity/CSRF → capabilities → conversation → voice session
|
||||
let streamPath: string;
|
||||
let voiceSession: VoiceSessionResponse;
|
||||
try {
|
||||
const me = await this.api.me();
|
||||
if (stale()) return this.failure('cancelled', '');
|
||||
@@ -151,29 +190,31 @@ export class VoiceStreamService {
|
||||
return this.abortStart(session, { reason: 'unavailable', message: MESSAGES.voiceDisabled });
|
||||
}
|
||||
|
||||
const conversation = await this.api.createConversation(me.csrf_token, MESSAGES.conversationTitle);
|
||||
if (stale()) return this.failure('cancelled', '');
|
||||
|
||||
const voiceSession = await this.api.createVoiceSession(me.csrf_token, conversation.id);
|
||||
const remote = {
|
||||
sessionId: voiceSession.session_id,
|
||||
conversationId: conversation.id,
|
||||
csrf: me.csrf_token,
|
||||
};
|
||||
voiceSession = await this.reserve(me.csrf_token, options.title ?? MESSAGES.conversationTitle);
|
||||
if (stale()) {
|
||||
this.closeRemote(remote); // cancelled after the server already reserved the session
|
||||
this.closeRemote({ sessionId: voiceSession.session_id, csrf: me.csrf_token });
|
||||
this.attempt = null;
|
||||
clearPersistedAttempt();
|
||||
return this.failure('cancelled', '');
|
||||
}
|
||||
this.remote = remote;
|
||||
this.lastConversationId = conversation.id;
|
||||
streamPath = voiceSession.stream_path;
|
||||
} catch (err) {
|
||||
if (stale()) return this.failure('cancelled', '');
|
||||
return this.abortStart(session, this.mapApiError(err));
|
||||
// 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(streamPath));
|
||||
const transport = this.createTransport(this.api.streamUrl(voiceSession.stream_path));
|
||||
this.transport = transport;
|
||||
try {
|
||||
await this.ngZone.runOutsideAngular(() =>
|
||||
@@ -181,6 +222,7 @@ export class VoiceStreamService {
|
||||
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)),
|
||||
}),
|
||||
);
|
||||
} catch {
|
||||
@@ -216,8 +258,92 @@ export class VoiceStreamService {
|
||||
|
||||
/** User ends the call. Safe to call at any time. */
|
||||
end(): void {
|
||||
if (!this.isOpen()) return;
|
||||
this.finishSession();
|
||||
void this.close();
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
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 });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 {
|
||||
@@ -236,9 +362,10 @@ export class VoiceStreamService {
|
||||
this.clearError();
|
||||
}
|
||||
|
||||
/** Component teardown: release everything without emitting events. */
|
||||
/** Component teardown: release a live call without emitting events. */
|
||||
dispose(): void {
|
||||
this.rejectReady();
|
||||
if (!this.isOpen()) return; // keep an ambiguous attempt for reconciliation
|
||||
this.teardown();
|
||||
}
|
||||
|
||||
@@ -248,11 +375,11 @@ export class VoiceStreamService {
|
||||
if (this.streaming) this.transport?.sendAudio(pcm);
|
||||
}
|
||||
|
||||
// ---- audio from the server (outside the zone) ------------------------------
|
||||
// ---- audio from the server (outside the zone) -----------------------------
|
||||
|
||||
private onServerAudio(chunk: ArrayBuffer, session: number): void {
|
||||
if (session !== this.session || !this.streaming) return;
|
||||
this.engine.enqueuePlayback(chunk);
|
||||
this.engine.enqueuePlayback(chunk, this.currentAudioRef);
|
||||
this.clearSettleTimer();
|
||||
|
||||
if (this.state() !== 'SPEAKING') {
|
||||
@@ -266,6 +393,52 @@ export class VoiceStreamService {
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 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 {
|
||||
@@ -286,6 +459,10 @@ export class VoiceStreamService {
|
||||
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;
|
||||
@@ -294,6 +471,15 @@ export class VoiceStreamService {
|
||||
this.upsertSources(event);
|
||||
break;
|
||||
|
||||
case 'audio_started':
|
||||
this.currentAudioRef = event.audio_ref;
|
||||
break;
|
||||
|
||||
case 'audio_ended':
|
||||
// Generation ended; the ref's audio may still be playing — its final progress is
|
||||
// reported when the queue drains or the turn is interrupted.
|
||||
break;
|
||||
|
||||
case 'turn_interrupted':
|
||||
this.onTurnInterrupted(event.turn_ref);
|
||||
break;
|
||||
@@ -329,7 +515,7 @@ export class VoiceStreamService {
|
||||
|
||||
/** Server-side barge-in: the user spoke over the assistant. */
|
||||
private onTurnInterrupted(turnRef: string): void {
|
||||
this.engine.clearPlayback(); // empty the playback queue immediately
|
||||
this.engine.clearPlayback(); // the worklet posts the final progress for the active ref
|
||||
this.turnEnded = false;
|
||||
this.clearSettleTimer();
|
||||
this.markInterrupted(turnRef);
|
||||
@@ -349,6 +535,17 @@ export class VoiceStreamService {
|
||||
const { message, retryable, code } = event.error;
|
||||
console.warn('VoiceStreamService: server error', code, event.error.request_id);
|
||||
|
||||
// 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);
|
||||
return;
|
||||
@@ -426,12 +623,11 @@ export class VoiceStreamService {
|
||||
}
|
||||
|
||||
/**
|
||||
* The catalog does not say whether a `partial` carries the full text so far or only the new fragment,
|
||||
* The contract does not say whether a `partial` carries the full text so far or only the new fragment,
|
||||
* so both are handled:
|
||||
* - `completed` with text → the final full text replaces whatever was accumulated
|
||||
* - text that starts with what we already have → cumulative, replace
|
||||
* - anything else → a fragment, append as-is (fragments carry their own spacing)
|
||||
* If the backend turns out to use only one style, this is the single place to simplify.
|
||||
*/
|
||||
private mergeTranscriptText(previous: string, event: TranscriptEvent): string {
|
||||
const next = event.text;
|
||||
@@ -452,9 +648,14 @@ export class VoiceStreamService {
|
||||
|
||||
const sources = [...(current.sources ?? [])];
|
||||
for (const source of event.sources) {
|
||||
if (!sources.some((s) => s.source_ref === source.source_ref && s.chunk_id === source.chunk_id)) {
|
||||
sources.push(source);
|
||||
}
|
||||
// `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 };
|
||||
@@ -494,34 +695,29 @@ export class VoiceStreamService {
|
||||
|
||||
private failSession(message: string, session: number): void {
|
||||
if (session !== this.session || !this.isOpen()) return;
|
||||
this.finishSession(message);
|
||||
}
|
||||
|
||||
private finishSession(error?: string): void {
|
||||
const wasConnected = this.connection() === 'connected';
|
||||
const conversationId = this.remote?.conversationId ?? this.lastConversationId;
|
||||
this.rejectReady();
|
||||
this.finalizeAll();
|
||||
const messages = this.messages();
|
||||
this.teardown();
|
||||
if (wasConnected) this.sessionEnded$.next({ conversationId, messages, error });
|
||||
// `close()` performs the ordered teardown (final progress → V04 → transport) and
|
||||
// emits sessionEnded$ exactly once, carrying the failure message.
|
||||
void this.close({ error: message });
|
||||
}
|
||||
|
||||
private abortStart(
|
||||
session: number,
|
||||
failure: { reason: VoiceStartFailure; message: string },
|
||||
keepAttempt = false,
|
||||
): VoiceStartResult {
|
||||
if (session === this.session) this.teardown();
|
||||
if (session === this.session) this.teardown({ keepAttempt });
|
||||
return this.failure(failure.reason, failure.message);
|
||||
}
|
||||
|
||||
/** Releases every resource; idempotent. Invalidates all pending async work via `session`. */
|
||||
private teardown(): void {
|
||||
private teardown(options: { keepAttempt?: boolean } = {}): void {
|
||||
this.session++;
|
||||
this.streaming = false;
|
||||
this.resetTurnFlags();
|
||||
this.clearSettleTimer();
|
||||
this.clearError();
|
||||
this.resolveProgressWaiters();
|
||||
this.currentAudioRef = null;
|
||||
if (this.interruptTimer) {
|
||||
clearTimeout(this.interruptTimer);
|
||||
this.interruptTimer = null;
|
||||
@@ -532,9 +728,14 @@ export class VoiceStreamService {
|
||||
transport?.close();
|
||||
this.engine.stop();
|
||||
|
||||
// V04: tell the server the session is over (best effort).
|
||||
// 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;
|
||||
if (!options.keepAttempt) {
|
||||
this.attempt = null;
|
||||
clearPersistedAttempt();
|
||||
}
|
||||
if (remote) this.closeRemote(remote);
|
||||
|
||||
this.connection.set('disconnected');
|
||||
@@ -548,6 +749,23 @@ 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');
|
||||
};
|
||||
|
||||
private resetTurnFlags(): void {
|
||||
this.turnEnded = false;
|
||||
}
|
||||
@@ -589,6 +807,114 @@ export class VoiceStreamService {
|
||||
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 } {
|
||||
@@ -605,19 +931,24 @@ export class VoiceStreamService {
|
||||
return { reason: 'engine', message: MESSAGES.engine };
|
||||
}
|
||||
|
||||
/** Maps the catalog's error codes (§7) to a user-facing Persian message. */
|
||||
/** 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':
|
||||
return { reason: 'api', message: MESSAGES.sessionUnusable };
|
||||
case 'CONTEXT_REVOKED':
|
||||
case 'CONVERSATION_STALE':
|
||||
return { reason: 'api', message: MESSAGES.stale };
|
||||
case 'NETWORK':
|
||||
return { reason: 'connect', message: MESSAGES.connect };
|
||||
default:
|
||||
@@ -628,4 +959,56 @@ export class VoiceStreamService {
|
||||
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: crypto.randomUUID(),
|
||||
sessionRequestId: crypto.randomUUID(),
|
||||
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 */
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user