--- name: faq-chatbot description: 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 to `CLAUDE.md`, `AGENTS.md`, or `.cursorrules` if 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 through `AudioWorklet` and 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) 1. **Read** these files in full, in this order: 1. `./docs/SRC_STRUCTURE.md` — where every file goes and who may import whom. 2. `./docs/ARCHITECTURE.md` — state machine, audio pipeline, data contracts. 3. `./docs/DEPENDENCIES.md` — the **only** approved libraries and versions. 2. **If a file is missing or unreadable, stop and tell the user.** Do not guess its contents. 3. **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. 4. **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). 5. **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//` | 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.service` or as defined in `SRC_STRUCTURE.md`). Inject with `inject(HttpService)` in field initializers. - **Response shape:** every JSON endpoint returns `ApiResult` or `ApiResultArray`: ```ts export interface ApiResult { hasError: boolean; messages: string[]; result: T; } ``` - **Methods:** `get`, `post`, `put`, `patch`, `delete` → `Observable>`; `getStream` for SSE (auth headers included); `downloadFile` → `Observable`. - **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 as `Authorization: Bearer …`. Callers never set the Bearer token themselves unless adding extra headers via `options.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: ```ts private readonly http = inject(HttpService); loadFaq(): void { this.http.get('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` (functional `CanActivateFn`). - **Login:** always `AuthService.login({ username, password, rememberMe })`. On success it stores `access_token` and `username`, updates `currentUserSubject`, then loads permissions and license. Do not POST to `users/login` through `HttpService` from a component and then write tokens yourself. - **Session check:** `AuthService.isAuthenticated()` (token present). Route protection: add `canActivate: [authGuard]` (or equivalent) — the guard redirects to `/login` when 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 scatter `localStorage.removeItem('access_token')` in feature components. #### ThemeService - **Location:** theme service. Constructor already calls `initTheme()`. - **Init:** `initTheme()` reads `localStorage.theme`, applies `data-bs-theme` on `document.documentElement`, then reconciles with backend `GET users/get-dark-mode`. Ensure the service is instantiated once at app bootstrap (e.g. inject it in `App` or a root provider) so init runs; do not call `initTheme` from random components. - **Toggle:** only `ThemeService.toggleDarkMode()`. It flips local state, writes `localStorage`, applies the attribute, and syncs with `POST users/update-dark-mode`. Never toggle theme by only changing a CSS class or only writing localStorage. - **Read:** `isDarkMode` (sync getter) or `isDarkMode$` (observable). In new signal-based UI, wrap with `toSignal(this.theme.isDarkMode$, { initialValue: this.theme.isDarkMode })` rather than inventing a second theme signal. #### Agent rules (binding) 1. **HTTP request** → inject and call `HttpService` only. 2. **Login / is-logged-in / protect a route** → `AuthService` + `authGuard` only. 3. **Change or initialize theme** → `ThemeService` only (`initTheme` / `toggleDarkMode`). 4. Do **not** introduce a competing `ApiClient`, `AuthStore`, or `ThemeStore` that bypasses these services. 5. 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()` and `httpResource()` 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`, never a `BehaviorSubject`. #### Single-writer rule Every piece of state has **exactly one writer**. Expose a read-only view and keep the writable signal private. ```ts @Injectable({ providedIn: 'root' }) export class VoiceStateStore { private readonly _voiceState = signal('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()` through `untracked()` to "silence" dependencies; fix the dependency graph instead. - `effect()` is for side effects only. If you are about to call `.set()` inside an `effect()`, stop and check whether `computed()` or `linkedSignal()` 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). ```ts @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(); 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`, or `addEventListener` callback that changes plain fields will **not** update the screen. - Use `afterNextRender()` / `afterRenderEffect()` for DOM measurement and canvas setup instead of `ngAfterViewInit` timing 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): ```ts // 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`, or `ApplicationRef.isStable` for correctness. - Call `ChangeDetectorRef.detectChanges()` in hot paths. Prefer a signal write; use `markForCheck()` 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()`) and `await 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 redundant `standalone: true` either (it is the default); on Angular 18 it **must** be written explicitly. - Lazy-load features and heavy dependencies (`loadChildren`, `loadComponent`, dynamic `import()`), as listed in `DEPENDENCIES.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 `templateUrl` and `styleUrl` (singular) in the `@Component` decorator. - **Never** put `template: \`...\`` or `styles: [\`...\`]` inline inside the TypeScript file. - **Never** mix HTML or CSS into the `.ts` file. Example of correct decorator: ```ts @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 `@for` has a stable `track` expression (an id, never the index unless the list is static). - Templates call **signals and `computed()` values only**. No method calls that compute things, no `Date.now()`, no object/array literals in bindings. - Prefer `class` and `style` bindings over `ngClass` / `ngStyle`. Use `host: { … }` metadata instead of `@HostBinding` / `@HostListener`. - File naming (matches `angular.json` schematics): `*.component.ts`, `*.directive.ts`, `*.pipe.ts`, `*.service.ts`; route containers are `*.page.ts`; stores are `*.store.ts`. Selector prefix is `app-` (directives: `app`). - Class members: `protected readonly` for template-only values, `readonly` for public API, `private` for internals. - `strict` TypeScript and `strictTemplates` are on. No `any` (use `unknown` and 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 exhaustive `switch` ending in `assertNever`. - Style with **Tailwind utilities** and the design tokens in `src/styles/theme.css`. Use the `glass`, `glass-strong`, and `glow-*` 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. Never `ml-*`, `pr-*`, `left-*`, `right-*` for layout direction. ### 2.6 Icons Icons come **only** from `shared/ui/icon` (``) 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 ` } } @else {

{{ emptyText() }}

} ``` **`example.component.css`** ```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`** ```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 ```ts @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 ```ts 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`, or `DEPENDENCIES.md` change, update §1.5 (known deltas), §5 (navigation), and §8 (anti-patterns) accordingly. - When Angular is upgraded, re-verify §1.5 (zoneless provider name, `standalone` default, `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.