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:
Peyman Honarjoo
2026-10-10 00:20:00 +03:30
parent 0b5a882ecb
commit ff7fcbc4bb
71 changed files with 9148 additions and 780 deletions
@@ -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');
});
});