Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
57e8346d51 | ||
|
|
4dac437cc7 | ||
|
|
dc23dbeb69 | ||
|
|
a26c597d4f | ||
|
|
815191588c | ||
|
|
102ce9b909 | ||
|
|
3dddf1f12b | ||
|
|
52202c2a35 | ||
|
|
58c3c20933 |
+1
-1
@@ -3,7 +3,7 @@
|
||||
"version": "0.0.0",
|
||||
"scripts": {
|
||||
"ng": "ng",
|
||||
"start": "ng serve",
|
||||
"start": "ng serve --host 0.0.0.0",
|
||||
"build": "ng build",
|
||||
"watch": "ng build --watch --configuration development",
|
||||
"test": "ng test"
|
||||
|
||||
@@ -27,9 +27,9 @@
|
||||
*
|
||||
* Messages in: { type: 'push', pcm: ArrayBuffer (Int16 mono), sampleRate, audioRef }
|
||||
* { type: 'clear' } barge-in: drop everything immediately
|
||||
* { type: 'flush' } end of turn: emit the tail, play what is left, then idle
|
||||
* { type: 'flush', audioRef } end of turn: emit the tail, play what is left, then idle
|
||||
* Messages out: { type: 'progress', audioRef, playedMs }
|
||||
* { type: 'idle' } buffer ran dry after playing
|
||||
* { type: 'idle', audioRef } buffer ran dry after playing
|
||||
* { type: 'overflow' } bounded queue filled — caller fails the session safely
|
||||
*/
|
||||
const BOUND_BYTES = 96000; // contract cap on outstanding SOURCE PCM16
|
||||
@@ -74,7 +74,7 @@ class PcmPlaybackProcessor extends AudioWorkletProcessor {
|
||||
if (!m) return;
|
||||
if (m.type === 'push') this.push(new Int16Array(m.pcm), m.sampleRate, m.audioRef || null);
|
||||
else if (m.type === 'clear') this.clear();
|
||||
else if (m.type === 'flush') this.flush();
|
||||
else if (m.type === 'flush') this.flush(m.audioRef);
|
||||
};
|
||||
}
|
||||
|
||||
@@ -95,6 +95,16 @@ class PcmPlaybackProcessor extends AudioWorkletProcessor {
|
||||
|
||||
clear() {
|
||||
this.reportFinal(); // final cumulative report for the interrupted ref
|
||||
// Attribute queued output and the deferred tail to their real references.
|
||||
const discarded = new Map();
|
||||
for (const span of this.refQueue) {
|
||||
discarded.set(span.ref, (discarded.get(span.ref) ?? 0) + span.out);
|
||||
}
|
||||
const tail = Math.max(0, Math.round(this.admittedSrc / this.ratio) - this.emittedOut);
|
||||
if (tail > 0) discarded.set(this.pendingRef, (discarded.get(this.pendingRef) ?? 0) + tail);
|
||||
for (const [audioRef, discardedSamples] of discarded) {
|
||||
this.port.postMessage({ type: 'discarded', audioRef, discardedSamples, contextRate: sampleRate });
|
||||
}
|
||||
this.r = this.w = this.count = 0;
|
||||
this.queuedSource = 0;
|
||||
this.refQueue.length = 0;
|
||||
@@ -110,12 +120,12 @@ class PcmPlaybackProcessor extends AudioWorkletProcessor {
|
||||
this.playingRef = null;
|
||||
}
|
||||
|
||||
flush() {
|
||||
flush(audioRef = this.pendingRef) {
|
||||
this.finalizeTail(); // emit the deferred tail so every admitted sample becomes output
|
||||
if (this.count === 0) {
|
||||
this.started = false;
|
||||
this.reportFinal();
|
||||
this.port.postMessage({ type: 'idle' });
|
||||
this.port.postMessage({ type: 'idle', audioRef: audioRef || this.pendingRef });
|
||||
} else {
|
||||
this.started = true; // play the remaining audio + tail without waiting for the prebuffer
|
||||
}
|
||||
@@ -260,7 +270,7 @@ class PcmPlaybackProcessor extends AudioWorkletProcessor {
|
||||
this.queuedSource = 0;
|
||||
this.started = false;
|
||||
this.reportFinal();
|
||||
this.port.postMessage({ type: 'idle' });
|
||||
this.port.postMessage({ type: 'idle', audioRef: this.pendingRef });
|
||||
}
|
||||
} else {
|
||||
ch0.fill(0);
|
||||
@@ -310,7 +320,7 @@ class PcmPlaybackProcessor extends AudioWorkletProcessor {
|
||||
// Multiply integer counts first to avoid rounding an exact whole millisecond down.
|
||||
const playedMs = Math.floor((playedOut * 1000) / sampleRate);
|
||||
if (playedMs <= 0) return;
|
||||
this.port.postMessage({ type: 'progress', audioRef: ref, playedMs });
|
||||
this.port.postMessage({ type: 'progress', audioRef: ref, playedMs, consumedSamples: playedOut, contextRate: sampleRate });
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ import { AuthService } from '../services/auth/auth.service';
|
||||
import { VoiceStreamService } from '../services/voice-stream/voice-stream.service';
|
||||
import { ThemeService } from '../services/theme/theme.service';
|
||||
|
||||
/** Navigation outside the assistant: document management is admin-only per the contract. */
|
||||
/** Settings remain discoverable; document-management operations require admin authority. */
|
||||
const BASE_NAV_ITEMS: NavItem[] = [
|
||||
{ icon: 'M12 5v14M5 12h14', label: 'چت جدید', route: '/' },
|
||||
{ icon: 'M4 4v16h16M8 20V11M12.5 20V6M17 20V9', label: 'گزارشات', route: '/reports' },
|
||||
@@ -53,11 +53,8 @@ export class LayoutComponent {
|
||||
|
||||
/** The signed-in identity exactly as the server reported it. */
|
||||
readonly userName = computed(() => this.authService.currentUserSubject.value?.username ?? '');
|
||||
/** Hiding a nav entry is only cosmetic: every request is still authorized server-side. */
|
||||
readonly navItems = computed<NavItem[]>(() => {
|
||||
const isAdmin = this.authService.currentUserSubject.value?.role === 'admin';
|
||||
return isAdmin ? BASE_NAV_ITEMS : BASE_NAV_ITEMS.filter((item) => item.route !== '/settings');
|
||||
});
|
||||
/** The settings page handles role-specific controls; the server authorizes each operation. */
|
||||
readonly navItems = signal<NavItem[]>(BASE_NAV_ITEMS);
|
||||
|
||||
onProfile(): void {
|
||||
this.sidebarOpen.set(false);
|
||||
|
||||
@@ -244,6 +244,47 @@
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
|
||||
/* ---------- footnote row under the chat input: disclaimer + provider pill ---------- */
|
||||
.composer-footnote {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 0.75rem;
|
||||
padding: 0.4rem 0.75rem 0;
|
||||
max-width: 800px;
|
||||
margin-inline: auto;
|
||||
}
|
||||
|
||||
/* Fallback state (provider list failed to load, no pill to show): the footnote
|
||||
stacks as centered lines under the input instead of a squeezed side row. */
|
||||
.composer-footnote:has(.provider-picker.is-fallback) {
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
text-align: center;
|
||||
gap: 0.25rem;
|
||||
}
|
||||
|
||||
.composer-footnote:has(.provider-picker.is-fallback) .composer-disclaimer {
|
||||
flex: none;
|
||||
}
|
||||
|
||||
.composer-footnote:has(.provider-picker.is-fallback) app-voice-provider-picker {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.composer-disclaimer {
|
||||
margin: 0;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
font-size: 0.72rem;
|
||||
line-height: 1.8;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.composer-footnote app-voice-provider-picker {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
/* ---------- jump to latest ---------- */
|
||||
.jump-to-latest {
|
||||
position: absolute;
|
||||
|
||||
@@ -61,6 +61,12 @@
|
||||
(fileSelected)="onFileSelected($event)"
|
||||
(voiceToggled)="onVoiceToggled($event)"
|
||||
/>
|
||||
|
||||
<!-- footnote row under the input: disclaimer + selected provider pill -->
|
||||
<div class="composer-footnote" dir="rtl">
|
||||
<p class="composer-disclaimer">دستیار هوش مصنوعی ممکن است اشتباه کند؛ لطفاً پاسخها را بازبینی کنید.</p>
|
||||
<app-voice-provider-picker />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
@@ -17,6 +17,7 @@ import { Subscription } from 'rxjs';
|
||||
import { AiChatInputComponent } from '../../shared/ui/ai-chat-input/ai-chat-input.component';
|
||||
import { VoiceStreamPanelComponent } from '../../shared/ui/voice-stream-panel/voice-stream-panel.component';
|
||||
import { VoiceTranscriptComponent } from '../../shared/ui/voice-transcript/voice-transcript.component';
|
||||
import { VoiceProviderPickerComponent } from '../../shared/ui/voice-provider-picker/voice-provider-picker.component';
|
||||
import { VoiceStreamService } from '../../services/voice-stream/voice-stream.service';
|
||||
import { ThemeService } from '../../services/theme/theme.service';
|
||||
|
||||
@@ -41,7 +42,12 @@ const STICK_TO_BOTTOM_PX = 80;
|
||||
@Component({
|
||||
selector: 'app-home',
|
||||
standalone: true,
|
||||
imports: [AiChatInputComponent, VoiceStreamPanelComponent, VoiceTranscriptComponent],
|
||||
imports: [
|
||||
AiChatInputComponent,
|
||||
VoiceStreamPanelComponent,
|
||||
VoiceTranscriptComponent,
|
||||
VoiceProviderPickerComponent,
|
||||
],
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
templateUrl: './home.page.html',
|
||||
styleUrl: './home.page.css',
|
||||
|
||||
@@ -484,7 +484,8 @@
|
||||
.documents-table th,
|
||||
.documents-table td {
|
||||
padding: 0.6rem 0.75rem;
|
||||
text-align: right;
|
||||
/* Every column — labels and row content alike — is centred in the RTL table. */
|
||||
text-align: center;
|
||||
vertical-align: top;
|
||||
border-bottom: 1px solid var(--color-card-border);
|
||||
/* Fixed layout fits the card; wrap long tokens so a cell never widens the table. */
|
||||
@@ -509,6 +510,7 @@
|
||||
*/
|
||||
.documents-actions {
|
||||
align-items: flex-start;
|
||||
justify-content: center;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
|
||||
@@ -556,7 +556,7 @@
|
||||
<td class="px-3 py-2.5 align-top">
|
||||
@if (doc.status === 'ready' && !isReviewNeeded(doc) && isAdmin()) {
|
||||
@if (togglingDocId() === doc.id) {
|
||||
<div class="flex items-center gap-1.5 text-xs text-[var(--text-muted)]">
|
||||
<div class="flex items-center justify-center gap-1.5 text-xs text-[var(--text-muted)]">
|
||||
<svg
|
||||
class="w-3 h-3 animate-spin"
|
||||
viewBox="0 0 24 24"
|
||||
|
||||
@@ -166,6 +166,26 @@ describe('SettingsPage — document filters', () => {
|
||||
}
|
||||
});
|
||||
|
||||
it('centres the documents table headers and row cells', () => {
|
||||
// Regression: headers and cells both inherited the `text-align: right` of the
|
||||
// RTL table, leaving the whole table visually skewed to one side.
|
||||
const fixture = TestBed.createComponent(SettingsPage);
|
||||
fixture.detectChanges();
|
||||
const el = fixture.nativeElement as HTMLElement;
|
||||
|
||||
const headers = Array.from(el.querySelectorAll('.documents-table thead th'));
|
||||
expect(headers.length).toBe(6);
|
||||
for (const header of headers) {
|
||||
expect(getComputedStyle(header).textAlign).toBe('center');
|
||||
}
|
||||
|
||||
const cells = Array.from(el.querySelectorAll('.documents-table tbody td'));
|
||||
expect(cells.length).toBe(6);
|
||||
for (const cell of cells) {
|
||||
expect(getComputedStyle(cell).textAlign).toBe('center');
|
||||
}
|
||||
});
|
||||
|
||||
it('confirms before removing: the bin button opens a modal, cancel keeps the doc, confirm shows the MVP notice', () => {
|
||||
const fixture = TestBed.createComponent(SettingsPage);
|
||||
fixture.detectChanges();
|
||||
|
||||
@@ -120,6 +120,7 @@ describe('DocumentsService (backend handoff contract)', () => {
|
||||
|
||||
const req = httpMock.expectOne('/api/v1/documents/doc-1/retry');
|
||||
expect(req.request.method).toBe('POST');
|
||||
expect(req.request.serializeBody()).toBeNull();
|
||||
expect(req.request.headers.get('Idempotency-Key')).toBe('key-retry-1');
|
||||
req.flush({ job_id: 'job-1', status: 'queued' }, { status: 202, statusText: 'Accepted' });
|
||||
});
|
||||
|
||||
@@ -152,7 +152,7 @@ export class DocumentsService {
|
||||
): Observable<RetryResult> {
|
||||
return this.http.postRaw<RetryResult>(
|
||||
`${API}/documents/${encodeURIComponent(documentId)}/retry`,
|
||||
{},
|
||||
null,
|
||||
{ headers: this.idempotencyHeaders(idempotencyKey), skipToast: true },
|
||||
);
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ import { describe, it, expect, vi } from 'vitest';
|
||||
* (the class reads `sampleRate` at call time, not at module-eval time).
|
||||
*/
|
||||
interface Proc {
|
||||
out: Array<{ type: string; audioRef?: string; playedMs?: number }>;
|
||||
out: Array<{ type: string; audioRef?: string; playedMs?: number; consumedSamples?: number; discardedSamples?: number; contextRate?: number }>;
|
||||
port: { onmessage: (e: { data: unknown }) => void };
|
||||
count: number;
|
||||
capacity: number;
|
||||
@@ -20,10 +20,10 @@ interface Proc {
|
||||
}
|
||||
|
||||
class FakeAudioWorkletProcessor {
|
||||
out: Array<{ type: string; audioRef?: string; playedMs?: number }> = [];
|
||||
out: Array<{ type: string; audioRef?: string; playedMs?: number; consumedSamples?: number; discardedSamples?: number; contextRate?: number }> = [];
|
||||
port: {
|
||||
onmessage: ((e: { data: unknown }) => void) | null;
|
||||
postMessage: (m: { type: string; audioRef?: string; playedMs?: number }) => void;
|
||||
postMessage: (m: { type: string; audioRef?: string; playedMs?: number; consumedSamples?: number; discardedSamples?: number; contextRate?: number }) => void;
|
||||
};
|
||||
constructor() {
|
||||
this.port = { onmessage: null, postMessage: (m) => this.out.push(m) };
|
||||
@@ -150,6 +150,22 @@ describe('pcm-playback.worklet', () => {
|
||||
expect(peakSource).toBeLessThan(proc.sourceCapacity);
|
||||
});
|
||||
|
||||
it.each([24000, 44100, 48000])('reports actual consumed samples at %i Hz without crediting a discarded tail', async (rate) => {
|
||||
const proc = await loadPlaybackProcessor(rate);
|
||||
push(proc, frame(0, 4800), 'aud-counted');
|
||||
render(proc, 128);
|
||||
clear(proc);
|
||||
const reports = proc.out.filter((m) => m.type === 'progress');
|
||||
expect(reports.length).toBeGreaterThan(0);
|
||||
const final = reports.at(-1)!;
|
||||
expect(final.contextRate).toBe(rate);
|
||||
expect(final.consumedSamples).toBe(128);
|
||||
expect(final.playedMs).toBe(Math.floor(128 * 1000 / rate));
|
||||
expect(final.consumedSamples!).toBeLessThan(4800 * rate / 24000);
|
||||
const discarded = proc.out.find((m) => m.type === 'discarded')!;
|
||||
expect(discarded.discardedSamples! + final.consumedSamples!).toBe(Math.round(4800 * rate / 24000));
|
||||
});
|
||||
|
||||
describe('exact consumed-sample progress', () => {
|
||||
it('plays the 364800-byte incident fully before generation ends at 24 kHz', async () => {
|
||||
const proc = await loadPlaybackProcessor(24000);
|
||||
@@ -182,7 +198,9 @@ describe('pcm-playback.worklet', () => {
|
||||
drain(proc);
|
||||
expect(proc.refPlayedOut.get('aud-1')).toBe((rate * 1001) / 1000);
|
||||
expect(playedFor(proc, 'aud-1')).toBe(1001);
|
||||
const values = proc.out.filter((m) => m.audioRef === 'aud-1').map((m) => m.playedMs ?? 0);
|
||||
const values = proc.out
|
||||
.filter((m) => m.type === 'progress' && m.audioRef === 'aud-1')
|
||||
.map((m) => m.playedMs ?? 0);
|
||||
expect(values).toEqual([...values].sort((a, b) => a - b));
|
||||
expect(values.every((ms) => ms <= 1001)).toBe(true);
|
||||
});
|
||||
@@ -325,6 +343,19 @@ describe('pcm-playback.worklet', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('attributes discarded samples separately when two references share the queue', async () => {
|
||||
const proc = await loadPlaybackProcessor(24000);
|
||||
push(proc, frame(0, 3000), 'aud-a');
|
||||
push(proc, frame(3000, 3000), 'aud-b');
|
||||
render(proc, 128);
|
||||
clear(proc);
|
||||
const discarded = proc.out.filter((m) => m.type === 'discarded');
|
||||
expect(discarded.find((m) => m.audioRef === 'aud-a')?.discardedSamples).toBe(2872);
|
||||
expect(discarded.find((m) => m.audioRef === 'aud-b')?.discardedSamples).toBe(3000);
|
||||
expect(proc.refPlayedOut.get('aud-a')).toBe(128);
|
||||
expect(proc.refPlayedOut.get('aud-b') ?? 0).toBe(0);
|
||||
});
|
||||
|
||||
describe('interruption and clear', () => {
|
||||
it('clears the queue and reports only the source actually consumed', async () => {
|
||||
const proc = await loadPlaybackProcessor(24000);
|
||||
|
||||
@@ -25,6 +25,10 @@ export class VoiceApiError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
export type VoiceProvider = 'openai' | 'local_s2s' | 'gemini';
|
||||
export interface VoiceProviderOption { id: VoiceProvider; label: string; can_start: boolean; reason: string | null; }
|
||||
export interface VoiceProvidersResponse { default_provider: VoiceProvider; connection_checked: boolean; providers: VoiceProviderOption[]; }
|
||||
|
||||
export interface MeResponse {
|
||||
user: { id: string; username: string; role: string; organization_id: string };
|
||||
csrf_token: string;
|
||||
@@ -55,6 +59,7 @@ export interface ConversationResponse {
|
||||
}
|
||||
|
||||
export interface VoiceSessionResponse {
|
||||
provider?: VoiceProvider;
|
||||
session_id: string;
|
||||
conversation_id: string;
|
||||
status: string;
|
||||
@@ -84,8 +89,12 @@ export class VoiceApiService {
|
||||
}
|
||||
|
||||
/** F01: capabilities (the UI must check `voice` before offering a call). */
|
||||
configuration(): Promise<ConfigurationResponse> {
|
||||
return this.send(this.http.get<ConfigurationResponse>(this.url('/configuration'), this.readOptions()));
|
||||
configuration(provider?: VoiceProvider): Promise<ConfigurationResponse> {
|
||||
return this.send(this.http.get<ConfigurationResponse>(this.url('/configuration') + (provider ? '?provider=' + encodeURIComponent(provider) : ''), this.readOptions()));
|
||||
}
|
||||
|
||||
providers(): Promise<VoiceProvidersResponse> {
|
||||
return this.send(this.http.get<VoiceProvidersResponse>(this.url('/voice/sessions/providers'), this.readOptions()));
|
||||
}
|
||||
|
||||
/** C01: only `mode: "voice"` exists in the MVP. `clientRequestId` makes replays return the same conversation. */
|
||||
@@ -104,11 +113,12 @@ export class VoiceApiService {
|
||||
csrf: string,
|
||||
conversationId: string,
|
||||
clientRequestId: string,
|
||||
provider?: VoiceProvider,
|
||||
): Promise<VoiceSessionResponse> {
|
||||
return this.send(
|
||||
this.http.post<VoiceSessionResponse>(
|
||||
this.url('/voice/sessions'),
|
||||
{ conversation_id: conversationId, client_request_id: clientRequestId },
|
||||
{ conversation_id: conversationId, client_request_id: clientRequestId, ...(provider ? { provider } : {}) },
|
||||
this.writeOptions(csrf),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Injectable, NgZone, inject } from '@angular/core';
|
||||
import { Injectable, NgZone, inject, isDevMode } from '@angular/core';
|
||||
import { MicrophoneError, MicrophoneService } from '../microphone/microphone.service';
|
||||
import { VOICE_STREAM_CONFIG } from './voice-stream.types';
|
||||
|
||||
@@ -6,7 +6,7 @@ export interface VoiceEngineHandlers {
|
||||
/** One PCM16 frame (config.inputSampleRate, config.frameMs). Runs outside Angular's zone. */
|
||||
onFrame(pcm: ArrayBuffer, rms: number): void;
|
||||
/** The playback buffer ran dry (or `flushPlayback()` found it empty). */
|
||||
onPlaybackIdle(): void;
|
||||
onPlaybackIdle(audioRef?: string | null): void;
|
||||
/** The microphone track ended unexpectedly. */
|
||||
onMicEnded(): void;
|
||||
/**
|
||||
@@ -87,6 +87,16 @@ export class VoiceAudioEngine {
|
||||
// differs. Never assume the requested rate (SKILLS.md §3.2).
|
||||
const ctx = new AudioContext({ latencyHint: 'interactive', sampleRate: cfg.outputSampleRate });
|
||||
this.ctx = ctx;
|
||||
const startedAt = performance.now();
|
||||
let captureFrames = 0;
|
||||
let lastCaptureTrace = startedAt;
|
||||
ctx.onstatechange = () => {
|
||||
if (isDevMode()) console.info('Voice audio context state', {
|
||||
state: ctx.state, contextRate: ctx.sampleRate,
|
||||
elapsedMs: Math.floor(performance.now() - startedAt),
|
||||
contextMs: Math.floor(ctx.currentTime * 1000),
|
||||
});
|
||||
};
|
||||
|
||||
// Explicitly reject an unusable context rate: a 0/NaN/non-finite rate cannot resample
|
||||
// and must fail safely instead of silently producing no playback.
|
||||
@@ -111,6 +121,16 @@ export class VoiceAudioEngine {
|
||||
},
|
||||
});
|
||||
this.capture.port.onmessage = (event: MessageEvent<{ pcm: ArrayBuffer; rms: number }>) => {
|
||||
captureFrames++;
|
||||
const now = performance.now();
|
||||
if (isDevMode() && now - lastCaptureTrace >= 1000) {
|
||||
lastCaptureTrace = now;
|
||||
console.info('Voice capture clock', {
|
||||
captureFrames, state: ctx.state,
|
||||
elapsedMs: Math.floor(now - startedAt),
|
||||
contextMs: Math.floor(ctx.currentTime * 1000),
|
||||
});
|
||||
}
|
||||
this.inputRms = event.data.rms;
|
||||
handlers.onFrame(event.data.pcm, event.data.rms);
|
||||
};
|
||||
@@ -127,22 +147,32 @@ export class VoiceAudioEngine {
|
||||
outputChannelCount: [1],
|
||||
});
|
||||
this.playback.port.onmessage = (
|
||||
event: MessageEvent<{ type: string; audioRef?: string; playedMs?: number }>,
|
||||
event: MessageEvent<{ type: string; audioRef?: string; playedMs?: number; consumedSamples?: number; discardedSamples?: number; contextRate?: number }>,
|
||||
) => {
|
||||
switch (event.data?.type) {
|
||||
case 'idle':
|
||||
handlers.onPlaybackIdle();
|
||||
handlers.onPlaybackIdle(event.data.audioRef);
|
||||
break;
|
||||
case 'progress':
|
||||
if (isDevMode()) console.info('Voice worklet consumption', { audioRef: event.data.audioRef, consumedSamples: event.data.consumedSamples, contextRate: event.data.contextRate });
|
||||
if (event.data.audioRef) {
|
||||
handlers.onPlaybackProgress(event.data.audioRef, event.data.playedMs ?? 0);
|
||||
}
|
||||
break;
|
||||
case 'discarded':
|
||||
if (isDevMode()) console.info('Voice worklet discarded samples', { audioRef: event.data.audioRef, discardedSamples: event.data.discardedSamples, contextRate: event.data.contextRate });
|
||||
break;
|
||||
case 'overflow':
|
||||
handlers.onPlaybackOverflow();
|
||||
break;
|
||||
}
|
||||
};
|
||||
this.playback.onprocessorerror = () => {
|
||||
console.error('Voice playback processor failed', { state: ctx.state });
|
||||
};
|
||||
this.capture.onprocessorerror = () => {
|
||||
console.error('Voice capture processor failed', { state: ctx.state });
|
||||
};
|
||||
this.analyser = ctx.createAnalyser();
|
||||
this.analyser.fftSize = 1024;
|
||||
this.analyser.smoothingTimeConstant = 0.6;
|
||||
@@ -185,8 +215,8 @@ export class VoiceAudioEngine {
|
||||
}
|
||||
|
||||
/** End of turn: play the remaining audio, then report idle. */
|
||||
flushPlayback(): void {
|
||||
this.playback?.port.postMessage({ type: 'flush' });
|
||||
flushPlayback(audioRef?: string | null): void {
|
||||
this.playback?.port.postMessage({ type: 'flush', audioRef });
|
||||
}
|
||||
|
||||
// ---- mic / meters ----------------------------------------------------------
|
||||
@@ -215,8 +245,14 @@ export class VoiceAudioEngine {
|
||||
// ---- cleanup ---------------------------------------------------------------
|
||||
|
||||
stop(): void {
|
||||
if (this.capture) this.capture.port.onmessage = null;
|
||||
if (this.playback) this.playback.port.onmessage = null;
|
||||
if (this.capture) {
|
||||
this.capture.port.onmessage = null;
|
||||
this.capture.onprocessorerror = null;
|
||||
}
|
||||
if (this.playback) {
|
||||
this.playback.port.onmessage = null;
|
||||
this.playback.onprocessorerror = null;
|
||||
}
|
||||
|
||||
this.source?.disconnect();
|
||||
this.capture?.disconnect();
|
||||
|
||||
@@ -40,14 +40,20 @@ describe('voice-event.validator', () => {
|
||||
expect(
|
||||
parseVoiceServerEvent(JSON.stringify({ ...ANSWER_LIMITED, reason: 'output_length_limit' })),
|
||||
).toBeNull();
|
||||
expect(parseVoiceServerEvent(JSON.stringify({ ...ANSWER_LIMITED, reason: 'token_limit' }))).toBeNull();
|
||||
expect(parseVoiceServerEvent(JSON.stringify({ type: 'answer_limited', turn_ref: 't1' }))).toBeNull();
|
||||
expect(
|
||||
parseVoiceServerEvent(JSON.stringify({ ...ANSWER_LIMITED, reason: 'token_limit' })),
|
||||
).toBeNull();
|
||||
expect(
|
||||
parseVoiceServerEvent(JSON.stringify({ type: 'answer_limited', turn_ref: 't1' })),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it('rejects answer_limited without a valid turn_ref', () => {
|
||||
expect(parseVoiceServerEvent(JSON.stringify({ ...ANSWER_LIMITED, turn_ref: '' }))).toBeNull();
|
||||
expect(parseVoiceServerEvent(JSON.stringify({ ...ANSWER_LIMITED, turn_ref: 7 }))).toBeNull();
|
||||
expect(parseVoiceServerEvent('{"type":"answer_limited","reason":"output_token_limit"}')).toBeNull();
|
||||
expect(
|
||||
parseVoiceServerEvent('{"type":"answer_limited","reason":"output_token_limit"}'),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it('only advertises the contract reason and statuses', () => {
|
||||
@@ -58,12 +64,24 @@ describe('voice-event.validator', () => {
|
||||
|
||||
describe('transcript frames', () => {
|
||||
it('accepts a limited assistant transcript', () => {
|
||||
const frame = { type: 'transcript', turn_ref: 't1', role: 'assistant', text: 'پاسخ', status: 'limited' };
|
||||
const frame = {
|
||||
type: 'transcript',
|
||||
turn_ref: 't1',
|
||||
role: 'assistant',
|
||||
text: 'پاسخ',
|
||||
status: 'limited',
|
||||
};
|
||||
expect(parseVoiceServerEvent(JSON.stringify(frame))).toEqual(frame);
|
||||
});
|
||||
|
||||
it('rejects a limited USER transcript (limited is assistant-only)', () => {
|
||||
const frame = { type: 'transcript', turn_ref: 't1', role: 'user', text: 'ادامه بده', status: 'limited' };
|
||||
const frame = {
|
||||
type: 'transcript',
|
||||
turn_ref: 't1',
|
||||
role: 'user',
|
||||
text: 'ادامه بده',
|
||||
status: 'limited',
|
||||
};
|
||||
expect(parseVoiceServerEvent(JSON.stringify(frame))).toBeNull();
|
||||
});
|
||||
|
||||
@@ -80,12 +98,25 @@ describe('voice-event.validator', () => {
|
||||
const base = { type: 'transcript', turn_ref: 't1', role: 'assistant', text: 'متن' };
|
||||
expect(parseVoiceServerEvent(JSON.stringify({ ...base, status: 'capped' }))).toBeNull();
|
||||
expect(parseVoiceServerEvent(JSON.stringify({ ...base, status: 5 }))).toBeNull();
|
||||
expect(parseVoiceServerEvent(JSON.stringify({ ...base, status: 'limited', text: 3 }))).toBeNull();
|
||||
expect(parseVoiceServerEvent(JSON.stringify({ ...base, status: 'limited', role: 'system' }))).toBeNull();
|
||||
expect(parseVoiceServerEvent(JSON.stringify({ ...base, status: 'limited', turn_ref: '' }))).toBeNull();
|
||||
expect(
|
||||
parseVoiceServerEvent(JSON.stringify({ ...base, status: 'limited', text: 3 })),
|
||||
).toBeNull();
|
||||
expect(
|
||||
parseVoiceServerEvent(JSON.stringify({ ...base, status: 'limited', role: 'system' })),
|
||||
).toBeNull();
|
||||
expect(
|
||||
parseVoiceServerEvent(JSON.stringify({ ...base, status: 'limited', turn_ref: '' })),
|
||||
).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
it('accepts bounded audio_ended sent_bytes and rejects malformed counters', () => {
|
||||
const frame = { type: 'audio_ended', audio_ref: 'aud-1', turn_ref: 'turn-1', sent_bytes: 9600 };
|
||||
expect(parseVoiceServerEvent(JSON.stringify(frame))).toEqual(frame);
|
||||
for (const sent_bytes of [-1, 1.5, '9600', Number.MAX_SAFE_INTEGER + 1]) {
|
||||
expect(parseVoiceServerEvent(JSON.stringify({ ...frame, sent_bytes }))).toBeNull();
|
||||
}
|
||||
});
|
||||
describe('existing events keep passing (older backends)', () => {
|
||||
it('accepts every known event type with a valid payload', () => {
|
||||
const frames: VoiceServerEvent[] = [
|
||||
@@ -131,9 +162,7 @@ describe('voice-event.validator', () => {
|
||||
});
|
||||
|
||||
it('defaults a missing error retryable flag to false instead of dropping the frame', () => {
|
||||
const parsed = parseVoiceServerEvent(
|
||||
'{"type":"error","error":{"code":"X","message":"y"}}',
|
||||
);
|
||||
const parsed = parseVoiceServerEvent('{"type":"error","error":{"code":"X","message":"y"}}');
|
||||
expect(parsed).toEqual({
|
||||
type: 'error',
|
||||
error: { code: 'X', message: 'y', retryable: false },
|
||||
@@ -145,7 +174,11 @@ describe('voice-event.validator', () => {
|
||||
it('drops unknown event types instead of forwarding them', () => {
|
||||
expect(parseVoiceServerEvent('{"type":"response.create"}')).toBeNull();
|
||||
expect(parseVoiceServerEvent('{"type":"continue"}')).toBeNull();
|
||||
expect(parseVoiceServerEvent('{"type":"answer_limited2","turn_ref":"t1","reason":"output_token_limit"}')).toBeNull();
|
||||
expect(
|
||||
parseVoiceServerEvent(
|
||||
'{"type":"answer_limited2","turn_ref":"t1","reason":"output_token_limit"}',
|
||||
),
|
||||
).toBeNull();
|
||||
expect(parseVoiceServerEvent('{"type":42}')).toBeNull();
|
||||
});
|
||||
|
||||
@@ -160,13 +193,19 @@ describe('voice-event.validator', () => {
|
||||
it('drops frames with a broken audio/session/interruption payload', () => {
|
||||
expect(parseVoiceServerEvent('{"type":"audio_started"}')).toBeNull();
|
||||
expect(parseVoiceServerEvent('{"type":"audio_started","audio_ref":""}')).toBeNull();
|
||||
expect(parseVoiceServerEvent('{"type":"turn_interrupted","turn_ref":"t1","cancelled_tool_call_ids":[1]}')).toBeNull();
|
||||
expect(
|
||||
parseVoiceServerEvent(
|
||||
'{"type":"turn_interrupted","turn_ref":"t1","cancelled_tool_call_ids":[1]}',
|
||||
),
|
||||
).toBeNull();
|
||||
expect(
|
||||
parseVoiceServerEvent(
|
||||
'{"type":"session_ready","session_id":"s","input_audio":{"encoding":"pcm_s16le","sample_rate":24000,"channels":1}}',
|
||||
),
|
||||
).toBeNull();
|
||||
expect(parseVoiceServerEvent('{"type":"sources","turn_ref":"t1","sources":"none"}')).toBeNull();
|
||||
expect(
|
||||
parseVoiceServerEvent('{"type":"sources","turn_ref":"t1","sources":"none"}'),
|
||||
).toBeNull();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -120,7 +120,10 @@ function isVoiceServerEvent(value: unknown): value is VoiceServerEvent {
|
||||
case 'audio_ended':
|
||||
return (
|
||||
isApplicationReference(value['audio_ref']) &&
|
||||
(value['turn_ref'] === undefined || isApplicationReference(value['turn_ref']))
|
||||
(value['turn_ref'] === undefined || isApplicationReference(value['turn_ref'])) &&
|
||||
(value['type'] !== 'audio_ended' ||
|
||||
value['sent_bytes'] === undefined ||
|
||||
(Number.isSafeInteger(value['sent_bytes']) && (value['sent_bytes'] as number) >= 0))
|
||||
);
|
||||
|
||||
case 'turn_interrupted':
|
||||
|
||||
@@ -10,7 +10,11 @@ import { VoiceStreamService } from './voice-stream.service';
|
||||
import { VOICE_TRANSPORT_FACTORY, VoiceTransport, VoiceTransportHandlers } from './voice-transport';
|
||||
import { PlaybackProgressMessage, VoiceServerEvent } from './voice-stream.types';
|
||||
|
||||
const ME = { user: { id: 'u1', username: 'admin', role: 'admin', organization_id: 'o1' }, csrf_token: 'csrf-1', expires_at: 'later' };
|
||||
const ME = {
|
||||
user: { id: 'u1', username: 'admin', role: 'admin', organization_id: 'o1' },
|
||||
csrf_token: 'csrf-1',
|
||||
expires_at: 'later',
|
||||
};
|
||||
const CONFIG = {
|
||||
revision: 1,
|
||||
assistant_name: 'دستیار',
|
||||
@@ -34,7 +38,8 @@ const READY_EVENT: VoiceServerEvent = {
|
||||
};
|
||||
|
||||
const OVERFLOW_MESSAGE = 'حجم صدای در حال پخش از محدودهٔ مجاز گذشت و گفتگو بهطور ایمن پایان یافت.';
|
||||
const SEND_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));
|
||||
@@ -51,6 +56,7 @@ type TransportMock = Omit<VoiceTransport, 'connect' | 'sendAudio' | 'sendControl
|
||||
describe('VoiceStreamService (backend handoff contract)', () => {
|
||||
let service: VoiceStreamService;
|
||||
let api: {
|
||||
providers: ReturnType<typeof vi.fn>;
|
||||
me: ReturnType<typeof vi.fn>;
|
||||
configuration: ReturnType<typeof vi.fn>;
|
||||
createConversation: ReturnType<typeof vi.fn>;
|
||||
@@ -78,6 +84,10 @@ describe('VoiceStreamService (backend handoff contract)', () => {
|
||||
engineClear = vi.fn();
|
||||
|
||||
api = {
|
||||
providers: vi.fn().mockResolvedValue({ default_provider: 'openai', connection_checked: false, providers: [
|
||||
{ id: 'openai', label: 'OpenAI', can_start: true, reason: null },
|
||||
{ id: 'local_s2s', label: 'سیستم جدید', can_start: true, reason: null },
|
||||
] }),
|
||||
me: vi.fn().mockResolvedValue(ME),
|
||||
configuration: vi.fn().mockResolvedValue(CONFIG),
|
||||
createConversation: vi.fn().mockResolvedValue(CONVERSATION),
|
||||
@@ -96,7 +106,9 @@ describe('VoiceStreamService (backend handoff contract)', () => {
|
||||
return Promise.resolve();
|
||||
}),
|
||||
sendAudio: vi.fn(),
|
||||
sendControl: vi.fn().mockImplementation((message: PlaybackProgressMessage) => controls.push(message)),
|
||||
sendControl: vi
|
||||
.fn()
|
||||
.mockImplementation((message: PlaybackProgressMessage) => controls.push(message)),
|
||||
close: vi.fn(),
|
||||
};
|
||||
|
||||
@@ -138,7 +150,9 @@ describe('VoiceStreamService (backend handoff contract)', () => {
|
||||
}
|
||||
|
||||
function firstEndedError(): Promise<string | undefined> {
|
||||
return new Promise((resolve) => service.sessionEnded$.pipe(first()).subscribe((end) => resolve(end.error)));
|
||||
return new Promise((resolve) =>
|
||||
service.sessionEnded$.pipe(first()).subscribe((end) => resolve(end.error)),
|
||||
);
|
||||
}
|
||||
|
||||
it('creates conversation then voice session with two separate client request ids', async () => {
|
||||
@@ -166,7 +180,11 @@ describe('VoiceStreamService (backend handoff contract)', () => {
|
||||
output_audio: { encoding: 'pcm_s16le', sample_rate: 24000, channels: 1 },
|
||||
});
|
||||
const result = await started;
|
||||
expect(result).toEqual({ ok: false, reason: 'connect', message: 'فرمت صدای سرور با برنامه سازگار نیست.' });
|
||||
expect(result).toEqual({
|
||||
ok: false,
|
||||
reason: 'connect',
|
||||
message: 'فرمت صدای سرور با برنامه سازگار نیست.',
|
||||
});
|
||||
});
|
||||
|
||||
it('reconciles an ambiguous V01 through V03 instead of creating a second session', async () => {
|
||||
@@ -226,7 +244,13 @@ describe('VoiceStreamService (backend handoff contract)', () => {
|
||||
it('reports the final real played progress when the turn is interrupted', async () => {
|
||||
await startConnected();
|
||||
|
||||
transportHandlers?.onEvent({ type: 'transcript', turn_ref: 'turn-1', role: 'assistant', text: 'پاسخ', status: 'partial' });
|
||||
transportHandlers?.onEvent({
|
||||
type: 'transcript',
|
||||
turn_ref: 'turn-1',
|
||||
role: 'assistant',
|
||||
text: 'پاسخ',
|
||||
status: 'partial',
|
||||
});
|
||||
transportHandlers?.onEvent({ type: 'audio_started', audio_ref: 'aud-2' });
|
||||
engineHandlers?.onPlaybackProgress('aud-2', 300);
|
||||
controls = [];
|
||||
@@ -235,9 +259,7 @@ describe('VoiceStreamService (backend handoff contract)', () => {
|
||||
// The worklet answers `clear` with its final cumulative report for the ref.
|
||||
engineHandlers?.onPlaybackProgress('aud-2', 780);
|
||||
|
||||
expect(controls).toEqual([
|
||||
{ type: 'playback_progress', audio_ref: 'aud-2', played_ms: 780 },
|
||||
]);
|
||||
expect(controls).toEqual([{ type: 'playback_progress', audio_ref: 'aud-2', played_ms: 780 }]);
|
||||
expect(service.messages().find((m) => m.id === 'turn-1:assistant')?.interrupted).toBe(true);
|
||||
});
|
||||
|
||||
@@ -314,6 +336,56 @@ describe('VoiceStreamService (backend handoff contract)', () => {
|
||||
expect(api.closeVoiceSession).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('keeps listening closed across an open-audio underrun and ignores a stale seal', async () => {
|
||||
await startConnected();
|
||||
transportHandlers?.onEvent({ type: 'audio_started', audio_ref: 'aud-1', turn_ref: 'turn-1' });
|
||||
transportHandlers?.onAudio(new ArrayBuffer(9600));
|
||||
engineHandlers?.onPlaybackIdle('aud-1');
|
||||
|
||||
vi.useFakeTimers();
|
||||
try {
|
||||
vi.advanceTimersByTime(2000);
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
expect(service.state()).toBe('SPEAKING');
|
||||
|
||||
transportHandlers?.onEvent({
|
||||
type: 'transcript',
|
||||
turn_ref: 'turn-1',
|
||||
role: 'assistant',
|
||||
text: 'complete text',
|
||||
status: 'completed',
|
||||
});
|
||||
engineHandlers?.onPlaybackIdle('aud-1');
|
||||
transportHandlers?.onEvent({ type: 'audio_ended', audio_ref: 'stale', turn_ref: 'turn-0' });
|
||||
expect(service.state()).toBe('SPEAKING');
|
||||
expect(engineFlush).not.toHaveBeenCalled();
|
||||
|
||||
transportHandlers?.onEvent({ type: 'audio_ended', audio_ref: 'aud-1', turn_ref: 'turn-1' });
|
||||
engineHandlers?.onPlaybackIdle('stale');
|
||||
expect(service.state()).toBe('SPEAKING');
|
||||
engineHandlers?.onPlaybackIdle('aud-1');
|
||||
expect(service.state()).toBe('LISTENING');
|
||||
});
|
||||
it('does not reset received bytes on a duplicate audio start', async () => {
|
||||
await startConnected();
|
||||
transportHandlers?.onEvent({ type: 'audio_started', audio_ref: 'aud-1', turn_ref: 'turn-1' });
|
||||
transportHandlers?.onAudio(new ArrayBuffer(9600));
|
||||
transportHandlers?.onEvent({ type: 'audio_started', audio_ref: 'aud-1', turn_ref: 'turn-1' });
|
||||
const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
|
||||
try {
|
||||
transportHandlers?.onEvent({
|
||||
type: 'audio_ended',
|
||||
audio_ref: 'aud-1',
|
||||
turn_ref: 'turn-1',
|
||||
sent_bytes: 9600,
|
||||
});
|
||||
expect(warn).not.toHaveBeenCalledWith('Voice audio delivery mismatch', expect.anything());
|
||||
} finally {
|
||||
warn.mockRestore();
|
||||
}
|
||||
});
|
||||
it('drains on audio_ended so the ref reaches its true final progress (not solely on transcript)', async () => {
|
||||
await startConnected();
|
||||
transportHandlers?.onEvent({ type: 'audio_started', audio_ref: 'aud-1' });
|
||||
@@ -335,7 +407,7 @@ describe('VoiceStreamService (backend handoff contract)', () => {
|
||||
transportHandlers?.onEvent({ type: 'audio_ended', audio_ref: 'aud-1' });
|
||||
expect(engineFlush).toHaveBeenCalledTimes(1);
|
||||
|
||||
// Once generation is done, a late/second completed transcript re-flushes idempotently.
|
||||
// A duplicate final transcript does not flush the sealed reference again.
|
||||
transportHandlers?.onEvent({
|
||||
type: 'transcript',
|
||||
turn_ref: 'turn-1',
|
||||
@@ -343,7 +415,7 @@ describe('VoiceStreamService (backend handoff contract)', () => {
|
||||
text: '…',
|
||||
status: 'completed',
|
||||
});
|
||||
expect(engineFlush).toHaveBeenCalledTimes(2);
|
||||
expect(engineFlush).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('requires a fresh conversation after CONTEXT_REVOKED and drops the old attempt', async () => {
|
||||
@@ -355,7 +427,9 @@ describe('VoiceStreamService (backend handoff contract)', () => {
|
||||
error: { code: 'CONTEXT_REVOKED', message: 'context revoked', retryable: false },
|
||||
});
|
||||
|
||||
expect(await ended).toBe('محتوای دانش تغییر کرده و مکالمهٔ قبلی دیگر معتبر نیست. گفتگوی جدیدی شروع کنید.');
|
||||
expect(await ended).toBe(
|
||||
'محتوای دانش تغییر کرده و مکالمهٔ قبلی دیگر معتبر نیست. گفتگوی جدیدی شروع کنید.',
|
||||
);
|
||||
expect(sessionStorage.getItem('voice_creation_attempt')).toBeNull();
|
||||
expect(service.connection()).toBe('disconnected');
|
||||
});
|
||||
@@ -398,9 +472,27 @@ describe('VoiceStreamService (backend handoff contract)', () => {
|
||||
it('marks partial then completed transcripts final', async () => {
|
||||
await startConnected();
|
||||
|
||||
transportHandlers?.onEvent({ type: 'transcript', turn_ref: 't1', role: 'assistant', text: 'سلام', status: 'partial' });
|
||||
transportHandlers?.onEvent({ type: 'transcript', turn_ref: 't1', role: 'assistant', text: 'سلام و خوب', status: 'partial' });
|
||||
transportHandlers?.onEvent({ type: 'transcript', turn_ref: 't1', role: 'assistant', text: 'سلام و خوب', status: 'completed' });
|
||||
transportHandlers?.onEvent({
|
||||
type: 'transcript',
|
||||
turn_ref: 't1',
|
||||
role: 'assistant',
|
||||
text: 'سلام',
|
||||
status: 'partial',
|
||||
});
|
||||
transportHandlers?.onEvent({
|
||||
type: 'transcript',
|
||||
turn_ref: 't1',
|
||||
role: 'assistant',
|
||||
text: 'سلام و خوب',
|
||||
status: 'partial',
|
||||
});
|
||||
transportHandlers?.onEvent({
|
||||
type: 'transcript',
|
||||
turn_ref: 't1',
|
||||
role: 'assistant',
|
||||
text: 'سلام و خوب',
|
||||
status: 'completed',
|
||||
});
|
||||
|
||||
const assistant = service.messages().find((m) => m.id === 't1:assistant');
|
||||
expect(assistant?.text).toBe('سلام و خوب');
|
||||
@@ -411,8 +503,20 @@ describe('VoiceStreamService (backend handoff contract)', () => {
|
||||
await startConnected();
|
||||
|
||||
// The server streams assistant partials before the user transcript for the same turn.
|
||||
transportHandlers?.onEvent({ type: 'transcript', turn_ref: 'turn-1', role: 'assistant', text: 'پاسخ فارسی', status: 'partial' });
|
||||
transportHandlers?.onEvent({ type: 'transcript', turn_ref: 'turn-1', role: 'user', text: 'سلام', status: 'completed' });
|
||||
transportHandlers?.onEvent({
|
||||
type: 'transcript',
|
||||
turn_ref: 'turn-1',
|
||||
role: 'assistant',
|
||||
text: 'پاسخ فارسی',
|
||||
status: 'partial',
|
||||
});
|
||||
transportHandlers?.onEvent({
|
||||
type: 'transcript',
|
||||
turn_ref: 'turn-1',
|
||||
role: 'user',
|
||||
text: 'سلام',
|
||||
status: 'completed',
|
||||
});
|
||||
|
||||
const list = service.messages();
|
||||
const userIndex = list.findIndex((m) => m.id === 'turn-1:user');
|
||||
@@ -424,11 +528,35 @@ describe('VoiceStreamService (backend handoff contract)', () => {
|
||||
it('keeps user→assistant order and stable turn order across turns', async () => {
|
||||
await startConnected();
|
||||
|
||||
transportHandlers?.onEvent({ type: 'transcript', turn_ref: 't1', role: 'user', text: 'سوال ۱', status: 'completed' });
|
||||
transportHandlers?.onEvent({ type: 'transcript', turn_ref: 't1', role: 'assistant', text: 'پاسخ ۱', status: 'completed' });
|
||||
transportHandlers?.onEvent({
|
||||
type: 'transcript',
|
||||
turn_ref: 't1',
|
||||
role: 'user',
|
||||
text: 'سوال ۱',
|
||||
status: 'completed',
|
||||
});
|
||||
transportHandlers?.onEvent({
|
||||
type: 'transcript',
|
||||
turn_ref: 't1',
|
||||
role: 'assistant',
|
||||
text: 'پاسخ ۱',
|
||||
status: 'completed',
|
||||
});
|
||||
// turn 2's assistant lands before its user transcript
|
||||
transportHandlers?.onEvent({ type: 'transcript', turn_ref: 't2', role: 'assistant', text: 'پاسخ ۲', status: 'partial' });
|
||||
transportHandlers?.onEvent({ type: 'transcript', turn_ref: 't2', role: 'user', text: 'سوال ۲', status: 'completed' });
|
||||
transportHandlers?.onEvent({
|
||||
type: 'transcript',
|
||||
turn_ref: 't2',
|
||||
role: 'assistant',
|
||||
text: 'پاسخ ۲',
|
||||
status: 'partial',
|
||||
});
|
||||
transportHandlers?.onEvent({
|
||||
type: 'transcript',
|
||||
turn_ref: 't2',
|
||||
role: 'user',
|
||||
text: 'سوال ۲',
|
||||
status: 'completed',
|
||||
});
|
||||
|
||||
expect(service.messages().map((m) => m.id)).toEqual([
|
||||
't1:user',
|
||||
@@ -445,9 +573,17 @@ describe('VoiceStreamService (backend handoff contract)', () => {
|
||||
transportHandlers?.onEvent({
|
||||
type: 'sources',
|
||||
turn_ref: 't1',
|
||||
sources: [{ source_ref: 's1', document_id: 'd1', chunk_id: 'c1', title: 'سند', excerpt: 'بند' }],
|
||||
sources: [
|
||||
{ source_ref: 's1', document_id: 'd1', chunk_id: 'c1', title: 'سند', excerpt: 'بند' },
|
||||
],
|
||||
});
|
||||
transportHandlers?.onEvent({
|
||||
type: 'transcript',
|
||||
turn_ref: 't1',
|
||||
role: 'user',
|
||||
text: 'سلام',
|
||||
status: 'completed',
|
||||
});
|
||||
transportHandlers?.onEvent({ type: 'transcript', turn_ref: 't1', role: 'user', text: 'سلام', status: 'completed' });
|
||||
|
||||
expect(service.messages().map((m) => m.id)).toEqual(['t1:user', 't1:assistant']);
|
||||
});
|
||||
@@ -549,9 +685,27 @@ describe('VoiceStreamService (backend handoff contract)', () => {
|
||||
it('preserves repeated legitimate partial words (no content-based dedup)', async () => {
|
||||
await startConnected();
|
||||
|
||||
transportHandlers?.onEvent({ type: 'transcript', turn_ref: 't1', role: 'assistant', text: 'بله', status: 'partial' });
|
||||
transportHandlers?.onEvent({ type: 'transcript', turn_ref: 't1', role: 'assistant', text: ' بله', status: 'partial' });
|
||||
transportHandlers?.onEvent({ type: 'transcript', turn_ref: 't1', role: 'assistant', text: ' بله', status: 'partial' });
|
||||
transportHandlers?.onEvent({
|
||||
type: 'transcript',
|
||||
turn_ref: 't1',
|
||||
role: 'assistant',
|
||||
text: 'بله',
|
||||
status: 'partial',
|
||||
});
|
||||
transportHandlers?.onEvent({
|
||||
type: 'transcript',
|
||||
turn_ref: 't1',
|
||||
role: 'assistant',
|
||||
text: ' بله',
|
||||
status: 'partial',
|
||||
});
|
||||
transportHandlers?.onEvent({
|
||||
type: 'transcript',
|
||||
turn_ref: 't1',
|
||||
role: 'assistant',
|
||||
text: ' بله',
|
||||
status: 'partial',
|
||||
});
|
||||
|
||||
expect(service.messages()[0].text).toBe('بله بله بله');
|
||||
});
|
||||
@@ -701,7 +855,11 @@ describe('VoiceStreamService (backend handoff contract)', () => {
|
||||
});
|
||||
|
||||
const list = service.messages();
|
||||
expect(list.map((m) => m.id)).toEqual(['turn-1:user', 'turn-1:assistant', 'turn-2:assistant']);
|
||||
expect(list.map((m) => m.id)).toEqual([
|
||||
'turn-1:user',
|
||||
'turn-1:assistant',
|
||||
'turn-2:assistant',
|
||||
]);
|
||||
expect(list.find((m) => m.id === 'turn-1:user')?.text).toBe('سوال اول');
|
||||
expect(list.find((m) => m.id === 'turn-1:user')?.limited).toBeFalsy();
|
||||
expect(list.find((m) => m.id === 'turn-1:assistant')?.limited).toBe(true);
|
||||
@@ -710,7 +868,11 @@ describe('VoiceStreamService (backend handoff contract)', () => {
|
||||
|
||||
it('cannot let an old session marker contaminate a new session', async () => {
|
||||
await startConnected(); // session A
|
||||
transportHandlers?.onEvent({ type: 'answer_limited', turn_ref: 'shared-turn', reason: 'output_token_limit' });
|
||||
transportHandlers?.onEvent({
|
||||
type: 'answer_limited',
|
||||
turn_ref: 'shared-turn',
|
||||
reason: 'output_token_limit',
|
||||
});
|
||||
await service.close();
|
||||
|
||||
await startConnected(); // session B
|
||||
@@ -845,9 +1007,7 @@ describe('VoiceStreamService (backend handoff contract)', () => {
|
||||
// The worklet answers `clear` with its final cumulative report for the ref.
|
||||
engineHandlers?.onPlaybackProgress('aud-2', 780);
|
||||
|
||||
expect(controls).toEqual([
|
||||
{ type: 'playback_progress', audio_ref: 'aud-2', played_ms: 780 },
|
||||
]);
|
||||
expect(controls).toEqual([{ type: 'playback_progress', audio_ref: 'aud-2', played_ms: 780 }]);
|
||||
});
|
||||
|
||||
it('never auto-continues, fabricates a control message or recreates the session', async () => {
|
||||
@@ -912,4 +1072,49 @@ describe('VoiceStreamService (backend handoff contract)', () => {
|
||||
expect(service.state()).toBe('LISTENING'); // completed turns finish immediately
|
||||
});
|
||||
});
|
||||
it('pins the selected provider in each new creation attempt', async () => {
|
||||
await service.loadProviders();
|
||||
await startConnected();
|
||||
expect(api.createVoiceSession.mock.calls[0][3]).toBe('openai');
|
||||
api.pollVoiceSession.mockResolvedValue({ session_id: 'ses-1', status: 'closed' });
|
||||
expect(await service.selectProvider('local_s2s')).toBe(true);
|
||||
expect(service.isOpen()).toBe(false);
|
||||
await startConnected();
|
||||
expect(api.createVoiceSession.mock.calls[1][3]).toBe('local_s2s');
|
||||
expect(api.createVoiceSession.mock.calls[1][2]).not.toBe(api.createVoiceSession.mock.calls[0][2]);
|
||||
});
|
||||
|
||||
it('keeps provider and request ids when the previous close is unconfirmed', async () => {
|
||||
await service.loadProviders();
|
||||
await startConnected();
|
||||
const previous = JSON.parse(sessionStorage.getItem('voice_creation_attempt')!);
|
||||
api.pollVoiceSession.mockResolvedValue({ session_id: 'ses-1', status: 'connected' });
|
||||
expect(await service.selectProvider('local_s2s')).toBe(false);
|
||||
expect(service.selectedProvider()).toBe('openai');
|
||||
expect(JSON.parse(sessionStorage.getItem('voice_creation_attempt')!)).toEqual(previous);
|
||||
expect(service.providerChoiceError()).toBeTruthy();
|
||||
api.pollVoiceSession.mockResolvedValue({ session_id: 'ses-1', status: 'closed' });
|
||||
expect(await service.selectProvider('local_s2s')).toBe(true);
|
||||
await startConnected();
|
||||
expect(api.createVoiceSession.mock.calls[1][3]).toBe('local_s2s');
|
||||
expect(api.createVoiceSession.mock.calls[1][2]).not.toBe(previous.sessionRequestId);
|
||||
});
|
||||
|
||||
it('rejects unavailable choices without touching the current call', async () => {
|
||||
await service.loadProviders();
|
||||
await startConnected();
|
||||
expect(await service.selectProvider('gemini')).toBe(false);
|
||||
expect(service.isOpen()).toBe(true);
|
||||
expect(api.closeVoiceSession).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('uses legacy default admission when an older backend has no provider discovery', async () => {
|
||||
service.selectedProvider.set('openai');
|
||||
api.providers.mockRejectedValue(new VoiceApiError(404, 'NOT_FOUND', 'missing'));
|
||||
await service.loadProviders();
|
||||
expect(service.selectedProvider()).toBeNull();
|
||||
await startConnected();
|
||||
expect(api.createVoiceSession.mock.calls[0][3]).toBeUndefined();
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { Injectable, NgZone, computed, inject, signal } from '@angular/core';
|
||||
import { Injectable, NgZone, computed, inject, isDevMode, 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 { VoiceApiError, VoiceApiService, VoiceSessionResponse, VoiceProvider, VoiceProviderOption } from './voice-api.service';
|
||||
import { VoiceAudioEngine, VoiceEngineError } from './voice-audio-engine.service';
|
||||
import { VOICE_TRANSPORT_FACTORY, VoiceTransport } from './voice-transport';
|
||||
import {
|
||||
@@ -27,8 +27,7 @@ export type VoiceStartFailure =
|
||||
| 'overflow';
|
||||
|
||||
export type VoiceStartResult =
|
||||
| { ok: true }
|
||||
| { ok: false; reason: VoiceStartFailure; message: string };
|
||||
{ ok: true } | { ok: false; reason: VoiceStartFailure; message: string };
|
||||
|
||||
type TranscriptEvent = Extract<VoiceServerEvent, { type: 'transcript' }>;
|
||||
type SourcesEvent = Extract<VoiceServerEvent, { type: 'sources' }>;
|
||||
@@ -58,7 +57,8 @@ interface TeardownOptions {
|
||||
}
|
||||
|
||||
const MESSAGES = {
|
||||
unsupported: 'گفتگوی صوتی در این مرورگر پشتیبانی نمیشود (اتصال امن HTTPS و مرورگر جدید لازم است).',
|
||||
unsupported:
|
||||
'گفتگوی صوتی در این مرورگر پشتیبانی نمیشود (اتصال امن HTTPS و مرورگر جدید لازم است).',
|
||||
micDenied: 'دسترسی به میکروفون رد شد. اجازهی دسترسی را در تنظیمات مرورگر فعال کنید.',
|
||||
micUnavailable: 'میکروفونی پیدا نشد یا در حال استفادهی برنامهی دیگری است.',
|
||||
micLost: 'اتصال میکروفون قطع شد و گفتگو پایان یافت.',
|
||||
@@ -127,6 +127,10 @@ export class VoiceStreamService {
|
||||
private readonly createTransport = inject(VOICE_TRANSPORT_FACTORY);
|
||||
private readonly cues = inject(VoiceCueService);
|
||||
|
||||
readonly selectedProvider = signal<VoiceProvider | null>(null);
|
||||
readonly providerOptions = signal<VoiceProviderOption[]>([]);
|
||||
readonly providerChoiceError = signal('');
|
||||
readonly providerSwitching = signal(false);
|
||||
readonly state = signal<VoiceStreamState>('IDLE');
|
||||
readonly connection = signal<VoiceConnection>('disconnected');
|
||||
readonly messages = signal<VoiceMessage[]>([]);
|
||||
@@ -147,7 +151,8 @@ export class VoiceStreamService {
|
||||
private cleanupPromise: Promise<void> | null = null;
|
||||
private session = 0;
|
||||
private streaming = false;
|
||||
private turnEnded = false;
|
||||
private traceStarted = performance.now();
|
||||
private underrunStarted: number | null = null;
|
||||
private audioGenerationDone = false; // server finished sending this audio_ref's frames
|
||||
private interruptTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
private settleTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
@@ -164,6 +169,10 @@ export class VoiceStreamService {
|
||||
/** Latest cumulative played_ms actually consumed by the worklet, per server audio_ref. */
|
||||
private readonly playedMsByRef = new Map<string, number>();
|
||||
private currentAudioRef: string | null = null;
|
||||
private readonly seenAudioRefs = new Set<string>();
|
||||
private currentAudioTurnRef: string | null = null;
|
||||
private currentAudioReceivedBytes = 0;
|
||||
private currentAudioSentBytes: number | null = null;
|
||||
private progressWaiters: Array<() => void> = [];
|
||||
/** Turns whose answer the server marked limited (bounded; marker may precede its row). */
|
||||
private readonly limitedTurns = new Set<string>();
|
||||
@@ -172,6 +181,7 @@ export class VoiceStreamService {
|
||||
|
||||
constructor() {
|
||||
this.attempt = loadPersistedAttempt();
|
||||
this.selectedProvider.set(this.attempt?.provider ?? null);
|
||||
// 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.
|
||||
@@ -183,11 +193,65 @@ export class VoiceStreamService {
|
||||
|
||||
// ---- public API -----------------------------------------------------------
|
||||
|
||||
async loadProviders(): Promise<void> {
|
||||
try {
|
||||
const result = await this.api.providers();
|
||||
this.providerOptions.set(result.providers.filter(row => row.id !== 'gemini' || row.can_start || row.id === result.default_provider));
|
||||
this.providerChoiceError.set('');
|
||||
if (!this.isOpen() && !this.attempt && !this.selectedProvider()) {
|
||||
this.selectedProvider.set(result.default_provider);
|
||||
}
|
||||
} catch (err) {
|
||||
if (err instanceof VoiceApiError && err.status === 404 && !this.attempt && !this.isOpen()) {
|
||||
this.selectedProvider.set(null);
|
||||
}
|
||||
this.providerChoiceError.set('فهرست ارائهدهندگان دریافت نشد؛ انتخاب پیشفرض سرویس برقرار است.');
|
||||
}
|
||||
}
|
||||
|
||||
async selectProvider(provider: VoiceProvider): Promise<boolean> {
|
||||
if (this.providerSwitching()) return false;
|
||||
if (provider === this.selectedProvider()) return true;
|
||||
if (!this.providerOptions().some(row => row.id === provider && row.can_start)) return false;
|
||||
this.providerSwitching.set(true);
|
||||
this.providerChoiceError.set('');
|
||||
const previous = this.attempt;
|
||||
try {
|
||||
await this.close();
|
||||
// Changing provider must never discard an ambiguous reservation or reuse
|
||||
// its request ids with different arguments. Require a terminal server row.
|
||||
if (previous) {
|
||||
if (!previous.sessionId) throw new Error('Unresolved reservation');
|
||||
const me = await this.api.me();
|
||||
const status = await this.withTimeout(this.api.pollVoiceSession(me.csrf_token, previous.sessionId), CLOSE_WAIT_MS);
|
||||
if (!status || !['closed', 'failed'].includes(status.status)) throw new Error('Close not confirmed');
|
||||
}
|
||||
if (previous && this.attempt === previous) {
|
||||
this.attempt = null;
|
||||
clearPersistedAttempt();
|
||||
}
|
||||
this.selectedProvider.set(provider);
|
||||
return true;
|
||||
} catch {
|
||||
if (previous) { this.attempt = previous; persistAttempt(previous); }
|
||||
this.providerChoiceError.set('پایان تماس قبلی تأیید نشد؛ ارائهدهنده تغییر نکرد.');
|
||||
return false;
|
||||
} finally {
|
||||
this.providerSwitching.set(false);
|
||||
}
|
||||
}
|
||||
|
||||
async start(options: { title?: string } = {}): Promise<VoiceStartResult> {
|
||||
if (this.providerSwitching()) return this.failure('cancelled', '');
|
||||
if (this.attempt?.provider && this.selectedProvider() && this.attempt.provider !== this.selectedProvider()) {
|
||||
return this.failure('api', 'ابتدا وضعیت تماس قبلی را مشخص کنید.');
|
||||
}
|
||||
if (this.isOpen()) return this.failure('cancelled', '');
|
||||
if (!this.isSupported) return this.failure('unsupported', MESSAGES.unsupported);
|
||||
|
||||
const session = ++this.session;
|
||||
this.traceStarted = performance.now();
|
||||
this.underrunStarted = null;
|
||||
const stale = (): boolean => session !== this.session;
|
||||
|
||||
this.messages.set([]);
|
||||
@@ -202,22 +266,24 @@ export class VoiceStreamService {
|
||||
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();
|
||||
if (!this.attempt) this.attempt = newCreationAttempt(this.selectedProvider());
|
||||
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()),
|
||||
onPlaybackIdle: (audioRef) => this.ngZone.run(() => this.onPlaybackIdle(audioRef)),
|
||||
onMicEnded: () => this.ngZone.run(() => this.failSession(MESSAGES.micLost, session)),
|
||||
onPlaybackProgress: (audioRef, playedMs) =>
|
||||
this.ngZone.run(() => this.onPlaybackProgress(audioRef, playedMs)),
|
||||
onPlaybackOverflow: () => this.ngZone.run(() => this.failSession(MESSAGES.overflow, session)),
|
||||
onPlaybackOverflow: () =>
|
||||
this.ngZone.run(() => this.failSession(MESSAGES.overflow, session)),
|
||||
});
|
||||
} catch (err) {
|
||||
return this.abortStart(session, this.mapEngineError(err));
|
||||
@@ -233,7 +299,7 @@ export class VoiceStreamService {
|
||||
const me = await this.api.me();
|
||||
if (stale()) return this.failure('cancelled', '');
|
||||
|
||||
const configuration = await this.api.configuration();
|
||||
const configuration = await this.api.configuration(this.attempt?.provider);
|
||||
if (stale()) return this.failure('cancelled', '');
|
||||
if (!configuration.capabilities.voice) {
|
||||
return this.abortStart(session, { reason: 'unavailable', message: MESSAGES.voiceDisabled });
|
||||
@@ -271,12 +337,17 @@ export class VoiceStreamService {
|
||||
onEvent: (event) => this.ngZone.run(() => this.onServerEvent(event, session)),
|
||||
onAudio: (chunk) => this.onServerAudio(chunk, session),
|
||||
onClose: (info) =>
|
||||
this.ngZone.run(() => this.failSession(MESSAGES.disconnected, session, this.describeSocketClose(info))),
|
||||
this.ngZone.run(() =>
|
||||
this.failSession(MESSAGES.disconnected, session, this.describeSocketClose(info)),
|
||||
),
|
||||
onOverflow: (which) =>
|
||||
this.ngZone.run(() =>
|
||||
// Playback queue overflow and capture/send overflow are different faults with
|
||||
// different causes; give each its own message instead of one shared string.
|
||||
this.failSession(which === 'send' ? MESSAGES.sendOverflow : MESSAGES.overflow, session),
|
||||
this.failSession(
|
||||
which === 'send' ? MESSAGES.sendOverflow : MESSAGES.overflow,
|
||||
session,
|
||||
),
|
||||
),
|
||||
}),
|
||||
);
|
||||
@@ -361,7 +432,10 @@ export class VoiceStreamService {
|
||||
if (this.isOpen() || this.attempt !== attempt) return true;
|
||||
let sessionId = attempt.sessionId;
|
||||
if (!sessionId) {
|
||||
const existing = await this.api.getVoiceSessionByRequest(me.csrf_token, attempt.sessionRequestId);
|
||||
const existing = await this.api.getVoiceSessionByRequest(
|
||||
me.csrf_token,
|
||||
attempt.sessionRequestId,
|
||||
);
|
||||
sessionId = existing?.session_id ?? null;
|
||||
}
|
||||
if (this.isOpen() || this.attempt !== attempt) return true;
|
||||
@@ -418,7 +492,15 @@ export class VoiceStreamService {
|
||||
|
||||
private onServerAudio(chunk: ArrayBuffer, session: number): void {
|
||||
if (session !== this.session || !this.streaming) return;
|
||||
if (this.underrunStarted !== null) {
|
||||
this.audioTrace('underrun_resumed', { gapMs: Math.floor(performance.now() - this.underrunStarted) });
|
||||
this.underrunStarted = null;
|
||||
}
|
||||
const chunkBytes = chunk.byteLength; // transfer to the worklet detaches this buffer
|
||||
this.currentAudioReceivedBytes += chunkBytes;
|
||||
this.audioTrace('audio_received', { chunkBytes });
|
||||
this.engine.enqueuePlayback(chunk, this.currentAudioRef);
|
||||
this.audioTrace('audio_enqueued', { chunkBytes });
|
||||
this.clearSettleTimer();
|
||||
|
||||
if (this.state() !== 'SPEAKING') {
|
||||
@@ -438,6 +520,7 @@ export class VoiceStreamService {
|
||||
if (playedMs <= 0) return;
|
||||
// Keep the latest cumulative value per ref; the final report is sent from here too.
|
||||
this.playedMsByRef.set(audioRef, playedMs);
|
||||
if (audioRef === this.currentAudioRef) this.audioTrace('playback_progress', { playedMs });
|
||||
this.sendPlaybackProgress(audioRef, playedMs);
|
||||
this.resolveProgressWaiters();
|
||||
}
|
||||
@@ -461,6 +544,7 @@ export class VoiceStreamService {
|
||||
const transport = this.transport;
|
||||
if (!ref || !transport || this.connection() !== 'connected') return Promise.resolve();
|
||||
|
||||
this.audioTrace('clear_session_end');
|
||||
this.engine.clearPlayback(); // worklet answers with its final cumulative report
|
||||
return new Promise<void>((resolve) => {
|
||||
const done = (): void => {
|
||||
@@ -511,8 +595,18 @@ export class VoiceStreamService {
|
||||
break;
|
||||
|
||||
case 'audio_started':
|
||||
if (
|
||||
this.seenAudioRefs.has(event.audio_ref) ||
|
||||
(event.turn_ref && this.interruptedTurns.has(event.turn_ref))
|
||||
)
|
||||
break;
|
||||
this.seenAudioRefs.add(event.audio_ref);
|
||||
this.currentAudioRef = event.audio_ref;
|
||||
this.currentAudioTurnRef = event.turn_ref ?? null;
|
||||
this.currentAudioReceivedBytes = 0;
|
||||
this.currentAudioSentBytes = null;
|
||||
this.audioGenerationDone = false; // frames for this ref are now streaming in
|
||||
this.clearSettleTimer();
|
||||
break;
|
||||
|
||||
case 'audio_ended':
|
||||
@@ -520,8 +614,24 @@ export class VoiceStreamService {
|
||||
// the ref's FINAL playback progress reaches its true duration (no phantom outstanding
|
||||
// sample the backend would read as a stall). This drives the drain on generation
|
||||
// completion, cooperating with — not depending solely on — the completed transcript.
|
||||
if (
|
||||
event.audio_ref !== this.currentAudioRef ||
|
||||
this.audioGenerationDone ||
|
||||
(event.turn_ref &&
|
||||
this.currentAudioTurnRef &&
|
||||
event.turn_ref !== this.currentAudioTurnRef)
|
||||
)
|
||||
break;
|
||||
this.audioGenerationDone = true;
|
||||
this.engine.flushPlayback();
|
||||
this.currentAudioSentBytes = event.sent_bytes ?? null;
|
||||
if (event.sent_bytes !== undefined && event.sent_bytes !== this.currentAudioReceivedBytes) {
|
||||
console.warn('Voice audio delivery mismatch', {
|
||||
sentBytes: event.sent_bytes,
|
||||
receivedBytes: this.currentAudioReceivedBytes,
|
||||
});
|
||||
}
|
||||
this.audioTrace('flush_audio_ended');
|
||||
this.engine.flushPlayback(this.currentAudioRef);
|
||||
break;
|
||||
|
||||
case 'turn_interrupted':
|
||||
@@ -556,13 +666,7 @@ export class VoiceStreamService {
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.status === 'completed') {
|
||||
// All text for this turn is out. Drain the queue only once generation has ended
|
||||
// (audio_ended); otherwise the tail would be finalized while audio is still streamed.
|
||||
this.turnEnded = true;
|
||||
if (this.audioGenerationDone) this.engine.flushPlayback();
|
||||
return;
|
||||
}
|
||||
if (event.status === 'completed') return;
|
||||
|
||||
if (event.status === 'limited') {
|
||||
// An answer state, not a playback or session event: the limited transcript does
|
||||
@@ -596,7 +700,7 @@ export class VoiceStreamService {
|
||||
* bounded settle the drain path uses.
|
||||
*/
|
||||
private scheduleLimitedSettle(): void {
|
||||
if (this.state() !== 'PROCESSING' || this.settleTimer) return;
|
||||
if (this.state() !== 'PROCESSING' || this.currentAudioRef || this.settleTimer) return;
|
||||
this.settleTimer = setTimeout(() => {
|
||||
this.settleTimer = null;
|
||||
if (this.state() === 'PROCESSING') this.finishTurn();
|
||||
@@ -605,8 +709,18 @@ export class VoiceStreamService {
|
||||
|
||||
/** Server-side barge-in: the user spoke over the assistant. */
|
||||
private onTurnInterrupted(turnRef: string): void {
|
||||
if (this.currentAudioTurnRef && this.currentAudioTurnRef !== turnRef) {
|
||||
this.markInterrupted(turnRef);
|
||||
return;
|
||||
}
|
||||
this.audioTrace('clear_interruption');
|
||||
this.underrunStarted = null;
|
||||
this.engine.clearPlayback(); // the worklet posts the final progress for the active ref
|
||||
this.turnEnded = false;
|
||||
if (!this.currentAudioTurnRef || this.currentAudioTurnRef === turnRef) {
|
||||
this.currentAudioRef = null;
|
||||
this.currentAudioTurnRef = null;
|
||||
this.audioGenerationDone = false;
|
||||
}
|
||||
this.clearSettleTimer();
|
||||
this.markInterrupted(turnRef);
|
||||
|
||||
@@ -645,8 +759,9 @@ export class VoiceStreamService {
|
||||
}
|
||||
|
||||
// The session survives a retryable failure (e.g. SEARCH_TIMEOUT): drop the failed turn and keep listening.
|
||||
this.audioTrace('clear_retryable_error');
|
||||
this.underrunStarted = null;
|
||||
this.engine.clearPlayback();
|
||||
this.turnEnded = false;
|
||||
this.clearSettleTimer();
|
||||
this.finalizeAssistant();
|
||||
if (this.state() === 'PROCESSING' || this.state() === 'SPEAKING') this.state.set('LISTENING');
|
||||
@@ -655,29 +770,49 @@ export class VoiceStreamService {
|
||||
|
||||
// ---- end of an assistant turn ----------------------------------------------
|
||||
|
||||
private onPlaybackIdle(): void {
|
||||
const state = this.state();
|
||||
if (state !== 'SPEAKING' && state !== 'PROCESSING') return;
|
||||
/** Numeric browser timeline; backend timestamps use a different clock. */
|
||||
private audioTrace(stage: string, counters: Record<string, number> = {}): void {
|
||||
if (!isDevMode()) return;
|
||||
console.info('Voice audio trace', {
|
||||
stage,
|
||||
sessionId: this.remote?.sessionId,
|
||||
turnRef: this.currentAudioTurnRef,
|
||||
audioRef: this.currentAudioRef,
|
||||
elapsedMs: Math.floor(performance.now() - this.traceStarted),
|
||||
receivedBytes: this.currentAudioReceivedBytes,
|
||||
sentBytes: this.currentAudioSentBytes,
|
||||
...counters,
|
||||
});
|
||||
}
|
||||
|
||||
if (this.turnEnded) {
|
||||
private onPlaybackIdle(audioRef?: string | null): void {
|
||||
if (audioRef && audioRef !== this.currentAudioRef) return;
|
||||
if (this.state() !== 'SPEAKING' && this.state() !== 'PROCESSING') return;
|
||||
if (!this.audioGenerationDone && this.currentAudioRef && this.underrunStarted === null) {
|
||||
this.underrunStarted = performance.now();
|
||||
this.audioTrace('underrun_started');
|
||||
}
|
||||
// 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.audioTrace('audio_drained', { playedMs });
|
||||
this.finishTurn();
|
||||
} else if (state === 'SPEAKING') {
|
||||
// The buffer drained but no `completed` transcript arrived (yet). If no more audio comes, the turn is over.
|
||||
this.clearSettleTimer();
|
||||
this.settleTimer = setTimeout(() => {
|
||||
this.settleTimer = null;
|
||||
if (this.state() === 'SPEAKING') this.finishTurn();
|
||||
}, this.config.settleMs);
|
||||
}
|
||||
}
|
||||
|
||||
private finishTurn(): void {
|
||||
this.turnEnded = false;
|
||||
this.underrunStarted = null;
|
||||
this.audioGenerationDone = false;
|
||||
this.currentAudioRef = null;
|
||||
this.currentAudioTurnRef = null;
|
||||
this.clearSettleTimer();
|
||||
this.finalizeAssistant();
|
||||
this.state.set('LISTENING');
|
||||
}
|
||||
|
||||
// ---- transcript ------------------------------------------------------------
|
||||
|
||||
private upsertTranscript(event: TranscriptEvent): void {
|
||||
@@ -688,9 +823,7 @@ export class VoiceStreamService {
|
||||
// `limited` is valid only for assistant rows (the transport rejects the rest), and a
|
||||
// user transcript of a limited turn stays a plain user row.
|
||||
const attachLimited =
|
||||
event.role === 'assistant' &&
|
||||
!interrupted &&
|
||||
(limited || this.isLimitedTurn(event.turn_ref));
|
||||
event.role === 'assistant' && !interrupted && (limited || this.isLimitedTurn(event.turn_ref));
|
||||
|
||||
// A turn the server already interrupted cannot be restored by late assistant text
|
||||
// (partial, completed or limited). The interrupted transcript itself still passes:
|
||||
@@ -802,7 +935,9 @@ export class VoiceStreamService {
|
||||
// not seen yet sorts after all existing ones.
|
||||
const turns: string[] = [];
|
||||
for (const m of list) if (!turns.includes(m.turnRef)) turns.push(m.turnRef);
|
||||
const turnRank = turns.includes(message.turnRef) ? turns.indexOf(message.turnRef) : turns.length;
|
||||
const turnRank = turns.includes(message.turnRef)
|
||||
? turns.indexOf(message.turnRef)
|
||||
: turns.length;
|
||||
|
||||
for (let i = 0; i < list.length; i++) {
|
||||
const existingTurn = turns.indexOf(list[i].turnRef);
|
||||
@@ -925,7 +1060,8 @@ export class VoiceStreamService {
|
||||
// Start-only failure: release immediately (unmount-style) and best-effort V04 for any
|
||||
// reservation that was made. Keep the attempt when it was an ambiguous reserve so the
|
||||
// next start() reconciles it with the same ids instead of duplicating.
|
||||
if (session === this.session) void this.teardown({ ordered: false, closeRemote: true, keepAttempt });
|
||||
if (session === this.session)
|
||||
void this.teardown({ ordered: false, closeRemote: true, keepAttempt });
|
||||
return this.failure(failure.reason, failure.message);
|
||||
}
|
||||
|
||||
@@ -993,7 +1129,10 @@ export class VoiceStreamService {
|
||||
// 2) supersede the session, then V04 /close (bounded), then 3) release.
|
||||
invalidate();
|
||||
if (options.closeRemote !== false && remote) {
|
||||
await this.withTimeout(this.api.closeVoiceSession(remote.csrf, remote.sessionId), CLOSE_WAIT_MS);
|
||||
await this.withTimeout(
|
||||
this.api.closeVoiceSession(remote.csrf, remote.sessionId),
|
||||
CLOSE_WAIT_MS,
|
||||
);
|
||||
}
|
||||
} catch {
|
||||
/* the session may already be closed/expired (e.g. 409 LIVE_SESSION_UNUSABLE) */
|
||||
@@ -1071,7 +1210,6 @@ export class VoiceStreamService {
|
||||
};
|
||||
|
||||
private resetTurnFlags(): void {
|
||||
this.turnEnded = false;
|
||||
this.audioGenerationDone = false;
|
||||
}
|
||||
|
||||
@@ -1123,7 +1261,7 @@ export class VoiceStreamService {
|
||||
* 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();
|
||||
const attempt = this.attempt ?? newCreationAttempt(this.selectedProvider());
|
||||
this.attempt = attempt;
|
||||
|
||||
let activeCsrf = csrf;
|
||||
@@ -1157,6 +1295,7 @@ export class VoiceStreamService {
|
||||
activeCsrf,
|
||||
attempt.conversationId!,
|
||||
attempt.sessionRequestId,
|
||||
attempt.provider,
|
||||
);
|
||||
} catch (err) {
|
||||
const refreshed = await this.refreshAfterCsrfFailure(err);
|
||||
@@ -1173,6 +1312,7 @@ export class VoiceStreamService {
|
||||
activeCsrf,
|
||||
attempt.conversationId!,
|
||||
attempt.sessionRequestId,
|
||||
attempt.provider,
|
||||
);
|
||||
}
|
||||
} else if (err instanceof VoiceApiError && err.code === 'LIVE_SESSION_BUSY') {
|
||||
@@ -1224,7 +1364,8 @@ export class VoiceStreamService {
|
||||
|
||||
private mapEngineError(err: unknown): { reason: VoiceStartFailure; message: string } {
|
||||
if (err instanceof MicrophoneError) {
|
||||
if (err.code === 'unsupported') return { reason: 'unsupported', message: MESSAGES.unsupported };
|
||||
if (err.code === 'unsupported')
|
||||
return { reason: 'unsupported', message: MESSAGES.unsupported };
|
||||
return {
|
||||
reason: 'mic',
|
||||
message: err.code === 'denied' ? MESSAGES.micDenied : MESSAGES.micUnavailable,
|
||||
@@ -1276,12 +1417,14 @@ interface VoiceCreationAttempt {
|
||||
conversationId: string | null;
|
||||
sessionId: string | null;
|
||||
streamPath: string | null;
|
||||
provider?: VoiceProvider;
|
||||
}
|
||||
|
||||
const ATTEMPT_STORAGE_KEY = 'voice_creation_attempt';
|
||||
|
||||
function newCreationAttempt(): VoiceCreationAttempt {
|
||||
function newCreationAttempt(provider: VoiceProvider | null = null): VoiceCreationAttempt {
|
||||
return {
|
||||
...(provider ? { provider } : {}),
|
||||
conversationRequestId: uuid(),
|
||||
sessionRequestId: uuid(),
|
||||
conversationId: null,
|
||||
|
||||
@@ -72,7 +72,7 @@ export type VoiceServerEvent =
|
||||
}
|
||||
| { type: 'sources'; turn_ref: string; tool_call_id?: string; sources: VoiceSource[] }
|
||||
| { type: 'audio_started'; audio_ref: string; turn_ref?: string }
|
||||
| { type: 'audio_ended'; audio_ref: string; turn_ref?: string }
|
||||
| { type: 'audio_ended'; audio_ref: string; turn_ref?: string; sent_bytes?: number }
|
||||
| { type: 'turn_interrupted'; turn_ref: string; cancelled_tool_call_ids?: string[] }
|
||||
/**
|
||||
* The assistant answer hit the backend's output-token limit. This is an ANSWER
|
||||
@@ -153,7 +153,7 @@ export interface VoiceStreamConfig {
|
||||
outputSampleRate: number;
|
||||
frameMs: number;
|
||||
connectTimeoutMs: number;
|
||||
/** After playback drains without a `completed` assistant transcript, wait this long, then return to LISTENING. */
|
||||
/** Fallback only for a limited response with no audio reference. */
|
||||
settleMs: number;
|
||||
/** Folder (relative to <base href>) holding the two *.worklet.js files, served from the UI origin. */
|
||||
workletBasePath: string;
|
||||
|
||||
@@ -0,0 +1,262 @@
|
||||
:host {
|
||||
display: block;
|
||||
flex: none;
|
||||
}
|
||||
|
||||
.provider-picker {
|
||||
position: relative;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-end;
|
||||
gap: 0.375rem;
|
||||
}
|
||||
|
||||
.provider-pill-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
/* Fallback state (provider list failed to load, no pill): the error is the only
|
||||
content, so center it instead of pinning it to the end. */
|
||||
.provider-picker.is-fallback {
|
||||
align-items: center;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
/* ---------- Pill trigger (like Claude's "Sonnet 5.5 Medium" badge) ---------- */
|
||||
.provider-pill {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.375rem;
|
||||
padding: 0.2rem 0.6rem;
|
||||
border: 1px solid var(--surface-border);
|
||||
border-radius: 0.5rem;
|
||||
background: var(--sidebar-hover);
|
||||
color: var(--text-secondary);
|
||||
font-family: inherit;
|
||||
font-size: 0.75rem;
|
||||
font-weight: 500;
|
||||
line-height: 1.6;
|
||||
white-space: nowrap;
|
||||
cursor: pointer;
|
||||
transition: background 0.15s ease, color 0.15s ease, border-color 0.15s ease;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.provider-pill:hover:not(:disabled) {
|
||||
background: var(--surface-border);
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.provider-pill.is-open {
|
||||
border-color: var(--color-primary);
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.provider-pill:disabled {
|
||||
opacity: 0.6;
|
||||
cursor: wait;
|
||||
}
|
||||
|
||||
.provider-pill:focus-visible {
|
||||
outline: 2px solid var(--color-primary);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.provider-pill-dot {
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
border-radius: 50%;
|
||||
background: var(--color-success, #22c55e);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.provider-pill-dot.is-busy {
|
||||
background: var(--color-warning, #f59e0b);
|
||||
animation: pillPulse 1s ease-in-out infinite;
|
||||
}
|
||||
|
||||
@keyframes pillPulse {
|
||||
0%,
|
||||
100% {
|
||||
opacity: 1;
|
||||
}
|
||||
50% {
|
||||
opacity: 0.35;
|
||||
}
|
||||
}
|
||||
|
||||
.provider-pill-chevron {
|
||||
opacity: 0.6;
|
||||
transition: transform 0.18s ease;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.provider-pill.is-open .provider-pill-chevron {
|
||||
transform: rotate(180deg);
|
||||
}
|
||||
|
||||
/* ---------- Popover menu (opens upward, like the Claude screenshot) ---------- */
|
||||
.provider-menu {
|
||||
position: absolute;
|
||||
bottom: calc(100% + 0.5rem);
|
||||
inset-inline-end: 0;
|
||||
min-width: 290px;
|
||||
max-width: min(340px, calc(100vw - 2rem));
|
||||
background: var(--surface-bg);
|
||||
border: 1px solid var(--surface-border);
|
||||
border-radius: 0.875rem;
|
||||
box-shadow: 0 12px 40px rgba(0, 0, 0, 0.16), 0 2px 8px rgba(0, 0, 0, 0.08);
|
||||
overflow: hidden;
|
||||
z-index: 60;
|
||||
animation: providerMenuIn 0.16s ease;
|
||||
}
|
||||
|
||||
@keyframes providerMenuIn {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(6px) scale(0.98);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateY(0) scale(1);
|
||||
}
|
||||
}
|
||||
|
||||
.provider-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 0.75rem;
|
||||
width: 100%;
|
||||
padding: 0.7rem 1rem;
|
||||
border: none;
|
||||
border-bottom: 1px solid var(--surface-border);
|
||||
background: transparent;
|
||||
color: var(--text-primary);
|
||||
font-family: inherit;
|
||||
text-align: start;
|
||||
cursor: pointer;
|
||||
transition: background 0.13s ease;
|
||||
}
|
||||
|
||||
.provider-item:last-of-type {
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
.provider-item:hover:not(:disabled),
|
||||
.provider-item:focus-visible:not(:disabled) {
|
||||
background: var(--sidebar-hover);
|
||||
}
|
||||
|
||||
.provider-item:focus-visible {
|
||||
outline: 2px solid var(--color-primary);
|
||||
outline-offset: -2px;
|
||||
}
|
||||
|
||||
.provider-item:disabled {
|
||||
opacity: 0.55;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.provider-item-text {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.1rem;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.provider-item-name {
|
||||
font-size: 0.875rem;
|
||||
font-weight: 600;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.provider-item-reason {
|
||||
font-size: 0.75rem;
|
||||
color: var(--muted);
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
.provider-item-check {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
color: var(--color-primary);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.provider-menu-foot {
|
||||
padding: 0.55rem 1rem;
|
||||
border-top: 1px solid var(--surface-border);
|
||||
background: var(--sidebar-hover);
|
||||
color: var(--muted);
|
||||
font-size: 0.72rem;
|
||||
line-height: 1.7;
|
||||
}
|
||||
|
||||
/* ---------- Inline error under the pill ---------- */
|
||||
.provider-error {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.375rem;
|
||||
max-width: 100%;
|
||||
padding: 0.2rem 0.55rem;
|
||||
border: 1px solid rgba(239, 68, 68, 0.4);
|
||||
border-radius: 0.5rem;
|
||||
background: rgba(239, 68, 68, 0.08);
|
||||
color: #dc2626;
|
||||
font-size: 0.72rem;
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
/* Fallback state (provider list failed to load, no pill): the error is the only
|
||||
content, so it stretches full-width and centers like a footnote line under
|
||||
the chat input instead of hugging the side. */
|
||||
.provider-picker.is-fallback .provider-error {
|
||||
display: flex;
|
||||
width: 100%;
|
||||
justify-content: center;
|
||||
text-align: center;
|
||||
border: none;
|
||||
background: transparent;
|
||||
color: var(--muted);
|
||||
padding-inline: 0.75rem;
|
||||
}
|
||||
|
||||
.provider-error-close {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
border: none;
|
||||
border-radius: 50%;
|
||||
background: transparent;
|
||||
color: inherit;
|
||||
cursor: pointer;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.provider-error-close:hover {
|
||||
background: rgba(239, 68, 68, 0.15);
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
.provider-menu {
|
||||
min-width: min(270px, calc(100vw - 2rem));
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.provider-pill,
|
||||
.provider-pill-chevron,
|
||||
.provider-menu,
|
||||
.provider-item {
|
||||
transition: none !important;
|
||||
animation: none !important;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
<div class="provider-picker" #container dir="rtl" [class.is-fallback]="!options().length">
|
||||
@if (options().length) {
|
||||
<!-- Pill trigger pinned to the end of the footnote row (bottom-right in LTR screenshots, bottom-left in RTL) -->
|
||||
<div class="provider-pill-row">
|
||||
<button
|
||||
#trigger
|
||||
type="button"
|
||||
class="provider-pill"
|
||||
[class.is-open]="isOpen()"
|
||||
[disabled]="switching()"
|
||||
[attr.aria-expanded]="isOpen()"
|
||||
aria-haspopup="menu"
|
||||
aria-controls="voice-provider-menu"
|
||||
[attr.aria-label]="'ارائهدهنده: ' + selectedLabel() + ' — برای تغییر کلیک کنید'"
|
||||
(click)="toggleMenu()"
|
||||
>
|
||||
<span class="provider-pill-dot" [class.is-busy]="switching()" aria-hidden="true"></span>
|
||||
<span class="provider-pill-label">{{ switching() ? 'در حال تغییر…' : selectedLabel() }}</span>
|
||||
<svg
|
||||
class="provider-pill-chevron"
|
||||
width="14"
|
||||
height="14"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
stroke-width="2"
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path d="m6 9 6 6 6-6" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
@if (isOpen()) {
|
||||
<div
|
||||
#menu
|
||||
id="voice-provider-menu"
|
||||
class="provider-menu"
|
||||
role="menu"
|
||||
aria-label="انتخاب ارائهدهندهٔ صدا"
|
||||
(keydown)="onMenuKeydown($event)"
|
||||
>
|
||||
@for (provider of options(); track provider.id) {
|
||||
<button
|
||||
type="button"
|
||||
class="provider-item"
|
||||
role="menuitemradio"
|
||||
[attr.aria-checked]="provider.id === selectedId()"
|
||||
[disabled]="!provider.can_start"
|
||||
[title]="!provider.can_start && provider.reason ? provider.reason : provider.label"
|
||||
(click)="choose(provider.id)"
|
||||
>
|
||||
<span class="provider-item-text">
|
||||
<span class="provider-item-name">{{ provider.label }}</span>
|
||||
@if (!provider.can_start) {
|
||||
<span class="provider-item-reason">{{ provider.reason || 'فعلاً در دسترس نیست' }}</span>
|
||||
} @else if (provider.id === selectedId()) {
|
||||
<span class="provider-item-reason">فعال برای گفتگوی بعدی</span>
|
||||
} @else {
|
||||
<span class="provider-item-reason">کلیک برای انتخاب</span>
|
||||
}
|
||||
</span>
|
||||
<span class="provider-item-check" aria-hidden="true">
|
||||
@if (provider.id === selectedId()) {
|
||||
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M20 6 9 17l-5-5" />
|
||||
</svg>
|
||||
}
|
||||
</span>
|
||||
</button>
|
||||
}
|
||||
|
||||
<div class="provider-menu-foot">
|
||||
@if (callOpen()) {
|
||||
<span>تغییر ارائهدهنده تماس فعلی را پایان میدهد.</span>
|
||||
} @else {
|
||||
<span>انتخاب شما برای گفتگوی بعدی استفاده میشود.</span>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
|
||||
<!-- Load/switch failures render here: inside the footnote row, under the chat input.
|
||||
Kept outside the options guard on purpose — this error fires exactly when the
|
||||
provider list failed to load (options empty), so gating on options would hide it. -->
|
||||
@if (choiceError(); as err) {
|
||||
<div class="provider-error" role="status">
|
||||
<span>{{ err }}</span>
|
||||
<button type="button" class="provider-error-close" aria-label="بستن پیام" (click)="dismissError()">
|
||||
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
|
||||
<line x1="18" x2="6" y1="6" y2="18" />
|
||||
<line x1="6" x2="18" y1="6" y2="18" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
@@ -0,0 +1,139 @@
|
||||
import {
|
||||
ChangeDetectionStrategy,
|
||||
Component,
|
||||
ElementRef,
|
||||
Injector,
|
||||
OnInit,
|
||||
afterNextRender,
|
||||
computed,
|
||||
effect,
|
||||
inject,
|
||||
signal,
|
||||
viewChild,
|
||||
} from '@angular/core';
|
||||
import { VoiceProvider } from '../../../services/voice-stream/voice-api.service';
|
||||
import { VoiceStreamService } from '../../../services/voice-stream/voice-stream.service';
|
||||
|
||||
/**
|
||||
* Claude-style provider picker that lives under the chat input.
|
||||
* A small pill shows the selected provider; clicking it opens a popover
|
||||
* menu with every provider option (checkmark on the active one).
|
||||
* All state lives in `VoiceStreamService` — this component only renders it.
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-voice-provider-picker',
|
||||
standalone: true,
|
||||
changeDetection: ChangeDetectionStrategy.OnPush,
|
||||
templateUrl: './voice-provider-picker.component.html',
|
||||
styleUrl: './voice-provider-picker.component.css',
|
||||
})
|
||||
export class VoiceProviderPickerComponent implements OnInit {
|
||||
private readonly injector = inject(Injector);
|
||||
private readonly voice = inject(VoiceStreamService);
|
||||
|
||||
readonly options = this.voice.providerOptions;
|
||||
readonly selectedId = this.voice.selectedProvider;
|
||||
readonly switching = this.voice.providerSwitching;
|
||||
readonly choiceError = this.voice.providerChoiceError;
|
||||
readonly callOpen = this.voice.isOpen;
|
||||
|
||||
readonly isOpen = signal(false);
|
||||
|
||||
readonly selectedOption = computed(() =>
|
||||
this.options().find((row) => row.id === this.selectedId()) ?? null,
|
||||
);
|
||||
|
||||
/** Pill text: backend label, or the legacy "service default" fallback. */
|
||||
readonly selectedLabel = computed(() => this.selectedOption()?.label ?? 'پیشفرض سرویس');
|
||||
|
||||
private readonly containerRef = viewChild<ElementRef<HTMLElement>>('container');
|
||||
private readonly menuRef = viewChild<ElementRef<HTMLDivElement>>('menu');
|
||||
private readonly triggerRef = viewChild<ElementRef<HTMLButtonElement>>('trigger');
|
||||
|
||||
constructor() {
|
||||
// Close on any pointer press outside the pill + menu, only while open.
|
||||
effect((onCleanup) => {
|
||||
if (!this.isOpen()) return;
|
||||
const onPointerDown = (event: PointerEvent): void => {
|
||||
const target = event.target as Node | null;
|
||||
if (target && this.containerRef()?.nativeElement.contains(target)) return;
|
||||
this.closeMenu();
|
||||
};
|
||||
document.addEventListener('pointerdown', onPointerDown);
|
||||
onCleanup(() => document.removeEventListener('pointerdown', onPointerDown));
|
||||
});
|
||||
}
|
||||
|
||||
ngOnInit(): void {
|
||||
void this.voice.loadProviders();
|
||||
}
|
||||
|
||||
toggleMenu(): void {
|
||||
if (this.switching()) return;
|
||||
const opening = !this.isOpen();
|
||||
this.isOpen.set(opening);
|
||||
if (opening) {
|
||||
afterNextRender(() => this.menuItems()[0]?.focus(), { injector: this.injector });
|
||||
}
|
||||
}
|
||||
|
||||
closeMenu(focusTrigger = false): void {
|
||||
if (!this.isOpen()) return;
|
||||
this.isOpen.set(false);
|
||||
if (focusTrigger) this.triggerRef()?.nativeElement.focus();
|
||||
}
|
||||
|
||||
async choose(provider: VoiceProvider): Promise<void> {
|
||||
if (provider === this.selectedId()) {
|
||||
this.closeMenu(true);
|
||||
return;
|
||||
}
|
||||
const ok = await this.voice.selectProvider(provider);
|
||||
// Keep the menu open on failure so the error stays visible next to it.
|
||||
if (ok) this.closeMenu(true);
|
||||
}
|
||||
|
||||
onMenuKeydown(event: KeyboardEvent): void {
|
||||
if (event.key === 'Escape') {
|
||||
event.preventDefault();
|
||||
this.closeMenu(true);
|
||||
return;
|
||||
}
|
||||
const items = this.menuItems();
|
||||
if (!items.length) return;
|
||||
const index = items.indexOf(document.activeElement as HTMLElement);
|
||||
let next = -1;
|
||||
switch (event.key) {
|
||||
case 'ArrowDown':
|
||||
next = (index + 1) % items.length;
|
||||
break;
|
||||
case 'ArrowUp':
|
||||
next = (index - 1 + items.length) % items.length;
|
||||
break;
|
||||
case 'Home':
|
||||
next = 0;
|
||||
break;
|
||||
case 'End':
|
||||
next = items.length - 1;
|
||||
break;
|
||||
case 'Tab':
|
||||
this.closeMenu();
|
||||
return;
|
||||
default:
|
||||
return;
|
||||
}
|
||||
event.preventDefault();
|
||||
items[next].focus();
|
||||
}
|
||||
|
||||
dismissError(): void {
|
||||
this.choiceError.set('');
|
||||
}
|
||||
|
||||
private menuItems(): HTMLElement[] {
|
||||
const menu = this.menuRef()?.nativeElement;
|
||||
return menu
|
||||
? Array.from(menu.querySelectorAll<HTMLElement>('[role="menuitemradio"]:not(:disabled)'))
|
||||
: [];
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user