# Project XiaoChun — Full Technical Documentation

> 100% browser-native 3D anime companion (二次元伴侣). Complete architecture, dependency inventory, AI inference pipelines, modular 3D engine, universal motion pipeline, i18n / SSR setup, and Cloudflare Workers deployment guide.

---

## 1. System Architecture

Project XiaoChun is a full-stack web application built on **Vite 8 + TanStack Start (full-stack SSR) + React 19 + three.js 0.185** deployed to **Cloudflare Workers**. WebLLM, EMAGE, and on-device `@firetable/stream-asr` streaming STT run in the browser tab; Edge-TTS audio is proxied at the edge; the edge runtime handles SSR stream rendering and WebSocket Edge-TTS proxying.

- **3D Engine Architecture**: Decoupled into modular sub-engines:
  - `src/core/vrmEngine.ts`: Master facade and lifecycle coordinator, supporting both **VRM 1.0** and **VRM 0.x** avatars seamlessly.
  - `src/core/character/vrmCharacter.ts`: VRM 1.0 & VRM 0.x lifecycle, spring bones (`VRMSpringBoneManager`), MToon material calibration, facial expression presets, and LookAt head tracking.
  - `src/core/lighting/studioLighting.ts`: 3-channel studio lighting rig (directional sun `1.00`, hemisphere sky/ground `0.95`, back-rim fill `1.40`) with 2048 PCFSoft shadow camera.
  - `src/core/scene/lineworkWorld.ts`: Procedural linework outdoor world with Light / Dark dual themes (sun with radial rays, 19 buildings, wireframe ground grid, 5 stylized trees).
  - `src/core/material/vrmMaterialManager.ts`: Semantic material categorization with dynamic `uMatSaturation` fragment shader injection.
  - `src/core/morph/vrmBodyMorph.ts`: 28-parameter body morphing with orthogonal bone scaling (VRoid 1.0 guarded).
  - `src/core/postfx/postFxPipeline.ts`: Cinematic post-processing pipeline (UnrealBloomPass background luminance filter, ToneMapping, ColorGrading, and physical bypass).
  - `src/core/outfitSwap.ts`: Snapshot capture & in-memory pre-restore atomic outfit swapping.
  - `src/core/vrmWorker.ts`: Dedicated worker with WASM bspatch and 2-tier IndexedDB delta cache.
  - `src/core/render/vrmRenderLoop.ts`: Adaptive requestAnimationFrame render loop with visibility-aware throttling and clock delta clamping.
- **Universal Motion Pipeline (`src/motion/pipeline/motionPipeline.ts`)**:
  - Unifies custom clips (mixamo, bvh, fbx, vrma), procedural natural idle/breathing, and AI co-speech motion (EMAGE) under a single pipeline.
  - Transparently bridges VRM 1.0 ($+Z$ facing) authoring into VRM 0.0 ($-Z$ facing, local $X/Z$ mirrored) in `PoseBuffer.commitToVRM` and `sampleFromVRM`.
  - Features dual-mode crossfade (smooth blending or instantaneous cuts), Quintic Smootherstep 0.75s inbetweening, non-linear root displacement locking (anti-ground-penetration), and automated rest-pose restoration.
