Files
2026-10-06 09:57:33 +03:30

650 lines
39 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# SRC_STRUCTURE.md — `src/` Directory Architecture
> **Companion to:** `ARCHITECTURE.md`, `DEPENDENCIES.md`
> **Targets:** Angular 22 · standalone components · Signals · `ChangeDetectionStrategy.OnPush` · zoneless (with a Zone.js-compatible phase)
### Changes relative to `ARCHITECTURE.md`
This document is now the canonical layout. Four things moved or were renamed:
| Was (`ARCHITECTURE.md`) | Now | Reason |
|---|---|---|
| `core/state/` | `core/services/` (stores) + `core/models/` (types) | Matches the requested `core/services/` for global state and local storage |
| `features/voice-agent/services/visualizer/` | `core/audio/visualizer/` | The Three.js engine has no feature-specific logic; the voice feature only hosts the `<canvas>` |
| `core/audio/worklets/*.worklet.js` | `src/assets/worklets/pcm-*.js` | Worklets run in their own global scope and are fetched by URL, so they live in assets |
| `provideExperimentalZonelessChangeDetection` | `provideZonelessChangeDetection` | The experimental name does not exist in Angular 22 (see `DEPENDENCIES.md` §0) |
---
## 1. Full tree
```text
voice-faq-app/
├─ .postcssrc.json # Tailwind v4 PostCSS plugin (project root)
├─ angular.json · package.json · tsconfig*.json · eslint.config.js · playwright.config.ts · .nvmrc
│
└─ src/
├─ index.html
├─ main.ts
├─ styles.css
├─ favicon.ico
│
├─ styles/
│ ├─ theme.css # @theme tokens: colors, glow shadows, fonts, keyframes
│ └─ utilities.css # @utility glass, glow-*, scrollbar, focus ring
│
├─ environments/
│ ├─ environment.ts # development defaults
│ └─ environment.production.ts # production values (file-replaced at build)
│
├─ assets/
│ ├─ worklets/
│ │ ├─ pcm-capture-processor.js # mic -> 20 ms Int16 frames (audio thread)
│ │ └─ pcm-playback-processor.js # ring/jitter buffer -> speakers (audio thread)
│ └─ textures/
│ └─ .gitkeep # empty in v1 (orb noise is procedural)
│
└─ app/
├─ app.component.ts
├─ app.config.ts
├─ app.routes.ts
│
├─ core/
│ ├─ config/
│ │ ├─ app-config.token.ts # APP_CONFIG injection token + typed AppConfig
│ │ └─ app-config.provider.ts # provideAppConfig() reads environment
│ │
│ ├─ models/
│ │ ├─ voice.types.ts # VoiceState, VoiceEvent, VoiceSession, TranscriptEntry, VoiceError
│ │ ├─ protocol.types.ts # AudioFrame, ClientMessage, ServerMessage, AudioFormat
│ │ └─ app-error.ts # AppError class + error code union
│ │
│ ├─ audio/
│ │ ├─ audio-context.provider.ts # AUDIO_CONTEXT_HOLDER token, provideAudio(), lazy AudioContext
│ │ ├─ audio.tokens.ts # AUDIO_CONFIG (sample rates, frame ms, prebuffer ms, fftSize)
│ │ ├─ audio.types.ts # worklet command/event unions
│ │ ├─ audio-engine.service.ts # orchestrates mic, nodes, analysers, mute/flush/play
│ │ ├─ mic-capture.service.ts # getUserMedia, device list, permission signal
│ │ ├─ pcm-capture.node.ts # typed wrapper around the capture AudioWorkletNode
│ │ ├─ pcm-playback.node.ts # typed wrapper around the playback AudioWorkletNode
│ │ ├─ audio-level-bus.ts # mutable per-frame levels shared with the visualizer
│ │ ├─ pcm-utils.ts # float<->int16, resample, RMS
│ │ └─ visualizer/
│ │ ├─ visualizer.interface.ts # Visualizer contract (init/applyState/resize/dispose)
│ │ ├─ visualizer.service.ts # VisualizerEngine: rAF loop outside NgZone
│ │ ├─ audio-visualizer.directive.ts# attribute directive placed on <canvas>
│ │ ├─ three-orb.visualizer.ts # WebGL implementation (lazy `import('three')`)
│ │ ├─ canvas2d.visualizer.ts # fallback when WebGL is unavailable or lost
│ │ ├─ state-presets.ts # per-state color, turbulence, easing, source
│ │ ├─ shader-source.d.ts # declare module '*.glsl'
│ │ └─ shaders/
│ │ ├─ orb.vert.glsl # displacement by level + noise
│ │ └─ orb.frag.glsl # fresnel glow, state color blend
│ │
│ ├─ websocket/
│ │ ├─ realtime-transport.ts # abstract RealtimeTransport (WS today, WebRTC later)
│ │ ├─ websocket.service.ts # WebSocket implementation of the transport
│ │ ├─ connection.machine.ts # connection state machine (pure reducer)
│ │ ├─ reconnect-policy.ts # exponential backoff with jitter
│ │ ├─ heartbeat.ts # ping/pong watchdog
│ │ ├─ frame-codec.ts # 16-byte binary header encode/decode
│ │ └─ audio-stream.handler.ts # sequencing, turnId filter, hand-off to playback node
│ │
│ ├─ services/
│ │ ├─ voice-state.store.ts # voiceState, activeSession, transcript signals
│ │ ├─ app-settings.store.ts # persisted preferences (device, volume, transcript open)
│ │ ├─ storage.service.ts # typed, versioned localStorage wrapper
│ │ ├─ auth.service.ts # short-lived WebSocket ticket and HTTP token
│ │ ├─ browser-capabilities.service.ts # AudioWorklet / getUserMedia / WebGL checks
│ │ ├─ notification.service.ts # toast queue (signal)
│ │ ├─ telemetry.service.ts # latency marks, underruns, transitions (no PII)
│ │ └─ logger.service.ts # leveled logger, silenced in production
│ │
│ ├─ guards/
│ │ ├─ auth.guard.ts
│ │ ├─ browser-support.guard.ts
│ │ └─ unsaved-changes.guard.ts
│ │
│ └─ interceptors/
│ ├─ auth.interceptor.ts
│ ├─ retry.interceptor.ts
│ └─ error.interceptor.ts
│
├─ features/
│ ├─ voice-agent/
│ │ ├─ voice-agent.routes.ts
│ │ ├─ voice-agent.page.ts
│ │ ├─ components/
│ │ │ ├─ voice-orb/
│ │ │ │ ├─ voice-orb.component.ts
│ │ │ │ └─ voice-orb.component.html
│ │ │ ├─ mic-control-bar/
│ │ │ ├─ transcript-overlay/
│ │ │ ├─ status-badge/
│ │ │ ├─ faq-suggestions/
│ │ │ └─ mic-permission-prompt/
│ │ └─ services/
│ │ ├─ voice-session.service.ts # the only writer of voiceState
│ │ ├─ voice-transitions.ts # TRANSITIONS table + guards (pure data/functions)
│ │ ├─ voice-effects.ts # side effects per transition (engine + socket)
│ │ └─ barge-in-detector.service.ts # client energy gate for instant interruption
│ │
│ └─ faq-manager/
│ ├─ faq-manager.routes.ts
│ ├─ faq-manager.page.ts
│ ├─ models/
│ │ └─ faq.types.ts
│ ├─ components/
│ │ ├─ faq-drawer/
│ │ ├─ file-dropzone/
│ │ ├─ upload-preview-table/
│ │ ├─ document-list/
│ │ ├─ qa-grid/
│ │ └─ qa-editor-modal/
│ ├─ grid/
│ │ ├─ register-grid-modules.ts
│ │ ├─ qa-grid.columns.ts
│ │ ├─ qa-grid.theme.ts
│ │ └─ cell-renderers/
│ │ ├─ status-cell.renderer.ts
│ │ ├─ tags-cell.renderer.ts
│ │ └─ actions-cell.renderer.ts
│ ├─ services/
│ │ ├─ faq-store.ts
│ │ ├─ faq-api.service.ts
│ │ ├─ faq-ingestion.service.ts
│ │ ├─ ingestion-events.service.ts
│ │ ├─ file-validator.service.ts
│ │ ├─ csv-parser.service.ts
│ │ └─ faq-drawer.service.ts
│ └─ utils/
│ ├─ file-signatures.ts
│ └─ csv-column-detect.ts
│
└─ shared/
├─ ui/
│ ├─ button/
│ ├─ icon-button/
│ ├─ badge/
│ ├─ icon/ # <app-icon> + central Lucide registry (icons.ts)
│ ├─ glass-panel/
│ ├─ drawer-shell/
│ ├─ dialog-shell/
│ ├─ toast-host/
│ ├─ spinner/
│ ├─ progress-bar/
│ ├─ skeleton/
│ └─ empty-state/
├─ directives/
│ ├─ glass-panel.directive.ts
│ ├─ state-glow.directive.ts
│ ├─ file-drop.directive.ts
│ ├─ autofocus.directive.ts
│ └─ resize-observer.directive.ts
├─ pipes/
│ ├─ file-size.pipe.ts
│ ├─ relative-time.pipe.ts
│ ├─ duration.pipe.ts
│ └─ truncate.pipe.ts
└─ utils/
├─ assert.ts
├─ id.ts
├─ math.ts
└─ raf-throttle.ts
```
### Dependency rule (enforce with ESLint `no-restricted-imports`)
```text
shared <- core <- features
```
- `shared` imports nothing from `core` or `features`.
- `core` imports from `shared` only (and never from `features`).
- A feature imports from `core` and `shared`, **never from another feature**. If both features need something, it moves to `core` or `shared`.
- `core/audio` and `core/websocket` import no UI (no components, no CDK), so they can be unit-tested without a DOM.
**Path aliases:** `@core/*`, `@features/*`, `@shared/*`, `@env/*` (see `DEPENDENCIES.md` §6.4).
---
## 2. Root configuration files (full contents)
### 2.1 `src/main.ts`
```ts
import { bootstrapApplication } from '@angular/platform-browser';
import { AppComponent } from './app/app.component';
import { appConfig } from './app/app.config';
bootstrapApplication(AppComponent, appConfig).catch((err) => console.error(err));
```
### 2.2 `src/app/app.config.ts`
```ts
import {
ApplicationConfig,
provideBrowserGlobalErrorListeners,
provideZonelessChangeDetection,
// provideZoneChangeDetection, // <- zone phase: use this instead (needs "zone.js" in polyfills)
} from '@angular/core';
import { provideHttpClient, withFetch, withInterceptors } from '@angular/common/http';
import { provideRouter, withComponentInputBinding } from '@angular/router';
import { routes } from './app.routes';
import { provideAppConfig } from '@core/config/app-config.provider';
import { provideAudio } from '@core/audio/audio-context.provider';
import { authInterceptor } from '@core/interceptors/auth.interceptor';
import { retryInterceptor } from '@core/interceptors/retry.interceptor';
import { errorInterceptor } from '@core/interceptors/error.interceptor';
export const appConfig: ApplicationConfig = {
providers: [
// Zoneless (target). Angular 18/19 name: provideExperimentalZonelessChangeDetection().
provideZonelessChangeDetection(),
// Zone phase alternative: provideZoneChangeDetection({ eventCoalescing: true }),
provideBrowserGlobalErrorListeners(),
provideRouter(routes, withComponentInputBinding()),
provideHttpClient(
withFetch(),
withInterceptors([authInterceptor, retryInterceptor, errorInterceptor]),
),
provideAppConfig(),
provideAudio(), // registers AUDIO_CONFIG + the lazy AudioContext holder (no context is created yet)
],
};
```
### 2.3 `src/app/app.routes.ts`
```ts
import { Routes } from '@angular/router';
import { authGuard } from '@core/guards/auth.guard';
import { browserSupportGuard } from '@core/guards/browser-support.guard';
import { unsavedChangesGuard } from '@core/guards/unsaved-changes.guard';
export const routes: Routes = [
{ path: '', pathMatch: 'full', redirectTo: 'voice' },
{
path: 'voice',
title: 'Voice FAQ',
canActivate: [browserSupportGuard, authGuard],
loadChildren: () =>
import('@features/voice-agent/voice-agent.routes').then((m) => m.VOICE_AGENT_ROUTES),
},
{
path: 'knowledge-base',
title: 'Knowledge Base',
canActivate: [authGuard],
canDeactivate: [unsavedChangesGuard],
loadChildren: () =>
import('@features/faq-manager/faq-manager.routes').then((m) => m.FAQ_MANAGER_ROUTES),
},
{
path: 'unsupported',
title: 'Browser not supported',
loadComponent: () =>
import('@shared/ui/empty-state/empty-state.component').then((m) => m.EmptyStateComponent),
data: { reason: 'unsupported-browser' },
},
{ path: '**', redirectTo: 'voice' },
];
```
### 2.4 `src/app/app.component.ts`
```ts
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { ToastHostComponent } from '@shared/ui/toast-host/toast-host.component';
@Component({
selector: 'app-root',
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [RouterOutlet, ToastHostComponent],
template: `
<main class="min-h-dvh bg-void-950 text-slate-100 antialiased">
<router-outlet />
</main>
<app-toast-host />
`,
})
export class AppComponent {}
```
### 2.5 `src/styles.css`
```css
@import 'tailwindcss';
@import './styles/theme.css';
@import './styles/utilities.css';
:root {
color-scheme: dark;
}
html,
body {
height: 100%;
background: var(--color-void-950);
}
@media (prefers-reduced-motion: reduce) {
*,
*::before,
*::after {
animation-duration: 0.01ms !important;
animation-iteration-count: 1 !important;
transition-duration: 0.01ms !important;
}
}
```
### 2.6 `src/styles/theme.css`
```css
@theme {
/* Surfaces */
--color-void-950: #05060a;
--color-void-900: #0a0c14;
--color-void-800: #11141f;
/* Voice state colors (shared by the orb shader presets and the status badge) */
--color-state-idle: #5b6b8c;
--color-state-listening: #22d3ee;
--color-state-processing: #a78bfa;
--color-state-speaking: #34d399;
--color-state-interrupted: #fb7185;
/* Glow shadows */
--shadow-glow-idle: 0 0 24px rgb(91 107 140 / 0.35);
--shadow-glow-listening: 0 0 28px rgb(34 211 238 / 0.55), 0 0 80px rgb(34 211 238 / 0.2);
--shadow-glow-processing: 0 0 28px rgb(167 139 250 / 0.55), 0 0 80px rgb(167 139 250 / 0.2);
--shadow-glow-speaking: 0 0 28px rgb(52 211 153 / 0.55), 0 0 80px rgb(52 211 153 / 0.2);
--shadow-glow-interrupted: 0 0 28px rgb(251 113 133 / 0.6), 0 0 80px rgb(251 113 133 / 0.25);
--font-sans: 'Inter', ui-sans-serif, system-ui, sans-serif;
--animate-breathe: breathe 6s ease-in-out infinite;
--animate-slide-in-end: slide-in-end 220ms cubic-bezier(0.22, 1, 0.36, 1);
@keyframes breathe {
0%, 100% { transform: scale(1); opacity: 0.85; }
50% { transform: scale(1.04); opacity: 1; }
}
@keyframes slide-in-end {
from { transform: translateX(calc(var(--dir, 1) * 100%)); opacity: 0; }
to { transform: translateX(0); opacity: 1; }
}
}
```
### 2.7 `src/styles/utilities.css`
```css
/* Glassmorphic surface: use as `class="glass"` or through GlassPanelDirective */
@utility glass {
background: rgb(15 18 30 / 0.55);
-webkit-backdrop-filter: blur(16px) saturate(140%);
backdrop-filter: blur(16px) saturate(140%);
border: 1px solid rgb(255 255 255 / 0.08);
box-shadow: inset 0 1px 0 rgb(255 255 255 / 0.06), 0 10px 40px rgb(0 0 0 / 0.45);
}
@utility glass-strong {
background: rgb(10 12 20 / 0.78);
-webkit-backdrop-filter: blur(24px) saturate(160%);
backdrop-filter: blur(24px) saturate(160%);
border: 1px solid rgb(255 255 255 / 0.1);
}
/* Glow rings per voice state */
@utility glow-idle { box-shadow: var(--shadow-glow-idle); }
@utility glow-listening { box-shadow: var(--shadow-glow-listening); }
@utility glow-processing { box-shadow: var(--shadow-glow-processing); }
@utility glow-speaking { box-shadow: var(--shadow-glow-speaking); }
@utility glow-interrupted { box-shadow: var(--shadow-glow-interrupted); }
@utility focus-ring {
outline: 2px solid var(--color-state-listening);
outline-offset: 2px;
}
@utility scrollbar-thin-dark {
scrollbar-width: thin;
scrollbar-color: rgb(255 255 255 / 0.2) transparent;
}
```
### 2.8 `src/index.html`
```html
<!doctype html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8" />
<title>Voice FAQ</title>
<base href="/" />
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
<meta name="color-scheme" content="dark" />
<link rel="icon" type="image/x-icon" href="favicon.ico" />
</head>
<body>
<app-root></app-root>
<noscript>This application requires JavaScript and microphone access.</noscript>
</body>
</html>
```
### 2.9 `src/environments/environment.ts`
```ts
export const environment = {
production: false,
apiBaseUrl: 'http://localhost:8080/api',
wsUrl: 'ws://localhost:8080/realtime',
workletVersion: 'dev', // appended as ?v= to worklet URLs
features: { webrtc: false, clientVad: true },
} as const;
```
`environment.production.ts` has the same shape with `production: true`, `https`/`wss` URLs, and `workletVersion` injected from the CI build id.
---
## 3. `src/app/core/` in detail
### 3.1 `core/config/` and `core/models/`
| File | Purpose |
|---|---|
| `app-config.token.ts` | `AppConfig` interface (`apiBaseUrl`, `wsUrl`, `workletVersion`, `features`) and `APP_CONFIG` `InjectionToken`. Everything that needs a URL injects this instead of importing `environment` directly (easy to override in tests). |
| `app-config.provider.ts` | `provideAppConfig()` returns `{ provide: APP_CONFIG, useValue: environment }`. |
| `voice.types.ts` | `VoiceState`, `VoiceEvent`, `VoiceSession`, `TranscriptEntry`, `VoiceError` exactly as in `ARCHITECTURE.md` §5.1. Framework-free. |
| `protocol.types.ts` | `AudioFormat`, `AudioFrame`, `ClientMessage`, `ServerMessage` (§5.2). Framework-free, shareable with the backend repo. |
| `app-error.ts` | `class AppError extends Error { code; recoverable; cause? }` plus the code union. The error interceptor and `VoiceError` mapping use it. |
### 3.2 `core/audio/`
| File | Purpose |
|---|---|
| `audio-context.provider.ts` | Exports `AUDIO_CONTEXT_HOLDER` and `provideAudio()`. The holder **does not create an `AudioContext` at startup** (autoplay policy). It exposes `ensureRunning()`, called from the first user gesture (the orb click), which creates `new AudioContext({ latencyHint: 'interactive', sampleRate })`, loads both worklet modules, and resumes the context. Exposes a `state` signal (`'none' \| 'suspended' \| 'running' \| 'closed'`). |
| `audio.tokens.ts` | `AUDIO_CONFIG`: `captureSampleRate` (16000), `playbackSampleRate` (24000), `frameMs` (20), `prebufferMs` (80), `analyserFftSize` (256), `bandCount` (64). |
| `audio.types.ts` | `CaptureCommand`, `PlaybackCommand`, `PlaybackEvent` unions (§5.3). |
| `audio-engine.service.ts` | The facade the voice feature talks to: `start()`, `stop()`, `unmuteCapture()`, `muteCapture()`, `startPlayback()`, `flushPlayback()`, `enqueueAgentFrame()`, plus event streams (`captureFrame$`, `playback$`). Builds the node graph, owns both analysers, and writes `AudioLevelBus` every frame. Creates its listeners **outside the zone**. |
| `mic-capture.service.ts` | `getUserMedia` with `echoCancellation`, `noiseSuppression`, `autoGainControl`, `channelCount: 1`; `enumerateDevices()`; exposes `permission` (`'prompt' \| 'granted' \| 'denied'`) and `devices` signals; handles device-change events and `NotAllowedError`/`NotFoundError` mapping to `VoiceError`. |
| `pcm-capture.node.ts` | Creates the `AudioWorkletNode('pcm-capture-processor')`, sends `{ type: 'active' }`, and surfaces transferred `ArrayBuffer` frames as a typed callback. Returns used buffers to a pool. |
| `pcm-playback.node.ts` | Creates `AudioWorkletNode('pcm-playback-processor')`; methods `config()`, `push(frame)`, `flush()`, `endOfTurn()`; surfaces `started`, `drained`, `underrun`, `level` events. |
| `audio-level-bus.ts` | The per-frame shared buffer (`inputRms`, `outputRms`, `inputBands`, `outputBands`). A plain class, **not signals**: this is the documented exception that keeps the render loop out of change detection. |
| `pcm-utils.ts` | `floatToInt16`, `int16ToFloat`, `resampleLinear`, `rms`, and `bytesToMs`. Pure functions, unit-tested with golden arrays. |
#### 3.2.1 `core/audio/visualizer/`
| File | Purpose |
|---|---|
| `visualizer.interface.ts` | `interface Visualizer { init(canvas): Promise<void>; applyState(state): void; resize(w, h, dpr): void; render(t): void; dispose(): void; }`. Lets WebGL and Canvas 2D be interchangeable. |
| `visualizer.service.ts` | `VisualizerEngine` (component-scoped provider). `start(canvas)` calls `NgZone.runOutsideAngular`, picks the implementation (WebGL → fallback), runs the `requestAnimationFrame` loop, pauses on `visibilitychange` and `IntersectionObserver`, monitors frame time to step quality down, and cleans up through `DestroyRef`. `applyState()` only swaps a target preset object; the loop eases toward it. |
| `audio-visualizer.directive.ts` | Selector `canvas[appAudioVisualizer]`. Inputs: `state` (signal `input<VoiceState>()`). Creates the engine in `afterNextRender`, wires a `ResizeObserver` (outside the zone), and runs an `effect()` that calls `engine.applyState(state())`. The directive is the only Angular-facing surface of the visualizer. |
| `three-orb.visualizer.ts` | `await import('three')`; builds `WebGLRenderer` (DPR capped at 2), `PerspectiveCamera`, an `IcosahedronGeometry` orb with `ShaderMaterial`, uniforms `uTime`, `uLevel`, `uTurbulence`, `uColor`, `uFresnel`. Reads `AudioLevelBus` each frame; selects input bands in `listening`, output bands in `speaking`, a synthetic pulse in `processing`. Handles `webglcontextlost`/`restored`. Disposes geometry, material, and renderer. |
| `canvas2d.visualizer.ts` | Radial bar/waveform fallback with the same preset system. Used when WebGL is unavailable, context restore fails, or `prefers-reduced-motion` requests a calmer mode. |
| `state-presets.ts` | `STATE_PRESETS: Record<VoiceState, { color, turbulence, levelGain, easing, source }>`. Colors reference the same tokens as `theme.css`. |
| `shader-source.d.ts` | `declare module '*.glsl' { const source: string; export default source; }` so shaders can be imported as strings (the `loader` option in `angular.json`). |
| `shaders/orb.vert.glsl` | Vertex displacement: simplex noise scaled by `uLevel` and `uTurbulence`. |
| `shaders/orb.frag.glsl` | Fresnel rim glow and state color blend (the glow is computed here, not with post-processing). |
> **Shader placement note.** Shaders live beside the visualizer and are imported as text at build time instead of being fetched from `assets/`. This removes a network request and the "orb appears before its shader loads" flash. `assets/textures/` exists for later texture-based effects and is intentionally empty in v1.
### 3.3 `core/websocket/`
| File | Purpose |
|---|---|
| `realtime-transport.ts` | `abstract class RealtimeTransport { connect(); disconnect(); sendAudio(buf); sendControl(msg); readonly audio$; readonly control$; readonly status: Signal<ConnectionStatus>; }`. `VoiceSessionService` depends only on this class. |
| `websocket.service.ts` | `WebSocketService extends RealtimeTransport`. Sets `binaryType = 'arraybuffer'`, sends `session.start` (with the ticket) on open, parses text frames to `ServerMessage`, routes binary frames to `AudioStreamHandler`, and runs all socket callbacks **outside the zone**. Re-enters Angular only by writing the `status` signal or emitting control events. |
| `connection.machine.ts` | The **connection** state machine as a pure reducer: `disconnected → connecting → connected → reconnecting → failed`, with events `OPEN`, `CLOSE`, `ERROR`, `RETRY`, `GIVE_UP`, `USER_DISCONNECT`. Separate from the voice machine so transport failures never leak into voice-state logic. |
| `reconnect-policy.ts` | Backoff: 500 ms → 8 s, ×2, ±25% jitter, max attempts configurable; resets after a stable connection. |
| `heartbeat.ts` | Sends `ping` every 15 s and declares the link dead after two missed `pong`s, triggering a `CLOSE` event. |
| `frame-codec.ts` | `encodeAudioFrame()` / `decodeAudioFrame()` for the 16-byte little-endian header (`ARCHITECTURE.md` §5.2). Validates `version` and payload length; returns `null` for malformed frames (counted, never thrown). |
| `audio-stream.handler.ts` | The binary audio stream handler: tracks `seq` for loss/reorder detection, drops frames whose `turnIdHash` does not match the current turn (barge-in safety), transfers payloads to `PcmPlaybackNode`, and keeps counters for telemetry (dropped, late, bytes). |
### 3.4 `core/services/`
| File | Purpose |
|---|---|
| `voice-state.store.ts` | `voiceState`, `activeSession`, `transcript` as private writable signals with read-only public views and `computed` helpers (`isMicOpen`, `canInterrupt`). Only `VoiceSessionService` calls its underscore-prefixed mutators. |
| `app-settings.store.ts` | Persisted preferences signal: preferred input device id, output volume, transcript open/closed, reduced-motion override, locale. Loads from `StorageService` on init; an `effect()` writes back (debounced). |
| `storage.service.ts` | Typed `get/set/remove` over `localStorage` with a namespaced, versioned key (`vfaq:v1:<key>`), `try/catch` on every call, JSON validation with a fallback, and `storage`-event sync between tabs. Never stores audio, transcripts, or tokens. |
| `auth.service.ts` | Holds the HTTP bearer token (in memory) and `requestRealtimeTicket()` for the short-lived WebSocket ticket. Exposes `isAuthenticated` signal. |
| `browser-capabilities.service.ts` | One-time checks: `AudioWorklet`, `getUserMedia`, `WebSocket`, WebGL2 (optional), secure context. Exposes a `capabilities` signal consumed by `browserSupportGuard` and the orb fallback logic. |
| `notification.service.ts` | `toasts` signal (`{ id, kind, message, timeoutMs }[]`) with `show()` and `dismiss()`. Rendered by `ToastHostComponent`. |
| `telemetry.service.ts` | `mark('ttfa')`, `count('underrun')`, `transition(from, to, ms)`. Batches and sends via `navigator.sendBeacon`. No audio, transcripts, or file contents. |
| `logger.service.ts` | `debug/info/warn/error`; `debug` and `info` are no-ops in production. |
### 3.5 `core/guards/`
| File | Purpose |
|---|---|
| `auth.guard.ts` | Functional `CanActivateFn`: allows if `AuthService.isAuthenticated()`, otherwise tries a silent refresh, then redirects to the configured login URL. |
| `browser-support.guard.ts` | Functional guard: if `AudioWorklet`, `getUserMedia`, or `WebSocket` is missing (or the page is not a secure context), returns `router.parseUrl('/unsupported')`. |
| `unsaved-changes.guard.ts` | `CanDeactivateFn` for the knowledge-base route: if `FaqStore` has pending edits or an upload in progress, asks for confirmation through a CDK Dialog before leaving. |
### 3.6 `core/interceptors/`
| File | Purpose |
|---|---|
| `auth.interceptor.ts` | Adds `Authorization: Bearer …` to requests whose URL starts with `apiBaseUrl`; never to third-party URLs. |
| `retry.interceptor.ts` | Retries **idempotent** requests (GET/HEAD) on network failure and 502/503/504, max 2 times, with jittered backoff. Never retries uploads or mutations. |
| `error.interceptor.ts` | Maps `HttpErrorResponse` to `AppError`, raises a toast for user-visible failures (not for 401 handled by the auth flow), and rethrows. |
---
## 4. `src/app/features/` in detail
### 4.1 `features/voice-agent/`
| File / folder | Purpose |
|---|---|
| `voice-agent.routes.ts` | `VOICE_AGENT_ROUTES` (one route to `VoiceAgentPage`); provides route-scoped services (`VoiceSessionService`, `BargeInDetectorService`). |
| `voice-agent.page.ts` | Smart container. Injects `VoiceStateStore`, `VoiceSessionService`, `FaqStore`, and `FaqDrawerService`. Lays out the orb, status badge, control bar, transcript overlay, suggestions, and the button that opens the knowledge-base drawer. Contains no audio logic. |
| `components/voice-orb/` | Hosts `<canvas appAudioVisualizer [state]="state()">` inside a glass-ringed container with the state glow (`StateGlowDirective`). Inputs: `state`. Outputs: `orbClick` (the first click is the user gesture that starts audio). OnPush; no per-frame bindings. |
| `components/mic-control-bar/` | Mic toggle / push-to-talk, stop, mute-output, input device selector (popover). Inputs: `state`, `micPermission`, `devices`. Outputs: `toggleMic`, `stop`, `deviceChange`. Keyboard: Space toggles, Esc stops. |
| `components/transcript-overlay/` | Collapsible glass panel using CDK virtual scroll. Partial entries update in place; the latest entry has `aria-live="polite"`. Shows citation chips that open the source in the knowledge-base drawer. |
| `components/status-badge/` | Pill showing state icon, localized label, and glow color. Announces changes through CDK `LiveAnnouncer`. Color is never the only signal (icon + label + motion). |
| `components/faq-suggestions/` | Suggested question chips from `suggestions` messages; clicking one sends it as text input. |
| `components/mic-permission-prompt/` | Explains how to enable the microphone per browser when permission is `denied`, with a retry button. |
| `services/voice-session.service.ts` | The **only** writer of `voiceState`. `dispatch(event)` looks up `TRANSITIONS[current][event.type]`, evaluates guards, runs effects, then sets the state signal. Subscribes to `RealtimeTransport.control$` and `AudioEngine` events and converts them to `VoiceEvent`s. |
| `services/voice-transitions.ts` | Pure `TRANSITIONS` table and `guards` (minimum utterance length, barge-in debounce). No Angular imports. Table-driven tests live beside it. |
| `services/voice-effects.ts` | Maps each `(from, to, event)` to side effects: `unmuteCapture`, `muteCapture`, `flushPlayback` (local first), `sendControl({type:'interrupt', playedMs})`, and so on. Keeps `voice-session.service.ts` small. |
| `services/barge-in-detector.service.ts` | Client-side energy gate that runs while `speaking`: if input RMS stays above a threshold for ≥120 ms (echo-cancelled input), dispatches `BARGE_IN`. Reads `AudioLevelBus` on a 20 ms timer outside the zone. |
### 4.2 `features/faq-manager/`
| File / folder | Purpose |
|---|---|
| `faq-manager.routes.ts` | `FAQ_MANAGER_ROUTES`: the full-page knowledge-base route (`FaqManagerPage`). The drawer is opened from any page via `FaqDrawerService`. |
| `faq-manager.page.ts` | Full-page layout: `DocumentList` on the left, `QaGrid` on the right, dropzone on top. |
| `models/faq.types.ts` | `FaqDocument`, `FaqDocumentStatus` (`uploading \| indexing \| active \| error`), `QaPair`, `QaFilter`, `CsvPreview`, `CsvRowError`, `IngestionEvent` (`ARCHITECTURE.md` §5.4). |
| `components/faq-drawer/` | The slide-over (CDK Overlay) containing dropzone, preview, and document list. Glass surface, focus trap, Esc to close, slides in from the inline-end edge (RTL-aware). Opened and closed through `FaqDrawerService`. |
| `components/file-dropzone/` | Uses `FileDropDirective`. Accepts `.csv .json .pdf .docx`, shows drag-over state, runs `FileValidatorService`, and emits `filesAccepted` / `filesRejected`. |
| `components/upload-preview-table/` | For CSV: shows the first N parsed rows, auto-detected question/answer columns with manual remapping, and per-row validation errors. "Confirm" starts the upload. |
| `components/document-list/` | One row per document: name, type icon, size, `Badge` with status (`Uploading`, `Indexing`, `Active`, `Error`), progress bar, item count, enable toggle, retry/delete. |
| `components/qa-grid/` | AG Grid wrapper: inputs `rows`, `filter`; outputs `editRow`, `toggleOverride`, `bulkDelete`. Lazy-registers grid modules, applies the dark glass theme, supports inline edit, quick filter, and row selection. |
| `components/qa-editor-modal/` | CDK Dialog with a reactive form (question, answer, tags, enabled, "manual override"). Validates length, warns when overriding ingested content, and returns the saved `QaPair`. |
| `grid/register-grid-modules.ts` | One-time `ModuleRegistry.registerModules(...)` (see `DEPENDENCIES.md` §6.3). |
| `grid/qa-grid.columns.ts` | `ColDef[]` factory: question, answer (large text editor), tags, source, overridden, enabled, updated, actions. |
| `grid/qa-grid.theme.ts` | AG Grid theme built with the JS theme API, colors taken from the Tailwind tokens. |
| `grid/cell-renderers/` | `status-cell.renderer.ts`, `tags-cell.renderer.ts`, `actions-cell.renderer.ts`: small OnPush Angular components used as cell renderers. |
| `services/faq-store.ts` | Signals: `documents`, `pairs` (Map), `filter`; computeds: `activeDocuments`, `visiblePairs`, `hasProcessing`, `totalActiveItems`. Single writer for FAQ state; supports optimistic edits with rollback. |
| `services/faq-api.service.ts` | `HttpClient` calls: list documents/pairs, create/update/delete pair, delete document, toggle enabled. |
| `services/faq-ingestion.service.ts` | Orchestrates `validate → (CSV preview) → upload with progress (reportProgress) → subscribe to status events`. Updates `FaqStore` as `uploading → indexing → active \| error`. |
| `services/ingestion-events.service.ts` | Server-sent events (or WebSocket control messages) for `document.progress` / `document.active` / `document.error`, with reconnect. Callbacks write to `FaqStore` signals. |
| `services/file-validator.service.ts` | Extension, MIME, size, and **magic-byte** checks against `file-signatures.ts`. Client-side UX only; the server revalidates. |
| `services/csv-parser.service.ts` | Lazy `import('papaparse')`. `preview(file, n)` uses `preview: n`; `scan(file)` uses chunked streaming to count rows and collect row errors. Avoids `worker: true` (see `DEPENDENCIES.md` §3.4). |
| `services/faq-drawer.service.ts` | `open()`, `close()`, `isOpen` signal; creates/disposes the CDK overlay and focus trap. |
| `utils/file-signatures.ts` | Magic bytes: PDF `%PDF`, DOCX/ZIP `PK\x03\x04` (plus `word/` check by the server), JSON and CSV validated as text. |
| `utils/csv-column-detect.ts` | Heuristics mapping headers (`question`, `q`, `faq`, `answer`, `a`, `response`, …) to the question/answer columns. |
---
## 5. `src/app/shared/` in detail
| Area | Contents |
|---|---|
| `ui/button`, `ui/icon-button` | Variants (`primary`, `ghost`, `danger`), sizes, loading state, `focus-ring`. Signal inputs. |
| `ui/badge` | Generic pill; `variant` input maps to state/status colors (used by `StatusBadge` and `DocumentList`). |
| `ui/icon` | `<app-icon name="mic" />` plus `icons.ts`, the **single registry** of Lucide icons used by the app. This isolates the Lucide package API so only this folder changes if the package changes. |
| `ui/glass-panel` | Container component applying the `glass` utility with optional glow state. |
| `ui/drawer-shell` | Visual frame for slide-overs (header, close button, scroll body, footer); used by `FaqDrawer`. |
| `ui/dialog-shell` | Visual frame for CDK Dialog content (title, body, actions). |
| `ui/toast-host` | Renders `NotificationService.toasts()` with `aria-live`; timers cleaned through `DestroyRef`. |
| `ui/spinner`, `ui/progress-bar`, `ui/skeleton` | Loading primitives (CSS-only animations). |
| `ui/empty-state` | Icon, title, description, optional action; also used for the unsupported-browser page. |
| `directives/glass-panel.directive.ts` | Adds the `glass`/`glass-strong` classes and optional rounded/border variants to any element. |
| `directives/state-glow.directive.ts` | Input `voiceState`; applies the matching `glow-*` utility class with a CSS transition. |
| `directives/file-drop.directive.ts` | Handles `dragenter/dragover/dragleave/drop` with a depth counter (avoids flicker), exposes `dragging` signal, emits `filesDropped`. Generic; used by the dropzone. |
| `directives/autofocus.directive.ts` | Focuses an element after render (modals, filters). |
| `directives/resize-observer.directive.ts` | Emits `ResizeObserverEntry` sizes outside the zone; re-enters only through an output when the value changes meaningfully. |
| `pipes/file-size.pipe.ts` | `1536 → "1.5 KB"`. |
| `pipes/relative-time.pipe.ts` | `Intl.RelativeTimeFormat`-based ("2 minutes ago"); pure pipe, refreshed by a parent signal rather than a timer. |
| `pipes/duration.pipe.ts` | `ms → "1:05"`. |
| `pipes/truncate.pipe.ts` | Word-safe truncation with ellipsis. |
| `utils/assert.ts`, `id.ts`, `math.ts`, `raf-throttle.ts` | `assertNever`/`invariant`; `crypto.randomUUID()` wrapper; `clamp`/`lerp`/`easeTo`; throttle a callback to one call per animation frame. |
---
## 6. `src/assets/` in detail
### 6.1 `assets/worklets/`
| File | Purpose |
|---|---|
| `pcm-capture-processor.js` | `class PcmCaptureProcessor extends AudioWorkletProcessor`, registered as `'pcm-capture-processor'`. Accumulates 128-sample render quanta into a preallocated buffer, converts every `frameMs` to Int16, and posts the buffer with a **transfer list**. Honors `{ type: 'active' }` commands. Starts with `// @ts-check` (types from `@types/audioworklet`). |
| `pcm-playback-processor.js` | Registered as `'pcm-playback-processor'`. Holds a ring buffer (~2 s), prebuffers `prebufferMs` before starting, converts Int16 → Float32, outputs silence on underrun (posting `{ type: 'underrun' }`), handles `{ type: 'flush' }` in O(1), and posts `{ type: 'drained' }` after `end-of-turn`. |
The two processors are separate files (rather than one `pcm-processor.js`) so the capture path can load without the playback code and each file can be tested in isolation. Loading, with cache-busting:
```ts
// core/audio/audio-context.provider.ts (excerpt)
const v = inject(APP_CONFIG).workletVersion;
await ctx.audioWorklet.addModule(new URL(`assets/worklets/pcm-capture-processor.js?v=${v}`, document.baseURI).href);
await ctx.audioWorklet.addModule(new URL(`assets/worklets/pcm-playback-processor.js?v=${v}`, document.baseURI).href);
```
### 6.2 `assets/textures/`
Empty in v1 (`.gitkeep`). The orb noise is procedural in `orb.vert.glsl`. Add environment maps or noise textures here later; they are copied verbatim by the `assets` glob in `angular.json` and fetched with `TextureLoader` inside `ThreeOrbVisualizer`.
---
## 7. Where things run (quick reference)
| Code | Thread / zone | Writes signals? |
|---|---|---|
| `assets/worklets/*.js` | Audio render thread | No (messages only) |
| `audio-engine.service.ts`, `websocket.service.ts`, `audio-stream.handler.ts` | Main thread, **outside** the Angular zone | Only at low frequency (status, events) |
| `visualizer.service.ts`, `three-orb.visualizer.ts` | Main thread, **outside** the zone, `requestAnimationFrame` | **Never** |
| `voice-session.service.ts`, stores, components | Angular domain | Yes (events, ~1–5 Hz) |
This split is what keeps change detection at **zero ticks per second** while the orb animates (`ARCHITECTURE.md` §3.6–3.7).