Author SHA1 Message Date
amirhosein mazaheri 57e8346d51 build: allow external host access in dev server start script 2026-10-17 17:03:36 +03:30
PeymanHonarjoo 4dac437cc7 feat(voice): implement new pill-style provider picker
Replace the legacy select dropdown in the home page with a modern,
Claude-style provider picker component. This improves the user
experience and encapsulates provider loading and selection logic
within the new component.
2026-10-17 10:47:21 +03:30
PeymanHonarjoo dc23dbeb69 Merge branch 'backend/local-s2s' of http://git.raymandcti.com/p.honarjoo/faq_chatbot_frontend into backend/local-s2s 2026-10-17 09:54:45 +03:30
11linear11 a26c597d4f feat(voice): add session provider selection to the frontend
Pin provider choices to creation attempts, confirm session closure before switching and handle unavailable providers without fallback. Restore Settings navigation for non-admin users while preserving operation-level authorization.
2026-10-16 17:09:31 -04:00
amirhosein mazaheri 815191588c fix(documents): send empty body for ingestion retry 2026-10-14 13:55:14 +03:30
PeymanHonarjoo 102ce9b909 Merge branch 'feat/backend-changes' of http://git.raymandcti.com/p.honarjoo/faq_chatbot_frontend into feat/backend-changes 2026-10-13 09:32:29 +03:30
PeymanHonarjoo 3dddf1f12b fix(settings): center document table alignment and actions
The documents table headers and cells were inheriting text-align: right
from the RTL context, causing visual skewing. This change ensures they
are centered. Additionally, document actions are now centered within
their container.
2026-10-13 09:23:41 +03:30
11linear11 52202c2a35 Add live voice playback diagnostics and sample accounting 2026-10-12 17:52:20 -04:00
amirhosein mazaheri 58c3c20933 feat(voice): enhance audio stream lifecycle with sent_bytes validation and ref-attributed idle tracking 2026-10-12 18:51:05 +03:30
amirhosein mazaheri 89c6bc6d44 build: adjust initial and component style budgets in angular.json 2026-10-12 17:52:07 +03:30
amirhosein mazaheri 97427a1581 fix(voice): handle exact consumed-sample progress and direct native-rate playback 2026-10-12 17:51:52 +03:30
PeymanHonarjoo b3eb4a6de5 feat(settings): adjust document actions layout to prevent button wrapping 2026-10-12 17:30:23 +03:30
PeymanHonarjoo 9e8dd33927 feat: implement answer-limited state handling in voice stream service
- Introduced handling for 'answer_limited' events from the server, allowing the UI to reflect when an assistant's answer has reached the output-token limit.
- Updated the VoiceStreamService to manage limited and interrupted turns with bounded memory.
- Enhanced the transcript component to display appropriate messages for limited answers, including a fallback for unavailable text.
- Added styles to visually indicate limited answers in the UI.
- Created unit tests for the new functionality, ensuring correct behavior for limited answers and their presentation.
2026-10-12 16:51:04 +03:30
PeymanHonarjoo 0af55f52a3 feat(uuid): implement UUID generation for non-secure contexts and replace crypto.randomUUID() usage 2026-10-12 16:50:52 +03:30
PeymanHonarjoo e268631386 feat(voice): add audio cues for session lifecycle
Introduce VoiceCueService to play 'ready' and 'end' audio cues during
voice stream sessions. This provides auditory feedback when a session
starts and concludes.
2026-10-11 17:25:44 +03:30
PeymanHonarjoo a6c466e1ba feat(settings): implement document removal and responsive table layout
Add a confirmation workflow for removing documents and refactor the
documents table to support responsive layouts. The table now uses
a fixed layout with defined column widths and handles overflow on
mobile devices. The redundant filename column has been removed.
2026-10-11 17:25:28 +03:30
PeymanHonarjoo 2ac7a099b5 feat(ui): add ngx-toastr with zoneless compatibility
Add ngx-toastr and a proxy-based ToastrService wrapper that
manually triggers appRef.tick() to ensure toast notifications
render correctly in a zoneless change detection environment.
2026-10-11 17:24:52 +03:30
PeymanHonarjoo c1e7a8ac5a feat(sidebar): implement smooth expansion animations and RTL support
Add staggered transitions to sidebar labels to prevent text reflow during expansion. Update account menu to RTL direction and localize logout text. Refine collapsed sidebar layout for improved icon alignment.
2026-10-11 17:23:34 +03:30
41 changed files with 3478 additions and 239 deletions
+5 -7
View File
@@ -26,22 +26,20 @@
"output": "assets" "output": "assets"
} }
], ],
"styles": [ "styles": ["node_modules/ngx-toastr/toastr.css", "src/styles.css"]
"src/styles.css"
]
}, },
"configurations": { "configurations": {
"production": { "production": {
"budgets": [ "budgets": [
{ {
"type": "initial", "type": "initial",
"maximumWarning": "1.5MB", "maximumWarning": "2MB",
"maximumError": "2MB" "maximumError": "3MB"
}, },
{ {
"type": "anyComponentStyle", "type": "anyComponentStyle",
"maximumWarning": "8kB", "maximumWarning": "20kB",
"maximumError": "12kB" "maximumError": "30kB"
} }
], ],
"outputHashing": "all" "outputHashing": "all"
+1 -1
View File
@@ -3,7 +3,7 @@
"version": "0.0.0", "version": "0.0.0",
"scripts": { "scripts": {
"ng": "ng", "ng": "ng",
"start": "ng serve", "start": "ng serve --host 0.0.0.0",
"build": "ng build", "build": "ng build",
"watch": "ng build --watch --configuration development", "watch": "ng build --watch --configuration development",
"test": "ng test" "test": "ng test"
+2 -2
View File
@@ -1,13 +1,13 @@
{ {
"/api": { "/api": {
"target": "http://10.2.8.3:8080", "target": "http://192.168.180.151:8080",
"secure": false, "secure": false,
"changeOrigin": true, "changeOrigin": true,
"ws": true, "ws": true,
"logLevel": "debug" "logLevel": "debug"
}, },
"/users": { "/users": {
"target": "http://10.2.8.3:8080", "target": "http://192.168.180.151:8080",
"secure": false, "secure": false,
"changeOrigin": true "changeOrigin": true
} }
Binary file not shown.
Binary file not shown.
+41 -19
View File
@@ -27,27 +27,27 @@
* *
* Messages in: { type: 'push', pcm: ArrayBuffer (Int16 mono), sampleRate, audioRef } * Messages in: { type: 'push', pcm: ArrayBuffer (Int16 mono), sampleRate, audioRef }
* { type: 'clear' } barge-in: drop everything immediately * { 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 } * 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 * { type: 'overflow' } bounded queue filled — caller fails the session safely
*/ */
const BOUND_BYTES = 96000; // contract cap on outstanding SOURCE PCM16 const BOUND_BYTES = 96000; // contract cap on outstanding SOURCE PCM16
const RESAMPLE_MARGIN = 64; // slack for fractional-boundary rounding (never widens the source bound) const RESAMPLE_MARGIN = 64; // slack for fractional-boundary rounding (never widens the source bound)
const REPORT_INTERVAL_MS = 250; const REPORT_INTERVAL_MS = 250;
class PcmPlaybackProcessor extends AudioWorkletProcessor { class PcmPlaybackProcessor extends AudioWorkletProcessor {
constructor() { constructor() {
super(); super();
this.sourceCapacity = Math.floor(BOUND_BYTES / 2); // 48,000 SOURCE samples (admission bound) this.sourceCapacity = Math.floor(BOUND_BYTES / 2); // 48,000 SOURCE samples (admission bound)
this.ratio = 1; // SOURCE samples per OUTPUT sample (resolved on first push) this.ratio = 1; // SOURCE samples per OUTPUT sample (resolved on first push)
this.sized = false; // true once the output ring matches the real context rate this.sized = false; // true once the output ring matches the real context rate
this.capacity = this.sourceCapacity; // OUTPUT slots currently allocated (grows for upsampling) this.capacity = this.sourceCapacity; // OUTPUT slots currently allocated (grows for upsampling)
this.buf = new Float32Array(this.capacity); this.buf = new Float32Array(this.capacity);
this.r = 0; this.r = 0;
this.w = 0; this.w = 0;
this.count = 0; // OUTPUT samples currently queued this.count = 0; // OUTPUT samples currently queued
this.queuedSource = 0; // SOURCE samples currently queued (the admission bound unit) this.queuedSource = 0; // SOURCE samples currently queued (the admission bound unit)
this.prebuffer = Math.floor(sampleRate * 0.08); // jitter buffer before (re)starting this.prebuffer = Math.floor(sampleRate * 0.08); // jitter buffer before (re)starting
this.started = false; this.started = false;
this.prev = 0; this.prev = 0;
@@ -56,17 +56,17 @@ class PcmPlaybackProcessor extends AudioWorkletProcessor {
// `emittedOut` let flush() emit the exact OUTPUT count for all admitted source; the last // `emittedOut` let flush() emit the exact OUTPUT count for all admitted source; the last
// chunk window is retained so the tail can be interpolated correctly. // chunk window is retained so the tail can be interpolated correctly.
this.admittedSrc = 0; // SOURCE samples admitted this turn this.admittedSrc = 0; // SOURCE samples admitted this turn
this.emittedOut = 0; // OUTPUT samples emitted for them so far this.emittedOut = 0; // OUTPUT samples emitted for them so far
this.windowSrc = null; // last chunk's src window (for tail interpolation) this.windowSrc = null; // last chunk's src window (for tail interpolation)
this.windowN = 0; this.windowN = 0;
// Per-audio_ref attribution. `refQueue` keeps the still-queued OUTPUT span of each ref // Per-audio_ref attribution. `refQueue` keeps the still-queued OUTPUT span of each ref
// (merged per ref so it stays ≤ the number of turns); `refPlayedOut` keeps each ref's // (merged per ref so it stays ≤ the number of turns); `refPlayedOut` keeps each ref's
// cumulative OUTPUT samples consumed. Together they tie queued audio to its own ref and // cumulative OUTPUT samples consumed. Together they tie queued audio to its own ref and
// keep progress cumulative and correct across ref changes. // keep progress cumulative and correct across ref changes.
this.refQueue = []; // [{ ref, out }] out = remaining OUTPUT samples of that ref this.refQueue = []; // [{ ref, out }] out = remaining OUTPUT samples of that ref
this.refPlayedOut = new Map(); this.refPlayedOut = new Map();
this.playingRef = null; // ref currently being consumed / reported this.playingRef = null; // ref currently being consumed / reported
this.pendingRef = null; // audio_ref of the most recent push (the one flush() tail belongs to) this.pendingRef = null; // audio_ref of the most recent push (the one flush() tail belongs to)
this.unreportedOut = 0; this.unreportedOut = 0;
this.overflowPosted = false; this.overflowPosted = false;
this.port.onmessage = (e) => { this.port.onmessage = (e) => {
@@ -74,7 +74,7 @@ class PcmPlaybackProcessor extends AudioWorkletProcessor {
if (!m) return; if (!m) return;
if (m.type === 'push') this.push(new Int16Array(m.pcm), m.sampleRate, m.audioRef || null); 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 === '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() { clear() {
this.reportFinal(); // final cumulative report for the interrupted ref 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.r = this.w = this.count = 0;
this.queuedSource = 0; this.queuedSource = 0;
this.refQueue.length = 0; this.refQueue.length = 0;
@@ -110,12 +120,12 @@ class PcmPlaybackProcessor extends AudioWorkletProcessor {
this.playingRef = null; this.playingRef = null;
} }
flush() { flush(audioRef = this.pendingRef) {
this.finalizeTail(); // emit the deferred tail so every admitted sample becomes output this.finalizeTail(); // emit the deferred tail so every admitted sample becomes output
if (this.count === 0) { if (this.count === 0) {
this.started = false; this.started = false;
this.reportFinal(); this.reportFinal();
this.port.postMessage({ type: 'idle' }); this.port.postMessage({ type: 'idle', audioRef: audioRef || this.pendingRef });
} else { } else {
this.started = true; // play the remaining audio + tail without waiting for the prebuffer this.started = true; // play the remaining audio + tail without waiting for the prebuffer
} }
@@ -162,7 +172,8 @@ class PcmPlaybackProcessor extends AudioWorkletProcessor {
this.configure(ratio); this.configure(ratio);
// OUTPUT samples this chunk's main loop will add — an upper bound on the exact count. // OUTPUT samples this chunk's main loop will add — an upper bound on the exact count.
const produced = this.pos < n ? Math.ceil((n - this.pos) / this.ratio) : 0; const produced =
this.ratio === 1 ? n : this.pos < n ? Math.ceil((n - this.pos) / this.ratio) : 0;
// Bounded queue — two consistent guards, each in its own unit: // Bounded queue — two consistent guards, each in its own unit:
// 1) SOURCE bound: the contract 96,000-byte cap, invariant across context rates. // 1) SOURCE bound: the contract 96,000-byte cap, invariant across context rates.
@@ -173,6 +184,16 @@ class PcmPlaybackProcessor extends AudioWorkletProcessor {
this.queuedSource += n; this.queuedSource += n;
this.admittedSrc += n; // every admitted source sample must eventually become output this.admittedSrc += n; // every admitted source sample must eventually become output
// Matching rates need no interpolation or deferred tail. Render every admitted
// sample even while generation is still open; progress reflects only consumed PCM.
if (this.ratio === 1) {
this.pendingRef = audioRef;
for (let i = 0; i < n; i++) this.write(int16[i] / 32768);
this.creditQueue(n);
this.emittedOut += n;
return;
}
const src = new Float32Array(n + 1); const src = new Float32Array(n + 1);
src[0] = this.prev; src[0] = this.prev;
for (let i = 0; i < n; i++) src[i + 1] = int16[i] / 32768; for (let i = 0; i < n; i++) src[i + 1] = int16[i] / 32768;
@@ -249,7 +270,7 @@ class PcmPlaybackProcessor extends AudioWorkletProcessor {
this.queuedSource = 0; this.queuedSource = 0;
this.started = false; this.started = false;
this.reportFinal(); this.reportFinal();
this.port.postMessage({ type: 'idle' }); this.port.postMessage({ type: 'idle', audioRef: this.pendingRef });
} }
} else { } else {
ch0.fill(0); ch0.fill(0);
@@ -296,9 +317,10 @@ class PcmPlaybackProcessor extends AudioWorkletProcessor {
// OUTPUT samples at the context rate → milliseconds; floor never claims an unheard ms and // OUTPUT samples at the context rate → milliseconds; floor never claims an unheard ms and
// stays monotonic because it is cumulative. Output-time equals source-time (SRC preserves // stays monotonic because it is cumulative. Output-time equals source-time (SRC preserves
// duration), so this equals the contract's played source / srcRate. // duration), so this equals the contract's played source / srcRate.
const playedMs = Math.floor((playedOut / sampleRate) * 1000); // Multiply integer counts first to avoid rounding an exact whole millisecond down.
const playedMs = Math.floor((playedOut * 1000) / sampleRate);
if (playedMs <= 0) return; if (playedMs <= 0) return;
this.port.postMessage({ type: 'progress', audioRef: ref, playedMs }); this.port.postMessage({ type: 'progress', audioRef: ref, playedMs, consumedSamples: playedOut, contextRate: sampleRate });
} }
} }
+63 -10
View File
@@ -1,12 +1,49 @@
import { ApplicationConfig, provideBrowserGlobalErrorListeners, provideZonelessChangeDetection, APP_INITIALIZER } from '@angular/core'; import {
ApplicationConfig,
provideBrowserGlobalErrorListeners,
provideZonelessChangeDetection,
APP_INITIALIZER,
importProvidersFrom,
ApplicationRef,
Injector,
NgZone,
} from '@angular/core';
import { provideRouter } from '@angular/router'; import { provideRouter } from '@angular/router';
import { provideAnimations } from '@angular/platform-browser/animations'; import { provideAnimations } from '@angular/platform-browser/animations';
import { provideHttpClient } from '@angular/common/http'; import { provideHttpClient } from '@angular/common/http';
import { TOAST_CONFIG, DefaultGlobalConfig } from 'ngx-toastr'; import { DomSanitizer } from '@angular/platform-browser';
import { Overlay, ToastrModule, ToastrService, TOAST_CONFIG } from 'ngx-toastr';
import { routes } from './app.routes'; import { routes } from './app.routes';
import { AuthService } from './services/auth/auth.service'; import { AuthService } from './services/auth/auth.service';
/** The type of the injected TOAST_CONFIG value (the `{ default, config }` toast token). */
type ToastConfigToken = ConstructorParameters<typeof ToastrService>[0];
/**
* Builds the real ToastrService wrapped so every method forces an `ApplicationRef.tick()`.
* ngx-toastr v14 attaches each toast to ApplicationRef without rendering it; under this app's
* ZONELESS change detection there is no zone tick to render it, so without this no toast
* appears. `tick()` renders the just-attached overlay view.
*/
function zonelessToastr(
real: ToastrService,
appRef: ApplicationRef,
): ToastrService {
return new Proxy(real, {
get(target, prop, receiver) {
const value = Reflect.get(target, prop, receiver);
return typeof value === 'function'
? (...args: unknown[]) => {
const result = (value as (...a: unknown[]) => unknown).apply(target, args);
appRef.tick();
return result;
}
: value;
},
}) as ToastrService;
}
/** /**
* On every page load the HttpOnly `rag_session` cookie is validated with `GET /me` * On every page load the HttpOnly `rag_session` cookie is validated with `GET /me`
* before the first route activates; a 401 drops the authenticated state so the * before the first route activates; a 401 drops the authenticated state so the
@@ -23,18 +60,34 @@ export const appConfig: ApplicationConfig = {
provideRouter(routes), provideRouter(routes),
provideAnimations(), provideAnimations(),
provideHttpClient(), provideHttpClient(),
// Registers ngx-toastr's Toast component + TOAST_CONFIG.
importProvidersFrom(
ToastrModule.forRoot({
timeOut: 4000,
positionClass: 'toast-bottom-left',
preventDuplicates: true,
}),
),
{
// Override the library's root ToastrService with a zoneless-aware wrapper so toasts
// actually render (see zonelessToastr()).
provide: ToastrService,
useFactory: (
appRef: ApplicationRef,
injector: Injector,
config: ToastConfigToken,
overlay: Overlay,
sanitizer: DomSanitizer,
zone: NgZone,
) =>
zonelessToastr(new ToastrService(config, overlay, injector, sanitizer, zone), appRef),
deps: [ApplicationRef, Injector, TOAST_CONFIG, Overlay, DomSanitizer, NgZone],
},
{ {
provide: APP_INITIALIZER, provide: APP_INITIALIZER,
useFactory: initializeAuth, useFactory: initializeAuth,
deps: [AuthService], deps: [AuthService],
multi: true, multi: true,
}, },
{ ],
provide: TOAST_CONFIG,
useValue: {
default: DefaultGlobalConfig,
config: {}
}
}
]
}; };
+3 -6
View File
@@ -6,7 +6,7 @@ import { AuthService } from '../services/auth/auth.service';
import { VoiceStreamService } from '../services/voice-stream/voice-stream.service'; import { VoiceStreamService } from '../services/voice-stream/voice-stream.service';
import { ThemeService } from '../services/theme/theme.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[] = [ const BASE_NAV_ITEMS: NavItem[] = [
{ icon: 'M12 5v14M5 12h14', label: 'چت جدید', route: '/' }, { icon: 'M12 5v14M5 12h14', label: 'چت جدید', route: '/' },
{ icon: 'M4 4v16h16M8 20V11M12.5 20V6M17 20V9', label: 'گزارشات', route: '/reports' }, { 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. */ /** The signed-in identity exactly as the server reported it. */
readonly userName = computed(() => this.authService.currentUserSubject.value?.username ?? ''); readonly userName = computed(() => this.authService.currentUserSubject.value?.username ?? '');
/** Hiding a nav entry is only cosmetic: every request is still authorized server-side. */ /** The settings page handles role-specific controls; the server authorizes each operation. */
readonly navItems = computed<NavItem[]>(() => { readonly navItems = signal<NavItem[]>(BASE_NAV_ITEMS);
const isAdmin = this.authService.currentUserSubject.value?.role === 'admin';
return isAdmin ? BASE_NAV_ITEMS : BASE_NAV_ITEMS.filter((item) => item.route !== '/settings');
});
onProfile(): void { onProfile(): void {
this.sidebarOpen.set(false); this.sidebarOpen.set(false);
+41
View File
@@ -244,6 +244,47 @@
margin-bottom: 0.5rem; 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 ---------- */
.jump-to-latest { .jump-to-latest {
position: absolute; position: absolute;
+6
View File
@@ -61,6 +61,12 @@
(fileSelected)="onFileSelected($event)" (fileSelected)="onFileSelected($event)"
(voiceToggled)="onVoiceToggled($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>
</div> </div>
+7 -1
View File
@@ -17,6 +17,7 @@ import { Subscription } from 'rxjs';
import { AiChatInputComponent } from '../../shared/ui/ai-chat-input/ai-chat-input.component'; 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 { VoiceStreamPanelComponent } from '../../shared/ui/voice-stream-panel/voice-stream-panel.component';
import { VoiceTranscriptComponent } from '../../shared/ui/voice-transcript/voice-transcript.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 { VoiceStreamService } from '../../services/voice-stream/voice-stream.service';
import { ThemeService } from '../../services/theme/theme.service'; import { ThemeService } from '../../services/theme/theme.service';
@@ -41,7 +42,12 @@ const STICK_TO_BOTTOM_PX = 80;
@Component({ @Component({
selector: 'app-home', selector: 'app-home',
standalone: true, standalone: true,
imports: [AiChatInputComponent, VoiceStreamPanelComponent, VoiceTranscriptComponent], imports: [
AiChatInputComponent,
VoiceStreamPanelComponent,
VoiceTranscriptComponent,
VoiceProviderPickerComponent,
],
changeDetection: ChangeDetectionStrategy.OnPush, changeDetection: ChangeDetectionStrategy.OnPush,
templateUrl: './home.page.html', templateUrl: './home.page.html',
styleUrl: './home.page.css', styleUrl: './home.page.css',
+76 -1
View File
@@ -208,6 +208,10 @@
background-color: color-mix(in srgb, var(--color-primary) 78%, #000); background-color: color-mix(in srgb, var(--color-primary) 78%, #000);
} }
.file-remove-btn:hover{
cursor: pointer;
}
@keyframes fadeInDown { @keyframes fadeInDown {
from { opacity: 0; transform: translateY(-10px); } from { opacity: 0; transform: translateY(-10px); }
to { opacity: 1; transform: translateY(0); } to { opacity: 1; transform: translateY(0); }
@@ -428,6 +432,50 @@
} }
.documents-table-wrapper { .documents-table-wrapper {
border: 1px solid var(--color-card-border); border: 1px solid var(--color-card-border);
/* Clip the table to the rounded corners on wide layouts. */
overflow: hidden;
}
/*
* md and below (Tailwind md = 48rem/768px).
*
* Six fixed-percentage columns stop being readable well before 768px: the date wraps,
* and the status column's error text overflows its column and bleeds into the
* neighbouring cells — which is what makes the row contents look mixed.
*
* Switching to `table-layout: auto` lets each column size to its own content, so no
* cell can overflow into the next one. The table then grows past the card and the
* wrapper scrolls horizontally instead of squeezing the columns.
*/
@media (max-width: 767.98px) {
.documents-table-wrapper {
overflow-x: auto;
/* Keep the scroll chain inside the card instead of leaking to the page. */
overscroll-behavior-x: contain;
-webkit-overflow-scrolling: touch;
}
.documents-table {
/* Auto layout ignores the <col> percentages, so columns follow their content. */
table-layout: auto;
min-width: 720px;
}
/* Short cells stay on one line so each column keeps a clean width. */
.documents-table th,
.documents-table td {
white-space: nowrap;
}
/* Title and status hold long text; let them wrap instead of widening the table. */
.documents-table td:nth-child(1),
.documents-table td:nth-child(2) {
white-space: normal;
}
.documents-table td:nth-child(1) {
max-width: 220px;
}
} }
.documents-table { .documents-table {
border-collapse: separate; border-collapse: separate;
@@ -436,9 +484,12 @@
.documents-table th, .documents-table th,
.documents-table td { .documents-table td {
padding: 0.6rem 0.75rem; 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; vertical-align: top;
border-bottom: 1px solid var(--color-card-border); border-bottom: 1px solid var(--color-card-border);
/* Fixed layout fits the card; wrap long tokens so a cell never widens the table. */
overflow-wrap: anywhere;
} }
.documents-table thead th { .documents-table thead th {
background: var(--sidebar-hover); background: var(--sidebar-hover);
@@ -450,6 +501,26 @@
border-bottom: none; border-bottom: none;
} }
/*
* Row actions: the buttons must not be squeezed by the fixed column.
* Flex items shrink by default, which used to wrap «تلاش‌مجدد» / «بازبینی سند»
* mid-word (the cell's `overflow-wrap: anywhere` leaked into the button), so
* each button keeps its intrinsic width and the cell wraps to a new line only
* when there is genuinely no room.
*/
.documents-actions {
align-items: flex-start;
justify-content: center;
flex-wrap: wrap;
}
.documents-actions > .btn {
flex: 0 0 auto;
white-space: nowrap;
overflow-wrap: normal;
word-break: normal;
}
/* Status badges */ /* Status badges */
.status-queued { .status-queued {
background: var(--color-warning)/15; background: var(--color-warning)/15;
@@ -562,6 +633,10 @@
padding: 1rem 1.25rem; padding: 1rem 1.25rem;
border-bottom: 1px solid var(--color-card-border); border-bottom: 1px solid var(--color-card-border);
} }
/* Narrower variant for confirmations (e.g. remove document). */
.review-modal--sm {
max-width: 30rem;
}
.review-modal-body { .review-modal-body {
padding: 1.25rem; padding: 1.25rem;
overflow-y: auto; overflow-y: auto;
+112 -13
View File
@@ -496,11 +496,18 @@
</button> </button>
</div> </div>
<div class="documents-table-wrapper overflow-x-auto rounded-xl border border-[var(--color-card-border)] bg-[var(--card-bg)]"> <div class="documents-table-wrapper rounded-xl border border-[var(--color-card-border)] bg-[var(--card-bg)]">
<table class="documents-table min-w-full text-sm text-right"> <table class="documents-table w-full table-fixed text-sm text-right">
<colgroup>
<col class="w-[24%]" />
<col class="w-[17%]" />
<col class="w-[9%]" />
<col class="w-[16%]" />
<col class="w-[14%]" />
<col class="w-[20%]" />
</colgroup>
<thead class="bg-[var(--sidebar-hover)]"> <thead class="bg-[var(--sidebar-hover)]">
<tr> <tr>
<th class="px-3 py-2 text-xs font-medium text-[var(--text-muted)]">نام فایل</th>
<th class="px-3 py-2 text-xs font-medium text-[var(--text-muted)]">عنوان سند</th> <th class="px-3 py-2 text-xs font-medium text-[var(--text-muted)]">عنوان سند</th>
<th class="px-3 py-2 text-xs font-medium text-[var(--text-muted)]">وضعیت پردازش</th> <th class="px-3 py-2 text-xs font-medium text-[var(--text-muted)]">وضعیت پردازش</th>
<th class="px-3 py-2 text-xs font-medium text-[var(--text-muted)]">تعداد بخش‌ها</th> <th class="px-3 py-2 text-xs font-medium text-[var(--text-muted)]">تعداد بخش‌ها</th>
@@ -513,11 +520,9 @@
@for (doc of documents(); track doc.id) { @for (doc of documents(); track doc.id) {
<tr class="table-row-animate"> <tr class="table-row-animate">
<td class="px-3 py-2.5 align-top"> <td class="px-3 py-2.5 align-top">
<span class="text-sm text-[var(--text-secondary)] truncate block max-w-[14rem]" <span class="text-sm text-[var(--text-secondary)] truncate block" title="{{ doc.title ?? '' }}">{{
>{{ doc.filename }}</span> doc.title ?? '—'
</td> }}</span>
<td class="px-3 py-2.5 align-top">
<span class="text-sm text-[var(--text-secondary)]">{{ doc.title ?? '—' }}</span>
</td> </td>
<td class="px-3 py-2.5 align-top"> <td class="px-3 py-2.5 align-top">
<span <span
@@ -548,10 +553,10 @@
<td class="px-3 py-2.5 align-top"> <td class="px-3 py-2.5 align-top">
<span class="text-sm text-[var(--text-muted)]">{{ formatDateTime(doc.created_at) }}</span> <span class="text-sm text-[var(--text-muted)]">{{ formatDateTime(doc.created_at) }}</span>
</td> </td>
<td class="px-3 py-2.5 align-top min-w-[11rem]"> <td class="px-3 py-2.5 align-top">
@if (doc.status === 'ready' && !isReviewNeeded(doc) && isAdmin()) { @if (doc.status === 'ready' && !isReviewNeeded(doc) && isAdmin()) {
@if (togglingDocId() === doc.id) { @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 <svg
class="w-3 h-3 animate-spin" class="w-3 h-3 animate-spin"
viewBox="0 0 24 24" viewBox="0 0 24 24"
@@ -585,7 +590,7 @@
} }
</td> </td>
<td class="px-3 py-2.5 align-top"> <td class="px-3 py-2.5 align-top">
<div class="flex items-center gap-1.5"> <div class="documents-actions flex items-center gap-1.5">
@if (isReviewNeeded(doc) && doc.status === 'failed') { @if (isReviewNeeded(doc) && doc.status === 'failed') {
<button <button
type="button" type="button"
@@ -632,6 +637,30 @@
<span>تلاش‌مجدد</span> <span>تلاش‌مجدد</span>
</button> </button>
} }
<button
type="button"
class="file-remove-btn p-2 text-[var(--text-muted)] rounded-lg transition-all duration-200 hover:text-red-400 hover:bg-red-400/10 hover:scale-110 shrink-0"
[attr.aria-label]="'حذف سند ' + (doc.title ?? doc.filename)"
title="حذف سند"
(click)="removeDocument(doc)"
>
<svg
class="w-4 h-4"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<path d="M3 6h18" />
<path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6" />
<path d="M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2" />
<line x1="10" y1="11" x2="10" y2="17" />
<line x1="14" y1="11" x2="14" y2="17" />
</svg>
</button>
</div> </div>
</td> </td>
</tr> </tr>
@@ -639,7 +668,7 @@
@if (!documentsLoading()) { @if (!documentsLoading()) {
<tr> <tr>
<td <td
colspan="7" colspan="6"
class="px-3 py-10 text-center text-sm text-[var(--text-muted)]" class="px-3 py-10 text-center text-sm text-[var(--text-muted)]"
> >
هیچ سندی با فیلتر انتخاب‌شده مطابقت ندارد. هیچ سندی با فیلتر انتخاب‌شده مطابقت ندارد.
@@ -884,6 +913,57 @@
</div> </div>
</div> </div>
} }
<!-- Remove-document confirmation -->
@if (deletingDoc(); as doc) {
<div class="review-backdrop" (click)="cancelDelete()">
<div
class="review-modal review-modal--sm"
(click)="onReviewModalClick($event)"
role="alertdialog"
aria-modal="true"
aria-label="حذف سند"
>
<header class="review-modal-header">
<h3 class="text-lg font-semibold text-[var(--text-primary)]">حذف سند</h3>
<button
type="button"
class="file-remove-btn p-1 text-[var(--text-muted)]"
(click)="cancelDelete()"
aria-label="بستن"
>
<svg
class="w-4 h-4"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<line x1="18" y1="6" x2="6" y2="18" />
<line x1="6" y1="6" x2="18" y2="18" />
</svg>
</button>
</header>
<div class="review-modal-body">
<p class="text-sm text-[var(--text-secondary)]">
آیا از حذف سند «{{ doc.title ?? doc.filename }}» مطمئن هستید؟ این عملیات قابل بازگشت نیست.
</p>
</div>
<footer
class="review-modal-footer border-t border-[var(--color-card-border)] p-3 flex justify-end gap-2"
>
<button type="button" class="btn btn--outline" (click)="cancelDelete()">
<span>انصراف</span>
</button>
<button type="button" class="btn btn--primary" (click)="confirmDeleteDocument()">
<span>حذف سند</span>
</button>
</footer>
</div>
</div>
}
</section> </section>
} }
@@ -946,6 +1026,25 @@
</label> </label>
</div> </div>
</div> </div>
<div
class="setting-item flex items-center justify-between gap-4 p-4 bg-[var(--card-bg)] rounded-xl shadow-[0_2px_8px_rgba(0,0,0,0.04)] transition-all duration-200 hover:shadow-[0_4px_16px_rgba(0,0,0,0.08)] hover:-translate-y-0.5"
>
<div class="setting-info flex flex-col gap-1 min-w-0">
<label class="text-sm font-medium text-[var(--text-secondary)] cursor-pointer">
نیاز به تأیید ادمین برای اسناد FAQ
</label>
<span class="text-xs text-[var(--text-muted)] block mt-0.5">
در صورت فعال بودن، محتوای استخراج‌شده از اسناد FAQ باید توسط ادمین بازبینی و تأیید شود.
</span>
</div>
<div class="setting-control shrink-0">
<label class="toggle-switch" [class.toggle-active]="faqAdminApproval()">
<input type="checkbox" [checked]="faqAdminApproval()" (change)="toggleFaqApproval()" />
<span class="toggle-slider"></span>
</label>
</div>
</div>
</div> </div>
</section> </section>
+138 -2
View File
@@ -30,12 +30,18 @@ function readyDoc(): DocumentListItem {
}; };
} }
const toastr = { success: vi.fn(), error: vi.fn(), warning: vi.fn(), info: vi.fn() };
const filterSelect = (el: HTMLElement): HTMLSelectElement | null => el.querySelector('.documents-filters select'); const filterSelect = (el: HTMLElement): HTMLSelectElement | null => el.querySelector('.documents-filters select');
describe('SettingsPage — document filters', () => { describe('SettingsPage — document filters', () => {
let getDocuments: ReturnType<typeof vi.fn>; let getDocuments: ReturnType<typeof vi.fn>;
beforeEach(async () => { beforeEach(async () => {
toastr.success.mockClear();
toastr.error.mockClear();
toastr.warning.mockClear();
toastr.info.mockClear();
// Server-side filtering: `all` returns one ready doc; every other status matches none. // Server-side filtering: `all` returns one ready doc; every other status matches none.
getDocuments = vi.fn((params: { status?: string } = {}): Observable<DocumentListResponse> => { getDocuments = vi.fn((params: { status?: string } = {}): Observable<DocumentListResponse> => {
const items = params.status ? [] : [readyDoc()]; const items = params.status ? [] : [readyDoc()];
@@ -59,7 +65,7 @@ describe('SettingsPage — document filters', () => {
{ provide: AuthService, useValue: { getCurrentUserValue: () => ({ role: 'admin' }) } }, { provide: AuthService, useValue: { getCurrentUserValue: () => ({ role: 'admin' }) } },
{ provide: HttpService, useValue: { apiUrl: '/api/v1' } }, { provide: HttpService, useValue: { apiUrl: '/api/v1' } },
{ provide: ThemeService, useValue: { isDarkMode: () => false, toggleDarkMode: () => {} } }, { provide: ThemeService, useValue: { isDarkMode: () => false, toggleDarkMode: () => {} } },
{ provide: ToastrService, useValue: { success: vi.fn(), error: vi.fn(), warning: vi.fn(), info: vi.fn() } }, { provide: ToastrService, useValue: toastr },
], ],
}).compileComponents(); }).compileComponents();
}); });
@@ -108,7 +114,137 @@ describe('SettingsPage — document filters', () => {
fixture.detectChanges(); fixture.detectChanges();
const rows = (fixture.nativeElement as HTMLElement).querySelectorAll('.documents-table tbody tr'); const rows = (fixture.nativeElement as HTMLElement).querySelectorAll('.documents-table tbody tr');
expect(rows.length).toBe(1); expect(rows.length).toBe(1);
expect(rows[0].textContent).toContain('guide.pdf'); // نام فایل column was dropped (redundant with عنوان سند); the row shows the title.
expect(rows[0].textContent).toContain('سند آزمون');
expect(rows[0].textContent).not.toContain('guide.pdf');
});
it('drops the redundant نام فایل column and renders exactly 6 columns', () => {
const fixture = TestBed.createComponent(SettingsPage);
fixture.detectChanges();
const el = fixture.nativeElement as HTMLElement;
const headers = Array.from(el.querySelectorAll('.documents-table thead th')).map((t) =>
t.textContent?.trim(),
);
expect(headers).toEqual([
'عنوان سند',
'وضعیت پردازش',
'تعداد بخش‌ها',
'تاریخ آپلود',
'فعال‌سازی',
'عملیات',
]);
expect(headers).not.toContain('نام فایل');
// A data row has exactly 6 cells matching the 6 columns.
expect(el.querySelector('.documents-table tbody tr')?.children.length).toBe(6);
});
it('keeps row action buttons unwrapped inside the narrow عملیات column', () => {
// Regression: the actions column used to be only 15% wide and inherited the
// table's `overflow-wrap: anywhere`, so «تلاش‌مجدد» / «بازبینی سند» broke in
// the middle of the word and the button looked broken.
const fixture = TestBed.createComponent(SettingsPage);
fixture.detectChanges();
const el = fixture.nativeElement as HTMLElement;
const actionsCell = el.querySelector('.documents-table tbody tr td:last-child') as HTMLElement;
expect(actionsCell).not.toBeNull();
const wrapper = actionsCell.querySelector('.documents-actions') as HTMLElement;
expect(wrapper).not.toBeNull();
// Whatever renders inside must stay on a single line per button.
const actionButtons = Array.from(wrapper.querySelectorAll('button'));
expect(actionButtons.length).toBeGreaterThan(0);
for (const button of actionButtons) {
const style = getComputedStyle(button);
if (button.classList.contains('btn')) {
expect(style.whiteSpace).toBe('nowrap');
expect(style.overflowWrap).toBe('normal');
}
}
});
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();
const el = fixture.nativeElement as HTMLElement;
const openRemoveModal = () => {
const row = el.querySelector('.documents-table tbody tr') as HTMLElement;
const remove = Array.from(row.querySelectorAll('button')).find((b) =>
(b.getAttribute('aria-label') ?? '').includes('حذف سند'),
) as HTMLButtonElement;
remove.click();
fixture.detectChanges();
};
openRemoveModal();
const modal = el.querySelector('[role="alertdialog"]') as HTMLElement;
expect(modal).toBeTruthy();
expect(modal.textContent).toContain('سند آزمون');
expect(modal.textContent).toContain('مطمئن هستید');
expect(toastr.info).not.toHaveBeenCalled(); // nothing happens until confirmed
// Cancel closes the modal and keeps the document, with no notice.
(modal.querySelector('.btn--outline') as HTMLButtonElement).click();
fixture.detectChanges();
expect(el.querySelector('[role="alertdialog"]')).toBeNull();
expect(el.querySelectorAll('.documents-table tbody tr').length).toBe(1);
expect(toastr.info).not.toHaveBeenCalled();
// Confirm closes the modal and surfaces the MVP notice (deletion is not yet implemented);
// the row is left in place and no backend delete call is made.
openRemoveModal();
(el.querySelector('[role="alertdialog"] .btn--primary') as HTMLButtonElement).click();
fixture.detectChanges();
expect(toastr.info).toHaveBeenCalledTimes(1);
expect(el.querySelector('[role="alertdialog"]')).toBeNull();
expect(el.querySelectorAll('.documents-table tbody tr').length).toBe(1);
});
it('renders OCR and FAQ admin-approval toggles in the app settings and toggles FAQ', () => {
const fixture = TestBed.createComponent(SettingsPage);
fixture.detectChanges();
const component = fixture.componentInstance;
component.selectTab('app');
fixture.detectChanges();
const el = fixture.nativeElement as HTMLElement;
const labels = Array.from(el.querySelectorAll('.setting-info label')).map((l) =>
l.textContent?.trim(),
);
expect(labels).toContain('نیاز به تأیید ادمین برای اسناد OCR شده');
expect(labels).toContain('نیاز به تأیید ادمین برای اسناد FAQ');
// Toggles in order: dark mode, OCR, FAQ. The FAQ toggle flips its own signal.
const switches = el.querySelectorAll('.setting-control .toggle-switch');
expect(switches.length).toBe(3);
expect(component.faqAdminApproval()).toBe(false);
(switches[2].querySelector('input') as HTMLInputElement).click();
fixture.detectChanges();
expect(component.faqAdminApproval()).toBe(true);
}); });
it('hasActiveFilters reflects the active status/active-only filters', () => { it('hasActiveFilters reflects the active status/active-only filters', () => {
+40 -5
View File
@@ -14,6 +14,7 @@ import { ThemeService } from '../../services/theme/theme.service';
import { DocumentsService } from '../../services/documents/documents.service'; import { DocumentsService } from '../../services/documents/documents.service';
import { AuthService } from '../../services/auth/auth.service'; import { AuthService } from '../../services/auth/auth.service';
import { HttpService } from '../../services/http-request/http.service'; import { HttpService } from '../../services/http-request/http.service';
import { uuid } from '../../shared/utils/uuid';
import { import {
AiModelConfigCardComponent, AiModelConfigCardComponent,
AiModelConfig, AiModelConfig,
@@ -241,6 +242,8 @@ export class SettingsPage implements OnInit, OnDestroy {
// ---- knowledge selection (K01/K02) ---- // ---- knowledge selection (K01/K02) ----
readonly knowledgeSelection = signal<KnowledgeSelection | null>(null); readonly knowledgeSelection = signal<KnowledgeSelection | null>(null);
readonly togglingDocId = signal<string | null>(null); readonly togglingDocId = signal<string | null>(null);
/** Document awaiting remove confirmation (non-null while the confirm modal is open). */
readonly deletingDoc = signal<DocumentListItem | null>(null);
// ---- extraction review modal (D06/D07) ---- // ---- extraction review modal (D06/D07) ----
readonly reviewingDocId = signal<string | null>(null); readonly reviewingDocId = signal<string | null>(null);
@@ -256,6 +259,7 @@ export class SettingsPage implements OnInit, OnDestroy {
readonly notificationsEnabled = signal(true); readonly notificationsEnabled = signal(true);
readonly isDarkMode = this.themeService.isDarkMode; readonly isDarkMode = this.themeService.isDarkMode;
readonly ocrAdminApproval = signal(false); readonly ocrAdminApproval = signal(false);
readonly faqAdminApproval = signal(false);
readonly textModelConfig = signal<AiModelConfig>(DEFAULT_MODEL_CONFIG.text); readonly textModelConfig = signal<AiModelConfig>(DEFAULT_MODEL_CONFIG.text);
readonly embeddingModelConfig = signal<AiModelConfig>(DEFAULT_MODEL_CONFIG.embedding); readonly embeddingModelConfig = signal<AiModelConfig>(DEFAULT_MODEL_CONFIG.embedding);
@@ -431,7 +435,7 @@ export class SettingsPage implements OnInit, OnDestroy {
progress: 0, progress: 0,
status: 'uploading', status: 'uploading',
error: null, error: null,
idempotencyKey: crypto.randomUUID(), idempotencyKey: uuid(),
}); });
} }
} }
@@ -928,7 +932,7 @@ export class SettingsPage implements OnInit, OnDestroy {
checked: [], checked: [],
note: '', note: '',
excludedGroupIds: [], excludedGroupIds: [],
idempotencyKey: crypto.randomUUID(), idempotencyKey: uuid(),
}; };
} }
} }
@@ -1020,7 +1024,7 @@ export class SettingsPage implements OnInit, OnDestroy {
this.toastr.warning('هنوز شواهد بازبینی تکمیل نشده‌اند.'); this.toastr.warning('هنوز شواهد بازبینی تکمیل نشده‌اند.');
return; return;
} }
const key = this.retryKeys.get(doc.id) ?? crypto.randomUUID(); const key = this.retryKeys.get(doc.id) ?? uuid();
this.retryKeys.set(doc.id, key); this.retryKeys.set(doc.id, key);
this.documentsService.retryDocument(doc.id, key).subscribe({ this.documentsService.retryDocument(doc.id, key).subscribe({
next: () => { next: () => {
@@ -1048,7 +1052,7 @@ export class SettingsPage implements OnInit, OnDestroy {
checked: [], checked: [],
note: '', note: '',
excludedGroupIds: [], excludedGroupIds: [],
idempotencyKey: crypto.randomUUID(), idempotencyKey: uuid(),
} }
); );
} }
@@ -1166,7 +1170,7 @@ export class SettingsPage implements OnInit, OnDestroy {
this.toastr.warning('سند در حال حاضر قابل تلاش مجدد نیست.'); this.toastr.warning('سند در حال حاضر قابل تلاش مجدد نیست.');
return; return;
} }
const key = this.retryKeys.get(doc.id) ?? crypto.randomUUID(); const key = this.retryKeys.get(doc.id) ?? uuid();
this.retryKeys.set(doc.id, key); this.retryKeys.set(doc.id, key);
this.documentsService.retryDocument(doc.id, key).subscribe({ this.documentsService.retryDocument(doc.id, key).subscribe({
next: (res: RetryResult) => { next: (res: RetryResult) => {
@@ -1187,6 +1191,32 @@ export class SettingsPage implements OnInit, OnDestroy {
}); });
} }
/**
* Open the remove confirmation for a document. Deletion itself is a destructive,
* epoch-changing action the backend MVP does not expose, so it is confirmed here before the
* (still stubbed) removal runs in `confirmDeleteDocument()`.
*/
removeDocument(doc: DocumentListItem): void {
this.deletingDoc.set(doc);
}
/** Dismiss the remove confirmation without deleting. */
cancelDelete(): void {
this.deletingDoc.set(null);
}
/**
* Confirmed removal. The backend MVP has no document-deletion endpoint (removing an active
* document also revokes its excerpts and can invalidate live voice sessions), so — like the
* other not-yet-implemented actions — this closes the dialog and surfaces an informative
* notice instead of calling an unsupported route. No data is deleted and no call is made.
*/
confirmDeleteDocument(): void {
const doc = this.deletingDoc();
this.deletingDoc.set(null);
if (doc) this.toastr.info(`حذف سند «${doc.title ?? doc.filename}» در فاز MVP پشتیبانی نمی‌شود.`);
}
/** Server-provided preview URL (authenticated via the session cookie); null = no preview. */ /** Server-provided preview URL (authenticated via the session cookie); null = no preview. */
previewImageUrl(item: ExtractionItem): string | null { previewImageUrl(item: ExtractionItem): string | null {
const path = item.preview_path; const path = item.preview_path;
@@ -1227,6 +1257,11 @@ export class SettingsPage implements OnInit, OnDestroy {
this.toastr.info('ذخیره‌سازی سیاست بازبینی OCR در فاز MVP پشتیبانی نمی‌شود.'); this.toastr.info('ذخیره‌سازی سیاست بازبینی OCR در فاز MVP پشتیبانی نمی‌شود.');
} }
toggleFaqApproval(): void {
this.faqAdminApproval.set(!this.faqAdminApproval());
this.toastr.info('ذخیره‌سازی سیاست بازبینی FAQ در فاز MVP پشتیبانی نمی‌شود.');
}
toggleDarkMode(): void { toggleDarkMode(): void {
this.themeService.toggleDarkMode(); this.themeService.toggleDarkMode();
} }
+2 -1
View File
@@ -3,6 +3,7 @@ import { Observable, BehaviorSubject, firstValueFrom, throwError } from 'rxjs';
import { tap, catchError } from 'rxjs/operators'; import { tap, catchError } from 'rxjs/operators';
import { HttpErrorResponse } from '@angular/common/http'; import { HttpErrorResponse } from '@angular/common/http';
import { HttpService } from '../http-request/http.service'; import { HttpService } from '../http-request/http.service';
import { uuid } from '../../shared/utils/uuid';
export interface AuthUser { export interface AuthUser {
id: string; id: string;
@@ -92,7 +93,7 @@ export class AuthService {
/** Per-request correlation id shared with the server's `X-Request-ID`. */ /** Per-request correlation id shared with the server's `X-Request-ID`. */
private correlationHeaders(): Record<string, string> { private correlationHeaders(): Record<string, string> {
return { 'X-Request-ID': crypto.randomUUID() }; return { 'X-Request-ID': uuid() };
} }
/** /**
@@ -120,6 +120,7 @@ describe('DocumentsService (backend handoff contract)', () => {
const req = httpMock.expectOne('/api/v1/documents/doc-1/retry'); const req = httpMock.expectOne('/api/v1/documents/doc-1/retry');
expect(req.request.method).toBe('POST'); expect(req.request.method).toBe('POST');
expect(req.request.serializeBody()).toBeNull();
expect(req.request.headers.get('Idempotency-Key')).toBe('key-retry-1'); expect(req.request.headers.get('Idempotency-Key')).toBe('key-retry-1');
req.flush({ job_id: 'job-1', status: 'queued' }, { status: 202, statusText: 'Accepted' }); req.flush({ job_id: 'job-1', status: 'queued' }, { status: 202, statusText: 'Accepted' });
}); });
@@ -3,6 +3,7 @@ import { HttpErrorResponse, HttpEventType, HttpHeaders, HttpParams } from '@angu
import { map, filter, Observable, tap } from 'rxjs'; import { map, filter, Observable, tap } from 'rxjs';
import { HttpService } from '../http-request/http.service'; import { HttpService } from '../http-request/http.service';
import { AuthService } from '../auth/auth.service'; import { AuthService } from '../auth/auth.service';
import { uuid } from '../../shared/utils/uuid';
import { import {
DocumentDetail, DocumentDetail,
DocumentListParams, DocumentListParams,
@@ -34,7 +35,7 @@ export class DocumentsService {
* (from the login/`/me` flow) and a per-request correlation id. * (from the login/`/me` flow) and a per-request correlation id.
*/ */
private csrfHeaders(): Record<string, string> { private csrfHeaders(): Record<string, string> {
const headers: Record<string, string> = { 'X-Request-ID': crypto.randomUUID() }; const headers: Record<string, string> = { 'X-Request-ID': uuid() };
const token = this.auth.getCsrfToken(); const token = this.auth.getCsrfToken();
if (token) { if (token) {
headers['X-CSRF-Token'] = token; headers['X-CSRF-Token'] = token;
@@ -91,7 +92,7 @@ export class DocumentsService {
title: string | undefined, title: string | undefined,
onProgress: (percent: number) => void, onProgress: (percent: number) => void,
signal?: AbortSignal, signal?: AbortSignal,
idempotencyKey: string = crypto.randomUUID(), idempotencyKey: string = uuid(),
): Observable<DocumentUploadResult> { ): Observable<DocumentUploadResult> {
const form = new FormData(); const form = new FormData();
form.append('file', file); form.append('file', file);
@@ -123,7 +124,7 @@ export class DocumentsService {
submitReviewDecision( submitReviewDecision(
documentId: string, documentId: string,
request: ReviewDecisionRequest, request: ReviewDecisionRequest,
idempotencyKey: string = crypto.randomUUID(), idempotencyKey: string = uuid(),
): Observable<ReviewDecisionResponse> { ): Observable<ReviewDecisionResponse> {
return this.http.postRaw<ReviewDecisionResponse>( return this.http.postRaw<ReviewDecisionResponse>(
`${API}/documents/${encodeURIComponent(documentId)}/extraction-review/decisions`, `${API}/documents/${encodeURIComponent(documentId)}/extraction-review/decisions`,
@@ -147,11 +148,11 @@ export class DocumentsService {
/** D04 — retry processing of a document. */ /** D04 — retry processing of a document. */
retryDocument( retryDocument(
documentId: string, documentId: string,
idempotencyKey: string = crypto.randomUUID(), idempotencyKey: string = uuid(),
): Observable<RetryResult> { ): Observable<RetryResult> {
return this.http.postRaw<RetryResult>( return this.http.postRaw<RetryResult>(
`${API}/documents/${encodeURIComponent(documentId)}/retry`, `${API}/documents/${encodeURIComponent(documentId)}/retry`,
{}, null,
{ headers: this.idempotencyHeaders(idempotencyKey), skipToast: true }, { headers: this.idempotencyHeaders(idempotencyKey), skipToast: true },
); );
} }
@@ -52,7 +52,7 @@ export class HttpService {
* and is sent automatically; no bearer token is used for the MVP endpoints. * 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 * 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 * (e.g. `http://192.168.180.151:8080`) turns every request cross-origin, and browsers
* refuse to send the session cookie cross-origin over plain HTTP — the backend * 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. * then answers 401 AUTH_REQUIRED even though the user is logged in.
*/ */
@@ -9,7 +9,7 @@ import { describe, it, expect, vi } from 'vitest';
* (the class reads `sampleRate` at call time, not at module-eval time). * (the class reads `sampleRate` at call time, not at module-eval time).
*/ */
interface Proc { 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 }; port: { onmessage: (e: { data: unknown }) => void };
count: number; count: number;
capacity: number; capacity: number;
@@ -20,10 +20,10 @@ interface Proc {
} }
class FakeAudioWorkletProcessor { 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: { port: {
onmessage: ((e: { data: unknown }) => void) | null; 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() { constructor() {
this.port = { onmessage: null, postMessage: (m) => this.out.push(m) }; this.port = { onmessage: null, postMessage: (m) => this.out.push(m) };
@@ -150,6 +150,63 @@ describe('pcm-playback.worklet', () => {
expect(peakSource).toBeLessThan(proc.sourceCapacity); 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);
for (let chunk = 0; chunk < 38; chunk++) {
push(proc, frame(chunk * 4800, 4800), 'aud-incident');
drain(proc, 128);
}
// No audio_ended/flush: every native-rate sample can already be rendered.
expect(proc.refPlayedOut.get('aud-incident')).toBe(182400);
expect(playedFor(proc, 'aud-incident')).toBe(7600);
expect(proc.count).toBe(0);
expect(overflowCount(proc)).toBe(0);
});
it('renders native-rate PCM directly without an inserted leading sample', async () => {
const proc = await loadPlaybackProcessor(24000);
const pcm = frame(200, 4800);
push(proc, pcm, 'aud-1');
const output = new Float32Array(128);
proc.process([[]], [[output]]);
expect(Array.from(output)).toEqual(Array.from(pcm.slice(0, 128), (v) => v / 32768));
expect(proc.refPlayedOut.get('aud-1')).toBe(128);
});
for (const rate of [24000, 48000]) {
it(`reports 1001 ms after rendering every sample at ${rate} Hz`, async () => {
const proc = await loadPlaybackProcessor(rate);
push(proc, frame(0, 24024), 'aud-1');
flush(proc);
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.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);
});
}
});
describe('fractional resampling across chunk boundaries', () => { describe('fractional resampling across chunk boundaries', () => {
// 6,000 source samples = 250 ms at 24 kHz. A linear resampler carries ~1 sample of latency // 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 // across a boundary, so reported progress is within 1 ms of 250 — but it must never
@@ -286,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', () => { describe('interruption and clear', () => {
it('clears the queue and reports only the source actually consumed', async () => { it('clears the queue and reports only the source actually consumed', async () => {
const proc = await loadPlaybackProcessor(24000); const proc = await loadPlaybackProcessor(24000);
@@ -1,6 +1,7 @@
import { HttpClient, HttpErrorResponse, HttpHeaders } from '@angular/common/http'; import { HttpClient, HttpErrorResponse, HttpHeaders } from '@angular/common/http';
import { Injectable, inject } from '@angular/core'; import { Injectable, inject } from '@angular/core';
import { firstValueFrom, Observable } from 'rxjs'; import { firstValueFrom, Observable } from 'rxjs';
import { uuid } from '../../shared/utils/uuid';
import { VOICE_STREAM_CONFIG, VoiceSessionStatus } from './voice-stream.types'; import { VOICE_STREAM_CONFIG, VoiceSessionStatus } from './voice-stream.types';
/** /**
@@ -24,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 { export interface MeResponse {
user: { id: string; username: string; role: string; organization_id: string }; user: { id: string; username: string; role: string; organization_id: string };
csrf_token: string; csrf_token: string;
@@ -54,6 +59,7 @@ export interface ConversationResponse {
} }
export interface VoiceSessionResponse { export interface VoiceSessionResponse {
provider?: VoiceProvider;
session_id: string; session_id: string;
conversation_id: string; conversation_id: string;
status: string; status: string;
@@ -83,8 +89,12 @@ export class VoiceApiService {
} }
/** F01: capabilities (the UI must check `voice` before offering a call). */ /** F01: capabilities (the UI must check `voice` before offering a call). */
configuration(): Promise<ConfigurationResponse> { configuration(provider?: VoiceProvider): Promise<ConfigurationResponse> {
return this.send(this.http.get<ConfigurationResponse>(this.url('/configuration'), this.readOptions())); 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. */ /** C01: only `mode: "voice"` exists in the MVP. `clientRequestId` makes replays return the same conversation. */
@@ -103,11 +113,12 @@ export class VoiceApiService {
csrf: string, csrf: string,
conversationId: string, conversationId: string,
clientRequestId: string, clientRequestId: string,
provider?: VoiceProvider,
): Promise<VoiceSessionResponse> { ): Promise<VoiceSessionResponse> {
return this.send( return this.send(
this.http.post<VoiceSessionResponse>( this.http.post<VoiceSessionResponse>(
this.url('/voice/sessions'), this.url('/voice/sessions'),
{ conversation_id: conversationId, client_request_id: clientRequestId }, { conversation_id: conversationId, client_request_id: clientRequestId, ...(provider ? { provider } : {}) },
this.writeOptions(csrf), this.writeOptions(csrf),
), ),
); );
@@ -165,7 +176,7 @@ export class VoiceApiService {
} }
private readOptions() { private readOptions() {
return { withCredentials: true, headers: new HttpHeaders({ 'X-Request-ID': crypto.randomUUID() }) }; return { withCredentials: true, headers: new HttpHeaders({ 'X-Request-ID': uuid() }) };
} }
private writeOptions(csrf: string) { private writeOptions(csrf: string) {
@@ -173,7 +184,7 @@ export class VoiceApiService {
withCredentials: true, withCredentials: true,
headers: new HttpHeaders({ headers: new HttpHeaders({
'X-CSRF-Token': csrf, 'X-CSRF-Token': csrf,
'X-Request-ID': crypto.randomUUID(), 'X-Request-ID': uuid(),
}), }),
}; };
} }
@@ -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 { MicrophoneError, MicrophoneService } from '../microphone/microphone.service';
import { VOICE_STREAM_CONFIG } from './voice-stream.types'; 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. */ /** One PCM16 frame (config.inputSampleRate, config.frameMs). Runs outside Angular's zone. */
onFrame(pcm: ArrayBuffer, rms: number): void; onFrame(pcm: ArrayBuffer, rms: number): void;
/** The playback buffer ran dry (or `flushPlayback()` found it empty). */ /** The playback buffer ran dry (or `flushPlayback()` found it empty). */
onPlaybackIdle(): void; onPlaybackIdle(audioRef?: string | null): void;
/** The microphone track ended unexpectedly. */ /** The microphone track ended unexpectedly. */
onMicEnded(): void; onMicEnded(): void;
/** /**
@@ -87,6 +87,16 @@ export class VoiceAudioEngine {
// differs. Never assume the requested rate (SKILLS.md §3.2). // differs. Never assume the requested rate (SKILLS.md §3.2).
const ctx = new AudioContext({ latencyHint: 'interactive', sampleRate: cfg.outputSampleRate }); const ctx = new AudioContext({ latencyHint: 'interactive', sampleRate: cfg.outputSampleRate });
this.ctx = ctx; 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 // Explicitly reject an unusable context rate: a 0/NaN/non-finite rate cannot resample
// and must fail safely instead of silently producing no playback. // 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 }>) => { 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; this.inputRms = event.data.rms;
handlers.onFrame(event.data.pcm, event.data.rms); handlers.onFrame(event.data.pcm, event.data.rms);
}; };
@@ -127,22 +147,32 @@ export class VoiceAudioEngine {
outputChannelCount: [1], outputChannelCount: [1],
}); });
this.playback.port.onmessage = ( 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) { switch (event.data?.type) {
case 'idle': case 'idle':
handlers.onPlaybackIdle(); handlers.onPlaybackIdle(event.data.audioRef);
break; break;
case 'progress': 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) { if (event.data.audioRef) {
handlers.onPlaybackProgress(event.data.audioRef, event.data.playedMs ?? 0); handlers.onPlaybackProgress(event.data.audioRef, event.data.playedMs ?? 0);
} }
break; 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': case 'overflow':
handlers.onPlaybackOverflow(); handlers.onPlaybackOverflow();
break; 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 = ctx.createAnalyser();
this.analyser.fftSize = 1024; this.analyser.fftSize = 1024;
this.analyser.smoothingTimeConstant = 0.6; this.analyser.smoothingTimeConstant = 0.6;
@@ -185,8 +215,8 @@ export class VoiceAudioEngine {
} }
/** End of turn: play the remaining audio, then report idle. */ /** End of turn: play the remaining audio, then report idle. */
flushPlayback(): void { flushPlayback(audioRef?: string | null): void {
this.playback?.port.postMessage({ type: 'flush' }); this.playback?.port.postMessage({ type: 'flush', audioRef });
} }
// ---- mic / meters ---------------------------------------------------------- // ---- mic / meters ----------------------------------------------------------
@@ -215,8 +245,14 @@ export class VoiceAudioEngine {
// ---- cleanup --------------------------------------------------------------- // ---- cleanup ---------------------------------------------------------------
stop(): void { stop(): void {
if (this.capture) this.capture.port.onmessage = null; if (this.capture) {
if (this.playback) this.playback.port.onmessage = null; 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.source?.disconnect();
this.capture?.disconnect(); this.capture?.disconnect();
@@ -0,0 +1,152 @@
import { DOCUMENT } from '@angular/common';
import { Injectable, inject } from '@angular/core';
export type VoiceCueKind = 'ready' | 'end';
const CUE_ASSETS: Record<VoiceCueKind, string> = {
ready: 'assets/audio/voice-ready.wav',
end: 'assets/audio/voice-end.wav',
};
/**
* Plays the short reference cues extracted from the supplied recording.
*
* Unlike the previous synthesized version, this service plays the original
* recorded waveform. Do not add a convolver/reverb to it: the reference cue
* already contains its original tone and tail.
*/
@Injectable({ providedIn: 'root' })
export class VoiceCueService {
private readonly document = inject(DOCUMENT);
private ctx: AudioContext | null = null;
private readonly buffers = new Map<VoiceCueKind, AudioBuffer>();
private readonly pending = new Map<VoiceCueKind, Promise<AudioBuffer | null>>();
private enabled = true;
/** Disable or enable subsequent cues. */
setEnabled(on: boolean): void {
this.enabled = on;
}
/**
* Optional warm-up. Call once when the voice UI/component initializes,
* so fetching and decoding do not delay the first cue.
*/
async preload(): Promise<void> {
if (typeof AudioContext === 'undefined' || typeof fetch === 'undefined') {
return;
}
try {
const ctx = this.ensureContext();
await Promise.all([this.loadBuffer('ready', ctx), this.loadBuffer('end', ctx)]);
} catch {
// Preloading is best-effort; audio must never block the voice UI.
}
}
/** Play the recorded cue when the voice session is ready. */
playReady(): void {
void this.play('ready');
}
/** Play the recorded cue when the voice session ends. */
playEnd(): void {
void this.play('end');
}
private async play(kind: VoiceCueKind): Promise<void> {
if (!this.enabled || typeof AudioContext === 'undefined') {
return;
}
try {
const ctx = this.ensureContext();
// Request resume immediately, before awaiting fetch/decode, to preserve
// browser user activation when the call originates from a user gesture.
const resumePromise =
ctx.state === 'suspended' ? ctx.resume().catch(() => undefined) : Promise.resolve();
const bufferPromise = this.loadBuffer(kind, ctx);
const [buffer] = await Promise.all([bufferPromise, resumePromise]);
if (!buffer || ctx.state !== 'running') {
return;
}
const source = ctx.createBufferSource();
const output = ctx.createGain();
source.buffer = buffer;
output.gain.setValueAtTime(1, ctx.currentTime);
source.connect(output);
output.connect(ctx.destination);
source.onended = () => {
source.disconnect();
output.disconnect();
};
// A tiny scheduling lead avoids starting mid-render quantum.
source.start(ctx.currentTime + 0.01);
} catch {
// A cue is optional; never let audio playback break session handling.
}
}
private ensureContext(): AudioContext {
if (!this.ctx || this.ctx.state === 'closed') {
this.ctx = new AudioContext({ latencyHint: 'interactive' });
// AudioBuffers are decoded against a particular context. Rebuild them
// when that context is recreated.
this.buffers.clear();
this.pending.clear();
}
return this.ctx;
}
private loadBuffer(kind: VoiceCueKind, ctx: AudioContext): Promise<AudioBuffer | null> {
const cached = this.buffers.get(kind);
if (cached) {
return Promise.resolve(cached);
}
const inFlight = this.pending.get(kind);
if (inFlight) {
return inFlight;
}
const assetUrl = new URL(CUE_ASSETS[kind], this.document.baseURI).href;
const promise = fetch(assetUrl, { cache: 'force-cache' })
.then((response) => {
if (!response.ok) {
throw new Error(`Unable to load voice cue: ${response.status}`);
}
return response.arrayBuffer();
})
.then((bytes) => ctx.decodeAudioData(bytes))
.then((buffer) => {
if (this.ctx === ctx) {
this.buffers.set(kind, buffer);
}
return buffer;
})
.catch(() => {
// Let a later call retry if the asset was temporarily unavailable.
if (this.ctx === ctx) {
this.pending.delete(kind);
}
return null;
});
this.pending.set(kind, promise);
return promise;
}
}
@@ -0,0 +1,211 @@
import { describe, expect, it } from 'vitest';
import {
ANSWER_LIMITED_REASONS,
TRANSCRIPT_STATUSES,
VOICE_SERVER_EVENT_TYPES,
isApplicationReference,
parseVoiceServerEvent,
} from './voice-event.validator';
import { VoiceServerEvent } from './voice-stream.types';
const ANSWER_LIMITED: VoiceServerEvent = {
type: 'answer_limited',
turn_ref: 'live-turn-1',
reason: 'output_token_limit',
};
describe('voice-event.validator', () => {
describe('application references', () => {
it('accepts a non-empty bounded string reference', () => {
expect(isApplicationReference('live-turn-1')).toBe(true);
expect(isApplicationReference('a'.repeat(256))).toBe(true);
});
it('rejects missing, empty, wrong-typed or oversized references', () => {
expect(isApplicationReference('')).toBe(false);
expect(isApplicationReference(null)).toBe(false);
expect(isApplicationReference(undefined)).toBe(false);
expect(isApplicationReference(42)).toBe(false);
expect(isApplicationReference({})).toBe(false);
expect(isApplicationReference('a'.repeat(257))).toBe(false);
});
});
describe('answer_limited frames', () => {
it('parses a valid answer_limited frame and reaches the dispatcher shape', () => {
expect(parseVoiceServerEvent(JSON.stringify(ANSWER_LIMITED))).toEqual(ANSWER_LIMITED);
});
it('rejects an unknown reason (exactly output_token_limit is accepted)', () => {
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();
});
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();
});
it('only advertises the contract reason and statuses', () => {
expect(ANSWER_LIMITED_REASONS).toEqual(['output_token_limit']);
expect(TRANSCRIPT_STATUSES).toEqual(['partial', 'completed', 'interrupted', 'limited']);
});
});
describe('transcript frames', () => {
it('accepts a limited assistant transcript', () => {
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',
};
expect(parseVoiceServerEvent(JSON.stringify(frame))).toBeNull();
});
it('accepts the existing (older backend) transcript statuses for both roles', () => {
for (const status of ['partial', 'completed', 'interrupted'] as const) {
for (const role of ['user', 'assistant'] as const) {
const frame = { type: 'transcript', turn_ref: 't1', role, text: 'متن', status };
expect(parseVoiceServerEvent(JSON.stringify(frame))).toEqual(frame);
}
}
});
it('rejects unknown statuses and malformed transcript fields', () => {
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();
});
});
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[] = [
{
type: 'session_ready',
session_id: 'ses-1',
input_audio: { encoding: 'pcm_s16le', sample_rate: 24000, channels: 1 },
output_audio: { encoding: 'pcm_s16le', sample_rate: 24000, channels: 1 },
},
{ type: 'user_speech_started', turn_ref: 'turn-1' },
{ type: 'transcript', turn_ref: 'turn-1', role: 'user', text: 'سلام', status: 'completed' },
{
type: 'sources',
turn_ref: 'turn-1',
sources: [
{ source_ref: 'src-1', document_id: 'doc-1', chunk_id: 'chunk-1', title: 'سند' },
],
},
{ type: 'audio_started', audio_ref: 'aud-1', turn_ref: 'turn-1' },
{ type: 'audio_ended', audio_ref: 'aud-1', turn_ref: 'turn-1' },
{ type: 'turn_interrupted', turn_ref: 'turn-1', cancelled_tool_call_ids: [] },
{
type: 'error',
turn_ref: 'turn-1',
error: { code: 'SEARCH_TIMEOUT', message: 'دیر شد', retryable: true },
},
];
for (const frame of frames) {
expect(parseVoiceServerEvent(JSON.stringify(frame))).toEqual(frame);
}
// The enforced allowlist: every type the transport accepts, and nothing else.
expect(VOICE_SERVER_EVENT_TYPES).toEqual([
'session_ready',
'user_speech_started',
'transcript',
'sources',
'audio_started',
'audio_ended',
'turn_interrupted',
'answer_limited',
'error',
]);
});
it('defaults a missing error retryable flag to false instead of dropping the frame', () => {
const parsed = parseVoiceServerEvent('{"type":"error","error":{"code":"X","message":"y"}}');
expect(parsed).toEqual({
type: 'error',
error: { code: 'X', message: 'y', retryable: false },
});
});
});
describe('allowlist and malformed input', () => {
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":42}')).toBeNull();
});
it('drops malformed JSON and non-object payloads', () => {
expect(parseVoiceServerEvent('not json')).toBeNull();
expect(parseVoiceServerEvent('')).toBeNull();
expect(parseVoiceServerEvent('null')).toBeNull();
expect(parseVoiceServerEvent('[]')).toBeNull();
expect(parseVoiceServerEvent('"transcript"')).toBeNull();
});
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":"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();
});
});
});
@@ -0,0 +1,183 @@
import {
AnswerLimitedReason,
TranscriptStatus,
VoiceServerEvent,
VoiceServerEventType,
} from './voice-stream.types';
/**
* Runtime guards for the JSON frames that arrive on the voice stream.
*
* The transport used to hand every parsed object straight to the service. A frame with
* an unknown `type` then fell through the dispatcher silently, and a frame with a
* broken payload reached a handler that reads its fields. Every JSON frame now passes
* this explicit allowlist first: known types are checked field by field, unknown types
* and malformed payloads are DROPPED — never thrown, never re-interpreted, and never
* able to end a call. Dropping matches how malformed JSON was already treated, so no
* malformed frame can enter an error path or trigger cleanup.
*
* The guards mirror the contract in `VoiceServerEvent`; they do not invent protocol.
*/
export const VOICE_SERVER_EVENT_TYPES = [
'session_ready',
'user_speech_started',
'transcript',
'sources',
'audio_started',
'audio_ended',
'turn_interrupted',
'answer_limited',
'error',
] as const;
export const ANSWER_LIMITED_REASONS = ['output_token_limit'] as const;
export const TRANSCRIPT_STATUSES = ['partial', 'completed', 'interrupted', 'limited'] as const;
/**
* Compile-time alignment between the allowlists above and the wire unions in
* `voice-stream.types.ts`: a union member missing from an allowlist (or an allowlisted
* value with no union member) fails to compile here, so the transport can never
* silently start dropping a valid frame after a contract change.
*/
type Exactly<T extends true> = T;
export type AllowlistsAligned = [
Exactly<VoiceServerEventType extends (typeof VOICE_SERVER_EVENT_TYPES)[number] ? true : false>,
Exactly<(typeof VOICE_SERVER_EVENT_TYPES)[number] extends VoiceServerEventType ? true : false>,
Exactly<TranscriptStatus extends (typeof TRANSCRIPT_STATUSES)[number] ? true : false>,
Exactly<(typeof TRANSCRIPT_STATUSES)[number] extends TranscriptStatus ? true : false>,
Exactly<AnswerLimitedReason extends (typeof ANSWER_LIMITED_REASONS)[number] ? true : false>,
Exactly<(typeof ANSWER_LIMITED_REASONS)[number] extends AnswerLimitedReason ? true : false>,
];
/** Longest application reference accepted on the wire (session/turn/audio ids). */
const MAX_REFERENCE_LENGTH = 256;
/**
* An application reference issued by the backend (`session_id`, `turn_ref`, `audio_ref`,
* `source_ref`, …): a non-empty, length-bounded string. Anything else (number, null,
* empty string, oversized string) is not a reference and cannot correlate a frame.
*/
export function isApplicationReference(value: unknown): value is string {
return typeof value === 'string' && value.length > 0 && value.length <= MAX_REFERENCE_LENGTH;
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
function isAudioFormat(value: unknown): boolean {
return (
isRecord(value) &&
typeof value['encoding'] === 'string' &&
typeof value['sample_rate'] === 'number' &&
typeof value['channels'] === 'number'
);
}
/** Only the fields the client actually reads are required; presentation is tolerant. */
function isVoiceSource(value: unknown): boolean {
return (
isRecord(value) &&
isApplicationReference(value['source_ref']) &&
isApplicationReference(value['chunk_id'])
);
}
function isVoiceServerEvent(value: unknown): value is VoiceServerEvent {
if (!isRecord(value)) return false;
// Allowlist: an unknown event type is dropped, never forwarded.
if (!VOICE_SERVER_EVENT_TYPES.includes(value['type'] as VoiceServerEventType)) return false;
switch (value['type']) {
case 'session_ready':
return (
isApplicationReference(value['session_id']) &&
isAudioFormat(value['input_audio']) &&
isAudioFormat(value['output_audio'])
);
case 'user_speech_started':
return isApplicationReference(value['turn_ref']);
case 'transcript':
return (
isApplicationReference(value['turn_ref']) &&
(value['role'] === 'user' || value['role'] === 'assistant') &&
typeof value['text'] === 'string' &&
TRANSCRIPT_STATUSES.includes(value['status'] as TranscriptStatus) &&
// `limited` is valid only for assistant transcripts.
(value['status'] !== 'limited' || value['role'] === 'assistant')
);
case 'sources':
return (
isApplicationReference(value['turn_ref']) &&
Array.isArray(value['sources']) &&
value['sources'].every(isVoiceSource)
);
case 'audio_started':
case 'audio_ended':
return (
isApplicationReference(value['audio_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':
return (
isApplicationReference(value['turn_ref']) &&
(value['cancelled_tool_call_ids'] === undefined ||
(Array.isArray(value['cancelled_tool_call_ids']) &&
value['cancelled_tool_call_ids'].every(isApplicationReference)))
);
case 'answer_limited':
return (
isApplicationReference(value['turn_ref']) &&
ANSWER_LIMITED_REASONS.includes(value['reason'] as AnswerLimitedReason)
);
case 'error':
return (
isRecord(value['error']) &&
typeof value['error']['code'] === 'string' &&
typeof value['error']['message'] === 'string' &&
(value['error']['retryable'] === undefined ||
typeof value['error']['retryable'] === 'boolean') &&
(value['turn_ref'] === undefined || isApplicationReference(value['turn_ref'])) &&
(value['audio_ref'] === undefined || isApplicationReference(value['audio_ref']))
);
default:
// Defense in depth: unreachable while the allowlist above matches this switch,
// and it keeps a newly modeled-but-unhandled type from reaching the service.
return false;
}
}
/**
* Parse one JSON control frame from the wire.
*
* Returns the validated event, or `null` when the frame is malformed JSON, an unknown
* event type, or a known type with an invalid payload. A `null` result is dropped by
* the transport exactly like malformed JSON always was — it is not an error state.
*/
export function parseVoiceServerEvent(raw: string): VoiceServerEvent | null {
let parsed: unknown;
try {
parsed = JSON.parse(raw);
} catch {
return null;
}
if (!isVoiceServerEvent(parsed)) return null;
if (parsed.type === 'error' && parsed.error.retryable === undefined) {
// A frame without the flag behaves like a non-retryable error, which is what the
// service's boolean read produced before validation existed.
return { ...parsed, error: { ...parsed.error, retryable: false } };
}
return parsed;
}
@@ -10,7 +10,11 @@ import { VoiceStreamService } from './voice-stream.service';
import { VOICE_TRANSPORT_FACTORY, VoiceTransport, VoiceTransportHandlers } from './voice-transport'; import { VOICE_TRANSPORT_FACTORY, VoiceTransport, VoiceTransportHandlers } from './voice-transport';
import { PlaybackProgressMessage, VoiceServerEvent } from './voice-stream.types'; 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 = { const CONFIG = {
revision: 1, revision: 1,
assistant_name: 'دستیار', assistant_name: 'دستیار',
@@ -34,7 +38,8 @@ const READY_EVENT: VoiceServerEvent = {
}; };
const OVERFLOW_MESSAGE = 'حجم صدای در حال پخش از محدودهٔ مجاز گذشت و گفتگو به‌طور ایمن پایان یافت.'; const OVERFLOW_MESSAGE = 'حجم صدای در حال پخش از محدودهٔ مجاز گذشت و گفتگو به‌طور ایمن پایان یافت.';
const SEND_OVERFLOW_MESSAGE = 'حجم صدای ارسالی از محدودهٔ مجاز گذشت و گفتگو به‌طور ایمن پایان یافت.'; const SEND_OVERFLOW_MESSAGE =
'حجم صدای ارسالی از محدودهٔ مجاز گذشت و گفتگو به‌طور ایمن پایان یافت.';
/** Flush pending microtasks/timers so the service reaches a stable await point. */ /** Flush pending microtasks/timers so the service reaches a stable await point. */
const flush = (): Promise<void> => new Promise((resolve) => setTimeout(resolve, 5)); 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)', () => { describe('VoiceStreamService (backend handoff contract)', () => {
let service: VoiceStreamService; let service: VoiceStreamService;
let api: { let api: {
providers: ReturnType<typeof vi.fn>;
me: ReturnType<typeof vi.fn>; me: ReturnType<typeof vi.fn>;
configuration: ReturnType<typeof vi.fn>; configuration: ReturnType<typeof vi.fn>;
createConversation: ReturnType<typeof vi.fn>; createConversation: ReturnType<typeof vi.fn>;
@@ -78,6 +84,10 @@ describe('VoiceStreamService (backend handoff contract)', () => {
engineClear = vi.fn(); engineClear = vi.fn();
api = { 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), me: vi.fn().mockResolvedValue(ME),
configuration: vi.fn().mockResolvedValue(CONFIG), configuration: vi.fn().mockResolvedValue(CONFIG),
createConversation: vi.fn().mockResolvedValue(CONVERSATION), createConversation: vi.fn().mockResolvedValue(CONVERSATION),
@@ -96,7 +106,9 @@ describe('VoiceStreamService (backend handoff contract)', () => {
return Promise.resolve(); return Promise.resolve();
}), }),
sendAudio: vi.fn(), sendAudio: vi.fn(),
sendControl: vi.fn().mockImplementation((message: PlaybackProgressMessage) => controls.push(message)), sendControl: vi
.fn()
.mockImplementation((message: PlaybackProgressMessage) => controls.push(message)),
close: vi.fn(), close: vi.fn(),
}; };
@@ -138,7 +150,9 @@ describe('VoiceStreamService (backend handoff contract)', () => {
} }
function firstEndedError(): Promise<string | undefined> { 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 () => { 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 }, output_audio: { encoding: 'pcm_s16le', sample_rate: 24000, channels: 1 },
}); });
const result = await started; 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 () => { 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 () => { it('reports the final real played progress when the turn is interrupted', async () => {
await startConnected(); 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' }); transportHandlers?.onEvent({ type: 'audio_started', audio_ref: 'aud-2' });
engineHandlers?.onPlaybackProgress('aud-2', 300); engineHandlers?.onPlaybackProgress('aud-2', 300);
controls = []; controls = [];
@@ -235,9 +259,7 @@ describe('VoiceStreamService (backend handoff contract)', () => {
// The worklet answers `clear` with its final cumulative report for the ref. // The worklet answers `clear` with its final cumulative report for the ref.
engineHandlers?.onPlaybackProgress('aud-2', 780); engineHandlers?.onPlaybackProgress('aud-2', 780);
expect(controls).toEqual([ expect(controls).toEqual([{ type: 'playback_progress', audio_ref: 'aud-2', played_ms: 780 }]);
{ type: 'playback_progress', audio_ref: 'aud-2', played_ms: 780 },
]);
expect(service.messages().find((m) => m.id === 'turn-1:assistant')?.interrupted).toBe(true); 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); 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 () => { it('drains on audio_ended so the ref reaches its true final progress (not solely on transcript)', async () => {
await startConnected(); await startConnected();
transportHandlers?.onEvent({ type: 'audio_started', audio_ref: 'aud-1' }); 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' }); transportHandlers?.onEvent({ type: 'audio_ended', audio_ref: 'aud-1' });
expect(engineFlush).toHaveBeenCalledTimes(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({ transportHandlers?.onEvent({
type: 'transcript', type: 'transcript',
turn_ref: 'turn-1', turn_ref: 'turn-1',
@@ -343,7 +415,7 @@ describe('VoiceStreamService (backend handoff contract)', () => {
text: '…', text: '…',
status: 'completed', status: 'completed',
}); });
expect(engineFlush).toHaveBeenCalledTimes(2); expect(engineFlush).toHaveBeenCalledTimes(1);
}); });
it('requires a fresh conversation after CONTEXT_REVOKED and drops the old attempt', async () => { 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 }, 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(sessionStorage.getItem('voice_creation_attempt')).toBeNull();
expect(service.connection()).toBe('disconnected'); expect(service.connection()).toBe('disconnected');
}); });
@@ -398,9 +472,27 @@ describe('VoiceStreamService (backend handoff contract)', () => {
it('marks partial then completed transcripts final', async () => { it('marks partial then completed transcripts final', async () => {
await startConnected(); await startConnected();
transportHandlers?.onEvent({ type: 'transcript', turn_ref: 't1', role: 'assistant', text: 'سلام', status: 'partial' }); transportHandlers?.onEvent({
transportHandlers?.onEvent({ type: 'transcript', turn_ref: 't1', role: 'assistant', text: 'سلام و خوب', status: 'partial' }); type: 'transcript',
transportHandlers?.onEvent({ type: 'transcript', turn_ref: 't1', role: 'assistant', text: 'سلام و خوب', status: 'completed' }); 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'); const assistant = service.messages().find((m) => m.id === 't1:assistant');
expect(assistant?.text).toBe('سلام و خوب'); expect(assistant?.text).toBe('سلام و خوب');
@@ -411,8 +503,20 @@ describe('VoiceStreamService (backend handoff contract)', () => {
await startConnected(); await startConnected();
// The server streams assistant partials before the user transcript for the same turn. // 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({
transportHandlers?.onEvent({ type: 'transcript', turn_ref: 'turn-1', role: 'user', text: 'سلام', status: 'completed' }); 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 list = service.messages();
const userIndex = list.findIndex((m) => m.id === 'turn-1:user'); 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 () => { it('keeps user→assistant order and stable turn order across turns', async () => {
await startConnected(); await startConnected();
transportHandlers?.onEvent({ type: 'transcript', turn_ref: 't1', role: 'user', text: 'سوال ۱', status: 'completed' }); transportHandlers?.onEvent({
transportHandlers?.onEvent({ type: 'transcript', turn_ref: 't1', role: 'assistant', text: 'پاسخ ۱', status: 'completed' }); 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 // turn 2's assistant lands before its user transcript
transportHandlers?.onEvent({ type: 'transcript', turn_ref: 't2', role: 'assistant', text: 'پاسخ ۲', status: 'partial' }); transportHandlers?.onEvent({
transportHandlers?.onEvent({ type: 'transcript', turn_ref: 't2', role: 'user', text: 'سوال ۲', status: 'completed' }); 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([ expect(service.messages().map((m) => m.id)).toEqual([
't1:user', 't1:user',
@@ -445,9 +573,17 @@ describe('VoiceStreamService (backend handoff contract)', () => {
transportHandlers?.onEvent({ transportHandlers?.onEvent({
type: 'sources', type: 'sources',
turn_ref: 't1', 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']); expect(service.messages().map((m) => m.id)).toEqual(['t1:user', 't1:assistant']);
}); });
@@ -460,4 +596,525 @@ describe('VoiceStreamService (backend handoff contract)', () => {
expect(sessionStorage.getItem('voice_creation_attempt')).toBeNull(); expect(sessionStorage.getItem('voice_creation_attempt')).toBeNull();
expect(service.connection()).toBe('disconnected'); expect(service.connection()).toBe('disconnected');
}); });
describe('bounded answers (answer_limited)', () => {
const MARKER: VoiceServerEvent = {
type: 'answer_limited',
turn_ref: 'turn-1',
reason: 'output_token_limit',
};
it('keeps the marker as bounded metadata when it arrives before any transcript text', async () => {
await startConnected();
transportHandlers?.onEvent(MARKER);
// No transcript text is invented for the answer.
expect(service.messages()).toEqual([]);
expect(service.connection()).toBe('connected');
expect(service.state()).toBe('LISTENING');
});
it('attaches the marker to the row when the first transcript lands after it', async () => {
await startConnected();
transportHandlers?.onEvent(MARKER); // marker first, no text yet
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: 'limited',
});
const assistant = service.messages().find((m) => m.id === 'turn-1:assistant');
expect(assistant?.text).toBe('پاسخ نهایی'); // final snapshot replaces the partial text
expect(assistant?.limited).toBe(true);
expect(assistant?.final).toBe(true);
});
it('keeps exact text and limited status when the limited transcript arrives before the marker', async () => {
await startConnected();
transportHandlers?.onEvent({
type: 'transcript',
turn_ref: 'turn-1',
role: 'assistant',
text: 'پاسخ کامل',
status: 'limited',
});
expect(service.messages()[0].limited).toBe(true); // the transcript alone marks the answer
transportHandlers?.onEvent(MARKER);
const assistant = service.messages().find((m) => m.id === 'turn-1:assistant');
expect(assistant?.text).toBe('پاسخ کامل');
expect(assistant?.limited).toBe(true);
});
it('treats repeated answer_limited markers as idempotent (no duplicate rows or notices)', async () => {
await startConnected();
transportHandlers?.onEvent({
type: 'transcript',
turn_ref: 'turn-1',
role: 'assistant',
text: 'پاسخ',
status: 'limited',
});
const before = service.messages();
transportHandlers?.onEvent(MARKER);
transportHandlers?.onEvent(MARKER);
transportHandlers?.onEvent(MARKER);
expect(service.messages()).toHaveLength(1);
expect(service.messages()).toBe(before); // no state write at all → no re-announcement
expect(service.messages()[0].text).toBe('پاسخ');
expect(service.streamError()).toBeNull(); // informational, never an error banner
expect(service.connection()).toBe('connected');
});
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',
});
expect(service.messages()[0].text).toBe('بله بله بله');
});
it('does not downgrade a limited answer on delayed completed/partial events', async () => {
await startConnected();
transportHandlers?.onEvent({
type: 'transcript',
turn_ref: 't1',
role: 'assistant',
text: 'پاسخ محدود',
status: 'limited',
});
// Delayed frames for the same turn arrive after the final snapshot.
transportHandlers?.onEvent({
type: 'transcript',
turn_ref: 't1',
role: 'assistant',
text: 'پاسخ کامل‌تر',
status: 'completed',
});
transportHandlers?.onEvent({
type: 'transcript',
turn_ref: 't1',
role: 'assistant',
text: ' ادامه',
status: 'partial',
});
const assistant = service.messages().find((m) => m.id === 't1:assistant');
expect(assistant?.limited).toBe(true); // never reverts to completed/partial
expect(assistant?.final).toBe(true);
expect(assistant?.text).toBe('پاسخ کامل‌تر'); // the late partial did not extend it
});
it('lets turn_interrupted take precedence over limited and blocks late text', 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: 'limited',
});
transportHandlers?.onEvent(MARKER);
engineClear.mockClear();
transportHandlers?.onEvent({ type: 'turn_interrupted', turn_ref: 'turn-1' });
const assistant = service.messages().find((m) => m.id === 'turn-1:assistant');
expect(assistant?.interrupted).toBe(true); // interruption wins over the limited state
expect(engineClear).toHaveBeenCalledTimes(1); // the existing barge-in flush still runs
// Late assistant text cannot restore the interrupted answer.
transportHandlers?.onEvent({
type: 'transcript',
turn_ref: 'turn-1',
role: 'assistant',
text: 'متن دیرکرده',
status: 'limited',
});
transportHandlers?.onEvent({
type: 'transcript',
turn_ref: 'turn-1',
role: 'assistant',
text: 'ادامه',
status: 'partial',
});
const after = service.messages().find((m) => m.id === 'turn-1:assistant');
expect(after?.text).toBe('پاسخ نهایی');
expect(after?.interrupted).toBe(true);
});
it('does not mark an already interrupted answer as limited', async () => {
await startConnected();
transportHandlers?.onEvent({
type: 'transcript',
turn_ref: 'turn-1',
role: 'assistant',
text: 'پاسخ',
status: 'partial',
});
transportHandlers?.onEvent({ type: 'turn_interrupted', turn_ref: 'turn-1' });
transportHandlers?.onEvent(MARKER);
const assistant = service.messages().find((m) => m.id === 'turn-1:assistant');
expect(assistant?.interrupted).toBe(true);
expect(assistant?.limited).toBeFalsy();
});
it('does not mark a sources-only row of an interrupted turn as limited', async () => {
await startConnected();
// The turn is capped, then cut off before any transcript row exists, then its
// sources arrive: the row must not be presented as a limited answer.
transportHandlers?.onEvent(MARKER);
transportHandlers?.onEvent({ type: 'turn_interrupted', turn_ref: 'turn-1' });
transportHandlers?.onEvent({
type: 'sources',
turn_ref: 'turn-1',
sources: [{ source_ref: 'src-1', document_id: 'doc-1', chunk_id: 'chunk-1', title: 'سند' }],
});
const assistant = service.messages().find((m) => m.id === 'turn-1:assistant');
expect(assistant?.limited).toBeFalsy();
expect(assistant?.sources).toHaveLength(1);
});
it('keeps a delayed user transcript attached to its own turn, independent of assistant status', async () => {
await startConnected();
transportHandlers?.onEvent({ type: 'user_speech_started', turn_ref: 'turn-1' });
transportHandlers?.onEvent({
type: 'transcript',
turn_ref: 'turn-1',
role: 'assistant',
text: 'پاسخ اول',
status: 'limited',
});
// Turn 2 starts before turn 1's user transcript is finalized.
transportHandlers?.onEvent({ type: 'user_speech_started', turn_ref: 'turn-2' });
transportHandlers?.onEvent({
type: 'transcript',
turn_ref: 'turn-2',
role: 'assistant',
text: 'پاسخ دوم',
status: 'partial',
});
transportHandlers?.onEvent({
type: 'transcript',
turn_ref: 'turn-1',
role: 'user',
text: 'سوال اول',
status: 'completed',
});
const list = service.messages();
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);
expect(list.find((m) => m.id === 'turn-2:assistant')?.limited).toBeFalsy();
});
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',
});
await service.close();
await startConnected(); // session B
transportHandlers?.onEvent({
type: 'transcript',
turn_ref: 'shared-turn',
role: 'assistant',
text: 'پاسخ تازه',
status: 'partial',
});
const assistant = service.messages().find((m) => m.id === 'shared-turn:assistant');
expect(assistant?.text).toBe('پاسخ تازه');
expect(assistant?.limited).toBeFalsy(); // session A's metadata did not leak
});
it('does not stop capture, close the socket, flush audio or reset playback progress', async () => {
await startConnected();
transportHandlers?.onEvent({ type: 'audio_started', audio_ref: 'aud-1' });
engineHandlers?.onPlaybackProgress('aud-1', 120);
controls = [];
engineFlush.mockClear();
engineClear.mockClear();
engineStop.mockClear();
transportMock.close.mockClear();
transportHandlers?.onEvent(MARKER);
transportHandlers?.onEvent({
type: 'transcript',
turn_ref: 'turn-1',
role: 'assistant',
text: 'پاسخ',
status: 'limited',
});
expect(engineFlush).not.toHaveBeenCalled(); // no flush/mute of playback
expect(engineClear).not.toHaveBeenCalled();
expect(engineStop).not.toHaveBeenCalled(); // microphone keeps capturing
expect(transportMock.close).not.toHaveBeenCalled(); // socket stays open
expect(api.closeVoiceSession).not.toHaveBeenCalled(); // no backend close request
expect(service.connection()).toBe('connected');
expect(service.state()).toBe('LISTENING');
// Capture keeps flowing and playback progress keeps being reported.
engineHandlers?.onFrame(new ArrayBuffer(9600), 0.5);
expect(transportMock.sendAudio).toHaveBeenCalledTimes(1);
engineHandlers?.onPlaybackProgress('aud-1', 300);
expect(controls).toEqual([{ type: 'playback_progress', audio_ref: 'aud-1', played_ms: 300 }]);
});
it('keeps buffered audio playing after the marker; audio_ended only seals generation', async () => {
await startConnected();
transportHandlers?.onEvent({ type: 'audio_started', audio_ref: 'aud-1' });
transportHandlers?.onAudio(new ArrayBuffer(9600)); // real binary audio
expect(service.state()).toBe('SPEAKING');
engineHandlers?.onPlaybackProgress('aud-1', 100);
controls = [];
engineFlush.mockClear();
transportHandlers?.onEvent(MARKER);
// Still playing: state unchanged, no flush, no clear, audio keeps arriving.
expect(service.state()).toBe('SPEAKING');
expect(engineFlush).not.toHaveBeenCalled();
expect(engineClear).not.toHaveBeenCalled();
transportHandlers?.onAudio(new ArrayBuffer(9600));
expect(engineStop).not.toHaveBeenCalled();
// audio_ended seals GENERATION (drain) — it is not actual playback completion:
// progress keeps being reported from what the worklet really plays.
transportHandlers?.onEvent({ type: 'audio_ended', audio_ref: 'aud-1' });
expect(engineFlush).toHaveBeenCalledTimes(1);
expect(service.state()).toBe('SPEAKING');
engineHandlers?.onPlaybackProgress('aud-1', 400);
expect(controls).toEqual([{ type: 'playback_progress', audio_ref: 'aud-1', played_ms: 400 }]);
// The turn only finishes when playback actually drains.
vi.useFakeTimers();
try {
engineHandlers?.onPlaybackIdle();
vi.advanceTimersByTime(900); // no completed transcript for this limited turn → settle
} finally {
vi.useRealTimers();
}
expect(service.state()).toBe('LISTENING');
});
it('does not leave the UI thinking when a limited answer produces no audio', async () => {
await startConnected();
transportHandlers?.onEvent({
type: 'transcript',
turn_ref: 'turn-1',
role: 'user',
text: 'سوال',
status: 'completed',
});
expect(service.state()).toBe('PROCESSING');
// The marker lands while no audio is outstanding at all.
vi.useFakeTimers();
try {
transportHandlers?.onEvent(MARKER);
vi.advanceTimersByTime(900); // the bounded settle fallback
} finally {
vi.useRealTimers();
}
expect(service.state()).toBe('LISTENING'); // usable again, session alive
expect(service.connection()).toBe('connected');
// The user can immediately speak a genuine continuation ("ادامه بده").
engineHandlers?.onFrame(new ArrayBuffer(9600), 0.5);
expect(transportMock.sendAudio).toHaveBeenCalledTimes(1);
});
it('reports the real final played progress when a limited answer is interrupted', async () => {
await startConnected();
transportHandlers?.onEvent({
type: 'transcript',
turn_ref: 'turn-1',
role: 'assistant',
text: 'پاسخ',
status: 'limited',
});
transportHandlers?.onEvent({ type: 'audio_started', audio_ref: 'aud-2' });
engineHandlers?.onPlaybackProgress('aud-2', 300);
controls = [];
transportHandlers?.onEvent({ type: 'turn_interrupted', turn_ref: 'turn-1' });
// 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 }]);
});
it('never auto-continues, fabricates a control message or recreates the session', async () => {
await startConnected();
controls = [];
transportHandlers?.onEvent(MARKER);
expect(controls).toEqual([]); // no continue/resume/response.create text command
expect(api.createVoiceSession).toHaveBeenCalledTimes(1); // no second reservation
expect(transportMock.connect).toHaveBeenCalledTimes(1); // no second socket
expect(api.closeVoiceSession).not.toHaveBeenCalled(); // no close request either
expect(service.connection()).toBe('connected'); // the session stays usable
});
it('still fails safely on a genuine error frame after a limited answer', async () => {
await startConnected();
const ended = firstEndedError();
transportHandlers?.onEvent(MARKER);
transportHandlers?.onEvent({
type: 'error',
error: { code: 'LIVE_BUFFER_OVERFLOW', message: 'overflow', retryable: false },
});
expect(await ended).toBe('overflow'); // a fatal error is NOT reinterpreted as limited
expect(api.closeVoiceSession).toHaveBeenCalledTimes(1);
expect(service.connection()).toBe('disconnected');
});
it('still fails safely on a real playback overflow after a limited answer', async () => {
await startConnected();
const ended = firstEndedError();
transportHandlers?.onEvent(MARKER);
engineHandlers?.onPlaybackOverflow();
expect(await ended).toBe(OVERFLOW_MESSAGE);
expect(service.connection()).toBe('disconnected');
});
it('keeps the ordinary completed-answer flow of an older backend intact', async () => {
await startConnected();
transportHandlers?.onEvent({ type: 'audio_started', audio_ref: 'aud-1' });
transportHandlers?.onAudio(new ArrayBuffer(9600));
transportHandlers?.onEvent({
type: 'transcript',
turn_ref: 'turn-1',
role: 'assistant',
text: 'پاسخ کامل',
status: 'completed',
});
transportHandlers?.onEvent({ type: 'audio_ended', audio_ref: 'aud-1' });
const assistant = service.messages().find((m) => m.id === 'turn-1:assistant');
expect(assistant?.text).toBe('پاسخ کامل');
expect(assistant?.limited).toBeFalsy();
expect(assistant?.final).toBe(true);
expect(engineFlush).toHaveBeenCalledTimes(1);
engineHandlers?.onPlaybackIdle();
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,7 +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 { Subject } from 'rxjs';
import { MicrophoneError } from '../microphone/microphone.service'; import { MicrophoneError } from '../microphone/microphone.service';
import { VoiceApiError, VoiceApiService, VoiceSessionResponse } from './voice-api.service'; import { uuid } from '../../shared/utils/uuid';
import { VoiceApiError, VoiceApiService, VoiceSessionResponse, VoiceProvider, VoiceProviderOption } from './voice-api.service';
import { VoiceAudioEngine, VoiceEngineError } from './voice-audio-engine.service'; import { VoiceAudioEngine, VoiceEngineError } from './voice-audio-engine.service';
import { VOICE_TRANSPORT_FACTORY, VoiceTransport } from './voice-transport'; import { VOICE_TRANSPORT_FACTORY, VoiceTransport } from './voice-transport';
import { import {
@@ -12,6 +13,7 @@ import {
VoiceSessionEnd, VoiceSessionEnd,
VoiceStreamState, VoiceStreamState,
} from './voice-stream.types'; } from './voice-stream.types';
import { VoiceCueService } from './voice-cue.service';
export type VoiceStartFailure = export type VoiceStartFailure =
| 'cancelled' | 'cancelled'
@@ -25,8 +27,7 @@ export type VoiceStartFailure =
| 'overflow'; | 'overflow';
export type VoiceStartResult = export type VoiceStartResult =
| { ok: true } { ok: true } | { ok: false; reason: VoiceStartFailure; message: string };
| { ok: false; reason: VoiceStartFailure; message: string };
type TranscriptEvent = Extract<VoiceServerEvent, { type: 'transcript' }>; type TranscriptEvent = Extract<VoiceServerEvent, { type: 'transcript' }>;
type SourcesEvent = Extract<VoiceServerEvent, { type: 'sources' }>; type SourcesEvent = Extract<VoiceServerEvent, { type: 'sources' }>;
@@ -56,7 +57,8 @@ interface TeardownOptions {
} }
const MESSAGES = { const MESSAGES = {
unsupported: 'گفتگوی صوتی در این مرورگر پشتیبانی نمی‌شود (اتصال امن HTTPS و مرورگر جدید لازم است).', unsupported:
'گفتگوی صوتی در این مرورگر پشتیبانی نمی‌شود (اتصال امن HTTPS و مرورگر جدید لازم است).',
micDenied: 'دسترسی به میکروفون رد شد. اجازه‌ی دسترسی را در تنظیمات مرورگر فعال کنید.', micDenied: 'دسترسی به میکروفون رد شد. اجازه‌ی دسترسی را در تنظیمات مرورگر فعال کنید.',
micUnavailable: 'میکروفونی پیدا نشد یا در حال استفاده‌ی برنامه‌ی دیگری است.', micUnavailable: 'میکروفونی پیدا نشد یا در حال استفاده‌ی برنامه‌ی دیگری است.',
micLost: 'اتصال میکروفون قطع شد و گفتگو پایان یافت.', micLost: 'اتصال میکروفون قطع شد و گفتگو پایان یافت.',
@@ -86,13 +88,21 @@ const ERROR_BANNER_MS = 6000;
const FINAL_PROGRESS_WAIT_MS = 300; const FINAL_PROGRESS_WAIT_MS = 300;
/** Longest wait for V04 /close before releasing local resources anyway (the POST keeps running). */ /** Longest wait for V04 /close before releasing local resources anyway (the POST keeps running). */
const CLOSE_WAIT_MS = 3000; const CLOSE_WAIT_MS = 3000;
/**
* Bounded per-turn answer-state memory (turns the server marked `answer_limited`, and
* turns it interrupted). A marker can arrive before its transcript row exists, so the
* record must survive until the row lands — but a long call must not grow it forever,
* so the oldest entries are dropped past this cap.
*/
const TURN_STATE_MEMORY = 50;
/** /**
* One live voice call against the backend handoff contract (§7–§9): * One live voice call against the backend handoff contract (§7–§9):
* *
* mic ─▶ engine ─▶ PCM16 24 kHz frames ─▶ WSS ─▶ server * mic ─▶ engine ─▶ PCM16 24 kHz frames ─▶ WSS ─▶ server
* server ─▶ session_ready / user_speech_started / transcript / sources / * server ─▶ session_ready / user_speech_started / transcript / sources /
* audio_started / audio_ended / turn_interrupted / error (JSON) * audio_started / audio_ended / turn_interrupted / answer_limited /
* error (JSON)
* ─▶ PCM16 24 kHz audio (binary) ─▶ engine playback * ─▶ PCM16 24 kHz audio (binary) ─▶ engine playback
* client ─▶ playback_progress (the only JSON control message, cumulative played_ms) * client ─▶ playback_progress (the only JSON control message, cumulative played_ms)
* *
@@ -115,7 +125,12 @@ export class VoiceStreamService {
private readonly api = inject(VoiceApiService); private readonly api = inject(VoiceApiService);
private readonly config = inject(VOICE_STREAM_CONFIG); private readonly config = inject(VOICE_STREAM_CONFIG);
private readonly createTransport = inject(VOICE_TRANSPORT_FACTORY); 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 state = signal<VoiceStreamState>('IDLE');
readonly connection = signal<VoiceConnection>('disconnected'); readonly connection = signal<VoiceConnection>('disconnected');
readonly messages = signal<VoiceMessage[]>([]); readonly messages = signal<VoiceMessage[]>([]);
@@ -136,7 +151,8 @@ export class VoiceStreamService {
private cleanupPromise: Promise<void> | null = null; private cleanupPromise: Promise<void> | null = null;
private session = 0; private session = 0;
private streaming = false; 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 audioGenerationDone = false; // server finished sending this audio_ref's frames
private interruptTimer: ReturnType<typeof setTimeout> | null = null; private interruptTimer: ReturnType<typeof setTimeout> | null = null;
private settleTimer: ReturnType<typeof setTimeout> | null = null; private settleTimer: ReturnType<typeof setTimeout> | null = null;
@@ -153,10 +169,19 @@ export class VoiceStreamService {
/** Latest cumulative played_ms actually consumed by the worklet, per server audio_ref. */ /** Latest cumulative played_ms actually consumed by the worklet, per server audio_ref. */
private readonly playedMsByRef = new Map<string, number>(); private readonly playedMsByRef = new Map<string, number>();
private currentAudioRef: string | null = null; 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> = []; private progressWaiters: Array<() => void> = [];
/** Turns whose answer the server marked limited (bounded; marker may precede its row). */
private readonly limitedTurns = new Set<string>();
/** Turns the server interrupted (bounded; late assistant text must not restore them). */
private readonly interruptedTurns = new Set<string>();
constructor() { constructor() {
this.attempt = loadPersistedAttempt(); this.attempt = loadPersistedAttempt();
this.selectedProvider.set(this.attempt?.provider ?? null);
// A reload during a call leaves an un-reconciled reservation: reconcile with the // 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 // 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. // never auto-resumed — the user starts a fresh conversation explicitly.
@@ -168,11 +193,65 @@ export class VoiceStreamService {
// ---- public API ----------------------------------------------------------- // ---- 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> { 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.isOpen()) return this.failure('cancelled', '');
if (!this.isSupported) return this.failure('unsupported', MESSAGES.unsupported); if (!this.isSupported) return this.failure('unsupported', MESSAGES.unsupported);
const session = ++this.session; const session = ++this.session;
this.traceStarted = performance.now();
this.underrunStarted = null;
const stale = (): boolean => session !== this.session; const stale = (): boolean => session !== this.session;
this.messages.set([]); this.messages.set([]);
@@ -180,25 +259,31 @@ export class VoiceStreamService {
this.clearError(); this.clearError();
this.cleanupPromise = null; this.cleanupPromise = null;
this.resetTurnFlags(); this.resetTurnFlags();
// Per-session answer state: a new session can never inherit the previous one's
// limited/interrupted turn markers.
this.limitedTurns.clear();
this.interruptedTurns.clear();
this.lastConversationId = null; this.lastConversationId = null;
this.currentAudioRef = null; this.currentAudioRef = null;
this.playedMsByRef.clear(); this.playedMsByRef.clear();
this.seenAudioRefs.clear();
this.state.set('IDLE'); this.state.set('IDLE');
this.connection.set('connecting'); this.connection.set('connecting');
// Reuse a persisted attempt (ambiguous outcome of a previous try); otherwise create one. // 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); persistAttempt(this.attempt);
// 1) microphone + worklets (needs the user gesture; shows the permission prompt) // 1) microphone + worklets (needs the user gesture; shows the permission prompt)
try { try {
await this.engine.start({ await this.engine.start({
onFrame: (pcm) => this.onMicFrame(pcm), 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)), onMicEnded: () => this.ngZone.run(() => this.failSession(MESSAGES.micLost, session)),
onPlaybackProgress: (audioRef, playedMs) => onPlaybackProgress: (audioRef, playedMs) =>
this.ngZone.run(() => this.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) { } catch (err) {
return this.abortStart(session, this.mapEngineError(err)); return this.abortStart(session, this.mapEngineError(err));
@@ -214,7 +299,7 @@ export class VoiceStreamService {
const me = await this.api.me(); const me = await this.api.me();
if (stale()) return this.failure('cancelled', ''); 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 (stale()) return this.failure('cancelled', '');
if (!configuration.capabilities.voice) { if (!configuration.capabilities.voice) {
return this.abortStart(session, { reason: 'unavailable', message: MESSAGES.voiceDisabled }); return this.abortStart(session, { reason: 'unavailable', message: MESSAGES.voiceDisabled });
@@ -252,12 +337,17 @@ export class VoiceStreamService {
onEvent: (event) => this.ngZone.run(() => this.onServerEvent(event, session)), onEvent: (event) => this.ngZone.run(() => this.onServerEvent(event, session)),
onAudio: (chunk) => this.onServerAudio(chunk, session), onAudio: (chunk) => this.onServerAudio(chunk, session),
onClose: (info) => 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) => onOverflow: (which) =>
this.ngZone.run(() => this.ngZone.run(() =>
// Playback queue overflow and capture/send overflow are different faults with // Playback queue overflow and capture/send overflow are different faults with
// different causes; give each its own message instead of one shared string. // 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,
),
), ),
}), }),
); );
@@ -289,6 +379,8 @@ export class VoiceStreamService {
this.connection.set('connected'); this.connection.set('connected');
this.state.set('LISTENING'); this.state.set('LISTENING');
this.streaming = true; this.streaming = true;
// "You can speak now" — once per session, not per turn (a turn cue would be noise).
this.cues.playReady();
return { ok: true }; return { ok: true };
} }
@@ -340,7 +432,10 @@ export class VoiceStreamService {
if (this.isOpen() || this.attempt !== attempt) return true; if (this.isOpen() || this.attempt !== attempt) return true;
let sessionId = attempt.sessionId; let sessionId = attempt.sessionId;
if (!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; sessionId = existing?.session_id ?? null;
} }
if (this.isOpen() || this.attempt !== attempt) return true; if (this.isOpen() || this.attempt !== attempt) return true;
@@ -397,7 +492,15 @@ export class VoiceStreamService {
private onServerAudio(chunk: ArrayBuffer, session: number): void { private onServerAudio(chunk: ArrayBuffer, session: number): void {
if (session !== this.session || !this.streaming) return; 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.engine.enqueuePlayback(chunk, this.currentAudioRef);
this.audioTrace('audio_enqueued', { chunkBytes });
this.clearSettleTimer(); this.clearSettleTimer();
if (this.state() !== 'SPEAKING') { if (this.state() !== 'SPEAKING') {
@@ -417,6 +520,7 @@ export class VoiceStreamService {
if (playedMs <= 0) return; if (playedMs <= 0) return;
// Keep the latest cumulative value per ref; the final report is sent from here too. // Keep the latest cumulative value per ref; the final report is sent from here too.
this.playedMsByRef.set(audioRef, playedMs); this.playedMsByRef.set(audioRef, playedMs);
if (audioRef === this.currentAudioRef) this.audioTrace('playback_progress', { playedMs });
this.sendPlaybackProgress(audioRef, playedMs); this.sendPlaybackProgress(audioRef, playedMs);
this.resolveProgressWaiters(); this.resolveProgressWaiters();
} }
@@ -440,6 +544,7 @@ export class VoiceStreamService {
const transport = this.transport; const transport = this.transport;
if (!ref || !transport || this.connection() !== 'connected') return Promise.resolve(); if (!ref || !transport || this.connection() !== 'connected') return Promise.resolve();
this.audioTrace('clear_session_end');
this.engine.clearPlayback(); // worklet answers with its final cumulative report this.engine.clearPlayback(); // worklet answers with its final cumulative report
return new Promise<void>((resolve) => { return new Promise<void>((resolve) => {
const done = (): void => { const done = (): void => {
@@ -490,8 +595,18 @@ export class VoiceStreamService {
break; break;
case 'audio_started': 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.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.audioGenerationDone = false; // frames for this ref are now streaming in
this.clearSettleTimer();
break; break;
case 'audio_ended': case 'audio_ended':
@@ -499,14 +614,36 @@ export class VoiceStreamService {
// the ref's FINAL playback progress reaches its true duration (no phantom outstanding // 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 // sample the backend would read as a stall). This drives the drain on generation
// completion, cooperating with — not depending solely on — the completed transcript. // 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.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; break;
case 'turn_interrupted': case 'turn_interrupted':
this.onTurnInterrupted(event.turn_ref); this.onTurnInterrupted(event.turn_ref);
break; break;
case 'answer_limited':
// Answer state only — see onAnswerLimited: no cleanup, no socket/mic/playback
// side effects, no automatic continuation.
this.onAnswerLimited(event.turn_ref);
break;
case 'error': case 'error':
this.onServerError(event, session); this.onServerError(event, session);
break; break;
@@ -529,18 +666,61 @@ export class VoiceStreamService {
return; return;
} }
if (event.status === 'completed') { if (event.status === 'completed') return;
// 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. if (event.status === 'limited') {
this.turnEnded = true; // An answer state, not a playback or session event: the limited transcript does
if (this.audioGenerationDone) this.engine.flushPlayback(); // NOT seal the audio reference, so generated audio keeps playing until audio_ended
// and the real queue drain finish it. Only the "thinking" state needs a bounded
// fallback, for a limited answer that produced no audio to drain.
this.scheduleLimitedSettle();
} }
} }
/**
* `answer_limited`: the assistant answer reached the backend's output-token limit.
*
* This is an ANSWER state — not an error and not a session-lifecycle event. It must
* not close or reconnect the socket, stop the microphone, flush or mute playback,
* reset `audio_ref`/`played_ms`, mark the session failed, mark playback finished, ask
* the backend to close, or request another answer automatically. The audio already
* generated keeps playing; the user asks for more ("ادامه بده") as a genuine new
* microphone turn.
*/
private onAnswerLimited(turnRef: string): void {
this.rememberLimitedTurn(turnRef);
this.markLimited(turnRef);
this.scheduleLimitedSettle();
}
/**
* Never leave the UI permanently "thinking" after a limited answer: when audio is
* queued the state is SPEAKING and the normal drain path returns to LISTENING, but a
* limited answer can arrive with no outstanding audio at all — then schedule the same
* bounded settle the drain path uses.
*/
private scheduleLimitedSettle(): void {
if (this.state() !== 'PROCESSING' || this.currentAudioRef || this.settleTimer) return;
this.settleTimer = setTimeout(() => {
this.settleTimer = null;
if (this.state() === 'PROCESSING') this.finishTurn();
}, this.config.settleMs);
}
/** Server-side barge-in: the user spoke over the assistant. */ /** Server-side barge-in: the user spoke over the assistant. */
private onTurnInterrupted(turnRef: string): void { 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.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.clearSettleTimer();
this.markInterrupted(turnRef); this.markInterrupted(turnRef);
@@ -579,8 +759,9 @@ export class VoiceStreamService {
} }
// The session survives a retryable failure (e.g. SEARCH_TIMEOUT): drop the failed turn and keep listening. // 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.engine.clearPlayback();
this.turnEnded = false;
this.clearSettleTimer(); this.clearSettleTimer();
this.finalizeAssistant(); this.finalizeAssistant();
if (this.state() === 'PROCESSING' || this.state() === 'SPEAKING') this.state.set('LISTENING'); if (this.state() === 'PROCESSING' || this.state() === 'SPEAKING') this.state.set('LISTENING');
@@ -589,40 +770,75 @@ export class VoiceStreamService {
// ---- end of an assistant turn ---------------------------------------------- // ---- end of an assistant turn ----------------------------------------------
private onPlaybackIdle(): void { /** Numeric browser timeline; backend timestamps use a different clock. */
const state = this.state(); private audioTrace(stage: string, counters: Record<string, number> = {}): void {
if (state !== 'SPEAKING' && state !== 'PROCESSING') return; 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(); 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 { private finishTurn(): void {
this.turnEnded = false; this.underrunStarted = null;
this.audioGenerationDone = false;
this.currentAudioRef = null;
this.currentAudioTurnRef = null;
this.clearSettleTimer(); this.clearSettleTimer();
this.finalizeAssistant();
this.state.set('LISTENING'); this.state.set('LISTENING');
} }
// ---- transcript ------------------------------------------------------------ // ---- transcript ------------------------------------------------------------
private upsertTranscript(event: TranscriptEvent): void { private upsertTranscript(event: TranscriptEvent): void {
const id = `${event.turn_ref}:${event.role}`; const id = `${event.turn_ref}:${event.role}`;
const final = event.status !== 'partial'; const final = event.status !== 'partial';
const interrupted = event.status === 'interrupted'; const interrupted = event.status === 'interrupted';
const limited = event.status === 'limited';
// `limited` is valid only for assistant rows (the transport rejects the rest), and a
// user transcript of a limited turn stays a plain user row.
const attachLimited =
event.role === 'assistant' && !interrupted && (limited || this.isLimitedTurn(event.turn_ref));
// A turn the server already interrupted cannot be restored by late assistant text
// (partial, completed or limited). The interrupted transcript itself still passes:
// it carries the final text of the cut-off answer.
if (event.role === 'assistant' && !interrupted && this.interruptedTurns.has(event.turn_ref)) {
return;
}
this.messages.update((list) => { this.messages.update((list) => {
const index = list.findIndex((m) => m.id === id); const index = list.findIndex((m) => m.id === id);
if (index === -1) { if (index === -1) {
if (!event.text.trim()) return list; // A `limited` transcript is kept even with empty text: the row carries the
// answer state and the UI shows the unavailable-text presentation for it —
// spoken text is never manufactured.
if (!event.text.trim() && !limited) return list;
return this.insertTranscript(list, { return this.insertTranscript(list, {
id, id,
turnRef: event.turn_ref, turnRef: event.turn_ref,
@@ -630,35 +846,41 @@ export class VoiceStreamService {
text: event.text, text: event.text,
final, final,
interrupted: interrupted || undefined, interrupted: interrupted || undefined,
limited: attachLimited || undefined,
}); });
} }
const current = list[index]; const current = list[index];
if (current.interrupted && !interrupted) return list; // late partial for a cut-off message if (current.interrupted && !interrupted) return list; // late partial for a cut-off message
// A late `partial` must not extend an answer that is already final (completed or
// limited): the answer would silently revert to growing partial text.
if (current.final && event.status === 'partial' && event.role === 'assistant') return list;
const copy = [...list]; const copy = [...list];
copy[index] = { copy[index] = {
...current, ...current,
text: this.mergeTranscriptText(current.text, event), text: this.mergeTranscriptText(current.text, event),
final: current.final || final, final: current.final || final,
interrupted: current.interrupted || interrupted || undefined, interrupted: current.interrupted || interrupted || undefined,
// Monotonic: once an answer is limited, a delayed completed/partial transcript
// cannot downgrade it back.
limited: current.limited || attachLimited || undefined,
}; };
return copy; return copy;
}); });
} }
/** /**
* The contract does not say whether a `partial` carries the full text so far or only the new fragment, * Transcript text semantics (contract):
* so both are handled: * - `partial` is a DELTA: it is appended as-is, with its own spacing. Identical
* - `completed` with text → the final full text replaces whatever was accumulated * deltas are legitimately repeated words and are never deduplicated by content.
* - text that starts with what we already have → cumulative, replace * - `completed` and `limited` are FINAL SNAPSHOTS: they replace the accumulated
* - anything else → a fragment, append as-is (fragments carry their own spacing) * text exactly, so the last partial accumulation is never kept alongside them.
*/ */
private mergeTranscriptText(previous: string, event: TranscriptEvent): string { private mergeTranscriptText(previous: string, event: TranscriptEvent): string {
const next = event.text; const next = event.text;
if (!next) return previous; if (!next) return previous;
if (!previous || event.status === 'completed') return next; if (event.status === 'partial') return previous + next;
if (next.startsWith(previous)) return next; return next;
return previous + next;
} }
private upsertSources(event: SourcesEvent): void { private upsertSources(event: SourcesEvent): void {
@@ -667,7 +889,17 @@ export class VoiceStreamService {
const index = list.findIndex((m) => m.id === id); const index = list.findIndex((m) => m.id === id);
const current: VoiceMessage = const current: VoiceMessage =
index === -1 index === -1
? { id, turnRef: event.turn_ref, role: 'assistant', text: '', final: false } ? {
id,
turnRef: event.turn_ref,
role: 'assistant',
text: '',
final: false,
// A sources row for a turn the server already marked limited shows the
// limited indication with the unavailable-text presentation — unless the
// turn was interrupted, which takes precedence.
limited: this.isLimitedTurn(event.turn_ref) || undefined,
}
: list[index]; : list[index];
const sources = [...(current.sources ?? [])]; const sources = [...(current.sources ?? [])];
@@ -703,7 +935,9 @@ export class VoiceStreamService {
// not seen yet sorts after all existing ones. // not seen yet sorts after all existing ones.
const turns: string[] = []; const turns: string[] = [];
for (const m of list) if (!turns.includes(m.turnRef)) turns.push(m.turnRef); 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++) { for (let i = 0; i < list.length; i++) {
const existingTurn = turns.indexOf(list[i].turnRef); const existingTurn = turns.indexOf(list[i].turnRef);
@@ -716,16 +950,67 @@ export class VoiceStreamService {
} }
private markInterrupted(turnRef: string): void { private markInterrupted(turnRef: string): void {
this.rememberInterruptedTurn(turnRef);
const id = `${turnRef}:assistant`; const id = `${turnRef}:assistant`;
this.messages.update((list) => { this.messages.update((list) => {
const index = list.findIndex((m) => m.id === id); const index = list.findIndex((m) => m.id === id);
if (index === -1 || list[index].interrupted) return list; if (index === -1 || list[index].interrupted) return list;
const copy = [...list]; const copy = [...list];
// Interruption takes precedence over a limited marker on the same answer: the row
// is presented as cut off, not as a completed-capped answer.
copy[index] = { ...copy[index], final: true, interrupted: true }; copy[index] = { ...copy[index], final: true, interrupted: true };
return copy; return copy;
}); });
} }
/**
* Flag the assistant answer of `turnRef` as limited. When the row does not exist yet
* (the marker arrived before any transcript text) the bounded `limitedTurns` record
* carries the state until the row is created — no text is ever invented here.
*/
private markLimited(turnRef: string): void {
const id = `${turnRef}:assistant`;
this.messages.update((list) => {
const index = list.findIndex((m) => m.id === id);
// No row yet (the bounded record carries the state), already limited, or
// interrupted (interruption takes precedence): nothing to change.
if (index === -1 || list[index].limited || list[index].interrupted) return list;
const copy = [...list];
copy[index] = { ...copy[index], limited: true };
return copy;
});
}
/**
* Whether the server marked `turnRef`'s answer limited. Interrupted turns answer
* `false`: the interruption takes precedence over the limited state everywhere this
* predicate is used (transcript rows, sources rows and the marker application), so
* the answer is always presented as cut off rather than capped.
*/
private isLimitedTurn(turnRef: string): boolean {
return this.limitedTurns.has(turnRef) && !this.interruptedTurns.has(turnRef);
}
/** Bounded memory of limited turns; repeated markers are idempotent. */
private rememberLimitedTurn(turnRef: string): void {
this.limitedTurns.add(turnRef);
this.evictOldest(this.limitedTurns);
}
/** Bounded memory of interrupted turns, so late assistant text cannot restore them. */
private rememberInterruptedTurn(turnRef: string): void {
this.interruptedTurns.add(turnRef);
this.evictOldest(this.interruptedTurns);
}
private evictOldest(turns: Set<string>): void {
while (turns.size > TURN_STATE_MEMORY) {
const oldest = turns.values().next().value;
if (oldest === undefined) break;
turns.delete(oldest);
}
}
private finalizeAssistant(): void { private finalizeAssistant(): void {
this.messages.update((list) => this.messages.update((list) =>
list.some((m) => m.role === 'assistant' && !m.final) list.some((m) => m.role === 'assistant' && !m.final)
@@ -775,7 +1060,8 @@ export class VoiceStreamService {
// Start-only failure: release immediately (unmount-style) and best-effort V04 for any // 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 // 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. // 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); return this.failure(failure.reason, failure.message);
} }
@@ -805,6 +1091,13 @@ export class VoiceStreamService {
// Stop admitting new media BEFORE any await. // Stop admitting new media BEFORE any await.
this.streaming = false; this.streaming = false;
// "Call finished" — once per connected session, before local resources (including the
// engine AudioContext) are released; every end path funnels through this single-flight
// cleanup, so ordered and unordered teardown both trigger it exactly once.
if (wasConnected) {
this.cues.playEnd();
}
const release = (): void => { const release = (): void => {
// A newer session may have taken over during an await: never touch its resources. // A newer session may have taken over during an await: never touch its resources.
if (superseded()) return; if (superseded()) return;
@@ -823,6 +1116,10 @@ export class VoiceStreamService {
this.interruptTimer = null; this.interruptTimer = null;
} }
this.currentAudioRef = null; this.currentAudioRef = null;
// The markers describe this session's turns only: drop them so a later session
// starts clean even if a late frame slipped through.
this.limitedTurns.clear();
this.interruptedTurns.clear();
}; };
if (options.ordered) { if (options.ordered) {
@@ -832,7 +1129,10 @@ export class VoiceStreamService {
// 2) supersede the session, then V04 /close (bounded), then 3) release. // 2) supersede the session, then V04 /close (bounded), then 3) release.
invalidate(); invalidate();
if (options.closeRemote !== false && remote) { 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 { } catch {
/* the session may already be closed/expired (e.g. 409 LIVE_SESSION_UNUSABLE) */ /* the session may already be closed/expired (e.g. 409 LIVE_SESSION_UNUSABLE) */
@@ -910,7 +1210,6 @@ export class VoiceStreamService {
}; };
private resetTurnFlags(): void { private resetTurnFlags(): void {
this.turnEnded = false;
this.audioGenerationDone = false; this.audioGenerationDone = false;
} }
@@ -962,7 +1261,7 @@ export class VoiceStreamService {
* replay — never new ids, never a blind retry of an unknown state. * replay — never new ids, never a blind retry of an unknown state.
*/ */
private async reserve(csrf: string, title: string): Promise<VoiceSessionResponse> { private async reserve(csrf: string, title: string): Promise<VoiceSessionResponse> {
const attempt = this.attempt ?? newCreationAttempt(); const attempt = this.attempt ?? newCreationAttempt(this.selectedProvider());
this.attempt = attempt; this.attempt = attempt;
let activeCsrf = csrf; let activeCsrf = csrf;
@@ -996,6 +1295,7 @@ export class VoiceStreamService {
activeCsrf, activeCsrf,
attempt.conversationId!, attempt.conversationId!,
attempt.sessionRequestId, attempt.sessionRequestId,
attempt.provider,
); );
} catch (err) { } catch (err) {
const refreshed = await this.refreshAfterCsrfFailure(err); const refreshed = await this.refreshAfterCsrfFailure(err);
@@ -1012,6 +1312,7 @@ export class VoiceStreamService {
activeCsrf, activeCsrf,
attempt.conversationId!, attempt.conversationId!,
attempt.sessionRequestId, attempt.sessionRequestId,
attempt.provider,
); );
} }
} else if (err instanceof VoiceApiError && err.code === 'LIVE_SESSION_BUSY') { } else if (err instanceof VoiceApiError && err.code === 'LIVE_SESSION_BUSY') {
@@ -1063,7 +1364,8 @@ export class VoiceStreamService {
private mapEngineError(err: unknown): { reason: VoiceStartFailure; message: string } { private mapEngineError(err: unknown): { reason: VoiceStartFailure; message: string } {
if (err instanceof MicrophoneError) { 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 { return {
reason: 'mic', reason: 'mic',
message: err.code === 'denied' ? MESSAGES.micDenied : MESSAGES.micUnavailable, message: err.code === 'denied' ? MESSAGES.micDenied : MESSAGES.micUnavailable,
@@ -1115,14 +1417,16 @@ interface VoiceCreationAttempt {
conversationId: string | null; conversationId: string | null;
sessionId: string | null; sessionId: string | null;
streamPath: string | null; streamPath: string | null;
provider?: VoiceProvider;
} }
const ATTEMPT_STORAGE_KEY = 'voice_creation_attempt'; const ATTEMPT_STORAGE_KEY = 'voice_creation_attempt';
function newCreationAttempt(): VoiceCreationAttempt { function newCreationAttempt(provider: VoiceProvider | null = null): VoiceCreationAttempt {
return { return {
conversationRequestId: crypto.randomUUID(), ...(provider ? { provider } : {}),
sessionRequestId: crypto.randomUUID(), conversationRequestId: uuid(),
sessionRequestId: uuid(),
conversationId: null, conversationId: null,
sessionId: null, sessionId: null,
streamPath: null, streamPath: null,
@@ -23,7 +23,11 @@ export interface VoiceSource {
chunk_id: string; chunk_id: string;
title: string; title: string;
excerpt?: string; excerpt?: string;
location?: { page?: number; section?: string } | null; /**
* Where the chunk lives in its document. `page` is `null` when the backend cannot
* attribute a page (it serializes the absence as JSON `null`, not as an omission).
*/
location?: { page?: number | null; section?: string } | null;
/** `false` = the excerpt is no longer valid and must be hidden, not kept on screen. */ /** `false` = the excerpt is no longer valid and must be hidden, not kept on screen. */
available?: boolean; available?: boolean;
} }
@@ -34,7 +38,14 @@ export interface VoiceAudioFormat {
channels: number; channels: number;
} }
export type TranscriptStatus = 'partial' | 'completed' | 'interrupted'; export type TranscriptStatus = 'partial' | 'completed' | 'interrupted' | 'limited';
/**
* Why an assistant answer was marked limited. The backend applies a conservative
* output-token budget (tool calls included); reaching it ends the GENERATION of the
* answer, not the session and not the playback of the audio already produced.
*/
export type AnswerLimitedReason = 'output_token_limit';
export type VoiceServerEvent = export type VoiceServerEvent =
| { | {
@@ -52,16 +63,24 @@ export type VoiceServerEvent =
turn_ref: string; turn_ref: string;
role: 'user' | 'assistant'; role: 'user' | 'assistant';
/** /**
* Full text so far OR a new fragment: the contract does not say which, so * `partial` is a delta (append it); `completed` and `limited` are final
* `VoiceStreamService.mergeTranscriptText` accepts both (`completed` always carries the final text). * snapshots (they replace the accumulated text). See
* `VoiceStreamService.mergeTranscriptText`.
*/ */
text: string; text: string;
status: TranscriptStatus; status: TranscriptStatus;
} }
| { type: 'sources'; turn_ref: string; tool_call_id?: string; sources: VoiceSource[] } | { type: 'sources'; turn_ref: string; tool_call_id?: string; sources: VoiceSource[] }
| { type: 'audio_started'; audio_ref: string; turn_ref?: string } | { 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[] } | { 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
* state, not an error and not a session-lifecycle event: it does not stop or seal
* audio playback, does not close the session or the microphone, and does not ask
* for an automatic continuation — a genuine new user turn is required for more.
*/
| { type: 'answer_limited'; turn_ref: string; reason: AnswerLimitedReason }
| { | {
type: 'error'; type: 'error';
turn_ref?: string; turn_ref?: string;
@@ -69,6 +88,9 @@ export type VoiceServerEvent =
error: { code: string; message: string; request_id?: string; retryable: boolean }; error: { code: string; message: string; request_id?: string; retryable: boolean };
}; };
/** Every `type` discriminator of `VoiceServerEvent`. */
export type VoiceServerEventType = VoiceServerEvent['type'];
/** /**
* The only client→server JSON control message. `played_ms` is the cumulative real * The only client→server JSON control message. `played_ms` is the cumulative real
* playback time of `audio_ref` (computed from samples actually consumed by the * playback time of `audio_ref` (computed from samples actually consumed by the
@@ -91,6 +113,11 @@ export interface VoiceMessage {
final: boolean; final: boolean;
/** assistant message cut short by the user speaking over it */ /** assistant message cut short by the user speaking over it */
interrupted?: boolean; interrupted?: boolean;
/**
* Assistant answer the server capped (output-token limit). The session and the
* playback of the produced audio stay usable; only the answer is limited.
*/
limited?: boolean;
/** retrieved documents that back this answer */ /** retrieved documents that back this answer */
sources?: VoiceSource[]; sources?: VoiceSource[];
} }
@@ -126,7 +153,7 @@ export interface VoiceStreamConfig {
outputSampleRate: number; outputSampleRate: number;
frameMs: number; frameMs: number;
connectTimeoutMs: 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; settleMs: number;
/** Folder (relative to <base href>) holding the two *.worklet.js files, served from the UI origin. */ /** Folder (relative to <base href>) holding the two *.worklet.js files, served from the UI origin. */
workletBasePath: string; workletBasePath: string;
@@ -0,0 +1,177 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { WebSocketVoiceTransport } from './voice-transport';
import { VoiceServerEvent } from './voice-stream.types';
/**
* Minimal fake WebSocket: captures the handlers the transport installs and lets the test
* deliver string control frames / binary audio frames exactly like a server would.
*/
class FakeWebSocket {
static readonly CONNECTING = 0;
static readonly OPEN = 1;
static readonly CLOSING = 2;
static readonly CLOSED = 3;
static instances: FakeWebSocket[] = [];
readyState = FakeWebSocket.OPEN;
binaryType: 'blob' | 'arraybuffer' = 'blob';
sent: unknown[] = [];
onopen: (() => void) | null = null;
onmessage: ((event: { data: unknown }) => void) | null = null;
onerror: (() => void) | null = null;
onclose: ((event: { code: number; reason: string; wasClean: boolean }) => void) | null = null;
constructor(public readonly url: string) {
FakeWebSocket.instances.push(this);
}
send(data: unknown): void {
this.sent.push(data);
}
close(): void {
this.readyState = FakeWebSocket.CLOSED;
}
// ---- test helpers ---------------------------------------------------------
/** The transport attaches its handlers inside connect(); simulate the open handshake. */
static async connectTransport(transport: WebSocketVoiceTransport): Promise<FakeWebSocket> {
const connected = transport.connect({
onEvent: vi.fn(),
onAudio: vi.fn(),
onClose: vi.fn(),
onOverflow: vi.fn(),
});
const ws = FakeWebSocket.instances.at(-1)!;
ws.onopen?.();
await connected;
return ws;
}
deliverText(payload: string): void {
this.onmessage?.({ data: payload });
}
deliverJson(payload: unknown): void {
this.deliverText(JSON.stringify(payload));
}
deliverAudio(bytes: ArrayBuffer): void {
this.onmessage?.({ data: bytes });
}
}
describe('WebSocketVoiceTransport (JSON frame parsing)', () => {
beforeEach(() => {
FakeWebSocket.instances = [];
vi.stubGlobal('WebSocket', FakeWebSocket);
});
const ANSWER_LIMITED_FRAME = {
type: 'answer_limited',
turn_ref: 'live-turn-1',
reason: 'output_token_limit',
};
it('parses a valid answer_limited frame and forwards it to the handlers', async () => {
const events: VoiceServerEvent[] = [];
const transport = new WebSocketVoiceTransport('wss://ui.local/stream', 1000);
const connected = transport.connect({
onEvent: (event) => events.push(event),
onAudio: vi.fn(),
onClose: vi.fn(),
onOverflow: vi.fn(),
});
const ws = FakeWebSocket.instances.at(-1)!;
ws.onopen?.();
await connected;
ws.deliverJson(ANSWER_LIMITED_FRAME);
expect(events).toEqual([ANSWER_LIMITED_FRAME]);
});
it('keeps forwarding the existing event types (older backends unaffected)', async () => {
const events: VoiceServerEvent[] = [];
const transport = new WebSocketVoiceTransport('wss://ui.local/stream', 1000);
const connected = transport.connect({
onEvent: (event) => events.push(event),
onAudio: vi.fn(),
onClose: vi.fn(),
onOverflow: vi.fn(),
});
const ws = FakeWebSocket.instances.at(-1)!;
ws.onopen?.();
await connected;
ws.deliverJson({ type: 'user_speech_started', turn_ref: 'live-turn-2' });
ws.deliverJson({ type: 'audio_started', audio_ref: 'live-audio-1' });
ws.deliverJson({
type: 'transcript',
turn_ref: 'live-turn-2',
role: 'assistant',
text: 'سلام',
status: 'partial',
});
expect(events.map((e) => e.type)).toEqual(['user_speech_started', 'audio_started', 'transcript']);
});
it('drops unknown and malformed frames without an error path or cleanup', async () => {
const events: VoiceServerEvent[] = [];
const onClose = vi.fn();
const onOverflow = vi.fn();
const transport = new WebSocketVoiceTransport('wss://ui.local/stream', 1000);
const connected = transport.connect({
onEvent: (event) => events.push(event),
onAudio: vi.fn(),
onClose,
onOverflow,
});
const ws = FakeWebSocket.instances.at(-1)!;
ws.onopen?.();
await connected;
ws.deliverText('not json');
ws.deliverJson({ type: 'response.create' });
ws.deliverJson({ type: 'answer_limited', turn_ref: 'live-turn-1', reason: 'other_limit' });
ws.deliverJson({ type: 'transcript', turn_ref: 't1', role: 'user', text: 'x', status: 'limited' });
ws.deliverJson({ type: 'audio_started', audio_ref: '' });
expect(events).toEqual([]); // nothing entered the service
expect(onClose).not.toHaveBeenCalled();
expect(onOverflow).not.toHaveBeenCalled();
expect(ws.readyState).toBe(FakeWebSocket.OPEN); // socket untouched
});
it('delivers binary audio frames as ArrayBuffers to onAudio', async () => {
const onAudio = vi.fn();
const transport = new WebSocketVoiceTransport('wss://ui.local/stream', 1000);
const connected = transport.connect({
onEvent: vi.fn(),
onAudio,
onClose: vi.fn(),
onOverflow: vi.fn(),
});
const ws = FakeWebSocket.instances.at(-1)!;
ws.onopen?.();
await connected;
const pcm = new ArrayBuffer(9600);
ws.deliverAudio(pcm);
expect(onAudio).toHaveBeenCalledWith(pcm);
});
it('sendControl only emits playback_progress (no fabricated continue/resume command)', async () => {
const transport = new WebSocketVoiceTransport('wss://ui.local/stream', 1000);
const ws = await FakeWebSocket.connectTransport(transport);
transport.sendControl({ type: 'playback_progress', audio_ref: 'live-audio-1', played_ms: 120 });
expect(ws.sent).toEqual([
JSON.stringify({ type: 'playback_progress', audio_ref: 'live-audio-1', played_ms: 120 }),
]);
});
});
@@ -1,5 +1,6 @@
import { InjectionToken, inject } from '@angular/core'; import { InjectionToken, inject } from '@angular/core';
import { PlaybackProgressMessage, VOICE_STREAM_CONFIG, VoiceServerEvent } from './voice-stream.types'; import { PlaybackProgressMessage, VOICE_STREAM_CONFIG, VoiceServerEvent } from './voice-stream.types';
import { parseVoiceServerEvent } from './voice-event.validator';
export interface VoiceTransportHandlers { export interface VoiceTransportHandlers {
onEvent(event: VoiceServerEvent): void; onEvent(event: VoiceServerEvent): void;
@@ -79,13 +80,11 @@ export class WebSocketVoiceTransport implements VoiceTransport {
ws.onmessage = (event: MessageEvent) => { ws.onmessage = (event: MessageEvent) => {
if (typeof event.data === 'string') { if (typeof event.data === 'string') {
let parsed: VoiceServerEvent | null = null; // Allowlist + field guards: an unknown type or a malformed payload is dropped
try { // here, exactly like malformed JSON always was — it never reaches the service,
parsed = JSON.parse(event.data) as VoiceServerEvent; // never enters an error path and never triggers cleanup.
} catch { const parsed = parseVoiceServerEvent(event.data);
/* ignore malformed control frames */ if (!parsed) return;
return;
}
this.traceFrame(parsed); this.traceFrame(parsed);
handlers.onEvent(parsed); handlers.onEvent(parsed);
} else if (event.data instanceof ArrayBuffer) { } else if (event.data instanceof ArrayBuffer) {
@@ -208,6 +207,10 @@ export class WebSocketVoiceTransport implements VoiceTransport {
const t = event as { status?: string; text?: string }; const t = event as { status?: string; text?: string };
return `transcript[${t.status ?? '?'}] ${(t.text ?? '').slice(0, 80)}`; return `transcript[${t.status ?? '?'}] ${(t.text ?? '').slice(0, 80)}`;
} }
if (type === 'answer_limited') {
const a = event as { turn_ref?: string; reason?: string };
return `answer_limited ${a.turn_ref ?? ''} reason=${a.reason ?? ''}`.trim();
}
if (type === 'audio_started' || type === 'audio_ended') { if (type === 'audio_started' || type === 'audio_ended') {
return `${type} ${(event as { audio_ref?: string }).audio_ref ?? ''}`.trim(); return `${type} ${(event as { audio_ref?: string }).audio_ref ?? ''}`.trim();
} }
+118 -46
View File
@@ -7,11 +7,14 @@
background: var(--sidebar-bg); background: var(--sidebar-bg);
color: var(--sidebar-text); color: var(--sidebar-text);
transform: translateX(0); transform: translateX(0);
transition: width 0.3s ease; /* The width transition drives the whole expansion; text reveal is gated by the
matching delay below so labels never reflow mid-flight. */
transition: width 0.35s cubic-bezier(0.4, 0, 0.2, 1);
z-index: 40; z-index: 40;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
border-left: 1px solid var(--sidebar-border); border-left: 1px solid var(--sidebar-border);
overflow: hidden;
} }
.sidebar.open { .sidebar.open {
@@ -30,6 +33,52 @@
overflow: hidden; overflow: hidden;
} }
/* Sidebar width animation: 0.35s. Text must not appear until the sidebar is wide
enough to hold the label on one line, so every label fades in only AFTER the
width transition finishes (delay = full duration) and fades out immediately
when collapsing. This prevents Persian text from wrapping vertically. */
:root {
--sidebar-expand-duration: 0.35s;
--sidebar-collapse-duration: 0.15s;
}
/* Scoped to `.sidebar`: the account menu is a CDK overlay rendered outside the sidebar
DOM, so unscoping these selectors would hide the username inside the dropdown too. */
.sidebar .nav-label,
.sidebar .history-text,
.sidebar .history-header .history-title,
.sidebar .user-info,
.sidebar .theme-toggle span {
max-width: 0;
opacity: 0;
overflow: hidden;
white-space: nowrap;
transform: translateX(-8px);
/* Fast fade OUT when collapsing — no delay on the way in. */
transition:
max-width var(--sidebar-collapse-duration) ease-in,
opacity var(--sidebar-collapse-duration) ease-in,
transform var(--sidebar-collapse-duration) ease-in;
}
/* Expanded state: the sidebar has finished growing, so the label can fade in.
`max-width: 100%` lets it occupy only the remaining space next to the icon
(never forcing a second line), and the delay guarantees the width is already
sufficient before the text becomes visible. */
.sidebar.open .nav-label,
.sidebar.open .history-text,
.sidebar.open .history-header .history-title,
.sidebar.open .user-info,
.sidebar.open .theme-toggle span {
max-width: 100%;
opacity: 1;
transform: translateX(0);
transition:
max-width var(--sidebar-expand-duration) ease-out var(--sidebar-expand-duration),
opacity var(--sidebar-expand-duration) ease-out var(--sidebar-expand-duration),
transform var(--sidebar-expand-duration) ease-out var(--sidebar-expand-duration);
}
.sidebar-top { .sidebar-top {
padding: 0.75rem; padding: 0.75rem;
display: flex; display: flex;
@@ -67,16 +116,19 @@
.sidebar:not(.open) .sidebar-logo-link { .sidebar:not(.open) .sidebar-logo-link {
justify-content: center; justify-content: center;
width: 100%; width: 40px;
height: 40px;
margin: 0 auto;
} }
.sidebar:not(.open) .sidebar-logo { .sidebar:not(.open) .sidebar-logo {
height: 36px; height: 28px;
} }
/* Keep the logo in the same 40px column as the nav items. */
.sidebar:not(.open) .sidebar-header { .sidebar:not(.open) .sidebar-header {
justify-content: center; justify-content: center;
padding: 0.5rem 0.25rem; padding: 0.5rem 0;
} }
.sidebar:not(.open) .close-btn { .sidebar:not(.open) .close-btn {
@@ -181,6 +233,8 @@
font-size: 0.875rem; font-size: 0.875rem;
font-weight: 500; font-weight: 500;
transition: background 0.2s; transition: background 0.2s;
/* Keep the icon and label on one line regardless of sidebar width. */
min-width: 0;
} }
.nav-item:hover { .nav-item:hover {
@@ -193,17 +247,28 @@
font-weight: 500; font-weight: 500;
} }
/* Collapsed rail (72px): a fixed 40px item column centred in the rail, so every icon
lines up with the others and with the logo/avatar above it. */
.sidebar:not(.open) .sidebar-top {
padding: 0.75rem 1rem;
align-items: center;
}
.sidebar:not(.open) .nav-item { .sidebar:not(.open) .nav-item {
justify-content: center; justify-content: center;
padding: 0.75rem 0; gap: 0;
width: 40px;
height: 40px;
padding: 0;
margin: 0 auto;
box-sizing: border-box;
} }
.sidebar:not(.open) .nav-item svg { .sidebar:not(.open) .nav-item .nav-icon {
margin: 0; flex-shrink: 0;
} display: flex;
align-items: center;
.sidebar:not(.open) .nav-label { justify-content: center;
display: none;
} }
.sidebar-divider { .sidebar-divider {
@@ -213,7 +278,8 @@
} }
.sidebar:not(.open) .sidebar-divider { .sidebar:not(.open) .sidebar-divider {
margin: 0 0.5rem; /* Same 40px column inset (16px each side of the 72px rail). */
margin: 0 1rem;
} }
.sidebar-bottom { .sidebar-bottom {
@@ -229,15 +295,6 @@
display: none; display: none;
} }
.history-header {
padding: 0.25rem 0.5rem;
font-size: 0.75rem;
font-weight: 500;
color: var(--sidebar-muted);
text-transform: uppercase;
letter-spacing: 0.05em;
}
.sidebar:not(.open) .history-header { .sidebar:not(.open) .history-header {
display: none; display: none;
} }
@@ -277,6 +334,23 @@
margin: 0; margin: 0;
} }
/* The whole lower section collapses with the sidebar; its labels animate via
the shared width/opacity transition defined earlier. */
.sidebar:not(.open) .history-header {
justify-content: center;
}
.history-header {
display: flex;
padding: 0.25rem 0.5rem;
font-size: 0.75rem;
font-weight: 500;
color: var(--sidebar-muted);
text-transform: uppercase;
letter-spacing: 0.05em;
min-width: 0;
}
.history-icon { .history-icon {
flex-shrink: 0; flex-shrink: 0;
opacity: 0.7; opacity: 0.7;
@@ -286,10 +360,7 @@
overflow: hidden; overflow: hidden;
text-overflow: ellipsis; text-overflow: ellipsis;
white-space: nowrap; white-space: nowrap;
} min-width: 0;
.sidebar:not(.open) .history-text {
display: none;
} }
.history-empty { .history-empty {
@@ -304,10 +375,6 @@
text-align: center; text-align: center;
} }
.sidebar:not(.open) .history-empty {
display: none;
}
.history-empty-icon { .history-empty-icon {
opacity: 0.5; opacity: 0.5;
margin-bottom: 0.25rem; margin-bottom: 0.25rem;
@@ -324,25 +391,20 @@
.sidebar:not(.open) .sidebar-footer { .sidebar:not(.open) .sidebar-footer {
align-items: center; align-items: center;
padding: 0.5rem; padding: 0.75rem 1rem;
margin-top: auto; margin-top: auto;
} }
.sidebar:not(.open) .user-info {
display: none;
}
.sidebar:not(.open) .user-profile { .sidebar:not(.open) .user-profile {
width: 56px; width: 40px;
height: 56px; height: 40px;
padding: 0; padding: 0;
gap: 0;
border-radius: 50%; border-radius: 50%;
justify-content: center; justify-content: center;
} }
.sidebar:not(.open) .theme-toggle span { /* Theme-toggle label animates with the shared transition instead of display:none. */
display: none;
}
.user-profile { .user-profile {
display: flex; display: flex;
@@ -356,6 +418,7 @@
color: var(--sidebar-text); color: var(--sidebar-text);
text-align: start; text-align: start;
cursor: pointer; cursor: pointer;
min-width: 0;
} }
.user-profile:hover, .user-profile:hover,
@@ -383,10 +446,16 @@
.account-menu-header { .account-menu-header {
display: flex; display: flex;
align-items: center; align-items: center;
/* dir="rtl" on .account-menu already lays children right→left, so the default
`row` order puts the avatar on the right and the name beside it to the left. */
gap: 0.5rem; gap: 0.5rem;
padding: 0.5rem; padding: 0.5rem;
} }
.account-menu-header .user-info {
text-align: start;
}
.account-menu-divider { .account-menu-divider {
height: 1px; height: 1px;
margin: 0.375rem 0.5rem; margin: 0.375rem 0.5rem;
@@ -396,6 +465,7 @@
.account-menu-item { .account-menu-item {
display: flex; display: flex;
align-items: center; align-items: center;
/* justify-content: space-between; */
gap: 0.75rem; gap: 0.75rem;
width: 100%; width: 100%;
padding: 0.625rem 0.75rem; padding: 0.625rem 0.75rem;
@@ -436,6 +506,7 @@
flex-direction: column; flex-direction: column;
gap: 0.125rem; gap: 0.125rem;
overflow: hidden; overflow: hidden;
min-width: 0;
} }
.user-name { .user-name {
@@ -479,9 +550,7 @@
margin: 0; margin: 0;
} }
.sidebar:not(.open) .claim-btn span { /* Label collapse is handled by the shared width/opacity transition. */
display: none;
}
.theme-toggle { .theme-toggle {
display: flex; display: flex;
@@ -504,17 +573,20 @@
} }
.sidebar:not(.open) .theme-toggle { .sidebar:not(.open) .theme-toggle {
width: 56px; width: 40px;
height: 56px; height: 40px;
padding: 0; padding: 0;
gap: 0;
border-radius: 0.5rem; border-radius: 0.5rem;
justify-content: center; justify-content: center;
} }
.sidebar:not(.open) .theme-toggle svg { .sidebar:not(.open) .theme-toggle svg {
margin: 0; margin: 0;
flex-shrink: 0;
} }
.sidebar:not(.open) .theme-toggle span { /* Collapsed rail: the avatar text must not stretch the 40px column. */
display: none; .sidebar:not(.open) .user-avatar {
flex-shrink: 0;
} }
@@ -44,6 +44,7 @@
fill="none" fill="none"
stroke="currentColor" stroke="currentColor"
stroke-width="2" stroke-width="2"
class="nav-icon"
> >
<path [attr.d]="item.icon" /> <path [attr.d]="item.icon" />
</svg> </svg>
@@ -116,13 +117,14 @@
</div> </div>
</button> </button>
<ng-template #accountMenu> <ng-template #accountMenu>
<div class="account-menu" cdkMenu aria-label="Account menu" dir="ltr"> <div class="account-menu" cdkMenu aria-label="Account menu" dir="rtl">
<div class="account-menu-header"> <div class="account-menu-header">
<div class="user-avatar">{{ userInitials() }}</div> <div class="user-avatar">{{ userInitials() }}</div>
<div class="user-info"> <div class="user-info">
<span class="user-name">{{ userName() }}</span> <span class="user-name">{{ userName() }}</span>
</div> </div>
</div> </div>
<!--
<div class="account-menu-divider" role="separator"></div> <div class="account-menu-divider" role="separator"></div>
<button type="button" class="account-menu-item" cdkMenuItem (cdkMenuItemTriggered)="profileClick.emit()"> <button type="button" class="account-menu-item" cdkMenuItem (cdkMenuItemTriggered)="profileClick.emit()">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
@@ -132,12 +134,13 @@
</svg> </svg>
<span>Profile</span> <span>Profile</span>
</button> </button>
-->
<div class="account-menu-divider" role="separator"></div> <div class="account-menu-divider" role="separator"></div>
<button type="button" class="account-menu-item" cdkMenuItem (cdkMenuItemTriggered)="logoutClick.emit()"> <button type="button" class="account-menu-item" cdkMenuItem (cdkMenuItemTriggered)="logoutClick.emit()">
<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4M16 17l5-5-5-5M21 12H9" /> <path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4M16 17l5-5-5-5M21 12H9" />
</svg> </svg>
<span>Log out</span> <span>خروج</span>
</button> </button>
</div> </div>
</ng-template> </ng-template>
@@ -69,7 +69,8 @@ export class SidebarComponent {
readonly close = output<void>(); readonly close = output<void>();
readonly navClick = output<void>(); readonly navClick = output<void>();
readonly open = output<void>(); readonly open = output<void>();
readonly profileClick = output<void>(); // Profile page is disabled; the account-menu entry is commented out in the template.
// readonly profileClick = output<void>();
readonly logoutClick = output<void>(); readonly logoutClick = output<void>();
readonly userInitials = computed(() => { readonly userInitials = computed(() => {
@@ -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)'))
: [];
}
}
@@ -48,12 +48,43 @@
opacity: 0.8; opacity: 0.8;
} }
.bubble.is-limited {
/* informational answer state: a quiet accent, never an error treatment */
border-inline-start: 2px solid var(--color-primary);
padding-inline-start: 0.5rem;
}
.bubble-tag { .bubble-tag {
margin-inline-start: 0.375rem; margin-inline-start: 0.375rem;
font-size: 0.75rem; font-size: 0.75rem;
opacity: 0.7; opacity: 0.7;
} }
.bubble-tag.is-limited {
color: var(--color-primary);
font-weight: 600;
opacity: 1;
}
.bubble-footer {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 0.125rem;
margin-top: 0.25rem;
}
.bubble-help {
font-size: 0.75rem;
line-height: 1.6;
color: var(--muted);
}
.bubble-text.is-missing {
color: var(--muted);
font-style: italic;
}
@keyframes bubbleIn { @keyframes bubbleIn {
from { from {
opacity: 0; opacity: 0;
@@ -77,7 +108,7 @@
.source-chip { .source-chip {
display: flex; display: flex;
align-items: baseline; align-items: flex-start;
gap: 0.375rem; gap: 0.375rem;
padding: 0.25rem 0.5rem; padding: 0.25rem 0.5rem;
border: 1px solid var(--surface-border); border: 1px solid var(--surface-border);
@@ -85,7 +116,7 @@
background: var(--surface-bg); background: var(--surface-bg);
color: var(--text-secondary); color: var(--text-secondary);
font-size: 0.75rem; font-size: 0.75rem;
line-height: 1.5; line-height: 1.6;
} }
.source-chip.is-unavailable { .source-chip.is-unavailable {
@@ -103,6 +134,15 @@
font-weight: 600; font-weight: 600;
} }
/* The excerpt is the chip's content, shown complete with the provider's own line
breaks — it is the retrieved answer text the user asked to see as the source. */
.source-label {
flex: 1 1 auto;
min-width: 0;
white-space: pre-wrap;
overflow-wrap: anywhere;
}
.transcript-empty { .transcript-empty {
margin: auto; margin: auto;
margin-bottom:10px; margin-bottom:10px;
@@ -5,13 +5,23 @@
[class.is-user]="message.role === 'user'" [class.is-user]="message.role === 'user'"
[class.is-partial]="!message.final" [class.is-partial]="!message.final"
[class.is-interrupted]="message.interrupted" [class.is-interrupted]="message.interrupted"
[class.is-limited]="message.limited && !message.interrupted"
dir="rtl" dir="rtl"
> >
@if (message.text) { @if (message.text) {
<span class="bubble-text">{{ message.text }}</span> <span class="bubble-text">{{ message.text }}</span>
} @else if (message.limited && !message.interrupted) {
<!-- A limited answer with no transcript text: never manufacture spoken text. -->
<span class="bubble-text is-missing">متن این پاسخ در دسترس نیست</span>
} }
@if (message.interrupted) { @if (message.interrupted) {
<span class="bubble-tag">(قطع شد)</span> <span class="bubble-tag">(قطع شد)</span>
} @else if (message.limited) {
<!-- Informational answer state: the answer is limited, not a failure and not complete. -->
<span class="bubble-footer">
<span class="bubble-tag is-limited">پاسخ محدود شده</span>
<span class="bubble-help">برای توضیح بیشتر بگویید «ادامه بده».</span>
</span>
} }
@if (message.sources?.length) { @if (message.sources?.length) {
<ul class="source-list" aria-label="منابع پاسخ"> <ul class="source-list" aria-label="منابع پاسخ">
@@ -19,7 +29,7 @@
<li <li
class="source-chip" class="source-chip"
[class.is-unavailable]="source.available === false" [class.is-unavailable]="source.available === false"
[attr.title]="source.excerpt ?? null" [attr.title]="sourceTooltip(source)"
> >
<span class="source-ref">{{ source.source_ref }}</span> <span class="source-ref">{{ source.source_ref }}</span>
<span class="source-label">{{ sourceLabel(source) }}</span> <span class="source-label">{{ sourceLabel(source) }}</span>
@@ -0,0 +1,234 @@
import { provideZonelessChangeDetection } from '@angular/core';
import { TestBed } from '@angular/core/testing';
import { VoiceTranscriptComponent } from './voice-transcript.component';
import { VoiceMessage, VoiceSource } from '../../../services/voice-stream/voice-stream.types';
const LIMITED_LABEL = 'پاسخ محدود شده';
const LIMITED_HELP = 'برای توضیح بیشتر بگویید «ادامه بده».';
const UNAVAILABLE_TEXT = 'متن این پاسخ در دسترس نیست';
function message(overrides: Partial<VoiceMessage>): VoiceMessage {
return {
id: 'turn-1:assistant',
turnRef: 'turn-1',
role: 'assistant',
text: 'پاسخ',
final: true,
...overrides,
};
}
async function render(messages: VoiceMessage[]): Promise<HTMLElement> {
const fixture = TestBed.createComponent(VoiceTranscriptComponent);
fixture.componentRef.setInput('messages', messages);
fixture.detectChanges();
await fixture.whenStable();
return fixture.nativeElement as HTMLElement;
}
describe('VoiceTranscriptComponent', () => {
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [VoiceTranscriptComponent],
providers: [provideZonelessChangeDetection()],
}).compileComponents();
});
it('shows the limited indication with the continuation help next to the transcript text', async () => {
const element = await render([message({ limited: true })]);
expect(element.textContent).toContain('پاسخ'); // the available transcript stays visible
expect(element.textContent).toContain(LIMITED_LABEL);
expect(element.textContent).toContain(LIMITED_HELP);
// The help text is a separate indication, never appended to the provider transcript.
const text = element.querySelector('.bubble-text')?.textContent ?? '';
expect(text).toBe('پاسخ');
expect(text).not.toContain(LIMITED_HELP);
});
it('shows the unavailable-text presentation when a limited answer has no transcript text', async () => {
const element = await render([message({ text: '', limited: true })]);
expect(element.textContent).toContain(UNAVAILABLE_TEXT);
expect(element.textContent).toContain(LIMITED_LABEL);
expect(element.textContent).toContain(LIMITED_HELP);
});
it('keeps the sources of a limited answer visible', async () => {
const element = await render([
message({
limited: true,
sources: [
{
source_ref: 'S1',
document_id: 'doc-1',
chunk_id: 'chunk-1',
title: 'سند آزمون',
excerpt: 'بانک سؤالات و پاسخ‌های سامانه هوش مصنوعی تلفنی',
location: { page: null, section: 'docx/paragraph/1 | docx/table/1/row/1/cell/1' },
},
],
}),
]);
expect(element.querySelectorAll('.source-chip')).toHaveLength(1);
expect(element.textContent).toContain(LIMITED_LABEL);
});
it('shows the excerpt instead of the document section path', async () => {
const source: VoiceSource = {
source_ref: 'S1',
document_id: 'doc-1',
chunk_id: 'chunk-1',
title: 'document.docx',
excerpt: 'ساعت کاری شرکت از شنبه تا چهارشنبه است',
location: { page: null, section: 'docx/paragraph/1 | docx/table/1/row/1/cell/1' },
};
const element = await render([message({ sources: [source] })]);
const label = element.querySelector('.source-label')?.textContent ?? '';
expect(label).toContain('ساعت کاری شرکت از شنبه تا چهارشنبه است');
expect(label).not.toContain('docx/table/1/row/1/cell/1');
expect(label).not.toContain('document.docx'); // the filename is not the chip label
});
it('keeps the full excerpt and the document details in the hover tooltip', async () => {
const source: VoiceSource = {
source_ref: 'S1',
document_id: 'doc-1',
chunk_id: 'chunk-1',
title: 'document.docx',
excerpt: 'سؤال: ساعت کاری؟\nپاسخ: ۸ تا ۱۳',
location: { page: 3, section: 'docx/paragraph/1' },
};
const element = await render([message({ sources: [source] })]);
const tooltip = element.querySelector('.source-chip')?.getAttribute('title') ?? '';
expect(tooltip).toContain('document.docx');
expect(tooltip).toContain('docx/paragraph/1');
expect(tooltip).toContain('صفحه 3');
expect(tooltip).toContain('سؤال: ساعت کاری؟\nپاسخ: ۸ تا ۱۳');
});
it('shows a single-paragraph excerpt completely with its line breaks', async () => {
const excerpt =
'بانک سؤالات و پاسخ‌های سامانه هوش مصنوعی تلفنی: ساعت کاری شرکت از شنبه تا چهارشنبه است';
const source: VoiceSource = {
source_ref: 'S1',
document_id: 'doc-1',
chunk_id: 'chunk-1',
title: 'document.docx',
excerpt,
};
const element = await render([message({ sources: [source] })]);
const label = element.querySelector<HTMLElement>('.source-label');
// a single paragraph is not summarized: the full text is rendered…
expect(label?.textContent).toBe(excerpt);
// …and wraps instead of being clipped to one line
const style = getComputedStyle(label!);
expect(style.whiteSpace).toBe('pre-wrap');
expect(style.textOverflow).not.toBe('ellipsis');
});
it('summarizes a multi-paragraph excerpt to its first paragraph with an ellipsis', async () => {
const source: VoiceSource = {
source_ref: 'S1',
document_id: 'doc-1',
chunk_id: 'chunk-1',
title: 'document.docx',
excerpt:
'بانک سؤالات و پاسخ‌های سامانه هوش مصنوعی تلفنی\nسؤال: ساعت کاری شرکت چنده؟\nپاسخ: ۸ تا ۱۳',
};
const element = await render([message({ sources: [source] })]);
const label = element.querySelector('.source-label')?.textContent ?? '';
expect(label).toBe('بانک سؤالات و پاسخ‌های سامانه هوش مصنوعی تلفنی …');
expect(label).not.toContain('سؤال: ساعت کاری');
expect(label).not.toContain('پاسخ: ۸ تا ۱۳');
// the complete excerpt stays available in the hover tooltip
expect(element.querySelector('.source-chip')?.getAttribute('title')).toContain('پاسخ: ۸ تا ۱۳');
});
it('treats blank-line-separated paragraphs as multiple paragraphs', async () => {
const source: VoiceSource = {
source_ref: 'S1',
document_id: 'doc-1',
chunk_id: 'chunk-1',
title: 'document.docx',
excerpt: 'پاراگراف اول\n\nپاراگراف دوم',
};
const element = await render([message({ sources: [source] })]);
const label = element.querySelector('.source-label')?.textContent ?? '';
expect(label).toBe('پاراگراف اول …');
expect(label).not.toContain('پاراگراف دوم');
});
it('trims the excerpt so trailing wire newlines do not add empty lines', async () => {
const source: VoiceSource = {
source_ref: 'S1',
document_id: 'doc-1',
chunk_id: 'chunk-1',
title: 'document.docx',
excerpt: 'پاسخ: ۸ تا ۱۳\n',
};
const element = await render([message({ sources: [source] })]);
expect(element.querySelector('.source-label')?.textContent).toBe('پاسخ: ۸ تا ۱۳');
});
it('falls back to the document title for sources the server marks unavailable', async () => {
const element = await render([
message({
sources: [
{
source_ref: 'S1',
document_id: 'doc-1',
chunk_id: 'chunk-1',
title: 'document.docx',
excerpt: 'متن منقضی‌شده',
available: false,
},
],
}),
]);
const chip = element.querySelector('.source-chip');
expect(chip?.classList.contains('is-unavailable')).toBe(true);
expect(chip?.querySelector('.source-label')?.textContent).toBe('document.docx');
expect(chip?.querySelector('.source-label')?.textContent).not.toContain('متن منقضی‌شده');
// The revoked excerpt stays hidden in the tooltip too.
expect(chip?.getAttribute('title')).not.toContain('متن منقضی‌شده');
expect(chip?.getAttribute('title')).toContain('document.docx');
});
it('presents an interrupted answer as interrupted, not as limited', async () => {
const element = await render([
message({ limited: true, interrupted: true, text: 'پاسخ قطع‌شده' }),
]);
expect(element.textContent).toContain('(قطع شد)');
expect(element.textContent).not.toContain(LIMITED_LABEL);
expect(element.textContent).not.toContain(LIMITED_HELP);
});
it('never applies the limited indication to user rows or ordinary answers', async () => {
const element = await render([
message({ id: 'turn-1:user', turnRef: 'turn-1', role: 'user', text: 'ادامه بده' }),
message({ id: 'turn-2:assistant', turnRef: 'turn-2', text: 'پاسخ عادی' }),
]);
expect(element.textContent).not.toContain(LIMITED_LABEL);
expect(element.textContent).toContain('ادامه بده');
expect(element.textContent).toContain('پاسخ عادی');
});
it('renders the limited indication in an RTL bubble', async () => {
const element = await render([message({ limited: true })]);
const bubble = element.querySelector('.bubble');
expect(bubble?.getAttribute('dir')).toBe('rtl');
expect(bubble?.classList.contains('is-limited')).toBe(true);
});
});
@@ -12,11 +12,42 @@ import { VoiceMessage, VoiceSource } from '../../../services/voice-stream/voice-
export class VoiceTranscriptComponent { export class VoiceTranscriptComponent {
readonly messages = input.required<VoiceMessage[]>(); readonly messages = input.required<VoiceMessage[]>();
/** "عنوان — صفحه ۱، بند ۲" */ /**
* Compact chip label: the excerpt's first paragraph, followed by an ellipsis when the
* chunk holds more paragraphs. The document's internal `location.section` path (e.g.
* "docx/table/1/row/1/cell/1") is document structure, not content, so it is not shown
* in the chip (it stays in the hover tooltip, along with the complete excerpt). Sources
* the server marks unavailable keep their excerpt hidden and fall back to the title.
*/
sourceLabel(source: VoiceSource): string { sourceLabel(source: VoiceSource): string {
if (source.available !== false) {
const excerpt = source.excerpt?.trim();
if (excerpt) {
// Paragraph breaks (single or repeated newlines) separate the excerpt into
// paragraphs; only the first one is summarized into the chip.
const paragraphs = excerpt
.split(/\r?\n+/)
.map((paragraph) => paragraph.trim())
.filter(Boolean);
const first = paragraphs[0];
if (first) return paragraphs.length > 1 ? `${first} …` : first;
}
}
return source.title || source.document_id;
}
/** Hover tooltip: document, location and the complete, untruncated excerpt. */
sourceTooltip(source: VoiceSource): string {
const parts: string[] = []; const parts: string[] = [];
if (source.title) parts.push(source.title);
if (source.location?.page != null) parts.push(`صفحه ${source.location.page}`); if (source.location?.page != null) parts.push(`صفحه ${source.location.page}`);
if (source.location?.section) parts.push(source.location.section); if (source.location?.section) parts.push(source.location.section);
return parts.length ? `${source.title} — ${parts.join('، ')}` : source.title; // Same hidden-excerpt rule as the chip label: a source the server marks unavailable
// has revoked text, so it is not surfaced here either.
if (source.available !== false) {
const excerpt = source.excerpt?.trim();
if (excerpt) parts.push(excerpt);
}
return parts.join('\n');
} }
} }
+45
View File
@@ -0,0 +1,45 @@
/**
* UUID generation that works outside secure contexts.
*
* `crypto.randomUUID()` only exists in secure contexts (HTTPS or `localhost`). It is
* unavailable on plain-HTTP origins — common for internal/LAN deployments — and calling
* it there throws `TypeError: crypto.randomUUID is not a function`, which took down
* login entirely. Every id the frontend mints per request (`X-Request-ID`,
* `Idempotency-Key`, `client_request_id`) therefore goes through here.
*/
/**
* RFC 4122 v4 UUID.
*
* Prefers `crypto.randomUUID()`, then `crypto.getRandomValues()` (available in every
* context, and what `randomUUID` itself is built on), and only then `Math.random()` —
* ids stay unique per request in all cases.
*/
export function uuid(): string {
const c: Crypto | undefined = typeof crypto !== 'undefined' ? crypto : undefined;
if (typeof c?.randomUUID === 'function') return c.randomUUID();
if (typeof c?.getRandomValues === 'function') {
const bytes = new Uint8Array(16);
c.getRandomValues(bytes);
// Version 4 (random) + RFC 4122 variant bits.
bytes[6] = (bytes[6] & 0x0f) | 0x40;
bytes[8] = (bytes[8] & 0x3f) | 0x80;
const hex: string[] = [];
for (let i = 0; i < 16; i++) {
hex.push(bytes[i].toString(16).padStart(2, '0'));
}
return (
`${hex.slice(0, 4).join('')}-${hex.slice(4, 6).join('')}-` +
`${hex.slice(6, 8).join('')}-${hex.slice(8, 10).join('')}-${hex.slice(10, 16).join('')}`
);
}
// Last resort: no Web Crypto at all. Not cryptographically strong, but still unique.
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (ch) => {
const r = (Math.random() * 16) | 0;
return (ch === 'x' ? r : (r & 0x3) | 0x8).toString(16);
});
}