build(ui): expand application shell and implement administrative dashboard pages
This commit significantly expands the application's routing, navigation, and administrative capabilities. It introduces several new functional modules and refines the core layout for a more professional, dashboard-oriented experience. - **Routing & Navigation**: - Added routes for `wallboard`, `call-center`, `call-center/calls`, and `chat-questions`. - Updated `SidebarComponent` to include all new navigation items. - Enhanced `LayoutComponent` with dynamic navigation based on user roles (admin vs. user). - **New Administrative Pages**: - `WallboardPage`: Implements a real-time KPI dashboard with call activity trends and outcome distributions. - `CallCenterPage`: Provides a symbolic interface for managing call center connectivity and synchronization. - `CallCenterCallsPage`: Implements a call history retrieval interface with filtering capabilities. - `ChatQuestionsPage`: Adds a module for reviewing user questions from web and mobile channels. - **Core Infrastructure & Refinement**: - Updated `AppConfig` to include an `APP_INITIALIZER` for validating user identity via `AuthService` on startup. - Refined `HomeComponent` layout to a "Claude-style" continuous chat column. - Implemented global themed scrollbars and integrated the 'Lahze' font family. - Added `proxy.conf.json` and updated `angular.json` to support local backend development. - **Documentation**: - Added comprehensive API handoff guides for frontend-backend connection and MVP API catalog.
This commit is contained in:
@@ -1,4 +1,9 @@
|
||||
import { provideZonelessChangeDetection } from '@angular/core';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideAnimations } from '@angular/platform-browser/animations';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { provideRouter } from '@angular/router';
|
||||
import { TOAST_CONFIG, DefaultGlobalConfig } from 'ngx-toastr';
|
||||
|
||||
import { AuthService } from './auth.service';
|
||||
|
||||
@@ -6,7 +11,15 @@ describe('AuthService', () => {
|
||||
let service: AuthService;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({});
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
provideZonelessChangeDetection(),
|
||||
provideHttpClient(),
|
||||
provideRouter([]),
|
||||
provideAnimations(),
|
||||
{ provide: TOAST_CONFIG, useValue: { default: DefaultGlobalConfig, config: {} } },
|
||||
],
|
||||
});
|
||||
service = TestBed.inject(AuthService);
|
||||
});
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
import { Observable, BehaviorSubject, forkJoin, of, throwError } from 'rxjs';
|
||||
import { tap, map, switchMap, catchError } from 'rxjs/operators';
|
||||
import { Observable, BehaviorSubject, firstValueFrom, throwError } from 'rxjs';
|
||||
import { tap, catchError } from 'rxjs/operators';
|
||||
import { HttpErrorResponse } from '@angular/common/http';
|
||||
import { HttpService } from '../http-request/http.service';
|
||||
|
||||
export interface AuthUser {
|
||||
@@ -16,24 +17,25 @@ export interface LoginResponse {
|
||||
expires_at: string;
|
||||
}
|
||||
|
||||
export interface CurrentUserResponse {
|
||||
user: AuthUser;
|
||||
csrf_token: string;
|
||||
expires_at: string;
|
||||
}
|
||||
export type CurrentUserResponse = LoginResponse;
|
||||
|
||||
/** All MVP routes live under `/api/v1` and are reached through the same-origin proxy. */
|
||||
const API = 'api/v1';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class AuthService {
|
||||
public currentUserSubject = new BehaviorSubject<AuthUser | null>(null);
|
||||
/** CSRF token is kept in memory only (never persisted): it is re-read from `/me` after every reload. */
|
||||
private csrfToken: string | null = null;
|
||||
/** True once `/me` confirmed the identity for this page load (the cookie is the source of truth). */
|
||||
private identityVerified = false;
|
||||
|
||||
constructor(
|
||||
private httpService: HttpService,
|
||||
) {
|
||||
constructor(private httpService: HttpService) {
|
||||
// Restore the last known user for instant rendering; `ensureIdentity()` re-validates
|
||||
// it against `/me` at bootstrap (the HttpOnly `rag_session` cookie is the real session).
|
||||
const savedUser = localStorage.getItem('current_user');
|
||||
const savedCsrf = localStorage.getItem('csrf_token');
|
||||
if (savedUser) {
|
||||
try {
|
||||
this.currentUserSubject.next(JSON.parse(savedUser));
|
||||
@@ -41,21 +43,17 @@ export class AuthService {
|
||||
// ignore corrupt data
|
||||
}
|
||||
}
|
||||
if (savedCsrf) {
|
||||
this.csrfToken = savedCsrf;
|
||||
}
|
||||
}
|
||||
|
||||
login(credentials: {
|
||||
username: string;
|
||||
password: string;
|
||||
}): Observable<LoginResponse> {
|
||||
return this.httpService.postRaw<LoginResponse>('v1/auth/login', credentials).pipe(
|
||||
return this.httpService.postRaw<LoginResponse>(`${API}/auth/login`, credentials, {
|
||||
headers: this.correlationHeaders(),
|
||||
}).pipe(
|
||||
tap((response) => {
|
||||
this.currentUserSubject.next(response.user);
|
||||
this.csrfToken = response.csrf_token;
|
||||
localStorage.setItem('current_user', JSON.stringify(response.user));
|
||||
localStorage.setItem('csrf_token', response.csrf_token);
|
||||
this.applyIdentity(response);
|
||||
}),
|
||||
catchError((err) => {
|
||||
this.clearAuth();
|
||||
@@ -65,15 +63,17 @@ export class AuthService {
|
||||
}
|
||||
|
||||
logout(): Observable<void> {
|
||||
const headers: Record<string, string> = {};
|
||||
const headers: Record<string, string> = this.correlationHeaders();
|
||||
if (this.csrfToken) {
|
||||
headers['X-CSRF-Token'] = this.csrfToken;
|
||||
}
|
||||
return this.httpService.postRaw<void>('v1/auth/logout', {}, { headers }).pipe(
|
||||
// A02 has no body and returns 204 without a JSON payload.
|
||||
return this.httpService.postRaw<void>(`${API}/auth/logout`, null, { headers }).pipe(
|
||||
tap(() => {
|
||||
this.clearAuth();
|
||||
}),
|
||||
catchError((err) => {
|
||||
// Even when A02 fails, the local session is dropped so the UI shows the signed-out state.
|
||||
this.clearAuth();
|
||||
return throwError(() => err);
|
||||
}),
|
||||
@@ -81,16 +81,42 @@ export class AuthService {
|
||||
}
|
||||
|
||||
getCurrentUser(): Observable<CurrentUserResponse> {
|
||||
return this.httpService.getRaw<CurrentUserResponse>('v1/me').pipe(
|
||||
return this.httpService.getRaw<CurrentUserResponse>(`${API}/me`, {
|
||||
headers: this.correlationHeaders(),
|
||||
}).pipe(
|
||||
tap((response) => {
|
||||
this.currentUserSubject.next(response.user);
|
||||
this.csrfToken = response.csrf_token;
|
||||
localStorage.setItem('current_user', JSON.stringify(response.user));
|
||||
localStorage.setItem('csrf_token', response.csrf_token);
|
||||
this.applyIdentity(response);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
/** Per-request correlation id shared with the server's `X-Request-ID`. */
|
||||
private correlationHeaders(): Record<string, string> {
|
||||
return { 'X-Request-ID': crypto.randomUUID() };
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads `/me` once per page load. After a reload this is the first call the app makes,
|
||||
* so a restored user is only trusted when the server still accepts the session cookie.
|
||||
* `401 AUTH_REQUIRED` clears the authenticated state; anything else keeps the cached user.
|
||||
*/
|
||||
async ensureIdentity(): Promise<boolean> {
|
||||
if (this.identityVerified) return this.isAuthenticated();
|
||||
try {
|
||||
const response = await firstValueFrom(this.getCurrentUser());
|
||||
this.identityVerified = true;
|
||||
return !!response?.user;
|
||||
} catch (err) {
|
||||
const res = err as HttpErrorResponse | undefined;
|
||||
const code = (res?.error as { error?: { code?: string } } | null)?.error?.code;
|
||||
if (res?.status === 401 || code === 'AUTH_REQUIRED') {
|
||||
// The cookie session is gone (expired/revoked): drop the authenticated state.
|
||||
this.clearAuth();
|
||||
}
|
||||
return this.isAuthenticated();
|
||||
}
|
||||
}
|
||||
|
||||
isAuthenticated(): boolean {
|
||||
return !!this.currentUserSubject.value;
|
||||
}
|
||||
@@ -103,10 +129,40 @@ export class AuthService {
|
||||
return this.csrfToken;
|
||||
}
|
||||
|
||||
private applyIdentity(response: LoginResponse): void {
|
||||
this.currentUserSubject.next(response.user);
|
||||
this.csrfToken = response.csrf_token;
|
||||
this.identityVerified = true;
|
||||
localStorage.setItem('current_user', JSON.stringify(response.user));
|
||||
}
|
||||
|
||||
private clearAuth(): void {
|
||||
this.currentUserSubject.next(null);
|
||||
this.csrfToken = null;
|
||||
this.identityVerified = false;
|
||||
localStorage.removeItem('current_user');
|
||||
localStorage.removeItem('csrf_token');
|
||||
}
|
||||
|
||||
/** Persian message for a backend error envelope code (catalog §7 / handoff §10). */
|
||||
static messageForError(err: unknown, fallback = 'خطا در ارتباط با سرور. لطفاً دوباره تلاش کنید.'): string {
|
||||
const res = err as HttpErrorResponse | undefined;
|
||||
const code = (res?.error as { error?: { code?: string; message?: string } } | null)?.error?.code;
|
||||
switch (code) {
|
||||
case 'INVALID_CREDENTIALS':
|
||||
return 'نام کاربری یا رمز عبور نامعتبر است.';
|
||||
case 'AUTH_REQUIRED':
|
||||
return 'نشست شما منقضی شده است. دوباره وارد شوید.';
|
||||
case 'CSRF_INVALID':
|
||||
return 'نشست شما نامعتبر است. دوباره وارد شوید.';
|
||||
case 'FORBIDDEN':
|
||||
return 'دسترسی به این بخش مجاز نیست.';
|
||||
case 'RATE_LIMITED':
|
||||
return 'تلاشهای بیش از حد مجاز. لطفاً بعداً تلاش کنید.';
|
||||
case 'DEPENDENCY_UNAVAILABLE':
|
||||
return 'سرویس موقتاً در دسترس نیست. لطفاً دوباره تلاش کنید.';
|
||||
default:
|
||||
if (!code && res && res.status === 0) return 'ارتباط با سرور برقرار نشد.';
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
import { provideZonelessChangeDetection } from '@angular/core';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient, HttpEventType } from '@angular/common/http';
|
||||
import { provideHttpClientTesting, HttpTestingController } from '@angular/common/http/testing';
|
||||
import { provideRouter } from '@angular/router';
|
||||
import { provideAnimations } from '@angular/platform-browser/animations';
|
||||
import { TOAST_CONFIG, DefaultGlobalConfig } from 'ngx-toastr';
|
||||
import { DocumentsService } from './documents.service';
|
||||
import { AuthService } from '../auth/auth.service';
|
||||
|
||||
describe('DocumentsService (backend handoff contract)', () => {
|
||||
let service: DocumentsService;
|
||||
let httpMock: HttpTestingController;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
provideZonelessChangeDetection(),
|
||||
provideHttpClient(),
|
||||
provideHttpClientTesting(),
|
||||
provideRouter([]),
|
||||
provideAnimations(),
|
||||
{ provide: TOAST_CONFIG, useValue: { default: DefaultGlobalConfig, config: {} } },
|
||||
{ provide: AuthService, useValue: { getCsrfToken: () => 'csrf-abc' } },
|
||||
],
|
||||
});
|
||||
service = TestBed.inject(DocumentsService);
|
||||
httpMock = TestBed.inject(HttpTestingController);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
httpMock.verify();
|
||||
});
|
||||
|
||||
it('uses same-origin /api/v1 paths for every MVP endpoint', () => {
|
||||
service.getConfiguration().subscribe();
|
||||
const req = httpMock.expectOne('/api/v1/configuration');
|
||||
expect(req.request.method).toBe('GET');
|
||||
req.flush({});
|
||||
|
||||
service.getDocuments({ status: 'ready', is_active: true }).subscribe();
|
||||
const list = httpMock.expectOne('/api/v1/documents?status=ready&is_active=true');
|
||||
list.flush({ items: [], next_cursor: null, knowledge_revision: 1 });
|
||||
|
||||
service.getKnowledgeSelection().subscribe();
|
||||
const selection = httpMock.expectOne('/api/v1/knowledge-selection');
|
||||
selection.flush({ active_document_ids: [], revision: 1 });
|
||||
});
|
||||
|
||||
it('sends the caller idempotency key for uploads and reuses FormData without manual Content-Type', () => {
|
||||
const file = new File([new Uint8Array([1, 2, 3])], 'faq.pdf', { type: 'application/pdf' });
|
||||
const progress: number[] = [];
|
||||
|
||||
service.uploadDocument(file, 'عنوان', (percent) => progress.push(percent), undefined, 'key-upload-1').subscribe();
|
||||
|
||||
const req = httpMock.expectOne('/api/v1/documents');
|
||||
expect(req.request.method).toBe('POST');
|
||||
expect(req.request.headers.get('Idempotency-Key')).toBe('key-upload-1');
|
||||
expect(req.request.headers.get('X-CSRF-Token')).toBe('csrf-abc');
|
||||
// The browser must own the multipart boundary.
|
||||
expect(req.request.headers.get('Content-Type')).toBeNull();
|
||||
expect((req.request.body as FormData).get('title')).toBe('عنوان');
|
||||
req.event({ type: HttpEventType.UploadProgress, loaded: 3, total: 3 });
|
||||
req.flush(
|
||||
{ document_id: 'doc-1', job_id: 'job-1' },
|
||||
{ status: 202, statusText: 'Accepted' },
|
||||
);
|
||||
expect(progress).toEqual([100]);
|
||||
});
|
||||
|
||||
it('sends the same decision key on replay and forbids an empty note payload shape', () => {
|
||||
service
|
||||
.submitReviewDecision('doc-1', {
|
||||
evidence_sha256: 'sha-1',
|
||||
decision: 'approve',
|
||||
checked: ['check-a'],
|
||||
note: 'تأیید شد',
|
||||
excluded_group_ids: [],
|
||||
}, 'key-decision-1')
|
||||
.subscribe();
|
||||
|
||||
const req = httpMock.expectOne('/api/v1/documents/doc-1/extraction-review/decisions');
|
||||
expect(req.request.method).toBe('POST');
|
||||
expect(req.request.headers.get('Idempotency-Key')).toBe('key-decision-1');
|
||||
expect(req.request.body).toEqual({
|
||||
evidence_sha256: 'sha-1',
|
||||
decision: 'approve',
|
||||
checked: ['check-a'],
|
||||
note: 'تأیید شد',
|
||||
excluded_group_ids: [],
|
||||
});
|
||||
req.flush({ decision_id: 'dec-1', review_state: 'pending' });
|
||||
|
||||
// Replaying the SAME key must hit the same URL with the same payload — the server
|
||||
// deduplicates it (Idempotency-Replayed: true) instead of creating a second decision.
|
||||
service
|
||||
.submitReviewDecision(
|
||||
'doc-1',
|
||||
{
|
||||
evidence_sha256: 'sha-1',
|
||||
decision: 'approve',
|
||||
checked: ['check-a'],
|
||||
note: 'تأیید شد',
|
||||
excluded_group_ids: [],
|
||||
},
|
||||
'key-decision-1',
|
||||
)
|
||||
.subscribe();
|
||||
const replay = httpMock.expectOne('/api/v1/documents/doc-1/extraction-review/decisions');
|
||||
expect(replay.request.headers.get('Idempotency-Key')).toBe('key-decision-1');
|
||||
replay.flush({ decision_id: 'dec-1', review_state: 'pending' }, {
|
||||
status: 200,
|
||||
statusText: 'OK',
|
||||
headers: { 'Idempotency-Replayed': 'true' },
|
||||
} as never);
|
||||
});
|
||||
|
||||
it('retries the same job through D04 with an explicit idempotency key', () => {
|
||||
service.retryDocument('doc-1', 'key-retry-1').subscribe();
|
||||
|
||||
const req = httpMock.expectOne('/api/v1/documents/doc-1/retry');
|
||||
expect(req.request.method).toBe('POST');
|
||||
expect(req.request.headers.get('Idempotency-Key')).toBe('key-retry-1');
|
||||
req.flush({ job_id: 'job-1', status: 'queued' }, { status: 202, statusText: 'Accepted' });
|
||||
});
|
||||
|
||||
it('replaces the whole selection with a revision guard and no idempotency key (K02)', () => {
|
||||
service.updateKnowledgeSelection({ expected_revision: 3, document_ids: ['doc-1', 'doc-2'] }).subscribe();
|
||||
|
||||
const req = httpMock.expectOne('/api/v1/knowledge-selection');
|
||||
expect(req.request.method).toBe('PATCH');
|
||||
expect(req.request.body).toEqual({ expected_revision: 3, document_ids: ['doc-1', 'doc-2'] });
|
||||
// K02 is revision-controlled: no Idempotency-Key header.
|
||||
expect(req.request.headers.get('Idempotency-Key')).toBeNull();
|
||||
expect(req.request.headers.get('X-CSRF-Token')).toBe('csrf-abc');
|
||||
req.flush({ revision: 4, active_document_ids: ['doc-1', 'doc-2'], conversations_invalidated: true });
|
||||
});
|
||||
|
||||
it('surfaces the error envelope code and request id for correlation', () => {
|
||||
let captured: { code: string; message: string; requestId?: string } = { code: '', message: '' };
|
||||
service.updateKnowledgeSelection({ expected_revision: 9, document_ids: [] }).subscribe({
|
||||
error: (err) => {
|
||||
captured = DocumentsService.getErrorInfo(err);
|
||||
},
|
||||
});
|
||||
|
||||
httpMock.expectOne('/api/v1/knowledge-selection').flush(
|
||||
{ error: { code: 'REVISION_CONFLICT', message: 'Request could not be completed.', request_id: 'corr-1', retryable: false } },
|
||||
{ status: 409, statusText: 'Conflict', headers: { 'X-Request-ID': 'corr-1' } },
|
||||
);
|
||||
|
||||
expect(captured.code).toBe('REVISION_CONFLICT');
|
||||
expect(captured.requestId).toBe('corr-1');
|
||||
expect(DocumentsService.statusForError(captured.code, captured.message)).toContain('همزمان');
|
||||
});
|
||||
|
||||
it('maps contract error codes to Persian guidance', () => {
|
||||
expect(DocumentsService.statusForError('DOCUMENT_NOT_READY', '')).toContain('آماده');
|
||||
expect(DocumentsService.statusForError('EXTRACTION_REVIEW_PENDING', '')).toContain('بازبینی');
|
||||
expect(DocumentsService.statusForError('REVIEW_STALE', '')).toContain('شواهد');
|
||||
expect(DocumentsService.statusForError('CONTEXT_REVOKED', '')).toContain('باطل');
|
||||
expect(DocumentsService.statusForError('RATE_LIMITED', '')).toContain('حد مجاز');
|
||||
expect(DocumentsService.isPolling('processing')).toBe(true);
|
||||
expect(DocumentsService.isPolling('ready')).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,244 @@
|
||||
import { Injectable, inject } from '@angular/core';
|
||||
import { HttpErrorResponse, HttpEventType, HttpHeaders, HttpParams } from '@angular/common/http';
|
||||
import { map, filter, Observable, tap } from 'rxjs';
|
||||
import { HttpService } from '../http-request/http.service';
|
||||
import { AuthService } from '../auth/auth.service';
|
||||
import {
|
||||
DocumentDetail,
|
||||
DocumentListParams,
|
||||
DocumentListResponse,
|
||||
DocumentStatus,
|
||||
DocumentUploadResult,
|
||||
ErrorEnvelope,
|
||||
ExtractionItem,
|
||||
ExtractionReviewResponse,
|
||||
KnowledgeSelection,
|
||||
KnowledgeSelectionPatch,
|
||||
KnowledgeSelectionResponse,
|
||||
RetryResult,
|
||||
ReviewDecisionRequest,
|
||||
ReviewDecisionResponse,
|
||||
SystemConfiguration,
|
||||
} from './documents.types';
|
||||
|
||||
/** Base path for the documented MVP endpoints (`/api/v1/...`), served same-origin. */
|
||||
const API = 'api/v1';
|
||||
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class DocumentsService {
|
||||
private readonly http = inject(HttpService);
|
||||
private readonly auth = inject(AuthService);
|
||||
|
||||
/**
|
||||
* Headers required for every state-changing MVP call: a fresh CSRF token
|
||||
* (from the login/`/me` flow) and a per-request correlation id.
|
||||
*/
|
||||
private csrfHeaders(): Record<string, string> {
|
||||
const headers: Record<string, string> = { 'X-Request-ID': crypto.randomUUID() };
|
||||
const token = this.auth.getCsrfToken();
|
||||
if (token) {
|
||||
headers['X-CSRF-Token'] = token;
|
||||
}
|
||||
return headers;
|
||||
}
|
||||
|
||||
/**
|
||||
* Idempotent operations (D01 upload, D07 decisions, D04 retry) take the caller's key:
|
||||
* an ambiguous failure (timeout / dropped connection) must replay the SAME key with the
|
||||
* SAME payload — minting a new key would create a second document/decision/retry.
|
||||
* `Idempotency-Replayed: true` on a successful replay confirms the server deduplicated it.
|
||||
*/
|
||||
private idempotencyHeaders(key: string): Record<string, string> {
|
||||
return { ...this.csrfHeaders(), 'Idempotency-Key': key };
|
||||
}
|
||||
|
||||
private onlyDefined(params: DocumentListParams): Record<string, string> {
|
||||
const out: Record<string, string> = {};
|
||||
if (params.limit != null) out['limit'] = String(params.limit);
|
||||
if (params.cursor) out['cursor'] = params.cursor;
|
||||
if (params.status) out['status'] = params.status;
|
||||
if (params.is_active != null) out['is_active'] = String(params.is_active);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** F01 — read-only capabilities used to configure upload validation. */
|
||||
getConfiguration(): Observable<SystemConfiguration> {
|
||||
return this.http.getRaw<SystemConfiguration>(`${API}/configuration`, { skipToast: true });
|
||||
}
|
||||
|
||||
/** D02 — paginated document list. */
|
||||
getDocuments(params: DocumentListParams = {}): Observable<DocumentListResponse> {
|
||||
const query = new HttpParams({ fromObject: this.onlyDefined(params) });
|
||||
return this.http.getRaw<DocumentListResponse>(`${API}/documents`, {
|
||||
params: query,
|
||||
skipToast: true,
|
||||
});
|
||||
}
|
||||
|
||||
/** D03 — single document detail (used for 2-second status polling). */
|
||||
getDocument(id: string): Observable<DocumentDetail> {
|
||||
return this.http.getRaw<DocumentDetail>(`${API}/documents/${encodeURIComponent(id)}`, {
|
||||
skipToast: true,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* D01 — upload a single document with live progress.
|
||||
* @param idempotencyKey caller-owned key; replay the SAME key for an uncertain outcome.
|
||||
*/
|
||||
uploadDocument(
|
||||
file: File,
|
||||
title: string | undefined,
|
||||
onProgress: (percent: number) => void,
|
||||
signal?: AbortSignal,
|
||||
idempotencyKey: string = crypto.randomUUID(),
|
||||
): Observable<DocumentUploadResult> {
|
||||
const form = new FormData();
|
||||
form.append('file', file);
|
||||
if (title) {
|
||||
form.append('title', title);
|
||||
}
|
||||
return this.http
|
||||
.uploadWithProgress<DocumentUploadResult>(`${API}/documents`, form, {
|
||||
headers: this.idempotencyHeaders(idempotencyKey),
|
||||
skipToast: true,
|
||||
signal,
|
||||
})
|
||||
.pipe(
|
||||
tap((event) => {
|
||||
if (event.type === HttpEventType.UploadProgress && event.total) {
|
||||
onProgress(Math.round((100 * event.loaded) / event.total));
|
||||
}
|
||||
}),
|
||||
filter((event) => event.type === HttpEventType.Response),
|
||||
map(
|
||||
(event) =>
|
||||
(event as import('@angular/common/http').HttpResponse<DocumentUploadResult>)
|
||||
.body as DocumentUploadResult,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/** D07 — submit an extraction-review decision (approve/reject). */
|
||||
submitReviewDecision(
|
||||
documentId: string,
|
||||
request: ReviewDecisionRequest,
|
||||
idempotencyKey: string = crypto.randomUUID(),
|
||||
): Observable<ReviewDecisionResponse> {
|
||||
return this.http.postRaw<ReviewDecisionResponse>(
|
||||
`${API}/documents/${encodeURIComponent(documentId)}/extraction-review/decisions`,
|
||||
request,
|
||||
{ headers: this.idempotencyHeaders(idempotencyKey), skipToast: true },
|
||||
);
|
||||
}
|
||||
|
||||
/** D06 — extraction-review evidence items. */
|
||||
getExtractionReview(documentId: string, cursor?: string): Observable<ExtractionReviewResponse> {
|
||||
const params: Record<string, string> = {};
|
||||
if (cursor) {
|
||||
params['cursor'] = cursor;
|
||||
}
|
||||
return this.http.getRaw<ExtractionReviewResponse>(
|
||||
`${API}/documents/${encodeURIComponent(documentId)}/extraction-review`,
|
||||
{ params, skipToast: true },
|
||||
);
|
||||
}
|
||||
|
||||
/** D04 — retry processing of a document. */
|
||||
retryDocument(
|
||||
documentId: string,
|
||||
idempotencyKey: string = crypto.randomUUID(),
|
||||
): Observable<RetryResult> {
|
||||
return this.http.postRaw<RetryResult>(
|
||||
`${API}/documents/${encodeURIComponent(documentId)}/retry`,
|
||||
{},
|
||||
{ headers: this.idempotencyHeaders(idempotencyKey), skipToast: true },
|
||||
);
|
||||
}
|
||||
|
||||
/** K01 — current active-knowledge selection (revision + active document ids). */
|
||||
getKnowledgeSelection(): Observable<KnowledgeSelection> {
|
||||
return this.http.getRaw<KnowledgeSelection>(`${API}/knowledge-selection`, { skipToast: true });
|
||||
}
|
||||
|
||||
/**
|
||||
* K02 — replace the whole active-knowledge selection. The full set is keyed by
|
||||
* `expected_revision` (no Idempotency-Key): after a timeout or REVISION_CONFLICT the UI
|
||||
* re-reads K01 first instead of blindly repeating the request.
|
||||
*/
|
||||
updateKnowledgeSelection(patch: KnowledgeSelectionPatch): Observable<KnowledgeSelectionResponse> {
|
||||
return this.http.patchRaw<KnowledgeSelectionResponse>(`${API}/knowledge-selection`, patch, {
|
||||
headers: this.csrfHeaders(),
|
||||
skipToast: true,
|
||||
});
|
||||
}
|
||||
|
||||
/** Extract the standard error envelope from an HttpErrorResponse, if present. */
|
||||
static getErrorInfo(error: unknown): { code: string; message: string; requestId?: string } {
|
||||
const res = error as HttpErrorResponse | undefined;
|
||||
const envelope = res?.error as ErrorEnvelope | undefined;
|
||||
const code = envelope?.error?.code ?? (res?.status === 0 ? 'NETWORK' : 'UNKNOWN');
|
||||
const message = envelope?.error?.message ?? res?.message ?? 'خطای ناشناخته سرور';
|
||||
const requestId =
|
||||
envelope?.error?.request_id ??
|
||||
(res?.headers?.get?.('X-Request-ID') as string | undefined) ??
|
||||
undefined;
|
||||
return { code, message, requestId };
|
||||
}
|
||||
|
||||
/** Map a backend error code to a user-facing Persian message (handoff §10 / catalog §7). */
|
||||
static statusForError(code: string, fallback: string): string {
|
||||
switch (code) {
|
||||
case 'DOCUMENT_NOT_READY':
|
||||
return 'فقط اسناد وضعیت آماده قابل فعالسازی هستند.';
|
||||
case 'EXTRACTION_REVIEW_PENDING':
|
||||
return 'قبل از تلاش مجدد، شواهد نیازمند بازبینی را تکمیل کنید.';
|
||||
case 'REVISION_CONFLICT':
|
||||
return 'لیست دانش همزمان توسط کاربر دیگری بهروز شده است. صفحه را تازهسازی کنید.';
|
||||
case 'IDEMPOTENCY_CONFLICT':
|
||||
return 'این عملیات قبلاً با محتوای دیگری ثبت شده است.';
|
||||
case 'REVIEW_STALE':
|
||||
case 'REVIEW_ALREADY_DECIDED':
|
||||
return 'شواهد بازبینی تغییر کرده است؛ موارد را دوباره خوانده و تصمیم بگیرید.';
|
||||
case 'FILE_TOO_LARGE':
|
||||
case 'PAYLOAD_TOO_LARGE':
|
||||
return 'حجم فایل یا درخواست بیش از حد مجاز است.';
|
||||
case 'UNSUPPORTED_FILE_TYPE':
|
||||
return 'نوع فایل پشتیبانی نمیشود.';
|
||||
case 'INVALID_FILE':
|
||||
return 'فایل قابل پردازش نیست.';
|
||||
case 'VALIDATION_ERROR':
|
||||
return 'شکل درخواست نامعتبر است.';
|
||||
case 'CONTEXT_REVOKED':
|
||||
case 'CONVERSATION_STALE':
|
||||
return 'مکالمههای صوتی قبلی بهدلیل تغییر محتوای دانش باطل شدهاند. گفتگوی جدیدی شروع کنید.';
|
||||
case 'LIVE_SESSION_UNUSABLE':
|
||||
return 'نشست صوتی بسته شده است. گفتگوی جدیدی شروع کنید.';
|
||||
case 'RATE_LIMITED':
|
||||
return 'تلاشهای بیش از حد مجاز. لطفاً بعداً تلاش کنید.';
|
||||
case 'CALIBRATION_REQUIRED':
|
||||
case 'DEPENDENCY_UNAVAILABLE':
|
||||
return 'سرویس موقتاً در دسترس نیست. لطفاً دوباره تلاش کنید.';
|
||||
case 'AUTH_REQUIRED':
|
||||
return 'ابتدا وارد سیستم شوید.';
|
||||
case 'CSRF_INVALID':
|
||||
return 'نشست شما نامعتبر است. دوباره وارد شوید.';
|
||||
case 'FORBIDDEN':
|
||||
return 'دسترسی به این عملیات مجاز نیست.';
|
||||
case 'NETWORK':
|
||||
return 'ارتباط با سرور برقرار نشد.';
|
||||
default:
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
/** True if the backend status is a terminal state (no more polling). */
|
||||
static isTerminal(status: DocumentStatus): boolean {
|
||||
return status === 'ready' || status === 'failed';
|
||||
}
|
||||
|
||||
/** Whether a status row still needs to be polled per D03. */
|
||||
static isPolling(status: DocumentStatus): boolean {
|
||||
return !DocumentsService.isTerminal(status);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
/**
|
||||
* Type definitions for the MVP document / knowledge-selection / extraction-review API.
|
||||
* Source of truth: docs/backend-api-docs/mvp_ui_api_catalog.md
|
||||
*
|
||||
* These endpoints return *raw* JSON (not the ApiResult envelope used by the legacy
|
||||
* HttpService envelope methods), so they are consumed through `getRaw`/`postRaw`/
|
||||
* `patchRaw`/`uploadWithProgress` and errors are inspected via the standard
|
||||
* `{ error: { code, message, request_id, retryable, details } }` envelope.
|
||||
*/
|
||||
|
||||
/** Document processing lifecycle. */
|
||||
export type DocumentStatus = 'queued' | 'processing' | 'ready' | 'failed';
|
||||
|
||||
/** Frozen-per-document OCR review policy state (D03). */
|
||||
export type ReviewState = 'not_evaluated' | 'not_required' | 'pending' | 'approved' | 'rejected';
|
||||
|
||||
/** Extraction quality decision; never fabricate a human-approval claim from it. */
|
||||
export type ExtractionQualityDecision = null | 'passed' | 'reviewed' | 'partially_reviewed';
|
||||
|
||||
export interface DocumentLocation {
|
||||
page?: number | null;
|
||||
section?: string | null;
|
||||
}
|
||||
|
||||
export interface DocumentJobError {
|
||||
code: string;
|
||||
message: string;
|
||||
request_id?: string;
|
||||
retryable?: boolean;
|
||||
details?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface DocumentJob {
|
||||
id: string;
|
||||
status: string;
|
||||
stage: string | null;
|
||||
attempt_count: number;
|
||||
retry_generation: number;
|
||||
can_retry: boolean;
|
||||
error: DocumentJobError | null;
|
||||
}
|
||||
|
||||
/** A single document row as returned by `GET /documents` (D02). */
|
||||
export interface DocumentListItem {
|
||||
id: string;
|
||||
title: string | null;
|
||||
filename: string;
|
||||
status: DocumentStatus;
|
||||
is_active: boolean;
|
||||
searchable: boolean;
|
||||
chunk_count: number;
|
||||
created_at: string;
|
||||
job: DocumentJob;
|
||||
/** Present on the detail/polling response (D03); absent from the base list. */
|
||||
review_required?: boolean;
|
||||
/** Frozen OCR policy of this document (D03); the UI has no toggle for it. */
|
||||
ocr_review_required?: boolean;
|
||||
review_state?: ReviewState;
|
||||
extraction_quality_decision?: ExtractionQualityDecision;
|
||||
}
|
||||
|
||||
/** `GET /documents` (D02) paginated result. */
|
||||
export interface DocumentListResponse {
|
||||
items: DocumentListItem[];
|
||||
next_cursor: string | null;
|
||||
knowledge_revision: number;
|
||||
}
|
||||
|
||||
/** Query parameters accepted by `GET /documents`. */
|
||||
export interface DocumentListParams {
|
||||
limit?: number;
|
||||
cursor?: string;
|
||||
status?: DocumentStatus;
|
||||
is_active?: boolean;
|
||||
}
|
||||
|
||||
/** `GET /documents/{id}` (D03) — same as a list item plus the review flag. */
|
||||
export interface DocumentDetail extends DocumentListItem {
|
||||
review_required: boolean;
|
||||
}
|
||||
|
||||
/** `POST /documents` (D01) accepted payload. */
|
||||
export interface DocumentUploadResult {
|
||||
document_id: string;
|
||||
job_id: string;
|
||||
status: DocumentStatus;
|
||||
is_active: boolean;
|
||||
searchable: boolean;
|
||||
}
|
||||
|
||||
/** `POST /documents/{id}/retry` (D04) accepted payload. */
|
||||
export interface RetryResult {
|
||||
document_id: string;
|
||||
job_id: string;
|
||||
status: DocumentStatus;
|
||||
retry_generation: number;
|
||||
}
|
||||
|
||||
/** A single extraction block from `GET /documents/{id}/extraction-review` (D06). */
|
||||
export interface ExtractionBlock {
|
||||
block_id: string;
|
||||
text: string;
|
||||
group_id: string | null;
|
||||
}
|
||||
|
||||
/** One reviewable evidence item from D06 (extraction or factual_corpus). */
|
||||
export interface ExtractionItem {
|
||||
evidence_sha256: string;
|
||||
review_kind: string;
|
||||
location?: DocumentLocation | null;
|
||||
blocks: ExtractionBlock[];
|
||||
required_checks: string[];
|
||||
decision: 'approve' | 'reject' | null;
|
||||
/** Authenticated preview URL from the server (may be null, e.g. factual evidence). */
|
||||
preview_path: string | null;
|
||||
}
|
||||
|
||||
/** `GET /documents/{id}/extraction-review` (D06). */
|
||||
export interface ExtractionReviewResponse {
|
||||
document_id: string;
|
||||
status: DocumentStatus;
|
||||
review_required: boolean;
|
||||
items: ExtractionItem[];
|
||||
next_cursor: string | null;
|
||||
}
|
||||
|
||||
/** `POST /documents/{id}/extraction-review/decisions` (D07). */
|
||||
export interface ReviewDecisionRequest {
|
||||
evidence_sha256: string;
|
||||
decision: 'approve' | 'reject';
|
||||
checked: string[];
|
||||
note?: string;
|
||||
excluded_group_ids?: string[];
|
||||
}
|
||||
|
||||
export interface ReviewDecisionResponse {
|
||||
document_id: string;
|
||||
evidence_sha256: string;
|
||||
decision: 'approve' | 'reject';
|
||||
review_required: boolean;
|
||||
}
|
||||
|
||||
/** System configuration / capabilities from `GET /configuration` (F01). */
|
||||
export interface SystemConfiguration {
|
||||
revision: number;
|
||||
assistant_name: string;
|
||||
instruction: string;
|
||||
capabilities: SystemCapabilities;
|
||||
}
|
||||
|
||||
export interface SystemCapabilities {
|
||||
text: boolean;
|
||||
voice: boolean;
|
||||
captions: boolean;
|
||||
supported_upload_types: string[];
|
||||
max_upload_bytes: number;
|
||||
max_pdf_pages: number;
|
||||
supported_structure_notes: string;
|
||||
}
|
||||
|
||||
/** `GET /knowledge-selection` (K01). */
|
||||
export interface KnowledgeSelection {
|
||||
revision: number;
|
||||
access_epoch: number;
|
||||
document_ids: string[];
|
||||
}
|
||||
|
||||
/** `PATCH /knowledge-selection` (K02) request / response. */
|
||||
export interface KnowledgeSelectionPatch {
|
||||
expected_revision: number;
|
||||
document_ids: string[];
|
||||
}
|
||||
|
||||
export interface KnowledgeSelectionResponse extends KnowledgeSelection {
|
||||
conversations_invalidated: boolean;
|
||||
}
|
||||
|
||||
/** Standard error envelope carried on a non-2xx response body. */
|
||||
export interface ErrorEnvelope {
|
||||
error: {
|
||||
code: string;
|
||||
message: string;
|
||||
request_id?: string;
|
||||
retryable?: boolean;
|
||||
details?: Record<string, unknown>;
|
||||
};
|
||||
}
|
||||
|
||||
/** Persian labels for document processing status. */
|
||||
export const DOCUMENT_STATUS_LABEL: Record<DocumentStatus, string> = {
|
||||
queued: 'در صف پردازش',
|
||||
processing: 'در حال پردازش',
|
||||
ready: 'آماده',
|
||||
failed: 'ناموفق',
|
||||
};
|
||||
@@ -1,4 +1,9 @@
|
||||
import { provideZonelessChangeDetection } from '@angular/core';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideAnimations } from '@angular/platform-browser/animations';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { provideRouter } from '@angular/router';
|
||||
import { TOAST_CONFIG, DefaultGlobalConfig } from 'ngx-toastr';
|
||||
|
||||
import { HttpService } from './http.service';
|
||||
|
||||
@@ -6,7 +11,15 @@ describe('HttpService', () => {
|
||||
let service: HttpService;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({});
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
provideZonelessChangeDetection(),
|
||||
provideHttpClient(),
|
||||
provideRouter([]),
|
||||
provideAnimations(),
|
||||
{ provide: TOAST_CONFIG, useValue: { default: DefaultGlobalConfig, config: {} } },
|
||||
],
|
||||
});
|
||||
service = TestBed.inject(HttpService);
|
||||
});
|
||||
|
||||
|
||||
@@ -1,7 +1,13 @@
|
||||
import { Injectable } from '@angular/core';
|
||||
import { HttpClient, HttpErrorResponse, HttpHeaders } from '@angular/common/http';
|
||||
import {
|
||||
HttpClient,
|
||||
HttpErrorResponse,
|
||||
HttpHeaders,
|
||||
HttpEvent,
|
||||
HttpEventType,
|
||||
} from '@angular/common/http';
|
||||
import { Router } from '@angular/router';
|
||||
import { catchError, Observable, throwError, map } from 'rxjs';
|
||||
import { catchError, Observable, throwError, map, race } from 'rxjs';
|
||||
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
|
||||
import { ToastrService } from 'ngx-toastr';
|
||||
|
||||
@@ -25,6 +31,8 @@ export interface HttpOptions {
|
||||
cooldownMs?: number;
|
||||
skipHasErrorCheck?: boolean;
|
||||
headers?: Record<string, string>;
|
||||
/** Optional AbortSignal forwarded to the underlying XMLHttpRequest. */
|
||||
signal?: AbortSignal;
|
||||
}
|
||||
|
||||
export const EVENT_STREAM_HEADERS = {
|
||||
@@ -37,15 +45,16 @@ export const EVENT_STREAM_HEADERS = {
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class HttpService {
|
||||
// private readonly baseUrl = `${window.location.protocol}//${window.location.hostname}/api`;
|
||||
// public readonly backendUrl = `${window.location.protocol}//${window.location.hostname}/api`;
|
||||
// public readonly apiUrl = `${window.location.protocol}//${window.location.hostname}/api`;
|
||||
// public readonly imagesUrl = `${window.location.protocol}//${window.location.hostname}`;
|
||||
|
||||
private readonly baseUrl = `http://192.168.180.151:1321`;
|
||||
public readonly backendUrl = `http://192.168.180.151:1321`;
|
||||
public readonly apiUrl = `http://192.168.180.151:1321`;
|
||||
public readonly imagesUrl = `http://192.168.180.151:1321`;
|
||||
/**
|
||||
* Same-origin deployment: the browser talks to `/api/v1/...` on the UI origin and
|
||||
* the dev-server proxy (proxy.conf.json) forwards `/api` — including WebSocket
|
||||
* upgrades — to the backend. The `rag_session` cookie therefore stays same-origin
|
||||
* and is sent automatically; no bearer token is used for the MVP endpoints.
|
||||
*/
|
||||
private readonly baseUrl = 'http://10.0.8.51:1321';
|
||||
public readonly backendUrl = 'http://10.0.8.51:1321';
|
||||
public readonly apiUrl = 'http://10.0.8.51:1321';
|
||||
public readonly imagesUrl = 'http://10.0.8.51:1321';
|
||||
|
||||
constructor(
|
||||
private readonly http: HttpClient,
|
||||
@@ -197,7 +206,7 @@ export class HttpService {
|
||||
...headers,
|
||||
},
|
||||
signal: controller.signal,
|
||||
credentials: 'omit',
|
||||
credentials: 'same-origin',
|
||||
})
|
||||
.then((response) => {
|
||||
if (!response.ok || !response.body) {
|
||||
@@ -275,6 +284,57 @@ export class HttpService {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Raw PATCH (no envelope processing, no bearer token): used by MVP endpoints
|
||||
* such as `PATCH /knowledge-selection` whose auth is the `rag_session` cookie.
|
||||
*/
|
||||
patchRaw<T>(endpoint: string, data: any, options: HttpOptions = {}): Observable<T> {
|
||||
const url = `${this.baseUrl}/${endpoint}`;
|
||||
const headers = options.headers ? new HttpHeaders(options.headers) : new HttpHeaders();
|
||||
return this.http
|
||||
.patch<T>(url, data, { headers, params: options.params })
|
||||
.pipe(catchError((err) => this.handleError(err, options.skipToast)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Multipart upload that reports byte-level progress as `HttpEvent`s.
|
||||
* Auth is the session cookie (same origin), so — like `postRaw`/`getRaw` — the
|
||||
* bearer token is not injected; pass `X-CSRF-Token` / `Idempotency-Key` via `options.headers`.
|
||||
* Cancellation is driven by racing the request against an `AbortSignal`-derived error;
|
||||
* the race's teardown unsubscribes and aborts the in-flight XHR.
|
||||
*/
|
||||
uploadWithProgress<T>(
|
||||
endpoint: string,
|
||||
data: FormData,
|
||||
options: HttpOptions = {},
|
||||
): Observable<HttpEvent<T>> {
|
||||
const url = `${this.baseUrl}/${endpoint}`;
|
||||
const headers = options.headers ? new HttpHeaders(options.headers) : new HttpHeaders();
|
||||
const http$ = this.http.post<T>(url, data, {
|
||||
headers,
|
||||
params: options.params,
|
||||
reportProgress: true,
|
||||
observe: 'events',
|
||||
});
|
||||
|
||||
if (!options.signal) {
|
||||
return http$.pipe(catchError((err) => this.handleError(err, options.skipToast)));
|
||||
}
|
||||
|
||||
const abort$ = new Observable<never>((subscriber) => {
|
||||
if (options.signal!.aborted) {
|
||||
subscriber.error(new HttpErrorResponse({ status: 0, statusText: 'Aborted', url }));
|
||||
return;
|
||||
}
|
||||
const onAbort = () =>
|
||||
subscriber.error(new HttpErrorResponse({ status: 0, statusText: 'Aborted', url }));
|
||||
options.signal!.addEventListener('abort', onAbort);
|
||||
return () => options.signal!.removeEventListener('abort', onAbort);
|
||||
});
|
||||
|
||||
return race(http$, abort$).pipe(catchError((err) => this.handleError(err, options.skipToast)));
|
||||
}
|
||||
|
||||
getRaw<T>(endpoint: string, options: HttpOptions = {}): Observable<T> {
|
||||
const url = `${this.baseUrl}/${endpoint}`;
|
||||
const headers = options.headers ? new HttpHeaders(options.headers) : new HttpHeaders();
|
||||
|
||||
@@ -1,4 +1,9 @@
|
||||
import { provideZonelessChangeDetection } from '@angular/core';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideAnimations } from '@angular/platform-browser/animations';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { provideRouter } from '@angular/router';
|
||||
import { TOAST_CONFIG, DefaultGlobalConfig } from 'ngx-toastr';
|
||||
|
||||
import { ThemeService } from './theme.service';
|
||||
|
||||
@@ -6,7 +11,15 @@ describe('ThemeService', () => {
|
||||
let service: ThemeService;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({});
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
provideZonelessChangeDetection(),
|
||||
provideHttpClient(),
|
||||
provideRouter([]),
|
||||
provideAnimations(),
|
||||
{ provide: TOAST_CONFIG, useValue: { default: DefaultGlobalConfig, config: {} } },
|
||||
],
|
||||
});
|
||||
service = TestBed.inject(ThemeService);
|
||||
});
|
||||
|
||||
|
||||
@@ -21,7 +21,7 @@ export class ThemeService {
|
||||
this.applyTheme('light');
|
||||
}
|
||||
|
||||
this.httpService.get('users/get-dark-mode').subscribe({
|
||||
this.httpService.get('users/get-dark-mode', { skipToast: true }).subscribe({
|
||||
next: (res: any) => {
|
||||
const isBackendDark = res.result.dark_mode;
|
||||
const trueTheme = isBackendDark ? 'dark' : 'light';
|
||||
@@ -41,7 +41,7 @@ export class ThemeService {
|
||||
|
||||
const payload = { dark_mode: isDark };
|
||||
|
||||
this.httpService.post('users/update-dark-mode', payload).subscribe({
|
||||
this.httpService.post('users/update-dark-mode', payload, { skipToast: true }).subscribe({
|
||||
next: () => {},
|
||||
error: () => {}
|
||||
});
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
import { HttpClient, HttpErrorResponse, HttpHeaders } from '@angular/common/http';
|
||||
import { Injectable, inject } from '@angular/core';
|
||||
import { firstValueFrom, Observable } from 'rxjs';
|
||||
import { VOICE_STREAM_CONFIG } from './voice-stream.types';
|
||||
import { firstValueFrom, race, throwError, Observable } from 'rxjs';
|
||||
import { delay } from 'rxjs/operators';
|
||||
import { VOICE_STREAM_CONFIG, VoiceSessionStatus } from './voice-stream.types';
|
||||
|
||||
/** Error envelope from the catalog: { error: { code, message, request_id, retryable, details } }. */
|
||||
/** The voice helper's HTTP deadline: a client timeout never means the server rolled back. */
|
||||
const REQUEST_DEADLINE_MS = 5000;
|
||||
|
||||
/** Error envelope from the contract: { error: { code, message, request_id, retryable, details } }. */
|
||||
export class VoiceApiError extends Error {
|
||||
constructor(
|
||||
readonly status: number,
|
||||
@@ -24,14 +28,26 @@ export interface MeResponse {
|
||||
}
|
||||
|
||||
export interface ConfigurationResponse {
|
||||
capabilities: { text: boolean; voice: boolean; captions: boolean };
|
||||
revision: number;
|
||||
assistant_name: string;
|
||||
instruction: string;
|
||||
capabilities: {
|
||||
text: boolean;
|
||||
voice: boolean;
|
||||
captions: boolean;
|
||||
supported_upload_types?: string[];
|
||||
max_upload_bytes?: number;
|
||||
max_pdf_pages?: number;
|
||||
};
|
||||
}
|
||||
|
||||
export interface ConversationResponse {
|
||||
id: string;
|
||||
mode: 'voice';
|
||||
title: string;
|
||||
title?: string;
|
||||
status: string;
|
||||
access_epoch?: number;
|
||||
created_at?: string;
|
||||
}
|
||||
|
||||
export interface VoiceSessionResponse {
|
||||
@@ -43,10 +59,15 @@ export interface VoiceSessionResponse {
|
||||
poll_url: string;
|
||||
}
|
||||
|
||||
/** V02: status + safe diagnostics for a reserved/connected session. */
|
||||
export interface VoiceSessionPollResponse extends VoiceSessionStatus {
|
||||
recent_tool_results?: unknown[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Thin client for the endpoints the live voice call needs (A03, F01, C01, V01, V04).
|
||||
* Uses HttpClient so the app's existing interceptors (401 → login redirect, etc.) still apply.
|
||||
* Auth is the HttpOnly `rag_session` cookie; state-changing calls also need `X-CSRF-Token`.
|
||||
* Thin client for the endpoints the live voice call needs (A03, F01, C01, V01, V02, V03, V04).
|
||||
* Auth is the HttpOnly `rag_session` cookie (same-origin proxy); state-changing calls also need
|
||||
* `X-CSRF-Token`. C01/V01 are idempotent through their JSON `client_request_id`, never headers.
|
||||
*/
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class VoiceApiService {
|
||||
@@ -55,50 +76,78 @@ export class VoiceApiService {
|
||||
|
||||
/** A03: identity + a fresh CSRF token. 401 AUTH_REQUIRED when not logged in. */
|
||||
me(): Promise<MeResponse> {
|
||||
return this.send(this.http.get<MeResponse>(this.url('/me'), { withCredentials: true }));
|
||||
return this.send(this.http.get<MeResponse>(this.url('/me'), this.readOptions()));
|
||||
}
|
||||
|
||||
/** F01: capabilities (the UI must check `voice` before offering a call). */
|
||||
configuration(): Promise<ConfigurationResponse> {
|
||||
return this.send(
|
||||
this.http.get<ConfigurationResponse>(this.url('/configuration'), { withCredentials: true }),
|
||||
);
|
||||
return this.send(this.http.get<ConfigurationResponse>(this.url('/configuration'), this.readOptions()));
|
||||
}
|
||||
|
||||
/** C01: only `mode: "voice"` exists in the MVP. */
|
||||
createConversation(csrf: string, title: string): Promise<ConversationResponse> {
|
||||
/** C01: only `mode: "voice"` exists in the MVP. `clientRequestId` makes replays return the same conversation. */
|
||||
createConversation(csrf: string, title: string, clientRequestId: string): Promise<ConversationResponse> {
|
||||
return this.send(
|
||||
this.http.post<ConversationResponse>(
|
||||
this.url('/conversations'),
|
||||
{ client_request_id: crypto.randomUUID(), mode: 'voice', title },
|
||||
this.options(csrf),
|
||||
{ client_request_id: clientRequestId, mode: 'voice', title },
|
||||
this.writeOptions(csrf),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/** V01: reserves a live session; connect the WebSocket to the returned `stream_path`. */
|
||||
createVoiceSession(csrf: string, conversationId: string): Promise<VoiceSessionResponse> {
|
||||
createVoiceSession(
|
||||
csrf: string,
|
||||
conversationId: string,
|
||||
clientRequestId: string,
|
||||
): Promise<VoiceSessionResponse> {
|
||||
return this.send(
|
||||
this.http.post<VoiceSessionResponse>(
|
||||
this.url('/voice/sessions'),
|
||||
{ conversation_id: conversationId, client_request_id: crypto.randomUUID() },
|
||||
this.options(csrf),
|
||||
{ conversation_id: conversationId, client_request_id: clientRequestId },
|
||||
this.writeOptions(csrf),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/** V04: closes the session (idempotent from the UI's point of view). */
|
||||
/** V02: status + safe diagnostics (no secrets). */
|
||||
pollVoiceSession(csrf: string, sessionId: string): Promise<VoiceSessionPollResponse> {
|
||||
return this.send(
|
||||
this.http.get<VoiceSessionPollResponse>(
|
||||
this.url(`/voice/sessions/${encodeURIComponent(sessionId)}`),
|
||||
this.readOptions(),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* V03: reconcile a reservation by its C01/V01 `client_request_id` — used after an
|
||||
* ambiguous (timeout / network) reserve, or after a reload. Never opens a new provider
|
||||
* connection: `null` means the attempt was never reserved.
|
||||
*/
|
||||
getVoiceSessionByRequest(csrf: string, clientRequestId: string): Promise<VoiceSessionResponse | null> {
|
||||
return this.send(
|
||||
this.http
|
||||
.get<VoiceSessionResponse>(
|
||||
this.url(`/voice/sessions/by-request/${encodeURIComponent(clientRequestId)}`),
|
||||
this.readOptions(),
|
||||
)
|
||||
.pipe(this.mapNotFoundToNull()),
|
||||
);
|
||||
}
|
||||
|
||||
/** V04: closes the session explicitly (no body). */
|
||||
async closeVoiceSession(csrf: string, sessionId: string): Promise<void> {
|
||||
await this.send(
|
||||
this.http.post<unknown>(
|
||||
this.url(`/voice/sessions/${encodeURIComponent(sessionId)}/close`),
|
||||
{},
|
||||
this.options(csrf),
|
||||
this.writeOptions(csrf),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/** `wss://…` URL for a V01 `stream_path`. */
|
||||
/** `wss://…` URL for a V01 `stream_path` (same origin as the UI). */
|
||||
streamUrl(streamPath: string): string {
|
||||
const base = this.config.apiOrigin || window.location.origin;
|
||||
const url = new URL(streamPath, base);
|
||||
@@ -112,22 +161,56 @@ export class VoiceApiService {
|
||||
return `${this.config.apiOrigin}${this.config.apiBase}${path}`;
|
||||
}
|
||||
|
||||
private options(csrf: string) {
|
||||
private readOptions() {
|
||||
return { withCredentials: true, headers: new HttpHeaders({ 'X-Request-ID': crypto.randomUUID() }) };
|
||||
}
|
||||
|
||||
private writeOptions(csrf: string) {
|
||||
return {
|
||||
withCredentials: true,
|
||||
headers: new HttpHeaders({ 'X-CSRF-Token': csrf, 'X-Request-ID': crypto.randomUUID() }),
|
||||
headers: new HttpHeaders({
|
||||
'X-CSRF-Token': csrf,
|
||||
'X-Request-ID': crypto.randomUUID(),
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
private mapNotFoundToNull<T>() {
|
||||
return (source: Observable<T>): Observable<T | null> =>
|
||||
new Observable<T | null>((observer) => {
|
||||
const sub = source.subscribe({
|
||||
next: (value) => observer.next(value),
|
||||
error: (err: unknown) => {
|
||||
if (err instanceof HttpErrorResponse && err.status === 404) observer.next(null);
|
||||
else observer.error(err);
|
||||
observer.complete();
|
||||
},
|
||||
complete: () => observer.complete(),
|
||||
});
|
||||
return () => sub.unsubscribe();
|
||||
});
|
||||
}
|
||||
|
||||
private async send<T>(request: Observable<T>): Promise<T> {
|
||||
try {
|
||||
return await firstValueFrom(request);
|
||||
return await firstValueFrom(this.withDeadline(request));
|
||||
} catch (err) {
|
||||
throw this.toApiError(err);
|
||||
}
|
||||
}
|
||||
|
||||
/** A short deadline keeps the UI responsive; the caller reconciles the uncertain outcome. */
|
||||
private withDeadline<T>(request: Observable<T>): Observable<T> {
|
||||
return race(
|
||||
request,
|
||||
throwError(() => new VoiceApiError(0, 'TIMEOUT', 'request-deadline')).pipe(
|
||||
delay(REQUEST_DEADLINE_MS),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
private toApiError(err: unknown): VoiceApiError {
|
||||
if (err instanceof VoiceApiError) return err; // deadline / already-normalized error
|
||||
if (err instanceof HttpErrorResponse) {
|
||||
const envelope = (err.error as { error?: Record<string, unknown> } | null)?.error;
|
||||
return new VoiceApiError(
|
||||
@@ -140,4 +223,4 @@ export class VoiceApiService {
|
||||
}
|
||||
return new VoiceApiError(0, 'UNKNOWN', err instanceof Error ? err.message : 'unknown error');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,6 +9,13 @@ export interface VoiceEngineHandlers {
|
||||
onPlaybackIdle(): void;
|
||||
/** The microphone track ended unexpectedly. */
|
||||
onMicEnded(): void;
|
||||
/**
|
||||
* Real playback progress for one server `audio_ref`: cumulative milliseconds computed
|
||||
* from consumed samples (never a timer), reported ~4×/s and finally on interruption/stop.
|
||||
*/
|
||||
onPlaybackProgress(audioRef: string, playedMs: number): void;
|
||||
/** The bounded playback queue filled: the session must fail safely (no silent PCM drop). */
|
||||
onPlaybackOverflow(): void;
|
||||
}
|
||||
|
||||
export class VoiceEngineError extends Error {
|
||||
@@ -20,8 +27,8 @@ export class VoiceEngineError extends Error {
|
||||
|
||||
/**
|
||||
* Low-level audio for the call:
|
||||
* mic → [pcm-capture worklet] → PCM16 frames → (service → transport)
|
||||
* (transport → service) → PCM16 chunks → [pcm-playback worklet] → speakers
|
||||
* mic → [pcm-capture worklet] → PCM16 24 kHz frames → (service → transport)
|
||||
* (transport → service) → PCM16 24 kHz chunks → [pcm-playback worklet] → speakers
|
||||
* Everything here runs outside Angular's zone; frames arrive ~50×/s and must not trigger change detection.
|
||||
*/
|
||||
@Injectable({ providedIn: 'root' })
|
||||
@@ -106,8 +113,22 @@ export class VoiceAudioEngine {
|
||||
numberOfOutputs: 1,
|
||||
outputChannelCount: [1],
|
||||
});
|
||||
this.playback.port.onmessage = (event: MessageEvent<{ type: string }>) => {
|
||||
if (event.data?.type === 'idle') handlers.onPlaybackIdle();
|
||||
this.playback.port.onmessage = (
|
||||
event: MessageEvent<{ type: string; audioRef?: string; playedMs?: number }>,
|
||||
) => {
|
||||
switch (event.data?.type) {
|
||||
case 'idle':
|
||||
handlers.onPlaybackIdle();
|
||||
break;
|
||||
case 'progress':
|
||||
if (event.data.audioRef) {
|
||||
handlers.onPlaybackProgress(event.data.audioRef, event.data.playedMs ?? 0);
|
||||
}
|
||||
break;
|
||||
case 'overflow':
|
||||
handlers.onPlaybackOverflow();
|
||||
break;
|
||||
}
|
||||
};
|
||||
this.analyser = ctx.createAnalyser();
|
||||
this.analyser.fftSize = 1024;
|
||||
@@ -119,17 +140,17 @@ export class VoiceAudioEngine {
|
||||
|
||||
// ---- playback --------------------------------------------------------------
|
||||
|
||||
/** Queues a PCM16 mono chunk at config.outputSampleRate. Ownership of the buffer moves to the worklet. */
|
||||
enqueuePlayback(chunk: ArrayBuffer): void {
|
||||
/** Queues a PCM16 mono chunk at config.outputSampleRate under its server `audio_ref`. */
|
||||
enqueuePlayback(chunk: ArrayBuffer, audioRef: string | null): void {
|
||||
if (!this.playback) return;
|
||||
const buffer = chunk.byteLength % 2 === 0 ? chunk : chunk.slice(0, chunk.byteLength - 1);
|
||||
this.playback.port.postMessage(
|
||||
{ type: 'push', pcm: buffer, sampleRate: this.config.outputSampleRate },
|
||||
{ type: 'push', pcm: buffer, sampleRate: this.config.outputSampleRate, audioRef },
|
||||
[buffer],
|
||||
);
|
||||
}
|
||||
|
||||
/** Barge-in: drop all queued audio immediately. */
|
||||
/** Barge-in: drop all queued audio immediately (final progress is reported by the worklet). */
|
||||
clearPlayback(): void {
|
||||
this.playback?.port.postMessage({ type: 'clear' });
|
||||
}
|
||||
@@ -189,4 +210,4 @@ export class VoiceAudioEngine {
|
||||
this.stream = null;
|
||||
this.inputRms = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,304 @@
|
||||
import { provideZonelessChangeDetection } from '@angular/core';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { provideRouter } from '@angular/router';
|
||||
import { first } from 'rxjs';
|
||||
import { vi } from 'vitest';
|
||||
import { VoiceApiError, VoiceApiService } from './voice-api.service';
|
||||
import { VoiceAudioEngine, VoiceEngineHandlers } from './voice-audio-engine.service';
|
||||
import { VoiceStreamService } from './voice-stream.service';
|
||||
import { VOICE_TRANSPORT_FACTORY, VoiceTransport, VoiceTransportHandlers } from './voice-transport';
|
||||
import { PlaybackProgressMessage, VoiceServerEvent } from './voice-stream.types';
|
||||
|
||||
const ME = { user: { id: 'u1', username: 'admin', role: 'admin', organization_id: 'o1' }, csrf_token: 'csrf-1', expires_at: 'later' };
|
||||
const CONFIG = {
|
||||
revision: 1,
|
||||
assistant_name: 'دستیار',
|
||||
instruction: '',
|
||||
capabilities: { text: true, voice: true, captions: true },
|
||||
};
|
||||
const CONVERSATION = { id: 'conv-1', mode: 'voice' as const, status: 'active' };
|
||||
const SESSION = {
|
||||
session_id: 'ses-1',
|
||||
conversation_id: 'conv-1',
|
||||
status: 'reserved',
|
||||
stream_path: '/api/v1/voice/sessions/ses-1/stream',
|
||||
expires_at: 'later',
|
||||
poll_url: '/api/v1/voice/sessions/ses-1',
|
||||
};
|
||||
const READY_EVENT: 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 },
|
||||
};
|
||||
|
||||
/** Flush pending microtasks/timers so the service reaches a stable await point. */
|
||||
const flush = (): Promise<void> => new Promise((resolve) => setTimeout(resolve, 5));
|
||||
|
||||
describe('VoiceStreamService (backend handoff contract)', () => {
|
||||
let service: VoiceStreamService;
|
||||
let api: {
|
||||
me: ReturnType<typeof vi.fn>;
|
||||
configuration: ReturnType<typeof vi.fn>;
|
||||
createConversation: ReturnType<typeof vi.fn>;
|
||||
createVoiceSession: ReturnType<typeof vi.fn>;
|
||||
getVoiceSessionByRequest: ReturnType<typeof vi.fn>;
|
||||
pollVoiceSession: ReturnType<typeof vi.fn>;
|
||||
closeVoiceSession: ReturnType<typeof vi.fn>;
|
||||
streamUrl: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let engineHandlers: VoiceEngineHandlers | null;
|
||||
let transportHandlers: VoiceTransportHandlers | null;
|
||||
let controls: PlaybackProgressMessage[];
|
||||
|
||||
beforeEach(() => {
|
||||
sessionStorage.clear();
|
||||
engineHandlers = null;
|
||||
transportHandlers = null;
|
||||
controls = [];
|
||||
|
||||
api = {
|
||||
me: vi.fn().mockResolvedValue(ME),
|
||||
configuration: vi.fn().mockResolvedValue(CONFIG),
|
||||
createConversation: vi.fn().mockResolvedValue(CONVERSATION),
|
||||
createVoiceSession: vi.fn().mockResolvedValue(SESSION),
|
||||
getVoiceSessionByRequest: vi.fn().mockResolvedValue(null),
|
||||
pollVoiceSession: vi.fn().mockResolvedValue({ session_id: 'ses-1', status: 'connected' }),
|
||||
closeVoiceSession: vi.fn().mockResolvedValue(undefined),
|
||||
streamUrl: vi.fn().mockReturnValue('wss://ui.local/api/v1/voice/sessions/ses-1/stream'),
|
||||
};
|
||||
|
||||
const transportMock: VoiceTransport & { handlers: VoiceTransportHandlers | null } = {
|
||||
handlers: null,
|
||||
connect: vi.fn().mockImplementation((handlers: VoiceTransportHandlers) => {
|
||||
transportHandlers = handlers;
|
||||
transportMock.handlers = handlers;
|
||||
return Promise.resolve();
|
||||
}),
|
||||
sendAudio: vi.fn(),
|
||||
sendControl: vi.fn().mockImplementation((message: PlaybackProgressMessage) => controls.push(message)),
|
||||
close: vi.fn(),
|
||||
};
|
||||
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
provideZonelessChangeDetection(),
|
||||
provideHttpClient(),
|
||||
provideRouter([]),
|
||||
{ provide: VoiceApiService, useValue: api },
|
||||
{
|
||||
provide: VoiceAudioEngine,
|
||||
useValue: {
|
||||
isSupported: true,
|
||||
start: vi.fn().mockImplementation((handlers: VoiceEngineHandlers) => {
|
||||
engineHandlers = handlers;
|
||||
return Promise.resolve();
|
||||
}),
|
||||
stop: vi.fn(),
|
||||
setMuted: vi.fn(),
|
||||
enqueuePlayback: vi.fn(),
|
||||
clearPlayback: vi.fn(),
|
||||
flushPlayback: vi.fn(),
|
||||
inputLevel: () => 0,
|
||||
outputLevel: () => 0,
|
||||
},
|
||||
},
|
||||
{ provide: VOICE_TRANSPORT_FACTORY, useFactory: () => () => transportMock },
|
||||
],
|
||||
});
|
||||
service = TestBed.inject(VoiceStreamService);
|
||||
});
|
||||
|
||||
/** Drives a full start() up to `connected`, emitting the server `session_ready`. */
|
||||
async function startConnected(): Promise<void> {
|
||||
const started = service.start();
|
||||
await flush();
|
||||
transportHandlers?.onEvent(READY_EVENT);
|
||||
await started;
|
||||
}
|
||||
|
||||
function firstEndedError(): Promise<string | undefined> {
|
||||
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 () => {
|
||||
await startConnected();
|
||||
|
||||
expect(api.createConversation).toHaveBeenCalledTimes(1);
|
||||
const [, , conversationRequestId] = api.createConversation.mock.calls[0];
|
||||
expect(conversationRequestId).toMatch(/^[0-9a-f-]{36}$/);
|
||||
|
||||
expect(api.createVoiceSession).toHaveBeenCalledTimes(1);
|
||||
const [, conversationId, sessionRequestId] = api.createVoiceSession.mock.calls[0];
|
||||
expect(conversationId).toBe('conv-1');
|
||||
expect(sessionRequestId).not.toBe(conversationRequestId); // the two ids are independent
|
||||
expect(service.connection()).toBe('connected');
|
||||
expect(service.state()).toBe('LISTENING');
|
||||
});
|
||||
|
||||
it('rejects a session_ready whose audio format breaks the 24 kHz mono PCM16LE contract', async () => {
|
||||
const started = service.start();
|
||||
await flush();
|
||||
transportHandlers?.onEvent({
|
||||
type: 'session_ready',
|
||||
session_id: 'ses-1',
|
||||
input_audio: { encoding: 'pcm_s16le', sample_rate: 16000, channels: 1 },
|
||||
output_audio: { encoding: 'pcm_s16le', sample_rate: 24000, channels: 1 },
|
||||
});
|
||||
const result = await started;
|
||||
expect(result).toEqual({ ok: false, reason: 'connect', message: 'فرمت صدای سرور با برنامه سازگار نیست.' });
|
||||
});
|
||||
|
||||
it('reconciles an ambiguous V01 through V03 instead of creating a second session', async () => {
|
||||
api.createVoiceSession
|
||||
.mockRejectedValueOnce(new VoiceApiError(0, 'TIMEOUT', 'timeout'))
|
||||
.mockResolvedValue(SESSION);
|
||||
api.getVoiceSessionByRequest.mockResolvedValue(SESSION);
|
||||
|
||||
await startConnected();
|
||||
|
||||
expect(api.getVoiceSessionByRequest).toHaveBeenCalledTimes(1);
|
||||
const requestedId = api.getVoiceSessionByRequest.mock.calls[0][1];
|
||||
expect(typeof requestedId).toBe('string');
|
||||
expect(api.createVoiceSession).toHaveBeenCalledTimes(1); // no blind duplicate create
|
||||
expect(service.connection()).toBe('connected');
|
||||
});
|
||||
|
||||
it('replays V01 with the same client_request_id when reconciliation finds nothing', async () => {
|
||||
api.createVoiceSession
|
||||
.mockRejectedValueOnce(new VoiceApiError(0, 'TIMEOUT', 'timeout'))
|
||||
.mockResolvedValue(SESSION);
|
||||
api.getVoiceSessionByRequest.mockResolvedValue(null);
|
||||
|
||||
await startConnected();
|
||||
|
||||
expect(api.createVoiceSession).toHaveBeenCalledTimes(2);
|
||||
const firstId = api.createVoiceSession.mock.calls[0][2];
|
||||
const secondId = api.createVoiceSession.mock.calls[1][2];
|
||||
expect(secondId).toBe(firstId); // same attempt, same payload
|
||||
});
|
||||
|
||||
it('keeps the creation attempt after an ambiguous reserve so the next start() reconciles', async () => {
|
||||
api.createConversation.mockRejectedValue(new VoiceApiError(0, 'TIMEOUT', 'timeout'));
|
||||
|
||||
const first = await service.start();
|
||||
expect(first.ok).toBe(false);
|
||||
expect(sessionStorage.getItem('voice_creation_attempt')).toBeTruthy();
|
||||
// The replay used the same ids, never a fresh uuid.
|
||||
const firstId = api.createConversation.mock.calls[0][2];
|
||||
const secondId = api.createConversation.mock.calls[1][2];
|
||||
expect(secondId).toBe(firstId);
|
||||
});
|
||||
|
||||
it('sends playback_progress with the cumulative played_ms reported by the worklet', async () => {
|
||||
await startConnected();
|
||||
|
||||
transportHandlers?.onEvent({ type: 'audio_started', audio_ref: 'aud-1' });
|
||||
engineHandlers?.onPlaybackProgress('aud-1', 120);
|
||||
engineHandlers?.onPlaybackProgress('aud-1', 900);
|
||||
|
||||
expect(controls).toEqual([
|
||||
{ type: 'playback_progress', audio_ref: 'aud-1', played_ms: 120 },
|
||||
{ type: 'playback_progress', audio_ref: 'aud-1', played_ms: 900 },
|
||||
]);
|
||||
});
|
||||
|
||||
it('reports the final real played progress when the turn is interrupted', async () => {
|
||||
await startConnected();
|
||||
|
||||
transportHandlers?.onEvent({ type: 'transcript', turn_ref: 'turn-1', role: 'assistant', text: 'پاسخ', status: 'partial' });
|
||||
transportHandlers?.onEvent({ type: '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 },
|
||||
]);
|
||||
expect(service.messages().find((m) => m.id === 'turn-1:assistant')?.interrupted).toBe(true);
|
||||
});
|
||||
|
||||
it('ends safely with a failure when the bounded playback queue overflows', async () => {
|
||||
await startConnected();
|
||||
const ended = firstEndedError();
|
||||
|
||||
engineHandlers?.onPlaybackOverflow();
|
||||
|
||||
expect(await ended).toBe('حجم صدای در حال پخش از محدودهٔ مجاز گذشت و گفتگو بهطور ایمن پایان یافت.');
|
||||
expect(service.connection()).toBe('disconnected');
|
||||
});
|
||||
|
||||
it('requires a fresh conversation after CONTEXT_REVOKED and drops the old attempt', async () => {
|
||||
await startConnected();
|
||||
const ended = firstEndedError();
|
||||
|
||||
transportHandlers?.onEvent({
|
||||
type: 'error',
|
||||
error: { code: 'CONTEXT_REVOKED', message: 'context revoked', retryable: false },
|
||||
});
|
||||
|
||||
expect(await ended).toBe('محتوای دانش تغییر کرده و مکالمهٔ قبلی دیگر معتبر نیست. گفتگوی جدیدی شروع کنید.');
|
||||
expect(sessionStorage.getItem('voice_creation_attempt')).toBeNull();
|
||||
expect(service.connection()).toBe('disconnected');
|
||||
});
|
||||
|
||||
it('keeps a retryable server error non-fatal (the session stays usable)', async () => {
|
||||
await startConnected();
|
||||
|
||||
transportHandlers?.onEvent({
|
||||
type: 'error',
|
||||
error: { code: 'SEARCH_TIMEOUT', message: 'جستوجو دیر شد', retryable: true },
|
||||
});
|
||||
|
||||
expect(service.streamError()).toBe('جستوجو دیر شد');
|
||||
expect(service.connection()).toBe('connected');
|
||||
});
|
||||
|
||||
it('hides excerpts of sources the server marks unavailable', async () => {
|
||||
await startConnected();
|
||||
|
||||
transportHandlers?.onEvent({
|
||||
type: 'sources',
|
||||
turn_ref: 'turn-9',
|
||||
sources: [
|
||||
{
|
||||
source_ref: 'src-1',
|
||||
document_id: 'doc-1',
|
||||
chunk_id: 'chunk-1',
|
||||
title: 'سند آزمون',
|
||||
excerpt: 'متن منقضیشده',
|
||||
available: false,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const assistant = service.messages().find((m) => m.id === 'turn-9:assistant');
|
||||
expect(assistant?.sources?.[0].available).toBe(false);
|
||||
expect(assistant?.sources?.[0].excerpt).toBeUndefined();
|
||||
});
|
||||
|
||||
it('marks partial then completed transcripts final', async () => {
|
||||
await startConnected();
|
||||
|
||||
transportHandlers?.onEvent({ type: 'transcript', turn_ref: 't1', role: 'assistant', text: 'سلام', status: 'partial' });
|
||||
transportHandlers?.onEvent({ type: 'transcript', turn_ref: 't1', role: 'assistant', text: 'سلام و خوب', status: 'partial' });
|
||||
transportHandlers?.onEvent({ type: 'transcript', turn_ref: 't1', role: 'assistant', text: 'سلام و خوب', status: 'completed' });
|
||||
|
||||
const assistant = service.messages().find((m) => m.id === 't1:assistant');
|
||||
expect(assistant?.text).toBe('سلام و خوب');
|
||||
expect(assistant?.final).toBe(true);
|
||||
});
|
||||
|
||||
it('closes the reservation (V04) when the call ends on user request', async () => {
|
||||
await startConnected();
|
||||
await service.close();
|
||||
|
||||
expect(api.closeVoiceSession).toHaveBeenCalledWith('csrf-1', 'ses-1');
|
||||
expect(sessionStorage.getItem('voice_creation_attempt')).toBeNull();
|
||||
expect(service.connection()).toBe('disconnected');
|
||||
});
|
||||
});
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Injectable, NgZone, computed, inject, signal } from '@angular/core';
|
||||
import { Subject } from 'rxjs';
|
||||
import { MicrophoneError } from '../microphone/microphone.service';
|
||||
import { VoiceApiError, VoiceApiService } from './voice-api.service';
|
||||
import { VoiceApiError, VoiceApiService, VoiceSessionResponse } from './voice-api.service';
|
||||
import { VoiceAudioEngine, VoiceEngineError } from './voice-audio-engine.service';
|
||||
import { VOICE_TRANSPORT_FACTORY, VoiceTransport } from './voice-transport';
|
||||
import {
|
||||
@@ -21,7 +21,8 @@ export type VoiceStartFailure =
|
||||
| 'auth'
|
||||
| 'unavailable'
|
||||
| 'api'
|
||||
| 'connect';
|
||||
| 'connect'
|
||||
| 'overflow';
|
||||
|
||||
export type VoiceStartResult =
|
||||
| { ok: true }
|
||||
@@ -45,8 +46,11 @@ const MESSAGES = {
|
||||
api: 'شروع گفتگوی صوتی ناموفق بود. دوباره تلاش کنید.',
|
||||
connect: 'اتصال به سرور صوتی برقرار نشد. دوباره تلاش کنید.',
|
||||
badFormat: 'فرمت صدای سرور با برنامه سازگار نیست.',
|
||||
overflow: 'حجم صدای در حال پخش از محدودهٔ مجاز گذشت و گفتگو بهطور ایمن پایان یافت.',
|
||||
disconnected: 'ارتباط با سرور قطع شد و گفتگو پایان یافت.',
|
||||
server: 'سرور گفتگوی صوتی با خطا مواجه شد.',
|
||||
contextRevoked: 'محتوای دانش تغییر کرده و مکالمهٔ قبلی دیگر معتبر نیست. گفتگوی جدیدی شروع کنید.',
|
||||
stale: 'مکالمهٔ قبلی منقضی شده است. گفتگوی جدیدی شروع کنید.',
|
||||
conversationTitle: 'گفتگوی صوتی',
|
||||
} as const;
|
||||
|
||||
@@ -54,20 +58,29 @@ const MESSAGES = {
|
||||
const INTERRUPTED_FLASH_MS = 150;
|
||||
/** How long a retryable server error stays on screen. */
|
||||
const ERROR_BANNER_MS = 6000;
|
||||
/** Longest wait for the worklet's final playback report when closing a call. */
|
||||
const FINAL_PROGRESS_WAIT_MS = 300;
|
||||
|
||||
/**
|
||||
* One live voice call against the MVP API (mvp_ui_api_catalog.md §6):
|
||||
* One live voice call against the backend handoff contract (§7–§9):
|
||||
*
|
||||
* mic ─▶ engine ─▶ PCM16 16 kHz frames ─▶ WSS ─▶ server
|
||||
* server ─▶ session_ready / transcript / sources / turn_interrupted / error (JSON)
|
||||
* mic ─▶ engine ─▶ PCM16 24 kHz frames ─▶ WSS ─▶ server
|
||||
* server ─▶ session_ready / user_speech_started / transcript / sources /
|
||||
* audio_started / audio_ended / turn_interrupted / error (JSON)
|
||||
* ─▶ PCM16 24 kHz audio (binary) ─▶ engine playback
|
||||
* client ─▶ playback_progress (the only JSON control message, cumulative played_ms)
|
||||
*
|
||||
* Start: mic permission → GET /me (CSRF) → GET /configuration (voice enabled?)
|
||||
* → POST /conversations → POST /voice/sessions → WSS stream_path → `session_ready`.
|
||||
* End: close the socket, stop audio, POST /voice/sessions/{id}/close.
|
||||
* Start: mic permission → GET /me (CSRF) → POST /conversations → POST /voice/sessions
|
||||
* → WSS stream_path → `session_ready`.
|
||||
* End: final playback progress → V04 close → close the socket, stop the audio.
|
||||
*
|
||||
* Barge-in is decided by the server: it sends `turn_interrupted` and the client flushes playback.
|
||||
* (The contract has no client→server interrupt message.)
|
||||
* Barge-in is decided by the server: it sends `turn_interrupted` and the client flushes
|
||||
* playback. The contract has no other client→server JSON message.
|
||||
*
|
||||
* Ambiguous C01/V01 outcomes (timeout / network) are reconciled with the SAME
|
||||
* `client_request_id` pair — replayed via V03 or the identical request — never with new
|
||||
* ids, so a second conversation/session is never created. The attempt is kept in
|
||||
* sessionStorage (ids and paths only, no secrets) so a reload can reconcile first.
|
||||
*/
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class VoiceStreamService {
|
||||
@@ -106,6 +119,24 @@ export class VoiceStreamService {
|
||||
} | null = null;
|
||||
private lastConversationId: string | null = null;
|
||||
|
||||
/** Creation attempt: stable client request ids + the ids/paths the server returned. */
|
||||
private attempt: VoiceCreationAttempt | null = null;
|
||||
/** Latest cumulative played_ms actually consumed by the worklet, per server audio_ref. */
|
||||
private readonly playedMsByRef = new Map<string, number>();
|
||||
private currentAudioRef: string | null = null;
|
||||
private progressWaiters: Array<() => void> = [];
|
||||
|
||||
constructor() {
|
||||
this.attempt = loadPersistedAttempt();
|
||||
// A reload during a call leaves an un-reconciled reservation: reconcile with the
|
||||
// server first (V02/V03), close what is still open, and drop the attempt. Media is
|
||||
// never auto-resumed — the user starts a fresh conversation explicitly.
|
||||
if (this.attempt) void this.recover();
|
||||
|
||||
// Leaving the page releases mic/worklet/AudioContext/WebSocket immediately.
|
||||
window.addEventListener('pagehide', this.onPageLeave);
|
||||
}
|
||||
|
||||
// ---- public API -----------------------------------------------------------
|
||||
|
||||
async start(options: { title?: string } = {}): Promise<VoiceStartResult> {
|
||||
@@ -120,27 +151,35 @@ export class VoiceStreamService {
|
||||
this.clearError();
|
||||
this.resetTurnFlags();
|
||||
this.lastConversationId = null;
|
||||
this.currentAudioRef = null;
|
||||
this.playedMsByRef.clear();
|
||||
this.state.set('IDLE');
|
||||
this.connection.set('connecting');
|
||||
|
||||
// Reuse a persisted attempt (ambiguous outcome of a previous try); otherwise create one.
|
||||
if (!this.attempt) this.attempt = newCreationAttempt();
|
||||
persistAttempt(this.attempt);
|
||||
|
||||
// 1) microphone + worklets (needs the user gesture; shows the permission prompt)
|
||||
try {
|
||||
await this.engine.start({
|
||||
onFrame: (pcm) => this.onMicFrame(pcm),
|
||||
onPlaybackIdle: () => this.ngZone.run(() => this.onPlaybackIdle()),
|
||||
onMicEnded: () => this.ngZone.run(() => this.failSession(MESSAGES.micLost, session)),
|
||||
onPlaybackProgress: (audioRef, playedMs) =>
|
||||
this.ngZone.run(() => this.onPlaybackProgress(audioRef, playedMs)),
|
||||
onPlaybackOverflow: () => this.ngZone.run(() => this.failSession(MESSAGES.overflow, session)),
|
||||
});
|
||||
} catch (err) {
|
||||
return this.abortStart(session, this.mapEngineError(err));
|
||||
}
|
||||
if (stale()) {
|
||||
// Cancelled while the permission prompt / worklets were loading: release what was just opened.
|
||||
if (!this.isOpen()) this.engine.stop();
|
||||
return this.failure('cancelled', '');
|
||||
}
|
||||
|
||||
// 2) REST: identity/CSRF → capabilities → conversation → voice session
|
||||
let streamPath: string;
|
||||
let voiceSession: VoiceSessionResponse;
|
||||
try {
|
||||
const me = await this.api.me();
|
||||
if (stale()) return this.failure('cancelled', '');
|
||||
@@ -151,29 +190,31 @@ export class VoiceStreamService {
|
||||
return this.abortStart(session, { reason: 'unavailable', message: MESSAGES.voiceDisabled });
|
||||
}
|
||||
|
||||
const conversation = await this.api.createConversation(me.csrf_token, MESSAGES.conversationTitle);
|
||||
if (stale()) return this.failure('cancelled', '');
|
||||
|
||||
const voiceSession = await this.api.createVoiceSession(me.csrf_token, conversation.id);
|
||||
const remote = {
|
||||
sessionId: voiceSession.session_id,
|
||||
conversationId: conversation.id,
|
||||
csrf: me.csrf_token,
|
||||
};
|
||||
voiceSession = await this.reserve(me.csrf_token, options.title ?? MESSAGES.conversationTitle);
|
||||
if (stale()) {
|
||||
this.closeRemote(remote); // cancelled after the server already reserved the session
|
||||
this.closeRemote({ sessionId: voiceSession.session_id, csrf: me.csrf_token });
|
||||
this.attempt = null;
|
||||
clearPersistedAttempt();
|
||||
return this.failure('cancelled', '');
|
||||
}
|
||||
this.remote = remote;
|
||||
this.lastConversationId = conversation.id;
|
||||
streamPath = voiceSession.stream_path;
|
||||
} catch (err) {
|
||||
if (stale()) return this.failure('cancelled', '');
|
||||
return this.abortStart(session, this.mapApiError(err));
|
||||
// An ambiguous reserve outcome (timeout / network / 5xx) keeps the attempt: the
|
||||
// next start reconciles it with the same client_request_ids instead of creating a
|
||||
// second conversation/session. A definitive failure (4xx) drops it.
|
||||
const keepAttempt = err instanceof VoiceApiError && this.isAmbiguous(err);
|
||||
return this.abortStart(session, this.mapApiError(err), keepAttempt);
|
||||
}
|
||||
|
||||
this.remote = {
|
||||
sessionId: voiceSession.session_id,
|
||||
conversationId: voiceSession.conversation_id,
|
||||
csrf: this.lastCsrf,
|
||||
};
|
||||
this.lastConversationId = voiceSession.conversation_id;
|
||||
|
||||
// 3) WebSocket (created outside the zone so socket events don't trigger change detection)
|
||||
const transport = this.createTransport(this.api.streamUrl(streamPath));
|
||||
const transport = this.createTransport(this.api.streamUrl(voiceSession.stream_path));
|
||||
this.transport = transport;
|
||||
try {
|
||||
await this.ngZone.runOutsideAngular(() =>
|
||||
@@ -181,6 +222,7 @@ export class VoiceStreamService {
|
||||
onEvent: (event) => this.ngZone.run(() => this.onServerEvent(event, session)),
|
||||
onAudio: (chunk) => this.onServerAudio(chunk, session),
|
||||
onClose: () => this.ngZone.run(() => this.failSession(MESSAGES.disconnected, session)),
|
||||
onOverflow: () => this.ngZone.run(() => this.failSession(MESSAGES.overflow, session)),
|
||||
}),
|
||||
);
|
||||
} catch {
|
||||
@@ -216,8 +258,92 @@ export class VoiceStreamService {
|
||||
|
||||
/** User ends the call. Safe to call at any time. */
|
||||
end(): void {
|
||||
if (!this.isOpen()) return;
|
||||
this.finishSession();
|
||||
void this.close();
|
||||
}
|
||||
|
||||
/**
|
||||
* Intentional close: final playback progress for the active audio_ref, then V04, and
|
||||
* only then the socket/audio teardown — the order required by the contract.
|
||||
*/
|
||||
async close(options: { error?: string } = {}): Promise<void> {
|
||||
if (!this.isOpen()) {
|
||||
// Idle: nothing to close. A persisted creation attempt from an ambiguous reserve
|
||||
// outcome is kept so the next start() reconciles it instead of duplicating it.
|
||||
return;
|
||||
}
|
||||
const remote = this.remote;
|
||||
// 1) final, worklet-computed playback progress for the ref that is still playing
|
||||
await this.reportFinalProgress();
|
||||
// 2) V04 before the transport closes
|
||||
if (remote) {
|
||||
try {
|
||||
await this.api.closeVoiceSession(remote.csrf, remote.sessionId);
|
||||
} catch {
|
||||
/* the session may already be closed/expired (e.g. 409 LIVE_SESSION_UNUSABLE) */
|
||||
}
|
||||
}
|
||||
// 3) release mic, worklets, AudioContext and the WebSocket
|
||||
const wasConnected = this.connection() === 'connected';
|
||||
const conversationId = this.remote?.conversationId ?? this.lastConversationId;
|
||||
// Invalidate pending async work BEFORE resolving the session_ready waiter, so a
|
||||
// start() still waiting sees a cancelled session instead of a connect failure.
|
||||
this.session++;
|
||||
this.rejectReady();
|
||||
this.finalizeAll();
|
||||
const messages = this.messages();
|
||||
this.teardown();
|
||||
if (wasConnected) {
|
||||
this.sessionEnded$.next({ conversationId, messages, error: options.error });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* After media/context loss the user starts a brand-new conversation: the old
|
||||
* reservation is closed (V04) and its creation attempt is dropped, so the next
|
||||
* `start()` mints fresh client request ids. An ambiguous attempt that was never
|
||||
* connected is still reconciled with the same ids — never duplicated.
|
||||
*/
|
||||
async freshSession(title?: string): Promise<VoiceStartResult> {
|
||||
await this.close();
|
||||
return this.start({ title });
|
||||
}
|
||||
|
||||
/**
|
||||
* Reconcile a persisted creation attempt with the server (V02/V03) and close whatever
|
||||
* reservation is still open. Media is never resumed automatically: recovery is not a
|
||||
* seamless reconnect. Returns whether an attempt existed.
|
||||
*/
|
||||
async recover(): Promise<boolean> {
|
||||
const attempt = this.attempt;
|
||||
if (!attempt) return false;
|
||||
try {
|
||||
const me = await this.api.me();
|
||||
// A call may have started while the request was in flight: never close its session.
|
||||
if (this.isOpen() || this.attempt !== attempt) return true;
|
||||
let sessionId = attempt.sessionId;
|
||||
if (!sessionId) {
|
||||
const existing = await this.api.getVoiceSessionByRequest(me.csrf_token, attempt.sessionRequestId);
|
||||
sessionId = existing?.session_id ?? null;
|
||||
}
|
||||
if (this.isOpen() || this.attempt !== attempt) return true;
|
||||
if (sessionId) {
|
||||
await this.api.closeVoiceSession(me.csrf_token, sessionId).catch(() => undefined);
|
||||
}
|
||||
} catch {
|
||||
/* the attempt is stale either way: drop it below */
|
||||
}
|
||||
if (!this.isOpen() && this.attempt === attempt) {
|
||||
this.attempt = null;
|
||||
clearPersistedAttempt();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** V02: status + safe diagnostics of the current reservation (for the UI, no secrets). */
|
||||
async poll(): Promise<unknown> {
|
||||
const remote = this.remote;
|
||||
if (!remote) return null;
|
||||
return this.api.pollVoiceSession(remote.csrf, remote.sessionId);
|
||||
}
|
||||
|
||||
toggleMute(): void {
|
||||
@@ -236,9 +362,10 @@ export class VoiceStreamService {
|
||||
this.clearError();
|
||||
}
|
||||
|
||||
/** Component teardown: release everything without emitting events. */
|
||||
/** Component teardown: release a live call without emitting events. */
|
||||
dispose(): void {
|
||||
this.rejectReady();
|
||||
if (!this.isOpen()) return; // keep an ambiguous attempt for reconciliation
|
||||
this.teardown();
|
||||
}
|
||||
|
||||
@@ -248,11 +375,11 @@ export class VoiceStreamService {
|
||||
if (this.streaming) this.transport?.sendAudio(pcm);
|
||||
}
|
||||
|
||||
// ---- audio from the server (outside the zone) ------------------------------
|
||||
// ---- audio from the server (outside the zone) -----------------------------
|
||||
|
||||
private onServerAudio(chunk: ArrayBuffer, session: number): void {
|
||||
if (session !== this.session || !this.streaming) return;
|
||||
this.engine.enqueuePlayback(chunk);
|
||||
this.engine.enqueuePlayback(chunk, this.currentAudioRef);
|
||||
this.clearSettleTimer();
|
||||
|
||||
if (this.state() !== 'SPEAKING') {
|
||||
@@ -266,6 +393,52 @@ export class VoiceStreamService {
|
||||
}
|
||||
}
|
||||
|
||||
// ---- playback progress ------------------------------------------------------
|
||||
|
||||
private onPlaybackProgress(audioRef: string, playedMs: number): void {
|
||||
if (playedMs <= 0) return;
|
||||
// Keep the latest cumulative value per ref; the final report is sent from here too.
|
||||
this.playedMsByRef.set(audioRef, playedMs);
|
||||
this.sendPlaybackProgress(audioRef, playedMs);
|
||||
this.resolveProgressWaiters();
|
||||
}
|
||||
|
||||
/**
|
||||
* The only client→server JSON control message: cumulative REAL played milliseconds
|
||||
* for a server audio_ref, computed by the worklet from consumed samples.
|
||||
*/
|
||||
private sendPlaybackProgress(audioRef: string, playedMs: number): void {
|
||||
const transport = this.transport;
|
||||
if (!transport || playedMs <= 0) return;
|
||||
transport.sendControl({ type: 'playback_progress', audio_ref: audioRef, played_ms: playedMs });
|
||||
}
|
||||
|
||||
/**
|
||||
* Before closing a call, ask the worklet for the final played report of the active ref
|
||||
* (barge-in drops the queue, so the last 250 ms cadence may be stale).
|
||||
*/
|
||||
private reportFinalProgress(): Promise<void> {
|
||||
const ref = this.currentAudioRef;
|
||||
const transport = this.transport;
|
||||
if (!ref || !transport || this.connection() !== 'connected') return Promise.resolve();
|
||||
|
||||
this.engine.clearPlayback(); // worklet answers with its final cumulative report
|
||||
return new Promise<void>((resolve) => {
|
||||
const done = (): void => {
|
||||
clearTimeout(timer);
|
||||
resolve();
|
||||
};
|
||||
const timer = setTimeout(done, FINAL_PROGRESS_WAIT_MS);
|
||||
this.progressWaiters.push(done);
|
||||
});
|
||||
}
|
||||
|
||||
private resolveProgressWaiters(): void {
|
||||
const waiters = this.progressWaiters;
|
||||
this.progressWaiters = [];
|
||||
waiters.forEach((waiter) => waiter());
|
||||
}
|
||||
|
||||
// ---- JSON events from the server -------------------------------------------
|
||||
|
||||
private onServerEvent(event: VoiceServerEvent, session: number): void {
|
||||
@@ -286,6 +459,10 @@ export class VoiceStreamService {
|
||||
break;
|
||||
}
|
||||
|
||||
case 'user_speech_started':
|
||||
// A new server turn started; the transcript/sources of older turns stay untouched.
|
||||
break;
|
||||
|
||||
case 'transcript':
|
||||
this.onTranscript(event);
|
||||
break;
|
||||
@@ -294,6 +471,15 @@ export class VoiceStreamService {
|
||||
this.upsertSources(event);
|
||||
break;
|
||||
|
||||
case 'audio_started':
|
||||
this.currentAudioRef = event.audio_ref;
|
||||
break;
|
||||
|
||||
case 'audio_ended':
|
||||
// Generation ended; the ref's audio may still be playing — its final progress is
|
||||
// reported when the queue drains or the turn is interrupted.
|
||||
break;
|
||||
|
||||
case 'turn_interrupted':
|
||||
this.onTurnInterrupted(event.turn_ref);
|
||||
break;
|
||||
@@ -329,7 +515,7 @@ export class VoiceStreamService {
|
||||
|
||||
/** Server-side barge-in: the user spoke over the assistant. */
|
||||
private onTurnInterrupted(turnRef: string): void {
|
||||
this.engine.clearPlayback(); // empty the playback queue immediately
|
||||
this.engine.clearPlayback(); // the worklet posts the final progress for the active ref
|
||||
this.turnEnded = false;
|
||||
this.clearSettleTimer();
|
||||
this.markInterrupted(turnRef);
|
||||
@@ -349,6 +535,17 @@ export class VoiceStreamService {
|
||||
const { message, retryable, code } = event.error;
|
||||
console.warn('VoiceStreamService: server error', code, event.error.request_id);
|
||||
|
||||
// The old conversation/session is no longer usable: the user must start a fresh one
|
||||
// (Gemini interruption can also require ending the session entirely).
|
||||
if (code === 'CONTEXT_REVOKED' || code === 'CONVERSATION_STALE') {
|
||||
this.failSession(MESSAGES.contextRevoked, session);
|
||||
return;
|
||||
}
|
||||
if (code === 'LIVE_SESSION_UNUSABLE' || code === 'SESSION_CLOSED') {
|
||||
this.failSession(MESSAGES.sessionUnusable, session);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!retryable) {
|
||||
this.failSession(message || MESSAGES.server, session);
|
||||
return;
|
||||
@@ -426,12 +623,11 @@ export class VoiceStreamService {
|
||||
}
|
||||
|
||||
/**
|
||||
* The catalog does not say whether a `partial` carries the full text so far or only the new fragment,
|
||||
* The contract does not say whether a `partial` carries the full text so far or only the new fragment,
|
||||
* so both are handled:
|
||||
* - `completed` with text → the final full text replaces whatever was accumulated
|
||||
* - text that starts with what we already have → cumulative, replace
|
||||
* - anything else → a fragment, append as-is (fragments carry their own spacing)
|
||||
* If the backend turns out to use only one style, this is the single place to simplify.
|
||||
*/
|
||||
private mergeTranscriptText(previous: string, event: TranscriptEvent): string {
|
||||
const next = event.text;
|
||||
@@ -452,9 +648,14 @@ export class VoiceStreamService {
|
||||
|
||||
const sources = [...(current.sources ?? [])];
|
||||
for (const source of event.sources) {
|
||||
if (!sources.some((s) => s.source_ref === source.source_ref && s.chunk_id === source.chunk_id)) {
|
||||
sources.push(source);
|
||||
}
|
||||
// `available: false` means the excerpt is no longer valid: keep the reference for
|
||||
// the turn but hide its excerpt instead of showing revoked text.
|
||||
const normalized = source.available === false ? { ...source, excerpt: undefined } : source;
|
||||
const existing = sources.findIndex(
|
||||
(s) => s.source_ref === normalized.source_ref && s.chunk_id === normalized.chunk_id,
|
||||
);
|
||||
if (existing === -1) sources.push(normalized);
|
||||
else sources[existing] = normalized;
|
||||
}
|
||||
|
||||
const next = { ...current, sources };
|
||||
@@ -494,34 +695,29 @@ export class VoiceStreamService {
|
||||
|
||||
private failSession(message: string, session: number): void {
|
||||
if (session !== this.session || !this.isOpen()) return;
|
||||
this.finishSession(message);
|
||||
}
|
||||
|
||||
private finishSession(error?: string): void {
|
||||
const wasConnected = this.connection() === 'connected';
|
||||
const conversationId = this.remote?.conversationId ?? this.lastConversationId;
|
||||
this.rejectReady();
|
||||
this.finalizeAll();
|
||||
const messages = this.messages();
|
||||
this.teardown();
|
||||
if (wasConnected) this.sessionEnded$.next({ conversationId, messages, error });
|
||||
// `close()` performs the ordered teardown (final progress → V04 → transport) and
|
||||
// emits sessionEnded$ exactly once, carrying the failure message.
|
||||
void this.close({ error: message });
|
||||
}
|
||||
|
||||
private abortStart(
|
||||
session: number,
|
||||
failure: { reason: VoiceStartFailure; message: string },
|
||||
keepAttempt = false,
|
||||
): VoiceStartResult {
|
||||
if (session === this.session) this.teardown();
|
||||
if (session === this.session) this.teardown({ keepAttempt });
|
||||
return this.failure(failure.reason, failure.message);
|
||||
}
|
||||
|
||||
/** Releases every resource; idempotent. Invalidates all pending async work via `session`. */
|
||||
private teardown(): void {
|
||||
private teardown(options: { keepAttempt?: boolean } = {}): void {
|
||||
this.session++;
|
||||
this.streaming = false;
|
||||
this.resetTurnFlags();
|
||||
this.clearSettleTimer();
|
||||
this.clearError();
|
||||
this.resolveProgressWaiters();
|
||||
this.currentAudioRef = null;
|
||||
if (this.interruptTimer) {
|
||||
clearTimeout(this.interruptTimer);
|
||||
this.interruptTimer = null;
|
||||
@@ -532,9 +728,14 @@ export class VoiceStreamService {
|
||||
transport?.close();
|
||||
this.engine.stop();
|
||||
|
||||
// V04: tell the server the session is over (best effort).
|
||||
// The reservation is over: drop the attempt so the next start() mints fresh request ids —
|
||||
// unless an ambiguous reserve failure still needs the same ids replayed/reconciled.
|
||||
const remote = this.remote;
|
||||
this.remote = null;
|
||||
if (!options.keepAttempt) {
|
||||
this.attempt = null;
|
||||
clearPersistedAttempt();
|
||||
}
|
||||
if (remote) this.closeRemote(remote);
|
||||
|
||||
this.connection.set('disconnected');
|
||||
@@ -548,6 +749,23 @@ export class VoiceStreamService {
|
||||
});
|
||||
}
|
||||
|
||||
private onPageLeave = (): void => {
|
||||
if (!this.isOpen()) return;
|
||||
const transport = this.transport;
|
||||
const remote = this.remote;
|
||||
this.session++;
|
||||
this.streaming = false;
|
||||
this.transport = null;
|
||||
transport?.close();
|
||||
this.engine.stop();
|
||||
this.remote = null;
|
||||
if (remote) this.closeRemote(remote);
|
||||
// The attempt id/path stay in sessionStorage on purpose: the next page load reconciles
|
||||
// it with V02/V03 (V04 may not complete while unloading) before anything else.
|
||||
this.connection.set('disconnected');
|
||||
this.state.set('IDLE');
|
||||
};
|
||||
|
||||
private resetTurnFlags(): void {
|
||||
this.turnEnded = false;
|
||||
}
|
||||
@@ -589,6 +807,114 @@ export class VoiceStreamService {
|
||||
waiter.reject(error);
|
||||
}
|
||||
|
||||
// ---- creation attempt / reservation -----------------------------------------
|
||||
|
||||
/** CSRF of the most recent `/me`; refreshed per attempt. */
|
||||
private lastCsrf = '';
|
||||
|
||||
/**
|
||||
* C01 then V01 with the attempt's stable client request ids. Ambiguous outcomes
|
||||
* (timeout / network) are reconciled with the SAME ids: V03 first, then an identical
|
||||
* replay — never new ids, never a blind retry of an unknown state.
|
||||
*/
|
||||
private async reserve(csrf: string, title: string): Promise<VoiceSessionResponse> {
|
||||
const attempt = this.attempt ?? newCreationAttempt();
|
||||
this.attempt = attempt;
|
||||
|
||||
let activeCsrf = csrf;
|
||||
if (!attempt.conversationId) {
|
||||
try {
|
||||
const conversation = await this.api.createConversation(
|
||||
activeCsrf,
|
||||
title,
|
||||
attempt.conversationRequestId,
|
||||
);
|
||||
attempt.conversationId = conversation.id;
|
||||
} catch (err) {
|
||||
const refreshed = await this.refreshAfterCsrfFailure(err);
|
||||
activeCsrf = refreshed ?? activeCsrf;
|
||||
if (!this.isAmbiguous(err) && !refreshed) throw err;
|
||||
// Replay the identical request: C01 is idempotent on client_request_id.
|
||||
const conversation = await this.api.createConversation(
|
||||
activeCsrf,
|
||||
title,
|
||||
attempt.conversationRequestId,
|
||||
);
|
||||
attempt.conversationId = conversation.id;
|
||||
}
|
||||
persistAttempt(attempt);
|
||||
}
|
||||
|
||||
if (!attempt.sessionId || !attempt.streamPath) {
|
||||
let voiceSession: VoiceSessionResponse | null = null;
|
||||
try {
|
||||
voiceSession = await this.api.createVoiceSession(
|
||||
activeCsrf,
|
||||
attempt.conversationId!,
|
||||
attempt.sessionRequestId,
|
||||
);
|
||||
} catch (err) {
|
||||
const refreshed = await this.refreshAfterCsrfFailure(err);
|
||||
activeCsrf = refreshed ?? activeCsrf;
|
||||
if (this.isAmbiguous(err) || refreshed) {
|
||||
// Did the ambiguous V01 create a reservation? Reconcile before replaying.
|
||||
const existing = await this.api
|
||||
.getVoiceSessionByRequest(activeCsrf, attempt.sessionRequestId)
|
||||
.catch(() => null);
|
||||
if (existing?.stream_path) {
|
||||
voiceSession = existing;
|
||||
} else {
|
||||
voiceSession = await this.api.createVoiceSession(
|
||||
activeCsrf,
|
||||
attempt.conversationId!,
|
||||
attempt.sessionRequestId,
|
||||
);
|
||||
}
|
||||
} else if (err instanceof VoiceApiError && err.code === 'LIVE_SESSION_BUSY') {
|
||||
// A session already exists for this request: reconcile instead of a second one.
|
||||
const existing = await this.api
|
||||
.getVoiceSessionByRequest(activeCsrf, attempt.sessionRequestId)
|
||||
.catch(() => null);
|
||||
if (existing?.stream_path) voiceSession = existing;
|
||||
else throw err;
|
||||
} else {
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
attempt.sessionId = voiceSession!.session_id;
|
||||
attempt.streamPath = voiceSession!.stream_path;
|
||||
persistAttempt(attempt);
|
||||
}
|
||||
|
||||
this.lastCsrf = activeCsrf;
|
||||
this.lastConversationId = attempt.conversationId;
|
||||
return {
|
||||
session_id: attempt.sessionId!,
|
||||
conversation_id: attempt.conversationId!,
|
||||
status: 'connecting',
|
||||
stream_path: attempt.streamPath!,
|
||||
expires_at: '',
|
||||
poll_url: '',
|
||||
};
|
||||
}
|
||||
|
||||
/** 403 CSRF_INVALID → read a fresh token from `/me` and allow one identical replay. */
|
||||
private async refreshAfterCsrfFailure(err: unknown): Promise<string | null> {
|
||||
if (!(err instanceof VoiceApiError) || err.code !== 'CSRF_INVALID') return null;
|
||||
try {
|
||||
const me = await this.api.me();
|
||||
return me.csrf_token;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Timeout / network / 5xx: the outcome is unknown, so reconcile instead of assuming. */
|
||||
private isAmbiguous(err: unknown): boolean {
|
||||
if (!(err instanceof VoiceApiError)) return true;
|
||||
return err.status === 0 || err.status === 408 || err.status >= 500;
|
||||
}
|
||||
|
||||
// ---- error mapping ---------------------------------------------------------
|
||||
|
||||
private mapEngineError(err: unknown): { reason: VoiceStartFailure; message: string } {
|
||||
@@ -605,19 +931,24 @@ export class VoiceStreamService {
|
||||
return { reason: 'engine', message: MESSAGES.engine };
|
||||
}
|
||||
|
||||
/** Maps the catalog's error codes (§7) to a user-facing Persian message. */
|
||||
/** Maps the contract's error codes (handoff §10) to a user-facing Persian message. */
|
||||
private mapApiError(err: unknown): { reason: VoiceStartFailure; message: string } {
|
||||
if (!(err instanceof VoiceApiError)) return { reason: 'api', message: MESSAGES.api };
|
||||
|
||||
switch (err.code) {
|
||||
case 'AUTH_REQUIRED':
|
||||
return { reason: 'auth', message: MESSAGES.auth };
|
||||
case 'CSRF_INVALID':
|
||||
return { reason: 'auth', message: MESSAGES.auth };
|
||||
case 'RATE_LIMITED':
|
||||
return { reason: 'api', message: MESSAGES.rateLimited };
|
||||
case 'CALIBRATION_REQUIRED':
|
||||
case 'DEPENDENCY_UNAVAILABLE':
|
||||
return { reason: 'unavailable', message: MESSAGES.unavailable };
|
||||
case 'LIVE_SESSION_UNUSABLE':
|
||||
return { reason: 'api', message: MESSAGES.sessionUnusable };
|
||||
case 'CONTEXT_REVOKED':
|
||||
case 'CONVERSATION_STALE':
|
||||
return { reason: 'api', message: MESSAGES.stale };
|
||||
case 'NETWORK':
|
||||
return { reason: 'connect', message: MESSAGES.connect };
|
||||
default:
|
||||
@@ -628,4 +959,56 @@ export class VoiceStreamService {
|
||||
private failure(reason: VoiceStartFailure, message: string): VoiceStartResult {
|
||||
return { ok: false, reason, message };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Creation-attempt persistence (ids and paths only — never cookies, CSRF or audio)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
interface VoiceCreationAttempt {
|
||||
conversationRequestId: string;
|
||||
sessionRequestId: string;
|
||||
conversationId: string | null;
|
||||
sessionId: string | null;
|
||||
streamPath: string | null;
|
||||
}
|
||||
|
||||
const ATTEMPT_STORAGE_KEY = 'voice_creation_attempt';
|
||||
|
||||
function newCreationAttempt(): VoiceCreationAttempt {
|
||||
return {
|
||||
conversationRequestId: crypto.randomUUID(),
|
||||
sessionRequestId: crypto.randomUUID(),
|
||||
conversationId: null,
|
||||
sessionId: null,
|
||||
streamPath: null,
|
||||
};
|
||||
}
|
||||
|
||||
function loadPersistedAttempt(): VoiceCreationAttempt | null {
|
||||
try {
|
||||
const raw = sessionStorage.getItem(ATTEMPT_STORAGE_KEY);
|
||||
if (!raw) return null;
|
||||
const parsed = JSON.parse(raw) as VoiceCreationAttempt;
|
||||
if (!parsed?.conversationRequestId || !parsed?.sessionRequestId) return null;
|
||||
return parsed;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function persistAttempt(attempt: VoiceCreationAttempt): void {
|
||||
try {
|
||||
sessionStorage.setItem(ATTEMPT_STORAGE_KEY, JSON.stringify(attempt));
|
||||
} catch {
|
||||
/* storage unavailable (private mode): the attempt lives in memory only */
|
||||
}
|
||||
}
|
||||
|
||||
function clearPersistedAttempt(): void {
|
||||
try {
|
||||
sessionStorage.removeItem(ATTEMPT_STORAGE_KEY);
|
||||
} catch {
|
||||
/* storage unavailable: nothing to clear */
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,7 +12,9 @@ export type VoiceStreamState = 'IDLE' | 'LISTENING' | 'PROCESSING' | 'SPEAKING'
|
||||
export type VoiceConnection = 'disconnected' | 'connecting' | 'connected';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Backend contract: mvp_ui_api_catalog.md (§6, "Live Voice Conversations & WSS")
|
||||
// Backend contract: docs/backend-api-docs/frontend-backend-connection-handoff.md (§7–§9)
|
||||
// Audio is raw mono signed PCM16 little-endian at 24000 Hz in BOTH directions
|
||||
// (no WAV header). The session id, stream path and refs always come from the server.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export interface VoiceSource {
|
||||
@@ -21,7 +23,8 @@ export interface VoiceSource {
|
||||
chunk_id: string;
|
||||
title: string;
|
||||
excerpt?: string;
|
||||
location?: { page?: number; section?: string };
|
||||
location?: { page?: number; section?: string } | null;
|
||||
/** `false` = the excerpt is no longer valid and must be hidden, not kept on screen. */
|
||||
available?: boolean;
|
||||
}
|
||||
|
||||
@@ -40,25 +43,44 @@ export type VoiceServerEvent =
|
||||
input_audio: VoiceAudioFormat;
|
||||
output_audio: VoiceAudioFormat;
|
||||
}
|
||||
| {
|
||||
type: 'user_speech_started';
|
||||
turn_ref: string;
|
||||
}
|
||||
| {
|
||||
type: 'transcript';
|
||||
turn_ref: string;
|
||||
role: 'user' | 'assistant';
|
||||
/**
|
||||
* Full text so far OR a new fragment: the catalog does not say which, so
|
||||
* Full text so far OR a new fragment: the contract does not say which, so
|
||||
* `VoiceStreamService.mergeTranscriptText` accepts both (`completed` always carries the final text).
|
||||
*/
|
||||
text: string;
|
||||
status: TranscriptStatus;
|
||||
}
|
||||
| { type: 'sources'; turn_ref: string; tool_call_id: string; sources: VoiceSource[] }
|
||||
| { type: 'turn_interrupted'; turn_ref: string; cancelled_tool_call_ids: string[] }
|
||||
| { type: 'sources'; turn_ref: string; tool_call_id?: string; sources: VoiceSource[] }
|
||||
| { type: 'audio_started'; audio_ref: string; turn_ref?: string }
|
||||
| { type: 'audio_ended'; audio_ref: string; turn_ref?: string }
|
||||
| { type: 'turn_interrupted'; turn_ref: string; cancelled_tool_call_ids?: string[] }
|
||||
| {
|
||||
type: 'error';
|
||||
turn_ref?: string;
|
||||
audio_ref?: string;
|
||||
error: { code: string; message: string; request_id?: string; retryable: boolean };
|
||||
};
|
||||
|
||||
/**
|
||||
* 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 worklet — never an elapsed timer), and is sent again as the final
|
||||
* interruption/stop report.
|
||||
*/
|
||||
export interface PlaybackProgressMessage {
|
||||
type: 'playback_progress';
|
||||
audio_ref: string;
|
||||
played_ms: number;
|
||||
}
|
||||
|
||||
export interface VoiceMessage {
|
||||
/** `${turn_ref}:${role}` */
|
||||
id: string;
|
||||
@@ -80,26 +102,34 @@ export interface VoiceSessionEnd {
|
||||
error?: string;
|
||||
}
|
||||
|
||||
/** V02/V03 polling shape (safe diagnostics only). */
|
||||
export interface VoiceSessionStatus {
|
||||
session_id: string;
|
||||
status: string;
|
||||
close_reason?: string | null;
|
||||
expires_at?: string;
|
||||
}
|
||||
|
||||
export interface VoiceStreamConfig {
|
||||
/** API prefix. */
|
||||
apiBase: string;
|
||||
/** Origin of the API; '' = same origin as the app (required for the `rag_session` cookie handshake). */
|
||||
apiOrigin: string;
|
||||
/** Fixed by the contract: 16 kHz up, 24 kHz down, mono PCM16. */
|
||||
/** Fixed by the contract: 24 kHz up and 24 kHz down, mono PCM16LE. */
|
||||
inputSampleRate: number;
|
||||
outputSampleRate: number;
|
||||
frameMs: number;
|
||||
connectTimeoutMs: number;
|
||||
/** After playback drains without a `completed` assistant transcript, wait this long, then return to LISTENING. */
|
||||
settleMs: number;
|
||||
/** Folder (relative to <base href>) holding the two *.worklet.js files. */
|
||||
/** Folder (relative to <base href>) holding the two *.worklet.js files, served from the UI origin. */
|
||||
workletBasePath: string;
|
||||
}
|
||||
|
||||
export const DEFAULT_VOICE_STREAM_CONFIG: VoiceStreamConfig = {
|
||||
apiBase: '/api/v1',
|
||||
apiOrigin: 'http://192.168.180.151:1322',
|
||||
inputSampleRate: 16000,
|
||||
apiOrigin: 'http://10.0.8.51:1322',
|
||||
inputSampleRate: 24000,
|
||||
outputSampleRate: 24000,
|
||||
frameMs: 20,
|
||||
connectTimeoutMs: 8000,
|
||||
|
||||
@@ -1,31 +1,46 @@
|
||||
import { InjectionToken, inject } from '@angular/core';
|
||||
import { VOICE_STREAM_CONFIG, VoiceServerEvent } from './voice-stream.types';
|
||||
import { PlaybackProgressMessage, VOICE_STREAM_CONFIG, VoiceServerEvent } from './voice-stream.types';
|
||||
|
||||
export interface VoiceTransportHandlers {
|
||||
onEvent(event: VoiceServerEvent): void;
|
||||
onAudio(chunk: ArrayBuffer): void;
|
||||
/** Only called for closes the client did not ask for. */
|
||||
onClose(info: { clean: boolean; code: number; reason: string }): void;
|
||||
/**
|
||||
* A bounded queue filled up (capture send queue or socket backpressure). The call must
|
||||
* end safely with a failure — silently dropping PCM and continuing is not allowed.
|
||||
*/
|
||||
onOverflow(which: 'send'): void;
|
||||
}
|
||||
|
||||
export interface VoiceTransport {
|
||||
connect(handlers: VoiceTransportHandlers): Promise<void>;
|
||||
/** PCM16 mono 16 kHz frame. */
|
||||
/** PCM16 mono 24 kHz frame, sample-aligned, at most MAX_MESSAGE_BYTES. */
|
||||
sendAudio(frame: ArrayBuffer): void;
|
||||
/** The only client→server JSON message (`playback_progress`). */
|
||||
sendControl(message: PlaybackProgressMessage): void;
|
||||
close(): void;
|
||||
}
|
||||
|
||||
/** Drop mic frames instead of queueing when the socket is this far behind (~0.5 MB ≈ 16 s of audio). */
|
||||
const MAX_BUFFERED_BYTES = 512 * 1024;
|
||||
/** Maximum size of one binary frame on the wire (contract: 9600 bytes, sample-aligned). */
|
||||
export const MAX_MESSAGE_BYTES = 9600;
|
||||
/** Bounded capture queue: 96000 bytes / 100 messages. Filled capacity fails the call. */
|
||||
const MAX_QUEUE_BYTES = 96000;
|
||||
const MAX_QUEUE_MESSAGES = 100;
|
||||
|
||||
/**
|
||||
* Plain WebSocket. Authentication is the `rag_session` cookie sent automatically on the handshake,
|
||||
* so the page must be served from the same site as the API. The contract has no client→server
|
||||
* JSON messages: the client only sends binary audio frames.
|
||||
* Plain WebSocket. Authentication is the `rag_session` cookie sent automatically on the
|
||||
* handshake, so the page is served from the same origin as the API (same-origin `/api`
|
||||
* proxy). The contract has exactly one client→server JSON message: `playback_progress`.
|
||||
*/
|
||||
export class WebSocketVoiceTransport implements VoiceTransport {
|
||||
private ws: WebSocket | null = null;
|
||||
private handlers: VoiceTransportHandlers | null = null;
|
||||
private closedByClient = false;
|
||||
/** Frames produced before the socket opens (or while backpressured). */
|
||||
private sendQueue: ArrayBuffer[] = [];
|
||||
private sendQueuedBytes = 0;
|
||||
private sendQueuedMessages = 0;
|
||||
|
||||
constructor(
|
||||
private readonly url: string,
|
||||
@@ -37,6 +52,8 @@ export class WebSocketVoiceTransport implements VoiceTransport {
|
||||
const ws = new WebSocket(this.url);
|
||||
ws.binaryType = 'arraybuffer';
|
||||
this.ws = ws;
|
||||
this.handlers = handlers;
|
||||
this.closedByClient = false;
|
||||
|
||||
let opened = false;
|
||||
const timer = setTimeout(() => {
|
||||
@@ -47,6 +64,7 @@ export class WebSocketVoiceTransport implements VoiceTransport {
|
||||
ws.onopen = () => {
|
||||
opened = true;
|
||||
clearTimeout(timer);
|
||||
this.flushSendQueue();
|
||||
resolve();
|
||||
};
|
||||
|
||||
@@ -75,6 +93,7 @@ export class WebSocketVoiceTransport implements VoiceTransport {
|
||||
reject(new Error('connect-failed'));
|
||||
return;
|
||||
}
|
||||
this.dropSendQueue();
|
||||
if (!this.closedByClient) {
|
||||
handlers.onClose({ clean: event.wasClean, code: event.code, reason: event.reason });
|
||||
}
|
||||
@@ -84,13 +103,41 @@ export class WebSocketVoiceTransport implements VoiceTransport {
|
||||
|
||||
sendAudio(frame: ArrayBuffer): void {
|
||||
const ws = this.ws;
|
||||
if (ws?.readyState === WebSocket.OPEN && ws.bufferedAmount < MAX_BUFFERED_BYTES) {
|
||||
if (!ws || this.closedByClient) return;
|
||||
|
||||
// Contract guards: every binary message is sample-aligned and bounded.
|
||||
if (frame.byteLength === 0 || frame.byteLength % 2 !== 0 || frame.byteLength > MAX_MESSAGE_BYTES) {
|
||||
return; // never emit an out-of-contract frame; the capture worklet guarantees this shape
|
||||
}
|
||||
|
||||
if (ws.readyState === WebSocket.OPEN) {
|
||||
ws.send(frame);
|
||||
return;
|
||||
}
|
||||
if (ws.readyState !== WebSocket.CONNECTING) return;
|
||||
|
||||
this.sendQueuedBytes += frame.byteLength;
|
||||
this.sendQueuedMessages += 1;
|
||||
if (this.sendQueuedBytes > MAX_QUEUE_BYTES || this.sendQueuedMessages > MAX_QUEUE_MESSAGES) {
|
||||
// Filled capacity is a safe failure, not a silent drop.
|
||||
this.dropSendQueue();
|
||||
const handlers = this.handlers;
|
||||
this.close();
|
||||
handlers?.onOverflow('send');
|
||||
}
|
||||
this.sendQueue.push(frame);
|
||||
}
|
||||
|
||||
sendControl(message: PlaybackProgressMessage): void {
|
||||
const ws = this.ws;
|
||||
if (ws?.readyState === WebSocket.OPEN && !this.closedByClient) {
|
||||
ws.send(JSON.stringify(message));
|
||||
}
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.closedByClient = true;
|
||||
this.dropSendQueue();
|
||||
const ws = this.ws;
|
||||
this.ws = null;
|
||||
if (!ws) return;
|
||||
@@ -102,6 +149,25 @@ export class WebSocketVoiceTransport implements VoiceTransport {
|
||||
/* already closed */
|
||||
}
|
||||
}
|
||||
|
||||
private flushSendQueue(): void {
|
||||
const ws = this.ws;
|
||||
const queue = this.sendQueue;
|
||||
this.sendQueue = [];
|
||||
this.sendQueuedBytes = 0;
|
||||
this.sendQueuedMessages = 0;
|
||||
if (!ws) return; // the onclose handler already runs for this socket
|
||||
for (const frame of queue) {
|
||||
if (ws.readyState !== WebSocket.OPEN) break;
|
||||
ws.send(frame);
|
||||
}
|
||||
}
|
||||
|
||||
private dropSendQueue(): void {
|
||||
this.sendQueue = [];
|
||||
this.sendQueuedBytes = 0;
|
||||
this.sendQueuedMessages = 0;
|
||||
}
|
||||
}
|
||||
|
||||
/** Replace in tests, or to plug a different transport. */
|
||||
@@ -114,4 +180,4 @@ export const VOICE_TRANSPORT_FACTORY = new InjectionToken<(url: string) => Voice
|
||||
return (url: string) => new WebSocketVoiceTransport(url, config.connectTimeoutMs);
|
||||
},
|
||||
},
|
||||
);
|
||||
);
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
import {
|
||||
CallActivityPoint,
|
||||
CallOutcomeShare,
|
||||
HourlyCallPoint,
|
||||
WallboardKpis,
|
||||
} from './wallboard.types';
|
||||
|
||||
const ACTIVITY_DAYS = 14;
|
||||
|
||||
const HOUR_BUCKETS: { hour: number; span: number }[] = [
|
||||
{ hour: 8, span: 2 },
|
||||
{ hour: 10, span: 2 },
|
||||
{ hour: 12, span: 2 },
|
||||
{ hour: 14, span: 2 },
|
||||
{ hour: 16, span: 2 },
|
||||
{ hour: 18, span: 2 },
|
||||
{ hour: 20, span: 2 },
|
||||
];
|
||||
|
||||
/** Deterministic pseudo-random source so mock data stays stable across reloads and tests. */
|
||||
function seededNoise(seed: number): number {
|
||||
const value = Math.sin(seed * 12.9898) * 43758.5453;
|
||||
return Math.abs(value - Math.floor(value));
|
||||
}
|
||||
|
||||
function buildActivity(): CallActivityPoint[] {
|
||||
const points: CallActivityPoint[] = [];
|
||||
const today = new Date();
|
||||
|
||||
for (let offset = ACTIVITY_DAYS - 1; offset >= 0; offset--) {
|
||||
const date = new Date(today);
|
||||
date.setDate(today.getDate() - offset);
|
||||
|
||||
const weekday = date.getDay();
|
||||
const isWeekend = weekday === 4 || weekday === 5;
|
||||
const noise = seededNoise(offset + 3);
|
||||
|
||||
// Lower weekend volume with a mild upward drift toward today.
|
||||
const base = isWeekend ? 620 : 980;
|
||||
const drift = (ACTIVITY_DAYS - offset) * 6;
|
||||
|
||||
points.push({
|
||||
label: date.toLocaleDateString('fa-IR', { day: 'numeric', month: 'long' }),
|
||||
count: Math.round(base + noise * 180 + drift),
|
||||
});
|
||||
}
|
||||
|
||||
return points;
|
||||
}
|
||||
|
||||
function buildHourly(): HourlyCallPoint[] {
|
||||
return HOUR_BUCKETS.map((bucket, index) => {
|
||||
const noise = seededNoise(index + 11);
|
||||
// Mid-day and late-afternoon peaks, quiet early morning.
|
||||
const peak = bucket.hour <= 12 ? 1.35 : bucket.hour >= 18 ? 1.5 : 1.15;
|
||||
return {
|
||||
label: `${toPersianHour(bucket.hour)}–${toPersianHour(bucket.hour + bucket.span)}`,
|
||||
count: Math.round((520 + noise * 260) * peak),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function toPersianHour(hour: number): string {
|
||||
const persianDigits = ['۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹'];
|
||||
return String(hour)
|
||||
.padStart(2, '0')
|
||||
.replace(/\d/g, (digit) => persianDigits[Number(digit)]);
|
||||
}
|
||||
|
||||
export const MOCK_WALLBOARD_KPIS: WallboardKpis = {
|
||||
totalCalls: 12846,
|
||||
aiCalls: 8412,
|
||||
avgAiTalkSeconds: 142,
|
||||
successfulAiCalls: 7156,
|
||||
transferredToAgentCalls: 1256,
|
||||
periodLabel: 'امروز',
|
||||
};
|
||||
|
||||
export const MOCK_CALL_OUTCOMES: CallOutcomeShare[] = [
|
||||
{ id: 'ai', label: 'پاسخگویی هوش مصنوعی', value: 7156 },
|
||||
{ id: 'transfer', label: 'انتقال به کارشناس پس از هوش مصنوعی', value: 1256 },
|
||||
{ id: 'direct-agent', label: 'تماس مستقیم با کارشناس', value: 4434 },
|
||||
];
|
||||
|
||||
export const MOCK_CALL_ACTIVITY: CallActivityPoint[] = buildActivity();
|
||||
|
||||
export const MOCK_HOURLY_CALLS: HourlyCallPoint[] = buildHourly();
|
||||
@@ -0,0 +1,77 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { provideZonelessChangeDetection } from '@angular/core';
|
||||
import { provideAnimations } from '@angular/platform-browser/animations';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { provideRouter } from '@angular/router';
|
||||
import { TOAST_CONFIG, DefaultGlobalConfig } from 'ngx-toastr';
|
||||
import { firstValueFrom } from 'rxjs';
|
||||
import { WallboardService } from './wallboard.service';
|
||||
|
||||
describe('WallboardService', () => {
|
||||
let service: WallboardService;
|
||||
|
||||
beforeEach(() => {
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
provideZonelessChangeDetection(),
|
||||
provideHttpClient(),
|
||||
provideRouter([]),
|
||||
provideAnimations(),
|
||||
{ provide: TOAST_CONFIG, useValue: { default: DefaultGlobalConfig, config: {} } },
|
||||
],
|
||||
});
|
||||
service = TestBed.inject(WallboardService);
|
||||
});
|
||||
|
||||
it('should be created', () => {
|
||||
expect(service).toBeTruthy();
|
||||
});
|
||||
|
||||
it('returns KPIs with a consistent AI breakdown', async () => {
|
||||
const kpis = await firstValueFrom(service.getKpis());
|
||||
|
||||
expect(kpis.totalCalls).toBeGreaterThan(0);
|
||||
expect(kpis.aiCalls).toBeGreaterThan(0);
|
||||
expect(kpis.aiCalls).toBeLessThanOrEqual(kpis.totalCalls);
|
||||
expect(kpis.successfulAiCalls + kpis.transferredToAgentCalls).toBe(kpis.aiCalls);
|
||||
expect(kpis.avgAiTalkSeconds).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('returns outcome shares summing up to the total call count', async () => {
|
||||
const outcomes = await firstValueFrom(service.getOutcomes());
|
||||
const kpis = await firstValueFrom(service.getKpis());
|
||||
const total = outcomes.reduce((sum, outcome) => sum + outcome.value, 0);
|
||||
|
||||
expect(outcomes.length).toBeGreaterThan(0);
|
||||
expect(total).toBe(kpis.totalCalls);
|
||||
});
|
||||
|
||||
it('returns a 14 point activity trend with valid labels', async () => {
|
||||
const activity = await firstValueFrom(service.getActivity());
|
||||
|
||||
expect(activity).toHaveLength(14);
|
||||
activity.forEach((point) => {
|
||||
expect(point.label).toBeTruthy();
|
||||
expect(point.count).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
|
||||
it('returns hourly buckets covering the whole working day', async () => {
|
||||
const hourly = await firstValueFrom(service.getHourlyDistribution());
|
||||
|
||||
expect(hourly.length).toBeGreaterThan(0);
|
||||
hourly.forEach((bucket) => {
|
||||
expect(bucket.label).toMatch(/–/);
|
||||
expect(bucket.count).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
|
||||
it('returns a complete overview combining every wallboard dataset', async () => {
|
||||
const overview = await firstValueFrom(service.getOverview());
|
||||
|
||||
expect(overview.kpis.totalCalls).toBeGreaterThan(0);
|
||||
expect(overview.outcomes.length).toBeGreaterThan(0);
|
||||
expect(overview.activity).toHaveLength(14);
|
||||
expect(overview.hourly.length).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,77 @@
|
||||
import { Injectable, inject } from '@angular/core';
|
||||
import { map, Observable, of } from 'rxjs';
|
||||
import { HttpService } from '../http-request/http.service';
|
||||
import {
|
||||
CallActivityPoint,
|
||||
CallOutcomeShare,
|
||||
HourlyCallPoint,
|
||||
WallboardKpis,
|
||||
WallboardView,
|
||||
} from './wallboard.types';
|
||||
import {
|
||||
MOCK_CALL_ACTIVITY,
|
||||
MOCK_CALL_OUTCOMES,
|
||||
MOCK_HOURLY_CALLS,
|
||||
MOCK_WALLBOARD_KPIS,
|
||||
} from './wallboard.mock';
|
||||
|
||||
/**
|
||||
* Call center wallboard data source. The dashboard is read-only, so every
|
||||
* endpoint is a plain GET that returns a ready-to-render view. While no
|
||||
* wallboard endpoints exist on the backend, deterministic mock data keeps the
|
||||
* dashboard fully explorable; flip `useMockData` to false (and align the
|
||||
* endpoint paths) to consume the real API without touching the page.
|
||||
*/
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class WallboardService {
|
||||
private readonly http = inject(HttpService);
|
||||
|
||||
/** Flip to false once the backend wallboard endpoints are deployed. */
|
||||
private readonly useMockData = true;
|
||||
|
||||
getKpis(): Observable<WallboardKpis> {
|
||||
return this.request<WallboardKpis>('wallboard/kpis', {}, MOCK_WALLBOARD_KPIS);
|
||||
}
|
||||
|
||||
/** سهم روشهای پاسخگویی: هوش مصنوعی در مقابل کارشناس. */
|
||||
getOutcomes(): Observable<CallOutcomeShare[]> {
|
||||
return this.request<CallOutcomeShare[]>('wallboard/call-outcomes', {}, MOCK_CALL_OUTCOMES);
|
||||
}
|
||||
|
||||
getActivity(days = 14): Observable<CallActivityPoint[]> {
|
||||
return this.request<CallActivityPoint[]>(
|
||||
'wallboard/call-activity',
|
||||
{ days },
|
||||
MOCK_CALL_ACTIVITY,
|
||||
);
|
||||
}
|
||||
|
||||
getHourlyDistribution(): Observable<HourlyCallPoint[]> {
|
||||
return this.request<HourlyCallPoint[]>(
|
||||
'wallboard/hourly-distribution',
|
||||
{},
|
||||
MOCK_HOURLY_CALLS,
|
||||
);
|
||||
}
|
||||
|
||||
getOverview(): Observable<WallboardView> {
|
||||
return this.request<WallboardView>('wallboard/overview', {}, {
|
||||
kpis: MOCK_WALLBOARD_KPIS,
|
||||
outcomes: MOCK_CALL_OUTCOMES,
|
||||
activity: MOCK_CALL_ACTIVITY,
|
||||
hourly: MOCK_HOURLY_CALLS,
|
||||
});
|
||||
}
|
||||
|
||||
private request<T>(endpoint: string, params: Record<string, unknown>, fallback: T): Observable<T> {
|
||||
if (this.useMockData) {
|
||||
return of(fallback);
|
||||
}
|
||||
|
||||
return this.http
|
||||
.get<T>(endpoint, { params, skipToast: true, skipHasErrorCheck: true })
|
||||
.pipe(map((response) => response.result));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
/** KPI snapshot for the wallboard («والبورد») dashboard. */
|
||||
export interface WallboardKpis {
|
||||
/** کل تماسهای دریافتی */
|
||||
totalCalls: number;
|
||||
/** تماسهایی که با هوش مصنوعی گفتگو شدهاند */
|
||||
aiCalls: number;
|
||||
/** میانگین زمان صحبت کاربر با هوش مصنوعی (ثانیه) */
|
||||
avgAiTalkSeconds: number;
|
||||
/** تماسهایی که هوش مصنوعی با موفقیت به پایان رسانده است */
|
||||
successfulAiCalls: number;
|
||||
/** تماسهایی که پس از هوش مصنوعی به کارشناس transfer شدهاند */
|
||||
transferredToAgentCalls: number;
|
||||
/** برچسب بازه زمانی گزارش */
|
||||
periodLabel: string;
|
||||
}
|
||||
|
||||
/** سهم هر روش پاسخگویی از کل تماسها (نمودار دایرهای هوش مصنوعی/کارشناس) */
|
||||
export interface CallOutcomeShare {
|
||||
id: string;
|
||||
label: string;
|
||||
value: number;
|
||||
}
|
||||
|
||||
/** نقطه از روند فعالیت تماسها در گذر زمان (نمودار خطی) */
|
||||
export interface CallActivityPoint {
|
||||
label: string;
|
||||
count: number;
|
||||
}
|
||||
|
||||
/** حجم تماسها در هر بازه ساعتی (نمودار میلهای) */
|
||||
export interface HourlyCallPoint {
|
||||
label: string;
|
||||
count: number;
|
||||
}
|
||||
|
||||
export interface WallboardView {
|
||||
kpis: WallboardKpis;
|
||||
outcomes: CallOutcomeShare[];
|
||||
activity: CallActivityPoint[];
|
||||
hourly: HourlyCallPoint[];
|
||||
}
|
||||
Reference in New Issue
Block a user