first commit
This commit is contained in:
@@ -0,0 +1,909 @@
|
||||
# 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<br/>Float32 to Int16 PCM, 20 ms frames"]
|
||||
PLAY["playback-processor<br/>ring buffer / jitter buffer"]
|
||||
end
|
||||
|
||||
subgraph MainOutside["Main Thread - outside Angular zone / CD"]
|
||||
ACTX["AudioContext graph<br/>MediaStreamSource, AnalyserNode in/out"]
|
||||
WS["WebSocketService<br/>binary audio + JSON control"]
|
||||
VIS["VisualizerEngine<br/>Three.js orb, rAF loop"]
|
||||
BUS["AudioLevelBus<br/>mutable Float32 snapshot"]
|
||||
end
|
||||
|
||||
subgraph NG["Angular Reactive Domain (Signals, OnPush)"]
|
||||
SESS["VoiceSessionService<br/>state machine orchestrator"]
|
||||
VSTATE["VoiceStateStore<br/>voiceState, activeSession, transcript"]
|
||||
FAQ["FaqStore<br/>faqDocuments, qaPairs, filters"]
|
||||
UI["Components<br/>VoiceAgent, FaqDrawer, FaqGrid"]
|
||||
end
|
||||
end
|
||||
|
||||
subgraph Backend["Backend"]
|
||||
GW["Realtime Gateway<br/>auth, session, VAD"]
|
||||
RAG["RAG Retriever<br/>vector index"]
|
||||
LLM["LLM"]
|
||||
TTS["TTS / STT"]
|
||||
ING["Ingestion API<br/>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<VoiceState>` | events (~1–5 Hz) | templates, visualizer (via `effect`) | Written only by `VoiceSessionService` |
|
||||
| `activeSession` | `Signal<VoiceSession \| null>` | rare | header, guards | id, startedAt, connection status |
|
||||
| `transcript` | `Signal<TranscriptEntry[]>` | per utterance / partial | transcript drawer | Partials update the last entry immutably |
|
||||
| `faqDocuments` | `Signal<FaqDocument[]>` | per upload event | drawer, grid toolbar | Keyed by `id`; status updated via `update()` |
|
||||
| `qaPairs` | `Signal<QaPair[]>` | per edit | grid | Large lists: keep as `Map` internally, expose array via `computed` |
|
||||
| `activeDocumentIds` | `Signal<Set<string>>` | 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<VoiceState>('idle');
|
||||
private readonly _activeSession = signal<VoiceSession | null>(null);
|
||||
private readonly _transcript = signal<TranscriptEntry[]>([]);
|
||||
|
||||
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<VoiceState, Partial<Record<VoiceEvent['type'], VoiceState>>> = {
|
||||
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<ElementRef<HTMLCanvasElement>>('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 `<canvas>`, creates visualizer in `afterNextRender` |
|
||||
| `VoiceControlsComponent` | `state`, `micPermission` | `toggleMic`, `stop` | Keyboard: Space toggles, Esc stops |
|
||||
| `TranscriptPanelComponent` | `entries`, `open` | `openChange` | `aria-live="polite"` for the latest entry |
|
||||
| `FaqDrawerComponent` | `open` | `closed` | CDK `Overlay` + focus trap; slides from the inline-end edge |
|
||||
| `FileDropzoneComponent` | `accept`, `maxBytes` | `filesSelected`, `rejected` | Validates MIME + extension + size before anything uploads |
|
||||
| `DocumentListComponent` | `documents` | `retry`, `remove`, `toggleActive` | Status badge per `FaqDocumentStatus` |
|
||||
| `QaGridComponent` | `rows`, `filters` | `editRow`, `toggleOverride`, `bulkDelete` | Virtualized; server-side row model if > 50k rows |
|
||||
|
||||
### 4.2 Component interaction (voice screen)
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant U as User
|
||||
participant C as VoiceControls
|
||||
participant S as VoiceSessionService
|
||||
participant E as AudioEngine
|
||||
participant T as WebSocketService
|
||||
participant B as Backend
|
||||
participant V as VisualizerEngine
|
||||
|
||||
U->>C: click orb
|
||||
C->>S: dispatch(START_LISTENING)
|
||||
S->>E: unmuteCapture()
|
||||
S->>T: control turn.start
|
||||
loop every 20 ms
|
||||
E->>T: PCM frame
|
||||
T->>B: binary frame
|
||||
end
|
||||
B-->>T: control vad.end_of_speech
|
||||
T-->>S: END_OF_UTTERANCE
|
||||
S->>E: muteCapture()
|
||||
B-->>T: PCM reply frames (turnId=n)
|
||||
T->>E: transfer to playback worklet
|
||||
T-->>S: AGENT_AUDIO_START
|
||||
S-->>V: state signal changes, effect applies preset
|
||||
U->>E: starts talking (VAD energy over threshold)
|
||||
E-->>S: BARGE_IN
|
||||
S->>E: flushPlayback() (local, immediate)
|
||||
S->>T: control interrupt with playedMs
|
||||
S-->>S: FLUSH_DONE, state becomes listening
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 5. Data Contracts & Types
|
||||
|
||||
All shared types live in `core/**/**.types.ts` and are **framework-free** (no Angular imports) so they can be shared with the backend repo or generated from an OpenAPI/AsyncAPI spec later.
|
||||
|
||||
### 5.1 Voice states and session
|
||||
|
||||
```ts
|
||||
// core/state/voice-state.types.ts
|
||||
export const VOICE_STATES = ['idle', 'listening', 'processing', 'speaking', 'interrupted'] as const;
|
||||
export type VoiceState = (typeof VOICE_STATES)[number];
|
||||
|
||||
export type VoiceEvent =
|
||||
| { type: 'SESSION_READY' }
|
||||
| { type: 'START_LISTENING'; source: 'ui' | 'client-vad' }
|
||||
| { type: 'END_OF_UTTERANCE'; source: 'server-vad' | 'ui'; durationMs: number }
|
||||
| { type: 'AGENT_AUDIO_START'; turnId: string }
|
||||
| { type: 'AGENT_AUDIO_END'; turnId: string }
|
||||
| { type: 'BARGE_IN'; playedMs: number }
|
||||
| { type: 'FLUSH_DONE' }
|
||||
| { type: 'ERROR'; error: VoiceError }
|
||||
| { type: 'STOP' };
|
||||
|
||||
export type ConnectionStatus = 'disconnected' | 'connecting' | 'connected' | 'reconnecting' | 'failed';
|
||||
|
||||
export interface VoiceSession {
|
||||
readonly id: string;
|
||||
readonly startedAt: number; // epoch ms
|
||||
readonly connection: ConnectionStatus;
|
||||
readonly activeDocumentIds: readonly string[];
|
||||
readonly locale: string; // BCP-47, e.g. 'en-US', 'fa-IR'
|
||||
readonly currentTurnId: string | null;
|
||||
}
|
||||
|
||||
export interface TranscriptEntry {
|
||||
readonly id: string;
|
||||
readonly turnId: string;
|
||||
readonly role: 'user' | 'agent';
|
||||
readonly text: string;
|
||||
readonly final: boolean; // false while streaming partials
|
||||
readonly timestamp: number;
|
||||
readonly citations?: readonly FaqCitation[];
|
||||
}
|
||||
|
||||
export interface FaqCitation {
|
||||
readonly documentId: string;
|
||||
readonly qaPairId?: string;
|
||||
readonly title: string;
|
||||
readonly score?: number; // retrieval relevance 0..1
|
||||
}
|
||||
|
||||
export type VoiceErrorCode =
|
||||
| 'MIC_PERMISSION_DENIED' | 'MIC_NOT_FOUND' | 'AUDIO_CONTEXT_FAILED' | 'WORKLET_LOAD_FAILED'
|
||||
| 'SOCKET_FAILED' | 'AUTH_EXPIRED' | 'SERVER_ERROR' | 'RATE_LIMITED' | 'UNSUPPORTED_BROWSER';
|
||||
|
||||
export interface VoiceError {
|
||||
readonly code: VoiceErrorCode;
|
||||
readonly message: string;
|
||||
readonly recoverable: boolean;
|
||||
}
|
||||
```
|
||||
|
||||
### 5.2 WebSocket protocol
|
||||
|
||||
A **hybrid protocol**: *binary* frames for audio (low overhead), *text/JSON* frames for control.
|
||||
|
||||
#### Binary audio frame layout (little-endian)
|
||||
|
||||
| Offset | Size | Field | Description |
|
||||
|---|---|---|---|
|
||||
| 0 | 1 B | `version` | Protocol version (currently `1`) |
|
||||
| 1 | 1 B | `kind` | `0x01` = mic audio (client → server), `0x02` = agent audio (server → client) |
|
||||
| 2 | 1 B | `flags` | bit0 = last frame of turn, bit1 = contains silence |
|
||||
| 3 | 1 B | `reserved` | `0` |
|
||||
| 4 | 4 B | `seq` | Monotonic per direction, wraps at 2³² |
|
||||
| 8 | 4 B | `timestampMs` | Capture/synthesis offset from turn start |
|
||||
| 12 | 4 B | `turnIdHash` | 32-bit hash of the `turnId` (full id is sent in control messages) |
|
||||
| 16 | N | `payload` | PCM16 mono, little-endian, 20 ms per frame (e.g. 640 B @ 16 kHz) |
|
||||
|
||||
```ts
|
||||
// core/websocket/protocol.types.ts
|
||||
export type AudioEncoding = 'pcm_s16le' | 'opus';
|
||||
|
||||
export interface AudioFormat {
|
||||
readonly encoding: AudioEncoding;
|
||||
readonly sampleRate: 16000 | 24000 | 48000;
|
||||
readonly channels: 1;
|
||||
readonly frameMs: 10 | 20 | 40;
|
||||
}
|
||||
|
||||
/** Decoded view of a binary audio frame */
|
||||
export interface AudioFrame {
|
||||
readonly version: 1;
|
||||
readonly kind: 'mic' | 'agent';
|
||||
readonly lastOfTurn: boolean;
|
||||
readonly silent: boolean;
|
||||
readonly seq: number;
|
||||
readonly timestampMs: number;
|
||||
readonly turnIdHash: number;
|
||||
readonly payload: ArrayBuffer; // PCM bytes, transferable
|
||||
}
|
||||
|
||||
/* ---------- Client -> Server (JSON) ---------- */
|
||||
export type ClientMessage =
|
||||
| { type: 'session.start'; token: string; locale: string; inputFormat: AudioFormat;
|
||||
outputFormat: AudioFormat; documentIds: string[] }
|
||||
| { type: 'turn.start'; turnId: string }
|
||||
| { type: 'turn.end'; turnId: string }
|
||||
| { type: 'turn.cancel'; turnId: string }
|
||||
| { type: 'interrupt'; turnId: string; playedMs: number } // how much agent audio the user actually heard
|
||||
| { type: 'config.update'; documentIds: string[] }
|
||||
| { type: 'ping'; t: number }
|
||||
| { type: 'session.end' };
|
||||
|
||||
/* ---------- Server -> Client (JSON) ---------- */
|
||||
export type ServerMessage =
|
||||
| { type: 'session.ready'; sessionId: string; inputFormat: AudioFormat; outputFormat: AudioFormat }
|
||||
| { type: 'vad.speech_start' }
|
||||
| { type: 'vad.speech_end'; durationMs: number }
|
||||
| { type: 'transcript.partial'; turnId: string; role: 'user' | 'agent'; text: string }
|
||||
| { type: 'transcript.final'; turnId: string; role: 'user' | 'agent'; text: string; citations?: FaqCitationDto[] }
|
||||
| { type: 'agent.audio_start'; turnId: string }
|
||||
| { type: 'agent.audio_end'; turnId: string }
|
||||
| { type: 'suggestions'; items: string[] }
|
||||
| { type: 'error'; code: string; message: string; recoverable: boolean }
|
||||
| { type: 'pong'; t: number };
|
||||
|
||||
export interface FaqCitationDto { documentId: string; qaPairId?: string; title: string; score?: number }
|
||||
```
|
||||
|
||||
**Protocol rules**
|
||||
|
||||
- Authentication happens in the first JSON message (`session.start.token`, a short-lived ticket), **not** in the URL query string (URLs are logged).
|
||||
- The server must echo/choose the final `AudioFormat`s in `session.ready`; the client configures worklets from that response.
|
||||
- `interrupt.playedMs` lets the server truncate the conversation history to what the user actually heard.
|
||||
- Heartbeat: client `ping` every 15 s; no `pong` within 2 intervals ⇒ reconnect with exponential backoff (500 ms → 8 s, jittered). Reconnect starts a *new* session, never resumes mid-turn.
|
||||
|
||||
### 5.3 Worklet message contracts
|
||||
|
||||
```ts
|
||||
// core/audio/audio.types.ts
|
||||
export type CaptureCommand = { type: 'active'; value: boolean };
|
||||
export type CaptureEvent = ArrayBuffer; // transferred Int16 PCM frame (raw message)
|
||||
|
||||
export type PlaybackCommand =
|
||||
| { type: 'config'; sampleRate: number; prebufferMs: number }
|
||||
| { type: 'frame'; pcm: ArrayBuffer; turnIdHash: number } // transferred
|
||||
| { type: 'flush' }
|
||||
| { type: 'end-of-turn' };
|
||||
|
||||
export type PlaybackEvent =
|
||||
| { type: 'started' }
|
||||
| { type: 'drained' }
|
||||
| { type: 'underrun'; count: number }
|
||||
| { type: 'level'; rms: number }; // optional, low-rate (~20 Hz)
|
||||
```
|
||||
|
||||
### 5.4 FAQ knowledge base
|
||||
|
||||
```ts
|
||||
// features/faq-manager/models/faq.types.ts
|
||||
export type FaqFileType = 'pdf' | 'csv' | 'json' | 'docx';
|
||||
|
||||
export type FaqDocumentStatus = 'uploading' | 'indexing' | 'active' | 'error';
|
||||
|
||||
export interface FaqDocument {
|
||||
readonly id: string; // client-generated UUID until the server assigns one
|
||||
readonly serverId?: string;
|
||||
readonly name: string;
|
||||
readonly type: FaqFileType;
|
||||
readonly sizeBytes: number;
|
||||
readonly status: FaqDocumentStatus;
|
||||
readonly progress: number; // 0..1 (upload progress, then indexing progress if available)
|
||||
readonly itemCount: number | null; // Q&A pairs extracted; null until known
|
||||
readonly enabled: boolean; // included in the voice session's retrieval scope
|
||||
readonly uploadedAt: number;
|
||||
readonly updatedAt: number;
|
||||
readonly error?: FaqDocumentError;
|
||||
}
|
||||
|
||||
export interface FaqDocumentError {
|
||||
readonly code: 'VALIDATION_FAILED' | 'UPLOAD_FAILED' | 'PARSE_FAILED' | 'INDEX_FAILED' | 'QUOTA_EXCEEDED';
|
||||
readonly message: string;
|
||||
readonly retryable: boolean;
|
||||
readonly rowErrors?: readonly CsvRowError[];
|
||||
}
|
||||
|
||||
export interface QaPair {
|
||||
readonly id: string;
|
||||
readonly documentId: string;
|
||||
readonly question: string;
|
||||
readonly answer: string;
|
||||
readonly tags: readonly string[];
|
||||
readonly source: 'ingested' | 'manual';
|
||||
readonly overridden: boolean; // manual edit wins over re-ingested content
|
||||
readonly enabled: boolean;
|
||||
readonly updatedAt: number;
|
||||
readonly updatedBy?: string;
|
||||
}
|
||||
|
||||
export interface QaFilter {
|
||||
readonly query: string;
|
||||
readonly documentIds: readonly string[];
|
||||
readonly source: 'all' | 'ingested' | 'manual';
|
||||
readonly onlyOverridden: boolean;
|
||||
readonly onlyDisabled: boolean;
|
||||
}
|
||||
|
||||
/* ---------- Client-side validation ---------- */
|
||||
export interface FileValidationRule {
|
||||
readonly maxBytes: number; // e.g. 25 MB
|
||||
readonly allowedExtensions: readonly FaqFileType[];
|
||||
readonly allowedMimeTypes: readonly string[];
|
||||
}
|
||||
|
||||
export interface CsvPreview {
|
||||
readonly headers: readonly string[];
|
||||
readonly rows: readonly Record<string, string>[]; // first N rows only
|
||||
readonly totalRowsEstimate: number;
|
||||
readonly questionColumn: string | null; // auto-detected or user-mapped
|
||||
readonly answerColumn: string | null;
|
||||
readonly errors: readonly CsvRowError[];
|
||||
}
|
||||
|
||||
export interface CsvRowError {
|
||||
readonly row: number;
|
||||
readonly code: 'MISSING_QUESTION' | 'MISSING_ANSWER' | 'TOO_LONG' | 'MALFORMED';
|
||||
readonly message: string;
|
||||
}
|
||||
|
||||
/* ---------- Server status stream (SSE or WS) ---------- */
|
||||
export type IngestionEvent =
|
||||
| { type: 'document.progress'; id: string; stage: 'uploading' | 'indexing'; progress: number }
|
||||
| { type: 'document.active'; id: string; itemCount: number }
|
||||
| { type: 'document.error'; id: string; error: FaqDocumentError };
|
||||
```
|
||||
|
||||
**FAQ state shape (signals)**
|
||||
|
||||
```ts
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class FaqStore {
|
||||
private readonly _documents = signal<readonly FaqDocument[]>([]);
|
||||
private readonly _pairs = signal<ReadonlyMap<string, QaPair>>(new Map());
|
||||
readonly filter = signal<QaFilter>(DEFAULT_FILTER);
|
||||
|
||||
readonly documents = this._documents.asReadonly();
|
||||
readonly activeDocuments = computed(() => this._documents().filter(d => d.status === 'active' && d.enabled));
|
||||
readonly hasProcessing = computed(() => this._documents().some(d => d.status === 'uploading' || d.status === 'indexing'));
|
||||
readonly visiblePairs = computed(() => applyFilter([...this._pairs().values()], this.filter()));
|
||||
readonly totalActiveItems = computed(() => this.activeDocuments().reduce((n, d) => n + (d.itemCount ?? 0), 0));
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 6. Cross-Cutting Concerns
|
||||
|
||||
### 6.1 Error handling & resilience
|
||||
|
||||
| Failure | Detection | Behaviour |
|
||||
|---|---|---|
|
||||
| Mic permission denied | `getUserMedia` rejection (`NotAllowedError`) | Inline explainer with browser-specific steps; text input fallback |
|
||||
| `AudioContext` suspended (autoplay policy) | `ctx.state === 'suspended'` | Create/resume only inside a user gesture (the first orb click) |
|
||||
| Worklet module fails to load | `addModule` rejection | Fatal `WORKLET_LOAD_FAILED`; show unsupported-browser message |
|
||||
| Socket drop mid-turn | `onclose` / missed pong | Flush playback, state → `idle`, auto-reconnect with backoff, toast |
|
||||
| Token expiry | `error` message `AUTH_EXPIRED` | Refresh ticket via HTTP, then restart session |
|
||||
| Playback underrun | worklet `underrun` event | Increase prebuffer adaptively (up to 200 ms), log telemetry |
|
||||
| WebGL context lost | `webglcontextlost` | Swap to `Canvas2DVisualizer`; try restore on `webglcontextrestored` |
|
||||
|
||||
### 6.2 Security & privacy
|
||||
|
||||
- `wss://` only; CSP with `connect-src` restricted to the API/gateway hosts and `worker-src`/`script-src` allowing the worklet assets.
|
||||
- Mic access only after an explicit user gesture; a visible "mic live" indicator in the UI whenever capture is active.
|
||||
- Uploaded files are validated by **magic bytes + extension + size** on the client for UX only; the server must re-validate (client checks are never a trust boundary).
|
||||
- Do not log raw audio or transcripts to telemetry; log durations, counts, and error codes.
|
||||
- `Cross-Origin-Opener-Policy` / `Cross-Origin-Embedder-Policy` headers are *only* required if `SharedArrayBuffer` ring buffers are adopted (optional optimization, see ADR-06).
|
||||
|
||||
### 6.3 Accessibility
|
||||
|
||||
- The orb is decorative; the **status label** (`aria-live="polite"`) announces state changes ("Listening…", "Thinking…", "Speaking…").
|
||||
- Full keyboard operation (Space = talk/stop, Esc = end, Tab order through drawer, focus trap in CDK Dialog/Overlay).
|
||||
- Transcript panel gives a complete text alternative, with captions of the agent's reply as it is spoken.
|
||||
- Respect `prefers-reduced-motion`; never rely on color alone for state (icon + label + motion).
|
||||
- Drawer and layout use **logical CSS properties** (`ms-*`, `ps-*`, `inset-inline-end`) and `dir`-aware Tailwind variants so RTL locales work without forks.
|
||||
|
||||
### 6.4 Observability
|
||||
|
||||
Telemetry events (no PII): `session_start`, `state_transition {from,to,ms_in_state}`, `barge_in {playedMs}`, `underrun_count`, `ttfa_ms` (end-of-utterance → first agent audio), `reconnect {attempt}`, `ingestion_complete {type,items,ms}`. A dev-only HUD shows FPS, CD tick count, jitter-buffer depth, and RTT.
|
||||
|
||||
### 6.5 Testing strategy (summary)
|
||||
|
||||
| Layer | Approach |
|
||||
|---|---|
|
||||
| Transition table & guards | Pure unit tests (table-driven), including "ignored event" cases |
|
||||
| Frame codec / PCM utils | Unit tests with golden byte arrays |
|
||||
| Worklets | Run processor classes in Node/Vitest with a fake `AudioWorkletGlobalScope`; assert pooling and flush behaviour |
|
||||
| `VoiceSessionService` | Integration test with fake `AudioEngine` + fake `RealtimeTransport`; simulate barge-in races and stale `turnId` frames |
|
||||
| Components | Angular Testing Library; verify `OnPush` correctness via signal inputs only |
|
||||
| Zoneless safety | Run the full suite with `provideExperimentalZonelessChangeDetection()` (or the stable name) and **without** Zone.js |
|
||||
| E2E | Playwright with Chromium flags `--use-fake-device-for-media-stream --use-file-for-fake-audio-capture=...` and a mock WS gateway |
|
||||
| Perf | Lighthouse CI budget + scripted Chrome trace asserting zero CD ticks during a 30 s visualized idle |
|
||||
|
||||
---
|
||||
|
||||
## 7. Architecture Decision Records (summary)
|
||||
|
||||
| # | Decision | Rationale | Trade-off |
|
||||
|---|---|---|---|
|
||||
| ADR-01 | **State machine as a data table** in a single service | Testable, diagrammable, one writer | Slightly more ceremony than ad-hoc signal sets |
|
||||
| ADR-02 | **Per-frame audio levels bypass signals** (`AudioLevelBus`) | Avoids 60 Hz CD scheduling in zoneless mode | Visualizer reads mutable data; documented exception to "everything is a signal" |
|
||||
| ADR-03 | **Hybrid binary/JSON WebSocket protocol** | Lowest overhead for audio; readable control plane | Two codecs to maintain |
|
||||
| ADR-04 | **`interrupted` is a distinct, auto-resolving state** | Observability and testability of barge-in | One extra transition |
|
||||
| ADR-05 | **Local-first flush on barge-in**, server informed after | Perceived latency independent of RTT | Must handle late frames via `turnId` |
|
||||
| ADR-06 | **`postMessage` with transferables** first; `SharedArrayBuffer` only if profiling demands | Avoids COOP/COEP deployment constraints | Slightly higher overhead per frame |
|
||||
| ADR-07 | **`RealtimeTransport` abstraction** | WebSocket now, WebRTC later without touching the state machine | Interface must stay minimal |
|
||||
| ADR-08 | **Lazy-load Three.js, PapaParse, AG Grid** | Keeps initial bundle small | First visit to each feature pays a small fetch |
|
||||
| ADR-09 | **Server-side VAD for end-of-utterance; client-side energy gate only for barge-in** | Server has better models and context; client gate gives instant barge-in | Two VAD paths to tune |
|
||||
| ADR-10 | **Raw PCM16 over WS for MVP**, Opus (WebCodecs) as a later optimization | Simplicity and debuggability | ~256 kbps at 16 kHz up/down vs ~24–32 kbps Opus |
|
||||
|
||||
---
|
||||
|
||||
## 8. Open Questions
|
||||
|
||||
These affect later documents and should be resolved with the backend team:
|
||||
|
||||
1. **Audio formats:** does the gateway accept 16 kHz PCM16 in and emit 24 kHz PCM16 out (assumed here), or Opus?
|
||||
2. **VAD ownership:** server VAD only, or both? What are the end-of-utterance silence defaults, and is the threshold configurable per session?
|
||||
3. **Barge-in semantics:** does the server stop TTS on `interrupt`, or only on its own VAD? (The client protocol sends both.)
|
||||
4. **Ingestion status channel:** SSE or reuse of the realtime WebSocket? (The types support either.)
|
||||
5. **Grid scale:** expected maximum Q&A pairs per knowledge base — this decides between client-side filtering and AG Grid's server-side row model.
|
||||
6. **Locales:** which languages and writing directions must the voice and the UI support at launch?
|
||||
7. **Auth model:** how is the short-lived WebSocket ticket issued, and how long does it live?
|
||||
|
||||
---
|
||||
|
||||
## 9. Next Documents
|
||||
|
||||
| File | Contents |
|
||||
|---|---|
|
||||
| **`ROADMAP.md`** | Sprint-by-sprint implementation plan: scope, deliverables, acceptance criteria, risks, and a dependency graph. Proposed phases: (1) worklet + visualizer spike, (2) WS duplex + voice state machine, (3) FAQ manager UI, (4) zoneless hardening, performance, and testing. |
|
||||
| **`VOICE_AUDIO_PIPELINE.md`** | Implementation guide: full `AudioEngineService`, capture/playback worklets with pooled buffers, resampling, jitter-buffer tuning, `AnalyserNode` wiring, the Three.js orb (shader uniforms, state presets, quality scaling), and the Canvas 2D fallback. |
|
||||
| **`FAQ_MANAGEMENT_SPEC.md`** | Ingestion UX and logic: dropzone validation, PapaParse preview with column mapping (worker mode, streaming for large files), upload with progress, status stream handling, AG Grid configuration (columns, editors, filters, optimistic edits, overrides), and error recovery. |
|
||||
| **`ZONELESS_CONVENTION.md`** | Coding standards: signal conventions (one writer, `asReadonly`), `input()`/`output()`/`viewChild()` usage, `OnPush` rules, `effect` and `untracked` guidelines, `toSignal` interop rules, forbidden patterns (e.g., mutating state outside signals), and the Zone.js-removal migration checklist with a CI gate. |
|
||||
|
||||
> Say **"continue"** and I'll write `ROADMAP.md` next, or tell me which file you'd like first.
|
||||
@@ -0,0 +1,374 @@
|
||||
# DEPENDENCIES.md — Voice-to-Voice FAQ Web Application
|
||||
|
||||
> **Companion to:** `ARCHITECTURE.md` · **See also:** `SRC_STRUCTURE.md`
|
||||
> **Versions verified against the npm registry on 2026-10-05.** The latest Angular line at that date is **22.2.x**. Everything below targets Angular 22; section 1 lists what changes if you must stay on 18/19.
|
||||
|
||||
---
|
||||
|
||||
## 0. Read this first: six findings that change the install
|
||||
|
||||
These came out of checking real peer-dependency ranges and package contents, not from memory. Each one would otherwise cost you an `ERESOLVE` error or a runtime failure.
|
||||
|
||||
| # | Finding | What to do |
|
||||
|---|---|---|
|
||||
| 1 | **`provideExperimentalZonelessChangeDetection` no longer exists in Angular 22** (it is absent from `@angular/core@22.2.1`). The stable name is `provideZonelessChangeDetection`. The experimental name is only correct for Angular 18/19. | Use `provideZonelessChangeDetection()` (see `SRC_STRUCTURE.md` → `app.config.ts`). |
|
||||
| 2 | **TypeScript must be `>=6.0 <6.1`.** `@angular/compiler-cli@22.2.1` and `@angular/build@22.2.1` both declare that peer range, while `typescript@latest` is already 7.0.x. | Pin `"typescript": "~6.0.3"`. Do not run `npm i typescript@latest`. |
|
||||
| 3 | **`lucide-angular` is deprecated** on npm ("Please use `@lucide/angular` instead"). Its peer range stops at Angular 21 (`13.x – 21.x`), so it will conflict with Angular 22. | Use **`@lucide/angular`** (peer `>=17`). Icons are isolated behind `shared/ui/icons`, so only that folder knows which package is in use. |
|
||||
| 4 | **Tailwind CSS is v4** (`4.3.x`). It is configured in CSS (`@theme`, `@utility`), runs through `@tailwindcss/postcss`, and **does not need Autoprefixer**. | Install `tailwindcss`, `@tailwindcss/postcss`, `postcss`. Skip `autoprefixer` (explained in §3.3). |
|
||||
| 5 | **Three.js is pre-1.0** (`0.186.x`), and minor versions can contain breaking changes. | Pin with a **tilde** (`~0.186.1`) and keep `@types/three` on the matching minor (`~0.186.0`). |
|
||||
| 6 | **Node.js `^22.22.3 \|\| ^24.15.0 \|\| >=26`** is required by Angular 22. | Set `engines` and add an `.nvmrc` (`24`). |
|
||||
|
||||
---
|
||||
|
||||
## 1. If you must stay on Angular 18 or 19
|
||||
|
||||
| Topic | Angular 22 (this document) | Angular 18/19 |
|
||||
|---|---|---|
|
||||
| Zoneless provider | `provideZonelessChangeDetection()` | `provideExperimentalZonelessChangeDetection()` |
|
||||
| TypeScript | `~6.0.3` | Use the range printed by `npm view @angular/compiler-cli@<your-version> peerDependencies` |
|
||||
| Icons | `@lucide/angular` | `lucide-angular` also works (its peer range covers these versions) |
|
||||
| Tailwind | v4 via `@tailwindcss/postcss` | Stay on Tailwind v3 (`tailwind.config.js`, `postcss`, `autoprefixer`) unless your CLI version documents v4 support |
|
||||
| Unit tests | Vitest via `@angular/build:unit-test` | Karma + Jasmine (default for those versions) |
|
||||
| Components | `OnPush` set explicitly (kept explicit for readability) | `OnPush` set explicitly (required) |
|
||||
|
||||
For every other package (Three.js, AG Grid, PapaParse, CDK) install the version whose `peerDependencies` match your Angular major.
|
||||
|
||||
---
|
||||
|
||||
## 2. Complete `package.json`
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "voice-faq-app",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"engines": {
|
||||
"node": "^22.22.3 || ^24.15.0"
|
||||
},
|
||||
"scripts": {
|
||||
"start": "ng serve",
|
||||
"build": "ng build",
|
||||
"build:prod": "ng build --configuration production",
|
||||
"build:stats": "ng build --configuration production --stats-json",
|
||||
"watch": "ng build --watch --configuration development",
|
||||
"test": "ng test",
|
||||
"test:ci": "ng test --no-watch",
|
||||
"e2e": "playwright test",
|
||||
"lint": "ng lint",
|
||||
"format": "prettier --write \"src/**/*.{ts,html,css,json}\"",
|
||||
"format:check": "prettier --check \"src/**/*.{ts,html,css,json}\""
|
||||
},
|
||||
"dependencies": {
|
||||
"@angular/cdk": "^22.2.1",
|
||||
"@angular/common": "^22.2.1",
|
||||
"@angular/compiler": "^22.2.1",
|
||||
"@angular/core": "^22.2.1",
|
||||
"@angular/forms": "^22.2.1",
|
||||
"@angular/platform-browser": "^22.2.1",
|
||||
"@angular/router": "^22.2.1",
|
||||
"@lucide/angular": "^1.52.0",
|
||||
"ag-grid-angular": "^36.2.0",
|
||||
"ag-grid-community": "^36.2.0",
|
||||
"papaparse": "^5.7.0",
|
||||
"rxjs": "~7.8.2",
|
||||
"three": "~0.186.1",
|
||||
"tslib": "^2.8.1",
|
||||
"zone.js": "~0.16.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@angular/build": "^22.2.1",
|
||||
"@angular/cli": "^22.2.1",
|
||||
"@angular/compiler-cli": "^22.2.1",
|
||||
"@playwright/test": "^1.63.0",
|
||||
"@tailwindcss/postcss": "^4.3.3",
|
||||
"@types/audioworklet": "^0.0.100",
|
||||
"@types/node": "^24.0.0",
|
||||
"@types/papaparse": "^5.5.2",
|
||||
"@types/three": "~0.186.0",
|
||||
"angular-eslint": "^22.5.0",
|
||||
"eslint": "^10.12.0",
|
||||
"jsdom": "^30.1.2",
|
||||
"postcss": "^8.5.28",
|
||||
"prettier": "^3.9.9",
|
||||
"prettier-plugin-tailwindcss": "^0.8.1",
|
||||
"tailwindcss": "^4.3.3",
|
||||
"typescript": "~6.0.3",
|
||||
"typescript-eslint": "^8.71.0",
|
||||
"vitest": "^5.0.3"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**About `zone.js`:** it is listed because your plan keeps Zone.js enabled during development and removes it at the zoneless milestone (`ZONELESS_CONVENTION.md`). When that milestone passes, delete it from `dependencies` and from the `polyfills` array in `angular.json`, and switch `app.config.ts` from `provideZoneChangeDetection` to `provideZonelessChangeDetection`. A project that starts zoneless can omit it from day one.
|
||||
|
||||
**Optional packages** (PDF/DOCX client-side previews) are intentionally **not** in the block above. See §3.5.
|
||||
|
||||
---
|
||||
|
||||
## 3. `dependencies`, justified
|
||||
|
||||
### 3.1 Core & framework
|
||||
|
||||
| Package | Version | Why it is needed | Notes |
|
||||
|---|---|---|---|
|
||||
| `@angular/core` | `^22.2.1` | Signals (`signal`, `computed`, `effect`, `input()`, `output()`, `viewChild()`), `DestroyRef`, `NgZone`, zoneless scheduler, `provideZonelessChangeDetection`. | **Includes `@angular/core/rxjs-interop`** (`toSignal`, `toObservable`, `takeUntilDestroyed`) as a *secondary entry point*; there is nothing separate to install. |
|
||||
| `@angular/common` | `^22.2.1` | `NgOptimizedImage`, pipes, and **`@angular/common/http`** (`HttpClient`, `withFetch`, `withInterceptors`) for the FAQ REST API and upload progress. | `common/http` is also a secondary entry point of this package. |
|
||||
| `@angular/compiler` | `^22.2.1` | Required at runtime by the standard CLI scaffold and by JIT paths in tests. | Keep on the same version as `core`. |
|
||||
| `@angular/platform-browser` | `^22.2.1` | `bootstrapApplication`, DOM renderer, `Meta`/`Title`. | |
|
||||
| `@angular/router` | `^22.2.1` | Lazy-loaded feature routes (`voice`, `knowledge-base`), functional guards, `withComponentInputBinding()`. | |
|
||||
| `@angular/forms` | `^22.2.1` | Reactive forms in the Q&A editor modal and drawer filters. | Also a **peer dependency of `@angular/cdk`**. |
|
||||
| `@angular/cdk` | `^22.2.1` | **`@angular/cdk/overlay`** (slide-over drawer positioning, scroll strategies), **`@angular/cdk/dialog`** (Q&A editor modal, focus trap, `aria-modal`), **`@angular/cdk/a11y`** (`FocusTrap`, `LiveAnnouncer` for state changes), `@angular/cdk/portal`, `@angular/cdk/scrolling` (virtual scroll for the transcript). | Peer range is `^22 \|\| ^23`; versions of `cdk` and `core` must match the major. |
|
||||
| `rxjs` | `~7.8.2` | WebSocket event streams (`audio$`, `control$`), ingestion status stream (SSE), debouncing filters. Signals hold state; RxJS carries **events over time**. | Angular peers `^6.5.3 \|\| ^7.4.0`. |
|
||||
| `tslib` | `^2.8.1` | Helper functions for emitted code (no duplication per file). | Required by the Angular build. |
|
||||
| `zone.js` | `~0.16.3` | Only while the app still runs in zone mode. | Remove at the zoneless milestone (see §2). |
|
||||
|
||||
### 3.2 Audio & graphics
|
||||
|
||||
| Package | Version | Why it is needed | Notes |
|
||||
|---|---|---|---|
|
||||
| `three` | `~0.186.1` | WebGL renderer, scene graph, `ShaderMaterial`, icosahedron geometry for the audio-reactive orb. | Use **named imports** (`import { WebGLRenderer, Scene } from 'three'`) so esbuild can tree-shake. Load it only in the visualizer chunk via `import('three')` (lazy). Post-processing (bloom) lives in `three/addons/...` and is **not** planned for v1: the glow is computed in the fragment shader plus a CSS `drop-shadow`, which is far cheaper. |
|
||||
| `@types/three` *(dev)* | `~0.186.0` | Type definitions (Three.js ships no types). | Same minor as `three`. |
|
||||
|
||||
**Web Audio API utilities.** The Web Audio API, `AudioWorklet`, `AnalyserNode`, and `MediaDevices` are **browser built-ins**: no runtime package is required, and none is recommended. Libraries like Tone.js or Howler.js are excluded (§5). The only audio-related package is the type shim below.
|
||||
|
||||
| Package | Version | Why | Notes |
|
||||
|---|---|---|---|
|
||||
| `@types/audioworklet` *(dev)* | `^0.0.100` | Types for `AudioWorkletProcessor`, `registerProcessor`, and the worklet global scope, used by `// @ts-check` in the `.js` processors and by any future TypeScript worklet sources. | Add `"types": ["audioworklet"]` only in a dedicated `tsconfig.worklet.json`, **not** in the app tsconfig (it conflicts with DOM lib globals). |
|
||||
|
||||
### 3.3 UI, layout & icons
|
||||
|
||||
| Package | Version | Why it is needed | Notes |
|
||||
|---|---|---|---|
|
||||
| `tailwindcss` *(dev)* | `^4.3.3` | Utility CSS, design tokens via `@theme` (glow shadows, state colors, glass surfaces), custom `@utility` classes (`glass`, `glow-*`). | v4 reads tokens from CSS; there is **no `tailwind.config.js`** by default. |
|
||||
| `@tailwindcss/postcss` *(dev)* | `^4.3.3` | The PostCSS plugin the Angular build calls via `.postcssrc.json`. It also handles vendor prefixing and `@import` inlining. | |
|
||||
| `postcss` *(dev)* | `^8.5.28` | Required by `@tailwindcss/postcss` and by the Angular CSS pipeline. | |
|
||||
| `autoprefixer` | **not installed** | You asked for it, and it is the right choice on Tailwind v3. On **Tailwind v4 it is redundant**: prefixing is built into `@tailwindcss/postcss`. Adding it only adds build time. | If you stay on Tailwind v3 (Angular 18), install `autoprefixer ^10.6.1` and use `tailwind.config.js`. |
|
||||
| `@lucide/angular` | `^1.52.0` | Tree-shakeable Lucide icons as Angular components. Used for mic, stop, transcript, upload, trash, edit, status icons. | Replaces the deprecated `lucide-angular`. Register only the icons you use through the wrapper in `shared/ui/icons` so unused icons never reach the bundle. Follow the package README for its exact component/directive API. |
|
||||
| `ag-grid-community` | `^36.2.0` | Grid engine for the Q&A pairs: virtualized rows, inline editing, quick filter, column filters, row selection. | Register modules once (see §6.3). Keep community and angular wrapper on the **same version**. |
|
||||
| `ag-grid-angular` | `^36.2.0` | Angular wrapper (`<ag-grid-angular>`), signal-friendly inputs, cell renderer components. | Peer: `@angular/core >= 20`. |
|
||||
| `prettier-plugin-tailwindcss` *(dev)* | `^0.8.1` | Deterministic class ordering in templates. | |
|
||||
|
||||
**AG Grid vs. a custom Tailwind table.** The default plan is AG Grid because the grid needs inline editing, filtering, selection, and virtualization over potentially tens of thousands of Q&A rows. A Tailwind table remains a valid fallback for under roughly 500 rows. Both live behind `QaGridComponent`'s inputs/outputs, so swapping is a one-component change. Choosing the Tailwind table lets you drop both `ag-grid-*` packages.
|
||||
|
||||
### 3.4 Parsing & transport
|
||||
|
||||
| Package | Version | Why it is needed | Notes |
|
||||
|---|---|---|---|
|
||||
| `papaparse` | `^5.7.0` | Client-side CSV preview (first N rows), delimiter and header detection, row validation (`MISSING_QUESTION`, `MISSING_ANSWER`) before upload. | Lazy-load with `import('papaparse')`. Use `preview: N` for the preview and `chunk`/`step` streaming for counting rows in large files. **Do not rely on `worker: true`** under bundlers: PapaParse builds its worker from its own script URL, which commonly breaks once bundled; test it before depending on it. |
|
||||
| `@types/papaparse` *(dev)* | `^5.5.2` | Types for PapaParse. | |
|
||||
| WebSocket client | **none (native `WebSocket`)** | The browser's `WebSocket` supports binary frames (`binaryType = 'arraybuffer'`), which is exactly what the PCM protocol needs. Reconnect, backoff, heartbeat, and framing are ~150 lines in `core/websocket`. | See the Socket.IO note below. |
|
||||
|
||||
**Why not Socket.IO.** `socket.io-client` (latest `4.8.4`) speaks the Socket.IO protocol, which only works against a Socket.IO server and adds its own packet framing, optional long-polling transport, and event envelope on top of WebSocket. For a latency-critical raw-PCM stream with a custom 16-byte binary header (`ARCHITECTURE.md` §5.2), that is overhead without benefit. **Use it only if your backend is already Socket.IO.** In that case, install `socket.io-client@^4.8.4` and write a `SocketIoTransport implements RealtimeTransport` adapter; nothing else in the app changes, because everything consumes the transport interface.
|
||||
|
||||
### 3.5 Optional packages (add only if you need them)
|
||||
|
||||
The default design uploads files and lets the server do real parsing. The browser only validates type, size, and **magic bytes** (no library needed) and previews CSV. Add these only if you want richer previews:
|
||||
|
||||
| Package | Version | Purpose | Cost / caveat |
|
||||
|---|---|---|---|
|
||||
| `pdfjs-dist` | `^6.4.299` | Page count and first-page text preview of a PDF before upload. | Large; needs its worker file served as a static asset. Lazy-load behind the preview panel only. |
|
||||
| `mammoth` | `^1.13.0` | DOCX → plain text/HTML preview in the browser. | Sizeable; lazy-load. A server-side preview is often simpler. |
|
||||
| `socket.io-client` | `^4.8.4` | Only if the backend is Socket.IO (see §3.4). | Adds protocol overhead. |
|
||||
|
||||
---
|
||||
|
||||
## 4. `devDependencies`, justified
|
||||
|
||||
| Package | Version | Why |
|
||||
|---|---|---|
|
||||
| `@angular/cli` | `^22.2.1` | `ng serve`, `ng build`, `ng test`, `ng generate`, `ng update`. |
|
||||
| `@angular/build` | `^22.2.1` | The esbuild/Vite-based builders (`application`, `dev-server`, `unit-test`). Supports the `loader` option used to import `.glsl` shader files as strings. |
|
||||
| `@angular/compiler-cli` | `^22.2.1` | AOT compiler and `ngc`. Pins the supported TypeScript range (`>=6.0 <6.1`). |
|
||||
| `typescript` | `~6.0.3` | Language and type checker; **tilde-pinned to the supported minor** (see §0, finding 2). |
|
||||
| `tailwindcss`, `@tailwindcss/postcss`, `postcss` | see §3.3 | Styling pipeline. |
|
||||
| `prettier`, `prettier-plugin-tailwindcss` | `^3.9.9`, `^0.8.1` | Formatting and class sorting. |
|
||||
| `eslint`, `angular-eslint`, `typescript-eslint` | `^10.12.0`, `^22.5.0`, `^8.71.0` | Linting, including Angular template rules (`prefer-on-push-component-change-detection`, `prefer-signals`-style rules, `no-restricted-imports` to enforce the `shared ← core ← features` dependency rule). `typescript-eslint` supports TypeScript `<6.1`. |
|
||||
| `vitest`, `jsdom` | `^5.0.3`, `^30.1.2` | Unit/integration tests through `@angular/build:unit-test`. Used for the transition table, frame codec, PCM utilities, stores, and components. Worklet processors are tested by loading the class into a fake worklet scope. |
|
||||
| `@playwright/test` | `^1.63.0` | E2E: fake-microphone flags (`--use-fake-device-for-media-stream`), mock WebSocket gateway, and the "zero change-detection ticks" performance assertion. |
|
||||
| `@types/three`, `@types/papaparse`, `@types/audioworklet`, `@types/node` | see §2 | Type packages. `@types/node` is for config files and test tooling only. |
|
||||
|
||||
---
|
||||
|
||||
## 5. Deliberately excluded
|
||||
|
||||
| Package | Why it is not here |
|
||||
|---|---|
|
||||
| `autoprefixer` | Redundant with Tailwind v4 (§3.3). |
|
||||
| `lucide-angular` | Deprecated; conflicts with Angular 22 peers. Use `@lucide/angular`. |
|
||||
| `socket.io-client` | Needs a Socket.IO server; unnecessary overhead for raw PCM (§3.4). Optional only. |
|
||||
| `@ngrx/*` (Store, SignalStore) | The app has three small stores (`VoiceStateStore`, `FaqStore`, `AppSettingsStore`) with one writer each. Plain signals are sufficient and keep the zoneless story simple. Revisit if a fourth cross-feature store appears. |
|
||||
| `@angular/material` | Duplicates CDK + Tailwind and conflicts with the glassmorphic design language. |
|
||||
| `tone`, `howler`, `wavesurfer.js` | The app needs low-level PCM control through `AudioWorklet`; these add abstraction and bundle weight without helping. |
|
||||
| `@angular/animations` | Not used: state transitions are CSS (Tailwind) and shader uniforms. |
|
||||
| `lodash`, `moment`, `uuid` | Native `structuredClone`, `Intl`, and `crypto.randomUUID()` cover the need. |
|
||||
| `ngx-papaparse`, `ngx-socket-io` | Thin, often lagging wrappers. Our own services (`CsvParserService`, `WebSocketService`) are small and zoneless-safe. |
|
||||
| `three-stdlib`, `postprocessing` | Not needed for v1 (§3.2). |
|
||||
|
||||
---
|
||||
|
||||
## 6. Configuration these packages require
|
||||
|
||||
### 6.1 Tailwind v4 with the Angular build
|
||||
|
||||
`/.postcssrc.json` (project root, **not** inside `src/`):
|
||||
|
||||
```json
|
||||
{
|
||||
"plugins": {
|
||||
"@tailwindcss/postcss": {}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
`src/styles.css` starts with `@import "tailwindcss";` (full file in `SRC_STRUCTURE.md`). There is no `tailwind.config.js` and no `content` array; Tailwind v4 detects sources automatically.
|
||||
|
||||
### 6.2 `angular.json` fragments
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"projects": {
|
||||
"voice-faq-app": {
|
||||
"schematics": {
|
||||
// Keep ".component.ts" / ".service.ts" suffixes (Angular 20+ CLI omits them by default)
|
||||
"@schematics/angular:component": { "type": "component", "changeDetection": "OnPush", "style": "none", "skipTests": false },
|
||||
"@schematics/angular:directive": { "type": "directive" },
|
||||
"@schematics/angular:service": { "type": "service" }
|
||||
},
|
||||
"architect": {
|
||||
"build": {
|
||||
"builder": "@angular/build:application",
|
||||
"options": {
|
||||
"browser": "src/main.ts",
|
||||
"tsConfig": "tsconfig.app.json",
|
||||
"styles": ["src/styles.css"],
|
||||
// Zone phase only. Delete this line at the zoneless milestone:
|
||||
"polyfills": ["zone.js"],
|
||||
"assets": [
|
||||
{ "glob": "favicon.ico", "input": "src", "output": "/" },
|
||||
{ "glob": "**/*", "input": "src/assets", "output": "assets" }
|
||||
],
|
||||
// Import shader sources as strings: import vert from './orb.vert.glsl'
|
||||
"loader": { ".glsl": "text", ".vert": "text", ".frag": "text" }
|
||||
},
|
||||
"configurations": {
|
||||
"production": {
|
||||
"budgets": [
|
||||
{ "type": "initial", "maximumWarning": "250kB", "maximumError": "400kB" },
|
||||
{ "type": "anyComponentStyle", "maximumWarning": "4kB", "maximumError": "8kB" }
|
||||
],
|
||||
"outputHashing": "all",
|
||||
"fileReplacements": [
|
||||
{ "replace": "src/environments/environment.ts", "with": "src/environments/environment.production.ts" }
|
||||
]
|
||||
},
|
||||
"development": { "optimization": false, "extractLicenses": false, "sourceMap": true }
|
||||
}
|
||||
},
|
||||
"test": {
|
||||
"builder": "@angular/build:unit-test",
|
||||
"options": { "tsConfig": "tsconfig.spec.json", "runner": "vitest", "buildTarget": "::development" }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Notes:
|
||||
|
||||
- `src/assets` is copied verbatim and is **not hashed**. Worklet files are fetched by URL at runtime, so load them with a version query (`pcm-capture-processor.js?v=<buildId>`) or the browser may run a stale processor after a deploy.
|
||||
- The initial budget (`250 kB` warning) is what enforces lazy-loading of Three.js, AG Grid, and PapaParse.
|
||||
|
||||
### 6.3 AG Grid module registration (once, in the lazy `qa-grid` entry)
|
||||
|
||||
```ts
|
||||
// features/faq-manager/grid/register-grid-modules.ts
|
||||
import { AllCommunityModule, ModuleRegistry } from 'ag-grid-community';
|
||||
|
||||
let registered = false;
|
||||
export function registerGridModules(): void {
|
||||
if (registered) return;
|
||||
ModuleRegistry.registerModules([AllCommunityModule]);
|
||||
registered = true;
|
||||
}
|
||||
```
|
||||
|
||||
`AllCommunityModule` is the simplest correct start. Before production, replace it with only the modules you use (client-side row model, text editors, filters, row selection) following AG Grid's module-selection guide, to shrink the grid chunk. Theming uses AG Grid's JavaScript theme API, so **no AG Grid CSS imports** are needed in `styles.css`.
|
||||
|
||||
### 6.4 `tsconfig` essentials
|
||||
|
||||
```jsonc
|
||||
// tsconfig.json (excerpt)
|
||||
{
|
||||
"compilerOptions": {
|
||||
"strict": true,
|
||||
"noImplicitOverride": true,
|
||||
"noPropertyAccessFromIndexSignature": true,
|
||||
"noImplicitReturns": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"isolatedModules": true,
|
||||
"target": "ES2022",
|
||||
"module": "preserve",
|
||||
"moduleResolution": "bundler",
|
||||
"lib": ["ES2022", "dom", "dom.iterable"],
|
||||
"paths": {
|
||||
"@core/*": ["src/app/core/*"],
|
||||
"@features/*": ["src/app/features/*"],
|
||||
"@shared/*": ["src/app/shared/*"],
|
||||
"@env/*": ["src/environments/*"]
|
||||
}
|
||||
},
|
||||
"angularCompilerOptions": {
|
||||
"strictInjectionParameters": true,
|
||||
"strictInputAccessModifiers": true,
|
||||
"strictTemplates": true
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Add a one-line ambient declaration so shader imports type-check (`declare module '*.glsl' { const source: string; export default source; }`), kept in `src/app/core/audio/visualizer/shader-source.d.ts`.
|
||||
|
||||
### 6.5 Lazy-loading map (what must stay out of the initial bundle)
|
||||
|
||||
| Package | Loaded when | How |
|
||||
|---|---|---|
|
||||
| `three` | The voice page's orb mounts | `await import('three')` inside `ThreeOrbVisualizer.create()` |
|
||||
| `ag-grid-*` | The FAQ grid first renders | Route-level lazy feature + dynamic import in `QaGridComponent` |
|
||||
| `papaparse` | A CSV is dropped | `await import('papaparse')` inside `CsvParserService` |
|
||||
| `pdfjs-dist`, `mammoth` (if used) | The preview panel opens | Dynamic import in the preview component |
|
||||
| `@angular/cdk/overlay`, `/dialog` | The drawer or modal opens | Tree-shaken per entry point; opened through a small service |
|
||||
|
||||
---
|
||||
|
||||
## 7. Install & maintenance
|
||||
|
||||
```bash
|
||||
# 1. Runtime and tooling
|
||||
nvm install 24 && nvm use 24
|
||||
|
||||
# 2. Create the project (Angular 22), zoneless, no routing scaffolding conflicts
|
||||
npx @angular/cli@22 new voice-faq-app --style=css --routing --ssr=false
|
||||
cd voice-faq-app
|
||||
|
||||
# 3. Runtime dependencies
|
||||
npm i @angular/cdk@^22.2.1 @lucide/angular@^1.52.0 \
|
||||
ag-grid-angular@^36.2.0 ag-grid-community@^36.2.0 \
|
||||
papaparse@^5.7.0 three@~0.186.1
|
||||
|
||||
# 4. Dev dependencies
|
||||
npm i -D tailwindcss@^4.3.3 @tailwindcss/postcss@^4.3.3 postcss@^8.5.28 \
|
||||
@types/three@~0.186.0 @types/papaparse@^5.5.2 @types/audioworklet@^0.0.100 \
|
||||
prettier prettier-plugin-tailwindcss @playwright/test
|
||||
|
||||
# 5. Make sure TypeScript stayed in the supported range
|
||||
npm ls typescript # expect 6.0.x
|
||||
```
|
||||
|
||||
**Version policy**
|
||||
|
||||
- **Angular packages:** move together using `ng update @angular/core @angular/cli @angular/cdk` (never bump one alone).
|
||||
- **`three` and `@types/three`:** tilde-pinned; upgrade deliberately, one minor at a time, reading the migration notes and running the visual regression screenshot of each of the five orb states.
|
||||
- **AG Grid:** `ag-grid-community` and `ag-grid-angular` always share an identical version.
|
||||
- **Automation:** enable Renovate or Dependabot with groups (`angular`, `ag-grid`, `three`, `tailwind`, `tooling`) and require CI (lint, unit, E2E, bundle budgets) to pass.
|
||||
- **Audit:** `npm audit --omit=dev` in CI; fail on high severity in runtime dependencies.
|
||||
- **Lockfile:** commit `package-lock.json`; use `npm ci` in CI.
|
||||
@@ -0,0 +1,649 @@
|
||||
# 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).
|
||||
Reference in New Issue
Block a user