48 KiB
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
- System Overview & High-Level Architecture
- State Machine Specification
- Audio Pipeline & Performance Strategy
- Folder Structure & Component Breakdown
- Data Contracts & Types
- Cross-Cutting Concerns
- Architecture Decision Records (summary)
- Open Questions
- 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
- 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.
- 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.
- Transport is dumb, the state machine is smart. The WebSocket service emits typed events; only
VoiceSessionServicedecides what they mean. - One writer per state. Each signal has exactly one service that writes it and exposes a read-only view (
asReadonly()). - Everything disposable. Every
AudioContext,MediaStream,WebSocket,WebGLRenderer, andrequestAnimationFramehandle is released throughDestroyRef.
1.3 High-level data flow
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 —
interruptedis transient. It is a real state (so the UI, analytics, and tests can observe it), but it always resolves tolisteningautomatically 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
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 whoseturnId≠ 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:
// 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
// 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]); }
}
// 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)
getUserMedia({ audio: { echoCancellation: true, noiseSuppression: true, autoGainControl: true, channelCount: 1 } }). Echo cancellation is mandatory; barge-in duringspeakingdepends on it.- Create
AudioContext({ latencyHint: 'interactive', sampleRate: 16000 }). Browsers may ignore the requested rate — always readctx.sampleRateand let the worklet resample to the wire rate if they differ. MediaStreamAudioSourceNode→AudioWorkletNode('capture-processor'). The same source also feeds anAnalyserNode(fftSize = 256,smoothingTimeConstant = 0.8) for visuals.- In
process(), copy 128-sample render quanta into a preallocated accumulator. Every 20 ms (320 samples @ 16 kHz) convert Float32 → Int16 little-endian andport.postMessage(buffer, [buffer])(transfer, don't copy). Use a small pool of ArrayBuffers recycled via a return message to avoid GC churn. - The main thread forwards each frame to
WebSocketService.sendAudio()as a binary message (header + payload, see §5.2). No per-frame Angular involvement.
// 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)
WebSocketServicereceives binary frames (outside the zone), validates the header, drops staleturnIds, and transfers the PCM payload toplayback-processorviaport.postMessage.playback-processorowns 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).- 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.
- Flush (
{type:'flush'}) resets read/write pointers in O(1) — this is what makes barge-in feel instant. - Playback node →
AnalyserNode(output) →ctx.destination. The analyser feedsAudioLevelBus.outputBands. - When the server sends
turn.end, the worklet reports{type:'drained'}once the ring buffer empties; only then does the engine emitAGENT_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.
// 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:
- Create the renderer and start the loop inside
NgZone.runOutsideAngular. (Under zoneless this is a harmless no-op, so the code is portable.) - Wire sockets and worklet
port.onmessageoutside 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. - 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. - Reuse everything per frame: no
newobjects, no array allocation, no string building in the loop. UsegetByteFrequencyData(prealloc). - 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). - Pause when not visible:
document.visibilitychangeandIntersectionObserverstop the loop and suspend analyser polling. prefers-reduced-motion: switch to a reduced preset (no turbulence, slower easing).- WebGL fallback: on
webglcontextlostor no WebGL, swap to aCanvas2DVisualizerimplementing the sameVisualizerinterface (ring of bars/radial waveform). - Template side: the canvas host component is
OnPush, has no bindings that change per frame, and exposes the canvas viaviewChild.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
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 fromassets/. 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 stabilizedprovideZonelessChangeDetection(). Keep Zone.js inpolyfillsuntil 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/audioandcore/websocketnever import Angular UI. - Smart vs dumb:
*.page.tsand services are smart; everything incomponents/isOnPush, input/output driven, with no service injection except forvisualizerhosts 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)
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
// 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) |
// 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
AudioFormats insession.ready; the client configures worklets from that response. interrupt.playedMslets the server truncate the conversation history to what the user actually heard.- Heartbeat: client
pingevery 15 s; nopongwithin 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
// 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
// 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)
@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 withconnect-srcrestricted to the API/gateway hosts andworker-src/script-srcallowing 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-Policyheaders are only required ifSharedArrayBufferring 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) anddir-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:
- Audio formats: does the gateway accept 16 kHz PCM16 in and emit 24 kHz PCM16 out (assumed here), or Opus?
- VAD ownership: server VAD only, or both? What are the end-of-utterance silence defaults, and is the threshold configurable per session?
- Barge-in semantics: does the server stop TTS on
interrupt, or only on its own VAD? (The client protocol sends both.) - Ingestion status channel: SSE or reuse of the realtime WebSocket? (The types support either.)
- Grid scale: expected maximum Q&A pairs per knowledge base — this decides between client-side filtering and AG Grid's server-side row model.
- Locales: which languages and writing directions must the voice and the UI support at launch?
- 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.mdnext, or tell me which file you'd like first.