# ARCHITECTURE.md — Voice-to-Voice FAQ Web Application
> **Status:** Draft v1 · **Audience:** frontend engineers, tech leads, backend integrators
> **Stack:** Angular 18/19+ (Standalone, Signals, OnPush, zoneless-ready) · Tailwind CSS · Angular CDK · Lucide Angular · Web Audio API / AudioWorklet · Three.js · WebSocket (WebRTC optional)
---
## Table of Contents
1. [System Overview & High-Level Architecture](#1-system-overview--high-level-architecture)
2. [State Machine Specification](#2-state-machine-specification)
3. [Audio Pipeline & Performance Strategy](#3-audio-pipeline--performance-strategy)
4. [Folder Structure & Component Breakdown](#4-folder-structure--component-breakdown)
5. [Data Contracts & Types](#5-data-contracts--types)
6. [Cross-Cutting Concerns](#6-cross-cutting-concerns)
7. [Architecture Decision Records (summary)](#7-architecture-decision-records-summary)
8. [Open Questions](#8-open-questions)
9. [Next Documents](#9-next-documents)
---
## 1. System Overview & High-Level Architecture
### 1.1 Goals and non-goals
| Goal | Target |
|---|---|
| Natural, full-duplex conversation with an AI FAQ agent | Barge-in supported at any time |
| Mouth-to-ear perceived latency (user stops talking → first audio back) | **< 800 ms p50**, < 1.5 s p95 (network + backend dependent) |
| Visualizer smoothness | Steady 60 FPS, **zero Angular change-detection cycles** from the render loop |
| Main-thread safety | No audio sample processing on the main thread |
| Knowledge-base management | Upload → validate → index → inspect/edit Q&A, with live status |
| Future-proofing | Works identically with Zone.js today and zoneless tomorrow |
**Non-goals (v1):** multi-party calls, client-side speech recognition/TTS models, offline mode, mobile-native wrappers.
### 1.2 Architectural principles
1. **Three execution domains, strict boundaries.** (a) *Audio render thread* (AudioWorklet), (b) *main thread outside Angular* (canvas/WebGL loop, socket I/O hot path), (c) *Angular reactive domain* (UI state, signals, templates). Data crosses domains only through explicit, narrow channels.
2. **Signals for state that humans read; plain mutable buffers for state that machines read.** A value that changes 60 times per second and is consumed only by a shader is *not* a signal.
3. **Transport is dumb, the state machine is smart.** The WebSocket service emits typed events; only `VoiceSessionService` decides what they mean.
4. **One writer per state.** Each signal has exactly one service that writes it and exposes a read-only view (`asReadonly()`).
5. **Everything disposable.** Every `AudioContext`, `MediaStream`, `WebSocket`, `WebGLRenderer`, and `requestAnimationFrame` handle is released through `DestroyRef`.
### 1.3 High-level data flow
```mermaid
flowchart LR
subgraph Device["User Device"]
MIC["Microphone"]
SPK["Speakers"]
end
subgraph Browser["Browser"]
subgraph AudioThread["Audio Render Thread (AudioWorklet)"]
CAP["capture-processor
Float32 to Int16 PCM, 20 ms frames"]
PLAY["playback-processor
ring buffer / jitter buffer"]
end
subgraph MainOutside["Main Thread - outside Angular zone / CD"]
ACTX["AudioContext graph
MediaStreamSource, AnalyserNode in/out"]
WS["WebSocketService
binary audio + JSON control"]
VIS["VisualizerEngine
Three.js orb, rAF loop"]
BUS["AudioLevelBus
mutable Float32 snapshot"]
end
subgraph NG["Angular Reactive Domain (Signals, OnPush)"]
SESS["VoiceSessionService
state machine orchestrator"]
VSTATE["VoiceStateStore
voiceState, activeSession, transcript"]
FAQ["FaqStore
faqDocuments, qaPairs, filters"]
UI["Components
VoiceAgent, FaqDrawer, FaqGrid"]
end
end
subgraph Backend["Backend"]
GW["Realtime Gateway
auth, session, VAD"]
RAG["RAG Retriever
vector index"]
LLM["LLM"]
TTS["TTS / STT"]
ING["Ingestion API
parse, chunk, embed"]
end
MIC --> ACTX
ACTX -->|"MediaStreamSource"| CAP
CAP -->|"postMessage (transfer ArrayBuffer)"| WS
WS <-->|"wss: PCM frames + control JSON"| GW
GW --> TTS
TTS --> LLM
LLM <--> RAG
GW -->|"PCM reply frames"| WS
WS -->|"postMessage (transfer)"| PLAY
PLAY --> ACTX
ACTX --> SPK
ACTX -->|"getByteFrequencyData into preallocated array"| BUS
BUS -->|"read each frame"| VIS
WS -->|"typed control events"| SESS
SESS -->|"signal.set()"| VSTATE
VSTATE -->|"voiceState read by effect"| VIS
VSTATE --> UI
FAQ --> UI
UI -->|"upload / edit"| ING
ING -->|"status events (SSE or WS)"| FAQ
ING --> RAG
```
### 1.4 Component responsibilities at a glance
| Component | Domain | Responsibility | Writes | Reads |
|---|---|---|---|---|
| `AudioEngineService` | Main (outside zone) | Owns `AudioContext`, mic stream, worklet nodes, analysers | `AudioLevelBus` | — |
| `capture-processor` | Audio thread | Downmix, resample (if needed), quantize to Int16, frame to 20 ms | — | mic samples |
| `playback-processor` | Audio thread | Jitter buffering, underrun handling, instant flush on barge-in | — | PCM frames |
| `WebSocketService` | Main (outside zone) | Connection lifecycle, reconnect, framing, heartbeat | event streams | PCM from worklet |
| `VoiceSessionService` | Angular | The **only** writer of `voiceState`; applies transition table | `VoiceStateStore` | WS events, engine events |
| `VisualizerEngine` | Main (outside zone) | Three.js scene + rAF loop; no Angular imports in the hot path | canvas | `AudioLevelBus`, state snapshot |
| `FaqStore` | Angular | Document list, Q&A pairs, filters, optimistic edits | signals | ingestion events |
| `FaqIngestionService` | Angular | Validation, PapaParse, upload with progress, status subscription | `FaqStore` | HTTP/SSE |
---
## 2. State Machine Specification
### 2.1 States
| State | Meaning | Mic capture | Playback | Visualizer behaviour |
|---|---|---|---|---|
| `idle` | Session connected (or ready); nobody speaking | Muted at the worklet (stream stays warm) | Empty | Slow ambient breathing, cool tint |
| `listening` | User is speaking / mic is open and streaming | **Streaming** | Empty | Orb deforms with **input** level |
| `processing` | User finished; backend is thinking (STT → RAG → LLM → TTS first byte) | Paused (optionally keep VAD running) | Empty | Rotating / pulsing "thinking" pattern, level-independent |
| `speaking` | Agent audio is playing | Streaming to server **for barge-in detection only** (AEC on) | **Playing** | Orb deforms with **output** level |
| `interrupted` | User barged in during `speaking`; playback is being flushed | Streaming | **Flushing** | Brief collapse/flash animation (~150–250 ms) |
> **Design note — `interrupted` is transient.** It is a real state (so the UI, analytics, and tests can observe it), but it always resolves to `listening` automatically once the flush is acknowledged locally. It never waits on the network.
### 2.2 Events
| Event | Source | Description |
|---|---|---|
| `SESSION_READY` | WS | Handshake complete, server accepted session |
| `START_LISTENING` | UI / VAD | User pressed the orb or push-to-talk, or client VAD detected speech |
| `END_OF_UTTERANCE` | Server VAD / UI | End of user turn (silence threshold or manual release) |
| `AGENT_AUDIO_START` | WS | First TTS frame received |
| `AGENT_AUDIO_END` | WS + engine | Server signalled `turn.end` **and** playback buffer drained |
| `BARGE_IN` | Client VAD / server | User speech detected while `speaking` |
| `FLUSH_DONE` | Engine | Playback ring buffer cleared (synchronous in practice) |
| `ERROR` | any | Recoverable or fatal fault |
| `STOP` | UI | User ended the session |
### 2.3 Transition diagram
```mermaid
stateDiagram-v2
[*] --> idle
idle --> listening: START_LISTENING
listening --> processing: END_OF_UTTERANCE
listening --> idle: STOP / mic muted
processing --> speaking: AGENT_AUDIO_START
processing --> listening: START_LISTENING (user talks over thinking)
processing --> idle: ERROR (recovered) / empty answer
speaking --> idle: AGENT_AUDIO_END
speaking --> interrupted: BARGE_IN
interrupted --> listening: FLUSH_DONE
speaking --> idle: STOP
idle --> idle: ERROR (recovered)
```
### 2.4 Transition table (authoritative)
| From | Event | Guard | To | Side effects (executed by `VoiceSessionService`) |
|---|---|---|---|---|
| `idle` | `START_LISTENING` | session connected, mic permission granted | `listening` | `engine.unmuteCapture()`, send `{type:'turn.start'}` |
| `listening` | `END_OF_UTTERANCE` | utterance ≥ min length (default 300 ms) | `processing` | `engine.muteCapture()`, send `{type:'turn.end'}` |
| `listening` | `END_OF_UTTERANCE` | utterance < min length | `idle` | discard, send `{type:'turn.cancel'}` |
| `processing` | `AGENT_AUDIO_START` | — | `speaking` | `engine.startPlayback()`, re-open capture for barge-in |
| `processing` | `START_LISTENING` | allowed by config `allowTalkOverThinking` | `listening` | send `{type:'turn.cancel'}`, then `turn.start` |
| `speaking` | `AGENT_AUDIO_END` | playback buffer empty | `idle` | `engine.muteCapture()` |
| `speaking` | `BARGE_IN` | debounce ≥ 120 ms of sustained speech energy | `interrupted` | `engine.flushPlayback()` (**local first**), send `{type:'interrupt', playedMs}` |
| `interrupted` | `FLUSH_DONE` | — | `listening` | send `{type:'turn.start'}`; ignore any late agent frames with a stale `turnId` |
| any | `ERROR` | fatal | `idle` | tear down socket/engine, surface toast, offer retry |
| any | `STOP` | — | `idle` | graceful teardown |
**Invariants**
- Any event not listed for the current state is **ignored and logged** (never throws).
- Agent frames carry a `turnId`; frames whose `turnId` ≠ current turn are dropped (this makes barge-in race-free).
- Barge-in flushes audio **locally before** informing the server — perceived responsiveness must not depend on RTT.
### 2.5 Signal state design
State is split by *rate of change* and *consumer*:
| Signal / store | Type | Rate | Consumer | Notes |
|---|---|---|---|---|
| `voiceState` | `Signal` | events (~1–5 Hz) | templates, visualizer (via `effect`) | Written only by `VoiceSessionService` |
| `activeSession` | `Signal` | rare | header, guards | id, startedAt, connection status |
| `transcript` | `Signal` | per utterance / partial | transcript drawer | Partials update the last entry immutably |
| `faqDocuments` | `Signal` | per upload event | drawer, grid toolbar | Keyed by `id`; status updated via `update()` |
| `qaPairs` | `Signal` | per edit | grid | Large lists: keep as `Map` internally, expose array via `computed` |
| `activeDocumentIds` | `Signal>` | rare | session config | Which sources feed the current session |
| `audioLevel` | **NOT a per-frame signal** | 60 Hz | visualizer only | See below |
#### The `audioLevel` rule
Per-frame levels are written into a mutable `AudioLevelBus` (a preallocated `Float32Array` + a couple of numbers). The canvas loop reads it directly. For any Angular UI that wants a level (e.g., a mic meter), expose a **throttled** signal:
```ts
// core/audio/audio-level-bus.ts
export class AudioLevelBus {
/** written by AudioEngine each frame, read by VisualizerEngine each frame */
readonly inputRms = new Float32Array(1);
readonly outputRms = new Float32Array(1);
readonly inputBands = new Uint8Array(64); // from AnalyserNode (preallocated)
readonly outputBands = new Uint8Array(64);
}
// core/audio/audio-engine.service.ts (excerpt)
private readonly _meter = signal(0);
/** 10 Hz, UI-only (e.g., mic meter). Never bind this to the canvas. */
readonly meter = this._meter.asReadonly();
```
Writing a signal at 60 Hz in a zoneless app **schedules change detection at 60 Hz**; in a zone app it is cheaper only if the write happens outside the zone, but any template reading it would still re-render. Hence: bus for machines, throttled signal for humans.
#### Reference implementation skeleton
```ts
// core/state/voice-state.store.ts
@Injectable({ providedIn: 'root' })
export class VoiceStateStore {
private readonly _voiceState = signal('idle');
private readonly _activeSession = signal(null);
private readonly _transcript = signal([]);
readonly voiceState = this._voiceState.asReadonly();
readonly activeSession = this._activeSession.asReadonly();
readonly transcript = this._transcript.asReadonly();
readonly isMicOpen = computed(() => ['listening', 'speaking', 'interrupted'].includes(this._voiceState()));
readonly canInterrupt = computed(() => this._voiceState() === 'speaking');
readonly statusLabelKey = computed(() => `voice.state.${this._voiceState()}`);
/** Only VoiceSessionService may call these (enforced by convention + lint rule). */
_setState(next: VoiceState) { this._voiceState.set(next); }
_setSession(s: VoiceSession | null) { this._activeSession.set(s); }
_appendTranscript(e: TranscriptEntry) { this._transcript.update(list => [...list, e]); }
}
```
```ts
// features/voice-agent/services/voice-session.service.ts (transition core)
const TRANSITIONS: Record>> = {
idle: { START_LISTENING: 'listening' },
listening: { END_OF_UTTERANCE: 'processing', STOP: 'idle' },
processing: { AGENT_AUDIO_START: 'speaking', START_LISTENING: 'listening', ERROR: 'idle' },
speaking: { AGENT_AUDIO_END: 'idle', BARGE_IN: 'interrupted', STOP: 'idle', ERROR: 'idle' },
interrupted: { FLUSH_DONE: 'listening', ERROR: 'idle' },
};
dispatch(event: VoiceEvent) {
const current = this.store.voiceState();
const next = TRANSITIONS[current][event.type];
if (!next) { this.log.debug('ignored', current, event.type); return; }
if (!this.guards.allow(current, event, next)) return;
this.effects.run(current, next, event); // engine + socket side effects
this.store._setState(next);
}
```
Keeping the table as data (rather than `switch` statements) makes it unit-testable and lets the docs/diagram be generated from it.
---
## 3. Audio Pipeline & Performance Strategy
### 3.1 Thread separation
| Thread | Runs | Must never |
|---|---|---|
| **Audio render thread** (`AudioWorkletGlobalScope`) | `capture-processor`, `playback-processor` | allocate in `process()`, log, touch DOM, wait on anything |
| **Main thread, outside Angular** | `AudioContext` graph management, `WebSocketService` I/O, `VisualizerEngine` | trigger change detection, write per-frame signals |
| **Main thread, Angular** | components, signals, templates | process audio samples, run the render loop |
| **(Optional) Dedicated Worker** | socket I/O + encode/decode if profiling shows main-thread jank | — |
### 3.2 Capture path (mic → server)
1. `getUserMedia({ audio: { echoCancellation: true, noiseSuppression: true, autoGainControl: true, channelCount: 1 } })`. Echo cancellation is **mandatory**; barge-in during `speaking` depends on it.
2. Create `AudioContext({ latencyHint: 'interactive', sampleRate: 16000 })`. Browsers may ignore the requested rate — always read `ctx.sampleRate` and let the worklet resample to the wire rate if they differ.
3. `MediaStreamAudioSourceNode` → `AudioWorkletNode('capture-processor')`. The same source also feeds an `AnalyserNode` (`fftSize = 256`, `smoothingTimeConstant = 0.8`) for visuals.
4. In `process()`, copy 128-sample render quanta into a preallocated accumulator. Every **20 ms** (320 samples @ 16 kHz) convert Float32 → Int16 little-endian and `port.postMessage(buffer, [buffer])` (**transfer, don't copy**). Use a small pool of ArrayBuffers recycled via a return message to avoid GC churn.
5. The main thread forwards each frame to `WebSocketService.sendAudio()` as a binary message (header + payload, see §5.2). No per-frame Angular involvement.
```js
// core/audio/worklets/capture-processor.worklet.js
class CaptureProcessor extends AudioWorkletProcessor {
constructor(options) {
super();
this.frameSamples = options.processorOptions.frameSamples; // e.g. 320
this.acc = new Float32Array(this.frameSamples);
this.fill = 0;
this.active = false;
this.port.onmessage = (e) => { if (e.data.type === 'active') this.active = e.data.value; };
}
process(inputs) {
const ch = inputs[0]?.[0];
if (!ch || !this.active) return true;
for (let i = 0; i < ch.length; i++) {
this.acc[this.fill++] = ch[i];
if (this.fill === this.frameSamples) {
const out = new Int16Array(this.frameSamples); // replace with pooled buffers in production
for (let j = 0; j < out.length; j++) {
const s = Math.max(-1, Math.min(1, this.acc[j]));
out[j] = s < 0 ? s * 0x8000 : s * 0x7fff;
}
this.port.postMessage(out.buffer, [out.buffer]);
this.fill = 0;
}
}
return true;
}
}
registerProcessor('capture-processor', CaptureProcessor);
```
### 3.3 Playback path (server → speakers)
1. `WebSocketService` receives binary frames (outside the zone), validates the header, drops stale `turnId`s, and transfers the PCM payload to `playback-processor` via `port.postMessage`.
2. `playback-processor` owns a **ring buffer** sized for ~2 s of audio and a **jitter buffer target** (default 60–100 ms prebuffer before starting). On underrun it outputs silence and posts `{type:'underrun'}` (counted in telemetry).
3. Decoded Int16 → Float32 happens inside the worklet; sample-rate conversion (e.g. server 24 kHz → context rate) is linear-interpolation in the worklet, or avoided by making the server emit the context rate.
4. **Flush** (`{type:'flush'}`) resets read/write pointers in O(1) — this is what makes barge-in feel instant.
5. Playback node → `AnalyserNode` (output) → `ctx.destination`. The analyser feeds `AudioLevelBus.outputBands`.
6. When the server sends `turn.end`, the worklet reports `{type:'drained'}` once the ring buffer empties; only then does the engine emit `AGENT_AUDIO_END`.
### 3.4 Transport choice
| | **WebSocket (default)** | **WebRTC (optional phase)** |
|---|---|---|
| Latency | Good (TCP head-of-line blocking under loss) | Best (UDP, Opus, built-in jitter/AEC) |
| Complexity | Low; full control over framing | Higher: signalling, STUN/TURN, SDP |
| Audio format | Raw PCM16 (simple, bigger) or Opus via WebCodecs | Opus, handled by the browser |
| Fit | MVP, corporate networks | Lossy/mobile networks, scale |
`WebSocketService` implements an abstract `RealtimeTransport` interface (`connect`, `sendAudio`, `sendControl`, `audio$`, `control$`, `status`). A `WebRtcTransport` can later replace it without touching `VoiceSessionService`.
### 3.5 Latency budget (target, p50)
| Segment | Budget |
|---|---|
| Capture frame + worklet handoff | 20–30 ms |
| Uplink (frame to gateway) | 30–80 ms |
| End-of-utterance detection | 200–400 ms (server VAD tuning) |
| STT final + RAG retrieval + LLM first token | 250–500 ms |
| TTS first audio chunk | 100–200 ms |
| Downlink + jitter buffer + output latency | 80–150 ms |
The frontend owns roughly 100–200 ms of this; its job is not to add to it (small frames, no copies, no main-thread stalls).
### 3.6 Bypassing Angular change detection for 60 FPS rendering
**Problem.** In a Zone.js app every `requestAnimationFrame`, `WebSocket.onmessage`, and `setTimeout` callback triggers `ApplicationRef.tick()`. A 60 FPS loop would run change detection 60×/s across the app.
**Strategy.**
```ts
// features/voice-agent/services/visualizer-engine.ts
@Injectable()
export class VisualizerEngine {
private readonly zone = inject(NgZone);
private readonly destroyRef = inject(DestroyRef);
private readonly bus = inject(AudioLevelBus);
private rafId = 0;
private renderer?: THREE.WebGLRenderer;
private target = { level: 0, hue: 0.58, turbulence: 0.1 }; // eased per frame
init(canvas: HTMLCanvasElement) {
this.zone.runOutsideAngular(() => {
this.renderer = new THREE.WebGLRenderer({ canvas, antialias: true, alpha: true, powerPreference: 'high-performance' });
this.renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
// build scene, orb mesh, ShaderMaterial with uniforms: uTime, uLevel, uTurbulence, uColor
this.loop();
});
this.destroyRef.onDestroy(() => this.dispose());
}
/** Called from an Angular effect() when voiceState changes (~1-5 Hz): cheap, no per-frame signal reads. */
applyState(state: VoiceState) { this.target = STATE_PRESETS[state]; }
private loop = () => {
this.rafId = requestAnimationFrame(this.loop); // already outside the zone
const src = this.currentSourceBands(); // input vs output bands by state
// read this.bus.* directly, ease uniforms toward targets, renderer.render(scene, camera)
};
private dispose() { cancelAnimationFrame(this.rafId); /* dispose geometries, materials, renderer, listeners */ }
}
```
Rules:
1. **Create the renderer and start the loop inside `NgZone.runOutsideAngular`.** (Under zoneless this is a harmless no-op, so the code is portable.)
2. **Wire sockets and worklet `port.onmessage` outside the zone too**, and re-enter Angular only by *writing a signal* when something human-visible changes (state transition, transcript partial). In zoneless mode, the signal write is what schedules rendering.
3. **State → visuals via an `effect`, not per-frame signal reads.** The effect runs on state changes and updates a plain target object; the rAF loop eases toward it.
4. **Reuse everything per frame**: no `new` objects, no array allocation, no string building in the loop. Use `getByteFrequencyData(prealloc)`.
5. **Cap DPR at 2**, resize via `ResizeObserver` (outside the zone), and render at half resolution on low-power devices (`navigator.hardwareConcurrency`, frame-time monitor that steps quality down).
6. **Pause when not visible**: `document.visibilitychange` and `IntersectionObserver` stop the loop and suspend analyser polling.
7. **`prefers-reduced-motion`**: switch to a reduced preset (no turbulence, slower easing).
8. **WebGL fallback**: on `webglcontextlost` or no WebGL, swap to a `Canvas2DVisualizer` implementing the same `Visualizer` interface (ring of bars/radial waveform).
9. **Template side**: the canvas host component is `OnPush`, has no bindings that change per frame, and exposes the canvas via `viewChild.required>('canvas')`.
### 3.7 Performance budgets & verification
| Metric | Budget | How verified |
|---|---|---|
| Frame time (visualizer) | ≤ 8 ms avg on mid-range laptop | Chrome Performance panel, in-app dev HUD |
| Change-detection ticks during idle visualization | **0 per second** | Angular DevTools profiler; `ApplicationRef.tick` counter in dev build |
| Main-thread long tasks (> 50 ms) during a conversation | 0 | PerformanceObserver `longtask` |
| Worklet underruns per 10 min | < 2 on a stable network | Telemetry counter |
| Heap growth over 30 min session | < 10 MB | Memory profiler (buffer pooling check) |
| Initial bundle (excluding lazy Three.js chunk) | < 250 KB gz | `source-map-explorer`, CI budget |
Three.js, PapaParse, and AG Grid are **lazy-loaded** (dynamic `import()`), so first paint is not penalized by the visualizer or grid code.
---
## 4. Folder Structure & Component Breakdown
```text
src/
├─ app/
│ ├─ app.config.ts # provideRouter, provideHttpClient, zoneless provider (see note)
│ ├─ app.routes.ts # lazy routes: voice, knowledge-base
│ ├─ app.component.ts
│ │
│ ├─ core/
│ │ ├─ audio/
│ │ │ ├─ audio-engine.service.ts # AudioContext, mic stream, node graph, mute/flush/play APIs
│ │ │ ├─ audio-level-bus.ts # mutable per-frame data shared with the visualizer
│ │ │ ├─ pcm-utils.ts # float<->int16, resample helpers (shared with tests)
│ │ │ ├─ audio.tokens.ts # AUDIO_CONFIG (sample rates, frame ms, prebuffer ms)
│ │ │ └─ worklets/
│ │ │ ├─ capture-processor.worklet.js
│ │ │ └─ playback-processor.worklet.js
│ │ ├─ websocket/
│ │ │ ├─ realtime-transport.ts # abstract interface (WS today, WebRTC later)
│ │ │ ├─ websocket.service.ts # connect/reconnect/backoff/heartbeat
│ │ │ ├─ frame-codec.ts # binary header encode/decode (see §5.2)
│ │ │ └─ protocol.types.ts # ClientMessage / ServerMessage unions
│ │ ├─ state/
│ │ │ ├─ voice-state.store.ts # voiceState, activeSession, transcript
│ │ │ └─ voice-state.types.ts
│ │ ├─ http/
│ │ │ ├─ auth.interceptor.ts
│ │ │ └─ error.interceptor.ts
│ │ ├─ telemetry/
│ │ │ └─ telemetry.service.ts # underruns, latency marks, state transitions
│ │ └─ config/
│ │ └─ app-config.token.ts # wsUrl, apiBaseUrl, feature flags
│ │
│ ├─ features/
│ │ ├─ voice-agent/
│ │ │ ├─ voice-agent.page.ts # route container (smart)
│ │ │ ├─ components/
│ │ │ │ ├─ voice-orb/ # canvas host (dumb, OnPush)
│ │ │ │ ├─ voice-controls/ # mic button, push-to-talk, stop
│ │ │ │ ├─ voice-status-label/ # state text + aria-live
│ │ │ │ ├─ transcript-panel/ # collapsible transcript
│ │ │ │ └─ faq-suggestions/ # suggested questions chips
│ │ │ ├─ services/
│ │ │ │ ├─ voice-session.service.ts # state machine orchestrator
│ │ │ │ ├─ voice-transitions.ts # TRANSITIONS table + guards
│ │ │ │ └─ visualizer/
│ │ │ │ ├─ visualizer.interface.ts
│ │ │ │ ├─ three-orb.visualizer.ts # WebGL implementation
│ │ │ │ ├─ canvas2d.visualizer.ts # fallback
│ │ │ │ └─ state-presets.ts
│ │ │ └─ voice-agent.routes.ts
│ │ │
│ │ └─ faq-manager/
│ │ ├─ faq-manager.page.ts # optional full-page route
│ │ ├─ components/
│ │ │ ├─ faq-drawer/ # CDK Overlay slide-over host
│ │ │ ├─ file-dropzone/ # drag & drop, type/size validation
│ │ │ ├─ csv-preview/ # PapaParse preview (first N rows, column mapping)
│ │ │ ├─ document-list/ # rows with status badges and progress
│ │ │ ├─ qa-grid/ # AG Grid (lazy) or Tailwind table
│ │ │ └─ qa-edit-dialog/ # CDK Dialog for manual override
│ │ ├─ services/
│ │ │ ├─ faq-store.ts # signals: documents, qaPairs, filters
│ │ │ ├─ faq-ingestion.service.ts # validate, upload, status stream
│ │ │ ├─ faq-api.service.ts # HTTP client
│ │ │ └─ csv-parser.service.ts # lazy PapaParse wrapper (worker: true)
│ │ └─ faq-manager.routes.ts
│ │
│ └─ shared/
│ ├─ ui/
│ │ ├─ button/ · badge/ · drawer/ · dialog/ · toast/ · spinner/ · empty-state/
│ │ └─ icons/ # Lucide icon registration (tree-shaken)
│ ├─ directives/ # autofocus, resize-observer, click-outside
│ ├─ pipes/ # file-size, relative-time
│ └─ utils/ # assert, raf-throttle, id generation
│
├─ assets/
│ └─ worklets/ # compiled worklet files served as static assets
├─ environments/
└─ styles/
└─ tailwind.css
```
**Notes**
- **Worklet files are static assets**, loaded with `ctx.audioWorklet.addModule(new URL('./capture-processor.worklet.js', import.meta.url))` or from `assets/`. They are *not* part of the Angular bundle graph (they run in a separate global scope).
- **Zoneless provider:** use `provideExperimentalZonelessChangeDetection()` on Angular 18/19; newer majors expose the stabilized `provideZonelessChangeDetection()`. Keep Zone.js in `polyfills` until the zoneless checklist passes, then remove it.
- **Dependency rule (enforced via ESLint `no-restricted-imports` / Nx-style boundaries):**
`shared` ← `core` ← `features`; features never import from each other; `core/audio` and `core/websocket` never import Angular UI.
- **Smart vs dumb:** `*.page.ts` and services are smart; everything in `components/` is `OnPush`, input/output driven, with no service injection except for `visualizer` hosts and the dialog/overlay hosts.
### 4.1 Key component contracts
| Component | Inputs (signal `input()`) | Outputs (`output()`) | Notes |
|---|---|---|---|
| `VoiceOrbComponent` | `state: VoiceState` | `ready`, `webglUnavailable` | Owns `