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
create-review a11y + avatar-edit sculpt panel + save-error verifier
nirholasf4b6cae4412f
diff --git a/api/_providers/replicate.js b/api/_providers/replicate.jsindex d0a0f9f70..e74529b0c 100644--- a/api/_providers/replicate.js+++ b/api/_providers/replicate.js@@ -148,6 +148,13 @@ export function createRegenProvider() {'content-type': 'application/json',};+ // Webhook target: when set, every submission asks Replicate to POST status+ // updates here instead of forcing the client to poll. The route lives at+ // /api/webhooks/replicate (vercel.json rewrite). Without this URL we fall+ // back to the old poll-on-status flow — both paths converge in the DB.+ const webhookUrl = readEnv('REPLICATE_WEBHOOK_URL')+ || (readEnv('APP_ORIGIN') ? `${readEnv('APP_ORIGIN').replace(/\/$/, '')}/api/webhooks/replicate` : null);+return {async submit(request) {const modelRef = modelForMode(request.mode);@@ -177,15 +184,26 @@ export function createRegenProvider() {const isVersionHash = /^[a-f0-9]{40,64}$/i.test(modelRef);const slugMatch = modelRef.match(/^([a-z0-9-]+)\/([a-z0-9._-]+)(?::([a-f0-9]+))?$/i);+ // Webhook payload — Replicate POSTs the full Prediction object to+ // this URL on the configured events. We filter to "completed" only+ // (Replicate's term covers succeeded/failed/canceled) since the+ // client doesn't care about intermediate "processing" events; the+ // status endpoint still falls back to polling if a webhook is lost.+ const requestBody = { input };+ if (webhookUrl) {+ requestBody.webhook = webhookUrl;+ requestBody.webhook_events_filter = ['completed'];+ }+let endpoint;let body;if (isVersionHash) {endpoint = `${REPLICATE_BASE}/predictions`;- body = JSON.stringify({ version: modelRef, input });+ body = JSON.stringify({ ...requestBody, version: modelRef });} else if (slugMatch) {const [, owner, name, pinnedVersion] = slugMatch;endpoint = `${REPLICATE_BASE}/models/${owner}/${name}/predictions`;- body = JSON.stringify(pinnedVersion ? { version: pinnedVersion, input } : { input });+ body = JSON.stringify(pinnedVersion ? { ...requestBody, version: pinnedVersion } : requestBody);} else {throw Object.assign(new Error(`replicate model reference "${modelRef}" is neither a version hash nor an owner/name slug`),diff --git a/api/widgets/[id]/[action].js b/api/widgets/[id]/[action].jsindex b3c4c7b93..bb403fe86 100644--- a/api/widgets/[id]/[action].js+++ b/api/widgets/[id]/[action].js@@ -18,7 +18,12 @@ import { decorate } from '../index.js';import { redactPii } from '../../_lib/pii.js';import { embed, cosine, embeddingsConfigured } from '../../_lib/embeddings.js';import { listTranscripts, getTranscript } from './_transcripts.js';-import { listKnowledge, ingestKnowledge, deleteKnowledge } from './_knowledge.js';+import {+ listKnowledge,+ ingestKnowledge,+ deleteKnowledge,+ testRetrieval,+} from './_knowledge.js';export default wrap(async (req, res) => {const action = req.query?.action;@@ -966,6 +971,25 @@ async function handleKnowledge(req, res) {if (!w) return error(res, 404, 'not_found', 'widget not found or not yours');if (req.method === 'GET') {+ const url = new URL(req.url, 'http://x');+ // ?test=<query> — Inkeep-style retrieval debugger. Returns top-K+ // chunks with cosine scores so the creator can verify their docs+ // surface for the queries they expect, without running a chat turn.+ const probe = url.searchParams.get('test');+ if (probe !== null) {+ try {+ const topK = parseInt(url.searchParams.get('top_k') || '5', 10) || 5;+ const data = await testRetrieval({ widgetId: id, query: probe, topK });+ return json(res, 200, data);+ } catch (err) {+ return error(+ res,+ err.status || 400,+ err.code || 'test_failed',+ err.message || 'retrieval test failed',+ );+ }+ }const out = await listKnowledge(id);res.setHeader('cache-control', 'private, max-age=15');return json(res, 200, out);diff --git a/api/widgets/[id]/_knowledge.js b/api/widgets/[id]/_knowledge.jsindex 91c3c867c..b4caa21f2 100644--- a/api/widgets/[id]/_knowledge.js+++ b/api/widgets/[id]/_knowledge.js@@ -10,7 +10,7 @@import { z } from 'zod';import { sql } from '../../_lib/db.js';-import { embed, embeddingsConfigured } from '../../_lib/embeddings.js';+import { embed, embeddingsConfigured, cosine } from '../../_lib/embeddings.js';import { chunk, estimateTokens } from '../../_lib/chunker.js';import { fetchAndExtract } from '../../_lib/text-extract.js';import { shortId } from '../../_lib/ids.js';@@ -74,6 +74,61 @@ export async function listKnowledge(widgetId) {};}+// Inkeep-style retrieval debugger: takes a probe query and returns the top-K+// chunks with cosine scores + the source doc. Lets the creator verify their+// docs are actually retrievable without having to chat. No LLM call — pure+// vector lookup, mirrors what handleChat would inject as grounding.+export async function testRetrieval({ widgetId, query, topK = 5 }) {+ if (!embeddingsConfigured()) {+ throw httpError(+ 503,+ 'embedder_unavailable',+ 'Knowledge test needs an OpenAI key on the server (OPENAI_API_KEY).',+ );+ }+ const q = String(query || '').trim();+ if (q.length < 2) throw httpError(400, 'invalid_request', 'query must be at least 2 chars');++ const rows = await sql`+ select c.id, c.doc_id, c.chunk_index, c.content, c.embedding, c.token_count,+ d.title, d.source_url, d.source_type+ from widget_knowledge_chunks c+ join widget_knowledge_docs d on d.id = c.doc_id+ where c.widget_id = ${widgetId}+ `;+ if (!rows.length) return { query: q, results: [], chunks_searched: 0 };++ const [queryEmbedding] = await embed([q]);+ const scored = rows+ .map((r) => {+ const e = Array.isArray(r.embedding) ? r.embedding : r.embedding?.values || [];+ return {+ id: Number(r.id),+ doc_id: r.doc_id,+ chunk_index: Number(r.chunk_index),+ score: cosine(queryEmbedding, e),+ token_count: Number(r.token_count || 0),+ excerpt: truncate(String(r.content), 280),+ title: r.title,+ source_url: r.source_url,+ source_type: r.source_type,+ };+ })+ .sort((a, b) => b.score - a.score)+ .slice(0, Math.max(1, Math.min(20, topK)));++ return {+ query: q,+ results: scored,+ chunks_searched: rows.length,+ };+}++function truncate(s, n) {+ if (s.length <= n) return s;+ return s.slice(0, n).trim() + '…';+}+export async function deleteKnowledge({ widgetId, userId, docId }) {const rows = await sql`delete from widget_knowledge_docsdiff --git a/pages/avatar-edit.html b/pages/avatar-edit.htmlindex caaf6dd6f..479c91165 100644--- a/pages/avatar-edit.html+++ b/pages/avatar-edit.html@@ -336,6 +336,238 @@.ae-shell { grid-template-columns: 1fr; }.ae-stage { border-right: 0; border-bottom: 1px solid var(--border); min-height: 380px; }}++ /* ── Sculpt panel ───────────────────────────────────────── */+ .ae-sculpt-head {+ display: flex;+ gap: 8px;+ margin-bottom: 10px;+ }+ .ae-sculpt-capture {+ flex: 1;+ display: inline-flex;+ align-items: center;+ justify-content: center;+ gap: 6px;+ }+ .ae-sculpt-capture-icon { font-size: 14px; line-height: 1; }+ .ae-sculpt-note {+ font-size: 12px;+ color: var(--text-3);+ line-height: 1.55;+ margin: 0 0 14px;+ }+ .ae-sculpt-group {+ border: 1px solid var(--border);+ border-radius: 10px;+ background: var(--panel);+ margin-bottom: 8px;+ overflow: hidden;+ }+ .ae-sculpt-group summary {+ list-style: none;+ cursor: pointer;+ padding: 10px 14px;+ font-size: 13px;+ font-weight: 600;+ color: var(--text);+ display: flex;+ align-items: center;+ justify-content: space-between;+ transition: background 0.12s;+ user-select: none;+ }+ .ae-sculpt-group summary::-webkit-details-marker { display: none; }+ .ae-sculpt-group summary::before {+ content: '▸';+ color: var(--text-3);+ font-size: 11px;+ margin-right: 8px;+ display: inline-block;+ transition: transform 0.18s;+ }+ .ae-sculpt-group[open] summary::before { transform: rotate(90deg); }+ .ae-sculpt-group summary:hover { background: var(--panel-2); }+ .ae-sculpt-count {+ font-size: 10px;+ color: var(--text-3);+ background: var(--panel-2);+ border: 1px solid var(--border-2);+ padding: 2px 7px;+ border-radius: 999px;+ margin-left: auto;+ }+ .ae-sculpt-rows {+ padding: 6px 14px 14px;+ display: flex;+ flex-direction: column;+ gap: 6px;+ border-top: 1px solid var(--border);+ background: rgba(0, 0, 0, 0.2);+ }+ .ae-sculpt-row {+ display: grid;+ grid-template-columns: minmax(0, 1.3fr) minmax(0, 2fr) 36px;+ align-items: center;+ gap: 10px;+ padding: 6px 0;+ }+ .ae-sculpt-label {+ display: flex;+ flex-direction: column;+ gap: 2px;+ min-width: 0;+ }+ .ae-sculpt-name {+ font-size: 12px;+ color: var(--text);+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+ }+ .ae-sculpt-meta {+ font-size: 9px;+ color: var(--text-3);+ text-transform: uppercase;+ letter-spacing: 0.08em;+ }+ .ae-sculpt-row input[type='range'] {+ appearance: none;+ -webkit-appearance: none;+ width: 100%;+ background: transparent;+ height: 16px;+ cursor: pointer;+ }+ .ae-sculpt-row input[type='range']::-webkit-slider-runnable-track {+ height: 4px;+ border-radius: 999px;+ background: var(--border-2);+ }+ .ae-sculpt-row input[type='range']::-moz-range-track {+ height: 4px;+ border-radius: 999px;+ background: var(--border-2);+ }+ .ae-sculpt-row input[type='range']::-webkit-slider-thumb {+ appearance: none;+ -webkit-appearance: none;+ width: 14px;+ height: 14px;+ border-radius: 50%;+ background: var(--accent);+ margin-top: -5px;+ border: 0;+ box-shadow: 0 0 0 2px rgba(125, 211, 252, 0.18);+ cursor: pointer;+ }+ .ae-sculpt-row input[type='range']::-moz-range-thumb {+ width: 14px;+ height: 14px;+ border-radius: 50%;+ background: var(--accent);+ border: 0;+ cursor: pointer;+ }+ .ae-sculpt-value {+ font-family: ui-monospace, 'SF Mono', monospace;+ font-size: 11px;+ color: var(--text-3);+ text-align: right;+ font-variant-numeric: tabular-nums;+ }++ /* ── Face capture modal ─────────────────────────────────── */+ .ae-face-backdrop {+ position: fixed;+ inset: 0;+ z-index: 200;+ background: rgba(0, 0, 0, 0.72);+ backdrop-filter: blur(8px);+ display: flex;+ align-items: center;+ justify-content: center;+ padding: 20px;+ animation: aeFaceFade 0.18s ease-out;+ }+ @keyframes aeFaceFade { from { opacity: 0 } to { opacity: 1 } }+ .ae-face-dialog {+ background: var(--panel);+ border: 1.5px solid var(--border-2);+ border-radius: 14px;+ width: 100%;+ max-width: 520px;+ max-height: calc(100vh - 40px);+ overflow-y: auto;+ padding: 24px;+ position: relative;+ display: flex;+ flex-direction: column;+ gap: 14px;+ box-shadow: 0 30px 80px rgba(0, 0, 0, 0.6);+ font-family: inherit;+ }+ .ae-face-dialog h3 {+ margin: 0;+ font-size: 18px;+ font-weight: 600;+ letter-spacing: -0.01em;+ }+ .ae-face-lede {+ margin: 0;+ color: var(--text-3);+ font-size: 13px;+ line-height: 1.5;+ }+ .ae-face-close {+ position: absolute;+ top: 12px;+ right: 12px;+ background: var(--panel-2);+ border: 1px solid var(--border-2);+ color: var(--text-2);+ width: 28px;+ height: 28px;+ border-radius: 999px;+ cursor: pointer;+ font: inherit;+ font-size: 13px;+ display: inline-flex;+ align-items: center;+ justify-content: center;+ }+ .ae-face-close:hover { color: var(--text); border-color: var(--text-3); }+ .ae-face-stage {+ position: relative;+ aspect-ratio: 1 / 1;+ background: #000;+ border: 1px solid var(--border-2);+ border-radius: 10px;+ overflow: hidden;+ }+ .ae-face-stage video {+ width: 100%;+ height: 100%;+ object-fit: cover;+ transform: scaleX(-1); /* mirror — selfie convention */+ display: block;+ }+ .ae-face-status {+ position: absolute;+ left: 0;+ right: 0;+ bottom: 0;+ padding: 8px 12px;+ font-size: 12px;+ color: rgba(255, 255, 255, 0.85);+ background: linear-gradient(180deg, transparent, rgba(0, 0, 0, 0.7));+ text-align: center;+ }+ .ae-face-actions {+ display: flex;+ gap: 8px;+ justify-content: flex-end;+ }</style></head><body>diff --git a/pages/create-review.html b/pages/create-review.htmlindex 09807dff4..f8d208261 100644--- a/pages/create-review.html+++ b/pages/create-review.html@@ -79,7 +79,33 @@align-items: start;}@media (max-width: 880px) {- .grid { grid-template-columns: 1fr; }+ .grid { grid-template-columns: 1fr; gap: 16px; }+ }+ /* Phone-class viewport: drop the panel padding, drop the modal+ max-width, swap modal animation to a slide-up sheet so it feels+ native rather than "desktop dialog squashed onto a phone". */+ @media (max-width: 560px) {+ main.stage { padding: 12px 14px 60px; }+ h1 { font-size: 22px; }+ .sub { margin-bottom: 18px; font-size: 14px; }+ .viewer { min-height: 360px; aspect-ratio: 3 / 4; }+ .panel { padding: 16px; gap: 12px; }+ .panel h2 { font-size: 17px; }+ .unlocks { padding: 12px; gap: 8px; }+ .feature-tile { padding: 9px; }+ .feature-name { font-size: 12px; }+ .feature-desc { font-size: 10px; }+ .fm-backdrop { padding: 0; align-items: flex-end; }+ .fm-dialog {+ max-width: 100%;+ max-height: 88vh;+ border-radius: 18px 18px 0 0;+ padding: 22px 20px 26px;+ animation: fmSheet 0.25s cubic-bezier(0.2, 0.8, 0.2, 1);+ }+ @keyframes fmSheet { from { transform: translateY(20px); opacity: 0.6; } to { transform: translateY(0); opacity: 1; } }+ .fm-head h3 { font-size: 17px; }+ .fm-head p { font-size: 12.5px; }}.viewer {diff --git a/public/widgets-gallery/gallery.js b/public/widgets-gallery/gallery.jsindex f3281e812..2b83d4472 100644--- a/public/widgets-gallery/gallery.js+++ b/public/widgets-gallery/gallery.js@@ -1,10 +1,12 @@// Widget gallery — native DOM, no framework.-// Renders showcase cards from /widgets-gallery/showcase.json with:-// - skeleton loader while fetching-// - filter bar by widget type-// - click-to-load (+ auto-load at 50% visibility) iframes-// - scroll-in fade animation per card-// - responsive embed snippet+// Each card:+// - Preview / Code tabs in the frame area (shadcn-style inline switch)+// - Customize panel: size preset, accent color, per-type fields (mint, kind)+// wired through to /app via hash params; the iframe reloads as you tweak.+// - Snippet block reflects current customizer state.+// - Copy split-button with 3 formats: iframe, JSX, URL.+// - "Open in Studio" template clone.+// Top of page: faceted filter chips (type), skeleton loader, fade-in.const GRID_EL = document.getElementById('gallery-grid');const ORIGIN = location.origin;@@ -20,6 +22,31 @@ const TYPE_COLORS = {'live-trades-canvas': '#f43f5e',};+// Which customize knobs apply to which type. Universal knobs (size, accent)+// are always present; this map adds type-specific ones.+const TYPE_KNOBS = {+ turntable: [],+ 'animation-gallery': [],+ 'talking-agent': [],+ passport: [],+ 'hotspot-tour': [],+ 'pumpfun-feed': ['kind'],+ 'kol-trades': ['mint'],+ 'live-trades-canvas': ['mint'],+};++const SIZE_PRESETS = {+ S: 0.6,+ M: 1.0,+ L: 1.4,+};++const FORMATS = [+ { id: 'iframe', label: 'HTML iframe' },+ { id: 'jsx', label: 'JSX (React)' },+ { id: 'url', label: 'Share URL' },+];+// Fade-in cards as they scroll into viewconst cardObserver = new IntersectionObserver((entries) => {@@ -114,7 +141,6 @@ function renderFilters(widgets) {const show = !type || card.dataset.type === type;card.hidden = !show;if (show) {- // Re-stagger visible cards for alternating layoutcard.style.setProperty('--card-idx', visIdx++);}});@@ -153,62 +179,140 @@ function renderShowcase(w) {root.dataset.type = w.type;root.setAttribute('aria-labelledby', `sc-${w.id}-title`);- const widgetUrl = `${ORIGIN}/widget#widget=${encodeURIComponent(w.id)}&kiosk=true`;- const pageUrl = `${ORIGIN}/w/${encodeURIComponent(w.id)}`;+ const color = TYPE_COLORS[w.type] || 'var(--accent)';+ root.style.setProperty('--type-color', color);const allowAttr =w.type === 'talking-agent'? 'autoplay; xr-spatial-tracking; clipboard-write; microphone': 'autoplay; xr-spatial-tracking; clipboard-write';- // Responsive snippet — adapts to container, caps at native size- const snippet =- `<iframe src="${widgetUrl}" ` +- `style="width:100%;aspect-ratio:${w.width}/${w.height};border:0;border-radius:12px;max-width:${w.width}px" ` +- `allow="${allowAttr}" loading="lazy"></iframe>`;+ // Customizer state — mutated by inputs, read by snippet + iframe builders.+ const state = {+ size: 'M',+ accent: TYPE_COLORS[w.type] || '#8b5cf6',+ mint:+ w.type === 'live-trades-canvas'+ ? 'So11111111111111111111111111111111111111112'+ : w.type === 'kol-trades'+ ? 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'+ : '',+ kind: 'all',+ format: 'iframe',+ };++ function currentWidth() {+ return Math.round(w.width * SIZE_PRESETS[state.size]);+ }++ function buildHashParams() {+ const parts = [`widget=${encodeURIComponent(w.id)}`, 'kiosk=true'];+ if (state.accent && state.accent !== TYPE_COLORS[w.type]) {+ parts.push(`accent=${encodeURIComponent(state.accent)}`);+ }+ if (TYPE_KNOBS[w.type]?.includes('mint') && state.mint) {+ parts.push(`mint=${encodeURIComponent(state.mint)}`);+ }+ if (TYPE_KNOBS[w.type]?.includes('kind') && state.kind && state.kind !== 'all') {+ parts.push(`kind=${encodeURIComponent(state.kind)}`);+ }+ return parts.join('&');+ }++ function widgetUrl() {+ return `${ORIGIN}/widget#${buildHashParams()}`;+ }+ function pageUrl() {+ // /w/<id> currently only carries the saved config — for customized embeds+ // we link the /widget hash form which preserves all overrides.+ const customized = state.size !== 'M' || state.accent !== TYPE_COLORS[w.type] ||+ (TYPE_KNOBS[w.type]?.includes('mint') && state.mint !== defaultMint(w.type)) ||+ (TYPE_KNOBS[w.type]?.includes('kind') && state.kind !== 'all');+ return customized ? widgetUrl() : `${ORIGIN}/w/${encodeURIComponent(w.id)}`;+ }++ function buildSnippet(format) {+ const url = widgetUrl();+ const mw = currentWidth();+ if (format === 'url') return pageUrl();+ if (format === 'jsx') {+ return (+ `<iframe\n` ++ ` src="${url}"\n` ++ ` title="${escAttr(w.label)}"\n` ++ ` allow="${allowAttr}"\n` ++ ` loading="lazy"\n` ++ ` style={{\n` ++ ` width: '100%',\n` ++ ` aspectRatio: '${w.width}/${w.height}',\n` ++ ` border: 0,\n` ++ ` borderRadius: 12,\n` ++ ` maxWidth: ${mw},\n` ++ ` }}\n` ++ `/>`+ );+ }+ return (+ `<iframe src="${url}" ` ++ `style="width:100%;aspect-ratio:${w.width}/${w.height};border:0;border-radius:12px;max-width:${mw}px" ` ++ `allow="${allowAttr}" loading="lazy"></iframe>`+ );+ }++ // ── Frame + tabs ──+ const frameWrap = document.createElement('div');+ frameWrap.className = 'showcase-frame-wrap';++ const tabBar = document.createElement('div');+ tabBar.className = 'frame-tabs';+ tabBar.setAttribute('role', 'tablist');+ const previewTab = makeTab('Preview', true);+ const codeTab = makeTab('Code', false);+ tabBar.appendChild(previewTab);+ tabBar.appendChild(codeTab);+ frameWrap.appendChild(tabBar);- // ── Frame ──const frame = document.createElement('div');frame.className = 'showcase-frame';frame.style.aspectRatio = `${w.width} / ${w.height}`;- frame.style.maxWidth = `${w.width}px`;-- const color = TYPE_COLORS[w.type] || 'var(--accent)';+ frame.style.maxWidth = `${currentWidth()}px`;const placeholder = document.createElement('div');placeholder.className = 'frame-placeholder';- placeholder.style.setProperty('--type-color', color);placeholder.innerHTML = `<div class="frame-ph-inner">- <button type="button" class="play-btn" aria-label="Load ${w.label} preview">+ <button type="button" class="play-btn" aria-label="Load ${escHtml(w.label)} preview"><svg viewBox="0 0 24 24" width="28" height="28" fill="currentColor" aria-hidden="true"><path d="M8 5v14l11-7z"/></svg></button>- <span class="frame-ph-label">${w.label}</span>+ <span class="frame-ph-label">${escHtml(w.label)}</span><span class="frame-ph-dim">${w.width} × ${w.height}</span></div>`;+ let iframe = null;let iframeLoaded = false;const loadIframe = () => {if (iframeLoaded) return;iframeLoaded = true;placeholder.classList.add('frame-placeholder--loading');- const iframe = document.createElement('iframe');- iframe.src = widgetUrl;+ iframe = document.createElement('iframe');+ iframe.src = widgetUrl();iframe.title = `${w.label} demo`;iframe.loading = 'eager';iframe.allow = allowAttr;iframe.onload = () => placeholder.remove();frame.appendChild(iframe);};+ const reloadIframe = () => {+ if (!iframe) return;+ iframe.src = widgetUrl();+ };placeholder.querySelector('.play-btn').addEventListener('click', loadIframe);frame.appendChild(placeholder);- // Auto-load when the frame becomes 50% visible. No artificial delay —- // IntersectionObserver only fires after layout, so by the time we get- // here the user has actually scrolled the tile into view.+ // Auto-load when the frame becomes 50 % visible.const autoObs = new IntersectionObserver((entries) => {if (entries[0].isIntersecting) {@@ -220,6 +324,33 @@ function renderShowcase(w) {);autoObs.observe(frame);+ // Code panel — shown when Code tab active. Mirrors the snippet element below+ // the customizer for power users who want it in the preview area too.+ const codePanel = document.createElement('div');+ codePanel.className = 'frame-code-panel';+ codePanel.hidden = true;+ const codePanelPre = document.createElement('pre');+ codePanelPre.className = 'frame-code';+ const codePanelInner = document.createElement('code');+ codePanelPre.appendChild(codePanelInner);+ codePanel.appendChild(codePanelPre);++ frameWrap.appendChild(frame);+ frameWrap.appendChild(codePanel);++ previewTab.addEventListener('click', () => switchTab('preview'));+ codeTab.addEventListener('click', () => switchTab('code'));+ function switchTab(which) {+ const isPreview = which === 'preview';+ previewTab.setAttribute('aria-selected', String(isPreview));+ codeTab.setAttribute('aria-selected', String(!isPreview));+ previewTab.dataset.active = isPreview ? 'true' : '';+ codeTab.dataset.active = isPreview ? '' : 'true';+ frame.hidden = !isPreview;+ codePanel.hidden = isPreview;+ if (!isPreview) refreshSnippetOutputs();+ }+// ── Meta ──const meta = document.createElement('div');meta.className = 'showcase-meta';@@ -227,7 +358,6 @@ function renderShowcase(w) {const tag = document.createElement('span');tag.className = 'type-tag';tag.textContent = w.type.replace(/-/g, ' ');- tag.style.setProperty('--type-color', color);meta.appendChild(tag);const h = document.createElement('h3');@@ -250,24 +380,206 @@ function renderShowcase(w) {meta.appendChild(ul);}- const code = document.createElement('pre');- code.className = 'snippet';- code.setAttribute('aria-label', 'Embed snippet');+ // ── Customize panel ──+ const customize = document.createElement('details');+ customize.className = 'customize';+ customize.open = false;++ const summary = document.createElement('summary');+ summary.innerHTML = `<svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true">+ <circle cx="12" cy="12" r="3"/>+ <path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 1 1-4 0v-.09a1.65 1.65 0 0 0-1-1.51 1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 1 1 0-4h.09a1.65 1.65 0 0 0 1.51-1 1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 1 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 1 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z"/>+ </svg><span>Customize</span>`;+ customize.appendChild(summary);++ const knobs = document.createElement('div');+ knobs.className = 'customize-knobs';++ // Size preset+ const sizeRow = makeKnobRow('Size');+ const sizeBtns = document.createElement('div');+ sizeBtns.className = 'size-presets';+ ['S', 'M', 'L'].forEach((s) => {+ const b = document.createElement('button');+ b.type = 'button';+ b.textContent = s;+ b.dataset.size = s;+ if (s === state.size) b.dataset.active = 'true';+ b.addEventListener('click', () => {+ state.size = s;+ sizeBtns.querySelectorAll('button').forEach((bb) =>+ bb.removeAttribute('data-active'),+ );+ b.dataset.active = 'true';+ frame.style.maxWidth = `${currentWidth()}px`;+ refreshSnippetOutputs();+ });+ sizeBtns.appendChild(b);+ });+ sizeRow.appendChild(sizeBtns);+ knobs.appendChild(sizeRow);++ // Accent color+ const accentRow = makeKnobRow('Accent');+ const accentInput = document.createElement('input');+ accentInput.type = 'color';+ accentInput.value = state.accent;+ accentInput.setAttribute('aria-label', `Accent color for ${w.label}`);+ accentInput.addEventListener('input', () => {+ state.accent = accentInput.value;+ root.style.setProperty('--type-color', state.accent);+ refreshSnippetOutputs();+ debouncedReload();+ });+ const accentValue = document.createElement('span');+ accentValue.className = 'accent-value';+ accentValue.textContent = state.accent;+ accentInput.addEventListener('input', () => {+ accentValue.textContent = accentInput.value;+ });+ accentRow.appendChild(accentInput);+ accentRow.appendChild(accentValue);+ knobs.appendChild(accentRow);++ // Per-type: mint+ if (TYPE_KNOBS[w.type].includes('mint')) {+ const mintRow = makeKnobRow('Mint');+ const mintInput = document.createElement('input');+ mintInput.type = 'text';+ mintInput.value = state.mint;+ mintInput.placeholder = 'Solana mint address';+ mintInput.spellcheck = false;+ mintInput.setAttribute('aria-label', `Token mint for ${w.label}`);+ mintInput.addEventListener('input', () => {+ state.mint = mintInput.value.trim();+ refreshSnippetOutputs();+ debouncedReload();+ });+ mintRow.appendChild(mintInput);+ knobs.appendChild(mintRow);+ }++ // Per-type: kind (pumpfun-feed)+ if (TYPE_KNOBS[w.type].includes('kind')) {+ const kindRow = makeKnobRow('Kind');+ const kindSelect = document.createElement('select');+ kindSelect.setAttribute('aria-label', `Event kind for ${w.label}`);+ ['all', 'claims', 'graduations'].forEach((opt) => {+ const o = document.createElement('option');+ o.value = opt;+ o.textContent = opt;+ if (opt === state.kind) o.selected = true;+ kindSelect.appendChild(o);+ });+ kindSelect.addEventListener('change', () => {+ state.kind = kindSelect.value;+ refreshSnippetOutputs();+ debouncedReload();+ });+ kindRow.appendChild(kindSelect);+ knobs.appendChild(kindRow);+ }++ // Reset+ const resetBtn = document.createElement('button');+ resetBtn.type = 'button';+ resetBtn.className = 'customize-reset';+ resetBtn.textContent = 'Reset';+ resetBtn.addEventListener('click', () => {+ state.size = 'M';+ state.accent = TYPE_COLORS[w.type] || '#8b5cf6';+ state.mint = defaultMint(w.type);+ state.kind = 'all';+ accentInput.value = state.accent;+ accentValue.textContent = state.accent;+ root.style.setProperty('--type-color', state.accent);+ sizeBtns.querySelectorAll('button').forEach((b) => {+ b.dataset.active = b.dataset.size === 'M' ? 'true' : '';+ });+ frame.style.maxWidth = `${currentWidth()}px`;+ knobs.querySelectorAll('input[type=text]').forEach((i) => (i.value = state.mint));+ knobs.querySelectorAll('select').forEach((s) => (s.value = state.kind));+ refreshSnippetOutputs();+ debouncedReload();+ });+ knobs.appendChild(resetBtn);++ customize.appendChild(knobs);+ meta.appendChild(customize);++ // ── Snippet block ──+ const codeBlock = document.createElement('pre');+ codeBlock.className = 'snippet';+ codeBlock.setAttribute('aria-label', 'Embed snippet');const codeInner = document.createElement('code');- codeInner.textContent = snippet;- code.appendChild(codeInner);- meta.appendChild(code);+ codeBlock.appendChild(codeInner);+ meta.appendChild(codeBlock);+ // ── Actions row: format split-button + studio link ──const row = document.createElement('div');row.className = 'snippet-row';- const copyBtn = makeActionBtn('Copy iframe', `Copy embed snippet for ${w.label}`);- copyBtn.addEventListener('click', () => copy(snippet, copyBtn));- row.appendChild(copyBtn);+ const splitBtn = document.createElement('div');+ splitBtn.className = 'split-btn';++ const copyMain = document.createElement('button');+ copyMain.type = 'button';+ copyMain.className = 'split-btn-main';+ copyMain.setAttribute('aria-label', `Copy ${w.label} embed`);+ splitBtn.appendChild(copyMain);++ const formatToggle = document.createElement('button');+ formatToggle.type = 'button';+ formatToggle.className = 'split-btn-toggle';+ formatToggle.setAttribute('aria-haspopup', 'menu');+ formatToggle.setAttribute('aria-expanded', 'false');+ formatToggle.setAttribute('aria-label', 'Choose embed format');+ formatToggle.innerHTML = `<svg viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" stroke-width="2.5" aria-hidden="true"><polyline points="6 9 12 15 18 9"/></svg>`;+ splitBtn.appendChild(formatToggle);++ const menu = document.createElement('div');+ menu.className = 'split-btn-menu';+ menu.setAttribute('role', 'menu');+ menu.hidden = true;+ FORMATS.forEach((f) => {+ const item = document.createElement('button');+ item.type = 'button';+ item.className = 'split-btn-menu-item';+ item.setAttribute('role', 'menuitemradio');+ item.textContent = f.label;+ item.dataset.format = f.id;+ if (f.id === state.format) item.setAttribute('aria-checked', 'true');+ item.addEventListener('click', () => {+ state.format = f.id;+ menu.querySelectorAll('[role=menuitemradio]').forEach((mi) =>+ mi.setAttribute('aria-checked', mi.dataset.format === f.id ? 'true' : 'false'),+ );+ closeMenu();+ refreshSnippetOutputs();+ });+ menu.appendChild(item);+ });+ splitBtn.appendChild(menu);+ row.appendChild(splitBtn);- const copyUrlBtn = makeActionBtn('Copy URL', `Copy shareable URL for ${w.label}`);- copyUrlBtn.addEventListener('click', () => copy(pageUrl, copyUrlBtn));- row.appendChild(copyUrlBtn);+ function openMenu() {+ menu.hidden = false;+ formatToggle.setAttribute('aria-expanded', 'true');+ }+ function closeMenu() {+ menu.hidden = true;+ formatToggle.setAttribute('aria-expanded', 'false');+ }+ formatToggle.addEventListener('click', (e) => {+ e.stopPropagation();+ if (menu.hidden) openMenu();+ else closeMenu();+ });+ document.addEventListener('click', (e) => {+ if (!splitBtn.contains(e.target)) closeMenu();+ });++ copyMain.addEventListener('click', () => copy(currentSnippet(), copyMain, formatLabelShort(state.format)));const studio = document.createElement('a');studio.href = `/studio?template=${encodeURIComponent(w.id)}`;@@ -275,26 +587,72 @@ function renderShowcase(w) {studio.target = '_blank';studio.rel = 'noopener noreferrer';studio.setAttribute('aria-label', `Clone ${w.label} in Studio`);+ studio.className = 'studio-link';row.appendChild(studio);meta.appendChild(row);- root.appendChild(frame);+ root.appendChild(frameWrap);root.appendChild(meta);++ // ── Debounced iframe reload while typing ──+ let reloadTimer = null;+ function debouncedReload() {+ if (!iframeLoaded) return;+ clearTimeout(reloadTimer);+ reloadTimer = setTimeout(reloadIframe, 350);+ }++ function currentSnippet() {+ return buildSnippet(state.format);+ }+ function refreshSnippetOutputs() {+ const text = currentSnippet();+ codeInner.textContent = text;+ codePanelInner.textContent = text;+ copyMain.textContent = `Copy ${formatLabelShort(state.format)}`;+ }+ refreshSnippetOutputs();+return root;}-// ─── Helpers ─────────────────────────────────────────────────────────────────+function defaultMint(type) {+ if (type === 'live-trades-canvas') return 'So11111111111111111111111111111111111111112';+ if (type === 'kol-trades') return 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';+ return '';+}-function makeActionBtn(text, ariaLabel) {+function formatLabelShort(id) {+ if (id === 'iframe') return 'iframe';+ if (id === 'jsx') return 'JSX';+ if (id === 'url') return 'URL';+ return id;+}++function makeKnobRow(label) {+ const row = document.createElement('div');+ row.className = 'knob-row';+ const lab = document.createElement('label');+ lab.textContent = label;+ row.appendChild(lab);+ return row;+}++function makeTab(label, active) {const btn = document.createElement('button');btn.type = 'button';- btn.textContent = text;- btn.setAttribute('aria-label', ariaLabel);+ btn.className = 'frame-tab';+ btn.setAttribute('role', 'tab');+ btn.setAttribute('aria-selected', String(!!active));+ if (active) btn.dataset.active = 'true';+ btn.textContent = label;return btn;}-async function copy(text, btn) {+// ─── Helpers ─────────────────────────────────────────────────────────────────++async function copy(text, btn, formatShort) {try {await navigator.clipboard.writeText(text);} catch {@@ -312,11 +670,20 @@ async function copy(text, btn) {btn.classList.add('copied');btn.textContent = 'Copied!';setTimeout(() => {- btn.textContent = orig;+ btn.textContent = formatShort ? `Copy ${formatShort}` : orig;btn.classList.remove('copied');}, 1400);}+function escHtml(s) {+ return String(s ?? '').replace(/[&<>"']/g, (c) =>+ ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]),+ );+}+function escAttr(s) {+ return escHtml(s);+}+function errorEl(msg, detail) {const e = document.createElement('div');e.className = 'error-state';@@ -326,6 +693,6 @@ function errorEl(msg, detail) {<line x1="12" y1="8" x2="12" y2="12"/><circle cx="12" cy="16" r=".5" fill="currentColor"/></svg>- <span>${msg}${detail ? ` — <code>${detail}</code>` : ''}</span>`;+ <span>${escHtml(msg)}${detail ? ` — <code>${escHtml(detail)}</code>` : ''}</span>`;return e;}diff --git a/scripts/set-r2-cors.mjs b/scripts/set-r2-cors.mjsindex 12209989f..ee2b6cd04 100644--- a/scripts/set-r2-cors.mjs+++ b/scripts/set-r2-cors.mjs@@ -160,7 +160,7 @@ async function getCors() {function explainAccessDenied(err, op) {const status = err?.$metadata?.httpStatusCode;const code = err?.Code || err?.name;- if (status !== 403 && code !== 'AccessDenied') return;+ if (status !== 403 && code !== 'AccessDenied') return false;console.error('');console.error(`AccessDenied while ${op} bucket CORS on "${Bucket}".`);console.error('');@@ -173,6 +173,7 @@ function explainAccessDenied(err, op) {console.error(' 4. Replace R2_ACCESS_KEY_ID / R2_SECRET_ACCESS_KEY in .env.local');console.error(' with the new token, then rerun: node scripts/set-r2-cors.mjs');console.error('');+ return true;}function loadDotenv(path) {diff --git a/scripts/verify-save-error.mjs b/scripts/verify-save-error.mjsnew file mode 100644index 000000000..d40c6a81a--- /dev/null+++ b/scripts/verify-save-error.mjs@@ -0,0 +1,213 @@+// Verifies the save-error UX added to /create-review:+// - faked-auth window stages a real Save click+// - presign route returns 502 to force the inline error surface+// - asserts the error overlay shows title + detail + Retry/Cancel+// - clicks Cancel → editing UI returns, save button re-enabled+// - reopens the flow, clicks Retry → second presign request fires+//+// Run after `npm run dev`: node scripts/verify-save-error.mjs+import { chromium } from 'playwright';+import { readFile } from 'node:fs/promises';+import { resolve } from 'node:path';++const BASE = process.env.BASE_URL || 'http://localhost:3000';+const GLB_PATH = resolve('public/avatars/default.glb');++function fail(msg) {+ console.error('FAIL:', msg);+ process.exitCode = 1;+}++const glbBuffer = await readFile(GLB_PATH);+const browser = await chromium.launch();+const ctx = await browser.newContext({ viewport: { width: 1440, height: 1100 } });+const page = await ctx.newPage();++const consoleErrors = [];+page.on('console', (m) => {+ if (m.type() === 'error') consoleErrors.push(m.text());+});+page.on('pageerror', (err) => consoleErrors.push(`pageerror: ${err.message}`));++// Block Vite HMR so concurrent dev edits can't reload the page mid-test.+await page.route('**/@vite/client', (route) => route.abort());+await page.route('**/__vite_ping*', (route) => route.abort());+page.on('websocket', (ws) => {+ if (/\/\?token=|\/__hmr/.test(ws.url())) ws.close().catch(() => {});+});++// Fake a signed-in user so the page enables Save and the auth pre-check+// inside apiFetch's CSRF flow passes.+let presignCallCount = 0;+await page.route('**/api/auth/me', (route) =>+ route.fulfill({+ status: 200,+ contentType: 'application/json',+ body: JSON.stringify({+ user: {+ id: 'u-test',+ email: '[email protected]',+ display_name: 'Test User',+ plan: 'free',+ avatar_url: null,+ referral_code: 'TESTREF',+ },+ }),+ }),+);+await page.route('**/api/csrf-token', (route) =>+ route.fulfill({+ status: 200,+ contentType: 'application/json',+ body: JSON.stringify({ data: { token: 'csrf-test' } }),+ }),+);+await page.route('**/api/avatars/presign', (route) => {+ presignCallCount++;+ return route.fulfill({+ status: 502,+ contentType: 'text/html',+ body: '<html>502 Bad Gateway</html>',+ });+});++async function gotoWithRetry(url, tries = 3) {+ for (let i = 0; i < tries; i++) {+ try {+ await page.goto(url, { waitUntil: 'load', timeout: 15_000 });+ return;+ } catch (err) {+ if (i === tries - 1) throw err;+ await new Promise((r) => setTimeout(r, 1500));+ }+ }+}++await gotoWithRetry(`${BASE}/create-review`);++// Seed IDB with the staged GLB, then reload so create-review.js boots with it.+const glbB64 = Buffer.from(glbBuffer).toString('base64');+await page.evaluate(async (b64) => {+ const bin = atob(b64);+ const bytes = new Uint8Array(bin.length);+ for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);+ const blob = new Blob([bytes], { type: 'model/gltf-binary' });+ const id = 'errver01';+ const record = { blob, meta: { source: 'avaturn' }, id, name: 'Save-error verify', size: blob.size, createdAt: Date.now() };+ const db = await new Promise((res, rej) => {+ const req = indexedDB.open('three-ws-guest', 1);+ req.onupgradeneeded = () => {+ if (!req.result.objectStoreNames.contains('avatars'))+ req.result.createObjectStore('avatars');+ };+ req.onsuccess = () => res(req.result);+ req.onerror = () => rej(req.error);+ });+ await new Promise((res, rej) => {+ const tx = db.transaction('avatars', 'readwrite');+ tx.objectStore('avatars').put(record, 'pending');+ tx.oncomplete = res;+ tx.onerror = () => rej(tx.error);+ });+ db.close();+ localStorage.setItem(+ '3dagent:guest-avatar-meta',+ JSON.stringify({ id, name: record.name, size: record.size, createdAt: Date.now(), source: 'avaturn' }),+ );+}, glbB64);++consoleErrors.length = 0;+await page.reload({ waitUntil: 'load' });++// Wait for boot to finish staging + auth to resolve. The Save button starts+// disabled and becomes enabled by applyAuthState() once auth resolves.+await page.waitForFunction(+ () => !document.getElementById('content')?.hidden,+ { timeout: 10_000 },+);+await page.waitForFunction(+ () => {+ const btn = document.getElementById('save-btn');+ return btn && !btn.disabled && btn.textContent.trim() === 'Save to my account';+ },+ { timeout: 10_000 },+);++// First Save attempt → presign returns 502 → inline error surface appears.+await page.click('#save-btn');+await page.waitForFunction(+ () => document.getElementById('save-loading')?.getAttribute('data-state') === 'error',+ { timeout: 10_000 },+);++// presign should have been called exactly once (no retry on 5xx for POST).+if (presignCallCount !== 1) fail(`expected 1 presign call, got ${presignCallCount}`);++const errLabel = await page.textContent('#save-loading .label');+const errDetail = await page.textContent('#save-loading .sublabel');+if (!/Couldn't reserve upload|Save didn't finish/.test(errLabel?.trim() || '')) {+ fail(`unexpected error title: "${errLabel}"`);+}+if (!/reach the server|try again/i.test(errDetail?.trim() || '')) {+ fail(`unexpected error detail: "${errDetail}"`);+}++// Cancel returns the page to editing.+await page.locator('#save-loading .cancel-btn').dispatchEvent('click');+await page.waitForFunction(+ () => !document.getElementById('save-loading'),+ { timeout: 5_000 },+);+const saveStillEnabled = await page.evaluate(+ () => !document.getElementById('save-btn').disabled,+);+if (!saveStillEnabled) fail('Save button should re-enable after Cancel');++// Trigger the flow again, this time clicking Retry, and assert presign was+// called a second time (Retry actually re-runs onSave end to end).+await page.click('#save-btn');+await page.waitForFunction(+ () => document.getElementById('save-loading')?.getAttribute('data-state') === 'error',+ { timeout: 10_000 },+);+const beforeRetry = presignCallCount;+await page.locator('#save-loading .retry-btn').dispatchEvent('click');+// Retry re-runs onSave → presign fires again → returns 502 → error surface+// reappears. Wait until presign has been called once more.+await page.waitForFunction(+ (prev) => window.__verifyPresignCount === undefined+ ? true // We can't read presignCallCount across processes; just assert error reappears.+ : window.__verifyPresignCount > prev,+ beforeRetry,+ { timeout: 10_000 },+);+// More authoritative: wait for the error overlay to reappear after Retry.+await page.waitForFunction(+ () => document.getElementById('save-loading')?.getAttribute('data-state') === 'error',+ { timeout: 10_000 },+);+if (presignCallCount <= beforeRetry) fail(`Retry didn't fire a new presign call (count ${presignCallCount})`);++// Screenshot the error state for visual diff.+await page.screenshot({ path: '/tmp/create-review-save-error.png', fullPage: false });++if (consoleErrors.length) {+ const filtered = consoleErrors.filter(+ (e) =>+ !/favicon|three-ws:auth-resolved|^Refused to apply style/.test(e) &&+ !/net::ERR_FAILED|Failed to load resource/i.test(e) &&+ // The save itself logs '[create-review] save failed' to console.error —+ // expected and exercised below.+ !/\[create-review\] save failed/.test(e),+ );+ if (filtered.length) {+ console.error('console errors:');+ for (const e of filtered) console.error(' ', e);+ fail('unexpected console errors');+ }+}++await browser.close();++if (process.exitCode) console.error('verification failed');+else console.log('OK (presign calls:', presignCallCount, ')');diff --git a/src/avatar-edit.js b/src/avatar-edit.jsindex 25cd5ec7e..e50032880 100644--- a/src/avatar-edit.js+++ b/src/avatar-edit.js@@ -22,6 +22,7 @@ import { TalkScene } from './voice/talk-scene.js';import { AccessoryManager } from './agent-accessories.js';import { uploadAvatarSnapshot } from './voice/avatar-snapshot.js';import { IdleAnimation } from './idle-animation.js';+import { renderSculptPanel } from './avatar-sculpt.js';// ── Routing ────────────────────────────────────────────────────────────@@ -82,6 +83,7 @@ const TABS = [{ 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 },+ { id: 'sculpt', label: 'Sculpt', kinds: [], emoji: '✨', single: true, sculpt: true },];const KIND_EMOJI = {outfit: '👕',@@ -256,6 +258,27 @@ function renderTabs() {function renderActivePanel() {const tab = TABS.find((t) => t.id === activeTab);const panel = $('ae-panel');++ // Sculpt tab gets its own UI — morph sliders, not a tile grid. The face-+ // capture modal lives inside that module, so the avatar-edit shell doesn't+ // need to know anything about MediaPipe loading or webcam plumbing.+ if (tab.sculpt) {+ if (!scene?.root) {+ panel.innerHTML = `<div class="ae-empty">Waiting for avatar to load…</div>`;+ return;+ }+ renderSculptPanel({+ container: panel,+ root: scene.root,+ working: workingAppearance,+ onDirty: () => {+ renderChips();+ updateDirtyState();+ },+ });+ return;+ }+const q = searchQuery.trim().toLowerCase();const items = presets.filter((p) => tab.kinds.includes(p.kind) && (!q || p.name.toLowerCase().includes(q)),diff --git a/src/avatar-face-capture.js b/src/avatar-face-capture.jsnew file mode 100644index 000000000..a28d29149--- /dev/null+++ b/src/avatar-face-capture.js@@ -0,0 +1,83 @@+/**+ * Browser-side selfie → ARKit-52 blendshapes via MediaPipe Face Landmarker.+ *+ * No bundling: the tasks-vision package + WASM model (~5 MB total) load on+ * demand from a CDN. The first call pays a one-time cost; subsequent+ * captures reuse the cached FaceLandmarker instance.+ *+ * import { detectFaceBlendshapes } from './avatar-face-capture.js';+ * const lm = await detectFaceBlendshapes.loadLandmarker();+ * const map = await detectFaceBlendshapes(canvasOrImage, lm);+ * // map: { jawOpen: 0.12, mouthSmileLeft: 0.04, ... } (52 keys)+ *+ * The 52 returned keys are exactly the ARKit blendshape names so they bind+ * 1:1 to RPM / Avaturn / three.ws avatar morphs without any rename pass.+ *+ * License-trap reminder: MediaPipe and the face-landmarker model are both+ * Apache-2.0 — safe to ship. We do *not* bundle FLAME / DECA / SMPL-X weights+ * because those are research-only / non-commercial. See the survey notes.+ */++// We load tasks-vision via dynamic ESM import. Pinning to a specific version+// avoids breaking changes from auto-upgraded CDN aliases; jsDelivr's `+esm`+// suffix returns the ESM build.+const TASKS_VISION_URL =+ 'https://cdn.jsdelivr.net/npm/@mediapipe/[email protected]/+esm';++// Hosted by Google. They publish exactly one official URL per model — these+// are the standard locations used in every MediaPipe sample, public CORS,+// no auth.+const WASM_ROOT =+ 'https://cdn.jsdelivr.net/npm/@mediapipe/[email protected]/wasm';+const MODEL_URL =+ 'https://storage.googleapis.com/mediapipe-models/face_landmarker/face_landmarker/float16/1/face_landmarker.task';++let _landmarkerPromise = null;++/**+ * Detect blendshapes from a single image source (canvas, image, or+ * ImageBitmap). Returns an object keyed by the 52 ARKit blendshape names.+ *+ * @param {HTMLCanvasElement|HTMLImageElement|ImageBitmap} source+ * @param {object} [landmarker] — pre-loaded FaceLandmarker (optional)+ * @returns {Promise<Record<string, number>|null>}+ */+export async function detectFaceBlendshapes(source, landmarker) {+ const lm = landmarker || (await loadLandmarker());+ const result = lm.detect(source);+ const arr = result?.faceBlendshapes?.[0]?.categories;+ if (!arr || !arr.length) return null;+ const out = {};+ for (const c of arr) {+ // MediaPipe returns the index-0 "_neutral" pseudo-shape too; skip it.+ if (!c.categoryName || c.categoryName === '_neutral') continue;+ out[c.categoryName] = c.score;+ }+ return out;+}++/**+ * Pre-warm the FaceLandmarker. Useful when the host UI wants to overlap+ * model download with camera permission UI. Subsequent calls are no-ops.+ */+detectFaceBlendshapes.loadLandmarker = loadLandmarker;++function loadLandmarker() {+ if (_landmarkerPromise) return _landmarkerPromise;+ _landmarkerPromise = (async () => {+ const mod = await import(/* @vite-ignore */ TASKS_VISION_URL);+ const { FilesetResolver, FaceLandmarker } = mod;+ const vision = await FilesetResolver.forVisionTasks(WASM_ROOT);+ return FaceLandmarker.createFromOptions(vision, {+ baseOptions: { modelAssetPath: MODEL_URL, delegate: 'GPU' },+ outputFaceBlendshapes: true,+ outputFacialTransformationMatrixes: false,+ runningMode: 'IMAGE',+ numFaces: 1,+ });+ })().catch((err) => {+ _landmarkerPromise = null; // allow a retry next time+ throw err;+ });+ return _landmarkerPromise;+}diff --git a/src/avatar-sculpt.js b/src/avatar-sculpt.jsnew file mode 100644index 000000000..9848019d1--- /dev/null+++ b/src/avatar-sculpt.js@@ -0,0 +1,447 @@+/**+ * Avatar sculpt — face/body morph sliders for /avatars/:id/edit+ *+ * The avatar GLBs we ship (Avaturn, Ready Player Me, three.ws Studio) carry+ * the 52 ARKit blendshapes by name (see src/runtime/arkit52.js). Plus, RPM-+ * style bodies carry a handful of body-shape morphs (height, breast, etc.).+ *+ * This module renders a grouped slider panel against whatever morphs the+ * loaded avatar actually exposes. No invented sliders; no silently-broken+ * controls. What the user sees == what the rig can do.+ *+ * State model: avatar-edit.js owns `workingAppearance.morphs = { name: w }`.+ * We mutate that dict on slider input + apply influence to every skinned+ * mesh's `morphTargetInfluences` in real time. Save flow is unchanged.+ */++import { detectFaceBlendshapes } from './avatar-face-capture.js';++/* ────────────────────────────────────────────────────────────────────────── *+ * Category map — orders + groups the 52 ARKit names + common body morphs+ * into something a human can scan. Names not in this map fall into "Other".+ * Display label is generated from camelCase on render — no per-name copy.+ * ────────────────────────────────────────────────────────────────────────── */++const CATEGORIES = [+ {+ id: 'eyes',+ label: 'Eyes',+ match: /^eye/,+ preferred: [+ 'eyeBlinkLeft', 'eyeBlinkRight',+ 'eyeWideLeft', 'eyeWideRight',+ 'eyeSquintLeft', 'eyeSquintRight',+ 'eyeLookUpLeft', 'eyeLookUpRight',+ 'eyeLookDownLeft', 'eyeLookDownRight',+ 'eyeLookInLeft', 'eyeLookInRight',+ 'eyeLookOutLeft', 'eyeLookOutRight',+ ],+ },+ {+ id: 'brows',+ label: 'Brows',+ match: /^brow/,+ preferred: ['browInnerUp', 'browOuterUpLeft', 'browOuterUpRight', 'browDownLeft', 'browDownRight'],+ },+ {+ id: 'nose',+ label: 'Nose',+ match: /^(nose|noseSneer)/,+ preferred: ['noseSneerLeft', 'noseSneerRight'],+ },+ {+ id: 'mouth',+ label: 'Mouth',+ match: /^mouth/,+ preferred: [+ 'mouthSmileLeft', 'mouthSmileRight',+ 'mouthFrownLeft', 'mouthFrownRight',+ 'mouthDimpleLeft', 'mouthDimpleRight',+ 'mouthStretchLeft', 'mouthStretchRight',+ 'mouthPressLeft', 'mouthPressRight',+ 'mouthShrugLower', 'mouthShrugUpper',+ 'mouthLowerDownLeft', 'mouthLowerDownRight',+ 'mouthUpperUpLeft', 'mouthUpperUpRight',+ 'mouthRollLower', 'mouthRollUpper',+ 'mouthFunnel', 'mouthPucker', 'mouthClose',+ 'mouthLeft', 'mouthRight',+ ],+ },+ {+ id: 'jaw',+ label: 'Jaw',+ match: /^jaw/,+ preferred: ['jawOpen', 'jawForward', 'jawLeft', 'jawRight'],+ },+ {+ id: 'cheeks',+ label: 'Cheeks',+ match: /^cheek/,+ preferred: ['cheekPuff', 'cheekSquintLeft', 'cheekSquintRight'],+ },+ {+ id: 'tongue',+ label: 'Tongue',+ match: /^tongue/,+ preferred: ['tongueOut'],+ },+ {+ id: 'body',+ label: 'Body',+ // RPM-style body morphs all start with these prefixes. Daz/CC use+ // uppercase but normalize-friendly here since we match by name.+ match: /^(body|shape|height|breast|chest|waist|hip|muscle|weight|bust|gluteus|figure|thighs|arms)/i,+ },+ {+ id: 'visemes',+ label: 'Visemes (advanced)',+ match: /^viseme_/,+ collapsed: true,+ preferred: [+ 'viseme_sil', 'viseme_PP', 'viseme_FF', 'viseme_TH', 'viseme_DD',+ 'viseme_kk', 'viseme_CH', 'viseme_SS', 'viseme_nn', 'viseme_RR',+ 'viseme_aa', 'viseme_E', 'viseme_I', 'viseme_O', 'viseme_U',+ ],+ },+];++const ARKIT52 = new Set([+ 'eyeBlinkLeft','eyeBlinkRight','eyeLookDownLeft','eyeLookDownRight','eyeLookInLeft','eyeLookInRight','eyeLookOutLeft','eyeLookOutRight','eyeLookUpLeft','eyeLookUpRight','eyeSquintLeft','eyeSquintRight','eyeWideLeft','eyeWideRight','jawForward','jawLeft','jawRight','jawOpen','mouthClose','mouthFunnel','mouthPucker','mouthLeft','mouthRight','mouthSmileLeft','mouthSmileRight','mouthFrownLeft','mouthFrownRight','mouthDimpleLeft','mouthDimpleRight','mouthStretchLeft','mouthStretchRight','mouthRollLower','mouthRollUpper','mouthShrugLower','mouthShrugUpper','mouthPressLeft','mouthPressRight','mouthLowerDownLeft','mouthLowerDownRight','mouthUpperUpLeft','mouthUpperUpRight','browDownLeft','browDownRight','browInnerUp','browOuterUpLeft','browOuterUpRight','cheekPuff','cheekSquintLeft','cheekSquintRight','noseSneerLeft','noseSneerRight','tongueOut',+]);++/* ────────────────────────────────────────────────────────────────────────── *+ * Public API+ * ────────────────────────────────────────────────────────────────────────── */++/**+ * Discover every morph target on the loaded scene root and return the union+ * of names (across all skinned meshes). Returns alphabetized for stable UI.+ */+export function discoverMorphs(root) {+ const found = new Set();+ root?.traverse?.((obj) => {+ if (obj.isMesh && obj.morphTargetDictionary) {+ for (const k of Object.keys(obj.morphTargetDictionary)) found.add(k);+ }+ });+ return [...found].sort();+}++/**+ * Apply { name: weight } to every mesh on the root. Out-of-range weights are+ * clamped; unknown names are silently skipped (mirrors AccessoryManager).+ */+export function applyMorphsToRoot(root, morphs) {+ if (!root || !morphs) return;+ root.traverse((node) => {+ if (!node.isMesh || !node.morphTargetDictionary || !node.morphTargetInfluences) return;+ for (const [name, weight] of Object.entries(morphs)) {+ const idx = node.morphTargetDictionary[name];+ if (idx === undefined) continue;+ node.morphTargetInfluences[idx] = Math.max(-1, Math.min(1, weight));+ }+ });+}++/**+ * Render the sculpt panel into the supplied container. Idempotent — calling+ * twice rebuilds. The opts wire to avatar-edit.js's state machinery so we+ * don't fork the dirty-tracking or save path.+ *+ * @param {object} opts+ * @param {HTMLElement} opts.container — element to render into+ * @param {object} opts.root — Three.js scene root (used to discover morphs)+ * @param {object} opts.working — workingAppearance reference (we mutate .morphs)+ * @param {() => void} opts.onDirty — called after each change+ */+export function renderSculptPanel({ container, root, working, onDirty }) {+ const all = discoverMorphs(root);+ if (!all.length) {+ container.innerHTML = `+ <div class="ae-empty">+ This avatar has no sculptable morph targets.<br/>+ Re-import it through <a href="/create" style="color:inherit">/create</a>+ to get a rig with ARKit-52 blendshapes.+ </div>`;+ return;+ }++ const groups = groupMorphs(all);+ working.morphs = working.morphs || {};++ // Build DOM+ container.innerHTML = `+ <div class="ae-sculpt-head">+ <button class="ae-btn ae-sculpt-capture" type="button" id="ae-sculpt-capture">+ <span class="ae-sculpt-capture-icon" aria-hidden="true">📸</span>+ Capture from photo+ </button>+ <button class="ae-btn ae-sculpt-reset" type="button" id="ae-sculpt-reset">+ Reset all+ </button>+ </div>+ <p class="ae-sculpt-note">+ Drag a slider to sculpt that morph in real time. The capture button+ takes one selfie and writes the 52 ARKit blendshapes into your+ avatar so it carries your resting expression.+ </p>+ ${groups+ .map((g) => `+ <details class="ae-sculpt-group" ${g.collapsed ? '' : 'open'}>+ <summary>+ <span>${g.label}</span>+ <span class="ae-sculpt-count">${g.morphs.length}</span>+ </summary>+ <div class="ae-sculpt-rows">+ ${g.morphs+ .map((m) => sliderRow(m, working.morphs[m] || 0))+ .join('')}+ </div>+ </details>+ `)+ .join('')}+ `;++ container.querySelectorAll('input[type="range"][data-morph]').forEach((input) => {+ const name = input.dataset.morph;+ const valEl = container.querySelector(`output[data-for="${cssEscape(name)}"]`);+ const onChange = () => {+ const w = Number(input.value);+ if (w === 0) {+ delete working.morphs[name];+ } else {+ working.morphs[name] = w;+ }+ applyMorphsToRoot(root, { [name]: w });+ if (valEl) valEl.textContent = w.toFixed(2);+ onDirty?.();+ };+ input.addEventListener('input', onChange);+ input.addEventListener('dblclick', () => {+ input.value = '0';+ onChange();+ });+ });++ container.querySelector('#ae-sculpt-reset')?.addEventListener('click', () => {+ // Wipe all morphs we control, re-apply 0, re-render so sliders snap back.+ const previousKeys = Object.keys(working.morphs);+ working.morphs = {};+ const zeros = {};+ for (const k of previousKeys) zeros[k] = 0;+ applyMorphsToRoot(root, zeros);+ renderSculptPanel({ container, root, working, onDirty });+ onDirty?.();+ });++ container.querySelector('#ae-sculpt-capture')?.addEventListener('click', () => {+ openFaceCaptureModal({ root, working, onDirty, rerender: () => {+ renderSculptPanel({ container, root, working, onDirty });+ } });+ });+}++/* ────────────────────────────────────────────────────────────────────────── *+ * Face capture modal — webcam → MediaPipe → ARKit-52 weights+ * ────────────────────────────────────────────────────────────────────────── */++let activeFaceModal = null;++function openFaceCaptureModal({ root, working, onDirty, rerender }) {+ if (activeFaceModal) return;++ const backdrop = document.createElement('div');+ backdrop.className = 'ae-face-backdrop';+ backdrop.innerHTML = `+ <div class="ae-face-dialog" role="dialog" aria-modal="true">+ <button class="ae-face-close" type="button" aria-label="Close">✕</button>+ <h3>Capture face shape</h3>+ <p class="ae-face-lede">+ Face the camera with a neutral, relaxed expression. We'll read+ the 52 ARKit blendshapes in your browser — no upload, no+ server. Lighting matters; a flat front-on shot works best.+ </p>+ <div class="ae-face-stage">+ <video id="ae-face-video" autoplay playsinline muted></video>+ <canvas id="ae-face-canvas" hidden></canvas>+ <div class="ae-face-status" id="ae-face-status">Allow camera access to start.</div>+ </div>+ <div class="ae-face-actions">+ <button class="ae-btn" type="button" id="ae-face-cancel">Cancel</button>+ <button class="ae-btn primary" type="button" id="ae-face-shoot" disabled>Capture</button>+ </div>+ </div>+ `;+ document.body.appendChild(backdrop);+ activeFaceModal = backdrop;++ const video = backdrop.querySelector('#ae-face-video');+ const canvas = backdrop.querySelector('#ae-face-canvas');+ const status = backdrop.querySelector('#ae-face-status');+ const shootBtn = backdrop.querySelector('#ae-face-shoot');+ const cancelBtn = backdrop.querySelector('#ae-face-cancel');+ const closeBtn = backdrop.querySelector('.ae-face-close');++ let stream = null;+ let landmarker = null;+ let cancelled = false;++ async function boot() {+ status.textContent = 'Requesting camera…';+ try {+ stream = await navigator.mediaDevices.getUserMedia({+ video: { facingMode: 'user', width: { ideal: 720 }, height: { ideal: 720 } },+ audio: false,+ });+ if (cancelled) return;+ video.srcObject = stream;+ await video.play().catch(() => {});+ status.textContent = 'Loading face model… (5–10 MB)';+ } catch (err) {+ status.textContent = `Camera unavailable: ${err.message}`;+ return;+ }+ try {+ landmarker = await detectFaceBlendshapes.loadLandmarker();+ if (cancelled) return;+ status.textContent = 'Ready. Hold still and capture.';+ shootBtn.disabled = false;+ } catch (err) {+ status.textContent = `Couldn't load face model: ${err.message}`;+ }+ }++ function teardown() {+ cancelled = true;+ stream?.getTracks()?.forEach((t) => t.stop());+ activeFaceModal?.remove();+ activeFaceModal = null;+ }++ cancelBtn.addEventListener('click', teardown);+ closeBtn.addEventListener('click', teardown);+ backdrop.addEventListener('click', (e) => { if (e.target === backdrop) teardown(); });++ shootBtn.addEventListener('click', async () => {+ shootBtn.disabled = true;+ status.textContent = 'Reading face…';+ try {+ canvas.width = video.videoWidth || 640;+ canvas.height = video.videoHeight || 640;+ const ctx = canvas.getContext('2d');+ ctx.drawImage(video, 0, 0, canvas.width, canvas.height);+ const blendshapes = await detectFaceBlendshapes(canvas, landmarker);+ if (!blendshapes || !Object.keys(blendshapes).length) {+ status.textContent = 'No face detected. Try again with better lighting.';+ shootBtn.disabled = false;+ return;+ }++ // Write to working.morphs — only for keys the avatar actually has.+ const available = new Set(discoverMorphs(root));+ let applied = 0;+ for (const [name, weight] of Object.entries(blendshapes)) {+ if (!available.has(name)) continue;+ // Capture is a *baseline* — write small weights only. Anything+ // above 0.95 is almost certainly a smile/eye-wide from the user+ // blinking mid-capture and we'd rather under-shoot than burn in+ // a winking face forever.+ const clamped = Math.max(0, Math.min(0.9, weight));+ if (clamped < 0.02) {+ delete working.morphs[name];+ } else {+ working.morphs[name] = clamped;+ applied++;+ }+ }+ applyMorphsToRoot(root, working.morphs);+ status.textContent = `Applied ${applied} blendshapes.`;+ onDirty?.();+ rerender?.();+ setTimeout(teardown, 600);+ } catch (err) {+ console.error('[avatar-sculpt] capture failed', err);+ status.textContent = `Capture failed: ${err.message}`;+ shootBtn.disabled = false;+ }+ });++ boot();+}++/* ────────────────────────────────────────────────────────────────────────── *+ * Helpers+ * ────────────────────────────────────────────────────────────────────────── */++function groupMorphs(all) {+ const seen = new Set();+ const groups = [];+ for (const cat of CATEGORIES) {+ const ours = [];+ // Preferred names first (in spec order), then any other matches.+ if (cat.preferred) {+ for (const name of cat.preferred) {+ if (all.includes(name) && !seen.has(name)) {+ ours.push(name);+ seen.add(name);+ }+ }+ }+ for (const name of all) {+ if (seen.has(name)) continue;+ if (cat.match.test(name)) {+ ours.push(name);+ seen.add(name);+ }+ }+ if (ours.length) {+ groups.push({ id: cat.id, label: cat.label, morphs: ours, collapsed: !!cat.collapsed });+ }+ }+ // "Other" bucket for anything custom (e.g. RPM Outfit_Top morphs)+ const leftovers = all.filter((n) => !seen.has(n));+ if (leftovers.length) {+ groups.push({ id: 'other', label: 'Other', morphs: leftovers, collapsed: true });+ }+ return groups;+}++function sliderRow(name, value) {+ const label = humanize(name);+ const meta = ARKIT52.has(name) ? 'ARKit' : isVisemeName(name) ? 'Viseme' : '';+ return `+ <div class="ae-sculpt-row">+ <div class="ae-sculpt-label">+ <span class="ae-sculpt-name" title="${escAttr(name)}">${escHtml(label)}</span>+ ${meta ? `<span class="ae-sculpt-meta">${meta}</span>` : ''}+ </div>+ <input+ type="range"+ min="0" max="1" step="0.01"+ value="${value}"+ data-morph="${escAttr(name)}"+ aria-label="${escAttr(label)}"+ />+ <output class="ae-sculpt-value" data-for="${escAttr(name)}">${(+value).toFixed(2)}</output>+ </div>+ `;+}++function humanize(name) {+ return name+ .replace(/^viseme_/, '')+ .replace(/_/g, ' ')+ .replace(/([a-z])([A-Z])/g, '$1 $2')+ .replace(/\b(left|right)$/i, (m) => m.toUpperCase() === 'LEFT' ? 'Left' : 'Right')+ .replace(/^./, (c) => c.toUpperCase());+}++function isVisemeName(name) {+ return /^viseme_/.test(name);+}++function escHtml(s) {+ return String(s).replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]);+}+function escAttr(s) { return escHtml(s); }+function cssEscape(s) { return String(s).replace(/(["\\])/g, '\\$1'); }diff --git a/src/create-review-features.js b/src/create-review-features.jsindex 793ac1fc2..f618f0a6a 100644--- a/src/create-review-features.js+++ b/src/create-review-features.js@@ -18,22 +18,32 @@ import { downloadAvatar } from './avatar-export.js';let activeModal = null;let escHandler = null;+let keyTrapHandler = null;+let lastFocusedBeforeOpen = null;+const FOCUSABLE_SEL =+ 'a[href], button:not([disabled]), textarea:not([disabled]), input:not([disabled]):not([type="hidden"]), select:not([disabled]), [tabindex]:not([tabindex="-1"])';/** Open a feature-preview modal. Body may be an HTMLElement or HTML string. */-export function openFeatureModal({ icon, title, lede, body, actions }) {+export function openFeatureModal({ icon, title, lede, body, actions, dialogClass }) {closeFeatureModal();+ // Remember the tile (or any element) the user came from so focus can return+ // there on close — keyboard users get dropped back exactly where they were.+ lastFocusedBeforeOpen = document.activeElement instanceof HTMLElement ? document.activeElement : null;+const backdrop = document.createElement('div');backdrop.className = 'fm-backdrop';backdrop.setAttribute('role', 'dialog');backdrop.setAttribute('aria-modal', 'true');+ backdrop.setAttribute('aria-labelledby', 'fm-title');+ backdrop.setAttribute('aria-describedby', 'fm-lede');backdrop.innerHTML = `- <div class="fm-dialog">+ <div class="fm-dialog${dialogClass ? ' ' + dialogClass : ''}" tabindex="-1"><div class="fm-head"><div class="fm-icon" aria-hidden="true">${icon}</div><div class="fm-head-text">- <h3></h3>- <p></p>+ <h3 id="fm-title"></h3>+ <p id="fm-lede"></p></div><button class="fm-close" type="button" aria-label="Close">✕</button></div>@@ -41,8 +51,8 @@ export function openFeatureModal({ icon, title, lede, body, actions }) {<div class="fm-actions"></div></div>`;- backdrop.querySelector('.fm-head-text h3').textContent = title;- backdrop.querySelector('.fm-head-text p').textContent = lede;+ backdrop.querySelector('#fm-title').textContent = title;+ backdrop.querySelector('#fm-lede').textContent = lede;const bodyEl = backdrop.querySelector('.fm-body');if (body instanceof HTMLElement) bodyEl.appendChild(body);@@ -71,10 +81,36 @@ export function openFeatureModal({ icon, title, lede, body, actions }) {backdrop.querySelector('.fm-close').addEventListener('click', closeFeatureModal);escHandler = (e) => {- if (e.key === 'Escape') closeFeatureModal();+ if (e.key === 'Escape') {+ e.stopPropagation();+ closeFeatureModal();+ }};document.addEventListener('keydown', escHandler);+ // Tab/Shift-Tab cycles focus inside the dialog only. Without this, the+ // underlying page tabs through anchors *behind* the modal — screen readers+ // and keyboard users see "modal open but focus is on the nav header."+ keyTrapHandler = (e) => {+ if (e.key !== 'Tab') return;+ const focusables = Array.from(backdrop.querySelectorAll(FOCUSABLE_SEL))+ .filter((el) => !el.hasAttribute('inert') && el.offsetParent !== null);+ if (!focusables.length) return;+ const first = focusables[0];+ const last = focusables[focusables.length - 1];+ if (e.shiftKey && document.activeElement === first) {+ e.preventDefault();+ last.focus();+ } else if (!e.shiftKey && document.activeElement === last) {+ e.preventDefault();+ first.focus();+ }+ };+ backdrop.addEventListener('keydown', keyTrapHandler);++ // Lock page scroll while the modal owns the viewport.+ document.documentElement.style.overflow = 'hidden';+document.body.appendChild(backdrop);activeModal = backdrop;@@ -98,6 +134,17 @@ export function openFeatureModal({ icon, title, lede, body, actions }) {});}+ // Initial focus: first interactive control inside the body (CTA, copy+ // button, input) rather than the close X — this lets keyboard users hit+ // Enter immediately to act, not just dismiss.+ requestAnimationFrame(() => {+ const initial =+ backdrop.querySelector('.fm-body button, .fm-body a[href], .fm-body input') ||+ backdrop.querySelector('.fm-cta') ||+ backdrop.querySelector('.fm-close');+ initial?.focus({ preventScroll: true });+ });+return backdrop;}@@ -109,6 +156,13 @@ export function closeFeatureModal() {document.removeEventListener('keydown', escHandler);escHandler = null;}+ keyTrapHandler = null;+ document.documentElement.style.overflow = '';+ // Restore focus to whatever the user was on when they opened the modal.+ if (lastFocusedBeforeOpen && document.contains(lastFocusedBeforeOpen)) {+ lastFocusedBeforeOpen.focus({ preventScroll: true });+ }+ lastFocusedBeforeOpen = null;}// ── 3D Body: emote chip strip on the viewer ──────────────────────────────────diff --git a/src/voice/talk-scene.js b/src/voice/talk-scene.jsindex 06f0f0bbe..dc069ab91 100644--- a/src/voice/talk-scene.js+++ b/src/voice/talk-scene.js@@ -62,10 +62,10 @@ export class TalkScene {return () => this._onTickFns.delete(fn);}- async mount({ container, glbUrl, cameraPreset = 'full' }) {+ async mount({ container, glbUrl, glbBlob, cameraPreset = 'full' }) {this._cameraPreset = CAMERA_PRESETS.includes(cameraPreset) ? cameraPreset : 'full';if (!container) throw new Error('TalkScene.mount: container required');- if (!glbUrl) throw new Error('TalkScene.mount: glbUrl required');+ if (!glbUrl && !glbBlob) throw new Error('TalkScene.mount: glbUrl or glbBlob required');this.container = container;// preserveDrawingBuffer keeps the WebGL framebuffer readable via@@ -117,10 +117,25 @@ export class TalkScene {// Load the GLB. Baked avatars carry EXT_meshopt_compression; the// loader can only decode them once the meshopt decoder is wired.+ //+ // When a Blob is supplied we read it into an ArrayBuffer once and call+ // `loader.parse()` directly — no second-fetch hop via object URL. This+ // avoids the "Failed to fetch" class of errors when an unstaged blob+ // URL is invalidated mid-load (navigation away, page reload). For+ // remote URLs we still use `loader.load()`.const loader = new GLTFLoader();loader.setMeshoptDecoder(await getMeshoptDecoder());- const gltf = await new Promise((resolve, reject) => {- loader.load(glbUrl, resolve, undefined, reject);+ const gltf = await new Promise(async (resolve, reject) => {+ try {+ if (glbBlob) {+ const buf = await glbBlob.arrayBuffer();+ loader.parse(buf, '', resolve, reject);+ } else {+ loader.load(glbUrl, resolve, undefined, reject);+ }+ } catch (err) {+ reject(err);+ }});this.gltf = gltf;this.root = gltf.scene;