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: voice page, brain/selfie modules, brain chat expansion, XR and API updates

nirholas4a73c27af564
diff --git a/api/_lib/avatars.js b/api/_lib/avatars.js
index 7fbf78933..bbe9ddedc 100644
--- a/api/_lib/avatars.js
+++ b/api/_lib/avatars.js
@@ -5,6 +5,7 @@ import { createHash } from 'node:crypto';
import { sql } from './db.js';
import { publicUrl, presignGet, deleteObject } from './r2.js';
import { defaultStorageMode } from './storage-mode.js';
+import { isUuid } from './validate.js';
export async function listAvatars({
userId,
@@ -55,6 +56,11 @@ export async function listAvatars({
}
export async function getAvatar({ id, requesterId = null }) {
+ // Non-UUID ids (e.g. "badid", "undefined") would cause a Postgres 22P02
+ // error when cast to uuid. Short-circuit with null — callers already
+ // handle null as "not found".
+ if (!isUuid(id)) return null;
+
const rows = await sql`
select a.*, ai.id as agent_id, ai.wallet_address as agent_wallet_address
from avatars a
diff --git a/api/_lib/embed-policy.js b/api/_lib/embed-policy.js
index b61ea02ad..b5b176227 100644
--- a/api/_lib/embed-policy.js
+++ b/api/_lib/embed-policy.js
@@ -3,6 +3,7 @@
import { z } from 'zod';
import { sql } from './db.js';
+import { isUuid } from './validate.js';
const hostPattern =
/^(\*\.)?([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)(\.[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i;
@@ -78,6 +79,8 @@ export function normalizeLegacyPolicy(input) {
}
export async function readEmbedPolicy(agentId) {
+ if (!isUuid(agentId)) return null;
+
let row;
try {
[row] = await sql`
@@ -101,6 +104,8 @@ export async function readEmbedPolicy(agentId) {
// Read the embed policy for an agent_identity row identified by its avatar_id.
// Used by the MCP middleware where only the avatar id is on the request.
export async function readEmbedPolicyByAvatarId(avatarId) {
+ if (!isUuid(avatarId)) return null;
+
let row;
try {
[row] = await sql`
diff --git a/api/_lib/validate.js b/api/_lib/validate.js
index 595e631b0..bbc056d47 100644
--- a/api/_lib/validate.js
+++ b/api/_lib/validate.js
@@ -102,6 +102,12 @@ export const presignUploadBody = z.object({
.optional(),
});
+const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+
+export function isUuid(value) {
+ return typeof value === 'string' && UUID_RE.test(value);
+}
+
export function isValidSolanaAddress(address) {
return typeof address === 'string' && /^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(address);
}
diff --git a/api/brain/chat.js b/api/brain/chat.js
index 454702839..1f914ed55 100644
--- a/api/brain/chat.js
+++ b/api/brain/chat.js
@@ -2,11 +2,13 @@
//
// Body: { provider, messages, system?, maxTokens? }
// Response: SSE stream:
-// event: meta → { provider, label, network, model }
-// event: first → { firstTokenMs } (time to first token)
+// event: meta → { provider, label, network, model, tier }
+// event: first → { firstTokenMs }
// (data-only) → JSON-encoded text chunk
// event: done → { elapsedMs, firstTokenMs, usage }
// event: error → { message, elapsedMs }
+//
+// GET /api/brain/chat → returns available providers list
import { streamText } from 'ai';
import { createAnthropic } from '@ai-sdk/anthropic';
@@ -15,13 +17,14 @@ import { createQwen } from 'qwen-ai-provider';
import { env } from '../_lib/env.js';
import { cors, method, readJson, error, wrap } from '../_lib/http.js';
-export const maxDuration = 60;
+export const maxDuration = 120;
const PROVIDERS = {
'claude-opus-4-7': {
label: 'Claude Opus 4.7',
network: 'Anthropic',
tier: 'flagship',
+ maxOutput: 16384,
description: 'Most capable. Extended thinking, complex reasoning.',
build: () => {
const key = env.ANTHROPIC_API_KEY;
@@ -33,6 +36,7 @@ const PROVIDERS = {
label: 'Claude Sonnet 4.6',
network: 'Anthropic',
tier: 'balanced',
+ maxOutput: 16384,
description: 'Balanced speed and intelligence. Best for most tasks.',
build: () => {
const key = env.ANTHROPIC_API_KEY;
@@ -44,6 +48,7 @@ const PROVIDERS = {
label: 'Claude Haiku 4.5',
network: 'Anthropic',
tier: 'fast',
+ maxOutput: 8192,
description: 'Fastest Claude. Low latency, high throughput.',
build: () => {
const key = env.ANTHROPIC_API_KEY;
@@ -55,6 +60,7 @@ const PROVIDERS = {
label: 'GPT-4o',
network: 'OpenAI',
tier: 'flagship',
+ maxOutput: 16384,
description: 'OpenAI flagship. Strong multimodal reasoning.',
build: () => {
const key = env.OPENAI_API_KEY;
@@ -66,6 +72,7 @@ const PROVIDERS = {
label: 'GPT-4o-mini',
network: 'OpenAI',
tier: 'fast',
+ maxOutput: 16384,
description: 'Fast, affordable GPT. Great for simple tasks.',
build: () => {
const key = env.OPENAI_API_KEY;
@@ -73,11 +80,24 @@ const PROVIDERS = {
return createOpenAI({ apiKey: key })('gpt-4o-mini');
},
},
+ 'o3-mini': {
+ label: 'o3-mini',
+ network: 'OpenAI',
+ tier: 'reasoning',
+ maxOutput: 16384,
+ description: 'Reasoning-optimized. Fast chain-of-thought.',
+ build: () => {
+ const key = env.OPENAI_API_KEY;
+ if (!key) return null;
+ return createOpenAI({ apiKey: key })('o3-mini');
+ },
+ },
'groq-llama': {
label: 'Llama 3.3 70B',
network: 'Groq',
tier: 'fast',
- description: 'Open-weight model on Groq. Extremely fast inference.',
+ maxOutput: 8192,
+ description: 'Open-weight on Groq. Extremely fast inference.',
build: () => {
const key = env.GROQ_API_KEY;
if (!key) return null;
@@ -89,9 +109,10 @@ const PROVIDERS = {
},
'qwen-plus': {
label: 'Qwen Plus',
- network: 'Alibaba DashScope',
+ network: 'DashScope',
tier: 'balanced',
- description: 'Qwen Plus on Alibaba DashScope. Strong multilingual.',
+ maxOutput: 8192,
+ description: 'Qwen Plus on DashScope. Strong multilingual.',
build: () => {
if (env.DASHSCOPE_API_KEY) {
return createQwen({ apiKey: env.DASHSCOPE_API_KEY })('qwen-plus');
@@ -103,10 +124,11 @@ const PROVIDERS = {
},
},
'modelscope-qwen': {
- label: 'Qwen3-Coder-480B',
+ label: 'Qwen3-Coder 480B',
network: 'ModelScope',
tier: 'flagship',
- description: 'Largest Qwen coder model. Exceptional at code generation.',
+ maxOutput: 16384,
+ description: 'Largest Qwen coder. Exceptional code generation.',
build: () => {
if (env.MODELSCOPE_API_KEY) {
return createOpenAI({
@@ -120,6 +142,25 @@ const PROVIDERS = {
return null;
},
},
+ 'deepseek-r1': {
+ label: 'DeepSeek R1',
+ network: 'DeepSeek',
+ tier: 'reasoning',
+ maxOutput: 8192,
+ description: 'Open reasoning model. Strong at math and code.',
+ build: () => {
+ if (env.DEEPSEEK_API_KEY) {
+ return createOpenAI({
+ apiKey: env.DEEPSEEK_API_KEY,
+ baseURL: 'https://api.deepseek.com/v1',
+ })('deepseek-reasoner');
+ }
+ if (env.OPENROUTER_API_KEY) {
+ return openrouter()('deepseek/deepseek-r1');
+ }
+ return null;
+ },
+ },
};
function openrouter() {
@@ -134,14 +175,14 @@ function validateMessages(input) {
if (!Array.isArray(input)) {
throw Object.assign(new Error('messages must be an array'), { status: 400 });
}
- if (input.length === 0 || input.length > 60) {
+ if (input.length === 0 || input.length > 100) {
throw Object.assign(new Error('messages length out of range'), { status: 400 });
}
const out = [];
for (const m of input) {
if (!m || typeof m !== 'object') throw Object.assign(new Error('bad message'), { status: 400 });
const role = m.role;
- const content = typeof m.content === 'string' ? m.content.slice(0, 8000) : '';
+ const content = typeof m.content === 'string' ? m.content.slice(0, 16000) : '';
if (!['user', 'assistant'].includes(role)) {
throw Object.assign(new Error('role must be user|assistant'), { status: 400 });
}
@@ -151,8 +192,32 @@ function validateMessages(input) {
return out;
}
+function getAvailableProviders() {
+ return Object.entries(PROVIDERS).map(([key, spec]) => {
+ const available = Boolean(spec.build());
+ return {
+ key,
+ label: spec.label,
+ network: spec.network,
+ tier: spec.tier,
+ maxOutput: spec.maxOutput,
+ description: spec.description,
+ available,
+ };
+ });
+}
+
export default wrap(async function handler(req, res) {
- if (cors(req, res, { methods: 'POST,OPTIONS' })) return;
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;
+
+ if (req.method === 'GET') {
+ const providers = getAvailableProviders();
+ res.setHeader('content-type', 'application/json');
+ res.setHeader('cache-control', 'public, s-maxage=60, stale-while-revalidate=120');
+ res.end(JSON.stringify({ providers }));
+ return;
+ }
+
if (method(req, res, ['POST'])) return;
let body;
@@ -183,8 +248,8 @@ export default wrap(async function handler(req, res) {
return error(res, e.status || 400, 'bad_request', e.message);
}
- const system = typeof body.system === 'string' ? body.system.slice(0, 4000) : undefined;
- const maxTokens = Math.min(Math.max(Number(body.maxTokens) || 1024, 32), 4096);
+ const system = typeof body.system === 'string' ? body.system.slice(0, 8000) : undefined;
+ const maxTokens = Math.min(Math.max(Number(body.maxTokens) || 4096, 64), spec.maxOutput);
res.statusCode = 200;
res.setHeader('content-type', 'text/event-stream; charset=utf-8');
diff --git a/pages/create-selfie.html b/pages/create-selfie.html
index 79dc10630..cd43d1a57 100644
--- a/pages/create-selfie.html
+++ b/pages/create-selfie.html
@@ -690,6 +690,49 @@
object-fit: cover;
}
#cam-stage video { transform: scaleX(-1); }
+ #cam-mesh-overlay {
+ position: absolute;
+ inset: 0;
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ transform: scaleX(-1);
+ pointer-events: none;
+ z-index: 1;
+ }
+ .cam-badges {
+ position: absolute;
+ top: env(safe-area-inset-top, 12px);
+ left: 12px;
+ right: 12px;
+ display: flex;
+ gap: 5px;
+ flex-wrap: wrap;
+ z-index: 3;
+ padding-top: 50px;
+ }
+ .cam-badge-chip {
+ font-size: 10.5px;
+ font-weight: 600;
+ padding: 3px 8px;
+ border-radius: 6px;
+ letter-spacing: 0.03em;
+ text-transform: uppercase;
+ background: rgba(0, 0, 0, 0.55);
+ border: 1px solid rgba(255, 255, 255, 0.1);
+ color: rgba(255, 255, 255, 0.5);
+ backdrop-filter: blur(6px);
+ }
+ .cam-badge-chip.ok {
+ color: var(--accent);
+ border-color: rgba(255, 255, 255, 0.25);
+ background: rgba(255, 255, 255, 0.1);
+ }
+ .cam-badge-chip.bad {
+ color: #ff6b6b;
+ border-color: rgba(255, 107, 107, 0.3);
+ background: rgba(255, 107, 107, 0.08);
+ }
.cam-prompt {
position: absolute;
top: env(safe-area-inset-top, 18px);
@@ -1094,11 +1137,13 @@
<div id="cam-overlay" role="dialog" aria-modal="true" aria-label="Camera capture">
<div id="cam-stage">
<video id="cam-video" autoplay playsinline muted></video>
+ <canvas id="cam-mesh-overlay" aria-hidden="true"></canvas>
<div class="cam-oval" id="cam-oval" aria-hidden="true">
<svg viewBox="0 0 300 400" preserveAspectRatio="xMidYMid meet">
<ellipse cx="150" cy="180" rx="115" ry="155" />
</svg>
</div>
+ <div class="cam-badges" id="cam-badges" aria-hidden="true"></div>
<div class="cam-hint" id="cam-hint">Center your face in the oval</div>
<div class="cam-countdown" id="cam-countdown" aria-hidden="true">
<span class="count-num" id="cam-count-num">3</span>
diff --git a/pages/home-next.html b/pages/home-next.html
index 02560d59d..b676b7bec 100644
--- a/pages/home-next.html
+++ b/pages/home-next.html
@@ -24,8 +24,8 @@
--text-2: #a8a8a8;
--text-3: #6a6a6a;
--text-4: #4a4a4a;
- --accent: #6a5cff;
- --accent-2: #ff5ca8;
+ --accent: #ffffff;
+ --accent-2: #ffffff;
--green: #22c55e;
--font-display: "Inter Tight", "Inter", -apple-system, BlinkMacSystemFont, system-ui, sans-serif;
--font-body: "Inter", -apple-system, BlinkMacSystemFont, system-ui, sans-serif;
@@ -506,7 +506,7 @@
}
.token-avatar {
width: 44px; height: 44px; border-radius: 50%; flex-shrink: 0;
- background: linear-gradient(135deg, #6a5cff 0%, #ff5ca8 100%);
+ background: linear-gradient(135deg, #ffffff 0%, #ffffff 100%);
display: flex; align-items: center; justify-content: center;
font-family: var(--font-mono); font-size: 11px; font-weight: 700; color: #fff;
}
@@ -611,7 +611,7 @@
padding: 2px 7px; border-radius: 4px; font-weight: 700;
}
.dev-badge.get { background: rgba(34,197,94,0.12); color: var(--green); }
- .dev-badge.post { background: rgba(106,92,255,0.15); color: #a59dff; }
+ .dev-badge.post { background: rgba(255,255,255,0.15); color: #cccccc; }
.dev-badge.mcp { background: rgba(255,92,168,0.12); color: #ff8cc8; }
/* ── PRICING TEASER ──────────────────────────────────────── */
@@ -629,13 +629,13 @@
.pricing-card:hover { background: var(--surface-1); }
.pricing-card.featured {
background: var(--surface-1);
- box-shadow: inset 0 0 0 1px rgba(106,92,255,0.25);
+ box-shadow: inset 0 0 0 1px rgba(255,255,255,0.25);
}
.pricing-badge {
position: absolute; top: 16px; right: 16px;
font-family: var(--font-mono); font-size: 10px;
letter-spacing: 0.15em; text-transform: uppercase;
- background: rgba(106,92,255,0.15); color: #a59dff;
+ background: rgba(255,255,255,0.15); color: #cccccc;
padding: 3px 9px; border-radius: 99px;
}
.pricing-tier {
@@ -911,7 +911,7 @@
<!-- Avatar Studio -->
<div class="bento-card span2">
<div class="bento-icon">
- <span class="dot" style="background:#6a5cff;box-shadow:0 0 8px #6a5cff55"></span>
+ <span class="dot" style="background:#ffffff;box-shadow:0 0 8px #ffffff55"></span>
<span style="font-family:var(--font-mono);font-size:11px;letter-spacing:0.15em;text-transform:uppercase;color:var(--text-3)">Avatar Studio</span>
</div>
<p class="bento-title">Selfie → 3D avatar in 60 seconds</p>
@@ -947,7 +947,7 @@
<!-- Voice & Mocap -->
<div class="bento-card">
<div class="bento-icon">
- <span class="dot" style="background:#ff5ca8;box-shadow:0 0 8px #ff5ca855"></span>
+ <span class="dot" style="background:#ffffff;box-shadow:0 0 8px #ffffff55"></span>
<span style="font-family:var(--font-mono);font-size:11px;letter-spacing:0.15em;text-transform:uppercase;color:var(--text-3)">Voice + Mocap</span>
</div>
<p class="bento-title">Real-time voice &amp; face capture</p>
@@ -994,7 +994,7 @@
<!-- On-chain Identity -->
<div class="bento-card">
<div class="bento-icon">
- <span class="dot" style="background:#6a5cff;box-shadow:0 0 8px #6a5cff55"></span>
+ <span class="dot" style="background:#ffffff;box-shadow:0 0 8px #ffffff55"></span>
<span style="font-family:var(--font-mono);font-size:11px;letter-spacing:0.15em;text-transform:uppercase;color:var(--text-3)">On-chain Identity</span>
</div>
<p class="bento-title">ERC-8004 agent standard</p>
@@ -1010,7 +1010,7 @@
<!-- MCP / A2A Skills -->
<div class="bento-card">
<div class="bento-icon">
- <span class="dot" style="background:#ff5ca8;box-shadow:0 0 8px #ff5ca855"></span>
+ <span class="dot" style="background:#ffffff;box-shadow:0 0 8px #ffffff55"></span>
<span style="font-family:var(--font-mono);font-size:11px;letter-spacing:0.15em;text-transform:uppercase;color:var(--text-3)">Skills</span>
</div>
<p class="bento-title">MCP · A2A · tool chain</p>
@@ -1229,14 +1229,14 @@
<div class="feat-visual-label">Walk embed · live preview</div>
<div style="padding:28px;display:flex;flex-direction:column;gap:14px;">
<div style="background:var(--surface-2);border-radius:8px;border:1px solid var(--hairline-strong);aspect-ratio:16/9;display:flex;align-items:center;justify-content:center;position:relative;overflow:hidden;">
- <div style="position:absolute;inset:0;background:radial-gradient(ellipse at 30% 60%, rgba(106,92,255,0.12) 0%, transparent 60%), radial-gradient(ellipse at 70% 40%, rgba(34,197,94,0.08) 0%, transparent 50%);"></div>
+ <div style="position:absolute;inset:0;background:radial-gradient(ellipse at 30% 60%, rgba(255,255,255,0.12) 0%, transparent 60%), radial-gradient(ellipse at 70% 40%, rgba(34,197,94,0.08) 0%, transparent 50%);"></div>
<div style="display:flex;gap:16px;align-items:flex-end;position:relative;z-index:1;">
<div style="display:flex;flex-direction:column;align-items:center;gap:6px;">
- <div style="width:28px;height:48px;background:linear-gradient(180deg,#6a5cff,#a59dff);border-radius:14px 14px 6px 6px;opacity:0.9;"></div>
+ <div style="width:28px;height:48px;background:linear-gradient(180deg,#ffffff,#cccccc);border-radius:14px 14px 6px 6px;opacity:0.9;"></div>
<div style="font-family:var(--font-mono);font-size:9px;color:var(--text-3);letter-spacing:0.1em;">@alice</div>
</div>
<div style="display:flex;flex-direction:column;align-items:center;gap:6px;">
- <div style="width:28px;height:52px;background:linear-gradient(180deg,#ff5ca8,#ffb3d6);border-radius:14px 14px 6px 6px;opacity:0.9;"></div>
+ <div style="width:28px;height:52px;background:linear-gradient(180deg,#ffffff,#cccccc);border-radius:14px 14px 6px 6px;opacity:0.9;"></div>
<div style="font-family:var(--font-mono);font-size:9px;color:var(--text-3);letter-spacing:0.1em;">@bob</div>
</div>
<div style="display:flex;flex-direction:column;align-items:center;gap:6px;">
@@ -1402,7 +1402,7 @@
</div>
</a>
<a class="shot" href="/discover?filter=onchain">
- <div class="shot-fill" style="background:linear-gradient(135deg, rgba(106,92,255,0.12) 0%, var(--surface-0) 100%);"></div>
+ <div class="shot-fill" style="background:linear-gradient(135deg, rgba(255,255,255,0.12) 0%, var(--surface-0) 100%);"></div>
<div class="shot-meta">
<div class="shot-name">On-chain</div>
<div class="shot-sub">ERC-8004 directory</div>
diff --git a/pages/mocap-studio.html b/pages/mocap-studio.html
index 6e2a2db19..724ee3793 100644
--- a/pages/mocap-studio.html
+++ b/pages/mocap-studio.html
@@ -24,9 +24,9 @@
--text-2: #a8a8a8;
--text-3: #6a6a6a;
--text-4: #4a4a4a;
- --accent: #8b5cf6;
- --accent-2: #6366f1;
- --accent-glow: rgba(139, 92, 246, 0.35);
+ --accent: #ffffff;
+ --accent-2: #ffffff;
+ --accent-glow: rgba(255, 255, 255, 0.15);
--rec: #f43f5e;
--rec-glow: rgba(244, 63, 94, 0.4);
--ok: #4ade80;
@@ -303,8 +303,8 @@
.field-row input:focus,
.field-row select:focus,
.field-row textarea:focus {
- border-color: rgba(139, 92, 246, 0.5);
- box-shadow: 0 0 0 3px rgba(139, 92, 246, 0.1);
+ border-color: rgba(255, 255, 255, 0.5);
+ box-shadow: 0 0 0 3px rgba(255, 255, 255, 0.1);
}
.field-row textarea { resize: vertical; min-height: 64px; }
.field-row select { appearance: none; background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='8' viewBox='0 0 12 8'%3E%3Cpath d='M1 1l5 5 5-5' stroke='%236a6a6a' stroke-width='1.5' fill='none' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E"); background-repeat: no-repeat; background-position: right 13px center; padding-right: 32px; }
@@ -334,9 +334,9 @@
.btn:active { transform: scale(0.97); }
.btn[disabled] { opacity: 0.35; cursor: not-allowed; pointer-events: none; }
.btn-primary {
- background: linear-gradient(135deg, #8b5cf6 0%, #6366f1 100%);
+ background: #ffffff;
color: #fff;
- box-shadow: 0 1px 0 rgba(255,255,255,0.15) inset, 0 6px 18px -8px rgba(139, 92, 246, 0.6);
+ box-shadow: 0 1px 0 rgba(255,255,255,0.15) inset, 0 6px 18px -8px rgba(255, 255, 255, 0.6);
}
.btn-primary:hover { opacity: 0.9; }
.btn-danger {
diff --git a/pages/voice.html b/pages/voice.html
new file mode 100644
index 000000000..b9725d198
--- /dev/null
+++ b/pages/voice.html
@@ -0,0 +1,777 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
+ <title>Voice Lab · three.ws</title>
+ <meta name="description" content="Clone your voice in seconds. Record, preview, and use your cloned voice across three.ws avatars and agents." />
+ <link rel="canonical" href="https://three.ws/voice" />
+ <meta property="og:title" content="Voice Lab · three.ws" />
+ <meta property="og:description" content="Clone your voice and give your 3D avatars and AI agents a unique voice. Record 20-30 seconds and get an instant voice clone." />
+ <meta property="og:url" content="https://three.ws/voice" />
+ <meta name="twitter:card" content="summary_large_image" />
+ <link rel="stylesheet" href="/style.css" />
+ <link rel="stylesheet" href="/nav.css" />
+ <link rel="stylesheet" href="/fonts/fonts.css" />
+ <style>
+ :root { color-scheme: dark; }
+ *, *::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;
+ min-height: 100vh;
+ }
+
+ /* ── Layout ─────────────────────────────────── */
+ .vl-root {
+ max-width: 920px;
+ margin: 0 auto;
+ padding: 32px 24px 80px;
+ }
+ .vl-header {
+ margin-bottom: 36px;
+ }
+ .vl-header h1 {
+ font-family: 'Space Grotesk', system-ui, sans-serif;
+ font-size: 32px;
+ font-weight: 700;
+ letter-spacing: -0.02em;
+ margin: 0 0 8px;
+ background: linear-gradient(135deg, #e8eaf0 30%, #3dc1ff 70%, #a78bfa);
+ -webkit-background-clip: text;
+ -webkit-text-fill-color: transparent;
+ background-clip: text;
+ }
+ .vl-header p {
+ color: #8a8d9b;
+ font-size: 15px;
+ margin: 0;
+ max-width: 56ch;
+ line-height: 1.6;
+ }
+
+ /* ── Card base ──────────────────────────────── */
+ .vl-card {
+ background: #0a0b12;
+ border: 1px solid #1a1c28;
+ border-radius: 16px;
+ overflow: hidden;
+ }
+ .vl-card-head {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 16px 20px 14px;
+ border-bottom: 1px solid #1a1c28;
+ }
+ .vl-card-title {
+ font-family: 'Space Grotesk', system-ui, sans-serif;
+ font-size: 14px;
+ font-weight: 600;
+ letter-spacing: 0.04em;
+ text-transform: uppercase;
+ color: #8a8d9b;
+ }
+ .vl-card-body {
+ padding: 20px;
+ }
+
+ /* ── Recorder ───────────────────────────────── */
+ .vl-recorder {
+ margin-bottom: 28px;
+ }
+ .vl-wave-wrap {
+ position: relative;
+ height: 200px;
+ background: #07080e;
+ border-bottom: 1px solid #1a1c28;
+ overflow: hidden;
+ }
+ .vl-wave-wrap canvas {
+ display: block;
+ width: 100%;
+ height: 100%;
+ }
+ .vl-wave-overlay {
+ position: absolute;
+ inset: 0;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ pointer-events: none;
+ z-index: 1;
+ }
+ .vl-timer {
+ font: 700 28px/1 'Space Grotesk', ui-monospace, monospace;
+ color: #e8eaf0;
+ letter-spacing: 0.02em;
+ opacity: 0;
+ transition: opacity 0.2s;
+ }
+ .vl-recorder[data-state="recording"] .vl-timer { opacity: 1; }
+ .vl-timer-sub {
+ font-size: 12px;
+ color: #565870;
+ margin-top: 4px;
+ opacity: 0;
+ transition: opacity 0.2s;
+ }
+ .vl-recorder[data-state="recording"] .vl-timer-sub { opacity: 1; }
+
+ /* Progress bar along bottom of waveform */
+ .vl-progress {
+ position: absolute;
+ bottom: 0;
+ left: 0;
+ height: 3px;
+ background: linear-gradient(90deg, #3dc1ff, #a78bfa);
+ width: 0%;
+ transition: width 0.3s linear;
+ z-index: 2;
+ }
+
+ /* Recording indicator dot */
+ .vl-rec-dot {
+ position: absolute;
+ top: 14px;
+ left: 16px;
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ opacity: 0;
+ transition: opacity 0.15s;
+ z-index: 2;
+ }
+ .vl-rec-dot-circle {
+ width: 10px;
+ height: 10px;
+ background: #ef4444;
+ border-radius: 50%;
+ }
+ .vl-rec-dot-label {
+ font-size: 11px;
+ font-weight: 600;
+ text-transform: uppercase;
+ letter-spacing: 0.08em;
+ color: #ef4444;
+ }
+ .vl-recorder[data-state="recording"] .vl-rec-dot {
+ opacity: 1;
+ }
+ .vl-recorder[data-state="recording"] .vl-rec-dot-circle {
+ animation: vl-pulse 1.2s ease-in-out infinite;
+ }
+ @keyframes vl-pulse {
+ 0%, 100% { opacity: 1; transform: scale(1); }
+ 50% { opacity: 0.4; transform: scale(0.85); }
+ }
+
+ /* Level meter */
+ .vl-level {
+ position: absolute;
+ top: 14px;
+ right: 16px;
+ display: flex;
+ gap: 2px;
+ align-items: flex-end;
+ height: 20px;
+ opacity: 0;
+ transition: opacity 0.15s;
+ z-index: 2;
+ }
+ .vl-recorder[data-state="recording"] .vl-level { opacity: 1; }
+ .vl-level-bar {
+ width: 3px;
+ border-radius: 1.5px;
+ background: #3dc1ff;
+ transition: height 0.08s ease-out;
+ min-height: 3px;
+ }
+
+ /* ── Controls row ───────────────────────────── */
+ .vl-controls {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ gap: 12px;
+ padding: 20px;
+ border-bottom: 1px solid #1a1c28;
+ }
+ .vl-btn {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ gap: 8px;
+ border: 0;
+ border-radius: 12px;
+ font: 600 14px/1 system-ui, sans-serif;
+ cursor: pointer;
+ transition: opacity 0.12s, transform 0.1s, background 0.15s, box-shadow 0.15s;
+ white-space: nowrap;
+ }
+ .vl-btn:disabled { opacity: 0.35; cursor: not-allowed; transform: none !important; }
+ .vl-btn:not(:disabled):hover { transform: translateY(-1px); }
+ .vl-btn:not(:disabled):active { transform: translateY(0); }
+
+ .vl-btn-record {
+ background: #e8eaf0;
+ color: #0a0a0a;
+ padding: 14px 28px;
+ font-size: 15px;
+ border-radius: 999px;
+ }
+ .vl-btn-record:not(:disabled):hover {
+ box-shadow: 0 0 0 4px rgba(232,234,240,0.12);
+ }
+ .vl-recorder[data-state="recording"] .vl-btn-record { display: none; }
+
+ .vl-btn-stop {
+ background: #ef4444;
+ color: #fff;
+ padding: 14px 28px;
+ font-size: 15px;
+ border-radius: 999px;
+ display: none;
+ }
+ .vl-recorder[data-state="recording"] .vl-btn-stop { display: inline-flex; }
+ .vl-btn-stop:not(:disabled):hover {
+ box-shadow: 0 0 0 4px rgba(239,68,68,0.18);
+ }
+
+ .vl-btn-ghost {
+ background: rgba(255,255,255,0.06);
+ border: 1px solid rgba(255,255,255,0.12);
+ color: #c8cadf;
+ padding: 10px 18px;
+ }
+ .vl-btn-ghost:not(:disabled):hover {
+ background: rgba(255,255,255,0.10);
+ border-color: rgba(255,255,255,0.20);
+ }
+
+ .vl-btn-primary {
+ background: #3dc1ff;
+ color: #05060a;
+ padding: 12px 22px;
+ }
+ .vl-btn-primary:not(:disabled):hover {
+ background: #5dccff;
+ box-shadow: 0 0 0 4px rgba(61,193,255,0.15);
+ }
+
+ .vl-btn-danger {
+ background: rgba(239,68,68,0.12);
+ border: 1px solid rgba(239,68,68,0.3);
+ color: #f87171;
+ padding: 8px 14px;
+ font-size: 12px;
+ }
+
+ .vl-btn-sm {
+ padding: 8px 14px;
+ font-size: 12px;
+ border-radius: 8px;
+ }
+
+ .vl-rec-dot-icon {
+ width: 10px;
+ height: 10px;
+ background: #ef4444;
+ border-radius: 50%;
+ flex-shrink: 0;
+ }
+
+ /* ── Script prompts ─────────────────────────── */
+ .vl-scripts {
+ padding: 16px 20px;
+ border-bottom: 1px solid #1a1c28;
+ display: none;
+ }
+ .vl-recorder[data-state="recording"] .vl-scripts,
+ .vl-recorder[data-state="idle"] .vl-scripts { display: block; }
+ .vl-scripts-label {
+ font-size: 11px;
+ font-weight: 600;
+ text-transform: uppercase;
+ letter-spacing: 0.08em;
+ color: #565870;
+ margin-bottom: 8px;
+ }
+ .vl-script-text {
+ font-size: 15px;
+ line-height: 1.65;
+ color: #c8cadf;
+ font-style: italic;
+ min-height: 52px;
+ }
+ .vl-script-nav {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ margin-top: 10px;
+ }
+ .vl-script-dots {
+ display: flex;
+ gap: 6px;
+ }
+ .vl-script-dot {
+ width: 6px;
+ height: 6px;
+ border-radius: 50%;
+ background: #1e2035;
+ transition: background 0.2s;
+ }
+ .vl-script-dot.active {
+ background: #3dc1ff;
+ }
+ .vl-script-next {
+ background: none;
+ border: none;
+ color: #565870;
+ font: 600 12px system-ui, sans-serif;
+ cursor: pointer;
+ padding: 4px 8px;
+ border-radius: 6px;
+ transition: color 0.12s, background 0.12s;
+ }
+ .vl-script-next:hover { color: #c8cadf; background: rgba(255,255,255,0.05); }
+
+ /* ── Review panel (after recording) ─────────── */
+ .vl-review {
+ padding: 20px;
+ display: none;
+ }
+ .vl-recorder[data-state="review"] .vl-review,
+ .vl-recorder[data-state="cloning"] .vl-review,
+ .vl-recorder[data-state="done"] .vl-review { display: block; }
+
+ .vl-review audio {
+ width: 100%;
+ height: 40px;
+ margin-bottom: 16px;
+ border-radius: 8px;
+ }
+ .vl-review-row {
+ display: flex;
+ gap: 10px;
+ align-items: flex-end;
+ flex-wrap: wrap;
+ }
+ .vl-review-field {
+ flex: 1;
+ min-width: 200px;
+ }
+ .vl-review-field label {
+ display: block;
+ font-size: 11px;
+ font-weight: 600;
+ text-transform: uppercase;
+ letter-spacing: 0.06em;
+ color: #565870;
+ margin-bottom: 6px;
+ }
+ .vl-review-field input {
+ width: 100%;
+ padding: 10px 12px;
+ background: #07080e;
+ border: 1px solid #1e2035;
+ border-radius: 9px;
+ color: #e8eaf0;
+ font: inherit;
+ font-size: 14px;
+ outline: none;
+ transition: border-color 0.15s;
+ }
+ .vl-review-field input:focus { border-color: #3dc1ff; }
+ .vl-review-actions {
+ display: flex;
+ gap: 8px;
+ margin-top: 14px;
+ }
+
+ /* Cloning state overlay */
+ .vl-cloning-overlay {
+ display: none;
+ align-items: center;
+ gap: 10px;
+ padding: 14px 0;
+ }
+ .vl-recorder[data-state="cloning"] .vl-cloning-overlay { display: flex; }
+ .vl-recorder[data-state="cloning"] .vl-review-row,
+ .vl-recorder[data-state="cloning"] .vl-review-actions { display: none; }
+ .vl-recorder[data-state="done"] .vl-review-row,
+ .vl-recorder[data-state="done"] .vl-review-actions { display: none; }
+
+ .vl-spinner {
+ width: 18px;
+ height: 18px;
+ border-radius: 50%;
+ border: 2.5px solid rgba(61,193,255,0.2);
+ border-top-color: #3dc1ff;
+ animation: vl-spin 0.8s linear infinite;
+ flex-shrink: 0;
+ }
+ @keyframes vl-spin { to { transform: rotate(360deg); } }
+ .vl-cloning-text {
+ font-size: 14px;
+ color: #8a8d9b;
+ }
+
+ /* Done state */
+ .vl-done-msg {
+ display: none;
+ padding: 14px 0;
+ }
+ .vl-recorder[data-state="done"] .vl-done-msg { display: block; }
+ .vl-done-success {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ padding: 14px 16px;
+ background: rgba(52,211,153,0.08);
+ border: 1px solid rgba(52,211,153,0.25);
+ border-radius: 10px;
+ margin-bottom: 14px;
+ }
+ .vl-done-check {
+ width: 22px;
+ height: 22px;
+ background: #34d399;
+ border-radius: 50%;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ flex-shrink: 0;
+ color: #05060a;
+ font-size: 13px;
+ font-weight: 700;
+ }
+ .vl-done-text {
+ font-size: 14px;
+ color: #34d399;
+ font-weight: 500;
+ }
+ .vl-done-actions {
+ display: flex;
+ gap: 8px;
+ flex-wrap: wrap;
+ }
+
+ /* ── Status bar ─────────────────────────────── */
+ .vl-status {
+ padding: 10px 20px;
+ font-size: 12px;
+ color: #565870;
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ min-height: 38px;
+ }
+ .vl-status.ok { color: #34d399; }
+ .vl-status.err { color: #f87171; }
+ .vl-status.warn { color: #fbbf24; }
+
+ /* ── Section spacing ─────────────────────────── */
+ .vl-section {
+ margin-bottom: 28px;
+ }
+ .vl-section-head {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ margin-bottom: 14px;
+ }
+ .vl-section-title {
+ font-family: 'Space Grotesk', system-ui, sans-serif;
+ font-size: 18px;
+ font-weight: 600;
+ color: #e8eaf0;
+ }
+
+ /* ── Voice library grid ─────────────────────── */
+ .vl-voices {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
+ gap: 12px;
+ }
+ .vl-voice-card {
+ background: #0a0b12;
+ border: 1px solid #1a1c28;
+ border-radius: 12px;
+ padding: 16px;
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+ transition: border-color 0.15s;
+ }
+ .vl-voice-card:hover { border-color: #252840; }
+ .vl-voice-name {
+ font-weight: 600;
+ font-size: 14px;
+ color: #e8eaf0;
+ }
+ .vl-voice-meta {
+ font-size: 11.5px;
+ color: #565870;
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ }
+ .vl-voice-id {
+ font-family: ui-monospace, monospace;
+ font-size: 11px;
+ color: #3dc1ff;
+ background: rgba(61,193,255,0.08);
+ padding: 2px 8px;
+ border-radius: 4px;
+ word-break: break-all;
+ }
+ .vl-voice-actions {
+ display: flex;
+ gap: 6px;
+ margin-top: auto;
+ }
+ .vl-empty {
+ text-align: center;
+ padding: 32px 20px;
+ color: #565870;
+ font-size: 14px;
+ border: 1px dashed #1a1c28;
+ border-radius: 12px;
+ }
+ .vl-empty-title {
+ font-weight: 600;
+ color: #8a8d9b;
+ margin-bottom: 4px;
+ }
+
+ /* ── Playground ─────────────────────────────── */
+ .vl-pg-row {
+ display: flex;
+ gap: 12px;
+ align-items: flex-end;
+ margin-bottom: 14px;
+ flex-wrap: wrap;
+ }
+ .vl-pg-field {
+ flex: 1;
+ min-width: 200px;
+ }
+ .vl-pg-field label {
+ display: block;
+ font-size: 11px;
+ font-weight: 600;
+ text-transform: uppercase;
+ letter-spacing: 0.06em;
+ color: #565870;
+ margin-bottom: 6px;
+ }
+ .vl-pg-field select {
+ width: 100%;
+ padding: 10px 12px;
+ background: #07080e;
+ border: 1px solid #1e2035;
+ border-radius: 9px;
+ color: #e8eaf0;
+ font: inherit;
+ font-size: 14px;
+ cursor: pointer;
+ outline: none;
+ }
+ .vl-pg-field select:focus { border-color: #3dc1ff; }
+ .vl-pg-textarea {
+ width: 100%;
+ min-height: 100px;
+ padding: 12px 14px;
+ background: #07080e;
+ border: 1px solid #1e2035;
+ border-radius: 10px;
+ color: #e8eaf0;
+ font: inherit;
+ font-size: 14px;
+ line-height: 1.55;
+ resize: vertical;
+ outline: none;
+ transition: border-color 0.15s;
+ }
+ .vl-pg-textarea:focus { border-color: #3dc1ff; }
+ .vl-pg-samples {
+ display: flex;
+ gap: 6px;
+ flex-wrap: wrap;
+ margin-bottom: 14px;
+ }
+ .vl-pg-sample {
+ background: rgba(255,255,255,0.04);
+ border: 1px solid #1a1c28;
+ color: #8a8d9b;
+ padding: 6px 12px;
+ border-radius: 999px;
+ font: 500 12px system-ui, sans-serif;
+ cursor: pointer;
+ transition: background 0.12s, color 0.12s, border-color 0.12s;
+ }
+ .vl-pg-sample:hover {
+ background: rgba(61,193,255,0.08);
+ border-color: rgba(61,193,255,0.3);
+ color: #3dc1ff;
+ }
+ .vl-pg-output {
+ margin-top: 16px;
+ display: none;
+ }
+ .vl-pg-output.visible { display: block; }
+ .vl-pg-output audio {
+ width: 100%;
+ height: 40px;
+ border-radius: 8px;
+ }
+ .vl-pg-actions {
+ display: flex;
+ gap: 10px;
+ align-items: center;
+ }
+
+ /* ── Responsive ─────────────────────────────── */
+ @media (max-width: 640px) {
+ .vl-root { padding: 20px 16px 60px; }
+ .vl-header h1 { font-size: 26px; }
+ .vl-wave-wrap { height: 160px; }
+ .vl-controls { padding: 16px; }
+ .vl-card-body { padding: 16px; }
+ .vl-voices { grid-template-columns: 1fr; }
+ .vl-review-row { flex-direction: column; }
+ }
+ </style>
+ </head>
+ <body>
+ <header><div id="nav-container"></div></header>
+
+ <main class="vl-root">
+ <div class="vl-header">
+ <h1>Voice Lab</h1>
+ <p>Clone your voice in seconds. Record 20-30 seconds of clear speech, and we'll create a digital replica you can use across your avatars and agents.</p>
+ </div>
+
+ <!-- ── Recorder ─────────────────────────────── -->
+ <div class="vl-section">
+ <div class="vl-card vl-recorder" data-state="idle" id="recorder">
+ <div class="vl-wave-wrap">
+ <canvas id="waveCanvas"></canvas>
+ <div class="vl-rec-dot">
+ <div class="vl-rec-dot-circle"></div>
+ <div class="vl-rec-dot-label">Recording</div>
+ </div>
+ <div class="vl-level" id="levelMeter"></div>
+ <div class="vl-wave-overlay">
+ <div class="vl-timer" id="timer">0:00</div>
+ <div class="vl-timer-sub" id="timerSub">Recommended: 20-30 seconds</div>
+ </div>
+ <div class="vl-progress" id="progress"></div>
+ </div>
+
+ <div class="vl-scripts" id="scripts">
+ <div class="vl-scripts-label">Read aloud for best results</div>
+ <div class="vl-script-text" id="scriptText"></div>
+ <div class="vl-script-nav">
+ <div class="vl-script-dots" id="scriptDots"></div>
+ <button class="vl-script-next" id="scriptNext">Next prompt</button>
+ </div>
+ </div>
+
+ <div class="vl-controls" id="controls">
+ <button class="vl-btn vl-btn-record" id="btnRecord">
+ <span class="vl-rec-dot-icon"></span>
+ Start recording
+ </button>
+ <button class="vl-btn vl-btn-stop" id="btnStop">
+ Stop recording
+ </button>
+ </div>
+
+ <div class="vl-review" id="review">
+ <audio id="reviewAudio" controls></audio>
+ <div class="vl-review-row">
+ <div class="vl-review-field">
+ <label for="voiceName">Voice name</label>
+ <input type="text" id="voiceName" placeholder="e.g. My Voice" maxlength="64" />
+ </div>
+ </div>
+ <div class="vl-review-actions">
+ <button class="vl-btn vl-btn-primary" id="btnClone">Clone voice</button>
+ <button class="vl-btn vl-btn-ghost vl-btn-sm" id="btnRerecord">Re-record</button>
+ </div>
+ <div class="vl-cloning-overlay">
+ <div class="vl-spinner"></div>
+ <div class="vl-cloning-text">Cloning your voice...</div>
+ </div>
+ <div class="vl-done-msg" id="doneMsg">
+ <div class="vl-done-success">
+ <div class="vl-done-check">&#10003;</div>
+ <div class="vl-done-text" id="doneText">Voice cloned successfully</div>
+ </div>
+ <div class="vl-done-actions">
+ <button class="vl-btn vl-btn-primary vl-btn-sm" id="btnTryPlayground">Try in playground</button>
+ <button class="vl-btn vl-btn-ghost vl-btn-sm" id="btnRecordAnother">Record another</button>
+ </div>
+ </div>
+ </div>
+
+ <div class="vl-status" id="status">Ready to record</div>
+ </div>
+ </div>
+
+ <!-- ── Voice Library ─────────────────────────── -->
+ <div class="vl-section" id="librarySection">
+ <div class="vl-section-head">
+ <h2 class="vl-section-title">My Voices</h2>
+ </div>
+ <div id="voiceLibrary">
+ <div class="vl-empty">
+ <div class="vl-empty-title">No cloned voices yet</div>
+ Record a voice sample above to get started.
+ </div>
+ </div>
+ </div>
+
+ <!-- ── TTS Playground ────────────────────────── -->
+ <div class="vl-section" id="playgroundSection">
+ <div class="vl-section-head">
+ <h2 class="vl-section-title">Text-to-Speech Playground</h2>
+ </div>
+ <div class="vl-card">
+ <div class="vl-card-body">
+ <div class="vl-pg-row">
+ <div class="vl-pg-field">
+ <label for="pgVoice">Voice</label>
+ <select id="pgVoice">
+ <option value="" disabled selected>Clone a voice first</option>
+ </select>
+ </div>
+ </div>
+ <textarea class="vl-pg-textarea" id="pgText" placeholder="Type something to hear it spoken..." maxlength="500">Hello, I'm a three.ws agent. Nice to meet you.</textarea>
+ <div class="vl-pg-samples" id="pgSamples">
+ <button class="vl-pg-sample" data-text="Welcome to three.ws, the home of agentic 3D characters.">Welcome</button>
+ <button class="vl-pg-sample" data-text="Numbers test: one, two, three, four, five, six, seven, eight, nine, ten.">Numbers</button>
+ <button class="vl-pg-sample" data-text="The quick brown fox jumps over the lazy dog. She sells seashells by the seashore.">Diction</button>
+ <button class="vl-pg-sample" data-text="I believe technology should serve people. The future of interaction lies in natural, conversational interfaces that feel like talking to a friend.">Natural speech</button>
+ </div>
+ <div class="vl-pg-actions">
+ <button class="vl-btn vl-btn-primary" id="pgSpeak" disabled>Speak</button>
+ <span class="vl-pg-hint" id="pgHint" style="font-size:12px;color:#565870;"></span>
+ </div>
+ <div class="vl-pg-output" id="pgOutput">
+ <audio id="pgAudio" controls></audio>
+ </div>
+ </div>
+ </div>
+ </div>
+ </main>
+
+ <script src="/nav.js" defer></script>
+ <script type="module" src="/src/voice-lab.js"></script>
+ </body>
+</html>
diff --git a/pages/walk-app.html b/pages/walk-app.html
index a3b79b876..65f59bca4 100644
--- a/pages/walk-app.html
+++ b/pages/walk-app.html
@@ -66,7 +66,7 @@
--border: rgba(255, 255, 255, 0.08);
--text: #fafafa;
--text-2: #a1a1aa;
- --accent: #7dd3fc;
+ --accent: #ffffff;
--danger: #f87171;
}
@@ -187,8 +187,8 @@
.walk-btn:hover { background: rgba(34, 34, 34, 0.85); }
.walk-btn:active { transform: scale(0.97); }
.walk-btn[aria-pressed="true"] {
- background: rgba(125, 211, 252, 0.18);
- border-color: rgba(125, 211, 252, 0.45);
+ background: rgba(255, 255, 255, 0.18);
+ border-color: rgba(255, 255, 255, 0.45);
color: #e0f2fe;
}
.walk-btn[disabled] { opacity: 0.5; cursor: not-allowed; }
@@ -363,7 +363,7 @@
align-items: center;
gap: 10px;
padding: 10px 14px 10px 12px;
- background: linear-gradient(135deg, rgba(125, 211, 252, 0.92), rgba(96, 165, 250, 0.92));
+ background: linear-gradient(135deg, rgba(255, 255, 255, 0.92), rgba(255, 255, 255, 0.92));
color: #07111c;
border: 1px solid rgba(255, 255, 255, 0.35);
border-radius: 999px;
diff --git a/pages/walk.html b/pages/walk.html
index ce448190c..0342c5b64 100644
--- a/pages/walk.html
+++ b/pages/walk.html
@@ -66,7 +66,7 @@
--border: rgba(255, 255, 255, 0.08);
--text: #fafafa;
--text-2: #a1a1aa;
- --accent: #7dd3fc;
+ --accent: #ffffff;
--danger: #f87171;
}
@@ -187,8 +187,8 @@
.walk-btn:hover { background: rgba(34, 34, 34, 0.85); }
.walk-btn:active { transform: scale(0.97); }
.walk-btn[aria-pressed="true"] {
- background: rgba(125, 211, 252, 0.18);
- border-color: rgba(125, 211, 252, 0.45);
+ background: rgba(255, 255, 255, 0.18);
+ border-color: rgba(255, 255, 255, 0.45);
color: #e0f2fe;
}
.walk-btn[disabled] { opacity: 0.5; cursor: not-allowed; }
@@ -363,7 +363,7 @@
align-items: center;
gap: 10px;
padding: 10px 14px 10px 12px;
- background: linear-gradient(135deg, rgba(125, 211, 252, 0.92), rgba(96, 165, 250, 0.92));
+ background: linear-gradient(135deg, rgba(255, 255, 255, 0.92), rgba(255, 255, 255, 0.92));
color: #07111c;
border: 1px solid rgba(255, 255, 255, 0.35);
border-radius: 999px;
@@ -596,7 +596,7 @@
.walk-emote-btn:active { transform: scale(0.95); }
.walk-emote-btn[aria-pressed="true"] {
border-color: var(--accent);
- background: rgba(125, 211, 252, 0.18);
+ background: rgba(255, 255, 255, 0.18);
}
.walk-emote-btn .emote-label {
position: absolute;
diff --git a/public/ai-stream.css b/public/ai-stream.css
index 5d060a15a..702256ee6 100644
--- a/public/ai-stream.css
+++ b/public/ai-stream.css
@@ -50,9 +50,9 @@ html, body {
gap: 12px;
}
.ai-stream-header select, .ai-stream-header button {
- background: #161620;
+ background: #111111;
color: #eee;
- border: 1px solid #2a2a36;
+ border: 1px solid #2a2a2a;
border-radius: 6px;
padding: 6px 10px;
font-size: 13px;
@@ -105,8 +105,8 @@ html, body {
}
/* Event card styles from pumpfun.html can be reused here */
.evt {
- border: 1px solid #232330;
- background: #15151d;
+ border: 1px solid #1a1a1a;
+ background: #111111;
border-radius: 8px;
padding: 10px 12px;
font-size: 12px;
diff --git a/public/avatar-studio-demo.css b/public/avatar-studio-demo.css
index 3afffd683..809b19a22 100644
--- a/public/avatar-studio-demo.css
+++ b/public/avatar-studio-demo.css
@@ -438,7 +438,7 @@ html, body {
top: 50%;
border-radius: 50%;
background: var(--as-accent);
- box-shadow: 0 0 8px rgba(125, 211, 252, 0.4);
+ box-shadow: 0 0 8px rgba(255, 255, 255, 0.3);
cursor: grab;
touch-action: none;
z-index: 2;
diff --git a/public/demos/halfbody-xr.html b/public/demos/halfbody-xr.html
index ac393823a..9fe202616 100644
--- a/public/demos/halfbody-xr.html
+++ b/public/demos/halfbody-xr.html
@@ -208,11 +208,19 @@
viewer.scene.add(root);
viewer.content = root;
- // Attach animations
- await viewer.animationManager.loadAll();
+ // Attach animations — fetch manifest lazily
+ try {
+ const manifest = await fetch('/animations/manifest.json', { cache: 'force-cache' })
+ .then((r) => r.ok ? r.json() : []);
+ const idleDef = manifest.find((d) => d.name === 'idle') || manifest[0];
+ if (idleDef) {
+ viewer.animationManager.setAnimationDefs([idleDef]);
+ await viewer.animationManager.loadAll();
+ }
+ } catch {}
viewer.animationManager.attach(root);
viewer.mixer = viewer.animationManager.mixer;
- viewer.animationManager.play('idle');
+ if (viewer.animationManager._animationDefs.length) viewer.animationManager.play('idle');
if (applyHalfBody) {
let hidden = 0;
diff --git a/public/home-overhaul.css b/public/home-overhaul.css
index 270f2a894..8e48df1de 100644
--- a/public/home-overhaul.css
+++ b/public/home-overhaul.css
@@ -361,7 +361,7 @@ body.home-page {
.h-livewall-card-visual {
position: relative;
flex: 1 1 auto;
- background: var(--card-grad, linear-gradient(135deg, #1c1438, #0b0a14));
+ background: var(--card-grad, linear-gradient(135deg, #1a1a1a, #0a0a0a));
display: grid;
place-items: center;
overflow: hidden;
diff --git a/public/home-saas.css b/public/home-saas.css
index a1d006013..4d4c55b53 100644
--- a/public/home-saas.css
+++ b/public/home-saas.css
@@ -335,7 +335,7 @@
background: linear-gradient(135deg, #999, #ccc);
font-family: inherit;
font-size: 0.65rem;
- color: #08070b;
+ color: #000000;
display: grid;
place-items: center;
font-weight: 700;
diff --git a/public/my-agents/my-agents.css b/public/my-agents/my-agents.css
index c5664536b..7b68bb667 100644
--- a/public/my-agents/my-agents.css
+++ b/public/my-agents/my-agents.css
@@ -158,7 +158,7 @@ a:hover {
.my-agents-card__thumb {
aspect-ratio: 1 / 1;
- background: #0f0f17;
+ background: #0a0a0a;
display: grid;
place-items: center;
color: #444;
@@ -177,8 +177,8 @@ a:hover {
width: 100%;
height: 100%;
display: block;
- background: #0f0f17;
- --poster-color: #0f0f17;
+ background: #0a0a0a;
+ --poster-color: #0a0a0a;
}
.my-agents-card__body {
@@ -264,7 +264,7 @@ a:hover {
}
.my-agents-btn--sec {
- background: #222230;
+ background: #222222;
color: #ddd;
}
@@ -294,7 +294,7 @@ a:hover {
.my-agents-skeleton__thumb {
aspect-ratio: 1 / 1;
- background: linear-gradient(90deg, #1a1a24 25%, #22222e 50%, #1a1a24 75%);
+ background: linear-gradient(90deg, #1a1a1a 25%, #222222 50%, #1a1a1a 75%);
background-size: 600px 100%;
animation: my-agents-shimmer 1.4s infinite linear;
}
@@ -309,7 +309,7 @@ a:hover {
.my-agents-skeleton__line {
height: 12px;
border-radius: 6px;
- background: linear-gradient(90deg, #1a1a24 25%, #22222e 50%, #1a1a24 75%);
+ background: linear-gradient(90deg, #1a1a1a 25%, #222222 50%, #1a1a1a 75%);
background-size: 600px 100%;
animation: my-agents-shimmer 1.4s infinite linear;
}
diff --git a/public/nav.html b/public/nav.html
index fc19a66cc..0de3df159 100644
--- a/public/nav.html
+++ b/public/nav.html
@@ -215,8 +215,8 @@
</li>
<li role="none">
<a href="/brain" role="menuitem"
- ><span class="nav-mi-title">Multi-LLM brain<span class="nav-pill" aria-hidden="true">NEW</span></span
- ><span class="nav-mi-sub">Claude · GPT · Qwen · ModelScope · Groq, side-by-side</span></a
+ ><span class="nav-mi-title">Brain</span
+ ><span class="nav-mi-sub">Chat &amp; compare — Claude, GPT, Llama, Qwen with real metrics</span></a
>
</li>
<li role="none">
diff --git a/public/studio/studio.css b/public/studio/studio.css
index c3cf82370..f784510c9 100644
--- a/public/studio/studio.css
+++ b/public/studio/studio.css
@@ -61,7 +61,7 @@ a:hover {
gap: 1rem;
height: var(--header-h);
padding: 0 1.25rem;
- background: rgba(10, 10, 15, 0.85);
+ background: rgba(0, 0, 0, 0.85);
backdrop-filter: blur(12px);
border-bottom: 1px solid var(--border-soft);
}
@@ -153,7 +153,7 @@ a:hover {
.user-menu-signin:hover {
background: rgba(255, 255, 255, 0.05);
- border-color: #3a3a48;
+ border-color: #333333;
text-decoration: none;
}
@@ -174,12 +174,12 @@ a:hover {
.user-menu-trigger:hover {
background: rgba(255, 255, 255, 0.05) !important;
- border-color: #3a3a48;
+ border-color: #333333;
}
.user-menu-trigger[aria-expanded='true'] {
background: rgba(255, 255, 255, 0.06);
- border-color: #3a3a48;
+ border-color: #333333;
}
.user-menu-avatar {
@@ -189,7 +189,7 @@ a:hover {
width: 26px;
height: 26px;
border-radius: 999px;
- background: linear-gradient(135deg, #3a3a4a, #2a2a38);
+ background: linear-gradient(135deg, #333333, #2a2a2a);
color: #ccc;
font-size: 0.78rem;
font-weight: 600;
@@ -501,7 +501,7 @@ a:hover {
.avatar-card:hover {
border-color: rgba(255, 255, 255, 0.25);
- background: #1f1f2a;
+ background: #1a1a1a;
transform: translateY(-1px);
box-shadow: 0 4px 16px rgba(0,0,0,0.3);
}
@@ -539,7 +539,7 @@ a:hover {
align-items: center;
justify-content: center;
border-radius: var(--radius-sm);
- background: #0d0d14;
+ background: #0a0a0a;
overflow: hidden;
font-size: 1.6rem;
color: rgba(255, 255, 255, 0.4);
@@ -568,7 +568,7 @@ a:hover {
pointer-events: none;
}
.avatar-card--skeleton .thumb {
- background: linear-gradient(90deg, #1a1a24 25%, #222230 50%, #1a1a24 75%);
+ background: linear-gradient(90deg, #1a1a1a 25%, #222222 50%, #1a1a1a 75%);
background-size: 200% 100%;
animation: shimmer 1.5s ease-in-out infinite;
}
@@ -576,7 +576,7 @@ a:hover {
width: 65%;
height: 10px;
border-radius: 999px;
- background: linear-gradient(90deg, #1a1a24 25%, #222230 50%, #1a1a24 75%);
+ background: linear-gradient(90deg, #1a1a1a 25%, #222222 50%, #1a1a1a 75%);
background-size: 200% 100%;
animation: shimmer 1.5s ease-in-out infinite 0.15s;
color: transparent;
@@ -667,7 +667,7 @@ a:hover {
.type-card:hover {
border-color: rgba(255, 255, 255, 0.22);
- background: #1f1f2a;
+ background: #1a1a1a;
}
.type-card.selected {
@@ -751,14 +751,14 @@ a:hover {
width: 100%;
aspect-ratio: 1 / 1;
max-height: calc(100vh - var(--header-h) - 8rem);
- background: #050507;
+ background: #000000;
border-radius: var(--radius-md);
overflow: hidden;
background-image:
- linear-gradient(45deg, #15151c 25%, transparent 25%),
- linear-gradient(-45deg, #15151c 25%, transparent 25%),
- linear-gradient(45deg, transparent 75%, #15151c 75%),
- linear-gradient(-45deg, transparent 75%, #15151c 75%);
+ linear-gradient(45deg, #111111 25%, transparent 25%),
+ linear-gradient(-45deg, #111111 25%, transparent 25%),
+ linear-gradient(45deg, transparent 75%, #111111 75%),
+ linear-gradient(-45deg, transparent 75%, #111111 75%);
background-size: 24px 24px;
background-position: 0 0, 0 12px, 12px -12px, -12px 0;
}
@@ -825,7 +825,7 @@ a:hover {
gap: 0.25rem;
margin: -0.4rem -0.4rem 0.9rem;
padding: 0.3rem;
- background: #0d0d14;
+ background: #0a0a0a;
border: 1px solid var(--border);
border-radius: var(--radius-md);
}
@@ -892,7 +892,7 @@ a:hover {
.field textarea {
width: 100%;
padding: 0.5rem 0.65rem;
- background: #0d0d14;
+ background: #0a0a0a;
border: 1px solid var(--border);
border-radius: var(--radius-sm);
color: var(--text);
@@ -912,7 +912,7 @@ a:hover {
width: 60px;
height: 30px;
padding: 2px;
- background: #0d0d14;
+ background: #0a0a0a;
border: 1px solid var(--border);
border-radius: var(--radius-sm);
cursor: pointer;
@@ -997,7 +997,7 @@ a:hover {
.btn-ghost:hover {
background: rgba(255, 255, 255, 0.04);
- border-color: #3a3a48;
+ border-color: #333333;
color: #fff;
}
@@ -1112,7 +1112,7 @@ a:hover {
margin: 0.85rem 0;
border-radius: var(--radius-md);
border: 1px solid var(--border);
- background: #050507;
+ background: #000000;
overflow: hidden;
}
@@ -1134,7 +1134,7 @@ a:hover {
flex: 1;
font-family: ui-monospace, 'SF Mono', Menlo, monospace;
font-size: 0.78rem;
- background: #0d0d14;
+ background: #0a0a0a;
border: 1px solid var(--border);
border-radius: var(--radius-sm);
color: var(--text);
@@ -1188,7 +1188,7 @@ a:hover {
z-index: 200;
white-space: nowrap;
/* default: info */
- background: #1f1f2a;
+ background: #1a1a1a;
color: #eee;
}
@@ -1255,7 +1255,7 @@ a:hover {
bottom: calc(100% + 6px);
left: 50%;
transform: translateX(-50%) translateY(2px);
- background: #1f1f2a;
+ background: #1a1a1a;
color: #eee;
font-size: 0.72rem;
font-weight: 400;
@@ -1307,7 +1307,7 @@ a:hover {
}
.bonding-curve-preview {
- background: #0d0d14;
+ background: #0a0a0a;
border: 1px solid var(--border);
border-radius: var(--radius-md);
padding: 0.7rem 0.8rem;
@@ -1331,7 +1331,7 @@ a:hover {
.bonding-curve-track {
height: 6px;
- background: #1f1f2a;
+ background: #1a1a1a;
border-radius: 999px;
overflow: hidden;
}
@@ -1442,7 +1442,7 @@ a:hover {
.kp-row-form, .kp-paste-form { display: flex; flex-direction: column; gap: 0.45rem; }
.kp-row-form input, .kp-paste-form textarea {
width: 100%;
- background: #0f0f17;
+ background: #0a0a0a;
border: 1px solid rgba(255, 255, 255, 0.1);
color: #eee;
border-radius: 6px;
@@ -1728,7 +1728,7 @@ a:hover {
.hotspot-pos-row input[type='number'] {
width: 100%;
padding: 0.4rem 0.45rem;
- background: #0d0d14;
+ background: #0a0a0a;
border: 1px solid var(--border);
border-radius: var(--radius-sm);
color: var(--text);
diff --git a/src/brain.js b/src/brain.js
new file mode 100644
index 000000000..54df1535d
--- /dev/null
+++ b/src/brain.js
@@ -0,0 +1,976 @@
+// ── brain.js — Persona builder + multi-model playground ─────────────────────
+
+// ── 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]));
+
+// ── Interview questions ──────────────────────────────────────────────────────
+const QUESTIONS = [
+ { q: 'How would you describe your personality in a few words?', placeholder: 'e.g. Curious, blunt, late.' },
+ { q: 'What do you spend most of your time doing?', placeholder: 'Work, hobbies, obsessions...' },
+ { q: "What topic could you talk about for an hour straight?", placeholder: 'The thing you geek out about...' },
+ { q: "What's a phrase or saying your friends know you for?", placeholder: 'Your catchphrase or motto...' },
+ { q: 'How would you describe your sense of humor?', placeholder: 'Dry, sarcastic, wholesome, chaotic...' },
+ { q: "What kind of language or phrases would you never use?", placeholder: 'Corporate jargon, slang, etc...' },
+];
+const EXAMPLES = [
+ 'Curious, blunt, late.',
+ 'Building small tools for crypto traders — Solana RPC, indexers, dashboards. Some skateboarding when the rain stops.',
+ 'Why most token launches fail in the first 90 minutes. The mechanics, the wallet patterns, the bot dynamics.',
+ '"ship it ugly, fix it Friday"',
+ 'Dry. Self-deprecating. I laugh at my own bugs before anyone else can.',
+ '"Per my last email." or anything that sounds like a LinkedIn post.',
+];
+
+// ── State ────────────────────────────────────────────────────────────────────
+const state = {
+ activeTab: 'persona',
+ method: 'interview',
+ persona: null,
+ personaEnabled: true,
+
+ playMode: 'compare',
+ focusKey: 'anthropic',
+ active: new Set(['anthropic', 'openai', 'qwen-plus', 'groq-llama']),
+ sessions: [],
+ currentId: null,
+ streaming: false,
+ agents: [],
+};
+
+// ── DOM helpers ──────────────────────────────────────────────────────────────
+const $ = id => document.getElementById(id);
+const escHtml = s => s.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
+
+function uuid() {
+ if (crypto?.randomUUID) return crypto.randomUUID();
+ return Math.random().toString(36).slice(2) + Date.now().toString(36);
+}
+
+// ── Persistence ──────────────────────────────────────────────────────────────
+function save(key, val) { try { localStorage.setItem(key, JSON.stringify(val)); } catch {} }
+function load(key) { try { const r = localStorage.getItem(key); return r ? JSON.parse(r) : null; } catch { return null; } }
+
+function persistSessions() { save('brain_sessions_v3', state.sessions); }
+function loadSessions() { state.sessions = load('brain_sessions_v3') || []; }
+function persistPersona() { save('brain_persona_v1', state.persona); }
+function loadPersona() { state.persona = load('brain_persona_v1'); }
+
+// ── Toast ────────────────────────────────────────────────────────────────────
+let toastTimer;
+function toast(msg) {
+ const el = $('brToast');
+ el.textContent = msg;
+ el.classList.add('show');
+ clearTimeout(toastTimer);
+ toastTimer = setTimeout(() => el.classList.remove('show'), 2500);
+}
+
+function showNotice(msg) {
+ const el = $('brNotice');
+ el.textContent = msg;
+ el.style.display = 'block';
+ clearTimeout(el._t);
+ el._t = setTimeout(() => { el.style.display = 'none'; }, 3500);
+}
+
+// ── Markdown renderer ────────────────────────────────────────────────────────
+function inlineMd(s) {
+ 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">$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];
+ if (line.startsWith('```')) {
+ const codeLines = [];
+ i++;
+ while (i < lines.length && !lines[i].startsWith('```')) { codeLines.push(escHtml(lines[i])); i++; }
+ i++;
+ out.push(`<pre class="md-code"><code>${codeLines.join('\n')}</code></pre>`);
+ continue;
+ }
+ const hm = line.match(/^(#{1,3})\s+(.+)/);
+ if (hm) { out.push(`<h${hm[1].length} class="md-h${hm[1].length}">${inlineMd(escHtml(hm[2]))}</h${hm[1].length}>`); i++; continue; }
+ 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;
+ }
+ 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;
+ }
+ if (!line.trim()) { i++; continue; }
+ 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('');
+}
+
+// ── Session helpers ──────────────────────────────────────────────────────────
+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;
+}
+
+// ── Persona helpers ──────────────────────────────────────────────────────────
+function buildPersonaSystemPrompt(persona) {
+ if (!persona) return '';
+ const parts = [];
+ parts.push(`You are an AI agent with a specific persona. Respond in character.`);
+ if (persona.tone) parts.push(`Tone: ${persona.tone}`);
+ if (persona.communication_style) parts.push(`Communication style: ${persona.communication_style}`);
+ if (persona.vocabulary?.length) parts.push(`Vocabulary you use: ${persona.vocabulary.join(', ')}`);
+ if (persona.interests?.length) parts.push(`Interests: ${persona.interests.join(', ')}`);
+ if (persona.dont_say?.length) parts.push(`Never say: ${persona.dont_say.join(', ')}`);
+ if (persona.sample_greeting) parts.push(`Example greeting: "${persona.sample_greeting}"`);
+ return parts.join('\n');
+}
+
+function getEffectiveSystemPrompt() {
+ const manual = $('brSystem').value.trim();
+ if (manual) return manual;
+ if (state.persona && state.personaEnabled) return buildPersonaSystemPrompt(state.persona);
+ return '';
+}
+
+// ── Render: Tabs ─────────────────────────────────────────────────────────────
+function setTab(tab) {
+ state.activeTab = tab;
+ document.querySelectorAll('.br-tab').forEach(t => t.classList.toggle('active', t.dataset.tab === tab));
+ $('brPanelPersona').classList.toggle('active', tab === 'persona');
+ $('brPanelPlayground').classList.toggle('active', tab === 'playground');
+}
+
+// ── Render: Interview questions ──────────────────────────────────────────────
+function renderQuestions() {
+ const container = $('brQuestions');
+ container.innerHTML = '';
+ QUESTIONS.forEach((q, i) => {
+ const card = document.createElement('div');
+ card.className = 'br-q-card';
+ card.innerHTML = `
+ <span class="br-q-num">Question ${i + 1}</span>
+ <div class="br-q-text">${escHtml(q.q)}</div>
+ <textarea class="br-q-input" id="brQ${i}" placeholder="${escHtml(q.placeholder)}" rows="2"></textarea>
+ `;
+ container.appendChild(card);
+ });
+ container.querySelectorAll('.br-q-input').forEach(el => {
+ el.addEventListener('input', updateSynthButton);
+ });
+}
+
+function collectAnswers() {
+ return QUESTIONS.map((q, i) => ({
+ question: q.q,
+ answer: ($(`brQ${i}`)?.value || '').trim(),
+ }));
+}
+
+function updateSynthButton() {
+ const allFilled = collectAnswers().every(a => a.answer.length > 0);
+ $('brSynthesize').disabled = !allFilled;
+}
+
+// ── Render: Persona card ─────────────────────────────────────────────────────
+function renderPersonaCard(p) {
+ $('brPersonaCard').classList.add('show');
+ $('brPcTone').textContent = p.tone || '-';
+ $('brPcStyle').textContent = p.communication_style || '-';
+ renderChips($('brPcVocab'), p.vocabulary, 'br-chip br-chip-blue');
+ renderChips($('brPcInterests'), p.interests, 'br-chip br-chip-purple');
+ renderChips($('brPcDont'), p.dont_say, 'br-chip br-chip-red');
+ $('brPcGreet').textContent = p.sample_greeting ? `"${p.sample_greeting}"` : '-';
+ $('brRawJson').textContent = JSON.stringify(p, null, 2);
+ updatePersonaMini();
+ updatePersonaBanner();
+}
+
+function renderChips(container, list, cls) {
+ container.innerHTML = '';
+ if (!list?.length) { container.innerHTML = '<span style="color:#4a4e6a;font-size:12px">-</span>'; return; }
+ for (const item of list) {
+ const span = document.createElement('span');
+ span.className = cls;
+ span.textContent = item;
+ container.appendChild(span);
+ }
+}
+
+function updatePersonaMini() {
+ const mini = $('brPersonaMini');
+ if (state.persona) {
+ mini.classList.add('has-persona');
+ $('brMiniTone').textContent = state.persona.tone || 'Custom persona';
+ $('brMiniStyle').textContent = state.persona.communication_style ? `Style: ${state.persona.communication_style}` : '';
+ $('brPersonaBadge').classList.add('on');
+ } else {
+ mini.classList.remove('has-persona');
+ $('brPersonaBadge').classList.remove('on');
+ }
+}
+
+function updatePersonaBanner() {
+ const banner = $('brPersonaBanner');
+ if (state.persona && state.personaEnabled) {
+ banner.classList.add('show');
+ $('brBannerTone').textContent = state.persona.tone || 'Active';
+ } else {
+ banner.classList.remove('show');
+ }
+}
+
+// ── Persona: Synthesis ───────────────────────────────────────────────────────
+async function synthesizeFromInterview() {
+ const answers = collectAnswers();
+ if (!answers.every(a => a.answer.length > 0)) return;
+ await runExtraction({ answers });
+}
+
+async function synthesizeFromFreeform() {
+ const text = $('brFreeformText').value.trim();
+ if (!text) return;
+ await runExtraction({ freeform: text });
+}
+
+async function runExtraction(payload) {
+ $('brLoading').classList.add('show');
+ $('brPersonaCard').classList.remove('show');
+
+ try {
+ let body, endpoint;
+ if (payload.answers) {
+ endpoint = '/api/persona/extract';
+ body = JSON.stringify({ answers: payload.answers });
+ } else {
+ endpoint = '/api/persona/extract';
+ body = JSON.stringify({ freeform: payload.freeform });
+ }
+
+ const res = await fetch(endpoint, {
+ method: 'POST',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body,
+ });
+ const data = await res.json();
+ if (!res.ok) throw new Error(data.error_description || data.error || `HTTP ${res.status}`);
+
+ state.persona = data.persona;
+ persistPersona();
+ renderPersonaCard(state.persona);
+ toast(`Persona extracted (${data.tokens_used} tokens, ${data.latency_ms}ms)`);
+ } catch (err) {
+ toast(`Extraction failed: ${err.message}`);
+ } finally {
+ $('brLoading').classList.remove('show');
+ }
+}
+
+function setPersonaFromManual() {
+ const split = v => v.split(',').map(s => s.trim()).filter(Boolean);
+ state.persona = {
+ tone: $('brManTone').value.trim() || 'Neutral',
+ communication_style: $('brManStyle').value,
+ vocabulary: split($('brManVocab').value),
+ interests: split($('brManInterests').value),
+ dont_say: split($('brManDont').value),
+ sample_greeting: $('brManGreet').value.trim(),
+ };
+ persistPersona();
+ renderPersonaCard(state.persona);
+ toast('Persona set');
+}
+
+// ── Persona: Edit inline ─────────────────────────────────────────────────────
+function openEditMode() {
+ if (!state.persona) return;
+ const p = state.persona;
+ $('brEditTone').value = p.tone || '';
+ $('brEditStyle').value = p.communication_style || 'warm';
+ $('brEditVocab').value = (p.vocabulary || []).join(', ');
+ $('brEditInterests').value = (p.interests || []).join(', ');
+ $('brEditDont').value = (p.dont_say || []).join(', ');
+ $('brEditGreet').value = p.sample_greeting || '';
+ $('brPcBody').style.display = 'none';
+ $('brPcEditBody').style.display = 'flex';
+ $('brEditPersona').style.display = 'none';
+}
+
+function saveEdit() {
+ const split = v => v.split(',').map(s => s.trim()).filter(Boolean);
+ state.persona = {
+ tone: $('brEditTone').value.trim() || 'Neutral',
+ communication_style: $('brEditStyle').value,
+ vocabulary: split($('brEditVocab').value),
+ interests: split($('brEditInterests').value),
+ dont_say: split($('brEditDont').value),
+ sample_greeting: $('brEditGreet').value.trim(),
+ };
+ persistPersona();
+ closeEditMode();
+ renderPersonaCard(state.persona);
+ toast('Persona updated');
+}
+
+function closeEditMode() {
+ $('brPcBody').style.display = '';
+ $('brPcEditBody').style.display = 'none';
+ $('brEditPersona').style.display = '';
+}
+
+// ── Persona: Save to agent ───────────────────────────────────────────────────
+async function loadAgents() {
+ try {
+ const res = await fetch('/api/agents', { credentials: 'include' });
+ if (!res.ok) return;
+ const data = await res.json();
+ state.agents = data.agents || data || [];
+ renderAgentSelect();
+ } catch {}
+}
+
+function renderAgentSelect() {
+ const sel = $('brAgentSelect');
+ sel.innerHTML = '<option value="">Select agent...</option>';
+ for (const agent of state.agents) {
+ const opt = document.createElement('option');
+ opt.value = agent.id;
+ opt.textContent = agent.name || `Agent ${agent.id.slice(0, 8)}`;
+ sel.appendChild(opt);
+ }
+}
+
+async function savePersonaToAgent() {
+ const agentId = $('brAgentSelect').value;
+ if (!agentId || !state.persona) return;
+
+ const btn = $('brSaveToAgent');
+ btn.disabled = true;
+ btn.textContent = 'Saving...';
+
+ try {
+ const persona = {
+ system_prompt: buildPersonaSystemPrompt(state.persona),
+ tone: state.persona.tone,
+ traits: [
+ ...(state.persona.vocabulary || []),
+ ...(state.persona.interests || []),
+ ],
+ };
+ const res = await fetch(`/api/agents/${agentId}`, {
+ method: 'PUT',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ persona }),
+ });
+ if (!res.ok) {
+ const data = await res.json().catch(() => ({}));
+ throw new Error(data.error || `HTTP ${res.status}`);
+ }
+ const agentName = state.agents.find(a => a.id === agentId)?.name || 'agent';
+ toast(`Persona saved to ${agentName}`);
+ } catch (err) {
+ toast(`Save failed: ${err.message}`);
+ } finally {
+ btn.disabled = false;
+ btn.textContent = 'Save to Agent';
+ }
+}
+
+// ── Render: Sidebar sessions ─────────────────────────────────────────────────
+function renderSidebar() {
+ const el = $('brSessions');
+ if (!state.sessions.length) {
+ el.innerHTML = '<div class="br-empty">No sessions yet.<br>Send a message to start.</div>';
+ return;
+ }
+ el.innerHTML = state.sessions.map(s => `
+ <div class="br-sess${s.id === state.currentId ? ' active' : ''}" data-id="${escHtml(s.id)}">
+ <span class="br-sess-name">${escHtml(s.name)}</span>
+ <button class="br-sess-del" data-del="${escHtml(s.id)}" title="Delete">x</button>
+ </div>
+ `).join('');
+}
+
+// ── Render: Playground toolbar ───────────────────────────────────────────────
+function renderPlayControls() {
+ const ctrl = $('brPlayControls');
+ const label = $('brPlayLabel');
+ if (state.playMode === 'compare') {
+ label.textContent = 'Models';
+ ctrl.innerHTML = `<div class="br-provider-pills">${
+ PROVIDERS.map(p => `
+ <label class="br-pill${state.active.has(p.key) ? ' on' : ''}" style="--pc:${p.color}" data-key="${p.key}">
+ <span class="br-pill-dot"></span>
+ <span>${p.short}</span>
+ </label>
+ `).join('')
+ }</div>`;
+ } else {
+ label.textContent = 'Model';
+ ctrl.innerHTML = `<select class="br-focus-sel" id="brFocusSel">${
+ PROVIDERS.map(p => `<option value="${p.key}"${p.key === state.focusKey ? ' selected' : ''}>${p.label}</option>`).join('')
+ }</select>`;
+ }
+ bindPlayControlEvents();
+}
+
+// ── Render: Compare canvas ───────────────────────────────────────────────────
+function renderCompareCanvas() {
+ const canvas = $('brCanvas');
+ const session = currentSession();
+ const active = [...state.active];
+ canvas.innerHTML = `<div class="br-compare">${
+ active.map(key => {
+ const p = PMAP.get(key);
+ if (!p) return '';
+ return `
+ <div class="br-col" data-col="${escHtml(key)}" style="--pc:${p.color}">
+ <div class="br-col-head">
+ <div>
+ <div class="br-col-name">${escHtml(p.short)}</div>
+ <div class="br-col-meta">${escHtml(p.network)} / ${escHtml(p.ctx)} / ${escHtml(p.tier)}</div>
+ </div>
+ <div style="display:flex;gap:6px;align-items:center">
+ <div class="br-col-stats" data-stats="${escHtml(key)}"></div>
+ <button class="br-col-copy" data-copy="${escHtml(key)}">Copy</button>
+ </div>
+ </div>
+ <div class="br-col-msgs" data-msgs="${escHtml(key)}">
+ ${session?.turns.length ? renderColTurns(session, key) : '<div class="br-col-empty">Waiting for a message...</div>'}
+ </div>
+ </div>`;
+ }).join('')
+ }</div>`;
+}
+
+function renderColTurns(session, provKey) {
+ return session.turns.map(turn => {
+ let html = `<div class="br-col-user">${escHtml(turn.user)}</div>`;
+ const resp = turn.responses[provKey];
+ if (resp?.text) html += `<div class="br-col-assistant">${renderMd(resp.text)}</div>`;
+ else if (resp?.error) html += `<div class="br-col-assistant" style="color:#ff8a8a">${escHtml(resp.error)}</div>`;
+ return html;
+ }).join('');
+}
+
+// ── Render: Chat canvas ──────────────────────────────────────────────────────
+function renderChatCanvas() {
+ const canvas = $('brCanvas');
+ const session = currentSession();
+ const p = PMAP.get(state.focusKey);
+
+ if (!session || !session.turns.length) {
+ canvas.innerHTML = `
+ <div class="br-chat">
+ <div class="br-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 at once.</p>
+ </div>
+ </div>`;
+ return;
+ }
+
+ const msgHtml = session.turns.map(turn => {
+ const resp = turn.responses[state.focusKey];
+ let html = `
+ <div class="br-msg user">
+ <div class="br-msg-label">You</div>
+ <div class="br-msg-body">${escHtml(turn.user)}</div>
+ </div>`;
+ if (resp?.text) {
+ html += `
+ <div class="br-msg assistant" style="--pc:${escHtml(p?.color || '#fff')}">
+ <div class="br-msg-label">${escHtml(p?.short || state.focusKey)}</div>
+ <div class="br-msg-body">${renderMd(resp.text)}</div>
+ </div>`;
+ } else if (resp?.error) {
+ html += `
+ <div class="br-msg assistant">
+ <div class="br-msg-label" style="color:#ff8a8a">Error</div>
+ <div class="br-msg-body" style="color:#ff8a8a">${escHtml(resp.error)}</div>
+ </div>`;
+ }
+ return html;
+ }).join('');
+
+ canvas.innerHTML = `
+ <div class="br-chat">
+ <div class="br-chat-msgs" id="brChatMsgs">${msgHtml}</div>
+ </div>`;
+}
+
+function renderCanvas() {
+ if (state.playMode === 'compare') renderCompareCanvas();
+ else renderChatCanvas();
+}
+
+// ── Scroll ───────────────────────────────────────────────────────────────────
+function scrollColToBottom(key) {
+ const el = document.querySelector(`[data-msgs="${key}"]`);
+ if (el) el.scrollTop = el.scrollHeight;
+}
+function scrollChatToBottom() {
+ const el = document.getElementById('brChatMsgs');
+ if (el) el.scrollTop = el.scrollHeight;
+}
+
+// ── Streaming ────────────────────────────────────────────────────────────────
+async function streamProvider(provKey, messages, system, { onChunk, onDone, onError, signal }) {
+ 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: 1024 }),
+ });
+ } 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;
+ }
+
+ 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 { onDone?.({ elapsedMs: JSON.parse(data).elapsedMs, usage: JSON.parse(data).usage }); } catch {}
+ } else if (evType === 'error') {
+ try { onError?.(JSON.parse(data).message || 'upstream error'); } catch {}
+ }
+ }
+ }
+ } finally {
+ onDone?.({ elapsedMs: Math.round(performance.now() - t0), usage: null });
+ }
+}
+
+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;
+}
+
+// ── Send message ─────────────────────────────────────────────────────────────
+async function sendMessage() {
+ const promptEl = $('brPrompt');
+ const text = promptEl.value.trim();
+ if (!text || state.streaming) return;
+
+ const activeKeys = state.playMode === 'compare' ? [...state.active] : [state.focusKey];
+ if (!activeKeys.length) { showNotice('Select at least one model.'); return; }
+
+ const system = getEffectiveSystemPrompt();
+ promptEl.value = '';
+
+ if (!state.currentId) {
+ const s = newSession(system);
+ state.sessions.unshift(s);
+ state.currentId = s.id;
+ }
+
+ const session = currentSession();
+ if (!session) return;
+
+ const turn = { id: uuid(), user: text, responses: {} };
+ session.turns.push(turn);
+ autoName(session);
+ persistSessions();
+ renderSidebar();
+
+ state.streaming = true;
+ $('brSend').disabled = true;
+
+ renderCanvas();
+ if (state.playMode === 'compare') activeKeys.forEach(scrollColToBottom);
+ else scrollChatToBottom();
+
+ // Add streaming indicators
+ if (state.playMode === 'compare') {
+ for (const key of activeKeys) {
+ const el = document.querySelector(`[data-msgs="${key}"]`);
+ if (el) {
+ const spin = document.createElement('div');
+ spin.className = 'br-col-assistant';
+ spin.dataset.stream = key;
+ spin.innerHTML = '<span class="br-spin"></span>';
+ el.appendChild(spin);
+ el.scrollTop = el.scrollHeight;
+ }
+ }
+ } else {
+ const msgs = document.getElementById('brChatMsgs');
+ if (msgs) {
+ const spin = document.createElement('div');
+ spin.className = 'br-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="br-msg-label">${escHtml(p?.short || state.focusKey)}</div><div class="br-msg-body"><span class="br-spin"></span></div>`;
+ msgs.appendChild(spin);
+ msgs.scrollTop = msgs.scrollHeight;
+ }
+ }
+
+ const abortCtrl = new AbortController();
+
+ 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.playMode === 'compare') {
+ const streamEl = document.querySelector(`[data-stream="${key}"]`);
+ if (streamEl) { streamEl.innerHTML = renderMd(accumulated) + '<span class="br-spin"></span>'; scrollColToBottom(key); }
+ } else if (key === state.focusKey) {
+ const streamEl = document.querySelector(`[data-stream-chat="${key}"] .br-msg-body`);
+ if (streamEl) { streamEl.innerHTML = renderMd(accumulated) + '<span class="br-spin"></span>'; scrollChatToBottom(); }
+ }
+ },
+ onDone({ elapsedMs, usage }) {
+ turn.responses[key] = turn.responses[key] || {};
+ turn.responses[key].elapsedMs = elapsedMs;
+ turn.responses[key].usage = usage;
+
+ if (state.playMode === 'compare') {
+ const streamEl = document.querySelector(`[data-stream="${key}"]`);
+ if (streamEl) { streamEl.removeAttribute('data-stream'); streamEl.innerHTML = renderMd(turn.responses[key].text || ''); }
+ 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('.br-msg-body');
+ if (body) body.innerHTML = renderMd(turn.responses[key].text || '');
+ }
+ }
+ persistSessions();
+ },
+ onError(msg) {
+ turn.responses[key] = { text: '', error: msg, elapsedMs: 0 };
+ if (state.playMode === '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('.br-msg-body');
+ if (body) { body.style.color = '#ff8a8a'; body.textContent = msg; }
+ }
+ }
+ persistSessions();
+ },
+ });
+ }));
+
+ state.streaming = false;
+ $('brSend').disabled = false;
+}
+
+// ── Export ────────────────────────────────────────────────────────────────────
+function exportSession() {
+ const session = currentSession();
+ if (!session?.turns.length) { showNotice('Nothing to export yet.'); return; }
+
+ const lines = [`# ${session.name}\n`];
+ const provKeys = state.playMode === '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');
+ }
+
+ if (state.persona) {
+ lines.push('\n## Persona\n```json\n' + JSON.stringify(state.persona, null, 2) + '\n```\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);
+}
+
+// ── Copy provider ────────────────────────────────────────────────────────────
+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(() => toast('Copied'));
+}
+
+// ── Session management ───────────────────────────────────────────────────────
+function loadSession(id) {
+ state.currentId = id;
+ const s = state.sessions.find(x => x.id === id);
+ if (s?.system) $('brSystem').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();
+}
+
+function setPlayMode(m) {
+ state.playMode = m;
+ document.querySelectorAll('.br-mode-btn').forEach(b => b.classList.toggle('active', b.dataset.mode === m));
+ renderPlayControls();
+ renderCanvas();
+}
+
+// ── Bind playground control events ───────────────────────────────────────────
+function bindPlayControlEvents() {
+ if (state.playMode === 'compare') {
+ document.querySelectorAll('.br-pill').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();
+ });
+ });
+ } else {
+ const sel = document.getElementById('brFocusSel');
+ if (sel) sel.addEventListener('change', () => { state.focusKey = sel.value; renderCanvas(); });
+ }
+}
+
+// ── Method tabs ──────────────────────────────────────────────────────────────
+function setMethod(method) {
+ state.method = method;
+ document.querySelectorAll('.br-method-tab').forEach(t => t.classList.toggle('active', t.dataset.method === method));
+ $('brInterview').classList.toggle('active', method === 'interview');
+ $('brFreeform').classList.toggle('active', method === 'freeform');
+ $('brManual').classList.toggle('active', method === 'manual');
+}
+
+// ── Bind all events ──────────────────────────────────────────────────────────
+function bindEvents() {
+ // Tab switching
+ document.querySelectorAll('.br-tab').forEach(t => {
+ t.addEventListener('click', () => setTab(t.dataset.tab));
+ });
+
+ // Method tabs
+ document.querySelectorAll('.br-method-tab').forEach(t => {
+ t.addEventListener('click', () => setMethod(t.dataset.method));
+ });
+
+ // Interview
+ $('brSynthesize').addEventListener('click', synthesizeFromInterview);
+ $('brFillExample').addEventListener('click', () => {
+ EXAMPLES.forEach((v, i) => { const el = $(`brQ${i}`); if (el) el.value = v; });
+ updateSynthButton();
+ });
+
+ // Freeform
+ $('brFreeformText').addEventListener('input', () => {
+ $('brFreeformSynth').disabled = !$('brFreeformText').value.trim();
+ });
+ $('brFreeformSynth').addEventListener('click', synthesizeFromFreeform);
+
+ // Manual
+ $('brManualSave').addEventListener('click', setPersonaFromManual);
+
+ // Persona card actions
+ $('brEditPersona').addEventListener('click', openEditMode);
+ $('brSaveEdit').addEventListener('click', saveEdit);
+ $('brCancelEdit').addEventListener('click', closeEditMode);
+ $('brToggleRaw').addEventListener('click', () => {
+ const raw = $('brRawJson');
+ raw.classList.toggle('show');
+ $('brToggleRaw').textContent = raw.classList.contains('show') ? 'Hide JSON' : 'JSON';
+ });
+ $('brCopyJson').addEventListener('click', () => {
+ if (state.persona) {
+ navigator.clipboard.writeText(JSON.stringify(state.persona, null, 2)).then(() => toast('Copied to clipboard'));
+ }
+ });
+ $('brTestInPlayground').addEventListener('click', () => {
+ if (state.persona) {
+ $('brSystem').value = buildPersonaSystemPrompt(state.persona);
+ }
+ setTab('playground');
+ });
+ $('brResetPersona').addEventListener('click', () => {
+ state.persona = null;
+ persistPersona();
+ $('brPersonaCard').classList.remove('show');
+ updatePersonaMini();
+ updatePersonaBanner();
+ toast('Persona cleared');
+ });
+
+ // Save to agent
+ $('brAgentSelect').addEventListener('change', () => {
+ $('brSaveToAgent').disabled = !$('brAgentSelect').value;
+ });
+ $('brSaveToAgent').addEventListener('click', savePersonaToAgent);
+
+ // Sidebar: build persona shortcut
+ $('brBuildPersonaBtn').addEventListener('click', () => setTab('persona'));
+ $('brMiniClear').addEventListener('click', () => {
+ state.persona = null;
+ persistPersona();
+ updatePersonaMini();
+ updatePersonaBanner();
+ toast('Persona cleared');
+ });
+
+ // Playground mode toggle
+ document.querySelectorAll('.br-mode-btn').forEach(b => {
+ b.addEventListener('click', () => setPlayMode(b.dataset.mode));
+ });
+
+ // Send
+ $('brSend').addEventListener('click', sendMessage);
+ $('brPrompt').addEventListener('keydown', e => {
+ if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) { e.preventDefault(); sendMessage(); }
+ });
+
+ // New chat
+ $('brNewChat').addEventListener('click', () => {
+ const s = newSession($('brSystem').value.trim());
+ state.sessions.unshift(s);
+ state.currentId = s.id;
+ persistSessions();
+ renderSidebar();
+ renderCanvas();
+ });
+
+ // Export
+ $('brExport').addEventListener('click', exportSession);
+
+ // Session list (delegated)
+ $('brSessions').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)
+ $('brCanvas').addEventListener('click', e => {
+ const copy = e.target.closest('[data-copy]');
+ if (copy) copyProvider(copy.dataset.copy);
+ });
+
+ // Persona banner
+ $('brBannerDismiss').addEventListener('click', () => {
+ state.personaEnabled = false;
+ updatePersonaBanner();
+ });
+}
+
+// ── Boot ─────────────────────────────────────────────────────────────────────
+loadSessions();
+loadPersona();
+
+renderQuestions();
+renderPlayControls();
+renderSidebar();
+renderCanvas();
+bindEvents();
+
+if (state.persona) {
+ renderPersonaCard(state.persona);
+}
+updatePersonaMini();
+updatePersonaBanner();
+
+const activeSess = currentSession();
+if (activeSess?.system) $('brSystem').value = activeSess.system;
+
+loadAgents();
diff --git a/src/dashboard-next/pages/home.js b/src/dashboard-next/pages/home.js
index 3543f19f1..649e89de9 100644
--- a/src/dashboard-next/pages/home.js
+++ b/src/dashboard-next/pages/home.js
@@ -496,6 +496,7 @@ function renderQuickActions(host, { avatars = [], agents = [] } = {}) {
actions.push(
{ href: '/dashboard/widgets', title: 'Embed an agent', sub: 'Drop-in widget for any site', icon: '◧' },
{ href: '/dashboard/api', title: 'Open API keys', sub: 'REST + MCP for your agents', icon: '⌘' },
+ { href: '/brain', title: 'Brain — multi-LLM chat', sub: 'Compare Claude, GPT, Llama side-by-side', icon: '◎' },
);
host.innerHTML = actions.map((a) => `
diff --git a/src/selfie-capture.js b/src/selfie-capture.js
index 1a4a36689..b0f163532 100644
--- a/src/selfie-capture.js
+++ b/src/selfie-capture.js
@@ -8,8 +8,13 @@
* On submit, dispatches a `selfie:submit` CustomEvent on document with
* detail = { files: { frontal, left?, right? }, bodyType, avatarType, method }
* which the selfie pipeline picks up to drive avatar reconstruction.
+ *
+ * Camera overlay uses the face-quality engine for real-time 468-point wireframe,
+ * head-pose estimation, blur/lighting/centering quality gates.
*/
+import { createQualitySession, preload, SLOT_PRESETS } from './face-quality.js';
+
const REQUIRED_SLOT = 'frontal';
const OPTIONAL_SLOTS = /** @type {const} */ (['left', 'right']);
const ALL_SLOTS = /** @type {const} */ ([REQUIRED_SLOT, ...OPTIONAL_SLOTS]);
@@ -351,8 +356,7 @@ const cam = {
slot: /** @type {string | null} */ (null),
pendingFile: /** @type {File | null} */ (null),
pendingUrl: /** @type {string | null} */ (null),
- detector: /** @type {any} */ (null),
- detectInterval: /** @type {number | null} */ (null),
+ qualitySession: /** @type {any} */ (null),
faceLocked: false,
countdownTimers: /** @type {number[]} */ ([]),
};
@@ -395,87 +399,118 @@ async function openCamera(slot) {
return;
}
- // Best-effort face tracking. FaceDetector is non-standard but ships in
- // Chromium on Android/desktop; on Safari/Firefox we fall back to always-
- // enabled shutter and a softer hint.
- if (slot === REQUIRED_SLOT) {
- startFaceDetect();
- }
+ startFaceQuality(slot);
}
-function startFaceDetect() {
- const FD = /** @type {any} */ (window).FaceDetector;
- if (typeof FD !== 'function') {
- // No detector available — let the user shoot freely; keep the dashed oval
- // as a framing guide.
+async function startFaceQuality(slot) {
+ const meshOverlay = document.getElementById('cam-mesh-overlay');
+ const badges = document.getElementById('cam-badges');
+ if (!camVideo || !meshOverlay) {
setShutterEnabled(true);
return;
}
+
+ preload();
+
+ await new Promise((res) => {
+ if (camVideo.readyState >= 2) return res();
+ camVideo.addEventListener('loadeddata', res, { once: true });
+ });
+
try {
- cam.detector = new FD({ fastMode: true, maxDetectedFaces: 1 });
+ const slotKey = slot === REQUIRED_SLOT ? 'frontal' : slot;
+ cam.qualitySession = await createQualitySession(camVideo, meshOverlay, {
+ slot: slotKey,
+ onUpdate: (report) => {
+ renderQualityBadges(badges, report, slotKey);
+ updateCameraHints(report, slotKey);
+ },
+ });
+ cam.qualitySession.start();
+ camOval?.setAttribute('hidden', '');
} catch (err) {
- console.warn('[selfie] FaceDetector init failed:', err);
+ console.warn('[selfie] face-quality init failed, falling back:', err);
setShutterEnabled(true);
- return;
}
- cam.detectInterval = window.setInterval(runDetect, 250);
}
-async function runDetect() {
- if (!cam.detector || !camVideo || !cam.stream) return;
- if (camVideo.readyState < 2) return;
- let faces;
- try {
- faces = await cam.detector.detect(camVideo);
- } catch (_) {
- // Detector failed mid-stream — degrade gracefully, never block the user.
- stopFaceDetect();
- setShutterEnabled(true);
+function renderQualityBadges(container, report, slot) {
+ if (!container) return;
+
+ if (!report.faceFound) {
+ container.innerHTML = '<span class="cam-badge-chip bad">No face</span>';
return;
}
- const got = Array.isArray(faces) && faces.length > 0;
- if (got) {
- const face = faces[0];
- const bb = face.boundingBox;
- const vw = camVideo.videoWidth || 1;
- const vh = camVideo.videoHeight || 1;
- const cx = (bb.x + bb.width / 2) / vw;
- const cy = (bb.y + bb.height / 2) / vh;
- const sz = Math.max(bb.width / vw, bb.height / vh);
- const centered = Math.abs(cx - 0.5) < 0.18 && Math.abs(cy - 0.5) < 0.22;
- const sized = sz > 0.32 && sz < 0.85;
- const ok = centered && sized;
- setShutterEnabled(true);
- camOval?.classList.toggle('detected', ok);
- if (camHint) {
- if (ok) {
- camHint.textContent = 'Looks good — tap the shutter';
- camHint.classList.add('ok');
- cam.faceLocked = true;
- } else if (!sized) {
- camHint.textContent = sz <= 0.32 ? 'Move closer' : 'Move back';
- camHint.classList.remove('ok');
- } else {
- camHint.textContent = 'Center your face in the oval';
- camHint.classList.remove('ok');
- }
- }
- } else {
+
+ const slotCfg = SLOT_PRESETS[slot] || SLOT_PRESETS.frontal;
+ const chips = [
+ { text: 'Face', ok: true },
+ { text: `Yaw ${Math.round(report.yaw)}°`, ok: report.yawOk },
+ { text: report.centered ? 'Centered' : 'Recenter', ok: report.centered },
+ { text: report.blurOk ? 'Sharp' : 'Blurry', ok: report.blurOk },
+ ];
+
+ const lumaLabel = report.luma < 40 ? 'Too dark' : report.luma > 218 ? 'Bright' : 'Lit';
+ chips.push({ text: lumaLabel, ok: report.lumaOk });
+
+ container.innerHTML = chips.map((c) =>
+ `<span class="cam-badge-chip ${c.ok ? 'ok' : 'bad'}">${c.text}</span>`
+ ).join('');
+}
+
+function updateCameraHints(report, slot) {
+ if (!report.faceFound) {
setShutterEnabled(false);
camOval?.classList.remove('detected');
if (camHint) {
camHint.textContent = 'No face detected — face the camera';
camHint.classList.remove('ok');
}
+ return;
+ }
+
+ const allPass = report.allPass;
+ setShutterEnabled(true);
+ camOval?.classList.toggle('detected', allPass);
+
+ if (camHint) {
+ if (allPass) {
+ camHint.textContent = 'Looks good — tap the shutter';
+ camHint.classList.add('ok');
+ cam.faceLocked = true;
+ } else if (!report.yawOk) {
+ camHint.textContent = slot === 'frontal'
+ ? 'Face the camera straight on'
+ : `Turn your head ${slot} (~45°)`;
+ camHint.classList.remove('ok');
+ } else if (!report.centered) {
+ camHint.textContent = 'Center your face in the oval';
+ camHint.classList.remove('ok');
+ } else if (!report.blurOk) {
+ camHint.textContent = 'Hold steady — image is blurry';
+ camHint.classList.remove('ok');
+ } else if (!report.lumaOk) {
+ camHint.textContent = report.luma < 40 ? 'Too dark — find better light' : 'Too bright — reduce glare';
+ camHint.classList.remove('ok');
+ } else {
+ camHint.textContent = 'Almost there...';
+ camHint.classList.remove('ok');
+ }
}
}
-function stopFaceDetect() {
- if (cam.detectInterval != null) {
- clearInterval(cam.detectInterval);
- cam.detectInterval = null;
+function stopFaceQuality() {
+ if (cam.qualitySession) {
+ cam.qualitySession.stop();
+ cam.qualitySession = null;
+ }
+ const meshOverlay = document.getElementById('cam-mesh-overlay');
+ if (meshOverlay) {
+ const ctx = meshOverlay.getContext('2d');
+ if (ctx) ctx.clearRect(0, 0, meshOverlay.width, meshOverlay.height);
}
- cam.detector = null;
+ const badges = document.getElementById('cam-badges');
+ if (badges) badges.innerHTML = '';
}
/** @param {boolean} on */
@@ -486,7 +521,7 @@ function setShutterEnabled(on) {
}
function closeCamera() {
- stopFaceDetect();
+ stopFaceQuality();
cancelCountdown();
if (cam.stream) {
cam.stream.getTracks().forEach((t) => t.stop());
@@ -538,7 +573,7 @@ camOverlay?.addEventListener('click', (e) => {
else if (action === 'retake') {
clearPending();
setCamMode('live');
- if (cam.slot === REQUIRED_SLOT) startFaceDetect();
+ startFaceQuality(cam.slot || REQUIRED_SLOT);
} else if (action === 'use') confirmCamShot();
});
@@ -591,7 +626,7 @@ async function shoot() {
// should match what the camera actually sees.
ctx.drawImage(camVideo, 0, 0, w, h);
- stopFaceDetect();
+ stopFaceQuality();
const blob = await new Promise((res) => canvas.toBlob(res, 'image/jpeg', 0.92));
if (!blob) {
diff --git a/src/selfie-modal.js b/src/selfie-modal.js
new file mode 100644
index 000000000..2a5a25a6a
--- /dev/null
+++ b/src/selfie-modal.js
@@ -0,0 +1,905 @@
+/**
+ * Selfie Modal — reusable full-screen selfie capture component.
+ *
+ * Drop this into any page to let users create or update an avatar from a
+ * selfie. Uses the face-quality engine for real-time 468-point wireframe,
+ * head-pose estimation, blur/lighting/centering quality gates.
+ *
+ * Usage:
+ * import { openSelfieModal } from '/src/selfie-modal.js';
+ * const result = await openSelfieModal();
+ * if (result) console.log('Avatar ID:', result.avatarId);
+ *
+ * Options:
+ * existingAvatarId — if set, updates this avatar instead of creating new
+ * bodyType — 'male' | 'female' (default 'male')
+ * avatarType — 'v1' | 'v2' (default 'v1')
+ * slot — 'frontal' | 'left' | 'right' (default 'frontal')
+ */
+
+import { createQualitySession, preload, SLOT_PRESETS } from './face-quality.js';
+
+const RECONSTRUCT_ENDPOINT = '/api/avatars/reconstruct';
+const STATUS_ENDPOINT = '/api/avatars/regenerate-status';
+const MAX_DIM = 1024;
+const JPEG_QUALITY = 0.88;
+
+let _activeModal = null;
+
+/**
+ * Open a selfie capture modal.
+ * @param {{
+ * existingAvatarId?: string,
+ * bodyType?: 'male' | 'female',
+ * avatarType?: 'v1' | 'v2',
+ * multiAngle?: boolean,
+ * }} [opts]
+ * @returns {Promise<{ avatarId: string } | null>}
+ */
+export async function openSelfieModal(opts = {}) {
+ if (_activeModal) return null;
+ preload();
+
+ return new Promise((resolve) => {
+ const modal = new SelfieModal({
+ ...opts,
+ onDone: (result) => {
+ modal.destroy();
+ _activeModal = null;
+ resolve(result);
+ },
+ onCancel: () => {
+ modal.destroy();
+ _activeModal = null;
+ resolve(null);
+ },
+ });
+ _activeModal = modal;
+ modal.mount();
+ });
+}
+
+class SelfieModal {
+ constructor(opts) {
+ this.opts = opts;
+ this.bodyType = opts.bodyType || 'male';
+ this.avatarType = opts.avatarType || 'v1';
+ this.multiAngle = opts.multiAngle !== false;
+ this.existingAvatarId = opts.existingAvatarId || null;
+ this.photos = { frontal: null, left: null, right: null };
+ this.currentSlot = 'frontal';
+ this.phase = 'capture';
+ this.stream = null;
+ this.session = null;
+ this.root = null;
+ }
+
+ mount() {
+ this.root = document.createElement('div');
+ this.root.className = 'sfm-root';
+ this.root.innerHTML = this._html();
+ document.body.appendChild(this.root);
+ this._injectStyles();
+ requestAnimationFrame(() => this.root.classList.add('sfm-open'));
+ this._wire();
+ this._startCamera();
+ }
+
+ destroy() {
+ this._stopCamera();
+ if (this.root) {
+ this.root.classList.remove('sfm-open');
+ setTimeout(() => this.root?.remove(), 200);
+ }
+ }
+
+ _html() {
+ return `
+ <div class="sfm-backdrop"></div>
+ <div class="sfm-panel">
+ <div class="sfm-header">
+ <button type="button" class="sfm-close" data-sfm-close aria-label="Close">
+ <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
+ </button>
+ <div class="sfm-title" data-sfm-title>Take a selfie</div>
+ <div class="sfm-slot-label" data-sfm-slot-label>Front-facing</div>
+ </div>
+ <div class="sfm-stage" data-sfm-stage>
+ <video class="sfm-video" data-sfm-video autoplay playsinline muted></video>
+ <canvas class="sfm-canvas" data-sfm-canvas></canvas>
+ <img class="sfm-preview-img" data-sfm-preview hidden />
+ <div class="sfm-badges" data-sfm-badges></div>
+ <div class="sfm-hint" data-sfm-hint>Loading face mesh...</div>
+ </div>
+ <div class="sfm-captures" data-sfm-captures>
+ <div class="sfm-thumb sfm-thumb-active" data-sfm-thumb="frontal">
+ <span class="sfm-thumb-label">Front</span>
+ </div>
+ ${this.multiAngle ? `
+ <div class="sfm-thumb" data-sfm-thumb="left">
+ <span class="sfm-thumb-label">Left</span>
+ </div>
+ <div class="sfm-thumb" data-sfm-thumb="right">
+ <span class="sfm-thumb-label">Right</span>
+ </div>
+ ` : ''}
+ </div>
+ <div class="sfm-bar" data-sfm-bar>
+ <div class="sfm-bar-live" data-sfm-bar-live>
+ <button type="button" class="sfm-btn sfm-btn-ghost" data-sfm-cancel>Cancel</button>
+ <button type="button" class="sfm-shutter" data-sfm-shutter disabled aria-label="Capture">
+ <span class="sfm-shutter-ring"></span>
+ </button>
+ <button type="button" class="sfm-btn sfm-btn-ghost" data-sfm-upload-alt>Upload</button>
+ </div>
+ <div class="sfm-bar-review" data-sfm-bar-review hidden>
+ <button type="button" class="sfm-btn sfm-btn-ghost" data-sfm-retake>Retake</button>
+ <button type="button" class="sfm-btn sfm-btn-primary" data-sfm-accept>Use this</button>
+ </div>
+ <div class="sfm-bar-submit" data-sfm-bar-submit hidden>
+ <div class="sfm-opts">
+ <div class="sfm-opt-group">
+ <span class="sfm-opt-label">Body</span>
+ <div class="sfm-toggle" data-sfm-body-toggle>
+ <button type="button" class="sfm-toggle-btn ${this.bodyType === 'male' ? 'active' : ''}" data-sfm-body="male">Masc</button>
+ <button type="button" class="sfm-toggle-btn ${this.bodyType === 'female' ? 'active' : ''}" data-sfm-body="female">Femme</button>
+ </div>
+ </div>
+ <div class="sfm-opt-group">
+ <span class="sfm-opt-label">Style</span>
+ <div class="sfm-toggle" data-sfm-style-toggle>
+ <button type="button" class="sfm-toggle-btn ${this.avatarType === 'v1' ? 'active' : ''}" data-sfm-style="v1">Photoreal</button>
+ <button type="button" class="sfm-toggle-btn ${this.avatarType === 'v2' ? 'active' : ''}" data-sfm-style="v2">Stylized</button>
+ </div>
+ </div>
+ </div>
+ <button type="button" class="sfm-btn sfm-btn-primary sfm-btn-full" data-sfm-submit>
+ Build my avatar
+ </button>
+ </div>
+ <div class="sfm-bar-building" data-sfm-bar-building hidden>
+ <div class="sfm-build-spinner"></div>
+ <div class="sfm-build-label" data-sfm-build-label>Submitting...</div>
+ </div>
+ </div>
+ <input type="file" data-sfm-file-input accept="image/jpeg,image/png,image/webp" hidden />
+ </div>
+ `;
+ }
+
+ _wire() {
+ const $ = (sel) => this.root.querySelector(sel);
+ const $$ = (sel) => this.root.querySelectorAll(sel);
+
+ $('[data-sfm-close]').addEventListener('click', () => this.opts.onCancel());
+ $('.sfm-backdrop').addEventListener('click', () => this.opts.onCancel());
+ $('[data-sfm-cancel]').addEventListener('click', () => this.opts.onCancel());
+
+ $('[data-sfm-shutter]').addEventListener('click', () => this._capture());
+ $('[data-sfm-retake]').addEventListener('click', () => this._retake());
+ $('[data-sfm-accept]').addEventListener('click', () => this._acceptPhoto());
+ $('[data-sfm-submit]').addEventListener('click', () => this._submit());
+
+ $('[data-sfm-upload-alt]').addEventListener('click', () => {
+ $('[data-sfm-file-input]').click();
+ });
+ $('[data-sfm-file-input]').addEventListener('change', (e) => {
+ const file = e.target.files?.[0];
+ if (file) this._handleUpload(file);
+ e.target.value = '';
+ });
+
+ $$('[data-sfm-thumb]').forEach((thumb) => {
+ thumb.addEventListener('click', () => {
+ const slot = thumb.dataset.sfmThumb;
+ if (this.phase === 'submit') {
+ this._switchToSlot(slot);
+ }
+ });
+ });
+
+ $$('[data-sfm-body]').forEach((btn) => {
+ btn.addEventListener('click', () => {
+ this.bodyType = btn.dataset.sfmBody;
+ $$('[data-sfm-body]').forEach((b) => b.classList.toggle('active', b === btn));
+ });
+ });
+ $$('[data-sfm-style]').forEach((btn) => {
+ btn.addEventListener('click', () => {
+ this.avatarType = btn.dataset.sfmStyle;
+ $$('[data-sfm-style]').forEach((b) => b.classList.toggle('active', b === btn));
+ });
+ });
+
+ document.addEventListener('keydown', this._onKey = (e) => {
+ if (e.key === 'Escape') this.opts.onCancel();
+ });
+ }
+
+ async _startCamera() {
+ const video = this.root.querySelector('[data-sfm-video]');
+ const canvas = this.root.querySelector('[data-sfm-canvas]');
+ const hint = this.root.querySelector('[data-sfm-hint]');
+
+ try {
+ this.stream = await navigator.mediaDevices.getUserMedia({
+ video: { facingMode: 'user', width: { ideal: 1280 }, height: { ideal: 1706 } },
+ audio: false,
+ });
+ video.srcObject = this.stream;
+ await new Promise((res) => video.addEventListener('loadedmetadata', res, { once: true }));
+ await video.play();
+ } catch (err) {
+ hint.textContent = 'Camera unavailable. Use Upload instead.';
+ hint.classList.add('sfm-hint-err');
+ return;
+ }
+
+ try {
+ this.session = await createQualitySession(video, canvas, {
+ slot: this.currentSlot,
+ onUpdate: (report) => this._onQualityUpdate(report),
+ });
+ this.session.start();
+ hint.textContent = 'Center your face';
+ } catch (err) {
+ hint.textContent = 'Face mesh loading...';
+ const shutter = this.root.querySelector('[data-sfm-shutter]');
+ if (shutter) shutter.disabled = false;
+ }
+ }
+
+ _stopCamera() {
+ if (this.session) {
+ this.session.stop();
+ this.session = null;
+ }
+ if (this.stream) {
+ this.stream.getTracks().forEach((t) => t.stop());
+ this.stream = null;
+ }
+ if (this._onKey) {
+ document.removeEventListener('keydown', this._onKey);
+ this._onKey = null;
+ }
+ }
+
+ _onQualityUpdate(report) {
+ const badges = this.root.querySelector('[data-sfm-badges]');
+ const hint = this.root.querySelector('[data-sfm-hint]');
+ const shutter = this.root.querySelector('[data-sfm-shutter]');
+ if (!badges || !hint || !shutter) return;
+
+ const slotCfg = SLOT_PRESETS[this.currentSlot] || SLOT_PRESETS.frontal;
+ const chips = [];
+
+ if (!report.faceFound) {
+ chips.push({ text: 'No face', ok: false });
+ badges.innerHTML = chips.map((c) => `<span class="sfm-chip ${c.ok ? 'sfm-chip-ok' : 'sfm-chip-bad'}">${c.text}</span>`).join('');
+ hint.textContent = 'Face the camera';
+ hint.className = 'sfm-hint';
+ shutter.disabled = true;
+ return;
+ }
+
+ chips.push({ text: 'Face', ok: true });
+ chips.push({ text: `Yaw ${Math.round(report.yaw)}°`, ok: report.yawOk });
+ chips.push({ text: report.centered ? 'Centered' : 'Recenter', ok: report.centered });
+ chips.push({ text: report.blurOk ? 'Sharp' : 'Blurry', ok: report.blurOk });
+
+ const lumaLabel = report.luma < 40 ? 'Too dark' : report.luma > 218 ? 'Bright' : 'Lit';
+ chips.push({ text: lumaLabel, ok: report.lumaOk });
+
+ badges.innerHTML = chips.map((c) =>
+ `<span class="sfm-chip ${c.ok ? 'sfm-chip-ok' : 'sfm-chip-bad'}">${c.text}</span>`
+ ).join('');
+
+ shutter.disabled = !report.allPass;
+
+ if (report.allPass) {
+ hint.textContent = 'Looking good — tap to capture';
+ hint.className = 'sfm-hint sfm-hint-ok';
+ } else if (!report.yawOk) {
+ const target = slotCfg.label;
+ hint.textContent = this.currentSlot === 'frontal'
+ ? 'Face the camera straight on'
+ : `Turn your head ${this.currentSlot} (~45°)`;
+ hint.className = 'sfm-hint';
+ } else if (!report.centered) {
+ hint.textContent = 'Center your face';
+ hint.className = 'sfm-hint';
+ } else if (!report.blurOk) {
+ hint.textContent = 'Hold steady — image is blurry';
+ hint.className = 'sfm-hint';
+ } else {
+ hint.textContent = 'Adjust lighting';
+ hint.className = 'sfm-hint';
+ }
+ }
+
+ async _capture() {
+ const video = this.root.querySelector('[data-sfm-video]');
+ if (!video) return;
+ const w = video.videoWidth;
+ const h = video.videoHeight;
+ if (!w || !h) return;
+
+ if (this.session) this.session.stop();
+
+ const c = document.createElement('canvas');
+ c.width = w; c.height = h;
+ const ctx = c.getContext('2d');
+ ctx.drawImage(video, 0, 0, w, h);
+
+ const blob = await new Promise((res) => c.toBlob(res, 'image/jpeg', 0.92));
+ if (!blob) return;
+
+ this._pendingBlob = blob;
+ this._showReview(blob);
+ }
+
+ _showReview(blob) {
+ const preview = this.root.querySelector('[data-sfm-preview]');
+ const video = this.root.querySelector('[data-sfm-video]');
+ const canvas = this.root.querySelector('[data-sfm-canvas]');
+ const badges = this.root.querySelector('[data-sfm-badges]');
+ const hint = this.root.querySelector('[data-sfm-hint]');
+
+ const url = URL.createObjectURL(blob);
+ preview.src = url;
+ preview.onload = () => URL.revokeObjectURL(url);
+ preview.hidden = false;
+ video.style.display = 'none';
+ canvas.style.display = 'none';
+ badges.innerHTML = '<span class="sfm-chip sfm-chip-ok">Captured</span>';
+ hint.textContent = '';
+
+ this._setBarMode('review');
+ }
+
+ _retake() {
+ this._pendingBlob = null;
+ const preview = this.root.querySelector('[data-sfm-preview]');
+ const video = this.root.querySelector('[data-sfm-video]');
+ const canvas = this.root.querySelector('[data-sfm-canvas]');
+
+ preview.hidden = true;
+ video.style.display = '';
+ canvas.style.display = '';
+
+ if (this.session) this.session.start();
+ this._setBarMode('live');
+ }
+
+ _acceptPhoto() {
+ if (!this._pendingBlob) return;
+ this.photos[this.currentSlot] = this._pendingBlob;
+ this._pendingBlob = null;
+ this._updateThumbs();
+
+ if (this.multiAngle && !this.photos.left && this.currentSlot === 'frontal') {
+ this._switchToSlot('left');
+ return;
+ }
+ if (this.multiAngle && !this.photos.right && this.currentSlot === 'left') {
+ this._switchToSlot('right');
+ return;
+ }
+
+ this._showSubmitPhase();
+ }
+
+ _switchToSlot(slot) {
+ this.currentSlot = slot;
+ if (this.session) this.session.setSlot(slot);
+
+ const slotLabel = this.root.querySelector('[data-sfm-slot-label]');
+ const slotCfg = SLOT_PRESETS[slot] || SLOT_PRESETS.frontal;
+ if (slotLabel) slotLabel.textContent = slotCfg.label;
+
+ this.root.querySelectorAll('[data-sfm-thumb]').forEach((t) => {
+ t.classList.toggle('sfm-thumb-active', t.dataset.sfmThumb === slot);
+ });
+
+ if (this.photos[slot]) {
+ this._pendingBlob = this.photos[slot];
+ this._showReview(this.photos[slot]);
+ } else {
+ this._pendingBlob = null;
+ const preview = this.root.querySelector('[data-sfm-preview]');
+ const video = this.root.querySelector('[data-sfm-video]');
+ const canvas = this.root.querySelector('[data-sfm-canvas]');
+ preview.hidden = true;
+ video.style.display = '';
+ canvas.style.display = '';
+ if (this.session) this.session.start();
+ this._setBarMode('live');
+ }
+ }
+
+ _showSubmitPhase() {
+ this.phase = 'submit';
+ const preview = this.root.querySelector('[data-sfm-preview]');
+ const video = this.root.querySelector('[data-sfm-video]');
+ const canvas = this.root.querySelector('[data-sfm-canvas]');
+ const hint = this.root.querySelector('[data-sfm-hint]');
+ const badges = this.root.querySelector('[data-sfm-badges]');
+
+ if (this.photos.frontal) {
+ const url = URL.createObjectURL(this.photos.frontal);
+ preview.src = url;
+ preview.onload = () => URL.revokeObjectURL(url);
+ preview.hidden = false;
+ }
+ video.style.display = 'none';
+ canvas.style.display = 'none';
+ if (this.session) this.session.stop();
+
+ const count = [this.photos.frontal, this.photos.left, this.photos.right].filter(Boolean).length;
+ badges.innerHTML = `<span class="sfm-chip sfm-chip-ok">${count} photo${count > 1 ? 's' : ''} ready</span>`;
+ hint.textContent = '';
+
+ const title = this.root.querySelector('[data-sfm-title]');
+ if (title) title.textContent = 'Build your avatar';
+
+ this._setBarMode('submit');
+ }
+
+ _updateThumbs() {
+ this.root.querySelectorAll('[data-sfm-thumb]').forEach((thumb) => {
+ const slot = thumb.dataset.sfmThumb;
+ const photo = this.photos[slot];
+ const existing = thumb.querySelector('.sfm-thumb-img');
+ if (photo && !existing) {
+ const img = document.createElement('img');
+ img.className = 'sfm-thumb-img';
+ const url = URL.createObjectURL(photo);
+ img.src = url;
+ img.onload = () => URL.revokeObjectURL(url);
+ thumb.insertBefore(img, thumb.firstChild);
+ thumb.classList.add('sfm-thumb-filled');
+ } else if (!photo && existing) {
+ existing.remove();
+ thumb.classList.remove('sfm-thumb-filled');
+ }
+ });
+ }
+
+ async _handleUpload(file) {
+ if (!/^image\/(jpeg|png|webp)$/i.test(file.type)) return;
+ const blob = file.slice(0, file.size, file.type);
+ this._pendingBlob = blob;
+ this._showReview(blob);
+ }
+
+ _setBarMode(mode) {
+ const modes = ['live', 'review', 'submit', 'building'];
+ modes.forEach((m) => {
+ const el = this.root.querySelector(`[data-sfm-bar-${m}]`);
+ if (el) el.hidden = m !== mode;
+ });
+ }
+
+ async _submit() {
+ if (!this.photos.frontal) return;
+ const submitBtn = this.root.querySelector('[data-sfm-submit]');
+ if (submitBtn) {
+ submitBtn.disabled = true;
+ submitBtn.textContent = 'Preparing...';
+ }
+ this._setBarMode('building');
+
+ try {
+ const photos = [];
+ for (const slot of ['frontal', 'left', 'right']) {
+ if (!this.photos[slot]) continue;
+ const dataUrl = await blobToDataUrl(this.photos[slot]);
+ photos.push(dataUrl);
+ }
+
+ this._setBuildLabel('Submitting to avatar engine...');
+ const res = await fetch(RECONSTRUCT_ENDPOINT, {
+ method: 'POST',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({
+ name: `Selfie ${new Date().toISOString().slice(0, 10)}`,
+ photos,
+ visibility: 'private',
+ params: { bodyType: this.bodyType, style: this.avatarType },
+ ...(this.existingAvatarId ? { replaceAvatarId: this.existingAvatarId } : {}),
+ }),
+ });
+
+ if (res.status === 401) {
+ this._setBuildLabel('Sign in required');
+ const next = encodeURIComponent(location.pathname + location.search);
+ window.location.assign(`/login?next=${next}`);
+ return;
+ }
+
+ if (!res.ok) {
+ const payload = await res.json().catch(() => ({}));
+ throw new Error(payload.error_description || payload.error || `HTTP ${res.status}`);
+ }
+
+ const data = await res.json();
+ if (!data.jobId) throw new Error('No job ID returned');
+
+ this._setBuildLabel('Generating 3D mesh...');
+ const avatarId = await this._pollJob(data.jobId);
+ this.opts.onDone({ avatarId });
+ } catch (err) {
+ this._setBuildLabel(err.message || 'Failed. Try again.');
+ this._setBarMode('submit');
+ if (submitBtn) {
+ submitBtn.disabled = false;
+ submitBtn.textContent = 'Build my avatar';
+ }
+ }
+ }
+
+ async _pollJob(jobId) {
+ const deadline = Date.now() + 8 * 60 * 1000;
+ let attempt = 0;
+ const labels = [
+ 'Generating 3D mesh...',
+ 'Building geometry and textures...',
+ 'Auto-rigging skeleton...',
+ 'Finishing avatar...',
+ ];
+
+ while (Date.now() < deadline) {
+ const interval = attempt === 0 ? 1500 : Math.min(3000 * Math.pow(1.3, Math.min(attempt, 10)), 10000);
+ await new Promise((r) => setTimeout(r, interval));
+ attempt++;
+
+ this._setBuildLabel(labels[Math.min(Math.floor(attempt / 5), labels.length - 1)]);
+
+ const r = await fetch(`${STATUS_ENDPOINT}?jobId=${encodeURIComponent(jobId)}`, {
+ credentials: 'include',
+ });
+ if (!r.ok) continue;
+ const job = await r.json();
+ if (job.status === 'done' && job.resultAvatarId) return job.resultAvatarId;
+ if (job.status === 'failed') throw new Error(job.error || 'Reconstruction failed');
+ }
+ throw new Error('Timed out — check your dashboard in a few minutes');
+ }
+
+ _setBuildLabel(text) {
+ const el = this.root.querySelector('[data-sfm-build-label]');
+ if (el) el.textContent = text;
+ }
+
+ _injectStyles() {
+ if (document.getElementById('sfm-styles')) return;
+ const style = document.createElement('style');
+ style.id = 'sfm-styles';
+ style.textContent = SFM_CSS;
+ document.head.appendChild(style);
+ }
+}
+
+async function blobToDataUrl(blob) {
+ const bitmap = await createImageBitmap(blob);
+ const scale = Math.min(1, MAX_DIM / Math.max(bitmap.width, bitmap.height));
+ const w = Math.round(bitmap.width * scale);
+ const h = Math.round(bitmap.height * scale);
+ const c = document.createElement('canvas');
+ c.width = w; c.height = h;
+ const ctx = c.getContext('2d');
+ ctx.drawImage(bitmap, 0, 0, w, h);
+ try { bitmap.close?.(); } catch (_) {}
+ return c.toDataURL('image/jpeg', JPEG_QUALITY);
+}
+
+const SFM_CSS = `
+.sfm-root {
+ position: fixed;
+ inset: 0;
+ z-index: 10000;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ opacity: 0;
+ transition: opacity 200ms ease;
+}
+.sfm-root.sfm-open { opacity: 1; }
+.sfm-backdrop {
+ position: absolute;
+ inset: 0;
+ background: rgba(0, 0, 0, 0.88);
+ backdrop-filter: blur(12px);
+}
+.sfm-panel {
+ position: relative;
+ width: min(440px, 96vw);
+ max-height: 94vh;
+ display: flex;
+ flex-direction: column;
+ background: #0a0a0a;
+ border: 1px solid #1a1a1a;
+ border-radius: 20px;
+ overflow: hidden;
+ box-shadow: 0 24px 64px rgba(0, 0, 0, 0.7);
+}
+.sfm-header {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+ padding: 14px 16px;
+ border-bottom: 1px solid #1a1a1a;
+ flex-shrink: 0;
+}
+.sfm-close {
+ background: transparent;
+ border: 1px solid #2a2a2a;
+ color: #888;
+ width: 32px;
+ height: 32px;
+ border-radius: 8px;
+ display: grid;
+ place-items: center;
+ cursor: pointer;
+ transition: color 120ms, border-color 120ms;
+}
+.sfm-close:hover { color: #e8e8e8; border-color: #444; }
+.sfm-title {
+ font-size: 15px;
+ font-weight: 600;
+ color: #e8e8e8;
+ flex: 1;
+}
+.sfm-slot-label {
+ font-size: 12px;
+ color: #888;
+ letter-spacing: 0.04em;
+ text-transform: uppercase;
+}
+.sfm-stage {
+ position: relative;
+ aspect-ratio: 3 / 4;
+ background: #000;
+ overflow: hidden;
+}
+.sfm-video {
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ transform: scaleX(-1);
+}
+.sfm-canvas {
+ position: absolute;
+ inset: 0;
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ transform: scaleX(-1);
+ pointer-events: none;
+}
+.sfm-preview-img {
+ position: absolute;
+ inset: 0;
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ transform: scaleX(-1);
+}
+.sfm-badges {
+ position: absolute;
+ top: 10px;
+ left: 10px;
+ right: 10px;
+ display: flex;
+ gap: 5px;
+ flex-wrap: wrap;
+ z-index: 2;
+}
+.sfm-chip {
+ font-size: 10.5px;
+ font-weight: 600;
+ padding: 3px 8px;
+ border-radius: 6px;
+ letter-spacing: 0.03em;
+ text-transform: uppercase;
+ background: rgba(0, 0, 0, 0.55);
+ border: 1px solid rgba(255, 255, 255, 0.1);
+ color: #888;
+ backdrop-filter: blur(6px);
+}
+.sfm-chip-ok {
+ color: #e8e8e8;
+ border-color: rgba(255, 255, 255, 0.25);
+ background: rgba(255, 255, 255, 0.1);
+}
+.sfm-chip-bad {
+ color: #ff6b6b;
+ border-color: rgba(255, 107, 107, 0.3);
+ background: rgba(255, 107, 107, 0.08);
+}
+.sfm-hint {
+ position: absolute;
+ bottom: 12px;
+ left: 0;
+ right: 0;
+ text-align: center;
+ font-size: 13px;
+ color: rgba(255, 255, 255, 0.75);
+ padding: 8px 16px;
+ pointer-events: none;
+ text-shadow: 0 1px 4px rgba(0, 0, 0, 0.6);
+}
+.sfm-hint-ok { color: #e8e8e8; font-weight: 500; }
+.sfm-hint-err { color: #ff6b6b; }
+
+.sfm-captures {
+ display: flex;
+ gap: 8px;
+ padding: 10px 16px;
+ border-bottom: 1px solid #1a1a1a;
+ justify-content: center;
+ flex-shrink: 0;
+}
+.sfm-thumb {
+ width: 52px;
+ height: 52px;
+ border-radius: 10px;
+ border: 1.5px dashed #2a2a2a;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ cursor: pointer;
+ position: relative;
+ overflow: hidden;
+ transition: border-color 120ms;
+}
+.sfm-thumb:hover { border-color: #444; }
+.sfm-thumb-active { border-color: #e8e8e8; border-style: solid; }
+.sfm-thumb-filled { border-style: solid; border-color: #2a2a2a; }
+.sfm-thumb-label {
+ font-size: 9.5px;
+ color: #888;
+ text-transform: uppercase;
+ letter-spacing: 0.05em;
+}
+.sfm-thumb-img {
+ position: absolute;
+ inset: 0;
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ transform: scaleX(-1);
+}
+
+.sfm-bar {
+ padding: 14px 16px;
+ flex-shrink: 0;
+}
+.sfm-bar-live, .sfm-bar-review {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+}
+.sfm-bar-submit {
+ display: flex;
+ flex-direction: column;
+ gap: 14px;
+}
+.sfm-bar-building {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ gap: 12px;
+ padding: 8px 0;
+}
+
+.sfm-btn {
+ padding: 10px 16px;
+ border-radius: 10px;
+ font: 600 13.5px/1 -apple-system, system-ui, sans-serif;
+ cursor: pointer;
+ border: none;
+ transition: background 120ms, color 120ms;
+}
+.sfm-btn-ghost {
+ background: transparent;
+ color: #888;
+ border: 1px solid #2a2a2a;
+}
+.sfm-btn-ghost:hover { color: #e8e8e8; border-color: #444; }
+.sfm-btn-primary {
+ background: #e8e8e8;
+ color: #0a0a0a;
+}
+.sfm-btn-primary:hover { background: #fff; }
+.sfm-btn-primary:disabled { opacity: 0.4; cursor: not-allowed; }
+.sfm-btn-full { width: 100%; text-align: center; }
+
+.sfm-shutter {
+ width: 64px;
+ height: 64px;
+ border-radius: 50%;
+ background: #e8e8e8;
+ border: none;
+ cursor: pointer;
+ display: grid;
+ place-items: center;
+ transition: opacity 120ms, transform 120ms;
+ flex-shrink: 0;
+}
+.sfm-shutter:disabled { opacity: 0.3; cursor: not-allowed; }
+.sfm-shutter:not(:disabled):active { transform: scale(0.92); }
+.sfm-shutter-ring {
+ width: 50px;
+ height: 50px;
+ border-radius: 50%;
+ border: 3px solid #0a0a0a;
+ display: block;
+}
+
+.sfm-opts {
+ display: flex;
+ gap: 16px;
+ align-items: center;
+}
+.sfm-opt-group {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+}
+.sfm-opt-label {
+ font-size: 11px;
+ color: #888;
+ text-transform: uppercase;
+ letter-spacing: 0.05em;
+}
+.sfm-toggle {
+ display: flex;
+ background: #111;
+ border: 1px solid #1a1a1a;
+ border-radius: 8px;
+ padding: 2px;
+ gap: 2px;
+}
+.sfm-toggle-btn {
+ background: transparent;
+ border: none;
+ color: #888;
+ font: 600 12px/1 -apple-system, system-ui, sans-serif;
+ padding: 6px 10px;
+ border-radius: 6px;
+ cursor: pointer;
+ transition: background 120ms, color 120ms;
+}
+.sfm-toggle-btn.active {
+ background: #1a1a1a;
+ color: #e8e8e8;
+}
+.sfm-toggle-btn:hover:not(.active) { color: #bbb; }
+
+.sfm-build-spinner {
+ width: 20px;
+ height: 20px;
+ border-radius: 50%;
+ border: 2px solid #2a2a2a;
+ border-top-color: #e8e8e8;
+ animation: sfm-spin 0.8s linear infinite;
+}
+@keyframes sfm-spin { to { transform: rotate(360deg); } }
+.sfm-build-label {
+ font-size: 13.5px;
+ color: #888;
+}
+
+@media (max-width: 480px) {
+ .sfm-panel {
+ width: 100vw;
+ max-height: 100vh;
+ border-radius: 0;
+ height: 100vh;
+ }
+}
+`;
diff --git a/src/xr.js b/src/xr.js
index 8b6af00f8..abdadf272 100644
--- a/src/xr.js
+++ b/src/xr.js
@@ -420,11 +420,19 @@ async function loadAvatar() {
camera.position.set(0, center.y + size * 0.2, size * 1.4);
controls.update();
- // Animations
- await animationManager.loadAll();
+ // Animations — fetch manifest, load idle clip, attach to model
+ try {
+ const manifest = await fetch('/animations/manifest.json', { cache: 'force-cache' })
+ .then((r) => r.ok ? r.json() : []);
+ const idleDef = manifest.find((d) => d.name === 'idle') || manifest[0];
+ if (idleDef) {
+ animationManager.setAnimationDefs([idleDef]);
+ await animationManager.loadAll();
+ }
+ } catch {}
animationManager.attach(root);
xrViewer.mixer = animationManager.mixer;
- animationManager.play('idle');
+ if (animationManager._animationDefs.length) animationManager.play('idle');
// Avatar name from URL param
const params = new URLSearchParams(location.search);