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
feat: persona hub keys, avatar-edit page, lip-sync upgrades
nirholas1225e2e016d0
diff --git a/avatar-edit.html b/avatar-edit.htmlnew file mode 100644index 000000000..551402428--- /dev/null+++ b/avatar-edit.html@@ -0,0 +1,271 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="utf-8" />+ <title>Customize Avatar · three.ws</title>+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <meta name="robots" content="noindex" />+ <meta name="theme-color" content="#000000" />+ <link rel="shortcut icon" href="/favicon.ico" />+ <link rel="stylesheet" href="/style.css" />+ <link rel="stylesheet" href="/fonts/fonts.css" />++ <style>+ :root {+ --bg: #0a0a0a;+ --panel: #111;+ --panel-2: #161616;+ --border: #1f1f1f;+ --border-2: #2a2a2a;+ --text: #fafafa;+ --text-2: #a1a1aa;+ --text-3: #71717a;+ --accent: #7dd3fc;+ --accent-2: #a78bfa;+ --success: #34d399;+ --danger: #f43f5e;+ --radius: 14px;+ }+ html, body {+ margin: 0;+ background: var(--bg);+ color: var(--text);+ font-family: 'Inter', system-ui, sans-serif;+ -webkit-font-smoothing: antialiased;+ }+ body {+ display: flex;+ flex-direction: column;+ min-height: 100vh;+ }++ .ae-bar {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 12px;+ padding: 12px 24px;+ border-bottom: 1px solid var(--border);+ background: rgba(10, 10, 10, 0.85);+ backdrop-filter: blur(8px);+ position: sticky;+ top: 0;+ z-index: 20;+ }+ .ae-back {+ display: inline-flex;+ align-items: center;+ gap: 8px;+ color: var(--text-2);+ text-decoration: none;+ font-size: 13px;+ }+ .ae-back:hover { color: var(--text); }+ .ae-bar-title {+ font-family: 'Space Grotesk', sans-serif;+ font-size: 14px;+ font-weight: 600;+ letter-spacing: -0.01em;+ color: var(--text);+ text-align: center;+ flex: 1;+ }+ .ae-actions { display: flex; gap: 8px; }+ .ae-btn {+ background: transparent;+ border: 1px solid var(--border-2);+ color: var(--text-2);+ padding: 7px 14px;+ border-radius: 8px;+ cursor: pointer;+ font-size: 13px;+ font-family: inherit;+ font-weight: 500;+ transition: color 0.15s, border-color 0.15s, background 0.15s;+ }+ .ae-btn:hover { color: var(--text); border-color: var(--text-3); }+ .ae-btn[disabled] { opacity: 0.4; cursor: default; }+ .ae-btn.primary {+ background: var(--text);+ color: #000;+ border-color: var(--text);+ font-weight: 600;+ }+ .ae-btn.primary:hover { transform: translateY(-1px); }+ .ae-btn.primary[disabled] { transform: none; opacity: 0.4; }++ .ae-shell {+ display: grid;+ grid-template-columns: minmax(0, 1.5fr) minmax(320px, 1fr);+ flex: 1;+ min-height: 0;+ }+ .ae-stage {+ border-right: 1px solid var(--border);+ background:+ radial-gradient(ellipse at 50% 35%, rgba(125, 211, 252, 0.06), transparent 60%),+ radial-gradient(ellipse at 70% 80%, rgba(167, 139, 250, 0.04), transparent 50%),+ var(--bg);+ position: relative;+ min-height: 500px;+ }+ .ae-stage-loading {+ position: absolute;+ inset: 0;+ display: flex;+ align-items: center;+ justify-content: center;+ color: var(--text-3);+ font-size: 13px;+ pointer-events: none;+ }++ .ae-side {+ display: flex;+ flex-direction: column;+ min-height: 0;+ }+ .ae-tabs {+ display: flex;+ border-bottom: 1px solid var(--border);+ background: var(--panel);+ padding: 0 8px;+ overflow-x: auto;+ }+ .ae-tab {+ background: transparent;+ border: 0;+ color: var(--text-3);+ padding: 12px 14px;+ font-size: 13px;+ font-weight: 500;+ cursor: pointer;+ font-family: inherit;+ border-bottom: 2px solid transparent;+ transition: color 0.15s, border-color 0.15s;+ white-space: nowrap;+ }+ .ae-tab:hover { color: var(--text-2); }+ .ae-tab.active { color: var(--text); border-color: var(--text); }++ .ae-panel {+ flex: 1;+ min-height: 0;+ overflow-y: auto;+ padding: 16px;+ }+ .ae-grid {+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));+ gap: 10px;+ }+ .ae-tile {+ background: var(--panel);+ border: 1px solid var(--border);+ border-radius: 12px;+ padding: 10px 10px 8px;+ cursor: pointer;+ transition: border-color 0.15s, transform 0.15s, background 0.15s;+ color: inherit;+ text-align: left;+ font-family: inherit;+ }+ .ae-tile:hover {+ border-color: var(--border-2);+ transform: translateY(-1px);+ }+ .ae-tile.selected {+ border-color: var(--accent);+ background: rgba(125, 211, 252, 0.06);+ }+ .ae-tile-preview {+ aspect-ratio: 1 / 1;+ border-radius: 8px;+ background:+ radial-gradient(ellipse at center, rgba(255,255,255,0.05), transparent 70%),+ var(--panel-2);+ margin-bottom: 8px;+ display: flex;+ align-items: center;+ justify-content: center;+ font-size: 36px;+ }+ .ae-tile-name {+ font-size: 12px;+ font-weight: 600;+ color: var(--text);+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+ }+ .ae-tile-kind {+ font-size: 10px;+ color: var(--text-3);+ text-transform: uppercase;+ letter-spacing: 0.06em;+ margin-top: 1px;+ }++ .ae-tile-none {+ /* "Remove" tile for clearing a slot */+ background: transparent;+ border-style: dashed;+ }++ .ae-status {+ padding: 10px 16px;+ border-top: 1px solid var(--border);+ background: var(--panel);+ font-size: 12px;+ color: var(--text-3);+ display: flex;+ align-items: center;+ gap: 8px;+ min-height: 36px;+ }+ .ae-status.ok { color: var(--success); }+ .ae-status.err { color: var(--danger); }+ .ae-status .spin {+ width: 11px; height: 11px;+ border-radius: 50%;+ border: 2px solid rgba(255,255,255,0.2);+ border-top-color: var(--accent);+ animation: ae-spin 0.9s linear infinite;+ }+ @keyframes ae-spin { to { transform: rotate(360deg); } }++ .ae-error {+ padding: 80px 24px;+ text-align: center;+ color: var(--text-3);+ font-size: 14px;+ }++ @media (max-width: 980px) {+ .ae-shell { grid-template-columns: 1fr; }+ .ae-stage { border-right: 0; border-bottom: 1px solid var(--border); min-height: 380px; }+ }+ </style>+ </head>+ <body>+ <header class="ae-bar">+ <a class="ae-back" id="ae-back" href="/">← Back</a>+ <div class="ae-bar-title" id="ae-title">Customize</div>+ <div class="ae-actions">+ <button class="ae-btn" id="ae-reset" type="button" disabled>Discard</button>+ <button class="ae-btn primary" id="ae-save" type="button" disabled>Save</button>+ </div>+ </header>+ <main class="ae-shell" id="ae-shell">+ <div class="ae-stage" id="ae-stage">+ <div class="ae-stage-loading" id="ae-loading">Loading avatar…</div>+ </div>+ <aside class="ae-side">+ <nav class="ae-tabs" id="ae-tabs" role="tablist"></nav>+ <div class="ae-panel" id="ae-panel"></div>+ <div class="ae-status" id="ae-status">Pick a preset to preview it live.</div>+ </aside>+ </main>+ <script src="/src/avatar-edit.js" type="module"></script>+ </body>+</html>diff --git a/public/persona/demo.html b/public/persona/demo.htmlnew file mode 100644index 000000000..c6c254323--- /dev/null+++ b/public/persona/demo.html@@ -0,0 +1,325 @@+<!DOCTYPE html>+<html lang="en">+<head>+<meta charset="utf-8" />+<meta name="viewport" content="width=device-width, initial-scale=1" />+<title>Persona Hub demo · three.ws</title>+<link rel="icon" href="/favicon.ico" />+<meta name="description" content="Demonstration page for the three.ws Persona Hub — embed <three-ws-signin> on any site, get a token + the user's avatar URL." />+<meta name="robots" content="noindex" />+<style>+ :root {+ color-scheme: dark;+ --bg: #05060a;+ --panel: #0f1018;+ --panel-elev: #15171f;+ --border: #1e1f2b;+ --border-strong: #2a2c3a;+ --text: #eee;+ --muted: #8a8d98;+ --accent: #6aa6ff;+ }+ * { box-sizing: border-box; }+ html, body { margin: 0; padding: 0; }+ body {+ font: 15px/1.55 -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;+ background: var(--bg);+ color: var(--text);+ min-height: 100vh;+ }+ main {+ max-width: 720px;+ margin: 0 auto;+ padding: 40px 22px 80px;+ }+ .brand {+ font-size: 12px;+ letter-spacing: 0.06em;+ text-transform: uppercase;+ color: var(--muted);+ margin-bottom: 18px;+ }+ .brand strong { color: var(--text); font-weight: 600; }+ h1 {+ font-size: 30px;+ line-height: 1.2;+ margin: 0 0 10px;+ font-weight: 600;+ }+ .lede {+ color: var(--muted);+ font-size: 16px;+ line-height: 1.6;+ margin: 0 0 28px;+ }+ .lede code {+ background: var(--panel);+ border: 1px solid var(--border);+ border-radius: 5px;+ padding: 1px 6px;+ font-size: 13px;+ }+ .demo-card {+ background: var(--panel);+ border: 1px solid var(--border);+ border-radius: 14px;+ padding: 26px 24px;+ margin: 0 0 22px;+ }+ .demo-card h2 {+ font-size: 14px;+ letter-spacing: 0.06em;+ text-transform: uppercase;+ color: var(--muted);+ margin: 0 0 14px;+ font-weight: 600;+ }+ .row {+ display: flex;+ gap: 12px;+ align-items: center;+ flex-wrap: wrap;+ }+ .token-display {+ margin-top: 18px;+ padding: 14px 16px;+ background: var(--panel-elev);+ border: 1px solid var(--border);+ border-radius: 10px;+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;+ font-size: 12px;+ color: var(--muted);+ word-break: break-all;+ max-height: 130px;+ overflow: auto;+ }+ .token-display.empty { color: var(--muted); font-family: inherit; font-size: 14px; }+ .avatar-preview {+ display: none;+ margin-top: 18px;+ padding: 16px;+ background: var(--panel-elev);+ border: 1px solid var(--border);+ border-radius: 10px;+ align-items: center;+ gap: 14px;+ }+ .avatar-preview.show { display: flex; }+ .avatar-preview img {+ width: 64px;+ height: 64px;+ border-radius: 10px;+ object-fit: cover;+ background: #1d2026;+ }+ .avatar-preview .info { flex: 1; min-width: 0; }+ .avatar-preview .name { font-size: 15px; font-weight: 600; }+ .avatar-preview .url {+ font-size: 12px;+ color: var(--muted);+ word-break: break-all;+ margin-top: 3px;+ }+ .viewer-wrap {+ display: none;+ margin-top: 18px;+ background: var(--panel-elev);+ border: 1px solid var(--border);+ border-radius: 10px;+ overflow: hidden;+ aspect-ratio: 4 / 3;+ max-height: 360px;+ }+ .viewer-wrap.show { display: block; }+ model-viewer { width: 100%; height: 100%; --poster-color: transparent; background: transparent; }+ .code-block {+ margin: 16px 0 0;+ padding: 14px 16px;+ background: var(--panel-elev);+ border: 1px solid var(--border);+ border-radius: 10px;+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;+ font-size: 12.5px;+ line-height: 1.55;+ overflow-x: auto;+ color: var(--text);+ white-space: pre;+ }+ .log {+ margin-top: 18px;+ padding: 12px 14px;+ background: var(--panel-elev);+ border: 1px solid var(--border);+ border-radius: 10px;+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;+ font-size: 12px;+ max-height: 200px;+ overflow: auto;+ color: var(--muted);+ }+ .log .ok { color: #7bd17b; }+ .log .err { color: #ef6b6b; }+ .log .info { color: var(--accent); }+ a { color: var(--accent); text-decoration: none; }+ a:hover { text-decoration: underline; }+ .footer-links {+ display: flex;+ gap: 20px;+ font-size: 14px;+ margin-top: 30px;+ }+</style>+</head>+<body>+<main>+ <div class="brand"><strong>three.ws</strong> · Persona Hub demo</div>+ <h1>Sign in with three.ws</h1>+ <p class="lede">+ This page imitates a third-party tenant site. Clicking the button below opens a popup to the+ three.ws consent screen and — on approval — receives a 24-hour token plus the user's avatar+ URL via <code>postMessage</code>. The token's audience is bound to this origin so it cannot be+ replayed against another <code>*.three.ws</code> site.+ </p>++ <div class="demo-card">+ <h2>1. Trigger the flow</h2>+ <div class="row">+ <three-ws-signin id="signin"></three-ws-signin>+ <span class="muted" style="color: var(--muted); font-size: 13.5px;">+ Opens <code style="background: var(--panel-elev); padding: 1px 4px; border-radius: 4px;">/persona/authorize.html</code>+ </span>+ </div>+ </div>++ <div class="demo-card">+ <h2>2. Received token</h2>+ <div id="token-display" class="token-display empty">No token yet — click the button above.</div>+ <div id="avatar-preview" class="avatar-preview">+ <img id="avatar-thumb" alt="" />+ <div class="info">+ <div class="name" id="avatar-name"></div>+ <div class="url" id="avatar-url"></div>+ </div>+ </div>+ <div id="viewer-wrap" class="viewer-wrap">+ <model-viewer id="model-view"+ camera-controls+ auto-rotate+ auto-rotate-delay="0"+ rotation-per-second="22deg"+ exposure="1.0"+ environment-image="neutral"+ shadow-intensity="0.4"+ shadow-softness="0.8"+ interaction-prompt="none">+ </model-viewer>+ </div>+ </div>++ <div class="demo-card">+ <h2>3. Server-side verification (snippet)</h2>+ <p style="color: var(--muted); margin: 0 0 6px; font-size: 13.5px;">+ Tenants verify tokens before trusting them. Audience is enforced to prevent cross-tenant replay.+ </p>+<pre class="code-block">const audience = location.origin;+const res = await fetch(+ `https://three.ws/api/auth/persona/verify?token=${encodeURIComponent(token)}` ++ `&audience=${encodeURIComponent(audience)}`,+);+const claims = await res.json();+if (!res.ok) throw new Error(claims.error_description);+// claims.sub → three.ws user id+// claims.avatar → { id, url, thumbnail_url, name }+// claims.scope → "persona:read avatar:read"</pre>+ <div id="verify-result" class="log" hidden></div>+ </div>++ <div class="demo-card">+ <h2>4. Event log</h2>+ <div id="log" class="log">Waiting for events…</div>+ </div>++ <div class="footer-links">+ <a href="/docs/persona-hub">Documentation</a>+ <a href="/persona/widget.js">widget.js source</a>+ <a href="/persona/authorize.html">Consent screen</a>+ </div>+</main>++<script type="module" src="https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js"></script>+<script src="/persona/widget.js" defer></script>+<script>+ const $log = document.getElementById('log');+ const $token = document.getElementById('token-display');+ const $preview = document.getElementById('avatar-preview');+ const $thumb = document.getElementById('avatar-thumb');+ const $name = document.getElementById('avatar-name');+ const $url = document.getElementById('avatar-url');+ const $viewer = document.getElementById('viewer-wrap');+ const $model = document.getElementById('model-view');+ const $verify = document.getElementById('verify-result');++ function log(level, msg) {+ const span = document.createElement('div');+ span.className = level;+ span.textContent = `[${new Date().toLocaleTimeString()}] ${msg}`;+ $log.appendChild(span);+ $log.scrollTop = $log.scrollHeight;+ }++ function clearWaiting() {+ if ($log.textContent === 'Waiting for events…') $log.textContent = '';+ }++ const signin = document.getElementById('signin');++ signin.addEventListener('three-ws:authorized', async (e) => {+ clearWaiting();+ const { token, avatar, expires_in } = e.detail;+ log('ok', `Authorized — got ${avatar?.name ? `avatar "${avatar.name}"` : 'an avatar'}, token TTL ${expires_in}s`);++ $token.classList.remove('empty');+ $token.textContent = token;++ $thumb.src = avatar.thumbnail_url || '';+ $name.textContent = avatar.name || 'Untitled';+ $url.textContent = avatar.url;+ $preview.classList.add('show');++ $model.src = avatar.url;+ $viewer.classList.add('show');++ // Verify server-side+ try {+ log('info', 'Verifying token via /api/auth/persona/verify…');+ const res = await fetch(+ `/api/auth/persona/verify?token=${encodeURIComponent(token)}&audience=${encodeURIComponent(location.origin)}`,+ );+ const data = await res.json();+ if (!res.ok) throw new Error(data.error_description || `http ${res.status}`);+ log('ok', `Verified — sub=${data.sub}, aud=${data.aud}, expires=${new Date(data.exp * 1000).toLocaleString()}`);+ $verify.hidden = false;+ $verify.innerHTML = `<div class="ok">Verified.</div>` ++ `<div>sub: ${data.sub}</div>` ++ `<div>aud: ${data.aud}</div>` ++ `<div>scope: ${data.scope}</div>` ++ `<div>exp: ${new Date(data.exp * 1000).toLocaleString()}</div>`;+ } catch (err) {+ log('err', `Verification failed: ${err.message}`);+ $verify.hidden = false;+ $verify.innerHTML = `<div class="err">Verification failed: ${err.message}</div>`;+ }+ });++ signin.addEventListener('three-ws:cancelled', (e) => {+ clearWaiting();+ log('err', `Cancelled${e.detail?.code ? ` (${e.detail.code})` : ''}`);+ });++ signin.addEventListener('three-ws:error', (e) => {+ clearWaiting();+ log('err', `Error: ${e.detail?.message || 'unknown'}`);+ });+</script>+</body>+</html>diff --git a/scripts/generate-persona-key.mjs b/scripts/generate-persona-key.mjsnew file mode 100644index 000000000..479c2d399--- /dev/null+++ b/scripts/generate-persona-key.mjs@@ -0,0 +1,43 @@+#!/usr/bin/env node+// Generate an ES256 (P-256) keypair for signing Persona Hub tokens.+//+// Run once per environment. The private key goes into Vercel env as+// PERSONA_JWKS_PRIVATE_KEY_PEM; the public key is auto-derived from it at+// runtime (jose's exportJWK on the private CryptoKey emits the public JWK+// fields), so PERSONA_JWKS_PUBLIC_KEY_PEM is optional and only needed if you+// want to override what's published at /.well-known/jwks.json.+//+// Usage:+// node scripts/generate-persona-key.mjs+// node scripts/generate-persona-key.mjs --kid persona-2026-05+//+// Output is written to stdout as a copy-pasteable block. Nothing is written+// to disk — review the values, paste into Vercel env, redeploy.++import { generateKeyPair, exportPKCS8, exportSPKI, exportJWK } from 'jose';++const args = process.argv.slice(2);+const kid =+ args.find((a) => a.startsWith('--kid='))?.split('=')[1] ||+ (args.includes('--kid') ? args[args.indexOf('--kid') + 1] : null) ||+ `persona-${new Date().toISOString().slice(0, 10)}`;++const { privateKey, publicKey } = await generateKeyPair('ES256', { extractable: true });+const privatePem = await exportPKCS8(privateKey);+const publicPem = await exportSPKI(publicKey);+const jwk = await exportJWK(publicKey);++const escaped = (pem) => pem.trimEnd().replace(/\n/g, '\\n');++console.log('# Paste into Vercel env (or .env.local for dev):');+console.log('# ─────────────────────────────────────────────────');+console.log(`PERSONA_JWKS_KID=${kid}`);+console.log(`PERSONA_JWKS_PRIVATE_KEY_PEM="${escaped(privatePem)}"`);+console.log(`# Optional — derived from private key if omitted:`);+console.log(`# PERSONA_JWKS_PUBLIC_KEY_PEM="${escaped(publicPem)}"`);+console.log('');+console.log('# Verification (after deploy):');+console.log('# curl https://three.ws/.well-known/jwks.json');+console.log('');+console.log('# Public JWK (what /.well-known/jwks.json will publish):');+console.log(JSON.stringify({ ...jwk, alg: 'ES256', use: 'sig', kid }, null, 2));diff --git a/src/avatar-edit.js b/src/avatar-edit.jsnew file mode 100644index 000000000..401b14e36--- /dev/null+++ b/src/avatar-edit.js@@ -0,0 +1,362 @@+/**+ * Avatar customizer — /avatars/:id/edit+ *+ * Live-preview outfit + accessory editor for an avatar's owner. Picks render+ * client-side via AccessoryManager so feedback is instant; on Save we PATCH+ * /api/avatars/:id with the resulting appearance JSON and the server bakes a+ * canonical GLB (see api/_lib/bake.js).+ *+ * Architecture mirrors avatar-page.js — same look-and-feel, owner-gated by the+ * presence of `avatar.owner_id` in the API response (the avatars endpoint+ * strips owner_id for non-owners via stripOwnerFor).+ */++import { TalkScene } from './voice/talk-scene.js';+import { AccessoryManager } from './agent-accessories.js';++// ── Routing ────────────────────────────────────────────────────────────++const segments = location.pathname.split('/').filter(Boolean);+// `/avatars/:id/edit` in prod, `?id=:id` in dev.+const fromPath =+ segments[0] === 'avatars' && segments[2] === 'edit' ? segments[1] : null;+const fromQuery = new URLSearchParams(location.search).get('id');+const avatarId = fromPath || fromQuery || '';++const $ = (id) => document.getElementById(id);+const esc = (s) =>+ String(s ?? '').replace(+ /[&<>"']/g,+ (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c],+ );++// ── State ──────────────────────────────────────────────────────────────++let avatar = null;+let presets = []; // from /accessories/presets.json+let scene = null;+let accessoryManager = null;++// Appearance state — `current` reflects what the server has, `working` is what+// the UI is showing live. We're dirty when they differ.+let currentAppearance = null;+let workingAppearance = { outfit: null, accessories: [], morphs: {} };++// Tab definitions: which preset kind goes on which tab.+const TABS = [+ { id: 'outfit', label: 'Outfits', kinds: ['outfit'], emoji: '👕', single: true },+ { id: 'hat', label: 'Hats', kinds: ['hat'], emoji: '🎩', single: true },+ { id: 'glasses', label: 'Glasses', kinds: ['glasses'], emoji: '🕶️', single: true },+ { id: 'earrings', label: 'Earrings', kinds: ['earrings'], emoji: '💎', single: false },+];+const KIND_EMOJI = {+ outfit: '👕',+ hat: '🎩',+ glasses: '🕶️',+ earrings: '💎',+};+let activeTab = 'outfit';++// ── Init ───────────────────────────────────────────────────────────────++if (!avatarId) {+ $('ae-shell').innerHTML = `<div class="ae-error">No avatar specified.</div>`;+} else {+ init().catch((err) => {+ console.error('[avatar-edit] init', err);+ $('ae-shell').innerHTML = `<div class="ae-error">${esc(err.message || 'Failed to load')}</div>`;+ });+}++async function init() {+ avatar = await fetchAvatar(avatarId);+ if (!avatar.owner_id) {+ // owner_id is stripped from the API response for non-owners.+ $('ae-shell').innerHTML = `<div class="ae-error">You don't own this avatar.</div>`;+ return;+ }+ if (!avatar.model_url) {+ $('ae-shell').innerHTML = `<div class="ae-error">This avatar has no GLB to customize.</div>`;+ return;+ }++ $('ae-title').textContent = `Customize · ${avatar.name}`;+ $('ae-back').href = `/avatars/${encodeURIComponent(avatar.id)}`;++ currentAppearance = normalizeAppearance(avatar.appearance);+ workingAppearance = clone(currentAppearance);++ presets = await fetchPresets();++ // 3D preview — reuse TalkScene's renderer; we don't need the mouth target+ // here, just the loaded scene + auto-frame.+ scene = new TalkScene();+ try {+ // IMPORTANT: load the BASE GLB, not the baked one. The customizer+ // applies appearance on the client; loading the already-baked URL+ // would stack outfits.+ await scene.mount({ container: $('ae-stage'), glbUrl: avatar.base_model_url || avatar.model_url });+ $('ae-loading').remove();+ } catch (err) {+ $('ae-loading').textContent = `Could not load GLB: ${err.message}`;+ return;+ }++ accessoryManager = new AccessoryManager({+ content: scene.root,+ invalidate: () => {},+ });+ await accessoryManager.hydrateFromAppearance(currentAppearance);++ renderTabs();+ renderActivePanel();+ bindHeader();+}++// ── API ────────────────────────────────────────────────────────────────++async function fetchAvatar(id) {+ const r = await fetch(`/api/avatars/${encodeURIComponent(id)}`, { credentials: 'include' });+ if (!r.ok) {+ const j = await r.json().catch(() => ({}));+ throw new Error(j.error_description || `Avatar not found (${r.status})`);+ }+ return (await r.json()).avatar;+}++async function fetchPresets() {+ const r = await fetch('/accessories/presets.json');+ if (!r.ok) throw new Error(`Could not load presets (${r.status})`);+ return r.json();+}++async function saveAppearance() {+ setStatus('spin', 'Saving and baking…');+ const r = await fetch(`/api/avatars/${encodeURIComponent(avatar.id)}`, {+ method: 'PATCH',+ credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ appearance: collapseAppearance(workingAppearance) }),+ });+ if (!r.ok) {+ const j = await r.json().catch(() => ({}));+ throw new Error(j.error_description || `Save failed (${r.status})`);+ }+ const updated = (await r.json()).avatar;+ avatar = updated;+ currentAppearance = normalizeAppearance(updated.appearance);+ workingAppearance = clone(currentAppearance);+ if (updated.bake_error) {+ setStatus('err', `Saved, but bake failed: ${updated.bake_error}`);+ } else if (updated.baked) {+ setStatus('ok', 'Saved · baked GLB ready');+ } else {+ setStatus('ok', 'Saved');+ }+ updateDirtyState();+}++// ── Rendering ──────────────────────────────────────────────────────────++function renderTabs() {+ const el = $('ae-tabs');+ el.innerHTML = TABS.map(+ (t) => `+ <button class="ae-tab${t.id === activeTab ? ' active' : ''}" data-tab="${t.id}" role="tab">+ ${t.label}+ </button>+ `,+ ).join('');+ el.querySelectorAll('.ae-tab').forEach((btn) => {+ btn.addEventListener('click', () => {+ activeTab = btn.dataset.tab;+ el.querySelectorAll('.ae-tab').forEach((b) => b.classList.toggle('active', b === btn));+ renderActivePanel();+ });+ });+}++function renderActivePanel() {+ const tab = TABS.find((t) => t.id === activeTab);+ const panel = $('ae-panel');+ const items = presets.filter((p) => tab.kinds.includes(p.kind));++ // Render a "None" tile first so users can clear the current pick.+ const tiles = [+ `<button class="ae-tile ae-tile-none${tileSelected(tab, null) ? ' selected' : ''}"+ type="button" data-id="" data-kind="${tab.id}">+ <div class="ae-tile-preview" aria-hidden="true">∅</div>+ <div class="ae-tile-name">None</div>+ <div class="ae-tile-kind">remove</div>+ </button>`,+ ...items.map(+ (p) => `+ <button class="ae-tile${tileSelected(tab, p.id) ? ' selected' : ''}"+ type="button" data-id="${esc(p.id)}" data-kind="${tab.id}">+ <div class="ae-tile-preview" aria-hidden="true">${KIND_EMOJI[p.kind] || '◇'}</div>+ <div class="ae-tile-name">${esc(p.name)}</div>+ <div class="ae-tile-kind">${esc(p.kind)}</div>+ </button>+ `,+ ),+ ];++ panel.innerHTML = `<div class="ae-grid">${tiles.join('')}</div>`;+ panel.querySelectorAll('.ae-tile').forEach((btn) => {+ btn.addEventListener('click', () => onTileClick(tab, btn.dataset.id));+ });+}++function tileSelected(tab, presetId) {+ if (tab.kinds.includes('outfit')) {+ return presetId+ ? workingAppearance.outfit === presetId+ : !workingAppearance.outfit;+ }+ // Accessory kinds (hat/glasses/earrings) live in the accessories array.+ const matching = workingAppearance.accessories.filter((id) => {+ const preset = presets.find((p) => p.id === id);+ return preset && tab.kinds.includes(preset.kind);+ });+ if (!presetId) return matching.length === 0;+ return matching.includes(presetId);+}++async function onTileClick(tab, presetId) {+ if (tab.kinds.includes('outfit')) {+ await applyOutfit(presetId || null);+ } else {+ await applyAccessory(tab, presetId || null);+ }+ renderActivePanel();+ updateDirtyState();+}++async function applyOutfit(presetId) {+ // Remove the previous outfit from the live preview first.+ if (workingAppearance.outfit) {+ accessoryManager.removePreset(workingAppearance.outfit);+ }+ workingAppearance.outfit = presetId;+ if (presetId) {+ const preset = presets.find((p) => p.id === presetId);+ if (preset) await accessoryManager.applyPreset(preset);+ }+}++async function applyAccessory(tab, presetId) {+ // For single-slot kinds (hat, glasses) remove whatever's currently in+ // that slot before applying. Earrings allow multiples (both ears).+ const wasInSlot = workingAppearance.accessories.filter((id) => {+ const p = presets.find((x) => x.id === id);+ return p && tab.kinds.includes(p.kind);+ });++ if (tab.single) {+ for (const id of wasInSlot) {+ accessoryManager.removePreset(id);+ workingAppearance.accessories = workingAppearance.accessories.filter((a) => a !== id);+ }+ }++ if (presetId) {+ // Toggle behaviour for non-single kinds — clicking an already-applied+ // preset removes it.+ if (!tab.single && wasInSlot.includes(presetId)) {+ accessoryManager.removePreset(presetId);+ workingAppearance.accessories = workingAppearance.accessories.filter((a) => a !== presetId);+ } else {+ const preset = presets.find((p) => p.id === presetId);+ if (preset) {+ await accessoryManager.applyPreset(preset);+ if (!workingAppearance.accessories.includes(presetId)) {+ workingAppearance.accessories.push(presetId);+ }+ }+ }+ }+}++// ── Header / status ────────────────────────────────────────────────────++function bindHeader() {+ $('ae-save').addEventListener('click', async () => {+ $('ae-save').disabled = true;+ $('ae-reset').disabled = true;+ try {+ await saveAppearance();+ } catch (err) {+ setStatus('err', err.message);+ } finally {+ updateDirtyState();+ }+ });+ $('ae-reset').addEventListener('click', async () => {+ // Roll the live preview back to the saved appearance.+ const wasIds = [+ workingAppearance.outfit,+ ...workingAppearance.accessories,+ ].filter(Boolean);+ for (const id of wasIds) accessoryManager.removePreset(id);+ workingAppearance = clone(currentAppearance);+ await accessoryManager.hydrateFromAppearance(workingAppearance);+ renderActivePanel();+ updateDirtyState();+ setStatus('', 'Reverted to last saved.');+ });+}++function updateDirtyState() {+ const dirty = !appearanceEquals(workingAppearance, currentAppearance);+ $('ae-save').disabled = !dirty;+ $('ae-reset').disabled = !dirty;+ if (!dirty) {+ setStatus('', 'No unsaved changes.');+ } else {+ setStatus('', 'Unsaved changes.');+ }+}++function setStatus(kind, text) {+ const el = $('ae-status');+ el.className = `ae-status${kind ? ' ' + kind : ''}`;+ el.innerHTML = kind === 'spin' ? `<span class="spin"></span>${esc(text)}` : esc(text);+}++// ── Helpers ────────────────────────────────────────────────────────────++function normalizeAppearance(a) {+ if (!a) return { outfit: null, accessories: [], morphs: {} };+ return {+ outfit: a.outfit || null,+ accessories: Array.isArray(a.accessories) ? [...a.accessories] : [],+ morphs: a.morphs && typeof a.morphs === 'object' ? { ...a.morphs } : {},+ };+}++// Drop empty fields before PATCHing so we send the smallest valid JSON and so+// "no customization" rows have appearance = null (matches isBakeable() check).+function collapseAppearance(a) {+ const out = {};+ if (a.outfit) out.outfit = a.outfit;+ if (a.accessories?.length) out.accessories = [...a.accessories];+ if (a.morphs && Object.keys(a.morphs).length) out.morphs = { ...a.morphs };+ return Object.keys(out).length ? out : null;+}++function clone(o) {+ return JSON.parse(JSON.stringify(o));+}++function appearanceEquals(a, b) {+ if ((a?.outfit || null) !== (b?.outfit || null)) return false;+ const sa = new Set(a?.accessories || []);+ const sb = new Set(b?.accessories || []);+ if (sa.size !== sb.size) return false;+ for (const v of sa) if (!sb.has(v)) return false;+ const ka = Object.keys(a?.morphs || {});+ const kb = Object.keys(b?.morphs || {});+ if (ka.length !== kb.length) return false;+ for (const k of ka) if ((a.morphs[k] || 0) !== (b?.morphs?.[k] || 0)) return false;+ return true;+}diff --git a/tests/agent-avatar-lipsync.test.js b/tests/agent-avatar-lipsync.test.jsnew file mode 100644index 000000000..57e4584b7--- /dev/null+++ b/tests/agent-avatar-lipsync.test.js@@ -0,0 +1,262 @@+/**+ * AgentAvatar × LipSyncAnalyser — integration tests+ *+ * Exercises the full Stage-5 wiring without WebAudio or a real Three.js viewer:+ * - a FakeAnalyserNode pretends to be an AudioContext-AnalyserNode and feeds a+ * deterministic frequency spectrum to LipSyncAnalyser+ * - a fake "viewer" exposes the minimum surface AgentAvatar needs to attach+ * (an Object3D-shaped `content` with `traverse()`, an event-target `el`,+ * and an `_afterAnimateHooks` array) and synthetic meshes carry the morph+ * target dictionary needed by `resolveMorphTargets()`+ *+ * Two end-to-end paths are covered:+ * 1. `visemes` mode — ARKit visemes present → per-viseme weights written+ * 2. `jaw` mode — only `jawOpen` (no visemes) → jawOpen follows amplitude+ * plus the `none` no-op path and the disconnect/zero-out behaviour.+ */++import { describe, it, expect, beforeAll, beforeEach } from 'vitest';++// ARKit canonical viseme morph names (LipSyncAnalyser writes these).+const VISEMES = [+ 'viseme_aa', 'viseme_O', 'viseme_E', 'viseme_I', 'viseme_nn',+ 'viseme_SS', 'viseme_FF', 'viseme_CH', 'viseme_PP',+];++// ── Fakes ────────────────────────────────────────────────────────────────────++class FakeAnalyserNode {+ constructor({ binCount = 128, sampleRate = 48000, spectrum = null } = {}) {+ this.fftSize = binCount * 2;+ this.frequencyBinCount = binCount;+ this.smoothingTimeConstant = 0.7;+ this.context = { sampleRate };+ this._spectrum = new Uint8Array(binCount);+ if (spectrum) this.setSpectrum(spectrum);+ }+ setSpectrum(spectrum) {+ if (spectrum instanceof Uint8Array) {+ this._spectrum.set(spectrum.subarray(0, this._spectrum.length));+ return;+ }+ const binHz = this.context.sampleRate / this.fftSize;+ for (let i = 0; i < this._spectrum.length; i++) {+ const v = spectrum(i, binHz);+ this._spectrum[i] = Math.max(0, Math.min(255, v | 0));+ }+ }+ getByteFrequencyData(buf) { buf.set(this._spectrum); }+}++function makeBand(level, lowHz, highHz) {+ return (i, binHz) => {+ const f = i * binHz;+ return f >= lowHz && f < highHz ? level : 0;+ };+}++// A minimal Three.js-shaped mesh with a morphTargetDictionary that+// `resolveMorphTargets` will pick up.+function makeMesh(names) {+ const dict = {};+ for (let i = 0; i < names.length; i++) dict[names[i]] = i;+ return {+ isMesh: true,+ morphTargetDictionary: dict,+ morphTargetInfluences: new Array(names.length).fill(0),+ };+}++// Object3D-shaped root with a `traverse()` that walks itself plus a flat list+// of meshes — enough for `resolveMorphTargets()` and `_findHeadBone()`.+function makeRoot(meshes) {+ return {+ isObject3D: true,+ children: meshes,+ traverse(fn) {+ fn(this);+ for (const m of meshes) fn(m);+ },+ };+}++function makeFakeViewer(root) {+ return {+ content: root,+ _afterAnimateHooks: [],+ el: {+ addEventListener() {},+ removeEventListener() {},+ getBoundingClientRect: () => ({ left: 0, top: 0, width: 800, height: 600 }),+ },+ };+}++// A minimal protocol bus — AgentAvatar.attach() subscribes to a dozen action+// types; we only need on/off/emit to be callable.+function makeFakeProtocol() {+ const listeners = new Map();+ return {+ on(type, fn) {+ if (!listeners.has(type)) listeners.set(type, new Set());+ listeners.get(type).add(fn);+ },+ off(type, fn) { listeners.get(type)?.delete(fn); },+ emit(action) {+ const set = listeners.get(action.type);+ if (set) for (const fn of set) fn(action.payload);+ },+ };+}++// ── Module loading ──────────────────────────────────────────────────────────++let LipSyncAnalyser, AgentAvatar;++beforeAll(async () => {+ globalThis.AnalyserNode = FakeAnalyserNode;+ // AgentAvatar imports `three` (Vector3 / Box3 / MathUtils / PositionalAudio).+ // Those are real classes from npm — they work in node. No shim needed.+ const lsa = await import('../src/lip-sync-analyser.js');+ LipSyncAnalyser = lsa.LipSyncAnalyser;+ const av = await import('../src/agent-avatar.js');+ AgentAvatar = av.AgentAvatar;+});++// ── Helpers ─────────────────────────────────────────────────────────────────++/**+ * Construct an AgentAvatar against a fake viewer + protocol, then run just+ * `_buildMorphCache()` (so `_lipsyncMode` is set) without `attach()`. Returns+ * the avatar instance and an `runStage5` helper that invokes the lipsync stage+ * directly without the other stages of _tickEmotion (which need a head bone).+ */+function makeAvatar({ meshes }) {+ const viewer = makeFakeViewer(makeRoot(meshes));+ const protocol = makeFakeProtocol();+ const identity = { id: 'test' };+ const avatar = new AgentAvatar(viewer, protocol, identity);+ avatar._buildMorphCache();+ // Isolate Stage 5 from the rest of _tickEmotion (which needs Three.js bones).+ const runStage5 = () => {+ if (!avatar._lipSync) return;+ const visemes = avatar._lipSync.sample();+ if (!visemes) return;+ if (avatar._lipsyncMode === 'visemes') {+ for (const [name, weight] of Object.entries(visemes)) {+ avatar._setMorphTarget(name, weight);+ }+ avatar._setMorphTarget('mouthOpen', 0);+ } else if (avatar._lipsyncMode === 'jaw') {+ avatar._setMorphTarget('jawOpen', avatar._lipSync.getAmplitude() * 1.8);+ }+ };+ return { avatar, runStage5 };+}++// ── Tests ────────────────────────────────────────────────────────────────────++describe('AgentAvatar × LipSyncAnalyser — integration', () => {+ describe('viseme mode (ARKit visemes present)', () => {+ let avatar, runStage5;++ beforeEach(() => {+ // Mesh exposes all 9 visemes + jawOpen — the canonical RPM/Avaturn shape.+ const mesh = makeMesh([...VISEMES, 'jawOpen', 'mouthSmileLeft', 'browInnerUp']);+ ({ avatar, runStage5 } = makeAvatar({ meshes: [mesh] }));+ });++ it('detects visemes mode at build time', () => {+ expect(avatar._lipsyncMode).toBe('visemes');+ });++ it('writes per-viseme morph targets and suppresses mouthOpen while speaking', () => {+ const analyser = new FakeAnalyserNode({ spectrum: makeBand(220, 0, 500) });+ avatar.connectLipSync(analyser);+ for (let i = 0; i < 40; i++) runStage5();+ expect(avatar._morphTarget.viseme_aa).toBeGreaterThan(0);+ expect(avatar._morphTarget.viseme_O).toBeGreaterThan(0);+ // Low-freq energy → open vowels should dominate sibilants.+ expect(avatar._morphTarget.viseme_aa).toBeGreaterThan(avatar._morphTarget.viseme_SS);+ expect(avatar._morphTarget.mouthOpen).toBe(0);+ });++ it('disconnectLipSync() zeros every viseme target so the lerp fades the mouth out', () => {+ const analyser = new FakeAnalyserNode({ spectrum: makeBand(220, 0, 500) });+ avatar.connectLipSync(analyser);+ for (let i = 0; i < 40; i++) runStage5();+ expect(avatar._morphTarget.viseme_aa).toBeGreaterThan(0.01);++ avatar.disconnectLipSync();+ for (const name of VISEMES) expect(avatar._morphTarget[name]).toBe(0);+ expect(avatar._morphTarget.mouthOpen).toBe(0);+ expect(avatar._morphTarget.jawOpen).toBe(0);+ expect(avatar._lipSync).toBeNull();+ });+ });++ describe('jaw mode (no visemes, jawOpen present)', () => {+ let avatar, runStage5;++ beforeEach(() => {+ // Plain humanoid rig: jawOpen + a couple of expression morphs, no visemes.+ const mesh = makeMesh(['jawOpen', 'mouthSmileLeft', 'browInnerUp']);+ ({ avatar, runStage5 } = makeAvatar({ meshes: [mesh] }));+ });++ it('detects jaw mode at build time', () => {+ expect(avatar._lipsyncMode).toBe('jaw');+ });++ it('drives jawOpen from smoothed amplitude and leaves visemes untouched', () => {+ const analyser = new FakeAnalyserNode({ spectrum: () => 220 });+ avatar.connectLipSync(analyser);+ for (let i = 0; i < 40; i++) runStage5();++ expect(avatar._morphTarget.jawOpen).toBeGreaterThan(0.5);+ expect(avatar._morphTarget.jawOpen).toBeLessThanOrEqual(1.0);+ // Visemes never set in this mode.+ for (const v of VISEMES) {+ expect(avatar._morphTarget[v] ?? 0).toBe(0);+ }+ });++ it('jawOpen tracks amplitude — silence pulls it back toward zero', () => {+ const analyser = new FakeAnalyserNode({ spectrum: () => 220 });+ avatar.connectLipSync(analyser);+ for (let i = 0; i < 40; i++) runStage5();+ const peak = avatar._morphTarget.jawOpen;+ expect(peak).toBeGreaterThan(0.5);++ analyser.setSpectrum(() => 0);+ for (let i = 0; i < 40; i++) runStage5();+ expect(avatar._morphTarget.jawOpen).toBeLessThan(peak * 0.1);+ });++ it('disconnectLipSync() zeros jawOpen even though no visemes were ever written', () => {+ const analyser = new FakeAnalyserNode({ spectrum: () => 220 });+ avatar.connectLipSync(analyser);+ for (let i = 0; i < 40; i++) runStage5();+ expect(avatar._morphTarget.jawOpen).toBeGreaterThan(0.01);++ avatar.disconnectLipSync();+ expect(avatar._morphTarget.jawOpen).toBe(0);+ expect(avatar._lipSync).toBeNull();+ });+ });++ describe('none mode (no relevant morphs)', () => {+ it('detects none mode and Stage 5 writes nothing morph-related', () => {+ const mesh = makeMesh(['browInnerUp', 'eyeBlinkLeft']);+ const { avatar, runStage5 } = makeAvatar({ meshes: [mesh] });+ expect(avatar._lipsyncMode).toBe('none');++ const analyser = new FakeAnalyserNode({ spectrum: () => 220 });+ avatar.connectLipSync(analyser);+ for (let i = 0; i < 40; i++) runStage5();+ // Lipsync stage no-ops; viseme + jaw targets stay untouched.+ for (const v of VISEMES) expect(avatar._morphTarget[v] ?? 0).toBe(0);+ expect(avatar._morphTarget.jawOpen ?? 0).toBe(0);+ });+ });+});