- **Application Framework**: TanStack Start provides file-based routing, full-stack SSR, and server-only helpers (`createServerOnlyFn`, `getCookie` from `@tanstack/react-start/server`).
- **Bundler**: Vite 8 with `@cloudflare/vite-plugin` and custom plugins in `vite/`: `localApiPlugin.ts` (TTS dev middleware + EU proxy), `dropDockerfatAssets.ts` (Cloudflare 25 MiB asset limit workaround).
- **LLM Layer**: Unified factory (`src/llm/chatWorkflow.ts`) dispatches between WebLLM and any custom OpenAI-compatible provider. Both implement the same `runChat(opts: RunChatOptions) → string` contract; new providers just need a `ChatProvider` descriptor.
- **Styling**: Tailwind CSS v4 with `@theme` tokens (`brand-*` coral palette, derived from the default VRM model's hair color) + `tailwindcss-animate` for micro-interactions.

---

## 2. AI Inference Pipelines

AI runs in the browser tab. **WebLLM may use WebGPU**; **EMAGE uses ONNX Runtime Web wasm + INT8 only** (int64 blocks WebGPU-EMAGE; E3-① closed):

### 2.1 LLM & Multimodal Vision (WebLLM, default)
- **Engine**: Workspace-patched `@firetable/web-llm` (`v0.2.88`) + `@firetable/web-runtime` (`0.28.0-dev2`) overriding `@mlc-ai/web-llm` and `@mlc-ai/web-runtime`, with `ThinMLCEngine` (`src/llm/webllmThinClient.ts`) on the main thread
- **Models**: MiniCPM5 2B (`MiniCPM5-2B-q4f16_1-MLC`, default), MiniCPM-V 4.7 1B (`MiniCPM-V-4.7-1B-q4f16_1-MLC`, on-device multimodal vision with SigLIP2 ViT + GatedDeltaNet), and Qwen2.5 0.5B (low-VRAM fallback) — downloaded on first launch and cached in `CacheStorage` (`cacheBackend: 'cache'`)
- **Model-Gated Vision Input**: Selecting a vision model unlocks image upload, drag-and-drop (`visionDropBus`, decoupled from `.vrm` drops), and clipboard paste (`Cmd/Ctrl + V`) in `ChatBar` (normalized client-side to max edge `1024px`, up to 4 images)
- **Runtime & 60 FPS Frame Pacing**: WebGPU with adaptive `desktop`/`mobile` cooperative frame pacing (`asyncLoadWebGPUPipelines` across all WebGPU sub-modules, `maxDispatchesPerEncoder` `24`/`12`, closed-loop weight upload slicing, and 64/128-token prefill yielding)
- **Streaming**: Chunked completion (`streamId` + `completionStreamReturn` early-abort lock release) with milestone callbacks (`loading-webgpu`, `thinking` states)
- **System Prompts**: Per-language (`src/llm/prompts.ts`) — each prompt enforces a `🌐 LANGUAGE RULE` so the LLM responds in the user's language regardless of input language

### 2.2 Custom OpenAI-Compatible Providers (optional)
- **Activation**: in-app **Custom Model Service** dialog (chat-bar menu or top-bar gear). Templates: Ollama / LM Studio / vLLM / LocalAI / Generic OpenAI-compatible.
- **Configuration**: `name` (display) + `baseURL` + optional `apiKey` + `model`. Test connection probes `GET {baseURL}/v1/models` before save.
- **Storage**: Each profile is a record in IndexedDB `xiaochun-providers` database, AES-GCM encrypted with PBKDF2-derived key from random salt. API keys never stored in plaintext.
- **Unified active key**: `custom:{providerId}` or `webllm:{modelId}` in localStorage (`xiaochun.llm.model`). Single source of truth. Upgrades from the previous sessionStorage-based active key start fresh on default — no migration, no legacy data.
- **Factory dispatch** (`chatWorkflow.getActiveChatRunner`): polls `ChatProvider` registry (`isActive` + `runChat`), picks first match. Custom takes precedence; webllm is fallback.
- **VRAM release**: when a custom provider is activated, `preloadWebLLM()` early-returns and `setActiveProviderId` calls `unloadEngine()` — releases 1-2 GB VRAM that webllm would have reserved.
- **Thinking mode**: passed through `extra_body: { enable_thinking: true }` (OpenAI-compatible convention used by DeepSeek / Qwen API / vLLM). Providers that don't support it silently ignore.
- **Output cleaning**: same `extractCleanSpeech` runs in chatWorkflow for both paths — strips `<think>` blocks, JSON wrappers, narrative parentheses, and quote marks.

### 2.3 Motion (EMAGE & Universal Motion Pipeline)
- **Model**: EMAGE full-body co-speech motion (PantoMatrix, Haiyang Liu, Zihao Zhu et al., [CVPR 2024](https://pantomatrix.github.io/EMAGE/); weights modified by this project, see packages/emage-onnx/NOTICE)
- **Runtime**: ONNX Runtime Web inside a Dedicated Web Worker (`src/motion/emageWorker.ts`) — **executionProviders: ['wasm']** + **INT8** (`useInt8`). **Not WebGPU** (int64).
- **Streaming**: Fixed **T=64** windows; per-window transferable **`motion_chunk`** for TTFA; A/V hold until TTS audible (`releaseMotionForAudio`).
- **Isolation (P0b)**: COOP/COEP `credentialless` on documents; SAB + wasm multi-thread when `crossOriginIsolated`.
- **Config**: `APP_CONFIG.emage.motion` hop/seams (`advanceFrames` 60..64). `vqFace` / `vqGlobal` disabled. Parallel VQ not viable on ORT WASM.
- **Orchestrator**: `src/motion/emagePlayer.ts` — streaming player, temporal Gaussian smoothing, natural idle blends → Universal Motion Pipeline Layer 1.
- **Status doc**: `docs/EMAGE_MODEL.md` (export = emage-onnx-export README scripts only). **Not shipped**: WebGPU-EMAGE, P0d residual-gate.

### 2.4 TTS & Vocal Post-Processing Pipeline
- **Edge TTS Engine**: native WebSocket client `src/lib/edge-tts-core.ts` (Microsoft Edge-TTS protocol; no third-party TTS SDK)
- **Default voice**: `zh-CN-XiaoyiNeural` with `+10Hz` pitch (energetic anime-girl timbre)
- **Production endpoint**: Cloudflare Worker at `src/server.ts` — opens WebSocket to `speech.platform.bing.com` / `api.msedgeservices.com`, streams audio chunks as `audio/mpeg`
- **Dev endpoint**: Same shape, served by `vite.config.ts → localApiPlugin` middleware with Miniflare / EU egress proxy
- **Emoji handling**: Text passed to TTS is stripped of `\p{Extended_Pictographic}` characters to avoid prosody glitches (Microsoft TTS tends to over-articulate emoji)
- **Client-Side Tone.js Vocal DSP Pipeline (`src/director/vocalProcessor.ts`)**:
  - Encapsulates Web Audio API and Tone.js 15.x (`VocalAudioProcessor`) inserted between `sourceNode` and audio output.
  - **Decoupled Lip-Sync**: Raw decoded audio is sent directly to `AnalyserNode` for viseme calculation and EMAGE motion prediction. EQ, compression, and reverb coloration never contaminate mouth shapes or body gesture timing.
  - **Dual-Branch Signal Routing**:
    - *Dry Bypass Branch* (`inputNode -> dryGain -> outputNode`): Active on default `bypass` (原声直通) preset or when enhancement is disabled. Completely bypasses filters and reverb with 0 phase shift and 0 latency.
    - *Wet Enhancement Chain* (`inputNode -> lowCut -> eq -> compressor -> reverb -> wetGain -> outputNode`): Highpass low-cut (80Hz), 3-band EQ3 (350Hz low chest resonance, mid clarity, 3500Hz high air), dynamic compressor (fast 10ms attack, 150ms release), and Freeverb room reflection.
  - **3D Camera Distance Attenuation Curve**:
    - *Near-field proximity* ($0.6\text{m} \sim 2.2\text{m}$): Volume boosted smoothly up to $+3.0\text{ dB}$, Low EQ (350Hz chest resonance) boosted up to $+3.0\text{ dB}$ for an intimate, close-mic whisper feel.
    - *Normal & mid-field flat zone* ($2.2\text{m} \sim 8.0\text{m}$): Completely flat unity gain ($0\text{ dB}$ offset, $0\text{ dB}$ chest resonance offset) ensuring pristine, uncolored conversation dialogue.
    - *Far-field distance falloff* ($8.0\text{m} \sim 15.0\text{m}$): Volume smoothly attenuates from $0\text{ dB}$ at $8.0\text{m}$ down to $-8.0\text{ dB}$ ($\approx 0.40\times$) at $15.0\text{m}$.
  - **Web Audio Safety Standard (`safeRampParam`)**: Uses `targetRampTo` (`setTargetAtTime`) and `linearRampTo` over 30ms windows to avert Web Audio `DOMException` when setting $\le 0$ dB on Tone.js decibel parameters.
  - **Presets**: `bypass` (default), `sweet`, `oneesan`, `radio`, `whisper`. Presets modify acoustic sliders only, never touching top-level switches (`enabled`, `sceneLinkage`, `distanceAttenuation`). Full documentation in `docs/TTS.md`.

### 2.5 Chat Director
- **File**: `src/director/chatDirector.ts`
- **Role**: Orchestrates LLM → TTS → EMAGE as a single streaming pipeline. Each utterance triggers:
  1. LLM streaming token callbacks
  2. On utterance boundary: dispatch to TTS (begin Edge-TTS WebSocket, stream audio to user)
  3. EMAGE receives the same utterance and generates motion frames in lockstep
  4. Lip-sync (viseme blending) updates from TTS audio energy + EMAGE mouth keyframes
- **Cancellation**: New user message cancels in-flight LLM/TTS/EMAGE via token cancellation

### 2.6 Cognitive Memory System (`@firetable/client-memory`)
- **Package**: `packages/client-memory/` and integration in `src/memory/`
- **Storage**: Browser-native IndexedDB database `client-memory-db` with four object stores (`turns`, `profile`, `episodes`, `lorebooks`). Zero telemetry or server transfer.
- **4-Tier Architecture**:
  1. *Working Turns*: Recalls last $N$ dialogue rounds (device-recommended 2~6 turns, customizable 1–50) for immediate conversational context.
  2. *User Persona & Facts*: Heuristic regex extraction (`IntentExtractor`) captures user nickname, occupation, location, and likes/dislikes with single-value overwrites and deduplication (`ConflictResolver`, max 60 facts).
  3. *Long-Term Episodic Journal*: Consolidates turns beyond the short-term window into narrative memory cards (`EpisodicConsolidator`), ranked via Stanford Generative Agents 3D cognitive scoring ($\text{Recency Decay} + \text{Importance} + \text{BM25 Relevance}$).
  4. *SillyTavern Lorebooks*: Ingests and matches Tavern worldbook entries with constant and keyword-based injection.
- **Deterministic Prefix Assembly**: Formats memory with strict prefix stability (`ContextAssembler`) to maximize WebLLM KV-cache reuse.
- **UI HUD & Safety**: Standalone `MemoryDialog` with 3 segmented tabs (`[记忆画像]`, `[时光回忆]`, `[世界书]`), inline SillyTavern JSON import, and a 2-step confirmation memory reset with 4s timeout protection (`memory.clearAll({ includeLorebook: false })`). Details in `/docs/CLIENT_MEMORY.md`.

---

## 3. i18n & SSR Hydration

- **Library**: `i18next` + `react-i18next`
- **Languages shipped**: `zh-CN`, `en`, `ja` (each in `src/i18n/<lang>.ts`, typed against `typeof zh-CN` for shape safety)
- **SSR hydration**: Cookie-based — `@tanstack/react-start/server`'s `getCookie()` reads the `lang` cookie during SSR. Wrapped in `createServerOnlyFn` (`src/i18n/server.ts`) so the server-only import never lands in the client bundle (TanStack Start's import-protection enforces this).
- **Client fallback**: `readClientLang()` parses `document.cookie` for the same value, ensuring zero hydration mismatch.
- **Per-language system prompts**: `src/llm/prompts.ts` exports `XIAOCHUN_SYSTEM_PROMPT: Record<Lang, string>` — same prompt template, three localized variants.

---

## 4. VRM Character & Scene

- **Default model & Delta Addons**:
  - Base model: `public/vrm/xiaochun_base.vrmbase` (~5.9 MB stripped base model, oxipng texture-compressed). Generated with [VRoid Studio](https://vroid.com/en/studio) (Pixiv Inc.), subject to the VRoid Studio License.
  - Addon outfits: 5 `.vrmaddon` files (`xiaochun_default.vrmaddon` Techwear, `xiaochun_cheongsam.vrmaddon`, `xiaochun_bikini.vrmaddon`, `xiaochun_maid.vrmaddon`, `xiaochun_swimsuit.vrmaddon`).
  - Patched in background via WASM bspatch (`src/core/vrmWorker.ts`) and cached in 2-tier IndexedDB (`xiaochun-vrm-cache`, base & patched stores).
  - Atomic Outfit Swapping (`src/core/outfitSwap.ts`): state snapshot & in-memory pre-restore guarantees zero-frame T-pose pop-in during clothing transitions.
- **Default thinking animation**: `public/vrm/motion/thinking.vrma` (63 KB, VRM animation, license unverified — verify before redistribution)
- **Runtime VRM upload**: Top-bar "上传 VRM" button (top-right) accepts any standard VRM 1.0 or VRM 0.x file via `<input type="file">` and `URL.createObjectURL`, seamlessly adapting bone coordinate spaces and ground anchors.
- **Scene composition** (`src/core/scene/lineworkWorld.ts`):
  - Procedural line-art outdoor world with Light / Dark dual themes (`linework-light` / `linework-dark`).
  - **Sun**: Spherical mesh at `(10, 14, -22)`, radius 1.5 with 12 radial line rays.
  - **Ground**: 60×60 wireframe grid (`WireframeGeometry` + `LineSegments`).
  - **Buildings**: 19 procedurally-placed wireframe buildings across 5 archetypes (cube / tall-rect / step-pyramid / cylinder / cross).
  - **Trees**: 5 stylized trees across 5 archetypes (conifer / fan / layered / cypress / vertical-oval). Trunk height `max(1.7, totalH * 0.35)` so all trunks reach character waist level.
- **Lighting** (`src/core/lighting/studioLighting.ts` — 3 independent channels):
  - `dir`: Main directional (sun), `base: 1.00`, position aligned with sun mesh.
  - `hemi`: Hemisphere sky/ground, `base: 0.95`.
  - `fill`: Back-rim fill, `base: 1.40`.
  - Global multiplier `1.0`.
- **Post-Processing Pipeline** (`src/core/postfx/postFxPipeline.ts`):
  - `UnrealBloomPass`: Luminance-filtered anime halo (threshold 0.75, strength 0.35, radius 0.65) with linework background rejection (`bloomBypassBackground: true`).
  - `ToneMapping`: ACESFilmic / Neutral / Cineon / Linear / None selectable with exposure control.
  - `ColorGrading`: Brightness, contrast, hue shift, and saturation adjustments.
- **Camera**: PerspectiveCamera, default FOV 20° (configurable via `APP_CONFIG.camera.defaultFov`), target `(0, 1.2, 0)`. Default position is **computed** via `computeDefaultCameraPosition()` from `defaultShotExtent` (1.4m) and the current FOV using `distance = extent / (2·tan(fov/2))`, so 15°/20°/60° all frame the same subject height instead of the previous fixed 3.6m close-up at long focal lengths. `fitCamera()` uses the same formula against the head bone instead of the previous hardcoded `z + 2.2`. Mouse-wheel / pinch zoom is clamped by `OrbitControls.minDistance / maxDistance`, both editable from the debug drawer's Camera section (defaults 1.0 / 15.0).

---

## 5. Mobile & Accessibility

- **Touch targets**: All interactive elements ≥ 40 px on mobile, ≥ 44 px for primary CTA. Follows iOS HIG 44 pt / Material 48 dp.
- **Input field**: 16 px font (iOS Safari won't auto-zoom on focus at ≥ 16 px).
- **Responsive breakpoints**: Tailwind `sm:` (≥ 640 px). Mobile-first; desktop tightens spacing.
- **Top-bar icons** (globe / settings) wrapped in Radix Tooltip with `delayDuration={300ms}` so they don't flash on quick hover; icons alone on mobile, label-on-tap reveal.
- **Speech bubble**: Floats above the character's head, follows head motion via additive `transform` interpolation with `transition-duration: 150ms`. Max width 240 px (mobile) / 320 px (desktop) with `break-words`.

---

## 6. Build & Deploy

### 6.1 Build
```bash
pnpm install
pnpm build    # tsc + vite build → dist/
```

### 6.2 Vite Plugins (`vite/`)
- **`localApiPlugin.ts`** — `/api/tts` dev middleware. If `TTS_PROXY_URL` env var is set, forwards the request to that endpoint (auto-appends `/api/tts` if missing); otherwise falls back to local `src/lib/edge-tts-core.ts`. Solves EU egress issues where Microsoft TTS endpoints hang.
- **`dropDockerfatAssets.ts`** — strips oversized assets from production build. Cloudflare Pages has a 25 MiB per-file limit; this removes `onnxruntime-web`'s `ort-wasm-simd-threaded.jsep.wasm` (26.5 MiB WebGPU EP variant, loaded from jsDelivr at runtime instead) and training data JSONs.

### 6.3 Cloudflare Workers (production)
- **Configuration**: `wrangler.jsonc` (`nodejs_compat` enabled, static assets bound to `./dist/client`)
- **Headers**: `public/_headers` + `src/server.ts` document headers define COOP/COEP `credentialless` (SAB / ORT wasm threads when isolated; Workers+Assets ignores `_headers` for HTML), security headers, and cache policy (`/assets/*` immutable; root path `must-revalidate`)
- **SSR & TTS Entry**: `src/server.ts` — full-stack SSR router + edge-runtime TTS WebSocket proxy
- **Static assets**: `dist/client/*` served directly via Cloudflare Assets (robots.txt, sitemap.xml, llms.txt, llms-full.txt, VRM model, fonts)

### 6.4 Two Deploy Modes
- **One-Command CLI (recommended)**: `pnpm deploy` (`pnpm build && wrangler deploy`)
- **Git-integrated**: Push to GitHub → Cloudflare Dashboard → Workers & Pages → Connect Git (leave Root directory blank) → auto-deploy on push.

### 6.5 First-Run Notes
- WebLLM downloads ~400 MB model on first browser visit; cached in `CacheStorage` thereafter. **Skipped entirely** when a custom OpenAI-compatible provider is active.
- VRM model (18 MB) is shipped in the bundle; not lazy-loaded.
- TTS endpoint has no auth — keep behind custom domain to avoid random abuse.
- Environment variables: see `.env.example` for the full list (`VITE_EMAGE_BASE`, `TTS_PROXY_URL`, `VITE_PROVIDER_*_URL` overrides). Copy to `.env.local` and fill in; `.env.local` is git-ignored.

---

## 7. API Reference

### `GET /api/tts`
Synthesizes text to speech via Microsoft Edge-TTS (XiaoyiNeural zh-CN).

**Query parameters**:
- `text` (required) — text to synthesize, URL-encoded
- `voice` (optional) — voice full name (default `zh-CN-XiaoyiNeural`)
- `pitch` (optional) — prosody pitch (default `+10Hz`)

**Response**: `audio/mpeg` stream, `Cache-Control: public, max-age=86400`

**CORS**: `Access-Control-Allow-Origin: *`

**Example**:
```
GET /api/tts?text=你好&voice=zh-CN-XiaoyiNeural&pitch=%2B10Hz
```

---

## 8. Debug Drawer (localhost-only developer panel)

Visible only when the page is served from a non-production host. Lives at `src/components/dev-drawer/` and is an **8-section** schema-driven panel:

1. **🎭 预设表情 / Expressions** — 6 preset buttons (default / happy / angry / sad / relaxed / surprised) bound to `vrmEngine.setExpression()`.
2. **🎥 镜头设置 / Camera** — FOV slider (15-60°, default 20°) with hover `ⓘ` tooltip explaining 20°/30°/45°/60° reference values; min / max camera distance sliders (mouse wheel / pinch zoom range, defaults 1.0-15.0); automatic body-turn toggle.
3. **🎨 画面色彩与饱和度 / Material Saturation** — 4 sliders (clothing / hair / eyes / skin) + 4 preset buttons (元气 vibrant / 甜美 sweet / 胶片 cinematic / 原画 original), driven by `uMatSaturation` shader uniform.
4. **✨ 骨骼体型微调 / Bone Morph** — 28 sliders grouped into 7 body-region sub-cards (整体 / 头颈 / 躯干 / 臀部 / 胸部 / 上肢 / 下肢). Shoulder width defaults to 110% with a range up to 250%. Each category is a self-contained sub-card with its label outside; search box filters and hides empty regions. Modified detection is per-section (uses a `useRef` baseline at mount, not `APP_CONFIG` defaults).
5. **🧩 模型部位调整 / Wardrobe** — 3-state per-part rendering: 穿 (checkbox on, normal) / 未穿 (checkbox off, line-through) / 未装配 (dashed disabled div, no checkbox). "Equipped" comes from `vrmEngine.materialManager.partMaterials[id]?.length > 0` — not the user's visibility toggle. Note: For full-character outfit changing, use the TopHeader outfit selector.
6. **💡 灯光通道与全局倍率 / Lighting** — 3 studio channels (dir / hemi / fill) with independent enable toggle + brightness slider, plus a global multiplier slider.
7. **🔮 画面后期调色 / PostFx** — Post-processing toggle, Bloom sliders (strength, radius, threshold), ToneMapping selector (ACESFilmic, Neutral, Cineon, Linear, None) with exposure slider, Color grading sliders (brightness, contrast, hue shift, saturation), and background bloom bypass toggle.
8. **⚡ EMAGE Perf / EmagePerfSection** — P0b acceptance panel: `crossOriginIsolated`, SharedArrayBuffer, `numThreads`, stage timings (screenshot-friendly; no public UX).

### Architecture highlights

- **Per-section state isolation**: Each section owns its `useState`. A 28-slider `BoneMorphSection` does not re-render its siblings on drag.
- **Slider drag split** (`SliderWithAnchors`): per-frame `onTick` writes the engine directly (canvas stays smooth); `onChange` (Radix `onValueCommit`, fires on release) updates React state + `localStorage` once per drag. The 28-slider section therefore writes `localStorage` exactly 1 time per drag, not 60+ times.
- **Per-frame display without re-render**: Section passes `liveValueRef` + `liveValueFormatter` to `SliderWithAnchors`; a `useEffect([local])` writes `ref.current.textContent` imperatively, so the `90%` number follows the thumb in real time without React reconciliation.
- **Global reset broadcast**: A `resetSignal` counter on `DevDrawerContext` is included in `<SectionRenderer key={...}>`; on global reset the shell bumps it, React unmounts and remounts every section, and each section's `useState` initializer re-runs against the now-defaulted engine.
- **Schema-driven render order**: `src/components/dev-drawer/schema.ts` `SECTIONS[]` defines the order; `renderer.tsx` `REGISTRY` maps id → component. Adding a section = one line in `SECTIONS` + one in `REGISTRY`.
- **Collapse gate**: `SectionCard` accepts an optional `id` prop — when set, it reads `collapsed.has(id)` from context and hides everything except the first child (the header). Eight sections set their `id`; nested cards (bone morph categories) leave it off.

Full implementation details in [`docs/ARCHITECTURE_AND_RULES.md` §3](https://github.com/FireTable/project-xiaochun/blob/main/docs/ARCHITECTURE_AND_RULES.md).

---

## 9. Native Hybrid Desktop Companion (Tauri 2.x) & IPC Protocol

Project XiaoChun features a cross-platform desktop build powered by **Tauri 2.x**:

### 9.1 Transparent Desktop Companion
- **Frameless OS Compositing**: Floats borderless and chromeless with true alpha transparency directly above the user's workspace.
- **60Hz Alpha Bitmask Click-Through Engine**: A dedicated background thread in `src-tauri/src/lib.rs` computes real-time 1-nanosecond bitwise hit tests on the rendered canvas alpha channel. Transparent spaces pass clicks through to background OS windows, while solid parts (character, clothing, UI) capture mouse events.
- **Window State Persistence**: Automatically records and restores window dimensions and screen coordinates via `tauri-plugin-window-state`.

### 9.2 Cross-Process Protocol (`xiaochun://`)
- **System URL Scheme**: Registered custom protocol (`xiaochun://`) allows external tools, AI coding agents, and shell scripts to awaken XiaoChun.
- **Single-Instance Multiplexing**: If XiaoChun is already running, triggering a URL unminimizes and focuses the companion without launching redundant processes.
- **Action Dispatcher**: Invoking `xiaochun://speak?text=...` or `xiaochun://speak?file=/path/to/txt` queues speech directly to `vrmEngine.speakText` with real-time lip-sync and 3D EMAGE gestures.
- **Agent Skill Integration**: Out-of-the-box standard AI Agent skill specification defined in `docs/AGENT_SKILL.md`.

---

## 9.3 Embedding & Host-Audio Sync (`/embed`, `@firetable/project-xiaochun`)

- `speakAudio(source, opts)` / `xc.audio`: host audio → EMAGE motion + RMS lip-sync. `audible: false` mutes the iframe so the page can be the only speaker. `playbackRate` 0.25–3 and `volume` 0–1; change live with `setPlaybackRate()` / `setVolume()` (`xc.transport`).
- **Host clock (0.1.35+)**: `hostClock: true` skips the thinking pose and start-up wait (`utterance start` as soon as the first motion window is ready). Then `syncClock({ time, playing, playbackRate?, seek? })` (`xc.clock`; `time` = seconds from the start of that `speakAudio` audio) drives motion + lips: `seek: true` snaps, `playing: false` freezes, in-audio seeks do not restart EMAGE; without clock messages it free-runs from start. Capability: `capabilities.audio.hostClock`; SDK `supportsHostClock()`. Older embeds ignore `hostClock`, and `syncClock()` returns `false` there.
- **Recommended host pattern**: fetch the audio once and share it (blob URL for the page `<audio>`, same bytes to `speakAudio`); hold the page player until `utterance start` (with a fallback timeout); send `syncClock` every ~250 ms and on play / pause / seeked / waiting; re-issue `speakAudio` only for seeks outside the sent audio; on old embeds, stop and restart on pause / seek. Details: `docs/EMBED.md` §2.4, `docs/PROTOCOL.md`.

## 10. Third-Party Attributions

- [pixiv / three-vrm](https://github.com/pixiv/three-vrm) — VRM runtime (MIT)
- [Pixiv / VRoid Studio](https://vroid.com/en/studio) — default character authoring tool (VRoid Studio License)
- [PantoMatrix / EMAGE](https://github.com/PantoMatrix/PantoMatrix) by Haiyang Liu*, Zihao Zhu* et al., "EMAGE: Towards Unified Holistic Co-Speech Gesture Generation via Expressive Masked Audio Gesture Modeling", [CVPR 2024](https://pantomatrix.github.io/EMAGE/); weights [H-Liu1997/emage_audio](https://huggingface.co/H-Liu1997/emage_audio) (Apache-2.0 per the model card), modified by this project (export, cross-attention layers removed, INT8 quantization, graph optimization), see packages/emage-onnx/NOTICE. Full-body motion model
- [Animation Inc.](https://www.animation.inc) — Ani-2 architecture inspiration
- [Qiuner / Qiuner.github.io](https://github.com/Qiuner/Qiuner.github.io) — linework outdoor scene visual inspiration
- [MLC AI / WebLLM](https://github.com/mlc-ai/web-llm) — in-browser LLM
- Native `src/lib/edge-tts-core.ts` — Edge-TTS WebSocket client (no third-party TTS SDK)
- [VolgaGerm / emage-onnx-export](https://github.com/VolgaGerm/emage-onnx-export) — README export scripts for ONNX / INT8 weights
- [TanStack Start](https://tanstack.com/start) — full-stack React framework
- [Tailwind CSS](https://tailwindcss.com) — utility-first styling

## On-Device Streaming STT & Speech Recognition Pipeline

ChatBar microphone dictation runs 100% in the browser tab:
- Engine: `@firetable/stream-asr` single-pass streaming recognition (WASM SIMD, Mode 3: continuous streaming + built-in neural VAD) in a Dedicated Worker; cloud `POST /api/stt` is retained server-side for backward compatibility but not exposed in the UI
- Model & Runtime: chunked model manifest (`VITE_STREAM_ASR_MODEL_URL`) cached in IndexedDB after first download + same-origin WASM runtime (`/wasm/`, `VITE_STREAM_ASR_WASM_BASE`)
- Acoustic Bleed Gate & Conversational Barge-In: suppresses speaker bleed while TTS is playing (`rms < bargeInRms`), while louder user voice immediately halts character speech and triggers the mocap attentive listening pose (`ListeningMotionSystem`)
- Streaming Draft & Final Punctuation: atomic in-place range replacement (`replaceOrInsertAtRange`) with heuristic draft/final punctuation, 1:1 Worker FIFO sequence fence (no ghost-paste after mic close or manual edits), and cross-browser IME macrotask guard
- Spec: `/docs/STT.md`

