Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
overlay-control page + hf failover tests + create-review/avatar polish
nirholasfb2f3c048f61
diff --git a/pages/create-review.html b/pages/create-review.htmlindex f8d208261..9dad31778 100644--- a/pages/create-review.html+++ b/pages/create-review.html@@ -510,6 +510,330 @@color: var(--muted);line-height: 1.45;}+ .fm-note code, .fm-bullets code, .fm-handshake code {+ background: rgba(255, 255, 255, 0.06);+ border: 1px solid var(--border);+ border-radius: 4px;+ padding: 1px 5px;+ font-size: 0.92em;+ font-family: ui-monospace, 'SF Mono', 'Cascadia Code', monospace;+ color: var(--text);+ }++ /* Wider dialog for code-heavy modals (embed, paid skills, reputation) */+ .fm-dialog--wide { max-width: 640px; }++ /* Code block <pre> tag inside fm-code — make snippets scroll horizontally+ instead of bursting out of the dialog, preserve whitespace, no margin. */+ .fm-code pre {+ margin: 0;+ padding: 0;+ background: transparent;+ color: inherit;+ font: inherit;+ white-space: pre;+ overflow-x: auto;+ }++ /* Language tabs above .fm-code */+ .fm-tabs {+ display: flex;+ gap: 4px;+ background: rgba(255, 255, 255, 0.03);+ border: 1px solid var(--border);+ border-radius: 9px;+ padding: 3px;+ }+ .fm-tab {+ appearance: none;+ flex: 1;+ background: transparent;+ color: var(--muted);+ border: none;+ border-radius: 6px;+ padding: 6px 10px;+ font: inherit;+ font-size: 12px;+ font-weight: 500;+ cursor: pointer;+ transition: background 0.15s, color 0.15s;+ }+ .fm-tab:hover { color: var(--text); }+ .fm-tab.is-active {+ background: rgba(214, 255, 61, 0.14);+ color: var(--accent);+ }++ /* ── Identity card ─────────────────────────────────────────────── */+ .fm-id-card {+ background:+ linear-gradient(135deg, rgba(214, 255, 61, 0.05) 0%, rgba(106, 92, 255, 0.06) 100%),+ rgba(255, 255, 255, 0.025);+ border: 1px solid var(--border);+ border-radius: 12px;+ padding: 14px 16px;+ display: flex;+ flex-direction: column;+ gap: 12px;+ }+ .fm-id-head {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 12px;+ }+ .fm-id-chain {+ font-size: 11px;+ color: var(--muted);+ text-transform: uppercase;+ letter-spacing: 0.06em;+ display: inline-flex;+ align-items: center;+ gap: 5px;+ }+ .fm-id-chain::before {+ content: '';+ width: 5px;+ height: 5px;+ border-radius: 50%;+ background: #9945FF; /* Solana purple */+ box-shadow: 0 0 6px rgba(153, 69, 255, 0.6);+ }+ .fm-id-pill {+ font-size: 10px;+ color: var(--accent);+ background: rgba(214, 255, 61, 0.1);+ border: 1px solid rgba(214, 255, 61, 0.3);+ border-radius: 999px;+ padding: 2px 8px;+ text-transform: uppercase;+ letter-spacing: 0.05em;+ }+ .fm-id-card[data-state='loading'] .fm-id-pill {+ color: var(--muted);+ background: rgba(255, 255, 255, 0.04);+ border-color: var(--border);+ }+ .fm-id-card[data-state='error'] .fm-id-pill { color: #ffb3b3; border-color: rgba(255, 92, 92, 0.4); background: rgba(255, 92, 92, 0.08); }+ .fm-id-addr {+ font-family: ui-monospace, 'SF Mono', monospace;+ font-size: 12px;+ color: var(--text);+ word-break: break-all;+ background: #07080d;+ border: 1px solid var(--border);+ border-radius: 8px;+ padding: 10px 12px;+ min-height: 36px;+ }+ .fm-id-card[data-state='loading'] .fm-id-addr {+ color: var(--muted);+ background: repeating-linear-gradient(110deg, rgba(255,255,255,0.02) 0 12px, transparent 12px 24px);+ background-size: 200% 100%;+ animation: shimmer 1.5s linear infinite;+ }+ @keyframes shimmer { from { background-position: 0 0; } to { background-position: -200% 0; } }+ .fm-id-meta {+ display: grid;+ grid-template-columns: 1fr 1fr;+ gap: 12px;+ font-size: 12px;+ }+ .fm-id-meta > div { display: flex; flex-direction: column; gap: 2px; }+ .fm-id-meta .muted { font-size: 10.5px; text-transform: uppercase; letter-spacing: 0.05em; }+ .fm-id-meta strong { font-size: 13px; font-weight: 600; }+ .fm-id-copy {+ align-self: flex-start;+ margin: 0;+ position: static;+ }+ .fm-id-copy:disabled { opacity: 0.4; cursor: not-allowed; }++ /* ── x402 handshake strip ──────────────────────────────────────── */+ .fm-handshake {+ display: grid;+ grid-template-columns: 1fr auto 1fr auto 1fr;+ gap: 6px;+ align-items: stretch;+ background: rgba(255, 255, 255, 0.025);+ border: 1px solid var(--border);+ border-radius: 12px;+ padding: 12px;+ }+ .fm-handshake-step {+ display: flex;+ align-items: flex-start;+ gap: 8px;+ font-size: 12px;+ min-width: 0;+ }+ .fm-handshake-step > div { min-width: 0; }+ .fm-handshake-step strong { font-size: 12.5px; font-weight: 600; display: block; }+ .fm-handshake-step .muted { font-size: 11px; line-height: 1.35; display: block; margin-top: 2px; }+ .fm-handshake-num {+ width: 18px;+ height: 18px;+ border-radius: 50%;+ background: rgba(214, 255, 61, 0.15);+ color: var(--accent);+ font-size: 11px;+ font-weight: 600;+ display: inline-flex;+ align-items: center;+ justify-content: center;+ flex-shrink: 0;+ }+ .fm-handshake-code {+ font-family: ui-monospace, monospace;+ font-size: 10px;+ color: var(--muted);+ background: #07080d;+ border: 1px solid var(--border);+ border-radius: 5px;+ padding: 1px 5px;+ align-self: flex-start;+ margin-left: auto;+ flex-shrink: 0;+ }+ .fm-handshake-arrow {+ color: var(--muted);+ font-size: 14px;+ align-self: center;+ opacity: 0.5;+ }++ /* ── Browser-chrome iframe preview ─────────────────────────────── */+ .fm-browser {+ border: 1px solid var(--border);+ border-radius: 11px;+ overflow: hidden;+ background: #07080d;+ }+ .fm-browser-bar {+ display: flex;+ align-items: center;+ gap: 6px;+ padding: 8px 10px;+ background: linear-gradient(180deg, #131420 0%, #0c0d15 100%);+ border-bottom: 1px solid var(--border);+ }+ .fm-browser-dot {+ width: 9px;+ height: 9px;+ border-radius: 50%;+ background: #2c2d3d;+ }+ .fm-browser-dot:nth-child(1) { background: #ff5f57; }+ .fm-browser-dot:nth-child(2) { background: #febc2e; }+ .fm-browser-dot:nth-child(3) { background: #28c840; }+ .fm-browser-url {+ flex: 1;+ margin-left: 8px;+ background: rgba(255, 255, 255, 0.04);+ border-radius: 999px;+ padding: 3px 10px;+ font-family: ui-monospace, monospace;+ font-size: 11px;+ color: var(--muted);+ text-align: center;+ }+ .fm-browser-stage {+ position: relative;+ aspect-ratio: 16 / 9;+ display: flex;+ align-items: center;+ justify-content: center;+ background: radial-gradient(60% 80% at 50% 20%, rgba(106, 92, 255, 0.08), transparent 70%);+ }+ .fm-browser-shot {+ width: 100%;+ height: 100%;+ object-fit: contain;+ background: #06070b;+ }+ .fm-browser-skeleton {+ color: var(--muted);+ font-size: 12.5px;+ }++ /* ── Reputation card ───────────────────────────────────────────── */+ .rep-card {+ background: rgba(255, 255, 255, 0.025);+ border: 1px solid var(--border);+ border-radius: 12px;+ padding: 14px 16px;+ display: flex;+ flex-direction: column;+ gap: 12px;+ }+ .rep-card-head {+ display: flex;+ align-items: flex-start;+ justify-content: space-between;+ gap: 10px;+ }+ .rep-card-head strong { font-size: 14px; }+ .rep-card-head .muted { font-size: 11.5px; }+ .rep-sample-pill {+ font-size: 10px;+ background: rgba(106, 92, 255, 0.15);+ color: #b9c0ff;+ border: 1px solid rgba(106, 92, 255, 0.35);+ border-radius: 999px;+ padding: 2px 8px;+ letter-spacing: 0.06em;+ }+ .rep-stats {+ display: grid;+ grid-template-columns: 1.4fr 1fr 1fr;+ gap: 10px;+ padding: 10px 12px;+ background: #07080d;+ border: 1px solid var(--border);+ border-radius: 9px;+ font-size: 12px;+ }+ .rep-stats > div { display: flex; flex-direction: column; gap: 2px; min-width: 0; }+ .rep-stats strong { font-weight: 600; font-size: 14px; }+ .rep-stat-big { font-size: 18px !important; }+ .rep-stats .muted { font-size: 10.5px; }+ .rep-stars { color: #ffd24a; letter-spacing: 1px; font-size: 12px; }+ .rep-reviews {+ display: flex;+ flex-direction: column;+ gap: 6px;+ max-height: 220px;+ overflow-y: auto;+ }+ .rep-review-item {+ background: #07080d;+ border: 1px solid var(--border);+ border-radius: 9px;+ padding: 9px 11px;+ display: flex;+ flex-direction: column;+ gap: 4px;+ }+ .rep-review-header {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 8px;+ font-size: 11.5px;+ }+ .rep-review-author { font-family: ui-monospace, monospace; color: var(--muted); }+ .rep-comment {+ margin: 0;+ font-size: 12.5px;+ color: var(--text);+ line-height: 1.45;+ }+ .rep-review-footer {+ display: flex;+ justify-content: space-between;+ font-size: 10.5px;+ }+ .rep-link { color: var(--muted); cursor: default; }.fm-download-list {list-style: none;@@ -726,6 +1050,23 @@border-radius: 999px;transition: width 0.18s ease-out;}+ #save-loading .abort-btn {+ margin-top: 6px;+ background: transparent;+ color: rgba(255, 255, 255, 0.55);+ border: 1px solid rgba(255, 255, 255, 0.14);+ border-radius: 999px;+ padding: 6px 14px;+ font: inherit;+ font-size: 12px;+ cursor: pointer;+ transition: border-color 0.15s, color 0.15s;+ }+ #save-loading .abort-btn[hidden] { display: none; }+ #save-loading .abort-btn:hover {+ color: #fff;+ border-color: rgba(255, 255, 255, 0.28);+ }#save-loading .error-actions {display: flex;gap: 10px;diff --git a/pages/overlay-control.html b/pages/overlay-control.htmlnew file mode 100644index 000000000..5eabba6a2--- /dev/null+++ b/pages/overlay-control.html@@ -0,0 +1,342 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="utf-8" />+ <title>Overlay Control · three.ws</title>+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <meta name="description" content="Stream Deck for your three.ws OBS overlay — emote hotkeys, expression mixer, mic threshold." />+ <meta name="theme-color" content="#0b0d10" />+ <link rel="shortcut icon" href="/favicon.ico" />+ <link rel="stylesheet" href="/fonts/fonts.css" />+ <style>+ :root {+ color-scheme: dark;+ --bg: #07090c;+ --panel: #11141a;+ --panel-edge: rgba(255, 255, 255, 0.07);+ --ink: #e8ecf2;+ --ink-dim: rgba(255, 255, 255, 0.6);+ --accent: #5fa8ff;+ --ok: #5fce6a;+ --warn: #ffb454;+ }+ * { box-sizing: border-box; }+ body {+ margin: 0;+ min-height: 100vh;+ background: radial-gradient(1200px 600px at 30% -10%, #1a1f29, var(--bg));+ color: var(--ink);+ font-family: system-ui, -apple-system, 'Segoe UI', sans-serif;+ display: grid;+ grid-template-columns: minmax(0, 1.4fr) minmax(320px, 0.9fr);+ gap: 22px;+ padding: 22px;+ }+ @media (max-width: 980px) {+ body { grid-template-columns: 1fr; padding: 14px; gap: 14px; }+ }+ h1 {+ margin: 0 0 4px;+ font-size: 22px;+ letter-spacing: -0.01em;+ }+ .sub {+ color: var(--ink-dim);+ font-size: 13px;+ margin-bottom: 18px;+ }+ .card {+ background: var(--panel);+ border: 1px solid var(--panel-edge);+ border-radius: 14px;+ padding: 16px;+ margin-bottom: 14px;+ }+ .card h2 {+ margin: 0 0 12px;+ font-size: 13px;+ text-transform: uppercase;+ letter-spacing: 0.1em;+ color: var(--ink-dim);+ font-weight: 600;+ }+ label.row {+ display: flex;+ align-items: center;+ gap: 10px;+ font-size: 13px;+ color: var(--ink);+ margin-bottom: 10px;+ }+ label.row input[type="text"],+ label.row input[type="url"] {+ flex: 1;+ min-width: 0;+ background: #06080b;+ color: var(--ink);+ border: 1px solid var(--panel-edge);+ border-radius: 8px;+ padding: 9px 11px;+ font-size: 13px;+ font-family: inherit;+ }+ label.row input[type="text"]:focus,+ label.row input[type="url"]:focus {+ border-color: var(--accent);+ outline: 0;+ }+ button.action {+ appearance: none;+ background: #fff;+ color: #0a0c10;+ border: 0;+ border-radius: 8px;+ padding: 10px 14px;+ font-size: 13px;+ font-weight: 600;+ letter-spacing: 0.02em;+ cursor: pointer;+ font-family: inherit;+ }+ button.action.ghost {+ background: transparent;+ color: var(--ink);+ border: 1px solid var(--panel-edge);+ }+ button.action[disabled] {+ opacity: 0.4;+ cursor: not-allowed;+ }+ .actions {+ display: flex;+ gap: 8px;+ flex-wrap: wrap;+ }++ .status {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ padding: 4px 10px;+ border-radius: 999px;+ background: rgba(255, 255, 255, 0.04);+ border: 1px solid var(--panel-edge);+ font-size: 11px;+ color: var(--ink-dim);+ }+ .status .dot {+ width: 6px;+ height: 6px;+ border-radius: 50%;+ background: #888;+ }+ .status.online .dot {+ background: var(--ok);+ box-shadow: 0 0 6px var(--ok);+ }++ .hotkey-grid {+ display: grid;+ grid-template-columns: repeat(5, 1fr);+ gap: 8px;+ }+ .hotkey {+ background: rgba(255, 255, 255, 0.03);+ border: 1px solid var(--panel-edge);+ border-radius: 12px;+ padding: 14px 10px;+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: 6px;+ cursor: pointer;+ user-select: none;+ transition: transform 0.08s ease, border-color 0.08s ease, background 0.08s ease;+ }+ .hotkey:hover {+ background: rgba(255, 255, 255, 0.07);+ border-color: rgba(255, 255, 255, 0.18);+ }+ .hotkey:active,+ .hotkey.fired {+ transform: scale(0.97);+ background: var(--accent);+ color: #06080b;+ border-color: var(--accent);+ }+ .hotkey .k {+ font-size: 22px;+ font-weight: 700;+ letter-spacing: 0;+ font-family: ui-monospace, SFMono-Regular, monospace;+ }+ .hotkey .l {+ font-size: 11px;+ letter-spacing: 0.04em;+ color: var(--ink-dim);+ }+ .hotkey:active .l,+ .hotkey.fired .l {+ color: rgba(6, 8, 11, 0.7);+ }++ .preview-wrap {+ background: var(--panel);+ border: 1px solid var(--panel-edge);+ border-radius: 14px;+ overflow: hidden;+ display: flex;+ flex-direction: column;+ min-height: 360px;+ }+ .preview-wrap iframe {+ flex: 1;+ width: 100%;+ border: 0;+ background: transparent;+ min-height: 360px;+ }+ .snippet {+ margin: 0;+ background: #06080b;+ border: 1px solid var(--panel-edge);+ border-radius: 8px;+ padding: 10px 12px;+ font-family: ui-monospace, SFMono-Regular, monospace;+ font-size: 11px;+ color: #cad6e8;+ white-space: pre-wrap;+ word-break: break-all;+ margin-bottom: 8px;+ }++ .slider-row {+ display: grid;+ grid-template-columns: 80px 1fr 56px;+ align-items: center;+ gap: 10px;+ margin-bottom: 8px;+ font-size: 12px;+ color: var(--ink-dim);+ }+ .slider-row input[type=range] {+ width: 100%;+ }+ .slider-row .val {+ text-align: right;+ font-family: ui-monospace, monospace;+ color: var(--ink);+ }++ .event-log {+ font-family: ui-monospace, SFMono-Regular, monospace;+ font-size: 11px;+ background: #06080b;+ border: 1px solid var(--panel-edge);+ border-radius: 8px;+ padding: 10px 12px;+ max-height: 140px;+ overflow: auto;+ color: var(--ink-dim);+ white-space: pre-wrap;+ }+ .event-log .e {+ display: block;+ padding: 2px 0;+ }+ .event-log .e.warn { color: var(--warn); }++ .top { display: flex; align-items: center; gap: 12px; justify-content: space-between; margin-bottom: 12px; }+ .brand a { color: var(--ink); text-decoration: none; font-weight: 600; }+ </style>+ </head>+ <body>+ <section class="left">+ <div class="top">+ <div>+ <h1>OBS overlay control</h1>+ <div class="sub">Hotkeys, expression mixer, and mic threshold for your three.ws avatar. Add the overlay URL to OBS Browser Source and keep this tab open.</div>+ </div>+ <div class="brand"><a href="/">← three.ws</a></div>+ </div>++ <div class="card">+ <h2>Avatar</h2>+ <label class="row">+ <span style="min-width:90px;color:var(--ink-dim)">Handle</span>+ <input id="avatar-handle" type="text" placeholder="@yourname" autocomplete="off" />+ <button class="action" id="apply-handle">Apply</button>+ </label>+ <div class="actions">+ <button class="action ghost" id="open-overlay">Open overlay window</button>+ <button class="action ghost" id="copy-overlay">Copy overlay URL</button>+ <span class="status" id="status"><span class="dot"></span><span class="label">offline</span></span>+ </div>+ <pre class="snippet" id="overlay-url" style="margin-top:10px"></pre>+ </div>++ <div class="card">+ <h2>Hotkeys · keys 1–9, 0</h2>+ <div class="hotkey-grid" id="hotkey-grid"></div>+ </div>++ <div class="card">+ <h2>Mic-driven talking state</h2>+ <label class="row" style="gap:14px">+ <button class="action" id="mic-toggle">Enable mic</button>+ <span class="status" id="mic-state"><span class="dot"></span><span class="label">off</span></span>+ </label>+ <div class="slider-row">+ <span>Noise floor</span>+ <input id="mic-floor" type="range" min="0" max="0.5" step="0.005" value="0.04" />+ <span class="val" id="mic-floor-v">0.040</span>+ </div>+ <div class="slider-row">+ <span>Mouth full</span>+ <input id="mic-ceiling" type="range" min="0.05" max="1" step="0.01" value="0.18" />+ <span class="val" id="mic-ceiling-v">0.180</span>+ </div>+ </div>++ <div class="card">+ <h2>Speak</h2>+ <label class="row">+ <input id="speak-text" type="text" placeholder="Type something for your avatar to say…" />+ <button class="action" id="speak-go">Speak</button>+ </label>+ <div class="actions">+ <button class="action ghost" data-control="stop">Stop / reset</button>+ <button class="action ghost" data-control="overlay-on">Overlay mode</button>+ <button class="action ghost" data-control="overlay-off">Show chrome</button>+ </div>+ </div>++ <div class="card">+ <h2>Event log</h2>+ <div class="event-log" id="event-log"></div>+ </div>+ </section>++ <section class="right">+ <div class="card" style="margin-bottom: 10px;">+ <h2>Preview</h2>+ <div class="sub" style="margin-bottom:10px">This is the same overlay your stream sees — emotes here fire there too via BroadcastChannel.</div>+ <div class="preview-wrap">+ <iframe id="preview" allow="autoplay; camera; microphone; clipboard-write; xr-spatial-tracking" title="Avatar preview"></iframe>+ </div>+ </div>++ <div class="card">+ <h2>How to wire OBS</h2>+ <ol style="margin:0;padding-left:18px;color:var(--ink-dim);font-size:13px;line-height:1.6;">+ <li>Click <em>Open overlay window</em> above — copy the URL from the new tab.</li>+ <li>In OBS, add a <strong>Browser Source</strong>. Paste the URL.</li>+ <li>Set width 600 px, height 800 px (or to taste). Check <strong>Refresh browser when scene becomes active</strong>.</li>+ <li>Keep this tab open while you stream — every hotkey or speak action you fire here is broadcast to the OBS overlay via BroadcastChannel.</li>+ </ol>+ </div>+ </section>++ <script type="module" src="/src/overlay-control.js"></script>+ </body>+</html>diff --git a/pages/widget.html b/pages/widget.htmlindex d03d27b0f..1c9bae30b 100644--- a/pages/widget.html+++ b/pages/widget.html@@ -62,7 +62,46 @@body.widget-ready .widget-poster {opacity: 0;}- /* Spinner — same look as the rest of the app, centred. */+ /* Reveal-on-interaction: tap-to-load overlay shown when the widget+ was embedded with reveal=interaction. Stays visible — and+ interactive — until the user clicks. WebGL doesn't init at all+ before that click, so a page with 12 widgets only pays the cost+ of the ones the user opens. */+ .widget-reveal-gate {+ position: fixed;+ inset: 0;+ display: flex;+ align-items: center;+ justify-content: center;+ background: rgba(0, 0, 0, 0.55);+ z-index: 3;+ cursor: pointer;+ transition: opacity 0.25s ease;+ }+ .widget-reveal-btn {+ width: 78px;+ height: 78px;+ border-radius: 50%;+ background: rgba(255, 255, 255, 0.9);+ color: #111;+ display: flex;+ align-items: center;+ justify-content: center;+ box-shadow: 0 18px 50px rgba(0, 0, 0, 0.45);+ pointer-events: none;+ }+ .widget-reveal-btn svg {+ width: 32px;+ height: 32px;+ transform: translateX(2px);+ }+ .widget-reveal-gate[data-dismissing] {+ opacity: 0;+ pointer-events: none;+ }+ /* Spinner — same look as the rest of the app, centred. Hidden+ until the reveal gate is dismissed (in interaction mode) so+ visitors see "tap to play," not "loading." */.spinner {position: fixed;left: 50%;@@ -76,6 +115,10 @@animation: widget-spin 0.9s linear infinite;z-index: 2;pointer-events: none;+ display: none;+ }+ body.widget-loading .spinner {+ display: block;}body.widget-ready .spinner {display: none;@@ -103,40 +146,109 @@// setup short-circuit when this flag is set.window.__WIDGET_SHELL = true;- // Optional ?poster=<url> renders a static image while WebGL boots.- // Encoded in the URL so it works without any postMessage handshake.(function () {- try {- var u = new URL(location.href);- var poster = u.searchParams.get('poster');- if (poster) {- document.addEventListener('DOMContentLoaded', function () {- var el = document.createElement('div');- el.className = 'widget-poster';- el.style.backgroundImage = 'url(' + JSON.stringify(poster).slice(1, -1) + ')';- document.body.appendChild(el);- });+ var qs = new URLSearchParams(location.search);+ var hash = location.hash || '';+ var hashParams = new URLSearchParams(hash.replace(/^#/, ''));+ function param(name) {+ return hashParams.get(name) || qs.get(name);+ }++ // Poster: ?poster=... or #poster=... — encoded URL of a static+ // preview shown until first frame (or used as the reveal-gate bg).+ var poster = param('poster');+ if (poster) {+ document.addEventListener('DOMContentLoaded', function () {+ var el = document.createElement('div');+ el.className = 'widget-poster';+ el.style.backgroundImage = 'url(' + JSON.stringify(poster).slice(1, -1) + ')';+ document.body.appendChild(el);+ });+ }++ // Reveal mode: 'auto' (default — boots on load) or 'interaction'+ // (deferred — boots only after the visitor clicks the play button).+ // On a gallery page with N embeds, interaction mode means WebGL+ // only spins up for the one(s) the visitor actually opens.+ var reveal = param('reveal') === 'interaction' ? 'interaction' : 'auto';++ function bootApp() {+ if (window.__WIDGET_BOOTED) return;+ window.__WIDGET_BOOTED = true;+ document.body.classList.add('widget-loading');+ var script = document.createElement('script');+ script.type = 'module';+ // Cache-buster only on first-time interaction boot so the+ // browser re-parses the module if a poster page was warm+ // from an earlier visit. Auto mode hits the module fresh.+ script.src = '/src/app.js';+ document.head.appendChild(script);+ // Notify the parent that the visitor revealed this widget —+ // lets a host page track engagement without our analytics.+ try {+ window.parent.postMessage(+ { jsonrpc: '2.0', method: 'widget.revealed', params: { mode: reveal } },+ '*',+ );+ } catch (_) {+ /* not in an iframe — ignore */}- } catch (_) {- /* malformed URL — skip poster */}- })();- // Reveal the body on the viewer's first successful frame. App.js fires- // a 'three-ws:first-frame' event after LOAD_END(success). 6s fallback- // guards against a hung load so visitors don't stare at a black box.- (function () {+ function setupRevealGate() {+ var gate = document.createElement('button');+ gate.type = 'button';+ gate.className = 'widget-reveal-gate';+ gate.setAttribute('aria-label', 'Play widget');+ gate.innerHTML =+ '<span class="widget-reveal-btn" aria-hidden="true">' ++ '<svg viewBox="0 0 24 24" fill="currentColor"><path d="M8 5v14l11-7z"/></svg>' ++ '</span>';+ gate.addEventListener('click', function () {+ gate.setAttribute('data-dismissing', '');+ bootApp();+ setTimeout(function () {+ if (gate.parentNode) gate.parentNode.removeChild(gate);+ }, 280);+ });+ document.body.appendChild(gate);+ // In interaction mode the body has nothing to hide — make it+ // visible so the play button is interactable.+ document.body.classList.add('widget-ready');+ }++ if (reveal === 'interaction') {+ document.addEventListener('DOMContentLoaded', setupRevealGate);+ } else {+ // Auto mode: boot now, no gate.+ document.addEventListener('DOMContentLoaded', bootApp);+ }++ // Reveal the body on the viewer's first successful frame. App.js+ // fires a 'three-ws:first-frame' event after LOAD_END(success).+ // 6s fallback guards against a hung load so visitors don't stare+ // at a black box. In interaction mode the body was already shown+ // for the gate; this re-firing is harmless (class already set).var revealed = false;- var reveal = function () {+ var revealBody = function () {if (revealed) return;revealed = true;+ document.body.classList.remove('widget-loading');document.body.classList.add('widget-ready');};- window.addEventListener('three-ws:first-frame', reveal, { once: true });- setTimeout(reveal, 6000);+ window.addEventListener('three-ws:first-frame', revealBody, { once: true });+ // Only arm the 6s fallback after the boot actually starts, so the+ // idle interaction-mode poster doesn't reveal itself.+ var armFallback = function () {+ setTimeout(revealBody, 6000);+ };+ if (reveal === 'interaction') {+ window.addEventListener('three-ws:boot-started', armFallback, { once: true });+ } else {+ armFallback();+ }})();</script>- <script defer type="module" src="/src/app.js"></script></head><body data-viewer-mode="embed"><main class="wrap">diff --git a/public/app-next.css b/public/app-next.cssindex 14c7a3529..f326402bb 100644--- a/public/app-next.css+++ b/public/app-next.css@@ -412,86 +412,6 @@ body.app-next-body {);}-/* ── Rotating "Try …" pill ─────────────────────────────────────────────── */--.nxt-try-pill {- position: fixed;- left: 50%;- bottom: 96px;- transform: translateX(-50%);- display: inline-flex;- align-items: center;- gap: 6px;- padding: 5px 6px 5px 12px;- background: var(--nxt-glass-strong);- border: 1px solid var(--nxt-stroke);- border-radius: var(--nxt-radius-pill);- backdrop-filter: blur(14px);- -webkit-backdrop-filter: blur(14px);- box-shadow: 0 16px 36px rgba(0, 0, 0, 0.5), 0 0 0 1px rgba(154, 124, 255, 0.05);- z-index: 20;- animation: nxt-rise 0.5s 0.4s both;-}--.nxt-try-pill[hidden] { display: none; }--@keyframes nxt-rise {- from { opacity: 0; transform: translate(-50%, 8px); }- to { opacity: 1; transform: translate(-50%, 0); }-}--.nxt-try-pill__label {- font-size: 11.5px;- font-weight: 600;- color: var(--nxt-ink-fade);- letter-spacing: 0.08em;- text-transform: uppercase;-}--.nxt-try-pill__btn {- display: inline-flex;- align-items: center;- gap: 6px;- background: var(--nxt-accent-soft);- border: 0;- color: var(--nxt-ink);- font: inherit;- font-size: 13.5px;- font-weight: 500;- padding: 6px 12px;- border-radius: var(--nxt-radius-pill);- cursor: pointer;- transition: background 0.15s;-}--.nxt-try-pill__btn:hover {- background: rgba(154, 124, 255, 0.32);-}--.nxt-try-pill__icon {- font-size: 15px;- line-height: 1;-}--.nxt-try-pill__next {- display: inline-flex;- align-items: center;- justify-content: center;- width: 26px;- height: 26px;- border-radius: 50%;- background: transparent;- border: 0;- color: var(--nxt-ink-fade);- cursor: pointer;- transition: background 0.15s, color 0.15s;-}--.nxt-try-pill__next:hover {- color: var(--nxt-ink);- background: rgba(255, 255, 255, 0.06);-}-/* ── Action bar ────────────────────────────────────────────────────────── */.nxt-action-bar {diff --git a/public/embed.js b/public/embed.jsindex 7e0ff6259..bcfeaf5ac 100644--- a/public/embed.js+++ b/public/embed.js@@ -60,37 +60,73 @@var height = attr(scriptEl, 'data-height', String(defaults[1]));var radius = attr(scriptEl, 'data-radius', '12');var border = attr(scriptEl, 'data-border', '0');+ // data-reveal="interaction" gates WebGL boot behind a click. Use for+ // gallery / grid pages where many widgets coexist — the browser only+ // pays for the ones the visitor actually opens. Default "auto" boots+ // the engine as soon as the iframe loads.+ var reveal = attr(scriptEl, 'data-reveal', 'auto');+ // data-poster="auto" uses /api/widgets/<id>/og as the preview image+ // (the same 1200×630 we ship to OpenGraph cards). Specify a URL to+ // override, or "off" to suppress. Posters mean visitors see the+ // avatar instantly instead of a black void during WebGL warm-up.+ var posterAttr = attr(scriptEl, 'data-poster', 'auto');+ var poster = null;+ if (posterAttr === 'auto') {+ poster = ORIGIN + '/api/widgets/' + encodeURIComponent(widgetId) + '/og';+ } else if (posterAttr && posterAttr !== 'off') {+ poster = posterAttr;+ }+ // data-priority="high" hints the browser to fetch this iframe ahead+ // of below-the-fold content — meaningful when a widget is the LCP+ // element on the embedder's page (hero banners).+ var priority = attr(scriptEl, 'data-priority', null);// /widget = slim viewer shell. Same engine as /app but without the// marketing nav/footer/auth chrome in the DOM, so the embed iframe// doesn't flash the parent site before the model renders.- var src = ORIGIN + '/widget#widget=' + encodeURIComponent(widgetId) + '&kiosk=true';+ var hashParts = ['widget=' + encodeURIComponent(widgetId), 'kiosk=true'];+ if (reveal === 'interaction') hashParts.push('reveal=interaction');+ if (poster) hashParts.push('poster=' + encodeURIComponent(poster));+ var src = ORIGIN + '/widget#' + hashParts.join('&');var iframe = document.createElement('iframe');- iframe.src = src;iframe.title = 'three.ws widget ' + widgetId;iframe.allow = 'autoplay; clipboard-write; xr-spatial-tracking';iframe.setAttribute('sandbox', 'allow-scripts allow-same-origin allow-popups');iframe.setAttribute('width', width);iframe.setAttribute('height', height);+ // Default: lazy. Embedders flagged as high-priority opt into eager.+ iframe.setAttribute('loading', priority === 'high' ? 'eager' : 'lazy');+ if (priority === 'high' && 'fetchPriority' in iframe) {+ iframe.fetchPriority = 'high';+ }iframe.style.border = border + 'px solid transparent';iframe.style.borderRadius = radius + 'px';iframe.style.maxWidth = '100%';iframe.style.display = 'block';- // Wrap in a positioned container that holds the skeleton placeholder.+ // Wrap in a positioned container that holds the placeholder. If a+ // poster is set, the wrapper shows the OG image as its background so+ // visitors see the avatar instantly. Otherwise we fall back to the+ // spinner skeleton.var wrapper = document.createElement('div');+ var bgCss = poster+ ? 'background:#0c0c12 url(' + JSON.stringify(poster).slice(1, -1) ++ ') center/contain no-repeat;'+ : 'background:#0c0c12;';wrapper.style.cssText ='position:relative;display:inline-block;max-width:100%;' +'width:' + width + 'px;height:' + height + 'px;' +'border-radius:' + radius + 'px;overflow:hidden;' +- 'background:#0c0c12;';+ bgCss;var skeleton = document.createElement('div');skeleton.setAttribute('aria-hidden', 'true');+ // Spinner is suppressed when we already have a poster — no double-loader.skeleton.style.cssText ='position:absolute;inset:0;display:flex;align-items:center;justify-content:center;' +- 'pointer-events:none;transition:opacity 0.3s;';+ 'pointer-events:none;transition:opacity 0.3s;' ++ (poster ? 'opacity:0;' : '');skeleton.innerHTML ='<div style="width:32px;height:32px;border:2px solid rgba(255,255,255,0.08);' +'border-top-color:rgba(255,255,255,0.35);border-radius:50%;' +diff --git a/src/app.js b/src/app.jsindex bfc01be24..75601f2d7 100644--- a/src/app.js+++ b/src/app.js@@ -2321,6 +2321,16 @@ class App {// embed iframe before kiosk JS hides it.if (!window.__WIDGET_SHELL) {document.body.innerHTML += Footer();+} else {+ // Tell the shell that the bundle has started executing. The shell uses+ // this to arm its 6s "still no first frame" fallback — without it, an+ // interaction-mode widget would fire the fallback during idle and break+ // the play-to-load promise.+ try {+ window.dispatchEvent(new CustomEvent('three-ws:boot-started'));+ } catch {+ /* CustomEvent ctor missing only on retired browsers — ignore */+ }}document.addEventListener('DOMContentLoaded', () => {diff --git a/src/avatar-embed.js b/src/avatar-embed.jsindex 4e4aebb11..7330a266e 100644--- a/src/avatar-embed.js+++ b/src/avatar-embed.js@@ -566,7 +566,7 @@ async function main() {function postReady() {const conformance = conformanceReport(root);- postToParent({+ const readyMsg = {type: 'v1.avatar.ready',version: BRIDGE_VERSION,capabilities: CAPABILITIES,@@ -578,29 +578,49 @@ async function main() {total: conformance.implemented.length + conformance.missing.length,coverage: conformance.coverage,},+ hotkeys: Object.fromEntries(+ Object.entries(hotkeys).map(([k, v]) => [k, { label: v.label, hold: v.hold }])+ ),+ };+ postToParent(readyMsg);+ // RPM-compatible aliases — emit the same payload under Ready Player+ // Me's event names so integrators can swap to three.ws with one URL+ // change. See docs.readyplayer.me/.../avatar-creator/events.+ postToParent({ ...readyMsg, type: 'v1.frame.ready' });+ postToParent({+ eventName: 'v2.avatar.exported',+ source: 'threews',+ data: {+ url: resolved.modelUrl,+ avatarId: resolved.id,+ handle: resolved.handle,+ name: resolved.name,+ },});+ broadcast(readyMsg);}- function handleMessage(ev) {- if (ev.source !== window.parent) return;- const msg = ev.data;+ // Unified control handler — same logic for parent postMessage and the+ // BroadcastChannel sibling-tab pathway. The only difference is origin+ // locking: postMessage messages are origin-checked above; broadcasts are+ // already same-origin per the spec.+ function handleControl(msg, ctx = {}) {if (!msg || typeof msg !== 'object') return;- if (typeof msg.type !== 'string' || !msg.type.startsWith('v1.avatar.')) return;-- if (!parentOriginLocked) {- parentOrigin = ev.origin;- parentOriginLocked = true;- } else if (ev.origin !== parentOrigin) {- return;- }+ if (typeof msg.type !== 'string') return;+ // Accept v1.avatar.* messages plus the RPM-compatible v1.frame.hello+ // handshake from integrators expecting the RPM event vocabulary.+ const accepted = msg.type.startsWith('v1.avatar.') || msg.type === 'v1.frame.hello';+ if (!accepted) return;switch (msg.type) {case 'v1.avatar.hello':+ case 'v1.frame.hello':if (bridgeReady) postReady();else pendingHellos.push(true);return;case 'v1.avatar.ping':postToParent({ type: 'v1.avatar.pong', id: msg.id });+ if (ctx.source === 'broadcast') broadcast({ type: 'v1.avatar.pong', id: msg.id });return;case 'v1.avatar.speak': {const tasks = [];@@ -650,7 +670,67 @@ async function main() {activeLipsync = null;stopMocap();return;+ // ── OBS / streaming overlay surface ──────────────────────────+ case 'v1.avatar.hotkey':+ if (msg.key != null) triggerHotkey(msg.key, msg);+ return;+ case 'v1.avatar.hotkeys':+ // Replace or merge the hotkey map. Pass `{ replace: true }`+ // for a clean wipe; otherwise merges so the host can override+ // just one slot.+ if (msg.map && typeof msg.map === 'object') {+ if (msg.replace) {+ for (const k of Object.keys(hotkeys)) delete hotkeys[k];+ }+ for (const [k, entry] of Object.entries(msg.map)) {+ hotkeys[String(k)] = {+ label: String(entry?.label || ''),+ hold: Number.isFinite(entry?.hold) ? Number(entry.hold) : 1200,+ morphs: entry?.morphs && typeof entry.morphs === 'object' ? entry.morphs : {},+ };+ }+ renderEmotePanel();+ }+ return;+ case 'v1.avatar.state':+ // Force a state update from outside (e.g. chat command says+ // "switch to angry expression for the next clip").+ if (msg.state && typeof msg.state === 'object') setState(msg.state);+ return;+ case 'v1.avatar.mic':+ if (msg.enabled) {+ if (Number.isFinite(msg.floor)) state.micFloor = clamp01s(msg.floor);+ if (Number.isFinite(msg.ceiling)) state.micCeiling = clamp01s(msg.ceiling);+ enableMic().catch((e) =>+ postToParent({ type: 'v1.avatar.error', message: e?.message || 'mic failed' }),+ );+ } else {+ disableMic();+ }+ return;+ case 'v1.avatar.overlay':+ // Toggle chrome-free overlay mode at runtime.+ if (msg.enabled === true) document.body.classList.add('overlay-mode');+ else if (msg.enabled === false) document.body.classList.remove('overlay-mode');+ return;+ }+ }++ function handleMessage(ev) {+ if (ev.source !== window.parent) return;+ const msg = ev.data;+ if (!msg || typeof msg !== 'object') return;+ if (typeof msg.type !== 'string') return;+ // Accept both v1.avatar.* and the RPM-compatible v1.frame.hello.+ if (!msg.type.startsWith('v1.avatar.') && msg.type !== 'v1.frame.hello') return;++ if (!parentOriginLocked) {+ parentOrigin = ev.origin;+ parentOriginLocked = true;+ } else if (ev.origin !== parentOrigin) {+ return;}+ handleControl(msg, { source: 'window' });}window.addEventListener('message', handleMessage);@@ -841,3 +921,23 @@ function showError(msg) {el.textContent = msg;el.style.display = 'flex';}++// ── Misc utilities ──────────────────────────────────────────────────────────++function escapeHtmlSafe(s) {+ if (s == null) return '';+ return String(s)+ .replace(/&/g, '&')+ .replace(/</g, '<')+ .replace(/>/g, '>')+ .replace(/"/g, '"')+ .replace(/'/g, ''');+}++function clamp01s(n) {+ const x = Number(n);+ if (!Number.isFinite(x)) return 0;+ if (x < 0) return 0;+ if (x > 1) return 1;+ return x;+}diff --git a/src/avatar-face-capture.js b/src/avatar-face-capture.jsindex fa0eab719..d76428622 100644--- a/src/avatar-face-capture.js+++ b/src/avatar-face-capture.js@@ -42,32 +42,83 @@ const MODEL_URL =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>}+ * Run face landmarking on a single image and return the full result.+ * Internal — exposed for callers that want both blendshapes + landmarks.*/-export async function detectFaceBlendshapes(source, landmarker) {+async function detectFace(source, landmarker) {const lm = landmarker || (await loadLandmarker());- const result = lm.detect(source);+ return lm.detect(source);+}++/**+ * Detect 52 ARKit *expression* blendshapes (smile/jawOpen/etc.). These are+ * NOT identity — driving them all from a single photo bakes whatever+ * expression the user happened to be wearing into the avatar permanently.+ * Use detectFaceIdentity() for "personalize from selfie" UX. Use this only+ * for live face tracking or one-shot mirroring.+ */+export async function detectFaceBlendshapes(source, landmarker) {+ const result = await detectFace(source, landmarker);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.+ // MediaPipe always emits index-0 "_neutral" — skip it.if (!c.categoryName || c.categoryName === '_neutral') continue;out[c.categoryName] = c.score;}return out;}+/**+ * Identity capture — derive ARKit-named morph weights from 478 landmarks+ * via geometric ratios that approximate face shape. Returns a small map+ * (≤12 keys) of *identity-shaped* morphs only. Expression morphs (smile,+ * frown, jaw open, squint) are intentionally absent so a candid selfie+ * doesn't burn a wink into the avatar forever.+ *+ * The ratios are calibrated against MediaPipe's canonical face mesh — the+ * 478-point neutral template ships baked into the model. Each ratio gets+ * mapped through a tanh-style normalizer so a person whose ratio matches+ * canonical → 0, person with a wider jaw → positive jaw weight, etc.+ *+ * @returns {Promise<Record<string, number>|null>}+ */+export async function detectFaceIdentity(source, landmarker) {+ const result = await detectFace(source, landmarker);+ const lm = result?.faceLandmarks?.[0];+ if (!lm || lm.length < 478) return null;+ return identityMorphsFromLandmarks(lm);+}++/**+ * Run both passes in one detect() call. Returns { blendshapes, identity }.+ */+export async function detectFaceAll(source, landmarker) {+ const result = await detectFace(source, landmarker);+ const lm = result?.faceLandmarks?.[0];+ const bsArr = result?.faceBlendshapes?.[0]?.categories || [];+ if (!lm || lm.length < 478) return null;+ const blendshapes = {};+ for (const c of bsArr) {+ if (!c.categoryName || c.categoryName === '_neutral') continue;+ blendshapes[c.categoryName] = c.score;+ }+ return {+ blendshapes,+ identity: identityMorphsFromLandmarks(lm),+ // 4x4 head pose; useful for live track if the caller wants it later.+ transform: result?.facialTransformationMatrixes?.[0]?.data || null,+ };+}+/*** 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;+detectFaceIdentity.loadLandmarker = loadLandmarker;+detectFaceAll.loadLandmarker = loadLandmarker;function loadLandmarker() {if (_landmarkerPromise) return _landmarkerPromise;@@ -78,7 +129,10 @@ function loadLandmarker() {return FaceLandmarker.createFromOptions(vision, {baseOptions: { modelAssetPath: MODEL_URL, delegate: 'GPU' },outputFaceBlendshapes: true,- outputFacialTransformationMatrixes: false,+ // Surfaces the 4×4 head-pose matrix — wired through detectFaceAll()+ // so live-track callers can drive head bone rotation later without+ // running a second detect pass.+ outputFacialTransformationMatrixes: true,runningMode: 'IMAGE',numFaces: 1,});@@ -88,3 +142,183 @@ function loadLandmarker() {});return _landmarkerPromise;}++/* ────────────────────────────────────────────────────────────────────────── *+ * Landmark indices — picked off the MediaPipe FaceMesh diagram.+ *+ * https://developers.google.com/static/mediapipe/images/solutions/face_landmarker_keypoints.png+ *+ * Each index references a {x,y,z} point in normalized image space (0..1 for+ * x/y, z is depth in face-relative units). x increases left-to-right in the+ * image (mirrored from the user's perspective when source is a front-cam+ * selfie). We normalize against an inter-ocular reference distance so the+ * ratios are scale-invariant.+ * ────────────────────────────────────────────────────────────────────────── */++const LMK = {+ // Eyes — outer / inner corners+ leftEyeOuter: 33,+ leftEyeInner: 133,+ rightEyeOuter: 263,+ rightEyeInner: 362,+ leftEyeTop: 159,+ leftEyeBottom: 145,+ rightEyeTop: 386,+ rightEyeBottom: 374,+ // Brows+ leftBrowInner: 105,+ leftBrowOuter: 70,+ rightBrowInner: 334,+ rightBrowOuter: 300,+ // Nose+ noseTip: 1,+ noseBridge: 6,+ noseLeftAla: 49,+ noseRightAla: 279,+ // Mouth+ mouthLeft: 61,+ mouthRight: 291,+ upperLipTop: 13,+ upperLipBottom: 14,+ lowerLipTop: 17,+ lowerLipBottom: 18,+ // Face boundary+ forehead: 10,+ chin: 152,+ jawLeft: 234,+ jawRight: 454,+ cheekLeft: 50,+ cheekRight: 280,+};++function dist(a, b) {+ const dx = a.x - b.x;+ const dy = a.y - b.y;+ return Math.hypot(dx, dy);+}++// Smooth tanh-style map: input ∈ R → output ∈ [-1, 1]. Sensitivity sets+// how far the input has to deviate from the canonical baseline to saturate.+function ratioToWeight(ratio, canonical, sensitivity = 8) {+ const x = (ratio - canonical) * sensitivity;+ return Math.tanh(x);+}++/**+ * Compute identity morph weights from 478 MediaPipe landmarks. Output map+ * uses ARKit-named morphs where one fits the semantic; uses our own+ * `body*` / `shape*` morph names for face-shape proportions that have no+ * ARKit equivalent. Avatars that lack those custom morphs silently no-op+ * those entries (AccessoryManager._applyRawMorphs skips unknown names).+ *+ * Values are always ≥0 and ≤0.7 — even the most extreme ratio shouldn't+ * push a slider into saturation. The user fine-tunes from the Sculpt UI.+ */+export function identityMorphsFromLandmarks(lm) {+ // Inter-ocular distance — scale reference. Every other measurement is+ // expressed as a ratio of this to make the result selfie-distance- and+ // resolution-independent.+ const eyeOuterL = lm[LMK.leftEyeOuter];+ const eyeOuterR = lm[LMK.rightEyeOuter];+ const interocular = dist(eyeOuterL, eyeOuterR) || 1e-6;++ const norm = (a, b) => dist(lm[a], lm[b]) / interocular;++ // ── Compute the raw ratios ────────────────────────────────────────────+ const faceHeight = norm(LMK.forehead, LMK.chin); // ~2.2 canonical+ const jawWidth = norm(LMK.jawLeft, LMK.jawRight); // ~2.2 canonical+ const lipThickness = norm(LMK.upperLipTop, LMK.lowerLipBottom); // ~0.5 canonical+ const noseWidth = norm(LMK.noseLeftAla, LMK.noseRightAla); // ~0.55 canonical+ const noseLength = norm(LMK.noseBridge, LMK.noseTip); // ~0.65 canonical+ const browHeightL = norm(LMK.leftBrowInner, LMK.leftEyeInner) /+ (norm(LMK.leftEyeTop, LMK.leftEyeBottom) || 1e-6); // ratio of brow-eye to eye-height+ const eyeHeight = (+ norm(LMK.leftEyeTop, LMK.leftEyeBottom) ++ norm(LMK.rightEyeTop, LMK.rightEyeBottom)+ ) / 2; // ~0.18 canonical+ const cheekWidth = norm(LMK.cheekLeft, LMK.cheekRight); // ~1.9 canonical+ const mouthWidth = norm(LMK.mouthLeft, LMK.mouthRight); // ~0.95 canonical++ // ── Map ratios → morph weights ────────────────────────────────────────+ // We only emit non-negative weights (additive morphs); negative ratios+ // (e.g. "thinner than canonical") get clamped to 0 — the avatar's neutral+ // already represents the canonical, so undershoot reads as "no change."+ const clampPos = (v) => Math.max(0, Math.min(0.7, v));++ const out = {};++ // Wider jaw → drive a custom `bodyJawWide` / `shapeJawWide` morph if the+ // avatar has it. Avatars without it no-op.+ const jaw = clampPos(ratioToWeight(jawWidth, 2.2, 4));+ if (jaw > 0.02) {+ out.bodyJawWide = jaw;+ out.shapeJawWide = jaw;+ }++ // Thicker lips+ const lips = clampPos(ratioToWeight(lipThickness, 0.5, 8));+ if (lips > 0.02) {+ out.bodyLipsThick = lips;+ out.shapeLipsThick = lips;+ // Also nudge mouthShrugLower/Upper — the ARKit-named morphs that come+ // closest to "fuller lip" on a stock RPM/Avaturn rig.+ out.mouthShrugLower = lips * 0.4;+ out.mouthShrugUpper = lips * 0.4;+ }++ // Wider nose ala+ const nose = clampPos(ratioToWeight(noseWidth, 0.55, 8));+ if (nose > 0.02) {+ out.bodyNoseWide = nose;+ out.shapeNoseWide = nose;+ }++ // Longer nose+ const noseLong = clampPos(ratioToWeight(noseLength, 0.65, 8));+ if (noseLong > 0.02) {+ out.bodyNoseLong = noseLong;+ out.shapeNoseLong = noseLong;+ }++ // Larger eye opening (resting "wider" eyes — not blink)+ const eyes = clampPos(ratioToWeight(eyeHeight, 0.18, 12));+ if (eyes > 0.02) {+ // Spread a small amount onto eyeWideLeft/Right as an identity baseline.+ // Cap heavily — 0.2 max — so it reads as "alert eyes" not "wide open."+ const cap = Math.min(0.2, eyes);+ out.eyeWideLeft = cap;+ out.eyeWideRight = cap;+ out.bodyEyesLarge = eyes;+ }++ // Higher brows — drives the ARKit browInnerUp baseline. Cap aggressively+ // (0.2 max) so it doesn't read as "permanently surprised."+ const brow = clampPos(ratioToWeight(browHeightL, 1.5, 4));+ if (brow > 0.05) {+ out.browInnerUp = Math.min(0.2, brow);+ out.bodyBrowHigh = brow;+ }++ // Longer face (vs canonical 2.2)+ const longFace = clampPos(ratioToWeight(faceHeight, 2.2, 4));+ if (longFace > 0.02) {+ out.bodyFaceLong = longFace;+ out.shapeFaceLong = longFace;+ }++ // Wider cheeks → cheekPuff baseline (capped low, otherwise reads as cheeks-puffed-out).+ const cheeks = clampPos(ratioToWeight(cheekWidth, 1.9, 4));+ if (cheeks > 0.05) {+ out.cheekPuff = Math.min(0.15, cheeks);+ out.bodyCheekWide = cheeks;+ }++ // Wider mouth opening corners — no clean ARKit slot, custom morph only.+ const mouth = clampPos(ratioToWeight(mouthWidth, 0.95, 8));+ if (mouth > 0.02) {+ out.bodyMouthWide = mouth;+ out.shapeMouthWide = mouth;+ }++ return out;+}diff --git a/src/avatar-sculpt.js b/src/avatar-sculpt.jsindex 9848019d1..061b846e6 100644--- a/src/avatar-sculpt.js+++ b/src/avatar-sculpt.js@@ -14,7 +14,7 @@* mesh's `morphTargetInfluences` in real time. Save flow is unchanged.*/-import { detectFaceBlendshapes } from './avatar-face-capture.js';+import { detectFaceAll } from './avatar-face-capture.js';/* ────────────────────────────────────────────────────────────────────────── ** Category map — orders + groups the 52 ARKit names + common body morphs@@ -79,12 +79,9 @@ const CATEGORIES = [match: /^cheek/,preferred: ['cheekPuff', 'cheekSquintLeft', 'cheekSquintRight'],},- {- id: 'tongue',- label: 'Tongue',- match: /^tongue/,- preferred: ['tongueOut'],- },+ // tongueOut intentionally omitted — RPM/Avaturn bake the morph but nobody+ // wants a "Tongue Out" slider on their face customizer. Drivers that need+ // it (lipsync, mocap) still hit it via runtime APIs.{id: 'body',label: 'Body',@@ -116,17 +113,33 @@ const ARKIT52 = new Set([/*** Discover every morph target on the loaded scene root and return the union* of names (across all skinned meshes). Returns alphabetized for stable UI.+ * tongueOut filtered out — it's a real morph but a useless slider.*/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);+ for (const k of Object.keys(obj.morphTargetDictionary)) {+ if (k === 'tongueOut') continue;+ found.add(k);+ }}});return [...found].sort();}+/** Detect whether a morph name is a Left/Right variant. Returns the pair root or null. */+function pairRootOf(name) {+ const m = name.match(/^(.*)(Left|Right)$/);+ return m ? m[1] : null;+}+/** Detect Left/Right side of a paired morph. */+function sideOf(name) {+ if (name.endsWith('Left')) return 'L';+ if (name.endsWith('Right')) return 'R';+ return null;+}+/*** Apply { name: weight } to every mesh on the root. Out-of-range weights are* clamped; unknown names are silently skipped (mirrors AccessoryManager).@@ -241,6 +254,87 @@ export function renderSculptPanel({ container, root, working, onDirty }) {});}+/* ────────────────────────────────────────────────────────────────────────── *+ * Slider wiring — with mirror-lock support for L/R paired morphs.+ * ────────────────────────────────────────────────────────────────────────── */++function wireSliders(container, root, working, onDirty) {+ container.querySelectorAll('input[type="range"][data-morph]').forEach((input) => {+ const name = input.dataset.morph;+ const valEl = container.querySelector(`output[data-for="${cssEscape(name)}"]`);+ const pairName = input.dataset.pair || null; // companion morph when mirroring++ const onChange = () => {+ const w = Number(input.value);+ writeMorph(working, name, w);+ applyMorphsToRoot(root, { [name]: w });+ if (valEl) valEl.textContent = w.toFixed(2);+ // Mirror the value to the companion morph if active.+ if (pairName) {+ writeMorph(working, pairName, w);+ applyMorphsToRoot(root, { [pairName]: w });+ }+ onDirty?.();+ };+ input.addEventListener('input', onChange);+ input.addEventListener('dblclick', () => {+ input.value = '0';+ onChange();+ });+ });+}++function writeMorph(working, name, w) {+ if (w === 0) delete working.morphs[name];+ else working.morphs[name] = w;+}++function renderGroup(g, morphs) {+ if (_mirrorLocked) {+ // Collapse {fooLeft, fooRight} → single "Foo" slider that mutates both.+ const visible = [];+ const seenPair = new Set();+ for (const name of g.morphs) {+ const root = pairRootOf(name);+ if (root) {+ if (seenPair.has(root)) continue;+ seenPair.add(root);+ const left = `${root}Left`;+ const right = `${root}Right`;+ const hasLeft = g.morphs.includes(left);+ const hasRight = g.morphs.includes(right);+ if (hasLeft && hasRight) {+ visible.push({ name: left, pair: right, displayName: root });+ continue;+ }+ }+ visible.push({ name, pair: null, displayName: name });+ }+ return `+ <details class="ae-sculpt-group" ${g.collapsed ? '' : 'open'}>+ <summary>+ <span>${g.label}</span>+ <span class="ae-sculpt-count">${visible.length}</span>+ </summary>+ <div class="ae-sculpt-rows">+ ${visible.map((v) => sliderRow(v.name, morphs[v.name] || 0, v.displayName, v.pair)).join('')}+ </div>+ </details>+ `;+ }+ return `+ <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, morphs[m] || 0)).join('')}+ </div>+ </details>+ `;+}+/* ────────────────────────────────────────────────────────────────────────── ** Face capture modal — webcam → MediaPipe → ARKit-52 weights* ────────────────────────────────────────────────────────────────────────── */@@ -257,9 +351,11 @@ function openFaceCaptureModal({ root, working, onDirty, rerender }) {<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.+ Face the camera with a relaxed expression. We read the geometry+ of your face — width, jaw, nose, lips — and write those ratios+ as identity morphs. The expression you're wearing in the photo+ is ignored on purpose so a candid smile doesn't burn in+ forever. Runs entirely in your browser.</p><div class="ae-face-stage"><video id="ae-face-video" autoplay playsinline muted></video>@@ -302,7 +398,7 @@ function openFaceCaptureModal({ root, working, onDirty, rerender }) {return;}try {- landmarker = await detectFaceBlendshapes.loadLandmarker();+ landmarker = await detectFaceAll.loadLandmarker();if (cancelled) return;status.textContent = 'Ready. Hold still and capture.';shootBtn.disabled = false;@@ -330,23 +426,21 @@ function openFaceCaptureModal({ root, working, onDirty, rerender }) {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) {+ const full = await detectFaceAll(canvas, landmarker);+ if (!full || !full.identity || !Object.keys(full.identity).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.+ // Use identity morphs (from landmark ratios) as the primary signal.+ // The blendshape map is intentionally ignored for seeding — those+ // describe the user's expression in the photo, not their face shape.const available = new Set(discoverMorphs(root));let applied = 0;- for (const [name, weight] of Object.entries(blendshapes)) {+ for (const [name, weight] of Object.entries(full.identity)) {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));+ const clamped = Math.max(0, Math.min(0.7, weight));if (clamped < 0.02) {delete working.morphs[name];} else {@@ -406,9 +500,11 @@ function groupMorphs(all) {return groups;}-function sliderRow(name, value) {- const label = humanize(name);+function sliderRow(name, value, displayLabel, pairName) {+ const labelSource = displayLabel || name;+ const label = humanize(labelSource);const meta = ARKIT52.has(name) ? 'ARKit' : isVisemeName(name) ? 'Viseme' : '';+ const pairAttr = pairName ? ` data-pair="${escAttr(pairName)}"` : '';return `<div class="ae-sculpt-row"><div class="ae-sculpt-label">@@ -419,7 +515,7 @@ function sliderRow(name, value) {type="range"min="0" max="1" step="0.01"value="${value}"- data-morph="${escAttr(name)}"+ data-morph="${escAttr(name)}"${pairAttr}aria-label="${escAttr(label)}"/><output class="ae-sculpt-value" data-for="${escAttr(name)}">${(+value).toFixed(2)}</output>diff --git a/src/create-review.js b/src/create-review.jsindex 003635776..df6d95e56 100644--- a/src/create-review.js+++ b/src/create-review.js@@ -476,7 +476,7 @@ function releaseObjectUrl() {}}-function showSaveOverlay(label, sublabel) {+function showSaveOverlay(label, sublabel, opts = {}) {let el = document.getElementById('save-loading');if (!el) {el = document.createElement('div');@@ -491,6 +491,7 @@ function showSaveOverlay(label, sublabel) {<div class="progress" hidden><div class="progress-bar"></div></div>+ <button type="button" class="abort-btn" hidden>Cancel upload</button><div class="error-actions" hidden><button type="button" class="retry-btn">Retry</button><button type="button" class="cancel-btn">Cancel</button>@@ -504,6 +505,28 @@ function showSaveOverlay(label, sublabel) {el.querySelector('.label').textContent = label;el.querySelector('.sublabel').textContent = sublabel || '';el.querySelector('.error-actions').hidden = true;++ const abortBtn = el.querySelector('.abort-btn');+ if (opts.onCancel) {+ // Replace node to drop any handler from a previous overlay invocation,+ // then wire fresh — keeps cancel semantics tied to the current save.+ const fresh = abortBtn.cloneNode(true);+ abortBtn.replaceWith(fresh);+ fresh.hidden = false;+ fresh.addEventListener('click', opts.onCancel, { once: true });+ } else {+ abortBtn.hidden = true;+ }+}++// Toggle the in-flight cancel button — called with `false` once we cross the+// upload boundary into commit/redirect, where cancelling no longer makes+// sense (the bytes are already in R2 and the row is being inserted).+function setSaveCancellable(enabled) {+ const el = document.getElementById('save-loading');+ if (!el) return;+ const btn = el.querySelector('.abort-btn');+ if (btn) btn.hidden = !enabled;}function updateSaveOverlay(label, sublabel) {diff --git a/tests/api/providers-huggingface-failover.test.js b/tests/api/providers-huggingface-failover.test.jsnew file mode 100644index 000000000..a2c958d9a--- /dev/null+++ b/tests/api/providers-huggingface-failover.test.js@@ -0,0 +1,200 @@+// Tests for the HuggingFace provider failover chain.+//+// Critical invariants:+// • Try each Space in order; return first success.+// • Surface per-Space failures in the final error message so debugging+// "Avatar engine not available" tells you WHICH Spaces failed and HOW.+// • Env-driven chain config wins over the curated default.+// • Submit fails closed when chain is empty.+//+// We stub global fetch to model Space responses (queue enqueue, SSE stream).++import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';++const ORIGINAL_FETCH = globalThis.fetch;+const ORIGINAL_HF_TOKEN = process.env.HF_TOKEN;+const ORIGINAL_SPACES = process.env.HF_RECONSTRUCT_SPACES;+const ORIGINAL_SPACE = process.env.HF_RECONSTRUCT_SPACE;++function spaceUrl(slug) {+ return `https://${slug.replace(/\//g, '-').toLowerCase()}.hf.space`;+}++// Compose an SSE response stream emitting [event: complete, data: <output>] then close.+function sseStream(output) {+ const text =+ `event: generating\ndata: {}\n\n` ++ `event: complete\ndata: ${JSON.stringify(output)}\n\n`;+ const encoder = new TextEncoder();+ const stream = new ReadableStream({+ start(controller) {+ controller.enqueue(encoder.encode(text));+ controller.close();+ },+ });+ return new Response(stream, {+ status: 200,+ headers: { 'content-type': 'text/event-stream' },+ });+}++function jsonResp(body, status = 200) {+ return new Response(JSON.stringify(body), {+ status,+ headers: { 'content-type': 'application/json' },+ });+}++beforeEach(() => {+ process.env.HF_TOKEN = 'hf_test_token';+ delete process.env.HF_RECONSTRUCT_SPACES;+ delete process.env.HF_RECONSTRUCT_SPACE;+ vi.resetModules();+});++afterEach(() => {+ globalThis.fetch = ORIGINAL_FETCH;+ if (ORIGINAL_HF_TOKEN === undefined) delete process.env.HF_TOKEN;+ else process.env.HF_TOKEN = ORIGINAL_HF_TOKEN;+ if (ORIGINAL_SPACES === undefined) delete process.env.HF_RECONSTRUCT_SPACES;+ else process.env.HF_RECONSTRUCT_SPACES = ORIGINAL_SPACES;+ if (ORIGINAL_SPACE === undefined) delete process.env.HF_RECONSTRUCT_SPACE;+ else process.env.HF_RECONSTRUCT_SPACE = ORIGINAL_SPACE;+});++describe('huggingface provider — failover chain', () => {+ it('first Space succeeds: returns its GLB url without trying others', async () => {+ process.env.HF_RECONSTRUCT_SPACES = 'foo/A,bar/B';+ const fetchMock = vi.fn(async (url) => {+ if (url === `${spaceUrl('foo/A')}/call/generation_all`) {+ return jsonResp({ event_id: 'evt-A' });+ }+ if (url === `${spaceUrl('foo/A')}/call/generation_all/evt-A`) {+ return sseStream([{ url: 'https://files/foo.glb' }]);+ }+ throw new Error(`unexpected url ${url}`);+ });+ globalThis.fetch = fetchMock;++ const { createRegenProvider } = await import('../../api/_providers/huggingface.js');+ const provider = createRegenProvider();+ const out = await provider.submit({+ mode: 'reconstruct',+ params: { images: ['data:image/jpeg;base64,AAA'] },+ });+ expect(out.rawStatus).toBe('completed');++ // extJobId is base64url-encoded JSON pack — decode and check the result.+ const decoded = JSON.parse(Buffer.from(out.extJobId, 'base64url').toString('utf8'));+ expect(decoded.resultGlbUrl).toBe('https://files/foo.glb');+ expect(decoded.space).toBe('foo/A');+ expect(decoded.fellBackFrom).toEqual([]);+ expect(out.providerNote).toBeUndefined();++ // We only hit foo/A — 2 calls (enqueue + SSE).+ expect(fetchMock.mock.calls.length).toBe(2);+ });++ it('first Space 502s: falls over to second and surfaces the failure note', async () => {+ process.env.HF_RECONSTRUCT_SPACES = 'down/X,up/Y';+ const fetchMock = vi.fn(async (url) => {+ if (url.startsWith(spaceUrl('down/X'))) {+ return jsonResp({ detail: 'no GPU' }, 502);+ }+ if (url === `${spaceUrl('up/Y')}/call/generation_all`) {+ return jsonResp({ event_id: 'evt-Y' });+ }+ if (url === `${spaceUrl('up/Y')}/call/generation_all/evt-Y`) {+ return sseStream(['https://x/healed.glb']);+ }+ throw new Error(`unexpected url ${url}`);+ });+ globalThis.fetch = fetchMock;++ const { createRegenProvider } = await import('../../api/_providers/huggingface.js');+ const provider = createRegenProvider();+ const out = await provider.submit({+ mode: 'reconstruct',+ params: { images: ['data:image/jpeg;base64,AAA'] },+ });++ const decoded = JSON.parse(Buffer.from(out.extJobId, 'base64url').toString('utf8'));+ expect(decoded.resultGlbUrl).toBe('https://x/healed.glb');+ expect(decoded.space).toBe('up/Y');+ expect(decoded.fellBackFrom).toEqual(['down/X']);+ expect(out.providerNote).toMatch(/succeeded on up\/Y after 1 failover/);+ });++ it('all Spaces fail: throws with per-Space breakdown', async () => {+ process.env.HF_RECONSTRUCT_SPACES = 'a/1,b/2,c/3';+ const fetchMock = vi.fn(async () => jsonResp({ detail: 'No GPU function detected' }, 502));+ globalThis.fetch = fetchMock;++ const { createRegenProvider } = await import('../../api/_providers/huggingface.js');+ const provider = createRegenProvider();+ await expect(+ provider.submit({ mode: 'reconstruct', params: { images: ['data:image/jpeg;base64,AAA'] } }),+ ).rejects.toMatchObject({+ code: 'all_providers_failed',+ status: 502,+ message: expect.stringMatching(/all 3 huggingface Space\(s\) failed.*a\/1.*b\/2.*c\/3/s),+ failures: expect.arrayContaining([+ expect.objectContaining({ space: 'a/1' }),+ expect.objectContaining({ space: 'b/2' }),+ expect.objectContaining({ space: 'c/3' }),+ ]),+ });+ expect(fetchMock.mock.calls.length).toBe(3); // one enqueue per Space+ });++ it('legacy HF_RECONSTRUCT_SPACE env still works as a single-Space chain', async () => {+ process.env.HF_RECONSTRUCT_SPACE = 'legacy/only';+ const fetchMock = vi.fn(async (url) => {+ if (url === `${spaceUrl('legacy/only')}/call/generation_all`) {+ return jsonResp({ event_id: 'evt-L' });+ }+ if (url.endsWith('/evt-L')) {+ return sseStream(['https://x/legacy.glb']);+ }+ throw new Error(`unexpected ${url}`);+ });+ globalThis.fetch = fetchMock;++ const { createRegenProvider } = await import('../../api/_providers/huggingface.js');+ const provider = createRegenProvider();+ const out = await provider.submit({+ mode: 'reconstruct',+ params: { images: ['data:image/jpeg;base64,AAA'] },+ });+ const decoded = JSON.parse(Buffer.from(out.extJobId, 'base64url').toString('utf8'));+ expect(decoded.space).toBe('legacy/only');+ });++ it('rejects non-reconstruct mode immediately (no fetch)', async () => {+ const fetchMock = vi.fn();+ globalThis.fetch = fetchMock;++ const { createRegenProvider } = await import('../../api/_providers/huggingface.js');+ const provider = createRegenProvider();+ await expect(provider.submit({ mode: 'restyle', params: {} })).rejects.toMatchObject({+ code: 'mode_unconfigured',+ status: 501,+ });+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it('rejects when no images are provided', async () => {+ const { createRegenProvider } = await import('../../api/_providers/huggingface.js');+ const provider = createRegenProvider();+ await expect(provider.submit({ mode: 'reconstruct', params: {} })).rejects.toMatchObject({+ code: 'invalid_input',+ status: 400,+ });+ });++ it('factory throws when HF_TOKEN is missing', async () => {+ delete process.env.HF_TOKEN;+ const { createRegenProvider } = await import('../../api/_providers/huggingface.js');+ expect(() => createRegenProvider()).toThrow(/HF_TOKEN/);+ });+});diff --git a/tests/api/widgets.test.js b/tests/api/widgets.test.jsindex 30c7aabdb..8677c8a0d 100644--- a/tests/api/widgets.test.js+++ b/tests/api/widgets.test.js@@ -60,6 +60,19 @@ vi.mock('../../api/_lib/avatars.js', () => ({getAvatar: vi.fn(async () => null),}));+// Embeddings — keep tests offline. Configured=true so we exercise the test+// branch's validation; embed() returns a fixed vector if invoked.+vi.mock('../../api/_lib/embeddings.js', () => ({+ embeddingsConfigured: () => true,+ embed: vi.fn(async (texts) => texts.map(() => Float64Array.from([1, 0, 0, 0]))),+ cosine: (a, b) => {+ let dot = 0, na = 0, nb = 0;+ const n = Math.min(a.length, b.length);+ for (let i = 0; i < n; i++) { dot += a[i] * b[i]; na += a[i] ** 2; nb += b[i] ** 2; }+ return na && nb ? dot / Math.sqrt(na * nb) : 0;+ },+}));+// ── Import handlers AFTER mocks are registered ───────────────────────────────const listCreateHandler = (await import('../../api/widgets/index.js')).default;