first commit

This commit is contained in:
PeymanHonarjoo
2026-10-06 09:57:33 +03:30
parent fe4dfeb2ec
commit 268a431c1e
48 changed files with 10443 additions and 1782 deletions
+705
View File
@@ -0,0 +1,705 @@
# 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) |
**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<T>` or `ApiResultArray<T>`:
```ts
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 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<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` (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<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.
```ts
@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()` 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],
template: `
<span class="glass inline-flex items-center gap-2 rounded-full px-3 py-1" [class]="glowClass()">
<app-icon [name]="icon()" />
{{ label() }}
</span>
`,
})
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`, 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, and style
- 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` (`<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 `LiveAnnouncer` or an `aria-live="polite"` region.
- Drawers and dialogs use CDK `Overlay` / `Dialog` with focus trap, `Esc` to close, and focus restoration.
- Never convey state by color alone: pair it with icon + text.
- Honor `prefers-reduced-motion` in 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.js` and `src/assets/worklets/pcm-playback-processor.js` (see §1.5). Each starts with `// @ts-check` and 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 reports `started`, `drained`, `underrun`.
- Load modules with a **cache-busting version** and a base-href-aware URL:
```ts
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 `AudioContext` **only after a user gesture** (the orb click), via the holder in `core/audio/audio-context.provider.ts`. Never at app startup. Resume it if `state === 'suspended'`.
- Request the microphone with `echoCancellation`, `noiseSuppression`, `autoGainControl`, and `channelCount: 1`. Echo cancellation is mandatory because barge-in depends on it.
- Never assume the requested sample rate: read `ctx.sampleRate` and 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 `signal` that 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()`.
```ts
@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:
1. Start it **outside** the zone (a harmless no-op under zoneless, which keeps the code portable).
2. **No** `new` objects, arrays, closures, or strings inside the per-frame function.
3. 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.
4. Cap `devicePixelRatio` at 2; resize through a `ResizeObserver` created outside the zone.
5. **Pause** when the tab is hidden (`visibilitychange`) or the canvas is off-screen (`IntersectionObserver`).
6. Honor `prefers-reduced-motion` by choosing a calmer preset.
7. Provide a **Canvas 2D fallback** that implements the same `Visualizer` interface (WebGL missing or `webglcontextlost`).
8. 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()); })`.
- `ngOnDestroy` is acceptable when a class already implements `OnDestroy`; 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
- `voiceState` is written **only** by `VoiceSessionService` (`features/voice-agent/services/`), driven by the data table in `voice-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 (`interrupt` with `playedMs`). Never wait for the network.
- Agent audio frames carry a `turnId`; frames from a stale turn are dropped by `audio-stream.handler.ts`.
- `interrupted` is transient and resolves to `listening` after `FLUSH_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 `RealtimeTransport` abstraction (`core/websocket/realtime-transport.ts`). Feature code never touches `WebSocket` directly.
- Audio travels in **binary frames** with the documented header (`ARCHITECTURE.md` §5.2); control messages are JSON, typed by `ClientMessage` / `ServerMessage`. Set `binaryType = '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)
```text
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 `FaqStore` signals 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`** (via `FaqApiService` / `FaqIngestionService`). No feature injects `HttpClient` directly.
- `FaqIngestionService` is the only orchestrator of `validate → preview → upload → track status`.
- Status flows from the server through `IngestionEventsService` (SSE via `HttpService.getStream` or control messages) into `FaqStore` signals: `uploading → indexing → active | error`. Status is **never** inferred on the client.
- `features/faq-manager` must not import from `features/voice-agent` (and vice versa). Shared concerns go in `core/` or `shared/`.
- The voice session learns which documents to use only through `activeDocumentIds` in the session configuration (from `FaqStore.activeDocuments`), not by reaching into FAQ components.
### 4.2 PapaParse pre-parsing (CSV)
- **Lazy-load:** `const Papa = (await import('papaparse')).default;` inside `CsvParserService`. Never import it at the top of a component.
- **Preview** with `Papa.parse(file, { header: true, preview: N, skipEmptyLines: 'greedy', dynamicTyping: false })`, with `N` defaulting to 50.
- **Count and validate large files** with chunked streaming (`chunk` or `step`) so memory stays bounded. **Do not use `worker: 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 in `upload-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.ts` and `file-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 `FaqDocumentError` with a user-readable message and a `retryable` flag.
### 4.4 Upload, status, and Q&A editing
- Upload through **`HttpService`** (or `FaqApiService` built on it). If upload progress is required, extend `HttpService` with a progress-capable method rather than injecting raw `HttpClient` in a feature. Write `progress` into the document's signal state. Cancel with unsubscribe/`AbortController` when the owner is destroyed.
- The document row has one writer (`FaqStore`). Use immutable `update()` calls keyed by `id`.
- Q&A edits are **optimistic with rollback**: apply to `FaqStore`, send the request, roll back and toast on failure. A manual edit sets `overridden: true` so re-ingestion does not overwrite it.
- **AG Grid** (`ag-grid-angular`, `ag-grid-community` on 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).
---
## 5. Navigation Guide: where things go
| You are adding… | Put it in… |
|---|---|
| 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 | `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`) |
**Import boundaries** (enforced by ESLint `no-restricted-imports`):
```text
shared <- core <- features
```
- `shared` imports nothing from `core` or `features`.
- `core` imports from `shared` only, never from `features`.
- A feature never imports another feature.
- `core/audio` and `core/websocket` import 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://` and `https://` 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** by `AuthService` / `HttpService` (including 401 cleanup). Theme preference may live in `localStorage` **only** via `ThemeService`. Other preferences go through `StorageService` if present. Never tokens, transcripts, or file data in ad-hoc storage.
- Never use `innerHTML`, `bypassSecurityTrust*`, or `eval`/`new Function` with user, server, or model-generated text. Transcripts and Q&A are rendered as text.
- Every error path is handled: microphone denied, `AudioContext` suspended, worklet load failure, socket drop mid-turn, token expiry, WebGL context loss, upload failure. Map to `VoiceError` / `FaqDocumentError` and 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 only `console.log` them.
- Protect authenticated routes with `authGuard`. Do not implement a second guard that bypasses `AuthService.isAuthenticated()`.
---
## 7. Testing Rules
- **Colocate** `*.spec.ts` next 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`.
- `VoiceSessionService` is tested with fake `AudioEngine` and fake `RealtimeTransport`, including barge-in races and stale `turnId` frames.
- Configure tests for zoneless (`provideZonelessChangeDetection()`); await `fixture.whenStable()`; do not use `fakeAsync`.
- 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: []` |
| `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.OnPush` present on every component I created or touched?
- [ ] **Signals:** Is UI state in `signal()` / `computed()` / `linkedSignal()` (not `BehaviorSubject`, 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 inside `NgZone.runOutsideAngular()`, with **no signal read or written per frame**?
- [ ] **Cleanup:** Is every subscription, `AudioContext`, `AudioWorkletNode`, `MediaStream` track, `WebSocket`, observer, timer, overlay, and Three.js object (geometry, material, texture, renderer) released through `DestroyRef` / effect cleanup / `ngOnDestroy`?
- [ ] **Paths:** Does every file path match `./docs/SRC_STRUCTURE.md`, and do the imports respect `shared <- core <- features`?
### 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` (with `track`) / `@switch`; templates call only signals/computeds.
- [ ] Zoneless provider matches the installed Angular major (§1.5); no reliance on `NgZone.onStable` or `detectChanges()` in hot paths.
- [ ] One writer per state; public API exposes `asReadonly()`.
- [ ] No `effect()` used to derive state; no signal writes inside `computed()`.
- [ ] Exhaustive `switch` on 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.
- [ ] `AudioContext` is 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 `turnId` frames are dropped.
- [ ] Visualizer pauses when hidden, caps DPR at 2, honors `prefers-reduced-motion`, and has a fallback.
- [ ] `three` is lazily imported with named imports; shaders are imported as text from `core/audio/visualizer/shaders/`.
### 9.4 FAQ and file handling
- [ ] PapaParse is lazily imported, used with `preview`/chunking (never `worker: 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 through `shared/ui/icon`.
- [ ] Tailwind tokens and logical properties used; no hard-coded colors; no `ml-*`/`pr-*`.
- [ ] Accessible names, keyboard support, and `aria-live` for 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/*.md` file in the same change.
- [ ] **Http / Auth / Theme:** all API calls go through `HttpService`; login and session via `AuthService` + `authGuard`; theme init/toggle via `ThemeService` only (no parallel clients or direct token/theme storage).
---
## 10. Response Protocol for Agents
1. **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.
2. **Code:** complete files or clear diffs. No `// ...rest of code`, no pseudo-code, no TODO placeholders for core logic.
3. **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.
4. **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.
5. **Keep changes minimal and focused.** Mention (do not perform) unrelated cleanups.
6. **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
```ts
import { ChangeDetectionStrategy, Component, computed, input, output } from '@angular/core';
@Component({
selector: 'app-example',
changeDetection: ChangeDetectionStrategy.OnPush,
imports: [],
template: `
@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>
}
`,
})
export class ExampleComponent {
readonly items = input.required<readonly { id: string; label: string }[]>();
readonly selected = output<string>();
protected readonly emptyText = computed(() => 'Nothing here yet.');
}
```
### 11.2 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.3 `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.
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Brandon Roberts
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+304
View File
@@ -0,0 +1,304 @@
---
name: angular-component
description: >-
Create modern Angular standalone components following v20+ best practices. Use
for building UI components with signal-based inputs/outputs, OnPush change
detection, host bindings, content projection, and lifecycle hooks. Triggers on
component creation, refactoring class-based inputs to signals, adding host
bindings, or implementing accessible interactive components.
metadata:
category: development
suggest_for:
filename:
- '*.component.ts'
- '*.component.html'
source:
repository: 'https://github.com/analogjs/angular-skills'
path: skills/angular-component
license_path: LICENSE
commit: 610c90eb9490194bcff703f343f97fa0e00bdb2f
---
# Angular Component
Create standalone components for Angular v20+. Components are standalone by default—do NOT set `standalone: true`.
## Component Structure
```typescript
import { Component, ChangeDetectionStrategy, input, output, computed } from '@angular/core';
@Component({
selector: 'app-user-card',
changeDetection: ChangeDetectionStrategy.OnPush,
host: {
'class': 'user-card',
'[class.active]': 'isActive()',
'(click)': 'handleClick()',
},
template: `
<img [src]="avatarUrl()" [alt]="name() + ' avatar'" />
<h2>{{ name() }}</h2>
@if (showEmail()) {
<p>{{ email() }}</p>
}
`,
styles: `
:host { display: block; }
:host.active { border: 2px solid blue; }
`,
})
export class UserCard {
// Required input
name = input.required<string>();
// Optional input with default
email = input<string>('');
showEmail = input(false);
// Input with transform
isActive = input(false, { transform: booleanAttribute });
// Computed from inputs
avatarUrl = computed(() => `https://api.example.com/avatar/${this.name()}`);
// Output
selected = output<string>();
handleClick() {
this.selected.emit(this.name());
}
}
```
## Signal Inputs
```typescript
// Required - must be provided by parent
name = input.required<string>();
// Optional with default value
count = input(0);
// Optional without default (undefined allowed)
label = input<string>();
// With alias for template binding
size = input('medium', { alias: 'buttonSize' });
// With transform function
disabled = input(false, { transform: booleanAttribute });
value = input(0, { transform: numberAttribute });
```
## Signal Outputs
```typescript
import { output, outputFromObservable } from '@angular/core';
// Basic output
clicked = output<void>();
selected = output<Item>();
// With alias
valueChange = output<number>({ alias: 'change' });
// From Observable (for RxJS interop)
scroll$ = new Subject<number>();
scrolled = outputFromObservable(this.scroll$);
// Emit values
this.clicked.emit();
this.selected.emit(item);
```
## Host Bindings
Use the `host` object in `@Component`—do NOT use `@HostBinding` or `@HostListener` decorators.
```typescript
@Component({
selector: 'app-button',
host: {
// Static attributes
'role': 'button',
// Dynamic class bindings
'[class.primary]': 'variant() === "primary"',
'[class.disabled]': 'disabled()',
// Dynamic style bindings
'[style.--btn-color]': 'color()',
// Attribute bindings
'[attr.aria-disabled]': 'disabled()',
'[attr.tabindex]': 'disabled() ? -1 : 0',
// Event listeners
'(click)': 'onClick($event)',
'(keydown.enter)': 'onClick($event)',
'(keydown.space)': 'onClick($event)',
},
template: `<ng-content />`,
})
export class Button {
variant = input<'primary' | 'secondary'>('primary');
disabled = input(false, { transform: booleanAttribute });
color = input('#007bff');
clicked = output<void>();
onClick(event: Event) {
if (!this.disabled()) {
this.clicked.emit();
}
}
}
```
## Content Projection
```typescript
@Component({
selector: 'app-card',
template: `
<header>
<ng-content select="[card-header]" />
</header>
<main>
<ng-content />
</main>
<footer>
<ng-content select="[card-footer]" />
</footer>
`,
})
export class Card {}
// Usage:
// <app-card>
// <h2 card-header>Title</h2>
// <p>Main content</p>
// <button card-footer>Action</button>
// </app-card>
```
## Lifecycle Hooks
```typescript
import { OnDestroy, OnInit, afterNextRender, afterRender } from '@angular/core';
export class My implements OnInit, OnDestroy {
constructor() {
// For DOM manipulation after render (SSR-safe)
afterNextRender(() => {
// Runs once after first render
});
afterRender(() => {
// Runs after every render
});
}
ngOnInit() { /* Component initialized */ }
ngOnDestroy() { /* Cleanup */ }
}
```
## Accessibility Requirements
Components MUST:
- Pass AXE accessibility checks
- Meet WCAG AA standards
- Include proper ARIA attributes for interactive elements
- Support keyboard navigation
- Maintain visible focus indicators
```typescript
@Component({
selector: 'app-toggle',
host: {
'role': 'switch',
'[attr.aria-checked]': 'checked()',
'[attr.aria-label]': 'label()',
'tabindex': '0',
'(click)': 'toggle()',
'(keydown.enter)': 'toggle()',
'(keydown.space)': 'toggle(); $event.preventDefault()',
},
template: `<span class="toggle-track"><span class="toggle-thumb"></span></span>`,
})
export class Toggle {
label = input.required<string>();
checked = input(false, { transform: booleanAttribute });
checkedChange = output<boolean>();
toggle() {
this.checkedChange.emit(!this.checked());
}
}
```
## Template Syntax
Use native control flow—do NOT use `*ngIf`, `*ngFor`, `*ngSwitch`.
```html
<!-- Conditionals -->
@if (isLoading()) {
<app-spinner />
} @else if (error()) {
<app-error [message]="error()" />
} @else {
<app-content [data]="data()" />
}
<!-- Loops -->
@for (item of items(); track item.id) {
<app-item [item]="item" />
} @empty {
<p>No items found</p>
}
<!-- Switch -->
@switch (status()) {
@case ('pending') { <span>Pending</span> }
@case ('active') { <span>Active</span> }
@default { <span>Unknown</span> }
}
```
## Class and Style Bindings
Do NOT use `ngClass` or `ngStyle`. Use direct bindings:
```html
<!-- Class bindings -->
<div [class.active]="isActive()">Single class</div>
<div [class]="classString()">Class string</div>
<!-- Style bindings -->
<div [style.color]="textColor()">Styled text</div>
<div [style.width.px]="width()">With unit</div>
```
## Images
Use `NgOptimizedImage` for static images:
```typescript
import { NgOptimizedImage } from '@angular/common';
@Component({
imports: [NgOptimizedImage],
template: `
<img ngSrc="/assets/hero.jpg" width="800" height="600" priority />
<img [ngSrc]="imageUrl()" width="200" height="200" />
`,
})
export class Hero {
imageUrl = input.required<string>();
}
```
For detailed patterns, see [references/component-patterns.md](references/component-patterns.md).
@@ -0,0 +1,358 @@
# Angular Component Patterns
## Table of Contents
- [Model Inputs (Two-Way Binding)](#model-inputs-two-way-binding)
- [View Queries](#view-queries)
- [Content Queries](#content-queries)
- [Dependency Injection in Components](#dependency-injection-in-components)
- [Component Communication Patterns](#component-communication-patterns)
- [Dynamic Components](#dynamic-components)
## Model Inputs (Two-Way Binding)
For two-way binding with `[(value)]` syntax:
```typescript
import { Component, model } from '@angular/core';
@Component({
selector: 'app-slider',
host: {
'(input)': 'onInput($event)',
},
template: `
<input
type="range"
[value]="value()"
[min]="min()"
[max]="max()"
/>
<span>{{ value() }}</span>
`,
})
export class Slider {
// Model creates both input and output
value = model(0);
min = input(0);
max = input(100);
onInput(event: Event) {
const target = event.target as HTMLInputElement;
this.value.set(Number(target.value));
}
}
// Usage: <app-slider [(value)]="sliderValue" />
```
Required model:
```typescript
value = model.required<number>();
```
## View Queries
Query elements and components in the template:
```typescript
import { Component, viewChild, viewChildren, ElementRef } from '@angular/core';
@Component({
selector: 'app-gallery',
template: `
<div #container class="gallery">
@for (image of images(); track image.id) {
<app-image-card [image]="image" />
}
</div>
`,
})
export class Gallery {
images = input.required<Image[]>();
// Query single element
container = viewChild.required<ElementRef<HTMLDivElement>>('container');
// Query single component (optional)
firstCard = viewChild(ImageCard);
// Query all matching components
allCards = viewChildren(ImageCard);
}
```
## Content Queries
Query projected content:
```typescript
import { Component, contentChild, contentChildren, effect, signal } from '@angular/core';
@Component({
selector: 'app-tabs',
template: `
<div class="tab-headers">
@for (tab of tabs(); track tab.label()) {
<button
[class.active]="tab === activeTab()"
(click)="selectTab(tab)"
>
{{ tab.label() }}
</button>
}
</div>
<div class="tab-content">
<ng-content />
</div>
`,
})
export class Tabs {
// Query all projected Tab children
tabs = contentChildren(Tab);
// Query single projected element
header = contentChild('tabHeader');
activeTab = signal<Tab | undefined>(undefined);
constructor() {
// Set first tab as active when tabs are available
effect(() => {
const firstTab = this.tabs()[0];
if (firstTab && !this.activeTab()) {
this.activeTab.set(firstTab);
}
});
}
selectTab(tab: Tab) {
this.activeTab.set(tab);
}
}
@Component({
selector: 'app-tab',
template: `<ng-content />`,
host: {
'[class.active]': 'isActive()',
'[style.display]': 'isActive() ? "block" : "none"',
},
})
export class Tab {
label = input.required<string>();
isActive = input(false);
}
```
## Dependency Injection in Components
Use `inject()` function instead of constructor injection:
```typescript
import { Component, inject } from '@angular/core';
import { Router } from '@angular/router';
@Component({
selector: 'app-dashboard',
template: `...`,
})
export class Dashboard {
private router = inject(Router);
private userService = inject(User);
private config = inject(APP_CONFIG);
// Optional injection
private analytics = inject(Analytics, { optional: true });
// Self-only injection
private localService = inject(Local, { self: true });
navigateToProfile() {
this.router.navigate(['/profile']);
}
}
```
## Component Communication Patterns
### Parent to Child (Inputs)
```typescript
// Parent
@Component({
template: `<app-child [data]="parentData()" [config]="config" />`,
})
export class Parent {
parentData = signal({ name: 'Test' });
config = { theme: 'dark' };
}
// Child
@Component({ selector: 'app-child' })
export class Child {
data = input.required<Data>();
config = input<Config>();
}
```
### Child to Parent (Outputs)
```typescript
// Child
@Component({
selector: 'app-child',
template: `<button (click)="save()">Save</button>`,
})
export class Child {
saved = output<Data>();
save() {
this.saved.emit({ id: 1, name: 'Item' });
}
}
// Parent
@Component({
template: `<app-child (saved)="onSaved($event)" />`,
})
export class Parent {
onSaved(data: Data) {
console.log('Saved:', data);
}
}
```
### Shared Service Pattern
```typescript
// Shared state service
@Injectable({ providedIn: 'root' })
export class Cart {
private items = signal<CartItem[]>([]);
readonly items$ = this.items.asReadonly();
readonly total = computed(() =>
this.items().reduce((sum, item) => sum + item.price, 0)
);
addItem(item: CartItem) {
this.items.update(items => [...items, item]);
}
removeItem(id: string) {
this.items.update(items => items.filter(i => i.id !== id));
}
}
// Component A
@Component({ template: `<button (click)="add()">Add</button>` })
export class Product {
private cart = inject(Cart);
product = input.required<Product>();
add() {
this.cart.addItem({ ...this.product(), quantity: 1 });
}
}
// Component B
@Component({ template: `<span>Total: {{ cart.total() }}</span>` })
export class CartSummary {
cart = inject(Cart);
}
```
## Dynamic Components
Using `@defer` for lazy loading:
```typescript
@Component({
template: `
@defer (on viewport) {
<app-heavy-chart [data]="chartData()" />
} @placeholder {
<div class="chart-placeholder">Loading chart...</div>
} @loading (minimum 500ms) {
<app-spinner />
} @error {
<p>Failed to load chart</p>
}
`,
})
export class Dashboard {
chartData = input.required<ChartData>();
}
```
Defer triggers:
- `on viewport` - When element enters viewport
- `on idle` - When browser is idle
- `on interaction` - On user interaction (click, focus)
- `on hover` - On mouse hover
- `on immediate` - Immediately after non-deferred content
- `on timer(500ms)` - After specified delay
- `when condition` - When expression becomes true
```typescript
@Component({
template: `
@defer (on interaction; prefetch on idle) {
<app-comments [postId]="postId()" />
} @placeholder {
<button>Load Comments</button>
}
`,
})
export class Post {
postId = input.required<string>();
}
```
## Attribute Directives on Components
```typescript
@Directive({
selector: '[appHighlight]',
host: {
'[style.backgroundColor]': 'color()',
},
})
export class Highlight {
color = input('yellow', { alias: 'appHighlight' });
}
// Usage on component
@Component({
imports: [Highlight],
template: `<app-card appHighlight="lightblue" />`,
})
export class Page {}
```
## Error Boundaries
```typescript
@Component({
selector: 'app-error-boundary',
template: `
@if (hasError()) {
<div class="error">
<h3>Something went wrong</h3>
<button (click)="retry()">Retry</button>
</div>
} @else {
<ng-content />
}
`,
})
export class ErrorBoundary {
hasError = signal(false);
private errorHandler = inject(ErrorHandler);
retry() {
this.hasError.set(false);
}
}
```
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Brandon Roberts
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+314
View File
@@ -0,0 +1,314 @@
---
name: angular-signals
description: >-
Implement signal-based reactive state management in Angular v20+. Use for
creating reactive state with signal(), derived state with computed(),
dependent state with linkedSignal(), and side effects with effect(). Triggers
on state management questions, converting from BehaviorSubject/Observable
patterns to signals, or implementing reactive data flows.
metadata:
category: development
source:
repository: 'https://github.com/analogjs/angular-skills'
path: skills/angular-signals
license_path: LICENSE
commit: 610c90eb9490194bcff703f343f97fa0e00bdb2f
---
# Angular Signals
Signals are Angular's reactive primitive for state management. They provide synchronous, fine-grained reactivity.
## Core Signal APIs
### signal() - Writable State
```typescript
import { signal } from '@angular/core';
// Create writable signal
const count = signal(0);
// Read value
console.log(count()); // 0
// Set new value
count.set(5);
// Update based on current value
count.update(c => c + 1);
// With explicit type
const user = signal<User | null>(null);
user.set({ id: 1, name: 'Alice' });
```
### computed() - Derived State
```typescript
import { signal, computed } from '@angular/core';
const firstName = signal('John');
const lastName = signal('Doe');
// Derived signal - automatically updates when dependencies change
const fullName = computed(() => `${firstName()} ${lastName()}`);
console.log(fullName()); // "John Doe"
firstName.set('Jane');
console.log(fullName()); // "Jane Doe"
// Computed with complex logic
const items = signal<Item[]>([]);
const filter = signal('');
const filteredItems = computed(() => {
const query = filter().toLowerCase();
return items().filter(item =>
item.name.toLowerCase().includes(query)
);
});
const totalPrice = computed(() =>
filteredItems().reduce((sum, item) => sum + item.price, 0)
);
```
### linkedSignal() - Dependent State with Reset
```typescript
import { signal, linkedSignal } from '@angular/core';
const options = signal(['A', 'B', 'C']);
// Resets to first option when options change
const selected = linkedSignal(() => options()[0]);
console.log(selected()); // "A"
selected.set('B'); // User selects B
console.log(selected()); // "B"
options.set(['X', 'Y']); // Options change
console.log(selected()); // "X" - auto-reset to first
// With previous value access
const items = signal<Item[]>([]);
const selectedItem = linkedSignal<Item[], Item | null>({
source: () => items(),
computation: (newItems, previous) => {
// Try to preserve selection if item still exists
const prevItem = previous?.value;
if (prevItem && newItems.some(i => i.id === prevItem.id)) {
return prevItem;
}
return newItems[0] ?? null;
},
});
```
### effect() - Side Effects
```typescript
import { signal, effect, inject, DestroyRef } from '@angular/core';
@Component({...})
export class Search {
query = signal('');
constructor() {
// Effect runs when query changes
effect(() => {
console.log('Search query:', this.query());
});
// Effect with cleanup
effect((onCleanup) => {
const timer = setInterval(() => {
console.log('Current query:', this.query());
}, 1000);
onCleanup(() => clearInterval(timer));
});
}
}
```
**Effect rules:**
- Run in injection context (constructor or with `runInInjectionContext`)
- Automatically cleaned up when component destroys
## Component State Pattern
```typescript
@Component({
selector: 'app-todo-list',
template: `
<input [value]="newTodo()" (input)="newTodo.set($any($event.target).value)" />
<button (click)="addTodo()" [disabled]="!canAdd()">Add</button>
<ul>
@for (todo of filteredTodos(); track todo.id) {
<li [class.done]="todo.done">
{{ todo.text }}
<button (click)="toggleTodo(todo.id)">Toggle</button>
</li>
}
</ul>
<p>{{ remaining() }} remaining</p>
`,
})
export class TodoList {
// State
todos = signal<Todo[]>([]);
newTodo = signal('');
filter = signal<'all' | 'active' | 'done'>('all');
// Derived state
canAdd = computed(() => this.newTodo().trim().length > 0);
filteredTodos = computed(() => {
const todos = this.todos();
switch (this.filter()) {
case 'active': return todos.filter(t => !t.done);
case 'done': return todos.filter(t => t.done);
default: return todos;
}
});
remaining = computed(() =>
this.todos().filter(t => !t.done).length
);
// Actions
addTodo() {
const text = this.newTodo().trim();
if (text) {
this.todos.update(todos => [
...todos,
{ id: crypto.randomUUID(), text, done: false }
]);
this.newTodo.set('');
}
}
toggleTodo(id: string) {
this.todos.update(todos =>
todos.map(t => t.id === id ? { ...t, done: !t.done } : t)
);
}
}
```
## RxJS Interop
### toSignal() - Observable to Signal
```typescript
import { toSignal } from '@angular/core/rxjs-interop';
import { interval } from 'rxjs';
@Component({...})
export class Timer {
private http = inject(HttpClient);
// From observable - requires initial value or allowUndefined
counter = toSignal(interval(1000), { initialValue: 0 });
// From HTTP - undefined until loaded
users = toSignal(this.http.get<User[]>('/api/users'));
// With requireSync for synchronous observables (BehaviorSubject)
private user$ = new BehaviorSubject<User | null>(null);
currentUser = toSignal(this.user$, { requireSync: true });
}
```
### toObservable() - Signal to Observable
```typescript
import { toObservable } from '@angular/core/rxjs-interop';
import { switchMap, debounceTime } from 'rxjs';
@Component({...})
export class Search {
query = signal('');
private http = inject(HttpClient);
// Convert signal to observable for RxJS operators
results = toSignal(
toObservable(this.query).pipe(
debounceTime(300),
switchMap(q => this.http.get<Result[]>(`/api/search?q=${q}`))
),
{ initialValue: [] }
);
}
```
## Signal Equality
```typescript
// Custom equality function
const user = signal<User>(
{ id: 1, name: 'Alice' },
{ equal: (a, b) => a.id === b.id }
);
// Only triggers updates when ID changes
user.set({ id: 1, name: 'Alice Updated' }); // No update
user.set({ id: 2, name: 'Bob' }); // Triggers update
```
## Untracked Reads
```typescript
import { untracked } from '@angular/core';
const a = signal(1);
const b = signal(2);
// Only depends on 'a', not 'b'
const result = computed(() => {
const aVal = a();
const bVal = untracked(() => b());
return aVal + bVal;
});
```
## Service State Pattern
```typescript
@Injectable({ providedIn: 'root' })
export class Auth {
// Private writable state
private _user = signal<User | null>(null);
private _loading = signal(false);
// Public read-only signals
readonly user = this._user.asReadonly();
readonly loading = this._loading.asReadonly();
readonly isAuthenticated = computed(() => this._user() !== null);
private http = inject(HttpClient);
async login(credentials: Credentials): Promise<void> {
this._loading.set(true);
try {
const user = await firstValueFrom(
this.http.post<User>('/api/login', credentials)
);
this._user.set(user);
} finally {
this._loading.set(false);
}
}
logout(): void {
this._user.set(null);
}
}
```
For advanced patterns including resource(), see [references/signal-patterns.md](references/signal-patterns.md).
@@ -0,0 +1,404 @@
# Angular Signal Patterns
## Table of Contents
- [Resource API](#resource-api)
- [Signal Store Pattern](#signal-store-pattern)
- [Form State with Signals](#form-state-with-signals)
- [Async Operations](#async-operations)
- [Testing Signals](#testing-signals)
## Resource API
The `resource()` API handles async data fetching with signals:
```typescript
import { resource, signal, computed } from '@angular/core';
@Component({...})
export class UserProfile {
userId = signal<string>('');
// Resource fetches data when params change
userResource = resource({
params: () => ({ id: this.userId() }),
loader: async ({ params, abortSignal }) => {
const response = await fetch(`/api/users/${params.id}`, {
signal: abortSignal,
});
return response.json() as Promise<User>;
},
});
// Access resource state
user = computed(() => this.userResource.value());
isLoading = computed(() => this.userResource.isLoading());
error = computed(() => this.userResource.error());
}
```
### Resource Status
```typescript
const userResource = resource({...});
// Status signals
userResource.value(); // Current value or undefined
userResource.hasValue(); // Boolean - has resolved value
userResource.error(); // Error or undefined
userResource.isLoading(); // Boolean - currently loading
userResource.status(); // 'idle' | 'loading' | 'reloading' | 'resolved' | 'error' | 'local'
// Manual reload
userResource.reload();
// Local updates
userResource.set(newValue);
userResource.update(current => ({ ...current, name: 'Updated' }));
```
### Resource with Default Value
```typescript
const todosResource = resource({
defaultValue: [] as Todo[],
params: () => ({ filter: this.filter() }),
loader: async ({ params }) => {
const response = await fetch(`/api/todos?filter=${params.filter}`);
return response.json();
},
});
// value() returns Todo[] (never undefined due to defaultValue)
```
### Conditional Loading
```typescript
const userId = signal<string | null>(null);
const userResource = resource({
params: () => {
const id = userId();
// Return undefined to skip loading
return id ? { id } : undefined;
},
loader: async ({ params }) => {
return fetch(`/api/users/${params.id}`).then(r => r.json());
},
});
// Status is 'idle' when params returns undefined
```
## Signal Store Pattern
For complex state, create a dedicated store:
```typescript
interface ProductState {
products: Product[];
selectedId: string | null;
filter: string;
loading: boolean;
error: string | null;
}
@Injectable({ providedIn: 'root' })
export class ProductSt {
// Private state
private state = signal<ProductState>({
products: [],
selectedId: null,
filter: '',
loading: false,
error: null,
});
// Selectors (computed signals)
readonly products = computed(() => this.state().products);
readonly selectedId = computed(() => this.state().selectedId);
readonly filter = computed(() => this.state().filter);
readonly loading = computed(() => this.state().loading);
readonly error = computed(() => this.state().error);
readonly filteredProducts = computed(() => {
const { products, filter } = this.state();
if (!filter) return products;
return products.filter(p =>
p.name.toLowerCase().includes(filter.toLowerCase())
);
});
readonly selectedProduct = computed(() => {
const { products, selectedId } = this.state();
return products.find(p => p.id === selectedId) ?? null;
});
private http = inject(HttpClient);
// Actions
setFilter(filter: string): void {
this.state.update(s => ({ ...s, filter }));
}
selectProduct(id: string | null): void {
this.state.update(s => ({ ...s, selectedId: id }));
}
async loadProducts(): Promise<void> {
this.state.update(s => ({ ...s, loading: true, error: null }));
try {
const products = await firstValueFrom(
this.http.get<Product[]>('/api/products')
);
this.state.update(s => ({ ...s, products, loading: false }));
} catch (err) {
this.state.update(s => ({
...s,
loading: false,
error: 'Failed to load products'
}));
}
}
async addProduct(product: Omit<Product, 'id'>): Promise<void> {
const newProduct = await firstValueFrom(
this.http.post<Product>('/api/products', product)
);
this.state.update(s => ({
...s,
products: [...s.products, newProduct],
}));
}
}
```
## Form State with Signals
```typescript
interface FormState<T> {
value: T;
touched: boolean;
dirty: boolean;
valid: boolean;
errors: string[];
}
function createFormField<T>(
initialValue: T,
validators: ((value: T) => string | null)[] = []
) {
const value = signal(initialValue);
const touched = signal(false);
const dirty = signal(false);
const errors = computed(() => {
return validators
.map(v => v(value()))
.filter((e): e is string => e !== null);
});
const valid = computed(() => errors().length === 0);
return {
value,
touched: touched.asReadonly(),
dirty: dirty.asReadonly(),
errors,
valid,
setValue(newValue: T) {
value.set(newValue);
dirty.set(true);
},
markTouched() {
touched.set(true);
},
reset() {
value.set(initialValue);
touched.set(false);
dirty.set(false);
},
};
}
// Usage
@Component({...})
export class Signup {
email = createFormField('', [
v => !v ? 'Email is required' : null,
v => !v.includes('@') ? 'Invalid email' : null,
]);
password = createFormField('', [
v => !v ? 'Password is required' : null,
v => v.length < 8 ? 'Password must be at least 8 characters' : null,
]);
formValid = computed(() =>
this.email.valid() && this.password.valid()
);
}
```
## Async Operations
### Debounced Search
```typescript
@Component({...})
export class Search {
query = signal('');
private http = inject(HttpClient);
// Debounced search using toObservable
results = toSignal(
toObservable(this.query).pipe(
debounceTime(300),
distinctUntilChanged(),
filter(q => q.length >= 2),
switchMap(q => this.http.get<Result[]>(`/api/search?q=${q}`)),
catchError(() => of([]))
),
{ initialValue: [] }
);
// Loading state
private searching = signal(false);
readonly isSearching = this.searching.asReadonly();
constructor() {
// Track loading state
effect(() => {
const q = this.query();
if (q.length >= 2) {
this.searching.set(true);
}
});
effect(() => {
this.results(); // Subscribe to results
this.searching.set(false);
});
}
}
```
### Optimistic Updates
```typescript
@Injectable({ providedIn: 'root' })
export class Todo {
private todos = signal<Todo[]>([]);
readonly items = this.todos.asReadonly();
private http = inject(HttpClient);
async toggleTodo(id: string): Promise<void> {
// Optimistic update
const previousTodos = this.todos();
this.todos.update(todos =>
todos.map(t => t.id === id ? { ...t, done: !t.done } : t)
);
try {
await firstValueFrom(
this.http.patch(`/api/todos/${id}/toggle`, {})
);
} catch {
// Rollback on error
this.todos.set(previousTodos);
}
}
}
```
## Testing Signals
```typescript
describe('Counter', () => {
it('should increment count', () => {
const component = new Counter();
expect(component.count()).toBe(0);
component.increment();
expect(component.count()).toBe(1);
component.increment();
expect(component.count()).toBe(2);
});
it('should compute doubled value', () => {
const component = new Counter();
expect(component.doubled()).toBe(0);
component.count.set(5);
expect(component.doubled()).toBe(10);
});
});
describe('ProductSt', () => {
let store: ProductSt;
let httpMock: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
ProductSt,
provideHttpClient(),
provideHttpClientTesting(),
],
});
store = TestBed.inject(ProductSt);
httpMock = TestBed.inject(HttpTestingController);
});
it('should filter products', () => {
// Set initial state
store['state'].set({
products: [
{ id: '1', name: 'Apple' },
{ id: '2', name: 'Banana' },
],
selectedId: null,
filter: '',
loading: false,
error: null,
});
expect(store.filteredProducts().length).toBe(2);
store.setFilter('app');
expect(store.filteredProducts().length).toBe(1);
expect(store.filteredProducts()[0].name).toBe('Apple');
});
});
```
## Signal Debugging
```typescript
// Debug effect to log signal changes
effect(() => {
console.log('State changed:', {
count: this.count(),
items: this.items(),
filter: this.filter(),
});
});
// Conditional debugging
const DEBUG = signal(false);
effect(() => {
if (untracked(() => DEBUG())) {
console.log('Debug:', this.state());
}
});
```
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Brandon Roberts
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+471
View File
@@ -0,0 +1,471 @@
---
name: angular-testing
description: >-
Write unit and integration tests for Angular v20+ applications using Vitest or
Jasmine with TestBed and modern testing patterns. Use for testing components
with signals, OnPush change detection, services with inject(), and HTTP
interactions. Triggers on test creation, testing signal-based components,
mocking dependencies, or setting up test infrastructure. Don't use for E2E
testing with Cypress or Playwright, or for testing non-Angular
JavaScript/TypeScript code.
metadata:
category: development
source:
repository: 'https://github.com/analogjs/angular-skills'
path: skills/angular-testing
license_path: LICENSE
commit: 610c90eb9490194bcff703f343f97fa0e00bdb2f
---
# Angular Testing
Test Angular v20+ applications with Vitest (recommended) or Jasmine, focusing on signal-based components and modern patterns.
## Vitest Setup (Angular v20+)
Angular v20+ has native Vitest support through the `@angular/build` package.
```bash
npm install -D vitest jsdom
```
Configure in angular.json:
```json
{
"projects": {
"your-app": {
"architect": {
"test": {
"builder": "@angular/build:unit-test",
"options": {
"tsConfig": "tsconfig.spec.json",
"buildTarget": "your-app:build"
}
}
}
}
}
}
```
Run tests:
```bash
ng test # Run tests
ng test --watch # Watch mode
ng test --code-coverage # With coverage
```
For Vitest migration from Jasmine and advanced configuration, see [references/vitest-migration.md](references/vitest-migration.md).
## Basic Component Test
```typescript
import { describe, it, expect, beforeEach } from 'vitest';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { Counter } from './counter.component';
describe('Counter', () => {
let component: Counter;
let fixture: ComponentFixture<Counter>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [Counter], // Standalone component
}).compileComponents();
fixture = TestBed.createComponent(Counter);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
it('should increment count', () => {
expect(component.count()).toBe(0);
component.increment();
expect(component.count()).toBe(1);
});
it('should display count in template', () => {
component.count.set(5);
fixture.detectChanges();
const element = fixture.nativeElement.querySelector('.count');
expect(element.textContent).toContain('5');
});
});
```
## Testing Signals
### Direct Signal Testing
```typescript
import { signal, computed } from '@angular/core';
describe('Signal logic', () => {
it('should update computed when signal changes', () => {
const count = signal(0);
const doubled = computed(() => count() * 2);
expect(doubled()).toBe(0);
count.set(5);
expect(doubled()).toBe(10);
count.update(c => c + 1);
expect(doubled()).toBe(12);
});
});
```
### Testing Component Signals
```typescript
@Component({
selector: 'app-todo-list',
template: `
<ul>
@for (todo of filteredTodos(); track todo.id) {
<li>{{ todo.text }}</li>
}
</ul>
<p>{{ remaining() }} remaining</p>
`,
})
export class TodoList {
todos = signal<Todo[]>([]);
filter = signal<'all' | 'active' | 'done'>('all');
filteredTodos = computed(() => {
const todos = this.todos();
switch (this.filter()) {
case 'active': return todos.filter(t => !t.done);
case 'done': return todos.filter(t => t.done);
default: return todos;
}
});
remaining = computed(() => this.todos().filter(t => !t.done).length);
}
describe('TodoList', () => {
let component: TodoList;
let fixture: ComponentFixture<TodoList>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [TodoList],
}).compileComponents();
fixture = TestBed.createComponent(TodoList);
component = fixture.componentInstance;
});
it('should filter active todos', () => {
component.todos.set([
{ id: '1', text: 'Task 1', done: false },
{ id: '2', text: 'Task 2', done: true },
{ id: '3', text: 'Task 3', done: false },
]);
component.filter.set('active');
expect(component.filteredTodos().length).toBe(2);
expect(component.remaining()).toBe(2);
});
});
```
## Testing OnPush Components
OnPush components require explicit change detection:
```typescript
@Component({
changeDetection: ChangeDetectionStrategy.OnPush,
template: `<span>{{ data().name }}</span>`,
})
export class OnPushCmpt {
data = input.required<{ name: string }>();
}
describe('OnPushCmpt', () => {
it('should update when input signal changes', () => {
const fixture = TestBed.createComponent(OnPushCmpt);
// Set input using setInput (for signal inputs)
fixture.componentRef.setInput('data', { name: 'Initial' });
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('Initial');
// Update input
fixture.componentRef.setInput('data', { name: 'Updated' });
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('Updated');
});
});
```
## Testing Services
### Basic Service Test
```typescript
@Injectable({ providedIn: 'root' })
export class CounterService {
private _count = signal(0);
readonly count = this._count.asReadonly();
increment() { this._count.update(c => c + 1); }
reset() { this._count.set(0); }
}
describe('CounterService', () => {
let service: CounterService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(CounterService);
});
it('should increment count', () => {
expect(service.count()).toBe(0);
service.increment();
expect(service.count()).toBe(1);
});
});
```
### Service with HTTP
```typescript
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { provideHttpClient } from '@angular/common/http';
describe('UserService', () => {
let service: UserService;
let httpMock: HttpTestingController;
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
provideHttpClient(),
provideHttpClientTesting(),
],
});
service = TestBed.inject(UserService);
httpMock = TestBed.inject(HttpTestingController);
});
afterEach(() => {
httpMock.verify(); // Verify no outstanding requests
});
it('should fetch user by id', () => {
const mockUser = { id: '1', name: 'Test User' };
service.getUser('1').subscribe(user => {
expect(user).toEqual(mockUser);
});
const req = httpMock.expectOne('/api/users/1');
expect(req.request.method).toBe('GET');
req.flush(mockUser);
});
});
```
## Mocking Dependencies
### Using Vitest Mocks
```typescript
import { describe, it, expect, vi, beforeEach } from 'vitest';
describe('UserProfile', () => {
const mockUserService = {
getUser: vi.fn(),
updateUser: vi.fn(),
user: signal<User | null>(null),
};
beforeEach(async () => {
vi.clearAllMocks();
mockUserService.getUser.mockReturnValue(of({ id: '1', name: 'Test' }));
await TestBed.configureTestingModule({
imports: [UserProfile],
providers: [
{ provide: UserService, useValue: mockUserService },
],
}).compileComponents();
});
it('should call getUser on init', () => {
const fixture = TestBed.createComponent(UserProfile);
fixture.detectChanges();
expect(mockUserService.getUser).toHaveBeenCalledWith('1');
});
});
```
### Mock Signal-Based Service
```typescript
const mockAuth = {
user: signal<User | null>(null),
isAuthenticated: computed(() => mockAuth.user() !== null),
login: vi.fn(),
logout: vi.fn(),
};
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [ProtectedPage],
providers: [
{ provide: AuthService, useValue: mockAuth },
],
}).compileComponents();
});
it('should show content when authenticated', () => {
mockAuth.user.set({ id: '1', name: 'Test User' });
const fixture = TestBed.createComponent(ProtectedPage);
fixture.detectChanges();
expect(fixture.nativeElement.querySelector('.protected-content')).toBeTruthy();
});
```
## Testing Inputs and Outputs
```typescript
@Component({
selector: 'app-item',
template: `<div (click)="select()">{{ item().name }}</div>`,
})
export class ItemCmpt {
item = input.required<Item>();
selected = output<Item>();
select() {
this.selected.emit(this.item());
}
}
describe('ItemCmpt', () => {
it('should emit selected event on click', () => {
const fixture = TestBed.createComponent(ItemCmpt);
const item: Item = { id: '1', name: 'Test Item' };
fixture.componentRef.setInput('item', item);
fixture.detectChanges();
let emittedItem: Item | undefined;
fixture.componentInstance.selected.subscribe(i => emittedItem = i);
fixture.nativeElement.querySelector('div').click();
expect(emittedItem).toEqual(item);
});
});
```
## Testing Async Operations
### Using fakeAsync
```typescript
import { fakeAsync, tick, flush } from '@angular/core/testing';
it('should debounce search', fakeAsync(() => {
const fixture = TestBed.createComponent(SearchCmpt);
fixture.detectChanges();
fixture.componentInstance.query.set('test');
tick(300); // Advance time for debounce
fixture.detectChanges();
expect(fixture.componentInstance.results().length).toBeGreaterThan(0);
flush(); // Flush remaining timers
}));
```
### Using waitForAsync
```typescript
import { waitForAsync } from '@angular/core/testing';
it('should load data', waitForAsync(() => {
const fixture = TestBed.createComponent(DataCmpt);
fixture.detectChanges();
fixture.whenStable().then(() => {
fixture.detectChanges();
expect(fixture.componentInstance.data()).toBeDefined();
});
}));
```
## Testing HTTP Resources
```typescript
@Component({
template: `
@if (userResource.isLoading()) {
<p>Loading...</p>
} @else if (userResource.hasValue()) {
<p>{{ userResource.value().name }}</p>
}
`,
})
export class UserCmpt {
userId = signal('1');
userResource = httpResource<User>(() => `/api/users/${this.userId()}`);
}
describe('UserCmpt', () => {
let httpMock: HttpTestingController;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [UserCmpt],
providers: [
provideHttpClient(),
provideHttpClientTesting(),
],
}).compileComponents();
httpMock = TestBed.inject(HttpTestingController);
});
it('should display user name after loading', () => {
const fixture = TestBed.createComponent(UserCmpt);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('Loading');
const req = httpMock.expectOne('/api/users/1');
req.flush({ id: '1', name: 'John Doe' });
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toContain('John Doe');
});
});
```
For advanced testing patterns including component harnesses, router testing, form testing, and directive testing, see [references/testing-patterns.md](references/testing-patterns.md).
For Vitest migration from Jasmine, see [references/vitest-migration.md](references/vitest-migration.md).
@@ -0,0 +1,707 @@
# Angular Testing Patterns
## Table of Contents
- [Vitest Advanced Patterns](#vitest-advanced-patterns)
- [Component Harnesses](#component-harnesses)
- [Testing Router](#testing-router)
- [Testing Forms](#testing-forms)
- [Testing Directives](#testing-directives)
- [Testing Pipes](#testing-pipes)
- [E2E Testing Setup](#e2e-testing-setup)
## Vitest Advanced Patterns
### Snapshot Testing
```typescript
import { describe, it, expect } from 'vitest';
describe('UserCard', () => {
it('should match snapshot', () => {
const fixture = TestBed.createComponent(UserCard);
fixture.componentRef.setInput('user', { id: '1', name: 'John', email: 'john@example.com' });
fixture.detectChanges();
expect(fixture.nativeElement.innerHTML).toMatchSnapshot();
});
});
```
### Parameterized Tests
```typescript
import { describe, it, expect } from 'vitest';
describe('Validator', () => {
it.each([
{ input: '', expected: false },
{ input: 'test', expected: false },
{ input: 'test@example.com', expected: true },
{ input: 'invalid@', expected: false },
])('should validate email "$input" as $expected', ({ input, expected }) => {
expect(isValidEmail(input)).toBe(expected);
});
});
```
### Testing with Fake Timers
```typescript
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
describe('Debounced Search', () => {
beforeEach(() => {
vi.useFakeTimers();
});
afterEach(() => {
vi.useRealTimers();
});
it('should debounce search input', async () => {
const fixture = TestBed.createComponent(Search);
fixture.detectChanges();
fixture.componentInstance.query.set('test');
// Search not called yet
expect(fixture.componentInstance.results()).toEqual([]);
// Advance timers
vi.advanceTimersByTime(300);
await fixture.whenStable();
fixture.detectChanges();
expect(fixture.componentInstance.results().length).toBeGreaterThan(0);
});
});
```
### Module Mocking
```typescript
import { describe, it, expect, vi } from 'vitest';
// Mock entire module
vi.mock('./analytics.service', () => ({
Analytics: class {
track = vi.fn();
identify = vi.fn();
},
}));
describe('with mocked analytics', () => {
it('should track events', () => {
const fixture = TestBed.createComponent(Dashboard);
const analytics = TestBed.inject(Analytics);
fixture.detectChanges();
expect(analytics.track).toHaveBeenCalledWith('dashboard_viewed');
});
});
```
### Testing Async/Await
```typescript
import { describe, it, expect, vi } from 'vitest';
describe('User', () => {
it('should load user data', async () => {
const mockUser = { id: '1', name: 'Test' };
const httpMock = TestBed.inject(HttpTestingController);
const service = TestBed.inject(User);
const userPromise = service.loadUser('1');
httpMock.expectOne('/api/users/1').flush(mockUser);
const user = await userPromise;
expect(user).toEqual(mockUser);
});
});
```
### Coverage Configuration
```typescript
// vite.config.ts
export default defineConfig({
test: {
coverage: {
provider: 'v8',
reporter: ['text', 'html', 'lcov'],
exclude: [
'node_modules/',
'src/test-setup.ts',
'**/*.spec.ts',
'**/*.d.ts',
],
thresholds: {
statements: 80,
branches: 80,
functions: 80,
lines: 80,
},
},
},
});
```
### Vitest UI Mode
```bash
# Run with UI
npx vitest --ui
# Open UI at specific port
npx vitest --ui --port 51204
```
### Concurrent Tests
```typescript
import { describe, it, expect } from 'vitest';
// Run tests in this describe block concurrently
describe.concurrent('API calls', () => {
it('should fetch users', async () => {
// ...
});
it('should fetch products', async () => {
// ...
});
it('should fetch orders', async () => {
// ...
});
});
```
### Test Fixtures
```typescript
import { describe, it, expect, beforeEach } from 'vitest';
// Shared test fixtures
const createTestUser = (overrides = {}) => ({
id: '1',
name: 'Test User',
email: 'test@example.com',
...overrides,
});
const createTestProduct = (overrides = {}) => ({
id: '1',
name: 'Test Product',
price: 99.99,
...overrides,
});
describe('Order', () => {
it('should calculate total', () => {
const fixture = TestBed.createComponent(Order);
fixture.componentRef.setInput('user', createTestUser());
fixture.componentRef.setInput('products', [
createTestProduct({ price: 10 }),
createTestProduct({ id: '2', price: 20 }),
]);
fixture.detectChanges();
expect(fixture.componentInstance.total()).toBe(30);
});
});
```
## Component Harnesses
Use Angular CDK component harnesses for more maintainable tests:
### Creating a Harness
```typescript
import { ComponentHarness, HarnessPredicate } from '@angular/cdk/testing';
export class CounterHarn extends ComponentHarness {
static hostSelector = 'app-counter';
// Locators
private getIncrementButton = this.locatorFor('button.increment');
private getDecrementButton = this.locatorFor('button.decrement');
private getCountDisplay = this.locatorFor('.count');
// Actions
async increment(): Promise<void> {
const button = await this.getIncrementButton();
await button.click();
}
async decrement(): Promise<void> {
const button = await this.getDecrementButton();
await button.click();
}
// Queries
async getCount(): Promise<number> {
const display = await this.getCountDisplay();
const text = await display.text();
return parseInt(text, 10);
}
// Filter factory
static with(options: { count?: number } = {}): HarnessPredicate<CounterHarn> {
return new HarnessPredicate(CounterHarn, options)
.addOption('count', options.count, async (harness, count) => {
return (await harness.getCount()) === count;
});
}
}
```
### Using Harnesses in Tests
```typescript
import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed';
describe('Counter with Harness', () => {
let loader: HarnessLoader;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [Counter],
}).compileComponents();
const fixture = TestBed.createComponent(Counter);
loader = TestbedHarnessEnvironment.loader(fixture);
});
it('should increment count', async () => {
const counter = await loader.getHarness(CounterHarn);
expect(await counter.getCount()).toBe(0);
await counter.increment();
expect(await counter.getCount()).toBe(1);
await counter.increment();
expect(await counter.getCount()).toBe(2);
});
it('should find counter with specific count', async () => {
const counter = await loader.getHarness(CounterHarn);
await counter.increment();
await counter.increment();
// Find counter with count of 2
const counterWith2 = await loader.getHarness(CounterHarn.with({ count: 2 }));
expect(counterWith2).toBeTruthy();
});
});
```
## Testing Router
### RouterTestingHarness
```typescript
import { RouterTestingHarness } from '@angular/router/testing';
import { provideRouter } from '@angular/router';
describe('Router Navigation', () => {
let harness: RouterTestingHarness;
beforeEach(async () => {
await TestBed.configureTestingModule({
providers: [
provideRouter([
{ path: '', component: Home },
{ path: 'users/:id', component: UserCmpt },
]),
],
}).compileComponents();
harness = await RouterTestingHarness.create();
});
it('should navigate to user page', async () => {
const component = await harness.navigateByUrl('/users/123', UserCmpt);
expect(component.id()).toBe('123');
});
it('should display user name', async () => {
await harness.navigateByUrl('/users/123');
expect(harness.routeNativeElement?.textContent).toContain('User 123');
});
});
```
### Testing Guards
```typescript
describe('AuthGuard', () => {
let authService: jasmine.SpyObj<Auth>;
beforeEach(() => {
authService = jasmine.createSpyObj('Auth', ['isAuthenticated']);
TestBed.configureTestingModule({
providers: [
{ provide: Auth, useValue: authService },
provideRouter([
{ path: 'login', component: Login },
{
path: 'dashboard',
component: Dashboard,
canActivate: [authGuard],
},
]),
],
});
});
it('should allow access when authenticated', async () => {
authService.isAuthenticated.and.returnValue(true);
const harness = await RouterTestingHarness.create();
await harness.navigateByUrl('/dashboard');
expect(harness.routeNativeElement?.textContent).toContain('Dashboard');
});
it('should redirect to login when not authenticated', async () => {
authService.isAuthenticated.and.returnValue(false);
const harness = await RouterTestingHarness.create();
await harness.navigateByUrl('/dashboard');
expect(TestBed.inject(Router).url).toBe('/login');
});
});
```
## Testing Forms
### Testing Signal Forms
```typescript
import { form, FormField, required, email } from '@angular/forms/signals';
@Component({
imports: [FormField],
template: `
<form (submit)="onSubmit($event)">
<input [formField]="loginForm.email" />
<input [formField]="loginForm.password" type="password" />
<button type="submit" [disabled]="loginForm().invalid()">Submit</button>
</form>
`,
})
export class Login {
model = signal({ email: '', password: '' });
loginForm = form(this.model, (schemaPath) => {
required(schemaPath.email);
email(schemaPath.email);
required(schemaPath.password);
});
submitted = signal(false);
onSubmit(event: Event) {
event.preventDefault();
if (this.loginForm().valid()) {
this.submitted.set(true);
}
}
}
describe('Login', () => {
let fixture: ComponentFixture<Login>;
let component: Login;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [Login],
}).compileComponents();
fixture = TestBed.createComponent(Login);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should be invalid when empty', () => {
expect(component.loginForm().invalid()).toBeTrue();
});
it('should be valid with correct data', () => {
component.model.set({
email: 'test@example.com',
password: 'password123',
});
expect(component.loginForm().valid()).toBeTrue();
});
it('should show email error for invalid email', () => {
component.loginForm.email().value.set('invalid');
fixture.detectChanges();
expect(component.loginForm.email().invalid()).toBeTrue();
expect(component.loginForm.email().errors().some(e => e.kind === 'email')).toBeTrue();
});
it('should disable submit button when invalid', () => {
const button = fixture.nativeElement.querySelector('button');
expect(button.disabled).toBeTrue();
});
});
```
### Testing Reactive Forms
```typescript
describe('ReactiveForm', () => {
it('should validate form', () => {
const fixture = TestBed.createComponent(ProfileForm);
const component = fixture.componentInstance;
expect(component.form.valid).toBeFalse();
component.form.patchValue({
name: 'John',
email: 'john@example.com',
});
expect(component.form.valid).toBeTrue();
});
it('should show validation errors', () => {
const fixture = TestBed.createComponent(ProfileForm);
fixture.detectChanges();
const emailControl = fixture.componentInstance.form.controls.email;
emailControl.setValue('invalid');
emailControl.markAsTouched();
fixture.detectChanges();
const errorElement = fixture.nativeElement.querySelector('.error');
expect(errorElement.textContent).toContain('Invalid email');
});
});
```
## Testing Directives
### Attribute Directive
```typescript
@Directive({
selector: '[appHighlight]',
host: {
'[style.backgroundColor]': 'color()',
},
})
export class Highlight {
color = input('yellow', { alias: 'appHighlight' });
}
describe('Highlight', () => {
@Component({
imports: [Highlight],
template: `<p appHighlight="lightblue">Test</p>`,
})
class Test {}
it('should apply background color', () => {
const fixture = TestBed.createComponent(Test);
fixture.detectChanges();
const p = fixture.nativeElement.querySelector('p');
expect(p.style.backgroundColor).toBe('lightblue');
});
});
```
### Structural Directive
```typescript
@Directive({
selector: '[appIf]',
})
export class If {
private templateRef = inject(TemplateRef);
private viewContainer = inject(ViewContainerRef);
condition = input.required<boolean>({ alias: 'appIf' });
constructor() {
effect(() => {
if (this.condition()) {
this.viewContainer.createEmbeddedView(this.templateRef);
} else {
this.viewContainer.clear();
}
});
}
}
describe('If', () => {
@Component({
imports: [If],
template: `<p *appIf="show()">Visible</p>`,
})
class TestCmpt {
show = signal(false);
}
it('should show content when condition is true', () => {
const fixture = TestBed.createComponent(Test);
fixture.detectChanges();
expect(fixture.nativeElement.querySelector('p')).toBeNull();
fixture.componentInstance.show.set(true);
fixture.detectChanges();
expect(fixture.nativeElement.querySelector('p')).toBeTruthy();
});
});
```
## Testing Pipes
```typescript
@Pipe({ name: 'truncate' })
export class Truncate implements PipeTransform {
transform(value: string, length: number = 50): string {
if (value.length <= length) return value;
return value.substring(0, length) + '...';
}
}
describe('Truncate', () => {
let pipe: Truncate;
beforeEach(() => {
pipe = new Truncate();
});
it('should not truncate short strings', () => {
expect(pipe.transform('Hello', 10)).toBe('Hello');
});
it('should truncate long strings', () => {
expect(pipe.transform('Hello World', 5)).toBe('Hello...');
});
it('should use default length', () => {
const longString = 'a'.repeat(60);
const result = pipe.transform(longString);
expect(result.length).toBe(53); // 50 + '...'
});
});
```
## E2E Testing Setup
### Playwright Configuration
```typescript
// playwright.config.ts
import { defineConfig } from '@playwright/test';
export default defineConfig({
testDir: './e2e',
fullyParallel: true,
forbidOnly: !!process.env.CI,
retries: process.env.CI ? 2 : 0,
workers: process.env.CI ? 1 : undefined,
reporter: 'html',
use: {
baseURL: 'http://localhost:4200',
trace: 'on-first-retry',
},
webServer: {
command: 'npm run start',
url: 'http://localhost:4200',
reuseExistingServer: !process.env.CI,
},
});
```
### E2E Test Example
```typescript
// e2e/login.spec.ts
import { test, expect } from '@playwright/test';
test.describe('Login', () => {
test('should login successfully', async ({ page }) => {
await page.goto('/login');
await page.fill('input[name="email"]', 'test@example.com');
await page.fill('input[name="password"]', 'password123');
await page.click('button[type="submit"]');
await expect(page).toHaveURL('/dashboard');
await expect(page.locator('h1')).toContainText('Welcome');
});
test('should show error for invalid credentials', async ({ page }) => {
await page.goto('/login');
await page.fill('input[name="email"]', 'wrong@example.com');
await page.fill('input[name="password"]', 'wrongpassword');
await page.click('button[type="submit"]');
await expect(page.locator('.error')).toBeVisible();
await expect(page.locator('.error')).toContainText('Invalid credentials');
});
});
```
## Test Utilities
### Custom Test Helpers
```typescript
// test-utils.ts
export function setSignalInput<T>(
fixture: ComponentFixture<any>,
inputName: string,
value: T
): void {
fixture.componentRef.setInput(inputName, value);
fixture.detectChanges();
}
export async function waitForSignal<T>(
signal: () => T,
predicate: (value: T) => boolean,
timeout = 5000
): Promise<T> {
const start = Date.now();
while (Date.now() - start < timeout) {
const value = signal();
if (predicate(value)) return value;
await new Promise(resolve => setTimeout(resolve, 10));
}
throw new Error('Timeout waiting for signal');
}
// Usage
it('should load data', async () => {
const fixture = TestBed.createComponent(Data);
fixture.detectChanges();
await waitForSignal(
() => fixture.componentInstance.data(),
data => data !== undefined
);
expect(fixture.componentInstance.data()).toBeDefined();
});
```
@@ -0,0 +1,164 @@
# Vitest Setup and Migration Guide
## Vitest vs Jasmine Comparison
| Feature | Vitest | Jasmine/Karma |
|---------|--------|---------------|
| Speed | Faster (native ESM) | Slower |
| Watch mode | Instant feedback | Slower rebuilds |
| Mocking | `vi.fn()`, `vi.mock()` | `jasmine.createSpy()` |
| Assertions | `expect()` (Chai-style) | `expect()` (Jasmine) |
| UI | Built-in UI mode | Karma browser |
| Config | `angular.json` | `karma.conf.js` |
## Migration from Jasmine to Vitest
### Spy Migration
```typescript
// Jasmine
const spy = jasmine.createSpy('callback');
spy.and.returnValue('value');
expect(spy).toHaveBeenCalledWith('arg');
// Vitest
const spy = vi.fn();
spy.mockReturnValue('value');
expect(spy).toHaveBeenCalledWith('arg');
```
### SpyOn Migration
```typescript
// Jasmine
spyOn(service, 'method').and.returnValue(of(data));
// Vitest
vi.spyOn(service, 'method').mockReturnValue(of(data));
```
### createSpyObj Migration
```typescript
// Jasmine
const mockService = jasmine.createSpyObj('UserService', ['getUser', 'updateUser']);
mockService.getUser.and.returnValue(of({ id: '1', name: 'Test' }));
// Vitest
const mockService = {
getUser: vi.fn(),
updateUser: vi.fn(),
};
mockService.getUser.mockReturnValue(of({ id: '1', name: 'Test' }));
```
### Async Testing Migration
```typescript
// Jasmine - using done callback
it('should load data', (done) => {
service.loadData().subscribe(data => {
expect(data).toBeDefined();
done();
});
});
// Vitest - using async/await
it('should load data', async () => {
const data = await firstValueFrom(service.loadData());
expect(data).toBeDefined();
});
```
### Clock/Timer Migration
```typescript
// Jasmine
jasmine.clock().install();
jasmine.clock().tick(1000);
jasmine.clock().uninstall();
// Vitest
vi.useFakeTimers();
vi.advanceTimersByTime(1000);
vi.useRealTimers();
```
## Vitest Configuration Details
### Full angular.json Configuration
```json
{
"projects": {
"your-app": {
"architect": {
"test": {
"builder": "@angular/build:unit-test",
"options": {
"tsConfig": "tsconfig.spec.json",
"buildTarget": "your-app:build"
}
}
}
}
}
}
```
### tsconfig.spec.json
```json
{
"extends": "./tsconfig.json",
"compilerOptions": {
"types": ["vitest/globals"]
},
"include": ["src/**/*.spec.ts"]
}
```
### Optional vite.config.ts
For advanced configuration, create a `vite.config.ts`:
```typescript
import { defineConfig } from 'vitest/config';
export default defineConfig({
test: {
globals: true,
environment: 'jsdom',
include: ['src/**/*.spec.ts'],
coverage: {
provider: 'v8',
reporter: ['text', 'html', 'lcov'],
exclude: [
'node_modules/',
'src/test-setup.ts',
'**/*.spec.ts',
'**/*.d.ts',
],
},
},
});
```
## Running Vitest
```bash
# Run tests
ng test
# Watch mode
ng test --watch
# Coverage
ng test --code-coverage
# Run specific file pattern
ng test --include='**/user*.spec.ts'
# CI mode (single run)
ng test --watch=false
```
+795
View File
@@ -0,0 +1,795 @@
---
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/<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.service` or as defined in `SRC_STRUCTURE.md`). Inject with `inject(HttpService)` in field initializers.
- **Response shape:** every JSON endpoint returns `ApiResult<T>` or `ApiResultArray<T>`:
```ts
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 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<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` (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<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.
```ts
@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()` 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<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`, 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` (`<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 `LiveAnnouncer` or an `aria-live="polite"` region.
- Drawers and dialogs use CDK `Overlay` / `Dialog` with focus trap, `Esc` to close, and focus restoration.
- Never convey state by color alone: pair it with icon + text.
- Honor `prefers-reduced-motion` in 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.js` and `src/assets/worklets/pcm-playback-processor.js` (see §1.5). Each starts with `// @ts-check` and 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 reports `started`, `drained`, `underrun`.
- Load modules with a **cache-busting version** and a base-href-aware URL:
```ts
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 `AudioContext` **only after a user gesture** (the orb click), via the holder in `core/audio/audio-context.provider.ts`. Never at app startup. Resume it if `state === 'suspended'`.
- Request the microphone with `echoCancellation`, `noiseSuppression`, `autoGainControl`, and `channelCount: 1`. Echo cancellation is mandatory because barge-in depends on it.
- Never assume the requested sample rate: read `ctx.sampleRate` and 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 `signal` that 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()`.
```ts
@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:
1. Start it **outside** the zone (a harmless no-op under zoneless, which keeps the code portable).
2. **No** `new` objects, arrays, closures, or strings inside the per-frame function.
3. 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.
4. Cap `devicePixelRatio` at 2; resize through a `ResizeObserver` created outside the zone.
5. **Pause** when the tab is hidden (`visibilitychange`) or the canvas is off-screen (`IntersectionObserver`).
6. Honor `prefers-reduced-motion` by choosing a calmer preset.
7. Provide a **Canvas 2D fallback** that implements the same `Visualizer` interface (WebGL missing or `webglcontextlost`).
8. 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()); })`.
- `ngOnDestroy` is acceptable when a class already implements `OnDestroy`; 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
- `voiceState` is written **only** by `VoiceSessionService` (`features/voice-agent/services/`), driven by the data table in `voice-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 (`interrupt` with `playedMs`). Never wait for the network.
- Agent audio frames carry a `turnId`; frames from a stale turn are dropped by `audio-stream.handler.ts`.
- `interrupted` is transient and resolves to `listening` after `FLUSH_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 `RealtimeTransport` abstraction (`core/websocket/realtime-transport.ts`). Feature code never touches `WebSocket` directly.
- Audio travels in **binary frames** with the documented header (`ARCHITECTURE.md` §5.2); control messages are JSON, typed by `ClientMessage` / `ServerMessage`. Set `binaryType = '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)
```text
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 `FaqStore` signals 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`** (via `FaqApiService` / `FaqIngestionService`). No feature injects `HttpClient` directly.
- `FaqIngestionService` is the only orchestrator of `validate → preview → upload → track status`.
- Status flows from the server through `IngestionEventsService` (SSE via `HttpService.getStream` or control messages) into `FaqStore` signals: `uploading → indexing → active | error`. Status is **never** inferred on the client.
- `features/faq-manager` must not import from `features/voice-agent` (and vice versa). Shared concerns go in `core/` or `shared/`.
- The voice session learns which documents to use only through `activeDocumentIds` in the session configuration (from `FaqStore.activeDocuments`), not by reaching into FAQ components.
### 4.2 PapaParse pre-parsing (CSV)
- **Lazy-load:** `const Papa = (await import('papaparse')).default;` inside `CsvParserService`. Never import it at the top of a component.
- **Preview** with `Papa.parse(file, { header: true, preview: N, skipEmptyLines: 'greedy', dynamicTyping: false })`, with `N` defaulting to 50.
- **Count and validate large files** with chunked streaming (`chunk` or `step`) so memory stays bounded. **Do not use `worker: 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 in `upload-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.ts` and `file-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 `FaqDocumentError` with a user-readable message and a `retryable` flag.
### 4.4 Upload, status, and Q&A editing
- Upload through **`HttpService`** (or `FaqApiService` built on it). If upload progress is required, extend `HttpService` with a progress-capable method rather than injecting raw `HttpClient` in a feature. Write `progress` into the document's signal state. Cancel with unsubscribe/`AbortController` when the owner is destroyed.
- The document row has one writer (`FaqStore`). Use immutable `update()` calls keyed by `id`.
- Q&A edits are **optimistic with rollback**: apply to `FaqStore`, send the request, roll back and toast on failure. A manual edit sets `overridden: true` so re-ingestion does not overwrite it.
- **AG Grid** (`ag-grid-angular`, `ag-grid-community` on 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).
---
## 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`):
```text
shared <- core <- features
```
- `shared` imports nothing from `core` or `features`.
- `core` imports from `shared` only, never from `features`.
- A feature never imports another feature.
- `core/audio` and `core/websocket` import 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://` and `https://` 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** by `AuthService` / `HttpService` (including 401 cleanup). Theme preference may live in `localStorage` **only** via `ThemeService`. Other preferences go through `StorageService` if present. Never tokens, transcripts, or file data in ad-hoc storage.
- Never use `innerHTML`, `bypassSecurityTrust*`, or `eval`/`new Function` with user, server, or model-generated text. Transcripts and Q&A are rendered as text.
- Every error path is handled: microphone denied, `AudioContext` suspended, worklet load failure, socket drop mid-turn, token expiry, WebGL context loss, upload failure. Map to `VoiceError` / `FaqDocumentError` and 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 only `console.log` them.
- Protect authenticated routes with `authGuard`. Do not implement a second guard that bypasses `AuthService.isAuthenticated()`.
---
## 7. Testing Rules
- **Colocate** `*.spec.ts` next 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`.
- `VoiceSessionService` is tested with fake `AudioEngine` and fake `RealtimeTransport`, including barge-in races and stale `turnId` frames.
- Configure tests for zoneless (`provideZonelessChangeDetection()`); await `fixture.whenStable()`; do not use `fakeAsync`.
- 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.OnPush` present on every component I created or touched?
- [ ] **Signals:** Is UI state in `signal()` / `computed()` / `linkedSignal()` (not `BehaviorSubject`, 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 inside `NgZone.runOutsideAngular()`, with **no signal read or written per frame**?
- [ ] **Cleanup:** Is every subscription, `AudioContext`, `AudioWorkletNode`, `MediaStream` track, `WebSocket`, observer, timer, overlay, and Three.js object (geometry, material, texture, renderer) released through `DestroyRef` / effect cleanup / `ngOnDestroy`?
- [ ] **Paths:** Does every file path match `./docs/SRC_STRUCTURE.md`, and do the imports respect `shared <- core <- features`?
- [ ] **Separate files:** Does every component/page have separate `.ts` + `.html` + `.css` files (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` (with `track`) / `@switch`; templates call only signals/computeds.
- [ ] Zoneless provider matches the installed Angular major (§1.5); no reliance on `NgZone.onStable` or `detectChanges()` in hot paths.
- [ ] One writer per state; public API exposes `asReadonly()`.
- [ ] No `effect()` used to derive state; no signal writes inside `computed()`.
- [ ] Exhaustive `switch` on 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.
- [ ] `AudioContext` is 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 `turnId` frames are dropped.
- [ ] Visualizer pauses when hidden, caps DPR at 2, honors `prefers-reduced-motion`, and has a fallback.
- [ ] `three` is lazily imported with named imports; shaders are imported as text from `core/audio/visualizer/shaders/`.
### 9.4 FAQ and file handling
- [ ] PapaParse is lazily imported, used with `preview`/chunking (never `worker: 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 through `shared/ui/icon`.
- [ ] Tailwind tokens and logical properties used; no hard-coded colors; no `ml-*`/`pr-*`.
- [ ] Accessible names, keyboard support, and `aria-live` for 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/*.md` file in the same change.
- [ ] **Http / Auth / Theme:** all API calls go through `HttpService`; login and session via `AuthService` + `authGuard`; theme init/toggle via `ThemeService` only (no parallel clients or direct token/theme storage).
---
## 10. Response Protocol for Agents
1. **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.
2. **Code:** complete files or clear diffs. No `// ...rest of code`, no pseudo-code, no TODO placeholders for core logic.
3. **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.
4. **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.
5. **Keep changes minimal and focused.** Mention (do not perform) unrelated cleanups.
6. **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`**
```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`**
```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`**
```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.