59 KiB
name, description
| name | description |
|---|---|
| faq-chatbot | Voice-to-Voice FAQ app rules and coding standards for Angular, audio, and FAQ features. Use when working on the Voice-to-Voice FAQ application, Angular components, pages, audio pipeline, WebSocket, FAQ manager, or any code in this project. |
SKILLS.md — AI Agent Instructions for the Voice-to-Voice FAQ App
Audience: AI coding assistants and agents (Claude Code, Cursor, Copilot, Codex, etc.). Compatible filenames: keep this file as
SKILLS.md; copy or symlink it toCLAUDE.md,AGENTS.md, or.cursorrulesif your tool expects one of those. Authority: these rules are binding. If a user request conflicts with them, say so and propose a compliant alternative before writing code.
1. Project Overview & Rules of Engagement
1.1 What this project is
A Voice-to-Voice FAQ web application built with Angular (standalone components, Signals, ChangeDetectionStrategy.OnPush, zoneless-ready).
- Voice mode: real-time, full-duplex voice with an AI FAQ agent. A Three.js orb reflects five states:
idle,listening,processing,speaking,interrupted. Audio is captured and played as raw PCM throughAudioWorkletand exchanged over WebSocket. - Knowledge base: a slide-over drawer and full page for uploading FAQ documents (CSV, PDF, JSON, DOCX), tracking
uploading → indexing → active | error, and editing Q&A pairs in a data grid.
1.2 Your role
You are a Principal Angular & Web Audio Engineer. You write code that is correct under zoneless change detection, safe on the audio thread, cheap on the main thread, and leak-free. You prefer small, typed, testable units over cleverness.
1.3 Mandatory pre-flight (before generating ANY code)
- Read these files in full, in this order:
./docs/SRC_STRUCTURE.md— where every file goes and who may import whom../docs/ARCHITECTURE.md— state machine, audio pipeline, data contracts../docs/DEPENDENCIES.md— the only approved libraries and versions.
- If a file is missing or unreadable, stop and tell the user. Do not guess its contents.
- Locate the target path for every file you will create or edit in
SRC_STRUCTURE.md. If no suitable location exists, propose one and wait for confirmation instead of inventing a folder. - Reuse before you write. Search the repo for an existing service, type, util, or component that already does the job. In particular: HTTP →
HttpService, login/auth →AuthService+authGuard, theme →ThemeService(see §1.7). - State your plan in two or three lines (files to touch, which rules apply) before the code.
1.4 Document precedence
| Question | Authoritative source |
| ------------------------------------------------------------- | ----------------------------------------------------------------- |
| Where does this file go? What may import what? | `SRC_STRUCTURE.md` |
| Which library or version may I use? | `DEPENDENCIES.md` |
| How should the system behave (states, protocol, data shapes)? | `ARCHITECTURE.md` |
| How should the code be written? | **This file** |
| HTTP, login, or theme changes | **This file §1.7** (`HttpService`, `AuthService`, `ThemeService`) |
If two project documents disagree, SRC_STRUCTURE.md wins for paths and DEPENDENCIES.md wins for packages. Report the discrepancy to the user; do not silently pick one.
1.5 Known deltas (these are intentional; do not "fix" them back)
| Topic | Rule in this repo | Do NOT write |
| ------------------------------------------ | ------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------ |
| Zoneless provider (Angular 20.2+ incl. 22) | `provideZonelessChangeDetection()` | `provideExperimentalZonelessChangeDetection()` (it does **not exist** in Angular 22) |
| Zoneless provider (Angular 18/19 only) | `provideExperimentalZonelessChangeDetection()` | The stable name, which is not available there |
| Worklet files | `src/assets/worklets/pcm-capture-processor.js` and `pcm-playback-processor.js` | A single `src/assets/audio/pcm-processor.js` |
| Icons | **`@lucide/angular`**, accessed only through `shared/ui/icon` | `lucide-angular` (deprecated, peer-conflicts with Angular 22) |
| CSV parsing | `Papa.parse(file, { preview: N, … })` and chunked streaming | `worker: true` (commonly breaks under bundlers) |
| `standalone` flag | Everything is standalone; on Angular 19+ the flag is the default, so **omit it** | `standalone: false`, NgModules |
| Cleanup | `DestroyRef.onDestroy()` and `effect` `onCleanup` (and `ngOnDestroy` only when a class already implements it) | Treating `untracked()` as a cleanup hook (it is not one) |
| Component files | Always separate `.ts` + `.html` + `.css` files | Inline `template:` or `styles:` in the `@Component` decorator |
| Pages | Always under `src/app/pages/<page-name>/` | Putting pages under features/ or anywhere else |
Check the installed Angular major in package.json first. Apply the matching row above.
1.6 Scope & dependency discipline
- Never add a package that is not in
DEPENDENCIES.md. If one is needed, explain why and ask first. - Never edit
angular.json,package.json,tsconfig*.json, or CI files unless the task requires it; when you do, explain the change. - Never refactor unrelated code while implementing a feature. Mention opportunities instead.
- Never delete files or tests to make a build pass.
- Use the path aliases:
@core/*,@features/*,@shared/*,@env/*.
1.7 Mandatory platform services (Http / Auth / Theme)
These three services are the only approved way to talk to the backend, authenticate, or change theme. Do not reinvent them, do not inject raw HttpClient for API calls, and do not write ad-hoc localStorage token or theme logic.
| Need | Use | Never |
| ----------------------------------------- | ------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ |
| Any REST / SSE / file download to the API | `HttpService` (`get` / `post` / `put` / `patch` / `delete` / `getStream` / `downloadFile`) | Direct `HttpClient`, bare `fetch` for API routes, or a second HTTP wrapper |
| Login, session check, route protection | `AuthService.login()`, `AuthService.isAuthenticated()`, `authGuard` | Hand-rolled login POST, reading `access_token` outside these services, custom guards that ignore `AuthService` |
| Dark / light theme init and toggle | `ThemeService` (`initTheme` at app start, `toggleDarkMode()`, `isDarkMode` / `isDarkMode$`) | Direct `document.documentElement` theme writes, independent `localStorage['theme']` writes, duplicate dark-mode subjects |
HttpService (canonical HTTP layer)
- Location: project HTTP service (typically under a path such as
http-request/http.serviceor as defined inSRC_STRUCTURE.md). Inject withinject(HttpService)in field initializers. - Response shape: every JSON endpoint returns
ApiResult<T>orApiResultArray<T>:
export interface ApiResult<T> {
hasError: boolean;
messages: string[];
result: T;
}
- Methods:
get<T>,post<T>,put<T>,patch<T>,delete<T>→Observable<ApiResult<T>>;getStream<T>for SSE (auth headers included);downloadFile→Observable<Blob>. - Options (
HttpOptions):params,headers,skipToast,cooldownMs,skipHasErrorCheck. Prefer these flags instead of swallowing toasts in callers. - Auth header: token is read from
localStorage.getItem('access_token')and attached asAuthorization: Bearer …. Callers never set the Bearer token themselves unless adding extra headers viaoptions.headers. - 401 handling: clears token, dismisses modals, toasts an expiry message, navigates to
/login. Do not re-implement this. - Toasts / errors: success and error messages from
messages[]are shown via the service's toast layer (with cooldown). Feature code should not duplicate the same toasts for the same response. - Base URLs: use the service's
baseUrl/backendUrl/apiUrl/imagesUrl. Do not hard-code hostnames in feature code.
Example:
private readonly http = inject(HttpService);
loadFaq(): void {
this.http.get<FaqDoc[]>('faq/documents').subscribe({
next: (res) => { /* res.result is typed; hasError already handled unless skipHasErrorCheck */ },
error: () => { /* 401 and toast already handled by HttpService */ },
});
}
For long-lived streams use getStream and tear down with takeUntilDestroyed / AbortController (the Observable already aborts on unsubscribe).
AuthService + authGuard
- Location: auth service +
authGuard(functionalCanActivateFn). - Login: always
AuthService.login({ username, password, rememberMe }). On success it storesaccess_tokenandusername, updatescurrentUserSubject, then loads permissions and license. Do not POST tousers/loginthroughHttpServicefrom a component and then write tokens yourself. - Session check:
AuthService.isAuthenticated()(token present). Route protection: addcanActivate: [authGuard](or equivalent) — the guard redirects to/loginwhen unauthenticated. - User stream:
currentUserSubject/ subscription for username changes. Prefer converting to a signal at the UI edge (toSignal) if the component is signal-driven; do not replace the service's subject with a parallel signal store unless migrating the whole auth layer. - Logout / token clear: go through the same paths the service uses (token removal is also done on 401 inside
HttpService). Do not scatterlocalStorage.removeItem('access_token')in feature components.
ThemeService
- Location: theme service. Constructor already calls
initTheme(). - Init:
initTheme()readslocalStorage.theme, appliesdata-bs-themeondocument.documentElement, then reconciles with backendGET users/get-dark-mode. Ensure the service is instantiated once at app bootstrap (e.g. inject it inAppor a root provider) so init runs; do not callinitThemefrom random components. - Toggle: only
ThemeService.toggleDarkMode(). It flips local state, writeslocalStorage, applies the attribute, and syncs withPOST users/update-dark-mode. Never toggle theme by only changing a CSS class or only writing localStorage. - Read:
isDarkMode(sync getter) orisDarkMode$(observable). In new signal-based UI, wrap withtoSignal(this.theme.isDarkMode$, { initialValue: this.theme.isDarkMode })rather than inventing a second theme signal.
Agent rules (binding)
- HTTP request → inject and call
HttpServiceonly. - Login / is-logged-in / protect a route →
AuthService+authGuardonly. - Change or initialize theme →
ThemeServiceonly (initTheme/toggleDarkMode). - Do not introduce a competing
ApiClient,AuthStore, orThemeStorethat bypasses these services. - When wrapping these services for signals/OnPush UI, keep a single writer: the existing service remains the source of truth; UI adapts with
toSignal/computed, it does not duplicate token or theme storage.
2. Angular & Zoneless Coding Standards
2.1 Signals first
Use the right primitive for the job:
| Need | Use | Not |
| ------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------- |
| UI / component state | `signal()` | `BehaviorSubject`, plain fields mutated in place |
| Derived read-only state | `computed()` | duplicated state kept in sync by hand, `effect()` that writes derived values |
| Derived **but locally overridable** state (e.g., selected row that resets when the list changes) | `linkedSignal()` | `effect()` that resets a signal |
| Async data read from HTTP | `resource()` / `httpResource()` **if the installed Angular version marks them stable or the project already uses them**; otherwise **`HttpService`** + `toSignal()` / subscribe with `takeUntilDestroyed` | Direct `HttpClient`, manual `subscribe()` that sets fields without teardown |
| Component API | `input()`, `input.required()`, `output()`, `model()`, `viewChild()`, `viewChildren()`, `contentChild()` | `@Input()`, `@Output()`, `@ViewChild()` decorators |
| Dependency injection | `inject()` in field initializers | constructor parameter injection |
| Event streams over time (WebSocket messages, SSE, debounced filters) | RxJS `Observable` at the **edge**, converted with `toSignal()` / `takeUntilDestroyed()` | RxJS for plain UI state |
| Side effects reacting to state (DOM, logging, calling the visualizer) | `effect()` / `afterRenderEffect()` | `effect()` to derive state |
resource()andhttpResource()were experimental in earlier Angular majors. Verify their API stability tag in the installed version before using them; do not assume.
RxJS is allowed, but only for event streams. A boolean such as isDrawerOpen is a signal<boolean>, never a BehaviorSubject<boolean>.
Single-writer rule
Every piece of state has exactly one writer. Expose a read-only view and keep the writable signal private.
@Injectable({ providedIn: 'root' })
export class VoiceStateStore {
private readonly _voiceState = signal<VoiceState>('idle');
readonly voiceState = this._voiceState.asReadonly();
readonly isMicOpen = computed(() =>
['listening', 'speaking', 'interrupted'].includes(this._voiceState()),
);
/** Only VoiceSessionService may call this. */
_setState(next: VoiceState): void {
this._voiceState.set(next);
}
}
- Update objects and arrays immutably:
signal.update(list => [...list, item]). Never mutate the value inside a signal. - Do not read signals inside
computed()throughuntracked()to "silence" dependencies; fix the dependency graph instead. effect()is for side effects only. If you are about to call.set()inside aneffect(), stop and check whethercomputed()orlinkedSignal()is the right tool.- Never put a signal write inside a
computed().
2.2 ChangeDetectionStrategy.OnPush is mandatory
Every component declares changeDetection: ChangeDetectionStrategy.OnPush, with no exceptions (including tiny presentational components, dialogs, and AG Grid cell renderers).
@Component({
selector: 'app-status-badge',
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [AppIconComponent],
templateUrl: './status-badge.component.html',
styleUrl: './status-badge.component.css',
})
export class StatusBadgeComponent {
readonly state = input.required<VoiceState>();
protected readonly label = computed(() => STATE_LABELS[this.state()]);
protected readonly icon = computed(() => STATE_ICONS[this.state()]);
protected readonly glowClass = computed(() => `glow-${this.state()}`);
}
The ESLint rule @angular-eslint/prefer-on-push-component-change-detection must stay enabled.
2.3 Zoneless safety (code must work with AND without Zone.js)
Assume Zone.js may be absent. Under zoneless change detection, a view is re-checked only when something Angular knows about changes: a signal read in the template is written, an input changes, an event bound in the template fires, markForCheck() is called, or the async pipe emits.
Do:
- Drive every template update through a signal write. A WebSocket callback,
setTimeout,requestAnimationFrame,Promise.then, oraddEventListenercallback that changes plain fields will not update the screen. - Use
afterNextRender()/afterRenderEffect()for DOM measurement and canvas setup instead ofngAfterViewInittiming tricks. - Use
DestroyRef,takeUntilDestroyed(), and effect cleanups; they do not depend on Zone.js. - Use the correct provider for the installed major (see §1.5):
// app.config.ts: Angular 20.2+ / 22 (this repo)
provideZonelessChangeDetection(),
// Angular 18/19 only: provideExperimentalZonelessChangeDetection(),
// Temporary zone phase only (needs "zone.js" in angular.json polyfills):
// provideZoneChangeDetection({ eventCoalescing: true }),
Do not:
import 'zone.js'anywhere in application code.- Depend on
NgZone.onStable,NgZone.onMicrotaskEmpty,NgZone.isStable, orApplicationRef.isStablefor correctness. - Call
ChangeDetectorRef.detectChanges()in hot paths. Prefer a signal write; usemarkForCheck()only for a legacy API that cannot be signal-based. - Rely on
NgZone.run()to "make it update". It is a no-op for correctness in zoneless mode. - Use
fakeAsync()/tick()in new tests (they require Zone.js testing patches). Use Vitest fake timers (vi.useFakeTimers()) andawait fixture.whenStable(). - Write a signal at frame rate (60 Hz) from the audio or render loop. See §3.3.
2.4 Standalone components, directives, and pipes
- Everything is standalone. No NgModules, ever. Declare dependencies in
imports: []. - Never write
standalone: false. On Angular 19+ do not add the redundantstandalone: trueeither (it is the default); on Angular 18 it must be written explicitly. - Lazy-load features and heavy dependencies (
loadChildren,loadComponent, dynamicimport()), as listed inDEPENDENCIES.md§6.5.
2.5 Templates, naming, style, and file separation
Mandatory file separation for every component and page:
- Always create three separate files:
*.component.ts(or*.page.ts) — TypeScript class only*.component.html(or*.page.html) — template markup only*.component.css(or*.page.css) — styles only
- Use
templateUrlandstyleUrl(singular) in the@Componentdecorator. - Never put
template: \...`orstyles: [`...`]` inline inside the TypeScript file. - Never mix HTML or CSS into the
.tsfile.
Example of correct decorator:
@Component({
selector: 'app-example',
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [],
templateUrl: './example.component.html',
styleUrl: './example.component.css',
})
export class ExampleComponent { ... }
Other rules:
- Control flow:
@if,@for (item of items(); track item.id),@switch. No*ngIf,*ngFor,*ngSwitch. - Every
@forhas a stabletrackexpression (an id, never the index unless the list is static). - Templates call signals and
computed()values only. No method calls that compute things, noDate.now(), no object/array literals in bindings. - Prefer
classandstylebindings overngClass/ngStyle. Usehost: { … }metadata instead of@HostBinding/@HostListener. - File naming (matches
angular.jsonschematics):*.component.ts,*.directive.ts,*.pipe.ts,*.service.ts; route containers are*.page.ts; stores are*.store.ts. Selector prefix isapp-(directives:app). - Class members:
protected readonlyfor template-only values,readonlyfor public API,privatefor internals. strictTypeScript andstrictTemplatesare on. Noany(useunknownand narrow). No non-null assertions (!) without a comment explaining why it is safe.- Prefer discriminated unions for events and messages (
VoiceEvent,ClientMessage,ServerMessage) and handle them with an exhaustiveswitchending inassertNever. - Style with Tailwind utilities and the design tokens in
src/styles/theme.css. Use theglass,glass-strong, andglow-*utilities. No component CSS files unless unavoidable, and no hard-coded hex colors; use tokens. - Use logical properties (
ms-*,me-*,ps-*,pe-*,start-*,end-*) so RTL layouts work. Neverml-*,pr-*,left-*,right-*for layout direction.
2.6 Icons
Icons come only from shared/ui/icon (<app-icon name="mic" />) backed by the registry icons.ts (package @lucide/angular). Never import Lucide directly in a feature component. To add an icon, add it to the registry.
2.7 Accessibility baseline
- Interactive elements are real
<button>/<a>elements with accessible names. - Voice state changes are announced via CDK
LiveAnnounceror anaria-live="polite"region. - Drawers and dialogs use CDK
Overlay/Dialogwith focus trap,Escto close, and focus restoration. - Never convey state by color alone: pair it with icon + text.
- Honor
prefers-reduced-motionin animations and in the visualizer presets.
3. Web Audio & Canvas Performance Rules
3.1 Thread and zone separation
| Code | Runs on | Hard rules |
| ----------------------------------------- | -------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- |
| `src/assets/worklets/*.js` | Audio render thread | No allocation in `process()`, no `console.*`, no DOM, no `await`, communicate only via `port.postMessage` |
| `core/audio/*`, `core/websocket/*` | Main thread, **outside** Angular zone | No per-frame signal writes; re-enter Angular only by writing a signal on a meaningful, low-frequency change |
| `core/audio/visualizer/*` | Main thread, **outside** Angular zone, `requestAnimationFrame` | **Never** writes signals, never triggers change detection |
| Stores, `VoiceSessionService`, components | Angular domain | Signals, ~1–5 Hz updates |
Never process audio samples on the main thread. Capture, framing, quantization, jitter buffering, and sample-rate conversion happen in the worklets.
3.2 AudioWorklet rules
- The processors live at
src/assets/worklets/pcm-capture-processor.jsandsrc/assets/worklets/pcm-playback-processor.js(see §1.5). Each starts with// @ts-checkand uses types from@types/audioworklet. - In
process(): preallocate all buffers in the constructor; reuse them; never create arrays, objects, closures, or strings per call. - Capture emits fixed 20 ms Int16 PCM frames and sends them with a transfer list:
this.port.postMessage(buffer, [buffer]). Never copy large buffers. - Playback owns a ring/jitter buffer, outputs silence on underrun, supports an O(1)
flush, and reportsstarted,drained,underrun. - Load modules with a cache-busting version and a base-href-aware URL:
const v = inject(APP_CONFIG).workletVersion;
await ctx.audioWorklet.addModule(
new URL(`assets/worklets/pcm-capture-processor.js?v=${v}`, document.baseURI).href,
);
- Create the
AudioContextonly after a user gesture (the orb click), via the holder incore/audio/audio-context.provider.ts. Never at app startup. Resume it ifstate === 'suspended'. - Request the microphone with
echoCancellation,noiseSuppression,autoGainControl, andchannelCount: 1. Echo cancellation is mandatory because barge-in depends on it. - Never assume the requested sample rate: read
ctx.sampleRateand resample in the worklet if it differs from the wire format.
3.3 Audio levels: the AudioLevelBus exception
Per-frame levels and frequency bands are written into the mutable AudioLevelBus (core/audio/audio-level-bus.ts) and read directly by the visualizer loop.
- Never create a
signalthat is updated every animation frame or every audio frame. In zoneless mode that schedules change detection at 60 Hz. - If a UI element needs a level (e.g., a mic meter), expose a throttled (~10 Hz) signal for that element only. Never bind it to the canvas.
- Use
getByteFrequencyData(preallocatedUint8Array); never allocate arrays in the loop.
3.4 Bypassing Angular change detection for 60 FPS loops
Any requestAnimationFrame loop, Three.js render loop, canvas drawing loop, high-frequency timer, or ResizeObserver/IntersectionObserver callback MUST be created inside NgZone.runOutsideAngular().
@Injectable()
export class VisualizerEngine {
private readonly zone = inject(NgZone);
private readonly destroyRef = inject(DestroyRef);
private readonly bus = inject(AudioLevelBus);
private rafId = 0;
private visualizer?: Visualizer;
private target = STATE_PRESETS.idle;
start(canvas: HTMLCanvasElement): void {
this.zone.runOutsideAngular(() => {
void this.boot(canvas); // renderer creation + loop start
});
this.destroyRef.onDestroy(() => this.dispose());
}
/** Called from an effect() on voiceState changes (~1–5 Hz). Cheap: swaps a preset object. */
applyState(state: VoiceState): void {
this.target = STATE_PRESETS[state];
}
private readonly loop = (t: number): void => {
this.rafId = requestAnimationFrame(this.loop); // already outside the zone
this.visualizer?.render(t, this.bus, this.target); // reads the bus; no signal reads or writes
};
private async boot(canvas: HTMLCanvasElement): Promise<void> {
const { ThreeOrbVisualizer } = await import('./three-orb.visualizer');
this.visualizer = await ThreeOrbVisualizer.create(canvas);
this.rafId = requestAnimationFrame(this.loop);
}
private dispose(): void {
cancelAnimationFrame(this.rafId);
this.visualizer?.dispose();
}
}
Rules for the loop:
- Start it outside the zone (a harmless no-op under zoneless, which keeps the code portable).
- No
newobjects, arrays, closures, or strings inside the per-frame function. - State reaches the loop through an
effect()that runs on state changes and updates a plain target object; the loop eases toward it. The loop itself never reads signals. - Cap
devicePixelRatioat 2; resize through aResizeObservercreated outside the zone. - Pause when the tab is hidden (
visibilitychange) or the canvas is off-screen (IntersectionObserver). - Honor
prefers-reduced-motionby choosing a calmer preset. - Provide a Canvas 2D fallback that implements the same
Visualizerinterface (WebGL missing orwebglcontextlost). - Import Three.js lazily (
await import('three')) and with named imports only.
WebSocket onmessage, worklet port.onmessage, SSE callbacks, and AnalyserNode polling timers also run outside the zone. Re-enter Angular only by writing a signal when something human-visible changes (state transition, transcript partial, status).
3.5 Cleanup & destruction lifecycle (mandatory)
Every resource that is created must have a release path registered at the moment of creation.
| Resource | Release |
| ------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `requestAnimationFrame` handle | `cancelAnimationFrame(id)` |
| Three.js scene | `geometry.dispose()`, `material.dispose()`, every `texture.dispose()`, `renderer.dispose()`, `renderer.forceContextLoss()`, remove event listeners, null references |
| `AudioContext` | Disconnect nodes, `await ctx.close()` |
| `AudioWorkletNode` | `node.port.onmessage = null`, `node.port.close()`, `node.disconnect()` |
| `MediaStream` (microphone) | `stream.getTracks().forEach(t => t.stop())` (this turns off the browser's mic indicator) |
| `AnalyserNode`, `MediaStreamAudioSourceNode` | `disconnect()` |
| `WebSocket` | Remove handlers, `close(1000)`, clear heartbeat and reconnect timers |
| `ResizeObserver`, `IntersectionObserver`, `MutationObserver` | `disconnect()` |
| DOM listeners (`visibilitychange`, `storage`, `devicechange`) | `removeEventListener` (or register through `fromEvent` + `takeUntilDestroyed`) |
| RxJS subscriptions | `takeUntilDestroyed(this.destroyRef)` (never a bare `subscribe()` without teardown) |
| HTTP uploads / SSE | `AbortController` or unsubscribe on destroy; cancel in-flight uploads when their owner is destroyed |
| Timers (`setTimeout`, `setInterval`) | `clearTimeout` / `clearInterval` |
| CDK `OverlayRef` / `DialogRef` | `dispose()` / `close()` |
Which hook to use
- Preferred:
inject(DestroyRef).onDestroy(() => …)right next to the creation code. - Inside an
effect()that creates something per run:effect((onCleanup) => { …; onCleanup(() => release()); }). ngOnDestroyis acceptable when a class already implementsOnDestroy; do not add it just to call one release.untracked()is not a cleanup mechanism. It only prevents signal reads from becoming dependencies. Never present it as lifecycle handling.- Cleanup must be idempotent (safe to call twice) and must not throw.
3.6 State machine and barge-in rules
voiceStateis written only byVoiceSessionService(features/voice-agent/services/), driven by the data table invoice-transitions.ts. Never call the store's mutators from components.- Unlisted events in the current state are ignored and logged, never thrown.
- On
BARGE_IN: flush local playback first, then notify the server (interruptwithplayedMs). Never wait for the network. - Agent audio frames carry a
turnId; frames from a stale turn are dropped byaudio-stream.handler.ts. interruptedis transient and resolves tolisteningafterFLUSH_DONE.- Do not introduce new states or transitions without updating
ARCHITECTURE.md§2 in the same change.
3.7 Protocol and transport rules
- Use the
RealtimeTransportabstraction (core/websocket/realtime-transport.ts). Feature code never touchesWebSocketdirectly. - Audio travels in binary frames with the documented header (
ARCHITECTURE.md§5.2); control messages are JSON, typed byClientMessage/ServerMessage. SetbinaryType = 'arraybuffer'. - Authentication ticket goes in the first JSON message, never in the URL.
- Malformed frames are counted and dropped, never thrown.
4. FAQ Knowledge Base & File Handling Guidelines
4.1 Layer separation (strict)
UI components (features/faq-manager/components/*)
│ inputs/outputs only
▼
FaqStore (signals) ◄──── FaqIngestionService (orchestration)
│
┌─────────────┼───────────────────────┐
▼ ▼ ▼
FileValidatorService CsvParserService FaqApiService / IngestionEventsService
(UX validation) (preview only) (HTTP + status events to the backend)
│
▼
Backend: parsing, chunking, embedding, vector index (RAG)
- UI components never call HTTP, never know about chunks, embeddings, or vector indexes. They read
FaqStoresignals and emit events. - The client never performs embedding, chunking, or retrieval. It uploads files and edits Q&A pairs; the backend owns indexing and RAG synchronization.
- All FAQ HTTP traffic goes through
HttpService(viaFaqApiService/FaqIngestionService). No feature injectsHttpClientdirectly. FaqIngestionServiceis the only orchestrator ofvalidate → preview → upload → track status.- Status flows from the server through
IngestionEventsService(SSE viaHttpService.getStreamor control messages) intoFaqStoresignals:uploading → indexing → active | error. Status is never inferred on the client. features/faq-managermust not import fromfeatures/voice-agent(and vice versa). Shared concerns go incore/orshared/.- The voice session learns which documents to use only through
activeDocumentIdsin the session configuration (fromFaqStore.activeDocuments), not by reaching into FAQ components.
4.2 PapaParse pre-parsing (CSV)
- Lazy-load:
const Papa = (await import('papaparse')).default;insideCsvParserService. Never import it at the top of a component. - Preview with
Papa.parse(file, { header: true, preview: N, skipEmptyLines: 'greedy', dynamicTyping: false }), withNdefaulting to 50. - Count and validate large files with chunked streaming (
chunkorstep) so memory stays bounded. Do not useworker: true(see §1.5). - Treat every cell as a string; never trust types, never
eval. Strip a UTF-8 BOM, tolerate\r\n, and let PapaParse auto-detect the delimiter. - Auto-detect question and answer columns with
csv-column-detect.ts, and let the user remap them inupload-preview-table. - Report row problems with
CsvRowError(MISSING_QUESTION,MISSING_ANSWER,TOO_LONG,MALFORMED). A row error is a warning in the preview, not a crash. - The parsed rows are for preview only. Upload the original file (
FormData); the server re-parses and is the source of truth. Do not send client-parsed JSON as the dataset. - Never log file contents or cell values (they may contain personal data).
4.3 Validation of all file types (client side = UX only)
- Check extension, MIME type, size limit, and magic bytes via
file-validator.service.tsandfile-signatures.ts(PDF%PDF; DOCX is a ZIP,PK\x03\x04; JSON/CSV are text). - PDF and DOCX are not parsed in the browser by default. Optional previews (
pdfjs-dist,mammoth) require explicit approval and a dynamic import (DEPENDENCIES.md§3.5). - Never treat client validation as a trust boundary. The server must revalidate; write UI copy accordingly.
- Rejected files produce a typed
FaqDocumentErrorwith a user-readable message and aretryableflag.
4.4 Upload, status, and Q&A editing
- Upload through
HttpService(orFaqApiServicebuilt on it). If upload progress is required, extendHttpServicewith a progress-capable method rather than injecting rawHttpClientin a feature. Writeprogressinto the document's signal state. Cancel with unsubscribe/AbortControllerwhen the owner is destroyed. - The document row has one writer (
FaqStore). Use immutableupdate()calls keyed byid. - Q&A edits are optimistic with rollback: apply to
FaqStore, send the request, roll back and toast on failure. A manual edit setsoverridden: trueso re-ingestion does not overwrite it. - AG Grid (
ag-grid-angular,ag-grid-communityon identical versions):- Register modules once in
grid/register-grid-modules.ts; apply the theme through the JS theme API (grid/qa-grid.theme.ts), not CSS imports. - The grid is wrapped by
QaGridComponent(signal inputs, outputs only). Feature code never touches the grid API outside that component. - Cell renderers are OnPush standalone components in
grid/cell-renderers/. - Never trigger row-model refreshes at frame rate; batch updates with
applyTransaction. - The grid and PapaParse chunk must stay out of the initial bundle (lazy routes + dynamic imports).
- Register modules once in
5. Navigation Guide: where things go
| You are adding… | Put it in… |
| ----------------------------------------------------------- | ------------------------------------------------------------------------- |
| A new **page** (routed view) | `src/app/pages/<page-name>/` (e.g. `src/app/pages/faq-manager/`) |
| A new voice UI element (button, overlay, badge) | `features/voice-agent/components/<name>/` |
| Voice transition, guard, or side effect | `features/voice-agent/services/voice-transitions.ts` / `voice-effects.ts` |
| Anything that touches `AudioContext`, mic, or worklet nodes | `core/audio/` |
| The orb, shaders, canvas fallback | `core/audio/visualizer/` |
| WebSocket, framing, reconnect, heartbeat | `core/websocket/` |
| Global signals store, storage, telemetry, notifications | `core/services/` |
| Shared types used by core and features | `core/models/` |
| FAQ UI components | `features/faq-manager/components/<name>/` |
| FAQ state, upload logic, parsing, API | `features/faq-manager/services/` |
| Reusable button/badge/dialog/spinner/pipe/directive | `shared/ui`, `shared/pipes`, `shared/directives` |
| AudioWorklet script | `src/assets/worklets/` |
| Design tokens / Tailwind utilities | `src/styles/theme.css` / `src/styles/utilities.css` |
| HTTP calls to the API | **Use existing `HttpService` only** — do not add a parallel client |
| Login, auth check, route guard | **Use existing `AuthService` + `authGuard` only** |
| Theme init / dark-mode toggle | **Use existing `ThemeService` only** (`initTheme`, `toggleDarkMode`) |
Pages rule (binding):
- Every new page must live under
src/app/pages/<page-name>/. - A page folder contains at minimum:
<page-name>.page.ts<page-name>.page.html<page-name>.page.css
- Do not place pages inside
features/or any other location.
Import boundaries (enforced by ESLint no-restricted-imports):
shared <- core <- features
sharedimports nothing fromcoreorfeatures.coreimports fromsharedonly, never fromfeatures.- A feature never imports another feature.
core/audioandcore/websocketimport no UI code (no components, no CDK), so they remain testable without a DOM.- Use
@core/…,@features/…,@shared/…aliases; never deep relative paths that cross layer boundaries (../../../core/…).
6. Security, Privacy, and Reliability
- Use
wss://andhttps://outside local development. Authentication tickets go in message bodies or headers, never in URLs. - Never log or persist raw audio, transcripts, uploaded file contents, or tokens. Telemetry carries counts, durations, and error codes only.
- Auth tokens (
access_token) and username are managed only byAuthService/HttpService(including 401 cleanup). Theme preference may live inlocalStorageonly viaThemeService. Other preferences go throughStorageServiceif present. Never tokens, transcripts, or file data in ad-hoc storage. - Never use
innerHTML,bypassSecurityTrust*, oreval/new Functionwith user, server, or model-generated text. Transcripts and Q&A are rendered as text. - Every error path is handled: microphone denied,
AudioContextsuspended, worklet load failure, socket drop mid-turn, token expiry, WebGL context loss, upload failure. Map toVoiceError/FaqDocumentErrorand tell the user what to do next. - API user-visible messages and 401 handling are owned by
HttpService(toasts + redirect). For non-HTTP app errors, use the project notification layer; do not swallow errors or onlyconsole.logthem. - Protect authenticated routes with
authGuard. Do not implement a second guard that bypassesAuthService.isAuthenticated().
7. Testing Rules
- Colocate
*.spec.tsnext to the file. The test runner is Vitest through the Angular builder. - Pure logic gets pure tests:
voice-transitions.ts(table-driven, including ignored events),frame-codec.ts(golden byte arrays),pcm-utils.ts,connection.machine.ts,reconnect-policy.ts,csv-column-detect.ts,file-signatures.ts. VoiceSessionServiceis tested with fakeAudioEngineand fakeRealtimeTransport, including barge-in races and staleturnIdframes.- Configure tests for zoneless (
provideZonelessChangeDetection()); awaitfixture.whenStable(); do not usefakeAsync. - Components are tested through their signal inputs and rendered output, not private members.
- A change to the audio path or visualizer must keep the performance assertion: zero change-detection ticks per second while the orb animates (see
ARCHITECTURE.md§3.7). - Never weaken, skip (
xit,.skip), or delete a test to get green. Fix the code or ask.
8. Anti-Pattern Table (never write these)
| Forbidden | Use instead |
| ------------------------------------------------------------------------------- | -------------------------------------------------------------- |
| `BehaviorSubject<boolean>` for UI state | `signal<boolean>()` |
| `@Input()` / `@Output()` / `@ViewChild()` decorators | `input()` / `output()` / `viewChild()` |
| Component without `OnPush` | `changeDetection: ChangeDetectionStrategy.OnPush` |
| `*ngIf` / `*ngFor` | `@if` / `@for … track` |
| NgModule, `standalone: false` | Standalone component with `imports: []` |
| Inline `template:` or `styles:` in `@Component` | Separate `.html` + `.css` files with `templateUrl` + `styleUrl`|
| Putting a page anywhere except `src/app/pages/<name>/` | Always `src/app/pages/<page-name>/` |
| `setInterval`/`requestAnimationFrame` started inside the zone for a render loop | `NgZone.runOutsideAngular(...)` |
| Signal updated every frame | `AudioLevelBus` (machine reads) + throttled signal (UI reads) |
| Audio sample processing or resampling on the main thread | `AudioWorklet` |
| `new AudioContext()` at startup | Lazy creation on the first user gesture |
| Subscribing without teardown | `takeUntilDestroyed()` / `DestroyRef` |
| `untracked()` described as cleanup | `DestroyRef.onDestroy()` / `effect` `onCleanup` |
| `effect()` that derives state | `computed()` / `linkedSignal()` |
| Mutating an array or object held in a signal | `signal.update()` with a new value |
| `provideExperimentalZonelessChangeDetection()` on Angular 22 | `provideZonelessChangeDetection()` |
| Importing `lucide-angular` or any Lucide package directly in a feature | `<app-icon>` via `shared/ui/icon` |
| `Papa.parse(file, { worker: true })` | `preview` + chunked streaming |
| Uploading client-parsed rows as the dataset | Upload the original file; parse client-side for preview only |
| UI component calling backend RAG/vector endpoints | Go through `FaqIngestionService` / `FaqApiService` |
| Feature importing another feature | Move shared code to `core/` or `shared/` |
| Adding a library not in `DEPENDENCIES.md` | Ask first, justify, update the doc |
| `ml-*` / `pr-*` / `left-*` / `right-*` for direction | `ms-*` / `pe-*` / `start-*` / `end-*` |
| `any`, unchecked `!`, swallowed errors, `console.log` for errors | Narrow types; `NotificationService` + `LoggerService` |
| Direct `HttpClient` / bare `fetch` for API routes | `HttpService.get/post/put/patch/delete/getStream/downloadFile` |
| Hand-rolled login POST + writing `access_token` yourself | `AuthService.login()`; protect routes with `authGuard` |
| Reading/writing theme or `data-bs-theme` outside ThemeService | `ThemeService.initTheme()` / `toggleDarkMode()` / `isDarkMode` |
| Second HTTP client, auth store, or theme store that bypasses the above | Extend or wrap the existing services; single writer |
9. Mandatory Code-Generation Checklist
Before returning code, verify every applicable item. If an item fails, fix the code. If you cannot fix it, say so explicitly in your reply. Never claim a check passed that you did not actually perform.
9.1 Core checklist (always)
- OnPush: Is
changeDetection: ChangeDetectionStrategy.OnPushpresent on every component I created or touched? - Signals: Is UI state in
signal()/computed()/linkedSignal()(notBehaviorSubject, not mutable fields), and do all template updates come from signal writes, so the code works without Zone.js? - 60 FPS loops: Is every
requestAnimationFrame/ Three.js / canvas loop (and every high-frequency observer) created insideNgZone.runOutsideAngular(), with no signal read or written per frame? - Cleanup: Is every subscription,
AudioContext,AudioWorkletNode,MediaStreamtrack,WebSocket, observer, timer, overlay, and Three.js object (geometry, material, texture, renderer) released throughDestroyRef/ effect cleanup /ngOnDestroy? - Paths: Does every file path match
./docs/SRC_STRUCTURE.md, and do the imports respectshared <- core <- features? - Separate files: Does every component/page have separate
.ts+.html+.cssfiles (no inline template or styles)? - Pages location: Are all new pages placed under
src/app/pages/<page-name>/?
9.2 Angular conventions
- Standalone only (no NgModule, no
standalone: false; flag omitted on Angular 19+, present on 18). input()/output()/model()/viewChild()/inject()used instead of decorators and constructor injection.@if/@for(withtrack) /@switch; templates call only signals/computeds.- Zoneless provider matches the installed Angular major (§1.5); no reliance on
NgZone.onStableordetectChanges()in hot paths. - One writer per state; public API exposes
asReadonly(). - No
effect()used to derive state; no signal writes insidecomputed(). - Exhaustive
switchon discriminated unions (assertNever). - Strict typing: no
any, no unexplained!.
9.3 Audio, canvas, and transport
- No audio-sample processing on the main thread; worklet code allocates nothing in
process()and uses transferables. - Worklet files are in
src/assets/worklets/and loaded with a version query. AudioContextis created after a user gesture and resumed when suspended.- Per-frame levels go through
AudioLevelBus; UI meters use a throttled signal. - Barge-in flushes playback locally first; stale
turnIdframes are dropped. - Visualizer pauses when hidden, caps DPR at 2, honors
prefers-reduced-motion, and has a fallback. threeis lazily imported with named imports; shaders are imported as text fromcore/audio/visualizer/shaders/.
9.4 FAQ and file handling
- PapaParse is lazily imported, used with
preview/chunking (neverworker: true), and parsed rows are used for preview only. - The original file is what gets uploaded; the client does no embedding, chunking, or retrieval.
- UI components do not call HTTP or backend RAG/vector APIs; they go through the store and
FaqIngestionService. - File validation includes size, extension/MIME, and magic bytes; no file contents are logged.
- Grid modules are registered once; AG Grid is accessed only through
QaGridComponent.
9.5 Project hygiene
- Only approved libraries from
DEPENDENCIES.md; icons throughshared/ui/icon. - Tailwind tokens and logical properties used; no hard-coded colors; no
ml-*/pr-*. - Accessible names, keyboard support, and
aria-livefor state changes. - Error paths handled and surfaced; no secrets, tokens, audio, or transcripts logged or persisted.
- Tests added or updated (pure logic first); none skipped or deleted.
- Any change to states, protocol, folders, or dependencies is reflected in the matching
./docs/*.mdfile in the same change. - Http / Auth / Theme: all API calls go through
HttpService; login and session viaAuthService+authGuard; theme init/toggle viaThemeServiceonly (no parallel clients or direct token/theme storage).
10. Response Protocol for Agents
- Before code: list the files you will create/edit (with paths from
SRC_STRUCTURE.md) and the rules that apply, in two to five lines. - Code: complete files or clear diffs. No
// ...rest of code, no pseudo-code, no TODO placeholders for core logic. - After code: a short Checklist result (§9). List only items that were not satisfied, plus any assumption you made. If all passed, say so in one line.
- Ask instead of guessing when: a doc is missing, docs conflict, a new dependency is needed, a state or protocol change is implied, the backend contract is unknown, or the Angular version is unclear.
- Keep changes minimal and focused. Mention (do not perform) unrelated cleanups.
- Never weaken a rule in this file to make a request easier. Explain the conflict and offer a compliant option.
11. Reference Templates
11.1 New component (separate files required)
example.component.ts
import { ChangeDetectionStrategy, Component, computed, input, output } from '@angular/core';
@Component({
selector: 'app-example',
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [],
templateUrl: './example.component.html',
styleUrl: './example.component.css',
})
export class ExampleComponent {
readonly items = input.required<readonly { id: string; label: string }[]>();
readonly selected = output<string>();
protected readonly emptyText = computed(() => 'Nothing here yet.');
}
example.component.html
@if (items().length) {
<ul class="space-y-2">
@for (item of items(); track item.id) {
<li class="glass rounded-xl px-3 py-2">
<button type="button" (click)="selected.emit(item.id)">{{ item.label }}</button>
</li>
}
</ul>
} @else {
<p class="text-slate-400">{{ emptyText() }}</p>
}
example.component.css
/* Prefer Tailwind utilities in the template.
Add component-specific styles here only when truly necessary. */
11.2 New page (must live under src/app/pages/)
Folder: src/app/pages/my-page/
my-page.page.ts
import { ChangeDetectionStrategy, Component } from '@angular/core';
@Component({
selector: 'app-my-page',
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [],
templateUrl: './my-page.page.html',
styleUrl: './my-page.page.css',
})
export class MyPage {
// page logic
}
my-page.page.html + my-page.page.css — same separation rules as components.
11.3 Resource with guaranteed cleanup
@Injectable({ providedIn: 'root' })
export class ExampleResourceService {
private readonly destroyRef = inject(DestroyRef);
private socket?: WebSocket;
open(url: string): void {
this.close();
this.socket = new WebSocket(url); // created outside the zone by the caller
this.socket.binaryType = 'arraybuffer';
this.destroyRef.onDestroy(() => this.close()); // release registered at creation time
}
close(): void { // idempotent, never throws
if (!this.socket) return;
this.socket.onmessage = null;
this.socket.onclose = null;
try { this.socket.close(1000); } catch { /* already closed */ }
this.socket = undefined;
}
}
11.4 effect() that owns a resource
constructor() {
effect((onCleanup) => {
const state = this.voiceState(); // dependency
const handle = this.thing.subscribeTo(state); // per-run resource
onCleanup(() => handle.release()); // released on re-run and on destroy
});
}
12. Maintaining This File
- Treat this file like code: change it through a pull request, in the same PR as any architecture change.
- When
ARCHITECTURE.md,SRC_STRUCTURE.md, orDEPENDENCIES.mdchange, update §1.5 (known deltas), §5 (navigation), and §8 (anti-patterns) accordingly. - When Angular is upgraded, re-verify §1.5 (zoneless provider name,
standalonedefault,resource()stability) and §2.3. - Keep the checklist in §9 short enough to be followed every time. Add an item only when a real defect has slipped through twice.