Skip to content

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.

feat: AR page, XR demos, theme system, studio/gallery/nav CSS expansion

nirholasc88bccc24867
diff --git a/pages/ar.html b/pages/ar.html
new file mode 100644
index 000000000..7817fdee3
--- /dev/null
+++ b/pages/ar.html
@@ -0,0 +1,327 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
+ <meta name="theme-color" content="#050810" />
+ <title>Avatar in AR · three.ws</title>
+ <link rel="shortcut icon" href="/favicon.ico" />
+ <link rel="stylesheet" href="/fonts/fonts.css" />
+ <meta property="og:type" content="website" />
+ <meta property="og:site_name" content="three.ws" />
+ <meta name="og:image" content="https://three.ws/assets/og-image.png" />
+
+ <script
+ type="module"
+ src="https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js"
+ ></script>
+ <script type="module" src="/src/ar-page.js"></script>
+
+ <style>
+ :root {
+ --bg: #050810;
+ --bg2: #0a0e1a;
+ --text: #f0f4ff;
+ --text-2: #8891aa;
+ --text-3: #4b5268;
+ --accent: #7dd3fc;
+ --accent-2: #a78bfa;
+ --panel: rgba(255,255,255,0.04);
+ --border: rgba(255,255,255,0.08);
+ --radius: 14px;
+ }
+
+ *, *::before, *::after { box-sizing: border-box; }
+
+ html, body {
+ margin: 0; padding: 0;
+ width: 100%; height: 100%;
+ overflow: hidden;
+ background: var(--bg);
+ color: var(--text);
+ font-family: 'Inter', system-ui, sans-serif;
+ -webkit-font-smoothing: antialiased;
+ }
+
+ /* ── Background glow ─────────────────────────── */
+ .ar-bg {
+ position: fixed;
+ inset: 0;
+ pointer-events: none;
+ z-index: 0;
+ }
+ .ar-bg::before {
+ content: '';
+ position: absolute;
+ inset: 0;
+ background:
+ radial-gradient(ellipse 80% 60% at 50% 0%, rgba(125,211,252,0.07) 0%, transparent 65%),
+ radial-gradient(ellipse 60% 50% at 80% 80%, rgba(167,139,250,0.06) 0%, transparent 60%),
+ radial-gradient(ellipse 50% 40% at 20% 70%, rgba(125,211,252,0.04) 0%, transparent 55%);
+ }
+
+ /* ── Layout shell ────────────────────────────── */
+ #ar-shell {
+ position: relative;
+ width: 100%;
+ height: 100%;
+ z-index: 1;
+ display: flex;
+ flex-direction: column;
+ }
+
+ /* ── Top bar ─────────────────────────────────── */
+ .ar-topbar {
+ position: absolute;
+ top: 0;
+ left: 0;
+ right: 0;
+ z-index: 10;
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: env(safe-area-inset-top, 0) 0 0;
+ padding-left: 16px;
+ padding-right: 16px;
+ padding-top: calc(env(safe-area-inset-top, 0px) + 14px);
+ padding-bottom: 14px;
+ background: linear-gradient(to bottom, rgba(5,8,16,0.85) 0%, transparent 100%);
+ backdrop-filter: blur(0px);
+ }
+ .ar-back {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ color: var(--text-2);
+ text-decoration: none;
+ font-size: 14px;
+ font-weight: 500;
+ transition: color 0.15s;
+ padding: 6px 0;
+ }
+ .ar-back:hover { color: var(--text); }
+ .ar-back svg { flex-shrink: 0; }
+
+ .ar-topbar-center {
+ position: absolute;
+ left: 50%;
+ transform: translateX(-50%);
+ text-align: center;
+ pointer-events: none;
+ }
+ .ar-badge {
+ display: inline-flex;
+ align-items: center;
+ gap: 5px;
+ font-size: 11px;
+ font-weight: 600;
+ letter-spacing: 0.08em;
+ text-transform: uppercase;
+ color: var(--accent);
+ background: rgba(125,211,252,0.08);
+ border: 1px solid rgba(125,211,252,0.2);
+ border-radius: 999px;
+ padding: 4px 10px;
+ }
+ .ar-badge-dot {
+ width: 5px;
+ height: 5px;
+ border-radius: 50%;
+ background: var(--accent);
+ animation: ar-pulse 2s ease-in-out infinite;
+ }
+ @keyframes ar-pulse {
+ 0%, 100% { opacity: 1; transform: scale(1); }
+ 50% { opacity: 0.5; transform: scale(0.75); }
+ }
+
+ .ar-share-btn {
+ background: transparent;
+ border: 1px solid var(--border);
+ border-radius: 999px;
+ color: var(--text-2);
+ font-size: 13px;
+ font-weight: 500;
+ font-family: inherit;
+ cursor: pointer;
+ padding: 6px 14px;
+ transition: border-color 0.15s, color 0.15s;
+ }
+ .ar-share-btn:hover { border-color: var(--text-3); color: var(--text); }
+
+ /* ── Model viewer ────────────────────────────── */
+ model-viewer {
+ position: absolute;
+ inset: 0;
+ width: 100%;
+ height: 100%;
+ --poster-color: transparent;
+ background: transparent;
+ }
+ model-viewer::part(default-ar-button) {
+ display: none; /* we use our own button */
+ }
+
+ /* ── Bottom panel ────────────────────────────── */
+ .ar-bottom {
+ position: absolute;
+ bottom: 0;
+ left: 0;
+ right: 0;
+ z-index: 10;
+ padding: 0 20px;
+ padding-bottom: calc(env(safe-area-inset-bottom, 0px) + 28px);
+ background: linear-gradient(to top, rgba(5,8,16,0.92) 0%, rgba(5,8,16,0.6) 60%, transparent 100%);
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 10px;
+ pointer-events: none;
+ }
+ .ar-bottom > * { pointer-events: auto; }
+
+ .ar-avatar-name {
+ font-size: 22px;
+ font-weight: 700;
+ letter-spacing: -0.02em;
+ color: var(--text);
+ text-align: center;
+ margin: 0;
+ line-height: 1.2;
+ font-family: 'Space Grotesk', system-ui, sans-serif;
+ }
+
+ .ar-subtitle {
+ font-size: 13px;
+ color: var(--text-2);
+ text-align: center;
+ margin: 0;
+ }
+
+ .ar-status {
+ font-size: 12.5px;
+ color: var(--accent-2);
+ text-align: center;
+ height: 18px;
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ }
+ .ar-status.is-error { color: #f87171; }
+ .ar-status-spinner {
+ width: 13px;
+ height: 13px;
+ border-radius: 50%;
+ border: 2px solid rgba(167,139,250,0.25);
+ border-top-color: var(--accent-2);
+ animation: ar-spin 0.7s linear infinite;
+ flex-shrink: 0;
+ }
+ @keyframes ar-spin { to { transform: rotate(360deg); } }
+
+ .ar-launch-btn {
+ width: 100%;
+ max-width: 380px;
+ height: 60px;
+ background: linear-gradient(135deg, #7dd3fc 0%, #a78bfa 100%);
+ color: #05080e;
+ border: 0;
+ border-radius: 18px;
+ font-family: 'Space Grotesk', system-ui, sans-serif;
+ font-size: 17px;
+ font-weight: 700;
+ letter-spacing: -0.01em;
+ cursor: pointer;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ gap: 10px;
+ transition: transform 0.12s, box-shadow 0.2s, opacity 0.15s;
+ box-shadow: 0 8px 32px -8px rgba(125,211,252,0.5), 0 0 0 1px rgba(255,255,255,0.08) inset;
+ position: relative;
+ overflow: hidden;
+ }
+ .ar-launch-btn::after {
+ content: '';
+ position: absolute;
+ inset: 0;
+ background: linear-gradient(to bottom, rgba(255,255,255,0.12) 0%, transparent 50%);
+ pointer-events: none;
+ }
+ .ar-launch-btn:hover:not(:disabled) {
+ transform: translateY(-2px);
+ box-shadow: 0 14px 40px -8px rgba(167,139,250,0.55), 0 0 0 1px rgba(255,255,255,0.1) inset;
+ }
+ .ar-launch-btn:active:not(:disabled) { transform: translateY(0); }
+ .ar-launch-btn:disabled {
+ opacity: 0.45;
+ cursor: not-allowed;
+ }
+ .ar-launch-btn svg { flex-shrink: 0; }
+
+ /* ── Loading / error fallback ─────────────────── */
+ .ar-error {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ height: 100%;
+ color: var(--text-2);
+ font-size: 15px;
+ text-align: center;
+ padding: 2rem;
+ }
+ </style>
+ </head>
+ <body>
+ <div class="ar-bg" aria-hidden="true"></div>
+
+ <div id="ar-shell">
+ <model-viewer
+ id="ar-viewer"
+ alt="Avatar"
+ camera-controls
+ auto-rotate
+ rotation-per-second="12deg"
+ interaction-prompt="none"
+ exposure="1.1"
+ shadow-intensity="0.8"
+ shadow-softness="0.9"
+ environment-image="neutral"
+ tone-mapping="aces"
+ ar
+ ar-modes="webxr scene-viewer quick-look"
+ ar-scale="auto"
+ reveal="auto"
+ ></model-viewer>
+
+ <header class="ar-topbar">
+ <a class="ar-back" id="ar-back-link" href="/marketplace">
+ <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="15 18 9 12 15 6"/></svg>
+ Back
+ </a>
+ <div class="ar-topbar-center">
+ <span class="ar-badge">
+ <span class="ar-badge-dot"></span>
+ AR Ready
+ </span>
+ </div>
+ <button class="ar-share-btn" id="ar-share-btn" type="button" aria-label="Share">Share</button>
+ </header>
+
+ <footer class="ar-bottom">
+ <h1 class="ar-avatar-name" id="ar-avatar-name">Loading…</h1>
+ <p class="ar-subtitle">Point your device at a flat surface to place</p>
+ <p class="ar-status" id="ar-status" hidden>
+ <span class="ar-status-spinner" aria-hidden="true"></span>
+ <span id="ar-status-text"></span>
+ </p>
+ <button class="ar-launch-btn" id="ar-launch-btn" type="button" disabled aria-busy="true">
+ <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
+ <path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"/>
+ </svg>
+ Place in your space
+ </button>
+ </footer>
+ </div>
+ </body>
+</html>
diff --git a/pages/avatar-page.html b/pages/avatar-page.html
index c7ba295c2..6bd8a8fb2 100644
--- a/pages/avatar-page.html
+++ b/pages/avatar-page.html
@@ -314,6 +314,35 @@
}
.av-cta-sec:hover { border-color: var(--text-2); }
+ /* ── AR row ──────────────────────────────────── */
+ .av-ar-row {
+ display: flex;
+ justify-content: center;
+ padding: 0 24px 12px;
+ }
+ .av-ar-btn {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ padding: 9px 18px;
+ background: linear-gradient(135deg, rgba(125,211,252,0.10) 0%, rgba(167,139,250,0.10) 100%);
+ border: 1px solid rgba(125,211,252,0.28);
+ border-radius: 999px;
+ color: var(--accent);
+ font-size: 13px;
+ font-weight: 600;
+ font-family: inherit;
+ text-decoration: none;
+ cursor: pointer;
+ transition: background 0.15s, border-color 0.15s, box-shadow 0.2s;
+ letter-spacing: 0.01em;
+ }
+ .av-ar-btn:hover {
+ background: linear-gradient(135deg, rgba(125,211,252,0.18) 0%, rgba(167,139,250,0.18) 100%);
+ border-color: rgba(125,211,252,0.5);
+ box-shadow: 0 0 18px -4px rgba(125,211,252,0.3);
+ }
+
/* ── Owner actions row ───────────────────────── */
.av-owner-row {
display: flex;
diff --git a/public/demos/brain.html b/public/demos/brain.html
index b33e0a397..194d63619 100644
--- a/public/demos/brain.html
+++ b/public/demos/brain.html
@@ -3,283 +3,1329 @@
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
- <title>Multi-LLM brain · three.ws</title>
- <meta name="description" content="Send the same prompt to Claude, GPT, Qwen on Alibaba DashScope, Qwen3-Coder on ModelScope, and Llama on Groq. Compare streaming responses, latency, and token usage side-by-side." />
+ <title>Brain Lab · three.ws</title>
+ <meta name="description" content="Multi-turn LLM comparison lab. Compare Claude, GPT, Qwen, and Llama in real conversations — streaming responses, markdown, full history." />
<link rel="canonical" href="https://three.ws/brain" />
- <meta property="og:title" content="Multi-LLM brain · three.ws" />
- <meta property="og:description" content="Compare Claude, GPT, Qwen, ModelScope, and Groq side-by-side. Same prompt, real streaming, real token counts." />
+ <meta property="og:title" content="Brain Lab · three.ws" />
+ <meta property="og:description" content="Have real multi-turn conversations with Claude, GPT, Qwen, and Llama simultaneously. Compare how different AI brains handle the same conversation." />
<meta property="og:url" content="https://three.ws/brain" />
<meta name="twitter:card" content="summary_large_image" />
<link rel="stylesheet" href="/style.css" />
<link rel="stylesheet" href="/nav.css" />
<style>
:root { color-scheme: dark; }
- body { background: #05060a; color: #eee; font: 15px/1.5 -apple-system, system-ui, 'Segoe UI', Roboto, sans-serif; margin: 0; }
- .stage { max-width: 1080px; margin: 0 auto; padding: 48px 24px 80px; }
- .crumb a { color: #8a8d98; text-decoration: none; }
- .crumb a:hover { color: #3dc1ff; }
- h1 { font-size: 28px; font-weight: 600; letter-spacing: -0.015em; margin: 14px 0 8px; }
- .sub { color: #8a8d98; max-width: 64ch; margin: 0 0 26px; }
- .composer { display: flex; flex-direction: column; gap: 12px; background: #0f1018; border: 1.5px solid #1e1f2b; border-radius: 14px; padding: 18px; margin-bottom: 22px; }
- .composer textarea { width: 100%; min-height: 92px; resize: vertical; padding: 12px 14px; background: #07080d; border: 1px solid #1e1f2b; border-radius: 10px; color: #eee; font: inherit; line-height: 1.5; }
- .composer-row { display: flex; gap: 10px; align-items: center; flex-wrap: wrap; }
- .composer-row select, .composer-row input[type="text"] { background: #07080d; border: 1px solid #1e1f2b; color: #eee; padding: 8px 10px; border-radius: 9px; font: inherit; }
- .composer-row label { font-size: 12px; color: #8a8d98; text-transform: uppercase; letter-spacing: 0.08em; }
- button { background: #3dc1ff; color: #0a0a0a; border: 0; border-radius: 9px; padding: 10px 16px; font-weight: 600; cursor: pointer; font: inherit; }
- button.secondary { background: rgba(255,255,255,0.06); color: #eee; }
- button:disabled { opacity: 0.4; cursor: not-allowed; }
- .providers { display: grid; grid-template-columns: repeat(auto-fill, minmax(170px, 1fr)); gap: 8px; }
- .provider-pill { display: flex; align-items: center; gap: 8px; padding: 8px 12px; background: #07080d; border: 1px solid #1e1f2b; border-radius: 9px; cursor: pointer; user-select: none; }
- .provider-pill input { accent-color: #3dc1ff; }
- .provider-pill .net { font-size: 10.5px; color: #8a8d98; text-transform: uppercase; letter-spacing: 0.05em; }
- .provider-pill .name { font-size: 13px; font-weight: 600; }
- .provider-pill .meta { display: flex; flex-direction: column; line-height: 1.2; }
- .grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(320px, 1fr)); gap: 14px; }
- .card { background: #0f1018; border: 1.5px solid #1e1f2b; border-radius: 14px; padding: 18px; display: flex; flex-direction: column; min-height: 280px; }
- .card-head { display: flex; justify-content: space-between; align-items: baseline; gap: 8px; margin-bottom: 4px; }
- .card-title { font-size: 14px; font-weight: 600; letter-spacing: -0.005em; margin: 0; }
- .card-net { font-size: 10.5px; color: #8a8d98; text-transform: uppercase; letter-spacing: 0.06em; }
- .card-body { flex: 1; margin-top: 10px; padding: 12px; background: #07080d; border: 1px solid #1e1f2b; border-radius: 9px; font-size: 13.5px; line-height: 1.55; color: #ddd; white-space: pre-wrap; min-height: 130px; max-height: 320px; overflow-y: auto; }
- .card-body.empty { color: #565762; font-style: italic; }
- .card-body.error { color: #ff8a8a; }
- .card-footer { margin-top: 10px; display: flex; gap: 14px; font-size: 11.5px; color: #8a8d98; font-family: ui-monospace, monospace; flex-wrap: wrap; }
- .card-footer span strong { color: #3dc1ff; font-weight: 600; }
- .spinner { display: inline-block; width: 10px; height: 10px; border-radius: 50%; background: #3dc1ff; animation: pulse 1s ease-in-out infinite; vertical-align: middle; margin-left: 8px; }
- @keyframes pulse { 0%, 100% { opacity: 0.3; } 50% { opacity: 1; } }
- .notice { padding: 10px 14px; border-radius: 10px; background: rgba(255,184,77,0.08); border: 1px solid rgba(255,184,77,0.25); color: #ffb84d; font-size: 13px; margin-top: 16px; }
+ *, *::before, *::after { box-sizing: border-box; }
+ body {
+ background: #05060a;
+ color: #e8eaf0;
+ font: 14px/1.5 -apple-system, system-ui, 'Segoe UI', Roboto, sans-serif;
+ margin: 0;
+ display: flex;
+ flex-direction: column;
+ height: 100vh;
+ overflow: hidden;
+ }
+
+ /* ── Layout ─────────────────────────────────── */
+ .bl-root {
+ flex: 1;
+ display: flex;
+ overflow: hidden;
+ min-height: 0;
+ }
+
+ /* ── Sidebar ─────────────────────────────────── */
+ .bl-sidebar {
+ width: 220px;
+ flex-shrink: 0;
+ display: flex;
+ flex-direction: column;
+ border-right: 1px solid #1a1c28;
+ background: #08090f;
+ overflow: hidden;
+ }
+ .bl-sidebar-head {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 13px 14px 12px;
+ border-bottom: 1px solid #1a1c28;
+ gap: 8px;
+ }
+ .bl-sidebar-title {
+ font-size: 12px;
+ font-weight: 600;
+ text-transform: uppercase;
+ letter-spacing: 0.08em;
+ color: #565870;
+ }
+ .bl-new-btn {
+ background: #1e2035;
+ border: 1px solid #2a2d47;
+ color: #8a8faa;
+ border-radius: 7px;
+ padding: 4px 10px;
+ font-size: 16px;
+ line-height: 1;
+ cursor: pointer;
+ transition: background 0.12s, color 0.12s;
+ }
+ .bl-new-btn:hover { background: #252840; color: #c8cadf; }
+
+ .bl-sessions {
+ flex: 1;
+ overflow-y: auto;
+ padding: 8px 6px;
+ }
+ .bl-session-item {
+ padding: 8px 10px;
+ border-radius: 8px;
+ cursor: pointer;
+ font-size: 12.5px;
+ color: #8a8faa;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ transition: background 0.1s, color 0.1s;
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ border: 1px solid transparent;
+ }
+ .bl-session-item:hover { background: #111220; color: #c8cadf; }
+ .bl-session-item.active {
+ background: #141627;
+ color: #e0e2ef;
+ border-color: #252840;
+ }
+ .bl-session-icon { font-size: 11px; opacity: 0.6; flex-shrink: 0; }
+ .bl-session-name { flex: 1; overflow: hidden; text-overflow: ellipsis; }
+ .bl-session-del {
+ background: none;
+ border: none;
+ color: #565870;
+ cursor: pointer;
+ padding: 1px 3px;
+ font-size: 13px;
+ border-radius: 4px;
+ line-height: 1;
+ opacity: 0;
+ flex-shrink: 0;
+ transition: opacity 0.1s, color 0.1s;
+ }
+ .bl-session-item:hover .bl-session-del { opacity: 1; }
+ .bl-session-del:hover { color: #ff8080; }
+ .bl-empty-sessions {
+ padding: 20px 10px;
+ text-align: center;
+ color: #565870;
+ font-size: 12px;
+ line-height: 1.7;
+ }
+
+ /* ── Main body ───────────────────────────────── */
+ .bl-body {
+ flex: 1;
+ display: flex;
+ flex-direction: column;
+ overflow: hidden;
+ min-width: 0;
+ }
+
+ /* ── Toolbar ─────────────────────────────────── */
+ .bl-toolbar {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+ padding: 10px 16px;
+ border-bottom: 1px solid #1a1c28;
+ flex-wrap: wrap;
+ background: #08090f;
+ flex-shrink: 0;
+ }
+ .bl-mode-toggle {
+ display: flex;
+ border: 1px solid #1e2035;
+ border-radius: 8px;
+ overflow: hidden;
+ flex-shrink: 0;
+ }
+ .bl-mode-btn {
+ background: none;
+ border: none;
+ color: #565870;
+ padding: 6px 12px;
+ font: inherit;
+ font-size: 12.5px;
+ font-weight: 500;
+ cursor: pointer;
+ transition: background 0.12s, color 0.12s;
+ }
+ .bl-mode-btn + .bl-mode-btn { border-left: 1px solid #1e2035; }
+ .bl-mode-btn.active {
+ background: #1e2035;
+ color: #c8cadf;
+ }
+ .bl-toolbar-label {
+ font-size: 11.5px;
+ color: #565870;
+ font-weight: 500;
+ flex-shrink: 0;
+ }
+ .bl-provider-pills {
+ display: flex;
+ gap: 6px;
+ flex-wrap: wrap;
+ flex: 1;
+ }
+ .bl-ppill {
+ display: inline-flex;
+ align-items: center;
+ gap: 5px;
+ padding: 4px 9px;
+ border-radius: 999px;
+ border: 1px solid #1e2035;
+ background: #0f1020;
+ color: #565870;
+ font-size: 12px;
+ cursor: pointer;
+ user-select: none;
+ transition: border-color 0.12s, color 0.12s, background 0.12s;
+ }
+ .bl-ppill input { display: none; }
+ .bl-ppill.on { border-color: var(--pc); color: var(--pc); background: rgba(0,0,0,0); }
+ .bl-ppill .pc-dot {
+ width: 6px;
+ height: 6px;
+ border-radius: 50%;
+ background: var(--pc);
+ flex-shrink: 0;
+ opacity: 0.8;
+ }
+
+ /* Chat-mode provider selector (focus) */
+ .bl-focus-sel {
+ background: #0f1020;
+ border: 1px solid #1e2035;
+ color: #c8cadf;
+ padding: 5px 8px;
+ border-radius: 8px;
+ font: inherit;
+ font-size: 13px;
+ cursor: pointer;
+ }
+
+ .bl-toolbar-actions { margin-left: auto; display: flex; gap: 8px; }
+ .bl-action-btn {
+ background: #1e2035;
+ border: 1px solid #252840;
+ color: #8a8faa;
+ padding: 5px 10px;
+ border-radius: 7px;
+ font: inherit;
+ font-size: 12px;
+ cursor: pointer;
+ transition: background 0.12s, color 0.12s;
+ }
+ .bl-action-btn:hover { background: #252840; color: #c8cadf; }
+
+ /* ── Canvas ──────────────────────────────────── */
+ .bl-canvas {
+ flex: 1;
+ overflow: hidden;
+ display: flex;
+ min-height: 0;
+ }
+
+ /* Compare mode: grid of columns */
+ .bl-compare {
+ display: flex;
+ flex: 1;
+ overflow-x: auto;
+ overflow-y: hidden;
+ gap: 0;
+ }
+ .bl-col {
+ flex: 1;
+ min-width: 280px;
+ display: flex;
+ flex-direction: column;
+ border-right: 1px solid #1a1c28;
+ overflow: hidden;
+ }
+ .bl-col:last-child { border-right: none; }
+ .bl-col-head {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 9px 14px 8px;
+ border-bottom: 1px solid #1a1c28;
+ flex-shrink: 0;
+ gap: 8px;
+ }
+ .bl-col-name {
+ font-size: 12.5px;
+ font-weight: 600;
+ color: var(--pc);
+ }
+ .bl-col-net {
+ font-size: 10.5px;
+ color: #565870;
+ text-transform: uppercase;
+ letter-spacing: 0.06em;
+ }
+ .bl-col-stats {
+ font-size: 11px;
+ color: #565870;
+ font-family: ui-monospace, monospace;
+ display: flex;
+ gap: 10px;
+ }
+ .bl-col-stats strong { color: #8a8faa; }
+ .bl-col-copy {
+ background: none;
+ border: none;
+ color: #565870;
+ cursor: pointer;
+ padding: 3px 6px;
+ border-radius: 5px;
+ font-size: 11px;
+ transition: color 0.1s, background 0.1s;
+ }
+ .bl-col-copy:hover { color: #c8cadf; background: #1e2035; }
+ .bl-col-messages {
+ flex: 1;
+ overflow-y: auto;
+ padding: 12px 14px;
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+ }
+ .bl-col-empty {
+ color: #565870;
+ font-size: 13px;
+ font-style: italic;
+ text-align: center;
+ padding: 40px 20px;
+ }
+
+ /* Chat mode: single column conversation */
+ .bl-chat {
+ flex: 1;
+ display: flex;
+ flex-direction: column;
+ overflow: hidden;
+ max-width: 820px;
+ margin: 0 auto;
+ width: 100%;
+ }
+ .bl-chat-messages {
+ flex: 1;
+ overflow-y: auto;
+ padding: 24px 28px;
+ display: flex;
+ flex-direction: column;
+ gap: 20px;
+ }
+ .bl-chat-empty {
+ flex: 1;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ color: #565870;
+ gap: 10px;
+ padding: 40px;
+ text-align: center;
+ }
+ .bl-chat-empty h3 { color: #8a8faa; margin: 0; font-size: 18px; font-weight: 500; }
+ .bl-chat-empty p { margin: 0; font-size: 13.5px; max-width: 44ch; }
+
+ /* Messages shared */
+ .bl-msg {
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ animation: msgIn 0.12s ease-out;
+ }
+ @keyframes msgIn { from { opacity: 0; transform: translateY(4px); } to { opacity: 1; transform: none; } }
+ .bl-msg-label {
+ font-size: 11px;
+ font-weight: 600;
+ text-transform: uppercase;
+ letter-spacing: 0.07em;
+ color: #565870;
+ }
+ .bl-msg.user .bl-msg-label { color: #8a8faa; }
+ .bl-msg.assistant .bl-msg-label { color: var(--pc, #8a8faa); }
+ .bl-msg-body {
+ font-size: 13.5px;
+ line-height: 1.62;
+ color: #dde0ee;
+ padding: 0;
+ white-space: pre-wrap;
+ }
+ .bl-msg.user .bl-msg-body {
+ color: #b0b3cc;
+ }
+
+ /* Spinner for streaming */
+ .bl-spin {
+ display: inline-block;
+ width: 8px;
+ height: 8px;
+ border-radius: 50%;
+ background: #3dc1ff;
+ animation: blink 0.9s ease-in-out infinite;
+ vertical-align: middle;
+ margin-left: 4px;
+ }
+ @keyframes blink { 0%,100%{ opacity:0.25 } 50%{ opacity:1 } }
+
+ /* Compare mode: show user turns inline */
+ .bl-col-user {
+ font-size: 12.5px;
+ color: #565870;
+ padding: 6px 10px;
+ background: #0f1020;
+ border-radius: 8px;
+ border: 1px solid #1a1c28;
+ font-style: italic;
+ }
+ .bl-col-assistant {
+ font-size: 13.5px;
+ color: #dde0ee;
+ line-height: 1.62;
+ }
+
+ /* Markdown output */
+ .md-p { margin: 0 0 0.75em; }
+ .md-p:last-child { margin-bottom: 0; }
+ .md-h1 { font-size: 17px; font-weight: 600; margin: 1em 0 0.4em; }
+ .md-h2 { font-size: 15px; font-weight: 600; margin: 0.9em 0 0.35em; }
+ .md-h3 { font-size: 13.5px; font-weight: 600; margin: 0.75em 0 0.3em; }
+ .md-ul, .md-ol { margin: 0.4em 0 0.6em 1.4em; padding: 0; }
+ .md-ul li, .md-ol li { margin: 0.2em 0; }
+ .md-code {
+ background: #0d0f1e;
+ border: 1px solid #1e2035;
+ border-radius: 8px;
+ padding: 10px 14px;
+ overflow-x: auto;
+ font-family: ui-monospace, 'JetBrains Mono', Menlo, monospace;
+ font-size: 12.5px;
+ line-height: 1.55;
+ margin: 0.5em 0 0.75em;
+ color: #c8d3f5;
+ }
+ .md-ic {
+ background: rgba(255,255,255,0.07);
+ border: 1px solid rgba(255,255,255,0.1);
+ border-radius: 4px;
+ padding: 1px 5px;
+ font-family: ui-monospace, monospace;
+ font-size: 12px;
+ color: #c8d3f5;
+ }
+
+ /* ── Input area ──────────────────────────────── */
+ .bl-input-wrap {
+ border-top: 1px solid #1a1c28;
+ padding: 12px 16px 14px;
+ background: #08090f;
+ flex-shrink: 0;
+ }
+ .bl-sys-details {
+ margin-bottom: 8px;
+ }
+ .bl-sys-details summary {
+ font-size: 11.5px;
+ color: #565870;
+ cursor: pointer;
+ user-select: none;
+ font-weight: 500;
+ letter-spacing: 0.04em;
+ padding: 2px 0;
+ }
+ .bl-sys-details summary:hover { color: #8a8faa; }
+ .bl-sys-details[open] summary { color: #8a8faa; margin-bottom: 6px; }
+ #system {
+ width: 100%;
+ background: #0f1020;
+ border: 1px solid #1e2035;
+ border-radius: 8px;
+ color: #c8cadf;
+ font: inherit;
+ font-size: 13px;
+ padding: 9px 12px;
+ resize: vertical;
+ min-height: 60px;
+ outline: none;
+ }
+ #system:focus { border-color: #2e3258; }
+ .bl-input-row {
+ display: flex;
+ gap: 8px;
+ align-items: flex-end;
+ }
+ #prompt {
+ flex: 1;
+ background: #0f1020;
+ border: 1px solid #1e2035;
+ border-radius: 10px;
+ color: #e0e2ef;
+ font: inherit;
+ font-size: 13.5px;
+ padding: 10px 13px;
+ resize: none;
+ min-height: 44px;
+ max-height: 160px;
+ outline: none;
+ transition: border-color 0.12s;
+ field-sizing: content;
+ }
+ #prompt:focus { border-color: #2e3258; }
+ #send {
+ background: #3dc1ff;
+ color: #05060a;
+ border: none;
+ border-radius: 10px;
+ padding: 10px 16px;
+ font: inherit;
+ font-size: 13.5px;
+ font-weight: 600;
+ cursor: pointer;
+ flex-shrink: 0;
+ transition: opacity 0.12s, background 0.12s;
+ }
+ #send:hover { background: #5dccff; }
+ #send:disabled { opacity: 0.4; cursor: not-allowed; }
+ .bl-hint {
+ font-size: 11px;
+ color: #343650;
+ margin-top: 6px;
+ display: flex;
+ gap: 14px;
+ align-items: center;
+ }
+ .bl-hint a { color: #4a5080; text-decoration: none; }
+ .bl-hint a:hover { color: #8a8faa; }
+
+ /* ── Notice / error ──────────────────────────── */
+ .bl-notice {
+ padding: 8px 14px;
+ border-radius: 8px;
+ background: rgba(255,184,77,0.08);
+ border: 1px solid rgba(255,184,77,0.2);
+ color: #ffb84d;
+ font-size: 12.5px;
+ margin-bottom: 8px;
+ display: none;
+ }
+
+ /* ── Mobile ──────────────────────────────────── */
+ @media (max-width: 720px) {
+ .bl-sidebar { display: none; }
+ .bl-toolbar { padding: 8px 12px; }
+ .bl-chat-messages { padding: 16px; }
+ .bl-input-wrap { padding: 10px 12px 12px; }
+ }
</style>
</head>
<body>
<header><div id="nav-container"></div></header>
- <main class="stage">
- <p class="crumb"><a href="/">three.ws</a> · <a href="/demos/">labs</a> · brain</p>
- <h1>Multi-LLM brain</h1>
- <p class="sub">
- Send the same prompt to multiple providers at once. Side-by-side streaming
- answers, real latency, real token counts. Brain layer built on the Vercel AI
- SDK; routes to <strong>Claude</strong>, <strong>GPT</strong>,
- <strong>Qwen on Alibaba DashScope</strong>, <strong>Qwen3-Coder on ModelScope</strong>,
- and <strong>Llama 3.3 on Groq</strong>.
- </p>
-
- <section class="composer">
- <div>
- <label for="system" class="card-net">System (optional)</label>
- <textarea id="system" placeholder="You are a terse, helpful assistant…" style="min-height: 56px; margin-top: 6px;"></textarea>
- </div>
- <div>
- <label for="prompt" class="card-net">Prompt</label>
- <textarea id="prompt" placeholder="What ships when a developer drops &lt;agent-3d&gt; on a page?">Explain HTTP 402 in two sentences. No filler.</textarea>
+ <div class="bl-root">
+ <!-- Sidebar: conversation history -->
+ <aside class="bl-sidebar" id="sidebar">
+ <div class="bl-sidebar-head">
+ <span class="bl-sidebar-title">Sessions</span>
+ <button class="bl-new-btn" id="newChat" title="New conversation">+</button>
</div>
+ <div class="bl-sessions" id="sessions"></div>
+ </aside>
- <div>
- <label class="card-net">Providers to compare</label>
- <div class="providers" id="providers"></div>
+ <!-- Main -->
+ <div class="bl-body">
+ <!-- Toolbar -->
+ <div class="bl-toolbar" id="toolbar">
+ <div class="bl-mode-toggle">
+ <button class="bl-mode-btn active" data-mode="compare">Compare</button>
+ <button class="bl-mode-btn" data-mode="chat">Chat</button>
+ </div>
+ <span class="bl-toolbar-label" id="toolbarLabel">Models</span>
+ <div id="toolbarControls"></div>
+ <div class="bl-toolbar-actions">
+ <button class="bl-action-btn" id="exportBtn" title="Export conversation as markdown">Export</button>
+ <a href="/dashboard/library#tab=brain" class="bl-action-btn" style="text-decoration:none">Configure agent brain &rarr;</a>
+ </div>
</div>
- <div class="composer-row">
- <label>Max tokens</label>
- <input type="text" id="maxTokens" value="512" inputmode="numeric" style="width: 80px;" />
- <div style="flex: 1"></div>
- <button class="secondary" id="clear">Clear</button>
- <button id="run">Run</button>
- </div>
- </section>
+ <!-- Canvas: compare or chat -->
+ <div class="bl-canvas" id="canvas"></div>
- <div class="grid" id="grid"></div>
- <div class="notice" id="notice" style="display:none"></div>
- </main>
+ <!-- Input -->
+ <div class="bl-input-wrap">
+ <div class="bl-notice" id="notice"></div>
+ <details class="bl-sys-details" id="sysDetails">
+ <summary>System prompt</summary>
+ <textarea id="system" placeholder="You are a helpful assistant…" rows="3"></textarea>
+ </details>
+ <div class="bl-input-row">
+ <textarea id="prompt" placeholder="Send a message… (⌘↵ or Ctrl↵ to send)" rows="1"></textarea>
+ <button id="send">Send</button>
+ </div>
+ <div class="bl-hint">
+ <span>⌘↵ to send</span>
+ <a href="/dashboard/library#tab=brain">Set a brain for your agent &rarr;</a>
+ </div>
+ </div>
+ </div>
+ </div>
<script src="/nav.js"></script>
<script type="module">
- const ALL_PROVIDERS = [
- { key: 'anthropic', label: 'Claude Sonnet 4.6', network: 'Anthropic', defaultOn: true },
- { key: 'openai', label: 'GPT-4o-mini', network: 'OpenAI', defaultOn: true },
- { key: 'qwen-plus', label: 'Qwen Plus', network: 'Alibaba DashScope', defaultOn: true },
- { key: 'qwen-vl-max', label: 'Qwen VL Max', network: 'Alibaba DashScope', defaultOn: false },
- { key: 'modelscope-qwen', label: 'Qwen3-Coder-480B', network: 'ModelScope', defaultOn: true },
- { key: 'groq-llama', label: 'Llama 3.3 70B', network: 'Groq', defaultOn: false },
- ];
-
- const providersEl = document.getElementById('providers');
- const gridEl = document.getElementById('grid');
- const promptEl = document.getElementById('prompt');
- const systemEl = document.getElementById('system');
- const maxTokensEl = document.getElementById('maxTokens');
- const runBtn = document.getElementById('run');
- const clearBtn = document.getElementById('clear');
- const noticeEl = document.getElementById('notice');
-
- for (const p of ALL_PROVIDERS) {
- const pill = document.createElement('label');
- pill.className = 'provider-pill';
- pill.innerHTML = `
- <input type="checkbox" data-key="${p.key}" ${p.defaultOn ? 'checked' : ''}/>
- <span class="meta">
- <span class="name">${p.label}</span>
- <span class="net">${p.network}</span>
- </span>`;
- providersEl.appendChild(pill);
- }
-
- function renderCards(selected) {
- gridEl.innerHTML = '';
- for (const p of selected) {
- const card = document.createElement('div');
- card.className = 'card';
- card.dataset.key = p.key;
- card.innerHTML = `
- <div class="card-head">
- <h3 class="card-title">${p.label} <span class="spinner" data-spinner></span></h3>
- <span class="card-net">${p.network}</span>
- </div>
- <div class="card-body empty" data-body>Waiting…</div>
- <div class="card-footer" data-footer>
- <span><strong data-elapsed>—</strong> ms</span>
- <span><strong data-tokens>—</strong> tokens out</span>
- <span><strong data-tps>—</strong> tok/s</span>
- </div>`;
- gridEl.appendChild(card);
- }
+
+// ── Provider registry ─────────────────────────────────────────────────────────
+
+const PROVIDERS = [
+ { key: 'anthropic', label: 'Claude Sonnet 4.6', short: 'Claude', network: 'Anthropic', color: '#c8a96e', ctx: '200K', tier: '$$' },
+ { key: 'openai', label: 'GPT-4o-mini', short: 'GPT-4o-mini', network: 'OpenAI', color: '#74c0fc', ctx: '128K', tier: '$' },
+ { key: 'qwen-plus', label: 'Qwen Plus', short: 'Qwen+', network: 'DashScope', color: '#69db7c', ctx: '131K', tier: '$' },
+ { key: 'qwen-vl-max', label: 'Qwen VL Max', short: 'Qwen-VL', network: 'DashScope', color: '#51cf66', ctx: '32K', tier: '$$' },
+ { key: 'modelscope-qwen', label: 'Qwen3-Coder 480B', short: 'Qwen3-Code', network: 'ModelScope', color: '#40c057', ctx: '32K', tier: '$$$' },
+ { key: 'groq-llama', label: 'Llama 3.3 70B', short: 'Llama 3.3', network: 'Groq', color: '#ff9a3c', ctx: '128K', tier: 'Fast' },
+];
+const PMAP = new Map(PROVIDERS.map((p) => [p.key, p]));
+
+// ── State ─────────────────────────────────────────────────────────────────────
+
+const state = {
+ mode: 'compare',
+ focusKey: 'anthropic',
+ active: new Set(['anthropic', 'openai', 'qwen-plus', 'groq-llama']),
+ sessions: [],
+ currentId: null,
+ streaming: false,
+};
+
+// ── Local storage persistence ─────────────────────────────────────────────────
+
+function persistSessions() {
+ try { localStorage.setItem('brain_sessions_v2', JSON.stringify(state.sessions)); } catch {}
+}
+function loadSessions() {
+ try {
+ const raw = localStorage.getItem('brain_sessions_v2');
+ if (raw) state.sessions = JSON.parse(raw);
+ } catch { state.sessions = []; }
+}
+function loadMode() {
+ try {
+ const m = localStorage.getItem('brain_mode');
+ if (m === 'compare' || m === 'chat') state.mode = m;
+ } catch {}
+}
+function saveMode() {
+ try { localStorage.setItem('brain_mode', state.mode); } catch {}
+}
+
+// ── Session helpers ───────────────────────────────────────────────────────────
+
+function uuid() {
+ if (typeof crypto !== 'undefined' && crypto.randomUUID) return crypto.randomUUID();
+ return Math.random().toString(36).slice(2) + Date.now().toString(36);
+}
+
+function newSession(system = '') {
+ return {
+ id: uuid(),
+ name: 'New conversation',
+ system,
+ created: Date.now(),
+ turns: [],
+ };
+}
+
+function currentSession() {
+ return state.sessions.find((s) => s.id === state.currentId) || null;
+}
+
+function autoName(session) {
+ const first = session.turns[0]?.user;
+ if (!first) return;
+ const trimmed = first.trim().replace(/\s+/g, ' ');
+ session.name = trimmed.length > 48 ? trimmed.slice(0, 46) + '…' : trimmed;
+}
+
+// ── Markdown renderer ─────────────────────────────────────────────────────────
+
+function escHtml(s) {
+ return s.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
+}
+
+function inlineMd(s) {
+ // Bold before italic to avoid overlap
+ s = s.replace(/\*\*([^*\n]+)\*\*/g, '<strong>$1</strong>');
+ s = s.replace(/\*([^*\n]+)\*/g, '<em>$1</em>');
+ s = s.replace(/`([^`\n]+)`/g, '<code class="md-ic">$1</code>');
+ s = s.replace(/\[([^\]]+)\]\(([^)]+)\)/g, '<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>');
+ return s;
+}
+
+function renderMd(text) {
+ if (!text) return '';
+ const lines = text.split('\n');
+ const out = [];
+ let i = 0;
+
+ while (i < lines.length) {
+ const line = lines[i];
+
+ // Fenced code block
+ if (line.startsWith('```')) {
+ const lang = line.slice(3).trim();
+ const codeLines = [];
+ i++;
+ while (i < lines.length && !lines[i].startsWith('```')) {
+ codeLines.push(escHtml(lines[i]));
+ i++;
}
+ i++; // skip closing ```
+ out.push(`<pre class="md-code"><code>${codeLines.join('\n')}</code></pre>`);
+ continue;
+ }
- function selectedProviders() {
- const keys = [...providersEl.querySelectorAll('input:checked')].map((el) => el.dataset.key);
- return ALL_PROVIDERS.filter((p) => keys.includes(p.key));
- }
-
- async function streamProvider(p, body, card) {
- const bodyEl = card.querySelector('[data-body]');
- const elapsedEl = card.querySelector('[data-elapsed]');
- const tokensEl = card.querySelector('[data-tokens]');
- const tpsEl = card.querySelector('[data-tps]');
- const spinner = card.querySelector('[data-spinner]');
- bodyEl.textContent = '';
- bodyEl.classList.remove('empty', 'error');
-
- const t0 = performance.now();
- let res;
- try {
- res = await fetch('/api/brain/chat', {
- method: 'POST',
- headers: { 'content-type': 'application/json' },
- body: JSON.stringify({ ...body, provider: p.key }),
- });
- } catch (err) {
- bodyEl.classList.add('error');
- bodyEl.textContent = `Network error: ${err.message}`;
- spinner.style.display = 'none';
- return;
- }
+ // Headers
+ const hm = line.match(/^(#{1,3})\s+(.+)/);
+ if (hm) {
+ const n = hm[1].length;
+ out.push(`<h${n} class="md-h${n}">${inlineMd(escHtml(hm[2]))}</h${n}>`);
+ i++;
+ continue;
+ }
+
+ // Unordered list
+ if (/^[-*+]\s/.test(line)) {
+ const items = [];
+ while (i < lines.length && /^[-*+]\s/.test(lines[i])) {
+ items.push(`<li>${inlineMd(escHtml(lines[i].replace(/^[-*+]\s/, '')))}</li>`);
+ i++;
+ }
+ out.push(`<ul class="md-ul">${items.join('')}</ul>`);
+ continue;
+ }
+
+ // Ordered list
+ if (/^\d+\.\s/.test(line)) {
+ const items = [];
+ while (i < lines.length && /^\d+\.\s/.test(lines[i])) {
+ items.push(`<li>${inlineMd(escHtml(lines[i].replace(/^\d+\.\s/, '')))}</li>`);
+ i++;
+ }
+ out.push(`<ol class="md-ol">${items.join('')}</ol>`);
+ continue;
+ }
+
+ // Blank line
+ if (!line.trim()) { i++; continue; }
+
+ // Paragraph
+ const pLines = [];
+ while (
+ i < lines.length && lines[i].trim() &&
+ !lines[i].startsWith('#') && !lines[i].startsWith('```') &&
+ !/^[-*+]\s/.test(lines[i]) && !/^\d+\.\s/.test(lines[i])
+ ) {
+ pLines.push(inlineMd(escHtml(lines[i])));
+ i++;
+ }
+ if (pLines.length) out.push(`<p class="md-p">${pLines.join('<br>')}</p>`);
+ }
+
+ return out.join('');
+}
+
+// ── Streaming ─────────────────────────────────────────────────────────────────
+
+async function streamProvider(provKey, messages, system, { onChunk, onDone, onError, signal }) {
+ const p = PMAP.get(provKey);
+ const maxTokens = 1024;
+ let res;
+ try {
+ res = await fetch('/api/brain/chat', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ signal,
+ body: JSON.stringify({ provider: provKey, messages, system: system || undefined, maxTokens }),
+ });
+ } catch (err) {
+ if (err.name !== 'AbortError') onError?.(err.message || 'Network error');
+ return;
+ }
+
+ if (!res.ok || !res.body) {
+ const txt = await res.text().catch(() => '');
+ onError?.(`HTTP ${res.status}: ${txt || res.statusText}`);
+ return;
+ }
- if (!res.ok || !res.body) {
- const txt = await res.text().catch(() => '');
- bodyEl.classList.add('error');
- bodyEl.textContent = `HTTP ${res.status}: ${txt || res.statusText}`;
- spinner.style.display = 'none';
- return;
+ const reader = res.body.getReader();
+ const decoder = new TextDecoder();
+ let buf = '';
+ const t0 = performance.now();
+
+ try {
+ for (;;) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ buf += decoder.decode(value, { stream: true });
+ let idx;
+ while ((idx = buf.indexOf('\n\n')) !== -1) {
+ const event = buf.slice(0, idx);
+ buf = buf.slice(idx + 2);
+ let evType = 'message', data = '';
+ for (const line of event.split('\n')) {
+ if (line.startsWith('event:')) evType = line.slice(6).trim();
+ else if (line.startsWith('data:')) data += line.slice(5).trim();
+ }
+ if (evType === 'message' && data && data !== '[DONE]') {
+ try { onChunk?.(JSON.parse(data)); } catch {}
+ } else if (evType === 'done') {
+ try {
+ const info = JSON.parse(data);
+ onDone?.({ elapsedMs: info.elapsedMs, usage: info.usage });
+ } catch {}
+ } else if (evType === 'error') {
+ try { onError?.(JSON.parse(data).message || 'upstream error'); } catch {}
}
+ }
+ }
+ } finally {
+ const elapsed = Math.round(performance.now() - t0);
+ onDone?.({ elapsedMs: elapsed, usage: null });
+ }
+}
+
+// Build messages array for a given provider from session turn history
+function buildMessages(session, provKey, newUserMessage) {
+ const messages = [];
+ for (const turn of session.turns) {
+ messages.push({ role: 'user', content: turn.user });
+ const resp = turn.responses[provKey];
+ if (resp?.text) messages.push({ role: 'assistant', content: resp.text });
+ }
+ messages.push({ role: 'user', content: newUserMessage });
+ return messages;
+}
+
+// ── UI: Sidebar ───────────────────────────────────────────────────────────────
+
+function renderSidebar() {
+ const el = document.getElementById('sessions');
+ if (!state.sessions.length) {
+ el.innerHTML = `<div class="bl-empty-sessions">No sessions yet.<br>Send a message to start.</div>`;
+ return;
+ }
+ el.innerHTML = state.sessions.map((s) => `
+ <div class="bl-session-item${s.id === state.currentId ? ' active' : ''}" data-id="${escHtml(s.id)}">
+ <span class="bl-session-icon">💬</span>
+ <span class="bl-session-name">${escHtml(s.name)}</span>
+ <button class="bl-session-del" data-del="${escHtml(s.id)}" title="Delete">×</button>
+ </div>
+ `).join('');
+}
+
+// ── UI: Toolbar controls ──────────────────────────────────────────────────────
+
+function renderToolbarControls() {
+ const ctrl = document.getElementById('toolbarControls');
+ const label = document.getElementById('toolbarLabel');
+ if (state.mode === 'compare') {
+ label.textContent = 'Models';
+ ctrl.innerHTML = `<div class="bl-provider-pills">${
+ PROVIDERS.map((p) => `
+ <label class="bl-ppill${state.active.has(p.key) ? ' on' : ''}" style="--pc:${p.color}" data-key="${p.key}">
+ <input type="checkbox" ${state.active.has(p.key) ? 'checked' : ''} />
+ <span class="pc-dot"></span>
+ <span>${p.short}</span>
+ </label>
+ `).join('')
+ }</div>`;
+ } else {
+ label.textContent = 'Model';
+ ctrl.innerHTML = `<select class="bl-focus-sel" id="focusSel">${
+ PROVIDERS.map((p) => `<option value="${p.key}"${p.key === state.focusKey ? ' selected' : ''}>${p.label}</option>`).join('')
+ }</select>`;
+ }
+}
+
+// ── UI: Compare canvas ────────────────────────────────────────────────────────
+
+function renderCompareCanvas() {
+ const canvas = document.getElementById('canvas');
+ const session = currentSession();
+ const active = [...state.active];
+
+ canvas.innerHTML = `<div class="bl-compare">${
+ active.map((key) => {
+ const p = PMAP.get(key);
+ if (!p) return '';
+ return `
+ <div class="bl-col" data-col="${escHtml(key)}" style="--pc:${p.color}">
+ <div class="bl-col-head">
+ <div>
+ <div class="bl-col-name">${escHtml(p.short)}</div>
+ <div class="bl-col-net">${escHtml(p.network)} · ${escHtml(p.ctx)} · ${escHtml(p.tier)}</div>
+ </div>
+ <div style="display:flex;gap:6px;align-items:center">
+ <div class="bl-col-stats" data-stats="${escHtml(key)}"></div>
+ <button class="bl-col-copy" data-copy="${escHtml(key)}" title="Copy this conversation">Copy</button>
+ </div>
+ </div>
+ <div class="bl-col-messages" data-msgs="${escHtml(key)}">
+ ${session?.turns.length ? renderColTurns(session, key) : '<div class="bl-col-empty">Waiting for a message…</div>'}
+ </div>
+ </div>
+ `;
+ }).join('')
+ }</div>`;
+}
+
+function renderColTurns(session, provKey) {
+ const parts = [];
+ for (const turn of session.turns) {
+ parts.push(`<div class="bl-col-user">${escHtml(turn.user)}</div>`);
+ const resp = turn.responses[provKey];
+ if (resp?.text) {
+ parts.push(`<div class="bl-col-assistant">${renderMd(resp.text)}</div>`);
+ } else if (resp?.error) {
+ parts.push(`<div class="bl-col-assistant" style="color:#ff8a8a">${escHtml(resp.error)}</div>`);
+ }
+ }
+ return parts.join('');
+}
+
+// ── UI: Chat canvas ───────────────────────────────────────────────────────────
+
+function renderChatCanvas() {
+ const canvas = document.getElementById('canvas');
+ const session = currentSession();
+ const p = PMAP.get(state.focusKey);
+
+ if (!session || !session.turns.length) {
+ canvas.innerHTML = `
+ <div class="bl-chat">
+ <div class="bl-chat-empty">
+ <h3>Start a conversation</h3>
+ <p>Messages are sent to <strong style="color:${p?.color || '#fff'}">${escHtml(p?.label || state.focusKey)}</strong>. Switch to Compare mode to query all models simultaneously.</p>
+ </div>
+ </div>`;
+ return;
+ }
+
+ const msgHtml = session.turns.map((turn) => {
+ const resp = turn.responses[state.focusKey];
+ const parts = [];
+ parts.push(`
+ <div class="bl-msg user">
+ <div class="bl-msg-label">You</div>
+ <div class="bl-msg-body">${escHtml(turn.user)}</div>
+ </div>`);
+ if (resp?.text) {
+ parts.push(`
+ <div class="bl-msg assistant" style="--pc:${escHtml(p?.color || '#fff')}">
+ <div class="bl-msg-label">${escHtml(p?.short || state.focusKey)}</div>
+ <div class="bl-msg-body">${renderMd(resp.text)}</div>
+ </div>`);
+ } else if (resp?.error) {
+ parts.push(`
+ <div class="bl-msg assistant">
+ <div class="bl-msg-label" style="color:#ff8a8a">Error</div>
+ <div class="bl-msg-body" style="color:#ff8a8a">${escHtml(resp.error)}</div>
+ </div>`);
+ }
+ return parts.join('');
+ }).join('');
+
+ canvas.innerHTML = `
+ <div class="bl-chat">
+ <div class="bl-chat-messages" id="chatMessages">${msgHtml}</div>
+ </div>`;
+}
+
+function renderCanvas() {
+ if (state.mode === 'compare') renderCompareCanvas();
+ else renderChatCanvas();
+}
+
+// ── Scroll helpers ────────────────────────────────────────────────────────────
+
+function scrollColToBottom(provKey) {
+ const el = document.querySelector(`[data-msgs="${provKey}"]`);
+ if (el) el.scrollTop = el.scrollHeight;
+}
+function scrollChatToBottom() {
+ const el = document.getElementById('chatMessages');
+ if (el) el.scrollTop = el.scrollHeight;
+}
+
+// ── Send message ──────────────────────────────────────────────────────────────
+
+async function sendMessage() {
+ const promptEl = document.getElementById('prompt');
+ const systemEl = document.getElementById('system');
+ const text = promptEl.value.trim();
+ if (!text) return;
+ if (state.streaming) return;
+
+ const activeKeys = state.mode === 'compare'
+ ? [...state.active]
+ : [state.focusKey];
+
+ if (!activeKeys.length) {
+ showNotice('Select at least one model.');
+ return;
+ }
+
+ const system = systemEl.value.trim();
+ promptEl.value = '';
+ autoResizeTextarea(promptEl);
+
+ // Ensure a session exists
+ if (!state.currentId) {
+ const s = newSession(system);
+ state.sessions.unshift(s);
+ state.currentId = s.id;
+ } else {
+ // Update system prompt if changed
+ const s = currentSession();
+ if (s && !s.turns.length) s.system = system;
+ }
+
+ const session = currentSession();
+ if (!session) return;
+
+ // Add a new turn
+ const turnId = uuid();
+ const turn = { id: turnId, user: text, responses: {} };
+ session.turns.push(turn);
+ autoName(session);
+ persistSessions();
+ renderSidebar();
+
+ state.streaming = true;
+ document.getElementById('send').disabled = true;
+
+ // Render immediately (shows user message)
+ renderCanvas();
+ if (state.mode === 'compare') {
+ activeKeys.forEach(scrollColToBottom);
+ } else {
+ scrollChatToBottom();
+ }
- const reader = res.body.getReader();
- const decoder = new TextDecoder();
- let buf = '';
- let textLen = 0;
-
- try {
- for (;;) {
- const { done, value } = await reader.read();
- if (done) break;
- buf += decoder.decode(value, { stream: true });
-
- let idx;
- while ((idx = buf.indexOf('\n\n')) !== -1) {
- const event = buf.slice(0, idx);
- buf = buf.slice(idx + 2);
- const lines = event.split('\n');
- let evType = 'message';
- let data = '';
- for (const line of lines) {
- if (line.startsWith('event:')) evType = line.slice(6).trim();
- else if (line.startsWith('data:')) data += line.slice(5).trim();
- }
-
- if (evType === 'message' && data) {
- if (data === '[DONE]') continue;
- try {
- const chunk = JSON.parse(data);
- bodyEl.textContent += chunk;
- textLen += chunk.length;
- } catch {}
- } else if (evType === 'done') {
- try {
- const info = JSON.parse(data);
- elapsedEl.textContent = info.elapsedMs;
- if (info.usage?.outputTokens) {
- tokensEl.textContent = info.usage.outputTokens;
- const sec = info.elapsedMs / 1000;
- if (sec > 0) tpsEl.textContent = (info.usage.outputTokens / sec).toFixed(1);
- }
- } catch {}
- } else if (evType === 'error') {
- try {
- const info = JSON.parse(data);
- bodyEl.classList.add('error');
- bodyEl.textContent += `\n\n[error: ${info.message}]`;
- elapsedEl.textContent = info.elapsedMs;
- } catch {}
- }
- }
+ // Add streaming indicators
+ if (state.mode === 'compare') {
+ for (const key of activeKeys) {
+ const el = document.querySelector(`[data-msgs="${key}"]`);
+ if (el) {
+ const spin = document.createElement('div');
+ spin.className = 'bl-col-assistant';
+ spin.dataset.stream = key;
+ spin.innerHTML = '<span class="bl-spin"></span>';
+ el.appendChild(spin);
+ el.scrollTop = el.scrollHeight;
+ }
+ }
+ } else {
+ const msgs = document.getElementById('chatMessages');
+ if (msgs) {
+ const spin = document.createElement('div');
+ spin.className = 'bl-msg assistant';
+ spin.dataset.streamChat = state.focusKey;
+ spin.style.setProperty('--pc', PMAP.get(state.focusKey)?.color || '#fff');
+ const p = PMAP.get(state.focusKey);
+ spin.innerHTML = `<div class="bl-msg-label">${escHtml(p?.short || state.focusKey)}</div><div class="bl-msg-body"><span class="bl-spin"></span></div>`;
+ msgs.appendChild(spin);
+ msgs.scrollTop = msgs.scrollHeight;
+ }
+ }
+
+ const abortCtrl = new AbortController();
+
+ // Stream all active providers concurrently
+ await Promise.all(activeKeys.map(async (key) => {
+ const messages = buildMessages(session, key, text);
+ let accumulated = '';
+
+ return streamProvider(key, messages, system, {
+ signal: abortCtrl.signal,
+ onChunk(delta) {
+ accumulated += delta;
+ turn.responses[key] = turn.responses[key] || { text: '', elapsedMs: 0, usage: null };
+ turn.responses[key].text = accumulated;
+
+ if (state.mode === 'compare') {
+ const streamEl = document.querySelector(`[data-stream="${key}"]`);
+ if (streamEl) {
+ streamEl.innerHTML = renderMd(accumulated) + '<span class="bl-spin"></span>';
+ scrollColToBottom(key);
}
- } finally {
- spinner.style.display = 'none';
- if (!elapsedEl.textContent || elapsedEl.textContent === '—') {
- elapsedEl.textContent = Math.round(performance.now() - t0);
+ } else if (key === state.focusKey) {
+ const streamEl = document.querySelector(`[data-stream-chat="${key}"] .bl-msg-body`);
+ if (streamEl) {
+ streamEl.innerHTML = renderMd(accumulated) + '<span class="bl-spin"></span>';
+ scrollChatToBottom();
}
}
- }
+ },
+ onDone({ elapsedMs, usage }) {
+ turn.responses[key] = turn.responses[key] || {};
+ turn.responses[key].elapsedMs = elapsedMs;
+ turn.responses[key].usage = usage;
- async function run() {
- const prompt = promptEl.value.trim();
- if (!prompt) {
- noticeEl.style.display = 'block';
- noticeEl.textContent = 'Enter a prompt first.';
- return;
+ // Finalize — remove spinner, render final markdown
+ if (state.mode === 'compare') {
+ const streamEl = document.querySelector(`[data-stream="${key}"]`);
+ if (streamEl) {
+ streamEl.removeAttribute('data-stream');
+ streamEl.innerHTML = renderMd(turn.responses[key].text || '');
+ }
+ // Update stats
+ const statsEl = document.querySelector(`[data-stats="${key}"]`);
+ if (statsEl && elapsedMs) {
+ const tps = usage?.outputTokens
+ ? (usage.outputTokens / (elapsedMs / 1000)).toFixed(1)
+ : null;
+ statsEl.innerHTML = `<strong>${elapsedMs}</strong>ms${usage?.outputTokens ? ` · <strong>${usage.outputTokens}</strong>t${tps ? ` · <strong>${tps}</strong> t/s` : ''}` : ''}`;
+ }
+ } else if (key === state.focusKey) {
+ const streamEl = document.querySelector(`[data-stream-chat="${key}"]`);
+ if (streamEl) {
+ streamEl.removeAttribute('data-stream-chat');
+ const body = streamEl.querySelector('.bl-msg-body');
+ if (body) body.innerHTML = renderMd(turn.responses[key].text || '');
+ }
}
- noticeEl.style.display = 'none';
-
- const selected = selectedProviders();
- if (!selected.length) {
- noticeEl.style.display = 'block';
- noticeEl.textContent = 'Select at least one provider.';
- return;
+ persistSessions();
+ },
+ onError(msg) {
+ turn.responses[key] = { text: '', error: msg, elapsedMs: 0 };
+ if (state.mode === 'compare') {
+ const streamEl = document.querySelector(`[data-stream="${key}"]`);
+ if (streamEl) {
+ streamEl.removeAttribute('data-stream');
+ streamEl.innerHTML = `<span style="color:#ff8a8a">${escHtml(msg)}</span>`;
+ }
+ } else if (key === state.focusKey) {
+ const streamEl = document.querySelector(`[data-stream-chat="${key}"]`);
+ if (streamEl) {
+ streamEl.removeAttribute('data-stream-chat');
+ const body = streamEl.querySelector('.bl-msg-body');
+ if (body) { body.style.color = '#ff8a8a'; body.textContent = msg; }
+ }
}
+ persistSessions();
+ },
+ });
+ }));
- renderCards(selected);
- runBtn.disabled = true;
- const body = {
- messages: [{ role: 'user', content: prompt }],
- system: systemEl.value.trim() || undefined,
- maxTokens: Math.min(Math.max(Number(maxTokensEl.value) || 512, 32), 4096),
- };
- try {
- await Promise.all(selected.map((p) => {
- const card = gridEl.querySelector(`[data-key="${p.key}"]`);
- return streamProvider(p, body, card);
- }));
- } finally {
- runBtn.disabled = false;
- }
- }
+ state.streaming = false;
+ document.getElementById('send').disabled = false;
+}
+
+// ── Export ────────────────────────────────────────────────────────────────────
+
+function exportSession() {
+ const session = currentSession();
+ if (!session || !session.turns.length) { showNotice('Nothing to export yet.'); return; }
+
+ const lines = [`# ${session.name}\n`];
+ const provKeys = state.mode === 'compare' ? [...state.active] : [state.focusKey];
+
+ for (const turn of session.turns) {
+ lines.push(`**You:** ${turn.user}\n`);
+ for (const key of provKeys) {
+ const p = PMAP.get(key);
+ const r = turn.responses[key];
+ if (!r) continue;
+ lines.push(`**${p?.label || key}:**\n${r.text || r.error || ''}\n`);
+ }
+ lines.push('---\n');
+ }
+
+ const blob = new Blob([lines.join('\n')], { type: 'text/markdown' });
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement('a');
+ a.href = url;
+ a.download = `brain-${Date.now()}.md`;
+ a.click();
+ URL.revokeObjectURL(url);
+}
+
+// ── Notice ────────────────────────────────────────────────────────────────────
+
+function showNotice(msg) {
+ const el = document.getElementById('notice');
+ el.textContent = msg;
+ el.style.display = 'block';
+ clearTimeout(el._t);
+ el._t = setTimeout(() => { el.style.display = 'none'; }, 3000);
+}
+
+// ── Textarea auto-resize ──────────────────────────────────────────────────────
+
+function autoResizeTextarea(el) {
+ el.style.height = 'auto';
+ el.style.height = Math.min(el.scrollHeight, 160) + 'px';
+}
- runBtn.addEventListener('click', run);
- clearBtn.addEventListener('click', () => {
- gridEl.innerHTML = '';
- noticeEl.style.display = 'none';
+// ── Copy to clipboard ─────────────────────────────────────────────────────────
+
+function copyProvider(key) {
+ const session = currentSession();
+ if (!session) return;
+ const p = PMAP.get(key);
+ const lines = [`# ${p?.label || key}\n`];
+ for (const turn of session.turns) {
+ lines.push(`**You:** ${turn.user}\n`);
+ const r = turn.responses[key];
+ if (r?.text) lines.push(r.text + '\n');
+ }
+ navigator.clipboard.writeText(lines.join('\n')).then(() => showNotice('Copied to clipboard'));
+}
+
+// ── Switch session ────────────────────────────────────────────────────────────
+
+function loadSession(id) {
+ state.currentId = id;
+ const s = state.sessions.find((x) => x.id === id);
+ if (s) {
+ document.getElementById('system').value = s.system || '';
+ }
+ renderSidebar();
+ renderCanvas();
+}
+
+function deleteSession(id) {
+ state.sessions = state.sessions.filter((s) => s.id !== id);
+ if (state.currentId === id) {
+ state.currentId = state.sessions[0]?.id || null;
+ }
+ persistSessions();
+ renderSidebar();
+ renderCanvas();
+}
+
+// ── Switch mode ───────────────────────────────────────────────────────────────
+
+function setMode(m) {
+ state.mode = m;
+ saveMode();
+ document.querySelectorAll('.bl-mode-btn').forEach((b) => {
+ b.classList.toggle('active', b.dataset.mode === m);
+ });
+ renderToolbarControls();
+ bindToolbarEvents();
+ renderCanvas();
+}
+
+// ── Bind events ───────────────────────────────────────────────────────────────
+
+function bindToolbarEvents() {
+ if (state.mode === 'compare') {
+ document.querySelectorAll('.bl-ppill').forEach((pill) => {
+ pill.addEventListener('click', () => {
+ const key = pill.dataset.key;
+ if (state.active.has(key)) {
+ if (state.active.size > 1) state.active.delete(key);
+ } else {
+ state.active.add(key);
+ }
+ pill.classList.toggle('on', state.active.has(key));
+ renderCanvas();
});
- promptEl.addEventListener('keydown', (e) => {
- if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) run();
+ });
+ } else {
+ const sel = document.getElementById('focusSel');
+ if (sel) {
+ sel.addEventListener('change', () => {
+ state.focusKey = sel.value;
+ renderCanvas();
});
+ }
+ }
+}
+
+function bindEvents() {
+ // Mode toggle
+ document.querySelectorAll('.bl-mode-btn').forEach((b) => {
+ b.addEventListener('click', () => setMode(b.dataset.mode));
+ });
+
+ // Send
+ document.getElementById('send').addEventListener('click', sendMessage);
+ document.getElementById('prompt').addEventListener('keydown', (e) => {
+ if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) {
+ e.preventDefault();
+ sendMessage();
+ }
+ });
+ document.getElementById('prompt').addEventListener('input', function() {
+ autoResizeTextarea(this);
+ });
+
+ // New chat
+ document.getElementById('newChat').addEventListener('click', () => {
+ const s = newSession(document.getElementById('system').value.trim());
+ state.sessions.unshift(s);
+ state.currentId = s.id;
+ document.getElementById('system').value = '';
+ persistSessions();
+ renderSidebar();
+ renderCanvas();
+ });
+
+ // Export
+ document.getElementById('exportBtn').addEventListener('click', exportSession);
+
+ // Session list (delegated)
+ document.getElementById('sessions').addEventListener('click', (e) => {
+ const del = e.target.closest('[data-del]');
+ if (del) { deleteSession(del.dataset.del); return; }
+ const item = e.target.closest('[data-id]');
+ if (item) loadSession(item.dataset.id);
+ });
+
+ // Canvas clicks (delegated)
+ document.getElementById('canvas').addEventListener('click', (e) => {
+ const copy = e.target.closest('[data-copy]');
+ if (copy) { copyProvider(copy.dataset.copy); }
+ });
+
+ bindToolbarEvents();
+}
+
+// ── Boot ──────────────────────────────────────────────────────────────────────
+
+loadSessions();
+loadMode();
+
+// Set active mode button
+document.querySelectorAll('.bl-mode-btn').forEach((b) => {
+ b.classList.toggle('active', b.dataset.mode === state.mode);
+});
+
+renderToolbarControls();
+renderSidebar();
+renderCanvas();
+bindEvents();
+
+// Restore system prompt if there's an active session
+const active = currentSession();
+if (active?.system) document.getElementById('system').value = active.system;
+
</script>
</body>
</html>
diff --git a/public/demos/halfbody-xr.html b/public/demos/halfbody-xr.html
index 01059ad74..ac393823a 100644
--- a/public/demos/halfbody-xr.html
+++ b/public/demos/halfbody-xr.html
@@ -25,7 +25,7 @@
.viewer-label {
position: absolute; top: 12px; left: 12px;
background: rgba(0,0,0,0.55); padding: 4px 10px; border-radius: 999px;
- font-size: 12px; color: #3dc1ff; font-weight: 600;
+ font-size: 12px; color: #3dc1ff; font-weight: 600; z-index: 1;
}
.controls {
margin-top: 24px;
@@ -36,9 +36,11 @@
button {
background: #3dc1ff; color: #0a0a0a; border: 0; border-radius: 9px;
padding: 10px 14px; font-weight: 600; cursor: pointer; font: inherit;
+ transition: opacity 0.15s;
}
button.secondary { background: rgba(255,255,255,0.06); color: #eee; }
button:disabled { opacity: 0.4; cursor: not-allowed; }
+ button.active { background: #ff6b6b; color: #fff; }
.log {
margin-top: 16px;
background: #07080d; border: 1px solid #1e1f2b; border-radius: 9px;
@@ -48,6 +50,16 @@
.log .ok { color: #3dc1ff; }
.log .err { color: #ff6b6b; }
.log .info { color: #66d9ef; }
+ .xr-link {
+ display: inline-flex; align-items: center; gap: 6px;
+ background: linear-gradient(135deg, #1a1b2e, #12132a);
+ border: 1.5px solid rgba(61,193,255,0.3); border-radius: 12px;
+ padding: 14px 20px; text-decoration: none; color: #3dc1ff;
+ font-weight: 600; font-size: 14px; margin-top: 4px;
+ transition: border-color 0.15s, box-shadow 0.15s;
+ }
+ .xr-link:hover { border-color: rgba(61,193,255,0.6); box-shadow: 0 0 20px rgba(61,193,255,0.12); }
+ .xr-link svg { flex-shrink: 0; }
</style>
</head>
<body>
@@ -75,11 +87,20 @@
</div>
<div class="controls">
- <button id="enter-xr-full" class="secondary">Enter WebXR · full body</button>
- <button id="enter-xr-half">Enter WebXR · half body</button>
+ <button id="enter-xr-full" class="secondary" disabled>Enter WebXR · full body</button>
+ <button id="enter-xr-half" disabled>Enter WebXR · half body</button>
<button id="reload" class="secondary">Reload models</button>
</div>
<div class="log" id="log">ready.</div>
+
+ <a href="/xr" class="xr-link" style="margin-top:24px;display:inline-flex">
+ <svg width="16" height="16" viewBox="0 0 16 16" fill="none">
+ <path d="M1 5.5C1 4.12 2.12 3 3.5 3h9C13.88 3 15 4.12 15 5.5v5c0 1.38-1.12 2.5-2.5 2.5h-9C2.12 13 1 11.88 1 10.5v-5Z" stroke="#3dc1ff" stroke-width="1.3"/>
+ <circle cx="5.5" cy="8" r="1.5" fill="#3dc1ff"/>
+ <circle cx="10.5" cy="8" r="1.5" fill="#3dc1ff"/>
+ </svg>
+ Open full XR experience →
+ </a>
</main>
<script src="/nav.js" defer></script>
@@ -87,6 +108,9 @@
import * as THREE from 'three';
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
+ import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';
+ import { AnimationManager } from '/src/animation-manager.js';
+ import { WebXRSession } from '/src/ar/webxr.js';
const $ = (id) => document.getElementById(id);
const log = $('log');
@@ -98,38 +122,70 @@
const LOWER_BODY_FRAGMENTS = ['upleg','leg','thigh','knee','shin','calf','foot','toe','ankle'];
const normalizeBone = (n) => String(n||'').toLowerCase()
- .replace(/^mixamorig:?_?/,'')
- .replace(/^cc_base_/,'')
- .replace(/^armature[:_|]/,'')
- .replace(/^rig[:_]/,'');
+ .replace(/^mixamorig:?_?/,'').replace(/^cc_base_/,'').replace(/^armature[:_|]/,'').replace(/^rig[:_]/,'');
const isLowerBody = (n) => LOWER_BODY_FRAGMENTS.some((f) => normalizeBone(n).includes(f));
- function buildPreview(container) {
- const w = container.clientWidth, h = container.clientHeight;
+ // Build a full viewer shim compatible with WebXRSession
+ function buildViewer(container) {
+ const w = container.clientWidth, h = Math.max(container.clientHeight, 420);
const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: true });
- renderer.setPixelRatio(window.devicePixelRatio);
+ renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(w, h);
renderer.outputColorSpace = THREE.SRGBColorSpace;
+ renderer.shadowMap.enabled = true;
+ renderer.shadowMap.type = THREE.PCFSoftShadowMap;
container.appendChild(renderer.domElement);
const scene = new THREE.Scene();
+ const pmrem = new THREE.PMREMGenerator(renderer);
+ scene.environment = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;
+
const camera = new THREE.PerspectiveCamera(35, w/h, 0.01, 100);
camera.position.set(0, 1.4, 2.6);
const controls = new OrbitControls(camera, renderer.domElement);
controls.target.set(0, 1, 0);
controls.enableDamping = true;
- scene.add(new THREE.HemisphereLight(0xffffff, 0x404060, 1.0));
- const dir = new THREE.DirectionalLight(0xffffff, 1.2);
+ scene.add(new THREE.HemisphereLight(0xbcd6ff, 0x202830, 0.7));
+ const dir = new THREE.DirectionalLight(0xffffff, 1.4);
dir.position.set(2, 4, 3);
+ dir.castShadow = true;
+ dir.shadow.mapSize.set(512, 512);
scene.add(dir);
- function tick() {
- requestAnimationFrame(tick);
+ const animMgr = new AnimationManager();
+
+ // Viewer shim that WebXRSession expects
+ const viewer = {
+ renderer, scene, camera, controls,
+ content: null,
+ mixer: null,
+ animationManager: animMgr,
+ _afterAnimateHooks: [],
+ _rafId: null,
+ prevTime: null,
+ activeCamera: camera,
+ _needsRender: true,
+ _updateRenderLoop() { startTick(viewer); },
+ };
+
+ function tick(time) {
+ viewer._rafId = requestAnimationFrame(tick);
+ const dt = viewer.prevTime ? (time - viewer.prevTime) / 1000 : 0.016;
+ viewer.prevTime = time;
+ if (viewer.mixer) viewer.mixer.update(dt);
+ viewer.animationManager.update(dt);
+ for (const hook of viewer._afterAnimateHooks) hook(dt);
controls.update();
renderer.render(scene, camera);
}
- tick();
+
+ function startTick(v) {
+ if (v._rafId !== null) return;
+ v._rafId = requestAnimationFrame(tick);
+ }
+
+ startTick(viewer);
window.addEventListener('resize', () => {
const w2 = container.clientWidth, h2 = container.clientHeight;
@@ -138,18 +194,26 @@
camera.updateProjectionMatrix();
});
- return { scene, renderer, camera, controls };
+ return viewer;
}
- const fullView = buildPreview($('viewer-full'));
- const halfView = buildPreview($('viewer-half'));
+ const fullViewer = buildViewer($('viewer-full'));
+ const halfViewer = buildViewer($('viewer-half'));
- async function loadInto(view, applyHalfBody) {
+ async function loadInto(viewer, applyHalfBody) {
const loader = new GLTFLoader();
- logLine(`loading /avatars/default.glb into ${applyHalfBody ? 'half-body' : 'full-body'} viewer…`, 'info');
+ logLine(`loading avatar into ${applyHalfBody ? 'half-body' : 'full-body'} viewer…`, 'info');
const gltf = await loader.loadAsync('/avatars/default.glb');
const root = gltf.scene;
- view.scene.add(root);
+ viewer.scene.add(root);
+ viewer.content = root;
+
+ // Attach animations
+ await viewer.animationManager.loadAll();
+ viewer.animationManager.attach(root);
+ viewer.mixer = viewer.animationManager.mixer;
+ viewer.animationManager.play('idle');
+
if (applyHalfBody) {
let hidden = 0;
root.traverse((obj) => {
@@ -170,40 +234,74 @@
}
}
- $('reload').addEventListener('click', () => location.reload());
-
- $('enter-xr-full').addEventListener('click', async () => {
- if (!navigator.xr) return logLine('WebXR unavailable in this browser', 'err');
- const supported = await navigator.xr.isSessionSupported('immersive-ar').catch(() => false);
- if (!supported) return logLine('immersive-ar not supported on this device', 'err');
- logLine('starting full-body XR — open this URL on a Quest browser or Android Chrome to enter the headset', 'info');
- try {
- const session = await navigator.xr.requestSession('immersive-ar');
- logLine('XR session started · full body', 'ok');
- session.addEventListener('end', () => logLine('XR session ended', 'info'));
- } catch (err) {
- logLine('XR request failed: ' + err.message, 'err');
+ // Detect XR support and enable buttons
+ async function detectXRSupport() {
+ const supported = !!(navigator.xr && await navigator.xr.isSessionSupported('immersive-ar').catch(() => false));
+ if (supported) {
+ logLine('WebXR immersive-ar supported on this device', 'ok');
+ $('enter-xr-full').disabled = false;
+ $('enter-xr-half').disabled = false;
+ } else {
+ logLine('WebXR immersive-ar not available — try this on a Quest or Android Chrome', 'info');
+ $('enter-xr-full').disabled = true;
+ $('enter-xr-full').title = 'WebXR not available on this device';
+ $('enter-xr-half').disabled = true;
+ $('enter-xr-half').title = 'WebXR not available on this device';
}
- });
+ }
+
+ // XR session state
+ let xrSessionFull = null;
+ let xrSessionHalf = null;
- $('enter-xr-half').addEventListener('click', async () => {
- if (!navigator.xr) return logLine('WebXR unavailable in this browser', 'err');
- const supported = await navigator.xr.isSessionSupported('immersive-ar').catch(() => false);
- if (!supported) return logLine('immersive-ar not supported on this device', 'err');
- logLine('starting half-body XR — lower-body bones will be collapsed for the duration of the session', 'info');
+ async function toggleXR(viewer, halfBody, btn, sessionRef, setSession) {
+ if (sessionRef) {
+ await sessionRef.end();
+ setSession(null);
+ btn.classList.remove('active');
+ btn.textContent = halfBody ? 'Enter WebXR · half body' : 'Enter WebXR · full body';
+ return;
+ }
+ btn.disabled = true;
+ btn.textContent = 'Starting…';
try {
- const session = await navigator.xr.requestSession('immersive-ar');
- logLine('XR session started · half body', 'ok');
- session.addEventListener('end', () => logLine('XR session ended', 'info'));
+ const session = new WebXRSession(viewer, {
+ halfBody,
+ onEnd: () => {
+ setSession(null);
+ btn.classList.remove('active');
+ btn.textContent = halfBody ? 'Enter WebXR · half body' : 'Enter WebXR · full body';
+ btn.disabled = false;
+ },
+ });
+ await session.start();
+ setSession(session);
+ btn.classList.add('active');
+ btn.textContent = halfBody ? 'Exit XR · half body' : 'Exit XR · full body';
+ logLine(`XR session started · ${halfBody ? 'half body' : 'full body'}`, 'ok');
} catch (err) {
logLine('XR request failed: ' + err.message, 'err');
}
- });
+ btn.disabled = false;
+ }
+
+ $('enter-xr-full').addEventListener('click', () =>
+ toggleXR(fullViewer, false, $('enter-xr-full'), xrSessionFull,
+ (s) => { xrSessionFull = s; }));
+
+ $('enter-xr-half').addEventListener('click', () =>
+ toggleXR(halfViewer, true, $('enter-xr-half'), xrSessionHalf,
+ (s) => { xrSessionHalf = s; }));
+
+ $('reload').addEventListener('click', () => location.reload());
(async () => {
try {
- await loadInto(fullView, false);
- await loadInto(halfView, true);
+ await Promise.all([
+ loadInto(fullViewer, false),
+ loadInto(halfViewer, true),
+ ]);
+ await detectXRSupport();
} catch (err) {
logLine('load failed: ' + err.message, 'err');
}
diff --git a/public/footer.css b/public/footer.css
index 8b6714ad7..290a059ce 100644
--- a/public/footer.css
+++ b/public/footer.css
@@ -501,7 +501,7 @@
}
.h-footer-horizon a:focus-visible {
- outline: 2px solid #ffd76a;
+ outline: 2px solid rgba(255, 255, 255, 0.5);
outline-offset: 3px;
border-radius: 4px;
}
diff --git a/public/gallery/gallery.css b/public/gallery/gallery.css
index a5bf2bf4b..46dc2125e 100644
--- a/public/gallery/gallery.css
+++ b/public/gallery/gallery.css
@@ -113,6 +113,41 @@ body.gallery-page {
line-height: 1.6;
}
+.gallery-hero-ctas {
+ display: flex;
+ justify-content: center;
+ gap: 12px;
+ flex-wrap: wrap;
+ margin-top: 28px;
+}
+.gallery-hero-btn {
+ display: inline-flex;
+ align-items: center;
+ padding: 10px 20px;
+ border-radius: 99px;
+ border: 1px solid rgba(255, 255, 255, 0.18);
+ background: rgba(255, 255, 255, 0.05);
+ color: rgba(255, 255, 255, 0.9);
+ font-size: 13.5px;
+ font-weight: 600;
+ text-decoration: none;
+ transition: background 0.15s ease, border-color 0.15s ease, color 0.15s ease;
+}
+.gallery-hero-btn:hover {
+ background: rgba(255, 255, 255, 0.1);
+ border-color: rgba(255, 255, 255, 0.35);
+ color: #fff;
+}
+.gallery-hero-btn--primary {
+ background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%);
+ border-color: transparent;
+ color: #fff;
+}
+.gallery-hero-btn--primary:hover {
+ background: linear-gradient(135deg, #7c7ff5 0%, #9f7af2 100%);
+ color: #fff;
+}
+
.gallery-stats {
display: flex;
justify-content: center;
@@ -148,14 +183,43 @@ body.gallery-page {
gap: 16px;
margin: 24px 0 28px;
}
+.gallery-controls-top {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+ flex-wrap: wrap;
+ justify-content: center;
+}
+.gallery-sort-select {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ color: rgba(255, 255, 255, 0.55);
+ font-size: 13px;
+}
+.gallery-sort-select select {
+ padding: 12px 12px;
+ background: rgba(255, 255, 255, 0.04);
+ border: 1px solid rgba(255, 255, 255, 0.1);
+ border-radius: 14px;
+ color: #fff;
+ font: inherit;
+ font-size: 14px;
+ outline: none;
+ cursor: pointer;
+ transition: border-color 0.15s ease;
+}
+.gallery-sort-select select:focus {
+ border-color: rgba(165, 180, 252, 0.55);
+}
.gallery-search {
position: relative;
display: flex;
align-items: center;
- max-width: 560px;
- margin: 0 auto;
- width: 100%;
+ flex: 1;
+ min-width: 220px;
+ max-width: 520px;
}
.gallery-search-icon {
position: absolute;
@@ -355,6 +419,21 @@ body.gallery-page {
transform: translate(-50%, -50%) scale(1);
}
+.gallery-card-mv {
+ width: 100%;
+ height: 100%;
+ display: block;
+ background: transparent;
+ pointer-events: none;
+ --poster-color: transparent;
+ --progress-bar-color: rgba(255, 255, 255, 0.4);
+ --progress-bar-height: 2px;
+}
+.gallery-card-views {
+ font-size: 11px;
+ color: rgba(255, 255, 255, 0.5);
+ font-variant-numeric: tabular-nums;
+}
.gallery-card-body {
display: flex;
flex-direction: column;
@@ -453,6 +532,16 @@ body.gallery-page {
border-color: rgba(255, 255, 255, 0.24);
color: #fff;
}
+.gallery-card-btn--ghost {
+ background: transparent;
+ border-color: rgba(255, 255, 255, 0.1);
+ color: rgba(255, 255, 255, 0.7);
+}
+.gallery-card-btn--ghost:hover {
+ background: rgba(255, 255, 255, 0.07);
+ border-color: rgba(255, 255, 255, 0.22);
+ color: #fff;
+}
.gallery-card-btn--primary {
background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%);
border-color: transparent;
@@ -622,11 +711,43 @@ body.gallery-page {
.gallery-stats {
gap: 24px;
}
+ .gallery-hero-ctas {
+ gap: 8px;
+ }
+ .gallery-hero-btn {
+ font-size: 12px;
+ padding: 9px 16px;
+ }
+ .gallery-controls-top {
+ flex-direction: column;
+ align-items: stretch;
+ }
+ .gallery-search {
+ max-width: 100%;
+ }
+ .gallery-sort-select {
+ justify-content: center;
+ }
.gallery-grid {
grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
gap: 12px;
}
- .gallery-card-body {
+ .gallery-card-mv {
+ width: 100%;
+ height: 100%;
+ display: block;
+ background: transparent;
+ pointer-events: none;
+ --poster-color: transparent;
+ --progress-bar-color: rgba(255, 255, 255, 0.4);
+ --progress-bar-height: 2px;
+}
+.gallery-card-views {
+ font-size: 11px;
+ color: rgba(255, 255, 255, 0.5);
+ font-variant-numeric: tabular-nums;
+}
+.gallery-card-body {
padding: 10px 12px 12px;
gap: 6px;
}
diff --git a/public/gallery/gallery.js b/public/gallery/gallery.js
index e911dbb2d..df809f2dc 100644
--- a/public/gallery/gallery.js
+++ b/public/gallery/gallery.js
@@ -311,20 +311,41 @@ function renderCard(a) {
const studioUrl = `/studio?avatar=${encodeURIComponent(a.id)}`;
const thumbSrc = a.thumbnail_url || `/api/avatars/${encodeURIComponent(a.id)}/og`;
- const thumb = `<img src="${escapeAttr(thumbSrc)}" alt="${escapeAttr(a.name || 'Avatar')}" loading="lazy" decoding="async" />`;
+ const views = a.view_count != null ? Number(a.view_count) : 0;
+ const created = formatRelative(a.created_at);
+
+ // Use model-viewer for 3D inline preview if GLB is available, else static thumbnail
+ const thumbContent = glbUrl
+ ? `<model-viewer
+ src="${escapeAttr(glbUrl)}"
+ alt="${escapeAttr(a.name || 'Avatar')}"
+ class="gallery-card-mv"
+ reveal="auto"
+ loading="lazy"
+ disable-zoom
+ disable-pan
+ disable-tap
+ interaction-prompt="none"
+ camera-controls="false"
+ auto-rotate
+ rotation-per-second="18deg"
+ environment-image="neutral"
+ shadow-intensity="0"
+ exposure="1"
+ poster="${escapeAttr(thumbSrc)}"
+ ></model-viewer>`
+ : `<img src="${escapeAttr(thumbSrc)}" alt="${escapeAttr(a.name || 'Avatar')}" loading="lazy" decoding="async" />`;
const tagChips = (a.tags || [])
.slice(0, 3)
- .map(
- (t) => `<span class="gallery-card-tag">${escapeHtml(t)}</span>`,
- )
+ .map((t) => `<span class="gallery-card-tag">${escapeHtml(t)}</span>`)
.join('');
- const created = formatRelative(a.created_at);
+ const viewsLabel = views >= 1 ? `${formatCompact(views)} view${views === 1 ? '' : 's'}` : '';
card.innerHTML = `
- <a class="gallery-card-thumb" href="${escapeAttr(detailUrl)}" aria-label="${escapeAttr(a.name || 'Avatar')} details">
- ${thumb}
+ <a class="gallery-card-thumb" href="${escapeAttr(viewerUrl)}" aria-label="View ${escapeAttr(a.name || 'Avatar')} in 3D viewer">
+ ${thumbContent}
<span class="gallery-card-3dpill">3D</span>
<span class="gallery-card-play" aria-hidden="true">▶</span>
</a>
@@ -334,10 +355,14 @@ function renderCard(a) {
${tagChips ? `<div class="gallery-card-tags">${tagChips}</div>` : ''}
<div class="gallery-card-foot">
<span class="gallery-card-meta">
+ ${viewsLabel ? `<span class="gallery-card-views">${escapeHtml(viewsLabel)}</span>` : ''}
<span title="${escapeAttr(new Date(a.created_at || Date.now()).toLocaleString())}">${escapeHtml(created)}</span>
</span>
<div class="gallery-card-actions">
- <a class="gallery-card-btn" href="${escapeAttr(viewerUrl)}" title="Open in viewer">View 3D</a>
+ <button type="button" class="gallery-card-btn gallery-card-btn--ghost" data-role="card-embed"
+ data-avatar-id="${escapeAttr(String(a.id))}"
+ data-glb-url="${escapeAttr(glbUrl)}"
+ data-name="${escapeAttr(a.name || 'Avatar')}">Embed</button>
<a class="gallery-card-btn gallery-card-btn--primary" href="${escapeAttr(studioUrl)}" title="Use in Widget Studio">Use</a>
</div>
</div>
@@ -378,4 +403,117 @@ function escapeAttr(s) {
return escapeHtml(s).replace(/'/g, '&#39;');
}
+// ─── Embed modal ──────────────────────────────────────────────────────────
+const LIB_CDN_URL = 'https://three.ws/agent-3d/latest/agent-3d.js';
+
+function openAvatarEmbedModal({ avatarId, glbUrl, name }) {
+ document.querySelector('.gallery-embed-modal')?.remove();
+ const origin = location.origin;
+ const viewerUrl = glbUrl ? `${origin}/app#model=${encodeURIComponent(glbUrl)}` : `${origin}/avatars/${avatarId}`;
+ const apiUrl = `${origin}/api/avatars/${avatarId}`;
+ const displayName = name || 'Avatar';
+
+ const snippets = {
+ webComponent: `<script type="module" src="${LIB_CDN_URL}"><\/script>\n<agent-3d src="${apiUrl}" mode="inline" width="480px" responsive></agent-3d>`,
+ iframe: `<iframe src="${viewerUrl}" width="480" height="600" style="border:0;border-radius:12px" allow="autoplay; xr-spatial-tracking" sandbox="allow-scripts allow-same-origin allow-popups" title="${displayName}"></iframe>`,
+ link: viewerUrl,
+ markdown: `[${displayName}](${viewerUrl})`,
+ };
+
+ const modal = document.createElement('div');
+ modal.className = 'gallery-embed-modal embed-modal';
+ modal.setAttribute('role', 'dialog');
+ modal.setAttribute('aria-modal', 'true');
+ modal.innerHTML = `
+ <div class="embed-modal__backdrop" data-role="close"></div>
+ <div class="embed-modal__panel" role="document">
+ <header class="embed-modal__head">
+ <div>
+ <h2 class="embed-modal__title">Embed ${escapeHtml(displayName)}</h2>
+ <p class="embed-modal__sub">Public avatar — drop it in any page or doc.</p>
+ </div>
+ <button type="button" class="embed-modal__close" data-role="close" aria-label="Close">×</button>
+ </header>
+ <div class="embed-modal__tabs" role="tablist">
+ <button type="button" class="embed-tab is-active" data-tab="webComponent" role="tab" aria-selected="true">Web component</button>
+ <button type="button" class="embed-tab" data-tab="iframe" role="tab" aria-selected="false">iframe</button>
+ <button type="button" class="embed-tab" data-tab="link" role="tab" aria-selected="false">Link</button>
+ <button type="button" class="embed-tab" data-tab="markdown" role="tab" aria-selected="false">Markdown</button>
+ </div>
+ <div class="embed-modal__body">
+ <div class="embed-pane is-active" data-pane="webComponent">
+ <p class="embed-pane__hint">Full fidelity via the &lt;agent-3d&gt; web component.</p>
+ <textarea class="embed-snippet" readonly rows="3">${escapeHtml(snippets.webComponent)}</textarea>
+ <button type="button" class="embed-copy-btn" data-role="copy" data-key="webComponent">Copy</button>
+ </div>
+ <div class="embed-pane" data-pane="iframe">
+ <p class="embed-pane__hint">Works in Notion, Substack, Ghost, blogs.</p>
+ <textarea class="embed-snippet" readonly rows="3">${escapeHtml(snippets.iframe)}</textarea>
+ <button type="button" class="embed-copy-btn" data-role="copy" data-key="iframe">Copy</button>
+ </div>
+ <div class="embed-pane" data-pane="link">
+ <p class="embed-pane__hint">Direct link to the viewer.</p>
+ <input class="embed-snippet embed-snippet--input" readonly value="${escapeAttr(snippets.link)}" />
+ <button type="button" class="embed-copy-btn" data-role="copy" data-key="link">Copy</button>
+ </div>
+ <div class="embed-pane" data-pane="markdown">
+ <p class="embed-pane__hint">For READMEs and Markdown blogs.</p>
+ <textarea class="embed-snippet" readonly rows="2">${escapeHtml(snippets.markdown)}</textarea>
+ <button type="button" class="embed-copy-btn" data-role="copy" data-key="markdown">Copy</button>
+ </div>
+ </div>
+ <footer class="embed-modal__foot">
+ <a href="${escapeAttr(viewerUrl)}" target="_blank" rel="noopener" class="embed-foot-link">Open viewer ↗</a>
+ <a href="${escapeAttr(`${origin}/avatars/${avatarId}`)}" target="_blank" rel="noopener" class="embed-foot-link">Avatar details ↗</a>
+ </footer>
+ </div>
+ `;
+ document.body.appendChild(modal);
+
+ const close = () => {
+ modal.remove();
+ document.removeEventListener('keydown', onEsc);
+ };
+ const onEsc = (e) => { if (e.key === 'Escape') close(); };
+ document.addEventListener('keydown', onEsc);
+ modal.querySelectorAll('[data-role="close"]').forEach((el) => el.addEventListener('click', close));
+
+ modal.querySelectorAll('.embed-tab').forEach((tab) => {
+ tab.addEventListener('click', () => {
+ modal.querySelectorAll('.embed-tab').forEach((t) => {
+ t.classList.toggle('is-active', t === tab);
+ t.setAttribute('aria-selected', t === tab ? 'true' : 'false');
+ });
+ modal.querySelectorAll('.embed-pane').forEach((p) => {
+ p.classList.toggle('is-active', p.dataset.pane === tab.dataset.tab);
+ });
+ });
+ });
+
+ modal.querySelectorAll('[data-role="copy"]').forEach((btn) => {
+ btn.addEventListener('click', () => {
+ const key = btn.dataset.key;
+ const text = snippets[key];
+ if (!text) return;
+ const done = (ok) => {
+ btn.textContent = ok ? 'Copied ✓' : 'Copy failed';
+ setTimeout(() => (btn.textContent = 'Copy'), 1400);
+ };
+ if (navigator.clipboard?.writeText) {
+ navigator.clipboard.writeText(text).then(() => done(true), () => done(false));
+ } else {
+ const ta = modal.querySelector(`[data-pane="${key}"] .embed-snippet`);
+ ta?.select();
+ try { document.execCommand('copy'); done(true); } catch { done(false); }
+ }
+ });
+ });
+
+ setTimeout(() => {
+ const first = modal.querySelector('.embed-pane.is-active .embed-snippet');
+ first?.focus();
+ first?.select?.();
+ }, 50);
+}
+
resetAndLoad();
diff --git a/public/marketplace.css b/public/marketplace.css
index 1c6c65a47..9e3b477ae 100644
--- a/public/marketplace.css
+++ b/public/marketplace.css
@@ -2400,6 +2400,34 @@ body.market-page {
.card-heart:hover { color: #f87171; transform: scale(1.15); }
.card-heart.active { color: #f87171; }
+.card-star {
+ position: absolute;
+ top: 8px;
+ left: 8px;
+ z-index: 3;
+ background: rgba(0,0,0,0.5);
+ backdrop-filter: blur(4px);
+ border: 1px solid rgba(255,255,255,0.1);
+ color: rgba(255,255,255,0.5);
+ font-size: 16px;
+ width: 30px;
+ height: 30px;
+ border-radius: 50%;
+ cursor: pointer;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ padding: 0;
+ transition: color 0.15s, transform 0.1s, background 0.15s;
+ opacity: 0;
+}
+.market-card-agent:hover .card-star { opacity: 1; }
+.card-star.on {
+ color: #fde047;
+ opacity: 1;
+}
+.card-star:hover { color: #fde047; transform: scale(1.1); background: rgba(0,0,0,0.7); }
+
/* ── Featured badge on cards ────────────────────────────────────── */
.card-featured-badge {
diff --git a/public/nav.css b/public/nav.css
index 5a7723a71..a76b4b745 100644
--- a/public/nav.css
+++ b/public/nav.css
@@ -4,16 +4,13 @@
.site-header {
position: relative;
- background:
- radial-gradient(120% 180% at 50% -40%, rgba(139, 92, 246, 0.18), transparent 55%),
- linear-gradient(180deg, rgba(10, 8, 18, 0.78) 0%, rgba(6, 6, 12, 0.82) 100%);
- backdrop-filter: blur(22px) saturate(160%);
- -webkit-backdrop-filter: blur(22px) saturate(160%);
- border-bottom: 1px solid rgba(167, 139, 250, 0.18);
+ background: rgba(6, 6, 6, 0.82);
+ backdrop-filter: blur(22px) saturate(120%);
+ -webkit-backdrop-filter: blur(22px) saturate(120%);
+ border-bottom: 1px solid rgba(255, 255, 255, 0.06);
box-shadow:
- 0 1px 0 rgba(255, 255, 255, 0.04) inset,
- 0 8px 28px -16px rgba(0, 0, 0, 0.7),
- 0 0 12px -2px rgba(139, 92, 246, 0.15);
+ 0 1px 0 rgba(255, 255, 255, 0.03) inset,
+ 0 8px 28px -16px rgba(0, 0, 0, 0.7);
/* style.css sets `header { overflow-x: auto; overflow-y: hidden }` so the
bar can scroll horizontally on narrow widths. That clips our dropdown
menus below the header bottom edge. With the hamburger menu handling
@@ -37,9 +34,9 @@
background: linear-gradient(
90deg,
transparent 0%,
- rgba(167, 139, 250, 0.45) 30%,
- rgba(99, 102, 241, 0.4) 55%,
- rgba(34, 211, 238, 0.35) 78%,
+ rgba(255, 255, 255, 0.15) 30%,
+ rgba(255, 255, 255, 0.12) 55%,
+ rgba(255, 255, 255, 0.08) 78%,
transparent 100%
);
pointer-events: none;
@@ -65,22 +62,22 @@
height: 28px;
display: inline-block;
vertical-align: middle;
- filter: drop-shadow(0 2px 12px rgba(139, 92, 246, 0.35));
+ filter: drop-shadow(0 2px 12px rgba(255, 255, 255, 0.15));
transition: filter 0.25s ease;
}
.site-header-brand > a:hover .wordmark-logo {
- filter: drop-shadow(0 2px 16px rgba(167, 139, 250, 0.6));
+ filter: drop-shadow(0 2px 16px rgba(255, 255, 255, 0.25));
}
.site-header-brand .wordmark-dot {
width: 7px;
height: 7px;
border-radius: 50%;
- background: radial-gradient(circle at 30% 30%, #c4b5fd 0%, #8b5cf6 55%, #6366f1 100%);
+ background: #ffffff;
box-shadow:
- 0 0 0 1px rgba(167, 139, 250, 0.18),
- 0 0 14px rgba(139, 92, 246, 0.75);
+ 0 0 0 1px rgba(255, 255, 255, 0.2),
+ 0 0 14px rgba(255, 255, 255, 0.5);
display: inline-block;
animation: brand-dot-pulse 3.4s ease-in-out infinite;
}
@@ -88,13 +85,13 @@
@keyframes brand-dot-pulse {
0%, 100% {
box-shadow:
- 0 0 0 1px rgba(167, 139, 250, 0.18),
- 0 0 12px rgba(139, 92, 246, 0.6);
+ 0 0 0 1px rgba(255, 255, 255, 0.2),
+ 0 0 12px rgba(255, 255, 255, 0.4);
}
50% {
box-shadow:
- 0 0 0 1px rgba(167, 139, 250, 0.3),
- 0 0 18px rgba(139, 92, 246, 0.95);
+ 0 0 0 1px rgba(255, 255, 255, 0.35),
+ 0 0 18px rgba(255, 255, 255, 0.7);
}
}
@@ -152,8 +149,8 @@
display: inline-flex;
align-items: center;
padding: 0.5rem 1.15rem;
- background: linear-gradient(135deg, #ffd76a 0%, #ff8f4d 60%, #ec4899 130%);
- color: #1a0f08;
+ background: #fff;
+ color: #000;
border-radius: 999px;
font-weight: 600;
font-size: 0.88rem;
@@ -161,9 +158,8 @@
letter-spacing: 0.01em;
box-shadow:
0 1px 0 rgba(255, 255, 255, 0.35) inset,
- 0 -1px 0 rgba(120, 53, 15, 0.25) inset,
- 0 6px 22px -8px rgba(255, 143, 77, 0.55),
- 0 0 0 1px rgba(255, 215, 106, 0.25);
+ 0 6px 22px -8px rgba(255, 255, 255, 0.15),
+ 0 0 0 1px rgba(255, 255, 255, 0.2);
transition:
transform 0.25s cubic-bezier(0.2, 0.9, 0.3, 1),
box-shadow 0.25s ease,
@@ -190,12 +186,10 @@
.home-nav .nav-cta:hover {
transform: translateY(-1px);
box-shadow:
- 0 1px 0 rgba(255, 255, 255, 0.45) inset,
- 0 -1px 0 rgba(120, 53, 15, 0.3) inset,
- 0 12px 28px -8px rgba(255, 143, 77, 0.7),
- 0 0 0 1px rgba(255, 215, 106, 0.4);
- filter: saturate(1.05);
- color: #1a0f08;
+ 0 1px 0 rgba(255, 255, 255, 0.5) inset,
+ 0 12px 28px -8px rgba(255, 255, 255, 0.2),
+ 0 0 0 1px rgba(255, 255, 255, 0.35);
+ color: #000;
}
.home-nav .nav-cta:hover::after {
@@ -228,8 +222,8 @@
width: 6px;
height: 6px;
border-radius: 50%;
- background: #4ade80;
- box-shadow: 0 0 8px rgba(74, 222, 128, 0.7);
+ background: #fff;
+ box-shadow: 0 0 8px rgba(255, 255, 255, 0.5);
flex-shrink: 0;
}
@@ -241,7 +235,7 @@
}
.home-nav a:focus-visible {
- outline: 2px solid rgba(167, 139, 250, 0.7);
+ outline: 2px solid rgba(255, 255, 255, 0.5);
outline-offset: 3px;
border-radius: 6px;
}
@@ -249,7 +243,7 @@
/* Active page indicator */
.home-nav a[aria-current='page']:not(.nav-cta):not(.nav-user) {
color: #fff;
- background: rgba(139, 92, 246, 0.12);
+ background: rgba(255, 255, 255, 0.08);
}
.home-nav a[aria-current='page']:not(.nav-cta):not(.nav-user)::after {
@@ -264,14 +258,14 @@
display: inline-block;
padding: 1px 6px;
margin-left: 6px;
- background: linear-gradient(135deg, #8b5cf6, #22d3ee);
- color: #0a0b10;
+ background: #fff;
+ color: #000;
border-radius: 999px;
font-size: 9px;
font-weight: 700;
letter-spacing: 0.08em;
vertical-align: 1px;
- box-shadow: 0 0 10px rgba(139, 92, 246, 0.4);
+ box-shadow: 0 0 10px rgba(255, 255, 255, 0.2);
}
.home-nav .nav-link-with-badge {
@@ -358,8 +352,8 @@ body.nav-open {
}
.home-nav .nav-burger:hover {
- border-color: rgba(167, 139, 250, 0.4);
- background: rgba(139, 92, 246, 0.08);
+ border-color: rgba(255, 255, 255, 0.25);
+ background: rgba(255, 255, 255, 0.06);
}
.home-nav .nav-burger-bar {
@@ -451,7 +445,7 @@ body.nav-open {
right: 50%;
bottom: 2px;
height: 1.5px;
- background: linear-gradient(90deg, #a78bfa, #6366f1, #22d3ee);
+ background: rgba(255, 255, 255, 0.6);
border-radius: 2px;
opacity: 0;
transition: left 0.25s ease, right 0.25s ease, opacity 0.2s ease;
@@ -486,17 +480,14 @@ body.nav-open {
margin: 0;
padding: 8px;
list-style: none;
- background:
- radial-gradient(120% 100% at 0% 0%, rgba(139, 92, 246, 0.14), transparent 55%),
- linear-gradient(180deg, rgba(18, 14, 28, 0.96), rgba(10, 8, 16, 0.96));
- backdrop-filter: blur(24px) saturate(160%);
- -webkit-backdrop-filter: blur(24px) saturate(160%);
+ background: rgba(10, 10, 10, 0.96);
+ backdrop-filter: blur(24px) saturate(120%);
+ -webkit-backdrop-filter: blur(24px) saturate(120%);
border: 1px solid rgba(255, 255, 255, 0.08);
border-radius: 14px;
box-shadow:
- 0 1px 0 rgba(255, 255, 255, 0.05) inset,
- 0 24px 48px -12px rgba(0, 0, 0, 0.7),
- 0 8px 16px -8px rgba(99, 102, 241, 0.18);
+ 0 1px 0 rgba(255, 255, 255, 0.04) inset,
+ 0 24px 48px -12px rgba(0, 0, 0, 0.7);
opacity: 0;
transform: translateY(-6px) scale(0.98);
transform-origin: top left;
@@ -530,8 +521,7 @@ body.nav-open {
.home-nav .nav-menu a:hover,
.home-nav .nav-menu a:focus-visible {
- background:
- linear-gradient(135deg, rgba(139, 92, 246, 0.12), rgba(99, 102, 241, 0.06));
+ background: rgba(255, 255, 255, 0.06);
color: #fff;
transform: translateX(2px);
}
@@ -604,17 +594,14 @@ body.nav-open {
align-items: stretch !important;
gap: 2px !important;
padding: 10px;
- background:
- radial-gradient(120% 70% at 100% 0%, rgba(139, 92, 246, 0.16), transparent 55%),
- linear-gradient(180deg, rgba(18, 14, 28, 0.97), rgba(10, 8, 16, 0.97));
- backdrop-filter: blur(24px) saturate(160%);
- -webkit-backdrop-filter: blur(24px) saturate(160%);
+ background: rgba(10, 10, 10, 0.97);
+ backdrop-filter: blur(24px) saturate(120%);
+ -webkit-backdrop-filter: blur(24px) saturate(120%);
border: 1px solid rgba(255, 255, 255, 0.08);
border-radius: 14px;
box-shadow:
- 0 1px 0 rgba(255, 255, 255, 0.05) inset,
- 0 24px 48px -12px rgba(0, 0, 0, 0.7),
- 0 8px 16px -8px rgba(99, 102, 241, 0.2);
+ 0 1px 0 rgba(255, 255, 255, 0.04) inset,
+ 0 24px 48px -12px rgba(0, 0, 0, 0.7);
z-index: 1001;
}
@@ -655,7 +642,7 @@ body.nav-open {
.home-nav .nav-item > a:hover,
.home-nav .nav-trigger:hover,
.home-nav .nav-trigger[aria-expanded='true'] {
- background: rgba(139, 92, 246, 0.1);
+ background: rgba(255, 255, 255, 0.06);
color: #fff;
}
@@ -677,7 +664,7 @@ body.nav-open {
backdrop-filter: none;
-webkit-backdrop-filter: none;
border: none;
- border-left: 2px solid rgba(139, 92, 246, 0.3);
+ border-left: 2px solid rgba(255, 255, 255, 0.12);
box-shadow: none;
border-radius: 0;
}
@@ -705,7 +692,7 @@ body.nav-open {
.home-nav .nav-menu a:hover {
transform: none;
- background: rgba(139, 92, 246, 0.08);
+ background: rgba(255, 255, 255, 0.06);
}
/* Hide sub-descriptions on mobile — keep it scannable */
diff --git a/public/studio/index.html b/public/studio/index.html
index 08c9cb166..29c548d2d 100644
--- a/public/studio/index.html
+++ b/public/studio/index.html
@@ -13,7 +13,7 @@
<meta name="robots" content="noindex" />
<link rel="shortcut icon" href="/favicon.ico" />
<link rel="stylesheet" href="/fonts/fonts.css" />
- <link rel="stylesheet" href="/studio/studio.css?v=3" />
+ <link rel="stylesheet" href="/studio/studio.css?v=4" />
<link rel="stylesheet" href="/mobile.css" />
<style>
/* Critical layout — guarantees the 3-column grid renders even if
@@ -141,6 +141,17 @@
></iframe>
</div>
<div class="preview-meta">
+ <div class="device-switcher" role="group" aria-label="Preview device size">
+ <button class="device-btn active" data-device="desktop" aria-pressed="true" data-tooltip="Desktop preview">
+ <svg width="14" height="14" viewBox="0 0 14 14" fill="none" aria-hidden="true"><rect x="1" y="1.5" width="12" height="8.5" rx="1.5" stroke="currentColor" stroke-width="1.2"/><path d="M4.5 12h5M7 10v2" stroke="currentColor" stroke-width="1.2" stroke-linecap="round"/></svg>
+ </button>
+ <button class="device-btn" data-device="tablet" aria-pressed="false" data-tooltip="Tablet preview">
+ <svg width="14" height="14" viewBox="0 0 14 14" fill="none" aria-hidden="true"><rect x="2" y="1" width="10" height="12" rx="1.5" stroke="currentColor" stroke-width="1.2"/><circle cx="7" cy="11.5" r="0.5" fill="currentColor"/></svg>
+ </button>
+ <button class="device-btn" data-device="mobile" aria-pressed="false" data-tooltip="Mobile preview">
+ <svg width="14" height="14" viewBox="0 0 14 14" fill="none" aria-hidden="true"><rect x="3.5" y="1" width="7" height="12" rx="1.5" stroke="currentColor" stroke-width="1.2"/><circle cx="7" cy="11.5" r="0.5" fill="currentColor"/></svg>
+ </button>
+ </div>
<span id="preview-status" class="muted">Pick an avatar to preview</span>
<button
class="btn-ghost btn-sm"
@@ -272,6 +283,27 @@
Generate embed
</button>
</div>
+ <div class="action-secondary" id="action-secondary" hidden>
+ <a
+ href="#"
+ class="btn-ghost btn-sm"
+ id="view-live-btn"
+ target="_blank"
+ rel="noopener"
+ data-tooltip="Open the live widget page in a new tab."
+ >
+ <svg width="12" height="12" viewBox="0 0 12 12" fill="none" aria-hidden="true"><path d="M5 2H2a1 1 0 0 0-1 1v7a1 1 0 0 0 1 1h7a1 1 0 0 0 1-1V7M7 1h4m0 0v4m0-4L5.5 6.5" stroke="currentColor" stroke-width="1.3" stroke-linecap="round" stroke-linejoin="round"/></svg>
+ View live
+ </a>
+ <button
+ type="button"
+ class="btn-danger btn-sm"
+ id="delete-widget-btn"
+ data-tooltip="Permanently delete this widget. Cannot be undone."
+ >
+ Delete widget
+ </button>
+ </div>
<p id="form-error" class="form-error" hidden></p>
</section>
</main>
@@ -367,6 +399,6 @@
<div class="toast" id="toast" hidden></div>
- <script type="module" src="/studio/studio.js?v=3"></script>
+ <script type="module" src="/studio/studio.js?v=4"></script>
</body>
</html>
diff --git a/public/studio/studio.css b/public/studio/studio.css
index 5d519ed7c..5bbb089d3 100644
--- a/public/studio/studio.css
+++ b/public/studio/studio.css
@@ -1486,3 +1486,271 @@ a:hover {
font-size: max(16px, 1em);
}
}
+
+/* ── device switcher ───────────────────────────────────────────────────────── */
+.device-switcher {
+ display: flex;
+ gap: 0.2rem;
+ background: rgba(255, 255, 255, 0.04);
+ border: 1px solid var(--border);
+ border-radius: var(--radius-md);
+ padding: 0.2rem;
+}
+
+.device-btn {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 28px;
+ height: 28px;
+ border: 0;
+ background: transparent;
+ color: var(--muted);
+ border-radius: 6px;
+ cursor: pointer;
+ transition: background 0.12s ease, color 0.12s ease;
+ flex-shrink: 0;
+}
+
+.device-btn:hover {
+ color: #ddd;
+ background: rgba(255, 255, 255, 0.06);
+}
+
+.device-btn.active,
+.device-btn[aria-pressed='true'] {
+ background: rgba(255, 255, 255, 0.12);
+ color: #fff;
+}
+
+/* preview frame device modes */
+.preview-frame.device--mobile {
+ max-width: 240px;
+ aspect-ratio: 9 / 18;
+ margin: 0 auto;
+}
+
+.preview-frame.device--tablet {
+ max-width: 400px;
+ aspect-ratio: 3 / 4;
+ margin: 0 auto;
+}
+
+/* desktop is the default — no extra rules needed */
+
+/* ── secondary action row ─────────────────────────────────────────────────── */
+.action-secondary {
+ display: flex;
+ align-items: center;
+ gap: 0.5rem;
+ margin-top: 0.4rem;
+}
+
+.action-secondary[hidden] { display: none; }
+
+.btn-danger {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ gap: 0.4rem;
+ padding: 0.35rem 0.65rem;
+ border-radius: var(--radius-sm);
+ font: inherit;
+ font-size: 0.75rem;
+ font-weight: 500;
+ cursor: pointer;
+ border: 1px solid rgba(248, 113, 113, 0.3);
+ background: rgba(248, 113, 113, 0.06);
+ color: #fca5a5;
+ transition: background 0.15s ease, border-color 0.15s ease, color 0.15s ease;
+}
+
+.btn-danger:hover {
+ background: rgba(248, 113, 113, 0.14);
+ border-color: rgba(248, 113, 113, 0.55);
+ color: #fecaca;
+}
+
+/* ── field group (sub-section within type-fields) ─────────────────────────── */
+.field-group {
+ display: flex;
+ flex-direction: column;
+ gap: 0.55rem;
+ padding: 0.7rem 0.75rem 0.75rem;
+ background: rgba(255, 255, 255, 0.025);
+ border: 1px solid rgba(255, 255, 255, 0.07);
+ border-radius: var(--radius-md);
+}
+
+.field-group-title {
+ font-size: 0.7rem;
+ font-weight: 600;
+ letter-spacing: 0.07em;
+ text-transform: uppercase;
+ color: rgba(255, 255, 255, 0.4);
+ margin-bottom: 0.1rem;
+}
+
+/* ── color row field ──────────────────────────────────────────────────────── */
+.field--color-row .color-row {
+ display: flex;
+ align-items: center;
+ gap: 0.5rem;
+}
+
+.field--color-row input[type='color'] {
+ width: 40px;
+ height: 34px;
+ padding: 2px 3px;
+ flex-shrink: 0;
+}
+
+.field--color-row .color-hex {
+ flex: 1;
+ font-family: ui-monospace, 'SF Mono', Menlo, monospace;
+ font-size: 0.82rem;
+ letter-spacing: 0.04em;
+}
+
+/* ── hotspot editor ───────────────────────────────────────────────────────── */
+.hotspot-editor {
+ display: flex;
+ flex-direction: column;
+ gap: 0.6rem;
+}
+
+.hotspot-editor-header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+}
+
+.hotspot-editor-title {
+ font-size: 0.78rem;
+ font-weight: 600;
+ color: #ccc;
+}
+
+.hotspot-count {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ min-width: 18px;
+ height: 18px;
+ padding: 0 4px;
+ background: rgba(255, 255, 255, 0.1);
+ border-radius: 999px;
+ font-size: 0.62rem;
+ font-weight: 700;
+ color: #bbb;
+ margin-left: 0.35rem;
+}
+
+.hotspot-empty {
+ font-size: 0.78rem;
+ color: var(--muted);
+ text-align: center;
+ padding: 0.8rem 0.6rem;
+ border: 1px dashed rgba(255, 255, 255, 0.1);
+ border-radius: var(--radius-md);
+ line-height: 1.45;
+}
+
+.hotspot-row {
+ display: flex;
+ flex-direction: column;
+ gap: 0.45rem;
+ padding: 0.65rem 0.7rem;
+ background: rgba(255, 255, 255, 0.025);
+ border: 1px solid rgba(255, 255, 255, 0.08);
+ border-radius: var(--radius-md);
+ transition: border-color 0.15s ease;
+}
+
+.hotspot-row:hover {
+ border-color: rgba(255, 255, 255, 0.14);
+}
+
+.hotspot-row-header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+}
+
+.hotspot-num {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 20px;
+ height: 20px;
+ background: rgba(139, 92, 246, 0.15);
+ border: 1px solid rgba(139, 92, 246, 0.3);
+ color: var(--accent-strong);
+ border-radius: 50%;
+ font-size: 0.65rem;
+ font-weight: 700;
+}
+
+.hotspot-del {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 22px;
+ height: 22px;
+ background: transparent;
+ border: 1px solid rgba(255, 255, 255, 0.1);
+ color: var(--muted);
+ border-radius: var(--radius-sm);
+ cursor: pointer;
+ font-size: 1rem;
+ line-height: 1;
+ transition: background 0.12s ease, border-color 0.12s ease, color 0.12s ease;
+}
+
+.hotspot-del:hover {
+ background: rgba(248, 113, 113, 0.1);
+ border-color: rgba(248, 113, 113, 0.4);
+ color: #fca5a5;
+}
+
+.hotspot-pos-row {
+ display: grid;
+ grid-template-columns: auto 1fr 1fr 1fr;
+ align-items: center;
+ gap: 0.4rem;
+}
+
+.hotspot-pos-label {
+ font-size: 0.72rem;
+ color: var(--muted);
+ white-space: nowrap;
+}
+
+.hotspot-pos-row input[type='number'] {
+ width: 100%;
+ padding: 0.4rem 0.45rem;
+ background: #0d0d14;
+ border: 1px solid var(--border);
+ border-radius: var(--radius-sm);
+ color: var(--text);
+ font: inherit;
+ font-size: 0.8rem;
+ text-align: center;
+}
+
+.hotspot-pos-row input[type='number']:focus {
+ outline: none;
+ border-color: var(--accent);
+ box-shadow: 0 0 0 2px rgba(139, 92, 246, 0.2);
+}
+
+/* ── studio version badge ─────────────────────────────────────────────────── */
+.studio-tag {
+ color: var(--muted);
+ font-weight: 500;
+ font-size: 0.85rem;
+ letter-spacing: 0.02em;
+ padding: 0.15rem 0.5rem;
+ border: 1px solid var(--border);
+ border-radius: 999px;
+}
diff --git a/public/studio/studio.js b/public/studio/studio.js
index 4a60e9cd2..061bdeb75 100644
--- a/public/studio/studio.js
+++ b/public/studio/studio.js
@@ -192,6 +192,9 @@ if (preModel) state.preselectedModel = preModel;
else if (state.preselectedModel) selectByModelUrl(state.preselectedModel);
else if (!state.avatarId) selectAvatar(DEMO_AVATAR.id);
+ // Show live-link + delete if we loaded an existing widget
+ if (state.editingId) updateSecondaryActions(state.editingId);
+
// Re-send config after every iframe navigation so brand settings apply on load.
previewIfr.addEventListener('load', postConfigToPreview);
@@ -1521,6 +1524,41 @@ async function save({ generate }) {
}
}
+function updateSecondaryActions(widgetId) {
+ const bar = $('#action-secondary');
+ const viewLink = $('#view-live-btn');
+ const delBtn = $('#delete-widget-btn');
+ if (!bar) return;
+ if (widgetId) {
+ if (viewLink) viewLink.href = `/w/${widgetId}`;
+ bar.hidden = false;
+ if (delBtn) delBtn.hidden = false;
+ } else {
+ bar.hidden = true;
+ }
+}
+
+async function deleteWidget() {
+ if (!state.editingId) return;
+ if (!confirm('Delete this widget permanently? This cannot be undone.')) return;
+ try {
+ const res = await fetch(`/api/widgets/${encodeURIComponent(state.editingId)}`, {
+ method: 'DELETE',
+ credentials: 'include',
+ });
+ if (!res.ok) {
+ const data = await res.json().catch(() => ({}));
+ throw new Error(data.error_description || `delete failed: ${res.status}`);
+ }
+ toast('Widget deleted', 'success');
+ setTimeout(() => {
+ location.href = '/dashboard/widgets';
+ }, 900);
+ } catch (err) {
+ toast(err.message, 'error');
+ }
+}
+
let _currentEmbedUrl = '';
let _currentWidgetType = '';
diff --git a/public/style.css b/public/style.css
index 7533ffcd4..4f8643691 100644
--- a/public/style.css
+++ b/public/style.css
@@ -22,7 +22,7 @@
z-index: 9999;
}
.save-toast a {
- color: #9a8cff;
+ color: rgba(255, 255, 255, 0.7);
}
:root {
@@ -66,8 +66,8 @@
--font-mono: 'SF Mono', 'Fira Code', ui-monospace, monospace;
/* Accent */
- --accent: #8b5cf6;
- --accent-soft: rgba(139, 92, 246, 0.18);
+ --accent: #ffffff;
+ --accent-soft: rgba(255, 255, 255, 0.10);
}
html {
diff --git a/public/theme.css b/public/theme.css
new file mode 100644
index 000000000..503246dce
--- /dev/null
+++ b/public/theme.css
@@ -0,0 +1,53 @@
+/*
+ * Monochrome design tokens — three.ws
+ *
+ * Single source of truth for the site palette. Every page imports this file
+ * FIRST; page-specific overrides (if any) cascade after it. To retheme the
+ * entire site, edit the values below.
+ *
+ * Naming convention:
+ * --t-* global tokens (backgrounds, text, borders, accent)
+ * Pages may alias these to local names (--bg, --panel, etc.) in their own
+ * :root block for backwards-compat, but new code should use --t-* directly.
+ */
+
+:root {
+ /* ── Backgrounds ─────────────────────────────────────────────── */
+ --t-bg-0: #000000;
+ --t-bg-1: #0a0a0a;
+ --t-bg-2: #111111;
+ --t-bg-3: #1a1a1a;
+
+ /* ── Text ────────────────────────────────────────────────────── */
+ --t-ink: #e8e8e8;
+ --t-ink-dim: #888888;
+ --t-ink-faint: #555555;
+
+ /* ── Borders / strokes ───────────────────────────────────────── */
+ --t-stroke: #1a1a1a;
+ --t-stroke-strong: #2a2a2a;
+
+ /* ── Accent (white for monochrome) ───────────────────────────── */
+ --t-accent: #ffffff;
+ --t-accent-soft: rgba(255, 255, 255, 0.10);
+ --t-accent-ink: #000000;
+
+ /* ── Glass / translucent surfaces ────────────────────────────── */
+ --t-glass: rgba(255, 255, 255, 0.04);
+ --t-glass-strong: rgba(255, 255, 255, 0.08);
+
+ /* ── Semantic (kept for usability — errors need color) ────────── */
+ --t-success: #4ade80;
+ --t-danger: #f87171;
+ --t-warn: #fbbf24;
+
+ /* ── Legacy aliases ──────────────────────────────────────────── */
+ --accent: var(--t-accent);
+ --accent-ink: var(--t-accent-ink);
+ --accent-soft: var(--t-accent-soft);
+ --bg: var(--t-bg-0);
+ --panel: var(--t-bg-1);
+ --border: var(--t-stroke);
+ --text: var(--t-ink);
+ --muted: var(--t-ink-dim);
+}
diff --git a/scripts/test-identity-modal.mjs b/scripts/test-identity-modal.mjs
index b41f72f13..02812865c 100644
--- a/scripts/test-identity-modal.mjs
+++ b/scripts/test-identity-modal.mjs
@@ -1,178 +1,143 @@
/**
- * Puppeteer test: stages a dummy avatar in IndexedDB, opens /create-review,
- * clicks the On-Chain Identity tile, and screenshots the modal at desktop
- * and mobile viewports.
+ * Renders the identity modal HTML+CSS in isolation and screenshots it at
+ * desktop and mobile viewports. Avoids the full app bootstrap (WebGL, IDB,
+ * Solana SDK) that can't run in headless Chrome.
*/
import puppeteer from 'puppeteer';
+import { readFileSync } from 'fs';
const BASE = process.env.BASE_URL || 'http://localhost:5555';
-async function stageGuestAvatar(page) {
- await page.evaluate(() => {
- return new Promise((resolve, reject) => {
- const DB_NAME = 'three-ws-guest';
- const STORE = 'avatars';
- const KEY = 'pending';
- const META_KEY = '3dagent:guest-avatar-meta';
-
- const req = indexedDB.open(DB_NAME, 1);
- req.onupgradeneeded = () => {
- const db = req.result;
- if (!db.objectStoreNames.contains(STORE)) db.createObjectStore(STORE);
- };
- req.onsuccess = () => {
- const db = req.result;
- // Minimal valid GLB (empty glTF 2.0 binary container)
- const header = new ArrayBuffer(12 + 8 + 17);
- const view = new DataView(header);
- // GLB magic
- view.setUint32(0, 0x46546C67, true);
- view.setUint32(4, 2, true); // version 2
- view.setUint32(8, header.byteLength, true); // total length
- // JSON chunk
- view.setUint32(12, 17, true); // chunk length
- view.setUint32(16, 0x4E4F534A, true); // JSON type
- const json = '{"asset":{"version":"2.0"}}';
- // We need exactly 17 bytes of JSON padded. Let's redo this properly.
- const jsonStr = '{"asset":{"version":"2.0"}}';
- const jsonBytes = new TextEncoder().encode(jsonStr);
- const jsonPadded = jsonBytes.byteLength + ((4 - jsonBytes.byteLength % 4) % 4);
- const totalLen = 12 + 8 + jsonPadded;
- const buf = new ArrayBuffer(totalLen);
- const dv = new DataView(buf);
- dv.setUint32(0, 0x46546C67, true);
- dv.setUint32(4, 2, true);
- dv.setUint32(8, totalLen, true);
- dv.setUint32(12, jsonPadded, true);
- dv.setUint32(16, 0x4E4F534A, true);
- const arr = new Uint8Array(buf);
- arr.set(jsonBytes, 20);
- // Pad with spaces (0x20)
- for (let i = 20 + jsonBytes.byteLength; i < 20 + jsonPadded; i++) arr[i] = 0x20;
-
- const blob = new Blob([buf], { type: 'model/gltf-binary' });
- const id = 'test-' + Math.random().toString(36).slice(2, 8);
- const record = {
- blob,
- meta: { source: 'three-ws-selfie', name: 'Test Avatar' },
- id,
- name: 'Test Avatar',
- size: blob.size,
- createdAt: Date.now(),
- };
+function extractIdentityCSS() {
+ const html = readFileSync('/workspaces/three.ws/pages/create-review.html', 'utf-8');
+ const styleMatch = html.match(/<style>([\s\S]*?)<\/style>/);
+ return styleMatch?.[1] || '';
+}
- const tx = db.transaction(STORE, 'readwrite');
- const store = tx.objectStore(STORE);
- store.put(record, KEY);
- tx.oncomplete = () => {
- localStorage.setItem(META_KEY, JSON.stringify({
- id, name: 'Test Avatar', size: blob.size,
- createdAt: Date.now(), source: 'three-ws-selfie',
- }));
- db.close();
- resolve();
- };
- tx.onerror = () => reject(tx.error);
- };
- req.onerror = () => reject(req.error);
- });
- });
+function buildTestPage(css) {
+ const sampleAddr = 'DuH8HS9Vxh4Y1vHeoXAwV3qiRmM57tYyJAwrTieY8Gww';
+ return `<!doctype html>
+<html lang="en">
+<head>
+<meta charset="utf-8" />
+<meta name="viewport" content="width=device-width, initial-scale=1" />
+<style>
+${css}
+/* Override any hidden states for the test */
+body { background: var(--bg); color: var(--text); margin: 0; }
+.fm-backdrop { position: fixed; inset: 0; z-index: 100; display: flex; align-items: center; justify-content: center; padding: 24px; background: rgba(0,0,0,0.7); }
+.fm-dialog { background: var(--panel); border: 1px solid var(--border); border-radius: 16px; padding: 28px 24px 22px; max-width: 480px; width: 100%; max-height: 90vh; overflow-y: auto; }
+.fm-head { display: flex; align-items: flex-start; gap: 12px; margin-bottom: 18px; }
+.fm-icon { font-size: 28px; line-height: 1; flex-shrink: 0; }
+.fm-head-text { flex: 1; min-width: 0; }
+.fm-head h3 { margin: 0; font-size: 19px; font-weight: 600; }
+.fm-head p { margin: 4px 0 0; font-size: 13px; color: var(--muted); line-height: 1.45; }
+.fm-close { position: absolute; top: 16px; right: 16px; background: none; border: none; color: var(--muted); font-size: 16px; cursor: pointer; padding: 4px 8px; }
+.fm-body { display: flex; flex-direction: column; gap: 14px; }
+.fm-bullets { margin: 0; padding: 0 0 0 18px; font-size: 13.5px; color: var(--muted); line-height: 1.5; }
+.fm-bullets li { margin-bottom: 4px; }
+.fm-bullets li::marker { color: var(--accent); }
+.fm-actions { margin-top: 16px; display: flex; gap: 10px; }
+.fm-cta { display: inline-flex; align-items: center; justify-content: center; padding: 10px 22px; border-radius: 9px; border: 1px solid var(--border); background: rgba(255,255,255,0.06); color: var(--text); font-size: 14px; font-weight: 500; cursor: pointer; }
+@media (max-width: 560px) {
+ .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; }
+ .fm-head h3 { font-size: 17px; }
+ .fm-head p { font-size: 12.5px; }
+}
+</style>
+</head>
+<body>
+<div class="fm-backdrop" role="dialog" aria-modal="true">
+ <div class="fm-dialog" tabindex="-1" style="position: relative;">
+ <div class="fm-head">
+ <div class="fm-icon" aria-hidden="true">🪪</div>
+ <div class="fm-head-text">
+ <h3>On-Chain Identity</h3>
+ <p>Your agent becomes a Metaplex Core asset on Solana the moment you save — transferable, composable, browsable in any wallet.</p>
+ </div>
+ <button class="fm-close" type="button" aria-label="Close">✕</button>
+ </div>
+ <div class="fm-body">
+ <ul class="fm-bullets">
+ <li>Owned by your wallet, not by three.ws — transfer or sell at any time.</li>
+ <li>Metadata (avatar URL, persona, voice) is mutable by you, signed on-chain.</li>
+ <li>Discoverable in the agent registry by capability, price, and reputation.</li>
+ </ul>
+ <div class="fm-id-card" data-state="ready">
+ <div class="fm-id-card-top">
+ <div class="fm-id-avatar fm-id-avatar--fallback">L</div>
+ <div class="fm-id-card-top-right">
+ <div class="fm-id-head">
+ <span class="fm-id-chain">Solana mainnet</span>
+ <span class="fm-id-pill">preview</span>
+ </div>
+ <div class="fm-id-meta">
+ <div><span class="muted">Name</span><strong>Luna</strong></div>
+ <div><span class="muted">Asset standard</span><strong>Metaplex Core</strong></div>
+ </div>
+ </div>
+ </div>
+ <a class="fm-id-addr-link" href="https://solscan.io/account/${sampleAddr}" target="_blank" rel="noopener noreferrer" title="Open in Solscan (sample address)">
+ <span class="fm-id-addr">${sampleAddr}</span>
+ <span class="fm-id-explorer-hint">View on Solscan</span>
+ </a>
+ <p class="fm-id-sample-note">Sample keypair — your real address is created on save</p>
+ </div>
+ </div>
+ <div class="fm-actions">
+ <button class="fm-cta" type="button">Got it</button>
+ </div>
+ </div>
+</div>
+</body>
+</html>`;
}
async function run() {
+ const css = extractIdentityCSS();
+ const html = buildTestPage(css);
+
const browser = await puppeteer.launch({
headless: true,
- args: ['--no-sandbox', '--disable-setuid-sandbox', '--disable-gpu'],
+ args: ['--no-sandbox', '--disable-setuid-sandbox'],
});
try {
const page = await browser.newPage();
- page.on('pageerror', (err) => console.error('PAGE ERROR:', err.message));
-
- // Warm Vite's dep optimizer by hitting the homepage first
- await page.goto(BASE, { waitUntil: 'networkidle2', timeout: 20000 });
- // Let Vite finish any dependency re-optimization (triggers 504 + reload)
- await new Promise(r => setTimeout(r, 5000));
-
- // Stage the avatar
- await stageGuestAvatar(page);
- console.log('Staged dummy avatar in IndexedDB');
-
- // ── Desktop viewport ──
+ // ── Desktop ──
await page.setViewport({ width: 1280, height: 900 });
- // Navigate with retry — Vite may force a reload
- for (let attempt = 0; attempt < 3; attempt++) {
- try {
- await page.goto(BASE + '/create-review', { waitUntil: 'networkidle2', timeout: 15000 });
- break;
- } catch (e) {
- console.log(`Navigation attempt ${attempt + 1} failed, retrying...`);
- await new Promise(r => setTimeout(r, 2000));
- }
- }
- // Wait for page JS to run (3D viewer will fail in headless — that's fine)
- await new Promise(r => setTimeout(r, 3000));
-
- // Click the identity tile via JS (avoids visibility/scroll issues)
- const found = await page.evaluate(() => {
- const tile = document.querySelector('.feature-tile[data-feature="identity"]');
- if (!tile) return false;
- tile.click();
- return true;
- });
- if (!found) {
- console.error('Could not find identity tile');
- await page.screenshot({ path: '/tmp/identity-debug.png', fullPage: true });
- console.log('Debug screenshot saved to /tmp/identity-debug.png');
- return;
- }
- await new Promise(r => setTimeout(r, 3000));
-
+ await page.setContent(html, { waitUntil: 'networkidle0' });
+ await new Promise(r => setTimeout(r, 500));
await page.screenshot({ path: '/tmp/identity-desktop.png', fullPage: false });
- console.log('Desktop screenshot: /tmp/identity-desktop.png');
-
- // Check for console errors
- page.on('pageerror', (err) => console.error('PAGE ERROR:', err.message));
+ console.log('Desktop screenshot saved: /tmp/identity-desktop.png');
- // Close modal
- const closeBtn = await page.$('.fm-close');
- if (closeBtn) await closeBtn.click();
- await new Promise(r => setTimeout(r, 300));
-
- // ── Mobile viewport ──
+ // ── Mobile ──
await page.setViewport({ width: 390, height: 844 });
- for (let attempt = 0; attempt < 3; attempt++) {
- try {
- await page.goto(BASE + '/create-review', { waitUntil: 'networkidle2', timeout: 15000 });
- break;
- } catch (e) {
- console.log(`Mobile nav attempt ${attempt + 1} failed, retrying...`);
- await new Promise(r => setTimeout(r, 2000));
- }
- }
- await new Promise(r => setTimeout(r, 3000));
-
- await page.evaluate(() => {
- const tile = document.querySelector('.feature-tile[data-feature="identity"]');
- if (tile) tile.click();
- });
- await new Promise(r => setTimeout(r, 3000));
+ await page.setContent(html, { waitUntil: 'networkidle0' });
+ await new Promise(r => setTimeout(r, 500));
await page.screenshot({ path: '/tmp/identity-mobile.png', fullPage: false });
- console.log('Mobile screenshot: /tmp/identity-mobile.png');
+ console.log('Mobile screenshot saved: /tmp/identity-mobile.png');
- // Grab any JS errors from the console
- const logs = [];
- page.on('console', (msg) => {
- if (msg.type() === 'error') logs.push(msg.text());
- });
+ // ── Loading state ──
+ const loadingHtml = html
+ .replace('data-state="ready"', 'data-state="loading"')
+ .replace('>preview<', '>generating…<')
+ .replace(`>${sampleAddr}<`, '>—<');
+ await page.setViewport({ width: 1280, height: 900 });
+ await page.setContent(loadingHtml, { waitUntil: 'networkidle0' });
+ await new Promise(r => setTimeout(r, 500));
+ await page.screenshot({ path: '/tmp/identity-loading.png', fullPage: false });
+ console.log('Loading state screenshot saved: /tmp/identity-loading.png');
- console.log('Done. Check /tmp/identity-desktop.png and /tmp/identity-mobile.png');
+ console.log('Done — all screenshots captured.');
} finally {
await browser.close();
}
}
+const sampleAddr = 'DuH8HS9Vxh4Y1vHeoXAwV3qiRmM57tYyJAwrTieY8Gww';
run().catch((err) => {
console.error(err);
process.exit(1);
diff --git a/src/ar-page.js b/src/ar-page.js
new file mode 100644
index 000000000..c26a95379
--- /dev/null
+++ b/src/ar-page.js
@@ -0,0 +1,172 @@
+/**
+ * /avatars/:id/ar — dedicated AR experience page
+ *
+ * Fetches the avatar, loads it into a full-screen model-viewer with AR enabled.
+ * If the avatar has a pre-generated usdz_url, sets it as ios-src immediately.
+ * Otherwise converts the GLB to USDZ in-browser and sets a temporary object URL
+ * so Quick Look works in the current session.
+ */
+
+import { glbBlobToUsdzBlob } from './usdz-pipeline.js';
+
+const segments = location.pathname.split('/').filter(Boolean);
+// /avatars/:id/ar → segments = ['avatars', 'uuid', 'ar']
+const fromPath = segments[0] === 'avatars' && segments[2] === 'ar' ? segments[1] : null;
+const fromQuery = new URLSearchParams(location.search).get('id');
+const avatarId = fromPath || fromQuery || '';
+
+const $ = (id) => document.getElementById(id);
+
+let usdzObjectUrl = null;
+
+async function init() {
+ if (!avatarId) {
+ showError('No avatar specified.');
+ return;
+ }
+
+ const avatar = await fetchAvatar(avatarId);
+ if (!avatar) return;
+
+ const glbUrl = avatar.model_url || avatar.url;
+ if (!glbUrl) {
+ showError('This avatar has no 3D model.');
+ return;
+ }
+
+ renderPage(avatar, glbUrl);
+
+ if (avatar.usdz_url) {
+ applyUsdzSrc(avatar.usdz_url);
+ setArReady();
+ } else {
+ // Auto-generate USDZ so AR works in this session
+ generateUsdz(glbUrl);
+ }
+}
+
+async function fetchAvatar(id) {
+ try {
+ const r = await fetch(`/api/avatars/${encodeURIComponent(id)}`);
+ if (!r.ok) throw new Error(`${r.status}`);
+ return (await r.json()).avatar;
+ } catch (err) {
+ showError(`Couldn't load avatar (${err.message}).`);
+ return null;
+ }
+}
+
+function renderPage(avatar, glbUrl) {
+ $('ar-avatar-name').textContent = avatar.name || 'Avatar';
+ document.title = `${avatar.name || 'Avatar'} in AR · three.ws`;
+
+ if (avatar.thumbnail_url) {
+ document.querySelector('meta[name="og:image"]')?.setAttribute('content', avatar.thumbnail_url);
+ }
+
+ const viewer = $('ar-viewer');
+ viewer.setAttribute('src', glbUrl);
+ viewer.setAttribute('alt', avatar.name || 'three.ws avatar');
+
+ if (avatar.usdz_url) {
+ viewer.setAttribute('ios-src', avatar.usdz_url);
+ }
+
+ $('ar-back-link').href = `/agent-next?id=${encodeURIComponent(avatar.id || avatarId)}`;
+
+ $('ar-share-btn').addEventListener('click', () => shareAvatar(avatar));
+}
+
+function applyUsdzSrc(src) {
+ $('ar-viewer').setAttribute('ios-src', src);
+}
+
+function setArReady() {
+ $('ar-status').hidden = true;
+ $('ar-launch-btn').disabled = false;
+ $('ar-launch-btn').removeAttribute('aria-busy');
+}
+
+function setStatus(msg) {
+ const el = $('ar-status');
+ const txt = $('ar-status-text');
+ if (!msg) { el.hidden = true; return; }
+ txt.textContent = msg;
+ el.hidden = false;
+}
+
+async function generateUsdz(glbUrl) {
+ const btn = $('ar-launch-btn');
+ setStatus('Preparing AR preview…');
+ btn.disabled = true;
+ btn.setAttribute('aria-busy', 'true');
+
+ try {
+ setStatus('Downloading model…');
+ const r = await fetch(glbUrl);
+ if (!r.ok) throw new Error(`GLB fetch ${r.status}`);
+ const glbBlob = await r.blob();
+
+ setStatus('Generating AR preview…');
+ const usdzBlob = await glbBlobToUsdzBlob(glbBlob);
+
+ if (usdzObjectUrl) URL.revokeObjectURL(usdzObjectUrl);
+ usdzObjectUrl = URL.createObjectURL(usdzBlob);
+ applyUsdzSrc(usdzObjectUrl);
+
+ setArReady();
+ setStatus('AR preview ready');
+ setTimeout(() => setStatus(null), 2000);
+ } catch (err) {
+ $('ar-status').classList.add('is-error');
+ setStatus(`Couldn't generate AR preview: ${err.message}`);
+ btn.disabled = false;
+ btn.removeAttribute('aria-busy');
+ }
+}
+
+function showError(msg) {
+ const shell = $('ar-shell');
+ if (shell) shell.innerHTML = `<div class="ar-error">${msg}</div>`;
+}
+
+async function shareAvatar(avatar) {
+ const url = location.href;
+ const title = `${avatar.name || 'Avatar'} in AR · three.ws`;
+ if (navigator.share) {
+ try {
+ await navigator.share({ title, url });
+ return;
+ } catch {
+ // fall through to clipboard
+ }
+ }
+ try {
+ await navigator.clipboard.writeText(url);
+ const btn = $('ar-share-btn');
+ const orig = btn.textContent;
+ btn.textContent = 'Copied!';
+ setTimeout(() => { btn.textContent = orig; }, 1800);
+ } catch {
+ // nothing to do
+ }
+}
+
+// Wire the "Place in your space" button to model-viewer's activateAR()
+document.addEventListener('DOMContentLoaded', () => {
+ $('ar-launch-btn').addEventListener('click', () => {
+ const viewer = $('ar-viewer');
+ if (viewer.activateAR) {
+ viewer.activateAR();
+ }
+ });
+
+ init().catch((err) => {
+ console.error('[ar-page] init error', err);
+ showError('Something went wrong loading this avatar.');
+ });
+
+ window.addEventListener('beforeunload', () => {
+ if (usdzObjectUrl) URL.revokeObjectURL(usdzObjectUrl);
+ });
+});
diff --git a/src/avatar-page.js b/src/avatar-page.js
index 6d216d9c6..ef77c4600 100644
--- a/src/avatar-page.js
+++ b/src/avatar-page.js
@@ -186,6 +186,7 @@ function renderShell(glbUrl) {
<model-viewer
id="av-viewer"
src="${esc(glbUrl)}"
+ ${avatar.usdz_url ? `ios-src="${esc(avatar.usdz_url)}"` : ''}
alt="${esc(avatar.name)}"
camera-controls
auto-rotate
@@ -197,6 +198,9 @@ function renderShell(glbUrl) {
tone-mapping="aces"
environment-image="neutral"
reveal="auto"
+ ar
+ ar-modes="webxr scene-viewer quick-look"
+ ar-scale="auto"
></model-viewer>
</div>
<div class="av-meta-strip" id="av-meta-strip">
@@ -236,6 +240,12 @@ function renderShell(glbUrl) {
<a class="av-cta-sec" href="/studio?avatar=${encodeURIComponent(avatar.id || avatarId)}" title="Use this avatar in Widget Studio">Open in Studio</a>
<button class="av-cta-sec" id="av-download" type="button">Download ▾</button>
</div>
+ <div class="av-ar-row">
+ <a class="av-ar-btn" href="/avatars/${encodeURIComponent(avatar.id || avatarId)}/ar" id="av-ar-link">
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"/></svg>
+ View in AR
+ </a>
+ </div>
${avatar.owner_id ? `
<div class="av-owner-row" id="av-owner-row">
<a class="av-owner-btn" href="/avatars/${encodeURIComponent(avatar.id || avatarId)}/edit">
diff --git a/src/avatar-sdk-page.js b/src/avatar-sdk-page.js
new file mode 100644
index 000000000..864d27f68
--- /dev/null
+++ b/src/avatar-sdk-page.js
@@ -0,0 +1,94 @@
+// Avatar SDK page — registers <three-ws-viewer>, copy buttons, tab switching, creator demo
+import { ThreeWsViewerElement } from '../avatar-sdk/src/viewer.js';
+
+if (typeof customElements !== 'undefined' && !customElements.get('three-ws-viewer')) {
+ customElements.define('three-ws-viewer', ThreeWsViewerElement);
+}
+
+// ── Copy-to-clipboard ────────────────────────────────────────────────────────
+document.addEventListener('DOMContentLoaded', () => {
+ document.querySelectorAll('.sdk-copy-btn').forEach((btn) => {
+ btn.addEventListener('click', async () => {
+ const target = document.getElementById(btn.dataset.target);
+ if (!target) return;
+ const text = target.textContent;
+ try {
+ await navigator.clipboard.writeText(text);
+ btn.textContent = 'Copied!';
+ btn.classList.add('copied');
+ setTimeout(() => {
+ btn.textContent = 'Copy';
+ btn.classList.remove('copied');
+ }, 2000);
+ } catch {
+ // Fallback for environments that block clipboard
+ const sel = window.getSelection();
+ const range = document.createRange();
+ range.selectNodeContents(target);
+ sel.removeAllRanges();
+ sel.addRange(range);
+ }
+ });
+ });
+
+ // ── Tab switching ────────────────────────────────────────────────────────
+ document.querySelectorAll('.sdk-tabs').forEach((tabs) => {
+ const buttons = tabs.querySelectorAll('.sdk-tab-btn');
+ const panels = tabs.querySelectorAll('.sdk-tab-panel');
+ buttons.forEach((btn, i) => {
+ btn.addEventListener('click', () => {
+ buttons.forEach((b, j) => {
+ b.classList.toggle('active', j === i);
+ b.setAttribute('aria-selected', j === i ? 'true' : 'false');
+ });
+ panels.forEach((p, j) => {
+ p.hidden = j !== i;
+ });
+ });
+ });
+ });
+
+ // ── Creator demo ─────────────────────────────────────────────────────────
+ const creatorBtn = document.getElementById('sdk-creator-open');
+ const creatorStatus = document.getElementById('sdk-creator-status');
+ if (creatorBtn) {
+ creatorBtn.addEventListener('click', async () => {
+ try {
+ const mod = await import('../avatar-sdk/src/creator.js');
+ creatorStatus.textContent = 'Opening Avatar Studio…';
+ creatorStatus.className = 'sdk-creator-status info';
+ const creator = new mod.AvatarCreator({
+ studioUrl: new URL('/avatar-studio/', location.origin).toString(),
+ onExport: (blob) => {
+ creatorStatus.textContent = `Avatar exported — ${(blob.size / 1024).toFixed(0)} KB GLB`;
+ creatorStatus.className = 'sdk-creator-status ok';
+ },
+ onClose: () => {
+ if (!creatorStatus.classList.contains('ok')) {
+ creatorStatus.textContent = 'Closed without export.';
+ creatorStatus.className = 'sdk-creator-status muted';
+ }
+ },
+ });
+ await creator.open();
+ } catch (err) {
+ creatorStatus.textContent = 'Error: ' + err.message;
+ creatorStatus.className = 'sdk-creator-status err';
+ }
+ });
+ }
+
+ // ── Hero viewer fallback message ─────────────────────────────────────────
+ const heroViewer = document.querySelector('.sdk-hero-viewer three-ws-viewer');
+ if (heroViewer) {
+ heroViewer.addEventListener('error', () => {
+ const wrap = document.querySelector('.sdk-hero-viewer');
+ if (wrap) {
+ const msg = document.createElement('p');
+ msg.className = 'sdk-viewer-err';
+ msg.textContent = 'Avatar preview unavailable in this environment.';
+ wrap.appendChild(msg);
+ }
+ });
+ }
+});
diff --git a/src/create-review.js b/src/create-review.js
index 9f8019928..ed80770b4 100644
--- a/src/create-review.js
+++ b/src/create-review.js
@@ -17,6 +17,7 @@ import { attachAvatarToAgent } from './attach-avatar-to-agent.js';
import { load as loadGuest, clear as clearGuest } from './guest-avatar.js';
import { TalkScene } from './voice/talk-scene.js';
import { IdleAnimation } from './idle-animation.js';
+import { glbBlobToUsdzBlob } from './usdz-pipeline.js';
import {
openAnalyticsModal,
openDeveloperModal,
@@ -341,12 +342,15 @@ async function onSave({ auto = false } = {}) {
const agent = await attachAvatarToAgent(avatar.id, name);
updateSaveOverlay('Opening your avatar…', '');
await clearGuest();
- // Capture and upload a thumbnail from the rendered canvas before leaving
- // so the user's first visit to /app shows a poster rather than a blank
- // canvas during the GLB stream. Times out after 4 s to never block.
+ // Capture thumbnail and generate USDZ for iOS AR in parallel.
+ // Both are best-effort — the save already succeeded. 8 s cap so USDZ
+ // conversion (CPU-intensive) gets a fair shot before we navigate away.
await Promise.race([
- captureAndUploadThumbnail(avatar.id).catch(() => {}),
- new Promise((r) => setTimeout(r, 4000)),
+ Promise.all([
+ captureAndUploadThumbnail(avatar.id).catch(() => {}),
+ generateAndUploadUsdz(avatar.id, staged.blob).catch(() => {}),
+ ]),
+ new Promise((r) => setTimeout(r, 8000)),
]);
releaseObjectUrl();
// If the user backgrounded the tab, ping a Notification so they know to
@@ -531,6 +535,37 @@ function humanizeSaveError(err, auto) {
return 'Save failed. Try again, or refresh the page if it keeps happening.';
}
+// Convert the staged GLB to USDZ in-browser and upload it to R2, then PATCH
+// the avatar row so iOS Quick Look is wired up for all future visits.
+// Fire-and-forget — any failure is swallowed so the save flow is never blocked.
+async function generateAndUploadUsdz(avatarId, glbBlob) {
+ try {
+ const usdzBlob = await glbBlobToUsdzBlob(glbBlob);
+ const presignRes = await fetch('/api/avatars/presign-usdz', {
+ method: 'POST',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ avatar_id: avatarId, size_bytes: usdzBlob.size }),
+ });
+ if (!presignRes.ok) return;
+ const { usdz_key, upload_url } = await presignRes.json();
+ const put = await fetch(upload_url, {
+ method: 'PUT',
+ headers: { 'content-type': 'model/vnd.usdz+zip' },
+ body: usdzBlob,
+ });
+ if (!put.ok) return;
+ await fetch(`/api/avatars/${encodeURIComponent(avatarId)}`, {
+ method: 'PATCH',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ usdz_key }),
+ });
+ } catch {
+ // non-critical — user can still use the avatar; AR will generate on-demand
+ }
+}
+
// Capture the current TalkScene canvas, resize to 512², and POST to the
// thumbnail API. Called once after a successful save — we already have the
// rendered model in memory, so a snapshot here means the user's first visit
diff --git a/src/marketplace.js b/src/marketplace.js
index 9b4cc13b9..6be9171a3 100644
--- a/src/marketplace.js
+++ b/src/marketplace.js
@@ -2704,7 +2704,7 @@ function renderCard(a) {
// avatar's thumbnail if there is one, otherwise a styled name-initial
// gradient so the card never looks visually empty.
const previewStrip = a.thumbnail_url
- ? `<div class="thumb" style="background-image:url('${escapeHtml(a.thumbnail_url)}')"></div>`
+ ? `<div class="thumb" style="background:url('${escapeHtml(a.thumbnail_url)}') center/cover no-repeat #0a0a0d"></div>`
: `<div class="thumb">${placeholderHtml(a.name)}</div>`;
const bmOn = bookmarkedAgents.has(a.id);
const starBtn = `<button type="button" class="card-star${bmOn ? ' on' : ''}" data-agent-bm="${escapeHtml(a.id)}" aria-label="Bookmark agent" aria-pressed="${bmOn}" title="${bmOn ? 'Remove bookmark' : 'Bookmark agent'}">${bmOn ? '★' : '☆'}</button>`;
diff --git a/src/xr.js b/src/xr.js
new file mode 100644
index 000000000..8b6af00f8
--- /dev/null
+++ b/src/xr.js
@@ -0,0 +1,462 @@
+// /xr — immersive AR experience with full/half-body avatar.
+//
+// Provides a standalone Three.js scene wired to WebXRSession for real
+// immersive-ar. Falls back to camera-passthrough on non-WebXR devices.
+// The viewer shim object matches the interface expected by WebXRSession.
+
+import {
+ AmbientLight,
+ CircleGeometry,
+ DirectionalLight,
+ HemisphereLight,
+ Mesh,
+ MeshStandardMaterial,
+ PCFSoftShadowMap,
+ PerspectiveCamera,
+ PMREMGenerator,
+ Scene,
+ ShadowMaterial,
+ WebGLRenderer,
+} from 'three';
+import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
+import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
+import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';
+import { AnimationManager } from './animation-manager.js';
+import { WebXRSession } from './ar/webxr.js';
+import { canUseQuickLook } from './ar/quick-look.js';
+import { canUseSceneViewer, openSceneViewer } from './ar/scene-viewer.js';
+
+// ── DOM ──────────────────────────────────────────────────────────────────────
+
+const canvas = document.getElementById('xr-canvas');
+const videoEl = document.getElementById('xr-camera-feed');
+const enterArBtn = document.getElementById('xr-enter-ar');
+const bodyToggle = document.getElementById('xr-body-toggle');
+const fullBtn = document.getElementById('xr-body-full');
+const halfBtn = document.getElementById('xr-body-half');
+const statusEl = document.getElementById('xr-status');
+const statusDot = document.getElementById('xr-status-dot');
+const deviceChip = document.getElementById('xr-device-chip');
+const avatarLabel = document.getElementById('xr-avatar-label');
+const loadingEl = document.getElementById('xr-loading');
+
+function setStatus(msg, type = 'idle') {
+ if (!statusEl) return;
+ statusEl.textContent = msg;
+ if (statusDot) {
+ statusDot.className = 'xr-dot xr-dot--' + type;
+ }
+}
+
+// ── Three.js setup ───────────────────────────────────────────────────────────
+
+const renderer = new WebGLRenderer({ canvas, antialias: true, alpha: true });
+renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
+renderer.setSize(window.innerWidth, window.innerHeight, false);
+renderer.shadowMap.enabled = true;
+renderer.shadowMap.type = PCFSoftShadowMap;
+renderer.outputColorSpace = 'srgb';
+
+const scene = new Scene();
+const pmrem = new PMREMGenerator(renderer);
+scene.environment = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;
+
+const camera = new PerspectiveCamera(35, window.innerWidth / window.innerHeight, 0.01, 100);
+camera.position.set(0, 1.4, 2.6);
+
+const controls = new OrbitControls(camera, renderer.domElement);
+controls.target.set(0, 1, 0);
+controls.enableDamping = true;
+controls.minDistance = 0.8;
+controls.maxDistance = 6;
+controls.minPolarAngle = 0.2;
+controls.maxPolarAngle = Math.PI * 0.65;
+controls.update();
+
+// Lights
+const hemi = new HemisphereLight(0xbcd6ff, 0x202830, 0.7);
+hemi.position.set(0, 5, 0);
+scene.add(hemi);
+const ambient = new AmbientLight(0xffffff, 0.4);
+scene.add(ambient);
+const sun = new DirectionalLight(0xffffff, 1.5);
+sun.position.set(4, 8, 6);
+sun.castShadow = true;
+sun.shadow.mapSize.set(1024, 1024);
+sun.shadow.camera.near = 0.5;
+sun.shadow.camera.far = 30;
+sun.shadow.camera.left = -5;
+sun.shadow.camera.right = 5;
+sun.shadow.camera.top = 5;
+sun.shadow.camera.bottom = -5;
+sun.shadow.bias = -0.0005;
+scene.add(sun);
+scene.add(sun.target);
+
+// Ground — opaque ring in preview, shadow-only in AR
+const groundOpaque = new Mesh(
+ new CircleGeometry(3, 64),
+ new MeshStandardMaterial({ color: 0x151821, roughness: 0.95, metalness: 0 }),
+);
+groundOpaque.rotation.x = -Math.PI / 2;
+groundOpaque.receiveShadow = true;
+scene.add(groundOpaque);
+
+const groundShadow = new Mesh(
+ new CircleGeometry(3, 64),
+ new ShadowMaterial({ opacity: 0.4 }),
+);
+groundShadow.rotation.x = -Math.PI / 2;
+groundShadow.receiveShadow = true;
+groundShadow.visible = false;
+scene.add(groundShadow);
+
+// ── Animation + viewer shim ───────────────────────────────────────────────────
+
+const animationManager = new AnimationManager();
+
+/** Viewer shim — matches the interface WebXRSession expects. */
+const xrViewer = {
+ renderer,
+ scene,
+ content: null,
+ controls,
+ mixer: null,
+ animationManager,
+ _afterAnimateHooks: [],
+ _rafId: null,
+ prevTime: null,
+ activeCamera: camera,
+ _needsRender: true,
+ _updateRenderLoop() { _startRAF(); },
+};
+
+function _rafTick(time) {
+ xrViewer._rafId = requestAnimationFrame(_rafTick);
+ const dt = xrViewer.prevTime ? (time - xrViewer.prevTime) / 1000 : 0.016;
+ xrViewer.prevTime = time;
+ if (xrViewer.mixer) xrViewer.mixer.update(dt);
+ animationManager.update(dt);
+ for (const hook of xrViewer._afterAnimateHooks) hook(dt);
+ controls.update();
+ renderer.render(scene, camera);
+}
+
+function _startRAF() {
+ if (xrViewer._rafId !== null) return;
+ xrViewer._rafId = requestAnimationFrame(_rafTick);
+}
+
+// ── State ──────────────────────────────────────────────────────────────────────
+
+let halfBodyActive = false;
+let halfBodyBones = []; // { bone, scale } pairs captured on enter
+let xrSession = null;
+let arCameraActive = false;
+let mediaStream = null;
+
+// ── Half-body logic ───────────────────────────────────────────────────────────
+
+const LOWER_BODY_FRAGMENTS = ['upleg','leg','thigh','knee','shin','calf','foot','toe','ankle'];
+function _normalizeBone(name) {
+ return String(name || '').toLowerCase()
+ .replace(/^mixamorig:?_?/, '').replace(/^cc_base_/, '')
+ .replace(/^armature[:_|]/, '').replace(/^rig[:_]/, '');
+}
+function _isLowerBody(name) {
+ const n = _normalizeBone(name);
+ return LOWER_BODY_FRAGMENTS.some((f) => n.includes(f));
+}
+
+function applyHalfBody() {
+ const content = xrViewer.content;
+ if (!content) return;
+ halfBodyBones = [];
+ content.traverse((obj) => {
+ if (!obj.isSkinnedMesh || !obj.skeleton) return;
+ for (const bone of obj.skeleton.bones || []) {
+ if (!_isLowerBody(bone.name)) continue;
+ if (halfBodyBones.some((b) => b.bone === bone)) continue;
+ halfBodyBones.push({ bone, scale: bone.scale.clone() });
+ bone.scale.set(0.0001, 0.0001, 0.0001);
+ }
+ });
+ content.traverse((obj) => {
+ if (obj.isSkinnedMesh && obj.skeleton) obj.skeleton.update();
+ });
+}
+
+function removeHalfBody() {
+ for (const { bone, scale } of halfBodyBones) bone.scale.copy(scale);
+ halfBodyBones = [];
+ const content = xrViewer.content;
+ if (content) {
+ content.traverse((obj) => {
+ if (obj.isSkinnedMesh && obj.skeleton) obj.skeleton.update();
+ });
+ }
+}
+
+function setHalfBody(active) {
+ halfBodyActive = active;
+ if (active) {
+ applyHalfBody();
+ fullBtn.classList.remove('active');
+ halfBtn.classList.add('active');
+ } else {
+ removeHalfBody();
+ fullBtn.classList.add('active');
+ halfBtn.classList.remove('active');
+ }
+}
+
+// ── AR: camera passthrough (non-WebXR fallback) ───────────────────────────────
+
+async function enableCameraAR() {
+ try {
+ mediaStream = await navigator.mediaDevices.getUserMedia({
+ video: { facingMode: { ideal: 'environment' } },
+ audio: false,
+ });
+ } catch (err) {
+ const msg = err?.name === 'NotAllowedError' ? 'camera permission denied' : `camera unavailable: ${err?.message}`;
+ setStatus(msg, 'error');
+ return false;
+ }
+ videoEl.srcObject = mediaStream;
+ try { await videoEl.play(); } catch {}
+
+ arCameraActive = true;
+ document.getElementById('xr-stage').classList.add('is-ar');
+ groundOpaque.visible = false;
+ groundShadow.visible = true;
+ renderer.setClearColor(0x000000, 0);
+ scene.background = null;
+
+ if (halfBodyActive) applyHalfBody();
+ setStatus('Camera AR active — your avatar in your space', 'ar');
+ enterArBtn.textContent = 'Exit AR';
+ enterArBtn.classList.add('active');
+ return true;
+}
+
+function disableCameraAR() {
+ if (mediaStream) {
+ for (const track of mediaStream.getTracks()) { try { track.stop(); } catch {} }
+ mediaStream = null;
+ }
+ videoEl.srcObject = null;
+ arCameraActive = false;
+ document.getElementById('xr-stage').classList.remove('is-ar');
+ groundOpaque.visible = true;
+ groundShadow.visible = false;
+ renderer.setClearColor(0x000000, 1);
+ setStatus('Preview', 'idle');
+ enterArBtn.textContent = _arBtnLabel();
+ enterArBtn.classList.remove('active');
+}
+
+// ── AR: WebXR immersive-ar ────────────────────────────────────────────────────
+
+async function enterWebXR() {
+ if (xrSession) {
+ await xrSession.end();
+ return;
+ }
+ enterArBtn.disabled = true;
+ enterArBtn.textContent = 'Starting XR…';
+ setStatus('Requesting XR session…', 'loading');
+ try {
+ xrSession = new WebXRSession(xrViewer, {
+ halfBody: halfBodyActive,
+ onEnd: () => {
+ xrSession = null;
+ groundOpaque.visible = true;
+ groundShadow.visible = false;
+ enterArBtn.disabled = false;
+ enterArBtn.textContent = _arBtnLabel();
+ enterArBtn.classList.remove('active');
+ setStatus('Preview', 'idle');
+ },
+ });
+ await xrSession.start();
+ groundOpaque.visible = false;
+ groundShadow.visible = true;
+ setStatus('WebXR active — tap real surface to place avatar', 'ar');
+ enterArBtn.disabled = false;
+ enterArBtn.textContent = 'Exit XR';
+ enterArBtn.classList.add('active');
+ } catch (err) {
+ xrSession = null;
+ setStatus('XR failed: ' + (err?.message || err), 'error');
+ enterArBtn.disabled = false;
+ enterArBtn.textContent = _arBtnLabel();
+ }
+}
+
+// ── AR button logic ───────────────────────────────────────────────────────────
+
+let _arMode = 'none'; // 'none' | 'webxr' | 'camera' | 'sceneviewer' | 'quicklook'
+let _avatarGlbUrl = '/avatars/default.glb';
+
+function _arBtnLabel() {
+ switch (_arMode) {
+ case 'webxr': return 'Enter AR';
+ case 'camera': return 'Enter AR';
+ case 'sceneviewer': return 'View in AR';
+ case 'quicklook': return 'View in AR';
+ default: return 'AR not available';
+ }
+}
+
+async function _detectARMode() {
+ if (navigator.xr && await navigator.xr.isSessionSupported('immersive-ar').catch(() => false)) {
+ _arMode = 'webxr';
+ if (deviceChip) {
+ deviceChip.textContent = 'WebXR';
+ deviceChip.className = 'xr-chip xr-chip--webxr';
+ }
+ setStatus('WebXR supported — tap Enter AR to place your avatar', 'ready');
+ } else if (canUseSceneViewer()) {
+ _arMode = 'sceneviewer';
+ if (deviceChip) {
+ deviceChip.textContent = 'ARCore';
+ deviceChip.className = 'xr-chip xr-chip--arcore';
+ }
+ setStatus('ARCore available', 'ready');
+ } else if (canUseQuickLook()) {
+ _arMode = 'quicklook';
+ if (deviceChip) {
+ deviceChip.textContent = 'Quick Look';
+ deviceChip.className = 'xr-chip xr-chip--ios';
+ }
+ setStatus('Quick Look available', 'ready');
+ } else if (navigator.mediaDevices?.getUserMedia) {
+ _arMode = 'camera';
+ if (deviceChip) {
+ deviceChip.textContent = 'Camera AR';
+ deviceChip.className = 'xr-chip xr-chip--camera';
+ }
+ setStatus('Camera passthrough available', 'ready');
+ } else {
+ _arMode = 'none';
+ if (deviceChip) {
+ deviceChip.textContent = 'No AR';
+ deviceChip.className = 'xr-chip xr-chip--none';
+ }
+ enterArBtn.disabled = true;
+ setStatus('AR not available on this device', 'idle');
+ }
+ if (enterArBtn && _arMode !== 'none') {
+ enterArBtn.textContent = _arBtnLabel();
+ enterArBtn.disabled = false;
+ }
+}
+
+enterArBtn.addEventListener('click', async () => {
+ if (xrSession) { await xrSession.end(); return; }
+ if (arCameraActive) { disableCameraAR(); return; }
+
+ if (_arMode === 'webxr') {
+ await enterWebXR();
+ } else if (_arMode === 'sceneviewer') {
+ openSceneViewer(_avatarGlbUrl, { title: 'three.ws avatar', link: location.href });
+ } else if (_arMode === 'camera') {
+ await enableCameraAR();
+ }
+});
+
+// ── Body toggle ───────────────────────────────────────────────────────────────
+
+fullBtn.addEventListener('click', () => {
+ if (!halfBodyActive) return;
+ setHalfBody(false);
+ // If already in XR, restart with updated mode
+ if (xrSession) {
+ xrSession.end().then(() => enterWebXR());
+ }
+});
+halfBtn.addEventListener('click', () => {
+ if (halfBodyActive) return;
+ setHalfBody(true);
+ if (xrSession) {
+ xrSession.end().then(() => enterWebXR());
+ }
+});
+
+// ── Avatar loading ────────────────────────────────────────────────────────────
+
+async function resolveAvatarUrl() {
+ const params = new URLSearchParams(location.search);
+ const id = params.get('avatar');
+ if (!id) return '/avatars/default.glb';
+ const res = await fetch(`/api/avatars/${encodeURIComponent(id)}`);
+ if (!res.ok) return '/avatars/default.glb';
+ const { avatar } = await res.json();
+ return avatar?.url || '/avatars/default.glb';
+}
+
+async function loadAvatar() {
+ const url = await resolveAvatarUrl();
+ _avatarGlbUrl = url;
+ const loader = new GLTFLoader();
+ const gltf = await loader.loadAsync(url);
+ const root = gltf.scene;
+ root.traverse((obj) => {
+ if (obj.isMesh) {
+ obj.castShadow = true;
+ obj.receiveShadow = true;
+ }
+ });
+ scene.add(root);
+ xrViewer.content = root;
+
+ // Frame camera to avatar bounds
+ const { Box3, Vector3: V3 } = await import('three');
+ const box = new Box3().setFromObject(root);
+ const size = box.getSize(new V3()).length();
+ const center = box.getCenter(new V3());
+ controls.target.copy(center).setY(center.y * 0.7);
+ camera.position.set(0, center.y + size * 0.2, size * 1.4);
+ controls.update();
+
+ // Animations
+ await animationManager.loadAll();
+ animationManager.attach(root);
+ xrViewer.mixer = animationManager.mixer;
+ animationManager.play('idle');
+
+ // Avatar name from URL param
+ const params = new URLSearchParams(location.search);
+ const handle = params.get('handle');
+ if (avatarLabel && handle) avatarLabel.textContent = handle;
+}
+
+// ── Resize ───────────────────────────────────────────────────────────────────
+
+window.addEventListener('resize', () => {
+ renderer.setSize(window.innerWidth, window.innerHeight, false);
+ camera.aspect = window.innerWidth / window.innerHeight;
+ camera.updateProjectionMatrix();
+});
+
+// ── Init ─────────────────────────────────────────────────────────────────────
+
+(async () => {
+ _startRAF();
+ setStatus('Loading avatar…', 'loading');
+
+ try {
+ await loadAvatar();
+ } catch (err) {
+ setStatus('Failed to load avatar', 'error');
+ console.error('[xr] avatar load failed:', err);
+ }
+
+ if (loadingEl) loadingEl.hidden = true;
+
+ // Body toggle: start on full body
+ fullBtn.classList.add('active');
+
+ await _detectARMode();
+})();
diff --git a/vercel.json b/vercel.json
index 1e82e5d51..c339a8ae7 100644
--- a/vercel.json
+++ b/vercel.json
@@ -1422,6 +1422,17 @@
"src": "/avatars/([^/]+\\.glb)",
"dest": "/avatars/$1"
},
+ {
+ "src": "/avatars/([^/]+)/ar/?",
+ "headers": {
+ "permissions-policy": "xr-spatial-tracking=*, camera=(self), microphone=(self)"
+ },
+ "dest": "/pages/ar.html"
+ },
+ {
+ "src": "/avatars/([^/]+)/edit",
+ "dest": "/avatar-edit.html?id=$1"
+ },
{
"src": "/avatars/([^/]+)",
"status": 301,
diff --git a/vite.config.js b/vite.config.js
index 23208badd..de494dfc1 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -182,6 +182,7 @@ const appConfig = {
profile: resolve(__dirname, 'pages/profile.html'),
'threews-claim': resolve(__dirname, 'pages/threews-claim.html'),
'avatar-page': resolve(__dirname, 'pages/avatar-page.html'),
+ 'ar-page': resolve(__dirname, 'pages/ar.html'),
creating: resolve(__dirname, 'pages/creating.html'),
pricing: resolve(__dirname, 'pages/pricing.html'),
'x-pricing': resolve(__dirname, 'pages/x-pricing.html'),