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: avatar gallery picker, voice lab, nav expansion, brain demo and page updates

nirholas5d0c75a7393c
diff --git a/api/persona/extract.js b/api/persona/extract.js
index b0af9c00d..82a0d1b62 100644
--- a/api/persona/extract.js
+++ b/api/persona/extract.js
@@ -23,13 +23,20 @@ async function resolveUser(req) {
return bearer.userId;
}
-function validateAnswers(input) {
+const MAX_FREEFORM_CHARS = 8000;
+
+function validateInput(input) {
if (!input || typeof input !== 'object') {
throw Object.assign(new Error('body must be an object'), { status: 400 });
}
+
+ if (typeof input.freeform === 'string' && input.freeform.trim()) {
+ return { mode: 'freeform', text: input.freeform.trim().slice(0, MAX_FREEFORM_CHARS) };
+ }
+
const list = input.answers;
if (!Array.isArray(list) || list.length === 0) {
- throw Object.assign(new Error('answers must be a non-empty array'), { status: 400 });
+ throw Object.assign(new Error('provide answers array or freeform text'), { status: 400 });
}
if (list.length > MAX_ANSWERS) {
throw Object.assign(new Error(`max ${MAX_ANSWERS} answers`), { status: 400 });
@@ -49,7 +56,7 @@ function validateAnswers(input) {
answer: a.slice(0, MAX_QA_CHARS),
});
}
- return cleaned;
+ return { mode: 'interview', answers: cleaned };
}
const SYSTEM_PROMPT = `You are a persona-extraction analyst. You read a short interview between an onboarding system and a person, and you synthesize a compact persona profile that can later be used to shape an AI agent's voice on behalf of that person.
@@ -81,17 +88,21 @@ const handler = wrap(async (req, res) => {
}
const body = await readJson(req);
- const answers = validateAnswers(body);
+ const input = validateInput(body);
if (!env.ANTHROPIC_API_KEY) {
return error(res, 503, 'config_missing', 'ANTHROPIC_API_KEY not configured');
}
- const interview = answers
- .map((row, i) => `Q${i + 1}: ${row.question}\nA${i + 1}: ${row.answer}`)
- .join('\n\n');
-
- const userMessage = `Here is the onboarding interview. Synthesize the persona JSON.\n\n${interview}`;
+ let userMessage;
+ if (input.mode === 'freeform') {
+ userMessage = `Analyze the following text and synthesize a persona JSON that captures the voice, personality, and communication patterns present in it.\n\n---\n${input.text}\n---`;
+ } else {
+ const interview = input.answers
+ .map((row, i) => `Q${i + 1}: ${row.question}\nA${i + 1}: ${row.answer}`)
+ .join('\n\n');
+ userMessage = `Here is the onboarding interview. Synthesize the persona JSON.\n\n${interview}`;
+ }
const t0 = Date.now();
const anthropicRes = await fetch('https://api.anthropic.com/v1/messages', {
diff --git a/pages/agent-chat-widget.html b/pages/agent-chat-widget.html
index 146f4058d..bb2adbd92 100644
--- a/pages/agent-chat-widget.html
+++ b/pages/agent-chat-widget.html
@@ -8,7 +8,7 @@
<meta name="robots" content="noindex" />
<style>
:root {
- --brand-color: #4a9eff;
+ --brand-color: #ffffff;
--dark-bg: #1a1a1a;
--light-bg: #ffffff;
--dark-text: #ffffff;
@@ -88,7 +88,7 @@
const params = new URL(location.href).searchParams;
const agentId = params.get('agentId') || 'default';
const avatarUrl = params.get('avatarUrl') || '/avatars/default.glb';
- const brandColor = params.get('brandColor') || '#4a9eff';
+ const brandColor = params.get('brandColor') || '#ffffff';
const theme = params.get('theme') || 'dark';
const idleAnim = params.get('idleAnim') || '';
diff --git a/pages/agent-next.html b/pages/agent-next.html
index 3f61db24f..06a5b2e48 100644
--- a/pages/agent-next.html
+++ b/pages/agent-next.html
@@ -555,6 +555,7 @@
<button class="owner-btn" data-owner-act="embed" title="Copy embed snippet">Embed</button>
<button class="owner-btn" data-owner-act="skills" title="View skills">Skills</button>
<button class="owner-btn" data-owner-act="memory" title="View memory">Memory</button>
+ <button class="owner-btn" data-owner-act="selfie" title="Update avatar from selfie">Selfie</button>
<button class="owner-btn accent" data-owner-act="monetize" title="Monetize">Monetize</button>
<a class="owner-btn" href="/a/me" title="My Agents hub">My Agents</a>
</div>
@@ -567,6 +568,7 @@
<button class="act-btn" data-act="mocap"><span class="act-icon">●</span>Mocap</button>
<button class="act-btn" data-act="pose"><span class="act-icon">⊕</span>Pose</button>
<button class="act-btn" data-act="walk"><span class="act-icon">⇗</span>Walk</button>
+ <button class="act-btn" data-act="selfie"><span class="act-icon">📸</span>Selfie</button>
<button class="act-btn" data-act="ar"><span class="act-icon">◫</span>AR</button>
<button class="act-btn" data-act="tip"><span class="act-icon">$</span>Tip</button>
<button class="act-btn" data-act="remix"><span class="act-icon">⎘</span>Remix</button>
@@ -671,7 +673,9 @@
</section>
- <script>
+ <script type="module">
+ import { openSelfieModal } from '/src/selfie-modal.js';
+
// ── Parse ?id= from URL (default: nich) ─────────────────────
const params = new URLSearchParams(location.search);
const avatarId = params.get('id') || 'bacff13e-b64b-4ac0-860d-44f0168ad23b';
@@ -900,6 +904,14 @@
toggleOwnerPanel(panelsHost, 'memory');
break;
}
+ case 'selfie': {
+ const selfieResult = await openSelfieModal({ existingAvatarId: avatarId });
+ if (selfieResult?.avatarId) {
+ ownerToast('Avatar updated from selfie');
+ setTimeout(() => location.reload(), 1200);
+ }
+ break;
+ }
case 'monetize': {
window.open('/dashboard/monetize', '_blank');
break;
@@ -1171,6 +1183,13 @@
}
break;
}
+ case 'selfie': {
+ const result = await openSelfieModal({ existingAvatarId: avatarId });
+ if (result?.avatarId) {
+ location.reload();
+ }
+ break;
+ }
case 'remix':
location.href = `/create?fork=${encodeURIComponent(avatarId)}`;
break;
diff --git a/pages/avatar-edit.html b/pages/avatar-edit.html
index 23ccfab23..7be12b1da 100644
--- a/pages/avatar-edit.html
+++ b/pages/avatar-edit.html
@@ -23,7 +23,7 @@
--text-3: #71717a;
--accent: #ffffff;
--accent-2: #ffffff;
- --success: #34d399;
+ --success: #e8e8e8;
--danger: #f43f5e;
--radius: 14px;
}
@@ -555,7 +555,7 @@
width: 20px;
height: 20px;
border-radius: 50%;
- background: var(--accent, #7dd3fc);
+ background: var(--accent, #ffffff);
box-shadow: 0 0 0 3px rgba(255, 255, 255, 0.25), 0 2px 8px rgba(0,0,0,0.5);
transform: translate(-50%, -50%);
cursor: grab;
diff --git a/pages/avatar-sdk.html b/pages/avatar-sdk.html
index 876210503..b7cc229de 100644
--- a/pages/avatar-sdk.html
+++ b/pages/avatar-sdk.html
@@ -965,7 +965,7 @@
<span class="sdk-feat-tag">AvatarCreator class</span>
</div>
- <div class="sdk-feat-card" style="--card-accent:#34d399">
+ <div class="sdk-feat-card" style="--card-accent:#e8e8e8">
<div class="sdk-feat-icon" style="--icon-bg:rgba(52,211,153,0.12);--icon-border:rgba(52,211,153,0.22)">
<svg width="20" height="20" viewBox="0 0 20 20" fill="none" aria-hidden="true"><path d="M10 3v10M10 3l-3 3M10 3l3 3" stroke="#e8e8e8" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/><path d="M4 13v3a1 1 0 001 1h10a1 1 0 001-1v-3" stroke="#e8e8e8" stroke-width="1.5" stroke-linecap="round"/></svg>
</div>
diff --git a/pages/avatar-studio.html b/pages/avatar-studio.html
index f5fa64e0a..88640343d 100644
--- a/pages/avatar-studio.html
+++ b/pages/avatar-studio.html
@@ -28,10 +28,10 @@
--text: #fafafa;
--text-2: #a1a1aa;
--text-3: #71717a;
- --accent: #d6ff3d;
- --accent-dim: rgba(214, 255, 61, 0.12);
- --accent-ink: #0a0a0a;
- --success: #34d399;
+ --accent: #ffffff;
+ --accent-dim: rgba(255, 255, 255, 0.10);
+ --accent-ink: #000000;
+ --success: #e8e8e8;
--danger: #f43f5e;
--radius: 14px;
}
@@ -114,8 +114,8 @@
.as-stage {
border-right: 1px solid var(--border);
background:
- radial-gradient(ellipse at 50% 35%, rgba(214, 255, 61, 0.04), transparent 60%),
- radial-gradient(ellipse at 70% 80%, rgba(167, 139, 250, 0.03), transparent 50%),
+ radial-gradient(ellipse at 50% 35%, rgba(255, 255, 255, 0.04), transparent 60%),
+ radial-gradient(ellipse at 70% 80%, rgba(255, 255, 255, 0.03), transparent 50%),
var(--bg);
position: relative;
min-height: 500px;
@@ -172,7 +172,7 @@
transition: color 0.12s, background 0.12s;
}
.as-body-toggle button[aria-pressed="true"] {
- background: rgba(214, 255, 61, 0.12);
+ background: rgba(255, 255, 255, 0.12);
color: var(--text);
}
.as-body-toggle button:hover { color: var(--text); }
@@ -329,15 +329,15 @@
.as-tile:hover {
border-color: var(--accent);
transform: translateY(-1px);
- background: rgba(214, 255, 61, 0.03);
+ background: rgba(255, 255, 255, 0.03);
}
.as-tile.selected {
border-color: var(--accent);
- background: rgba(214, 255, 61, 0.05);
+ background: rgba(255, 255, 255, 0.05);
}
.as-tile.previewing {
- border-color: #a78bfa;
- box-shadow: 0 0 0 1px rgba(167, 139, 250, 0.35);
+ border-color: #ffffff;
+ box-shadow: 0 0 0 1px rgba(255, 255, 255, 0.35);
}
.as-tile-preview {
aspect-ratio: 1 / 1;
@@ -551,7 +551,7 @@
background: var(--accent);
margin-top: -5px;
border: 0;
- box-shadow: 0 0 0 2px rgba(214, 255, 61, 0.18);
+ box-shadow: 0 0 0 2px rgba(255, 255, 255, 0.18);
cursor: pointer;
}
.ae-sculpt-row input[type='range']::-moz-range-thumb {
@@ -584,7 +584,7 @@
height: 220px;
border: 1px solid var(--border-2);
border-radius: 50%;
- background: radial-gradient(circle at 50% 50%, rgba(214, 255, 61, 0.03) 0%, rgba(255,255,255,0.015) 60%, transparent 100%);
+ background: radial-gradient(circle at 50% 50%, rgba(255, 255, 255, 0.03) 0%, rgba(255,255,255,0.015) 60%, transparent 100%);
cursor: crosshair;
flex-shrink: 0;
outline: none;
@@ -616,14 +616,14 @@
width: 20px; height: 20px;
border-radius: 50%;
background: var(--accent);
- box-shadow: 0 0 0 3px rgba(214, 255, 61, 0.25), 0 2px 8px rgba(0,0,0,0.5);
+ box-shadow: 0 0 0 3px rgba(255, 255, 255, 0.25), 0 2px 8px rgba(0,0,0,0.5);
transform: translate(-50%, -50%);
cursor: grab;
touch-action: none;
z-index: 2;
transition: box-shadow 0.12s;
}
- .ae-blend-puck:active { cursor: grabbing; box-shadow: 0 0 0 5px rgba(214, 255, 61, 0.35), 0 3px 12px rgba(0,0,0,0.6); }
+ .ae-blend-puck:active { cursor: grabbing; box-shadow: 0 0 0 5px rgba(255, 255, 255, 0.35), 0 3px 12px rgba(0,0,0,0.6); }
.ae-blend-desc {
font-size: 11px;
color: var(--text-3);
diff --git a/pages/embed-demo.html b/pages/embed-demo.html
index 00fc663ab..fbcc996ca 100644
--- a/pages/embed-demo.html
+++ b/pages/embed-demo.html
@@ -21,8 +21,8 @@
--border: #1e1f2b;
--text: #eee;
--muted: #8a8d98;
- --accent: #d6ff3d;
- --accent-ink: #0a0a0a;
+ --accent: #ffffff;
+ --accent-ink: #000000;
}
* { box-sizing: border-box; }
html, body { margin: 0; padding: 0; height: 100%; }
@@ -31,8 +31,8 @@
color: var(--text);
background: var(--bg);
background-image:
- radial-gradient(800px 500px at 20% -10%, rgba(106, 92, 255, 0.12), transparent 70%),
- radial-gradient(700px 400px at 110% 110%, rgba(214, 255, 61, 0.07), transparent 70%);
+ radial-gradient(800px 500px at 20% -10%, rgba(255, 255, 255, 0.04), transparent 70%),
+ radial-gradient(700px 400px at 110% 110%, rgba(255, 255, 255, 0.03), transparent 70%);
}
.wrap { max-width: 1100px; margin: 0 auto; padding: 56px 24px 96px; }
.eyebrow {
@@ -115,8 +115,8 @@
transition: background 0.15s, border-color 0.15s;
}
.controls button:hover {
- background: rgba(214, 255, 61, 0.08);
- border-color: rgba(214, 255, 61, 0.4);
+ background: rgba(255, 255, 255, 0.08);
+ border-color: rgba(255, 255, 255, 0.4);
}
.snippet {
background: #07080d;
@@ -151,7 +151,7 @@
overflow-x: auto;
white-space: pre;
}
- .snippet-large .k { color: #d6ff3d; }
+ .snippet-large .k { color: #ffffff; }
.snippet-large .a { color: #b9c0ff; }
.snippet-large .s { color: #e8b87f; }
diff --git a/pages/import-rpm.html b/pages/import-rpm.html
index 41a56a614..541431c4f 100644
--- a/pages/import-rpm.html
+++ b/pages/import-rpm.html
@@ -21,8 +21,8 @@
--text: #e9ecef;
--text-2: rgba(255,255,255,0.65);
--text-3: rgba(255,255,255,0.38);
- --accent: #7dd3fc;
- --accent-dim: rgba(125,211,252,0.12);
+ --accent: #ffffff;
+ --accent-dim: rgba(255,255,255,0.10);
--warn: #f59e0b;
--warn-dim: rgba(245,158,11,0.10);
--ok: #4ade80;
@@ -166,7 +166,7 @@
}
input[type="text"]:focus, input[type="url"]:focus {
border-color: var(--accent);
- box-shadow: 0 0 0 3px rgba(125,211,252,0.10);
+ box-shadow: 0 0 0 3px rgba(255,255,255,0.10);
}
/* Drop zone */
diff --git a/pages/pump-visualizer.html b/pages/pump-visualizer.html
index 52d1296f4..d49db1dca 100644
--- a/pages/pump-visualizer.html
+++ b/pages/pump-visualizer.html
@@ -13,10 +13,10 @@
:root {
--vz-bg: #05060a;
--vz-panel: rgba(12, 14, 22, 0.88);
- --vz-border: rgba(139, 92, 246, 0.35);
- --vz-text: #e6e7ee;
- --vz-muted: #8a8fa6;
- --vz-accent: #8b5cf6;
+ --vz-border: rgba(255, 255, 255, 0.10);
+ --vz-text: #e8e8e8;
+ --vz-muted: #888888;
+ --vz-accent: #ffffff;
--vz-green: #34d399;
--vz-red: #f87171;
}
@@ -178,7 +178,7 @@
}
.vz-mode button:hover { color: var(--vz-text); }
.vz-mode button.is-active {
- background: rgba(139, 92, 246, 0.22);
+ background: rgba(255, 255, 255, 0.22);
color: var(--vz-text);
border-color: var(--vz-border);
}
@@ -238,7 +238,7 @@
}
.vz-sort button:hover { color: var(--vz-text); }
.vz-sort button.is-active {
- background: rgba(139, 92, 246, 0.18);
+ background: rgba(255, 255, 255, 0.18);
border-color: var(--vz-border);
color: var(--vz-text);
}
@@ -373,7 +373,7 @@
border: 1px solid var(--vz-border);
color: var(--vz-text);
text-decoration: none;
- background: rgba(139, 92, 246, 0.08);
+ background: rgba(255, 255, 255, 0.08);
transition: background 0.15s;
}
.vz-detail .links a:hover { background: var(--accent-soft); }
@@ -513,7 +513,7 @@
flex-direction: column;
align-items: center;
justify-content: center;
- background: radial-gradient(ellipse at center, rgba(139, 92, 246, 0.08) 0%, var(--vz-bg) 70%);
+ background: radial-gradient(ellipse at center, rgba(255, 255, 255, 0.08) 0%, var(--vz-bg) 70%);
pointer-events: none;
opacity: 1;
transition: opacity 0.6s ease 0.2s;
@@ -522,7 +522,7 @@
.vz-intro .ring {
width: 56px; height: 56px;
border-radius: 50%;
- border: 2px solid rgba(139, 92, 246, 0.18);
+ border: 2px solid rgba(255, 255, 255, 0.18);
border-top-color: var(--vz-accent);
animation: vzSpin 1s linear infinite;
}
diff --git a/public/demos/brain.html b/public/demos/brain.html
index f17fa730e..11355734b 100644
--- a/public/demos/brain.html
+++ b/public/demos/brain.html
@@ -107,16 +107,20 @@
font-size: 9px; font-weight: 700; letter-spacing: 0.08em;
text-transform: uppercase; padding: 1px 5px; border-radius: 4px;
}
- .badge-flagship { background: rgba(212,168,122,0.15); color: var(--anthropic); }
- .badge-balanced { background: rgba(61,193,255,0.12); color: var(--accent); }
- .badge-fast { background: rgba(34,209,122,0.12); color: var(--ok); }
+ .badge-flagship { background: rgba(212,168,122,0.15); color: var(--anthropic); }
+ .badge-balanced { background: rgba(61,193,255,0.12); color: var(--accent); }
+ .badge-fast { background: rgba(34,209,122,0.12); color: var(--ok); }
+ .badge-reasoning { background: rgba(167,139,250,0.15); color: var(--groq); }
+ .model-card.unavailable { opacity: 0.45; pointer-events: none; }
+ .model-card.unavailable .model-badge::after { content: ' · unavailable'; }
.model-net { font-size: 10.5px; color: var(--text3); margin-bottom: 4px; }
.model-desc { font-size: 11.5px; color: var(--text2); line-height: 1.4; }
- .net-anthropic { color: var(--anthropic); }
- .net-openai { color: var(--openai); }
- .net-groq { color: var(--groq); }
- .net-alibaba { color: var(--alibaba); }
+ .net-anthropic { color: var(--anthropic); }
+ .net-openai { color: var(--openai); }
+ .net-groq { color: var(--groq); }
+ .net-alibaba { color: var(--alibaba); }
.net-modelscope { color: var(--modelscope); }
+ .net-deepseek { color: #60b8ff; }
/* Chat panel */
.chat-panel {
@@ -530,14 +534,16 @@
<script src="/nav.js"></script>
<script type="module">
const MODELS = [
- { key: 'claude-opus-4-7', label: 'Claude Opus 4.7', network: 'Anthropic', netClass: 'net-anthropic', tier: 'flagship', desc: 'Most capable. Extended thinking, complex reasoning.', compareDefault: false, chatDefault: false },
- { key: 'claude-sonnet-4-6', label: 'Claude Sonnet 4.6', network: 'Anthropic', netClass: 'net-anthropic', tier: 'balanced', desc: 'Balanced speed and intelligence. Best for most tasks.', compareDefault: true, chatDefault: true },
- { key: 'claude-haiku-4-5', label: 'Claude Haiku 4.5', network: 'Anthropic', netClass: 'net-anthropic', tier: 'fast', desc: 'Fastest Claude. Low latency, high throughput.', compareDefault: true, chatDefault: false },
- { key: 'gpt-4o', label: 'GPT-4o', network: 'OpenAI', netClass: 'net-openai', tier: 'flagship', desc: 'OpenAI flagship. Strong multimodal reasoning.', compareDefault: false, chatDefault: false },
- { key: 'gpt-4o-mini', label: 'GPT-4o-mini', network: 'OpenAI', netClass: 'net-openai', tier: 'fast', desc: 'Fast, affordable GPT. Great for simple tasks.', compareDefault: true, chatDefault: false },
- { key: 'groq-llama', label: 'Llama 3.3 70B', network: 'Groq', netClass: 'net-groq', tier: 'fast', desc: 'Open-weight on Groq. Extremely fast inference.', compareDefault: true, chatDefault: false },
- { key: 'qwen-plus', label: 'Qwen Plus', network: 'Alibaba', netClass: 'net-alibaba', tier: 'balanced', desc: 'Qwen Plus on Alibaba DashScope. Strong multilingual.', compareDefault: false, chatDefault: false },
- { key: 'modelscope-qwen', label: 'Qwen3-Coder-480B', network: 'ModelScope', netClass: 'net-modelscope', tier: 'flagship', desc: 'Largest Qwen coder model. Exceptional at code generation.', compareDefault: false, chatDefault: false },
+ { key: 'claude-opus-4-7', label: 'Claude Opus 4.7', network: 'Anthropic', netClass: 'net-anthropic', tier: 'flagship', desc: 'Most capable. Extended thinking, complex reasoning.', compareDefault: false, chatDefault: false },
+ { key: 'claude-sonnet-4-6', label: 'Claude Sonnet 4.6', network: 'Anthropic', netClass: 'net-anthropic', tier: 'balanced', desc: 'Balanced speed and intelligence. Best for most tasks.', compareDefault: true, chatDefault: true },
+ { key: 'claude-haiku-4-5', label: 'Claude Haiku 4.5', network: 'Anthropic', netClass: 'net-anthropic', tier: 'fast', desc: 'Fastest Claude. Low latency, high throughput.', compareDefault: true, chatDefault: false },
+ { key: 'gpt-4o', label: 'GPT-4o', network: 'OpenAI', netClass: 'net-openai', tier: 'flagship', desc: 'OpenAI flagship. Strong multimodal reasoning.', compareDefault: false, chatDefault: false },
+ { key: 'gpt-4o-mini', label: 'GPT-4o-mini', network: 'OpenAI', netClass: 'net-openai', tier: 'fast', desc: 'Fast, affordable GPT. Great for simple tasks.', compareDefault: true, chatDefault: false },
+ { key: 'o3-mini', label: 'o3-mini', network: 'OpenAI', netClass: 'net-openai', tier: 'reasoning', desc: 'Reasoning-optimized. Fast chain-of-thought.', compareDefault: false, chatDefault: false },
+ { key: 'groq-llama', label: 'Llama 3.3 70B', network: 'Groq', netClass: 'net-groq', tier: 'fast', desc: 'Open-weight on Groq. Extremely fast inference.', compareDefault: true, chatDefault: false },
+ { key: 'deepseek-r1', label: 'DeepSeek R1', network: 'DeepSeek', netClass: 'net-deepseek', tier: 'reasoning', desc: 'Open reasoning model. Strong at math and code.', compareDefault: false, chatDefault: false },
+ { key: 'qwen-plus', label: 'Qwen Plus', network: 'DashScope', netClass: 'net-alibaba', tier: 'balanced', desc: 'Qwen Plus on DashScope. Strong multilingual.', compareDefault: false, chatDefault: false },
+ { key: 'modelscope-qwen', label: 'Qwen3-Coder 480B', network: 'ModelScope', netClass: 'net-modelscope', tier: 'flagship', desc: 'Largest Qwen coder. Exceptional at code generation.', compareDefault: false, chatDefault: false },
];
const TIER_LABEL = { flagship: 'Flagship', balanced: 'Balanced', fast: 'Fast' };
const STORAGE_KEY = 'brain_v2';
@@ -1083,6 +1089,32 @@ cmpPrompt.addEventListener('keydown', e => { if (e.key === 'Enter' && (e.metaKey
buildSidebar();
selectModel(activeModel);
renderHistory();
+
+// Fetch available providers and dim unavailable ones
+fetch('/api/brain/chat')
+ .then(r => r.json())
+ .then(({ providers }) => {
+ if (!Array.isArray(providers)) return;
+ const unavailable = new Set(providers.filter(p => !p.available).map(p => p.key));
+ document.querySelectorAll('.model-card').forEach(card => {
+ if (unavailable.has(card.dataset.key)) {
+ card.classList.add('unavailable');
+ if (card.classList.contains('selected')) {
+ const first = providers.find(p => p.available);
+ if (first) selectModel(first.key);
+ }
+ }
+ });
+ document.querySelectorAll('.provider-pill input').forEach(input => {
+ if (unavailable.has(input.dataset.key)) {
+ input.disabled = true;
+ input.checked = false;
+ input.closest('.provider-pill').style.opacity = '0.4';
+ input.closest('.provider-pill').title = 'Not configured on this deployment';
+ }
+ });
+ })
+ .catch(() => {});
</script>
</body>
</html>
diff --git a/public/demos/index.html b/public/demos/index.html
index ec9910659..3cee18bc1 100644
--- a/public/demos/index.html
+++ b/public/demos/index.html
@@ -181,10 +181,10 @@
<p>Three-tier pricing table. Hover any tier and the avatar leaps to its top edge with a debounced jump arc, lands with a card-thump, and uses the reaction clip to point down at the CTA.</p>
<span class="demo-status beta">Beta</span>
</a>
- <a class="demo-card" href="/demos/selfie-fit.html">
+ <a class="demo-card demo-card--feature" href="/demos/selfie-fit.html">
<h2>Selfie Fit — avatar from your face</h2>
- <p>Snap a selfie, fit a head texture to the default rig, and preview the result in the same scene the SDK ships with.</p>
- <span class="demo-status beta">Beta</span>
+ <p>Real-time 468-point face mesh with quality gates (yaw, blur, lighting, centering), three-angle capture, and head-pose estimation. Now integrated into <code>/create/selfie</code>, dashboard, and agent pages as a production feature.</p>
+ <span class="demo-status feature">Feature</span>
</a>
<a class="demo-card" href="/demos/gallery-picker.html">
<h2>Avatar gallery picker</h2>
diff --git a/public/nav.html b/public/nav.html
index 0de3df159..f6115ae72 100644
--- a/public/nav.html
+++ b/public/nav.html
@@ -53,6 +53,18 @@
><span class="nav-mi-sub">Khronos spec check</span></a
>
</li>
+ <li role="none">
+ <a href="/brain" role="menuitem"
+ ><span class="nav-mi-title">Brain<span class="nav-pill" aria-hidden="true">NEW</span></span
+ ><span class="nav-mi-sub">Persona builder + multi-model playground</span></a
+ >
+ </li>
+ <li role="none">
+ <a href="/voice" role="menuitem"
+ ><span class="nav-mi-title">Voice Lab<span class="nav-pill" aria-hidden="true">NEW</span></span
+ ><span class="nav-mi-sub">Clone your voice · TTS playground</span></a
+ >
+ </li>
</ul>
</li>
<li class="nav-item" role="none">
@@ -207,6 +219,12 @@
<li class="nav-menu-note" role="none" aria-hidden="true">
Experimental features — actively iterating. Expect rough edges.
</li>
+ <li role="none">
+ <a href="/voice" role="menuitem"
+ ><span class="nav-mi-title">Voice Lab<span class="nav-pill" aria-hidden="true">NEW</span></span
+ ><span class="nav-mi-sub">Clone your voice · TTS playground · assign to avatars</span></a
+ >
+ </li>
<li role="none">
<a href="/launchpad" role="menuitem"
><span class="nav-mi-title">Launchpad Studio<span class="nav-pill" aria-hidden="true">NEW</span></span
@@ -215,8 +233,8 @@
</li>
<li role="none">
<a href="/brain" role="menuitem"
- ><span class="nav-mi-title">Brain</span
- ><span class="nav-mi-sub">Chat &amp; compare — Claude, GPT, Llama, Qwen with real metrics</span></a
+ ><span class="nav-mi-title">Brain<span class="nav-pill" aria-hidden="true">NEW</span></span
+ ><span class="nav-mi-sub">Persona builder + multi-model playground</span></a
>
</li>
<li role="none">
diff --git a/src/avatar-gallery-picker.css b/src/avatar-gallery-picker.css
new file mode 100644
index 000000000..a35376771
--- /dev/null
+++ b/src/avatar-gallery-picker.css
@@ -0,0 +1,561 @@
+/* ── Avatar Gallery Picker ────────────────────────────────────────────────
+ Reusable avatar browser with search, tag filters, grid, 3D preview,
+ and multiple handoff modes. Works as a modal overlay or inline embed.
+
+ Uses theme.css tokens (--t-*) for consistency with the monochrome system.
+ ─────────────────────────────────────────────────────────────────────── */
+
+/* ── Overlay (modal mode) ───────────────────────────────────────────── */
+
+.agp-overlay {
+ position: fixed;
+ inset: 0;
+ z-index: 1000;
+ background: rgba(0, 0, 0, 0.72);
+ backdrop-filter: blur(8px);
+ -webkit-backdrop-filter: blur(8px);
+ display: grid;
+ place-items: center;
+ padding: 20px;
+ opacity: 0;
+ transition: opacity 180ms ease;
+}
+.agp-overlay.agp-open { opacity: 1; }
+
+/* ── Shell (the card — used in both modal and inline mode) ──────────── */
+
+.agp-shell {
+ width: 100%;
+ max-width: 1080px;
+ max-height: calc(100vh - 40px);
+ background: var(--t-bg-1, #0a0a0a);
+ border: 1px solid var(--t-stroke, #1a1a1a);
+ border-radius: 14px;
+ display: flex;
+ flex-direction: column;
+ overflow: hidden;
+ box-shadow: 0 24px 80px rgba(0, 0, 0, 0.6);
+ transform: translateY(8px);
+ transition: transform 180ms ease;
+}
+.agp-open .agp-shell { transform: translateY(0); }
+
+/* Inline mode — no shadow or max-height, fills its container */
+.agp-shell--inline {
+ max-height: none;
+ box-shadow: none;
+ border-radius: 12px;
+ transform: none;
+}
+
+/* ── Header ─────────────────────────────────────────────────────────── */
+
+.agp-header {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+ padding: 14px 18px;
+ border-bottom: 1px solid var(--t-stroke, #1a1a1a);
+ flex-shrink: 0;
+}
+.agp-title {
+ font-size: 15px;
+ font-weight: 600;
+ color: var(--t-ink, #e8e8e8);
+ flex: 1;
+ min-width: 0;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+.agp-close {
+ width: 28px;
+ height: 28px;
+ display: grid;
+ place-items: center;
+ background: transparent;
+ border: 1px solid var(--t-stroke, #1a1a1a);
+ border-radius: 8px;
+ color: var(--t-ink-dim, #888);
+ cursor: pointer;
+ font-size: 16px;
+ line-height: 1;
+ transition: background 120ms ease, color 120ms ease, border-color 120ms ease;
+ flex-shrink: 0;
+}
+.agp-close:hover {
+ background: var(--t-glass-strong, rgba(255,255,255,0.08));
+ color: var(--t-ink, #e8e8e8);
+ border-color: var(--t-stroke-strong, #2a2a2a);
+}
+
+/* ── Toolbar (search + status) ──────────────────────────────────────── */
+
+.agp-toolbar {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ padding: 12px 18px;
+ flex-shrink: 0;
+}
+.agp-search {
+ flex: 1 1 220px;
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 8px 12px;
+ background: var(--t-glass, rgba(255,255,255,0.04));
+ border: 1px solid var(--t-stroke, #1a1a1a);
+ border-radius: 10px;
+ transition: border-color 150ms ease, background 150ms ease;
+}
+.agp-search:focus-within {
+ border-color: var(--t-stroke-strong, #2a2a2a);
+ background: var(--t-glass-strong, rgba(255,255,255,0.08));
+}
+.agp-search svg {
+ flex-shrink: 0;
+ color: var(--t-ink-faint, #555);
+}
+.agp-search input {
+ flex: 1;
+ background: transparent;
+ border: 0;
+ outline: 0;
+ color: var(--t-ink, #e8e8e8);
+ font: inherit;
+ font-size: 13px;
+ min-width: 0;
+}
+.agp-search input::placeholder { color: var(--t-ink-faint, #555); }
+.agp-search-clear {
+ background: transparent;
+ border: 0;
+ color: var(--t-ink-faint, #555);
+ cursor: pointer;
+ padding: 2px 4px;
+ font-size: 14px;
+ line-height: 1;
+ transition: color 120ms ease;
+}
+.agp-search-clear:hover { color: var(--t-ink, #e8e8e8); }
+.agp-status {
+ font-size: 12px;
+ color: var(--t-ink-faint, #555);
+ flex-shrink: 0;
+ white-space: nowrap;
+}
+
+/* ── Tags ───────────────────────────────────────────────────────────── */
+
+.agp-tags {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 5px;
+ padding: 0 18px 10px;
+ flex-shrink: 0;
+ min-height: 0;
+}
+.agp-tag {
+ background: var(--t-glass, rgba(255,255,255,0.04));
+ color: var(--t-ink-dim, #888);
+ border: 1px solid var(--t-stroke, #1a1a1a);
+ border-radius: 999px;
+ padding: 4px 10px;
+ font: inherit;
+ font-size: 11.5px;
+ cursor: pointer;
+ transition: all 120ms ease;
+}
+.agp-tag:hover {
+ border-color: var(--t-stroke-strong, #2a2a2a);
+ color: var(--t-ink, #e8e8e8);
+}
+.agp-tag.active {
+ background: var(--t-accent, #fff);
+ color: var(--t-accent-ink, #000);
+ border-color: var(--t-accent, #fff);
+}
+
+/* ── Body (scrollable area: grid + preview) ─────────────────────────── */
+
+.agp-body {
+ flex: 1;
+ min-height: 0;
+ display: grid;
+ grid-template-columns: 1fr 340px;
+ gap: 0;
+ overflow: hidden;
+}
+
+/* ── Grid column ────────────────────────────────────────────────────── */
+
+.agp-grid-col {
+ overflow-y: auto;
+ padding: 12px 18px 18px;
+ border-right: 1px solid var(--t-stroke, #1a1a1a);
+}
+.agp-grid {
+ display: grid;
+ gap: 10px;
+ grid-template-columns: repeat(3, minmax(0, 1fr));
+}
+
+/* ── Card ───────────────────────────────────────────────────────────── */
+
+.agp-card {
+ background: var(--t-bg-2, #111);
+ border: 1.5px solid var(--t-stroke, #1a1a1a);
+ border-radius: 10px;
+ overflow: hidden;
+ cursor: pointer;
+ display: flex;
+ flex-direction: column;
+ text-align: left;
+ color: inherit;
+ font: inherit;
+ padding: 0;
+ transition: border-color 120ms ease, transform 120ms ease, box-shadow 120ms ease;
+}
+.agp-card:hover {
+ border-color: var(--t-stroke-strong, #2a2a2a);
+ transform: translateY(-1px);
+ box-shadow: 0 4px 16px rgba(0, 0, 0, 0.3);
+}
+.agp-card.selected {
+ border-color: var(--t-accent, #fff);
+ box-shadow: 0 0 0 1px var(--t-accent, #fff) inset, 0 4px 20px rgba(255, 255, 255, 0.06);
+}
+.agp-card-thumb {
+ aspect-ratio: 1 / 1;
+ background: var(--t-bg-3, #1a1a1a);
+ position: relative;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ overflow: hidden;
+}
+.agp-card-thumb img {
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ display: block;
+}
+.agp-card-ph {
+ width: 100%;
+ height: 100%;
+ background: linear-gradient(135deg, var(--t-bg-3, #1a1a1a) 0%, var(--t-bg-2, #111) 100%);
+ display: flex;
+ align-items: center;
+ justify-content: center;
+}
+.agp-card-ph svg {
+ width: 32px;
+ height: 32px;
+ color: var(--t-ink-faint, #555);
+ opacity: 0.5;
+}
+.agp-card-body {
+ padding: 8px 10px 10px;
+}
+.agp-card-name {
+ font-size: 12.5px;
+ font-weight: 600;
+ color: var(--t-ink, #e8e8e8);
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ margin: 0 0 3px;
+}
+.agp-card-meta {
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ flex-wrap: wrap;
+}
+.agp-card-chip {
+ font-size: 10px;
+ color: var(--t-ink-faint, #555);
+ background: var(--t-glass, rgba(255,255,255,0.04));
+ border-radius: 999px;
+ padding: 1px 6px;
+}
+
+/* ── Preview column ─────────────────────────────────────────────────── */
+
+.agp-preview-col {
+ display: flex;
+ flex-direction: column;
+ padding: 14px;
+ gap: 12px;
+ overflow-y: auto;
+}
+.agp-preview-stage {
+ aspect-ratio: 1 / 1;
+ border-radius: 10px;
+ overflow: hidden;
+ background: var(--t-bg-0, #000);
+ border: 1px solid var(--t-stroke, #1a1a1a);
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ flex-shrink: 0;
+}
+.agp-preview-stage model-viewer {
+ width: 100%;
+ height: 100%;
+ --poster-color: transparent;
+ background: var(--t-bg-0, #000);
+}
+.agp-preview-empty {
+ color: var(--t-ink-faint, #555);
+ font-size: 12.5px;
+ text-align: center;
+ padding: 0 16px;
+ line-height: 1.5;
+}
+.agp-preview-name {
+ font-size: 15px;
+ font-weight: 600;
+ color: var(--t-ink, #e8e8e8);
+ margin: 0;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+.agp-preview-sub {
+ color: var(--t-ink-dim, #888);
+ font-size: 12px;
+ margin: -4px 0 0;
+}
+.agp-preview-tags {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 4px;
+}
+.agp-preview-tag {
+ font-size: 10.5px;
+ color: var(--t-ink-dim, #888);
+ background: var(--t-glass, rgba(255,255,255,0.04));
+ border: 1px solid var(--t-stroke, #1a1a1a);
+ border-radius: 999px;
+ padding: 2px 8px;
+}
+
+/* ── Mode radio (share / glb / embed) ───────────────────────────────── */
+
+.agp-modes {
+ display: flex;
+ gap: 3px;
+ background: var(--t-bg-0, #000);
+ border: 1px solid var(--t-stroke, #1a1a1a);
+ border-radius: 9px;
+ padding: 3px;
+}
+.agp-modes label {
+ flex: 1;
+ text-align: center;
+ cursor: pointer;
+}
+.agp-modes input { display: none; }
+.agp-modes span {
+ display: block;
+ padding: 6px 4px;
+ border-radius: 7px;
+ font-size: 11.5px;
+ color: var(--t-ink-dim, #888);
+ transition: background 120ms ease, color 120ms ease;
+}
+.agp-modes input:checked + span {
+ background: var(--t-glass-strong, rgba(255,255,255,0.08));
+ color: var(--t-ink, #e8e8e8);
+}
+
+/* ── CTA button ─────────────────────────────────────────────────────── */
+
+.agp-cta {
+ background: var(--t-accent, #fff);
+ color: var(--t-accent-ink, #000);
+ border: 0;
+ border-radius: 9px;
+ padding: 10px 14px;
+ font-weight: 600;
+ font: inherit;
+ font-size: 13px;
+ font-weight: 600;
+ cursor: pointer;
+ width: 100%;
+ transition: opacity 120ms ease;
+}
+.agp-cta:disabled { opacity: 0.35; cursor: not-allowed; }
+.agp-cta.copied { background: var(--t-success, #4ade80); }
+
+/* ── Payload footer ─────────────────────────────────────────────────── */
+
+.agp-payload {
+ font-family: ui-monospace, 'SF Mono', monospace;
+ font-size: 11px;
+ color: var(--t-ink-dim, #888);
+ background: var(--t-bg-0, #000);
+ border: 1px solid var(--t-stroke, #1a1a1a);
+ border-radius: 8px;
+ padding: 8px 10px;
+ word-break: break-all;
+ max-height: 80px;
+ overflow: auto;
+ white-space: pre-wrap;
+}
+
+/* ── Loading / empty / error states ─────────────────────────────────── */
+
+.agp-loading {
+ grid-column: 1 / -1;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 12px;
+ padding: 48px 16px;
+}
+.agp-spinner {
+ width: 24px;
+ height: 24px;
+ border: 2px solid var(--t-stroke, #1a1a1a);
+ border-top-color: var(--t-ink-dim, #888);
+ border-radius: 50%;
+ animation: agp-spin 0.8s linear infinite;
+}
+@keyframes agp-spin { to { transform: rotate(360deg); } }
+
+.agp-empty, .agp-error {
+ grid-column: 1 / -1;
+ padding: 36px 16px;
+ text-align: center;
+ color: var(--t-ink-faint, #555);
+ border: 1.5px dashed var(--t-stroke, #1a1a1a);
+ border-radius: 10px;
+ font-size: 13px;
+ line-height: 1.5;
+}
+.agp-error { color: var(--t-danger, #f87171); border-color: rgba(248, 113, 113, 0.2); }
+
+/* ── Load more ──────────────────────────────────────────────────────── */
+
+.agp-loadmore {
+ grid-column: 1 / -1;
+ display: flex;
+ justify-content: center;
+ padding: 14px 0 4px;
+}
+.agp-loadmore-btn {
+ background: var(--t-glass, rgba(255,255,255,0.04));
+ color: var(--t-ink, #e8e8e8);
+ border: 1px solid var(--t-stroke, #1a1a1a);
+ border-radius: 8px;
+ padding: 8px 18px;
+ font: inherit;
+ font-size: 12.5px;
+ cursor: pointer;
+ transition: border-color 120ms ease, background 120ms ease;
+}
+.agp-loadmore-btn:hover {
+ border-color: var(--t-stroke-strong, #2a2a2a);
+ background: var(--t-glass-strong, rgba(255,255,255,0.08));
+}
+.agp-loadmore-btn:disabled { opacity: 0.5; cursor: not-allowed; }
+
+/* ── Skeleton cards ─────────────────────────────────────────────────── */
+
+.agp-skel {
+ background: var(--t-bg-2, #111);
+ border: 1.5px solid var(--t-stroke, #1a1a1a);
+ border-radius: 10px;
+ overflow: hidden;
+}
+.agp-skel-thumb {
+ aspect-ratio: 1 / 1;
+ background: linear-gradient(110deg, var(--t-bg-3, #1a1a1a) 30%, var(--t-bg-2, #111) 50%, var(--t-bg-3, #1a1a1a) 70%);
+ background-size: 200% 100%;
+ animation: agp-shimmer 1.4s ease-in-out infinite;
+}
+.agp-skel-bar {
+ height: 10px;
+ margin: 8px 10px;
+ border-radius: 4px;
+ background: var(--t-bg-3, #1a1a1a);
+}
+.agp-skel-bar:last-child { width: 55%; margin-top: 4px; }
+@keyframes agp-shimmer {
+ 0% { background-position: 200% 0; }
+ 100% { background-position: -200% 0; }
+}
+
+/* ── Source toggle (my avatars / public) ─────────────────────────────── */
+
+.agp-source-toggle {
+ display: flex;
+ gap: 3px;
+ background: var(--t-bg-0, #000);
+ border: 1px solid var(--t-stroke, #1a1a1a);
+ border-radius: 9px;
+ padding: 3px;
+ flex-shrink: 0;
+}
+.agp-source-btn {
+ padding: 6px 12px;
+ border-radius: 7px;
+ font: inherit;
+ font-size: 12px;
+ color: var(--t-ink-dim, #888);
+ background: transparent;
+ border: 0;
+ cursor: pointer;
+ transition: background 120ms ease, color 120ms ease;
+ white-space: nowrap;
+}
+.agp-source-btn.active {
+ background: var(--t-glass-strong, rgba(255,255,255,0.08));
+ color: var(--t-ink, #e8e8e8);
+}
+.agp-source-btn:hover:not(.active) {
+ color: var(--t-ink, #e8e8e8);
+}
+
+/* ── Responsive ─────────────────────────────────────────────────────── */
+
+@media (max-width: 860px) {
+ .agp-body {
+ grid-template-columns: 1fr;
+ }
+ .agp-grid-col {
+ border-right: 0;
+ border-bottom: 1px solid var(--t-stroke, #1a1a1a);
+ max-height: 50vh;
+ }
+ .agp-preview-col {
+ max-height: 50vh;
+ }
+ .agp-preview-stage {
+ aspect-ratio: auto;
+ height: 240px;
+ }
+ .agp-grid {
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ }
+}
+
+@media (max-width: 520px) {
+ .agp-shell {
+ max-height: calc(100vh - 20px);
+ border-radius: 10px;
+ }
+ .agp-overlay { padding: 10px; }
+ .agp-header { padding: 10px 14px; }
+ .agp-toolbar { padding: 8px 14px; flex-wrap: wrap; }
+ .agp-tags { padding: 0 14px 8px; }
+ .agp-grid-col { padding: 10px 14px 14px; }
+ .agp-preview-col { padding: 10px; }
+ .agp-grid {
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ gap: 8px;
+ }
+}
diff --git a/src/avatar-gallery-picker.js b/src/avatar-gallery-picker.js
new file mode 100644
index 000000000..e3b2f4075
--- /dev/null
+++ b/src/avatar-gallery-picker.js
@@ -0,0 +1,558 @@
+/**
+ * AvatarGalleryPicker — reusable avatar browser component.
+ *
+ * Opens as a modal overlay or mounts inline. Fetches avatars from
+ * /api/avatars/public (browse mode) or /api/avatars (user's own),
+ * renders a searchable/filterable grid with live 3D preview, and
+ * fires a callback with the selected avatar.
+ *
+ * Usage:
+ *
+ * // Modal mode — resolves with selected avatar or null
+ * import { openAvatarPicker } from './avatar-gallery-picker.js';
+ * const avatar = await openAvatarPicker({ source: 'public' });
+ *
+ * // With pre-selected avatar
+ * const avatar = await openAvatarPicker({ source: 'mine', selectedId: 'abc' });
+ */
+
+import './avatar-gallery-picker.css';
+
+const PAGE_SIZE = 24;
+
+function esc(s) {
+ return String(s ?? '')
+ .replace(/&/g, '&amp;')
+ .replace(/</g, '&lt;')
+ .replace(/>/g, '&gt;')
+ .replace(/"/g, '&quot;');
+}
+
+const compact = new Intl.NumberFormat('en', { notation: 'compact', maximumFractionDigits: 1 });
+const integer = new Intl.NumberFormat('en');
+
+const AVATAR_PH_SVG = `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="8" r="4"/><path d="M4 21c1.5-4.5 4.5-7 8-7s6.5 2.5 8 7"/></svg>`;
+const SEARCH_SVG = `<svg viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"><circle cx="7" cy="7" r="4.5"/><path d="m10.5 10.5 3 3"/></svg>`;
+
+export class AvatarGalleryPicker {
+ /**
+ * @param {Object} opts
+ * @param {'public'|'mine'|'both'} [opts.source='both'] Which API to fetch from
+ * @param {string} [opts.title='Choose an avatar']
+ * @param {string} [opts.selectedId] Pre-selected avatar ID
+ * @param {boolean} [opts.showModes=true] Show share/glb/embed handoff modes
+ * @param {string} [opts.ctaLabel='Select avatar'] Label for the CTA button
+ * @param {Function} [opts.onSelect] Callback with the selected avatar object
+ * @param {Function} [opts.onClose] Called when the picker is closed
+ */
+ constructor(opts = {}) {
+ this.opts = {
+ source: opts.source || 'both',
+ title: opts.title || 'Choose an avatar',
+ selectedId: opts.selectedId || '',
+ showModes: opts.showModes !== false,
+ ctaLabel: opts.ctaLabel || 'Select avatar',
+ onSelect: opts.onSelect || (() => {}),
+ onClose: opts.onClose || (() => {}),
+ };
+
+ this._state = {
+ query: '',
+ tag: '',
+ cursor: null,
+ loading: false,
+ total: null,
+ totalLoaded: 0,
+ selected: null,
+ mode: 'share',
+ loadedTags: new Set(),
+ cardsById: new Map(),
+ firstPageDone: false,
+ activeSource: this.opts.source === 'both' ? 'public' : this.opts.source,
+ };
+
+ this._overlay = null;
+ this._shell = null;
+ this._els = {};
+ this._io = null;
+ this._searchTimer = null;
+ this._copyTimer = null;
+ this._onKey = this._onKey.bind(this);
+ }
+
+ // ── Public API ──────────────────────────────────────────────────────
+
+ openModal() {
+ if (this._overlay) return;
+
+ this._overlay = document.createElement('div');
+ this._overlay.className = 'agp-overlay';
+ this._overlay.addEventListener('click', (e) => {
+ if (e.target === this._overlay) this.close();
+ });
+
+ this._shell = this._buildShell();
+ this._overlay.appendChild(this._shell);
+ document.body.appendChild(this._overlay);
+ document.addEventListener('keydown', this._onKey);
+
+ requestAnimationFrame(() => {
+ this._overlay.classList.add('agp-open');
+ this._els.searchInput?.focus();
+ });
+
+ this._loadPage();
+ }
+
+ mountInline(container) {
+ this._shell = this._buildShell();
+ this._shell.classList.add('agp-shell--inline');
+ const close = this._shell.querySelector('.agp-close');
+ if (close) close.remove();
+ container.appendChild(this._shell);
+ this._loadPage();
+ }
+
+ close() {
+ if (this._io) { this._io.disconnect(); this._io = null; }
+ document.removeEventListener('keydown', this._onKey);
+ if (this._overlay) {
+ this._overlay.classList.remove('agp-open');
+ setTimeout(() => { this._overlay.remove(); this._overlay = null; }, 200);
+ } else if (this._shell) {
+ this._shell.remove();
+ }
+ this._shell = null;
+ this.opts.onClose();
+ }
+
+ getSelected() { return this._state.selected; }
+
+ // ── Build ───────────────────────────────────────────────────────────
+
+ _buildShell() {
+ const shell = document.createElement('div');
+ shell.className = 'agp-shell';
+
+ const showSourceToggle = this.opts.source === 'both';
+ const showModes = this.opts.showModes;
+
+ shell.innerHTML = `
+ <div class="agp-header">
+ <span class="agp-title">${esc(this.opts.title)}</span>
+ <button type="button" class="agp-close" aria-label="Close">&times;</button>
+ </div>
+
+ <div class="agp-toolbar">
+ ${showSourceToggle ? `
+ <div class="agp-source-toggle" role="tablist" aria-label="Avatar source">
+ <button type="button" class="agp-source-btn${this._state.activeSource === 'public' ? ' active' : ''}" data-source="public">Public gallery</button>
+ <button type="button" class="agp-source-btn${this._state.activeSource === 'mine' ? ' active' : ''}" data-source="mine">My avatars</button>
+ </div>
+ ` : ''}
+ <div class="agp-search">
+ ${SEARCH_SVG}
+ <input type="text" placeholder="Search avatars..." autocomplete="off" aria-label="Search avatars" />
+ <button type="button" class="agp-search-clear" hidden aria-label="Clear">&times;</button>
+ </div>
+ <span class="agp-status" aria-live="polite">Loading...</span>
+ </div>
+
+ <div class="agp-tags" aria-label="Tag filters"></div>
+
+ <div class="agp-body">
+ <div class="agp-grid-col">
+ <div class="agp-grid"></div>
+ </div>
+ <div class="agp-preview-col">
+ <div class="agp-preview-stage">
+ <div class="agp-preview-empty">Select an avatar to preview</div>
+ </div>
+ <h2 class="agp-preview-name">No avatar selected</h2>
+ <p class="agp-preview-sub">Browse and pick an avatar</p>
+ <div class="agp-preview-tags"></div>
+ ${showModes ? `
+ <div class="agp-modes" role="radiogroup" aria-label="Output mode">
+ <label><input type="radio" name="agp-mode" value="share" checked /><span>Share link</span></label>
+ <label><input type="radio" name="agp-mode" value="glb" /><span>GLB URL</span></label>
+ <label><input type="radio" name="agp-mode" value="embed" /><span>Embed</span></label>
+ </div>
+ <div class="agp-payload">Selected payload appears here</div>
+ ` : ''}
+ <button type="button" class="agp-cta" disabled>${esc(this.opts.ctaLabel)}</button>
+ </div>
+ </div>
+ `;
+
+ this._els = {
+ searchInput: shell.querySelector('.agp-search input'),
+ searchClear: shell.querySelector('.agp-search-clear'),
+ status: shell.querySelector('.agp-status'),
+ tags: shell.querySelector('.agp-tags'),
+ grid: shell.querySelector('.agp-grid'),
+ gridCol: shell.querySelector('.agp-grid-col'),
+ previewStage: shell.querySelector('.agp-preview-stage'),
+ previewName: shell.querySelector('.agp-preview-name'),
+ previewSub: shell.querySelector('.agp-preview-sub'),
+ previewTags: shell.querySelector('.agp-preview-tags'),
+ payload: shell.querySelector('.agp-payload'),
+ cta: shell.querySelector('.agp-cta'),
+ };
+
+ this._wireEvents(shell);
+ return shell;
+ }
+
+ _wireEvents(shell) {
+ shell.querySelector('.agp-close')?.addEventListener('click', () => this.close());
+
+ // Source toggle
+ shell.querySelectorAll('.agp-source-btn').forEach((btn) => {
+ btn.addEventListener('click', () => {
+ const src = btn.dataset.source;
+ if (src === this._state.activeSource) return;
+ this._state.activeSource = src;
+ shell.querySelectorAll('.agp-source-btn').forEach((b) =>
+ b.classList.toggle('active', b === btn));
+ this._resetAndLoad();
+ });
+ });
+
+ // Search
+ this._els.searchInput.addEventListener('input', () => {
+ this._els.searchClear.hidden = !this._els.searchInput.value;
+ clearTimeout(this._searchTimer);
+ this._searchTimer = setTimeout(() => {
+ this._state.query = this._els.searchInput.value.trim();
+ this._resetAndLoad();
+ }, 250);
+ });
+
+ this._els.searchClear.addEventListener('click', () => {
+ this._els.searchInput.value = '';
+ this._els.searchClear.hidden = true;
+ this._state.query = '';
+ this._resetAndLoad();
+ this._els.searchInput.focus();
+ });
+
+ // Tags
+ this._els.tags.addEventListener('click', (e) => {
+ const btn = e.target.closest('.agp-tag');
+ if (!btn) return;
+ this._state.tag = btn.dataset.tag === this._state.tag ? '' : btn.dataset.tag;
+ this._renderTags();
+ this._resetAndLoad();
+ });
+
+ // Mode radio
+ shell.querySelectorAll('input[name="agp-mode"]').forEach((input) => {
+ input.addEventListener('change', () => {
+ if (!input.checked) return;
+ this._state.mode = input.value;
+ this._updatePayload();
+ });
+ });
+
+ // CTA
+ this._els.cta.addEventListener('click', () => {
+ if (!this._state.selected) return;
+ if (this.opts.showModes) {
+ this._copyPayload();
+ } else {
+ this.opts.onSelect(this._state.selected);
+ this.close();
+ }
+ });
+
+ // Infinite scroll
+ this._setupInfiniteScroll();
+ }
+
+ _setupInfiniteScroll() {
+ if (!('IntersectionObserver' in window)) return;
+ const sentinel = document.createElement('div');
+ sentinel.style.height = '1px';
+ sentinel.className = 'agp-sentinel';
+ this._els.grid.parentNode.appendChild(sentinel);
+
+ this._io = new IntersectionObserver((entries) => {
+ for (const entry of entries) {
+ if (entry.isIntersecting && this._state.cursor && !this._state.loading) {
+ this._loadPage();
+ }
+ }
+ }, { root: this._els.gridCol, rootMargin: '300px 0px' });
+ this._io.observe(sentinel);
+ }
+
+ // ── Data ────────────────────────────────────────────────────────────
+
+ _resetAndLoad() {
+ this._state.cursor = null;
+ this._state.totalLoaded = 0;
+ this._state.total = null;
+ this._state.loadedTags = new Set();
+ this._state.firstPageDone = false;
+ this._state.cardsById = new Map();
+ this._els.grid.innerHTML = '';
+ this._renderSkeletons(6);
+ this._loadPage();
+ }
+
+ async _loadPage() {
+ if (this._state.loading) return;
+ this._state.loading = true;
+ this._updateStatus();
+
+ const isPublic = this._state.activeSource === 'public';
+ const baseUrl = isPublic ? '/api/avatars/public' : '/api/avatars';
+ const params = new URLSearchParams();
+ if (this._state.query) params.set('q', this._state.query);
+ if (this._state.tag) params.set('tag', this._state.tag);
+ if (this._state.cursor) params.set('cursor', this._state.cursor);
+ params.set('limit', String(PAGE_SIZE));
+ if (!this._state.firstPageDone) params.set('totals', '1');
+
+ try {
+ const res = await fetch(`${baseUrl}?${params.toString()}`, { credentials: 'include' });
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
+ const data = await res.json();
+ const avatars = Array.isArray(data.avatars) ? data.avatars : [];
+
+ // Clear skeletons on first page
+ if (!this._state.firstPageDone) {
+ this._els.grid.innerHTML = '';
+ }
+
+ for (const a of avatars) {
+ this._state.cardsById.set(a.id, a);
+ this._els.grid.appendChild(this._renderCard(a));
+ this._state.totalLoaded += 1;
+ for (const t of a.tags || []) this._state.loadedTags.add(t);
+ }
+
+ if (!this._state.firstPageDone) {
+ if (typeof data.total === 'number') this._state.total = data.total;
+ this._state.firstPageDone = true;
+ }
+
+ this._state.cursor = data.next_cursor || null;
+
+ if (this._els.grid.children.length === 0) {
+ const empty = document.createElement('div');
+ empty.className = 'agp-empty';
+ empty.textContent = this._state.query || this._state.tag
+ ? 'No avatars match these filters.'
+ : isPublic ? 'No public avatars yet.' : 'You don\'t have any avatars yet.';
+ this._els.grid.appendChild(empty);
+ }
+
+ this._renderTags();
+ this._hydratePreselection();
+ } catch (err) {
+ if (this._state.totalLoaded === 0) {
+ this._els.grid.innerHTML = '';
+ const errDiv = document.createElement('div');
+ errDiv.className = 'agp-error';
+ errDiv.textContent = `Failed to load: ${err.message}`;
+ this._els.grid.appendChild(errDiv);
+ }
+ } finally {
+ this._state.loading = false;
+ this._updateStatus();
+ }
+ }
+
+ _hydratePreselection() {
+ if (!this.opts.selectedId || this._state.selected) return;
+ const match = this._state.cardsById.get(this.opts.selectedId);
+ if (match) this._selectAvatar(match);
+ }
+
+ // ── Rendering ───────────────────────────────────────────────────────
+
+ _renderSkeletons(n) {
+ for (let i = 0; i < n; i++) {
+ const sk = document.createElement('div');
+ sk.className = 'agp-skel';
+ sk.innerHTML = `<div class="agp-skel-thumb"></div><div class="agp-skel-bar"></div><div class="agp-skel-bar"></div>`;
+ this._els.grid.appendChild(sk);
+ }
+ }
+
+ _renderCard(a) {
+ const card = document.createElement('button');
+ card.type = 'button';
+ card.className = 'agp-card';
+ card.dataset.id = a.id;
+ if (a.id === this._state.selected?.id) card.classList.add('selected');
+
+ const thumb = a.thumbnail_url
+ ? `<img src="${esc(a.thumbnail_url)}" alt="${esc(a.name || 'Avatar')}" loading="lazy" decoding="async" />`
+ : `<div class="agp-card-ph">${AVATAR_PH_SVG}</div>`;
+
+ const tags = (a.tags || []).slice(0, 2).map((t) =>
+ `<span class="agp-card-chip">${esc(t)}</span>`).join('');
+
+ const views = Number(a.view_count) || 0;
+
+ card.innerHTML = `
+ <div class="agp-card-thumb">${thumb}</div>
+ <div class="agp-card-body">
+ <div class="agp-card-name">${esc(a.name || 'Untitled')}</div>
+ <div class="agp-card-meta">
+ ${tags}
+ ${views ? `<span class="agp-card-chip">${compact.format(views)} views</span>` : ''}
+ </div>
+ </div>
+ `;
+
+ card.addEventListener('click', () => this._selectAvatar(a));
+ return card;
+ }
+
+ _selectAvatar(a) {
+ this._state.selected = a;
+
+ // Update card selection visual
+ this._els.grid.querySelectorAll('.agp-card.selected').forEach((c) =>
+ c.classList.remove('selected'));
+ const card = this._els.grid.querySelector(`.agp-card[data-id="${CSS.escape(a.id)}"]`);
+ if (card) {
+ card.classList.add('selected');
+ card.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
+ }
+
+ // Preview info
+ this._els.previewName.textContent = a.name || 'Untitled';
+ const tagBits = (a.tags || []).join(' · ') || 'three.ws avatar';
+ const views = Number(a.view_count) || 0;
+ this._els.previewSub.textContent = views
+ ? `${tagBits} · ${compact.format(views)} views`
+ : tagBits;
+
+ // Preview tags
+ if (this._els.previewTags) {
+ this._els.previewTags.innerHTML = (a.tags || []).slice(0, 6).map((t) =>
+ `<span class="agp-preview-tag">${esc(t)}</span>`).join('');
+ }
+
+ // 3D preview
+ this._els.previewStage.innerHTML = '';
+ if (a.model_url) {
+ const mv = document.createElement('model-viewer');
+ mv.setAttribute('src', a.model_url);
+ mv.setAttribute('alt', a.name || 'three.ws avatar');
+ mv.setAttribute('camera-controls', '');
+ mv.setAttribute('auto-rotate', '');
+ mv.setAttribute('rotation-per-second', '16deg');
+ mv.setAttribute('interaction-prompt', 'none');
+ mv.setAttribute('exposure', '1.05');
+ mv.setAttribute('shadow-intensity', '0.8');
+ mv.setAttribute('environment-image', 'neutral');
+ if (a.thumbnail_url) mv.setAttribute('poster', a.thumbnail_url);
+ this._els.previewStage.appendChild(mv);
+ } else if (a.thumbnail_url) {
+ const img = document.createElement('img');
+ img.src = a.thumbnail_url;
+ img.alt = a.name || 'Avatar';
+ img.style.cssText = 'width:100%;height:100%;object-fit:contain';
+ this._els.previewStage.appendChild(img);
+ } else {
+ const div = document.createElement('div');
+ div.className = 'agp-preview-empty';
+ div.textContent = 'No preview available for this avatar.';
+ this._els.previewStage.appendChild(div);
+ }
+
+ this._els.cta.disabled = false;
+ this._updatePayload();
+ }
+
+ _renderTags() {
+ const tags = [...this._state.loadedTags].sort((a, b) => a.localeCompare(b)).slice(0, 20);
+ if (!tags.length && !this._state.tag) {
+ this._els.tags.innerHTML = '';
+ return;
+ }
+ const all = this._state.tag && !tags.includes(this._state.tag)
+ ? [this._state.tag, ...tags]
+ : tags;
+ this._els.tags.innerHTML = all.map((t) =>
+ `<button type="button" class="agp-tag${t === this._state.tag ? ' active' : ''}" data-tag="${esc(t)}">${esc(t)}</button>`
+ ).join('');
+ }
+
+ _updateStatus() {
+ if (!this._els.status) return;
+ if (this._state.loading && this._state.totalLoaded === 0) {
+ this._els.status.textContent = 'Loading...';
+ return;
+ }
+ if (this._state.total != null) {
+ this._els.status.textContent = `${integer.format(this._state.totalLoaded)} of ${integer.format(this._state.total)}`;
+ } else {
+ this._els.status.textContent = `${integer.format(this._state.totalLoaded)} avatars`;
+ }
+ }
+
+ // ── Payload / copy ──────────────────────────────────────────────────
+
+ _buildPayload() {
+ const a = this._state.selected;
+ if (!a) return '';
+ if (this._state.mode === 'share') return `https://three.ws/avatars/${a.id}`;
+ if (this._state.mode === 'glb') return a.model_url || '';
+ return `<script type="module" src="https://three.ws/avatar-sdk/dist/index.mjs"><\/script>\n<agent-3d avatar-id="${a.id}" style="width:100%;height:480px"></agent-3d>`;
+ }
+
+ _updatePayload() {
+ if (!this._els.payload) return;
+ if (!this._state.selected) {
+ this._els.payload.textContent = 'Selected payload appears here';
+ return;
+ }
+ const payload = this._buildPayload();
+ this._els.payload.textContent = payload || '(not available for this mode)';
+ }
+
+ async _copyPayload() {
+ const payload = this._buildPayload();
+ if (!payload) return;
+ try {
+ await navigator.clipboard.writeText(payload);
+ const prev = this._els.cta.textContent;
+ this._els.cta.classList.add('copied');
+ this._els.cta.textContent = 'Copied!';
+ if (this._copyTimer) clearTimeout(this._copyTimer);
+ this._copyTimer = setTimeout(() => {
+ this._els.cta.classList.remove('copied');
+ this._els.cta.textContent = prev;
+ }, 1400);
+ } catch (err) {
+ if (this._els.payload) {
+ this._els.payload.textContent = `Clipboard blocked: ${err.message}\n\n${payload}`;
+ }
+ }
+ }
+
+ // ── Keyboard ────────────────────────────────────────────────────────
+
+ _onKey(e) {
+ if (e.key === 'Escape') this.close();
+ }
+}
+
+// ── Convenience wrapper: opens modal, returns a promise ─────────────────
+
+export function openAvatarPicker(opts = {}) {
+ return new Promise((resolve) => {
+ const picker = new AvatarGalleryPicker({
+ ...opts,
+ onSelect: (avatar) => resolve(avatar),
+ onClose: () => resolve(null),
+ });
+ picker.openModal();
+ });
+}
diff --git a/src/avatar-page.js b/src/avatar-page.js
index ef77c4600..04bfc1ef2 100644
--- a/src/avatar-page.js
+++ b/src/avatar-page.js
@@ -237,6 +237,7 @@ function renderShell(glbUrl) {
</div>
<div class="av-cta-row">
<button class="av-cta" id="av-use">Start an agent</button>
+ <a class="av-cta-sec" href="/brain" title="Build a persona and test with AI models">Brain</a>
<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>
diff --git a/src/dashboard-next/pages/agents.js b/src/dashboard-next/pages/agents.js
index 18ea4f56e..48d542a54 100644
--- a/src/dashboard-next/pages/agents.js
+++ b/src/dashboard-next/pages/agents.js
@@ -506,7 +506,8 @@ function openPersonaModal(host, agent, allAgents, avatars) {
<div data-slot="error" style="font-size:12.5px;color:var(--nxt-danger);min-height:18px;margin-bottom:12px"></div>
- <div style="display:flex;gap:8px;justify-content:flex-end;margin-bottom:24px">
+ <div style="display:flex;gap:8px;justify-content:flex-end;margin-bottom:24px;flex-wrap:wrap">
+ <a href="/brain" target="_blank" class="dn-btn" style="text-decoration:none;font-size:12.5px;margin-right:auto">Build in Brain Studio</a>
<button class="dn-btn ghost" data-action="cancel">Cancel</button>
<button class="dn-btn primary" data-action="save-persona">Save persona</button>
</div>
diff --git a/src/dashboard-next/pages/avatars.js b/src/dashboard-next/pages/avatars.js
index 399a3dcf9..940eb25dd 100644
--- a/src/dashboard-next/pages/avatars.js
+++ b/src/dashboard-next/pages/avatars.js
@@ -7,6 +7,7 @@
import { mountShell } from '../shell.js';
import { requireUser, get, patch, del, esc, relTime, ApiError } from '../api.js';
+import { openSelfieModal } from '../../selfie-modal.js';
const PAGE_SIZE = 24;
const VISIBILITIES = ['public', 'unlisted', 'private'];
@@ -39,7 +40,8 @@ const state = {
<div class="dn-av-new-wrap">
<button class="dn-btn primary" type="button" data-new>+ New avatar</button>
<div class="dn-av-new-pop" data-new-pop hidden role="menu">
- <a href="/create/selfie" role="menuitem">From a selfie</a>
+ <button type="button" role="menuitem" data-new-selfie-quick>Snap a selfie</button>
+ <a href="/create/selfie" role="menuitem">Full selfie flow</a>
<a href="/create" role="menuitem">Upload a GLB</a>
<a href="/marketplace" role="menuitem">From an existing avatar</a>
</div>
@@ -166,6 +168,20 @@ function wireNewMenu(root) {
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && !pop.hidden) close();
});
+
+ const quickSelfie = pop.querySelector('[data-new-selfie-quick]');
+ if (quickSelfie) {
+ quickSelfie.addEventListener('click', async () => {
+ close();
+ const result = await openSelfieModal();
+ if (result?.avatarId) {
+ toast(root, 'Avatar created from selfie');
+ state.all = [];
+ state.nextCursor = null;
+ await loadInitial(root);
+ }
+ });
+ }
}
// ── Filtering / rendering ────────────────────────────────────────────────
@@ -365,6 +381,15 @@ function openMoreMenu(root, anchor, card, a) {
menu.setAttribute('role', 'menu');
const items = [
{ label: 'View live page', run: () => { window.open(`/agent-next?id=${encodeURIComponent(a.id)}`, '_blank'); } },
+ { label: 'Update from selfie', run: async () => {
+ const result = await openSelfieModal({ existingAvatarId: a.id });
+ if (result?.avatarId) {
+ toast(root, 'Avatar updated from selfie');
+ state.all = [];
+ state.nextCursor = null;
+ await loadInitial(root);
+ }
+ }},
{ label: 'Rename', run: () => card.querySelector('[data-rename]')?.click() },
{ label: 'Change visibility', run: () => openVisibilitySubmenu(root, anchor, card, a) },
{ label: 'Copy embed snippet', run: () => copyEmbedSnippet(root, a) },
@@ -700,15 +725,23 @@ function injectStyles() {
z-index: 40;
backdrop-filter: blur(20px);
}
- .dn-av-new-pop a {
+ .dn-av-new-pop a,
+ .dn-av-new-pop button {
display: block;
+ width: 100%;
+ text-align: left;
padding: 8px 12px;
border-radius: 7px;
font-size: 13px;
color: var(--nxt-ink);
+ background: transparent;
+ border: none;
+ cursor: pointer;
+ font-family: inherit;
transition: background 0.12s ease;
}
- .dn-av-new-pop a:hover { background: rgba(255,255,255,0.06); }
+ .dn-av-new-pop a:hover,
+ .dn-av-new-pop button:hover { background: rgba(255,255,255,0.06); }
.dn-av-filters {
display: flex;
diff --git a/src/voice-lab.js b/src/voice-lab.js
new file mode 100644
index 000000000..efcc7b4f4
--- /dev/null
+++ b/src/voice-lab.js
@@ -0,0 +1,626 @@
+const $ = (id) => document.getElementById(id);
+
+// ── Reading scripts ──────────────────────────────────────────────────────────
+
+const SCRIPTS = [
+ "Welcome to three.ws, the home of agentic 3D characters. I'm recording my voice to create a digital clone that will bring my avatar to life. This voice will power real-time conversations and text-to-speech synthesis across the platform.",
+ "The quick brown fox jumps over the lazy dog. She sells seashells by the seashore. Peter Piper picked a peck of pickled peppers. How much wood would a woodchuck chuck if a woodchuck could chuck wood?",
+ "Technology should serve people, not the other way around. When we build tools that feel intuitive and accessible, everyone benefits. The future of human-computer interaction lies in natural, conversational interfaces — less like commanding a machine, more like talking to a friend.",
+ "Three dot ws uses WebGL and Three.js to render real-time 3D avatars directly in the browser. Combined with instant voice cloning, speech recognition, and AI-powered conversation, we create fully interactive digital characters that can see, hear, and respond to people naturally.",
+];
+
+// ── Voice library (localStorage) ─────────────────────────────────────────────
+
+const STORAGE_KEY = 'voicelab_voices_v1';
+
+function loadVoices() {
+ try {
+ return JSON.parse(localStorage.getItem(STORAGE_KEY)) || [];
+ } catch { return []; }
+}
+
+function saveVoices(voices) {
+ try { localStorage.setItem(STORAGE_KEY, JSON.stringify(voices)); } catch {}
+}
+
+function addVoice(voice) {
+ const voices = loadVoices();
+ voices.unshift(voice);
+ if (voices.length > 20) voices.length = 20;
+ saveVoices(voices);
+}
+
+function removeVoice(voiceId) {
+ const voices = loadVoices().filter((v) => v.voiceId !== voiceId);
+ saveVoices(voices);
+}
+
+// ── State ────────────────────────────────────────────────────────────────────
+
+let state = 'idle';
+let mediaStream = null;
+let recorder = null;
+let audioCtx = null;
+let analyser = null;
+let recordedBlob = null;
+let recordedUrl = null;
+let startTs = 0;
+let rafId = 0;
+let scriptIdx = 0;
+let lastClonedVoiceId = null;
+
+const MAX_RECORD_S = 60;
+const RECOMMENDED_S = 25;
+
+// ── Canvas setup ─────────────────────────────────────────────────────────────
+
+const canvas = $('waveCanvas');
+const ctx = canvas.getContext('2d');
+let cW = 0;
+let cH = 0;
+
+function fitCanvas() {
+ const dpr = window.devicePixelRatio || 1;
+ cW = canvas.clientWidth;
+ cH = canvas.clientHeight;
+ canvas.width = cW * dpr;
+ canvas.height = cH * dpr;
+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
+}
+fitCanvas();
+window.addEventListener('resize', fitCanvas);
+
+// ── Level meter setup ────────────────────────────────────────────────────────
+
+const levelMeter = $('levelMeter');
+const LEVEL_BARS = 8;
+for (let i = 0; i < LEVEL_BARS; i++) {
+ const bar = document.createElement('div');
+ bar.className = 'vl-level-bar';
+ bar.style.height = '3px';
+ levelMeter.appendChild(bar);
+}
+
+// ── Waveform visualization ───────────────────────────────────────────────────
+
+const BAR_COUNT = 64;
+let idlePhase = 0;
+let smoothBars = new Float32Array(BAR_COUNT);
+
+function lerpColor(t) {
+ const r = Math.round(61 + t * (167 - 61));
+ const g = Math.round(193 + t * (139 - 193));
+ const b = 255;
+ return `rgba(${r},${g},${b},`;
+}
+const barColors = Array.from({ length: BAR_COUNT }, (_, i) => lerpColor(i / BAR_COUNT));
+
+function drawIdle() {
+ idlePhase += 0.015;
+ ctx.clearRect(0, 0, cW, cH);
+
+ const centerY = cH / 2;
+ const totalW = cW * 0.85;
+ const startX = (cW - totalW) / 2;
+ const barW = (totalW / BAR_COUNT) * 0.65;
+ const gap = (totalW / BAR_COUNT) * 0.35;
+
+ for (let i = 0; i < BAR_COUNT; i++) {
+ const t = i / BAR_COUNT;
+ const ambient = (Math.sin(idlePhase + t * 6) * 0.5 + 0.5) * 0.08 + 0.02;
+ smoothBars[i] += (ambient - smoothBars[i]) * 0.08;
+ const h = smoothBars[i] * centerY;
+ const x = startX + i * (barW + gap);
+ const alpha = 0.4 + smoothBars[i] * 3;
+
+ ctx.fillStyle = barColors[i] + alpha + ')';
+ ctx.beginPath();
+ ctx.roundRect(x, centerY - h, barW, h, 2);
+ ctx.fill();
+ ctx.beginPath();
+ ctx.roundRect(x, centerY + 1, barW, h, 2);
+ ctx.fill();
+ }
+}
+
+function drawLive() {
+ if (!analyser) return;
+ const data = new Uint8Array(analyser.frequencyBinCount);
+ analyser.getByteFrequencyData(data);
+
+ ctx.clearRect(0, 0, cW, cH);
+
+ const centerY = cH / 2;
+ const totalW = cW * 0.85;
+ const startX = (cW - totalW) / 2;
+ const barW = (totalW / BAR_COUNT) * 0.65;
+ const gap = (totalW / BAR_COUNT) * 0.35;
+ const binsPerBar = Math.floor(data.length / BAR_COUNT);
+
+ let rmsSum = 0;
+
+ for (let i = 0; i < BAR_COUNT; i++) {
+ let sum = 0;
+ const start = i * binsPerBar;
+ for (let j = start; j < start + binsPerBar; j++) sum += data[j];
+ const raw = (sum / binsPerBar) / 255;
+ rmsSum += raw * raw;
+ smoothBars[i] += (raw - smoothBars[i]) * 0.25;
+ const val = smoothBars[i];
+ const h = Math.max(2, val * centerY * 0.92);
+ const x = startX + i * (barW + gap);
+ const alpha = 0.5 + val * 0.5;
+
+ ctx.fillStyle = barColors[i] + alpha + ')';
+ ctx.beginPath();
+ ctx.roundRect(x, centerY - h, barW, h, 2);
+ ctx.fill();
+ ctx.beginPath();
+ ctx.roundRect(x, centerY + 1, barW, h, 2);
+ ctx.fill();
+ }
+
+ updateLevelMeter(Math.sqrt(rmsSum / BAR_COUNT));
+}
+
+function updateLevelMeter(rms) {
+ const bars = levelMeter.children;
+ for (let i = 0; i < LEVEL_BARS; i++) {
+ const threshold = (i + 1) / LEVEL_BARS;
+ const active = rms > threshold * 0.6;
+ const h = active ? Math.min(20, 4 + rms * 20) : 3;
+ bars[i].style.height = h + 'px';
+ if (i >= LEVEL_BARS - 2 && active) {
+ bars[i].style.background = '#ef4444';
+ } else if (i >= LEVEL_BARS - 4 && active) {
+ bars[i].style.background = '#fbbf24';
+ } else {
+ bars[i].style.background = '#3dc1ff';
+ }
+ }
+}
+
+function animationLoop() {
+ rafId = requestAnimationFrame(animationLoop);
+ if (state === 'recording' && analyser) {
+ drawLive();
+ updateTimer();
+ } else {
+ drawIdle();
+ }
+}
+animationLoop();
+
+// ── Timer ────────────────────────────────────────────────────────────────────
+
+function updateTimer() {
+ const elapsed = (performance.now() - startTs) / 1000;
+ const m = Math.floor(elapsed / 60);
+ const s = Math.floor(elapsed % 60);
+ $('timer').textContent = `${m}:${s.toString().padStart(2, '0')}`;
+
+ const pct = Math.min(100, (elapsed / RECOMMENDED_S) * 100);
+ $('progress').style.width = pct + '%';
+
+ if (elapsed >= RECOMMENDED_S) {
+ $('timerSub').textContent = 'Great length! You can stop whenever you\'re ready.';
+ $('timerSub').style.color = '#34d399';
+ } else {
+ const remaining = Math.ceil(RECOMMENDED_S - elapsed);
+ $('timerSub').textContent = `${remaining}s more recommended`;
+ $('timerSub').style.color = '';
+ }
+
+ if (elapsed >= MAX_RECORD_S) {
+ setStatus('info', `Reached ${MAX_RECORD_S}s limit — stopping automatically.`);
+ stopRecording();
+ }
+}
+
+// ── Scripts ──────────────────────────────────────────────────────────────────
+
+function renderScript() {
+ $('scriptText').textContent = `"${SCRIPTS[scriptIdx]}"`;
+ const dotsEl = $('scriptDots');
+ dotsEl.innerHTML = '';
+ for (let i = 0; i < SCRIPTS.length; i++) {
+ const dot = document.createElement('div');
+ dot.className = 'vl-script-dot' + (i === scriptIdx ? ' active' : '');
+ dotsEl.appendChild(dot);
+ }
+}
+renderScript();
+
+$('scriptNext').addEventListener('click', () => {
+ scriptIdx = (scriptIdx + 1) % SCRIPTS.length;
+ renderScript();
+});
+
+// ── Recording ────────────────────────────────────────────────────────────────
+
+function pickMime() {
+ const candidates = [
+ 'audio/webm;codecs=opus',
+ 'audio/webm',
+ 'audio/ogg;codecs=opus',
+ 'audio/mp4',
+ ];
+ for (const m of candidates) {
+ if (window.MediaRecorder && MediaRecorder.isTypeSupported(m)) return m;
+ }
+ return '';
+}
+
+async function startRecording() {
+ try {
+ mediaStream = await navigator.mediaDevices.getUserMedia({
+ audio: {
+ channelCount: 1,
+ echoCancellation: true,
+ noiseSuppression: true,
+ autoGainControl: true,
+ sampleRate: 48000,
+ },
+ });
+ } catch (err) {
+ setStatus('err', `Microphone access denied: ${err.message}`);
+ return;
+ }
+
+ audioCtx = new (window.AudioContext || window.webkitAudioContext)({ sampleRate: 48000 });
+ const src = audioCtx.createMediaStreamSource(mediaStream);
+ analyser = audioCtx.createAnalyser();
+ analyser.fftSize = 2048;
+ analyser.smoothingTimeConstant = 0.75;
+ src.connect(analyser);
+
+ const mime = pickMime();
+ const chunks = [];
+ try {
+ recorder = mime
+ ? new MediaRecorder(mediaStream, { mimeType: mime })
+ : new MediaRecorder(mediaStream);
+ } catch (err) {
+ setStatus('err', `Could not start recorder: ${err.message}`);
+ return;
+ }
+
+ recorder.ondataavailable = (e) => {
+ if (e.data?.size) chunks.push(e.data);
+ };
+ recorder.onstop = () => {
+ const blobMime = recorder.mimeType || mime || 'audio/webm';
+ recordedBlob = new Blob(chunks, { type: blobMime });
+ if (recordedUrl) URL.revokeObjectURL(recordedUrl);
+ recordedUrl = URL.createObjectURL(recordedBlob);
+ $('reviewAudio').src = recordedUrl;
+
+ const elapsed = (performance.now() - startTs) / 1000;
+ if (elapsed < 3) {
+ setStatus('err', 'Recording too short. Please record at least 3 seconds.');
+ setState('idle');
+ return;
+ }
+
+ setStatus('ok', `Captured ${(recordedBlob.size / 1024).toFixed(0)} KB (${Math.round(elapsed)}s). Review and clone below.`);
+ setState('review');
+ };
+
+ recorder.start(250);
+ startTs = performance.now();
+ setState('recording');
+ setStatus('info', 'Recording... read the script aloud or speak naturally.');
+}
+
+function stopRecording() {
+ if (recorder?.state === 'recording') recorder.stop();
+ mediaStream?.getTracks().forEach((t) => t.stop());
+ audioCtx?.close().catch(() => {});
+ analyser = null;
+ audioCtx = null;
+ mediaStream = null;
+}
+
+function resetRecording() {
+ recordedBlob = null;
+ if (recordedUrl) { URL.revokeObjectURL(recordedUrl); recordedUrl = null; }
+ $('reviewAudio').removeAttribute('src');
+ $('progress').style.width = '0%';
+ $('timer').textContent = '0:00';
+ $('timerSub').textContent = 'Recommended: 20-30 seconds';
+ $('timerSub').style.color = '';
+ smoothBars.fill(0);
+ setState('idle');
+ setStatus('info', 'Ready to record.');
+}
+
+// ── Clone ────────────────────────────────────────────────────────────────────
+
+async function cloneVoice() {
+ if (!recordedBlob) return;
+ const name = $('voiceName').value.trim();
+ if (!name) {
+ setStatus('err', 'Enter a name for your voice.');
+ $('voiceName').focus();
+ return;
+ }
+
+ setState('cloning');
+ setStatus('info', 'Uploading sample and cloning...');
+
+ const ext = recordedBlob.type.includes('mp4') ? 'm4a'
+ : recordedBlob.type.includes('ogg') ? 'ogg'
+ : recordedBlob.type.includes('wav') ? 'wav'
+ : 'webm';
+
+ const fd = new FormData();
+ fd.append('audio', recordedBlob, `sample.${ext}`);
+ fd.append('name', name);
+
+ let res;
+ try {
+ res = await fetch('/api/tts/eleven-clone', {
+ method: 'POST',
+ credentials: 'include',
+ body: fd,
+ });
+ } catch (err) {
+ setStatus('err', `Network error: ${err.message}`);
+ setState('review');
+ return;
+ }
+
+ let body;
+ try {
+ body = await res.json();
+ } catch {
+ body = { error_description: await res.text().catch(() => '') };
+ }
+
+ if (!res.ok) {
+ const msg = body.error_description || body.error || `HTTP ${res.status}`;
+ setStatus('err', `Clone failed: ${msg}`);
+ setState('review');
+ return;
+ }
+
+ const voiceId = body.voice_id;
+ lastClonedVoiceId = voiceId;
+
+ addVoice({
+ voiceId,
+ name,
+ createdAt: Date.now(),
+ status: body.status || 'ready',
+ });
+
+ $('doneText').textContent = `"${name}" cloned successfully`;
+ setStatus('ok', `Voice cloned. ID: ${voiceId}`);
+ setState('done');
+ renderLibrary();
+ renderPlaygroundVoices();
+}
+
+// ── State machine ────────────────────────────────────────────────────────────
+
+function setState(newState) {
+ state = newState;
+ $('recorder').dataset.state = newState;
+}
+
+function setStatus(type, text) {
+ const el = $('status');
+ el.className = 'vl-status' + (type !== 'info' ? ` ${type}` : '');
+ el.textContent = text;
+}
+
+// ── Voice library rendering ──────────────────────────────────────────────────
+
+function renderLibrary() {
+ const voices = loadVoices();
+ const container = $('voiceLibrary');
+
+ if (!voices.length) {
+ container.innerHTML = `
+ <div class="vl-empty">
+ <div class="vl-empty-title">No cloned voices yet</div>
+ Record a voice sample above to get started.
+ </div>`;
+ return;
+ }
+
+ container.innerHTML = `<div class="vl-voices">${
+ voices.map((v) => {
+ const age = timeAgo(v.createdAt);
+ return `
+ <div class="vl-voice-card" data-vid="${esc(v.voiceId)}">
+ <div class="vl-voice-name">${esc(v.name)}</div>
+ <div class="vl-voice-meta">
+ <span>${age}</span>
+ </div>
+ <div class="vl-voice-id">${esc(v.voiceId)}</div>
+ <div class="vl-voice-actions">
+ <button class="vl-btn vl-btn-ghost vl-btn-sm" data-play="${esc(v.voiceId)}">Play sample</button>
+ <button class="vl-btn vl-btn-danger vl-btn-sm" data-del="${esc(v.voiceId)}">Remove</button>
+ </div>
+ </div>`;
+ }).join('')
+ }</div>`;
+}
+
+function esc(s) {
+ return String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
+}
+
+function timeAgo(ts) {
+ const diff = Date.now() - ts;
+ if (diff < 60000) return 'Just now';
+ if (diff < 3600000) return `${Math.floor(diff / 60000)}m ago`;
+ if (diff < 86400000) return `${Math.floor(diff / 3600000)}h ago`;
+ return `${Math.floor(diff / 86400000)}d ago`;
+}
+
+// ── Playground ───────────────────────────────────────────────────────────────
+
+function renderPlaygroundVoices() {
+ const voices = loadVoices();
+ const sel = $('pgVoice');
+ const prev = sel.value;
+
+ sel.innerHTML = '';
+ if (!voices.length) {
+ sel.innerHTML = '<option value="" disabled selected>Clone a voice first</option>';
+ $('pgSpeak').disabled = true;
+ return;
+ }
+
+ voices.forEach((v) => {
+ const opt = document.createElement('option');
+ opt.value = v.voiceId;
+ opt.textContent = v.name;
+ sel.appendChild(opt);
+ });
+
+ if (lastClonedVoiceId && voices.find((v) => v.voiceId === lastClonedVoiceId)) {
+ sel.value = lastClonedVoiceId;
+ } else if (prev && voices.find((v) => v.voiceId === prev)) {
+ sel.value = prev;
+ } else {
+ sel.value = voices[0].voiceId;
+ }
+
+ $('pgSpeak').disabled = false;
+}
+
+async function speakPlayground() {
+ const voiceId = $('pgVoice').value;
+ const text = $('pgText').value.trim();
+ if (!voiceId || !text) return;
+
+ $('pgSpeak').disabled = true;
+ $('pgHint').textContent = 'Synthesizing...';
+
+ try {
+ const r = await fetch('/api/tts/eleven', {
+ method: 'POST',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ voiceId, text }),
+ });
+
+ if (!r.ok) {
+ const errText = await r.text().catch(() => '');
+ throw new Error(`HTTP ${r.status}: ${errText.slice(0, 200)}`);
+ }
+
+ const cacheHit = r.headers.get('x-tts-cache') === 'hit';
+ const buf = await r.arrayBuffer();
+ const blob = new Blob([buf], { type: 'audio/mpeg' });
+ const url = URL.createObjectURL(blob);
+
+ const audio = $('pgAudio');
+ if (audio.src) URL.revokeObjectURL(audio.src);
+ audio.src = url;
+ $('pgOutput').classList.add('visible');
+ audio.play().catch(() => {});
+
+ $('pgHint').textContent = `${(buf.byteLength / 1024).toFixed(0)} KB · ${cacheHit ? 'cached' : 'generated'}`;
+ } catch (err) {
+ $('pgHint').textContent = `Error: ${err.message}`;
+ } finally {
+ $('pgSpeak').disabled = false;
+ }
+}
+
+async function playVoiceSample(voiceId) {
+ const voice = loadVoices().find((v) => v.voiceId === voiceId);
+ if (!voice) return;
+
+ const btn = document.querySelector(`[data-play="${voiceId}"]`);
+ if (btn) { btn.disabled = true; btn.textContent = 'Loading...'; }
+
+ try {
+ const r = await fetch('/api/tts/eleven', {
+ method: 'POST',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({
+ voiceId,
+ text: "Hello, I'm your cloned voice. How does this sound?",
+ }),
+ });
+ if (!r.ok) throw new Error(`HTTP ${r.status}`);
+ const blob = await r.blob();
+ const audio = new Audio(URL.createObjectURL(blob));
+ audio.onended = () => URL.revokeObjectURL(audio.src);
+ audio.play();
+ } catch (err) {
+ setStatus('err', `Playback failed: ${err.message}`);
+ } finally {
+ if (btn) { btn.disabled = false; btn.textContent = 'Play sample'; }
+ }
+}
+
+function deleteVoice(voiceId) {
+ removeVoice(voiceId);
+ renderLibrary();
+ renderPlaygroundVoices();
+ setStatus('info', 'Voice removed from library.');
+}
+
+// ── Event wiring ─────────────────────────────────────────────────────────────
+
+$('btnRecord').addEventListener('click', startRecording);
+$('btnStop').addEventListener('click', stopRecording);
+$('btnRerecord').addEventListener('click', resetRecording);
+$('btnClone').addEventListener('click', cloneVoice);
+
+$('btnTryPlayground').addEventListener('click', () => {
+ $('playgroundSection').scrollIntoView({ behavior: 'smooth', block: 'center' });
+});
+$('btnRecordAnother').addEventListener('click', resetRecording);
+
+$('pgSpeak').addEventListener('click', speakPlayground);
+
+$('pgText').addEventListener('keydown', (e) => {
+ if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) {
+ e.preventDefault();
+ speakPlayground();
+ }
+});
+
+document.querySelectorAll('.vl-pg-sample').forEach((btn) => {
+ btn.addEventListener('click', () => {
+ $('pgText').value = btn.dataset.text;
+ });
+});
+
+$('voiceLibrary').addEventListener('click', (e) => {
+ const playBtn = e.target.closest('[data-play]');
+ if (playBtn) { playVoiceSample(playBtn.dataset.play); return; }
+ const delBtn = e.target.closest('[data-del]');
+ if (delBtn) { deleteVoice(delBtn.dataset.del); }
+});
+
+$('pgVoice').addEventListener('change', () => {
+ $('pgSpeak').disabled = !$('pgVoice').value;
+});
+
+// Keyboard shortcut: Space to toggle record/stop when not in an input
+document.addEventListener('keydown', (e) => {
+ if (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA' || e.target.tagName === 'SELECT') return;
+ if (e.code === 'Space') {
+ e.preventDefault();
+ if (state === 'idle') startRecording();
+ else if (state === 'recording') stopRecording();
+ }
+});
+
+// ── Init ─────────────────────────────────────────────────────────────────────
+
+renderLibrary();
+renderPlaygroundVoices();
+
+// Auto-populate voice name with a sensible default
+const now = new Date();
+$('voiceName').value = `My Voice ${now.toLocaleDateString('en-US', { month: 'short', day: 'numeric' })}`;
diff --git a/vercel.json b/vercel.json
index ff6a97345..b3f9d6b6d 100644
--- a/vercel.json
+++ b/vercel.json
@@ -360,9 +360,13 @@
"src": "/api/agenc/link",
"dest": "/api/agenc/[action]?action=link"
},
+ {
+ "src": "/voice/?",
+ "dest": "/voice.html"
+ },
{
"src": "/brain/?",
- "dest": "/demos/brain.html"
+ "dest": "/brain.html"
},
{
"src": "/lipsync/mic/?",
diff --git a/vite.config.js b/vite.config.js
index 365eea37b..57ca1e20e 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -192,8 +192,10 @@ const appConfig = {
'threews-claim': resolve(__dirname, 'pages/threews-claim.html'),
'avatar-page': resolve(__dirname, 'pages/avatar-page.html'),
'avatar-sdk': resolve(__dirname, 'pages/avatar-sdk.html'),
+ brain: resolve(__dirname, 'pages/brain.html'),
+ voice: resolve(__dirname, 'pages/voice.html'),
'ar-page': resolve(__dirname, 'pages/ar.html'),
-creating: resolve(__dirname, 'pages/creating.html'),
+ creating: resolve(__dirname, 'pages/creating.html'),
pricing: resolve(__dirname, 'pages/pricing.html'),
'x-pricing': resolve(__dirname, 'pages/x-pricing.html'),
'home-next': resolve(__dirname, 'pages/home-next.html'),
@@ -445,8 +447,10 @@ creating: resolve(__dirname, 'pages/creating.html'),
'/aws-marketplace/error/': resolve(root, 'pages/aws-marketplace/welcome.html'),
'/aws': resolve(root, 'pages/aws/index.html'),
'/aws/': resolve(root, 'pages/aws/index.html'),
- '/brain': resolve(root, 'public/demos/brain.html'),
- '/brain/': resolve(root, 'public/demos/brain.html'),
+ '/voice': resolve(root, 'pages/voice.html'),
+ '/voice/': resolve(root, 'pages/voice.html'),
+ '/brain': resolve(root, 'pages/brain.html'),
+ '/brain/': resolve(root, 'pages/brain.html'),
'/lipsync': resolve(root, 'public/demos/lipsync-tts.html'),
'/lipsync/': resolve(root, 'public/demos/lipsync-tts.html'),
'/lipsync/mic': resolve(root, 'public/demos/lipsync-mic.html'),