Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
overlay-control wiring + mocap clips migration + sculpt/feature polish
nirholasa60e58aee55a
diff --git a/api/_lib/migrations/2026-05-24-mocap-clips.sql b/api/_lib/migrations/2026-05-24-mocap-clips.sqlnew file mode 100644index 000000000..e4aa6c4c7--- /dev/null+++ b/api/_lib/migrations/2026-05-24-mocap-clips.sql@@ -0,0 +1,67 @@+-- Mocap clip storage — face/body motion recordings users can save, share, and+-- replay on any three.ws avatar.+--+-- A clip is the JSON-serialized output of FaceMocap.getRecording() (or its+-- pose / hand siblings when those land). Format string carries the version+-- so the runtime can refuse incompatible clips rather than silently mangle+-- them.+--+-- Frames are stored inline as JSONB. Typical 30s @ 30Hz face capture is ~50KB+-- compressed; well within Postgres comfort zone. Anything larger (multi-minute+-- full-body) belongs in R2 and we keep just the pointer.++CREATE TABLE IF NOT EXISTS mocap_clips (+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),+ owner_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,+ avatar_id uuid REFERENCES avatars(id) ON DELETE SET NULL,+ slug text NOT NULL,+ name text NOT NULL,+ description text,+ -- 'face' | 'pose' | 'hand' | 'composite'. Future: 'vmc'.+ kind text NOT NULL DEFAULT 'face' CHECK (kind IN ('face','pose','hand','composite','vmc')),+ -- Wire format identifier — three.ws.face-mocap.v1, etc. The runtime asserts+ -- on this before replaying so a v2 clip can't silently load on a v1 player.+ format text NOT NULL DEFAULT 'three.ws.face-mocap.v1',+ duration_ms int NOT NULL DEFAULT 0,+ frame_count int NOT NULL DEFAULT 0,+ -- Inline frame array — { t, shapes, mat? }[] for face clips. For clips+ -- larger than ~256KB, store a JSONB stub like { external: true } and put+ -- the payload at storage_key.+ frames jsonb,+ storage_key text,+ thumbnail_key text,+ tags text[] NOT NULL DEFAULT '{}',+ visibility text NOT NULL DEFAULT 'private' CHECK (visibility IN ('private','unlisted','public')),+ -- Optional pricing — when set, the clip is for sale via the marketplace+ -- pipeline. Mirrors avatars' price model: null = free.+ price_amount numeric(30,9),+ price_currency text,+ play_count bigint NOT NULL DEFAULT 0,+ created_at timestamptz NOT NULL DEFAULT now(),+ updated_at timestamptz NOT NULL DEFAULT now(),+ deleted_at timestamptz,+ UNIQUE (owner_id, slug)+);++CREATE INDEX IF NOT EXISTS mocap_clips_owner_idx+ ON mocap_clips (owner_id, created_at DESC)+ WHERE deleted_at IS NULL;++CREATE INDEX IF NOT EXISTS mocap_clips_public_idx+ ON mocap_clips (visibility, created_at DESC)+ WHERE visibility = 'public' AND deleted_at IS NULL;++CREATE INDEX IF NOT EXISTS mocap_clips_kind_idx+ ON mocap_clips (kind, created_at DESC)+ WHERE deleted_at IS NULL;++CREATE INDEX IF NOT EXISTS mocap_clips_tags_idx+ ON mocap_clips USING gin (tags);++-- updated_at trigger+DO $$ BEGIN+ CREATE TRIGGER mocap_clips_set_updated_at+ BEFORE UPDATE ON mocap_clips+ FOR EACH ROW EXECUTE FUNCTION set_updated_at();+EXCEPTION WHEN duplicate_object THEN NULL;+END $$;diff --git a/api/_lib/schema.sql b/api/_lib/schema.sqlindex 89ffb6c11..32bcf5e24 100644--- a/api/_lib/schema.sql+++ b/api/_lib/schema.sql@@ -59,6 +59,38 @@ create index if not exists avatars_tags_idx on avatars using gin(tags);alter table avatars add column if not exists storage_mode jsonb;alter table avatars add column if not exists parent_avatar_id uuid references avatars(id) on delete set null;+-- ── mocap_clips (recorded face / pose / hand motion clips) ──────────────────+-- See api/_lib/migrations/2026-05-24-mocap-clips.sql for the full schema ++-- rationale. Mirrored here so a clean schema.sql apply provisions the table.+create table if not exists mocap_clips (+ id uuid primary key default gen_random_uuid(),+ owner_id uuid not null references users(id) on delete cascade,+ avatar_id uuid references avatars(id) on delete set null,+ slug text not null,+ name text not null,+ description text,+ kind text not null default 'face' check (kind in ('face','pose','hand','composite','vmc')),+ format text not null default 'three.ws.face-mocap.v1',+ duration_ms int not null default 0,+ frame_count int not null default 0,+ frames jsonb,+ storage_key text,+ thumbnail_key text,+ tags text[] not null default '{}',+ visibility text not null default 'private' check (visibility in ('private','unlisted','public')),+ price_amount numeric(30,9),+ price_currency text,+ play_count bigint not null default 0,+ created_at timestamptz not null default now(),+ updated_at timestamptz not null default now(),+ deleted_at timestamptz,+ unique (owner_id, slug)+);+create index if not exists mocap_clips_owner_idx on mocap_clips(owner_id, created_at desc) where deleted_at is null;+create index if not exists mocap_clips_public_idx on mocap_clips(visibility, created_at desc) where visibility = 'public' and deleted_at is null;+create index if not exists mocap_clips_kind_idx on mocap_clips(kind, created_at desc) where deleted_at is null;+create index if not exists mocap_clips_tags_idx on mocap_clips using gin(tags);+-- ── OAuth 2.1 clients (for MCP & third-party apps) ──────────────────────────-- Supports RFC 7591 dynamic client registration.create table if not exists oauth_clients (diff --git a/pages/avatar-edit.html b/pages/avatar-edit.htmlindex 479c91165..079ff3092 100644--- a/pages/avatar-edit.html+++ b/pages/avatar-edit.html@@ -357,6 +357,22 @@line-height: 1.55;margin: 0 0 14px;}+ .ae-sculpt-mirror {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ margin: 0 0 8px;+ padding: 6px 10px;+ border: 1px solid var(--border);+ border-radius: 8px;+ background: var(--panel);+ cursor: pointer;+ font-size: 12px;+ color: var(--text-2);+ user-select: none;+ }+ .ae-sculpt-mirror input { accent-color: var(--accent); }+ .ae-sculpt-mirror:hover { color: var(--text); border-color: var(--border-2); }.ae-sculpt-group {border: 1px solid var(--border);border-radius: 10px;diff --git a/public/docs/widget-api.md b/public/docs/widget-api.mdnew file mode 100644index 000000000..36016faa6--- /dev/null+++ b/public/docs/widget-api.md@@ -0,0 +1,192 @@+# Widget API++The slim widget shell (`/widget`) is an embeddable 3D viewer. It supports:++- **URL parameters** — declarative configuration (model, type, brand, poster, reveal mode).+- **JSON-RPC 2.0 over `postMessage`** — programmatic control from the parent page (camera, animation, screenshot).+- **Auto-poster + lazy boot** — show a static preview, defer WebGL until the visitor interacts. Critical on gallery / grid pages.++## Quick start++The simplest embed — a single `<script>` tag that injects a sized iframe and forwards resize events:++```html+<script async src="https://three.ws/embed.js"+ data-widget="wdgt_abc123def456"+ data-width="600"+ data-height="600"+ data-reveal="interaction"+ data-poster="auto"></script>+```++That's it. The script:++- Mounts an iframe at the script tag's location.+- Uses `/api/widgets/<id>/og` (the OG image we already generate) as a poster — visitors see the avatar instantly.+- Defers WebGL boot until the visitor clicks the play button.+- Lazy-loads the iframe with `IntersectionObserver`.++### `<script>` attributes++| Attribute | Default | Values | Notes |+|-----------------|-------------|---------------------------------------|-------|+| `data-widget` | (required) | `wdgt_...` | The widget id from your dashboard. |+| `data-width` | type-aware | px | Iframe width. |+| `data-height` | type-aware | px | Iframe height. |+| `data-radius` | `12` | px | Border-radius on the iframe. |+| `data-border` | `0` | px | Iframe border width. |+| `data-reveal` | `auto` | `auto` \| `interaction` | `interaction` defers WebGL until the visitor clicks the poster. Use for gallery pages. |+| `data-poster` | `auto` | `auto` \| URL \| `off` | Static preview shown until first frame. `auto` uses the widget's OG image. |+| `data-priority` | (unset) | `high` | Sets `loading="eager"` + `fetchpriority="high"`. Use only when the widget is the page's LCP element. |+| `data-type` | (unset) | `turntable` \| `talking-agent` \| … | Lets the script pick a sensible default size for the type. |++## URL forms++You can also embed by hand — useful when you control the iframe directly:++| URL | Notes |+|-------------------------------------------|-------|+| `/widget#widget=<id>&kiosk=true` | Canonical embed URL. Slim shell, no chrome. |+| `/widget#model=<glb-url>&kiosk=true` | Embed any GLB without a saved widget. |+| `/w/<id>` | Server-rendered share page with OG tags + iframe. |+| `/app#widget=<id>&kiosk=true` | Legacy. Same engine but with the full marketing SPA shell — slower first paint. |++### Hash params++| Param | Type | Default | Notes |+|------------------|----------|-----------|-------|+| `widget` | id | — | Loads a saved widget config. |+| `model` | URL | — | Direct GLB URL (mutually exclusive with `widget`). |+| `type` | string | `turntable` | Widget type. Determines the UI overlay. |+| `kiosk` | bool | `false` | Hide all viewer chrome. Always `true` for embeds. |+| `reveal` | string | `auto` | `auto` boots immediately. `interaction` shows a play button and only loads the engine on click. |+| `poster` | URL | — | Static image shown until first frame. Use `/api/widgets/<id>/og` for the auto-generated card. |+| `preset` | string | — | Environment preset (`neutral`, `venice-sunset`, `footprint-court`). |+| `cameraPosition` | csv | — | Initial camera position as `x,y,z`. |+| `accent` | `#rrggbb`| — | UI accent color. |++## JSON-RPC API++The widget exposes a JSON-RPC 2.0 server inside the iframe. Drive it from the parent page using the bundled client:++```html+<iframe id="agent" src="https://three.ws/widget#widget=wdgt_abc"></iframe>+<script src="https://three.ws/widget-client.js"></script>+<script>+ const client = ThreeWidget.attach(document.getElementById('agent'));++ await client.ready();+ await client.call('camera.setLookAt', {+ eye: [0, 1.6, 3], target: [0, 1, 0], duration: 1.5,+ });+ await client.call('animation.play', { name: 'av-waving' });++ const { dataUrl } = await client.call('screenshot.capture', { width: 800, height: 800 });+ console.log('PNG:', dataUrl);+</script>+```++### Client API++| Method | Returns | Notes |+|---------------------------------|-------------------|-------|+| `ThreeWidget.attach(iframe)` | `Client` | Binds to an iframe. Validates `event.origin` against the iframe's `src`. |+| `client.ready(timeoutMs?)` | `Promise<void>` | Resolves on first `viewer.ready` event (or if the widget is already up). |+| `client.call(method, params?, timeoutMs?)` | `Promise<result>` | Calls an RPC method. Rejects with `Error` (`code` carries the JSON-RPC error code). |+| `client.on(event, fn)` | `() => void` | Subscribes to events. Returns an off-handle. `on('*', fn)` catches every event. |+| `client.close()` | `void` | Detaches the listener and rejects in-flight calls. |++### RPC methods (server)++| Method | Params | Result |+|-------------------------|-----------------------------------------------------|-----------------------------------------|+| `viewer.getInfo` | — | `{ version, ready, model, widget, type }` |+| `viewer.setBackground` | `{ color: '#rrggbb' }` | `{}` |+| `viewer.setAutoRotate` | `{ enabled?: bool, speed?: number }` | `{}` |+| `viewer.setEnvironment` | `{ preset: string }` | `{}` |+| `camera.getLookAt` | — | `{ eye: [x,y,z], target: [x,y,z], fov }`|+| `camera.setLookAt` | `{ eye?, target?, duration?, ease? }` | `{ eye, target }` |+| `camera.recenter` | `{ duration?: seconds }` | `{}` |+| `animation.list` | — | `{ clips: [{ name, duration }] }` |+| `animation.play` | `{ name: string, loop?: bool }` | `{ name }` |+| `animation.stop` | — | `{}` |+| `screenshot.capture` | `{ width?: int, height?: int, mime?: string }` | `{ dataUrl: 'data:image/png;base64,…' }`|+| `model.load` | `{ url: string }` | `{ url }` |+| `ping` | — | `{ pong: true, t: <ms> }` |++### Events (server → parent)++Notifications (no `id`) sent to the parent over `postMessage`:++| Event | Payload | Fires when |+|-------------------|--------------------------------------|------------|+| `viewer.ready` | `{}` | First successful model frame. |+| `model.loaded` | `{ url, success, error? }` | After every `model.load` (success or failure). |+| `widget.revealed` | `{ mode: 'auto' \| 'interaction' }` | Visitor clicked the play button (interaction mode) or auto mode booted. |+| `widget.resize` | `{ width, height, id? }` | The widget asks the host to resize its iframe. |++### Wire format++The server speaks JSON-RPC 2.0. Both request and response forms below:++```js+// Request (parent → iframe)+{ jsonrpc: '2.0', id: 7, method: 'camera.setLookAt',+ params: { eye: [0,1.6,3], target: [0,1,0], duration: 1.5 } }++// Response (iframe → parent)+{ jsonrpc: '2.0', id: 7, result: { eye: [...], target: [...] } }++// Error+{ jsonrpc: '2.0', id: 7, error: { code: -32601, message: 'Method not found' } }++// Notification (iframe → parent, no id)+{ jsonrpc: '2.0', method: 'viewer.ready', params: {} }+```++### Error codes++| Code | Meaning |+|----------|---------|+| `-32700` | Parse error (malformed JSON). |+| `-32600` | Invalid request (missing `jsonrpc` or `method`). |+| `-32601` | Method not found. |+| `-32602` | Invalid params. |+| `-32603` | Internal error (wraps a thrown exception). |+| `-32000` | Viewer not ready (model still loading). |++## Performance patterns++### Gallery / grid pages++Use `reveal="interaction"` + `data-poster="auto"`. WebGL only initializes for the widgets the visitor opens — most browsers cap a tab at ~16 simultaneous WebGL contexts, so eager-loading a grid of 12 widgets is borderline.++```html+<!-- Repeat for each widget in the grid -->+<script async src="https://three.ws/embed.js"+ data-widget="wdgt_..."+ data-reveal="interaction"+ data-poster="auto"></script>+```++### Hero / above-the-fold++Use `data-priority="high"` so the browser prioritises the iframe in the resource queue. Only set this on the widget that's actually the LCP element — high-priority every embed and you've defeated the point.++```html+<script async src="https://three.ws/embed.js"+ data-widget="wdgt_..."+ data-priority="high"+ data-poster="auto"></script>+```++### Multiple widgets you control++If you have multiple widgets and want to coordinate them (sync camera, broadcast events), keep one `ThreeWidget.attach()` client per iframe. The clients are independent — there's no global state.++## Security++- The widget shell validates `event.source` on every incoming message — only messages from a known parent are processed.+- The client validates `event.origin` against the iframe's `src` origin. Pass `{ origin: '*' }` to `attach()` to opt out (e.g. for cross-origin embed-in-embed scenarios), but you give up the guarantee that the response came from us.+- `screenshot.capture` returns the rendered canvas, so the parent gets exactly what the visitor sees. Nothing private leaks across the boundary.+- `model.load` accepts any URL the iframe can fetch — same-origin policy still applies to the GLB itself. If you need a private model, gate it behind a cookie/header at the GLB host.diff --git a/src/app-next-overlay.js b/src/app-next-overlay.jsindex 9a552513a..31287dc60 100644--- a/src/app-next-overlay.js+++ b/src/app-next-overlay.js@@ -3,18 +3,26 @@import { getMe, readAuthHint, saveRemoteGlbToAccount } from './account.js';const STORAGE_HINT_KEY = 'nxt:first-hint-dismissed';-const TRY_ROTATE_MS = 8000;--const TRY_PICKS = [- { name: 'av-waving', icon: '👋', label: 'Wave' },- { name: 'av-superhero-jump', icon: '🦸', label: 'Superhero jump' },- { name: 'boxer-dance', icon: '🥊', label: 'Boxer dance' },- { name: 'av-brag-and-clap', icon: '👏', label: 'Brag & clap' },- { name: 'facepalm', icon: '🤦', label: 'Facepalm' },- { name: 'av-flex-arm', icon: '💪', label: 'Flex' },- { name: 'covereyes', icon: '🙈', label: 'Cover eyes' },- { name: 'av-walk-crouching', icon: '🚶', label: 'Sneak walk' },+const CHIP_ROTATE_MS = 9000;+const IDLE_HIDE_MS = 5000;+const AGENT_BUBBLE_MS = 6000;++// Suggested chat prompts — animation primers + agent questions. Each prompt's+// optional `clip` plays the matching animation alongside the chat reply, so+// "Wave at me!" actually triggers the wave clip when the agent answers.+const CHAT_PROMPTS = [+ { text: 'Wave at me!', icon: '👋', clip: 'av-waving' },+ { text: 'Do a superhero jump', icon: '🦸', clip: 'av-superhero-jump' },+ { text: 'Show me a dance', icon: '🥊', clip: 'boxer-dance' },+ { text: 'Flex for me', icon: '💪', clip: 'av-flex-arm' },+ { text: 'Brag and clap', icon: '👏', clip: 'av-brag-and-clap' },+ { text: 'Who are you?', icon: '👤' },+ { text: 'What can you do?', icon: '✨' },+ { text: 'Tell me about three.ws', icon: '🌐' },+ { text: 'Why are you embodied?', icon: '🧠' },+ { text: 'Sneak walk away', icon: '🚶', clip: 'av-walk-crouching' },];+const VISIBLE_CHIPS = 3;const ICON_OVERRIDES = {idle: '🧍',@@ -31,6 +39,15 @@ const ICON_OVERRIDES = {'av-waiting': '🕰️',};+// Camera preset framings, all expressed relative to the avatar's bounding box.+// Each entry maps to (cameraOffset, targetOffset) computed at preset time.+const CAMERA_PRESETS = {+ face: { framePadding: 0.6, heightFrac: 0.92, distFrac: 1.5, targetY: 0.92 },+ body: { framePadding: 1.25, heightFrac: 0.55, distFrac: 2.6, targetY: 0.5 },+ wide: { framePadding: 1.9, heightFrac: 0.5, distFrac: 4.0, targetY: 0.45 },+ hero: { framePadding: 1.55, heightFrac: 0.3, distFrac: 3.2, targetY: 0.55 },+};+document.addEventListener('DOMContentLoaded', boot);function boot() {@@ -40,6 +57,12 @@ function boot() {wireKeyboardShortcuts();wirePrimaryCTA();wireAnimationSheet();+ wireChatDock();+ wireShare();+ wireFullscreen();+ wireCameraPresets();+ wireHelp();+ wireAutoHide();waitForViewer().then((viewer) => {if (!viewer) {@@ -47,8 +70,10 @@ function boot() {return;}polishStage(viewer);- startTryPillRotation(viewer);+ startChatChipRotation(viewer);startCameraDrift(viewer);+ hookAgentBubble();+ applyCameraPreset('body'); // initial framing});refreshAuthState();@@ -72,10 +97,22 @@ function waitForViewer(timeoutMs = 15000) {});}+function waitForAgent(timeoutMs = 15000) {+ return new Promise((resolve) => {+ const started = Date.now();+ const tick = () => {+ const a = window.VIEWER?.agent;+ if (a && typeof a._send === 'function' && a.panel) return resolve(a);+ if (Date.now() - started > timeoutMs) return resolve(null);+ setTimeout(tick, 150);+ };+ tick();+ });+}+// ── Stage polish ──────────────────────────────────────────────────────────function polishStage(viewer) {- // transparentBg via the viewer's own state — survives later updateBackground() calls.try {viewer.state.transparentBg = true;viewer.updateBackground();@@ -93,7 +130,6 @@ function startCameraDrift(viewer) {let resumeTimer = null;const enableDrift = () => {- // Mirror state.autoRotate so viewer.updateDisplay() doesn't undo it later.viewer.state.autoRotate = true;viewer.controls.autoRotate = true;viewer.controls.autoRotateSpeed = 0.35;@@ -117,85 +153,237 @@ function startCameraDrift(viewer) {viewer.controls.addEventListener('start', pauseDrift);}-// ── Try pill ──────────────────────────────────────────────────────────────+// ── Camera presets ────────────────────────────────────────────────────────++function applyCameraPreset(name) {+ const viewer = window.VIEWER?.viewer;+ if (!viewer || !viewer.content || !viewer.controls || !viewer.defaultCamera) return;+ const preset = CAMERA_PRESETS[name];+ if (!preset) return;++ const THREE = window.THREE;+ if (!THREE) return;++ const box = new THREE.Box3().setFromObject(viewer.content);+ const size = box.getSize(new THREE.Vector3());+ const center = box.getCenter(new THREE.Vector3());+ if (!isFinite(size.length()) || size.length() === 0) return;++ const fovRad = viewer.defaultCamera.fov * (Math.PI / 180);+ const fittingHeight = size.y * preset.framePadding;+ const baseDist = fittingHeight / 2 / Math.tan(fovRad / 2);+ const dist = baseDist * (preset.distFrac / 2.6);++ const targetY = box.min.y + size.y * preset.targetY;+ const camY = box.min.y + size.y * preset.heightFrac;+ const target = new THREE.Vector3(center.x, targetY, center.z);+ const pos = new THREE.Vector3(center.x + dist * 0.12, camY, center.z + dist);++ if (typeof viewer._tweenCamera === 'function') {+ viewer._tweenCamera(pos, target, 500);+ } else {+ viewer.defaultCamera.position.copy(pos);+ viewer.controls.target.copy(target);+ viewer.controls.update();+ viewer.invalidate?.();+ }+ updatePresetActive(name);+}++function updatePresetActive(name) {+ document.querySelectorAll('.nxt-preset').forEach((btn) => {+ btn.classList.toggle('is-active', btn.dataset.preset === name);+ });+}++function wireCameraPresets() {+ document.querySelectorAll('.nxt-preset').forEach((btn) => {+ btn.addEventListener('click', () => applyCameraPreset(btn.dataset.preset));+ });+}++// ── Chat chip rotation ────────────────────────────────────────────────────-function startTryPillRotation(viewer) {- const pill = document.getElementById('nxt-try-pill');- const iconEl = document.getElementById('nxt-try-pill-icon');- const nameEl = document.getElementById('nxt-try-pill-name');- const btn = document.getElementById('nxt-try-pill-btn');- const nextBtn = document.getElementById('nxt-try-pill-next');- if (!pill || !btn) return;+function startChatChipRotation(viewer) {+ const chipsEl = document.getElementById('nxt-chat-chips');+ if (!chipsEl) return;- let order = TRY_PICKS.slice();- let cursor = Math.floor(Math.random() * order.length);- let intervalId = null;+ let pool = CHAT_PROMPTS.slice();+ let cursor = Math.floor(Math.random() * pool.length);const render = () => {- const pick = order[cursor % order.length];- iconEl.textContent = pick.icon;- nameEl.textContent = pick.label;- pill.dataset.clip = pick.name;+ const available = new Set((viewer.animationManager?.getAnimationDefs?.() || []).map((d) => d.name));+ const filtered = pool.filter((p) => !p.clip || available.size === 0 || available.has(p.clip));+ const showPool = filtered.length >= VISIBLE_CHIPS ? filtered : pool;+ chipsEl.innerHTML = '';+ for (let i = 0; i < VISIBLE_CHIPS; i++) {+ const prompt = showPool[(cursor + i) % showPool.length];+ const chip = document.createElement('button');+ chip.type = 'button';+ chip.className = 'nxt-chat-chip';+ chip.setAttribute('role', 'listitem');+ chip.dataset.text = prompt.text;+ if (prompt.clip) chip.dataset.clip = prompt.clip;+ chip.innerHTML =+ `<span class="nxt-chat-chip__icon">${escHtml(prompt.icon || '✨')}</span>` ++ `<span>${escHtml(prompt.text)}</span>`;+ chip.addEventListener('click', () => sendChat(prompt.text, prompt.clip));+ chipsEl.appendChild(chip);+ }};- const advance = () => {- cursor = (cursor + 1) % order.length;+ render();+ let rotateTimer = setInterval(() => {+ cursor = (cursor + VISIBLE_CHIPS) % pool.length;render();- };+ }, CHIP_ROTATE_MS);++ // Pause rotation when the chat dock is focused/hovered+ const dock = document.getElementById('nxt-chat-dock');+ if (dock) {+ const stop = () => {+ if (rotateTimer) {+ clearInterval(rotateTimer);+ rotateTimer = null;+ }+ };+ const start = () => {+ if (!rotateTimer) {+ rotateTimer = setInterval(() => {+ cursor = (cursor + VISIBLE_CHIPS) % pool.length;+ render();+ }, CHIP_ROTATE_MS);+ }+ };+ dock.addEventListener('mouseenter', stop);+ dock.addEventListener('mouseleave', start);+ dock.addEventListener('focusin', stop);+ dock.addEventListener('focusout', start);+ }+}- pollForClips(viewer).then(() => {- const available = new Set(getAvailableClipNames(viewer));- if (available.size > 0) {- order = TRY_PICKS.filter((p) => available.has(p.name));- if (order.length === 0) order = TRY_PICKS.slice();- }- cursor = Math.floor(Math.random() * order.length);- render();- pill.hidden = false;- intervalId = setInterval(advance, TRY_ROTATE_MS);+// ── Chat dock — input + send wires through NichAgent ──────────────────────++function wireChatDock() {+ const input = document.getElementById('nxt-chat-input');+ const form = document.getElementById('nxt-chat-form');+ const mic = document.getElementById('nxt-chat-mic');+ if (!form || !input) return;++ form.addEventListener('submit', (e) => {+ e.preventDefault();+ const text = input.value.trim();+ if (!text) return;+ sendChat(text);+ input.value = '';});- btn.addEventListener('click', () => {- const pick = order[cursor % order.length];- playClip(viewer, pick.name);- clearInterval(intervalId);- intervalId = null;+ // Pin chat-active class while input is focused or NichAgent panel is open.+ input.addEventListener('focus', () => document.body.classList.add('nxt-chat-active'));+ input.addEventListener('blur', () => {setTimeout(() => {- if (!intervalId) intervalId = setInterval(advance, TRY_ROTATE_MS);- }, 12000);+ if (!document.activeElement?.closest('.nxt-chat-dock, .nich-panel')) {+ document.body.classList.remove('nxt-chat-active');+ }+ }, 100);});- nextBtn.addEventListener('click', advance);+ // Push-to-talk via spacebar (NichAgent's mic toggle covers the actual recognition).+ if (mic && 'webkitSpeechRecognition' in window) {+ mic.hidden = false;+ mic.addEventListener('click', () => triggerMicToggle(mic));+ document.addEventListener('keydown', (e) => {+ if (e.code !== 'Space') return;+ if (e.target.matches('input, textarea, [contenteditable="true"]')) return;+ e.preventDefault();+ triggerMicToggle(mic);+ });+ }}-function pollForClips(viewer, timeoutMs = 12000) {- return new Promise((resolve) => {- const started = Date.now();- const tick = () => {- const defs = viewer.animationManager?.getAnimationDefs?.() || [];- if (defs.length > 0) return resolve(defs);- if (Date.now() - started > timeoutMs) return resolve([]);- setTimeout(tick, 300);- };- tick();- });+async function triggerMicToggle(micEl) {+ const agent = await waitForAgent(8000);+ if (!agent) return;+ const agentMicBtn = agent.panel?.querySelector('.nich-mic');+ if (!agentMicBtn) {+ toast('Voice not available in this browser.');+ return;+ }+ agentMicBtn.click();+ micEl.classList.toggle('is-recording');}-function getAvailableClipNames(viewer) {- const defs = viewer.animationManager?.getAnimationDefs?.() || [];- return defs.map((d) => d.name);+async function sendChat(text, optionalClip) {+ const agent = await waitForAgent(8000);+ if (!agent) {+ toast('Agent loading… try again in a moment.');+ return;+ }++ // Open the panel so the user sees the conversation thread.+ const panelHidden = agent.panel.style.display === 'none';+ if (panelHidden && typeof agent._togglePanel === 'function') {+ agent._togglePanel();+ }+ document.body.classList.add('nxt-chat-active');++ // Optionally fire the matching animation alongside the chat reply.+ if (optionalClip) {+ const viewer = window.VIEWER?.viewer;+ const mgr = viewer?.animationManager;+ if (mgr && typeof mgr.ensureLoaded === 'function') {+ mgr.ensureLoaded(optionalClip)+ .then(() => mgr.play(optionalClip))+ .catch(() => {});+ }+ }++ const agentInput = agent.panel.querySelector('.nich-input');+ if (agentInput) {+ agentInput.value = text;+ // _send reads the input, pushes the user message, and dispatches to skills/LLM.+ try {+ agent._send();+ } catch (err) {+ console.warn('[nxt] chat send failed', err);+ }+ }}-function playClip(viewer, name) {- const mgr = viewer.animationManager;- if (!mgr) return;+// ── Agent speech bubble ───────────────────────────────────────────────────- const defs = mgr.getAnimationDefs();- const def = defs.find((d) => d.name === name);- if (!def) return;- mgr.ensureLoaded(name)- .then(() => mgr.play(name))- .catch((err) => console.warn('[nxt] clip play failed', name, err));+function hookAgentBubble() {+ const bubble = document.getElementById('nxt-agent-bubble');+ const textEl = document.getElementById('nxt-agent-bubble-text');+ if (!bubble || !textEl) return;++ let hideTimer = null;++ const showReply = (text) => {+ if (!text) return;+ textEl.textContent = text;+ bubble.hidden = false;+ clearTimeout(hideTimer);+ hideTimer = setTimeout(() => {+ bubble.hidden = true;+ }, AGENT_BUBBLE_MS);+ };++ // AgentProtocol emits SPEAK events whenever the agent says something.+ const protocol = window.VIEWER?.agent_protocol;+ if (protocol && typeof protocol.on === 'function') {+ protocol.on('SPEAK', (action) => {+ const t = action?.payload?.text;+ if (t) showReply(t);+ });+ // Some emit codepaths use the wildcard subscription pattern.+ protocol.on('*', (action) => {+ if (action?.type === 'SPEAK' || action?.type === 'speak') {+ const t = action?.payload?.text;+ if (t) showReply(t);+ }+ });+ }}// ── Animation sheet ───────────────────────────────────────────────────────@@ -250,15 +438,13 @@ function wireAnimationSheet() {async function renderGrid() {const viewer = await waitForViewer();if (!viewer) {- grid.innerHTML =- '<div class="nxt-anim-empty">Viewer not ready — reload to try again.</div>';+ grid.innerHTML = '<div class="nxt-anim-empty">Viewer not ready — reload to try again.</div>';return;}await pollForClips(viewer);const defs = viewer.animationManager.getAnimationDefs();if (!defs || defs.length === 0) {- grid.innerHTML =- '<div class="nxt-anim-empty">This avatar has no animations.</div>';+ grid.innerHTML = '<div class="nxt-anim-empty">This avatar has no animations.</div>';return;}@@ -305,7 +491,6 @@ function wireAnimationSheet() {c.style.display = match ? '' : 'none';if (match) visible++;});- // Remove any prior "no matches" hintgrid.querySelectorAll('.nxt-anim-empty[data-search]').forEach((n) => n.remove());if (visible === 0) {const empty = document.createElement('div');@@ -317,6 +502,119 @@ function wireAnimationSheet() {}}+function pollForClips(viewer, timeoutMs = 12000) {+ return new Promise((resolve) => {+ const started = Date.now();+ const tick = () => {+ const defs = viewer.animationManager?.getAnimationDefs?.() || [];+ if (defs.length > 0) return resolve(defs);+ if (Date.now() - started > timeoutMs) return resolve([]);+ setTimeout(tick, 300);+ };+ tick();+ });+}++function playClip(viewer, name) {+ const mgr = viewer.animationManager;+ if (!mgr) return;+ const defs = mgr.getAnimationDefs();+ const def = defs.find((d) => d.name === name);+ if (!def) return;+ mgr.ensureLoaded(name)+ .then(() => mgr.play(name))+ .catch((err) => console.warn('[nxt] clip play failed', name, err));+}++// ── Share / embed popover ─────────────────────────────────────────────────++function wireShare() {+ const btn = document.getElementById('nxt-share-btn');+ const pop = document.getElementById('nxt-share-popover');+ const closeBtn = document.getElementById('nxt-share-close');+ const urlEl = document.getElementById('nxt-share-url');+ const embedEl = document.getElementById('nxt-share-embed');+ const urlCopyBtn = document.getElementById('nxt-share-url-copy');+ const embedCopyBtn = document.getElementById('nxt-share-embed-copy');+ if (!btn || !pop) return;++ const refresh = () => {+ // Page URL: use current location stripped of hash demo-state.+ const baseUrl = location.origin + '/app';+ const params = new URLSearchParams();+ const currentModelUrl = window.VIEWER?.app?._currentModelUrl;+ if (currentModelUrl && !currentModelUrl.includes('/avatars/cz.glb')) {+ // Only surface non-default avatars in the share URL.+ params.set('model', currentModelUrl);+ }+ const share = params.toString() ? `${baseUrl}?${params.toString()}` : baseUrl;+ urlEl.value = share;++ // Embed snippet — iframe pointing at the same viewer in kiosk mode.+ const kiosk = share + (share.includes('?') ? '&' : '?') + 'kiosk=1';+ embedEl.value =+ `<iframe src="${kiosk}" width="540" height="720" ` ++ `style="border:0;border-radius:18px;overflow:hidden" ` ++ `allow="autoplay;microphone;camera"></iframe>`;+ };++ const open = () => {+ refresh();+ pop.hidden = false;+ btn.setAttribute('aria-expanded', 'true');+ };++ const close = () => {+ pop.hidden = true;+ btn.setAttribute('aria-expanded', 'false');+ };++ btn.addEventListener('click', () => (pop.hidden ? open() : close()));+ closeBtn?.addEventListener('click', close);++ document.addEventListener('pointerdown', (e) => {+ if (pop.hidden) return;+ if (pop.contains(e.target) || btn.contains(e.target)) return;+ close();+ });++ const copy = async (textEl, copyBtn) => {+ const text = textEl.value;+ try {+ await navigator.clipboard.writeText(text);+ } catch {+ textEl.select();+ document.execCommand?.('copy');+ }+ copyBtn.textContent = 'Copied ✓';+ copyBtn.classList.add('is-copied');+ setTimeout(() => {+ copyBtn.textContent = 'Copy';+ copyBtn.classList.remove('is-copied');+ }, 1800);+ };++ urlCopyBtn?.addEventListener('click', () => copy(urlEl, urlCopyBtn));+ embedCopyBtn?.addEventListener('click', () => copy(embedEl, embedCopyBtn));+}++// ── Fullscreen ────────────────────────────────────────────────────────────++function wireFullscreen() {+ const btn = document.getElementById('nxt-fullscreen-btn');+ if (!btn) return;+ const toggle = () => {+ if (!document.fullscreenElement) {+ document.documentElement.requestFullscreen?.().catch(() => {+ toast('Fullscreen blocked by browser.');+ });+ } else {+ document.exitFullscreen?.();+ }+ };+ btn.addEventListener('click', toggle);+}+// ── Header menus ──────────────────────────────────────────────────────────function wireExploreMenu() {@@ -471,15 +769,20 @@ function wirePrimaryCTA() {});}+// ── Toast ─────────────────────────────────────────────────────────────────++let toastTimer = null;function toast(message, href) {- const el = document.createElement('div');- el.className = 'save-toast';- el.style.zIndex = 9999;+ const el = document.getElementById('nxt-toast');+ if (!el) return;el.innerHTML = href? `${escHtml(message)} <a href="${escHtml(href)}">View →</a>`: escHtml(message);- document.body.appendChild(el);- setTimeout(() => el.remove(), 4200);+ el.hidden = false;+ clearTimeout(toastTimer);+ toastTimer = setTimeout(() => {+ el.hidden = true;+ }, 4200);}// ── First-visit hint ──────────────────────────────────────────────────────@@ -502,22 +805,126 @@ function wireFirstHint() {setTimeout(dismiss, 14000);}+// ── Help overlay ──────────────────────────────────────────────────────────++function wireHelp() {+ const help = document.getElementById('nxt-help');+ const closeBtn = document.getElementById('nxt-help-close');+ if (!help) return;++ const open = () => {+ help.hidden = false;+ };+ const close = () => {+ help.hidden = true;+ };++ closeBtn?.addEventListener('click', close);+ document.addEventListener('keydown', (e) => {+ if (e.target.matches('input, textarea, select, [contenteditable="true"]')) return;+ if (e.key === '?' || (e.shiftKey && e.key === '/')) {+ e.preventDefault();+ help.hidden ? open() : close();+ } else if (e.key === 'Escape' && !help.hidden) {+ close();+ }+ });+}+// ── Keyboard shortcuts ────────────────────────────────────────────────────function wireKeyboardShortcuts() {document.addEventListener('keydown', (e) => {- if (e.target.matches('input, textarea, select, [contenteditable="true"]')) return;+ // Allow shortcuts inside the chat input only for Esc (which blurs).+ const inField = e.target.matches('input, textarea, select, [contenteditable="true"]');+ if (inField) {+ if (e.key === 'Escape') {+ e.target.blur();+ document.body.classList.remove('nxt-chat-active');+ }+ return;+ }if (e.metaKey || e.ctrlKey || e.altKey) return;- if (e.key === 'a' || e.key === 'A') {- e.preventDefault();- document.getElementById('nxt-anim-btn')?.click();- } else if (e.key === 'u' || e.key === 'U') {- e.preventDefault();- document.getElementById('file-input')?.click();++ switch (e.key) {+ case 'a':+ case 'A':+ e.preventDefault();+ document.getElementById('nxt-anim-btn')?.click();+ break;+ case 'u':+ case 'U':+ e.preventDefault();+ document.getElementById('file-input')?.click();+ break;+ case 's':+ case 'S':+ e.preventDefault();+ document.getElementById('nxt-share-btn')?.click();+ break;+ case 'f':+ case 'F':+ e.preventDefault();+ document.getElementById('nxt-fullscreen-btn')?.click();+ break;+ case '/':+ if (!e.shiftKey) {+ e.preventDefault();+ document.getElementById('nxt-chat-input')?.focus();+ }+ break;+ case '1':+ e.preventDefault();+ applyCameraPreset('face');+ break;+ case '2':+ e.preventDefault();+ applyCameraPreset('body');+ break;+ case '3':+ e.preventDefault();+ applyCameraPreset('wide');+ break;+ case '4':+ e.preventDefault();+ applyCameraPreset('hero');+ break;}});}+// ── Auto-hide chrome on idle ──────────────────────────────────────────────++function wireAutoHide() {+ let idleTimer = null;+ const arm = () => {+ document.body.classList.remove('nxt-chrome-hidden');+ clearTimeout(idleTimer);+ idleTimer = setTimeout(() => {+ // Don't hide while user is in a panel/input.+ if (document.body.classList.contains('nxt-chat-active')) return;+ if (anyPanelOpen()) return;+ document.body.classList.add('nxt-chrome-hidden');+ }, IDLE_HIDE_MS);+ };++ ['mousemove', 'pointerdown', 'keydown', 'wheel', 'touchstart'].forEach((evt) =>+ window.addEventListener(evt, arm, { passive: true }),+ );+ arm();+}++function anyPanelOpen() {+ const ids = ['nxt-anim-sheet', 'nxt-share-popover', 'nxt-help', 'nxt-more-menu', 'nav-user-menu'];+ for (const id of ids) {+ const el = document.getElementById(id);+ if (el && !el.hidden) return true;+ }+ const nichPanel = document.querySelector('.nich-panel');+ if (nichPanel && nichPanel.style.display !== 'none') return true;+ return false;+}+// ── Helpers ───────────────────────────────────────────────────────────────function escHtml(s) {diff --git a/src/avatar-sculpt.js b/src/avatar-sculpt.jsindex 061b846e6..e2834d1a1 100644--- a/src/avatar-sculpt.js+++ b/src/avatar-sculpt.js@@ -449,10 +449,12 @@ function openFaceCaptureModal({ root, working, onDirty, rerender }) {}}applyMorphsToRoot(root, working.morphs);- status.textContent = `Applied ${applied} blendshapes.`;+ status.textContent = applied+ ? `Applied ${applied} identity ratios. Fine-tune with the sliders below.`+ : "Face read OK, but this avatar doesn't expose matching shape morphs.";onDirty?.();rerender?.();- setTimeout(teardown, 600);+ setTimeout(teardown, 1200);} catch (err) {console.error('[avatar-sculpt] capture failed', err);status.textContent = `Capture failed: ${err.message}`;diff --git a/src/create-review-features.js b/src/create-review-features.jsindex 1f6a61787..92ce98cc7 100644--- a/src/create-review-features.js+++ b/src/create-review-features.js@@ -440,9 +440,10 @@ print(reply.json()) # {"reply": "...", "tx": "<sig>"}`,export function openEmbedModal(ctx = {}) {const handle = slugify(ctx.name) || 'your-agent';const snippets = {- script: `<script async src="https://three.ws/embed.js"+ script: `<script src="https://three.ws/embed.js"data-widget="${handle}"- data-type="talking-agent"></script>`,+ data-type="talking-agent"+ async></script>`,webcomponent: `<agent-3d agent="${handle}" mode="full"></agent-3d><script type="module"src="https://three.ws/embed/agent-3d.js"></script>`,diff --git a/src/overlay-control.js b/src/overlay-control.jsnew file mode 100644index 000000000..b74be02be--- /dev/null+++ b/src/overlay-control.js@@ -0,0 +1,297 @@+// overlay-control.js — Stream Deck companion for the OBS overlay.+//+// Two-way control surface for an /embed/avatar runtime mounted in OBS Browser+// Source: emote hotkeys, expression mixer, mic threshold, speech queue. The+// control panel never owns the overlay — it just speaks the v1.avatar.* wire+// over both window.postMessage (to the in-page preview iframe) and+// BroadcastChannel (to the OBS overlay window on the same machine).+//+// Why BroadcastChannel: OBS Browser Source runs in a Chromium instance under+// the same origin as the user's logged-in browser tab when the URL points at+// our site. BroadcastChannel is the cheapest IPC across same-origin windows+// — no server, no WebSocket relay. The avatar embed listens on a channel+// derived from its handle or avatar id; the control panel pushes to the same+// channel.+//+// The companion also opens the overlay as a "real" window via window.open()+// so users can grab the URL from the new tab and drop it into OBS in two+// clicks.++const DEFAULT_HOTKEY_LABELS = ['smile', 'wink', 'surprised', 'sad', 'angry', 'disgust', 'thinking', 'kiss', 'tongue', 'neutral'];++// ── DOM ─────────────────────────────────────────────────────────────────────+const $ = (sel) => document.querySelector(sel);+const handleInput = $('#avatar-handle');+const applyBtn = $('#apply-handle');+const openOverlayBtn = $('#open-overlay');+const copyOverlayBtn = $('#copy-overlay');+const overlayUrlPre = $('#overlay-url');+const statusEl = $('#status');+const hotkeyGrid = $('#hotkey-grid');+const micToggleBtn = $('#mic-toggle');+const micStateEl = $('#mic-state');+const micFloor = $('#mic-floor');+const micCeiling = $('#mic-ceiling');+const micFloorV = $('#mic-floor-v');+const micCeilingV = $('#mic-ceiling-v');+const speakText = $('#speak-text');+const speakGo = $('#speak-go');+const eventLog = $('#event-log');+const preview = $('#preview');++// ── State ──────────────────────────────────────────────────────────────────+const state = {+ handle: localStorage.getItem('overlay:handle') || '',+ bc: null,+ online: false,+ micOn: false,+ hotkeys: null,+};++if (state.handle) handleInput.value = state.handle.replace(/^@/, '');++handleInput.addEventListener('keydown', (e) => {+ if (e.key === 'Enter') {+ e.preventDefault();+ apply();+ }+});+applyBtn.addEventListener('click', () => apply());+openOverlayBtn.addEventListener('click', () => openOverlay());+copyOverlayBtn.addEventListener('click', () => copyOverlay());++micToggleBtn.addEventListener('click', () => {+ if (state.micOn) {+ send({ type: 'v1.avatar.mic', enabled: false });+ setMicUi(false);+ } else {+ send({+ type: 'v1.avatar.mic',+ enabled: true,+ floor: Number(micFloor.value),+ ceiling: Number(micCeiling.value),+ });+ setMicUi(true);+ }+});++micFloor.addEventListener('input', () => {+ micFloorV.textContent = Number(micFloor.value).toFixed(3);+ if (state.micOn) send({ type: 'v1.avatar.mic', enabled: true, floor: Number(micFloor.value), ceiling: Number(micCeiling.value) });+});+micCeiling.addEventListener('input', () => {+ micCeilingV.textContent = Number(micCeiling.value).toFixed(3);+ if (state.micOn) send({ type: 'v1.avatar.mic', enabled: true, floor: Number(micFloor.value), ceiling: Number(micCeiling.value) });+});++speakGo.addEventListener('click', () => {+ const text = speakText.value.trim();+ if (!text) return;+ send({ type: 'v1.avatar.speak', text });+});+speakText.addEventListener('keydown', (e) => {+ if (e.key === 'Enter') {+ e.preventDefault();+ speakGo.click();+ }+});++document.querySelectorAll('[data-control]').forEach((btn) => {+ btn.addEventListener('click', () => {+ const ctl = btn.dataset.control;+ if (ctl === 'stop') send({ type: 'v1.avatar.stop' });+ else if (ctl === 'overlay-on') send({ type: 'v1.avatar.overlay', enabled: true });+ else if (ctl === 'overlay-off') send({ type: 'v1.avatar.overlay', enabled: false });+ });+});++// Global key listener — re-fires hotkeys when this tab has focus so the+// streamer can mash keys without clicking the buttons.+window.addEventListener('keydown', (e) => {+ if (e.target && /^(INPUT|TEXTAREA|SELECT)$/.test(e.target.tagName)) return;+ if (e.key >= '0' && e.key <= '9') {+ fireHotkey(e.key);+ e.preventDefault();+ }+});++renderHotkeys(buildDefaultHotkeys());+micFloorV.textContent = Number(micFloor.value).toFixed(3);+micCeilingV.textContent = Number(micCeiling.value).toFixed(3);++// ── Boot ───────────────────────────────────────────────────────────────────+if (state.handle) apply().catch((err) => log(`apply failed: ${err.message}`, 'warn'));++// ── Functions ──────────────────────────────────────────────────────────────++function buildDefaultHotkeys() {+ const out = {};+ const order = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0'];+ order.forEach((k, i) => {+ out[k] = { label: DEFAULT_HOTKEY_LABELS[i] || `emote ${k}`, hold: 1500 };+ });+ return out;+}++function renderHotkeys(map) {+ hotkeyGrid.innerHTML = '';+ const order = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0'];+ for (const k of order) {+ const entry = map[k];+ if (!entry) continue;+ const el = document.createElement('button');+ el.className = 'hotkey';+ el.dataset.key = k;+ el.setAttribute('aria-label', entry.label || `Hotkey ${k}`);+ el.innerHTML = `<span class="k">${escapeHtml(k)}</span><span class="l">${escapeHtml(entry.label || '')}</span>`;+ el.addEventListener('click', () => fireHotkey(k));+ hotkeyGrid.appendChild(el);+ }+}++function fireHotkey(key) {+ const k = String(key);+ send({ type: 'v1.avatar.hotkey', key: k });+ const el = hotkeyGrid.querySelector(`.hotkey[data-key="${CSS.escape(k)}"]`);+ if (el) {+ el.classList.add('fired');+ setTimeout(() => el.classList.remove('fired'), 220);+ }+}++async function apply() {+ const raw = (handleInput.value || '').trim().replace(/^@/, '').toLowerCase();+ if (!/^[a-z0-9_-]{3,30}$/.test(raw)) {+ log(`invalid handle: ${raw || '(empty)'}`, 'warn');+ return;+ }+ state.handle = raw;+ localStorage.setItem('overlay:handle', raw);+ const url = buildOverlayUrl(raw);+ overlayUrlPre.textContent = url;+ preview.src = url;+ setStatus(false);++ // Open / reset the BroadcastChannel.+ if (state.bc) {+ try { state.bc.close(); } catch {}+ }+ const channelKey = `three-ws-overlay:${raw}`;+ state.bc = new BroadcastChannel(channelKey);+ state.bc.onmessage = (ev) => onBroadcast(ev.data);+ // Ping every avatar listening on the channel.+ state.bc.postMessage({ type: 'v1.avatar.hello' });+ log(`Tracking @${raw} on ${channelKey}`);+}++function openOverlay() {+ if (!state.handle) {+ log('Set a handle first.', 'warn');+ return;+ }+ const url = buildOverlayUrl(state.handle);+ window.open(url, '_blank', 'noopener,popup,width=720,height=900');+}++async function copyOverlay() {+ if (!state.handle) {+ log('Set a handle first.', 'warn');+ return;+ }+ const url = buildOverlayUrl(state.handle);+ try {+ await navigator.clipboard.writeText(url);+ copyOverlayBtn.textContent = 'Copied';+ setTimeout(() => (copyOverlayBtn.textContent = 'Copy overlay URL'), 1400);+ } catch (err) {+ log(`clipboard failed: ${err?.message}`, 'warn');+ }+}++function buildOverlayUrl(handle) {+ const u = new URL(`${location.origin}/embed/avatar/${encodeURIComponent(handle)}`);+ u.searchParams.set('overlay', '1');+ u.searchParams.set('idle', 'on');+ u.searchParams.set('bg', 'transparent');+ return u.toString();+}++function send(msg) {+ // Send to both surfaces — preview iframe (window.postMessage) and OBS+ // overlay (BroadcastChannel). Either may be absent; both being missing+ // just means nothing is listening yet.+ try {+ if (preview && preview.contentWindow) {+ preview.contentWindow.postMessage(msg, location.origin);+ }+ } catch {}+ try {+ if (state.bc) state.bc.postMessage(msg);+ } catch {}+ log(`→ ${msg.type}${msg.key ? ' key=' + msg.key : ''}${msg.text ? ' "' + msg.text + '"' : ''}`);+}++function onBroadcast(msg) {+ if (!msg || typeof msg !== 'object' || typeof msg.type !== 'string') return;+ switch (msg.type) {+ case 'v1.avatar.ready':+ case 'v1.avatar.online':+ setStatus(true);+ if (msg.hotkeys) {+ state.hotkeys = msg.hotkeys;+ renderHotkeys(msg.hotkeys);+ }+ log(`← ready · ${msg.name || msg.handle || msg.id || ''}${msg.conformance ? ` · ${Math.round(msg.conformance.coverage * 100)}% morphs` : ''}`);+ return;+ case 'v1.avatar.hotkey:fired':+ log(`← hotkey ${msg.key} (${msg.label || ''})`);+ return;+ case 'v1.avatar.state':+ log(`← state · ${msg.state?.expression || '?'}${msg.state?.talking ? ' · talking' : ''}`);+ return;+ case 'v1.avatar.error':+ log(`← error · ${msg.message || ''}`, 'warn');+ return;+ case 'v1.avatar.pong':+ // Heartbeat acknowledged.+ return;+ }+}++window.addEventListener('message', (ev) => {+ if (preview && ev.source !== preview.contentWindow) return;+ onBroadcast(ev.data);+});++function setStatus(online) {+ state.online = online;+ statusEl.classList.toggle('online', online);+ statusEl.querySelector('.label').textContent = online ? 'live' : 'waiting';+}++function setMicUi(on) {+ state.micOn = on;+ micToggleBtn.textContent = on ? 'Disable mic' : 'Enable mic';+ micStateEl.classList.toggle('online', on);+ micStateEl.querySelector('.label').textContent = on ? 'on' : 'off';+}++function log(message, level = 'info') {+ const ts = new Date().toTimeString().slice(0, 8);+ const line = document.createElement('span');+ line.className = `e ${level}`;+ line.textContent = `${ts} ${message}\n`;+ eventLog.prepend(line);+ // Cap event-log entries so a long session doesn't grow unbounded.+ while (eventLog.children.length > 120) eventLog.removeChild(eventLog.lastChild);+}++function escapeHtml(s) {+ if (s == null) return '';+ return String(s)+ .replace(/&/g, '&')+ .replace(/</g, '<')+ .replace(/>/g, '>')+ .replace(/"/g, '"')+ .replace(/'/g, ''');+}