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:
@@ -50,11 +50,16 @@ export class HttpService {
|
||||
* the dev-server proxy (proxy.conf.json) forwards `/api` — including WebSocket
|
||||
* upgrades — to the backend. The `rag_session` cookie therefore stays same-origin
|
||||
* and is sent automatically; no bearer token is used for the MVP endpoints.
|
||||
*
|
||||
* NOTE: the origin MUST stay empty (`''`). Pointing these at an absolute host
|
||||
* (e.g. `http://10.2.8.3:8080`) turns every request cross-origin, and browsers
|
||||
* refuse to send the session cookie cross-origin over plain HTTP — the backend
|
||||
* then answers 401 AUTH_REQUIRED even though the user is logged in.
|
||||
*/
|
||||
private readonly baseUrl = 'http://10.0.8.51:1321';
|
||||
public readonly backendUrl = 'http://10.0.8.51:1321';
|
||||
public readonly apiUrl = 'http://10.0.8.51:1321';
|
||||
public readonly imagesUrl = 'http://10.0.8.51:1321';
|
||||
private readonly baseUrl = '';
|
||||
public readonly backendUrl = '';
|
||||
public readonly apiUrl = '';
|
||||
public readonly imagesUrl = '';
|
||||
|
||||
constructor(
|
||||
private readonly http: HttpClient,
|
||||
@@ -170,6 +175,7 @@ export class HttpService {
|
||||
.get<ApiResult<T>>(url, {
|
||||
headers,
|
||||
params: options.params,
|
||||
withCredentials: true,
|
||||
})
|
||||
.pipe(
|
||||
map((response) => this.processResponse(response, options)),
|
||||
@@ -206,7 +212,7 @@ export class HttpService {
|
||||
...headers,
|
||||
},
|
||||
signal: controller.signal,
|
||||
credentials: 'same-origin',
|
||||
credentials: 'include',
|
||||
})
|
||||
.then((response) => {
|
||||
if (!response.ok || !response.body) {
|
||||
@@ -268,6 +274,7 @@ export class HttpService {
|
||||
.post<ApiResult<T>>(url, data, {
|
||||
headers: this.mergeHeaders(options.headers),
|
||||
params: options.params,
|
||||
withCredentials: true,
|
||||
})
|
||||
.pipe(
|
||||
map((response) => this.processResponse(response, options)),
|
||||
@@ -281,6 +288,7 @@ export class HttpService {
|
||||
return this.http.post<T>(url, data, {
|
||||
headers,
|
||||
params: options.params,
|
||||
withCredentials: true,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -292,7 +300,7 @@ export class HttpService {
|
||||
const url = `${this.baseUrl}/${endpoint}`;
|
||||
const headers = options.headers ? new HttpHeaders(options.headers) : new HttpHeaders();
|
||||
return this.http
|
||||
.patch<T>(url, data, { headers, params: options.params })
|
||||
.patch<T>(url, data, { headers, params: options.params, withCredentials: true })
|
||||
.pipe(catchError((err) => this.handleError(err, options.skipToast)));
|
||||
}
|
||||
|
||||
@@ -315,6 +323,7 @@ export class HttpService {
|
||||
params: options.params,
|
||||
reportProgress: true,
|
||||
observe: 'events',
|
||||
withCredentials: true,
|
||||
});
|
||||
|
||||
if (!options.signal) {
|
||||
@@ -341,6 +350,7 @@ export class HttpService {
|
||||
return this.http.get<T>(url, {
|
||||
headers,
|
||||
params: options.params,
|
||||
withCredentials: true,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -350,6 +360,7 @@ export class HttpService {
|
||||
.put<ApiResult<T>>(url, data, {
|
||||
headers: this.mergeHeaders(options.headers),
|
||||
params: options.params,
|
||||
withCredentials: true,
|
||||
})
|
||||
.pipe(
|
||||
map((response) => this.processResponse(response, options)),
|
||||
@@ -363,6 +374,7 @@ export class HttpService {
|
||||
.patch<ApiResult<T>>(url, data, {
|
||||
headers: this.mergeHeaders(options.headers),
|
||||
params: options.params,
|
||||
withCredentials: true,
|
||||
})
|
||||
.pipe(
|
||||
map((response) => this.processResponse(response, options)),
|
||||
@@ -376,6 +388,7 @@ export class HttpService {
|
||||
.delete<ApiResult<T>>(url, {
|
||||
headers: this.mergeHeaders(options.headers),
|
||||
params: options.params,
|
||||
withCredentials: true,
|
||||
})
|
||||
.pipe(
|
||||
map((response) => this.processResponse(response, options)),
|
||||
@@ -388,6 +401,7 @@ export class HttpService {
|
||||
.get(url, {
|
||||
headers: this.getHeaders(),
|
||||
responseType: 'blob',
|
||||
withCredentials: true,
|
||||
})
|
||||
.pipe(catchError((err) => this.handleError(err, false)));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,225 @@
|
||||
import { describe, it, vi } from 'vitest';
|
||||
|
||||
/**
|
||||
* Loads the REAL public/assets/worklets/pcm-playback.worklet.js in a stubbed AudioWorklet
|
||||
* global scope (no browser, no node builtins) and returns a processor instance. The worklet
|
||||
* references the ambient `sampleRate`, `AudioWorkletProcessor` and `registerProcessor`
|
||||
* globals; we inject them on `globalThis` before importing the module, then vary
|
||||
* `globalThis.sampleRate` per instance to exercise every context rate deterministically
|
||||
* (the class reads `sampleRate` at call time, not at module-eval time).
|
||||
*/
|
||||
interface Proc {
|
||||
out: Array<{ type: string; audioRef?: string; playedMs?: number }>;
|
||||
port: { onmessage: (e: { data: unknown }) => void };
|
||||
count: number;
|
||||
capacity: number;
|
||||
queuedSource: number;
|
||||
sourceCapacity: number;
|
||||
refPlayedSamples: Map<string, number>;
|
||||
process: (inputs: unknown[][][], outputs: Float32Array[][]) => boolean;
|
||||
}
|
||||
|
||||
class FakeAudioWorkletProcessor {
|
||||
out: Array<{ type: string; audioRef?: string; playedMs?: number }> = [];
|
||||
port: {
|
||||
onmessage: ((e: { data: unknown }) => void) | null;
|
||||
postMessage: (m: { type: string; audioRef?: string; playedMs?: number }) => void;
|
||||
};
|
||||
constructor() {
|
||||
this.port = { onmessage: null, postMessage: (m) => this.out.push(m) };
|
||||
}
|
||||
}
|
||||
|
||||
let Registered: (new () => Proc) | null = null;
|
||||
const ensureRegistered = async (): Promise<new () => Proc> => {
|
||||
if (Registered) return Registered;
|
||||
const g = globalThis as unknown as Record<string, unknown>;
|
||||
g['AudioWorkletProcessor'] = FakeAudioWorkletProcessor;
|
||||
g['registerProcessor'] = (_name: string, cls: new () => Proc) => {
|
||||
Registered = cls;
|
||||
};
|
||||
// The worklet is plain JS with Web Audio ambient globals; silence the missing ambient types.
|
||||
// @ts-expect-error - worklet has no type declarations
|
||||
await import('../../../../public/assets/worklets/pcm-playback.worklet.js');
|
||||
if (!Registered) throw new Error('worklet did not register a processor');
|
||||
return Registered;
|
||||
};
|
||||
|
||||
async function loadPlaybackProcessor(contextRate: number): Promise<Proc> {
|
||||
const ctor = await ensureRegistered();
|
||||
(globalThis as unknown as { sampleRate: number }).sampleRate = contextRate;
|
||||
return new ctor();
|
||||
}
|
||||
|
||||
/** A frame of 24 kHz wire PCM with a non-trivial ramp signal. */
|
||||
function frame(sampleOffset: number, samples = 2400): Int16Array {
|
||||
const pcm = new Int16Array(samples);
|
||||
for (let i = 0; i < samples; i++) pcm[i] = ((sampleOffset + i) % 1000) - 500;
|
||||
return pcm;
|
||||
}
|
||||
|
||||
function push(proc: Proc, pcm: Int16Array, audioRef: string | null): void {
|
||||
// The engine transfers the buffer; the worklet re-wraps it. Copy so the frame is reusable.
|
||||
const copy = pcm.slice().buffer;
|
||||
proc.port.onmessage({ data: { type: 'push', pcm: copy, sampleRate: 24000, audioRef } });
|
||||
}
|
||||
|
||||
function clear(proc: Proc): void {
|
||||
proc.port.onmessage({ data: { type: 'clear' } });
|
||||
}
|
||||
|
||||
/** One render quantum: emit `samples` output slots and let process() consume/emit. */
|
||||
function render(proc: Proc, samples = 128): void {
|
||||
proc.process([[]], [[new Float32Array(samples)]]);
|
||||
}
|
||||
|
||||
/** Drain everything currently queued (bounded, so a bug cannot hang the test). */
|
||||
function drain(proc: Proc, quantum = 1024): void {
|
||||
let renders = 0;
|
||||
while (proc.count > 0 && renders < 100000) {
|
||||
render(proc, quantum);
|
||||
renders++;
|
||||
}
|
||||
}
|
||||
|
||||
const overflowCount = (proc: Proc): number => proc.out.filter((m) => m.type === 'overflow').length;
|
||||
const idleCount = (proc: Proc): number => proc.out.filter((m) => m.type === 'idle').length;
|
||||
const playedFor = (proc: Proc, ref: string): number =>
|
||||
Math.max(0, ...proc.out.filter((m) => m.audioRef === ref).map((m) => m.playedMs ?? 0));
|
||||
|
||||
describe('pcm-playback.worklet', () => {
|
||||
describe('bounded queue is rate-invariant (source units)', () => {
|
||||
// 12 × 2400 source samples = 57,600 source bytes < the 96,000-byte bound: never overflow,
|
||||
// whatever the context rate is. This is the exact reproduction that used to overflow at 48k.
|
||||
for (const rate of [24000, 44100, 48000]) {
|
||||
it(`admits 57,600 source bytes without overflow at a ${rate} Hz context`, async () => {
|
||||
const proc = await loadPlaybackProcessor(rate);
|
||||
for (let c = 0; c < 12; c++) push(proc, frame(c * 2400), 'aud-1');
|
||||
|
||||
expect(overflowCount(proc)).toBe(0);
|
||||
expect(proc.queuedSource).toBe(12 * 2400); // 28,800 source samples admitted
|
||||
expect(proc.queuedSource).toBeLessThanOrEqual(proc.sourceCapacity);
|
||||
expect(proc.count).toBeLessThanOrEqual(proc.capacity); // never exceeds the ring
|
||||
});
|
||||
}
|
||||
|
||||
// At any context rate the SAME 96,000 source bytes (48,000 samples) fit, and the next
|
||||
// source sample overflows — the bound is on SOURCE PCM, so it must not depend on rate.
|
||||
for (const rate of [24000, 48000]) {
|
||||
it(`overflows only past the 96,000-byte source bound at ${rate} Hz`, async () => {
|
||||
const proc = await loadPlaybackProcessor(rate);
|
||||
for (let c = 0; c < 20; c++) {
|
||||
push(proc, frame(c * 2400), 'aud-1');
|
||||
expect(proc.count).toBeLessThanOrEqual(proc.capacity);
|
||||
}
|
||||
expect(proc.queuedSource).toBe(20 * 2400); // exactly 48,000 source samples
|
||||
expect(overflowCount(proc)).toBe(0);
|
||||
|
||||
push(proc, frame(20 * 2400), 'aud-1'); // one source sample past the bound
|
||||
expect(overflowCount(proc)).toBe(1);
|
||||
expect(proc.count).toBeLessThanOrEqual(proc.capacity); // ring never overwritten
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
it('posts exactly one overflow under sustained overload (genuine overload fails safely)', async () => {
|
||||
const proc = await loadPlaybackProcessor(48000);
|
||||
for (let c = 0; c < 50; c++) push(proc, frame(c * 2400), 'aud-1');
|
||||
expect(overflowCount(proc)).toBe(1); // not one per rejected chunk
|
||||
});
|
||||
|
||||
it('keeps queue and outstanding source bounded under continuous enqueue + consumption', async () => {
|
||||
const proc = await loadPlaybackProcessor(48000);
|
||||
let peakCount = 0;
|
||||
let peakSource = 0;
|
||||
// Model real time: push 20 ms frames (480 source samples) and consume ~2× that in output,
|
||||
// so consumption outpaces production and the queue must stay near-empty (no overflow).
|
||||
for (let turn = 0; turn < 300; turn++) {
|
||||
push(proc, frame(turn * 480, 480), `aud-${turn % 3}`);
|
||||
for (let i = 0; i < 4; i++) render(proc, 256); // 1024 output slots consumed
|
||||
peakCount = Math.max(peakCount, proc.count);
|
||||
peakSource = Math.max(peakSource, proc.queuedSource);
|
||||
expect(proc.count).toBeLessThanOrEqual(proc.capacity);
|
||||
}
|
||||
expect(overflowCount(proc)).toBe(0);
|
||||
expect(peakCount).toBeLessThanOrEqual(proc.capacity);
|
||||
expect(peakSource).toBeLessThan(proc.sourceCapacity);
|
||||
});
|
||||
|
||||
describe('fractional resampling across chunk boundaries', () => {
|
||||
// 6,000 source samples = 250 ms at 24 kHz. A linear resampler carries ~1 sample of latency
|
||||
// across a boundary, so reported progress is within 1 ms of 250 — but it must never
|
||||
// OVER-claim (>250) and must not depend on where the chunk boundary falls.
|
||||
for (const rate of [24000, 44100, 48000]) {
|
||||
it(`reports the same ~250 ms whether split or whole at ${rate} Hz`, async () => {
|
||||
const oneChunk = await loadPlaybackProcessor(rate);
|
||||
push(oneChunk, frame(0, 6000), 'aud-1');
|
||||
drain(oneChunk);
|
||||
const singleFinal = playedFor(oneChunk, 'aud-1');
|
||||
|
||||
const twoChunks = await loadPlaybackProcessor(rate);
|
||||
push(twoChunks, frame(0, 3000), 'aud-1');
|
||||
push(twoChunks, frame(3000, 3000), 'aud-1');
|
||||
drain(twoChunks);
|
||||
const splitFinal = playedFor(twoChunks, 'aud-1');
|
||||
|
||||
expect(singleFinal).toBeGreaterThanOrEqual(249);
|
||||
expect(singleFinal).toBeLessThanOrEqual(250); // never claim an unheard millisecond
|
||||
expect(splitFinal).toBeGreaterThanOrEqual(249);
|
||||
expect(splitFinal).toBeLessThanOrEqual(250);
|
||||
expect(Math.abs(singleFinal - splitFinal)).toBeLessThanOrEqual(1); // boundary is seamless
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
describe('progress is accurate, monotonic and per audio_ref', () => {
|
||||
it('credits each queued ref its own consumed source (never the next ref)', async () => {
|
||||
const proc = await loadPlaybackProcessor(24000); // ratio 1 → 3,000 source ≈ 125 ms
|
||||
push(proc, frame(0, 3000), 'aud-a');
|
||||
push(proc, frame(3000, 3000), 'aud-b'); // arrives while 'aud-a' is still queued
|
||||
|
||||
// Consume only the first half: it must all be credited to 'aud-a', never 'aud-b'.
|
||||
render(proc, 1024);
|
||||
render(proc, 1024);
|
||||
expect(proc.out.filter((m) => m.audioRef === 'aud-b')).toHaveLength(0); // not heard yet
|
||||
|
||||
const aValues = proc.out.filter((m) => m.audioRef === 'aud-a').map((m) => m.playedMs ?? 0);
|
||||
expect(aValues).toEqual([...aValues].sort((x, y) => x - y)); // monotonic
|
||||
|
||||
drain(proc);
|
||||
|
||||
// Each ref consumed only its own ~3,000 source samples (±1 sample of resampler lag),
|
||||
// never the other ref's samples. The next-ref bug would credit 'aud-b' with 6,000.
|
||||
expect(Math.abs((proc.refPlayedSamples.get('aud-a') ?? 0) - 3000)).toBeLessThanOrEqual(1);
|
||||
expect(Math.abs((proc.refPlayedSamples.get('aud-b') ?? 0) - 3000)).toBeLessThanOrEqual(1);
|
||||
const finalA = playedFor(proc, 'aud-a');
|
||||
const finalB = playedFor(proc, 'aud-b');
|
||||
expect(finalA).toBeGreaterThanOrEqual(124);
|
||||
expect(finalA).toBeLessThanOrEqual(125);
|
||||
expect(finalB).toBeLessThanOrEqual(125); // NOT 250: 'aud-a' samples were not credited to 'aud-b'
|
||||
});
|
||||
});
|
||||
|
||||
describe('interruption and clear', () => {
|
||||
it('clears the queue and reports only the source actually consumed', async () => {
|
||||
const proc = await loadPlaybackProcessor(24000);
|
||||
push(proc, frame(0, 3000), 'aud-a');
|
||||
render(proc, 128); // started, consumes 128 source samples (~5 ms)
|
||||
clear(proc);
|
||||
|
||||
expect(proc.count).toBe(0);
|
||||
expect(proc.queuedSource).toBe(0);
|
||||
// Final progress reflects what was actually heard (~5 ms), not the whole 3,000 queue.
|
||||
const finals = proc.out.filter((m) => m.type === 'progress' && m.audioRef === 'aud-a');
|
||||
expect(finals.at(-1)?.playedMs).toBe(5);
|
||||
expect(proc.refPlayedSamples.get('aud-a') ?? 0).toBeCloseTo(128, 5);
|
||||
|
||||
// A fresh ref plays normally after the interruption.
|
||||
push(proc, frame(0, 3000), 'aud-b');
|
||||
drain(proc);
|
||||
expect(idleCount(proc)).toBe(1);
|
||||
expect(playedFor(proc, 'aud-b')).toBeGreaterThanOrEqual(124);
|
||||
expect(playedFor(proc, 'aud-b')).toBeLessThanOrEqual(125);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,11 +1,14 @@
|
||||
import { HttpClient, HttpErrorResponse, HttpHeaders } from '@angular/common/http';
|
||||
import { Injectable, inject } from '@angular/core';
|
||||
import { firstValueFrom, race, throwError, Observable } from 'rxjs';
|
||||
import { delay } from 'rxjs/operators';
|
||||
import { firstValueFrom, Observable } from 'rxjs';
|
||||
import { VOICE_STREAM_CONFIG, VoiceSessionStatus } from './voice-stream.types';
|
||||
|
||||
/** The voice helper's HTTP deadline: a client timeout never means the server rolled back. */
|
||||
const REQUEST_DEADLINE_MS = 5000;
|
||||
/**
|
||||
* The voice helper's HTTP deadline: a client timeout never means the server rolled back.
|
||||
* Generous on purpose — the UI runs against a remote backend through the dev-server proxy,
|
||||
* and the first call after a reload pays the proxy connection setup.
|
||||
*/
|
||||
const REQUEST_DEADLINE_MS = 15000;
|
||||
|
||||
/** Error envelope from the contract: { error: { code, message, request_id, retryable, details } }. */
|
||||
export class VoiceApiError extends Error {
|
||||
@@ -199,14 +202,52 @@ export class VoiceApiService {
|
||||
}
|
||||
}
|
||||
|
||||
/** A short deadline keeps the UI responsive; the caller reconciles the uncertain outcome. */
|
||||
/**
|
||||
* A deadline that never aborts the request.
|
||||
*
|
||||
* `race()` is not usable here: when the timer wins, `race` unsubscribes the loser, so the
|
||||
* HttpClient would abort its XHR. An aborted XHR is reported by the browser as
|
||||
* "(canceled)" — with no status code at all — which is exactly what was observed for
|
||||
* `/api/v1/me`. It also makes a reserve ambiguous ("did the server create it?") instead of
|
||||
* letting it settle, which defeats the V03 reconciliation this flow is built around.
|
||||
*
|
||||
* Here the request subscription is deliberately kept alive: the UI still gets the timeout,
|
||||
* the XHR runs to completion, and a late response is simply discarded.
|
||||
*/
|
||||
private withDeadline<T>(request: Observable<T>): Observable<T> {
|
||||
return race(
|
||||
request,
|
||||
throwError(() => new VoiceApiError(0, 'TIMEOUT', 'request-deadline')).pipe(
|
||||
delay(REQUEST_DEADLINE_MS),
|
||||
),
|
||||
);
|
||||
return new Observable<T>((observer) => {
|
||||
let settled = false;
|
||||
|
||||
const timer = setTimeout(() => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
observer.error(new VoiceApiError(0, 'TIMEOUT', 'request-deadline'));
|
||||
}, REQUEST_DEADLINE_MS);
|
||||
|
||||
request.subscribe({
|
||||
next: (value) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timer);
|
||||
observer.next(value);
|
||||
},
|
||||
error: (err: unknown) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timer);
|
||||
observer.error(this.toApiError(err));
|
||||
},
|
||||
complete: () => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timer);
|
||||
observer.complete();
|
||||
},
|
||||
});
|
||||
|
||||
// Only the timer is torn down: the in-flight request is left to finish naturally.
|
||||
return () => clearTimeout(timer);
|
||||
});
|
||||
}
|
||||
|
||||
private toApiError(err: unknown): VoiceApiError {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Injectable, NgZone, inject } from '@angular/core';
|
||||
import { MicrophoneService } from '../microphone/microphone.service';
|
||||
import { MicrophoneError, MicrophoneService } from '../microphone/microphone.service';
|
||||
import { VOICE_STREAM_CONFIG } from './voice-stream.types';
|
||||
|
||||
export interface VoiceEngineHandlers {
|
||||
@@ -72,15 +72,28 @@ export class VoiceAudioEngine {
|
||||
await this.ngZone.runOutsideAngular(() => this.buildGraph(stream, handlers));
|
||||
} catch (err) {
|
||||
this.stop();
|
||||
throw err instanceof Error && err.name === 'MicrophoneError' ? err : new VoiceEngineError('worklet-failed');
|
||||
// Preserve the specific engine error (unsupported vs worklet-failed); only a raw
|
||||
// failure inside buildGraph is a generic worklet failure.
|
||||
if (err instanceof MicrophoneError || err instanceof VoiceEngineError) throw err;
|
||||
throw new VoiceEngineError('worklet-failed');
|
||||
}
|
||||
}
|
||||
|
||||
private async buildGraph(stream: MediaStream, handlers: VoiceEngineHandlers): Promise<void> {
|
||||
const cfg = this.config;
|
||||
const ctx = new AudioContext({ latencyHint: 'interactive' });
|
||||
// The wire format is fixed at 24 kHz mono PCM16. Request that context rate so the
|
||||
// native path needs no conversion, but browsers MAY ignore the request — read the real
|
||||
// `ctx.sampleRate` below and let the worklets resample to/from the wire rate when it
|
||||
// differs. Never assume the requested rate (SKILLS.md §3.2).
|
||||
const ctx = new AudioContext({ latencyHint: 'interactive', sampleRate: cfg.outputSampleRate });
|
||||
this.ctx = ctx;
|
||||
|
||||
// Explicitly reject an unusable context rate: a 0/NaN/non-finite rate cannot resample
|
||||
// and must fail safely instead of silently producing no playback.
|
||||
if (!Number.isFinite(ctx.sampleRate) || ctx.sampleRate < 8000 || ctx.sampleRate > 192000) {
|
||||
throw new VoiceEngineError('unsupported');
|
||||
}
|
||||
|
||||
const base = cfg.workletBasePath.replace(/\/$/, '');
|
||||
await ctx.audioWorklet.addModule(`${base}/pcm-capture.worklet.js`);
|
||||
await ctx.audioWorklet.addModule(`${base}/pcm-playback.worklet.js`);
|
||||
@@ -136,6 +149,22 @@ export class VoiceAudioEngine {
|
||||
this.analyserData = new Uint8Array(this.analyser.fftSize);
|
||||
this.playback.connect(this.analyser);
|
||||
this.analyser.connect(ctx.destination);
|
||||
|
||||
this.logPipelineDiagnostics(ctx);
|
||||
}
|
||||
|
||||
/**
|
||||
* Bounded development diagnostics — one line per session, numbers only. Confirms the
|
||||
* ACTUAL context rate/state (not the requested one) and that the playback graph is
|
||||
* connected and running. Never logs audio, transcripts, cookies or credentials.
|
||||
*/
|
||||
private logPipelineDiagnostics(ctx: AudioContext): void {
|
||||
const requested = this.config.outputSampleRate;
|
||||
const resample = ctx.sampleRate === requested ? 'none' : 'worklet';
|
||||
console.info(
|
||||
`VoiceAudioEngine: ctx.sampleRate=${ctx.sampleRate}Hz (requested ${requested}Hz) ` +
|
||||
`state=${ctx.state} playbackGraph=connected resample=${resample}`,
|
||||
);
|
||||
}
|
||||
|
||||
// ---- playback --------------------------------------------------------------
|
||||
|
||||
@@ -33,9 +33,21 @@ const READY_EVENT: VoiceServerEvent = {
|
||||
output_audio: { encoding: 'pcm_s16le', sample_rate: 24000, channels: 1 },
|
||||
};
|
||||
|
||||
const OVERFLOW_MESSAGE = 'حجم صدای در حال پخش از محدودهٔ مجاز گذشت و گفتگو بهطور ایمن پایان یافت.';
|
||||
const SEND_OVERFLOW_MESSAGE = 'حجم صدای ارسالی از محدودهٔ مجاز گذشت و گفتگو بهطور ایمن پایان یافت.';
|
||||
|
||||
/** Flush pending microtasks/timers so the service reaches a stable await point. */
|
||||
const flush = (): Promise<void> => new Promise((resolve) => setTimeout(resolve, 5));
|
||||
|
||||
type Mock = ReturnType<typeof vi.fn>;
|
||||
type TransportMock = Omit<VoiceTransport, 'connect' | 'sendAudio' | 'sendControl' | 'close'> & {
|
||||
handlers: VoiceTransportHandlers | null;
|
||||
connect: Mock;
|
||||
sendAudio: Mock;
|
||||
sendControl: Mock;
|
||||
close: Mock;
|
||||
};
|
||||
|
||||
describe('VoiceStreamService (backend handoff contract)', () => {
|
||||
let service: VoiceStreamService;
|
||||
let api: {
|
||||
@@ -51,12 +63,15 @@ describe('VoiceStreamService (backend handoff contract)', () => {
|
||||
let engineHandlers: VoiceEngineHandlers | null;
|
||||
let transportHandlers: VoiceTransportHandlers | null;
|
||||
let controls: PlaybackProgressMessage[];
|
||||
let transportMock: TransportMock;
|
||||
let engineStop: ReturnType<typeof vi.fn>;
|
||||
|
||||
beforeEach(() => {
|
||||
sessionStorage.clear();
|
||||
engineHandlers = null;
|
||||
transportHandlers = null;
|
||||
controls = [];
|
||||
engineStop = vi.fn();
|
||||
|
||||
api = {
|
||||
me: vi.fn().mockResolvedValue(ME),
|
||||
@@ -69,7 +84,7 @@ describe('VoiceStreamService (backend handoff contract)', () => {
|
||||
streamUrl: vi.fn().mockReturnValue('wss://ui.local/api/v1/voice/sessions/ses-1/stream'),
|
||||
};
|
||||
|
||||
const transportMock: VoiceTransport & { handlers: VoiceTransportHandlers | null } = {
|
||||
transportMock = {
|
||||
handlers: null,
|
||||
connect: vi.fn().mockImplementation((handlers: VoiceTransportHandlers) => {
|
||||
transportHandlers = handlers;
|
||||
@@ -95,7 +110,7 @@ describe('VoiceStreamService (backend handoff contract)', () => {
|
||||
engineHandlers = handlers;
|
||||
return Promise.resolve();
|
||||
}),
|
||||
stop: vi.fn(),
|
||||
stop: engineStop,
|
||||
setMuted: vi.fn(),
|
||||
enqueuePlayback: vi.fn(),
|
||||
clearPlayback: vi.fn(),
|
||||
@@ -228,10 +243,73 @@ describe('VoiceStreamService (backend handoff contract)', () => {
|
||||
|
||||
engineHandlers?.onPlaybackOverflow();
|
||||
|
||||
expect(await ended).toBe('حجم صدای در حال پخش از محدودهٔ مجاز گذشت و گفتگو بهطور ایمن پایان یافت.');
|
||||
expect(await ended).toBe(OVERFLOW_MESSAGE);
|
||||
expect(service.connection()).toBe('disconnected');
|
||||
});
|
||||
|
||||
it('uses a distinct message for capture/send overflow vs playback overflow', async () => {
|
||||
await startConnected();
|
||||
const ended = firstEndedError();
|
||||
|
||||
transportHandlers?.onOverflow('send');
|
||||
|
||||
expect(await ended).toBe(SEND_OVERFLOW_MESSAGE);
|
||||
expect(await ended).not.toBe(OVERFLOW_MESSAGE);
|
||||
expect(service.connection()).toBe('disconnected');
|
||||
});
|
||||
|
||||
it('concurrent overflow + socket close + Stop send one /close and one teardown', async () => {
|
||||
await startConnected();
|
||||
const ended = firstEndedError();
|
||||
|
||||
// Several end triggers race for the same session (the reported live failure).
|
||||
engineHandlers?.onPlaybackOverflow(); // 1st → overflow error
|
||||
engineHandlers?.onPlaybackOverflow(); // duplicate
|
||||
transportHandlers?.onClose({ clean: false, code: 1006, reason: '' }); // socket close
|
||||
service.end(); // manual Stop
|
||||
|
||||
expect(await ended).toBe(OVERFLOW_MESSAGE); // first meaningful error preserved
|
||||
expect(api.closeVoiceSession).toHaveBeenCalledTimes(1); // V04 sent exactly once
|
||||
expect(transportMock.close).toHaveBeenCalledTimes(1); // socket released once
|
||||
expect(engineStop).toHaveBeenCalledTimes(1); // audio graph released once
|
||||
expect(service.connection()).toBe('disconnected');
|
||||
});
|
||||
|
||||
it('releases local resources even when V04 /close fails', async () => {
|
||||
await startConnected();
|
||||
api.closeVoiceSession.mockRejectedValueOnce(new Error('V04 boom'));
|
||||
|
||||
await service.close();
|
||||
|
||||
expect(api.closeVoiceSession).toHaveBeenCalledTimes(1);
|
||||
expect(transportMock.close).toHaveBeenCalledTimes(1);
|
||||
expect(engineStop).toHaveBeenCalledTimes(1);
|
||||
expect(service.connection()).toBe('disconnected');
|
||||
expect(sessionStorage.getItem('voice_creation_attempt')).toBeNull();
|
||||
});
|
||||
|
||||
it('ignores stale callbacks: an old session cannot close or affect a new one', async () => {
|
||||
await startConnected(); // session A
|
||||
await service.close();
|
||||
api.closeVoiceSession.mockClear();
|
||||
engineStop.mockClear();
|
||||
transportMock.close.mockClear();
|
||||
|
||||
// Late callbacks captured for session A arrive after A already ended.
|
||||
engineHandlers?.onPlaybackOverflow();
|
||||
transportHandlers?.onClose({ clean: false, code: 1006, reason: '' });
|
||||
await flush();
|
||||
expect(api.closeVoiceSession).not.toHaveBeenCalled();
|
||||
expect(service.connection()).toBe('disconnected');
|
||||
|
||||
// A brand-new session is independent and closes exactly once on its own.
|
||||
await startConnected(); // session B
|
||||
expect(service.connection()).toBe('connected');
|
||||
api.closeVoiceSession.mockClear();
|
||||
await service.close();
|
||||
expect(api.closeVoiceSession).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('requires a fresh conversation after CONTEXT_REVOKED and drops the old attempt', async () => {
|
||||
await startConnected();
|
||||
const ended = firstEndedError();
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -100,6 +100,12 @@ export interface VoiceSessionEnd {
|
||||
messages: VoiceMessage[];
|
||||
/** User-facing (Persian) message when the session ended because of a failure. */
|
||||
error?: string;
|
||||
/**
|
||||
* Machine-readable cause for logs/diagnostics, e.g. `ws close 1006 reason="…"`.
|
||||
* The server's close code/reason says why the socket died; without it the only
|
||||
* thing surfaced is a generic "disconnected" banner and the root cause is invisible.
|
||||
*/
|
||||
detail?: string;
|
||||
}
|
||||
|
||||
/** V02/V03 polling shape (safe diagnostics only). */
|
||||
@@ -128,7 +134,7 @@ export interface VoiceStreamConfig {
|
||||
|
||||
export const DEFAULT_VOICE_STREAM_CONFIG: VoiceStreamConfig = {
|
||||
apiBase: '/api/v1',
|
||||
apiOrigin: 'http://10.0.8.51:1322',
|
||||
apiOrigin: '',
|
||||
inputSampleRate: 24000,
|
||||
outputSampleRate: 24000,
|
||||
frameMs: 20,
|
||||
|
||||
@@ -32,6 +32,10 @@ const MAX_QUEUE_MESSAGES = 100;
|
||||
* Plain WebSocket. Authentication is the `rag_session` cookie sent automatically on the
|
||||
* handshake, so the page is served from the same origin as the API (same-origin `/api`
|
||||
* proxy). The contract has exactly one client→server JSON message: `playback_progress`.
|
||||
*
|
||||
* Diagnostics: every control frame received is kept in a short ring buffer and dumped when
|
||||
* the socket dies, so the server's last message — normally an `error` frame carrying the
|
||||
* real cause — is in the console instead of leaving only a bare close code.
|
||||
*/
|
||||
export class WebSocketVoiceTransport implements VoiceTransport {
|
||||
private ws: WebSocket | null = null;
|
||||
@@ -41,6 +45,11 @@ export class WebSocketVoiceTransport implements VoiceTransport {
|
||||
private sendQueue: ArrayBuffer[] = [];
|
||||
private sendQueuedBytes = 0;
|
||||
private sendQueuedMessages = 0;
|
||||
/** Recent server control frames (newest last), replayed when the socket closes. */
|
||||
private readonly recentFrames: string[] = [];
|
||||
|
||||
/** How many recent control frames to keep for a disconnect dump. */
|
||||
private static readonly FRAME_TRACE_LIMIT = 12;
|
||||
|
||||
constructor(
|
||||
private readonly url: string,
|
||||
@@ -70,11 +79,15 @@ export class WebSocketVoiceTransport implements VoiceTransport {
|
||||
|
||||
ws.onmessage = (event: MessageEvent) => {
|
||||
if (typeof event.data === 'string') {
|
||||
let parsed: VoiceServerEvent | null = null;
|
||||
try {
|
||||
handlers.onEvent(JSON.parse(event.data) as VoiceServerEvent);
|
||||
parsed = JSON.parse(event.data) as VoiceServerEvent;
|
||||
} catch {
|
||||
/* ignore malformed control frames */
|
||||
return;
|
||||
}
|
||||
this.traceFrame(parsed);
|
||||
handlers.onEvent(parsed);
|
||||
} else if (event.data instanceof ArrayBuffer) {
|
||||
handlers.onAudio(event.data);
|
||||
}
|
||||
@@ -84,7 +97,12 @@ export class WebSocketVoiceTransport implements VoiceTransport {
|
||||
if (!opened) {
|
||||
clearTimeout(timer);
|
||||
reject(new Error('connect-failed'));
|
||||
return;
|
||||
}
|
||||
// After the handshake a bare Event carries no detail; the `onclose` that follows
|
||||
// has the code/reason. Log it anyway so the disconnect sequence is visible in the
|
||||
// console instead of looking like a silent socket death.
|
||||
console.warn('WebSocketVoiceTransport: socket error after open');
|
||||
};
|
||||
|
||||
ws.onclose = (event: CloseEvent) => {
|
||||
@@ -95,6 +113,7 @@ export class WebSocketVoiceTransport implements VoiceTransport {
|
||||
}
|
||||
this.dropSendQueue();
|
||||
if (!this.closedByClient) {
|
||||
this.logDisconnect(event);
|
||||
handlers.onClose({ clean: event.wasClean, code: event.code, reason: event.reason });
|
||||
}
|
||||
};
|
||||
@@ -150,6 +169,54 @@ export class WebSocketVoiceTransport implements VoiceTransport {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Keep a bounded trace of incoming control frames, and log an `error` frame verbatim —
|
||||
* it is the server telling us why the call is about to end, and it is invisible unless
|
||||
* something prints it.
|
||||
*/
|
||||
private traceFrame(event: VoiceServerEvent): void {
|
||||
const type = event?.type;
|
||||
if (type === 'error') {
|
||||
console.warn('WebSocketVoiceTransport: server sent error frame', event);
|
||||
this.recentFrames.push('error ' + WebSocketVoiceTransport.summarize(event));
|
||||
} else {
|
||||
this.recentFrames.push(WebSocketVoiceTransport.summarize(event));
|
||||
}
|
||||
|
||||
if (this.recentFrames.length > WebSocketVoiceTransport.FRAME_TRACE_LIMIT) {
|
||||
this.recentFrames.shift();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Everything the backend asks for when a disconnect is reported: the close code/reason
|
||||
* plus the frames that led up to it, newest first.
|
||||
*/
|
||||
private logDisconnect(event: CloseEvent): void {
|
||||
const frames = [...this.recentFrames].reverse();
|
||||
console.warn(
|
||||
`WebSocketVoiceTransport: socket closed — code=${event.code} ` +
|
||||
`clean=${event.wasClean} reason="${event.reason}"` +
|
||||
(frames.length ? `\n last server frames (newest first):\n ${frames.join('\n ')}` : ''),
|
||||
);
|
||||
}
|
||||
|
||||
/** One compact line per control frame; errors are printed in full by traceFrame. */
|
||||
private static summarize(event: VoiceServerEvent): string {
|
||||
const type = event?.type ?? 'unknown';
|
||||
if (type === 'transcript') {
|
||||
const t = event as { status?: string; text?: string };
|
||||
return `transcript[${t.status ?? '?'}] ${(t.text ?? '').slice(0, 80)}`;
|
||||
}
|
||||
if (type === 'audio_started' || type === 'audio_ended') {
|
||||
return `${type} ${(event as { audio_ref?: string }).audio_ref ?? ''}`.trim();
|
||||
}
|
||||
if (type === 'error') {
|
||||
return JSON.stringify(event);
|
||||
}
|
||||
return type;
|
||||
}
|
||||
|
||||
private flushSendQueue(): void {
|
||||
const ws = this.ws;
|
||||
const queue = this.sendQueue;
|
||||
|
||||
Reference in New Issue
Block a user