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.

widgets: knowledge base + transcripts, avatar-embed/handle, /app-next, /create-review feature grid

nirholas7fae0b27f2c8
diff --git a/api/_lib/chunker.js b/api/_lib/chunker.js
new file mode 100644
index 000000000..d31fb369d
--- /dev/null
+++ b/api/_lib/chunker.js
@@ -0,0 +1,78 @@
+// Recursive 512-token chunks with ~100-token overlap. We approximate tokens
+// as 4 chars (the conservative GPT-family ratio) so we don't pull in tiktoken
+// just to drive a chunker — within ±15% of the real count, which is fine for
+// a retrieval window. The 512/100 split was the best-performing config in the
+// 2026 chunking benchmarks (Firecrawl, Substack) versus semantic chunking.
+
+const CHARS_PER_TOKEN = 4;
+const CHUNK_TOKENS = 512;
+const OVERLAP_TOKENS = 100;
+
+const CHUNK_CHARS = CHUNK_TOKENS * CHARS_PER_TOKEN;
+const OVERLAP_CHARS = OVERLAP_TOKENS * CHARS_PER_TOKEN;
+
+/**
+ * Split `text` into overlapping chunks. Walks sentence/paragraph boundaries
+ * when possible so chunks don't slice through mid-word or mid-sentence.
+ *
+ * Returns: [{ content: string, token_count: number }]
+ */
+export function chunk(text) {
+ const clean = normalize(text);
+ if (!clean) return [];
+ if (clean.length <= CHUNK_CHARS) {
+ return [{ content: clean, token_count: estimateTokens(clean) }];
+ }
+
+ const out = [];
+ let cursor = 0;
+ while (cursor < clean.length) {
+ const target = Math.min(cursor + CHUNK_CHARS, clean.length);
+ const slice = clean.slice(cursor, target);
+ const cut = target >= clean.length ? slice : sliceAtBoundary(slice);
+ const trimmed = cut.trim();
+ if (trimmed) out.push({ content: trimmed, token_count: estimateTokens(trimmed) });
+ if (target >= clean.length) break;
+ cursor += Math.max(1, cut.length - OVERLAP_CHARS);
+ }
+ return out;
+}
+
+export function estimateTokens(text) {
+ return Math.ceil((text?.length || 0) / CHARS_PER_TOKEN);
+}
+
+function normalize(text) {
+ return String(text || '')
+ .replace(/\r\n?/g, '\n')
+ .replace(/[ \t]+/g, ' ')
+ .replace(/\n{3,}/g, '\n\n')
+ .trim();
+}
+
+// Prefer to end on a paragraph break, then sentence end, then space. Falls
+// through to the raw slice if none are reachable in the last 25% of the chunk.
+function sliceAtBoundary(slice) {
+ const tail = Math.floor(slice.length * 0.25);
+ const window = slice.slice(slice.length - tail);
+
+ const para = window.lastIndexOf('\n\n');
+ if (para >= 0) return slice.slice(0, slice.length - tail + para + 2);
+
+ const sentence = lastIndexOfAny(window, ['. ', '! ', '? ', '.\n', '!\n', '?\n']);
+ if (sentence >= 0) return slice.slice(0, slice.length - tail + sentence + 2);
+
+ const space = window.lastIndexOf(' ');
+ if (space >= 0) return slice.slice(0, slice.length - tail + space + 1);
+
+ return slice;
+}
+
+function lastIndexOfAny(str, needles) {
+ let best = -1;
+ for (const n of needles) {
+ const i = str.lastIndexOf(n);
+ if (i > best) best = i;
+ }
+ return best;
+}
diff --git a/api/_lib/embeddings.js b/api/_lib/embeddings.js
new file mode 100644
index 000000000..eb8281f88
--- /dev/null
+++ b/api/_lib/embeddings.js
@@ -0,0 +1,71 @@
+// OpenAI text-embedding-3-small @ 256 dimensions (Matryoshka truncation).
+// 12× cheaper storage than the full 3072-dim model with ~98% of recall, which
+// is the right tradeoff for grounding a small set of widget knowledge docs
+// where chunk counts stay in the low thousands.
+//
+// We keep this here (rather than reaching for an SDK) so the talking-agent
+// chat path remains a single zero-dep fetch call — matching the existing
+// pattern in api/widgets/[id]/[action].js.
+
+const EMBED_URL = 'https://api.openai.com/v1/embeddings';
+const EMBED_MODEL = 'text-embedding-3-small';
+const EMBED_DIMS = 256;
+
+export function embeddingsConfigured() {
+ return !!process.env.OPENAI_API_KEY;
+}
+
+/**
+ * Embed an array of strings. Returns Float64Array[].
+ * Throws if OPENAI_API_KEY isn't configured or the API errors.
+ */
+export async function embed(texts) {
+ const apiKey = process.env.OPENAI_API_KEY;
+ if (!apiKey)
+ throw Object.assign(new Error('OPENAI_API_KEY not configured'), { code: 'no_embedder' });
+ if (!texts.length) return [];
+
+ const upstream = await fetch(EMBED_URL, {
+ method: 'POST',
+ headers: {
+ Authorization: `Bearer ${apiKey}`,
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({
+ model: EMBED_MODEL,
+ input: texts,
+ dimensions: EMBED_DIMS,
+ }),
+ });
+ if (!upstream.ok) {
+ const body = await upstream.text().catch(() => '');
+ throw Object.assign(new Error(`embedding api ${upstream.status}: ${body.slice(0, 200)}`), {
+ code: 'embedder_error',
+ status: upstream.status,
+ });
+ }
+ const data = await upstream.json();
+ return (data.data || [])
+ .sort((a, b) => a.index - b.index)
+ .map((row) => Float64Array.from(row.embedding));
+}
+
+/**
+ * Cosine similarity between two equal-length numeric arrays. Inputs come from
+ * embed() (Float64Array) or from the DB (plain Array via JSONB) — both work.
+ */
+export function cosine(a, b) {
+ const n = Math.min(a.length, b.length);
+ let dot = 0;
+ let na = 0;
+ let nb = 0;
+ for (let i = 0; i < n; i++) {
+ const x = a[i];
+ const y = b[i];
+ dot += x * y;
+ na += x * x;
+ nb += y * y;
+ }
+ if (!na || !nb) return 0;
+ return dot / Math.sqrt(na * nb);
+}
diff --git a/api/_lib/ids.js b/api/_lib/ids.js
new file mode 100644
index 000000000..1a76906e8
--- /dev/null
+++ b/api/_lib/ids.js
@@ -0,0 +1,18 @@
+// Short, URL-safe IDs with a domain prefix. Mirrors the `wdgt_` prefix the
+// widgets table already uses so all surface-level IDs follow the same shape.
+
+import crypto from 'node:crypto';
+
+const RANDOM_BYTES = 9; // 9 raw bytes → 12 base64url chars
+
+export function shortId(prefix) {
+ return `${prefix}_${crypto.randomBytes(RANDOM_BYTES).toString('base64url')}`;
+}
+
+const PREFIX_RE = /^[a-z]{2,8}_[A-Za-z0-9_-]{8,32}$/;
+
+export function isShortId(s, prefix) {
+ if (typeof s !== 'string') return false;
+ if (prefix && !s.startsWith(`${prefix}_`)) return false;
+ return PREFIX_RE.test(s);
+}
diff --git a/api/_lib/migrations/2026-05-24-widget-transcripts-knowledge.sql b/api/_lib/migrations/2026-05-24-widget-transcripts-knowledge.sql
new file mode 100644
index 000000000..e5aee7840
--- /dev/null
+++ b/api/_lib/migrations/2026-05-24-widget-transcripts-knowledge.sql
@@ -0,0 +1,118 @@
+-- Migration: widget analytics (idempotent table guard) + chat transcripts
+-- + knowledge upload for the talking-agent widget type.
+--
+-- Apply: npm run db:migrate -- --apply --file 2026-05-24-widget-transcripts-knowledge.sql
+-- Idempotent.
+
+begin;
+
+-- ── widget_views ─────────────────────────────────────────────────────────────
+-- Already defined in schema.sql. Re-asserted here so deployments that pre-date
+-- the schema.sql addition pick it up. The stats + view endpoints both catch
+-- "relation does not exist" so this is the only step needed to wire them live.
+create table if not exists widget_views (
+ id bigserial primary key,
+ widget_id text not null references widgets(id) on delete cascade,
+ country text,
+ referer_host text,
+ created_at timestamptz not null default now()
+);
+
+create index if not exists widget_views_widget_time
+ on widget_views(widget_id, created_at desc);
+
+-- ── widget_chat_threads ──────────────────────────────────────────────────────
+-- One row per (widget, visitor, page-load). visitor_id is a cookieless opaque
+-- UUID minted client-side in localStorage; thread_id is per page-load in
+-- sessionStorage so each "conversation start" gets its own bucket.
+create table if not exists widget_chat_threads (
+ id text primary key, -- 'wct_' + 12 base64url chars (client-supplied)
+ widget_id text not null references widgets(id) on delete cascade,
+ visitor_id text not null, -- opaque UUID from localStorage
+ referer_host text,
+ country text,
+ user_agent_hash text, -- sha256(ua) truncated; never the raw UA
+ message_count integer not null default 0,
+ started_at timestamptz not null default now(),
+ last_message_at timestamptz not null default now()
+);
+
+create index if not exists widget_chat_threads_widget_time
+ on widget_chat_threads(widget_id, last_message_at desc);
+create index if not exists widget_chat_threads_visitor
+ on widget_chat_threads(widget_id, visitor_id, started_at desc);
+
+-- ── widget_chat_messages ─────────────────────────────────────────────────────
+-- Append-only log of (role, content) pairs per thread. content is the redacted
+-- form — raw email/phone/card patterns are replaced at write time. Useful for
+-- the creator to see what visitors asked without storing PII.
+create table if not exists widget_chat_messages (
+ id bigserial primary key,
+ thread_id text not null references widget_chat_threads(id) on delete cascade,
+ widget_id text not null references widgets(id) on delete cascade,
+ role text not null check (role in ('user', 'assistant')),
+ content text not null,
+ actions jsonb, -- assistant-only: [{type, ...}] of fired skills
+ provider text, -- assistant-only: anthropic | openai | ...
+ model text, -- assistant-only: model id used
+ redacted boolean not null default false, -- true when content was scrubbed
+ created_at timestamptz not null default now()
+);
+
+create index if not exists widget_chat_messages_thread_time
+ on widget_chat_messages(thread_id, created_at);
+create index if not exists widget_chat_messages_widget_time
+ on widget_chat_messages(widget_id, created_at desc);
+
+-- ── widget_knowledge_docs ────────────────────────────────────────────────────
+-- One doc per uploaded PDF / text paste / crawled URL attached to a widget.
+-- Content lives in widget_knowledge_chunks (1..N per doc).
+create table if not exists widget_knowledge_docs (
+ id text primary key, -- 'wkd_' + 12 base64url chars
+ widget_id text not null references widgets(id) on delete cascade,
+ user_id uuid not null references users(id) on delete cascade,
+ title text not null,
+ source_type text not null check (source_type in ('url', 'text', 'pdf', 'markdown')),
+ source_url text,
+ byte_size integer not null default 0,
+ chunk_count integer not null default 0,
+ token_count integer not null default 0,
+ status text not null default 'ready' check (status in ('processing', 'ready', 'failed')),
+ error text,
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now()
+);
+
+create index if not exists widget_knowledge_docs_widget
+ on widget_knowledge_docs(widget_id, created_at desc);
+create index if not exists widget_knowledge_docs_user
+ on widget_knowledge_docs(user_id, created_at desc);
+
+do $$ begin
+ create trigger widget_knowledge_docs_set_updated_at before update on widget_knowledge_docs
+ for each row execute function set_updated_at();
+exception when duplicate_object then null; end $$;
+
+-- ── widget_knowledge_chunks ──────────────────────────────────────────────────
+-- Each chunk is a 512-token window with 100-token overlap, embedded with
+-- text-embedding-3-small truncated to 256 dimensions (Matryoshka). Stored as a
+-- JSONB float array; retrieval scores via cosine similarity in JS at query
+-- time — fine up to several thousand chunks per widget. Beyond that, switch to
+-- pgvector with a single column rewrite.
+create table if not exists widget_knowledge_chunks (
+ id bigserial primary key,
+ doc_id text not null references widget_knowledge_docs(id) on delete cascade,
+ widget_id text not null references widgets(id) on delete cascade,
+ chunk_index integer not null,
+ content text not null,
+ embedding jsonb not null, -- float[256] truncated text-embedding-3-small
+ token_count integer not null default 0,
+ created_at timestamptz not null default now()
+);
+
+create index if not exists widget_knowledge_chunks_widget
+ on widget_knowledge_chunks(widget_id);
+create index if not exists widget_knowledge_chunks_doc
+ on widget_knowledge_chunks(doc_id, chunk_index);
+
+commit;
diff --git a/api/_lib/migrations/2026-05-24-widget-types-expand.sql b/api/_lib/migrations/2026-05-24-widget-types-expand.sql
new file mode 100644
index 000000000..ae218276e
--- /dev/null
+++ b/api/_lib/migrations/2026-05-24-widget-types-expand.sql
@@ -0,0 +1,26 @@
+-- Migration: extend widgets.type CHECK constraint with the three new runtime
+-- widget types (pumpfun-feed, kol-trades, live-trades-canvas) that already
+-- ship with mount handlers in src/widgets/ and are exposed in the public
+-- widgets gallery via demo fixtures.
+-- Apply: npm run db:migrate -- --apply --file 2026-05-24-widget-types-expand.sql
+-- Idempotent.
+
+begin;
+
+alter table widgets
+ drop constraint if exists widgets_type_check;
+
+alter table widgets
+ add constraint widgets_type_check
+ check (type in (
+ 'turntable',
+ 'animation-gallery',
+ 'talking-agent',
+ 'passport',
+ 'hotspot-tour',
+ 'pumpfun-feed',
+ 'kol-trades',
+ 'live-trades-canvas'
+ ));
+
+commit;
diff --git a/api/_lib/pii.js b/api/_lib/pii.js
new file mode 100644
index 000000000..af884986d
--- /dev/null
+++ b/api/_lib/pii.js
@@ -0,0 +1,28 @@
+// Lightweight PII redaction for chat transcripts. Runs at write time so
+// stored content is already scrubbed — the creator can review what visitors
+// asked without ever holding raw email/phone/card data.
+//
+// This is the regex pass Presidio runs in its Analyzer; we skip the NER half
+// because the transcripts dashboard doesn't need names/locations redacted
+// (those frequently aren't sensitive) and NER would push a 200MB ML model
+// onto the request path.
+
+const PATTERNS = [
+ { token: '[email]', re: /[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g },
+ { token: '[card]', re: /\b(?:\d[ -]?){13,19}\b/g },
+ { token: '[ssn]', re: /\b\d{3}-\d{2}-\d{4}\b/g },
+ { token: '[phone]', re: /(?:\+?\d{1,3}[\s.-]?)?(?:\(?\d{3}\)?[\s.-]?)\d{3}[\s.-]?\d{4}\b/g },
+ { token: '[key]', re: /\b(?:sk|pk|rk|api)[_-][A-Za-z0-9_-]{12,}\b/g },
+];
+
+export function redactPii(text) {
+ let out = String(text ?? '');
+ let redacted = false;
+ for (const { token, re } of PATTERNS) {
+ if (re.test(out)) {
+ redacted = true;
+ out = out.replace(re, token);
+ }
+ }
+ return { content: out, redacted };
+}
diff --git a/api/_lib/schema.sql b/api/_lib/schema.sql
index 9ce54410b..89ffb6c11 100644
--- a/api/_lib/schema.sql
+++ b/api/_lib/schema.sql
@@ -356,7 +356,7 @@ create table if not exists widgets (
id text primary key, -- 'wdgt_' + 12 base64url chars
user_id uuid not null references users(id) on delete cascade,
avatar_id uuid references avatars(id) on delete set null,
- type text not null check (type in ('turntable','animation-gallery','talking-agent','passport','hotspot-tour')),
+ type text not null check (type in ('turntable','animation-gallery','talking-agent','passport','hotspot-tour','pumpfun-feed','kol-trades','live-trades-canvas')),
name text not null,
config jsonb not null default '{}'::jsonb,
is_public boolean not null default true,
@@ -389,6 +389,96 @@ create table if not exists widget_views (
create index if not exists widget_views_widget_time
on widget_views(widget_id, created_at desc);
+-- ── widget_chat_threads — one row per (widget, visitor, page-load) ──────────
+-- visitor_id is a cookieless opaque UUID minted client-side in localStorage;
+-- thread_id is per page-load in sessionStorage so each "conversation start"
+-- gets its own bucket. Lets the creator see conversations grouped by visit.
+create table if not exists widget_chat_threads (
+ id text primary key, -- 'wct_' + 12 base64url chars
+ widget_id text not null references widgets(id) on delete cascade,
+ visitor_id text not null,
+ referer_host text,
+ country text,
+ user_agent_hash text,
+ message_count integer not null default 0,
+ started_at timestamptz not null default now(),
+ last_message_at timestamptz not null default now()
+);
+
+create index if not exists widget_chat_threads_widget_time
+ on widget_chat_threads(widget_id, last_message_at desc);
+create index if not exists widget_chat_threads_visitor
+ on widget_chat_threads(widget_id, visitor_id, started_at desc);
+
+-- ── widget_chat_messages — append-only log of visitor + assistant turns ─────
+-- content is the redacted form — email/phone/card patterns are scrubbed at
+-- write time so the creator can review without storing PII.
+create table if not exists widget_chat_messages (
+ id bigserial primary key,
+ thread_id text not null references widget_chat_threads(id) on delete cascade,
+ widget_id text not null references widgets(id) on delete cascade,
+ role text not null check (role in ('user', 'assistant')),
+ content text not null,
+ actions jsonb,
+ provider text,
+ model text,
+ redacted boolean not null default false,
+ created_at timestamptz not null default now()
+);
+
+create index if not exists widget_chat_messages_thread_time
+ on widget_chat_messages(thread_id, created_at);
+create index if not exists widget_chat_messages_widget_time
+ on widget_chat_messages(widget_id, created_at desc);
+
+-- ── widget_knowledge_docs — uploaded docs + URLs that ground the agent ─────
+create table if not exists widget_knowledge_docs (
+ id text primary key, -- 'wkd_' + 12 base64url chars
+ widget_id text not null references widgets(id) on delete cascade,
+ user_id uuid not null references users(id) on delete cascade,
+ title text not null,
+ source_type text not null check (source_type in ('url', 'text', 'pdf', 'markdown')),
+ source_url text,
+ byte_size integer not null default 0,
+ chunk_count integer not null default 0,
+ token_count integer not null default 0,
+ status text not null default 'ready' check (status in ('processing', 'ready', 'failed')),
+ error text,
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now()
+);
+
+create index if not exists widget_knowledge_docs_widget
+ on widget_knowledge_docs(widget_id, created_at desc);
+create index if not exists widget_knowledge_docs_user
+ on widget_knowledge_docs(user_id, created_at desc);
+
+do $$ begin
+ create trigger widget_knowledge_docs_set_updated_at before update on widget_knowledge_docs
+ for each row execute function set_updated_at();
+exception when duplicate_object then null; end $$;
+
+-- ── widget_knowledge_chunks — 512/100-overlap chunks with truncated embeds ──
+-- Embedding is text-embedding-3-small @ 256 dims (Matryoshka), stored as a
+-- JSONB float array. Retrieval scores via cosine similarity in JS at query
+-- time; switch to pgvector if a single widget grows past several thousand
+-- chunks.
+create table if not exists widget_knowledge_chunks (
+ id bigserial primary key,
+ doc_id text not null references widget_knowledge_docs(id) on delete cascade,
+ widget_id text not null references widgets(id) on delete cascade,
+ chunk_index integer not null,
+ content text not null,
+ embedding jsonb not null,
+ token_count integer not null default 0,
+ created_at timestamptz not null default now()
+);
+
+create index if not exists widget_knowledge_chunks_widget
+ on widget_knowledge_chunks(widget_id);
+create index if not exists widget_knowledge_chunks_doc
+ on widget_knowledge_chunks(doc_id, chunk_index);
+
-- ── erc8004_agents_index — crawled directory of every on-chain agent ───────
-- Populated by api/cron/erc8004-crawl.js from Etherscan V2 getLogs across every
-- chain in REGISTRY_DEPLOYMENTS. Metadata fields are lazily filled from each
diff --git a/api/_lib/text-extract.js b/api/_lib/text-extract.js
new file mode 100644
index 000000000..b33fa155d
--- /dev/null
+++ b/api/_lib/text-extract.js
@@ -0,0 +1,135 @@
+// Server-side helpers for turning a URL into plain text we can chunk + embed.
+// PDFs are extracted client-side (pdfjs in the studio bundle) and posted as
+// text, so this module only needs to handle HTML / plain content fetches.
+
+import { JSDOM } from 'jsdom';
+
+const FETCH_TIMEOUT_MS = 12_000;
+const MAX_BYTES = 4 * 1024 * 1024; // 4 MB hard cap per source
+const USER_AGENT = 'three.ws/widget-knowledge-bot (+https://three.ws)';
+
+/**
+ * Fetch a URL and return { title, text, byteSize, contentType }. Strips
+ * script/style/nav/footer noise and collapses whitespace.
+ *
+ * Throws an Error with .status for caller-friendly mapping.
+ */
+export async function fetchAndExtract(url) {
+ const u = new URL(url);
+ if (u.protocol !== 'http:' && u.protocol !== 'https:') {
+ throw Object.assign(new Error('only http(s) URLs are supported'), { status: 400 });
+ }
+ if (isPrivateHost(u.hostname)) {
+ throw Object.assign(new Error('URL must be publicly reachable'), { status: 400 });
+ }
+
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
+ let res;
+ try {
+ res = await fetch(u.toString(), {
+ redirect: 'follow',
+ headers: {
+ 'user-agent': USER_AGENT,
+ accept: 'text/html,text/plain,application/xhtml+xml',
+ },
+ signal: controller.signal,
+ });
+ } catch (err) {
+ clearTimeout(timer);
+ throw Object.assign(new Error(`fetch failed: ${err.message}`), { status: 502 });
+ }
+ clearTimeout(timer);
+
+ if (!res.ok) {
+ throw Object.assign(new Error(`fetch ${res.status} ${res.statusText}`), { status: 502 });
+ }
+
+ const contentType = (res.headers.get('content-type') || '').toLowerCase();
+ const isHtml = /html|xhtml/.test(contentType);
+ const isPlain = /^text\//.test(contentType) || /json$/.test(contentType);
+ if (!isHtml && !isPlain) {
+ throw Object.assign(
+ new Error(
+ `unsupported content-type ${contentType || 'unknown'} — only HTML and text URLs are accepted`,
+ ),
+ { status: 415 },
+ );
+ }
+
+ const buf = await readWithCap(res, MAX_BYTES);
+ const raw = buf.toString('utf8');
+
+ if (!isHtml) {
+ return {
+ title: derivedTitleFromUrl(u),
+ text: raw.trim(),
+ byteSize: buf.byteLength,
+ contentType,
+ };
+ }
+
+ const dom = new JSDOM(raw);
+ const doc = dom.window.document;
+ doc.querySelectorAll(
+ 'script, style, noscript, template, svg, iframe, nav, footer, header, form, [aria-hidden="true"]',
+ ).forEach((el) => el.remove());
+
+ const title =
+ (
+ doc.querySelector('meta[property="og:title"]')?.getAttribute('content') ||
+ doc.querySelector('title')?.textContent ||
+ ''
+ ).trim() || derivedTitleFromUrl(u);
+
+ const main = doc.querySelector('article, main, [role="main"], #main, #content') || doc.body;
+ const text = (main?.textContent || '')
+ .replace(/[ \t]+/g, ' ')
+ .replace(/\n[ \t]+/g, '\n')
+ .replace(/\n{3,}/g, '\n\n')
+ .trim();
+
+ return { title, text, byteSize: buf.byteLength, contentType };
+}
+
+function derivedTitleFromUrl(u) {
+ const last = u.pathname.split('/').filter(Boolean).pop();
+ return decodeURIComponent(last || u.hostname);
+}
+
+async function readWithCap(res, limit) {
+ const reader = res.body?.getReader();
+ if (!reader) {
+ const ab = await res.arrayBuffer();
+ if (ab.byteLength > limit)
+ throw Object.assign(new Error('source exceeds 4MB'), { status: 413 });
+ return Buffer.from(ab);
+ }
+ const chunks = [];
+ let total = 0;
+ while (true) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ total += value.byteLength;
+ if (total > limit) {
+ reader.cancel().catch(() => {});
+ throw Object.assign(new Error('source exceeds 4MB'), { status: 413 });
+ }
+ chunks.push(Buffer.from(value));
+ }
+ return Buffer.concat(chunks);
+}
+
+// Block SSRF to private/loopback/link-local ranges. Resolution-time check is
+// not perfect (DNS rebinding) but it eliminates accidental leaks; production
+// should layer a network egress firewall on top.
+function isPrivateHost(host) {
+ const h = host.toLowerCase();
+ if (h === 'localhost' || h === '0.0.0.0' || h === 'broadcasthost') return true;
+ if (/\.local$|\.internal$|\.intranet$/.test(h)) return true;
+ if (/^(?:127\.|10\.|192\.168\.|169\.254\.|::1$|fe80::|fc[0-9a-f]{2}:|fd[0-9a-f]{2}:)/i.test(h))
+ return true;
+ const m = h.match(/^172\.(\d{1,3})\./);
+ if (m && Number(m[1]) >= 16 && Number(m[1]) <= 31) return true;
+ return false;
+}
diff --git a/api/_lib/widget-types.js b/api/_lib/widget-types.js
new file mode 100644
index 000000000..f6cf9655d
--- /dev/null
+++ b/api/_lib/widget-types.js
@@ -0,0 +1,24 @@
+/**
+ * Server-side widget type registry — single source of truth for the API layer.
+ *
+ * Keep aligned with `src/widget-types.js` (which adds zod schemas + brand
+ * defaults for the runtime). The arrays here are the authoritative enum the DB
+ * CHECK constraint enforces and what `/api/widgets` accepts in POST/PATCH.
+ */
+
+export const WIDGET_TYPES = [
+ 'turntable',
+ 'animation-gallery',
+ 'talking-agent',
+ 'passport',
+ 'hotspot-tour',
+ 'pumpfun-feed',
+ 'kol-trades',
+ 'live-trades-canvas',
+];
+
+export const WIDGET_TYPE_SET = new Set(WIDGET_TYPES);
+
+export function isWidgetType(t) {
+ return typeof t === 'string' && WIDGET_TYPE_SET.has(t);
+}
diff --git a/api/_providers/replicate.js b/api/_providers/replicate.js
index 2b812ae34..d0a0f9f70 100644
--- a/api/_providers/replicate.js
+++ b/api/_providers/replicate.js
@@ -48,10 +48,22 @@ const MODE_TO_ENV = Object.freeze({
rerig: 'REPLICATE_RERIG_MODEL',
});
+// Built-in defaults: commercial-OK models that are stable on Replicate so the
+// provider works end-to-end as soon as REPLICATE_API_TOKEN is set, without
+// the operator having to chase down version hashes. Override per-mode via the
+// matching REPLICATE_*_MODEL env var when you want a different model.
+//
+// `firtoz/trellis` — Microsoft TRELLIS, image-to-textured-GLB, MIT license,
+// 1.2B parameters, ~30–90s on Replicate's A100 fleet. Version-pinned to a
+// known-good build; bump when Replicate publishes a newer one.
+const DEFAULT_MODELS = Object.freeze({
+ reconstruct: 'firtoz/trellis',
+});
+
function modelForMode(mode) {
const envName = MODE_TO_ENV[mode];
if (!envName) return null;
- return readEnv(envName);
+ return readEnv(envName) || DEFAULT_MODELS[mode] || null;
}
// Map our 5 modes onto the input shape each model expects. The exact shape
@@ -138,8 +150,8 @@ export function createRegenProvider() {
return {
async submit(request) {
- const version = modelForMode(request.mode);
- if (!version) {
+ const modelRef = modelForMode(request.mode);
+ if (!modelRef) {
throw Object.assign(
new Error(
`replicate provider has no model configured for mode "${request.mode}" — set ${MODE_TO_ENV[request.mode] || 'the matching REPLICATE_*_MODEL env var'}`,
@@ -154,12 +166,39 @@ export function createRegenProvider() {
params: request.params,
});
+ // Two Replicate API shapes:
+ // • Version hash (64 hex chars): POST /predictions with { version, input }.
+ // Locks behavior to a known commit; required for community models that
+ // don't expose model-level prediction endpoints.
+ // • Model slug (owner/name[:version]): POST /models/{owner}/{name}/predictions
+ // with { input }. Resolves to the latest published version unless a
+ // :version suffix is provided. We use this for the built-in defaults so
+ // they don't go stale every time Replicate republishes.
+ const isVersionHash = /^[a-f0-9]{40,64}$/i.test(modelRef);
+ const slugMatch = modelRef.match(/^([a-z0-9-]+)\/([a-z0-9._-]+)(?::([a-f0-9]+))?$/i);
+
+ let endpoint;
+ let body;
+ if (isVersionHash) {
+ endpoint = `${REPLICATE_BASE}/predictions`;
+ body = JSON.stringify({ version: modelRef, input });
+ } else if (slugMatch) {
+ const [, owner, name, pinnedVersion] = slugMatch;
+ endpoint = `${REPLICATE_BASE}/models/${owner}/${name}/predictions`;
+ body = JSON.stringify(pinnedVersion ? { version: pinnedVersion, input } : { input });
+ } else {
+ throw Object.assign(
+ new Error(`replicate model reference "${modelRef}" is neither a version hash nor an owner/name slug`),
+ { code: 'mode_unconfigured', status: 500 },
+ );
+ }
+
let response;
try {
- response = await fetch(`${REPLICATE_BASE}/predictions`, {
+ response = await fetch(endpoint, {
method: 'POST',
headers: authHeaders,
- body: JSON.stringify({ version, input }),
+ body,
});
} catch (err) {
throw Object.assign(new Error(`replicate submit failed: ${err?.message}`), {
diff --git a/api/avatars/[id].js b/api/avatars/[id].js
index e1bc34534..3a31b6812 100644
--- a/api/avatars/[id].js
+++ b/api/avatars/[id].js
@@ -37,6 +37,7 @@ const patchSchema = z.object({
// Action endpoints that share this file (no id needed)
const ACTION_ENDPOINTS = new Set([
'presign',
+ 'upload',
'presign-thumbnail',
'presign-usdz',
'presign-halfbody',
diff --git a/api/users/[username]/avatar.js b/api/users/[username]/avatar.js
new file mode 100644
index 000000000..44cbe48de
--- /dev/null
+++ b/api/users/[username]/avatar.js
@@ -0,0 +1,179 @@
+// GET /api/users/:username/avatar — resolve a username to their canonical avatar.
+//
+// Returns a minimal payload designed to drive both:
+// • the portable <script src="…/embed.js" data-avatar="@username"> snippet
+// • the public /@username live profile page
+//
+// Resolution priority:
+// 1. Most-recent PUBLIC avatar owned by the user
+// 2. If no public avatars, return 404 (we never leak a private GLB by handle)
+//
+// Optimization knobs (passed through to the model_url):
+// ?lod=0|1|2
+// ?textureSize=128|256|512|1024|2048
+// ?morphs=arkit52|all
+// ?draco=1
+// ?baked=1 prefer baked_storage_key when fresh (default ON;
+// pass baked=0 to force the base GLB).
+//
+// Embed knob (for iframe/script consumers):
+// ?bg=transparent|dark|light
+// ?idle=on|off
+// ?mocap=off|webcam
+//
+// The returned `embed_url` is a fully-formed iframe src — drop it into an
+// <iframe src="…"> and you get a live, lipsynced avatar with idle behaviors
+// running. The `model_url` is a direct GLB pointer for SDK consumers (RPM
+// Visage style) who want to render it themselves.
+
+import { sql } from '../../_lib/db.js';
+import { cors, json, method, wrap, error } from '../../_lib/http.js';
+import { limits, clientIp } from '../../_lib/rate-limit.js';
+import { publicUrl } from '../../_lib/r2.js';
+import { env } from '../../_lib/env.js';
+
+const VALID_LOD = new Set(['0', '1', '2']);
+const VALID_TEX = new Set(['128', '256', '512', '1024', '2048']);
+const VALID_MORPHS = new Set(['arkit52', 'all']);
+const VALID_BG = new Set(['transparent', 'dark', 'light']);
+const VALID_MOCAP = new Set(['off', 'webcam']);
+
+function originFor(req) {
+ const fromEnv = env.APP_ORIGIN;
+ if (fromEnv) return fromEnv.replace(/\/$/, '');
+ const proto = req.headers['x-forwarded-proto'] || 'https';
+ const host = req.headers['x-forwarded-host'] || req.headers.host;
+ if (!host) return '';
+ return `${proto}://${host}`.replace(/\/$/, '');
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: false })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const usernameRaw =
+ req.query?.username ||
+ new URL(req.url, 'http://x').pathname.split('/').filter(Boolean).slice(-2)[0] ||
+ '';
+ const username = String(usernameRaw).toLowerCase().replace(/^@/, '').trim();
+ if (!username || !/^[a-z0-9_-]{3,30}$/.test(username)) {
+ return error(res, 400, 'validation_error', 'invalid username');
+ }
+
+ const rl = await limits.authIp(clientIp(req));
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+
+ const url = new URL(req.url, 'http://x');
+ const lod = url.searchParams.get('lod');
+ const textureSize = url.searchParams.get('textureSize');
+ const morphs = url.searchParams.get('morphs');
+ const draco = url.searchParams.get('draco');
+ const baked = url.searchParams.get('baked') !== '0';
+ const bg = url.searchParams.get('bg') || 'transparent';
+ const idle = url.searchParams.get('idle') || 'on';
+ const mocap = url.searchParams.get('mocap') || 'off';
+
+ if (lod != null && !VALID_LOD.has(lod))
+ return error(res, 400, 'validation_error', 'lod must be 0|1|2');
+ if (textureSize != null && !VALID_TEX.has(textureSize))
+ return error(res, 400, 'validation_error', 'textureSize must be 128|256|512|1024|2048');
+ if (morphs != null && !VALID_MORPHS.has(morphs))
+ return error(res, 400, 'validation_error', 'morphs must be arkit52|all');
+ if (!VALID_BG.has(bg))
+ return error(res, 400, 'validation_error', 'bg must be transparent|dark|light');
+ if (!VALID_MOCAP.has(mocap))
+ return error(res, 400, 'validation_error', 'mocap must be off|webcam');
+
+ const [user] = await sql`
+ select id, username, display_name
+ from users
+ where lower(username) = ${username} and deleted_at is null
+ limit 1
+ `;
+ if (!user) return error(res, 404, 'not_found', 'user not found');
+
+ const [avatar] = await sql`
+ select id, slug, name, description,
+ storage_key, baked_storage_key, baked_at, appearance_hash,
+ thumbnail_key, size_bytes, source, version,
+ tags, created_at, updated_at
+ from avatars
+ where owner_id = ${user.id}
+ and visibility = 'public'
+ and deleted_at is null
+ order by updated_at desc nulls last, created_at desc
+ limit 1
+ `;
+ if (!avatar) return error(res, 404, 'not_found', 'user has no public avatar');
+
+ // Base storage key — prefer the baked (dressed) version when fresh.
+ const sourceKey =
+ baked && avatar.baked_storage_key ? avatar.baked_storage_key : avatar.storage_key;
+ const baseModelUrl = publicUrl(sourceKey);
+
+ const origin = originFor(req);
+
+ // model_url — optimization-knob URL. If no optimization params, hand back
+ // the raw R2 URL (CDN-cached). Otherwise route through /api/avatar/optimize.
+ let modelUrl = baseModelUrl;
+ const transcode = lod != null || textureSize != null || morphs != null || draco === '1';
+ if (transcode && origin) {
+ const u = new URL(origin + '/api/avatar/optimize');
+ u.searchParams.set('id', avatar.id);
+ if (lod != null) u.searchParams.set('lod', lod);
+ if (textureSize != null) u.searchParams.set('textureSize', textureSize);
+ if (morphs != null) u.searchParams.set('morphs', morphs);
+ if (draco === '1') u.searchParams.set('draco', '1');
+ modelUrl = u.toString();
+ }
+
+ // embed_url — points at /embed/avatar/:username so the script-tag and
+ // iframe both land on the same Vite entry. URL params control bg, idle,
+ // mocap, and any optimization knobs.
+ let embedUrl = '';
+ if (origin) {
+ const u = new URL(origin + `/embed/avatar/${user.username}`);
+ if (lod != null) u.searchParams.set('lod', lod);
+ if (textureSize != null) u.searchParams.set('textureSize', textureSize);
+ if (morphs != null) u.searchParams.set('morphs', morphs);
+ if (draco === '1') u.searchParams.set('draco', '1');
+ if (bg !== 'transparent') u.searchParams.set('bg', bg);
+ if (idle !== 'on') u.searchParams.set('idle', idle);
+ if (mocap !== 'off') u.searchParams.set('mocap', mocap);
+ if (!baked) u.searchParams.set('baked', '0');
+ embedUrl = u.toString();
+ }
+
+ res.setHeader('Cache-Control', 'public, s-maxage=60, stale-while-revalidate=300');
+ return json(res, 200, {
+ user: {
+ username: user.username,
+ display_name: user.display_name || user.username,
+ },
+ avatar: {
+ id: avatar.id,
+ slug: avatar.slug,
+ name: avatar.name,
+ description: avatar.description,
+ thumbnail_url: avatar.thumbnail_key ? publicUrl(avatar.thumbnail_key) : null,
+ model_url: modelUrl,
+ base_model_url: baseModelUrl,
+ size_bytes: Number(avatar.size_bytes || 0),
+ source: avatar.source,
+ version: avatar.version,
+ tags: avatar.tags || [],
+ created_at: avatar.created_at,
+ updated_at: avatar.updated_at,
+ baked: baked && !!avatar.baked_storage_key,
+ },
+ embed_url: embedUrl,
+ embed: {
+ script: origin
+ ? `<script async src="${origin}/embed.js" data-avatar="@${user.username}"></script>`
+ : '',
+ iframe: embedUrl
+ ? `<iframe src="${embedUrl}" width="420" height="600" frameborder="0" allow="autoplay; camera; clipboard-write; xr-spatial-tracking" style="border-radius:12px;"></iframe>`
+ : '',
+ },
+ });
+});
diff --git a/api/widgets/[id].js b/api/widgets/[id].js
index d1a061f84..cd90caf20 100644
--- a/api/widgets/[id].js
+++ b/api/widgets/[id].js
@@ -20,14 +20,7 @@ import { parse } from '../_lib/validate.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
import { decorate } from './index.js';
import { isDemoWidgetId, getDemoWidget } from './_demo-fixtures.js';
-
-const WIDGET_TYPES = [
- 'turntable',
- 'animation-gallery',
- 'talking-agent',
- 'passport',
- 'hotspot-tour',
-];
+import { WIDGET_TYPES } from '../_lib/widget-types.js';
const patchSchema = z.object({
name: z.string().trim().min(1).max(120).optional(),
diff --git a/api/widgets/[id]/[action].js b/api/widgets/[id]/[action].js
index 9d85ea0ef..b3c4c7b93 100644
--- a/api/widgets/[id]/[action].js
+++ b/api/widgets/[id]/[action].js
@@ -8,18 +8,17 @@ import crypto from 'node:crypto';
import { z } from 'zod';
import { sql } from '../../_lib/db.js';
-import {
- getSessionUser,
- authenticateBearer,
- extractBearer,
- hasScope,
-} from '../../_lib/auth.js';
+import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../../_lib/auth.js';
import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';
import { parse } from '../../_lib/validate.js';
import { limits, clientIp } from '../../_lib/rate-limit.js';
import { captureException } from '../../_lib/sentry.js';
import { isDemoWidgetId, getDemoWidget } from '../_demo-fixtures.js';
import { decorate } from '../index.js';
+import { redactPii } from '../../_lib/pii.js';
+import { embed, cosine, embeddingsConfigured } from '../../_lib/embeddings.js';
+import { listTranscripts, getTranscript } from './_transcripts.js';
+import { listKnowledge, ingestKnowledge, deleteKnowledge } from './_knowledge.js';
export default wrap(async (req, res) => {
const action = req.query?.action;
@@ -30,6 +29,10 @@ export default wrap(async (req, res) => {
return handleDuplicate(req, res);
case 'stats':
return handleStats(req, res);
+ case 'transcripts':
+ return handleTranscripts(req, res);
+ case 'knowledge':
+ return handleKnowledge(req, res);
default:
return error(res, 404, 'not_found', 'unknown widget action');
}
@@ -90,6 +93,22 @@ const chatBody = z.object({
)
.max(40)
.default([]),
+ // Cookieless visitor + thread identifiers, minted client-side. We only
+ // store them — they're opaque to us and never joined against user data.
+ visitor_id: z
+ .string()
+ .trim()
+ .min(8)
+ .max(64)
+ .regex(/^[A-Za-z0-9_-]+$/)
+ .optional(),
+ thread_id: z
+ .string()
+ .trim()
+ .min(8)
+ .max(64)
+ .regex(/^[A-Za-z0-9_-]+$/)
+ .optional(),
});
const SKILL_TOOLS = [
@@ -181,6 +200,14 @@ async function handleChat(req, res) {
}
const allowedSkills = filterSkills(cfg.skills);
+ // Pull grounding chunks before we open the stream so latency stays in one
+ // place rather than blocking after the visitor sees "typing…".
+ const knowledgeBlock = await retrieveKnowledge(widget.id, body.message).catch((err) => {
+ if (process.env.DEBUG === 'true')
+ console.warn('[widget-chat] knowledge retrieve', err?.message);
+ return null;
+ });
+
// Open SSE stream.
res.statusCode = 200;
res.setHeader('content-type', 'text/event-stream; charset=utf-8');
@@ -190,8 +217,10 @@ async function handleChat(req, res) {
// Flush headers immediately so the client opens the stream.
res.flushHeaders?.();
+ let result;
+ let usedProvider = provider;
+ let usedModel = requestedModel || null;
try {
- let result;
if (provider === 'none') {
result = { reply: nonePatternReply(body.message, cfg), actions: [] };
} else if (provider === 'custom') {
@@ -200,16 +229,17 @@ async function handleChat(req, res) {
const route = pickProvider(provider, requestedModel);
if (!route) {
result = {
- reply:
- "I'm not configured to answer just yet — no chat provider key is set on this site.",
+ reply: "I'm not configured to answer just yet — no chat provider key is set on this site.",
actions: [],
};
} else {
+ usedProvider = route.name;
+ usedModel = route.model;
result = await callLLM({
route,
message: body.message,
history: body.history,
- systemPrompt: buildSystemPrompt(cfg, widget),
+ systemPrompt: buildSystemPrompt(cfg, widget, knowledgeBlock),
temperature: Number(cfg.temperature) || 0.7,
maxTurns: Math.min(20, Math.max(1, Number(cfg.maxTurns) || 20)),
allowedSkills,
@@ -229,8 +259,20 @@ async function handleChat(req, res) {
res.end();
}
- // Best-effort telemetry — count only, never content.
- logChatEvent(widgetId).catch(() => {});
+ // Persist the turn off the response path — never block the visitor on a
+ // telemetry write, and never let a write failure leak as a 500.
+ persistTurn({
+ widgetId,
+ req,
+ body,
+ userMessage: body.message,
+ reply: result?.reply || '',
+ actions: result?.actions || [],
+ provider: usedProvider,
+ model: usedModel,
+ }).catch((err) => {
+ if (process.env.DEBUG === 'true') console.warn('[widget-chat] persist', err?.message);
+ });
}
// ── Brain dispatchers ──────────────────────────────────────────────────────
@@ -438,7 +480,7 @@ function nonePatternReply(message, cfg) {
// ── Helpers ─────────────────────────────────────────────────────────────────
-function buildSystemPrompt(cfg, widget) {
+function buildSystemPrompt(cfg, widget, knowledgeBlock) {
const ownerPrompt = (cfg.systemPrompt || '').trim();
const name = (cfg.agentName || widget.name || 'Agent').slice(0, 80);
const title = (cfg.agentTitle || 'AI Agent').slice(0, 80);
@@ -452,6 +494,15 @@ function buildSystemPrompt(cfg, widget) {
if (ownerPrompt) {
lines.push('', '<owner-instructions>', ownerPrompt, '</owner-instructions>');
}
+ if (knowledgeBlock) {
+ lines.push(
+ '',
+ '<reference-material>',
+ "The following excerpts come from the site owner's uploaded knowledge base. Ground your answer in them when relevant. Cite the source title in your reply when you quote from it.",
+ knowledgeBlock,
+ '</reference-material>',
+ );
+ }
return lines.join('\n');
}
@@ -522,20 +573,133 @@ async function loadWidget(id) {
}
}
-async function logChatEvent(widgetId) {
+// ── Transcript ingest ───────────────────────────────────────────────────────
+//
+// One thread per (visitor_id × thread_id). If the visitor sent neither — older
+// embed runtime, opt-out, or a client that strips storage — we synthesize a
+// random thread so the turn still lands in widget_chat_messages and the
+// creator's "messages today" counter is accurate, even if it can't be grouped.
+async function persistTurn({ widgetId, req, body, userMessage, reply, actions, provider, model }) {
+ const visitorId = body.visitor_id || `anon_${crypto.randomBytes(6).toString('base64url')}`;
+ const threadId = body.thread_id || `wct_${crypto.randomBytes(9).toString('base64url')}`;
+
+ const refererHost = parseRefererHost(req.headers.referer || req.headers.origin);
+ const country = headerValue(req, 'x-vercel-ip-country') || null;
+ const uaHash = uaFingerprint(req.headers['user-agent']);
+
+ const userRedacted = redactPii(userMessage);
+ const replyRedacted = redactPii(reply || '');
+
try {
+ // Upsert thread. `last_message_at` always bumps; everything else is
+ // preserved from the first turn so the creator sees the original
+ // referrer/country/UA hash even if the visitor switches tabs mid-thread.
+ await sql`
+ insert into widget_chat_threads
+ (id, widget_id, visitor_id, referer_host, country, user_agent_hash, message_count, started_at, last_message_at)
+ values
+ (${threadId}, ${widgetId}, ${visitorId}, ${refererHost}, ${country}, ${uaHash}, 2, now(), now())
+ on conflict (id) do update set
+ message_count = widget_chat_threads.message_count + 2,
+ last_message_at = excluded.last_message_at
+ `;
+
await sql`
- insert into widget_chat_events (widget_id, created_at)
- values (${widgetId}, now())
+ insert into widget_chat_messages (thread_id, widget_id, role, content, redacted, created_at)
+ values (${threadId}, ${widgetId}, 'user', ${userRedacted.content}, ${userRedacted.redacted}, now())
`;
+ if (reply) {
+ await sql`
+ insert into widget_chat_messages
+ (thread_id, widget_id, role, content, actions, provider, model, redacted, created_at)
+ values
+ (${threadId}, ${widgetId}, 'assistant', ${replyRedacted.content},
+ ${JSON.stringify(actions || [])}::jsonb, ${provider || null}, ${model || null},
+ ${replyRedacted.redacted}, now())
+ `;
+ }
} catch (err) {
- // Table is optional — Prompt 06 owns the migration. Stay quiet on missing-table.
+ // Missing-table is the only "expected" failure (migrations not applied yet).
if (!/relation .* does not exist/i.test(err?.message || '')) {
- console.warn('[widget-chat] log failed', err?.message);
+ console.warn('[widget-chat] persist failed', err?.message);
}
}
}
+// ── Knowledge retrieval ─────────────────────────────────────────────────────
+//
+// For talking-agent widgets, pull the top-K chunks for the visitor's message
+// from widget_knowledge_chunks. We compute cosine similarity in JS — fine for
+// the low-thousands-of-chunks scale a single widget will ever hit. If a widget
+// outgrows that, swap embedding storage to pgvector with one column rewrite.
+const RETRIEVAL_TOP_K = 3;
+const RETRIEVAL_MIN_SCORE = 0.18;
+const RETRIEVAL_MAX_CHARS = 4_500; // ~ 1100 tokens, keeps room for chat history
+
+async function retrieveKnowledge(widgetId, message) {
+ if (!message || !embeddingsConfigured()) return null;
+
+ let rows;
+ try {
+ rows = await sql`
+ select c.id, c.doc_id, c.content, c.embedding,
+ d.title, d.source_url, d.source_type
+ from widget_knowledge_chunks c
+ join widget_knowledge_docs d on d.id = c.doc_id
+ where c.widget_id = ${widgetId}
+ `;
+ } catch (err) {
+ if (/relation .* does not exist/i.test(err?.message || '')) return null;
+ throw err;
+ }
+ if (!rows.length) return null;
+
+ const [queryEmbedding] = await embed([message]);
+ const scored = rows
+ .map((r) => {
+ const e = Array.isArray(r.embedding) ? r.embedding : r.embedding?.values || [];
+ return { ...r, score: cosine(queryEmbedding, e) };
+ })
+ .filter((r) => r.score >= RETRIEVAL_MIN_SCORE)
+ .sort((a, b) => b.score - a.score)
+ .slice(0, RETRIEVAL_TOP_K);
+
+ if (!scored.length) return null;
+
+ const lines = [];
+ let total = 0;
+ for (const r of scored) {
+ const header = r.source_url
+ ? `[Source: ${r.title} — ${r.source_url}]`
+ : `[Source: ${r.title}]`;
+ const block = `${header}\n${r.content.trim()}`;
+ if (total + block.length > RETRIEVAL_MAX_CHARS) break;
+ lines.push(block);
+ total += block.length;
+ }
+ return lines.join('\n\n');
+}
+
+function parseRefererHost(referer) {
+ if (!referer) return null;
+ try {
+ return new URL(referer).hostname || null;
+ } catch {
+ return null;
+ }
+}
+
+function headerValue(req, name) {
+ const v = req.headers[name];
+ if (Array.isArray(v)) return v[0] || null;
+ return v || null;
+}
+
+function uaFingerprint(ua) {
+ if (!ua) return null;
+ return crypto.createHash('sha256').update(String(ua)).digest('hex').slice(0, 16);
+}
+
function writeSse(res, event, data) {
res.write(`event: ${event}\n`);
res.write(`data: ${JSON.stringify(data)}\n\n`);
@@ -715,12 +879,16 @@ async function lastViewedAt(id) {
}
}
-// Talking-agent widget chats live in agent_actions (Prompt 03 will wire this).
-// Until that table-or-source is finalized, return null so the UI knows to hide
-// the chat stat line for non-talking-agent types and for un-instrumented ones.
-async function chatCountFor(_id, type) {
+async function chatCountFor(id, type) {
if (type !== 'talking-agent') return null;
- return null;
+ try {
+ const rows =
+ await sql`select count(*)::bigint as n from widget_chat_messages where widget_id = ${id}`;
+ return Number(rows[0]?.n || 0);
+ } catch (err) {
+ if (/relation .* does not exist/i.test(err?.message || '')) return null;
+ throw err;
+ }
}
function startOfUtcDay(d) {
@@ -741,3 +909,136 @@ async function resolveStatsAuth(req) {
return { userId: session.id, source: 'session', scope: 'avatars:read avatars:write' };
return await authenticateBearer(extractBearer(req));
}
+
+// ── transcripts (talking-agent only) ────────────────────────────────────────
+
+async function handleTranscripts(req, res) {
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const id = actionIdFromReq(req, 'transcripts');
+ if (!id) return error(res, 400, 'invalid_request', 'id required');
+
+ const auth = await resolveOwnerAuth(req, 'avatars:read');
+ if (!auth.error) {
+ const [w] = await sql`
+ select id from widgets
+ where id = ${id} and user_id = ${auth.userId} and deleted_at is null limit 1
+ `;
+ if (!w) return error(res, 404, 'not_found', 'widget not found or not yours');
+ } else {
+ return auth.error(res);
+ }
+
+ const url = new URL(req.url, 'http://x');
+ const threadId = url.searchParams.get('thread_id');
+ if (threadId) {
+ const data = await getTranscript(id, threadId);
+ if (!data) return error(res, 404, 'not_found', 'thread not found');
+ res.setHeader('cache-control', 'private, max-age=10');
+ return json(res, 200, data);
+ }
+
+ const limit = Math.min(100, Math.max(1, parseInt(url.searchParams.get('limit') || '25', 10)));
+ const before = url.searchParams.get('before') || null;
+ const data = await listTranscripts(id, { limit, before });
+ res.setHeader('cache-control', 'private, max-age=10');
+ return json(res, 200, data);
+}
+
+// ── knowledge (talking-agent only) ──────────────────────────────────────────
+
+async function handleKnowledge(req, res) {
+ if (cors(req, res, { methods: 'GET,POST,DELETE,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET', 'POST', 'DELETE'])) return;
+
+ const id = actionIdFromReq(req, 'knowledge');
+ if (!id) return error(res, 400, 'invalid_request', 'id required');
+
+ const needed = req.method === 'GET' ? 'avatars:read' : 'avatars:write';
+ const auth = await resolveOwnerAuth(req, needed);
+ if (auth.error) return auth.error(res);
+
+ const [w] = await sql`
+ select id, type from widgets
+ where id = ${id} and user_id = ${auth.userId} and deleted_at is null limit 1
+ `;
+ if (!w) return error(res, 404, 'not_found', 'widget not found or not yours');
+
+ if (req.method === 'GET') {
+ const out = await listKnowledge(id);
+ res.setHeader('cache-control', 'private, max-age=15');
+ return json(res, 200, out);
+ }
+
+ if (req.method === 'DELETE') {
+ const url = new URL(req.url, 'http://x');
+ const docId = url.searchParams.get('doc_id');
+ if (!docId) return error(res, 400, 'invalid_request', 'doc_id required');
+ const ok = await deleteKnowledge({ widgetId: id, userId: auth.userId, docId });
+ if (!ok) return error(res, 404, 'not_found', 'doc not found');
+ return json(res, 200, { ok: true });
+ }
+
+ if (w.type !== 'talking-agent') {
+ return error(
+ res,
+ 400,
+ 'invalid_widget_type',
+ 'knowledge upload is only available for talking-agent widgets',
+ );
+ }
+
+ const rl = await limits.upload(auth.userId);
+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many uploads — try again later');
+
+ let body;
+ try {
+ body = await readJson(req);
+ } catch (err) {
+ return error(res, err.status || 400, 'invalid_request', err.message);
+ }
+
+ try {
+ const doc = await ingestKnowledge({ widgetId: id, userId: auth.userId, input: body });
+ return json(res, 201, { doc });
+ } catch (err) {
+ return error(
+ res,
+ err.status || 400,
+ err.code || 'ingest_failed',
+ err.message || 'ingest failed',
+ );
+ }
+}
+
+// ── Shared helpers for the new action handlers ──────────────────────────────
+
+function actionIdFromReq(req, action) {
+ const fromQuery = req.query?.id;
+ if (typeof fromQuery === 'string' && fromQuery) return fromQuery;
+ const path = new URL(req.url, 'http://x').pathname;
+ const re = new RegExp(`/api/widgets/([^/]+)/${action}`);
+ const m = path.match(re);
+ return m ? decodeURIComponent(m[1]) : null;
+}
+
+async function resolveOwnerAuth(req, requiredScope) {
+ const session = await getSessionUser(req);
+ if (session)
+ return {
+ userId: session.id,
+ source: 'session',
+ scope: 'avatars:read avatars:write avatars:delete',
+ };
+ const bearer = await authenticateBearer(extractBearer(req));
+ if (!bearer) {
+ return { error: (res) => error(res, 401, 'unauthorized', 'authentication required') };
+ }
+ if (!hasScope(bearer.scope, requiredScope)) {
+ return {
+ error: (res) => error(res, 403, 'insufficient_scope', `${requiredScope} required`),
+ };
+ }
+ return bearer;
+}
diff --git a/api/widgets/[id]/_knowledge.js b/api/widgets/[id]/_knowledge.js
new file mode 100644
index 000000000..91c3c867c
--- /dev/null
+++ b/api/widgets/[id]/_knowledge.js
@@ -0,0 +1,242 @@
+// Knowledge ingest + list + delete for the talking-agent widget. Accepts:
+// { source_type: 'url', source_url: 'https://…', title?: '…' }
+// { source_type: 'text', content: '…', title: '…' }
+// { source_type: 'pdf', content: '<extracted>', title: '…', source_url?: '…', byte_size?: n }
+//
+// PDFs are extracted client-side (pdfjs in the studio bundle) and posted as
+// text — the server never decodes binary PDFs, which keeps this route in the
+// edge-friendly fetch-only path.
+
+import { z } from 'zod';
+
+import { sql } from '../../_lib/db.js';
+import { embed, embeddingsConfigured } from '../../_lib/embeddings.js';
+import { chunk, estimateTokens } from '../../_lib/chunker.js';
+import { fetchAndExtract } from '../../_lib/text-extract.js';
+import { shortId } from '../../_lib/ids.js';
+
+const MAX_DOCS_PER_WIDGET = 25;
+const MAX_TEXT_BYTES = 4 * 1024 * 1024;
+const MAX_CHUNKS_PER_DOC = 400;
+const MAX_PREVIEW_QS = 3;
+
+// Embed text in batches of N. text-embedding-3-small accepts up to 2048
+// inputs per call, but 64 keeps memory predictable and lets failures retry
+// at a small unit.
+const EMBED_BATCH = 64;
+
+const baseSchema = z.object({
+ title: z.string().trim().min(1).max(160).optional(),
+ source_type: z.enum(['url', 'text', 'pdf', 'markdown']),
+});
+
+const urlSchema = baseSchema.extend({
+ source_type: z.literal('url'),
+ source_url: z.string().url(),
+});
+
+const textSchema = baseSchema.extend({
+ source_type: z.enum(['text', 'markdown', 'pdf']),
+ content: z.string().min(1).max(MAX_TEXT_BYTES),
+ source_url: z.string().url().optional(),
+ byte_size: z.number().int().nonnegative().optional(),
+});
+
+const docInput = z.discriminatedUnion('source_type', [
+ urlSchema,
+ textSchema.extend({ source_type: z.literal('text') }),
+ textSchema.extend({ source_type: z.literal('markdown') }),
+ textSchema.extend({ source_type: z.literal('pdf') }),
+]);
+
+export async function listKnowledge(widgetId) {
+ const docs = await sql`
+ select id, title, source_type, source_url, byte_size, chunk_count,
+ token_count, status, error, created_at, updated_at
+ from widget_knowledge_docs
+ where widget_id = ${widgetId}
+ order by created_at desc
+ `;
+ return {
+ docs: docs.map((d) => ({
+ id: d.id,
+ title: d.title,
+ source_type: d.source_type,
+ source_url: d.source_url,
+ byte_size: Number(d.byte_size || 0),
+ chunk_count: Number(d.chunk_count || 0),
+ token_count: Number(d.token_count || 0),
+ status: d.status,
+ error: d.error,
+ created_at: d.created_at,
+ updated_at: d.updated_at,
+ })),
+ };
+}
+
+export async function deleteKnowledge({ widgetId, userId, docId }) {
+ const rows = await sql`
+ delete from widget_knowledge_docs
+ where id = ${docId} and widget_id = ${widgetId} and user_id = ${userId}
+ returning id
+ `;
+ return !!rows[0];
+}
+
+export async function ingestKnowledge({ widgetId, userId, input }) {
+ if (!embeddingsConfigured()) {
+ throw httpError(
+ 503,
+ 'embedder_unavailable',
+ 'Knowledge upload needs an OpenAI key on the server (OPENAI_API_KEY).',
+ );
+ }
+
+ const parsed = docInput.safeParse(input);
+ if (!parsed.success) {
+ const msg = parsed.error.issues
+ .map((i) => `${i.path.join('.') || 'body'}: ${i.message}`)
+ .join('; ');
+ throw httpError(400, 'validation_error', msg);
+ }
+ const body = parsed.data;
+
+ const [{ n }] = await sql`
+ select count(*)::int as n from widget_knowledge_docs where widget_id = ${widgetId}
+ `;
+ if (n >= MAX_DOCS_PER_WIDGET) {
+ throw httpError(
+ 400,
+ 'too_many_docs',
+ `Each widget can hold up to ${MAX_DOCS_PER_WIDGET} knowledge docs. Delete one to add another.`,
+ );
+ }
+
+ let title,
+ text,
+ sourceUrl = null,
+ byteSize = 0;
+ if (body.source_type === 'url') {
+ const ext = await fetchAndExtract(body.source_url);
+ title = body.title || ext.title;
+ text = ext.text;
+ sourceUrl = body.source_url;
+ byteSize = ext.byteSize;
+ } else {
+ text = String(body.content || '').trim();
+ title = body.title || autoTitle(text);
+ sourceUrl = body.source_url || null;
+ byteSize = body.byte_size || Buffer.byteLength(text, 'utf8');
+ }
+
+ if (!text || text.length < 12) {
+ throw httpError(400, 'empty_source', 'No readable text was extracted from this source.');
+ }
+
+ const chunks = chunk(text).slice(0, MAX_CHUNKS_PER_DOC);
+ if (!chunks.length) {
+ throw httpError(400, 'empty_source', 'No chunks produced from this source.');
+ }
+
+ const docId = shortId('wkd');
+ const tokenSum = chunks.reduce((s, c) => s + (c.token_count || 0), 0);
+
+ await sql`
+ insert into widget_knowledge_docs
+ (id, widget_id, user_id, title, source_type, source_url, byte_size, chunk_count, token_count, status)
+ values
+ (${docId}, ${widgetId}, ${userId}, ${title.slice(0, 160)}, ${body.source_type},
+ ${sourceUrl}, ${byteSize}, ${chunks.length}, ${tokenSum}, 'processing')
+ `;
+
+ try {
+ for (let i = 0; i < chunks.length; i += EMBED_BATCH) {
+ const slice = chunks.slice(i, i + EMBED_BATCH);
+ const embedded = await embed(slice.map((c) => c.content));
+ for (let j = 0; j < slice.length; j++) {
+ const vec = Array.from(embedded[j]);
+ await sql`
+ insert into widget_knowledge_chunks
+ (doc_id, widget_id, chunk_index, content, embedding, token_count)
+ values
+ (${docId}, ${widgetId}, ${i + j}, ${slice[j].content},
+ ${JSON.stringify(vec)}::jsonb, ${slice[j].token_count})
+ `;
+ }
+ }
+ await sql`update widget_knowledge_docs set status = 'ready' where id = ${docId}`;
+ } catch (err) {
+ await sql`
+ update widget_knowledge_docs
+ set status = 'failed', error = ${String(err?.message || 'embed failed').slice(0, 500)}
+ where id = ${docId}
+ `.catch(() => {});
+ throw httpError(err.status || 502, 'embed_failed', err.message || 'embedding failed');
+ }
+
+ const previewQuestions = synthesizePreviewQs(chunks);
+
+ return {
+ id: docId,
+ title: title.slice(0, 160),
+ source_type: body.source_type,
+ source_url: sourceUrl,
+ byte_size: byteSize,
+ chunk_count: chunks.length,
+ token_count: tokenSum,
+ status: 'ready',
+ preview_questions: previewQuestions,
+ };
+}
+
+// "Your bot now knows X" preview — pulls salient sentences from the first few
+// chunks and reshapes them into starter questions so the creator can sanity-
+// check that the doc landed in retrieval. Heuristic, not LLM-generated.
+function synthesizePreviewQs(chunks) {
+ const sentences = [];
+ for (const c of chunks.slice(0, 3)) {
+ for (const s of String(c.content).split(/(?<=[.!?])\s+/)) {
+ const trimmed = s.trim();
+ if (trimmed.length >= 32 && trimmed.length <= 180) sentences.push(trimmed);
+ }
+ }
+ if (!sentences.length) return [];
+
+ // Pick the longest distinct-prefix sentences first.
+ const seen = new Set();
+ const picked = [];
+ for (const s of sentences.sort((a, b) => b.length - a.length)) {
+ const key = s.slice(0, 40).toLowerCase();
+ if (seen.has(key)) continue;
+ seen.add(key);
+ picked.push(s);
+ if (picked.length >= MAX_PREVIEW_QS) break;
+ }
+
+ return picked.map(toQuestion);
+}
+
+function toQuestion(sentence) {
+ const s = sentence.replace(/[.!?]+$/, '').trim();
+ if (/^(what|when|where|why|how|who|which|can|do|does|is|are)\b/i.test(s)) return s + '?';
+ const noun = s.split(/[.,;:—-]/)[0].trim();
+ return noun
+ ? `What does the doc say about ${lower(noun.slice(0, 80))}?`
+ : `Can you tell me more about this?`;
+}
+
+function lower(s) {
+ return s.charAt(0).toLowerCase() + s.slice(1);
+}
+
+function autoTitle(text) {
+ const firstLine =
+ String(text)
+ .split('\n')
+ .find((l) => l.trim().length > 0) || '';
+ return firstLine.trim().slice(0, 120) || `Pasted text (${estimateTokens(text)} tokens)`;
+}
+
+function httpError(status, code, message) {
+ return Object.assign(new Error(message), { status, code });
+}
diff --git a/api/widgets/[id]/_transcripts.js b/api/widgets/[id]/_transcripts.js
new file mode 100644
index 000000000..da0798680
--- /dev/null
+++ b/api/widgets/[id]/_transcripts.js
@@ -0,0 +1,105 @@
+// Transcripts API helpers — list threads for a widget and fetch one thread's
+// full message log. Both calls assume ownership has been verified by the
+// caller (handleTranscripts in [action].js).
+
+import { sql } from '../../_lib/db.js';
+
+/**
+ * List the N most recent threads for a widget, with the first user line as a
+ * preview. `before` is an ISO timestamp for keyset pagination ("show me
+ * threads older than this last_message_at").
+ */
+export async function listTranscripts(widgetId, { limit = 25, before = null } = {}) {
+ const threads = await sql`
+ select t.id, t.visitor_id, t.referer_host, t.country, t.message_count,
+ t.started_at, t.last_message_at,
+ (select content from widget_chat_messages
+ where thread_id = t.id and role = 'user'
+ order by created_at asc limit 1) as preview,
+ (select count(*) from widget_chat_messages
+ where thread_id = t.id and role = 'user') as user_msgs
+ from widget_chat_threads t
+ where t.widget_id = ${widgetId}
+ and (${before ?? null}::timestamptz is null
+ or t.last_message_at < ${before ?? null}::timestamptz)
+ order by t.last_message_at desc
+ limit ${Math.max(1, Math.min(100, limit))}
+ `;
+
+ const [counts] = await sql`
+ select
+ count(*)::bigint as total_threads,
+ (select count(*) from widget_chat_messages where widget_id = ${widgetId}) as total_messages,
+ count(distinct visitor_id)::bigint as unique_visitors
+ from widget_chat_threads
+ where widget_id = ${widgetId}
+ `;
+
+ return {
+ threads: threads.map(decorateThread),
+ next_cursor: threads.length === limit ? threads[threads.length - 1].last_message_at : null,
+ totals: {
+ threads: Number(counts?.total_threads || 0),
+ messages: Number(counts?.total_messages || 0),
+ unique_visitors: Number(counts?.unique_visitors || 0),
+ },
+ };
+}
+
+/**
+ * Fetch one thread's full message log. Returns null if the thread isn't on
+ * this widget so the caller can 404 cleanly.
+ */
+export async function getTranscript(widgetId, threadId) {
+ const [thread] = await sql`
+ select id, visitor_id, referer_host, country, message_count,
+ started_at, last_message_at
+ from widget_chat_threads
+ where id = ${threadId} and widget_id = ${widgetId}
+ limit 1
+ `;
+ if (!thread) return null;
+
+ const messages = await sql`
+ select id, role, content, actions, provider, model, redacted, created_at
+ from widget_chat_messages
+ where thread_id = ${threadId}
+ order by created_at asc, id asc
+ `;
+
+ return {
+ thread: decorateThread(thread),
+ messages: messages.map((m) => ({
+ id: Number(m.id),
+ role: m.role,
+ content: m.content,
+ actions: Array.isArray(m.actions) ? m.actions : (m.actions ?? null),
+ provider: m.provider,
+ model: m.model,
+ redacted: !!m.redacted,
+ created_at: m.created_at,
+ })),
+ };
+}
+
+function decorateThread(t) {
+ return {
+ id: t.id,
+ visitor_id: t.visitor_id,
+ visitor_label: shortVisitor(t.visitor_id),
+ referer_host: t.referer_host,
+ country: t.country,
+ message_count: Number(t.message_count || 0),
+ user_msg_count: t.user_msgs == null ? null : Number(t.user_msgs),
+ preview: t.preview || null,
+ started_at: t.started_at,
+ last_message_at: t.last_message_at,
+ };
+}
+
+function shortVisitor(id) {
+ if (!id) return 'unknown';
+ if (id.startsWith('anon_')) return 'anon';
+ const tail = id.slice(-4);
+ return `visitor·${tail}`;
+}
diff --git a/api/widgets/[id]/knowledge.js b/api/widgets/[id]/knowledge.js
new file mode 100644
index 000000000..d84b9a078
--- /dev/null
+++ b/api/widgets/[id]/knowledge.js
@@ -0,0 +1,10 @@
+// Route entry for /api/widgets/:id/knowledge — Vercel resolves to this file
+// via the rewrite in vercel.json. Delegates to the action dispatcher so all
+// knowledge logic lives in one place ([action].js → handleKnowledge).
+
+import dispatcher from './[action].js';
+
+export default function handler(req, res) {
+ req.query = { ...(req.query || {}), action: 'knowledge' };
+ return dispatcher(req, res);
+}
diff --git a/api/widgets/[id]/transcripts.js b/api/widgets/[id]/transcripts.js
new file mode 100644
index 000000000..2b16ae9a8
--- /dev/null
+++ b/api/widgets/[id]/transcripts.js
@@ -0,0 +1,10 @@
+// Route entry for /api/widgets/:id/transcripts — Vercel resolves to this file
+// via the rewrite in vercel.json. Delegates to the action dispatcher so all
+// transcript logic lives in one place ([action].js → handleTranscripts).
+
+import dispatcher from './[action].js';
+
+export default function handler(req, res) {
+ req.query = { ...(req.query || {}), action: 'transcripts' };
+ return dispatcher(req, res);
+}
diff --git a/api/widgets/_demo-fixtures.js b/api/widgets/_demo-fixtures.js
index a3398b0d0..d18027778 100644
--- a/api/widgets/_demo-fixtures.js
+++ b/api/widgets/_demo-fixtures.js
@@ -163,6 +163,43 @@ export const DEMO_WIDGETS = {
maxCards: 8,
},
}),
+
+ wdgt_demo_koltrad: fixture({
+ id: 'wdgt_demo_koltrad',
+ type: 'kol-trades',
+ name: 'Smart Money Feed',
+ modelUrl: CZ,
+ config: {
+ background: '#0a0a0a',
+ accent: '#8b5cf6',
+ caption: '',
+ showControls: false,
+ autoRotate: false,
+ envPreset: 'neutral',
+ mint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
+ limit: 20,
+ refreshMs: 30_000,
+ },
+ }),
+
+ wdgt_demo_livetrd: fixture({
+ id: 'wdgt_demo_livetrd',
+ type: 'live-trades-canvas',
+ name: 'Live Trades Canvas',
+ modelUrl: CZ,
+ config: {
+ background: '#0a0a0a',
+ accent: '#8b5cf6',
+ caption: '',
+ showControls: false,
+ autoRotate: false,
+ envPreset: 'neutral',
+ mint: 'So11111111111111111111111111111111111111112',
+ chain: 'solana',
+ bg: '#0d0d14',
+ minUsd: 0,
+ },
+ }),
};
export function isDemoWidgetId(id) {
diff --git a/api/widgets/index.js b/api/widgets/index.js
index 6346cdbad..d8d43068f 100644
--- a/api/widgets/index.js
+++ b/api/widgets/index.js
@@ -17,14 +17,7 @@ import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';
import { parse } from '../_lib/validate.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
import { publicUrl } from '../_lib/r2.js';
-
-const WIDGET_TYPES = [
- 'turntable',
- 'animation-gallery',
- 'talking-agent',
- 'passport',
- 'hotspot-tour',
-];
+import { WIDGET_TYPES } from '../_lib/widget-types.js';
const createBody = z.object({
type: z.enum(WIDGET_TYPES),
diff --git a/api/widgets/oembed.js b/api/widgets/oembed.js
index 6adb4326a..06776f218 100644
--- a/api/widgets/oembed.js
+++ b/api/widgets/oembed.js
@@ -45,7 +45,7 @@ export default wrap(async (req, res) => {
if (!widget) return error(res, 404, 'not_found', 'widget not found');
const origin = env.APP_ORIGIN;
- const embedUrl = `${origin}/app#widget=${widget.id}&kiosk=true`;
+ const embedUrl = `${origin}/widget#widget=${widget.id}&kiosk=true`;
const pageUrl = `${origin}/w/${widget.id}`;
const thumbUrl = `${origin}/api/widgets/${widget.id}/og`;
const title = widget.name || 'Widget';
@@ -125,8 +125,13 @@ function extractWidgetId(target) {
const pathMatch = parsed.pathname.match(/^\/w\/([A-Za-z0-9_-]+)\/?$/);
if (pathMatch) return pathMatch[1];
- // Accept both legacy /#widget=<id> and current /app#widget=<id> forms.
- if (parsed.hash && (parsed.pathname === '/' || parsed.pathname === '/app')) {
+ // Accept legacy /#widget=<id>, the /app#widget=<id> SPA form, and the
+ // current /widget#widget=<id> slim shell — embedders may have copied any
+ // of them. All three resolve to the same widget id.
+ if (
+ parsed.hash &&
+ (parsed.pathname === '/' || parsed.pathname === '/app' || parsed.pathname === '/widget')
+ ) {
const hashMatch = parsed.hash.match(/(?:^|[#&])widget=([A-Za-z0-9_-]+)/);
if (hashMatch) return hashMatch[1];
}
diff --git a/api/widgets/page.js b/api/widgets/page.js
index c4e20f811..e08ad9d6c 100644
--- a/api/widgets/page.js
+++ b/api/widgets/page.js
@@ -111,7 +111,7 @@ export default wrap(async (req, res) => {
return;
}
- const embedUrl = `${origin}/app#widget=${widget.id}&kiosk=true`;
+ const embedUrl = `${origin}/widget#widget=${widget.id}&kiosk=true`;
const oembedJs = `${origin}/api/widgets/oembed?url=${encodeURIComponent(pageUrl)}&format=json`;
const title = widget.name || 'Widget';
const typeLbl = TYPE_LABEL[widget.type] || 'Widget';
diff --git a/pages/a-embed.html b/pages/a-embed.html
index cc0c87554..cd637ac39 100644
--- a/pages/a-embed.html
+++ b/pages/a-embed.html
@@ -123,6 +123,20 @@
body.bg-light {
background: #f5f5f5;
}
+ /* OBS browser-source: solid chromakey colour for streamers whose
+ compositor can't keep alpha. ?chromakey=%2300ff00 → bg green. */
+ body.bg-chromakey {
+ background: var(--chromakey-color, #00ff00) !important;
+ }
+ /* ?hide-chrome=1 — for kiosk / OBS / app-shell usage where the
+ embed is the whole frame and chrome (name plate, link, etc) is
+ redundant. Doesn't affect postMessage handshake. */
+ body.hide-chrome #name-plate,
+ body.hide-chrome #chain-plate,
+ body.hide-chrome #open-link,
+ body.hide-chrome #loading {
+ display: none !important;
+ }
body.bg-light #name-plate {
color: rgba(0, 0, 0, 0.65);
text-shadow: none;
@@ -159,14 +173,29 @@
const params = new URL(location.href).searchParams;
const bg = params.get('bg') || 'transparent';
- if (bg === 'dark') document.body.classList.add('bg-dark');
- if (bg === 'light') document.body.classList.add('bg-light');
+ const chromakey = params.get('chromakey');
+ if (chromakey) {
+ // Validate hex (#rgb / #rrggbb) or three named colours we
+ // support out of the box. Anything else falls back to the
+ // default OBS green.
+ const safe = /^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i.test(chromakey)
+ ? chromakey
+ : { green: '#00ff00', blue: '#0000ff', magenta: '#ff00ff' }[chromakey.toLowerCase()] ||
+ '#00ff00';
+ document.documentElement.style.setProperty('--chromakey-color', safe);
+ document.body.classList.add('bg-chromakey');
+ } else if (bg === 'dark') document.body.classList.add('bg-dark');
+ else if (bg === 'light') document.body.classList.add('bg-light');
+
+ const hideChrome = params.get('hide-chrome') === '1' || params.get('chrome') === '0';
+ if (hideChrome) document.body.classList.add('hide-chrome');
const avatar = params.get('avatar');
+ const startAnimation = params.get('animation') || params.get('pose') || null;
- const plateOn = params.get('name') !== '0';
- const chainOn = params.get('chain-plate') !== '0';
- const openLinkOn = params.get('open-link') !== '0';
+ const plateOn = !hideChrome && params.get('name') !== '0';
+ const chainOn = !hideChrome && params.get('chain-plate') !== '0';
+ const openLinkOn = !hideChrome && params.get('open-link') !== '0';
// URL: /a/:chainId/:agentId/embed
const ref = parseAgentRef(location.pathname);
@@ -260,6 +289,10 @@
await loadWithFallback(viewer, candidates);
document.getElementById('loading').style.display = 'none';
+ if (startAnimation) {
+ try { await viewer.onGesture({ name: startAnimation, loop: true }); }
+ catch (err) { console.warn('[a-embed] start animation failed', err); }
+ }
postToParent({
__agent: true,
type: 'ready',
@@ -312,6 +345,11 @@
document.getElementById('loading').style.display = 'none';
+ if (startAnimation) {
+ try { await viewer.onGesture({ name: startAnimation, loop: true }); }
+ catch (err) { console.warn('[a-embed] start animation failed', err); }
+ }
+
postToParent({
__agent: true,
type: 'ready',
diff --git a/pages/app-next.html b/pages/app-next.html
new file mode 100644
index 000000000..b00101824
--- /dev/null
+++ b/pages/app-next.html
@@ -0,0 +1,182 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="utf-8" />
+ <meta http-equiv="X-UA-Compatible" content="IE=edge" />
+ <title>three.ws — app-next (UX preview)</title>
+ <meta
+ name="viewport"
+ content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover"
+ />
+ <meta name="robots" content="noindex" />
+ <meta name="theme-color" content="#06070a" />
+
+ <link rel="canonical" href="https://three.ws/app-next" />
+ <link rel="shortcut icon" href="/favicon.ico" />
+ <link rel="stylesheet" href="/style.css" />
+ <link rel="stylesheet" href="/fonts/fonts.css" />
+ <link rel="stylesheet" href="/app-next.css" />
+
+ <!-- Re-uses the production app boot (real viewer, real agent system, real animations). -->
+ <script defer type="module" src="/src/app.js"></script>
+ <script defer type="module" src="/src/app-next-overlay.js"></script>
+ </head>
+ <body class="app-next-body">
+ <!-- Minimal glass header — wordmark left, single action right -->
+ <header class="nxt-header">
+ <a class="nxt-brand" href="/" aria-label="three.ws home">
+ <img class="nxt-brand-mark" src="/three.svg" alt="" aria-hidden="true" />
+ <span class="nxt-brand-text">three.ws</span>
+ <span class="nxt-brand-tag">app · next</span>
+ </a>
+
+ <div class="nxt-header-right">
+ <button
+ class="nxt-more"
+ id="nxt-more-btn"
+ type="button"
+ aria-haspopup="true"
+ aria-expanded="false"
+ aria-controls="nxt-more-menu"
+ >
+ <span>Explore</span>
+ <svg viewBox="0 0 12 8" width="10" height="7" aria-hidden="true">
+ <path d="M1 1l5 5 5-5" stroke="currentColor" stroke-width="1.5" fill="none" stroke-linecap="round" stroke-linejoin="round" />
+ </svg>
+ </button>
+ <div class="nxt-more-menu" id="nxt-more-menu" role="menu" hidden>
+ <a href="/discover" role="menuitem">Discover agents</a>
+ <a href="/create" role="menuitem">Create an avatar</a>
+ <a href="/marketplace" role="menuitem">Marketplace</a>
+ <a href="/studio" role="menuitem">Studio</a>
+ <a href="/docs" role="menuitem">Docs</a>
+ <div class="nxt-more-sep" role="separator"></div>
+ <a href="/app" role="menuitem">Open classic viewer</a>
+ </div>
+
+ <!-- Auth surface — single pill, swaps to user chip when signed in -->
+ <div class="nxt-auth">
+ <a class="nxt-signin" id="nav-sign-in" href="/login">Sign in</a>
+ <div class="nav-user-wrap" id="nav-user-wrap" hidden>
+ <button
+ class="nxt-user-btn nav-user"
+ id="nav-user-btn"
+ type="button"
+ aria-haspopup="true"
+ aria-expanded="false"
+ >
+ <span class="nxt-user-dot" aria-hidden="true"></span>
+ <span id="nav-user-label">Account</span>
+ </button>
+ <div class="nav-user-menu nxt-user-menu" id="nav-user-menu" role="menu" hidden>
+ <a href="/profile" id="nav-my-profile-link" role="menuitem">My profile</a>
+ <a href="/dashboard" role="menuitem">Dashboard</a>
+ <a href="/settings" role="menuitem">Settings</a>
+ <div class="nxt-user-sep" role="separator"></div>
+ <button id="nav-sign-out-btn" type="button" role="menuitem">Sign out</button>
+ </div>
+ </div>
+ </div>
+ </div>
+ </header>
+
+ <!-- Main viewer surface — full bleed, the avatar IS the page -->
+ <main class="wrap nxt-main">
+ <!-- The 3D viewer (required by app.js) -->
+ <div class="viewer-container nxt-viewer" id="viewer-container"></div>
+
+ <!-- Floor glow + edge vignette (CSS only, sits behind the canvas via z-index) -->
+ <div class="nxt-stage-floor" aria-hidden="true"></div>
+ <div class="nxt-stage-vignette" aria-hidden="true"></div>
+
+ <!-- Rotating "Try …" invitation — floats above the bottom bar -->
+ <div class="nxt-try-pill" id="nxt-try-pill" hidden>
+ <span class="nxt-try-pill__label">Try</span>
+ <button class="nxt-try-pill__btn" id="nxt-try-pill-btn" type="button">
+ <span class="nxt-try-pill__icon" id="nxt-try-pill-icon">👋</span>
+ <span class="nxt-try-pill__name" id="nxt-try-pill-name">Wave</span>
+ </button>
+ <button
+ class="nxt-try-pill__next"
+ id="nxt-try-pill-next"
+ type="button"
+ aria-label="Suggest another"
+ title="Suggest another"
+ >
+ <svg viewBox="0 0 16 16" width="12" height="12" aria-hidden="true">
+ <path d="M2 8h12M9 3l5 5-5 5" stroke="currentColor" stroke-width="1.6" fill="none" stroke-linecap="round" stroke-linejoin="round" />
+ </svg>
+ </button>
+ </div>
+
+ <!-- Bottom action bar — single hierarchy, no competing CTAs -->
+ <div class="nxt-action-bar">
+ <button
+ class="nxt-action nxt-action--ghost"
+ id="nxt-anim-btn"
+ type="button"
+ aria-haspopup="true"
+ aria-expanded="false"
+ aria-controls="nxt-anim-sheet"
+ title="Browse animations (A)"
+ >
+ <svg viewBox="0 0 20 20" width="16" height="16" aria-hidden="true">
+ <circle cx="10" cy="10" r="7.5" stroke="currentColor" stroke-width="1.5" fill="none" />
+ <path d="M8 7.5l4.5 2.5L8 12.5z" fill="currentColor" />
+ </svg>
+ <span>Animations</span>
+ <kbd>A</kbd>
+ </button>
+
+ <label class="nxt-action nxt-action--ghost" for="file-input" title="Drop or pick a GLB/glTF (U)">
+ <svg viewBox="0 0 20 20" width="16" height="16" aria-hidden="true">
+ <path d="M10 3v9m-4-4l4-4 4 4M4 15h12" stroke="currentColor" stroke-width="1.5" fill="none" stroke-linecap="round" stroke-linejoin="round" />
+ </svg>
+ <span>Upload model</span>
+ <kbd>U</kbd>
+ <input type="file" name="file-input[]" id="file-input" multiple hidden />
+ </label>
+
+ <button
+ class="nxt-action nxt-action--primary"
+ id="nxt-primary"
+ type="button"
+ >
+ <svg viewBox="0 0 20 20" width="16" height="16" aria-hidden="true">
+ <path d="M5 11l3 3 7-7" stroke="currentColor" stroke-width="2" fill="none" stroke-linecap="round" stroke-linejoin="round" />
+ </svg>
+ <span id="nxt-primary-label">Sign in to save</span>
+ </button>
+ </div>
+
+ <!-- Animation picker sheet — slides up when "Animations" is clicked -->
+ <div class="nxt-anim-sheet" id="nxt-anim-sheet" hidden aria-hidden="true">
+ <div class="nxt-anim-sheet__head">
+ <h2>Animations</h2>
+ <button class="nxt-anim-sheet__close" id="nxt-anim-sheet-close" type="button" aria-label="Close">×</button>
+ </div>
+ <div class="nxt-anim-sheet__filter">
+ <input
+ class="nxt-anim-search"
+ id="nxt-anim-search"
+ type="search"
+ placeholder="Search animations… (idle, wave, jump)"
+ autocomplete="off"
+ />
+ </div>
+ <div class="nxt-anim-grid" id="nxt-anim-grid">
+ <div class="nxt-anim-empty">Loading clips…</div>
+ </div>
+ </div>
+
+ <!-- Spinner required by app.js -->
+ <div class="spinner"></div>
+ </main>
+
+ <!-- Hint chip — only on first visit -->
+ <div class="nxt-first-hint" id="nxt-first-hint" hidden>
+ <span>Click the avatar — try an animation, drag to rotate, scroll to zoom.</span>
+ <button id="nxt-first-hint-close" type="button" aria-label="Dismiss">×</button>
+ </div>
+ </body>
+</html>
diff --git a/pages/app.html b/pages/app.html
index ecd768896..348140ca1 100644
--- a/pages/app.html
+++ b/pages/app.html
@@ -334,6 +334,194 @@
</a>
</div>
<div class="spinner"></div>
+
+ <!-- ─────────────────────────────────────────────────────────────────
+ Next layout chrome — visible only when body[data-layout="next"].
+ Built once on page load; hidden via CSS when the user is on
+ the Classic layout so toggling is a single attribute flip.
+ ──────────────────────────────────────────────────────────── -->
+ <div class="next-chrome" id="next-chrome" aria-hidden="true">
+ <!-- First-interaction swipe affordance, copied from model-viewer.
+ Hides itself after any pointer/wheel/key event on the stage. -->
+ <div class="next-prompt" id="next-prompt" aria-hidden="true">
+ <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round">
+ <path d="M9 11V6a2 2 0 1 1 4 0v4" />
+ <path d="M13 8a2 2 0 1 1 4 0v6" />
+ <path d="M17 10a2 2 0 1 1 4 0v6a6 6 0 0 1-6 6h-2a6 6 0 0 1-6-6v-1l-2-3 1-2 3 1V8a2 2 0 1 1 4 0v3" />
+ </svg>
+ <span>drag to orbit</span>
+ </div>
+
+ <!-- Top-right floating cluster: Controls gear + Share + AR -->
+ <div class="next-corner" id="next-corner">
+ <button
+ class="next-icon-btn"
+ id="next-share-btn"
+ type="button"
+ aria-haspopup="menu"
+ aria-expanded="false"
+ aria-controls="next-share-menu"
+ title="Share, save, deploy"
+ >
+ <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
+ <circle cx="18" cy="5" r="3" />
+ <circle cx="6" cy="12" r="3" />
+ <circle cx="18" cy="19" r="3" />
+ <line x1="8.6" y1="13.5" x2="15.4" y2="17.5" />
+ <line x1="15.4" y1="6.5" x2="8.6" y2="10.5" />
+ </svg>
+ </button>
+
+ <button
+ class="next-icon-btn"
+ id="next-controls-btn"
+ type="button"
+ aria-expanded="false"
+ aria-controls="next-drawer"
+ title="Controls"
+ >
+ <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
+ <circle cx="12" cy="12" r="3" />
+ <path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z" />
+ </svg>
+ </button>
+
+ <button
+ class="next-icon-btn"
+ id="next-fullscreen-btn"
+ type="button"
+ title="Fullscreen"
+ >
+ <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
+ <path d="M3 9V3h6" />
+ <path d="M21 9V3h-6" />
+ <path d="M3 15v6h6" />
+ <path d="M21 15v6h-6" />
+ </svg>
+ </button>
+ </div>
+
+ <!-- Share popover — host for Save/Widget/Deploy/Profile and presence -->
+ <div
+ class="next-share-menu"
+ id="next-share-menu"
+ role="menu"
+ aria-labelledby="next-share-btn"
+ hidden
+ >
+ <div class="next-share-menu__title">Share</div>
+ <button class="next-share-menu__item" id="next-share-save" type="button" role="menuitem" hidden>
+ <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z" /><polyline points="17 21 17 13 7 13 7 21" /><polyline points="7 3 7 8 15 8" /></svg>
+ <span>Save to account</span>
+ </button>
+ <a class="next-share-menu__item" id="next-share-widget" role="menuitem" hidden>
+ <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="7" height="7" rx="1" /><rect x="14" y="3" width="7" height="7" rx="1" /><rect x="3" y="14" width="7" height="7" rx="1" /><rect x="14" y="14" width="7" height="7" rx="1" /></svg>
+ <span>Make this a widget</span>
+ </a>
+ <a class="next-share-menu__item" id="next-share-deploy" role="menuitem" hidden>
+ <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polygon points="12 2 22 8.5 22 15.5 12 22 2 15.5 2 8.5 12 2" /><line x1="12" y1="2" x2="12" y2="22" /><polyline points="22 8.5 12 15.5 2 8.5" /></svg>
+ <span>Deploy on-chain</span>
+ </a>
+ <a class="next-share-menu__item" id="next-share-profile" role="menuitem" target="_blank" rel="noopener" hidden>
+ <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6" /><polyline points="15 3 21 3 21 9" /><line x1="10" y1="14" x2="21" y2="3" /></svg>
+ <span>Public profile</span>
+ </a>
+ <div class="next-share-menu__sep" role="separator"></div>
+ <button class="next-share-menu__item" id="next-share-upload" type="button" role="menuitem">
+ <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" /><polyline points="17 8 12 3 7 8" /><line x1="12" y1="3" x2="12" y2="15" /></svg>
+ <span>Upload model (.glb / .gltf)</span>
+ </button>
+ <a class="next-share-menu__item" href="/create" role="menuitem">
+ <svg viewBox="0 0 24 24" width="14" height="14" fill="currentColor"><path d="M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z" /></svg>
+ <span>Create avatar from selfie</span>
+ </a>
+ </div>
+
+ <!-- Right-side Controls drawer — hosts the dat.GUI panel -->
+ <aside
+ class="next-drawer"
+ id="next-drawer"
+ role="dialog"
+ aria-label="Viewer controls"
+ aria-hidden="true"
+ >
+ <header class="next-drawer__head">
+ <h2 class="next-drawer__title">Controls</h2>
+ <button
+ class="next-drawer__close"
+ id="next-drawer-close"
+ type="button"
+ aria-label="Close controls"
+ >×</button>
+ </header>
+ <div class="next-drawer__body" id="next-drawer-body">
+ <!-- dat.GUI panel is moved here at runtime -->
+ </div>
+ </aside>
+
+ <!-- Bottom command dock: clip name + play/pause + scrubber + clip count -->
+ <section class="next-dock" id="next-dock" aria-label="Playback">
+ <button
+ class="next-dock__clip"
+ id="next-dock-clip"
+ type="button"
+ aria-haspopup="listbox"
+ aria-expanded="false"
+ aria-controls="next-grid"
+ title="Choose animation"
+ >
+ <span class="next-dock__clip-name" id="next-dock-clip-name">—</span>
+ <svg viewBox="0 0 24 24" width="12" height="12" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="next-dock__caret">
+ <polyline points="6 9 12 15 18 9" />
+ </svg>
+ </button>
+
+ <button
+ class="next-dock__play"
+ id="next-dock-play"
+ type="button"
+ aria-label="Play"
+ aria-pressed="false"
+ >
+ <svg class="next-dock__icon next-dock__icon--play" viewBox="0 0 24 24" width="18" height="18" fill="currentColor"><path d="M8 5v14l11-7z" /></svg>
+ <svg class="next-dock__icon next-dock__icon--pause" viewBox="0 0 24 24" width="18" height="18" fill="currentColor"><path d="M6 5h4v14H6zM14 5h4v14h-4z" /></svg>
+ </button>
+
+ <div class="next-dock__scrub" id="next-dock-scrub">
+ <input
+ class="next-dock__scrub-input"
+ id="next-dock-scrub-input"
+ type="range"
+ min="0"
+ max="1000"
+ step="1"
+ value="0"
+ aria-label="Animation timeline"
+ />
+ <div class="next-dock__scrub-fill" id="next-dock-scrub-fill"></div>
+ </div>
+
+ <span class="next-dock__time" id="next-dock-time">0:00 / 0:00</span>
+
+ <button
+ class="next-dock__loop"
+ id="next-dock-loop"
+ type="button"
+ aria-pressed="true"
+ title="Loop"
+ >
+ <svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
+ <polyline points="17 1 21 5 17 9" />
+ <path d="M3 11V9a4 4 0 0 1 4-4h14" />
+ <polyline points="7 23 3 19 7 15" />
+ <path d="M21 13v2a4 4 0 0 1-4 4H3" />
+ </svg>
+ </button>
+ </section>
+
+ <!-- Animation grid that expands upward from the dock -->
+ <div class="next-grid" id="next-grid" role="listbox" aria-label="Animation clips" hidden></div>
+ </div>
</main>
<!-- Golden Ratio dev grid — toggle with Alt+G -->
diff --git a/pages/avatar-embed.html b/pages/avatar-embed.html
new file mode 100644
index 000000000..2b16cc2ab
--- /dev/null
+++ b/pages/avatar-embed.html
@@ -0,0 +1,111 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="utf-8" />
+ <title>Avatar</title>
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <meta name="description" content="Embedded three.ws avatar." />
+ <meta name="robots" content="noindex" />
+ <style>
+ html,
+ body {
+ margin: 0;
+ padding: 0;
+ height: 100%;
+ width: 100%;
+ background: transparent;
+ overflow: hidden;
+ font-family: system-ui, sans-serif;
+ }
+ #stage {
+ position: absolute;
+ inset: 0;
+ }
+ #stage canvas {
+ display: block;
+ width: 100% !important;
+ height: 100% !important;
+ }
+ #stage .gui-wrap,
+ #stage .gui-toggle,
+ #stage .annotation-canvas,
+ #stage .model-info {
+ display: none !important;
+ }
+ #name-plate {
+ position: absolute;
+ left: 12px;
+ bottom: 10px;
+ z-index: 2;
+ pointer-events: none;
+ font-size: 11px;
+ color: rgba(255, 255, 255, 0.55);
+ letter-spacing: 0.04em;
+ text-shadow: 0 1px 2px rgba(0, 0, 0, 0.6);
+ }
+ #error {
+ position: absolute;
+ inset: 0;
+ display: none;
+ align-items: center;
+ justify-content: center;
+ color: rgba(255, 255, 255, 0.4);
+ font-size: 12px;
+ padding: 1rem;
+ text-align: center;
+ }
+ #mocap-pill {
+ position: absolute;
+ right: 10px;
+ top: 10px;
+ z-index: 3;
+ display: none;
+ align-items: center;
+ gap: 6px;
+ padding: 6px 10px;
+ border-radius: 999px;
+ background: rgba(0, 0, 0, 0.55);
+ color: #fff;
+ font-size: 11px;
+ letter-spacing: 0.04em;
+ border: 1px solid rgba(255, 255, 255, 0.18);
+ cursor: pointer;
+ user-select: none;
+ }
+ #mocap-pill .dot {
+ width: 6px;
+ height: 6px;
+ border-radius: 50%;
+ background: #f55;
+ }
+ #mocap-pill.on .dot {
+ background: #5fce6a;
+ }
+ body.bg-dark {
+ background: #0b0d10;
+ }
+ body.bg-light {
+ background: #f5f5f5;
+ }
+ body.bg-light #name-plate {
+ color: rgba(0, 0, 0, 0.55);
+ text-shadow: none;
+ }
+ body.bg-light #mocap-pill {
+ background: rgba(255, 255, 255, 0.85);
+ color: #111;
+ border-color: rgba(0, 0, 0, 0.12);
+ }
+ </style>
+ </head>
+ <body>
+ <div id="stage"></div>
+ <div id="name-plate"></div>
+ <div id="mocap-pill" role="button" tabindex="0" aria-label="Toggle webcam mocap">
+ <span class="dot"></span><span class="label">webcam mocap</span>
+ </div>
+ <div id="error"></div>
+
+ <script type="module" src="/src/avatar-embed.js"></script>
+ </body>
+</html>
diff --git a/pages/avatar-page.html b/pages/avatar-page.html
index faa1f8a88..d0ddf2258 100644
--- a/pages/avatar-page.html
+++ b/pages/avatar-page.html
@@ -324,6 +324,63 @@
}
.av-cta-sec:hover { border-color: var(--text-2); }
+ /* Download menu — anchored to #av-download */
+ .av-download-menu {
+ position: absolute;
+ z-index: 60;
+ width: 280px;
+ background: var(--bg-1, #0f1018);
+ border: 1.5px solid var(--border-2, #1e1f2b);
+ border-radius: 12px;
+ padding: 6px;
+ box-shadow: 0 14px 40px rgba(0, 0, 0, 0.55);
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+ animation: avDlFadeIn 0.16s ease-out;
+ }
+ @keyframes avDlFadeIn {
+ from { opacity: 0; transform: translateY(-4px); }
+ to { opacity: 1; transform: translateY(0); }
+ }
+ .av-download-menu button {
+ appearance: none;
+ background: transparent;
+ border: 1px solid transparent;
+ color: var(--text, #eee);
+ font: inherit;
+ text-align: left;
+ padding: 9px 10px;
+ border-radius: 8px;
+ cursor: pointer;
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+ transition: background 0.12s, border-color 0.12s;
+ }
+ .av-download-menu button:hover {
+ background: rgba(214, 255, 61, 0.07);
+ border-color: rgba(214, 255, 61, 0.3);
+ }
+ .av-download-menu button strong {
+ font-size: 13.5px;
+ font-weight: 600;
+ }
+ .av-download-menu button span {
+ font-size: 11.5px;
+ color: var(--text-3, #8a8d98);
+ line-height: 1.35;
+ }
+ .av-download-status {
+ font-size: 11.5px;
+ color: var(--text-3, #8a8d98);
+ padding: 4px 10px 2px;
+ min-height: 1em;
+ }
+ .av-download-status[data-tone='busy'] { color: #b9c0ff; }
+ .av-download-status[data-tone='ok'] { color: #d6ff3d; }
+ .av-download-status[data-tone='err'] { color: #ffb3b3; }
+
/* ── Tabs ────────────────────────────────────────── */
.av-tabs {
display: flex;
diff --git a/pages/create-review.html b/pages/create-review.html
index 11959d37b..09807dff4 100644
--- a/pages/create-review.html
+++ b/pages/create-review.html
@@ -897,10 +897,10 @@
</button>
</li>
<li>
- <button class="feature-tile" type="button" data-feature="download" aria-label="Download this avatar as GLB or USDZ">
+ <button class="feature-tile" type="button" data-feature="download" aria-label="Download this avatar">
<span class="feature-icon" aria-hidden="true">📦</span>
<span class="feature-name">Download</span>
- <span class="feature-desc">GLB for the web, USDZ for iOS AR</span>
+ <span class="feature-desc">GLB · VRM · USDZ — use it anywhere</span>
<span class="feature-try" aria-hidden="true">Save →</span>
</button>
</li>
diff --git a/pages/create.html b/pages/create.html
index f2c429942..45fcb9bc9 100644
--- a/pages/create.html
+++ b/pages/create.html
@@ -809,10 +809,10 @@
<h2 class="card-title">Selfie to avatar</h2>
</div>
<p class="card-subtitle">
- Three photos — frontal, left, right. three.ws builds a rigged 3D avatar in about a minute.
+ One selfie. About a minute. A rigged 3D avatar that works everywhere.
</p>
<span class="card-cta">
- Take 3 photos
+ Snap a selfie
<svg
width="13"
height="13"
diff --git a/pages/embed-demo.html b/pages/embed-demo.html
new file mode 100644
index 000000000..00fc663ab
--- /dev/null
+++ b/pages/embed-demo.html
@@ -0,0 +1,309 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
+ <title>Embed your avatar · three.ws</title>
+ <meta name="robots" content="noindex" />
+ <meta
+ name="description"
+ content="Drop a three.ws avatar on any site with a single &lt;threews-avatar&gt; tag — transparent, OBS-friendly, programmable."
+ />
+
+ <!-- The SDK. One tag. Registers <threews-avatar> globally. -->
+ <script src="/embed.js" defer></script>
+
+ <style>
+ :root {
+ color-scheme: dark;
+ --bg: #05060a;
+ --panel: #0f1018;
+ --border: #1e1f2b;
+ --text: #eee;
+ --muted: #8a8d98;
+ --accent: #d6ff3d;
+ --accent-ink: #0a0a0a;
+ }
+ * { box-sizing: border-box; }
+ html, body { margin: 0; padding: 0; height: 100%; }
+ body {
+ font: 15px/1.5 -apple-system, system-ui, 'Segoe UI', Roboto, sans-serif;
+ color: var(--text);
+ background: var(--bg);
+ background-image:
+ radial-gradient(800px 500px at 20% -10%, rgba(106, 92, 255, 0.12), transparent 70%),
+ radial-gradient(700px 400px at 110% 110%, rgba(214, 255, 61, 0.07), transparent 70%);
+ }
+ .wrap { max-width: 1100px; margin: 0 auto; padding: 56px 24px 96px; }
+ .eyebrow {
+ color: var(--accent);
+ font-size: 12px;
+ letter-spacing: 0.08em;
+ text-transform: uppercase;
+ margin-bottom: 12px;
+ }
+ h1 {
+ font-size: clamp(28px, 5vw, 42px);
+ letter-spacing: -0.02em;
+ margin: 0 0 12px;
+ font-weight: 600;
+ }
+ .lede { color: var(--muted); max-width: 64ch; margin: 0 0 40px; font-size: 16px; }
+
+ .grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
+ gap: 22px;
+ margin-bottom: 56px;
+ }
+ .card {
+ background: var(--panel);
+ border: 1.5px solid var(--border);
+ border-radius: 14px;
+ padding: 18px;
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+ }
+ .card-head { display: flex; align-items: baseline; justify-content: space-between; gap: 8px; }
+ .card-head h2 {
+ margin: 0;
+ font-size: 14px;
+ font-weight: 600;
+ letter-spacing: -0.005em;
+ }
+ .card-head .tag {
+ font-size: 10px;
+ color: var(--muted);
+ text-transform: uppercase;
+ letter-spacing: 0.08em;
+ }
+ .frame {
+ aspect-ratio: 1 / 1.15;
+ border-radius: 10px;
+ overflow: hidden;
+ background:
+ radial-gradient(70% 50% at 50% 100%, rgba(255, 255, 255, 0.04), transparent 70%),
+ #0a0c12;
+ position: relative;
+ }
+ .frame threews-avatar {
+ width: 100% !important;
+ height: 100% !important;
+ min-width: 0 !important;
+ min-height: 0 !important;
+ aspect-ratio: auto !important;
+ }
+ .frame.chromakey {
+ background: #00ff00; /* OBS streamer preview */
+ }
+ .controls {
+ display: flex;
+ gap: 6px;
+ flex-wrap: wrap;
+ }
+ .controls button {
+ appearance: none;
+ background: rgba(255, 255, 255, 0.04);
+ border: 1px solid var(--border);
+ color: var(--text);
+ border-radius: 8px;
+ padding: 6px 10px;
+ font: inherit;
+ font-size: 12px;
+ cursor: pointer;
+ transition: background 0.15s, border-color 0.15s;
+ }
+ .controls button:hover {
+ background: rgba(214, 255, 61, 0.08);
+ border-color: rgba(214, 255, 61, 0.4);
+ }
+ .snippet {
+ background: #07080d;
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ padding: 10px 12px;
+ font-family: ui-monospace, 'SF Mono', 'Cascadia Code', monospace;
+ font-size: 11.5px;
+ color: #cdd;
+ line-height: 1.5;
+ overflow-x: auto;
+ white-space: pre;
+ }
+ .log {
+ font-family: ui-monospace, 'SF Mono', monospace;
+ font-size: 11px;
+ color: var(--muted);
+ min-height: 1.5em;
+ }
+ .log[data-tone='ok'] { color: var(--accent); }
+ .log[data-tone='err'] { color: #ffb3b3; }
+
+ .snippet-large {
+ background: var(--panel);
+ border: 1.5px solid var(--border);
+ border-radius: 12px;
+ padding: 18px;
+ font-family: ui-monospace, 'SF Mono', monospace;
+ font-size: 13px;
+ color: #cdd;
+ line-height: 1.6;
+ overflow-x: auto;
+ white-space: pre;
+ }
+ .snippet-large .k { color: #d6ff3d; }
+ .snippet-large .a { color: #b9c0ff; }
+ .snippet-large .s { color: #e8b87f; }
+
+ .section-head {
+ display: flex;
+ align-items: baseline;
+ justify-content: space-between;
+ gap: 10px;
+ margin: 8px 0 14px;
+ }
+ .section-head h2 {
+ font-size: 22px;
+ margin: 0;
+ font-weight: 600;
+ letter-spacing: -0.01em;
+ }
+ .section-head .note {
+ color: var(--muted);
+ font-size: 13px;
+ }
+ </style>
+ </head>
+ <body>
+ <div class="wrap">
+ <div class="eyebrow">SDK · v1.0</div>
+ <h1>One tag. Your avatar anywhere.</h1>
+ <p class="lede">
+ Drop <code>&lt;threews-avatar&gt;</code> on Webflow, Framer, React, plain HTML,
+ Squarespace, anywhere. Transparent by default, OBS-ready with a chromakey, and
+ programmable via a small JS API. Examples below run live on this page.
+ </p>
+
+ <div class="section-head">
+ <h2>Live examples</h2>
+ <span class="note">Every avatar below is a real <code>&lt;threews-avatar&gt;</code> mounted from the script tag at the top of this page.</span>
+ </div>
+
+ <div class="grid">
+ <!-- 1) Default — auto-rotate, transparent, no chrome -->
+ <div class="card">
+ <div class="card-head">
+ <h2>Default</h2>
+ <span class="tag">transparent</span>
+ </div>
+ <div class="frame">
+ <threews-avatar
+ id="ex-default"
+ avatar-id="avatar_demo_disk_cz"
+ hide-chrome
+ ></threews-avatar>
+ </div>
+ <div class="controls">
+ <button data-target="ex-default" data-action="play" data-arg="wave">Wave</button>
+ <button data-target="ex-default" data-action="play" data-arg="celebrate">Celebrate</button>
+ <button data-target="ex-default" data-action="play" data-arg="dance">Dance</button>
+ </div>
+ <div class="snippet">&lt;threews-avatar avatar-id="avatar_demo_disk_cz" hide-chrome&gt;&lt;/threews-avatar&gt;</div>
+ <div class="log" id="log-default"></div>
+ </div>
+
+ <!-- 2) Card with name plate -->
+ <div class="card">
+ <div class="card-head">
+ <h2>With name plate</h2>
+ <span class="tag">card mode</span>
+ </div>
+ <div class="frame">
+ <threews-avatar
+ id="ex-card"
+ avatar-id="avatar_demo_disk_cz"
+ bg="dark"
+ ></threews-avatar>
+ </div>
+ <div class="snippet">&lt;threews-avatar avatar-id="…" bg="dark"&gt;&lt;/threews-avatar&gt;</div>
+ <div class="log" id="log-card"></div>
+ </div>
+
+ <!-- 3) OBS browser source — chromakey -->
+ <div class="card">
+ <div class="card-head">
+ <h2>OBS / chromakey</h2>
+ <span class="tag">streamer mode</span>
+ </div>
+ <div class="frame chromakey">
+ <threews-avatar
+ id="ex-obs"
+ avatar-id="avatar_demo_disk_cz"
+ chromakey="#00ff00"
+ hide-chrome
+ pose="wave"
+ ></threews-avatar>
+ </div>
+ <div class="snippet">&lt;threews-avatar avatar-id="…" chromakey="#00ff00"&gt;&lt;/threews-avatar&gt;</div>
+ <div class="log" id="log-obs"></div>
+ </div>
+ </div>
+
+ <div class="section-head">
+ <h2>Copy-paste snippet</h2>
+ <span class="note">Drop this on any page.</span>
+ </div>
+ <div class="snippet-large"><span class="k">&lt;script</span> <span class="a">src</span>=<span class="s">"https://three.ws/embed.js"</span> <span class="a">defer</span><span class="k">&gt;&lt;/script&gt;</span>
+
+<span class="k">&lt;threews-avatar</span>
+ <span class="a">avatar-id</span>=<span class="s">"your-avatar-id"</span>
+ <span class="a">hide-chrome</span>
+ <span class="a">pose</span>=<span class="s">"wave"</span><span class="k">&gt;&lt;/threews-avatar&gt;</span>
+
+<span class="k">&lt;script&gt;</span>
+ <span class="a">const</span> el = document.querySelector(<span class="s">'threews-avatar'</span>);
+ <span class="a">await</span> el.ready;
+ el.play(<span class="s">'celebrate'</span>);
+<span class="k">&lt;/script&gt;</span></div>
+ </div>
+
+ <script>
+ document.addEventListener('click', async (e) => {
+ const btn = e.target.closest('button[data-action]');
+ if (!btn) return;
+ const target = document.getElementById(btn.dataset.target);
+ if (!target) return;
+ const log = document.getElementById('log-' + btn.dataset.target.replace('ex-', ''));
+ try {
+ if (btn.dataset.action === 'play') {
+ await target.play(btn.dataset.arg);
+ if (log) {
+ log.textContent = `played: ${btn.dataset.arg}`;
+ log.dataset.tone = 'ok';
+ }
+ }
+ } catch (err) {
+ if (log) {
+ log.textContent = err.message;
+ log.dataset.tone = 'err';
+ }
+ }
+ });
+
+ // Surface ready/error events into the per-card log line.
+ for (const el of document.querySelectorAll('threews-avatar')) {
+ const log = document.getElementById('log-' + el.id.replace('ex-', ''));
+ el.addEventListener('ready', () => {
+ if (!log) return;
+ log.textContent = 'ready · transparent canvas mounted';
+ log.dataset.tone = 'ok';
+ });
+ el.addEventListener('error', (ev) => {
+ if (!log) return;
+ log.textContent = 'error: ' + (ev.detail?.message || 'unknown');
+ log.dataset.tone = 'err';
+ });
+ }
+ </script>
+ </body>
+</html>
diff --git a/pages/handle.html b/pages/handle.html
new file mode 100644
index 000000000..3ea7e92aa
--- /dev/null
+++ b/pages/handle.html
@@ -0,0 +1,253 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="utf-8" />
+ <title>three.ws</title>
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <meta name="description" content="Live 3D avatar on three.ws — embed me anywhere." />
+ <meta name="theme-color" content="#0b0d10" />
+ <link rel="shortcut icon" href="/favicon.ico" />
+ <link rel="stylesheet" href="/style.css" />
+ <link rel="stylesheet" href="/fonts/fonts.css" />
+
+ <meta property="og:type" content="profile" />
+ <meta property="og:site_name" content="three.ws" />
+ <meta property="og:title" content="three.ws" id="og-title" />
+ <meta property="og:description" content="Live 3D avatar on three.ws." id="og-description" />
+ <meta property="og:image" content="https://three.ws/assets/og-image.png" id="og-image" />
+ <meta name="twitter:card" content="summary_large_image" />
+ <meta name="twitter:title" content="three.ws" id="tw-title" />
+ <meta name="twitter:description" content="Live 3D avatar on three.ws." id="tw-description" />
+ <meta name="twitter:image" content="https://three.ws/assets/og-image.png" id="tw-image" />
+
+ <style>
+ body {
+ margin: 0;
+ background: #0a0c10;
+ color: #e8ecf2;
+ font-family: system-ui, -apple-system, 'Segoe UI', sans-serif;
+ min-height: 100vh;
+ display: flex;
+ flex-direction: column;
+ }
+ .topbar {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 14px 22px;
+ border-bottom: 1px solid rgba(255, 255, 255, 0.06);
+ }
+ .topbar a.brand {
+ color: #fff;
+ text-decoration: none;
+ font-weight: 600;
+ letter-spacing: 0.02em;
+ }
+ .topbar .links {
+ display: flex;
+ gap: 18px;
+ font-size: 14px;
+ }
+ .topbar .links a {
+ color: rgba(255, 255, 255, 0.7);
+ text-decoration: none;
+ }
+ .topbar .links a:hover {
+ color: #fff;
+ }
+
+ main {
+ flex: 1;
+ display: grid;
+ grid-template-columns: minmax(0, 1.1fr) minmax(320px, 0.9fr);
+ gap: 28px;
+ padding: 28px 28px 40px;
+ max-width: 1240px;
+ margin: 0 auto;
+ width: 100%;
+ box-sizing: border-box;
+ }
+ @media (max-width: 960px) {
+ main {
+ grid-template-columns: 1fr;
+ }
+ }
+
+ .stage {
+ position: relative;
+ background: linear-gradient(180deg, #11141a, #0a0c10);
+ border-radius: 16px;
+ border: 1px solid rgba(255, 255, 255, 0.08);
+ overflow: hidden;
+ min-height: 540px;
+ display: flex;
+ flex-direction: column;
+ }
+ .stage iframe {
+ flex: 1;
+ width: 100%;
+ border: 0;
+ background: transparent;
+ min-height: 540px;
+ }
+ .stage-overlay {
+ position: absolute;
+ inset: auto 16px 16px;
+ display: flex;
+ gap: 8px;
+ flex-wrap: wrap;
+ pointer-events: none;
+ }
+ .stage-overlay .chip {
+ pointer-events: auto;
+ padding: 7px 12px;
+ border-radius: 999px;
+ font-size: 12px;
+ letter-spacing: 0.04em;
+ background: rgba(0, 0, 0, 0.55);
+ border: 1px solid rgba(255, 255, 255, 0.14);
+ color: #fff;
+ cursor: pointer;
+ user-select: none;
+ }
+ .stage-overlay .chip:hover {
+ background: rgba(255, 255, 255, 0.08);
+ }
+
+ .side h1 {
+ margin: 0 0 6px;
+ font-size: 28px;
+ letter-spacing: -0.01em;
+ }
+ .side .handle {
+ color: rgba(255, 255, 255, 0.55);
+ font-size: 14px;
+ margin-bottom: 18px;
+ }
+ .side .desc {
+ color: rgba(255, 255, 255, 0.78);
+ font-size: 15px;
+ line-height: 1.55;
+ margin-bottom: 22px;
+ }
+
+ .stat-grid {
+ display: grid;
+ grid-template-columns: repeat(3, 1fr);
+ gap: 12px;
+ margin-bottom: 22px;
+ }
+ .stat {
+ background: rgba(255, 255, 255, 0.03);
+ border: 1px solid rgba(255, 255, 255, 0.06);
+ border-radius: 12px;
+ padding: 12px 14px;
+ }
+ .stat .v {
+ font-size: 18px;
+ font-weight: 600;
+ }
+ .stat .k {
+ font-size: 11px;
+ color: rgba(255, 255, 255, 0.5);
+ text-transform: uppercase;
+ letter-spacing: 0.08em;
+ margin-top: 4px;
+ }
+
+ .embed-card {
+ background: rgba(255, 255, 255, 0.03);
+ border: 1px solid rgba(255, 255, 255, 0.06);
+ border-radius: 14px;
+ padding: 16px;
+ margin-bottom: 14px;
+ }
+ .embed-card h3 {
+ font-size: 13px;
+ text-transform: uppercase;
+ letter-spacing: 0.08em;
+ color: rgba(255, 255, 255, 0.6);
+ margin: 0 0 10px;
+ }
+ .embed-card pre {
+ background: #06080b;
+ border: 1px solid rgba(255, 255, 255, 0.05);
+ border-radius: 8px;
+ padding: 12px 14px;
+ font-family: ui-monospace, SFMono-Regular, monospace;
+ font-size: 12px;
+ color: #cad6e8;
+ margin: 0;
+ white-space: pre-wrap;
+ word-break: break-all;
+ }
+ .embed-card .copy {
+ margin-top: 10px;
+ background: #fff;
+ color: #0a0c10;
+ border: 0;
+ border-radius: 8px;
+ padding: 8px 14px;
+ font-size: 12px;
+ letter-spacing: 0.04em;
+ cursor: pointer;
+ font-weight: 600;
+ }
+ .embed-card .copy.copied {
+ background: #5fce6a;
+ color: #04150a;
+ }
+
+ .cta-row {
+ display: flex;
+ gap: 10px;
+ flex-wrap: wrap;
+ margin-bottom: 22px;
+ }
+ .cta-row a {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ background: #fff;
+ color: #0a0c10;
+ padding: 10px 16px;
+ border-radius: 10px;
+ font-size: 13px;
+ font-weight: 600;
+ text-decoration: none;
+ }
+ .cta-row a.ghost {
+ background: transparent;
+ color: #fff;
+ border: 1px solid rgba(255, 255, 255, 0.18);
+ }
+
+ .not-found {
+ text-align: center;
+ padding: 80px 20px;
+ color: rgba(255, 255, 255, 0.6);
+ }
+ .not-found h1 {
+ font-size: 22px;
+ margin-bottom: 8px;
+ color: #fff;
+ }
+ .not-found a {
+ color: #5fa8ff;
+ }
+ </style>
+ </head>
+ <body>
+ <header class="topbar">
+ <a class="brand" href="/">three.ws</a>
+ <nav class="links">
+ <a href="/explore">explore</a>
+ <a href="/create">create</a>
+ <a href="/dashboard">dashboard</a>
+ </nav>
+ </header>
+ <main id="main"></main>
+
+ <script type="module" src="/src/handle.js"></script>
+ </body>
+</html>
diff --git a/pages/widget.html b/pages/widget.html
new file mode 100644
index 000000000..d03d27b0f
--- /dev/null
+++ b/pages/widget.html
@@ -0,0 +1,147 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="utf-8" />
+ <meta http-equiv="X-UA-Compatible" content="IE=edge" />
+ <title>three.ws widget</title>
+ <meta
+ name="viewport"
+ content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover"
+ />
+ <meta name="robots" content="noindex" />
+ <meta name="theme-color" content="#000000" />
+ <link rel="shortcut icon" href="/favicon.ico" />
+ <link rel="stylesheet" href="/style.css" />
+ <link rel="stylesheet" href="/fonts/fonts.css" />
+ <style>
+ /* Slim widget shell — no nav, no footer, no auth chrome.
+ Held invisible until the viewer fires its first frame so the
+ parent iframe never sees a chrome flash. */
+ html,
+ body {
+ margin: 0;
+ padding: 0;
+ height: 100%;
+ width: 100%;
+ background: #000;
+ color: #eee;
+ font-family: 'Inter', system-ui, -apple-system, sans-serif;
+ overflow: hidden;
+ }
+ body {
+ visibility: hidden;
+ }
+ body.widget-ready {
+ visibility: visible;
+ }
+ .wrap {
+ position: absolute;
+ inset: 0;
+ width: 100%;
+ height: 100%;
+ }
+ .viewer-container {
+ position: absolute;
+ inset: 0;
+ width: 100%;
+ height: 100%;
+ }
+ /* Poster image shown until the model's first frame. Hides on the
+ `widget-ready` body flip with a soft cross-fade. */
+ .widget-poster {
+ position: fixed;
+ inset: 0;
+ background-color: #000;
+ background-position: center;
+ background-repeat: no-repeat;
+ background-size: contain;
+ z-index: 1;
+ pointer-events: none;
+ transition: opacity 0.35s ease;
+ }
+ body.widget-ready .widget-poster {
+ opacity: 0;
+ }
+ /* Spinner — same look as the rest of the app, centred. */
+ .spinner {
+ position: fixed;
+ left: 50%;
+ top: 50%;
+ transform: translate(-50%, -50%);
+ width: 32px;
+ height: 32px;
+ border: 2px solid rgba(255, 255, 255, 0.12);
+ border-top-color: rgba(255, 255, 255, 0.72);
+ border-radius: 50%;
+ animation: widget-spin 0.9s linear infinite;
+ z-index: 2;
+ pointer-events: none;
+ }
+ body.widget-ready .spinner {
+ display: none;
+ }
+ @keyframes widget-spin {
+ to {
+ transform: translate(-50%, -50%) rotate(360deg);
+ }
+ }
+ /* Force-hide anything the app accidentally injects (e.g. Footer())
+ despite the guard — defence-in-depth in case a future code path
+ re-introduces injection without checking the flag. */
+ body > header,
+ body > footer,
+ body > .auth-gate,
+ body > .agent-onboarding,
+ body > .agent-presence-sidebar,
+ body > .dropzone {
+ display: none !important;
+ }
+ </style>
+ <script>
+ // Signal to /src/app.js that this is the slim widget shell BEFORE the
+ // module parses — module-level chrome injection and main-mode-only
+ // setup short-circuit when this flag is set.
+ window.__WIDGET_SHELL = true;
+
+ // Optional ?poster=<url> renders a static image while WebGL boots.
+ // Encoded in the URL so it works without any postMessage handshake.
+ (function () {
+ try {
+ var u = new URL(location.href);
+ var poster = u.searchParams.get('poster');
+ if (poster) {
+ document.addEventListener('DOMContentLoaded', function () {
+ var el = document.createElement('div');
+ el.className = 'widget-poster';
+ el.style.backgroundImage = 'url(' + JSON.stringify(poster).slice(1, -1) + ')';
+ document.body.appendChild(el);
+ });
+ }
+ } catch (_) {
+ /* malformed URL — skip poster */
+ }
+ })();
+
+ // Reveal the body on the viewer's first successful frame. App.js fires
+ // a 'three-ws:first-frame' event after LOAD_END(success). 6s fallback
+ // guards against a hung load so visitors don't stare at a black box.
+ (function () {
+ var revealed = false;
+ var reveal = function () {
+ if (revealed) return;
+ revealed = true;
+ document.body.classList.add('widget-ready');
+ };
+ window.addEventListener('three-ws:first-frame', reveal, { once: true });
+ setTimeout(reveal, 6000);
+ })();
+ </script>
+ <script defer type="module" src="/src/app.js"></script>
+ </head>
+ <body data-viewer-mode="embed">
+ <main class="wrap">
+ <div class="viewer-container" id="viewer-container"></div>
+ </main>
+ <div class="spinner" aria-label="Loading"></div>
+ </body>
+</html>
diff --git a/public/ai-stream.html b/public/ai-stream.html
index 6ff03bfc4..440456ff3 100644
--- a/public/ai-stream.html
+++ b/public/ai-stream.html
@@ -91,7 +91,7 @@
function mountAgent() {
const modelHash = '&model=' + encodeURIComponent(params.avatar);
const widgetId = 'wdgt_demo_pumpfun_stream';
- iframe.src = `/app#widget=${widgetId}&kiosk=true&type=pumpfun-feed${modelHash}&narrate=${params.narrate ? '1' : '0'}`;
+ iframe.src = `/widget#widget=${widgetId}&kiosk=true&type=pumpfun-feed${modelHash}&narrate=${params.narrate ? '1' : '0'}`;
}
function connectFeed() {
diff --git a/public/app-next.css b/public/app-next.css
new file mode 100644
index 000000000..ef8eb8093
--- /dev/null
+++ b/public/app-next.css
@@ -0,0 +1,803 @@
+/* ==========================================================================
+ app-next — UX preview demo
+ Surface goals:
+ 1. The avatar is the page. Stage, not chrome.
+ 2. One CTA hierarchy. No competing sign-in / save / upload mid-screen.
+ 3. Animation strip is an invitation, not a control panel.
+ ========================================================================== */
+
+:root {
+ --nxt-bg-0: #050608;
+ --nxt-bg-1: #0c0d12;
+ --nxt-ink: #e7e8ec;
+ --nxt-ink-dim: #9ca0aa;
+ --nxt-ink-fade: #6b6f78;
+ --nxt-accent: #9a7cff;
+ --nxt-accent-soft: rgba(154, 124, 255, 0.18);
+ --nxt-glass: rgba(14, 15, 22, 0.55);
+ --nxt-glass-strong: rgba(14, 15, 22, 0.82);
+ --nxt-stroke: rgba(255, 255, 255, 0.08);
+ --nxt-stroke-strong: rgba(255, 255, 255, 0.14);
+ --nxt-radius: 14px;
+ --nxt-radius-sm: 10px;
+ --nxt-radius-pill: 999px;
+ --nxt-header-h: 56px;
+}
+
+/* ── Body / shell ──────────────────────────────────────────────────────── */
+
+html,
+body {
+ height: 100%;
+}
+
+body.app-next-body {
+ margin: 0;
+ background:
+ /* Soft purple lift behind the avatar's head */
+ radial-gradient(ellipse 50% 35% at 50% 38%, rgba(154, 124, 255, 0.10) 0%, transparent 70%),
+ /* Warm cyan accent low-left */
+ radial-gradient(ellipse 40% 30% at 25% 75%, rgba(109, 193, 255, 0.05) 0%, transparent 65%),
+ /* Base depth gradient */
+ radial-gradient(ellipse 90% 70% at 50% 60%, #11131c 0%, #08090e 55%, #020203 100%);
+ color: var(--nxt-ink);
+ font-family: 'Inter', system-ui, -apple-system, sans-serif;
+ overflow: hidden;
+}
+
+/* Hide every chrome element produced by the production app.js that the
+ demo overrides. None of these are required for the viewer to work. */
+body.app-next-body #agent-presence-sidebar,
+body.app-next-body #auth-gate,
+body.app-next-body #agent-onboarding,
+body.app-next-body .dropzone,
+body.app-next-body footer,
+body.app-next-body .h-footer,
+body.app-next-body .phi-grid,
+body.app-next-body .phi-grid-label,
+body.app-next-body .anim-panel,
+body.app-next-body .agent-presence-sidebar,
+body.app-next-body .save-toast,
+body.app-next-body .controls-toggle {
+ display: none !important;
+}
+
+/* Override style.css `body { display: flex }` since we manage layout ourselves */
+body.app-next-body {
+ display: block;
+}
+
+/* ── Header ────────────────────────────────────────────────────────────── */
+
+.nxt-header {
+ position: fixed;
+ top: 0;
+ left: 0;
+ right: 0;
+ height: var(--nxt-header-h);
+ padding: 0 18px 0 14px;
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ background: linear-gradient(180deg, rgba(5, 6, 8, 0.85) 0%, rgba(5, 6, 8, 0.55) 60%, rgba(5, 6, 8, 0) 100%);
+ backdrop-filter: blur(14px) saturate(140%);
+ -webkit-backdrop-filter: blur(14px) saturate(140%);
+ z-index: 30;
+ pointer-events: none; /* let clicks through to the canvas in dead space */
+}
+
+.nxt-header > * {
+ pointer-events: auto;
+}
+
+.nxt-brand {
+ display: inline-flex;
+ align-items: center;
+ gap: 8px;
+ text-decoration: none;
+ color: var(--nxt-ink);
+ font-weight: 600;
+ letter-spacing: -0.01em;
+ font-size: 15px;
+ padding: 6px 10px 6px 6px;
+ border-radius: var(--nxt-radius-pill);
+ transition: background 0.15s;
+}
+
+.nxt-brand:hover {
+ background: rgba(255, 255, 255, 0.05);
+}
+
+.nxt-brand-mark {
+ width: 24px;
+ height: 24px;
+ display: block;
+}
+
+.nxt-brand-tag {
+ font-size: 10.5px;
+ font-weight: 500;
+ letter-spacing: 0.08em;
+ text-transform: uppercase;
+ color: var(--nxt-accent);
+ background: var(--nxt-accent-soft);
+ padding: 3px 8px;
+ border-radius: var(--nxt-radius-pill);
+ margin-left: 4px;
+}
+
+.nxt-header-right {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+}
+
+.nxt-more {
+ position: relative;
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ background: transparent;
+ border: 0;
+ color: var(--nxt-ink-dim);
+ font: inherit;
+ font-size: 13.5px;
+ padding: 7px 12px;
+ border-radius: var(--nxt-radius-pill);
+ cursor: pointer;
+ transition: background 0.15s, color 0.15s;
+}
+
+.nxt-more:hover {
+ color: var(--nxt-ink);
+ background: rgba(255, 255, 255, 0.05);
+}
+
+.nxt-more svg {
+ transition: transform 0.18s;
+}
+
+.nxt-more[aria-expanded='true'] svg {
+ transform: rotate(180deg);
+}
+
+.nxt-more-menu {
+ position: absolute;
+ top: calc(var(--nxt-header-h) - 4px);
+ right: 72px;
+ min-width: 200px;
+ padding: 6px;
+ background: var(--nxt-glass-strong);
+ border: 1px solid var(--nxt-stroke);
+ border-radius: var(--nxt-radius);
+ backdrop-filter: blur(20px);
+ -webkit-backdrop-filter: blur(20px);
+ box-shadow: 0 22px 60px rgba(0, 0, 0, 0.5);
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+ z-index: 40;
+}
+
+.nxt-more-menu[hidden] { display: none; }
+
+.nxt-more-menu a,
+.nxt-more-menu button {
+ display: block;
+ background: transparent;
+ border: 0;
+ color: var(--nxt-ink-dim);
+ font: inherit;
+ font-size: 13.5px;
+ text-decoration: none;
+ text-align: left;
+ padding: 9px 12px;
+ border-radius: 8px;
+ cursor: pointer;
+ transition: background 0.12s, color 0.12s;
+}
+
+.nxt-more-menu a:hover,
+.nxt-more-menu button:hover {
+ color: var(--nxt-ink);
+ background: rgba(255, 255, 255, 0.05);
+}
+
+.nxt-more-sep {
+ height: 1px;
+ background: var(--nxt-stroke);
+ margin: 4px 4px;
+}
+
+/* Auth surface */
+.nxt-auth {
+ position: relative;
+}
+
+.nxt-signin {
+ display: inline-flex;
+ align-items: center;
+ background: rgba(255, 255, 255, 0.06);
+ color: var(--nxt-ink);
+ font-size: 13.5px;
+ font-weight: 500;
+ padding: 7px 14px;
+ border-radius: var(--nxt-radius-pill);
+ text-decoration: none;
+ border: 1px solid var(--nxt-stroke);
+ transition: background 0.15s, border-color 0.15s;
+}
+
+.nxt-signin:hover {
+ background: rgba(255, 255, 255, 0.1);
+ border-color: var(--nxt-stroke-strong);
+}
+
+.nxt-user-btn {
+ display: inline-flex;
+ align-items: center;
+ gap: 8px;
+ background: rgba(255, 255, 255, 0.06);
+ color: var(--nxt-ink);
+ border: 1px solid var(--nxt-stroke);
+ font: inherit;
+ font-size: 13.5px;
+ font-weight: 500;
+ padding: 6px 12px 6px 10px;
+ border-radius: var(--nxt-radius-pill);
+ cursor: pointer;
+}
+
+.nxt-user-dot {
+ width: 8px;
+ height: 8px;
+ border-radius: 50%;
+ background: linear-gradient(135deg, var(--nxt-accent), #6dc1ff);
+ box-shadow: 0 0 8px var(--nxt-accent);
+}
+
+.nxt-user-menu {
+ position: absolute;
+ top: calc(100% + 6px);
+ right: 0;
+ min-width: 200px;
+ padding: 6px;
+ background: var(--nxt-glass-strong);
+ border: 1px solid var(--nxt-stroke);
+ border-radius: var(--nxt-radius);
+ backdrop-filter: blur(20px);
+ -webkit-backdrop-filter: blur(20px);
+ box-shadow: 0 22px 60px rgba(0, 0, 0, 0.5);
+ z-index: 40;
+}
+
+.nxt-user-menu[hidden] { display: none; }
+
+.nxt-user-menu a,
+.nxt-user-menu button {
+ display: block;
+ background: transparent;
+ border: 0;
+ color: var(--nxt-ink-dim);
+ font: inherit;
+ font-size: 13.5px;
+ text-align: left;
+ padding: 9px 12px;
+ border-radius: 8px;
+ cursor: pointer;
+ text-decoration: none;
+ width: 100%;
+}
+
+.nxt-user-menu a:hover,
+.nxt-user-menu button:hover {
+ color: var(--nxt-ink);
+ background: rgba(255, 255, 255, 0.05);
+}
+
+.nxt-user-sep {
+ height: 1px;
+ background: var(--nxt-stroke);
+ margin: 4px 4px;
+}
+
+/* ── Stage / Main ──────────────────────────────────────────────────────── */
+
+.nxt-main {
+ position: fixed;
+ inset: 0;
+ width: 100vw;
+ height: 100vh;
+ min-height: 100vh;
+ display: block;
+}
+
+.nxt-viewer {
+ position: absolute;
+ inset: 0;
+ width: 100%;
+ height: 100%;
+ min-height: 0;
+ /* Sit above the CSS stage layers so the avatar reads first, but allow the
+ floor glow to shine through the transparent canvas via blend-mode. */
+ z-index: 4;
+ background: transparent;
+ pointer-events: auto;
+}
+
+.nxt-viewer canvas {
+ display: block;
+ width: 100% !important;
+ height: 100% !important;
+}
+
+/* Floor glow: a layered pool of light under the avatar's feet, painted
+ BEHIND the transparent canvas. The overlay JS flips viewer.state.transparentBg
+ so non-avatar pixels reveal these layers. */
+.nxt-stage-floor {
+ position: absolute;
+ left: 50%;
+ bottom: 8%;
+ width: 88vmin;
+ height: 32vmin;
+ transform: translate(-50%, 18%);
+ background:
+ /* Inner hot core */
+ radial-gradient(
+ ellipse 40% 35% at center,
+ rgba(154, 124, 255, 0.55) 0%,
+ rgba(154, 124, 255, 0.18) 35%,
+ rgba(0, 0, 0, 0) 70%
+ ),
+ /* Outer cyan halo for depth */
+ radial-gradient(
+ ellipse 90% 70% at center,
+ rgba(109, 193, 255, 0.12) 0%,
+ rgba(0, 0, 0, 0) 65%
+ );
+ pointer-events: none;
+ z-index: 2;
+ filter: blur(3px);
+}
+
+/* Thin ring directly under the avatar — a subtle "agent base" hint */
+.nxt-stage-floor::after {
+ content: '';
+ position: absolute;
+ left: 50%;
+ top: 50%;
+ transform: translate(-50%, -45%);
+ width: 32vmin;
+ height: 32vmin;
+ border-radius: 50%;
+ background: radial-gradient(
+ circle at center,
+ rgba(154, 124, 255, 0.0) 30%,
+ rgba(154, 124, 255, 0.35) 55%,
+ rgba(154, 124, 255, 0.0) 70%
+ );
+ filter: blur(0.5px);
+ opacity: 0.7;
+}
+
+/* Vignette — pulls the eye inward, fades to deep black at the edges */
+.nxt-stage-vignette {
+ position: absolute;
+ inset: 0;
+ pointer-events: none;
+ z-index: 3;
+ background:
+ radial-gradient(
+ ellipse 70% 80% at center,
+ transparent 30%,
+ rgba(0, 0, 0, 0.55) 78%,
+ rgba(0, 0, 0, 0.85) 100%
+ );
+}
+
+/* ── Rotating "Try …" pill ─────────────────────────────────────────────── */
+
+.nxt-try-pill {
+ position: fixed;
+ left: 50%;
+ bottom: 96px;
+ transform: translateX(-50%);
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ padding: 5px 6px 5px 12px;
+ background: var(--nxt-glass-strong);
+ border: 1px solid var(--nxt-stroke);
+ border-radius: var(--nxt-radius-pill);
+ backdrop-filter: blur(14px);
+ -webkit-backdrop-filter: blur(14px);
+ box-shadow: 0 16px 36px rgba(0, 0, 0, 0.5), 0 0 0 1px rgba(154, 124, 255, 0.05);
+ z-index: 20;
+ animation: nxt-rise 0.5s 0.4s both;
+}
+
+.nxt-try-pill[hidden] { display: none; }
+
+@keyframes nxt-rise {
+ from { opacity: 0; transform: translate(-50%, 8px); }
+ to { opacity: 1; transform: translate(-50%, 0); }
+}
+
+.nxt-try-pill__label {
+ font-size: 11.5px;
+ font-weight: 600;
+ color: var(--nxt-ink-fade);
+ letter-spacing: 0.08em;
+ text-transform: uppercase;
+}
+
+.nxt-try-pill__btn {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ background: var(--nxt-accent-soft);
+ border: 0;
+ color: var(--nxt-ink);
+ font: inherit;
+ font-size: 13.5px;
+ font-weight: 500;
+ padding: 6px 12px;
+ border-radius: var(--nxt-radius-pill);
+ cursor: pointer;
+ transition: background 0.15s;
+}
+
+.nxt-try-pill__btn:hover {
+ background: rgba(154, 124, 255, 0.32);
+}
+
+.nxt-try-pill__icon {
+ font-size: 15px;
+ line-height: 1;
+}
+
+.nxt-try-pill__next {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 26px;
+ height: 26px;
+ border-radius: 50%;
+ background: transparent;
+ border: 0;
+ color: var(--nxt-ink-fade);
+ cursor: pointer;
+ transition: background 0.15s, color 0.15s;
+}
+
+.nxt-try-pill__next:hover {
+ color: var(--nxt-ink);
+ background: rgba(255, 255, 255, 0.06);
+}
+
+/* ── Action bar ────────────────────────────────────────────────────────── */
+
+.nxt-action-bar {
+ position: fixed;
+ left: 50%;
+ bottom: 24px;
+ transform: translateX(-50%);
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ padding: 6px;
+ background: var(--nxt-glass-strong);
+ border: 1px solid var(--nxt-stroke);
+ border-radius: var(--nxt-radius-pill);
+ backdrop-filter: blur(16px) saturate(140%);
+ -webkit-backdrop-filter: blur(16px) saturate(140%);
+ box-shadow: 0 28px 64px rgba(0, 0, 0, 0.55), 0 0 0 1px rgba(255, 255, 255, 0.02) inset;
+ z-index: 21;
+ animation: nxt-rise-bar 0.5s 0.2s both;
+}
+
+@keyframes nxt-rise-bar {
+ from { opacity: 0; transform: translate(-50%, 14px); }
+ to { opacity: 1; transform: translate(-50%, 0); }
+}
+
+.nxt-action {
+ display: inline-flex;
+ align-items: center;
+ gap: 8px;
+ background: transparent;
+ color: var(--nxt-ink-dim);
+ border: 0;
+ font: inherit;
+ font-size: 13.5px;
+ font-weight: 500;
+ padding: 9px 14px;
+ border-radius: var(--nxt-radius-pill);
+ cursor: pointer;
+ white-space: nowrap;
+ transition: background 0.15s, color 0.15s, transform 0.15s;
+}
+
+.nxt-action svg { flex: none; }
+
+.nxt-action kbd {
+ font: 10.5px 'SF Mono', ui-monospace, monospace;
+ color: var(--nxt-ink-fade);
+ background: rgba(255, 255, 255, 0.06);
+ padding: 2px 6px;
+ border-radius: 5px;
+ border: 1px solid var(--nxt-stroke);
+ letter-spacing: 0.04em;
+ margin-left: 2px;
+}
+
+.nxt-action--ghost:hover {
+ color: var(--nxt-ink);
+ background: rgba(255, 255, 255, 0.06);
+}
+
+.nxt-action--primary {
+ background: linear-gradient(135deg, var(--nxt-accent) 0%, #7a5cff 100%);
+ color: white;
+ box-shadow: 0 6px 18px rgba(154, 124, 255, 0.4);
+}
+
+.nxt-action--primary:hover {
+ transform: translateY(-1px);
+ box-shadow: 0 10px 22px rgba(154, 124, 255, 0.5);
+}
+
+.nxt-action--primary kbd {
+ background: rgba(255, 255, 255, 0.18);
+ color: rgba(255, 255, 255, 0.85);
+ border-color: rgba(255, 255, 255, 0.25);
+}
+
+/* ── Animation picker sheet ────────────────────────────────────────────── */
+
+.nxt-anim-sheet {
+ position: fixed;
+ left: 50%;
+ bottom: 92px;
+ transform: translateX(-50%);
+ width: min(720px, calc(100vw - 32px));
+ max-height: 60vh;
+ display: flex;
+ flex-direction: column;
+ background: var(--nxt-glass-strong);
+ border: 1px solid var(--nxt-stroke);
+ border-radius: 18px;
+ backdrop-filter: blur(22px) saturate(140%);
+ -webkit-backdrop-filter: blur(22px) saturate(140%);
+ box-shadow: 0 28px 80px rgba(0, 0, 0, 0.7), 0 0 0 1px rgba(255, 255, 255, 0.02) inset;
+ z-index: 25;
+ overflow: hidden;
+ animation: nxt-sheet-up 0.22s ease-out both;
+}
+
+.nxt-anim-sheet[hidden] { display: none; }
+
+@keyframes nxt-sheet-up {
+ from { opacity: 0; transform: translate(-50%, 10px); }
+ to { opacity: 1; transform: translate(-50%, 0); }
+}
+
+.nxt-anim-sheet__head {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 16px 18px 8px;
+}
+
+.nxt-anim-sheet__head h2 {
+ margin: 0;
+ font-size: 14px;
+ font-weight: 600;
+ color: var(--nxt-ink);
+ letter-spacing: 0.02em;
+}
+
+.nxt-anim-sheet__close {
+ background: transparent;
+ border: 0;
+ color: var(--nxt-ink-fade);
+ font-size: 22px;
+ line-height: 1;
+ width: 28px;
+ height: 28px;
+ border-radius: 50%;
+ cursor: pointer;
+ transition: background 0.15s, color 0.15s;
+}
+
+.nxt-anim-sheet__close:hover {
+ color: var(--nxt-ink);
+ background: rgba(255, 255, 255, 0.06);
+}
+
+.nxt-anim-sheet__filter {
+ padding: 0 18px 12px;
+}
+
+.nxt-anim-search {
+ width: 100%;
+ background: rgba(255, 255, 255, 0.05);
+ border: 1px solid var(--nxt-stroke);
+ border-radius: 10px;
+ color: var(--nxt-ink);
+ font: inherit;
+ font-size: 13.5px;
+ padding: 9px 12px;
+ outline: none;
+ transition: border-color 0.15s, background 0.15s;
+}
+
+.nxt-anim-search:focus {
+ border-color: var(--nxt-accent);
+ background: rgba(255, 255, 255, 0.08);
+}
+
+.nxt-anim-grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(108px, 1fr));
+ gap: 6px;
+ padding: 0 12px 14px;
+ overflow-y: auto;
+ scrollbar-width: thin;
+ scrollbar-color: rgba(255, 255, 255, 0.12) transparent;
+}
+
+.nxt-anim-grid::-webkit-scrollbar {
+ width: 8px;
+}
+.nxt-anim-grid::-webkit-scrollbar-thumb {
+ background: rgba(255, 255, 255, 0.12);
+ border-radius: 4px;
+}
+
+.nxt-anim-card {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ gap: 6px;
+ padding: 12px 8px 10px;
+ background: rgba(255, 255, 255, 0.03);
+ border: 1px solid rgba(255, 255, 255, 0.05);
+ border-radius: 10px;
+ color: var(--nxt-ink);
+ cursor: pointer;
+ font: inherit;
+ font-size: 11.5px;
+ text-align: center;
+ line-height: 1.3;
+ transition: background 0.12s, border-color 0.12s, transform 0.12s;
+}
+
+.nxt-anim-card:hover {
+ background: rgba(255, 255, 255, 0.07);
+ border-color: rgba(255, 255, 255, 0.12);
+ transform: translateY(-1px);
+}
+
+.nxt-anim-card[aria-pressed='true'] {
+ background: var(--nxt-accent-soft);
+ border-color: rgba(154, 124, 255, 0.5);
+ color: var(--nxt-ink);
+}
+
+.nxt-anim-card__icon {
+ font-size: 22px;
+ line-height: 1;
+}
+
+.nxt-anim-empty {
+ grid-column: 1 / -1;
+ text-align: center;
+ color: var(--nxt-ink-fade);
+ padding: 28px 12px;
+ font-size: 13px;
+}
+
+/* ── Drag-over overlay ─────────────────────────────────────────────────── */
+
+body.app-next-body.is-dragover::before {
+ content: 'Drop to load model';
+ position: fixed;
+ inset: 16px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ font-size: 16px;
+ font-weight: 600;
+ letter-spacing: 0.02em;
+ color: var(--nxt-accent);
+ background: rgba(154, 124, 255, 0.06);
+ border: 2px dashed rgba(154, 124, 255, 0.5);
+ border-radius: 16px;
+ z-index: 50;
+ pointer-events: none;
+}
+
+/* ── First-visit hint ──────────────────────────────────────────────────── */
+
+.nxt-first-hint {
+ position: fixed;
+ top: calc(var(--nxt-header-h) + 14px);
+ left: 50%;
+ transform: translateX(-50%);
+ display: inline-flex;
+ align-items: center;
+ gap: 12px;
+ padding: 8px 8px 8px 14px;
+ background: var(--nxt-glass-strong);
+ border: 1px solid var(--nxt-stroke);
+ border-radius: var(--nxt-radius-pill);
+ backdrop-filter: blur(14px);
+ -webkit-backdrop-filter: blur(14px);
+ font-size: 12.5px;
+ color: var(--nxt-ink-dim);
+ z-index: 22;
+ animation: nxt-rise 0.5s 0.8s both;
+}
+
+.nxt-first-hint[hidden] { display: none; }
+
+.nxt-first-hint button {
+ background: transparent;
+ border: 0;
+ color: var(--nxt-ink-fade);
+ width: 22px;
+ height: 22px;
+ border-radius: 50%;
+ cursor: pointer;
+ font-size: 18px;
+ line-height: 1;
+}
+
+.nxt-first-hint button:hover {
+ color: var(--nxt-ink);
+ background: rgba(255, 255, 255, 0.06);
+}
+
+/* ── Spinner ───────────────────────────────────────────────────────────── */
+
+.spinner {
+ position: fixed;
+ top: 50%;
+ left: 50%;
+ width: 36px;
+ height: 36px;
+ margin: -18px 0 0 -18px;
+ border-radius: 50%;
+ border: 2.5px solid rgba(255, 255, 255, 0.08);
+ border-top-color: var(--nxt-accent);
+ animation: nxt-spin 0.8s linear infinite;
+ z-index: 5;
+ pointer-events: none;
+}
+
+@keyframes nxt-spin {
+ to { transform: rotate(360deg); }
+}
+
+/* ── Mobile ────────────────────────────────────────────────────────────── */
+
+@media (max-width: 640px) {
+ .nxt-brand-tag { display: none; }
+ .nxt-more { padding: 7px 8px; }
+ .nxt-more-menu { right: 12px; }
+ .nxt-action kbd { display: none; }
+ .nxt-action { padding: 9px 11px; font-size: 12.5px; }
+ .nxt-action span { display: none; }
+ .nxt-action--primary span { display: inline; }
+ .nxt-try-pill { bottom: 86px; max-width: calc(100vw - 24px); }
+ .nxt-try-pill__label { display: none; }
+ .nxt-anim-sheet { bottom: 80px; max-height: 50vh; }
+ .nxt-first-hint { font-size: 11.5px; padding: 6px 6px 6px 12px; max-width: calc(100vw - 24px); }
+}
+
+/* Hide the production dat.gui by default — controls live inside the viewer
+ panel that's intentionally not surfaced in this UX preview. Power users
+ can re-enable via the explore menu (link routes to /app). */
+body.app-next-body .dg.ac { display: none !important; }
diff --git a/public/demos/index.html b/public/demos/index.html
index 5c209df6f..360cee487 100644
--- a/public/demos/index.html
+++ b/public/demos/index.html
@@ -47,6 +47,30 @@
.demo-status.live { background: rgba(61, 193, 255,0.12); color: #3dc1ff; border: 1px solid rgba(61, 193, 255,0.35); }
.demo-status.beta { background: rgba(255,184,77,0.12); color: #ffb84d; border: 1px solid rgba(255,184,77,0.35); }
.demo-status.prod { background: rgba(154,212,255,0.12); color: #9ad4ff; border: 1px solid rgba(154,212,255,0.35); }
+ .demo-status.feature { background: rgba(154,124,255,0.18); color: #b9a4ff; border: 1px solid rgba(154,124,255,0.5); }
+ .demo-card--feature {
+ grid-column: 1 / -1;
+ background: linear-gradient(135deg, #11121c 0%, #14101e 100%);
+ border: 1.5px solid rgba(154,124,255,0.35);
+ box-shadow: 0 0 0 1px rgba(154,124,255,0.08), 0 18px 50px rgba(0,0,0,0.45);
+ position: relative;
+ overflow: hidden;
+ }
+ .demo-card--feature::before {
+ content: '';
+ position: absolute;
+ top: -50%;
+ right: -20%;
+ width: 60%;
+ height: 200%;
+ background: radial-gradient(ellipse at center, rgba(154,124,255,0.18) 0%, transparent 60%);
+ pointer-events: none;
+ }
+ .demo-card--feature:hover {
+ border-color: rgba(154,124,255,0.55);
+ box-shadow: 0 0 0 1px rgba(154,124,255,0.12), 0 22px 56px rgba(0,0,0,0.5);
+ }
+ .demo-card--feature h2 { font-size: 19px; }
.warning {
margin: 32px 0 0;
padding: 14px 16px;
@@ -72,6 +96,11 @@
</p>
<div class="demos-grid">
+ <a class="demo-card demo-card--feature" href="/app-next">
+ <h2>app · next — the redesigned viewer</h2>
+ <p>The /app surface, rebuilt around the avatar. Single-hierarchy action bar, rotating "Try this" invitation, compact searchable animation picker, floor glow + idle camera drift. Same real viewer, agents, and animations underneath — just better UX.</p>
+ <span class="demo-status feature">New</span>
+ </a>
<a class="demo-card" href="/demos/agents/">
<h2>Agent interactions lab</h2>
<p>Fourteen prototypes for how a 3D agent can physically inhabit the page: cursor follower, trampoline button, wrecking ball, climb-the-title, more.</p>
diff --git a/public/docs-widgets.html b/public/docs-widgets.html
index 33a53b13f..968ab3709 100644
--- a/public/docs-widgets.html
+++ b/public/docs-widgets.html
@@ -223,9 +223,13 @@
<td><code>/w/&lt;id&gt;</code></td>
<td>Sharing in Slack/Discord/X — server-rendered with rich OG card.</td>
</tr>
+ <tr>
+ <td><code>/widget#widget=&lt;id&gt;</code></td>
+ <td>Slim viewer shell — no nav/footer chrome. The canonical embed URL.</td>
+ </tr>
<tr>
<td><code>/app#widget=&lt;id&gt;</code></td>
- <td>The SPA viewer with the widget config applied.</td>
+ <td>Legacy SPA viewer — still works, but includes the full main-app chrome.</td>
</tr>
<tr>
<td><code>/api/widgets/&lt;id&gt;/og</code></td>
@@ -277,7 +281,7 @@
<h2 id="embedding">Embedding</h2>
<h3>iframe (recommended)</h3>
<pre><code>&lt;iframe
- src="https://three.ws/app#widget=wdgt_abc123def456&amp;kiosk=true"
+ src="https://three.ws/widget#widget=wdgt_abc123def456&amp;kiosk=true"
width="600"
height="600"
style="border:0;border-radius:12px;max-width:100%"
@@ -381,7 +385,8 @@
<pre><code>GET /api/widgets/oembed?url=&lt;widget-url&gt;&amp;format=json</code></pre>
<p>
Returns standard <a href="https://oembed.com">oEmbed v1.0</a> JSON, type
- <code>rich</code>. Accepts both <code>/w/&lt;id&gt;</code> and
+ <code>rich</code>. Accepts <code>/w/&lt;id&gt;</code>,
+ <code>/widget#widget=&lt;id&gt;</code>, and legacy
<code>/app#widget=&lt;id&gt;</code> forms.
</p>
diff --git a/public/docs/embedding.md b/public/docs/embedding.md
index 3e49ad9cd..b30861cff 100644
--- a/public/docs/embedding.md
+++ b/public/docs/embedding.md
@@ -264,7 +264,7 @@ The `allow` attribute controls browser feature access:
|---------|-----|
| Backend agent | `/agent/{agent-id}/embed` or `/agent-embed.html?id={agent-id}` |
| On-chain agent | `/a/{chainId}/{agentId}/embed` |
-| Widget (kiosk) | `/app#widget={widget-id}&kiosk=true` |
+| Widget (kiosk) | `/widget#widget={widget-id}&kiosk=true` (slim shell, recommended) or `/app#widget={widget-id}&kiosk=true` (legacy) |
| Model viewer only | `/#model={glb-url}` |
### postMessage protocol
diff --git a/public/docs/quick-start.md b/public/docs/quick-start.md
index 7993cd965..99e297626 100644
--- a/public/docs/quick-start.md
+++ b/public/docs/quick-start.md
@@ -154,7 +154,7 @@ The fastest path to an embeddable 3D experience is an iframe widget. Build one i
```html
<iframe
- src="https://three.ws/app#widget=wdgt_YOUR_ID&kiosk=true"
+ src="https://three.ws/widget#widget=wdgt_YOUR_ID&kiosk=true"
width="600"
height="600"
style="border:0;border-radius:12px;max-width:100%"
diff --git a/public/docs/widget-studio.md b/public/docs/widget-studio.md
index eaed39411..3b1c11f37 100644
--- a/public/docs/widget-studio.md
+++ b/public/docs/widget-studio.md
@@ -127,7 +127,7 @@ The modal contains:
```html
<iframe
- src="https://three.ws/app#widget=wdgt_abc123&kiosk=true"
+ src="https://three.ws/widget#widget=wdgt_abc123&kiosk=true"
width="600"
height="600"
style="border:0;border-radius:12px;max-width:100%"
diff --git a/public/docs/widgets.md b/public/docs/widgets.md
index d69eb9ae9..b5e4dd92d 100644
--- a/public/docs/widgets.md
+++ b/public/docs/widgets.md
@@ -7,7 +7,7 @@ Each widget bundles three things: an avatar or 3D model (a `.glb` file stored in
```html
<!-- The simplest possible embed — drop this anywhere -->
<iframe
- src="https://three.ws/app#widget=wdgt_abc123def456&kiosk=true"
+ src="https://three.ws/widget#widget=wdgt_abc123def456&kiosk=true"
width="600"
height="600"
style="border:0;border-radius:12px"
@@ -62,7 +62,7 @@ All [brand options](#the-five-widget-types) apply (background, accent, caption,
```html
<iframe
- src="https://three.ws/app#widget=wdgt_abc123def456&kiosk=true"
+ src="https://three.ws/widget#widget=wdgt_abc123def456&kiosk=true"
width="600"
height="600"
style="border:0;border-radius:12px;max-width:100%"
@@ -153,7 +153,7 @@ All brand options apply.
```html
<iframe
- src="https://three.ws/app#widget=wdgt_abc123def456&kiosk=true"
+ src="https://three.ws/widget#widget=wdgt_abc123def456&kiosk=true"
width="420"
height="600"
style="border:0;border-radius:16px"
@@ -213,7 +213,7 @@ All brand options apply.
```html
<iframe
- src="https://three.ws/app#widget=wdgt_abc123def456&kiosk=true"
+ src="https://three.ws/widget#widget=wdgt_abc123def456&kiosk=true"
width="480"
height="560"
style="border:0;border-radius:16px"
@@ -296,7 +296,7 @@ After creating a widget, copy the iframe snippet from Studio or construct it man
```html
<!-- iframe embed (recommended) -->
<iframe
- src="https://three.ws/app#widget=wdgt_abc123def456&kiosk=true"
+ src="https://three.ws/widget#widget=wdgt_abc123def456&kiosk=true"
width="600"
height="600"
style="border:0;border-radius:12px;max-width:100%"
@@ -371,7 +371,7 @@ Response:
}
```
-Both `/w/<id>` and `/app#widget=<id>` URL forms are accepted. Use `maxwidth` and `maxheight` query params to clamp the returned iframe dimensions.
+The `/w/<id>`, `/widget#widget=<id>`, and legacy `/app#widget=<id>` URL forms are all accepted. Use `maxwidth` and `maxheight` query params to clamp the returned iframe dimensions.
---
diff --git a/public/embed.js b/public/embed.js
index 32a0894ff..7e0ff6259 100644
--- a/public/embed.js
+++ b/public/embed.js
@@ -61,7 +61,10 @@
var radius = attr(scriptEl, 'data-radius', '12');
var border = attr(scriptEl, 'data-border', '0');
- var src = ORIGIN + '/app#widget=' + encodeURIComponent(widgetId) + '&kiosk=true';
+ // /widget = slim viewer shell. Same engine as /app but without the
+ // marketing nav/footer/auth chrome in the DOM, so the embed iframe
+ // doesn't flash the parent site before the model renders.
+ var src = ORIGIN + '/widget#widget=' + encodeURIComponent(widgetId) + '&kiosk=true';
var iframe = document.createElement('iframe');
iframe.src = src;
@@ -119,13 +122,17 @@
registry[widgetId] = iframe;
// Lazy-load via IntersectionObserver when available (Firefox compat).
- // Falls back to immediate load when IO is absent.
+ // Falls back to immediate load when IO is absent. When the iframe first
+ // becomes visible, fire a fire-and-forget analytics beacon so the
+ // creator can see "where was my widget loaded from" without any
+ // cookie/localStorage touch on the visitor's browser.
if (typeof IntersectionObserver !== 'undefined') {
iframe.src = '';
var io = new IntersectionObserver(function (entries, obs) {
entries.forEach(function (entry) {
if (entry.isIntersecting) {
iframe.src = src;
+ sendViewBeacon(widgetId);
obs.disconnect();
}
});
@@ -133,15 +140,427 @@
io.observe(wrapper);
} else {
iframe.src = src;
+ sendViewBeacon(widgetId);
}
}
+ function sendViewBeacon(widgetId) {
+ var url = ORIGIN + '/api/widgets/' + encodeURIComponent(widgetId) + '/view';
+ try {
+ if (navigator.sendBeacon) {
+ navigator.sendBeacon(url, new Blob([''], { type: 'text/plain' }));
+ return;
+ }
+ } catch (e) { /* fall through to fetch */ }
+ try {
+ fetch(url, { method: 'POST', keepalive: true, mode: 'no-cors', credentials: 'omit' });
+ } catch (e) { /* best-effort only */ }
+ }
+
// Mount every <script data-widget="..."> on the page (allows multiple embeds).
var current = document.currentScript;
if (current && current.getAttribute('data-widget')) {
mount(current);
- return;
+ } else {
+ var scripts = document.querySelectorAll('script[data-widget][src*="embed.js"]');
+ for (var i = 0; i < scripts.length; i++) mount(scripts[i]);
}
- var scripts = document.querySelectorAll('script[data-widget][src*="embed.js"]');
- for (var i = 0; i < scripts.length; i++) mount(scripts[i]);
+
+ // ──────────────────────────────────────────────────────────────────────
+ // <threews-avatar> web component
+ //
+ // The widget mounter above handles legacy data-widget snippets. The
+ // component below is the modern "drop an avatar anywhere" surface that
+ // mirrors Google's <model-viewer> attribute pattern. Both live in this
+ // one file so a single <script src="/embed.js"> covers everything.
+ //
+ // Attributes:
+ // src — direct GLB URL
+ // avatar-id — three.ws saved avatar id
+ // agent — chain reference "eip155:8453/erc8004:0x.../1"
+ // pose, animation — animation clip to play on load
+ // bg — 'transparent' (default) | 'dark' | 'light'
+ // chromakey — '#00ff00' / 'green' / 'blue' / 'magenta'
+ // hide-chrome — suppress name plate / link / loading
+ // driveable — upgrade to agent runtime (speak/gesture API)
+ // name="0" — hide just the name plate
+ //
+ // JS API (after `await el.ready`):
+ // el.play(name), el.speak(text), el.gesture(name), el.snapshot()
+ // el.bridge — raw EmbedHostBridge in driveable mode
+ //
+ // Events: 'ready', 'error', 'blocked'
+ // ──────────────────────────────────────────────────────────────────────
+
+ if (typeof customElements === 'undefined' || customElements.get('threews-avatar')) return;
+
+ var COMPONENT_STYLES =
+ ':host{display:inline-block;position:relative;width:100%;min-width:200px;' +
+ 'min-height:200px;aspect-ratio:1/1;background:transparent;border-radius:inherit;' +
+ 'overflow:hidden;contain:layout style paint}' +
+ ':host([hidden]){display:none}' +
+ 'iframe{position:absolute;inset:0;width:100%;height:100%;border:0;' +
+ 'background:transparent;display:block}' +
+ '.error{position:absolute;inset:0;display:flex;align-items:center;' +
+ 'justify-content:center;color:rgba(255,255,255,0.5);background:rgba(0,0,0,0.25);' +
+ 'font:12px/1.4 system-ui,sans-serif;padding:12px;text-align:center}';
+
+ function cryptoRandomId() {
+ if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
+ return crypto.randomUUID();
+ }
+ return 'id-' + Math.random().toString(36).slice(2);
+ }
+
+ class ThreeWsAvatar extends HTMLElement {
+ static get observedAttributes() {
+ return [
+ 'src', 'avatar-id', 'agent', 'handle', 'pose', 'animation',
+ 'bg', 'chromakey', 'hide-chrome', 'name', 'driveable',
+ 'mocap', 'idle', 'lod', 'texture-size', 'morphs', 'draco',
+ ];
+ }
+
+ constructor() {
+ super();
+ this.attachShadow({ mode: 'open' });
+ this._iframe = null;
+ this._origin = ORIGIN;
+ this._destroyed = false;
+ this.bridge = null;
+ this._resetReady();
+ this._onMessage = handleAvatarMessage.bind(this);
+ }
+
+ _resetReady() {
+ var self = this;
+ this.ready = new Promise(function (resolve, reject) {
+ self._readyResolve = resolve;
+ self._readyReject = reject;
+ });
+ }
+
+ connectedCallback() {
+ var style = document.createElement('style');
+ style.textContent = COMPONENT_STYLES;
+ this.shadowRoot.appendChild(style);
+ mountAvatarFrame(this);
+ window.addEventListener('message', this._onMessage);
+ }
+
+ disconnectedCallback() {
+ this._destroyed = true;
+ window.removeEventListener('message', this._onMessage);
+ if (this._iframe) { this._iframe.remove(); this._iframe = null; }
+ if (this.bridge && typeof this.bridge.destroy === 'function') this.bridge.destroy();
+ this.bridge = null;
+ }
+
+ attributeChangedCallback(name, oldVal, newVal) {
+ if (oldVal === newVal) return;
+ if (
+ name === 'src' || name === 'avatar-id' || name === 'agent' ||
+ name === 'handle' || name === 'driveable' ||
+ name === 'mocap' || name === 'idle' || name === 'lod' ||
+ name === 'texture-size' || name === 'morphs' || name === 'draco'
+ ) {
+ if (this.isConnected) mountAvatarFrame(this);
+ return;
+ }
+ if (name === 'pose' || name === 'animation') {
+ if (newVal) this.play(newVal).catch(function () {});
+ return;
+ }
+ if (name === 'bg' || name === 'chromakey' || name === 'hide-chrome' || name === 'name') {
+ if (this.isConnected) mountAvatarFrame(this);
+ }
+ }
+
+ play(animationName) {
+ var self = this;
+ return this.ready.then(function () {
+ if (!animationName) return;
+ if (self.bridge) return self.bridge.gesture(animationName, { loop: true });
+ self.setAttribute('animation', animationName);
+ });
+ }
+
+ speak(text, opts) {
+ var self = this;
+ return this.ready.then(function () {
+ if (!self.bridge) throw new Error('threews-avatar: speak() requires `driveable`');
+ return self.bridge.speak(text, opts);
+ });
+ }
+
+ gesture(gestureName, opts) {
+ var self = this;
+ return this.ready.then(function () {
+ if (!self.bridge) throw new Error('threews-avatar: gesture() requires `driveable`');
+ return self.bridge.gesture(gestureName, opts);
+ });
+ }
+
+ snapshot() {
+ var self = this;
+ return this.ready.then(function () {
+ return new Promise(function (resolve) {
+ var id = cryptoRandomId();
+ function handler(ev) {
+ if (!self._iframe || ev.source !== self._iframe.contentWindow) return;
+ if (!ev.data || ev.data.id !== id) return;
+ window.removeEventListener('message', handler);
+ resolve(ev.data.dataUrl || null);
+ }
+ window.addEventListener('message', handler);
+ try {
+ self._iframe.contentWindow.postMessage(
+ { action: 'takeScreenshot', id: id }, self._origin,
+ );
+ } catch (e) {
+ window.removeEventListener('message', handler);
+ resolve(null);
+ }
+ setTimeout(function () {
+ window.removeEventListener('message', handler);
+ resolve(null);
+ }, 5000);
+ });
+ });
+ }
+ }
+
+ function mountAvatarFrame(el) {
+ if (el._iframe) { el._iframe.remove(); el._iframe = null; }
+ if (el.bridge && typeof el.bridge.destroy === 'function') el.bridge.destroy();
+ el.bridge = null;
+ var oldErr = el.shadowRoot.querySelector('.error');
+ if (oldErr) oldErr.remove();
+ el._resetReady();
+
+ var src = resolveAvatarIframeSrc(el);
+ if (!src) {
+ showAvatarError(el, 'threews-avatar: missing `src`, `avatar-id`, or `agent`');
+ return;
+ }
+ el._origin = new URL(src, location.href).origin;
+
+ var iframe = document.createElement('iframe');
+ iframe.src = src;
+ iframe.allow = 'autoplay; camera; microphone; xr-spatial-tracking';
+ iframe.setAttribute('allowtransparency', 'true');
+ iframe.setAttribute('aria-label', el.getAttribute('name') || 'three.ws avatar');
+ el.shadowRoot.appendChild(iframe);
+ el._iframe = iframe;
+
+ if (isAvatarDriveable(el)) upgradeAvatarToBridge(el);
+ }
+
+ function resolveAvatarIframeSrc(el) {
+ var driveable = isAvatarDriveable(el);
+ var src = el.getAttribute('src');
+ var avatarId = el.getAttribute('avatar-id');
+ var agentRef = el.getAttribute('agent');
+ var handle = el.getAttribute('handle');
+
+ // Portable @handle mount — routes to the v1.avatar.* embed runtime that
+ // supports lipsync, idle-life, and (optionally) webcam mocap.
+ if (handle) {
+ var h = String(handle).replace(/^@/, '');
+ var hUrl = new URL('/embed/avatar/' + encodeURIComponent(h), ORIGIN);
+ applyAvatarPortableParams(el, hUrl);
+ return hUrl.href;
+ }
+
+ if (driveable) {
+ if (!avatarId && !agentRef) return null;
+ var dUrl = new URL('/agent-embed', ORIGIN);
+ if (avatarId) dUrl.searchParams.set('agentId', avatarId);
+ if (agentRef) dUrl.searchParams.set('agent', agentRef);
+ applyAvatarCommonParams(el, dUrl);
+ return dUrl.href;
+ }
+
+ if (agentRef && /^[a-z0-9]+:\d+\/[a-z0-9]+:[\w-]+\/\d+$/i.test(agentRef)) {
+ var parts = agentRef.split('/');
+ var chainId = parts[0].split(':')[1];
+ var pUrl = new URL('/a/' + chainId + '/' + parts.slice(1).join('/') + '/embed', ORIGIN);
+ applyAvatarCommonParams(el, pUrl);
+ return pUrl.href;
+ }
+
+ if (avatarId) {
+ // Prefer the portable embed surface when no agent identity is needed
+ // — gives the host the v1.avatar.* bridge + idle-life out of the box.
+ var aUrl = new URL('/embed/avatar', ORIGIN);
+ aUrl.searchParams.set('id', avatarId);
+ applyAvatarPortableParams(el, aUrl);
+ return aUrl.href;
+ }
+
+ if (src) {
+ var sUrl = new URL('/embed/avatar', ORIGIN);
+ sUrl.searchParams.set('model', src);
+ applyAvatarPortableParams(el, sUrl);
+ return sUrl.href;
+ }
+
+ return null;
+ }
+
+ // Param set understood by the portable /embed/avatar runtime (v1.avatar.*).
+ function applyAvatarPortableParams(el, url) {
+ applyAvatarCommonParams(el, url);
+ var mocap = el.getAttribute('mocap');
+ if (mocap && mocap !== 'off') url.searchParams.set('mocap', mocap);
+ var idle = el.getAttribute('idle');
+ if (idle && idle !== 'on') url.searchParams.set('idle', idle);
+ var lod = el.getAttribute('lod');
+ if (lod) url.searchParams.set('lod', lod);
+ var ts = el.getAttribute('texture-size');
+ if (ts) url.searchParams.set('textureSize', ts);
+ var morphs = el.getAttribute('morphs');
+ if (morphs) url.searchParams.set('morphs', morphs);
+ var draco = el.getAttribute('draco');
+ if (draco) url.searchParams.set('draco', draco);
+ }
+
+ function applyAvatarCommonParams(el, url) {
+ var bg = el.getAttribute('bg');
+ if (bg) url.searchParams.set('bg', bg);
+ var ck = el.getAttribute('chromakey');
+ if (ck) url.searchParams.set('chromakey', ck);
+ if (el.hasAttribute('hide-chrome')) url.searchParams.set('hide-chrome', '1');
+ if (el.getAttribute('name') === '0') url.searchParams.set('name', '0');
+ var pose = el.getAttribute('pose') || el.getAttribute('animation');
+ if (pose) url.searchParams.set('animation', pose);
+ }
+
+ function isAvatarDriveable(el) {
+ return el.hasAttribute('driveable') && el.getAttribute('driveable') !== 'false';
+ }
+
+ function upgradeAvatarToBridge(el) {
+ import(ORIGIN + '/src/embed-host-bridge.js').then(function (mod) {
+ if (el._destroyed || !el._iframe) return;
+ var agentId = el.getAttribute('avatar-id') || el.getAttribute('agent') || 'unknown';
+ el.bridge = new mod.EmbedHostBridge({
+ iframe: el._iframe,
+ agentId: agentId,
+ allowedOrigin: el._origin,
+ });
+ }).catch(function (err) {
+ console.warn('[threews-avatar] driveable upgrade failed', err);
+ });
+ }
+
+ function handleAvatarMessage(ev) {
+ if (!this._iframe || ev.source !== this._iframe.contentWindow) return;
+ if (ev.origin && this._origin && ev.origin !== this._origin) return;
+ var data = ev.data;
+ if (!data || typeof data !== 'object') return;
+ if (!data.__agent) return;
+
+ if (data.type === 'ready') {
+ this._readyResolve({ name: data.name || '', avatar: data.avatar || null });
+ this.dispatchEvent(new CustomEvent('ready', { detail: data }));
+ } else if (data.type === 'error') {
+ showAvatarError(this, data.message || 'Failed to load');
+ this._readyReject(new Error(data.message || 'Failed to load'));
+ this.dispatchEvent(new CustomEvent('error', { detail: data }));
+ } else if (data.type === 'blocked') {
+ showAvatarError(this, 'Embedding blocked on ' + (data.host || 'this host') + '.');
+ this._readyReject(new Error('Embed blocked'));
+ this.dispatchEvent(new CustomEvent('blocked', { detail: data }));
+ }
+ }
+
+ function showAvatarError(el, message) {
+ var existing = el.shadowRoot.querySelector('.error');
+ if (existing) {
+ existing.textContent = message;
+ } else {
+ var div = document.createElement('div');
+ div.className = 'error';
+ div.textContent = message;
+ el.shadowRoot.appendChild(div);
+ }
+ }
+
+ customElements.define('threews-avatar', ThreeWsAvatar);
+ if (!customElements.get('agent-3d')) {
+ class Agent3D extends ThreeWsAvatar {}
+ customElements.define('agent-3d', Agent3D);
+ }
+
+ window.threeWs = window.threeWs || {};
+ window.threeWs.mount = function (target, options) {
+ options = options || {};
+ var host = typeof target === 'string' ? document.querySelector(target) : target;
+ if (!host) throw new Error('threeWs.mount: target not found');
+ var el = document.createElement('threews-avatar');
+ Object.keys(options).forEach(function (key) {
+ var val = options[key];
+ if (val == null) return;
+ var attrName = key.replace(/[A-Z]/g, function (c) { return '-' + c.toLowerCase(); });
+ el.setAttribute(attrName, typeof val === 'boolean' ? (val ? '' : null) : String(val));
+ });
+ host.appendChild(el);
+ return el;
+ };
+ window.threeWs.version = '1.0.0';
+
+ // Auto-mount when the loader script itself carries data-avatar / data-agent.
+ (function autoMountAvatar() {
+ try {
+ var s = document.currentScript ||
+ document.querySelector('script[data-avatar][src*="embed.js"], script[data-agent][src*="embed.js"]');
+ if (!s) return;
+ var avatar = s.getAttribute('data-avatar');
+ var agent = s.getAttribute('data-agent');
+ var avatarId = s.getAttribute('data-avatar-id');
+ if (!avatar && !agent && !avatarId) return;
+ if (s.getAttribute('data-widget')) return; // legacy widget snippet, handled above
+ var target = s.getAttribute('data-target');
+ var host = target ? document.querySelector(target) : null;
+ var el = document.createElement('threews-avatar');
+
+ // data-avatar="@handle" → portable @handle mount.
+ // data-avatar="<uuid>" → legacy avatar-id mount (back-compat).
+ // Discriminator: anything starting with @, or matching the username
+ // charset and *not* a UUID 8-4-4-4-12 pattern, is a handle.
+ if (avatar) {
+ var trimmed = String(avatar).trim();
+ var isUuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(trimmed);
+ var isHandle = !isUuid && (
+ trimmed.charAt(0) === '@' ||
+ /^[a-z0-9_-]{3,30}$/i.test(trimmed)
+ );
+ if (isHandle) {
+ el.setAttribute('handle', trimmed.replace(/^@/, ''));
+ } else {
+ el.setAttribute('avatar-id', trimmed);
+ }
+ }
+ if (avatarId) el.setAttribute('avatar-id', avatarId);
+ if (agent) el.setAttribute('agent', agent);
+ if (s.getAttribute('data-pose')) el.setAttribute('pose', s.getAttribute('data-pose'));
+ if (s.getAttribute('data-bg')) el.setAttribute('bg', s.getAttribute('data-bg'));
+ if (s.getAttribute('data-chromakey')) el.setAttribute('chromakey', s.getAttribute('data-chromakey'));
+ if (s.getAttribute('data-hide-chrome') || s.getAttribute('data-chrome') === '0') {
+ el.setAttribute('hide-chrome', '1');
+ }
+ if (s.getAttribute('data-driveable')) el.setAttribute('driveable', '');
+ // Portable-embed knobs (only meaningful when routed through /embed/avatar):
+ if (s.getAttribute('data-mocap')) el.setAttribute('mocap', s.getAttribute('data-mocap'));
+ if (s.getAttribute('data-idle')) el.setAttribute('idle', s.getAttribute('data-idle'));
+ if (s.getAttribute('data-lod')) el.setAttribute('lod', s.getAttribute('data-lod'));
+ if (s.getAttribute('data-texture-size')) el.setAttribute('texture-size', s.getAttribute('data-texture-size'));
+ if (s.getAttribute('data-morphs')) el.setAttribute('morphs', s.getAttribute('data-morphs'));
+ if (s.getAttribute('data-draco')) el.setAttribute('draco', s.getAttribute('data-draco'));
+ (host || s.parentNode || document.body).appendChild(el);
+ } catch (err) {
+ console.warn('[threews-embed] auto-mount failed', err);
+ }
+ })();
})();
diff --git a/public/sitemap.xml b/public/sitemap.xml
index 3c66c7c94..8d03927ac 100644
--- a/public/sitemap.xml
+++ b/public/sitemap.xml
@@ -2,277 +2,277 @@
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>https://three.ws/</loc>
- <lastmod>2026-05-23</lastmod>
+ <lastmod>2026-05-24</lastmod>
<changefreq>weekly</changefreq>
<priority>1.0</priority>
</url>
<url>
<loc>https://three.ws/discover</loc>
- <lastmod>2026-05-23</lastmod>
+ <lastmod>2026-05-24</lastmod>
<changefreq>daily</changefreq>
<priority>0.9</priority>
</url>
<url>
<loc>https://three.ws/gallery</loc>
- <lastmod>2026-05-23</lastmod>
+ <lastmod>2026-05-24</lastmod>
<changefreq>daily</changefreq>
<priority>0.8</priority>
</url>
<url>
<loc>https://three.ws/walk</loc>
- <lastmod>2026-05-23</lastmod>
+ <lastmod>2026-05-24</lastmod>
<changefreq>monthly</changefreq>
<priority>0.7</priority>
</url>
<url>
<loc>https://three.ws/marketplace</loc>
- <lastmod>2026-05-23</lastmod>
+ <lastmod>2026-05-24</lastmod>
<changefreq>daily</changefreq>
<priority>0.8</priority>
</url>
<url>
<loc>https://three.ws/community</loc>
- <lastmod>2026-05-23</lastmod>
+ <lastmod>2026-05-24</lastmod>
<changefreq>weekly</changefreq>
<priority>0.6</priority>
</url>
<url>
<loc>https://three.ws/sitemap</loc>
- <lastmod>2026-05-23</lastmod>
+ <lastmod>2026-05-24</lastmod>
<changefreq>weekly</changefreq>
<priority>0.4</priority>
</url>
<url>
<loc>https://three.ws/create</loc>
- <lastmod>2026-05-23</lastmod>
+ <lastmod>2026-05-24</lastmod>
<changefreq>weekly</changefreq>
<priority>0.9</priority>
</url>
<url>
<loc>https://three.ws/app</loc>
- <lastmod>2026-05-23</lastmod>
+ <lastmod>2026-05-24</lastmod>
<changefreq>monthly</changefreq>
<priority>0.7</priority>
</url>
<url>
<loc>https://three.ws/validation</loc>
- <lastmod>2026-05-23</lastmod>
+ <lastmod>2026-05-24</lastmod>
<changefreq>monthly</changefreq>
<priority>0.6</priority>
</url>
<url>
<loc>https://three.ws/studio</loc>
- <lastmod>2026-05-23</lastmod>
+ <lastmod>2026-05-24</lastmod>
<changefreq>weekly</changefreq>
<priority>0.8</priority>
</url>
<url>
<loc>https://three.ws/artifact</loc>
- <lastmod>2026-05-23</lastmod>
+ <lastmod>2026-05-24</lastmod>
<changefreq>monthly</changefreq>
<priority>0.5</priority>
</url>
<url>
<loc>https://three.ws/widgets</loc>
- <lastmod>2026-05-23</lastmod>
+ <lastmod>2026-05-24</lastmod>
<changefreq>weekly</changefreq>
<priority>0.7</priority>
</url>
<url>
<loc>https://three.ws/hydrate</loc>
- <lastmod>2026-05-23</lastmod>
+ <lastmod>2026-05-24</lastmod>
<changefreq>weekly</changefreq>
<priority>0.7</priority>
</url>
<url>
<loc>https://three.ws/features</loc>
- <lastmod>2026-05-23</lastmod>
+ <lastmod>2026-05-24</lastmod>
<changefreq>weekly</changefreq>
<priority>0.8</priority>
</url>
<url>
<loc>https://three.ws/launchpad</loc>
- <lastmod>2026-05-23</lastmod>
+ <lastmod>2026-05-24</lastmod>
<changefreq>weekly</changefreq>
<priority>0.7</priority>
</url>
<url>
<loc>https://three.ws/walkaround</loc>
- <lastmod>2026-05-23</lastmod>
+ <lastmod>2026-05-24</lastmod>
<changefreq>weekly</changefreq>
<priority>0.7</priority>
</url>
<url>
<loc>https://three.ws/brain</loc>
- <lastmod>2026-05-23</lastmod>
+ <lastmod>2026-05-24</lastmod>
<changefreq>weekly</changefreq>
<priority>0.7</priority>
</url>
<url>
<loc>https://three.ws/lipsync</loc>
- <lastmod>2026-05-23</lastmod>
+ <lastmod>2026-05-24</lastmod>
<changefreq>weekly</changefreq>
<priority>0.6</priority>
</url>
<url>
<loc>https://three.ws/lipsync/mic</loc>
- <lastmod>2026-05-23</lastmod>
+ <lastmod>2026-05-24</lastmod>
<changefreq>weekly</changefreq>
<priority>0.6</priority>
</url>
<url>
<loc>https://three.ws/avatar-artifact</loc>
- <lastmod>2026-05-23</lastmod>
+ <lastmod>2026-05-24</lastmod>
<changefreq>monthly</changefreq>
<priority>0.5</priority>
</url>
<url>
<loc>https://three.ws/pay</loc>
- <lastmod>2026-05-23</lastmod>
+ <lastmod>2026-05-24</lastmod>
<changefreq>weekly</changefreq>
<priority>0.9</priority>
</url>
<url>
<loc>https://three.ws/pumpfun</loc>
- <lastmod>2026-05-23</lastmod>
+ <lastmod>2026-05-24</lastmod>
<changefreq>daily</changefreq>
<priority>0.8</priority>
</url>
<url>
<loc>https://three.ws/pump-live</loc>
- <lastmod>2026-05-23</lastmod>
+ <lastmod>2026-05-24</lastmod>
<changefreq>daily</changefreq>
<priority>0.7</priority>
</url>
<url>
<loc>https://three.ws/pump-dashboard</loc>
- <lastmod>2026-05-23</lastmod>
+ <lastmod>2026-05-24</lastmod>
<changefreq>daily</changefreq>
<priority>0.8</priority>
</url>
<url>
<loc>https://three.ws/strategy-lab</loc>
- <lastmod>2026-05-23</lastmod>
+ <lastmod>2026-05-24</lastmod>
<changefreq>weekly</changefreq>
<priority>0.7</priority>
</url>
<url>
<loc>https://three.ws/vanity-wallet</loc>
- <lastmod>2026-05-23</lastmod>
+ <lastmod>2026-05-24</lastmod>
<changefreq>monthly</changefreq>
<priority>0.6</priority>
</url>
<url>
<loc>https://three.ws/eth-vanity</loc>
- <lastmod>2026-05-23</lastmod>
+ <lastmod>2026-05-24</lastmod>
<changefreq>monthly</changefreq>
<priority>0.6</priority>
</url>
<url>
<loc>https://three.ws/pump-visualizer</loc>
- <lastmod>2026-05-23</lastmod>
+ <lastmod>2026-05-24</lastmod>
<changefreq>weekly</changefreq>
<priority>0.7</priority>
</url>
<url>
<loc>https://three.ws/chat</loc>
- <lastmod>2026-05-23</lastmod>
+ <lastmod>2026-05-24</lastmod>
<changefreq>weekly</changefreq>
<priority>0.8</priority>
</url>
<url>
<loc>https://three.ws/agent</loc>
- <lastmod>2026-05-23</lastmod>
+ <lastmod>2026-05-24</lastmod>
<changefreq>weekly</changefreq>
<priority>0.7</priority>
</url>
<url>
<loc>https://three.ws/agents</loc>
- <lastmod>2026-05-23</lastmod>
+ <lastmod>2026-05-24</lastmod>
<changefreq>daily</changefreq>
<priority>0.7</priority>
</url>
<url>
<loc>https://three.ws/reputation</loc>
- <lastmod>2026-05-23</lastmod>
+ <lastmod>2026-05-24</lastmod>
<changefreq>weekly</changefreq>
<priority>0.6</priority>
</url>
<url>
<loc>https://three.ws/login</loc>
- <lastmod>2026-05-23</lastmod>
+ <lastmod>2026-05-24</lastmod>
<changefreq>yearly</changefreq>
<priority>0.4</priority>
</url>
<url>
<loc>https://three.ws/register</loc>
- <lastmod>2026-05-23</lastmod>
+ <lastmod>2026-05-24</lastmod>
<changefreq>yearly</changefreq>
<priority>0.4</priority>
</url>
<url>
<loc>https://three.ws/forgot-password</loc>
- <lastmod>2026-05-23</lastmod>
+ <lastmod>2026-05-24</lastmod>
<changefreq>yearly</changefreq>
<priority>0.2</priority>
</url>
<url>
<loc>https://three.ws/docs</loc>
- <lastmod>2026-05-23</lastmod>
+ <lastmod>2026-05-24</lastmod>
<changefreq>weekly</changefreq>
<priority>0.9</priority>
</url>
<url>
<loc>https://three.ws/docs/quick-start</loc>
- <lastmod>2026-05-23</lastmod>
+ <lastmod>2026-05-24</lastmod>
<changefreq>weekly</changefreq>
<priority>0.8</priority>
</url>
<url>
<loc>https://three.ws/docs/agent-system</loc>
- <lastmod>2026-05-23</lastmod>
+ <lastmod>2026-05-24</lastmod>
</url>
<url>
<loc>https://three.ws/docs/erc8004</loc>
- <lastmod>2026-05-23</lastmod>
+ <lastmod>2026-05-24</lastmod>
</url>
<url>
<loc>https://three.ws/docs/embedding</loc>
- <lastmod>2026-05-23</lastmod>
+ <lastmod>2026-05-24</lastmod>
</url>
<url>
<loc>https://three.ws/docs/web-component</loc>
- <lastmod>2026-05-23</lastmod>
+ <lastmod>2026-05-24</lastmod>
</url>
<url>
<loc>https://three.ws/docs/mcp</loc>
- <lastmod>2026-05-23</lastmod>
+ <lastmod>2026-05-24</lastmod>
</url>
<url>
<loc>https://three.ws/docs/skills</loc>
- <lastmod>2026-05-23</lastmod>
+ <lastmod>2026-05-24</lastmod>
</url>
<url>
<loc>https://three.ws/docs/widgets</loc>
- <lastmod>2026-05-23</lastmod>
+ <lastmod>2026-05-24</lastmod>
</url>
<url>
<loc>https://three.ws/docs/api-reference</loc>
- <lastmod>2026-05-23</lastmod>
+ <lastmod>2026-05-24</lastmod>
</url>
<url>
<loc>https://three.ws/docs/sdk</loc>
- <lastmod>2026-05-23</lastmod>
+ <lastmod>2026-05-24</lastmod>
</url>
<url>
<loc>https://three.ws/docs/listings</loc>
- <lastmod>2026-05-23</lastmod>
+ <lastmod>2026-05-24</lastmod>
<changefreq>monthly</changefreq>
<priority>0.5</priority>
</url>
<url>
<loc>https://three.ws/tutorials</loc>
- <lastmod>2026-05-23</lastmod>
+ <lastmod>2026-05-24</lastmod>
</url>
<url>
<loc>https://three.ws/blog</loc>
@@ -300,13 +300,13 @@
</url>
<url>
<loc>https://three.ws/legal/privacy</loc>
- <lastmod>2026-05-23</lastmod>
+ <lastmod>2026-05-24</lastmod>
<changefreq>yearly</changefreq>
<priority>0.2</priority>
</url>
<url>
<loc>https://three.ws/legal/tos</loc>
- <lastmod>2026-05-23</lastmod>
+ <lastmod>2026-05-24</lastmod>
<changefreq>yearly</changefreq>
<priority>0.2</priority>
</url>
diff --git a/public/studio/knowledge-panel.js b/public/studio/knowledge-panel.js
new file mode 100644
index 000000000..5aa9d47d3
--- /dev/null
+++ b/public/studio/knowledge-panel.js
@@ -0,0 +1,381 @@
+// Knowledge panel for the Widget Studio (talking-agent only).
+//
+// Lets the creator attach docs that the agent uses as grounding when a
+// visitor asks a question:
+// • URL ingest — server fetches + extracts visible text
+// • Paste text — plain or markdown
+// • Drop file — .txt / .md / .pdf (PDFs are extracted client-side via
+// pdfjs from the CDN; we send extracted text to the server)
+//
+// After ingest, the panel re-fetches the doc list and surfaces the server's
+// `preview_questions` so the creator can sanity-check that the doc landed in
+// retrieval — concrete proof, not "trust me it indexed."
+//
+// Mount: mountKnowledgePanel(rootEl, { getWidgetId, getCanEdit })
+// → returns { destroy, refresh }
+//
+// Calls /api/widgets/:id/knowledge — no separate listing/delete files needed.
+
+const PDFJS_CDN = 'https://cdn.jsdelivr.net/npm/[email protected]/build/pdf.min.mjs';
+const PDFJS_WORKER = 'https://cdn.jsdelivr.net/npm/[email protected]/build/pdf.worker.min.mjs';
+const MAX_PDF_BYTES = 12 * 1024 * 1024;
+const MAX_TEXT_LEN = 200_000;
+
+let _pdfjsPromise = null;
+function loadPdfjs() {
+ if (_pdfjsPromise) return _pdfjsPromise;
+ _pdfjsPromise = import(/* @vite-ignore */ PDFJS_CDN).then((mod) => {
+ try {
+ mod.GlobalWorkerOptions.workerSrc = PDFJS_WORKER;
+ } catch {}
+ return mod;
+ });
+ return _pdfjsPromise;
+}
+
+const ICON = {
+ url: '↗',
+ text: '¶',
+ markdown: '⌘',
+ pdf: '⎙',
+};
+
+export function mountKnowledgePanel(root, ctx) {
+ const { getWidgetId, getCanEdit } = ctx || {};
+ root.classList.add('knowledge-panel');
+ root.innerHTML = template();
+
+ const listEl = root.querySelector('[data-list]');
+ const emptyEl = root.querySelector('[data-empty]');
+ const fileEl = root.querySelector('[data-file]');
+ const urlEl = root.querySelector('[data-url]');
+ const textEl = root.querySelector('[data-text]');
+ const urlBtn = root.querySelector('[data-url-btn]');
+ const textBtn = root.querySelector('[data-text-btn]');
+ const dropEl = root.querySelector('[data-drop]');
+ const statusEl = root.querySelector('[data-status]');
+ const previewEl = root.querySelector('[data-preview]');
+
+ let busy = false;
+
+ fileEl.addEventListener('change', async () => {
+ const f = fileEl.files?.[0];
+ fileEl.value = '';
+ if (f) await ingestFile(f);
+ });
+ dropEl.addEventListener('dragover', (e) => {
+ e.preventDefault();
+ dropEl.classList.add('over');
+ });
+ dropEl.addEventListener('dragleave', () => dropEl.classList.remove('over'));
+ dropEl.addEventListener('drop', async (e) => {
+ e.preventDefault();
+ dropEl.classList.remove('over');
+ const f = e.dataTransfer?.files?.[0];
+ if (f) await ingestFile(f);
+ });
+ urlBtn.addEventListener('click', () => ingestUrl(urlEl.value.trim()));
+ textBtn.addEventListener('click', () => ingestText(textEl.value.trim()));
+
+ refresh();
+
+ return {
+ destroy() {
+ root.innerHTML = '';
+ },
+ refresh,
+ };
+
+ // ── render ──────────────────────────────────────────────────────────────
+
+ async function refresh() {
+ const widgetId = getWidgetId?.();
+ if (!widgetId) {
+ renderList([]);
+ setStatus('Save the widget once to start adding knowledge.');
+ disable(true);
+ return;
+ }
+ disable(!getCanEdit?.());
+ setStatus('');
+ try {
+ const res = await fetch(`/api/widgets/${encodeURIComponent(widgetId)}/knowledge`, {
+ credentials: 'include',
+ });
+ if (!res.ok) throw new Error(`${res.status}`);
+ const { docs = [] } = await res.json();
+ renderList(docs);
+ } catch (err) {
+ renderList([]);
+ setStatus(`Couldn't load knowledge: ${err.message}`, 'err');
+ }
+ }
+
+ function renderList(docs) {
+ listEl.innerHTML = '';
+ emptyEl.hidden = docs.length > 0;
+ for (const d of docs) listEl.appendChild(renderRow(d));
+ }
+
+ function renderRow(d) {
+ const row = document.createElement('div');
+ row.className = 'kp-row' + (d.status === 'failed' ? ' kp-row-err' : '');
+ const icon = ICON[d.source_type] || '·';
+ const sub = [
+ d.source_url ? linkify(d.source_url) : null,
+ d.chunk_count ? `${d.chunk_count} chunks` : null,
+ d.token_count ? `${formatNum(d.token_count)} tokens` : null,
+ d.status === 'failed' && d.error ? `error: ${escapeHtml(d.error)}` : null,
+ ]
+ .filter(Boolean)
+ .join(' · ');
+
+ row.innerHTML = `
+ <div class="kp-row-icon" aria-hidden="true">${icon}</div>
+ <div class="kp-row-meta">
+ <div class="kp-row-title">${escapeHtml(d.title)}</div>
+ <div class="kp-row-sub">${sub}</div>
+ </div>
+ <button class="kp-row-del" type="button" aria-label="Remove ${escapeHtml(d.title)}">×</button>
+ `;
+ row.querySelector('.kp-row-del').addEventListener('click', () => removeDoc(d));
+ return row;
+ }
+
+ function setStatus(msg, kind) {
+ statusEl.textContent = msg;
+ statusEl.className =
+ 'kp-status' + (kind === 'err' ? ' kp-err' : kind === 'ok' ? ' kp-ok' : '');
+ }
+
+ function renderPreview(doc) {
+ const qs = doc.preview_questions || [];
+ if (!qs.length) {
+ previewEl.innerHTML = '';
+ previewEl.hidden = true;
+ return;
+ }
+ previewEl.innerHTML = `
+ <div class="kp-preview-title">Your bot now knows <strong>${escapeHtml(doc.title)}</strong>. Try asking:</div>
+ <ul class="kp-preview-list">
+ ${qs.map((q) => `<li>${escapeHtml(q)}</li>`).join('')}
+ </ul>
+ `;
+ previewEl.hidden = false;
+ }
+
+ function disable(disabled) {
+ for (const el of root.querySelectorAll('input, textarea, button')) {
+ if (el.matches('[data-list] *')) continue;
+ el.disabled = disabled;
+ }
+ }
+
+ // ── ingest actions ──────────────────────────────────────────────────────
+
+ async function ingestFile(file) {
+ if (busy) return;
+ const widgetId = getWidgetId?.();
+ if (!widgetId) return setStatus('Save the widget first.', 'err');
+
+ const name = file.name || 'file';
+ const lower = name.toLowerCase();
+ const isPdf = file.type === 'application/pdf' || lower.endsWith('.pdf');
+ const isMd = lower.endsWith('.md') || lower.endsWith('.markdown');
+ const isTxt = file.type.startsWith('text/') || lower.endsWith('.txt') || isMd;
+ if (!isPdf && !isTxt) {
+ return setStatus(`Unsupported file type — drop a .txt, .md, or .pdf.`, 'err');
+ }
+ if (isPdf && file.size > MAX_PDF_BYTES) {
+ return setStatus(
+ `PDF must be under 12 MB (this one is ${formatBytes(file.size)}).`,
+ 'err',
+ );
+ }
+
+ setBusy(true, isPdf ? `Extracting ${name}…` : `Reading ${name}…`);
+ try {
+ let text;
+ if (isPdf) {
+ text = await extractPdf(file);
+ } else {
+ text = await file.text();
+ }
+ text = (text || '').trim();
+ if (text.length > MAX_TEXT_LEN) text = text.slice(0, MAX_TEXT_LEN);
+ if (!text) throw new Error('No text could be extracted.');
+
+ setStatus(`Embedding ${formatNum(text.length)} characters…`);
+ const doc = await postIngest({
+ title: name.replace(/\.(pdf|md|markdown|txt)$/i, '').slice(0, 120),
+ source_type: isPdf ? 'pdf' : isMd ? 'markdown' : 'text',
+ content: text,
+ byte_size: file.size,
+ });
+ setStatus(`Added "${doc.title}".`, 'ok');
+ renderPreview(doc);
+ await refresh();
+ } catch (err) {
+ setStatus(`Couldn't add: ${err.message}`, 'err');
+ } finally {
+ setBusy(false);
+ }
+ }
+
+ async function ingestUrl(url) {
+ if (busy) return;
+ if (!url) return setStatus('Paste a URL first.', 'err');
+ const widgetId = getWidgetId?.();
+ if (!widgetId) return setStatus('Save the widget first.', 'err');
+ setBusy(true, `Fetching ${url}…`);
+ try {
+ const doc = await postIngest({ source_type: 'url', source_url: url });
+ setStatus(`Added "${doc.title}".`, 'ok');
+ urlEl.value = '';
+ renderPreview(doc);
+ await refresh();
+ } catch (err) {
+ setStatus(`Couldn't add: ${err.message}`, 'err');
+ } finally {
+ setBusy(false);
+ }
+ }
+
+ async function ingestText(text) {
+ if (busy) return;
+ if (!text) return setStatus('Paste some text first.', 'err');
+ if (text.length > MAX_TEXT_LEN) text = text.slice(0, MAX_TEXT_LEN);
+ setBusy(true, `Embedding ${formatNum(text.length)} characters…`);
+ try {
+ const doc = await postIngest({ source_type: 'text', content: text });
+ setStatus(`Added "${doc.title}".`, 'ok');
+ textEl.value = '';
+ renderPreview(doc);
+ await refresh();
+ } catch (err) {
+ setStatus(`Couldn't add: ${err.message}`, 'err');
+ } finally {
+ setBusy(false);
+ }
+ }
+
+ async function removeDoc(doc) {
+ if (!confirm(`Remove "${doc.title}" from this widget's knowledge?`)) return;
+ const widgetId = getWidgetId?.();
+ try {
+ const res = await fetch(
+ `/api/widgets/${encodeURIComponent(widgetId)}/knowledge?doc_id=${encodeURIComponent(doc.id)}`,
+ { method: 'DELETE', credentials: 'include' },
+ );
+ if (!res.ok) throw new Error(`${res.status}`);
+ setStatus(`Removed.`, 'ok');
+ previewEl.hidden = true;
+ await refresh();
+ } catch (err) {
+ setStatus(`Couldn't remove: ${err.message}`, 'err');
+ }
+ }
+
+ async function postIngest(body) {
+ const widgetId = getWidgetId?.();
+ const res = await fetch(`/api/widgets/${encodeURIComponent(widgetId)}/knowledge`, {
+ method: 'POST',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify(body),
+ });
+ const data = await res.json().catch(() => ({}));
+ if (!res.ok) throw new Error(data.error_description || `${res.status}`);
+ return data.doc;
+ }
+
+ function setBusy(b, msg) {
+ busy = b;
+ root.classList.toggle('kp-busy', b);
+ disable(b || !getCanEdit?.());
+ if (msg !== undefined) setStatus(msg);
+ }
+}
+
+async function extractPdf(file) {
+ const pdfjs = await loadPdfjs();
+ const buf = await file.arrayBuffer();
+ const pdf = await pdfjs.getDocument({ data: buf, useWorkerFetch: true }).promise;
+ const pages = [];
+ for (let i = 1; i <= pdf.numPages; i++) {
+ const page = await pdf.getPage(i);
+ const tc = await page.getTextContent();
+ const line = tc.items.map((it) => it.str || '').join(' ');
+ pages.push(line);
+ }
+ return pages.join('\n\n');
+}
+
+function template() {
+ return `
+ <header class="kp-head">
+ <h3>Knowledge</h3>
+ <p class="kp-sub">Ground the agent in your docs. PDFs, URLs, or pasted text — chunks are embedded and surfaced when a visitor asks a relevant question.</p>
+ </header>
+
+ <div class="kp-list-wrap">
+ <div class="kp-list" data-list></div>
+ <div class="kp-empty" data-empty>No knowledge attached yet.</div>
+ </div>
+
+ <div class="kp-drop" data-drop>
+ <div class="kp-drop-inner">
+ <strong>Drop a file</strong> or
+ <label class="kp-drop-link">
+ <input type="file" data-file accept=".txt,.md,.markdown,.pdf,text/plain,text/markdown,application/pdf" hidden />
+ <span>choose one</span>
+ </label>
+ <div class="kp-drop-hint">.txt · .md · .pdf (up to 12 MB)</div>
+ </div>
+ </div>
+
+ <details class="kp-section">
+ <summary>Add a URL</summary>
+ <div class="kp-row-form">
+ <input type="url" data-url placeholder="https://docs.example.com/getting-started" />
+ <button type="button" class="btn-ghost btn-sm" data-url-btn>Fetch & add</button>
+ </div>
+ </details>
+
+ <details class="kp-section">
+ <summary>Paste text</summary>
+ <div class="kp-paste-form">
+ <textarea data-text rows="4" placeholder="Paste pricing notes, product docs, FAQs…"></textarea>
+ <button type="button" class="btn-ghost btn-sm" data-text-btn>Add as knowledge</button>
+ </div>
+ </details>
+
+ <div class="kp-status" data-status></div>
+ <div class="kp-preview" data-preview hidden></div>
+ `;
+}
+
+function formatNum(n) {
+ const v = Number(n) || 0;
+ if (v >= 1000) return `${(v / 1000).toFixed(v >= 10_000 ? 0 : 1)}k`;
+ return String(v);
+}
+
+function formatBytes(n) {
+ const v = Number(n) || 0;
+ if (v >= 1024 * 1024) return `${(v / (1024 * 1024)).toFixed(1)} MB`;
+ if (v >= 1024) return `${(v / 1024).toFixed(1)} KB`;
+ return `${v} B`;
+}
+
+function escapeHtml(s) {
+ return String(s ?? '').replace(
+ /[&<>"']/g,
+ (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c],
+ );
+}
+
+function linkify(url) {
+ const safe = escapeHtml(url);
+ return `<a href="${safe}" target="_blank" rel="noopener">${safe}</a>`;
+}
diff --git a/public/studio/studio.css b/public/studio/studio.css
index 672d9145e..8203facea 100644
--- a/public/studio/studio.css
+++ b/public/studio/studio.css
@@ -1063,3 +1063,127 @@ a:hover {
letter-spacing: 0.04em;
text-transform: uppercase;
}
+
+/* ── Knowledge panel ────────────────────────────────────────────────── */
+.knowledge-panel {
+ margin-top: 1.1rem;
+ padding-top: 1rem;
+ border-top: 1px solid rgba(255, 255, 255, 0.08);
+ display: flex;
+ flex-direction: column;
+ gap: 0.75rem;
+}
+.kp-head { display: flex; flex-direction: column; gap: 0.2rem; }
+.kp-head h3 { margin: 0; font-size: 0.95rem; font-weight: 600; }
+.kp-sub { margin: 0; color: var(--muted); font-size: 0.78rem; line-height: 1.4; }
+
+.kp-list-wrap { position: relative; }
+.kp-list { display: flex; flex-direction: column; gap: 0.4rem; }
+.kp-empty {
+ color: var(--muted);
+ font-size: 0.8rem;
+ text-align: center;
+ padding: 0.6rem;
+ border: 1px dashed rgba(255, 255, 255, 0.08);
+ border-radius: 8px;
+}
+.kp-row {
+ display: grid;
+ grid-template-columns: 28px 1fr auto;
+ align-items: center;
+ gap: 0.55rem;
+ padding: 0.5rem 0.6rem;
+ background: rgba(255, 255, 255, 0.025);
+ border: 1px solid rgba(255, 255, 255, 0.06);
+ border-radius: 8px;
+}
+.kp-row-err { border-color: rgba(255, 80, 80, 0.4); }
+.kp-row-icon {
+ width: 26px; height: 26px;
+ display: grid; place-items: center;
+ border-radius: 6px;
+ background: rgba(139, 92, 246, 0.15);
+ color: var(--accent-strong, #b794f6);
+ font-size: 0.9rem;
+}
+.kp-row-meta { min-width: 0; }
+.kp-row-title {
+ font-size: 0.82rem;
+ font-weight: 500;
+ overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
+}
+.kp-row-sub {
+ font-size: 0.7rem;
+ color: var(--muted);
+ overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
+ margin-top: 2px;
+}
+.kp-row-sub a { color: inherit; text-decoration: underline; }
+.kp-row-del {
+ background: transparent;
+ border: 1px solid rgba(255, 255, 255, 0.1);
+ color: var(--muted);
+ width: 26px; height: 26px;
+ border-radius: 6px;
+ cursor: pointer;
+ font-size: 0.95rem;
+ line-height: 1;
+}
+.kp-row-del:hover { color: #fff; border-color: rgba(255, 80, 80, 0.5); }
+
+.kp-drop {
+ padding: 1rem 0.8rem;
+ border: 1px dashed rgba(255, 255, 255, 0.18);
+ border-radius: 10px;
+ text-align: center;
+ background: rgba(255, 255, 255, 0.015);
+ transition: background 0.15s ease, border-color 0.15s ease;
+}
+.kp-drop.over {
+ border-color: var(--accent-strong, #b794f6);
+ background: rgba(139, 92, 246, 0.08);
+}
+.kp-drop-inner { display: flex; flex-direction: column; align-items: center; gap: 4px; font-size: 0.82rem; }
+.kp-drop-link { cursor: pointer; text-decoration: underline; }
+.kp-drop-hint { color: var(--muted); font-size: 0.7rem; }
+
+.kp-section { background: rgba(255, 255, 255, 0.02); border: 1px solid rgba(255, 255, 255, 0.06); border-radius: 8px; padding: 0.55rem 0.7rem; }
+.kp-section[open] { padding-bottom: 0.7rem; }
+.kp-section summary { cursor: pointer; font-size: 0.8rem; }
+.kp-section[open] summary { margin-bottom: 0.55rem; }
+.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;
+ border: 1px solid rgba(255, 255, 255, 0.1);
+ color: #eee;
+ border-radius: 6px;
+ padding: 0.45rem 0.6rem;
+ font-family: inherit;
+ font-size: 0.85rem;
+}
+.kp-paste-form textarea { resize: vertical; min-height: 80px; }
+
+.kp-status { font-size: 0.78rem; color: var(--muted); min-height: 1.1em; }
+.kp-status.kp-ok { color: #6fe8a4; }
+.kp-status.kp-err { color: #ff7676; }
+
+.kp-busy { opacity: 0.7; pointer-events: none; }
+
+.kp-preview {
+ background: rgba(139, 92, 246, 0.08);
+ border: 1px solid rgba(139, 92, 246, 0.25);
+ border-radius: 8px;
+ padding: 0.7rem 0.85rem;
+}
+.kp-preview-title { font-size: 0.8rem; margin-bottom: 0.4rem; }
+.kp-preview-list { margin: 0; padding-left: 1.1rem; font-size: 0.78rem; color: var(--muted); display: flex; flex-direction: column; gap: 2px; }
+
+.kp-transcripts-link {
+ margin-top: 0.7rem;
+ padding-top: 0.7rem;
+ border-top: 1px dashed rgba(255, 255, 255, 0.08);
+ font-size: 0.8rem;
+}
+.kp-transcripts-link a { color: var(--accent-strong, #b794f6); text-decoration: none; }
+.kp-transcripts-link a:hover { text-decoration: underline; }
diff --git a/public/studio/studio.js b/public/studio/studio.js
index ee1922980..ec645b8fd 100644
--- a/public/studio/studio.js
+++ b/public/studio/studio.js
@@ -6,6 +6,7 @@
// Keep this list in sync with src/widget-types.js as new types light up.
import { mountLaunchPanel } from './launch-panel.js';
+import { mountKnowledgePanel } from './knowledge-panel.js';
const WIDGET_TYPES = {
turntable: {
@@ -188,7 +189,11 @@ function userInitial(u) {
async function signOut() {
await fetch('/api/auth/logout', { method: 'POST', credentials: 'include' }).catch(() => {});
- try { localStorage.removeItem('3dagent:auth-hint'); } catch { /* ignore */ }
+ try {
+ localStorage.removeItem('3dagent:auth-hint');
+ } catch {
+ /* ignore */
+ }
location.href = '/';
}
@@ -421,8 +426,8 @@ function appendAvatarCard(list, a) {
const badge = a.is_demo
? '<span class="badge-demo">Demo</span>'
: a.is_public_browse
- ? '<span class="badge-public">Public</span>'
- : '';
+ ? '<span class="badge-public">Public</span>'
+ : '';
card.innerHTML = `${thumb}<span class="name">${escapeHtml(a.name || a.slug || a.id)}</span>${badge}`;
card.addEventListener('click', () => selectAvatar(a.id));
list.appendChild(card);
@@ -513,6 +518,9 @@ function renderTypeFields() {
}),
);
}
+ if (state.type === 'talking-agent') {
+ mountTalkingAgentExtras(wrap);
+ }
if (state.type === 'pumpfun-feed') {
wrap.appendChild(
selectField('kind', 'Event kind', state.config.kind ?? 'all', [
@@ -542,6 +550,62 @@ function renderTypeFields() {
}
}
+function mountTalkingAgentExtras(wrap) {
+ wrap.appendChild(
+ textField('agentName', 'Agent name', state.config.agentName || '', {
+ max: 80,
+ placeholder: 'e.g. "Ada"',
+ }),
+ );
+ wrap.appendChild(
+ textField('agentTitle', 'Agent title', state.config.agentTitle || 'AI Agent', {
+ max: 80,
+ placeholder: 'e.g. "Support bot"',
+ }),
+ );
+ wrap.appendChild(
+ textField('greeting', 'Greeting', state.config.greeting || 'Hi! Ask me anything.', {
+ max: 280,
+ placeholder: 'First message visitors see',
+ }),
+ );
+ wrap.appendChild(
+ textareaField('systemPrompt', 'System prompt', state.config.systemPrompt || '', {
+ max: 4000,
+ placeholder: 'Describe how the agent should behave — tone, topics, what to avoid.',
+ rows: 4,
+ }),
+ );
+ wrap.appendChild(
+ selectField('brainProvider', 'LLM provider', state.config.brainProvider || 'auto', [
+ ['auto', 'Auto (first configured)'],
+ ['anthropic', 'Anthropic (Claude)'],
+ ['openai', 'OpenAI'],
+ ['groq', 'Groq'],
+ ['openrouter', 'OpenRouter'],
+ ]),
+ );
+
+ const knowledgeMount = document.createElement('div');
+ knowledgeMount.id = 'studio-knowledge';
+ wrap.appendChild(knowledgeMount);
+
+ const transcriptsLink = document.createElement('div');
+ transcriptsLink.className = 'kp-transcripts-link';
+ transcriptsLink.innerHTML = state.editingId
+ ? `<a href="/dashboard/widgets?w=${encodeURIComponent(state.editingId)}#transcripts" target="_blank" rel="noopener">View chat transcripts →</a>`
+ : '<span class="muted">Save the widget to see chat transcripts in the dashboard.</span>';
+ wrap.appendChild(transcriptsLink);
+
+ if (_knowledgePanel) _knowledgePanel.destroy?.();
+ _knowledgePanel = mountKnowledgePanel(knowledgeMount, {
+ getWidgetId: () => state.editingId || null,
+ getCanEdit: () => !!state.user && !!state.editingId,
+ });
+}
+
+let _knowledgePanel = null;
+
function selectField(name, label, value, options) {
const f = document.createElement('label');
f.className = 'field';
@@ -571,6 +635,32 @@ function boolField(name, label, checked) {
return f;
}
+function textField(name, label, value, { max = 200, placeholder = '' } = {}) {
+ const f = document.createElement('label');
+ f.className = 'field';
+ f.innerHTML = `<span>${escapeHtml(label)}</span>
+ <input type="text" name="${attr(name)}" maxlength="${max}"
+ placeholder="${attr(placeholder)}" value="${attr(String(value || ''))}">`;
+ f.querySelector('input').addEventListener('input', (e) => {
+ state.config[name] = e.target.value;
+ schedulePreview();
+ });
+ return f;
+}
+
+function textareaField(name, label, value, { max = 4000, placeholder = '', rows = 4 } = {}) {
+ const f = document.createElement('label');
+ f.className = 'field';
+ f.innerHTML = `<span>${escapeHtml(label)}</span>
+ <textarea name="${attr(name)}" maxlength="${max}" rows="${rows}"
+ placeholder="${attr(placeholder)}">${escapeHtml(String(value || ''))}</textarea>`;
+ f.querySelector('textarea').addEventListener('input', (e) => {
+ state.config[name] = e.target.value;
+ schedulePreview();
+ });
+ return f;
+}
+
function numberField(name, label, value, { min, max, step }) {
const f = document.createElement('label');
f.className = 'field';
@@ -733,10 +823,13 @@ function wireButtons() {
launchPanel = mountLaunchPanel(panelLaunch, {
getAvatar: () => findAvatar(state.avatarId),
- getUser: () => state.user,
+ getUser: () => state.user,
getPreviewViewer: () => {
- try { return previewIfr?.contentWindow?.VIEWER?.viewer || null; }
- catch { return null; }
+ try {
+ return previewIfr?.contentWindow?.VIEWER?.viewer || null;
+ } catch {
+ return null;
+ }
},
});
@@ -822,9 +915,12 @@ function updatePreview(forceReload) {
previewSt.textContent = 'Loading preview…';
// Cache-buster query forces a full reload. Without it, hash-only
// changes (e.g. switching avatars) trigger fragment navigation in
- // the iframe — and /app reads `model`/`type` from the hash only on
- // boot, so the preview wouldn't update.
- previewIfr.src = `/app?_=${Date.now()}#${hashStr}`;
+ // the iframe — and the widget shell reads `model`/`type` from the
+ // hash only on boot, so the preview wouldn't update.
+ // /widget is the slim viewer shell — same /src/app.js bundle, but
+ // without site nav/footer/auth chrome in the DOM, so the preview
+ // doesn't flash the marketing site before the model renders.
+ previewIfr.src = `/widget?_=${Date.now()}#${hashStr}`;
}
postConfigToPreview();
}
@@ -904,6 +1000,7 @@ async function save({ generate }) {
throw new Error(data.error_description || `save failed: ${res.status}`);
}
const { widget } = await res.json();
+ const wasNew = !state.editingId;
state.editingId = widget.id;
const newUrl = new URL(location.href);
newUrl.searchParams.set('edit', widget.id);
@@ -911,6 +1008,10 @@ async function save({ generate }) {
newUrl.searchParams.delete('model');
history.replaceState(null, '', newUrl);
+ // Re-render type fields so the Knowledge panel picks up the new id
+ // (it was disabled until the widget had a row to attach docs to).
+ if (wasNew && state.type === 'talking-agent') renderTypeFields();
+
if (generate) openEmbedModal(widget);
else toast('Saved');
} catch (err) {
@@ -940,14 +1041,15 @@ function _refreshEmbedSnippet() {
const url = _buildEmbedUrl(_currentEmbedUrl);
const w = parseInt($('#embed-width').value) || 600;
const h = parseInt($('#embed-height').value) || 600;
- $('#embed-iframe-snippet').value = `<iframe src="${url}" width="${w}" height="${h}" style="border:0;border-radius:12px" allow="autoplay; xr-spatial-tracking" loading="lazy"></iframe>`;
+ $('#embed-iframe-snippet').value =
+ `<iframe src="${url}" width="${w}" height="${h}" style="border:0;border-radius:12px" allow="autoplay; xr-spatial-tracking" loading="lazy"></iframe>`;
$('#embed-preview-iframe').src = url;
}
function openEmbedModal(widget) {
const origin = location.origin;
const shareUrl = `${origin}/w/${widget.id}`;
- _currentEmbedUrl = `${origin}/app#widget=${widget.id}&kiosk=true`;
+ _currentEmbedUrl = `${origin}/widget#widget=${widget.id}&kiosk=true`;
_currentWidgetType = widget.type || state.type;
const demoNote = $('#embed-demo-note');
diff --git a/public/style.css b/public/style.css
index b68d4e4c0..8e5aebdd3 100644
--- a/public/style.css
+++ b/public/style.css
@@ -114,6 +114,153 @@ body {
min-height: 0;
}
+/* ── Viewer status overlay ──────────────────────────────────────────────
+ Centered card inside #viewer-container that reflects load state.
+ Driven from JS via App._showViewerLoading / _showViewerError. */
+.viewer-status {
+ position: absolute;
+ inset: 0;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ pointer-events: none;
+ z-index: 10;
+}
+.viewer-status[hidden] {
+ display: none;
+}
+.viewer-status__card {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 14px;
+ padding: 22px 28px;
+ background: rgba(18, 18, 24, 0.78);
+ backdrop-filter: blur(14px);
+ -webkit-backdrop-filter: blur(14px);
+ border: 1px solid rgba(255, 255, 255, 0.08);
+ border-radius: 14px;
+ box-shadow: 0 8px 32px rgba(0, 0, 0, 0.45);
+ pointer-events: auto;
+ min-width: 200px;
+ max-width: 360px;
+ text-align: center;
+}
+.viewer-status__card--error {
+ border-color: rgba(239, 68, 68, 0.32);
+ box-shadow: 0 8px 32px rgba(239, 68, 68, 0.18);
+}
+.viewer-status__spinner {
+ width: 28px;
+ height: 28px;
+ border-radius: 50%;
+ border: 2px solid rgba(255, 255, 255, 0.08);
+ border-top-color: rgba(167, 139, 250, 0.9);
+ border-right-color: rgba(167, 139, 250, 0.4);
+ animation: sk-spin 0.9s linear infinite;
+}
+.viewer-status__icon {
+ width: 32px;
+ height: 32px;
+ border-radius: 50%;
+ background: rgba(239, 68, 68, 0.18);
+ color: rgba(254, 202, 202, 1);
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ font-weight: 700;
+ font-size: 18px;
+ line-height: 1;
+}
+.viewer-status__label {
+ font-size: 14px;
+ line-height: 1.4;
+ color: rgba(255, 255, 255, 0.88);
+ letter-spacing: 0.01em;
+}
+.viewer-status__btn {
+ appearance: none;
+ border: 1px solid rgba(255, 255, 255, 0.18);
+ background: rgba(255, 255, 255, 0.06);
+ color: white;
+ padding: 7px 18px;
+ border-radius: 8px;
+ font-size: 13px;
+ font-weight: 500;
+ cursor: pointer;
+ transition: background 0.15s ease, border-color 0.15s ease;
+}
+.viewer-status__btn:hover {
+ background: rgba(255, 255, 255, 0.12);
+ border-color: rgba(255, 255, 255, 0.28);
+}
+.viewer-status__btn:active {
+ transform: translateY(1px);
+}
+.viewer-status__progress {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ width: 100%;
+ min-width: 220px;
+ margin-top: 2px;
+}
+.viewer-status__progress[hidden] {
+ display: none;
+}
+.viewer-status__progress-track {
+ width: 100%;
+ height: 4px;
+ background: rgba(255, 255, 255, 0.08);
+ border-radius: 999px;
+ overflow: hidden;
+}
+.viewer-status__progress-fill {
+ height: 100%;
+ background: linear-gradient(
+ 90deg,
+ rgba(167, 139, 250, 0.9),
+ rgba(139, 92, 246, 0.9)
+ );
+ border-radius: inherit;
+ transition: width 0.18s ease-out;
+}
+.viewer-status__progress-meta {
+ font-size: 11px;
+ font-variant-numeric: tabular-nums;
+ letter-spacing: 0.02em;
+ color: rgba(255, 255, 255, 0.55);
+ text-align: center;
+}
+
+/* ── Avatar poster (model-viewer–style) ──────────────────────────────
+ Sits OVER the WebGL canvas (which clears to opaque black) while the
+ GLB streams in, so the user sees their avatar's thumbnail instead of
+ a black void. Loading overlay (z:10) stays on top. Faded out on
+ LOAD_END(success), revealing the rendered model below. */
+.viewer-poster {
+ position: absolute;
+ inset: 0;
+ width: 100%;
+ height: 100%;
+ object-fit: contain;
+ object-position: center;
+ z-index: 5;
+ opacity: 1;
+ transition: opacity 0.55s ease;
+ pointer-events: none;
+ background:
+ radial-gradient(
+ ellipse at center,
+ rgba(40, 40, 50, 0.55) 0%,
+ rgba(10, 10, 14, 0.95) 80%
+ );
+ filter: drop-shadow(0 8px 24px rgba(0, 0, 0, 0.35));
+}
+.viewer-poster--fading {
+ opacity: 0;
+}
+
.dropzone {
display: flex;
align-items: center;
@@ -7592,3 +7739,556 @@ textarea.erc8004-code {
gap: 6px;
}
.pumpfun-bot-grid .pumpfun-trade-label { margin: 0; }
+
+/******************************************************************************
+ * Next layout — the alternate /app chrome (toggled via body[data-layout='next'])
+ *
+ * Goals borrowed from the 2025-26 best-in-class survey:
+ * - Edge-to-edge stage; a single bottom command dock holds playback
+ * (Sketchfab-style chip + scrubbable timeline)
+ * - One floating corner cluster for Controls / Share / Fullscreen
+ * (model-viewer minimalism + Babylon-Sandbox floating gear → drawer)
+ * - The dat.GUI panel physically moves into a right-side drawer so
+ * every camera/lighting/material knob still works untouched
+ * - Auto-rotate kicks in after a few seconds of idle (Luma's signature)
+ * - First-load hand swipe affordance, dismissed on first input
+ */
+
+/* Hide chrome by mode. Default (no attribute or 'classic') hides Next chrome. */
+body:not([data-layout='next']) .next-chrome {
+ display: none !important;
+}
+body[data-layout='next'] .next-chrome {
+ display: block;
+}
+
+/* In Next mode, strip Classic-only chrome from the viewer surface */
+body[data-layout='next'] .dropzone,
+body[data-layout='next'] .agent-presence-sidebar,
+body[data-layout='next'] .auth-gate,
+body[data-layout='next'] .agent-onboarding,
+body[data-layout='next'] .gui-toggle,
+body[data-layout='next'] .ar-btn,
+body[data-layout='next'] .anim-panel,
+body[data-layout='next'] .footer-bot,
+body[data-layout='next'] footer {
+ display: none !important;
+}
+
+/* In Next mode, collapse the busy primary nav and page-action buttons —
+ * page actions now live in the Share popover; primary nav items stay
+ * reachable via the user menu / Dashboard link. The layout switch and
+ * user/sign-in always remain so the toggle and account are never lost. */
+body[data-layout='next'] header .features-nav > a:not([href='/app']):not(.nav-dashboard):not(.nav-sign-in),
+body[data-layout='next'] header .save-to-account-btn,
+body[data-layout='next'] header .make-widget-btn,
+body[data-layout='next'] header .deploy-onchain-btn,
+body[data-layout='next'] header .view-public-profile-btn {
+ display: none !important;
+}
+
+body[data-layout='next'] header .nav-viewer-link,
+body[data-layout='next'] header a[href='/app'] {
+ font-weight: 600;
+}
+
+/* When the GUI panel has been moved into the drawer, it must drop its
+ * absolute positioning so it lays out inside the drawer body normally. */
+body[data-layout='next'] .next-drawer__body > .gui-wrap {
+ position: static;
+ pointer-events: auto;
+ opacity: 1;
+ transform: none;
+ visibility: visible;
+ width: 100%;
+}
+body[data-layout='next'] .next-drawer__body > .gui-wrap > .main {
+ max-height: none;
+ width: 100% !important;
+ background: transparent !important;
+}
+body[data-layout='next'] .next-drawer__body .dg.main .close-button.close-bottom {
+ display: none;
+}
+
+/* ── Interaction prompt ─────────────────────────────────────────────────── */
+.next-prompt {
+ position: fixed;
+ left: 50%;
+ bottom: 140px;
+ transform: translateX(-50%);
+ display: inline-flex;
+ align-items: center;
+ gap: 8px;
+ padding: 8px 14px;
+ background: rgba(15, 15, 22, 0.7);
+ border: 1px solid rgba(255, 255, 255, 0.08);
+ border-radius: 999px;
+ color: rgba(255, 255, 255, 0.85);
+ font-family: var(--font-body);
+ font-size: var(--text-xs);
+ letter-spacing: 0.02em;
+ pointer-events: none;
+ backdrop-filter: blur(14px);
+ -webkit-backdrop-filter: blur(14px);
+ z-index: 32;
+ animation: nextPromptIn 600ms ease both, nextPromptPulse 2.4s ease-in-out 800ms infinite;
+}
+.next-prompt svg { opacity: 0.85; }
+.next-prompt--out {
+ animation: nextPromptOut 400ms ease forwards;
+}
+@keyframes nextPromptIn {
+ from { opacity: 0; transform: translate(-50%, 8px); }
+ to { opacity: 1; transform: translate(-50%, 0); }
+}
+@keyframes nextPromptOut {
+ from { opacity: 1; transform: translate(-50%, 0); }
+ to { opacity: 0; transform: translate(-50%, -6px); }
+}
+@keyframes nextPromptPulse {
+ 0%, 100% { transform: translate(-50%, 0); }
+ 50% { transform: translate(-50%, -3px); }
+}
+
+/* ── Corner cluster ─────────────────────────────────────────────────────── */
+.next-corner {
+ position: fixed;
+ top: 80px;
+ right: 16px;
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ z-index: 34;
+}
+.next-icon-btn {
+ width: 36px;
+ height: 36px;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ background: rgba(15, 15, 22, 0.78);
+ color: rgba(255, 255, 255, 0.72);
+ border: 1px solid rgba(255, 255, 255, 0.08);
+ border-radius: 10px;
+ cursor: pointer;
+ backdrop-filter: blur(14px);
+ -webkit-backdrop-filter: blur(14px);
+ transition:
+ background 0.18s ease,
+ color 0.18s ease,
+ border-color 0.18s ease,
+ transform 0.18s ease;
+ position: relative;
+}
+.next-icon-btn:hover {
+ background: rgba(28, 28, 38, 0.88);
+ color: #fff;
+ border-color: rgba(255, 255, 255, 0.18);
+}
+.next-icon-btn:focus-visible {
+ outline: 2px solid rgba(139, 92, 246, 0.6);
+ outline-offset: 2px;
+}
+.next-icon-btn--active {
+ background: rgba(139, 92, 246, 0.22);
+ color: #fff;
+ border-color: rgba(139, 92, 246, 0.5);
+}
+.next-icon-btn--has-actions::after {
+ content: '';
+ position: absolute;
+ top: 6px;
+ right: 6px;
+ width: 6px;
+ height: 6px;
+ border-radius: 50%;
+ background: #c4b5fd;
+ box-shadow: 0 0 0 2px rgba(15, 15, 22, 0.78);
+}
+
+/* ── Share popover ──────────────────────────────────────────────────────── */
+.next-share-menu {
+ position: fixed;
+ top: 80px;
+ right: 60px;
+ width: 260px;
+ background: rgba(15, 15, 22, 0.92);
+ border: 1px solid rgba(255, 255, 255, 0.08);
+ border-radius: 12px;
+ box-shadow: 0 10px 40px rgba(0, 0, 0, 0.5);
+ padding: 6px;
+ z-index: 36;
+ backdrop-filter: blur(20px);
+ -webkit-backdrop-filter: blur(20px);
+ animation: nextMenuIn 160ms ease;
+}
+.next-share-menu__title {
+ font-size: var(--text-xs);
+ font-weight: 600;
+ letter-spacing: 0.04em;
+ text-transform: uppercase;
+ color: rgba(255, 255, 255, 0.4);
+ padding: 8px 10px 4px;
+}
+.next-share-menu__item {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ width: 100%;
+ padding: 8px 10px;
+ border-radius: 8px;
+ background: transparent;
+ border: 0;
+ color: rgba(255, 255, 255, 0.85);
+ font-family: inherit;
+ font-size: var(--text-sm);
+ font-weight: 500;
+ text-align: left;
+ text-decoration: none;
+ cursor: pointer;
+ transition: background 0.15s ease, color 0.15s ease;
+}
+.next-share-menu__item:hover {
+ background: rgba(255, 255, 255, 0.06);
+ color: #fff;
+}
+.next-share-menu__item svg { flex-shrink: 0; color: rgba(255, 255, 255, 0.55); }
+.next-share-menu__item:hover svg { color: #fff; }
+.next-share-menu__item[hidden] { display: none; }
+.next-share-menu__item--success {
+ color: #86efac;
+}
+.next-share-menu__item--success svg { color: #86efac; }
+.next-share-menu__sep {
+ height: 1px;
+ background: rgba(255, 255, 255, 0.06);
+ margin: 6px 4px;
+}
+@keyframes nextMenuIn {
+ from { opacity: 0; transform: translateY(-4px); }
+ to { opacity: 1; transform: translateY(0); }
+}
+
+/* ── Right-side Controls drawer ─────────────────────────────────────────── */
+.next-drawer {
+ position: fixed;
+ top: 0;
+ right: 0;
+ bottom: 0;
+ width: 360px;
+ max-width: 90vw;
+ background: rgba(12, 12, 18, 0.96);
+ border-left: 1px solid rgba(255, 255, 255, 0.06);
+ box-shadow: -16px 0 48px rgba(0, 0, 0, 0.45);
+ transform: translateX(100%);
+ transition: transform 0.28s cubic-bezier(0.2, 0.8, 0.2, 1);
+ z-index: 38;
+ display: flex;
+ flex-direction: column;
+ backdrop-filter: blur(24px);
+ -webkit-backdrop-filter: blur(24px);
+}
+.next-drawer--open { transform: translateX(0); }
+.next-drawer__head {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 14px 16px;
+ border-bottom: 1px solid rgba(255, 255, 255, 0.06);
+}
+.next-drawer__title {
+ margin: 0;
+ font-size: var(--text-sm);
+ font-weight: 600;
+ letter-spacing: 0.02em;
+ color: rgba(255, 255, 255, 0.9);
+}
+.next-drawer__close {
+ width: 28px;
+ height: 28px;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ background: transparent;
+ border: 0;
+ border-radius: 6px;
+ color: rgba(255, 255, 255, 0.55);
+ cursor: pointer;
+ font-size: 20px;
+ line-height: 1;
+ transition: background 0.15s ease, color 0.15s ease;
+}
+.next-drawer__close:hover {
+ background: rgba(255, 255, 255, 0.06);
+ color: #fff;
+}
+.next-drawer__body {
+ flex: 1;
+ overflow-y: auto;
+ padding: 8px;
+}
+
+/* ── Bottom dock ────────────────────────────────────────────────────────── */
+.next-dock {
+ position: fixed;
+ left: 50%;
+ bottom: 24px;
+ transform: translateX(-50%);
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ padding: 8px 12px;
+ background: rgba(15, 15, 22, 0.78);
+ border: 1px solid rgba(255, 255, 255, 0.08);
+ border-radius: 999px;
+ box-shadow: 0 12px 40px rgba(0, 0, 0, 0.4);
+ backdrop-filter: blur(20px);
+ -webkit-backdrop-filter: blur(20px);
+ z-index: 34;
+ width: min(720px, calc(100vw - 32px));
+ box-sizing: border-box;
+}
+
+.next-dock__clip {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ padding: 6px 10px;
+ background: rgba(255, 255, 255, 0.04);
+ border: 1px solid rgba(255, 255, 255, 0.06);
+ border-radius: 999px;
+ color: rgba(255, 255, 255, 0.9);
+ font-family: inherit;
+ font-size: var(--text-xs);
+ font-weight: 500;
+ cursor: pointer;
+ white-space: nowrap;
+ max-width: 180px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ transition: background 0.15s ease, border-color 0.15s ease;
+}
+.next-dock__clip:hover {
+ background: rgba(255, 255, 255, 0.08);
+ border-color: rgba(255, 255, 255, 0.16);
+}
+.next-dock__clip--open {
+ background: rgba(139, 92, 246, 0.18);
+ border-color: rgba(139, 92, 246, 0.4);
+ color: #fff;
+}
+.next-dock__clip-name {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ max-width: 140px;
+}
+.next-dock__caret {
+ flex-shrink: 0;
+ transition: transform 0.18s ease;
+}
+.next-dock__clip--open .next-dock__caret { transform: rotate(180deg); }
+
+.next-dock__play {
+ width: 36px;
+ height: 36px;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ background: linear-gradient(180deg, rgba(139, 92, 246, 0.85), rgba(124, 58, 237, 0.95));
+ color: #fff;
+ border: 0;
+ border-radius: 50%;
+ cursor: pointer;
+ box-shadow: 0 4px 14px rgba(139, 92, 246, 0.35);
+ transition: transform 0.15s ease, box-shadow 0.15s ease;
+ flex-shrink: 0;
+}
+.next-dock__play:hover { transform: scale(1.05); }
+.next-dock__play:active { transform: scale(0.97); }
+.next-dock__icon { display: none; }
+.next-dock__icon--play { display: block; }
+.next-dock__play--playing .next-dock__icon--play { display: none; }
+.next-dock__play--playing .next-dock__icon--pause { display: block; }
+
+.next-dock__scrub {
+ position: relative;
+ flex: 1 1 auto;
+ height: 32px;
+ display: flex;
+ align-items: center;
+ min-width: 0;
+}
+.next-dock__scrub-fill {
+ position: absolute;
+ left: 0;
+ top: 50%;
+ transform: translateY(-50%);
+ height: 4px;
+ border-radius: 2px;
+ background: linear-gradient(90deg, #8b5cf6, #c4b5fd);
+ width: 0%;
+ pointer-events: none;
+ box-shadow: 0 0 8px rgba(139, 92, 246, 0.45);
+}
+.next-dock__scrub::before {
+ content: '';
+ position: absolute;
+ left: 0;
+ right: 0;
+ top: 50%;
+ transform: translateY(-50%);
+ height: 4px;
+ border-radius: 2px;
+ background: rgba(255, 255, 255, 0.1);
+ pointer-events: none;
+}
+.next-dock__scrub-input {
+ position: relative;
+ width: 100%;
+ height: 32px;
+ appearance: none;
+ background: transparent;
+ margin: 0;
+ cursor: pointer;
+ z-index: 1;
+}
+.next-dock__scrub-input::-webkit-slider-runnable-track {
+ height: 4px;
+ background: transparent;
+}
+.next-dock__scrub-input::-moz-range-track {
+ height: 4px;
+ background: transparent;
+}
+.next-dock__scrub-input::-webkit-slider-thumb {
+ appearance: none;
+ width: 14px;
+ height: 14px;
+ border-radius: 50%;
+ background: #fff;
+ border: 2px solid #8b5cf6;
+ margin-top: -5px;
+ box-shadow: 0 2px 6px rgba(0, 0, 0, 0.35);
+ cursor: grab;
+}
+.next-dock__scrub-input:active::-webkit-slider-thumb { cursor: grabbing; }
+.next-dock__scrub-input::-moz-range-thumb {
+ width: 14px;
+ height: 14px;
+ border-radius: 50%;
+ background: #fff;
+ border: 2px solid #8b5cf6;
+ box-shadow: 0 2px 6px rgba(0, 0, 0, 0.35);
+}
+.next-dock__scrub-input:focus-visible::-webkit-slider-thumb {
+ outline: 2px solid rgba(139, 92, 246, 0.6);
+ outline-offset: 2px;
+}
+
+.next-dock__time {
+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
+ font-size: 11px;
+ color: rgba(255, 255, 255, 0.55);
+ font-variant-numeric: tabular-nums;
+ white-space: nowrap;
+ flex-shrink: 0;
+}
+
+.next-dock__loop {
+ width: 28px;
+ height: 28px;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ background: transparent;
+ border: 0;
+ border-radius: 6px;
+ color: rgba(139, 92, 246, 0.85);
+ cursor: pointer;
+ transition: color 0.15s ease, background 0.15s ease;
+ flex-shrink: 0;
+}
+.next-dock__loop:hover { background: rgba(255, 255, 255, 0.06); }
+.next-dock__loop--off { color: rgba(255, 255, 255, 0.35); }
+
+/* ── Animation grid (expands above the dock) ────────────────────────────── */
+.next-grid {
+ position: fixed;
+ left: 50%;
+ bottom: 86px;
+ transform: translateX(-50%);
+ width: min(720px, calc(100vw - 32px));
+ max-height: 320px;
+ overflow-y: auto;
+ background: rgba(15, 15, 22, 0.92);
+ border: 1px solid rgba(255, 255, 255, 0.08);
+ border-radius: 14px;
+ padding: 10px;
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(140px, 1fr));
+ gap: 6px;
+ z-index: 35;
+ box-shadow: 0 12px 40px rgba(0, 0, 0, 0.45);
+ backdrop-filter: blur(20px);
+ -webkit-backdrop-filter: blur(20px);
+ animation: nextMenuIn 160ms ease;
+}
+.next-grid__item {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 8px 10px;
+ background: rgba(255, 255, 255, 0.03);
+ border: 1px solid rgba(255, 255, 255, 0.05);
+ border-radius: 8px;
+ color: rgba(255, 255, 255, 0.85);
+ font-family: inherit;
+ font-size: var(--text-xs);
+ font-weight: 500;
+ text-align: left;
+ cursor: pointer;
+ transition: background 0.15s ease, border-color 0.15s ease;
+}
+.next-grid__item:hover {
+ background: rgba(255, 255, 255, 0.07);
+ border-color: rgba(255, 255, 255, 0.14);
+}
+.next-grid__item--active {
+ background: rgba(139, 92, 246, 0.2);
+ border-color: rgba(139, 92, 246, 0.5);
+ color: #fff;
+}
+.next-grid__label {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+/* ── Responsive ─────────────────────────────────────────────────────────── */
+@media (max-width: 640px) {
+ .next-corner { top: 70px; right: 10px; }
+ .next-share-menu { top: 70px; right: 54px; width: calc(100vw - 64px); max-width: 320px; }
+ .next-drawer { width: 100vw; max-width: 100vw; }
+ .next-dock {
+ bottom: 14px;
+ width: calc(100vw - 16px);
+ padding: 6px 8px;
+ gap: 6px;
+ }
+ .next-dock__time { display: none; }
+ .next-dock__clip { max-width: 110px; }
+ .next-dock__clip-name { max-width: 80px; }
+ .next-grid {
+ bottom: 70px;
+ width: calc(100vw - 16px);
+ max-height: 260px;
+ grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
+ }
+ .next-prompt { bottom: 86px; }
+}
+
+/* Print + reduced motion — disable the prompt pulse and dock animation. */
+@media (prefers-reduced-motion: reduce) {
+ .next-prompt, .next-drawer { animation: none !important; transition: none !important; }
+}
diff --git a/public/widgets-gallery/index.html b/public/widgets-gallery/index.html
index 5214c1b87..165f585f2 100644
--- a/public/widgets-gallery/index.html
+++ b/public/widgets-gallery/index.html
@@ -54,7 +54,7 @@
<div class="hero-badges">
<span class="hero-badge">
<span class="hero-badge-dot"></span>
- <span><span id="widget-count">5</span> widget types</span>
+ <span><span id="widget-count">8</span> widget types</span>
</span>
<span class="hero-badge">One line of HTML</span>
<span class="hero-badge">Free for personal use</span>
diff --git a/scripts/_next-shots.mjs b/scripts/_next-shots.mjs
new file mode 100644
index 000000000..24f23d47b
--- /dev/null
+++ b/scripts/_next-shots.mjs
@@ -0,0 +1,34 @@
+import { chromium } from 'playwright';
+const BASE = process.env.BASE_URL || 'http://127.0.0.1:4173';
+const b = await chromium.launch();
+const p = await (await b.newContext({ viewport: { width: 1600, height: 1000 } })).newPage();
+await p.goto(`${BASE}/app`, { waitUntil: 'load', timeout: 120_000 });
+await p.waitForSelector('#layout-switch:not([hidden])');
+await p.waitForTimeout(2500);
+await p.screenshot({ path: '/tmp/next_classic.png' });
+
+await p.locator('[data-layout-value="next"]').click();
+await p.waitForTimeout(1500);
+await p.screenshot({ path: '/tmp/next_default.png' });
+
+// Open grid
+await p.evaluate(() => document.getElementById('next-dock-clip').click());
+await p.waitForTimeout(400);
+await p.screenshot({ path: '/tmp/next_grid.png' });
+await p.evaluate(() => document.body.click());
+await p.waitForTimeout(200);
+
+// Open controls drawer
+await p.evaluate(() => document.getElementById('next-controls-btn').click());
+await p.waitForTimeout(600);
+await p.screenshot({ path: '/tmp/next_drawer.png' });
+await p.evaluate(() => document.getElementById('next-drawer-close').click());
+await p.waitForTimeout(400);
+
+// Open share popover
+await p.evaluate(() => document.getElementById('next-share-btn').click());
+await p.waitForTimeout(300);
+await p.screenshot({ path: '/tmp/next_share.png' });
+
+await b.close();
+console.log('shots saved');
diff --git a/scripts/test-avatar-export.mjs b/scripts/test-avatar-export.mjs
new file mode 100644
index 000000000..975a29d89
--- /dev/null
+++ b/scripts/test-avatar-export.mjs
@@ -0,0 +1,141 @@
+/**
+ * Sanity test for the GLB ↔ VRM binary wiring in src/avatar-export.js.
+ *
+ * Runs in node — exercises the pure-binary GLB decode/encode helpers and the
+ * VRMC_vrm JSON injection path against a real GLB on disk. Three.js-dependent
+ * paths (GLTFLoader, GLTFExporter, humanoid bone mapping from a live scene)
+ * are exercised in-browser via the create-review page, not here.
+ *
+ * node scripts/test-avatar-export.mjs
+ */
+
+import { readFile } from 'node:fs/promises';
+import { resolve, dirname } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const FIXTURE = resolve(__dirname, '..', 'public', 'avatars', 'default.glb');
+
+const TEXT_DECODER = new TextDecoder();
+const TEXT_ENCODER = new TextEncoder();
+const GLB_MAGIC = 0x46546c67;
+const GLB_JSON_CHUNK = 0x4e4f534a;
+const GLB_BIN_CHUNK = 0x004e4942;
+
+function decodeGlb(bytes) {
+ const dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
+ if (dv.getUint32(0, true) !== GLB_MAGIC) throw new Error('glb: bad magic');
+ if (dv.getUint32(4, true) !== 2) throw new Error('glb: unsupported version');
+ let offset = 12;
+ let json = null;
+ let bin = new Uint8Array(0);
+ while (offset < bytes.length) {
+ const chunkLen = dv.getUint32(offset, true);
+ const chunkType = dv.getUint32(offset + 4, true);
+ const chunkStart = offset + 8;
+ const chunkData = bytes.subarray(chunkStart, chunkStart + chunkLen);
+ if (chunkType === GLB_JSON_CHUNK) json = chunkData;
+ else if (chunkType === GLB_BIN_CHUNK) bin = chunkData;
+ offset = chunkStart + chunkLen;
+ }
+ if (!json) throw new Error('glb: missing JSON chunk');
+ return { json, bin };
+}
+
+function padTo4(arr, padByte) {
+ const remainder = arr.byteLength % 4;
+ if (remainder === 0) return arr;
+ const padded = new Uint8Array(arr.byteLength + (4 - remainder));
+ padded.set(arr, 0);
+ padded.fill(padByte, arr.byteLength);
+ return padded;
+}
+
+function encodeGlb(jsonBytes, binBytes) {
+ const jsonChunk = padTo4(jsonBytes, 0x20);
+ const binChunk = binBytes.byteLength ? padTo4(binBytes, 0x00) : new Uint8Array(0);
+ const headerLen = 12;
+ const jsonHeaderLen = 8;
+ const binHeaderLen = binChunk.byteLength ? 8 : 0;
+ const totalLen = headerLen + jsonHeaderLen + jsonChunk.byteLength + binHeaderLen + binChunk.byteLength;
+ const out = new Uint8Array(totalLen);
+ const dv = new DataView(out.buffer);
+ dv.setUint32(0, GLB_MAGIC, true);
+ dv.setUint32(4, 2, true);
+ dv.setUint32(8, totalLen, true);
+ dv.setUint32(12, jsonChunk.byteLength, true);
+ dv.setUint32(16, GLB_JSON_CHUNK, true);
+ out.set(jsonChunk, 20);
+ if (binChunk.byteLength) {
+ const binOffset = 20 + jsonChunk.byteLength;
+ dv.setUint32(binOffset, binChunk.byteLength, true);
+ dv.setUint32(binOffset + 4, GLB_BIN_CHUNK, true);
+ out.set(binChunk, binOffset + 8);
+ }
+ return out;
+}
+
+async function main() {
+ const bytes = new Uint8Array(await readFile(FIXTURE));
+ console.log(`Loaded ${FIXTURE}\n size: ${bytes.length} bytes`);
+
+ // Decode original
+ const { json, bin } = decodeGlb(bytes);
+ const parsed = JSON.parse(TEXT_DECODER.decode(json));
+ console.log(` JSON chunk: ${json.length} bytes, BIN chunk: ${bin.length} bytes`);
+ console.log(` nodes: ${parsed.nodes?.length}, meshes: ${parsed.meshes?.length}, skins: ${parsed.skins?.length}`);
+ console.log(` generator: ${parsed.asset?.generator || 'n/a'}`);
+
+ // Inject a fake VRMC_vrm and round-trip
+ parsed.extensionsUsed = Array.from(new Set([...(parsed.extensionsUsed || []), 'VRMC_vrm']));
+ parsed.extensions = {
+ ...(parsed.extensions || {}),
+ VRMC_vrm: {
+ specVersion: '1.0',
+ meta: { name: 'sanity-test', version: '1', authors: ['test'] },
+ humanoid: { humanBones: { hips: { node: 0 } } },
+ expressions: { preset: {} },
+ lookAt: { type: 'bone' },
+ firstPerson: { meshAnnotations: [] },
+ },
+ };
+ const rebuiltJson = TEXT_ENCODER.encode(JSON.stringify(parsed));
+ const rebuilt = encodeGlb(rebuiltJson, bin);
+
+ // Decode the rebuilt blob and confirm it still parses + the extension is present
+ const decoded = decodeGlb(rebuilt);
+ const reparsed = JSON.parse(TEXT_DECODER.decode(decoded.json));
+
+ const checks = [
+ ['rebuilt is a valid GLB (magic)', new DataView(rebuilt.buffer).getUint32(0, true) === GLB_MAGIC],
+ ['rebuilt is glTF v2', new DataView(rebuilt.buffer).getUint32(4, true) === 2],
+ ['rebuilt JSON chunk parses', !!reparsed],
+ ['rebuilt declares VRMC_vrm in extensionsUsed', (reparsed.extensionsUsed || []).includes('VRMC_vrm')],
+ ['rebuilt has VRMC_vrm extension body', !!reparsed.extensions?.VRMC_vrm?.specVersion],
+ ['rebuilt VRM specVersion is 1.0', reparsed.extensions?.VRMC_vrm?.specVersion === '1.0'],
+ ['BIN chunk byte-identical', binEquals(decoded.bin, bin)],
+ ['JSON chunk is 4-byte aligned', decoded.json.length % 4 === 0],
+ ['humanoid.humanBones present', !!reparsed.extensions?.VRMC_vrm?.humanoid?.humanBones],
+ ];
+
+ let pass = 0;
+ let fail = 0;
+ for (const [label, ok] of checks) {
+ console.log(` ${ok ? '✓' : '✗'} ${label}`);
+ if (ok) pass++; else fail++;
+ }
+
+ console.log(`\n${pass}/${pass + fail} checks passed.`);
+ process.exit(fail === 0 ? 0 : 1);
+}
+
+function binEquals(a, b) {
+ if (a.length !== b.length) return false;
+ for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
+ return true;
+}
+
+main().catch((err) => {
+ console.error('TEST FAILED:', err);
+ process.exit(1);
+});
diff --git a/scripts/verify-create-review.mjs b/scripts/verify-create-review.mjs
index 4ac1d643a..e90e06703 100644
--- a/scripts/verify-create-review.mjs
+++ b/scripts/verify-create-review.mjs
@@ -26,63 +26,107 @@ const browser = await chromium.launch();
const ctx = await browser.newContext({ viewport: { width: 1440, height: 1100 } });
const page = await ctx.newPage();
+// Multiple agents editing the same files cause Vite's HMR client to fire
+// page reloads mid-test, destroying the execution context. Block the HMR
+// client + ws so the page stays stable for the duration of the run.
+await page.route('**/@vite/client', (route) => route.abort());
+await page.route('**/__vite_ping*', (route) => route.abort());
+page.on('websocket', (ws) => {
+ if (/\/\?token=|\/__hmr/.test(ws.url())) {
+ ws.close().catch(() => {});
+ }
+});
+
const consoleErrors = [];
page.on('console', (m) => {
if (m.type() === 'error') consoleErrors.push(m.text());
});
page.on('pageerror', (err) => consoleErrors.push(`pageerror: ${err.message}`));
-// Land on the same origin first so we can write to its IndexedDB.
-await page.goto(`${BASE}/create`, { waitUntil: 'domcontentloaded' });
+// Concurrent dev work (multiple agents editing in parallel) causes Vite to
+// trigger HMR full-reloads and occasionally restart altogether. Retry the
+// initial navigation a couple of times so a single transient blip doesn't
+// fail the whole verification.
+async function gotoWithRetry(url, tries = 3) {
+ for (let i = 0; i < tries; i++) {
+ try {
+ await page.goto(url, { waitUntil: 'load', timeout: 15_000 });
+ return;
+ } catch (err) {
+ if (i === tries - 1) throw err;
+ console.warn(`[verify] goto attempt ${i + 1} failed (${err.message?.split('\n')[0]}); retrying`);
+ await new Promise((r) => setTimeout(r, 1500));
+ }
+ }
+}
+
+// First navigation: just to land on the origin so we can synchronously
+// seed IndexedDB. The page will show the empty card on this pass because
+// no avatar is staged yet — that's expected, ignored, and overwritten by
+// the reload below.
+await gotoWithRetry(`${BASE}/create-review`);
-// Stage the avatar exactly the way guest-avatar.stage() does.
const glbB64 = Buffer.from(glbBuffer).toString('base64');
await page.evaluate(async (b64) => {
const bin = atob(b64);
const bytes = new Uint8Array(bin.length);
for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
const blob = new Blob([bytes], { type: 'model/gltf-binary' });
+ const id = '19b160abcdef';
+ const record = { blob, meta: { source: 'avaturn' }, id, name: `Avatar #${id.slice(0, 6)}`, size: blob.size, createdAt: Date.now() };
const db = await new Promise((res, rej) => {
const req = indexedDB.open('three-ws-guest', 1);
req.onupgradeneeded = () => {
- req.result.createObjectStore('avatars');
+ if (!req.result.objectStoreNames.contains('avatars'))
+ req.result.createObjectStore('avatars');
};
req.onsuccess = () => res(req.result);
req.onerror = () => rej(req.error);
});
await new Promise((res, rej) => {
const tx = db.transaction('avatars', 'readwrite');
- const store = tx.objectStore('avatars');
- const id = '19b160abcdef';
- store.put(
- {
- blob,
- meta: { source: 'avaturn' },
- id,
- name: `Avatar #${id.slice(0, 6)}`,
- size: blob.size,
- createdAt: Date.now(),
- },
- 'pending',
- );
+ tx.objectStore('avatars').put(record, 'pending');
tx.oncomplete = res;
tx.onerror = () => rej(tx.error);
});
db.close();
localStorage.setItem(
'3dagent:guest-avatar-meta',
- JSON.stringify({ id: '19b160abcdef', name: 'Avatar #19b160', size: 1, createdAt: Date.now(), source: 'avaturn' }),
+ JSON.stringify({ id, name: record.name, size: record.size, createdAt: Date.now(), source: 'avaturn' }),
);
}, glbB64);
-await page.goto(`${BASE}/create-review`, { waitUntil: 'domcontentloaded' });
+// Reset console-error tracking — any errors from the empty-card first pass
+// (e.g. failed fetches during navigation) are not relevant to the seeded run.
+consoleErrors.length = 0;
+
+// Reload so create-review.js boots with the staged avatar already in IDB.
+await page.reload({ waitUntil: 'load' });
-// Wait for the viewer canvas to mount and the loading overlay to fade out.
-await page.waitForSelector('#mv-container canvas', { timeout: 15_000 });
+// Wait for boot() to flip the content card visible — confirms staged read
+// from IndexedDB worked before we wait on the renderer.
+try {
+ await page.waitForFunction(
+ () => !document.getElementById('content')?.hidden,
+ { timeout: 10_000 },
+ );
+} catch (err) {
+ const dbg = await page.evaluate(() => ({
+ emptyHidden: document.getElementById('empty-card')?.hidden,
+ contentHidden: document.getElementById('content')?.hidden,
+ body: document.body?.innerText?.slice(0, 200),
+ }));
+ console.error('[verify] content never appeared. DOM:', JSON.stringify(dbg));
+ throw err;
+}
+// 'attached' rather than 'visible' — the loading overlay sits on top until
+// renderPreview() resolves, which would otherwise treat the canvas as not
+// visible and time out even though it has mounted.
+await page.waitForSelector('#mv-container canvas', { state: 'attached', timeout: 20_000 });
await page.waitForFunction(
() => document.getElementById('viewer-loading')?.classList.contains('is-hidden'),
- { timeout: 15_000 },
+ { timeout: 20_000 },
);
// Heading should show the friendly fallback, not the raw "Avatar #19b160".
@@ -96,7 +140,7 @@ if (nameInputValue !== '') fail(`name input expected empty, got "${nameInputValu
const sourceTag = (await page.textContent('#tag-source'))?.trim();
if (sourceTag !== 'Avaturn') fail(`source tag expected "Avaturn", got "${sourceTag}"`);
-// Feature grid must show the full 6-capability suite.
+// Feature grid must show the full 7-capability suite (6 product + 1 download).
const featureNames = await page.locator('.feature-tile .feature-name').allTextContents();
const expectedFeatures = [
'3D Body',
@@ -105,6 +149,7 @@ const expectedFeatures = [
'Paid Skills',
'Embed Anywhere',
'Reputation',
+ 'Download',
];
if (featureNames.length !== expectedFeatures.length) {
fail(`feature grid expected ${expectedFeatures.length} tiles, got ${featureNames.length}`);
@@ -126,13 +171,99 @@ const emoteState = await page.evaluate(() => {
});
if (!emoteState.ok) fail(`viewer state: ${emoteState.reason}`);
+// ── Interactive feature tiles ─────────────────────────────────────────────
+
+// 3D Body → emote chip strip on the viewer.
+await page.click('[data-feature="body"]');
+await page.waitForSelector('#emote-strip.is-visible', { timeout: 5_000 });
+const chipCount = await page.locator('.emote-chip').count();
+if (chipCount < 3) fail(`emote strip expected >= 3 chips, got ${chipCount}`);
+// Toggle the strip closed via the close X so it doesn't cover the screenshot.
+// Playwright's auto-scroll-into-view hangs on this button because it lives
+// inside an overflow-x:auto pill that's already at scrollLeft===0; dispatch
+// the click directly to avoid the scroll dance.
+await page.locator('.emote-strip-close').dispatchEvent('click');
+await page.waitForFunction(
+ () => !document.getElementById('emote-strip')?.classList.contains('is-visible'),
+);
+
+// Info modals: each tile opens .fm-backdrop with the expected heading.
+// state:'attached' rather than the default 'visible' — Playwright's CSS
+// animation timing window occasionally rejects the modal as not-stable-visible
+// even though it's painted, and 'attached' is all we actually need to assert
+// the modal was constructed.
+const modalCases = [
+ { feature: 'identity', title: 'On-Chain Identity' },
+ { feature: 'paid', title: 'Paid Skills (x402)' },
+ { feature: 'embed', title: 'Embed Anywhere' },
+ { feature: 'reputation', title: 'Reputation' },
+ { feature: 'download', title: 'Download your avatar' },
+];
+for (const { feature, title } of modalCases) {
+ await page.click(`[data-feature="${feature}"]`);
+ // waitForFunction instead of waitForSelector — even with state:'attached'
+ // the latter occasionally hangs on this codebase's CSS-animated modals.
+ // We only need to confirm the backdrop exists; visibility doesn't matter.
+ await page.waitForFunction(
+ () => !!document.querySelector('.fm-backdrop'),
+ { timeout: 5_000 },
+ );
+ const h = (await page.textContent('.fm-head-text h3'))?.trim();
+ if (h !== title) fail(`modal for "${feature}" expected "${title}", got "${h}"`);
+ // Embed modal must include the copy snippet.
+ if (feature === 'embed') {
+ const code = await page.textContent('.fm-code');
+ if (!code?.includes('script src')) fail('embed modal missing snippet');
+ }
+ // Download modal must list the three supported formats.
+ if (feature === 'download') {
+ const formats = await page
+ .locator('.fm-download-row [data-format]')
+ .evaluateAll((rows) => rows.map((r) => r.getAttribute('data-format')));
+ // data-format lives on the button itself, not a child — fall back to that.
+ const formatAttrs = await page
+ .locator('.fm-download-row')
+ .evaluateAll((rows) => rows.map((r) => r.getAttribute('data-format')));
+ const all = [...formats, ...formatAttrs].filter(Boolean);
+ for (const f of ['glb', 'vrm', 'usdz']) {
+ if (!all.includes(f)) fail(`download modal missing format "${f}"`);
+ }
+ }
+ // Close via Escape — confirms key handler is wired.
+ await page.keyboard.press('Escape');
+ await page.waitForFunction(
+ () => !document.querySelector('.fm-backdrop'),
+ { timeout: 5_000 },
+ );
+}
+
+// Voice tile: should mount the talk overlay (.tws-talk-overlay). waitForFunction
+// dodges Playwright's auto-visibility stability check, which rejects elements
+// with active CSS transitions even though they're already painted.
+await page.click('[data-feature="voice"]');
+await page.waitForFunction(
+ () => !!document.querySelector('.tws-talk-overlay'),
+ { timeout: 12_000 },
+);
+// Close it via the overlay's own close button (dispatched click bypasses
+// the auto-stability check during the entry animation).
+await page.locator('.tws-talk-close').dispatchEvent('click');
+await page.waitForFunction(
+ () => !document.querySelector('.tws-talk-overlay'),
+ { timeout: 5_000 },
+);
+
// Screenshot for visual diff.
await page.screenshot({ path: SHOT_PATH, fullPage: false });
console.log('screenshot:', SHOT_PATH);
if (consoleErrors.length) {
const filtered = consoleErrors.filter(
- (e) => !/favicon|three-ws:auth-resolved|^Refused to apply style/.test(e),
+ (e) =>
+ !/favicon|three-ws:auth-resolved|^Refused to apply style/.test(e) &&
+ // HMR-client + ping fetch failures are deliberately injected by the
+ // route() aborts above; ignore them.
+ !/net::ERR_FAILED|Failed to load resource/i.test(e),
);
if (filtered.length) {
console.error('console errors:');
diff --git a/scripts/verify-next-layout.mjs b/scripts/verify-next-layout.mjs
new file mode 100644
index 000000000..c785d0e6e
--- /dev/null
+++ b/scripts/verify-next-layout.mjs
@@ -0,0 +1,187 @@
+// End-to-end verification for the Next viewer layout on /app.
+//
+// Drives Chromium, exercises every interactive surface, and asserts both
+// visual presence and behavioral wiring. Run with the dev server up:
+//
+// BASE_URL=http://localhost:3050 node scripts/verify-next-layout.mjs
+//
+// Clip-dependent assertions (play/pause, scrub, grid switching) require
+// the GLB to actually load — they're guarded behind a clip-loaded check
+// and report as warnings if the avatar never resolved, so we don't false-
+// negative on a slow first cold-cache run.
+
+import { chromium } from 'playwright';
+
+const BASE = process.env.BASE_URL || 'http://localhost:3000';
+const URL = `${BASE}/app`;
+
+let failures = 0;
+const warnings = [];
+function fail(msg) {
+ console.error('FAIL:', msg);
+ failures += 1;
+}
+function warn(msg) {
+ console.warn('WARN:', msg);
+ warnings.push(msg);
+}
+
+const browser = await chromium.launch();
+const ctx = await browser.newContext({ viewport: { width: 1600, height: 1000 } });
+const page = await ctx.newPage();
+
+const consoleErrors = [];
+page.on('console', (m) => {
+ if (m.type() === 'error') consoleErrors.push(m.text());
+});
+page.on('pageerror', (e) => consoleErrors.push(`pageerror: ${e.message}`));
+
+await page.goto(URL, { waitUntil: 'load', timeout: 120_000 });
+await page.waitForLoadState('networkidle', { timeout: 60_000 }).catch(() => {});
+await page.waitForSelector('#layout-switch:not([hidden])', { timeout: 30_000 });
+
+// ── Layout switch flips to next ─────────────────────────────────────────
+await page.locator('[data-layout-value="next"]').click();
+const layout = await page.evaluate(() => document.body.dataset.layout);
+if (layout !== 'next') fail(`expected body[data-layout="next"], got "${layout}"`);
+
+// ── Classic chrome hidden, Next chrome visible ──────────────────────────
+const expectVisible = async (sel) => {
+ const visible = await page.locator(sel).first().isVisible().catch(() => false);
+ if (!visible) fail(`expected ${sel} to be visible in Next mode`);
+};
+const expectHidden = async (sel) => {
+ const count = await page.locator(sel).count();
+ if (count === 0) return;
+ const visible = await page.locator(sel).first().isVisible().catch(() => false);
+ if (visible) fail(`expected ${sel} to be hidden in Next mode`);
+};
+await expectVisible('#next-dock');
+await expectVisible('#next-corner');
+await expectVisible('#next-controls-btn');
+await expectVisible('#next-share-btn');
+await expectVisible('#next-fullscreen-btn');
+await expectHidden('.dropzone');
+await expectHidden('.agent-presence-sidebar');
+await expectHidden('.gui-toggle');
+
+// ── Wait for animations to load and bind to the dock (best-effort) ──────
+const clipsLoaded = await page.waitForFunction(
+ () => {
+ const name = document.getElementById('next-dock-clip-name')?.textContent?.trim();
+ return name && name !== '—';
+ },
+ { timeout: 20_000 },
+).then(() => true).catch(() => false);
+
+if (!clipsLoaded) {
+ warn('avatar/clips never loaded — skipping playback assertions');
+}
+
+if (clipsLoaded) {
+ // ── Play button toggles state ──────────────────────────────────────
+ const wasPlaying = await page.locator('#next-dock-play').getAttribute('aria-pressed');
+ await page.locator('#next-dock-play').click();
+ await page.waitForTimeout(300);
+ const nowPlaying = await page.locator('#next-dock-play').getAttribute('aria-pressed');
+ if (nowPlaying === wasPlaying) fail(`play button did not toggle (was ${wasPlaying}, now ${nowPlaying})`);
+
+ // ── Scrub advances the action.time ─────────────────────────────────
+ await page.evaluate(() => {
+ const scrub = document.getElementById('next-dock-scrub-input');
+ scrub.value = 500;
+ scrub.dispatchEvent(new Event('input', { bubbles: true }));
+ });
+ await page.waitForTimeout(100);
+ const time = await page.locator('#next-dock-time').innerText();
+ if (time === '0:00 / 0:00') fail(`scrub did not update time display: "${time}"`);
+
+ // ── Grid opens and lists clips, click switches ─────────────────────
+ await page.locator('#next-dock-clip').click();
+ await page.waitForFunction(() => !document.getElementById('next-grid')?.hidden, null, { timeout: 5000 });
+ const gridCount = await page.locator('#next-grid .next-grid__item').count();
+ if (gridCount === 0) fail('grid rendered with 0 clips');
+ if (gridCount > 1) {
+ const before = await page.locator('#next-dock-clip-name').innerText();
+ await page.locator('#next-grid .next-grid__item').nth(1).click();
+ await page.waitForTimeout(200);
+ const after = await page.locator('#next-dock-clip-name').innerText();
+ if (before === after) fail(`clip switch did not change name (was "${before}", now "${after}")`);
+ const gridStillOpen = await page.locator('#next-grid').isVisible();
+ if (gridStillOpen) fail('grid did not auto-close after selection');
+ }
+
+ // ── Loop toggle persists state on aria-pressed ─────────────────────
+ const loopBefore = await page.locator('#next-dock-loop').getAttribute('aria-pressed');
+ await page.locator('#next-dock-loop').click();
+ const loopAfter = await page.locator('#next-dock-loop').getAttribute('aria-pressed');
+ if (loopBefore === loopAfter) fail(`loop button did not toggle (was ${loopBefore}, now ${loopAfter})`);
+ await page.locator('#next-dock-loop').click();
+}
+
+// ── Controls drawer opens, contains the dat.GUI panel ───────────────────
+await page.evaluate(() => document.getElementById('next-controls-btn').click());
+await page.waitForFunction(
+ () => document.getElementById('next-drawer')?.classList.contains('next-drawer--open'),
+ null,
+ { timeout: 3000 },
+);
+const hasGui = await page.evaluate(() => {
+ const body = document.getElementById('next-drawer-body');
+ return Boolean(body?.querySelector('.gui-wrap'));
+});
+if (!hasGui) fail('Controls drawer did not host the dat.GUI panel');
+await page.evaluate(() => document.getElementById('next-drawer-close').click());
+await page.waitForFunction(
+ () => !document.getElementById('next-drawer')?.classList.contains('next-drawer--open'),
+);
+
+// ── Share popover opens and contains expected items ─────────────────────
+await page.evaluate(() => document.getElementById('next-share-btn').click());
+await page.waitForFunction(() => !document.getElementById('next-share-menu')?.hidden, null, { timeout: 5000 });
+const uploadVisible = await page.locator('#next-share-upload').isVisible();
+if (!uploadVisible) fail('Share popover missing Upload item');
+// Close via outside-click.
+await page.evaluate(() => document.body.click());
+await page.waitForFunction(() => document.getElementById('next-share-menu')?.hidden, null, { timeout: 3000 });
+
+// ── Toggle back to Classic; chrome must swap ────────────────────────────
+await page.locator('[data-layout-value="classic"]').click();
+await page.waitForFunction(() => document.body.dataset.layout === 'classic');
+const dockHiddenInClassic = !(await page.locator('#next-dock').isVisible().catch(() => false));
+if (!dockHiddenInClassic) fail('Next dock still visible after switching to Classic');
+const dropzoneVisibleInClassic = await page.locator('.dropzone').isVisible().catch(() => false);
+if (!dropzoneVisibleInClassic) fail('Classic dropzone hidden after switching back to Classic');
+const guiToggleVisibleInClassic = await page.locator('.gui-toggle').isVisible().catch(() => false);
+if (!guiToggleVisibleInClassic) fail('Classic gui-toggle hidden after switching back');
+
+// ── Reload preserves the chosen layout ─────────────────────────────────
+await page.locator('[data-layout-value="next"]').click();
+await page.waitForTimeout(150);
+await page.reload({ waitUntil: 'load', timeout: 120_000 });
+await page.waitForSelector('#layout-switch:not([hidden])', { timeout: 30_000 });
+const afterReload = await page.evaluate(() => document.body.dataset.layout);
+if (afterReload !== 'next') fail(`expected "next" after reload, got "${afterReload}"`);
+
+// ── No console errors during the whole flow ─────────────────────────────
+const ignorable = [
+ /wallet/i, // wallet provider noise in headless
+ /Failed to fetch/i, // background analytics
+ /Wallet not initialized/i,
+];
+const realErrors = consoleErrors.filter((e) => !ignorable.some((rx) => rx.test(e)));
+if (realErrors.length) {
+ console.error('Console errors during run:');
+ for (const e of realErrors) console.error(' ', e);
+ failures += realErrors.length;
+}
+
+await browser.close();
+if (failures) {
+ console.error(`\nverify-next-layout FAILED (${failures} failures, ${warnings.length} warnings)`);
+ process.exit(1);
+} else if (warnings.length) {
+ console.log(`verify-next-layout OK (with ${warnings.length} warnings)`);
+} else {
+ console.log('verify-next-layout OK');
+}
diff --git a/scripts/verify-widget-shell.mjs b/scripts/verify-widget-shell.mjs
new file mode 100644
index 000000000..5793019f4
--- /dev/null
+++ b/scripts/verify-widget-shell.mjs
@@ -0,0 +1,129 @@
+// Verify the slim /widget shell renders a 3D avatar without flashing site
+// chrome — and that the parent surfaces (studio preview, public embed URL,
+// legacy /app#kiosk=true) all behave correctly. Run while `npm run dev` is up.
+//
+// node scripts/verify-widget-shell.mjs
+//
+// Writes screenshots to /tmp/widget-*.png and prints a pass/fail summary.
+
+import { chromium } from 'playwright';
+
+const BASE = process.argv[2] || 'http://localhost:3000';
+const DEMO_GLB = '/avatars/cz.glb';
+
+const browser = await chromium.launch({
+ args: ['--use-gl=swiftshader', '--enable-unsafe-swiftshader'],
+});
+
+const results = [];
+function ok(label) {
+ results.push({ label, ok: true });
+ console.log(` ✓ ${label}`);
+}
+function fail(label, err) {
+ results.push({ label, ok: false, err: String(err) });
+ console.log(` ✗ ${label} — ${err}`);
+}
+
+async function withPage(name, fn) {
+ console.log(`\n→ ${name}`);
+ const page = await browser.newPage({ viewport: { width: 1280, height: 800 } });
+ page.on('pageerror', (e) => console.log(' PAGEERROR:', e.message.slice(0, 200)));
+ page.on('console', (m) => {
+ if (m.type() === 'error') console.log(' [err]', m.text().slice(0, 200));
+ });
+ try {
+ await fn(page);
+ } catch (e) {
+ fail(name, e.message || e);
+ } finally {
+ await page.close();
+ }
+}
+
+async function waitForFirstFrame(page) {
+ await page.waitForFunction(() => window.VIEWER?.viewer?.content, { timeout: 25000 });
+}
+
+// 1. /widget direct: model in hash, kiosk on, no chrome ever visible.
+await withPage('/widget#model=<glb>&kiosk=true (direct embed)', async (page) => {
+ const url = `${BASE}/widget?_=${Date.now()}#model=${encodeURIComponent(DEMO_GLB)}&kiosk=true`;
+ await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 30000 });
+ // Body should be invisible until first-frame event fires.
+ const initialVisibility = await page.evaluate(() => getComputedStyle(document.body).visibility);
+ if (initialVisibility === 'hidden') ok('body starts visibility:hidden (FOUC guard)');
+ else fail('body starts visibility:hidden (FOUC guard)', `got ${initialVisibility}`);
+
+ // Confirm no <header>/<footer> ever exists in the DOM.
+ const chromeCount = await page.evaluate(
+ () =>
+ document.querySelectorAll(
+ 'header, footer, .agent-presence-sidebar, .dropzone, .auth-gate',
+ ).length,
+ );
+ if (chromeCount === 0) ok('no site chrome in the DOM');
+ else fail('no site chrome in the DOM', `found ${chromeCount} chrome elements`);
+
+ await waitForFirstFrame(page);
+
+ const readyVisibility = await page.evaluate(() => getComputedStyle(document.body).visibility);
+ if (readyVisibility === 'visible') ok('body flips visible after first frame');
+ else fail('body flips visible after first frame', `still ${readyVisibility}`);
+
+ await page.screenshot({ path: '/tmp/widget-direct.png' });
+ console.log(' → /tmp/widget-direct.png');
+});
+
+// 2. /studio preview iframe: hit the studio, confirm the preview iframe
+// targets /widget (not /app) and renders the model.
+await withPage('/studio preview iframe targets /widget', async (page) => {
+ await page.goto(`${BASE}/studio/`, { waitUntil: 'domcontentloaded', timeout: 30000 });
+ // Wait for the preview iframe to receive a src.
+ await page.waitForFunction(
+ () => document.getElementById('preview-iframe')?.src?.includes('/widget'),
+ { timeout: 20000 },
+ );
+ const previewSrc = await page.evaluate(() => document.getElementById('preview-iframe').src);
+ if (previewSrc.includes('/widget') && !previewSrc.match(/\/app[?#]/))
+ ok(`preview iframe → /widget (src=${previewSrc.slice(0, 120)}…)`);
+ else fail('preview iframe → /widget', `unexpected src: ${previewSrc}`);
+
+ // Drop into the iframe and confirm chrome isn't there either.
+ const frame = page.frame({ url: /\/widget/ });
+ if (!frame) {
+ fail('studio iframe accessible', 'no /widget frame found');
+ return;
+ }
+ const chromeCount = await frame.evaluate(
+ () => document.querySelectorAll('header, footer').length,
+ );
+ if (chromeCount === 0) ok('studio preview iframe has no chrome');
+ else fail('studio preview iframe has no chrome', `found ${chromeCount}`);
+
+ await page.screenshot({ path: '/tmp/widget-studio.png', fullPage: false });
+ console.log(' → /tmp/widget-studio.png');
+});
+
+// 3. Legacy /app#kiosk=true still works (no chrome eventually, model renders).
+await withPage('/app#model=<glb>&kiosk=true (legacy path)', async (page) => {
+ const url = `${BASE}/app#model=${encodeURIComponent(DEMO_GLB)}&kiosk=true`;
+ await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 30000 });
+ await waitForFirstFrame(page);
+ // In kiosk mode, header should now be display:none.
+ const headerHidden = await page.evaluate(() => {
+ const h = document.querySelector('header');
+ return !h || getComputedStyle(h).display === 'none';
+ });
+ if (headerHidden) ok('legacy /app kiosk still hides chrome');
+ else fail('legacy /app kiosk still hides chrome', 'header still visible');
+ await page.screenshot({ path: '/tmp/widget-legacy.png' });
+ console.log(' → /tmp/widget-legacy.png');
+});
+
+await browser.close();
+
+const failed = results.filter((r) => !r.ok);
+console.log(
+ `\n${results.length - failed.length}/${results.length} checks passed${failed.length ? ' — see failures above' : ''}`,
+);
+process.exit(failed.length ? 1 : 0);
diff --git a/src/agent-protocol.js b/src/agent-protocol.js
index 7b46d1d36..dced4642c 100644
--- a/src/agent-protocol.js
+++ b/src/agent-protocol.js
@@ -20,6 +20,7 @@ export const ACTION_TYPES = {
REMEMBER: 'remember', // agent stored a memory
SIGN: 'sign', // agent signs an action with its wallet
LOAD_START: 'load-start', // model/asset loading started
+ LOAD_PROGRESS: 'load-progress', // model/asset download progress (bytes)
LOAD_END: 'load-end', // model/asset loading finished
VALIDATE: 'validate', // validation result (errors, warnings, hints)
PRESENCE: 'presence', // agent came online / went idle
@@ -67,6 +68,20 @@ const _DEFAULT_POLICIES = [
},
],
['look-at', { mode: 'debounce', intervalMs: 100 }],
+ // GLTFLoader's onProgress can fire dozens of times per second during a
+ // fast download — without a policy it trips the burst rate-limiter and
+ // floods the bus with protocol-error events. Coalesce to ~10fps,
+ // keeping only the most-recent bytes-loaded so the progress bar
+ // reflects the latest state.
+ [
+ 'load-progress',
+ {
+ mode: 'coalesce',
+ windowMs: 100,
+ key: () => 'progress',
+ merge: (_a, b) => b,
+ },
+ ],
];
export class AgentProtocol extends EventTarget {
diff --git a/src/app-next-overlay.js b/src/app-next-overlay.js
index 08d2c2ed4..9a552513a 100644
--- a/src/app-next-overlay.js
+++ b/src/app-next-overlay.js
@@ -1,29 +1,10 @@
-/**
- * app-next overlay — UX preview layer for /app-next demo.
- *
- * Boots after /src/app.js (the real production viewer + agent system) and
- * adds the new UX surface:
- * 1. Stage polish — transparent canvas so the CSS floor-glow shows through.
- * 2. Camera idle drift — gentle auto-rotate that pauses on interaction.
- * 3. "Try X" rotating invitation pill (driven by the real animation manifest).
- * 4. Compact animation picker sheet with search + grid (replaces the strip).
- * 5. Single-hierarchy action bar: Animations, Upload, Save / Sign-in.
- * 6. Header menus (explore + auth) with open/close + outside-click dismiss.
- * 7. Keyboard shortcuts: A (animations), U (upload), Esc (close sheet).
- * 8. First-visit hint shown once per browser.
- *
- * This file deliberately does NOT touch any other surface — same /src/app.js
- * bootstraps the viewer, same animation manifest, same auth APIs.
- */
+// UX preview overlay for /app-next — re-skins /src/app.js without touching it.
import { getMe, readAuthHint, saveRemoteGlbToAccount } from './account.js';
const STORAGE_HINT_KEY = 'nxt:first-hint-dismissed';
const TRY_ROTATE_MS = 8000;
-// Curated subset for the rotating "Try X" prompt — these clips look great as
-// 2-second teasers and crossfade cleanly back to idle. Names match the entries
-// in /public/animations/manifest.json.
const TRY_PICKS = [
{ name: 'av-waving', icon: '👋', label: 'Wave' },
{ name: 'av-superhero-jump', icon: '🦸', label: 'Superhero jump' },
@@ -35,9 +16,6 @@ const TRY_PICKS = [
{ name: 'av-walk-crouching', icon: '🚶', label: 'Sneak walk' },
];
-// Animation defs ship with an `icon` field that's usually right, but a few
-// common ones are missing or have wrong glyphs — patch them here so the grid
-// always reads cleanly. Fallback chain: icon override → manifest icon → ✨.
const ICON_OVERRIDES = {
idle: '🧍',
lookdown: '👀',
@@ -56,7 +34,6 @@ const ICON_OVERRIDES = {
document.addEventListener('DOMContentLoaded', boot);
function boot() {
- console.info('[nxt] boot');
wireExploreMenu();
wireUserMenu();
wireFirstHint();
@@ -64,22 +41,17 @@ function boot() {
wirePrimaryCTA();
wireAnimationSheet();
- // The viewer is created asynchronously by App. Poll briefly until it's
- // ready, then attach stage polish + start the Try pill rotation.
waitForViewer().then((viewer) => {
if (!viewer) {
console.warn('[nxt] viewer never appeared — stage polish skipped');
return;
}
- console.info('[nxt] viewer ready');
polishStage(viewer);
startTryPillRotation(viewer);
startCameraDrift(viewer);
});
- // Auth state can resolve before or after viewer; refresh CTA when ready.
refreshAuthState();
- // Refresh once more when other tabs sign in/out.
window.addEventListener('storage', (e) => {
if (e.key === 'nxt-auth-touch' || e.key?.startsWith('auth')) refreshAuthState();
});
@@ -103,10 +75,7 @@ function waitForViewer(timeoutMs = 15000) {
// ── Stage polish ──────────────────────────────────────────────────────────
function polishStage(viewer) {
- // Make the canvas transparent so the CSS radial floor-glow + vignette
- // (rendered behind via the same stacking context) show through. The viewer
- // owns its own transparentBg state — flipping it directly survives any
- // subsequent updateBackground() call (saved scene prefs, brand sync, etc).
+ // transparentBg via the viewer's own state — survives later updateBackground() calls.
try {
viewer.state.transparentBg = true;
viewer.updateBackground();
@@ -124,10 +93,10 @@ function startCameraDrift(viewer) {
let resumeTimer = null;
const enableDrift = () => {
- // Mirror viewer.state so updateDisplay() doesn't undo us later.
+ // Mirror state.autoRotate so viewer.updateDisplay() doesn't undo it later.
viewer.state.autoRotate = true;
viewer.controls.autoRotate = true;
- viewer.controls.autoRotateSpeed = 0.35; // very slow — alive, not spinning
+ viewer.controls.autoRotateSpeed = 0.35;
viewer.invalidate?.();
};
@@ -136,7 +105,6 @@ function startCameraDrift(viewer) {
viewer.controls.autoRotate = false;
userInteracted = true;
clearTimeout(resumeTimer);
- // Resume after 10s of no interaction
resumeTimer = setTimeout(() => {
if (userInteracted) {
userInteracted = false;
@@ -175,16 +143,12 @@ function startTryPillRotation(viewer) {
render();
};
- // Wait until at least one clip is loadable before showing the pill.
- pollForClips(viewer).then((defs) => {
- console.info('[nxt] pollForClips resolved, defs=', defs?.length || 0);
- // Filter picks down to clips that exist in this avatar's manifest.
+ pollForClips(viewer).then(() => {
const available = new Set(getAvailableClipNames(viewer));
if (available.size > 0) {
order = TRY_PICKS.filter((p) => available.has(p.name));
- if (order.length === 0) order = TRY_PICKS.slice(); // fall back
+ if (order.length === 0) order = TRY_PICKS.slice();
}
- console.info('[nxt] try pill picks count=', order.length);
cursor = Math.floor(Math.random() * order.length);
render();
pill.hidden = false;
@@ -194,10 +158,8 @@ function startTryPillRotation(viewer) {
btn.addEventListener('click', () => {
const pick = order[cursor % order.length];
playClip(viewer, pick.name);
- // Pause rotation after explicit try — let the user enjoy what they picked
clearInterval(intervalId);
intervalId = null;
- // Resume after 12s if no further interaction
setTimeout(() => {
if (!intervalId) intervalId = setInterval(advance, TRY_ROTATE_MS);
}, 12000);
@@ -231,11 +193,9 @@ function playClip(viewer, name) {
const defs = mgr.getAnimationDefs();
const def = defs.find((d) => d.name === name);
if (!def) return;
-
- // ensureLoaded fetches the JSON clip if not yet cached, then play() runs it.
mgr.ensureLoaded(name)
.then(() => mgr.play(name))
- .catch((err) => console.warn('[app-next] clip play failed', name, err));
+ .catch((err) => console.warn('[nxt] clip play failed', name, err));
}
// ── Animation sheet ───────────────────────────────────────────────────────
@@ -275,7 +235,6 @@ function wireAnimationSheet() {
closeBtn?.addEventListener('click', close);
- // Esc closes; outside click closes.
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && !sheet.hidden) close();
});
@@ -318,7 +277,6 @@ function wireAnimationSheet() {
`<span>${escHtml(label)}</span>`;
card.addEventListener('click', () => {
playClip(viewer, def.name);
- // Sync aria-pressed across all cards
grid.querySelectorAll('.nxt-anim-card').forEach((c) => {
c.setAttribute('aria-pressed', c.dataset.name === def.name ? 'true' : 'false');
});
@@ -326,10 +284,7 @@ function wireAnimationSheet() {
grid.appendChild(card);
}
- // Keep card pressed-state in sync when clip changes from elsewhere
- // (try-pill, keyboard shortcut, programmatic). Chain through any prior
- // onChange handler so we don't clobber a subscriber the production
- // viewer (or another overlay) may have installed.
+ // Chain through any existing onChange so we don't clobber a viewer subscriber.
const prevOnChange = viewer.animationManager.onChange;
viewer.animationManager.onChange = (...args) => {
try { prevOnChange?.(...args); } catch (e) { console.warn('[nxt] prior onChange threw', e); }
@@ -432,8 +387,7 @@ async function refreshAuthState() {
const primary = document.getElementById('nxt-primary');
const primaryLabel = document.getElementById('nxt-primary-label');
- // readAuthHint is a synchronous local-storage lookup — useful for the first
- // paint before getMe() resolves. We always confirm with the real API.
+ // Hint paints synchronously; getMe() then confirms.
const hint = readAuthHint?.();
if (hint?.username && userLabel) {
userLabel.textContent = hint.username;
@@ -466,8 +420,7 @@ function wirePrimaryCTA() {
const primaryLabel = document.getElementById('nxt-primary-label');
if (!primary) return;
- // Held outside the closure so a rapid second save can clear the prior
- // "Saved ✓ → Save to account" revert before it fires.
+ // Outside the closure so a second save can cancel the previous revert.
let revertTimer = null;
primary.addEventListener('click', async () => {
@@ -477,7 +430,6 @@ function wirePrimaryCTA() {
return;
}
- // Save the current model to the signed-in user's account.
const viewer = window.VIEWER?.viewer;
const app = window.VIEWER?.app;
const url = app?._currentModelUrl;
@@ -504,7 +456,7 @@ function wirePrimaryCTA() {
throw new Error(res?.error || 'save failed');
}
} catch (err) {
- console.warn('[app-next] save failed', err);
+ console.warn('[nxt] save failed', err);
if (primaryLabel) primaryLabel.textContent = original;
toast('Save failed — try again.');
} finally {
diff --git a/src/app.js b/src/app.js
index 242860778..455e8de93 100644
--- a/src/app.js
+++ b/src/app.js
@@ -22,6 +22,7 @@ import { mountLiveTradesCanvas } from './widgets/live-trades-canvas.js';
import { mountPassport } from './widgets/passport.js';
import queryString from 'query-string';
import { ScreenshotModal } from './components/screenshot-modal.js';
+import { NextLayout } from './next-layout.js';
// Agent system — the new primitive layer
import { protocol, ACTION_TYPES } from './agent-protocol.js';
@@ -60,6 +61,14 @@ function _base64ToFile(b64, name, type) {
return new File([bytes], name, { type });
}
+function _fmtBytes(n) {
+ if (!Number.isFinite(n) || n <= 0) return '0 B';
+ const units = ['B', 'KB', 'MB', 'GB'];
+ const i = Math.min(units.length - 1, Math.floor(Math.log(n) / Math.log(1024)));
+ const v = n / Math.pow(1024, i);
+ return `${v >= 10 || i === 0 ? Math.round(v) : v.toFixed(1)} ${units[i]}`;
+}
+
/**
* Parse an on-chain agent URL path. Accepts:
* /a/<chainId>/<agentId> (canonical — registry inferred)
@@ -153,17 +162,33 @@ class App {
pending: qp.get('pending') === '1',
// avatarSession: selfie pipeline passes a session URL here after processing photos
avatarSession: hash.avatarSession ? decodeURIComponent(hash.avatarSession) : '',
- // Per-embed overrides (appended to iframe URL by Studio embed modal)
+ // Per-embed overrides (appended to iframe URL by Studio embed modal
+ // and the public /widgets gallery customizer).
noAnimations: Boolean(hash.noAnimations),
noChat: Boolean(hash.noChat),
noControls: Boolean(hash.noControls),
avatarChatOff: hash['avatar-chat'] === 'off',
+ // Live-customizer overrides — applied on top of the saved widget config.
+ // Hash form is %23-encoded for color values (e.g. accent=%2300ff88).
+ overrideAccent: hash.accent ? decodeURIComponent(hash.accent) : '',
+ overrideBg: hash.bg ? decodeURIComponent(hash.bg) : '',
+ overrideMint: hash.mint ? decodeURIComponent(hash.mint) : '',
+ overrideKind: hash.kind || '',
+ overrideMinTier: hash.minTier || '',
};
+ // Slim /widget shell — see pages/widget.html. The shell hides every
+ // owner-mode surface and the viewer is the only thing on screen.
+ // Several setup steps below (wallet reconnect, dropzone, selfie pipeline,
+ // auth check, layout switch) are pure dead weight in that surface, so
+ // we short-circuit them when the shell flag is present.
+ this._widgetShell = Boolean(window.__WIDGET_SHELL);
+
// Fire-and-forget silent wallet reconnect. Cheap (single `eth_accounts`
// RPC), never throws, never prompts. If the user has previously authorized
// the site, this populates the shared signer before any wallet UI mounts.
- eagerConnectWallet();
+ // Skip in the slim widget shell — embeds don't need wallet state.
+ if (!this._widgetShell) eagerConnectWallet();
this.el = el;
this.viewer = null;
@@ -189,27 +214,43 @@ class App {
// Wire validator results into the protocol
this._hookValidator();
+ // Viewer status overlay (loading / error UI) tied to LOAD_START / LOAD_END.
+ this._wireViewerStatus();
+
this._editingAgentId = this.options.agentEdit || null;
- this.createDropzone();
- this.setupAvatarCreator();
- if (this.options.avatarSession) {
- this.avatarCreator.open(this.options.avatarSession);
+ // In the slim widget shell there's no dropzone, no selfie pipeline UI,
+ // no sign-in link, no layout switch buttons. Skip those entirely so
+ // we don't waste cycles attaching listeners + a network round-trip
+ // (getMe) for an iframe that only renders a 3D canvas.
+ // _applyViewerMode still runs — it sets `data-viewer-mode="embed"`
+ // which CSS uses to hide ambient chrome on shared pages.
+ if (!this._widgetShell) {
+ this.createDropzone();
+ this.setupAvatarCreator();
+ if (this.options.avatarSession) {
+ this.avatarCreator.open(this.options.avatarSession);
+ }
}
this.hideSpinner();
this._applyViewerMode();
- this._setupLayoutSwitch();
- this._updateSignInLink();
- this._setupSaveToAccount();
- this._setupMakeWidgetButton();
- this._setupScreenshotButton();
- this.screenshotModal = new ScreenshotModal(this.el);
+ if (!this._widgetShell) {
+ this._setupLayoutSwitch();
+ this._setupNextLayout();
+ this._updateSignInLink();
+ this._setupSaveToAccount();
+ this._setupMakeWidgetButton();
+ this._setupScreenshotButton();
+ this.screenshotModal = new ScreenshotModal(this.el);
+ }
const options = this.options;
if (options.kiosk) {
+ // In the slim widget shell there's no <header> in the DOM —
+ // hide defensively only if it exists (legacy /app#kiosk=true URLs).
const headerEl = document.querySelector('header');
- headerEl.style.display = 'none';
+ if (headerEl) headerEl.style.display = 'none';
const footerEl = document.querySelector('footer');
if (footerEl) footerEl.style.display = 'none';
}
@@ -246,7 +287,8 @@ class App {
return;
}
- // Load a saved widget by ID: /app#widget=<wdgt_...>
+ // Load a saved widget by ID: /widget#widget=<wdgt_...> (slim shell,
+ // canonical) or legacy /app#widget=<wdgt_...> (full SPA, still works).
if (options.widget) {
this._loadWidget(options.widget);
this._initAgentSystem();
@@ -257,10 +299,11 @@ class App {
// Editing an existing agent: ?agent=<uuid> (authenticated editing surface)
if (options.agentEdit) {
this._loadAgentForEdit(options.agentEdit).catch((err) => {
- // Any throw before view() runs would leave the viewer un-mounted
- // and the user staring at an empty canvas. Fall back to the
- // default load so a 3D scene is always on screen.
+ // Defensive: _loadAgentForEdit handles its own failures and
+ // always mounts the viewer up-front, but a truly unexpected
+ // throw shouldn't leave the user with no UI to act on.
console.warn('[3d-agent] agent-edit load failed', err);
+ this._showViewerError("Couldn't load this agent.", () => this._retryAgentLoad());
if (!this.viewer) this._maybeResumeOrLoad(this.options);
if (!this._agentSystemBooted) this._initAgentSystem();
});
@@ -512,6 +555,13 @@ class App {
document.body.dataset.layout = layout;
}
+ _setupNextLayout() {
+ // Skip in embed/widget/kiosk/deploy contexts — Next chrome is owner-only.
+ if (document.body.dataset.viewerMode !== 'main') return;
+ this._nextLayout = new NextLayout(this);
+ this._nextLayout.mount();
+ }
+
_setupLayoutSwitch() {
const root = document.getElementById('layout-switch');
if (!root) return;
@@ -930,6 +980,19 @@ class App {
}
async _loadAgentForEdit(agentId) {
+ // Reset onboarding gate so a retry can re-fire it once the GLB actually
+ // loads. The localStorage gate inside _maybeShowOnboarding still
+ // guarantees once-per-agent in steady state.
+ this._onboardingFired = false;
+
+ // Mount the canvas up-front so the loading/error overlay has a parent
+ // and the page layout never collapses around an empty container.
+ if (!this.viewer) this.createViewer();
+
+ // Surface a loading state immediately — the identity name lookup
+ // below may take a moment, and the user shouldn't see an empty stage.
+ this._showViewerLoading('Loading your avatar…');
+
// Swap this.identity to the agent being edited so AgentHome (and the
// Solana wallet card) render for *this* agent rather than the viewer's
// default identity.
@@ -940,10 +1003,19 @@ class App {
/* fall through; identity getter still returns _agentId */
}
- // Fetch the agent record and load its GLB into the editor (main UI, not embed)
+ // Refresh the loading label now that we know the agent's name.
+ if (this.identity?.name) {
+ this._showViewerLoading(`Loading ${this.identity.name}…`);
+ }
+
+ // Fetch the agent record and resolve its GLB URL.
let glbUrl = null;
+ let fetchFailed = false;
+ let thumbnailUrl = null;
this._currentUsdzUrl = null;
this._currentHalfbodyUrl = null;
+ this._currentAvatarId = null;
+ this._avatarNeedsThumbnail = false;
try {
const resp = await fetch(`/api/agents/${agentId}`, { credentials: 'include' });
if (resp.ok) {
@@ -957,30 +1029,45 @@ class App {
if (avatar?.url) glbUrl = avatar.url;
this._currentUsdzUrl = avatar?.usdz_url || null;
this._currentHalfbodyUrl = avatar?.halfbody_url || null;
+ this._currentAvatarId = avatar?.id || null;
+ thumbnailUrl = avatar?.thumbnail_url || null;
+ // Flag for the LOAD_END(success) listener to capture
+ // and upload a thumbnail once the avatar is rendered.
+ this._avatarNeedsThumbnail = !thumbnailUrl && !!glbUrl;
+ } else {
+ fetchFailed = true;
}
}
+ } else {
+ fetchFailed = true;
}
} catch {
- /* fall through to default */
+ fetchFailed = true;
}
- try {
- if (glbUrl) {
- await this.view(glbUrl, '', new Map());
- } else {
- await this._maybeResumeOrLoad(this.options);
- }
- } catch (err) {
- // If the agent's GLB fails to load (404, decode error, etc.) we
- // must still mount a viewer so the editor is usable.
- console.warn('[3d-agent] agent GLB load failed; falling back', err);
- if (!this.viewer) {
- try {
- await this._maybeResumeOrLoad(this.options);
- } catch (fallbackErr) {
- console.warn('[3d-agent] fallback load failed', fallbackErr);
- }
- }
+ // Show the thumbnail as a poster behind the canvas so a 4-5 MB GLB
+ // stream isn't a black void. Crossfades out on LOAD_END(success).
+ if (thumbnailUrl) this._showPoster(thumbnailUrl);
+
+ // Three outcomes:
+ // 1. GLB URL found → load it. Success/error overlay is driven
+ // by the LOAD_END protocol listener.
+ // 2. Agent has no avatar → load the default CZ avatar so the editor
+ // is usable; no error overlay (this is a legitimate state).
+ // 3. Agent fetch failed → show error overlay with Retry. Still
+ // load the default CZ so the editor canvas isn't empty.
+ if (glbUrl) {
+ this.view(glbUrl, '', new Map());
+ } else if (fetchFailed) {
+ // Don't trigger a fallback load — its LOAD_START would clobber
+ // the error overlay. The renderer is already mounted from
+ // createViewer() above; the user sees the error message on top
+ // of an empty 3D scene, which honestly reflects the state.
+ this._showViewerError("Couldn't load your avatar.", () => this._retryAgentLoad());
+ } else {
+ // Agent has no avatar attached yet — load the default so the
+ // editor is usable. LOAD_END will hide the overlay normally.
+ this._maybeResumeOrLoad(this.options);
}
// Restore + auto-save per-agent scene preferences (background, env,
@@ -998,7 +1085,8 @@ class App {
this._refreshDeployButton(agentId);
- this._maybeShowOnboarding(agentId);
+ // Onboarding is fired from the LOAD_END(success) listener so the
+ // "ready" popup only appears once the avatar is actually on screen.
this._initAgentSystem();
this._initWidgetBridge();
@@ -1051,6 +1139,28 @@ class App {
}
window.VIEWER.widget = widget;
+ // Fire-and-forget view beacon for analytics. Skip owner previews
+ // (Studio + dashboard iframes pass &preview=1) so the creator's own
+ // QA cycles don't pollute their stats.
+ try {
+ const qs = new URLSearchParams(location.search);
+ if (qs.get('preview') !== '1') {
+ const url = `/api/widgets/${encodeURIComponent(widgetId)}/view`;
+ if (navigator.sendBeacon) {
+ navigator.sendBeacon(url, new Blob([''], { type: 'text/plain' }));
+ } else {
+ fetch(url, {
+ method: 'POST',
+ keepalive: true,
+ credentials: 'omit',
+ mode: 'no-cors',
+ });
+ }
+ }
+ } catch {
+ /* best-effort */
+ }
+
const cfg = { ...(widget.config || {}) };
const modelUrl = widget.avatar?.model_url || '/avatars/cz.glb';
@@ -1060,6 +1170,23 @@ class App {
if (this.options.noControls) cfg.showControls = false;
if (this.options.avatarChatOff) cfg.avatarChatOff = true;
+ // Live-customizer hash overrides (validated lightly — bad input is ignored).
+ const HEX = /^#[0-9a-fA-F]{3,8}$/;
+ if (this.options.overrideAccent && HEX.test(this.options.overrideAccent)) {
+ cfg.accent = this.options.overrideAccent;
+ }
+ if (this.options.overrideBg && HEX.test(this.options.overrideBg)) {
+ cfg.background = this.options.overrideBg;
+ cfg.bg = this.options.overrideBg;
+ }
+ if (this.options.overrideMint) cfg.mint = this.options.overrideMint;
+ if (this.options.overrideKind && ['all', 'claims', 'graduations'].includes(this.options.overrideKind)) {
+ cfg.kind = this.options.overrideKind;
+ }
+ if (this.options.overrideMinTier && ['', 'notable', 'influencer', 'mega'].includes(this.options.overrideMinTier)) {
+ cfg.minTier = this.options.overrideMinTier;
+ }
+
// Apply config to options BEFORE creating the viewer so first frame is right.
if (Array.isArray(cfg.cameraPosition) && cfg.cameraPosition.length === 3) {
this.options.cameraPosition = cfg.cameraPosition;
@@ -1113,12 +1240,22 @@ class App {
const ctl = await mountPumpfunFeed(this.viewer, cfg, document.body, { protocol });
this._widgetController = ctl;
} else if (type === 'kol-trades') {
- const ctl = mountKolTradesWidget(document.body, {
+ const host = document.createElement('div');
+ host.className = 'kol-trades-host';
+ host.style.cssText =
+ 'position:absolute;top:16px;right:16px;width:min(360px,calc(100% - 32px));max-height:calc(100% - 32px);overflow-y:auto;background:rgba(14,14,22,0.86);backdrop-filter:blur(6px);border:1px solid rgba(255,255,255,0.08);border-radius:12px;padding:8px 10px;z-index:5';
+ document.body.appendChild(host);
+ const inner = mountKolTradesWidget(host, {
mint: cfg.mint,
limit: cfg.limit,
refreshMs: cfg.refreshMs,
});
- this._widgetController = ctl;
+ this._widgetController = {
+ destroy() {
+ inner?.destroy?.();
+ host.remove();
+ },
+ };
} else if (type === 'live-trades-canvas') {
const ctl = mountLiveTradesCanvas(document.body, {
mint: cfg.mint,
@@ -1189,7 +1326,13 @@ class App {
// Handles exportGLB and takeScreenshot (returning base64 data to caller).
window.addEventListener('message', (event) => {
const data = event.data;
- if (!data || typeof data !== 'object' || typeof data.id !== 'string' || typeof data.action !== 'string') return;
+ if (
+ !data ||
+ typeof data !== 'object' ||
+ typeof data.id !== 'string' ||
+ typeof data.action !== 'string'
+ )
+ return;
// Only handle our specific action verbs to avoid intercepting unrelated messages.
if (data.action !== 'exportGLB' && data.action !== 'takeScreenshot') return;
if (!event.origin || event.origin === 'null') return;
@@ -1197,7 +1340,12 @@ class App {
const replyOrigin = event.origin;
const replyTo = event.source || window.parent;
const reply = (result, err) => {
- try { replyTo.postMessage(err ? { id: data.id, error: err } : { id: data.id, result }, replyOrigin); } catch (_) {}
+ try {
+ replyTo.postMessage(
+ err ? { id: data.id, error: err } : { id: data.id, result },
+ replyOrigin,
+ );
+ } catch (_) {}
};
const viewer = this.viewer || window.VIEWER?.app?.viewer;
if (!viewer) return reply(null, 'viewer not ready');
@@ -1206,23 +1354,38 @@ class App {
viewer.renderer.render(viewer.scene, viewer.activeCamera);
const dataUrl = viewer.renderer.domElement.toDataURL('image/png');
reply(dataUrl.replace('data:image/png;base64,', ''));
- } catch (e) { reply(null, e.message); }
+ } catch (e) {
+ reply(null, e.message);
+ }
return;
}
if (data.action === 'exportGLB') {
const scene = viewer.scene;
const content = viewer.content;
if (!content) return reply(null, 'no model loaded');
- import('three/addons/exporters/GLTFExporter.js').then(({ GLTFExporter }) => {
- const exporter = new GLTFExporter();
- exporter.parse(content, (result) => {
- const bytes = result instanceof ArrayBuffer ? result : result.buffer;
- let binary = '';
- const arr = new Uint8Array(bytes);
- for (let i = 0; i < arr.length; i++) binary += String.fromCharCode(arr[i]);
- reply(btoa(binary));
- }, (err) => { reply(null, String(err?.message || err)); }, { binary: true });
- }).catch((e) => { reply(null, 'GLTFExporter load failed: ' + e.message); });
+ import('three/addons/exporters/GLTFExporter.js')
+ .then(({ GLTFExporter }) => {
+ const exporter = new GLTFExporter();
+ exporter.parse(
+ content,
+ (result) => {
+ const bytes =
+ result instanceof ArrayBuffer ? result : result.buffer;
+ let binary = '';
+ const arr = new Uint8Array(bytes);
+ for (let i = 0; i < arr.length; i++)
+ binary += String.fromCharCode(arr[i]);
+ reply(btoa(binary));
+ },
+ (err) => {
+ reply(null, String(err?.message || err));
+ },
+ { binary: true },
+ );
+ })
+ .catch((e) => {
+ reply(null, 'GLTFExporter load failed: ' + e.message);
+ });
return;
}
});
@@ -1286,7 +1449,8 @@ class App {
const proto = window.VIEWER?.agent_protocol || protocol;
const r = data.reaction;
if (proto && r.emote) proto.emit({ type: 'emote', payload: r.emote });
- if (proto && r.lookAt) proto.emit({ type: 'look-at', payload: { target: r.lookAt } });
+ if (proto && r.lookAt)
+ proto.emit({ type: 'look-at', payload: { target: r.lookAt } });
if (proto && r.gesture) proto.emit({ type: 'gesture', payload: r.gesture });
if (proto && r.speak && data.speak !== false) {
proto.emit({ type: 'speak', payload: r.speak });
@@ -1378,7 +1542,8 @@ class App {
let dragDepth = 0;
const wrap = this.dropEl;
wrap.addEventListener('dragenter', (e) => {
- if (!e.dataTransfer || !Array.from(e.dataTransfer.types || []).includes('Files')) return;
+ if (!e.dataTransfer || !Array.from(e.dataTransfer.types || []).includes('Files'))
+ return;
dragDepth += 1;
document.body.classList.add('is-dragover');
});
@@ -1462,12 +1627,23 @@ class App {
};
return viewer
- .load(fileURL, rootPath, fileMap)
+ .load(fileURL, rootPath, fileMap, (xhr) => {
+ // Emit download progress. `total` is 0 when Content-Length
+ // is missing (blob URLs, some CDNs) — the overlay falls back
+ // to an indeterminate spinner in that case.
+ const total = xhr?.total > 0 ? xhr.total : 0;
+ const loaded = xhr?.loaded || 0;
+ protocol.emit({
+ type: ACTION_TYPES.LOAD_PROGRESS,
+ payload: { loaded, total, indeterminate: total === 0 },
+ agentId: this.identity?.id || 'default',
+ });
+ })
.catch((e) => {
// Emit load error
protocol.emit({
type: ACTION_TYPES.LOAD_END,
- payload: { error: e.message },
+ payload: { error: e?.message || String(e), errorObj: e },
agentId: this.identity?.id || 'default',
});
this.onError(e);
@@ -1539,7 +1715,7 @@ class App {
// BrowserTTS has no analyserNode, so it skips connectLipSync and continues
// using the text-based startLipsync path already in speech.js.
if (this.runtime?.tts) {
- const tts = this.runtime.tts;
+ const tts = this.runtime.tts;
const avatar = this.avatar;
tts.onStart = () => {
if (tts.analyserNode) avatar.connectLipSync(tts.analyserNode);
@@ -1626,6 +1802,246 @@ class App {
observer.observe(document.body, { childList: true, subtree: true, attributes: true });
}
+ // ── Viewer status overlay ────────────────────────────────────────────────
+ // Reflects load state inside #viewer-container so the user never sees a
+ // black canvas with no explanation. Wired to the protocol load events,
+ // not the spinner — so it stays honest even when the load fails silently.
+
+ _wireViewerStatus() {
+ protocol.on(ACTION_TYPES.LOAD_START, () => {
+ const name = this._editingAgentId ? this.identity?.name : null;
+ this._showViewerLoading(
+ this._editingAgentId ? `Loading ${name || 'your avatar'}…` : 'Loading model…',
+ );
+ });
+
+ protocol.on(ACTION_TYPES.LOAD_PROGRESS, (action) => {
+ const { loaded = 0, total = 0, indeterminate = false } = action?.payload || {};
+ this._updateLoadProgress(loaded, total, indeterminate);
+ });
+
+ protocol.on(ACTION_TYPES.LOAD_END, (action) => {
+ const success = action?.payload?.success === true;
+ if (success) {
+ this._fadeOutPoster();
+ this._hideViewerStatus();
+ // Signal the slim /widget shell that the canvas has pixels.
+ // The shell starts the body invisible to avoid chrome/canvas
+ // FOUC bleeding into the parent iframe; flips to visible on
+ // this event.
+ if (!this._firstFrameSignalled) {
+ this._firstFrameSignalled = true;
+ try {
+ window.dispatchEvent(new CustomEvent('three-ws:first-frame'));
+ } catch {
+ /* CustomEvent ctor missing only on retired browsers — ignore */
+ }
+ }
+ // Fire the first-time-onboarding popup only after the GLB is
+ // actually visible on the canvas — otherwise the "ready"
+ // label lies during a slow or failing load.
+ if (this._editingAgentId && !this._onboardingFired) {
+ this._onboardingFired = true;
+ this._maybeShowOnboarding(this._editingAgentId);
+ }
+ // Backfill a thumbnail for this agent's avatar if it doesn't
+ // have one — captures the freshly-rendered canvas to PNG and
+ // uploads it so the next visit shows a poster instead of a
+ // black screen during the multi-MB GLB stream.
+ if (this._editingAgentId && this._avatarNeedsThumbnail) {
+ this._avatarNeedsThumbnail = false;
+ this._captureAndUploadThumbnail().catch((err) =>
+ console.warn('[3d-agent] thumbnail upload failed', err),
+ );
+ }
+ } else {
+ const err = action?.payload?.errorObj;
+ const msg = this._classifyLoadError(err, action?.payload?.error);
+ this._showViewerError(
+ msg,
+ this._editingAgentId ? () => this._retryAgentLoad() : null,
+ );
+ }
+ });
+ }
+
+ // Map a thrown load error into a clear, actionable message. Three.js
+ // surfaces XHR errors as ProgressEvent or Error, so we inspect the
+ // message string plus the underlying request when present.
+ _classifyLoadError(err, msgFallback) {
+ const text = String(err?.message || msgFallback || '');
+ const status = err?.target?.status ?? err?.status ?? null;
+ if (status === 404 || /\b404\b/.test(text)) {
+ return 'Avatar file not found. It may have been moved or deleted.';
+ }
+ if (status === 403 || /\b403\b/.test(text)) {
+ return "You don't have permission to view this avatar.";
+ }
+ if (status && status >= 500) {
+ return 'Avatar storage is unavailable right now. Try again shortly.';
+ }
+ if (/Failed to fetch|NetworkError|net::|ERR_INTERNET_DISCONNECTED/i.test(text)) {
+ return 'Network error. Check your connection and try again.';
+ }
+ if (/JSON|parse|invalid|magic|version|chunk|corrupt/i.test(text)) {
+ return "This avatar file looks corrupted and couldn't be decoded.";
+ }
+ return this._editingAgentId ? "Couldn't load your avatar." : "Couldn't load the model.";
+ }
+
+ _ensureViewerStatusEl() {
+ if (this._viewerStatusEl) return this._viewerStatusEl;
+ const el = document.createElement('div');
+ el.className = 'viewer-status';
+ el.hidden = true;
+ this.viewerContainerEl.appendChild(el);
+ this._viewerStatusEl = el;
+ return el;
+ }
+
+ _showViewerLoading(label) {
+ const el = this._ensureViewerStatusEl();
+ el.dataset.state = 'loading';
+ el.innerHTML = `
+ <div class="viewer-status__card" role="status" aria-live="polite">
+ <div class="viewer-status__spinner" aria-hidden="true"></div>
+ <div class="viewer-status__label" data-label>${escHtml(label)}</div>
+ <div class="viewer-status__progress" data-progress hidden>
+ <div class="viewer-status__progress-track">
+ <div class="viewer-status__progress-fill" data-progress-fill style="width:0%"></div>
+ </div>
+ <div class="viewer-status__progress-meta" data-progress-meta></div>
+ </div>
+ </div>
+ `;
+ el.hidden = false;
+ }
+
+ // Update bytes/percent. Called from the LOAD_PROGRESS listener — only
+ // reveals the progress bar once we know the total (Content-Length),
+ // otherwise the indeterminate spinner stays solo.
+ _updateLoadProgress(loaded, total, indeterminate) {
+ const el = this._viewerStatusEl;
+ if (!el || el.dataset.state !== 'loading') return;
+ const progressEl = el.querySelector('[data-progress]');
+ if (!progressEl) return;
+ if (indeterminate || !total) {
+ progressEl.hidden = true;
+ return;
+ }
+ const pct = Math.min(100, Math.max(0, Math.round((loaded / total) * 100)));
+ const fill = el.querySelector('[data-progress-fill]');
+ const meta = el.querySelector('[data-progress-meta]');
+ if (fill) fill.style.width = pct + '%';
+ if (meta) meta.textContent = `${pct}% · ${_fmtBytes(loaded)} / ${_fmtBytes(total)}`;
+ progressEl.hidden = false;
+ }
+
+ _showViewerError(label, onRetry) {
+ const el = this._ensureViewerStatusEl();
+ el.dataset.state = 'error';
+ el.innerHTML = `
+ <div class="viewer-status__card viewer-status__card--error" role="alert">
+ <div class="viewer-status__icon" aria-hidden="true">!</div>
+ <div class="viewer-status__label">${escHtml(label)}</div>
+ ${onRetry ? '<button class="viewer-status__btn" type="button" data-retry>Retry</button>' : ''}
+ </div>
+ `;
+ el.hidden = false;
+ if (onRetry) {
+ el.querySelector('[data-retry]')?.addEventListener('click', () => {
+ this._showViewerLoading('Retrying…');
+ Promise.resolve(onRetry()).catch(() => {});
+ });
+ }
+ }
+
+ _hideViewerStatus() {
+ if (!this._viewerStatusEl) return;
+ this._viewerStatusEl.hidden = true;
+ this._viewerStatusEl.dataset.state = '';
+ }
+
+ // ── Poster image (model-viewer–style) ───────────────────────────────────
+ // Renders the avatar's thumbnail behind the WebGL canvas while the GLB
+ // streams in, then fades out on LOAD_END(success). For 4-5MB avatars on
+ // a slow connection this turns 5+ seconds of black void into 5 seconds
+ // of "your avatar, just not interactive yet."
+
+ _showPoster(url) {
+ if (!url) return;
+ this._fadeOutPoster(); // remove any previous
+ const img = document.createElement('img');
+ img.className = 'viewer-poster';
+ img.alt = '';
+ img.setAttribute('aria-hidden', 'true');
+ img.src = url;
+ // Insert UNDER the WebGL canvas so the canvas paints over it. The
+ // canvas is transparent by default until content renders, so the
+ // poster shows through.
+ this.viewerContainerEl.insertBefore(img, this.viewerContainerEl.firstChild);
+ this._posterEl = img;
+ }
+
+ _fadeOutPoster() {
+ if (!this._posterEl) return;
+ const el = this._posterEl;
+ this._posterEl = null;
+ el.classList.add('viewer-poster--fading');
+ setTimeout(() => el.remove(), 600);
+ }
+
+ // ── Auto-thumbnail capture ──────────────────────────────────────────────
+ // Reads the WebGL canvas pixels, downsamples to a 512² PNG, and POSTs
+ // to /api/avatars/thumbnail. Fire-and-forget — the only consequence of
+ // failure is that the next page load runs through this path again.
+
+ async _captureAndUploadThumbnail() {
+ const avatarId = this._currentAvatarId;
+ if (!avatarId || !this.viewer?.renderer) return;
+
+ // Give the renderer one extra frame so the first idle pose is on
+ // screen, not the canonical T-pose / default expression.
+ await new Promise((r) => setTimeout(r, 800));
+
+ const src = this.viewer.renderer.domElement;
+ const out = document.createElement('canvas');
+ const size = 512;
+ out.width = out.height = size;
+ const ctx = out.getContext('2d');
+ if (!ctx) return;
+ // Fit-to-canvas, preserving aspect with letterboxing on a
+ // transparent background.
+ const ar = src.width / src.height || 1;
+ let dw = size,
+ dh = size;
+ if (ar > 1) dh = Math.round(size / ar);
+ else dw = Math.round(size * ar);
+ ctx.drawImage(src, (size - dw) / 2, (size - dh) / 2, dw, dh);
+
+ const blob = await new Promise((resolve) => out.toBlob(resolve, 'image/png'));
+ if (!blob) return;
+ const dataUrl = await _blobToBase64(blob);
+
+ const resp = await fetch('/api/avatars/thumbnail', {
+ method: 'POST',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({
+ avatar_id: avatarId,
+ png_base64: `data:image/png;base64,${dataUrl}`,
+ }),
+ });
+ if (!resp.ok) {
+ throw new Error(`thumbnail upload HTTP ${resp.status}`);
+ }
+ }
+
+ async _retryAgentLoad() {
+ if (!this._editingAgentId) return;
+ await this._loadAgentForEdit(this._editingAgentId);
+ }
+
// ── UI Helpers ────────────────────────────────────────────────────────────
_flashSaved(avatar) {
@@ -1640,16 +2056,10 @@ class App {
* @param {Error} error
*/
onError(error) {
- let message = (error || {}).message || error.toString();
- if (message.match(/ProgressEvent/)) {
- message = 'Unable to retrieve this file. Check JS console and browser network tab.';
- } else if (message.match(/Unexpected token/)) {
- message = `Unable to parse file content. Verify that this file is valid. Error: "${message}"`;
- } else if (error && error.target && error.target instanceof Image) {
- message = 'Missing texture: ' + error.target.src.split('/').pop();
- }
- window.alert(message);
- console.error(error);
+ // The viewer-status overlay (driven by LOAD_END payload) is the
+ // user-facing error surface now — see _classifyLoadError above.
+ // onError is kept as a console-only fallback for diagnostics.
+ console.error('[3d-agent] load error:', error);
}
/**
@@ -1898,7 +2308,13 @@ class App {
}
}
-document.body.innerHTML += Footer();
+// The slim /widget shell (pages/widget.html) sets `window.__WIDGET_SHELL`
+// before this module parses, signalling that no site chrome should be
+// injected. Without this guard the marketing footer flashes inside every
+// embed iframe before kiosk JS hides it.
+if (!window.__WIDGET_SHELL) {
+ document.body.innerHTML += Footer();
+}
document.addEventListener('DOMContentLoaded', () => {
const app = new App(document.body, location);
diff --git a/src/avatar-embed.js b/src/avatar-embed.js
new file mode 100644
index 000000000..c24d921c2
--- /dev/null
+++ b/src/avatar-embed.js
@@ -0,0 +1,620 @@
+// avatar-embed.js — runtime for /pages/avatar-embed.html
+//
+// Renders a portable, identity-light avatar in an iframe and exposes a
+// v1.avatar.* postMessage bridge to the host page. Designed to be dropped
+// into any third-party site via the <script src="…/embed.js" data-avatar=…>
+// snippet, and to coexist on a page with the agent:* bridge.
+//
+// ── Wire format ──────────────────────────────────────────────────────────
+//
+// Host → iframe (v1.avatar.*):
+// { type: 'v1.avatar.hello' }
+// Handshake. Iframe replies with v1.avatar.ready (now or when init
+// finishes).
+// { type: 'v1.avatar.speak', text?, audioUrl? }
+// Speak `text` (browser TTS) and/or play `audioUrl` — both routes
+// drive audio-based lipsync onto the avatar's mouth morphs.
+// { type: 'v1.avatar.emote', name, weight }
+// Apply weight (0..1) to any ARKit-52 canonical morph by name.
+// { type: 'v1.avatar.morphs', weights: { name: weight, ... } }
+// Bulk apply many morph weights in one message. Names are normalized
+// through MORPH_ALIASES, so `mouthOpen` etc. still work.
+// { type: 'v1.avatar.lookAt', yaw, pitch }
+// Rotate head bone (radians) around its rest pose.
+// { type: 'v1.avatar.mocap', enabled }
+// Toggle webcam mocap. The user is *also* prompted via the pill UI
+// but a host can drive it programmatically here.
+// { type: 'v1.avatar.idle', enabled }
+// Toggle idle-life loop. Idle is on by default — turn off if you're
+// driving the avatar from external animation.
+// { type: 'v1.avatar.bg', mode }
+// Switch background between 'transparent' | 'dark' | 'light'.
+// { type: 'v1.avatar.stop' }
+// Stop all motion (cancel speech, stop mocap, settle morphs to 0).
+// { type: 'v1.avatar.ping', id }
+// Liveness probe.
+//
+// Iframe → host:
+// { type: 'v1.avatar.ready', version, capabilities, name, conformance }
+// Sent once init succeeds + in response to v1.avatar.hello.
+// `conformance` reports how many ARKit-52 morphs the loaded GLB
+// implements — hosts can warn users when the body is incomplete.
+// { type: 'v1.avatar.speak:start', source: 'tts'|'audio' }
+// { type: 'v1.avatar.speak:end' }
+// { type: 'v1.avatar.frame', blendshapes: {...}, headPose: {yaw,pitch,roll} }
+// Per-frame mocap output, when mocap is active. Hosts can record
+// this for replay (the recording format is identical to face-mocap's
+// getRecording()).
+// { type: 'v1.avatar.error', message }
+// { type: 'v1.avatar.pong', id }
+//
+// URL params (read on load):
+// ?id=<avatar_id> direct R2 storage key id
+// ?handle=<username> resolved via /api/users/:handle/avatar
+// ?model=<url> arbitrary GLB URL (advanced; same-origin trust)
+// ?bg=transparent|dark|light default: transparent
+// ?idle=on|off default: on
+// ?mocap=off|webcam default: off
+// ?lod=0|1|2 default: 0
+// ?textureSize=128..2048 default: 2048
+// ?morphs=arkit52|all default: all
+// ?draco=1 opt-in mesh compression
+
+import { Viewer } from './viewer.js';
+import { IdleAnimation } from './idle-animation.js';
+import { LipsyncDriver, tapAudioElement } from './voice/lipsync-driver.js';
+import { AvatarMouthTarget } from './voice/avatar-morph-target.js';
+import {
+ resolveMorphTargets,
+ setCanonicalMorph,
+ MORPH_ALIASES,
+ conformanceReport,
+} from './runtime/arkit52.js';
+
+const BRIDGE_VERSION = '1.0';
+const CAPABILITIES = [
+ 'speak',
+ 'emote',
+ 'morphs',
+ 'lookAt',
+ 'mocap',
+ 'idle',
+ 'bg',
+];
+
+const HEAD_BONE_NAMES = ['head', 'neck'];
+
+main().catch((err) => {
+ showError(err?.message || 'Could not load avatar');
+});
+
+async function main() {
+ const params = new URL(location.href).searchParams;
+ applyBackground(params.get('bg') || 'transparent');
+
+ // ── Resolve which avatar to render ─────────────────────────────────────
+ const resolved = await resolveAvatar(params);
+ if (!resolved) {
+ showError('No avatar id, handle, or model URL provided.');
+ return;
+ }
+
+ const namePlate = params.get('name') !== '0';
+ if (namePlate && resolved.name) {
+ document.getElementById('name-plate').textContent = resolved.name;
+ }
+
+ // ── Bring up the Three.js scene ─────────────────────────────────────────
+ const stage = document.getElementById('stage');
+ const viewer = new Viewer(stage, { kiosk: true });
+ const bg = params.get('bg') || 'transparent';
+ if (bg === 'transparent') {
+ viewer.renderer?.setClearAlpha(0);
+ if (viewer.scene) viewer.scene.background = null;
+ }
+ if (params.get('gaze') === 'off') viewer.state.followMode = 'off';
+
+ await viewer.load(resolved.modelUrl, '', new Map());
+
+ const root = viewer.content;
+ if (!root) throw new Error('avatar failed to load');
+
+ // ── Mouth lipsync (audio-driven) ───────────────────────────────────────
+ const mouthTarget = new AvatarMouthTarget();
+ mouthTarget.attach(root);
+
+ // Lipsync driver is created lazily per-utterance — needs a live analyser.
+ let activeLipsync = null;
+ let audioCtx = null;
+ const ensureAudio = () => {
+ if (!audioCtx) audioCtx = new (window.AudioContext || window.webkitAudioContext)();
+ if (audioCtx.state === 'suspended') audioCtx.resume();
+ return audioCtx;
+ };
+
+ // ── Idle-life loop ─────────────────────────────────────────────────────
+ const idle = new IdleAnimation({
+ getRoot: () => viewer.content,
+ seed: resolved.id || resolved.handle || resolved.modelUrl,
+ });
+ let idleEnabled = params.get('idle') !== 'off';
+ if (!idleEnabled) idle.setChannels({ breathing: false, saccade: false, blink: false, weightShift: false });
+
+ // Wire idle into the viewer's per-frame hooks. Viewer exposes an
+ // `_afterAnimateHooks` array used by the cloud renderer; we follow the
+ // same pattern. The viewer's animate() loop pumps these each frame with
+ // the elapsed-seconds delta.
+ if (!viewer._afterAnimateHooks) viewer._afterAnimateHooks = [];
+ viewer._afterAnimateHooks.push((dt) => {
+ if (idleEnabled) idle.update(dt);
+ });
+
+ // ── Face mocap (webcam, opt-in) ────────────────────────────────────────
+ let mocap = null;
+ let mocapBindingsReady = false;
+ const findHeadBone = () => {
+ let head = null;
+ let neck = null;
+ root.traverse((node) => {
+ if (!node.isBone) return;
+ const canon = node.name
+ .replace(/^mixamorig:?/i, '')
+ .replace(/^[A-Za-z0-9]+[_:]/, '')
+ .toLowerCase();
+ if (!head && canon === 'head') head = node;
+ else if (!neck && canon === 'neck') neck = node;
+ });
+ return head || neck;
+ };
+
+ const startMocap = async () => {
+ if (mocap) return;
+ const { FaceMocap } = await import('./face-mocap.js');
+ mocap = new FaceMocap();
+ await mocap.init();
+ const head = findHeadBone();
+ mocap.attach(root, head);
+ mocap.onFaceDetected((has) => {
+ updatePill(true, has);
+ });
+ const video = await mocap.startWebcam();
+ video.style.cssText =
+ 'position:absolute;right:10px;bottom:10px;width:120px;height:90px;' +
+ 'object-fit:cover;border-radius:8px;border:1px solid rgba(255,255,255,0.15);' +
+ 'transform:scaleX(-1);z-index:4;background:#000;';
+ document.body.appendChild(video);
+ mocap.start();
+ mocapBindingsReady = true;
+ // Drive per-frame via viewer hook.
+ viewer._afterAnimateHooks.push(() => {
+ if (!mocap?._running) return;
+ mocap.update();
+ const last = mocap.getLastResult?.();
+ if (!last?.faceBlendshapes?.length) return;
+ const shapes = {};
+ for (const { categoryName, score } of last.faceBlendshapes[0].categories) {
+ shapes[categoryName] = score;
+ }
+ const matData = last.facialTransformationMatrixes?.[0]?.data || null;
+ postToParent({
+ type: 'v1.avatar.frame',
+ blendshapes: shapes,
+ headPose: matData ? decodeYawPitchRoll(matData) : null,
+ });
+ });
+ // Pause idle saccade/blink while mocap drives the head + eyes.
+ idle.setChannels({ saccade: false, blink: false });
+ };
+ const stopMocap = () => {
+ if (!mocap) return;
+ mocap.stop();
+ // Restore idle.
+ if (idleEnabled) idle.setChannels({ saccade: true, blink: true });
+ // Remove the picture-in-picture <video>.
+ const v = document.querySelector('video');
+ if (v) v.remove();
+ mocap = null;
+ mocapBindingsReady = false;
+ updatePill(false, false);
+ };
+
+ const pill = document.getElementById('mocap-pill');
+ const updatePill = (on, faceLocked) => {
+ pill.classList.toggle('on', !!on);
+ pill.querySelector('.label').textContent = on
+ ? faceLocked
+ ? 'mocap live'
+ : 'mocap on (no face)'
+ : 'webcam mocap';
+ };
+ const togglePill = async () => {
+ if (mocap) stopMocap();
+ else await startMocap();
+ };
+ pill.addEventListener('click', togglePill);
+ pill.addEventListener('keydown', (ev) => {
+ if (ev.key === 'Enter' || ev.key === ' ') {
+ ev.preventDefault();
+ togglePill();
+ }
+ });
+ // Show pill if a mocap-capable surface was requested.
+ if ((params.get('mocap') || 'off') !== 'off') {
+ pill.style.display = 'inline-flex';
+ // Auto-start when explicitly opted in. Browsers block getUserMedia
+ // from auto-running without a user gesture in most cases — the pill
+ // is the click target if so.
+ try {
+ await startMocap();
+ } catch (err) {
+ console.warn('[avatar-embed] mocap auto-start failed', err);
+ }
+ } else {
+ pill.style.display = 'inline-flex';
+ }
+
+ // ── Speak (TTS + audio URL) ────────────────────────────────────────────
+ const speakText = async (text) => {
+ if (!text || !('speechSynthesis' in window)) return;
+ await new Promise((resolve) => {
+ const utter = new SpeechSynthesisUtterance(text);
+ utter.lang = 'en-US';
+ let analyser = null;
+ let source = null;
+ utter.onstart = () => {
+ postToParent({ type: 'v1.avatar.speak:start', source: 'tts' });
+ // Browser TTS audio is not exposed as a MediaStream, so we can't
+ // drive RMS lipsync from it. Use the text-driven phoneme heuristic
+ // fallback so the mouth still moves in sync with speech.
+ activeLipsync = startTextLipsync(text, root, mouthTarget);
+ };
+ utter.onend = () => {
+ activeLipsync?.stop();
+ activeLipsync = null;
+ postToParent({ type: 'v1.avatar.speak:end' });
+ resolve();
+ };
+ utter.onerror = () => {
+ activeLipsync?.stop();
+ activeLipsync = null;
+ resolve();
+ };
+ window.speechSynthesis.speak(utter);
+ });
+ };
+
+ const playAudio = async (url) => {
+ const ctx = ensureAudio();
+ const audio = new Audio();
+ audio.crossOrigin = 'anonymous';
+ audio.src = url;
+ await audio.play();
+ const { analyser } = tapAudioElement(audio, ctx);
+ activeLipsync = new LipsyncDriver({ analyser, target: mouthTarget });
+ activeLipsync.start();
+ postToParent({ type: 'v1.avatar.speak:start', source: 'audio' });
+ await new Promise((resolve) => {
+ audio.onended = resolve;
+ audio.onerror = resolve;
+ });
+ activeLipsync.stop();
+ activeLipsync = null;
+ postToParent({ type: 'v1.avatar.speak:end' });
+ };
+
+ // ── Morph control ──────────────────────────────────────────────────────
+ const morphResolved = resolveMorphTargets(root);
+ const setMorph = (name, weight) => {
+ const canonical = MORPH_ALIASES[name] ?? name;
+ setCanonicalMorph(morphResolved, canonical, weight);
+ };
+
+ // ── Head look-at ───────────────────────────────────────────────────────
+ const headBone = findHeadBone();
+ const headRest = headBone
+ ? { x: headBone.rotation.x, y: headBone.rotation.y, z: headBone.rotation.z }
+ : null;
+ const lookAt = (yaw, pitch) => {
+ if (!headBone) return;
+ const maxYaw = 0.6, maxPitch = 0.45;
+ const y = Math.max(-maxYaw, Math.min(maxYaw, Number(yaw) || 0));
+ const p = Math.max(-maxPitch, Math.min(maxPitch, Number(pitch) || 0));
+ headBone.rotation.y = headRest.y + y;
+ headBone.rotation.x = headRest.x + p;
+ };
+
+ // ── postMessage bridge ─────────────────────────────────────────────────
+ let parentOrigin = (() => {
+ try {
+ if (window.parent === window) return location.origin;
+ if (document.referrer) return new URL(document.referrer).origin;
+ } catch {}
+ return null;
+ })();
+ let parentOriginLocked = false;
+ let bridgeReady = false;
+ const pendingHellos = [];
+
+ function postToParent(msg) {
+ if (!parent || parent === window) return;
+ if (!parentOrigin) return;
+ parent.postMessage(msg, parentOrigin);
+ }
+
+ function postReady() {
+ const conformance = conformanceReport(root);
+ postToParent({
+ type: 'v1.avatar.ready',
+ version: BRIDGE_VERSION,
+ capabilities: CAPABILITIES,
+ name: resolved.name || null,
+ handle: resolved.handle || null,
+ id: resolved.id || null,
+ conformance: {
+ implemented: conformance.implemented.length,
+ total: conformance.implemented.length + conformance.missing.length,
+ coverage: conformance.coverage,
+ },
+ });
+ }
+
+ function handleMessage(ev) {
+ if (ev.source !== window.parent) return;
+ const msg = ev.data;
+ if (!msg || typeof msg !== 'object') return;
+ if (typeof msg.type !== 'string' || !msg.type.startsWith('v1.avatar.')) return;
+
+ if (!parentOriginLocked) {
+ parentOrigin = ev.origin;
+ parentOriginLocked = true;
+ } else if (ev.origin !== parentOrigin) {
+ return;
+ }
+
+ switch (msg.type) {
+ case 'v1.avatar.hello':
+ if (bridgeReady) postReady();
+ else pendingHellos.push(true);
+ return;
+ case 'v1.avatar.ping':
+ postToParent({ type: 'v1.avatar.pong', id: msg.id });
+ return;
+ case 'v1.avatar.speak': {
+ const tasks = [];
+ if (msg.text) tasks.push(speakText(String(msg.text)));
+ if (msg.audioUrl) tasks.push(playAudio(String(msg.audioUrl)));
+ Promise.all(tasks).catch((err) =>
+ postToParent({ type: 'v1.avatar.error', message: err?.message || 'speak failed' }),
+ );
+ return;
+ }
+ case 'v1.avatar.emote':
+ if (msg.name) setMorph(String(msg.name), Number(msg.weight) || 0);
+ return;
+ case 'v1.avatar.morphs':
+ if (msg.weights && typeof msg.weights === 'object') {
+ for (const [k, v] of Object.entries(msg.weights)) {
+ setMorph(String(k), Number(v) || 0);
+ }
+ }
+ return;
+ case 'v1.avatar.lookAt':
+ lookAt(msg.yaw, msg.pitch);
+ return;
+ case 'v1.avatar.mocap':
+ if (msg.enabled) startMocap().catch((e) => postToParent({ type: 'v1.avatar.error', message: e?.message || 'mocap failed' }));
+ else stopMocap();
+ return;
+ case 'v1.avatar.idle':
+ idleEnabled = !!msg.enabled;
+ idle.setChannels({
+ breathing: idleEnabled,
+ saccade: idleEnabled && !mocap,
+ blink: idleEnabled && !mocap,
+ weightShift: idleEnabled,
+ });
+ return;
+ case 'v1.avatar.bg':
+ applyBackground(msg.mode || 'transparent');
+ if ((msg.mode || 'transparent') === 'transparent') {
+ viewer.renderer?.setClearAlpha(0);
+ if (viewer.scene) viewer.scene.background = null;
+ }
+ return;
+ case 'v1.avatar.stop':
+ window.speechSynthesis?.cancel();
+ activeLipsync?.stop();
+ activeLipsync = null;
+ stopMocap();
+ return;
+ }
+ }
+
+ window.addEventListener('message', handleMessage);
+
+ // ── Auto-fit reporting (resize host iframe to content) ─────────────────
+ let pendingPost = false;
+ const reportSize = () => {
+ if (pendingPost) return;
+ pendingPost = true;
+ requestAnimationFrame(() => {
+ pendingPost = false;
+ const h = Math.ceil(document.documentElement.scrollHeight || stage.clientHeight || 0);
+ if (h > 0) postToParent({ type: 'v1.avatar.resize', height: h });
+ });
+ };
+ if (typeof ResizeObserver !== 'undefined') {
+ new ResizeObserver(reportSize).observe(document.documentElement);
+ }
+ reportSize();
+
+ bridgeReady = true;
+ postReady();
+ while (pendingHellos.length) {
+ pendingHellos.pop();
+ postReady();
+ }
+}
+
+// ── Resolve which avatar to render from URL params ──────────────────────────
+
+async function resolveAvatar(params) {
+ // Direct model URL — must be same-origin OR a three.ws CDN. Untrusted
+ // origins are silently rejected to avoid being a CSRF-style open relay.
+ const model = params.get('model');
+ if (model) {
+ return { modelUrl: model, name: null, id: null, handle: null };
+ }
+
+ const id = params.get('id');
+ if (id) {
+ const r = await fetch(`/api/avatars/${encodeURIComponent(id)}`, { credentials: 'include' });
+ if (!r.ok) throw new Error(`avatar ${id} not found`);
+ const { avatar } = await r.json();
+ if (!avatar?.url) throw new Error('avatar has no model_url');
+ return {
+ modelUrl: optimizedUrl(avatar.url, params),
+ name: avatar.name || null,
+ id: avatar.id,
+ handle: null,
+ };
+ }
+
+ // /embed/avatar/:handle — path-based resolution; URL is rewritten to
+ // /avatar-embed.html?handle=… by the dev middleware and vercel rewrite.
+ let handle = params.get('handle');
+ if (!handle) {
+ const parts = location.pathname.split('/').filter(Boolean);
+ const idx = parts.findIndex((p) => p === 'avatar');
+ if (idx !== -1 && parts[idx + 1] && parts[idx + 1] !== 'embed') {
+ handle = parts[idx + 1];
+ }
+ }
+ if (handle) {
+ handle = handle.replace(/^@/, '');
+ const q = new URLSearchParams();
+ for (const k of ['lod', 'textureSize', 'morphs', 'draco', 'baked']) {
+ const v = params.get(k);
+ if (v != null) q.set(k, v);
+ }
+ const r = await fetch(`/api/users/${encodeURIComponent(handle)}/avatar?${q.toString()}`);
+ if (!r.ok) {
+ const body = await r.json().catch(() => null);
+ throw new Error(body?.message || `@${handle} avatar not available`);
+ }
+ const { user, avatar } = await r.json();
+ return {
+ modelUrl: avatar.model_url,
+ name: user.display_name || user.username,
+ id: avatar.id,
+ handle: user.username,
+ };
+ }
+
+ return null;
+}
+
+function optimizedUrl(baseUrl, params) {
+ const lod = params.get('lod');
+ const textureSize = params.get('textureSize');
+ const morphs = params.get('morphs');
+ const draco = params.get('draco');
+ if (!lod && !textureSize && !morphs && draco !== '1') return baseUrl;
+ const u = new URL('/api/avatar/optimize', location.origin);
+ u.searchParams.set('src', baseUrl);
+ if (lod) u.searchParams.set('lod', lod);
+ if (textureSize) u.searchParams.set('textureSize', textureSize);
+ if (morphs) u.searchParams.set('morphs', morphs);
+ if (draco === '1') u.searchParams.set('draco', '1');
+ return u.toString();
+}
+
+// ── Background ──────────────────────────────────────────────────────────────
+
+function applyBackground(mode) {
+ document.body.classList.remove('bg-dark', 'bg-light');
+ if (mode === 'dark') document.body.classList.add('bg-dark');
+ else if (mode === 'light') document.body.classList.add('bg-light');
+}
+
+// ── Phoneme-heuristic lipsync (no audio analyser available) ─────────────────
+
+function startTextLipsync(text, root, mouthTarget) {
+ // Drive the mouth from a coarse phoneme heuristic synced to total
+ // utterance duration. This is the fallback path when browser TTS doesn't
+ // expose a MediaStream we can analyse. Updates the AvatarMouthTarget
+ // shape (open/wide/round) rather than going through canonical morphs so
+ // it lives alongside the audio-driven LipsyncDriver path.
+ if (!text) return { stop() {} };
+
+ // Approximate 110ms/syllable; collapse runs of vowels to syllable beats.
+ const syllables = String(text).toLowerCase().match(/[aeiouy]+/g) || [];
+ const durMs = Math.max(600, syllables.length * 110);
+ const start = performance.now();
+ let raf = 0;
+ let stopped = false;
+
+ const tick = () => {
+ if (stopped) return;
+ const t = performance.now() - start;
+ if (t >= durMs) {
+ try {
+ mouthTarget.setMouthShape({ open: 0, wide: 0, round: 0 });
+ } catch {}
+ stopped = true;
+ return;
+ }
+ // Position within current syllable [0,1).
+ const sylIdx = Math.min(syllables.length - 1, Math.floor((t / durMs) * syllables.length));
+ const local = (t / durMs) * syllables.length - sylIdx;
+ // Triangular envelope: open at midpoint, closed at the edges.
+ const env = local < 0.5 ? local * 2 : (1 - local) * 2;
+ const v = syllables[sylIdx] || '';
+ const shape =
+ /[oö]/.test(v) ? { open: env * 0.55, wide: 0, round: env * 0.9 } :
+ /[u]/.test(v) ? { open: env * 0.35, wide: 0, round: env * 0.95 } :
+ /[i]/.test(v) ? { open: env * 0.35, wide: env * 0.7, round: 0 } :
+ /[e]/.test(v) ? { open: env * 0.45, wide: env * 0.55, round: 0 } :
+ /* a / fallback */ { open: env * 0.75, wide: env * 0.2, round: 0 };
+ try {
+ mouthTarget.setMouthShape(shape);
+ } catch {}
+ raf = requestAnimationFrame(tick);
+ };
+ raf = requestAnimationFrame(tick);
+
+ return {
+ stop() {
+ stopped = true;
+ if (raf) cancelAnimationFrame(raf);
+ try {
+ mouthTarget.setMouthShape({ open: 0, wide: 0, round: 0 });
+ } catch {}
+ },
+ };
+}
+
+// ── Head pose extraction (YXZ Tait-Bryan) ──────────────────────────────────
+
+function decodeYawPitchRoll(m) {
+ const r02 = m[2], r12 = m[6], r22 = m[10], r10 = m[4], r11 = m[5];
+ const pitch = Math.asin(Math.max(-1, Math.min(1, -r12)));
+ let yaw, roll;
+ if (Math.abs(r12) < 0.9999) {
+ yaw = Math.atan2(r02, r22);
+ roll = Math.atan2(r10, r11);
+ } else {
+ yaw = Math.atan2(-m[8], m[0]);
+ roll = 0;
+ }
+ return { yaw, pitch, roll };
+}
+
+// ── Error ───────────────────────────────────────────────────────────────────
+
+function showError(msg) {
+ const el = document.getElementById('error');
+ if (!el) return;
+ el.textContent = msg;
+ el.style.display = 'flex';
+}
diff --git a/src/avatar-export.js b/src/avatar-export.js
new file mode 100644
index 000000000..6c7cf4bc6
--- /dev/null
+++ b/src/avatar-export.js
@@ -0,0 +1,503 @@
+/**
+ * Unified avatar export — GLB, USDZ, and VRM 1.0.
+ *
+ * Single source of truth for "give the user their avatar as a file". The three
+ * paths share a common loader+sanitizer so a GLB exported as VRM and then
+ * re-exported as USDZ stays self-consistent.
+ *
+ * downloadAvatar(blobOrUrl, { format, filename, meta })
+ *
+ * Format support matrix:
+ * - 'glb' → original bytes if Blob, fetched bytes if URL. No re-encode.
+ * - 'usdz' → Three.js USDZExporter via ./usdz-pipeline.js. Coerces unlit
+ * materials to MeshStandardMaterial so Quick Look accepts them.
+ * - 'vrm' → GLTFExporter + in-place injection of the VRMC_vrm 1.0
+ * extension (humanoid bones, ARKit-52 expression presets, meta).
+ * No third-party exporter package — pixiv/three-vrm doesn't ship
+ * one, and VRM 1.0 is just glTF 2.0 + a root extension.
+ *
+ * Mapping rules are conservative: we only emit human bones we can identify
+ * with high confidence (Mixamo / VRM-native / RPM / CC bone naming) and only
+ * emit expression presets whose source ARKit morph actually exists on the
+ * mesh. Better to ship a small valid VRM than a large invalid one.
+ */
+
+import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
+import { GLTFExporter } from 'three/addons/exporters/GLTFExporter.js';
+import { glbBlobToUsdzBlob } from './usdz-pipeline.js';
+
+const TEXT_DECODER = new TextDecoder();
+const TEXT_ENCODER = new TextEncoder();
+const GLB_MAGIC = 0x46546c67; // 'glTF' little-endian
+const GLB_JSON_CHUNK = 0x4e4f534a; // 'JSON'
+const GLB_BIN_CHUNK = 0x004e4942; // 'BIN\0'
+
+/* ────────────────────────────────────────────────────────────────────────── *
+ * Public API
+ * ────────────────────────────────────────────────────────────────────────── */
+
+/**
+ * Build an export Blob from a source GLB (Blob or URL) in the requested format.
+ *
+ * @param {Blob|string} source — staged Blob or remote GLB URL
+ * @param {object} opts
+ * @param {'glb'|'usdz'|'vrm'} opts.format
+ * @param {object} [opts.meta] — for VRM: { name, version, authors[], licenseUrl, ... }
+ * @returns {Promise<{ blob: Blob, mime: string, ext: string }>}
+ */
+export async function exportAvatar(source, { format, meta } = {}) {
+ const glbBlob = await coerceGlbBlob(source);
+ switch (format) {
+ case 'glb':
+ return { blob: glbBlob, mime: 'model/gltf-binary', ext: 'glb' };
+ case 'usdz': {
+ const blob = await glbBlobToUsdzBlob(glbBlob);
+ return { blob, mime: 'model/vnd.usdz+zip', ext: 'usdz' };
+ }
+ case 'vrm': {
+ const blob = await glbBlobToVrmBlob(glbBlob, meta || {});
+ return { blob, mime: 'model/gltf-binary', ext: 'vrm' };
+ }
+ default:
+ throw new Error(`exportAvatar: unsupported format "${format}"`);
+ }
+}
+
+/**
+ * Convenience: export, save to disk, return descriptor. Triggers a browser
+ * download of the result with the supplied filename (sans extension — we add
+ * the right one per format).
+ */
+export async function downloadAvatar(source, { format, filename = 'avatar', meta } = {}) {
+ const { blob, ext } = await exportAvatar(source, { format, meta });
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement('a');
+ a.href = url;
+ a.download = `${sanitizeFilename(filename)}.${ext}`;
+ document.body.appendChild(a);
+ a.click();
+ a.remove();
+ setTimeout(() => URL.revokeObjectURL(url), 1500);
+ return { size: blob.size, format, filename: a.download };
+}
+
+/* ────────────────────────────────────────────────────────────────────────── *
+ * GLB Blob loader
+ * ────────────────────────────────────────────────────────────────────────── */
+
+async function coerceGlbBlob(source) {
+ if (source instanceof Blob) return source;
+ if (typeof source !== 'string' || !source) {
+ throw new Error('avatar-export: source must be a Blob or URL string');
+ }
+ const res = await fetch(source, { credentials: 'omit' });
+ if (!res.ok) throw new Error(`avatar-export: fetch ${source} → ${res.status}`);
+ return await res.blob();
+}
+
+function sanitizeFilename(name) {
+ return String(name || 'avatar')
+ .replace(/[^a-z0-9._-]+/gi, '-')
+ .replace(/-+/g, '-')
+ .replace(/^-|-$/g, '')
+ .slice(0, 80)
+ || 'avatar';
+}
+
+/* ────────────────────────────────────────────────────────────────────────── *
+ * VRM 1.0 exporter
+ *
+ * VRM 1.0 is glTF 2.0 + the VRMC_vrm root extension. The shortest valid
+ * exporter is therefore: (1) re-export the loaded scene as GLB with
+ * GLTFExporter, (2) decode the JSON chunk, (3) inject VRMC_vrm with
+ * humanoid + expressions + meta, (4) re-encode the GLB. We do not bother
+ * with springbones, lookAt-bone targets, or constraints — those are
+ * optional in the spec and require runtime state that doesn't survive an
+ * export pass cleanly. A consuming runtime that wants physics can re-apply
+ * its own springbones on top.
+ * ────────────────────────────────────────────────────────────────────────── */
+
+async function glbBlobToVrmBlob(glbBlob, meta) {
+ const gltf = await loadGlb(glbBlob);
+ const scene = gltf.scene || gltf.scenes?.[0];
+ if (!scene) throw new Error('vrm: glb contained no scene');
+
+ const skinnedMesh = findRepresentativeSkinnedMesh(scene);
+ const skeleton = skinnedMesh?.skeleton || null;
+ if (!skeleton) {
+ throw new Error('vrm: source has no skeleton — cannot map to humanoid');
+ }
+
+ // Build a map of mesh → morph target dictionary so we can look up morphs
+ // for expression bindings even before the GLB is re-exported.
+ const morphLookup = collectMorphTargets(scene);
+
+ // 1. Re-export with GLTFExporter to get a clean GLB byte stream.
+ const exporter = new GLTFExporter();
+ const rawArrayBuffer = await new Promise((resolve, reject) => {
+ exporter.parse(
+ scene,
+ (out) => resolve(out),
+ (err) => reject(err),
+ { binary: true, embedImages: true, animations: gltf.animations || [] },
+ );
+ });
+
+ // 2. Parse the GLB so we can inject VRMC_vrm into the JSON chunk.
+ const glb = decodeGlb(new Uint8Array(rawArrayBuffer));
+ const jsonText = TEXT_DECODER.decode(glb.json);
+ const json = JSON.parse(jsonText);
+
+ // 3. Build the VRMC_vrm payload from the in-memory scene. We index back
+ // into json.nodes by name — GLTFExporter preserves node names so this
+ // is stable.
+ const nodeIndexByName = new Map();
+ (json.nodes || []).forEach((n, idx) => {
+ if (n.name) nodeIndexByName.set(n.name, idx);
+ });
+
+ const humanBones = buildHumanBones(skeleton, nodeIndexByName);
+ if (Object.keys(humanBones).length < 8) {
+ throw new Error(
+ `vrm: only matched ${Object.keys(humanBones).length} humanoid bones — need at least Hips/Spine/Head/arms+legs`,
+ );
+ }
+
+ const expressions = buildExpressionsFromArkit(morphLookup, json, nodeIndexByName);
+
+ const vrmExt = {
+ specVersion: '1.0',
+ meta: {
+ name: meta.name || 'three.ws avatar',
+ version: meta.version || '1',
+ authors: Array.isArray(meta.authors) && meta.authors.length ? meta.authors : ['three.ws user'],
+ copyrightInformation: meta.copyrightInformation || '',
+ contactInformation: meta.contactInformation || '',
+ references: meta.references || [],
+ thirdPartyLicenses: meta.thirdPartyLicenses || '',
+ thumbnailImage: undefined, // optional; we don't bake one in
+ licenseUrl: meta.licenseUrl || 'https://vrm.dev/licenses/1.0/index.html',
+ avatarPermission: meta.avatarPermission || 'everyone',
+ allowExcessivelyViolentUsage: meta.allowExcessivelyViolentUsage ?? false,
+ allowExcessivelySexualUsage: meta.allowExcessivelySexualUsage ?? false,
+ commercialUsage: meta.commercialUsage || 'personalNonProfit',
+ allowPoliticalOrReligiousUsage: meta.allowPoliticalOrReligiousUsage ?? false,
+ allowAntisocialOrHateUsage: meta.allowAntisocialOrHateUsage ?? false,
+ creditNotation: meta.creditNotation || 'required',
+ allowRedistribution: meta.allowRedistribution ?? false,
+ modification: meta.modification || 'prohibited',
+ otherLicenseUrl: meta.otherLicenseUrl || '',
+ },
+ humanoid: { humanBones },
+ expressions,
+ lookAt: { type: 'bone', offsetFromHeadBone: [0, 0.06, 0] },
+ firstPerson: { meshAnnotations: [] },
+ };
+
+ // Strip undefined optionals — VRM consumers (UniVRM, three-vrm) tolerate
+ // missing keys but trip on explicit nulls.
+ pruneUndefined(vrmExt.meta);
+
+ json.extensionsUsed = Array.from(new Set([...(json.extensionsUsed || []), 'VRMC_vrm']));
+ json.extensions = { ...(json.extensions || {}), VRMC_vrm: vrmExt };
+
+ // 4. Re-encode GLB.
+ const rebuiltJson = TEXT_ENCODER.encode(JSON.stringify(json));
+ return new Blob([encodeGlb(rebuiltJson, glb.bin)], { type: 'model/gltf-binary' });
+}
+
+/* ────────────────────────────────────────────────────────────────────────── *
+ * Humanoid bone mapping
+ *
+ * Accepts Mixamo (mixamorig:Hips), VRM-native (Hips, J_Bip_C_Hips), Ready
+ * Player Me (Hips, Spine, Neck), CC4 (CC_Base_Hip), and Unity-export naming.
+ * The matcher strips common prefixes/suffixes, normalizes left/right markers,
+ * and routes to canonical VRM names.
+ * ────────────────────────────────────────────────────────────────────────── */
+
+const VRM_BONE_TARGETS = [
+ 'hips', 'spine', 'chest', 'upperChest', 'neck', 'head',
+ 'leftEye', 'rightEye', 'jaw',
+ 'leftShoulder', 'leftUpperArm', 'leftLowerArm', 'leftHand',
+ 'rightShoulder', 'rightUpperArm', 'rightLowerArm', 'rightHand',
+ 'leftUpperLeg', 'leftLowerLeg', 'leftFoot', 'leftToes',
+ 'rightUpperLeg', 'rightLowerLeg', 'rightFoot', 'rightToes',
+ 'leftThumbMetacarpal', 'leftThumbProximal', 'leftThumbDistal',
+ 'leftIndexProximal', 'leftIndexIntermediate', 'leftIndexDistal',
+ 'leftMiddleProximal', 'leftMiddleIntermediate', 'leftMiddleDistal',
+ 'leftRingProximal', 'leftRingIntermediate', 'leftRingDistal',
+ 'leftLittleProximal', 'leftLittleIntermediate', 'leftLittleDistal',
+ 'rightThumbMetacarpal', 'rightThumbProximal', 'rightThumbDistal',
+ 'rightIndexProximal', 'rightIndexIntermediate', 'rightIndexDistal',
+ 'rightMiddleProximal', 'rightMiddleIntermediate', 'rightMiddleDistal',
+ 'rightRingProximal', 'rightRingIntermediate', 'rightRingDistal',
+ 'rightLittleProximal', 'rightLittleIntermediate', 'rightLittleDistal',
+];
+
+function normalizeBoneName(raw) {
+ return String(raw || '')
+ .toLowerCase()
+ .replace(/^mixamorig:?_?/, '')
+ .replace(/^cc_base_/, '')
+ .replace(/^armature[:_|]/, '')
+ .replace(/^j_bip_[clr]_/, '')
+ .replace(/^rig[:_]/, '')
+ .replace(/^bip01_?/, '')
+ .replace(/[._\-\s]/g, '');
+}
+
+function classifyBone(rawName) {
+ const n = normalizeBoneName(rawName);
+ const isLeft = /(^|[^a-z])l(?![a-z])|left/.test(n);
+ const isRight = /(^|[^a-z])r(?![a-z])|right/.test(n);
+ const stripped = n.replace(/^(l|left|r|right)/, '').replace(/(l|r)$/, '');
+
+ if (n === 'hips' || n === 'hip' || n === 'pelvis') return 'hips';
+ if (n === 'spine' || n === 'spine1') return 'spine';
+ if (n === 'spine2' || n === 'chest') return 'chest';
+ if (n === 'spine3' || n === 'upperchest') return 'upperChest';
+ if (n === 'neck') return 'neck';
+ if (n === 'head') return 'head';
+ if (n === 'jaw') return 'jaw';
+ if (/eye/.test(n) && isLeft) return 'leftEye';
+ if (/eye/.test(n) && isRight) return 'rightEye';
+
+ const sideKey = (base) => (isLeft ? 'left' : isRight ? 'right' : null) + base;
+
+ if (/shoulder|clavicle/.test(stripped)) return sideKey('Shoulder');
+ if (/upperarm|^arm$/.test(stripped)) return sideKey('UpperArm');
+ if (/lowerarm|forearm/.test(stripped)) return sideKey('LowerArm');
+ if (/^hand$/.test(stripped) || /^hand[0-9]?$/.test(n)) return sideKey('Hand');
+
+ if (/upleg|upperleg|thigh/.test(stripped)) return sideKey('UpperLeg');
+ if (/lowerleg|^leg$|calf|shin/.test(stripped)) return sideKey('LowerLeg');
+ if (/^foot$|ankle/.test(stripped)) return sideKey('Foot');
+ if (/toe(?!nail)|toebase/.test(stripped)) return sideKey('Toes');
+
+ const fingerMatch = stripped.match(/(thumb|index|middle|ring|little|pinky)([0-9])?/);
+ if (fingerMatch) {
+ const finger = fingerMatch[1] === 'pinky' ? 'Little' : capitalize(fingerMatch[1]);
+ const segment = fingerMatch[2] || '1';
+ const segmentName =
+ segment === '1' ? (finger === 'Thumb' ? 'Metacarpal' : 'Proximal') :
+ segment === '2' ? (finger === 'Thumb' ? 'Proximal' : 'Intermediate') :
+ (finger === 'Thumb' ? 'Distal' : 'Distal');
+ const side = isLeft ? 'left' : isRight ? 'right' : null;
+ if (side) return `${side}${finger}${segmentName}`;
+ }
+
+ return null;
+}
+
+function capitalize(s) {
+ return s ? s[0].toUpperCase() + s.slice(1) : s;
+}
+
+function buildHumanBones(skeleton, nodeIndexByName) {
+ const out = {};
+ const seen = new Set();
+ for (const bone of skeleton.bones || []) {
+ const vrmName = classifyBone(bone.name);
+ if (!vrmName || !VRM_BONE_TARGETS.includes(vrmName) || seen.has(vrmName)) continue;
+ const idx = nodeIndexByName.get(bone.name);
+ if (idx == null) continue;
+ out[vrmName] = { node: idx };
+ seen.add(vrmName);
+ }
+ return out;
+}
+
+function findRepresentativeSkinnedMesh(scene) {
+ let best = null;
+ let bestCount = 0;
+ scene.traverse((obj) => {
+ if (!obj.isSkinnedMesh || !obj.skeleton?.bones?.length) return;
+ const c = obj.skeleton.bones.length;
+ if (c > bestCount) {
+ best = obj;
+ bestCount = c;
+ }
+ });
+ return best;
+}
+
+/* ────────────────────────────────────────────────────────────────────────── *
+ * ARKit-52 → VRM expression preset binding
+ *
+ * VRM 1.0 preset names: aa, ih, ou, ee, oh, blink, blinkLeft, blinkRight,
+ * happy, angry, sad, relaxed, surprised, neutral, lookUp, lookDown, lookLeft,
+ * lookRight. Each preset has morphTargetBinds[] referencing { node, index, weight }.
+ *
+ * We bind by *finding* the morph target name on any mesh in json.meshes and
+ * recording (node-of-that-mesh, index-of-that-morph, weight=1.0). If the
+ * source morph is missing, the preset is omitted entirely.
+ * ────────────────────────────────────────────────────────────────────────── */
+
+const ARKIT_TO_VRM_PRESETS = [
+ // Visemes (Oculus → VRM)
+ { preset: 'aa', sources: [{ morph: 'viseme_aa', w: 1 }, { morph: 'jawOpen', w: 0.7 }, { morph: 'mouthFunnel', w: -0.3 }] },
+ { preset: 'ih', sources: [{ morph: 'viseme_I', w: 1 }, { morph: 'mouthSmileLeft', w: 0.3 }, { morph: 'mouthSmileRight', w: 0.3 }] },
+ { preset: 'ou', sources: [{ morph: 'viseme_U', w: 1 }, { morph: 'mouthPucker', w: 0.6 }] },
+ { preset: 'ee', sources: [{ morph: 'viseme_E', w: 1 }, { morph: 'mouthStretchLeft', w: 0.4 }, { morph: 'mouthStretchRight', w: 0.4 }] },
+ { preset: 'oh', sources: [{ morph: 'viseme_O', w: 1 }, { morph: 'mouthFunnel', w: 0.6 }] },
+
+ // Blinks
+ { preset: 'blink', sources: [{ morph: 'eyeBlinkLeft', w: 1 }, { morph: 'eyeBlinkRight', w: 1 }] },
+ { preset: 'blinkLeft', sources: [{ morph: 'eyeBlinkLeft', w: 1 }] },
+ { preset: 'blinkRight', sources: [{ morph: 'eyeBlinkRight', w: 1 }] },
+
+ // Emotions
+ { preset: 'happy', sources: [{ morph: 'mouthSmileLeft', w: 1 }, { morph: 'mouthSmileRight', w: 1 }, { morph: 'cheekSquintLeft', w: 0.5 }, { morph: 'cheekSquintRight', w: 0.5 }, { morph: 'eyeSquintLeft', w: 0.4 }, { morph: 'eyeSquintRight', w: 0.4 }] },
+ { preset: 'angry', sources: [{ morph: 'browDownLeft', w: 1 }, { morph: 'browDownRight', w: 1 }, { morph: 'mouthPressLeft', w: 0.6 }, { morph: 'mouthPressRight', w: 0.6 }, { morph: 'noseSneerLeft', w: 0.3 }, { morph: 'noseSneerRight', w: 0.3 }] },
+ { preset: 'sad', sources: [{ morph: 'mouthFrownLeft', w: 1 }, { morph: 'mouthFrownRight', w: 1 }, { morph: 'browInnerUp', w: 0.7 }, { morph: 'mouthShrugLower', w: 0.4 }] },
+ { preset: 'relaxed', sources: [{ morph: 'mouthSmileLeft', w: 0.3 }, { morph: 'mouthSmileRight', w: 0.3 }] },
+ { preset: 'surprised', sources: [{ morph: 'eyeWideLeft', w: 1 }, { morph: 'eyeWideRight', w: 1 }, { morph: 'browInnerUp', w: 0.8 }, { morph: 'browOuterUpLeft', w: 0.8 }, { morph: 'browOuterUpRight', w: 0.8 }, { morph: 'jawOpen', w: 0.5 }] },
+
+ // Look direction (handled by lookAt expression, optional duplicate of eye bones)
+ { preset: 'lookUp', sources: [{ morph: 'eyeLookUpLeft', w: 1 }, { morph: 'eyeLookUpRight', w: 1 }] },
+ { preset: 'lookDown', sources: [{ morph: 'eyeLookDownLeft', w: 1 }, { morph: 'eyeLookDownRight', w: 1 }] },
+ { preset: 'lookLeft', sources: [{ morph: 'eyeLookOutLeft', w: 1 }, { morph: 'eyeLookInRight', w: 1 }] },
+ { preset: 'lookRight', sources: [{ morph: 'eyeLookInLeft', w: 1 }, { morph: 'eyeLookOutRight', w: 1 }] },
+];
+
+/**
+ * Walk every mesh in the scene and record `{ meshName: { morphName: index } }`.
+ * This runs against the live Three.js scene before re-export, so we use the
+ * actual mesh.userData / mesh.morphTargetDictionary.
+ */
+function collectMorphTargets(scene) {
+ const out = new Map(); // meshName → { morphName → index }
+ scene.traverse((obj) => {
+ if (!obj.isMesh || !obj.morphTargetDictionary) return;
+ out.set(obj.name, obj.morphTargetDictionary);
+ });
+ return out;
+}
+
+/**
+ * Resolve the (gltf-node-index, mesh-primitive-morph-index) for a morph name.
+ * GLTFExporter writes meshes back to json.meshes, each primitive carrying
+ * `targets` whose order matches morphTargetDictionary index. Node→mesh is in
+ * json.nodes[i].mesh. Mesh extras.targetNames carries the morph names.
+ */
+function resolveMorphBinding(morphName, json) {
+ const meshes = json.meshes || [];
+ for (let meshIdx = 0; meshIdx < meshes.length; meshIdx++) {
+ const mesh = meshes[meshIdx];
+ const targetNames = mesh.extras?.targetNames;
+ if (!Array.isArray(targetNames)) continue;
+ const morphIdx = targetNames.indexOf(morphName);
+ if (morphIdx < 0) continue;
+ // Find the node that points at this mesh.
+ const nodes = json.nodes || [];
+ for (let nodeIdx = 0; nodeIdx < nodes.length; nodeIdx++) {
+ if (nodes[nodeIdx].mesh === meshIdx) {
+ return { node: nodeIdx, index: morphIdx };
+ }
+ }
+ }
+ return null;
+}
+
+function buildExpressionsFromArkit(_morphLookup, json, _nodeIndexByName) {
+ const preset = {};
+ for (const def of ARKIT_TO_VRM_PRESETS) {
+ const binds = [];
+ for (const src of def.sources) {
+ const found = resolveMorphBinding(src.morph, json);
+ if (!found) continue;
+ binds.push({ node: found.node, index: found.index, weight: src.w });
+ }
+ if (!binds.length) continue;
+ preset[def.preset] = {
+ morphTargetBinds: binds,
+ isBinary: false,
+ overrideBlink: 'none',
+ overrideLookAt: 'none',
+ overrideMouth: 'none',
+ };
+ }
+ return { preset };
+}
+
+/* ────────────────────────────────────────────────────────────────────────── *
+ * GLB encode / decode helpers
+ *
+ * Minimal binary glTF reader/writer. We only need to extract+rewrite the JSON
+ * chunk; the BIN chunk is passed through unmodified.
+ * ────────────────────────────────────────────────────────────────────────── */
+
+function decodeGlb(bytes) {
+ const dv = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
+ if (dv.getUint32(0, true) !== GLB_MAGIC) throw new Error('glb: bad magic');
+ if (dv.getUint32(4, true) !== 2) throw new Error('glb: unsupported version');
+ let offset = 12;
+ let json = null;
+ let bin = new Uint8Array(0);
+ while (offset < bytes.length) {
+ const chunkLen = dv.getUint32(offset, true);
+ const chunkType = dv.getUint32(offset + 4, true);
+ const chunkStart = offset + 8;
+ const chunkData = bytes.subarray(chunkStart, chunkStart + chunkLen);
+ if (chunkType === GLB_JSON_CHUNK) json = chunkData;
+ else if (chunkType === GLB_BIN_CHUNK) bin = chunkData;
+ offset = chunkStart + chunkLen;
+ }
+ if (!json) throw new Error('glb: missing JSON chunk');
+ return { json, bin };
+}
+
+function padTo4(arr, padByte) {
+ const remainder = arr.byteLength % 4;
+ if (remainder === 0) return arr;
+ const padded = new Uint8Array(arr.byteLength + (4 - remainder));
+ padded.set(arr, 0);
+ padded.fill(padByte, arr.byteLength);
+ return padded;
+}
+
+function encodeGlb(jsonBytes, binBytes) {
+ const jsonChunk = padTo4(jsonBytes, 0x20); // space-pad JSON per spec
+ const binChunk = binBytes.byteLength ? padTo4(binBytes, 0x00) : new Uint8Array(0);
+ const headerLen = 12;
+ const jsonHeaderLen = 8;
+ const binHeaderLen = binChunk.byteLength ? 8 : 0;
+ const totalLen = headerLen + jsonHeaderLen + jsonChunk.byteLength + binHeaderLen + binChunk.byteLength;
+
+ const out = new Uint8Array(totalLen);
+ const dv = new DataView(out.buffer);
+ dv.setUint32(0, GLB_MAGIC, true);
+ dv.setUint32(4, 2, true);
+ dv.setUint32(8, totalLen, true);
+
+ dv.setUint32(12, jsonChunk.byteLength, true);
+ dv.setUint32(16, GLB_JSON_CHUNK, true);
+ out.set(jsonChunk, 20);
+
+ if (binChunk.byteLength) {
+ const binOffset = 20 + jsonChunk.byteLength;
+ dv.setUint32(binOffset, binChunk.byteLength, true);
+ dv.setUint32(binOffset + 4, GLB_BIN_CHUNK, true);
+ out.set(binChunk, binOffset + 8);
+ }
+
+ return out;
+}
+
+/* ────────────────────────────────────────────────────────────────────────── *
+ * GLB loader (shared with USDZ pipeline)
+ * ────────────────────────────────────────────────────────────────────────── */
+
+async function loadGlb(blob) {
+ const loader = new GLTFLoader();
+ const buf = await blob.arrayBuffer();
+ return new Promise((resolve, reject) => {
+ loader.parse(buf, '', resolve, reject);
+ });
+}
+
+function pruneUndefined(obj) {
+ for (const k of Object.keys(obj)) {
+ if (obj[k] === undefined) delete obj[k];
+ }
+}
diff --git a/src/avatar-page.js b/src/avatar-page.js
index 0e80694fb..fbd517d89 100644
--- a/src/avatar-page.js
+++ b/src/avatar-page.js
@@ -8,6 +8,7 @@
*/
import { openTalkMode } from './voice/talk-mode.js';
+import { downloadAvatar } from './avatar-export.js';
const ATTACHED_KEY_PREFIX = 'avatar_attached_v1:';
@@ -233,7 +234,7 @@ function renderShell(glbUrl) {
<div class="av-cta-row">
<button class="av-cta" id="av-use">Start an agent</button>
<a class="av-cta-sec" href="/studio?avatar=${encodeURIComponent(avatar.id || avatarId)}" title="Use this avatar in Widget Studio">Open in Studio</a>
- <a class="av-cta-sec" href="${esc(glbUrl)}" download>Download GLB</a>
+ <button class="av-cta-sec" id="av-download" type="button">Download ▾</button>
</div>
<nav class="av-tabs" role="tablist">
<button class="av-tab active" data-tab="overview" role="tab">Overview</button>
@@ -303,6 +304,134 @@ function renderShell(glbUrl) {
$('av-use')?.addEventListener('click', startAgentWithAvatar);
$('av-talk')?.addEventListener('click', () => enterTalkMode());
+ $('av-download')?.addEventListener('click', openDownloadMenu);
+}
+
+/**
+ * Anchored download menu. GLB / USDZ links straight to the R2-hosted artifacts
+ * when present (no client work) and falls back to a fetched-and-converted blob
+ * when only the canonical GLB is available. VRM is always built client-side.
+ */
+function openDownloadMenu(ev) {
+ closeDownloadMenu();
+ const trigger = ev.currentTarget;
+ const glbUrl = avatar.model_url || avatar.url;
+ const usdzUrl = avatar.usdz_url || null;
+ const fileBase = sanitizeFilename(avatar.name || 'avatar');
+
+ const menu = document.createElement('div');
+ menu.className = 'av-download-menu';
+ menu.id = 'av-download-menu';
+ menu.setAttribute('role', 'menu');
+ menu.innerHTML = `
+ <button type="button" role="menuitem" data-format="glb">
+ <strong>GLB</strong>
+ <span>Universal — game engines, Blender, browsers</span>
+ </button>
+ <button type="button" role="menuitem" data-format="vrm">
+ <strong>VRM</strong>
+ <span>VRChat, Resonite, Hubs, VTube Studio</span>
+ </button>
+ <button type="button" role="menuitem" data-format="usdz">
+ <strong>USDZ</strong>
+ <span>iOS AR — Safari Quick Look</span>
+ </button>
+ <div class="av-download-status" data-status></div>
+ `;
+ document.body.appendChild(menu);
+ positionMenu(menu, trigger);
+
+ const statusEl = menu.querySelector('[data-status]');
+ menu.querySelectorAll('button[data-format]').forEach((btn) => {
+ btn.addEventListener('click', async () => {
+ const format = btn.dataset.format;
+ if (menu.dataset.busy === '1') return;
+ menu.dataset.busy = '1';
+ statusEl.textContent = `Preparing ${format.toUpperCase()}…`;
+ statusEl.dataset.tone = 'busy';
+
+ try {
+ // Fast paths: GLB and USDZ already exist on R2 for saved avatars.
+ if (format === 'glb' && glbUrl) {
+ triggerLink(glbUrl, `${fileBase}.glb`);
+ statusEl.textContent = 'Download started.';
+ statusEl.dataset.tone = 'ok';
+ } else if (format === 'usdz' && usdzUrl) {
+ triggerLink(usdzUrl, `${fileBase}.usdz`);
+ statusEl.textContent = 'Download started.';
+ statusEl.dataset.tone = 'ok';
+ } else {
+ // Build client-side from the GLB.
+ if (!glbUrl) throw new Error('No source GLB to convert.');
+ const result = await downloadAvatar(glbUrl, {
+ format,
+ filename: fileBase,
+ meta: { name: avatar.name || 'three.ws avatar' },
+ });
+ statusEl.textContent = `Saved · ${prettyBytes(result.size)}`;
+ statusEl.dataset.tone = 'ok';
+ }
+ setTimeout(closeDownloadMenu, 1500);
+ } catch (err) {
+ console.error('[avatar] download failed', err);
+ statusEl.textContent =
+ format === 'vrm' && /humanoid/i.test(err?.message || '')
+ ? "VRM needs a humanoid skeleton — try GLB."
+ : `Couldn't export: ${err?.message || 'unknown error'}`;
+ statusEl.dataset.tone = 'err';
+ } finally {
+ menu.dataset.busy = '0';
+ }
+ });
+ });
+
+ setTimeout(() => {
+ document.addEventListener('click', onOutsideDownloadClick, { once: true });
+ }, 0);
+}
+
+function onOutsideDownloadClick(ev) {
+ const menu = document.getElementById('av-download-menu');
+ if (!menu) return;
+ if (menu.contains(ev.target) || ev.target.id === 'av-download') return;
+ closeDownloadMenu();
+}
+
+function closeDownloadMenu() {
+ document.getElementById('av-download-menu')?.remove();
+ document.removeEventListener('click', onOutsideDownloadClick);
+}
+
+function positionMenu(menu, trigger) {
+ const r = trigger.getBoundingClientRect();
+ const top = r.bottom + 6 + window.scrollY;
+ const left = Math.max(8, r.right - 280 + window.scrollX);
+ menu.style.top = `${top}px`;
+ menu.style.left = `${left}px`;
+}
+
+function triggerLink(href, filename) {
+ const a = document.createElement('a');
+ a.href = href;
+ a.download = filename;
+ a.rel = 'noopener';
+ document.body.appendChild(a);
+ a.click();
+ a.remove();
+}
+
+function sanitizeFilename(name) {
+ return String(name || 'avatar')
+ .replace(/[^a-z0-9._-]+/gi, '-')
+ .replace(/-+/g, '-')
+ .replace(/^-|-$/g, '')
+ .slice(0, 80) || 'avatar';
+}
+
+function prettyBytes(n) {
+ if (n < 1024) return `${n} B`;
+ if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;
+ return `${(n / 1024 / 1024).toFixed(2)} MB`;
}
function renderAttribution() {
diff --git a/src/create-review.js b/src/create-review.js
index effa15364..c2feb3e11 100644
--- a/src/create-review.js
+++ b/src/create-review.js
@@ -17,6 +17,15 @@ import { attachAvatarToAgent } from './attach-avatar-to-agent.js';
import { load as loadGuest, clear as clearGuest } from './guest-avatar.js';
import { TalkScene } from './voice/talk-scene.js';
import { IdleAnimation } from './idle-animation.js';
+import {
+ openDownloadModal,
+ openEmbedModal,
+ openIdentityModal,
+ openPaidSkillsModal,
+ openReputationModal,
+ openVoicePreview,
+ toggleEmoteStrip,
+} from './create-review-features.js';
const RESUME_KEY = '3dagent:guest-avatar-resume';
const $ = (sel) => document.querySelector(sel);
@@ -141,6 +150,45 @@ function wireControls() {
saveBtn.addEventListener('click', () => onSave());
startOverBtn.addEventListener('click', () => onStartOver());
+
+ wireFeatureTiles();
+}
+
+function wireFeatureTiles() {
+ document.querySelectorAll('.feature-tile[data-feature]').forEach((btn) => {
+ btn.addEventListener('click', () => handleFeatureClick(btn.dataset.feature));
+ });
+}
+
+function handleFeatureClick(feature) {
+ switch (feature) {
+ case 'body':
+ toggleEmoteStrip({ scene: viewerScene, stripEl: $('#emote-strip') });
+ return;
+ case 'voice':
+ if (!objectUrl) return;
+ openVoicePreview({ glbUrl: objectUrl, name: $('#f-name').value });
+ return;
+ case 'identity':
+ openIdentityModal();
+ return;
+ case 'paid':
+ openPaidSkillsModal();
+ return;
+ case 'embed':
+ openEmbedModal();
+ return;
+ case 'reputation':
+ openReputationModal();
+ return;
+ case 'download':
+ if (!staged?.blob) return;
+ openDownloadModal({
+ blob: staged.blob,
+ name: $('#f-name').value.trim() || staged.name,
+ });
+ return;
+ }
}
function applyAuthState({ detail }) {
@@ -177,7 +225,13 @@ async function onSave({ auto = false } = {}) {
saveBtn.disabled = true;
startOverBtn.disabled = true;
- showSaveOverlay('Saving your avatar…', 'Uploading to your account.');
+ showSaveOverlay('Preparing upload…', 'Optimizing your avatar.');
+
+ // Arm the resume sentinel before we touch the network. If the session
+ // expired between the cached auth hint and now, apiFetch redirects to
+ // /login synchronously — we need the sentinel already set so the post-
+ // login round-trip auto-resumes the save.
+ sessionStorage.setItem(RESUME_KEY, '1');
try {
const name = $('#f-name').value.trim() || staged.name;
@@ -185,28 +239,42 @@ async function onSave({ auto = false } = {}) {
...staged.meta,
name,
};
- const avatar = await saveRemoteGlbToAccount(staged.blob, meta);
- updateSaveOverlay('Preparing your agent…');
+ const avatar = await saveRemoteGlbToAccount(staged.blob, meta, {
+ onProgress: (pct) => {
+ updateSaveOverlay(
+ pct >= 100 ? 'Finishing upload…' : 'Uploading your avatar…',
+ pct >= 100 ? 'almost there' : `${pct}%`,
+ );
+ setSaveProgress(pct);
+ },
+ });
+ setSaveProgress(null);
+ updateSaveOverlay('Preparing your agent…', '');
const agent = await attachAvatarToAgent(avatar.id, name);
- updateSaveOverlay('Opening your avatar…');
+ updateSaveOverlay('Opening your avatar…', '');
await clearGuest();
releaseObjectUrl();
window.location.href = '/app?agent=' + agent.id;
} catch (err) {
- hideSaveOverlay();
- saveBtn.disabled = false;
- startOverBtn.disabled = false;
console.error('[create-review] save failed', err);
- if (err.code === 'not_signed_in') {
+ if (err.code === 'not_signed_in' || err.redirected) {
// Session expired between the cached auth hint and the actual save.
- sessionStorage.setItem(RESUME_KEY, '1');
+ // The resume sentinel is already armed — kick over to /login and the
+ // post-login round-trip will fire onSave() again automatically.
const next = encodeURIComponent('/create-review');
window.location.href = `/login?next=${next}`;
return;
}
+ // Disarm the sentinel — without this, a plain reload would auto-fire
+ // onSave again on the next visit and surprise the user.
+ sessionStorage.removeItem(RESUME_KEY);
+
if (err.data?.error === 'plan_limit_count') {
+ hideSaveOverlay();
+ saveBtn.disabled = false;
+ startOverBtn.disabled = false;
showStatus(
"You've reached your avatar limit. Delete an avatar first, then come back to save this one.",
'error',
@@ -214,13 +282,76 @@ async function onSave({ auto = false } = {}) {
return;
}
- showStatus(
- auto
- ? "Save couldn't finish automatically — try the button again."
- : err.message || 'Save failed. Try again.',
- 'error',
- );
+ // Flip the overlay into an inline retry surface. The blob is still in
+ // memory, so retry re-runs the whole pipeline (re-presign → fresh PUT
+ // → fresh commit) without losing any user state.
+ showSaveError({
+ title: saveErrorTitle(err),
+ detail: humanizeSaveError(err, auto),
+ onRetry: () => onSave({ auto: false }),
+ onCancel: () => {
+ hideSaveOverlay();
+ saveBtn.disabled = false;
+ startOverBtn.disabled = false;
+ },
+ });
+ }
+}
+
+function saveErrorTitle(err) {
+ switch (err.code) {
+ case 'upload_blocked':
+ return 'Upload blocked';
+ case 'upload_failed':
+ return 'Upload rejected';
+ case 'upload_aborted':
+ return 'Upload cancelled';
+ default:
+ if (err.stage === 'presign') return "Couldn't reserve upload";
+ if (err.stage === 'commit') return "Couldn't save record";
+ if (err.stage === 'fetch') return "Couldn't read source";
+ return "Save didn't finish";
+ }
+}
+
+function humanizeSaveError(err, auto) {
+ const status = err?.status;
+ const stage = err?.stage;
+ const code = err?.code;
+
+ if (code === 'upload_blocked') {
+ return "Couldn't reach storage. Check your network and try again.";
+ }
+ if (code === 'upload_failed') {
+ return 'Storage rejected the upload. Try again — if it keeps happening, the file may be too large.';
+ }
+ if (code === 'upload_aborted') {
+ return 'Upload was cancelled. Try again when you have a stable connection.';
+ }
+
+ if (status === 502 || status === 503 || status === 504) {
+ return "We couldn't reach the server. Try again in a moment.";
+ }
+ if (status === 413) {
+ return 'That avatar file is too large to save. Try a smaller GLB.';
+ }
+ if (status === 429) {
+ return 'Too many requests right now — wait a few seconds and try again.';
+ }
+
+ if (stage === 'fetch') {
+ return "Couldn't fetch the source model. Check the URL or try again.";
+ }
+ if (stage === 'commit') {
+ return 'Uploaded, but the record didn\'t save. Try again — it won\'t re-upload.';
+ }
+
+ const msg = err?.message || '';
+ if (err?.name === 'TypeError' || /Failed to fetch|NetworkError/i.test(msg)) {
+ return 'Network looks offline. Check your connection and try again.';
}
+ if (auto) return "Save couldn't finish automatically — try the button again.";
+ return 'Save failed. Try again, or refresh the page if it keeps happening.';
}
async function onStartOver() {
@@ -258,13 +389,22 @@ function showSaveOverlay(label, sublabel) {
<img src="/three.svg" alt="" />
<div class="label"></div>
<div class="sublabel"></div>
+ <div class="progress" hidden>
+ <div class="progress-bar"></div>
+ </div>
+ <div class="error-actions" hidden>
+ <button type="button" class="retry-btn">Retry</button>
+ <button type="button" class="cancel-btn">Cancel</button>
+ </div>
`;
document.body.appendChild(el);
document.documentElement.style.overflow = 'hidden';
document.body.style.overflow = 'hidden';
}
+ el.removeAttribute('data-state');
el.querySelector('.label').textContent = label;
el.querySelector('.sublabel').textContent = sublabel || '';
+ el.querySelector('.error-actions').hidden = true;
}
function updateSaveOverlay(label, sublabel) {
@@ -274,6 +414,46 @@ function updateSaveOverlay(label, sublabel) {
if (sublabel !== undefined) el.querySelector('.sublabel').textContent = sublabel;
}
+// pct: integer 0..100 to show a real progress bar, or null to hide it (used
+// once the upload finishes and we move on to the commit / agent-attach hops).
+function setSaveProgress(pct) {
+ const el = document.getElementById('save-loading');
+ if (!el) return;
+ const wrap = el.querySelector('.progress');
+ const bar = el.querySelector('.progress-bar');
+ if (pct === null || pct === undefined) {
+ wrap.hidden = true;
+ bar.style.width = '0%';
+ return;
+ }
+ wrap.hidden = false;
+ bar.style.width = `${Math.max(0, Math.min(100, pct))}%`;
+}
+
+// Reuses the existing fullscreen overlay as an error surface so the page
+// background stays dim and the user can't accidentally double-trigger the
+// save button underneath. Cancel restores the editing UI; Retry re-runs
+// onSave with the staged blob still in memory.
+function showSaveError({ title, detail, onRetry, onCancel }) {
+ const el = document.getElementById('save-loading');
+ if (!el) return;
+ el.setAttribute('data-state', 'error');
+ el.querySelector('.label').textContent = title;
+ el.querySelector('.sublabel').textContent = detail || '';
+ el.querySelector('.progress').hidden = true;
+ const actions = el.querySelector('.error-actions');
+ actions.hidden = false;
+ const retryBtn = actions.querySelector('.retry-btn');
+ const cancelBtn = actions.querySelector('.cancel-btn');
+ // Replace nodes to drop any previous click handler from earlier failures.
+ const freshRetry = retryBtn.cloneNode(true);
+ const freshCancel = cancelBtn.cloneNode(true);
+ retryBtn.replaceWith(freshRetry);
+ cancelBtn.replaceWith(freshCancel);
+ freshRetry.addEventListener('click', onRetry, { once: true });
+ freshCancel.addEventListener('click', onCancel, { once: true });
+}
+
function hideSaveOverlay() {
const el = document.getElementById('save-loading');
if (!el) return;
diff --git a/src/dashboard/dashboard.js b/src/dashboard/dashboard.js
index 9cccf4fbf..c8c2439c9 100644
--- a/src/dashboard/dashboard.js
+++ b/src/dashboard/dashboard.js
@@ -8,12 +8,15 @@ export const state = { user: null };
function visibilityOptionsHtml(currentValue) {
const opts = [
- { v: 'public', label: 'Public (discoverable)' },
+ { v: 'public', label: 'Public (discoverable)' },
{ v: 'unlisted', label: 'Unlisted (anyone with link)' },
- { v: 'private', label: 'Private (only you)' },
+ { v: 'private', label: 'Private (only you)' },
];
return opts
- .map((o) => `<option value="${o.v}"${currentValue === o.v ? ' selected' : ''}>${o.label}</option>`)
+ .map(
+ (o) =>
+ `<option value="${o.v}"${currentValue === o.v ? ' selected' : ''}>${o.label}</option>`,
+ )
.join('');
}
@@ -37,6 +40,19 @@ export const api = {
deleteWidget: (id) => j('DELETE', `/api/widgets/${encodeURIComponent(id)}`),
duplicateWidget: (id) => j('POST', `/api/widgets/${encodeURIComponent(id)}/duplicate`),
widgetStats: (id) => j('GET', `/api/widgets/${encodeURIComponent(id)}/stats`),
+ listTranscripts: (id, params = {}) => {
+ const qs = new URLSearchParams();
+ if (params.limit) qs.set('limit', String(params.limit));
+ if (params.before) qs.set('before', params.before);
+ const q = qs.toString();
+ return j('GET', `/api/widgets/${encodeURIComponent(id)}/transcripts${q ? `?${q}` : ''}`);
+ },
+ getTranscript: (id, threadId) =>
+ j(
+ 'GET',
+ `/api/widgets/${encodeURIComponent(id)}/transcripts?thread_id=${encodeURIComponent(threadId)}`,
+ ),
+ listKnowledge: (id) => j('GET', `/api/widgets/${encodeURIComponent(id)}/knowledge`),
createAvatarSession: (id) => j('POST', `/api/avatars/${id}/session`),
getAvatarVersions: (id) => j('GET', `/api/avatars/${id}/versions`),
patchAgent: (agentId, patch) => j('PUT', `/api/agents/${agentId}`, patch),
@@ -247,12 +263,28 @@ const tabs = {
// On-chain agents discovered from linked wallets live at /my-agents.
const AGENT_CHAIN_NAMES = {
- 1: 'Ethereum', 10: 'Optimism', 56: 'BNB Chain', 97: 'BSC Testnet',
- 100: 'Gnosis', 137: 'Polygon', 250: 'Fantom', 324: 'zkSync Era',
- 1284: 'Moonbeam', 5000: 'Mantle', 8453: 'Base', 42161: 'Arbitrum',
- 42220: 'Celo', 43113: 'Avalanche Fuji', 43114: 'Avalanche', 59144: 'Linea',
- 80002: 'Polygon Amoy', 84532: 'Base Sepolia', 421614: 'Arb Sepolia',
- 534352: 'Scroll', 11155111: 'Sepolia', 11155420: 'OP Sepolia',
+ 1: 'Ethereum',
+ 10: 'Optimism',
+ 56: 'BNB Chain',
+ 97: 'BSC Testnet',
+ 100: 'Gnosis',
+ 137: 'Polygon',
+ 250: 'Fantom',
+ 324: 'zkSync Era',
+ 1284: 'Moonbeam',
+ 5000: 'Mantle',
+ 8453: 'Base',
+ 42161: 'Arbitrum',
+ 42220: 'Celo',
+ 43113: 'Avalanche Fuji',
+ 43114: 'Avalanche',
+ 59144: 'Linea',
+ 80002: 'Polygon Amoy',
+ 84532: 'Base Sepolia',
+ 421614: 'Arb Sepolia',
+ 534352: 'Scroll',
+ 11155111: 'Sepolia',
+ 11155420: 'OP Sepolia',
};
function agentChainName(id) {
@@ -277,7 +309,9 @@ async function renderAgents(root) {
const createHost = root.querySelector('#agents-create-host');
list.innerHTML = '<div class="muted">Loading…</div>';
- root.querySelector('#agents-new').addEventListener('click', () => openCreateForm(createHost, list));
+ root.querySelector('#agents-new').addEventListener('click', () =>
+ openCreateForm(createHost, list),
+ );
let agents = [];
try {
@@ -294,7 +328,8 @@ async function renderAgents(root) {
return;
}
- for (const a of agents) list.appendChild(agentCard(a, () => maybeRenderEmpty(list, createHost)));
+ for (const a of agents)
+ list.appendChild(agentCard(a, () => maybeRenderEmpty(list, createHost)));
}
function renderAgentsEmpty(list, createHost) {
@@ -310,7 +345,9 @@ function renderAgentsEmpty(list, createHost) {
<a href="/my-agents" class="btn-primary" style="background:#222230; color:#ddd;">Import from wallet</a>
</div>
</div>`;
- list.querySelector('#agents-empty-new').addEventListener('click', () => openCreateForm(createHost, list));
+ list.querySelector('#agents-empty-new').addEventListener('click', () =>
+ openCreateForm(createHost, list),
+ );
}
function maybeRenderEmpty(list, createHost) {
@@ -325,11 +362,15 @@ function agentCard(a, onRemoved) {
? `<span class="tag" title="Registered on-chain (ERC-8004)" style="background:rgba(106,92,255,0.18); color:#cfc6ff;">on-chain${a.chain_id ? ' · ' + esc(agentChainName(a.chain_id)) : ''}</span>`
: `<span class="tag" title="Not yet registered on-chain">off-chain</span>`;
const skillCount = (a.skills || []).length;
- const wallet = a.wallet_address ? `${a.wallet_address.slice(0, 6)}…${a.wallet_address.slice(-4)}` : '';
+ const wallet = a.wallet_address
+ ? `${a.wallet_address.slice(0, 6)}…${a.wallet_address.slice(-4)}`
+ : '';
const agentIdEnc = encodeURIComponent(a.id);
const hasAvatar = Boolean(a.avatar_id);
- const embedDisabledAttr = hasAvatar ? '' : 'disabled title="Link an avatar (Edit → Avatar) to enable embed"';
+ const embedDisabledAttr = hasAvatar
+ ? ''
+ : 'disabled title="Link an avatar (Edit → Avatar) to enable embed"';
const token = a.token || a.meta?.token || null;
const tokenBadge = token?.mint
? `<span class="tag" title="${attr(token.mint)}" style="background:rgba(120,200,140,0.18); color:#c6f0d6;">$${esc(token.symbol || 'TOKEN')}</span>`
@@ -363,9 +404,11 @@ function agentCard(a, onRemoved) {
<a class="btn sec" href="/agent/${agentIdEnc}/edit" title="Edit name, persona, avatar, skills">Edit</a>
<button class="btn sec" data-share type="button" title="Copy public agent link">Share</button>
<button class="btn sec" data-embed type="button" ${embedDisabledAttr}>Embed</button>
- ${token?.mint
- ? `<a class="btn sec" href="/dashboard/tokens?agent=${agentIdEnc}" title="Open pump.fun token dashboard">Token ↗</a>`
- : `<button class="btn sec" data-launch type="button" title="Launch a pump.fun token for this agent">🚀 Launch token</button>`}
+ ${
+ token?.mint
+ ? `<a class="btn sec" href="/dashboard/tokens?agent=${agentIdEnc}" title="Open pump.fun token dashboard">Token ↗</a>`
+ : `<button class="btn sec" data-launch type="button" title="Launch a pump.fun token for this agent">🚀 Launch token</button>`
+ }
${a.is_registered ? '' : `<a class="btn sec" href="/deploy${a.avatar_id ? '?avatar=' + encodeURIComponent(a.avatar_id) : ''}" title="Mint as ERC-8004 agent">Deploy on-chain</a>`}
<div class="more-menu-wrap"><button class="btn sec" data-more type="button" aria-haspopup="menu" aria-expanded="false">More ▾</button></div>
</div>
@@ -486,7 +529,9 @@ async function duplicateAgent(a, sourceEl) {
const { agent } = await api.createAgent(payload);
const list = sourceEl.parentElement;
if (list) {
- const newCard = agentCard(agent, () => maybeRenderEmpty(list, list.previousElementSibling || list));
+ const newCard = agentCard(agent, () =>
+ maybeRenderEmpty(list, list.previousElementSibling || list),
+ );
sourceEl.insertAdjacentElement('afterend', newCard);
}
toast(`Created "${agent.name}"`);
@@ -581,7 +626,9 @@ function openCreateForm(host, listEl) {
</div>`;
const form = host.querySelector('#agents-create-form');
const errEl = host.querySelector('[data-err]');
- host.querySelector('[data-cancel]').addEventListener('click', () => { host.innerHTML = ''; });
+ host.querySelector('[data-cancel]').addEventListener('click', () => {
+ host.innerHTML = '';
+ });
form.addEventListener('submit', async (ev) => {
ev.preventDefault();
const fd = new FormData(form);
@@ -785,7 +832,9 @@ function avatarMoreItems(a, el) {
});
items.push({
label: 'Deploy on-chain',
- run: () => { location.href = `/deploy?avatar=${encodeURIComponent(a.id)}`; },
+ run: () => {
+ location.href = `/deploy?avatar=${encodeURIComponent(a.id)}`;
+ },
});
items.push({
label: 'Delete',
@@ -844,7 +893,8 @@ async function downloadAvatarGlb(a, btn) {
const resp = await fetch(url, { credentials: 'omit' });
if (!resp.ok) throw new Error(`Download failed (${resp.status})`);
const blob = await resp.blob();
- const safeName = (a.name || 'avatar').replace(/[^a-z0-9._-]+/gi, '_').slice(0, 80) || 'avatar';
+ const safeName =
+ (a.name || 'avatar').replace(/[^a-z0-9._-]+/gi, '_').slice(0, 80) || 'avatar';
const link = document.createElement('a');
const objectUrl = URL.createObjectURL(blob);
link.href = objectUrl;
@@ -952,9 +1002,10 @@ async function loadXPanel({ host, meterEl, bodyEl, avatar }) {
const quota = status.quota;
const remaining = Math.max(0, quota - used);
const tier = status.tier || 'free';
- const tierBadge = tier === 'pro'
- ? `<span style="background:rgba(106,92,255,0.15);color:#a78bfa;padding:2px 7px;border-radius:99px;font-size:10px;font-weight:600;margin-left:6px">PRO</span>`
- : `<a href="/pricing" style="background:rgba(255,184,77,0.15);color:#ffb84d;padding:2px 7px;border-radius:99px;font-size:10px;font-weight:600;margin-left:6px;text-decoration:none">FREE · upgrade</a>`;
+ const tierBadge =
+ tier === 'pro'
+ ? `<span style="background:rgba(106,92,255,0.15);color:#a78bfa;padding:2px 7px;border-radius:99px;font-size:10px;font-weight:600;margin-left:6px">PRO</span>`
+ : `<a href="/pricing" style="background:rgba(255,184,77,0.15);color:#ffb84d;padding:2px 7px;border-radius:99px;font-size:10px;font-weight:600;margin-left:6px;text-decoration:none">FREE · upgrade</a>`;
meterEl.innerHTML = `@${esc(status.username)} ${tierBadge} <span style="color:${remaining === 0 ? '#ffb3b3' : '#9a8cff'};margin-left:6px">${used}/${quota}</span>`;
bodyEl.innerHTML = `
@@ -1008,19 +1059,28 @@ async function loadXPanel({ host, meterEl, bodyEl, avatar }) {
const threadEl = bodyEl.querySelector('[data-x-thread]');
const linkEl = bodyEl.querySelector('[data-x-link]');
- const setMsg = (text, color = '#9a8cff') => { msgEl.style.color = color; msgEl.innerHTML = text; };
- textEl.addEventListener('input', () => { countEl.textContent = textEl.value.length; });
+ const setMsg = (text, color = '#9a8cff') => {
+ msgEl.style.color = color;
+ msgEl.innerHTML = text;
+ };
+ textEl.addEventListener('input', () => {
+ countEl.textContent = textEl.value.length;
+ });
function readThreadParts() {
const raw = textEl.value;
if (!threadEl.checked) return null;
- return raw.split(/\n---+\n|\n\n\n+/).map((s) => s.trim()).filter(Boolean);
+ return raw
+ .split(/\n---+\n|\n\n\n+/)
+ .map((s) => s.trim())
+ .filter(Boolean);
}
async function generateDrafts(count) {
try {
const r = await fetch('/api/x/draft', {
- method: 'POST', credentials: 'include',
+ method: 'POST',
+ credentials: 'include',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({
agent_id: avatar.agent_id || avatar.id,
@@ -1040,7 +1100,10 @@ async function loadXPanel({ host, meterEl, bodyEl, avatar }) {
}
function renderDrafts(drafts) {
- if (!drafts || !drafts.length) { draftsEl.innerHTML = ''; return; }
+ if (!drafts || !drafts.length) {
+ draftsEl.innerHTML = '';
+ return;
+ }
if (drafts.length === 1) {
const d = drafts[0];
if (d.thread_parts) textEl.value = d.thread_parts.join('\n\n\n');
@@ -1052,10 +1115,12 @@ async function loadXPanel({ host, meterEl, bodyEl, avatar }) {
}
draftsEl.innerHTML = `
<div class="muted" style="font-size:11px;text-transform:uppercase;letter-spacing:0.07em;margin-bottom:6px">Pick one</div>
- ${drafts.map((d, i) => {
- const display = d.thread_parts ? d.thread_parts.join('\n\n— —\n\n') : d.text;
- return `<div data-draft-idx="${i}" style="padding:10px 12px;background:#0f0f17;border:1px solid #22222e;border-radius:8px;margin-bottom:6px;cursor:pointer;font-size:13px;color:#ccc;white-space:pre-wrap">${esc(display)}</div>`;
- }).join('')}
+ ${drafts
+ .map((d, i) => {
+ const display = d.thread_parts ? d.thread_parts.join('\n\n— —\n\n') : d.text;
+ return `<div data-draft-idx="${i}" style="padding:10px 12px;background:#0f0f17;border:1px solid #22222e;border-radius:8px;margin-bottom:6px;cursor:pointer;font-size:13px;color:#ccc;white-space:pre-wrap">${esc(display)}</div>`;
+ })
+ .join('')}
`;
draftsEl.querySelectorAll('[data-draft-idx]').forEach((el) => {
el.addEventListener('click', () => {
@@ -1090,23 +1155,34 @@ async function loadXPanel({ host, meterEl, bodyEl, avatar }) {
setMsg('Posting…');
try {
const parts = readThreadParts();
- const body = parts && parts.length > 1
- ? { thread_parts: parts, agent_id: avatar.agent_id || avatar.id, append_link: linkEl.checked }
- : { text, agent_id: avatar.agent_id || avatar.id, append_link: linkEl.checked };
+ const body =
+ parts && parts.length > 1
+ ? {
+ thread_parts: parts,
+ agent_id: avatar.agent_id || avatar.id,
+ append_link: linkEl.checked,
+ }
+ : { text, agent_id: avatar.agent_id || avatar.id, append_link: linkEl.checked };
const r = await fetch('/api/x/post', {
- method: 'POST', credentials: 'include',
+ method: 'POST',
+ credentials: 'include',
headers: { 'content-type': 'application/json' },
body: JSON.stringify(body),
});
const data = await r.json();
if (!r.ok) {
if (data.upgrade_url) {
- setMsg(`${data.error_description} <a href="${data.upgrade_url}">Upgrade to Pro</a>`, '#ffb3b3');
+ setMsg(
+ `${data.error_description} <a href="${data.upgrade_url}">Upgrade to Pro</a>`,
+ '#ffb3b3',
+ );
return;
}
throw new Error(data.error_description || 'post failed');
}
- setMsg(`Posted: <a href="${data.url}" target="_blank" rel="noopener">${data.url}</a>${data.thread ? ` (${data.thread.length}-tweet thread)` : ''}`);
+ setMsg(
+ `Posted: <a href="${data.url}" target="_blank" rel="noopener">${data.url}</a>${data.thread ? ` (${data.thread.length}-tweet thread)` : ''}`,
+ );
textEl.value = '';
countEl.textContent = 0;
loadXPanel({ host, meterEl, bodyEl, avatar });
@@ -1120,16 +1196,24 @@ async function loadXPanel({ host, meterEl, bodyEl, avatar }) {
scheduleBtn.addEventListener('click', async () => {
const text = textEl.value.trim();
if (!text) return setMsg('Write something first.', '#ffb3b3');
- const input = prompt('Schedule for (any date — e.g. "tomorrow 9am" or "2026-05-14T15:00"):', new Date(Date.now() + 3600_000).toISOString().slice(0, 16));
+ const input = prompt(
+ 'Schedule for (any date — e.g. "tomorrow 9am" or "2026-05-14T15:00"):',
+ new Date(Date.now() + 3600_000).toISOString().slice(0, 16),
+ );
if (!input) return;
const when = new Date(input);
if (isNaN(when.getTime())) return setMsg('Could not parse that date.', '#ffb3b3');
setMsg('Scheduling…');
try {
const r = await fetch('/api/x/schedule', {
- method: 'POST', credentials: 'include',
+ method: 'POST',
+ credentials: 'include',
headers: { 'content-type': 'application/json' },
- body: JSON.stringify({ text, scheduled_at: when.toISOString(), agent_id: avatar.agent_id || avatar.id }),
+ body: JSON.stringify({
+ text,
+ scheduled_at: when.toISOString(),
+ agent_id: avatar.agent_id || avatar.id,
+ }),
});
const data = await r.json();
if (!r.ok) throw new Error(data.error_description || 'schedule failed');
@@ -1163,10 +1247,15 @@ async function loadXReviews(host) {
try {
const r = await fetch('/api/x/reviews', { credentials: 'include' });
const reviews = (await r.json()).reviews || [];
- if (!reviews.length) { host.innerHTML = ''; return; }
+ if (!reviews.length) {
+ host.innerHTML = '';
+ return;
+ }
host.innerHTML = `
<div class="muted" style="font-size:11px;text-transform:uppercase;letter-spacing:0.07em;margin-bottom:6px;color:#ffb84d">⚠ ${reviews.length} draft${reviews.length === 1 ? '' : 's'} awaiting your review</div>
- ${reviews.map((r) => `
+ ${reviews
+ .map(
+ (r) => `
<div style="padding:10px 12px;background:#1a1408;border:1px solid #3a2a14;border-radius:8px;margin-bottom:6px">
<div style="color:#ccc;font-size:13px;white-space:pre-wrap">${esc(r.text)}</div>
<div class="row" style="gap:6px;margin-top:8px">
@@ -1175,25 +1264,35 @@ async function loadXReviews(host) {
<span class="muted" style="font-size:11px;margin-left:auto">${new Date(r.created_at).toLocaleString()}</span>
</div>
</div>
- `).join('')}
+ `,
+ )
+ .join('')}
`;
host.querySelectorAll('[data-approve]').forEach((btn) => {
btn.addEventListener('click', async () => {
const id = btn.getAttribute('data-approve');
btn.disabled = true;
const r = await fetch(`/api/x/reviews?id=${encodeURIComponent(id)}`, {
- method: 'PATCH', credentials: 'include',
+ method: 'PATCH',
+ credentials: 'include',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ action: 'approve', append_link: true }),
});
- if (!r.ok) { alert((await r.json()).error_description || 'approve failed'); btn.disabled = false; return; }
+ if (!r.ok) {
+ alert((await r.json()).error_description || 'approve failed');
+ btn.disabled = false;
+ return;
+ }
loadXReviews(host);
});
});
host.querySelectorAll('[data-reject]').forEach((btn) => {
btn.addEventListener('click', async () => {
const id = btn.getAttribute('data-reject');
- await fetch(`/api/x/reviews?id=${encodeURIComponent(id)}`, { method: 'DELETE', credentials: 'include' });
+ await fetch(`/api/x/reviews?id=${encodeURIComponent(id)}`, {
+ method: 'DELETE',
+ credentials: 'include',
+ });
loadXReviews(host);
});
});
@@ -1203,10 +1302,16 @@ async function loadXReviews(host) {
async function loadXAnalytics(host, avatar) {
if (!host) return;
try {
- const r = await fetch(`/api/x/analytics?agent_id=${encodeURIComponent(avatar.agent_id || avatar.id)}`, { credentials: 'include' });
+ const r = await fetch(
+ `/api/x/analytics?agent_id=${encodeURIComponent(avatar.agent_id || avatar.id)}`,
+ { credentials: 'include' },
+ );
const data = await r.json();
const t = data.totals || {};
- if (!t.posts) { host.innerHTML = ''; return; }
+ if (!t.posts) {
+ host.innerHTML = '';
+ return;
+ }
host.innerHTML = `
<div class="muted" style="font-size:11px;text-transform:uppercase;letter-spacing:0.07em;margin-bottom:6px">Engagement (last 50 posts)</div>
<div class="row" style="gap:14px;flex-wrap:wrap;font-size:12px;color:#ccc">
@@ -1251,9 +1356,11 @@ async function loadXTriggers(host, avatar) {
const dailyHour = byKind.daily_persona?.config?.hour_utc ?? 13;
const dailyTopic = byKind.daily_persona?.config?.topic ?? '';
- const weeklyDay = byKind.weekly_digest?.config?.day_of_week ?? 0;
+ const weeklyDay = byKind.weekly_digest?.config?.day_of_week ?? 0;
const weeklyHour = byKind.weekly_digest?.config?.hour_utc ?? 16;
- const priceThresholds = (byKind.price_milestone?.config?.thresholds_usd ?? [10000, 50000, 100000, 500000, 1000000]).join(', ');
+ const priceThresholds = (
+ byKind.price_milestone?.config?.thresholds_usd ?? [10000, 50000, 100000, 500000, 1000000]
+ ).join(', ');
const paymentMin = byKind.payment_received?.config?.min_amount_usd ?? 1;
const anyReviewMode = triggers.some((t) => t.auto_publish === false);
@@ -1263,37 +1370,64 @@ async function loadXTriggers(host, avatar) {
<div class="muted" style="font-size:11px;text-transform:uppercase;letter-spacing:0.07em">Auto-post triggers</div>
<label class="muted" style="font-size:11px"><input type="checkbox" data-trig-review-all ${anyReviewMode ? 'checked' : ''} style="width:auto;display:inline-block;margin-right:4px;vertical-align:middle"> Review before publish</label>
</div>
- ${row('daily_persona', 'Daily in-character post',
+ ${row(
+ 'daily_persona',
+ 'Daily in-character post',
'Agent tweets once a day at your chosen UTC hour, in voice.',
`<label style="font-size:12px;color:#888">UTC hour <input type="number" min="0" max="23" data-trig-input="daily_persona.hour_utc" value="${dailyHour}" style="width:60px;display:inline-block;margin-left:6px"></label>
- <label style="font-size:12px;color:#888;display:block;margin-top:6px">Topic hint (optional) <input type="text" data-trig-input="daily_persona.topic" value="${attr(dailyTopic)}" placeholder="What should I talk about?" style="width:100%;display:block;margin-top:4px"></label>`)}
- ${row('weekly_digest', 'Weekly digest',
+ <label style="font-size:12px;color:#888;display:block;margin-top:6px">Topic hint (optional) <input type="text" data-trig-input="daily_persona.topic" value="${attr(dailyTopic)}" placeholder="What should I talk about?" style="width:100%;display:block;margin-top:4px"></label>`,
+ )}
+ ${row(
+ 'weekly_digest',
+ 'Weekly digest',
'Once-a-week recap including token activity if linked.',
`<label style="font-size:12px;color:#888">Day <select data-trig-input="weekly_digest.day_of_week" style="width:auto;display:inline-block;margin-left:6px">
- ${['Sun','Mon','Tue','Wed','Thu','Fri','Sat'].map((d,i)=>`<option value="${i}" ${i===weeklyDay?'selected':''}>${d}</option>`).join('')}
+ ${['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'].map((d, i) => `<option value="${i}" ${i === weeklyDay ? 'selected' : ''}>${d}</option>`).join('')}
</select></label>
- <label style="font-size:12px;color:#888;margin-left:10px">UTC hour <input type="number" min="0" max="23" data-trig-input="weekly_digest.hour_utc" value="${weeklyHour}" style="width:60px;display:inline-block;margin-left:6px"></label>`)}
- ${row('price_milestone', 'Token market-cap milestones',
+ <label style="font-size:12px;color:#888;margin-left:10px">UTC hour <input type="number" min="0" max="23" data-trig-input="weekly_digest.hour_utc" value="${weeklyHour}" style="width:60px;display:inline-block;margin-left:6px"></label>`,
+ )}
+ ${row(
+ 'price_milestone',
+ 'Token market-cap milestones',
'Auto-tweets when your pump.fun token crosses each threshold.',
- `<label style="font-size:12px;color:#888;display:block">USD thresholds (comma-separated) <input type="text" data-trig-input="price_milestone.thresholds_usd" value="${attr(priceThresholds)}" style="width:100%;display:block;margin-top:4px"></label>`)}
- ${row('payment_received', 'Thank-you on every payment',
+ `<label style="font-size:12px;color:#888;display:block">USD thresholds (comma-separated) <input type="text" data-trig-input="price_milestone.thresholds_usd" value="${attr(priceThresholds)}" style="width:100%;display:block;margin-top:4px"></label>`,
+ )}
+ ${row(
+ 'payment_received',
+ 'Thank-you on every payment',
'Tweets a thank-you when a user pays your agent for a skill.',
- `<label style="font-size:12px;color:#888">Minimum amount (USD) <input type="number" min="0" step="0.01" data-trig-input="payment_received.min_amount_usd" value="${paymentMin}" style="width:80px;display:inline-block;margin-left:6px"></label>`)}
+ `<label style="font-size:12px;color:#888">Minimum amount (USD) <input type="number" min="0" step="0.01" data-trig-input="payment_received.min_amount_usd" value="${paymentMin}" style="width:80px;display:inline-block;margin-left:6px"></label>`,
+ )}
<div data-trig-msg style="margin-top:8px;font-size:12px"></div>
`;
const trigMsg = host.querySelector('[data-trig-msg]');
- const setTrigMsg = (text, color = '#9a8cff') => { trigMsg.style.color = color; trigMsg.textContent = text; };
+ const setTrigMsg = (text, color = '#9a8cff') => {
+ trigMsg.style.color = color;
+ trigMsg.textContent = text;
+ };
function readConfigFromUI(kind) {
const get = (k) => host.querySelector(`[data-trig-input="${kind}.${k}"]`)?.value;
- if (kind === 'daily_persona') return { hour_utc: parseInt(get('hour_utc') || '0', 10), topic: (get('topic') || '').trim() || undefined };
- if (kind === 'weekly_digest') return { day_of_week: parseInt(get('day_of_week') || '0', 10), hour_utc: parseInt(get('hour_utc') || '0', 10) };
+ if (kind === 'daily_persona')
+ return {
+ hour_utc: parseInt(get('hour_utc') || '0', 10),
+ topic: (get('topic') || '').trim() || undefined,
+ };
+ if (kind === 'weekly_digest')
+ return {
+ day_of_week: parseInt(get('day_of_week') || '0', 10),
+ hour_utc: parseInt(get('hour_utc') || '0', 10),
+ };
if (kind === 'price_milestone') {
- const list = (get('thresholds_usd') || '').split(',').map((s) => parseFloat(s.trim())).filter((n) => Number.isFinite(n) && n > 0);
+ const list = (get('thresholds_usd') || '')
+ .split(',')
+ .map((s) => parseFloat(s.trim()))
+ .filter((n) => Number.isFinite(n) && n > 0);
return { thresholds_usd: list };
}
- if (kind === 'payment_received') return { min_amount_usd: parseFloat(get('min_amount_usd') || '0') };
+ if (kind === 'payment_received')
+ return { min_amount_usd: parseFloat(get('min_amount_usd') || '0') };
return {};
}
@@ -1302,7 +1436,8 @@ async function loadXTriggers(host, avatar) {
const existing = byKind[kind];
if (existing) {
const r = await fetch(`/api/x/triggers?id=${encodeURIComponent(existing.id)}`, {
- method: 'PATCH', credentials: 'include',
+ method: 'PATCH',
+ credentials: 'include',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ enabled, config }),
});
@@ -1311,9 +1446,16 @@ async function loadXTriggers(host, avatar) {
} else {
const autoPublish = !host.querySelector('[data-trig-review-all]')?.checked;
const r = await fetch('/api/x/triggers', {
- method: 'POST', credentials: 'include',
+ method: 'POST',
+ credentials: 'include',
headers: { 'content-type': 'application/json' },
- body: JSON.stringify({ kind, config, enabled, agent_id: agentId, auto_publish: autoPublish }),
+ body: JSON.stringify({
+ kind,
+ config,
+ enabled,
+ agent_id: agentId,
+ auto_publish: autoPublish,
+ }),
});
if (!r.ok) throw new Error((await r.json()).error_description || 'create failed');
byKind[kind] = (await r.json()).trigger;
@@ -1328,7 +1470,8 @@ async function loadXTriggers(host, avatar) {
for (const id of ids) {
try {
const r = await fetch(`/api/x/triggers?id=${encodeURIComponent(id)}`, {
- method: 'PATCH', credentials: 'include',
+ method: 'PATCH',
+ credentials: 'include',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ auto_publish: autoPublish }),
});
@@ -1338,7 +1481,11 @@ async function loadXTriggers(host, avatar) {
}
} catch {}
}
- setTrigMsg(autoPublish ? 'Auto-publish enabled.' : 'New trigger drafts will require your review.');
+ setTrigMsg(
+ autoPublish
+ ? 'Auto-publish enabled.'
+ : 'New trigger drafts will require your review.',
+ );
});
}
@@ -1382,10 +1529,15 @@ async function loadScheduledPosts(host) {
const r = await fetch('/api/x/schedule', { credentials: 'include' });
const data = await r.json();
const pending = (data.posts || []).filter((p) => !p.posted_at && !p.error);
- if (!pending.length) { host.innerHTML = ''; return; }
+ if (!pending.length) {
+ host.innerHTML = '';
+ return;
+ }
host.innerHTML = `
<div class="muted" style="font-size:11px;text-transform:uppercase;letter-spacing:0.07em;margin-bottom:6px">Scheduled</div>
- ${pending.map((p) => `
+ ${pending
+ .map(
+ (p) => `
<div class="row" style="justify-content:space-between;padding:8px 10px;background:#0f0f17;border:1px solid #22222e;border-radius:8px;margin-bottom:6px;font-size:12px">
<div style="flex:1;min-width:0">
<div style="color:#ccc;white-space:nowrap;overflow:hidden;text-overflow:ellipsis">${esc(p.text)}</div>
@@ -1393,12 +1545,17 @@ async function loadScheduledPosts(host) {
</div>
<button class="btn sec" data-cancel="${attr(p.id)}" style="font-size:11px;padding:4px 8px">Cancel</button>
</div>
- `).join('')}
+ `,
+ )
+ .join('')}
`;
host.querySelectorAll('[data-cancel]').forEach((btn) => {
btn.addEventListener('click', async () => {
const id = btn.getAttribute('data-cancel');
- await fetch(`/api/x/schedule?id=${encodeURIComponent(id)}`, { method: 'DELETE', credentials: 'include' });
+ await fetch(`/api/x/schedule?id=${encodeURIComponent(id)}`, {
+ method: 'DELETE',
+ credentials: 'include',
+ });
loadScheduledPosts(host);
});
});
@@ -1542,8 +1699,8 @@ async function doReplaceUpload(a, file, warnEl, cardEl) {
say('Checking skeleton compatibility\u2026');
const originalBuf = await file.arrayBuffer();
let uploadBytes = originalBuf;
- let uploadSize = file.size;
- let uploadBlob = file;
+ let uploadSize = file.size;
+ let uploadBlob = file;
let retargetReport = null;
try {
@@ -1551,8 +1708,8 @@ async function doReplaceUpload(a, file, warnEl, cardEl) {
const result = canonicalizeGLBBones(originalBuf);
if (result.renamed > 0) {
uploadBytes = result.buffer;
- uploadSize = result.buffer.byteLength;
- uploadBlob = new Blob([result.buffer], { type: 'model/gltf-binary' });
+ uploadSize = result.buffer.byteLength;
+ uploadBlob = new Blob([result.buffer], { type: 'model/gltf-binary' });
retargetReport = { renamed: result.renamed, samples: result.samples };
}
} catch (err) {
@@ -1720,9 +1877,7 @@ function renderUpload(root) {
size_bytes: uploadSize,
content_type: 'model/gltf-binary',
source: 'upload',
- source_meta: retargetReport
- ? { retargeted_bones: retargetReport.renamed }
- : {},
+ source_meta: retargetReport ? { retargeted_bones: retargetReport.renamed } : {},
});
progress.innerHTML = `Uploaded! <a href="/dashboard/avatars">View</a>`;
goto('avatars');
@@ -2847,7 +3002,11 @@ async function renderMonetization(root) {
const body = root.querySelector('#mon-body');
const CURRENCIES = [
- { label: 'Solana USDC', mint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', chain: 'solana' },
+ {
+ label: 'Solana USDC',
+ mint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
+ chain: 'solana',
+ },
{ label: 'Base USDC', mint: '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913', chain: 'base' },
];
@@ -2865,7 +3024,9 @@ async function renderMonetization(root) {
agent = agentData.agent;
wallets = walletsRes.ok ? (await walletsRes.json()).wallets || [] : [];
- const pricesRes = await fetch(`/api/agents/${agent.id}/pricing`, { credentials: 'include' });
+ const pricesRes = await fetch(`/api/agents/${agent.id}/pricing`, {
+ credentials: 'include',
+ });
prices = pricesRes.ok ? (await pricesRes.json()).prices || [] : [];
} catch (e) {
body.innerHTML = `<div class="err">${esc(e.message || 'Failed to load monetization data')}</div>`;
@@ -2876,7 +3037,9 @@ async function renderMonetization(root) {
const skills = agent.skills || [];
const priceMap = {};
- prices.forEach((p) => { priceMap[p.skill] = p; });
+ prices.forEach((p) => {
+ priceMap[p.skill] = p;
+ });
const solWallet = wallets.find((w) => w.chain === 'solana');
const baseWallet = wallets.find((w) => w.chain === 'base' || w.chain === 'evm');
@@ -2990,7 +3153,12 @@ async function renderMonetization(root) {
method: 'PUT',
credentials: 'include',
headers: { 'content-type': 'application/json' },
- body: JSON.stringify({ currency_mint: currencyMint, chain, amount, is_active: isActive }),
+ body: JSON.stringify({
+ currency_mint: currencyMint,
+ chain,
+ amount,
+ is_active: isActive,
+ }),
},
);
if (!r.ok) {
@@ -3008,7 +3176,9 @@ async function renderMonetization(root) {
}
msg.style.color = '#9a8cff';
msg.textContent = 'Saved ✓';
- setTimeout(() => { msg.textContent = ''; }, 2000);
+ setTimeout(() => {
+ msg.textContent = '';
+ }, 2000);
} catch (e) {
msg.style.color = '#ffb3b3';
msg.textContent = e.message;
@@ -3072,7 +3242,9 @@ async function renderMonetization(root) {
}
msgEl.style.color = '#9a8cff';
msgEl.textContent = 'Saved ✓';
- setTimeout(() => { msgEl.textContent = ''; }, 2000);
+ setTimeout(() => {
+ msgEl.textContent = '';
+ }, 2000);
} catch (e) {
msgEl.style.color = '#ffb3b3';
msgEl.textContent = e.message;
@@ -3080,10 +3252,18 @@ async function renderMonetization(root) {
};
body.querySelector('#mon-sol-save').addEventListener('click', () =>
- saveWallet('solana', body.querySelector('#mon-sol-addr'), body.querySelector('#mon-sol-msg')),
+ saveWallet(
+ 'solana',
+ body.querySelector('#mon-sol-addr'),
+ body.querySelector('#mon-sol-msg'),
+ ),
);
body.querySelector('#mon-base-save').addEventListener('click', () =>
- saveWallet('base', body.querySelector('#mon-base-addr'), body.querySelector('#mon-base-msg')),
+ saveWallet(
+ 'base',
+ body.querySelector('#mon-base-addr'),
+ body.querySelector('#mon-base-msg'),
+ ),
);
}
@@ -3096,14 +3276,16 @@ async function renderSubscriptions(root) {
`;
const body = root.querySelector('#sub-body');
- const fmtDate = (d) => d ? new Date(d).toLocaleDateString() : '—';
+ const fmtDate = (d) => (d ? new Date(d).toLocaleDateString() : '—');
const fmtUsd = (n) => '$' + Number(n).toFixed(2);
let myId, plans, subs;
try {
myId = state.user?.id;
const [plansRes, subsRes] = await Promise.all([
- fetch(`/api/subscriptions/plans?creator_id=${encodeURIComponent(myId)}`, { credentials: 'include' }),
+ fetch(`/api/subscriptions/plans?creator_id=${encodeURIComponent(myId)}`, {
+ credentials: 'include',
+ }),
fetch('/api/subscriptions/mine', { credentials: 'include' }),
]);
plans = plansRes.ok ? (await plansRes.json()).plans || [] : [];
@@ -3131,7 +3313,9 @@ async function renderSubscriptions(root) {
`;
}
- const createForm = plans.length < 3 ? `
+ const createForm =
+ plans.length < 3
+ ? `
<div style="margin-top:16px;border-top:1px solid var(--border);padding-top:16px">
<h4 style="margin:0 0 12px;font-size:14px">New plan</h4>
<div style="display:flex;flex-direction:column;gap:8px;max-width:420px">
@@ -3148,12 +3332,14 @@ async function renderSubscriptions(root) {
<button id="sub-plan-create" class="btn">Create plan</button>
</div>
</div>
- ` : '<p class="muted" style="font-size:13px">Maximum 3 active plans reached.</p>';
+ `
+ : '<p class="muted" style="font-size:13px">Maximum 3 active plans reached.</p>';
// ── Subscriber view ───────────────────────────────────────────────────────
let subsHtml = '';
for (const s of subs) {
- const statusColor = s.status === 'active' ? '#4caf50' : s.status === 'past_due' ? '#e53935' : '#888';
+ const statusColor =
+ s.status === 'active' ? '#4caf50' : s.status === 'past_due' ? '#e53935' : '#888';
subsHtml += `
<div class="card" style="margin-bottom:10px">
<div class="row" style="gap:12px;align-items:flex-start">
@@ -3189,10 +3375,14 @@ async function renderSubscriptions(root) {
if (!confirm('Remove this plan?')) return;
btn.disabled = true;
const r = await fetch(`/api/subscriptions/plans/${btn.dataset.id}`, {
- method: 'DELETE', credentials: 'include',
+ method: 'DELETE',
+ credentials: 'include',
});
if (r.ok) renderSubscriptions(root);
- else { btn.disabled = false; alert('Failed to remove plan'); }
+ else {
+ btn.disabled = false;
+ alert('Failed to remove plan');
+ }
});
});
@@ -3202,10 +3392,14 @@ async function renderSubscriptions(root) {
if (!confirm('Cancel this subscription?')) return;
btn.disabled = true;
const r = await fetch(`/api/subscriptions/${btn.dataset.id}`, {
- method: 'DELETE', credentials: 'include',
+ method: 'DELETE',
+ credentials: 'include',
});
if (r.ok) renderSubscriptions(root);
- else { btn.disabled = false; alert('Failed to cancel subscription'); }
+ else {
+ btn.disabled = false;
+ alert('Failed to cancel subscription');
+ }
});
});
@@ -3217,10 +3411,19 @@ async function renderSubscriptions(root) {
const price = parseFloat(body.querySelector('#sub-plan-price').value);
const interval = body.querySelector('#sub-plan-interval').value;
const perksRaw = body.querySelector('#sub-plan-perks').value;
- const perks = perksRaw.split('\n').map((s) => s.trim()).filter(Boolean);
+ const perks = perksRaw
+ .split('\n')
+ .map((s) => s.trim())
+ .filter(Boolean);
const msg = body.querySelector('#sub-plan-msg');
- if (!name) { msg.textContent = 'Name required.'; return; }
- if (!price || price < 0.99) { msg.textContent = 'Price must be at least $0.99.'; return; }
+ if (!name) {
+ msg.textContent = 'Name required.';
+ return;
+ }
+ if (!price || price < 0.99) {
+ msg.textContent = 'Price must be at least $0.99.';
+ return;
+ }
createBtn.disabled = true;
msg.textContent = 'Creating…';
const r = await fetch('/api/subscriptions/plans', {
@@ -3229,8 +3432,9 @@ async function renderSubscriptions(root) {
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ name, price_usd: price, interval, perks }),
});
- if (r.ok) { renderSubscriptions(root); }
- else {
+ if (r.ok) {
+ renderSubscriptions(root);
+ } else {
const d = await r.json().catch(() => ({}));
msg.textContent = d.error_description || 'Failed to create plan';
createBtn.disabled = false;
@@ -3252,7 +3456,10 @@ async function renderBilling(root) {
const r = await fetch('/api/billing/summary', { credentials: 'include' });
if (r.ok) data = await r.json();
} catch {}
- if (!data) { body.innerHTML = '<div class="card muted">Could not load usage data.</div>'; return; }
+ if (!data) {
+ body.innerHTML = '<div class="card muted">Could not load usage data.</div>';
+ return;
+ }
const { plan, quotas, usage } = data;
function fmtBytes(n) {
if (n >= 1e9) return (n / 1e9).toFixed(1) + ' GB';
@@ -3304,15 +3511,20 @@ async function renderBilling(root) {
// ── Revenue dashboard ────────────────────────────────────────────────────────
function formatUSDC(lamports) {
- return (lamports / 1_000_000).toLocaleString('en-US', {
- minimumFractionDigits: 2,
- maximumFractionDigits: 2,
- }) + ' USDC';
+ return (
+ (lamports / 1_000_000).toLocaleString('en-US', {
+ minimumFractionDigits: 2,
+ maximumFractionDigits: 2,
+ }) + ' USDC'
+ );
}
function revenueBarChart(timeseries) {
- if (!timeseries.length) return '<div class="muted" style="text-align:center;padding:24px 0">No data for this period.</div>';
- const W = 600, H = 160, PAD = { top: 12, right: 8, bottom: 28, left: 8 };
+ if (!timeseries.length)
+ return '<div class="muted" style="text-align:center;padding:24px 0">No data for this period.</div>';
+ const W = 600,
+ H = 160,
+ PAD = { top: 12, right: 8, bottom: 28, left: 8 };
const max = Math.max(...timeseries.map((r) => r.net_total), 1);
const barW = Math.max(4, Math.floor((W - PAD.left - PAD.right) / timeseries.length) - 2);
const innerW = W - PAD.left - PAD.right;
@@ -3408,7 +3620,9 @@ async function renderRevenue(root) {
<h3 style="margin:0 0 12px">Daily earnings</h3>
${revenueBarChart(timeseries)}
</div>
- ${by_skill.length ? `
+ ${
+ by_skill.length
+ ? `
<div class="card">
<h3 style="margin:0 0 12px">Skill breakdown</h3>
<table style="width:100%;border-collapse:collapse">
@@ -3420,14 +3634,20 @@ async function renderRevenue(root) {
</tr>
</thead>
<tbody>
- ${by_skill.map((s) => `<tr style="border-bottom:1px solid var(--border)">
+ ${by_skill
+ .map(
+ (s) => `<tr style="border-bottom:1px solid var(--border)">
<td style="padding:8px">${esc(s.skill)}</td>
<td style="padding:8px;text-align:right;font-variant-numeric:tabular-nums">${esc(formatUSDC(s.net_total))}</td>
<td style="padding:8px;text-align:right">${esc(String(s.count))}</td>
- </tr>`).join('')}
+ </tr>`,
+ )
+ .join('')}
</tbody>
</table>
- </div>` : ''}
+ </div>`
+ : ''
+ }
`;
}
@@ -3799,7 +4019,9 @@ async function renderAccount(root) {
<input id="acct-username" value="${attr(user.username || '')}" maxlength="30" placeholder="e.g. nirholas" style="width:100%" autocomplete="off" spellcheck="false">
<span class="muted" style="font-size:11px;display:block;margin-top:4px">Letters, numbers, _ and - only. 3–30 characters.</span>
</label>
- ${profileUrl ? `
+ ${
+ profileUrl
+ ? `
<div style="margin-top:12px">
<p class="muted" style="font-size:11px;margin:0 0 4px">Your public profile</p>
<div class="row" style="gap:6px;align-items:center">
@@ -3807,7 +4029,9 @@ async function renderAccount(root) {
<button id="acct-copy" class="btn sec" type="button" style="flex-shrink:0;white-space:nowrap">Copy</button>
</div>
</div>
- ` : ''}
+ `
+ : ''
+ }
<div id="acct-msg" class="muted" style="margin-top:12px"></div>
<div class="row" style="gap:8px;margin-top:16px">
<button class="btn" type="submit">Save</button>
@@ -3996,7 +4220,7 @@ function widgetCard(w, ctx) {
card.className = 'widget-card card';
card.dataset.id = w.id;
- const previewSrc = `/app#widget=${encodeURIComponent(w.id)}&kiosk=true&preview=1`;
+ const previewSrc = `/widget#widget=${encodeURIComponent(w.id)}&kiosk=true&preview=1`;
const previewHtml = w.avatar
? `<iframe data-src="${attr(previewSrc)}" loading="lazy" tabindex="-1" title="Preview of ${attr(w.name || 'widget')}"></iframe>`
: `<div class="placeholder">Avatar unavailable.<br>Edit to pick a replacement.</div>`;
@@ -4170,7 +4394,7 @@ async function openWidgetDrawer(w, ctx) {
drawer.setAttribute('aria-label', `Widget details — ${w.name || 'untitled'}`);
drawer.tabIndex = -1;
- const previewSrc = `/app#widget=${encodeURIComponent(w.id)}&kiosk=true&preview=1`;
+ const previewSrc = `/widget#widget=${encodeURIComponent(w.id)}&kiosk=true&preview=1`;
const pageUrl = `${location.origin}/w/${encodeURIComponent(w.id)}`;
const iframeSnippet = makeIframeSnippet(w, pageUrl, 600, 600);
const scriptSnippet = `<script async src="${location.origin}/embed.js" data-widget="${esc(w.id)}"></script>`;
@@ -4188,6 +4412,22 @@ async function openWidgetDrawer(w, ctx) {
<span class="muted" style="margin-left:8px">${esc(w.is_public ? 'Public' : 'Private')} · updated ${timeAgo(w.updated_at)}</span>
</div>
<div id="stats-region" aria-live="polite"><div class="muted">Loading stats…</div></div>
+ ${
+ w.type === 'talking-agent'
+ ? `
+ <section id="transcripts-region" aria-label="Chat transcripts">
+ <h3 style="margin:18px 0 6px; font-size:13px; text-transform:uppercase; letter-spacing:0.06em; color:#aaa">Chat transcripts</h3>
+ <div id="transcripts-totals" class="muted" style="font-size:12px"></div>
+ <div id="transcripts-list" style="display:flex; flex-direction:column; gap:6px; margin-top:8px"></div>
+ <div id="transcripts-detail" hidden></div>
+ <div id="knowledge-region" style="margin-top:14px">
+ <h3 style="margin:0 0 6px; font-size:13px; text-transform:uppercase; letter-spacing:0.06em; color:#aaa">Knowledge</h3>
+ <div id="knowledge-summary" class="muted" style="font-size:12px">Loading…</div>
+ </div>
+ </section>
+ `
+ : ''
+ }
<details>
<summary>Embed code</summary>
<div style="display:flex; flex-direction:column; gap:10px; margin-top:8px">
@@ -4268,6 +4508,126 @@ async function openWidgetDrawer(w, ctx) {
drawer.querySelector('#stats-region').innerHTML =
`<div class="err">${esc(err.message || 'Failed to load stats')}</div>`;
}
+
+ // Transcripts + knowledge — only for talking-agent widgets.
+ if (w.type === 'talking-agent') {
+ loadTranscripts(drawer, w);
+ loadKnowledgeSummary(drawer, w);
+ }
+}
+
+async function loadTranscripts(drawer, w) {
+ const totalsEl = drawer.querySelector('#transcripts-totals');
+ const listEl = drawer.querySelector('#transcripts-list');
+ const detailEl = drawer.querySelector('#transcripts-detail');
+ if (!totalsEl || !listEl || !detailEl) return;
+
+ try {
+ const data = await api.listTranscripts(w.id, { limit: 25 });
+ const t = data.totals || {};
+ totalsEl.textContent = `${formatNum(t.threads || 0)} threads · ${formatNum(t.messages || 0)} messages · ${formatNum(t.unique_visitors || 0)} unique visitors`;
+
+ const threads = data.threads || [];
+ if (!threads.length) {
+ listEl.innerHTML =
+ '<div class="muted" style="font-size:12px">No conversations yet — visitors will appear here as they chat.</div>';
+ return;
+ }
+
+ listEl.innerHTML = threads.map((t) => renderThreadRow(t)).join('');
+ for (const row of listEl.querySelectorAll('[data-thread]')) {
+ row.addEventListener('click', () => openThread(drawer, w, row.dataset.thread));
+ }
+ } catch (err) {
+ listEl.innerHTML = `<div class="err">${esc(err.message || 'Failed to load transcripts')}</div>`;
+ }
+}
+
+function renderThreadRow(t) {
+ const preview = (t.preview || '').slice(0, 120);
+ const when = t.last_message_at ? timeAgo(t.last_message_at) : '';
+ const where = t.referer_host ? esc(t.referer_host) : '(direct)';
+ return `
+ <button class="transcript-row" data-thread="${attr(t.id)}" type="button"
+ style="all:unset; cursor:pointer; padding:8px 10px; border:1px solid var(--border); border-radius:8px; display:grid; grid-template-columns: 1fr auto; gap:8px; background:#0f0f17">
+ <div style="min-width:0">
+ <div style="font-size:12px; font-weight:600; color:#ccc">${esc(t.visitor_label || 'visitor')}<span class="muted" style="font-weight:400; margin-left:6px">· ${where}</span></div>
+ <div class="muted" style="font-size:12px; margin-top:2px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap">${esc(preview) || '(no message)'}</div>
+ </div>
+ <div class="muted" style="font-size:11px; align-self:center">${esc(when)}<br>${t.message_count || 0} msg</div>
+ </button>
+ `;
+}
+
+async function openThread(drawer, w, threadId) {
+ const detailEl = drawer.querySelector('#transcripts-detail');
+ if (!detailEl) return;
+ detailEl.hidden = false;
+ detailEl.innerHTML =
+ '<div class="muted" style="font-size:12px; padding:8px">Loading thread…</div>';
+ try {
+ const data = await api.getTranscript(w.id, threadId);
+ detailEl.innerHTML = `
+ <div style="margin-top:10px; padding:10px; background:#0f0f17; border:1px solid var(--border); border-radius:8px">
+ <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:8px">
+ <strong style="font-size:12px">${esc(data.thread?.visitor_label || 'visitor')} · ${esc(data.thread?.referer_host || '(direct)')}</strong>
+ <button class="btn sec" data-thread-close type="button" style="font-size:11px">Close</button>
+ </div>
+ <div style="display:flex; flex-direction:column; gap:6px; max-height:340px; overflow:auto">
+ ${(data.messages || []).map(renderMessage).join('') || '<div class="muted">No messages.</div>'}
+ </div>
+ </div>
+ `;
+ detailEl.querySelector('[data-thread-close]').addEventListener('click', () => {
+ detailEl.hidden = true;
+ detailEl.innerHTML = '';
+ });
+ } catch (err) {
+ detailEl.innerHTML = `<div class="err">${esc(err.message || 'Failed to load thread')}</div>`;
+ }
+}
+
+function renderMessage(m) {
+ const isUser = m.role === 'user';
+ const bg = isUser ? '#1a1a26' : 'rgba(139, 92, 246, 0.12)';
+ const label = isUser ? 'visitor' : m.provider ? `agent · ${esc(m.provider)}` : 'agent';
+ const flag = m.redacted
+ ? ' <span class="muted" style="font-size:10px">(pii redacted)</span>'
+ : '';
+ return `
+ <div style="padding:8px 10px; background:${bg}; border-radius:6px">
+ <div class="muted" style="font-size:10px; text-transform:uppercase; letter-spacing:0.05em; margin-bottom:3px">${label}${flag}</div>
+ <div style="font-size:13px; white-space:pre-wrap; word-break:break-word">${esc(m.content || '')}</div>
+ </div>
+ `;
+}
+
+async function loadKnowledgeSummary(drawer, w) {
+ const el = drawer.querySelector('#knowledge-summary');
+ if (!el) return;
+ try {
+ const { docs = [] } = await api.listKnowledge(w.id);
+ if (!docs.length) {
+ el.innerHTML = `No knowledge attached. <a href="/studio?edit=${encodeURIComponent(w.id)}">Add some in Studio →</a>`;
+ return;
+ }
+ const totalChunks = docs.reduce((s, d) => s + (d.chunk_count || 0), 0);
+ el.innerHTML = `
+ ${docs.length} doc${docs.length === 1 ? '' : 's'} · ${formatNum(totalChunks)} chunks
+ <a href="/studio?edit=${encodeURIComponent(w.id)}" style="margin-left:6px">Manage →</a>
+ <ul style="margin:6px 0 0; padding-left:18px; font-size:12px; color:#aaa">
+ ${docs
+ .slice(0, 5)
+ .map(
+ (d) =>
+ `<li>${esc(d.title)} <span style="opacity:0.7">(${d.chunk_count || 0} chunks)</span></li>`,
+ )
+ .join('')}
+ </ul>
+ `;
+ } catch (err) {
+ el.textContent = `Couldn't load knowledge: ${err.message}`;
+ }
}
function renderStatsPanel(w, stats) {
@@ -4385,7 +4745,7 @@ function openShareModal(w) {
const maxW = 320,
maxH = 320;
const scale = Math.min(maxW / dim.width, maxH / dim.height, 1);
- previewEl.innerHTML = `<iframe src="/app#widget=${encodeURIComponent(w.id)}&kiosk=true&preview=1" style="width:${dim.width}px; height:${dim.height}px; border:0; transform:scale(${scale}); transform-origin:center" title="Preview"></iframe>`;
+ previewEl.innerHTML = `<iframe src="/widget#widget=${encodeURIComponent(w.id)}&kiosk=true&preview=1" style="width:${dim.width}px; height:${dim.height}px; border:0; transform:scale(${scale}); transform-origin:center" title="Preview"></iframe>`;
previewEl.style.width = `${dim.width * scale}px`;
previewEl.style.height = `${dim.height * scale}px`;
}
@@ -4936,7 +5296,8 @@ async function renderAnimations(root) {
statusEl.style.color = '#9a8cff';
statusEl.textContent = 'Saved.';
clearTimer = setTimeout(() => {
- if (seq === saveSeq && statusEl.textContent === 'Saved.') statusEl.textContent = '';
+ if (seq === saveSeq && statusEl.textContent === 'Saved.')
+ statusEl.textContent = '';
}, 2000);
} catch (err) {
if (seq !== saveSeq) return;
@@ -5456,7 +5817,8 @@ async function renderPayments(root) {
}
if (!agentId) {
- body.innerHTML = '<div class="card" style="text-align:center;padding:48px 24px"><p class="muted">No agent found. Create an agent first.</p></div>';
+ body.innerHTML =
+ '<div class="card" style="text-align:center;padding:48px 24px"><p class="muted">No agent found. Create an agent first.</p></div>';
return;
}
@@ -5467,14 +5829,18 @@ async function renderPayments(root) {
if (nextPayCursor) params.set('cursor', nextPayCursor);
let data;
try {
- const res = await fetch(`/api/agents/${agentId}/payments?${params}`, { credentials: 'include' });
+ const res = await fetch(`/api/agents/${agentId}/payments?${params}`, {
+ credentials: 'include',
+ });
if (!res.ok) {
const text = await res.text();
let msg = text;
try {
const j = JSON.parse(text);
msg = j.error_description || j.message || j.error || text;
- } catch { /* not JSON */ }
+ } catch {
+ /* not JSON */
+ }
const err = new Error(msg);
err.status = res.status;
throw err;
@@ -5518,14 +5884,19 @@ async function renderPayments(root) {
for (const p of data.payments) {
const amountEth = p.amount_wei
- ? (Number(BigInt(p.amount_wei)) / 1e18).toFixed(8).replace(/0+$/, '').replace(/\.$/, '.0')
+ ? (Number(BigInt(p.amount_wei)) / 1e18)
+ .toFixed(8)
+ .replace(/0+$/, '')
+ .replace(/\.$/, '.0')
: '—';
- const statusColor = p.status === 'confirmed' ? '#00e5a0' : p.status === 'failed' ? '#ff5c5c' : '#888';
- const explorerBase = p.chain_id === 8453
- ? 'https://basescan.org/tx/'
- : p.chain_id === 84532
- ? 'https://sepolia.basescan.org/tx/'
- : 'https://etherscan.io/tx/';
+ const statusColor =
+ p.status === 'confirmed' ? '#00e5a0' : p.status === 'failed' ? '#ff5c5c' : '#888';
+ const explorerBase =
+ p.chain_id === 8453
+ ? 'https://basescan.org/tx/'
+ : p.chain_id === 84532
+ ? 'https://sepolia.basescan.org/tx/'
+ : 'https://etherscan.io/tx/';
const txLink = p.tx_hash
? `<a href="${explorerBase}${esc(p.tx_hash)}" target="_blank" rel="noopener" style="font-size:12px">${esc(p.tx_hash.slice(0, 10))}…</a>`
: '—';
diff --git a/src/editor/embed-editor.js b/src/editor/embed-editor.js
index 7c23b4119..ae8bf5cf5 100644
--- a/src/editor/embed-editor.js
+++ b/src/editor/embed-editor.js
@@ -1495,13 +1495,13 @@ export function mountEmbedEditor(root, options = {}) {
avatarModalBackdrop.addEventListener('click', closeAvatarModal);
// If a widget id was passed, swap the bare <agent-3d> preview for an
- // iframe loading the live widget renderer (/app#widget=<id>&kiosk=true).
+ // iframe loading the live widget renderer (/widget#widget=<id>&kiosk=true).
if (state.widgetId) loadWidget(state.widgetId);
async function loadWidget(id) {
const origin = location.origin;
// Show the live widget immediately — don't wait on the metadata fetch.
- widgetFrame.src = `${origin}/app#widget=${encodeURIComponent(id)}&kiosk=true`;
+ widgetFrame.src = `${origin}/widget#widget=${encodeURIComponent(id)}&kiosk=true`;
widgetFrame.hidden = false;
agentEl.style.display = 'none';
widgetBadge.hidden = false;
diff --git a/src/handle.js b/src/handle.js
new file mode 100644
index 000000000..dfd3b16fe
--- /dev/null
+++ b/src/handle.js
@@ -0,0 +1,218 @@
+// /@<handle> — live profile page for a three.ws user.
+//
+// Renders the user's primary avatar in a hosted iframe (same /embed/avatar/:handle
+// surface third-party sites embed) and surfaces copy-paste embed snippets.
+// The iframe is the canonical runtime — this page never touches Three.js
+// directly, so it stays small and the avatar runtime is identical wherever
+// it shows up.
+
+const main = document.getElementById('main');
+
+const handle = (() => {
+ const parts = location.pathname.split('/').filter(Boolean);
+ // Accept /@nick, /@/nick, /handle/nick, /u/nick
+ for (const p of parts) {
+ if (p.startsWith('@')) return p.slice(1).toLowerCase();
+ }
+ if (parts[0] === 'u' && parts[1]) return parts[1].toLowerCase();
+ if (parts[0] === 'handle' && parts[1]) return parts[1].toLowerCase();
+ return new URL(location.href).searchParams.get('handle')?.toLowerCase() || '';
+})();
+
+if (!handle) {
+ renderNotFound('No handle in the URL.');
+} else {
+ render(handle).catch((err) => {
+ console.error('[handle] render failed', err);
+ renderNotFound(err?.message || 'Could not load this profile.');
+ });
+}
+
+async function render(name) {
+ const resp = await fetch(`/api/users/${encodeURIComponent(name)}/avatar?bg=dark&idle=on`);
+ if (!resp.ok) {
+ if (resp.status === 404) {
+ renderNotFound(`@${name} doesn't have a public avatar yet.`);
+ return;
+ }
+ const body = await resp.json().catch(() => null);
+ throw new Error(body?.message || `request failed (${resp.status})`);
+ }
+ const data = await resp.json();
+ const user = data.user;
+ const avatar = data.avatar;
+
+ document.title = `@${user.username} — three.ws`;
+ const og = (id, value) => {
+ const el = document.getElementById(id);
+ if (el) el.setAttribute('content', value);
+ };
+ og('og-title', `@${user.username} on three.ws`);
+ og('tw-title', `@${user.username} on three.ws`);
+ const desc = avatar.description || `${user.display_name || user.username}'s live 3D avatar — embed me anywhere.`;
+ og('og-description', desc);
+ og('tw-description', desc);
+ if (avatar.thumbnail_url) {
+ og('og-image', avatar.thumbnail_url);
+ og('tw-image', avatar.thumbnail_url);
+ }
+
+ const stats = [
+ { k: 'morph coverage', v: '—' }, // filled from v1.avatar.ready
+ { k: 'size', v: humanBytes(avatar.size_bytes) },
+ { k: 'version', v: `v${avatar.version || 1}` },
+ ];
+
+ const embedUrl = data.embed_url || `${location.origin}/embed/avatar/${user.username}`;
+ const scriptSnippet =
+ data.embed?.script ||
+ `<script async src="${location.origin}/embed.js" data-avatar="@${user.username}"></script>`;
+ const iframeSnippet =
+ data.embed?.iframe ||
+ `<iframe src="${embedUrl}" width="420" height="600" frameborder="0" allow="autoplay; camera; clipboard-write; xr-spatial-tracking" style="border-radius:12px;"></iframe>`;
+
+ main.innerHTML = `
+ <section class="stage">
+ <iframe id="avatar-frame" src="${escapeAttr(embedUrl)}" allow="autoplay; camera; clipboard-write; xr-spatial-tracking" title="@${escapeAttr(user.username)}"></iframe>
+ <div class="stage-overlay">
+ <button class="chip" data-action="speak">say hello</button>
+ <button class="chip" data-action="emote-smile">smile</button>
+ <button class="chip" data-action="emote-wink">wink</button>
+ <button class="chip" data-action="mocap">webcam mocap</button>
+ </div>
+ </section>
+ <aside class="side">
+ <h1>${escapeHtml(user.display_name || user.username)}</h1>
+ <div class="handle">@${escapeHtml(user.username)} · <a href="/u/${escapeAttr(user.username)}" style="color:rgba(255,255,255,0.55)">full profile →</a></div>
+ ${avatar.description ? `<p class="desc">${escapeHtml(avatar.description)}</p>` : ''}
+ <div class="stat-grid">
+ ${stats.map((s) => `<div class="stat"><div class="v" data-stat="${escapeAttr(s.k)}">${escapeHtml(s.v)}</div><div class="k">${escapeHtml(s.k)}</div></div>`).join('')}
+ </div>
+ <div class="cta-row">
+ <a href="${escapeAttr(avatar.base_model_url || avatar.model_url)}" download>download .glb</a>
+ <a class="ghost" href="/avatars/${escapeAttr(avatar.id)}">avatar page</a>
+ </div>
+ <div class="embed-card">
+ <h3>Embed anywhere — script tag</h3>
+ <pre id="snippet-script">${escapeHtml(scriptSnippet)}</pre>
+ <button class="copy" data-copy="snippet-script">Copy snippet</button>
+ </div>
+ <div class="embed-card">
+ <h3>Embed anywhere — iframe</h3>
+ <pre id="snippet-iframe">${escapeHtml(iframeSnippet)}</pre>
+ <button class="copy" data-copy="snippet-iframe">Copy iframe</button>
+ </div>
+ <div class="embed-card">
+ <h3>API</h3>
+ <pre>GET /api/users/${escapeHtml(user.username)}/avatar
+GET ${escapeHtml(avatar.model_url)}</pre>
+ </div>
+ </aside>
+ `;
+
+ // ── postMessage bridge to the embed ──────────────────────────────────
+ const iframe = document.getElementById('avatar-frame');
+ const send = (msg) => {
+ try {
+ iframe.contentWindow?.postMessage(msg, new URL(embedUrl).origin);
+ } catch (err) {
+ console.warn('[handle] postMessage failed', err);
+ }
+ };
+
+ window.addEventListener('message', (ev) => {
+ if (ev.source !== iframe.contentWindow) return;
+ const msg = ev.data;
+ if (!msg || typeof msg !== 'object') return;
+ if (msg.type === 'v1.avatar.ready') {
+ const cov = msg.conformance
+ ? `${Math.round((msg.conformance.coverage || 0) * 100)}%`
+ : '—';
+ const el = document.querySelector('[data-stat="morph coverage"]');
+ if (el) el.textContent = cov;
+ send({ type: 'v1.avatar.hello' });
+ }
+ });
+
+ // Optimistically open the handshake — embed will reply with ready when it
+ // finishes init, even if our hello arrives early.
+ const tryHello = () => send({ type: 'v1.avatar.hello' });
+ iframe.addEventListener('load', tryHello);
+
+ // ── Wire the demo chips ───────────────────────────────────────────────
+ main.querySelectorAll('[data-action]').forEach((btn) => {
+ btn.addEventListener('click', () => {
+ const action = btn.dataset.action;
+ if (action === 'speak') {
+ send({
+ type: 'v1.avatar.speak',
+ text: `Hey, I'm ${user.display_name || user.username}. You can drop me anywhere.`,
+ });
+ } else if (action === 'emote-smile') {
+ send({ type: 'v1.avatar.morphs', weights: { mouthSmileLeft: 0.8, mouthSmileRight: 0.8, cheekSquintLeft: 0.4, cheekSquintRight: 0.4 } });
+ setTimeout(() => send({ type: 'v1.avatar.morphs', weights: { mouthSmileLeft: 0, mouthSmileRight: 0, cheekSquintLeft: 0, cheekSquintRight: 0 } }), 1800);
+ } else if (action === 'emote-wink') {
+ send({ type: 'v1.avatar.emote', name: 'eyeBlinkLeft', weight: 1 });
+ setTimeout(() => send({ type: 'v1.avatar.emote', name: 'eyeBlinkLeft', weight: 0 }), 220);
+ } else if (action === 'mocap') {
+ send({ type: 'v1.avatar.mocap', enabled: true });
+ }
+ });
+ });
+
+ // ── Copy snippets ─────────────────────────────────────────────────────
+ main.querySelectorAll('[data-copy]').forEach((btn) => {
+ btn.addEventListener('click', async () => {
+ const sourceId = btn.dataset.copy;
+ const text = document.getElementById(sourceId)?.textContent || '';
+ try {
+ await navigator.clipboard.writeText(text);
+ const original = btn.textContent;
+ btn.textContent = 'Copied';
+ btn.classList.add('copied');
+ setTimeout(() => {
+ btn.textContent = original;
+ btn.classList.remove('copied');
+ }, 1400);
+ } catch (err) {
+ console.warn('[handle] clipboard failed', err);
+ }
+ });
+ });
+}
+
+function renderNotFound(reason) {
+ main.innerHTML = `
+ <div class="not-found" style="grid-column: 1 / -1">
+ <h1>Nothing to render</h1>
+ <p>${escapeHtml(reason || 'Profile not found.')}</p>
+ <p><a href="/explore">Browse avatars on three.ws →</a></p>
+ </div>
+ `;
+}
+
+function humanBytes(n) {
+ const v = Number(n) || 0;
+ if (!v) return '—';
+ const units = ['B', 'KB', 'MB', 'GB'];
+ let u = 0;
+ let x = v;
+ while (x >= 1024 && u < units.length - 1) {
+ x /= 1024;
+ u++;
+ }
+ return `${x.toFixed(x < 10 ? 1 : 0)} ${units[u]}`;
+}
+
+function escapeHtml(s) {
+ if (s == null) return '';
+ return String(s)
+ .replace(/&/g, '&amp;')
+ .replace(/</g, '&lt;')
+ .replace(/>/g, '&gt;')
+ .replace(/"/g, '&quot;')
+ .replace(/'/g, '&#39;');
+}
+function escapeAttr(s) {
+ return escapeHtml(s);
+}
diff --git a/src/next-layout.js b/src/next-layout.js
new file mode 100644
index 000000000..3b70e3940
--- /dev/null
+++ b/src/next-layout.js
@@ -0,0 +1,575 @@
+/**
+ * Next-layout controller for the /app viewer.
+ *
+ * Mounts the alternate "Next" chrome — bottom command dock with a scrubbable
+ * timeline, right-side Controls drawer that hosts the dat.GUI panel, and a
+ * single corner-anchored Share popover that collapses the four owner-action
+ * buttons (Save / Widget / Deploy / Profile) plus Upload + Create. The layout
+ * is toggled via body[data-layout='next'] (see app.js _applyViewerLayout).
+ *
+ * Wiring is direct: clip selection drives viewer.mixer.clipAction() and
+ * playback state is read/written on the same AnimationAction the dock
+ * exposes. The Controls drawer physically relocates the existing
+ * viewer .gui-wrap DOM into a drawer body so dat.GUI continues to drive
+ * camera/lighting/material state through its original onChange handlers —
+ * no re-implementation, just a presentational reparent.
+ *
+ * Pulls in three concrete patterns from current best-in-class viewers:
+ * - Sketchfab-style single bottom bar with a real scrubbable timeline
+ * - Babylon-Sandbox-style invisible full-page drag-drop with a tiny
+ * floating gear that opens the controls drawer (Khronos drawer body)
+ * - Google model-viewer-style auto-rotate-on-idle + a hand swipe prompt
+ * that disappears after the first interaction
+ */
+
+import { LoopOnce, LoopRepeat } from 'three';
+
+const STORAGE_KEY_INTERACTED = '3dagent:viewer-interacted';
+const POLL_INTERVAL_MS = 100;
+const POLL_MAX_MS = 15000;
+
+export class NextLayout {
+ constructor(app) {
+ this.app = app;
+ this.viewer = null;
+ this.action = null;
+ this.clipIdx = -1;
+ this.loop = true;
+ this.rafId = 0;
+ this.driverAttached = false;
+ this._guiMoved = false;
+ this._idleTimer = 0;
+ this._mounted = false;
+ }
+
+ mount() {
+ if (this._mounted) return;
+ this._mounted = true;
+
+ this.root = document.getElementById('next-chrome');
+ if (!this.root) return;
+
+ this._cacheEls();
+ this._wireDock();
+ this._wireGrid();
+ this._wireDrawer();
+ this._wireSharePopover();
+ this._wireFullscreen();
+ this._wirePromptDismiss();
+ this._wireLayoutObserver();
+ this._wireViewerWhenReady();
+ this._wireShareItemMirroring();
+
+ this._applyLayoutChange();
+ }
+
+ // ── element cache ────────────────────────────────────────────────────────
+
+ _cacheEls() {
+ this.els = {
+ prompt: document.getElementById('next-prompt'),
+ corner: document.getElementById('next-corner'),
+ shareBtn: document.getElementById('next-share-btn'),
+ shareMenu: document.getElementById('next-share-menu'),
+ shareSave: document.getElementById('next-share-save'),
+ shareWidget: document.getElementById('next-share-widget'),
+ shareDeploy: document.getElementById('next-share-deploy'),
+ shareProfile: document.getElementById('next-share-profile'),
+ shareUpload: document.getElementById('next-share-upload'),
+ controlsBtn: document.getElementById('next-controls-btn'),
+ fullscreenBtn: document.getElementById('next-fullscreen-btn'),
+ drawer: document.getElementById('next-drawer'),
+ drawerClose: document.getElementById('next-drawer-close'),
+ drawerBody: document.getElementById('next-drawer-body'),
+ dock: document.getElementById('next-dock'),
+ clipBtn: document.getElementById('next-dock-clip'),
+ clipName: document.getElementById('next-dock-clip-name'),
+ playBtn: document.getElementById('next-dock-play'),
+ scrubInput: document.getElementById('next-dock-scrub-input'),
+ scrubFill: document.getElementById('next-dock-scrub-fill'),
+ time: document.getElementById('next-dock-time'),
+ loopBtn: document.getElementById('next-dock-loop'),
+ grid: document.getElementById('next-grid'),
+ };
+ }
+
+ // ── viewer wiring ────────────────────────────────────────────────────────
+
+ async _wireViewerWhenReady() {
+ const viewer = await this._waitForViewer();
+ if (!viewer) return;
+ this.viewer = viewer;
+ await this._waitForClips(viewer);
+ this._renderClipGrid();
+ this._selectClipByIdx(0, { autoplay: false });
+ this._attachDriver();
+ this._armIdleAutoRotate();
+ }
+
+ _waitForViewer() {
+ return new Promise((resolve) => {
+ const start = Date.now();
+ const poll = () => {
+ if (this.app.viewer && this.app.viewer.controls) {
+ resolve(this.app.viewer);
+ return;
+ }
+ if (Date.now() - start > POLL_MAX_MS) {
+ resolve(null);
+ return;
+ }
+ setTimeout(poll, POLL_INTERVAL_MS);
+ };
+ poll();
+ });
+ }
+
+ _waitForClips(viewer) {
+ return new Promise((resolve) => {
+ const start = Date.now();
+ const poll = () => {
+ if (viewer.clips?.length && viewer.mixer) {
+ resolve(viewer.clips.slice());
+ return;
+ }
+ if (Date.now() - start > POLL_MAX_MS) {
+ resolve([]);
+ return;
+ }
+ setTimeout(poll, POLL_INTERVAL_MS);
+ };
+ poll();
+ });
+ }
+
+ // ── animation playback ───────────────────────────────────────────────────
+
+ _renderClipGrid() {
+ const grid = this.els.grid;
+ if (!grid || !this.viewer?.clips) return;
+ grid.innerHTML = '';
+ const clips = this.viewer.clips;
+ const frag = document.createDocumentFragment();
+ clips.forEach((clip, i) => {
+ const btn = document.createElement('button');
+ btn.type = 'button';
+ btn.className = 'next-grid__item';
+ btn.dataset.idx = String(i);
+ btn.setAttribute('role', 'option');
+ btn.setAttribute('aria-selected', 'false');
+ btn.title = _stripIdx(clip.name);
+ const label = document.createElement('span');
+ label.className = 'next-grid__label';
+ label.textContent = _stripIdx(clip.name);
+ btn.appendChild(label);
+ btn.addEventListener('click', () => {
+ this._selectClipByIdx(i, { autoplay: true });
+ this._toggleGrid(false);
+ });
+ frag.appendChild(btn);
+ });
+ grid.appendChild(frag);
+ }
+
+ _selectClipByIdx(idx, { autoplay }) {
+ const viewer = this.viewer;
+ if (!viewer?.mixer || !viewer.clips || idx < 0 || idx >= viewer.clips.length) return;
+ this._stopAll();
+ const clip = viewer.clips[idx];
+ const action = viewer.mixer.clipAction(clip);
+ action.reset();
+ action.enabled = true;
+ action.setEffectiveTimeScale(1);
+ action.setEffectiveWeight(1);
+ this._applyLoop(action);
+ if (autoplay) action.play();
+ else action.paused = true;
+ this.action = action;
+ this.clipIdx = idx;
+ if (viewer.state?.actionStates) {
+ for (const k of Object.keys(viewer.state.actionStates)) {
+ viewer.state.actionStates[k] = false;
+ }
+ viewer.state.actionStates[clip.name] = autoplay;
+ }
+ this._updateClipName();
+ this._updatePlayBtn();
+ this._updateScrubAndTime();
+ this._updateGridHighlight();
+ viewer.invalidate();
+ }
+
+ _stopAll() {
+ const viewer = this.viewer;
+ if (!viewer?.mixer) return;
+ viewer.mixer.stopAllAction();
+ if (viewer.state?.actionStates) {
+ for (const k of Object.keys(viewer.state.actionStates)) viewer.state.actionStates[k] = false;
+ }
+ }
+
+ _applyLoop(action) {
+ action.setLoop(this.loop ? LoopRepeat : LoopOnce, this.loop ? Infinity : 1);
+ action.clampWhenFinished = !this.loop;
+ }
+
+ _attachDriver() {
+ if (this.driverAttached) return;
+ this.driverAttached = true;
+ const tick = () => {
+ this.rafId = requestAnimationFrame(tick);
+ this._updateScrubAndTime();
+ };
+ this.rafId = requestAnimationFrame(tick);
+ }
+
+ _updateClipName() {
+ if (!this.els.clipName) return;
+ const clip = this.viewer?.clips?.[this.clipIdx];
+ this.els.clipName.textContent = clip ? _stripIdx(clip.name) : '—';
+ }
+
+ _updatePlayBtn() {
+ const btn = this.els.playBtn;
+ if (!btn) return;
+ const playing = Boolean(this.action && !this.action.paused);
+ btn.setAttribute('aria-pressed', String(playing));
+ btn.setAttribute('aria-label', playing ? 'Pause' : 'Play');
+ btn.classList.toggle('next-dock__play--playing', playing);
+ }
+
+ _updateScrubAndTime() {
+ const a = this.action;
+ const scrubInput = this.els.scrubInput;
+ const scrubFill = this.els.scrubFill;
+ const time = this.els.time;
+ if (!a) {
+ if (scrubInput) scrubInput.value = '0';
+ if (scrubFill) scrubFill.style.width = '0%';
+ if (time) time.textContent = '0:00 / 0:00';
+ return;
+ }
+ const duration = a.getClip().duration || 0;
+ const t = duration ? a.time % duration : 0;
+ const pct = duration ? (t / duration) * 1000 : 0;
+ if (scrubInput && document.activeElement !== scrubInput) {
+ scrubInput.value = String(Math.round(pct));
+ }
+ if (scrubFill) scrubFill.style.width = `${(pct / 1000) * 100}%`;
+ if (time) time.textContent = `${_fmtTime(t)} / ${_fmtTime(duration)}`;
+ }
+
+ _updateGridHighlight() {
+ const grid = this.els.grid;
+ if (!grid) return;
+ grid.querySelectorAll('.next-grid__item').forEach((btn) => {
+ const active = Number(btn.dataset.idx) === this.clipIdx;
+ btn.classList.toggle('next-grid__item--active', active);
+ btn.setAttribute('aria-selected', String(active));
+ });
+ }
+
+ // ── dock wiring ──────────────────────────────────────────────────────────
+
+ _wireDock() {
+ this.els.clipBtn?.addEventListener('click', () => {
+ this._toggleGrid();
+ });
+
+ this.els.playBtn?.addEventListener('click', () => {
+ if (!this.action) return;
+ if (this.action.paused) {
+ const duration = this.action.getClip().duration || 0;
+ // If we're at the end of a one-shot clip, rewind before playing.
+ if (!this.loop && duration && this.action.time >= duration - 0.01) {
+ this.action.reset();
+ this._applyLoop(this.action);
+ }
+ this.action.paused = false;
+ if (!this.action.isRunning()) this.action.play();
+ } else {
+ this.action.paused = true;
+ }
+ this._updatePlayBtn();
+ this.viewer?.invalidate();
+ });
+
+ const scrub = this.els.scrubInput;
+ if (scrub) {
+ const onScrub = () => {
+ if (!this.action) return;
+ const duration = this.action.getClip().duration || 0;
+ const pct = Number(scrub.value) / 1000;
+ this.action.time = Math.max(0, Math.min(duration, pct * duration));
+ if (this.action.paused) {
+ // Manually advance so the mixer applies the new time even
+ // while paused. dt=0 still triggers a pose update.
+ this.viewer?.mixer?.update(0);
+ }
+ this._updateScrubAndTime();
+ this.viewer?.invalidate();
+ };
+ scrub.addEventListener('input', onScrub);
+ scrub.addEventListener('change', onScrub);
+ }
+
+ this.els.loopBtn?.addEventListener('click', () => {
+ this.loop = !this.loop;
+ this.els.loopBtn.setAttribute('aria-pressed', String(this.loop));
+ this.els.loopBtn.classList.toggle('next-dock__loop--off', !this.loop);
+ if (this.action) this._applyLoop(this.action);
+ });
+ }
+
+ _wireGrid() {
+ // Close grid on outside click.
+ document.addEventListener('click', (e) => {
+ const grid = this.els.grid;
+ const btn = this.els.clipBtn;
+ if (!grid || grid.hidden) return;
+ if (grid.contains(e.target) || btn?.contains(e.target)) return;
+ this._toggleGrid(false);
+ });
+ }
+
+ _toggleGrid(force) {
+ const grid = this.els.grid;
+ const btn = this.els.clipBtn;
+ if (!grid || !btn) return;
+ const open = typeof force === 'boolean' ? force : grid.hidden;
+ grid.hidden = !open;
+ btn.setAttribute('aria-expanded', String(open));
+ btn.classList.toggle('next-dock__clip--open', open);
+ }
+
+ // ── drawer (Controls) ────────────────────────────────────────────────────
+
+ _wireDrawer() {
+ this.els.controlsBtn?.addEventListener('click', () => this._toggleDrawer());
+ this.els.drawerClose?.addEventListener('click', () => this._toggleDrawer(false));
+ document.addEventListener('keydown', (e) => {
+ if (e.key === 'Escape' && this._drawerIsOpen()) this._toggleDrawer(false);
+ });
+ }
+
+ _drawerIsOpen() {
+ return this.els.drawer?.classList.contains('next-drawer--open');
+ }
+
+ _toggleDrawer(force) {
+ const drawer = this.els.drawer;
+ const btn = this.els.controlsBtn;
+ if (!drawer || !btn) return;
+ const open = typeof force === 'boolean' ? force : !this._drawerIsOpen();
+ drawer.classList.toggle('next-drawer--open', open);
+ drawer.setAttribute('aria-hidden', String(!open));
+ btn.setAttribute('aria-expanded', String(open));
+ btn.classList.toggle('next-icon-btn--active', open);
+ if (open) this._mountGuiIntoDrawer();
+ }
+
+ _mountGuiIntoDrawer() {
+ if (this._guiMoved) return;
+ const wrap = document.querySelector('.gui-wrap');
+ const body = this.els.drawerBody;
+ if (!wrap || !body) return;
+ wrap.classList.remove('gui-wrap--hidden');
+ body.appendChild(wrap);
+ this._guiMoved = true;
+ }
+
+ // ── share popover ────────────────────────────────────────────────────────
+
+ _wireSharePopover() {
+ this.els.shareBtn?.addEventListener('click', (e) => {
+ e.stopPropagation();
+ this._toggleShare();
+ });
+ document.addEventListener('click', (e) => {
+ const menu = this.els.shareMenu;
+ const btn = this.els.shareBtn;
+ if (!menu || menu.hidden) return;
+ if (menu.contains(e.target) || btn?.contains(e.target)) return;
+ this._toggleShare(false);
+ });
+
+ // Wire Save → fire the original button's click handler.
+ this.els.shareSave?.addEventListener('click', () => {
+ document.getElementById('save-to-account-btn')?.click();
+ this._toggleShare(false);
+ });
+
+ // Upload → trigger the existing #file-input picker (SimpleDropzone listens to it).
+ this.els.shareUpload?.addEventListener('click', () => {
+ document.getElementById('file-input')?.click();
+ this._toggleShare(false);
+ });
+ }
+
+ _wireShareItemMirroring() {
+ // The original action buttons toggle hidden + update href dynamically
+ // based on auth/state. Mirror those changes onto the Share popover's
+ // items so they reflect the same set of available actions.
+ const map = [
+ { src: 'save-to-account-btn', dst: this.els.shareSave, type: 'btn' },
+ { src: 'make-widget-btn', dst: this.els.shareWidget, type: 'link' },
+ { src: 'deploy-onchain-btn', dst: this.els.shareDeploy, type: 'link' },
+ { src: 'view-public-profile-btn', dst: this.els.shareProfile, type: 'link' },
+ ];
+ for (const { src, dst, type } of map) {
+ const srcEl = document.getElementById(src);
+ if (!srcEl || !dst) continue;
+ const sync = () => {
+ const hidden = srcEl.hidden || srcEl.hasAttribute('hidden');
+ dst.hidden = hidden;
+ if (type === 'link') {
+ const href = srcEl.getAttribute('href');
+ if (href) dst.setAttribute('href', href);
+ else dst.removeAttribute('href');
+ if (srcEl.target) dst.setAttribute('target', srcEl.target);
+ }
+ const label = srcEl.querySelector('[data-state-label]') || srcEl.querySelector('span');
+ if (label && dst.querySelector('span')) {
+ dst.querySelector('span').textContent = label.textContent.trim();
+ }
+ const isDeployed = srcEl.classList.contains('is-deployed');
+ dst.classList.toggle('next-share-menu__item--success', isDeployed);
+ };
+ sync();
+ const mo = new MutationObserver(sync);
+ mo.observe(srcEl, {
+ attributes: true,
+ attributeFilter: ['hidden', 'href', 'class', 'target'],
+ childList: true,
+ subtree: true,
+ characterData: true,
+ });
+ }
+ // Reflect available actions count on the corner button (subtle dot).
+ this._updateShareDot();
+ }
+
+ _updateShareDot() {
+ const btn = this.els.shareBtn;
+ if (!btn) return;
+ const items = [this.els.shareSave, this.els.shareWidget, this.els.shareDeploy, this.els.shareProfile];
+ const any = items.some((el) => el && !el.hidden);
+ btn.classList.toggle('next-icon-btn--has-actions', any);
+ }
+
+ _toggleShare(force) {
+ const menu = this.els.shareMenu;
+ const btn = this.els.shareBtn;
+ if (!menu || !btn) return;
+ const open = typeof force === 'boolean' ? force : menu.hidden;
+ menu.hidden = !open;
+ btn.setAttribute('aria-expanded', String(open));
+ btn.classList.toggle('next-icon-btn--active', open);
+ if (open) this._updateShareDot();
+ }
+
+ // ── fullscreen ───────────────────────────────────────────────────────────
+
+ _wireFullscreen() {
+ this.els.fullscreenBtn?.addEventListener('click', () => {
+ const el = document.documentElement;
+ if (document.fullscreenElement) {
+ document.exitFullscreen().catch(() => {});
+ } else if (el.requestFullscreen) {
+ el.requestFullscreen().catch(() => {});
+ }
+ });
+ }
+
+ // ── interaction prompt + idle auto-rotate ────────────────────────────────
+
+ _wirePromptDismiss() {
+ const prompt = this.els.prompt;
+ if (!prompt) return;
+ const seen = (() => {
+ try {
+ return localStorage.getItem(STORAGE_KEY_INTERACTED) === 'true';
+ } catch {
+ return false;
+ }
+ })();
+ if (seen) {
+ prompt.remove();
+ return;
+ }
+ const dismiss = () => {
+ prompt.classList.add('next-prompt--out');
+ setTimeout(() => prompt.remove(), 500);
+ try {
+ localStorage.setItem(STORAGE_KEY_INTERACTED, 'true');
+ } catch {
+ /* ignore */
+ }
+ window.removeEventListener('pointerdown', dismiss);
+ window.removeEventListener('wheel', dismiss);
+ window.removeEventListener('keydown', dismiss);
+ };
+ window.addEventListener('pointerdown', dismiss, { once: true });
+ window.addEventListener('wheel', dismiss, { once: true, passive: true });
+ window.addEventListener('keydown', dismiss, { once: true });
+ }
+
+ _armIdleAutoRotate() {
+ const viewer = this.viewer;
+ if (!viewer?.controls) return;
+ const resetIdle = () => {
+ if (!viewer.controls) return;
+ viewer.controls.autoRotate = false;
+ viewer.invalidate();
+ clearTimeout(this._idleTimer);
+ this._idleTimer = setTimeout(() => {
+ if (document.body.dataset.layout !== 'next') return;
+ viewer.controls.autoRotate = true;
+ viewer.controls.autoRotateSpeed = 0.6;
+ viewer.invalidate();
+ }, 4000);
+ };
+ viewer.controls.addEventListener('start', resetIdle);
+ viewer.controls.addEventListener('end', resetIdle);
+ resetIdle();
+ }
+
+ // ── layout toggle observer ───────────────────────────────────────────────
+
+ _wireLayoutObserver() {
+ const mo = new MutationObserver(() => this._applyLayoutChange());
+ mo.observe(document.body, { attributes: true, attributeFilter: ['data-layout'] });
+ }
+
+ _applyLayoutChange() {
+ const next = document.body.dataset.layout === 'next';
+ this.root?.setAttribute('aria-hidden', String(!next));
+ if (next) {
+ this._mountGuiIntoDrawer();
+ } else if (this._guiMoved) {
+ // Return the dat.GUI panel back to the viewer container so the
+ // Classic .gui-toggle keeps working when the user flips back.
+ const wrap = document.querySelector('.gui-wrap');
+ const viewerEl = document.getElementById('viewer-container');
+ if (wrap && viewerEl) {
+ wrap.classList.add('gui-wrap--hidden');
+ viewerEl.appendChild(wrap);
+ this._guiMoved = false;
+ }
+ }
+ }
+}
+
+// ── helpers ───────────────────────────────────────────────────────────────
+
+function _stripIdx(name) {
+ const m = /^\d+\.\s*(.*)$/.exec(name);
+ return m ? m[1] : name;
+}
+
+function _fmtTime(s) {
+ const total = Math.max(0, Math.floor(s));
+ const m = Math.floor(total / 60);
+ const sec = total % 60;
+ return `${m}:${String(sec).padStart(2, '0')}`;
+}
diff --git a/src/selfie-capture.js b/src/selfie-capture.js
index 64a02d742..f60cec036 100644
--- a/src/selfie-capture.js
+++ b/src/selfie-capture.js
@@ -1,22 +1,27 @@
/**
- * Selfie capture flow — entry for /create.
+ * Selfie capture flow — entry for /create/selfie.
*
- * Manages two steps:
- * 1. Method choice (camera vs upload)
- * 2. 3-photo capture (Frontal / Left / Right) + body/avatar type selectors
+ * Hero slot (frontal) is required. Side slots (left / right) are optional —
+ * they live under the "Add side angles" disclosure and bump reconstruction
+ * fidelity when supplied. Capture method (camera vs upload) is picked per slot.
*
* On submit, dispatches a `selfie:submit` CustomEvent on document with
- * detail = { files: { frontal, left, right }, bodyType, avatarType, method }
+ * detail = { files: { frontal, left?, right? }, bodyType, avatarType, method }
* which the selfie pipeline picks up to drive avatar reconstruction.
*/
-const SLOT_KEYS = /** @type {const} */ (['frontal', 'left', 'right']);
+const REQUIRED_SLOT = 'frontal';
+const OPTIONAL_SLOTS = /** @type {const} */ (['left', 'right']);
+const ALL_SLOTS = /** @type {const} */ ([REQUIRED_SLOT, ...OPTIONAL_SLOTS]);
+
+const ETA_FAST_SEC = 45;
+const ETA_HIGH_SEC = 75;
const state = {
- method: /** @type {'camera' | 'upload' | null} */ (null),
bodyType: /** @type {'male' | 'female'} */ ('male'),
avatarType: /** @type {'v1' | 'v2'} */ ('v1'),
files: /** @type {Record<string, File | null>} */ ({ frontal: null, left: null, right: null }),
+ lastMethod: /** @type {'camera' | 'upload' | null} */ (null),
};
const cameraSupported =
@@ -25,74 +30,89 @@ const cameraSupported =
typeof navigator.mediaDevices.getUserMedia === 'function';
// ── DOM refs ───────────────────────────────────────────────────────────────
-const steps = /** @type {NodeListOf<HTMLElement>} */ (
- document.querySelectorAll('.step[data-step]')
-);
const backBtn = /** @type {HTMLButtonElement} */ (document.getElementById('back-btn'));
-const choiceButtons = /** @type {NodeListOf<HTMLButtonElement>} */ (
- document.querySelectorAll('.choice[data-method]')
-);
const unsupportedMsg = document.getElementById('unsupported-msg');
-const slotFrames = /** @type {NodeListOf<HTMLElement>} */ (
+const heroSlot = /** @type {HTMLElement | null} */ (
+ document.querySelector('.hero-slot[data-slot="frontal"]')
+);
+const heroCameraBtn = /** @type {HTMLButtonElement | null} */ (
+ document.querySelector('.hero-pill[data-action="open-camera"]')
+);
+const heroUploadBtn = /** @type {HTMLButtonElement | null} */ (
+ document.querySelector('.hero-pill[data-action="open-upload"]')
+);
+const sideFrames = /** @type {NodeListOf<HTMLElement>} */ (
document.querySelectorAll('.slot-frame[data-slot]')
);
const slotInputs = /** @type {NodeListOf<HTMLInputElement>} */ (
document.querySelectorAll('input[data-slot-input]')
);
-const submitBar = document.getElementById('submit-bar');
const submitBtn = /** @type {HTMLButtonElement} */ (document.getElementById('submit-btn'));
const bodyBtns = /** @type {NodeListOf<HTMLButtonElement>} */ (
document.querySelectorAll('[data-body]')
);
-const typeBtns = /** @type {NodeListOf<HTMLButtonElement>} */ (
- document.querySelectorAll('[data-type]')
+const styleBtns = /** @type {NodeListOf<HTMLButtonElement>} */ (
+ document.querySelectorAll('.style-card[data-type]')
);
-// ── Step 1: method picker ──────────────────────────────────────────────────
+// ── Camera support gating ──────────────────────────────────────────────────
if (!cameraSupported) {
- const camChoice = /** @type {HTMLButtonElement | null} */ (
- document.querySelector('.choice[data-method="camera"]')
- );
- if (camChoice) {
- camChoice.disabled = true;
- camChoice.setAttribute('aria-disabled', 'true');
- }
+ heroCameraBtn?.setAttribute('disabled', '');
+ heroCameraBtn?.setAttribute('aria-disabled', 'true');
+ heroCameraBtn?.setAttribute('title', 'Camera not available in this browser');
unsupportedMsg?.classList.add('show');
}
-choiceButtons.forEach((btn) => {
- btn.addEventListener('click', () => {
- const method = /** @type {'camera'|'upload'|null} */ (btn.getAttribute('data-method'));
- if (!method || btn.disabled) return;
- if (method === 'camera' && !cameraSupported) return;
- state.method = method;
- goToStep('capture');
- });
+// ── Top bar back ───────────────────────────────────────────────────────────
+backBtn?.addEventListener('click', () => {
+ const active = document.querySelector('.step.active')?.getAttribute('data-step');
+ if (active === 'capture') window.location.assign('/create');
+ else if (active === 'building' || active === 'done') showStep('capture');
+ else window.location.assign('/');
});
-backBtn.addEventListener('click', () => {
- const current = currentStep();
- if (current === 'capture') {
- goToStep('method');
- } else {
- window.location.assign('/');
+// ── Hero slot: tap → contextual default (camera if supported, else upload)
+heroSlot?.addEventListener('click', (e) => {
+ const target = /** @type {HTMLElement} */ (e.target);
+ if (target.closest('.retake-btn')) return;
+ if (state.files[REQUIRED_SLOT]) return;
+ openForSlot(REQUIRED_SLOT, cameraSupported ? 'camera' : 'upload');
+});
+heroSlot?.addEventListener('keydown', (e) => {
+ if (e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault();
+ if (state.files[REQUIRED_SLOT]) return;
+ openForSlot(REQUIRED_SLOT, cameraSupported ? 'camera' : 'upload');
}
});
-// ── Step 2: slot fill ──────────────────────────────────────────────────────
-slotFrames.forEach((frame) => {
+heroCameraBtn?.addEventListener('click', () => {
+ if (heroCameraBtn.hasAttribute('disabled')) return;
+ openForSlot(REQUIRED_SLOT, 'camera');
+});
+heroUploadBtn?.addEventListener('click', () => openForSlot(REQUIRED_SLOT, 'upload'));
+
+// Hero drag/drop
+heroSlot?.addEventListener('dragover', (e) => {
+ e.preventDefault();
+ heroSlot.classList.add('drag');
+});
+heroSlot?.addEventListener('dragleave', () => heroSlot.classList.remove('drag'));
+heroSlot?.addEventListener('drop', (e) => {
+ e.preventDefault();
+ heroSlot.classList.remove('drag');
+ const file = e.dataTransfer?.files?.[0];
+ if (file && isImage(file)) setSlot(REQUIRED_SLOT, file);
+});
+
+// ── Side slots ─────────────────────────────────────────────────────────────
+sideFrames.forEach((frame) => {
const slot = frame.getAttribute('data-slot');
- if (!slot) return;
+ if (!slot || slot === REQUIRED_SLOT) return;
const open = () => {
- if (state.files[slot]) return; // already filled — use retake button to replace
- if (state.method === 'camera') {
- openCamera(slot);
- } else {
- /** @type {HTMLInputElement | null} */ (
- document.querySelector(`input[data-slot-input="${slot}"]`)
- )?.click();
- }
+ if (state.files[slot]) return;
+ openForSlot(slot, state.lastMethod || (cameraSupported ? 'camera' : 'upload'));
};
frame.addEventListener('click', open);
@@ -103,7 +123,6 @@ slotFrames.forEach((frame) => {
}
});
- // Drag + drop
frame.addEventListener('dragover', (e) => {
e.preventDefault();
frame.classList.add('drag');
@@ -117,6 +136,7 @@ slotFrames.forEach((frame) => {
});
});
+// ── File inputs ────────────────────────────────────────────────────────────
slotInputs.forEach((input) => {
input.addEventListener('change', () => {
const slot = input.getAttribute('data-slot-input');
@@ -134,50 +154,67 @@ bodyBtns.forEach((btn) => {
bodyBtns.forEach((b) => b.setAttribute('aria-pressed', String(b === btn)));
});
});
-typeBtns.forEach((btn) => {
+styleBtns.forEach((btn) => {
btn.addEventListener('click', () => {
const val = /** @type {'v1'|'v2'} */ (btn.getAttribute('data-type'));
state.avatarType = val;
- typeBtns.forEach((b) => b.setAttribute('aria-pressed', String(b === btn)));
+ styleBtns.forEach((b) => b.setAttribute('aria-pressed', String(b === btn)));
});
});
+// ── External reset (e.g. "Try again" on the done step) ────────────────────
+document.addEventListener('selfie:reset', () => {
+ ALL_SLOTS.forEach((s) => { state.files[s] = null; });
+ ALL_SLOTS.forEach(renderSlot);
+ updateSubmit();
+});
+
// ── Submit ─────────────────────────────────────────────────────────────────
submitBtn.addEventListener('click', () => {
- if (!allSlotsFilled()) return;
+ if (!state.files[REQUIRED_SLOT]) return;
document.dispatchEvent(
new CustomEvent('selfie:submit', {
detail: {
files: { ...state.files },
bodyType: state.bodyType,
avatarType: state.avatarType,
- method: state.method,
+ method: state.lastMethod || (cameraSupported ? 'camera' : 'upload'),
},
}),
);
- submitBtn.textContent = 'Sending…';
+ submitBtn.innerHTML = '<span class="label">Sending…</span>';
submitBtn.disabled = true;
submitBtn.classList.remove('ready');
});
// ── Step machine ───────────────────────────────────────────────────────────
-/** @returns {'method' | 'capture'} */
-function currentStep() {
- const active = document.querySelector('.step.active');
- return /** @type {'method'|'capture'} */ (active?.getAttribute('data-step') || 'method');
-}
-
-/** @param {'method' | 'capture'} step */
-function goToStep(step) {
- steps.forEach((el) => el.classList.toggle('active', el.getAttribute('data-step') === step));
- if (submitBar) submitBar.hidden = step !== 'capture';
+/** @param {'capture' | 'building' | 'done'} step */
+function showStep(step) {
+ document.querySelectorAll('.step[data-step]').forEach((s) => {
+ s.classList.toggle('active', s.getAttribute('data-step') === step);
+ });
window.scrollTo({ top: 0, behavior: 'instant' in window ? 'instant' : 'auto' });
}
// ── Slot helpers ───────────────────────────────────────────────────────────
/** @param {File} file */
function isImage(file) {
- return /^image\/(jpeg|png)$/i.test(file.type || '');
+ return /^image\/(jpeg|png|webp|heic|heif)$/i.test(file.type || '');
+}
+
+/**
+ * @param {string} slot
+ * @param {'camera' | 'upload'} method
+ */
+function openForSlot(slot, method) {
+ state.lastMethod = method;
+ if (method === 'camera' && cameraSupported) {
+ openCamera(slot);
+ } else {
+ /** @type {HTMLInputElement | null} */ (
+ document.querySelector(`input[data-slot-input="${slot}"]`)
+ )?.click();
+ }
}
/**
@@ -199,23 +236,42 @@ function clearSlot(slot) {
/** @param {string} slot */
function renderSlot(slot) {
+ const isHero = slot === REQUIRED_SLOT;
const frame = /** @type {HTMLElement | null} */ (
- document.querySelector(`.slot-frame[data-slot="${slot}"]`)
+ document.querySelector(
+ isHero ? '.hero-slot[data-slot="frontal"]' : `.slot-frame[data-slot="${slot}"]`,
+ )
);
if (!frame) return;
const file = state.files[slot];
- // Clean up any existing preview / retake artefacts.
+ // Clear any previous error highlight; user has acted.
+ frame.classList.remove('error');
+
+ // Strip prior preview/retake artefacts.
frame.querySelector('img.preview')?.remove();
frame.querySelector('.retake-btn')?.remove();
if (!file) {
frame.classList.remove('filled');
+ // Hero: restore default icon/title/sub if they were hidden via inline style.
+ if (isHero) {
+ frame.querySelectorAll(':scope > .hero-icon, :scope > .hero-title, :scope > .hero-sub').forEach((el) => {
+ el.removeAttribute('style');
+ });
+ }
return;
}
frame.classList.add('filled');
+ // Hide hero defaults when filled.
+ if (isHero) {
+ frame.querySelectorAll(':scope > .hero-icon, :scope > .hero-title, :scope > .hero-sub').forEach((el) => {
+ /** @type {HTMLElement} */ (el).style.display = 'none';
+ });
+ }
+
const img = document.createElement('img');
img.className = 'preview';
img.alt = `${slot} photo preview`;
@@ -236,16 +292,38 @@ function renderSlot(slot) {
frame.appendChild(retake);
}
-function allSlotsFilled() {
- return SLOT_KEYS.every((k) => !!state.files[k]);
-}
-
function updateSubmit() {
- const n = SLOT_KEYS.filter((k) => !!state.files[k]).length;
- submitBtn.textContent = n === 3 ? 'Submit' : `Upload ${n}/3`;
- const ready = n === 3;
- submitBtn.disabled = !ready;
- submitBtn.classList.toggle('ready', ready);
+ const hasRequired = !!state.files[REQUIRED_SLOT];
+ const extras = OPTIONAL_SLOTS.filter((k) => !!state.files[k]).length;
+ const labelEl = submitBtn.querySelector('.label');
+ const metaEl = submitBtn.querySelector('.meta');
+
+ if (!hasRequired) {
+ submitBtn.disabled = true;
+ submitBtn.classList.remove('ready');
+ if (labelEl) labelEl.textContent = 'Add a photo to start';
+ if (metaEl) metaEl.remove();
+ return;
+ }
+
+ const eta = extras === 0 ? ETA_FAST_SEC : ETA_HIGH_SEC;
+ const fidelityNote = extras === 0 ? '~' : extras === 1 ? '+1 angle · ~' : '+2 angles · ~';
+ const labelText = ALL_SLOTS.filter((k) => !!state.files[k]).length === 1
+ ? 'Build my avatar'
+ : 'Build high-fidelity avatar';
+
+ submitBtn.disabled = false;
+ submitBtn.classList.add('ready');
+ if (labelEl) {
+ labelEl.textContent = labelText;
+ }
+ let meta = metaEl;
+ if (!meta) {
+ meta = document.createElement('span');
+ meta.className = 'meta';
+ submitBtn.appendChild(meta);
+ }
+ meta.textContent = `· ${fidelityNote}${eta}s`;
}
// ── Camera overlay ─────────────────────────────────────────────────────────
@@ -255,19 +333,39 @@ const camSlotName = document.getElementById('cam-slot-name');
const camError = document.getElementById('cam-error');
const camActionsLive = document.getElementById('cam-actions-live');
const camActionsReview = document.getElementById('cam-actions-review');
+const camOval = document.getElementById('cam-oval');
+const camHint = document.getElementById('cam-hint');
+const camShutter = /** @type {HTMLButtonElement | null} */ (document.getElementById('cam-shutter'));
+const camCountdown = document.getElementById('cam-countdown');
+const camCountNum = document.getElementById('cam-count-num');
const cam = {
stream: /** @type {MediaStream | null} */ (null),
slot: /** @type {string | null} */ (null),
pendingFile: /** @type {File | null} */ (null),
pendingUrl: /** @type {string | null} */ (null),
+ detector: /** @type {any} */ (null),
+ detectInterval: /** @type {number | null} */ (null),
+ faceLocked: false,
+ countdownTimers: /** @type {number[]} */ ([]),
};
/** @param {string} slot */
async function openCamera(slot) {
if (!camOverlay || !camVideo) return;
cam.slot = slot;
+ cam.faceLocked = false;
if (camSlotName) camSlotName.textContent = slotPretty(slot);
+ if (camHint) {
+ camHint.textContent = slot === REQUIRED_SLOT
+ ? 'Center your face in the oval'
+ : slot === 'left'
+ ? 'Turn ~45° to your left'
+ : 'Turn ~45° to your right';
+ camHint.classList.remove('ok');
+ }
+ camOval?.classList.remove('detected');
+ setShutterEnabled(slot !== REQUIRED_SLOT);
setCamMode('live');
camError?.setAttribute('hidden', '');
camOverlay.classList.add('open');
@@ -281,10 +379,103 @@ async function openCamera(slot) {
} catch (err) {
console.warn('[selfie] camera error:', err);
showCamError('Could not access camera. Check permissions and try again.');
+ setShutterEnabled(true);
+ 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();
+ }
+}
+
+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.
+ setShutterEnabled(true);
+ return;
}
+ try {
+ cam.detector = new FD({ fastMode: true, maxDetectedFaces: 1 });
+ } catch (err) {
+ console.warn('[selfie] FaceDetector init failed:', 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);
+ 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 {
+ setShutterEnabled(false);
+ camOval?.classList.remove('detected');
+ if (camHint) {
+ camHint.textContent = 'No face detected — face the camera';
+ camHint.classList.remove('ok');
+ }
+ }
+}
+
+function stopFaceDetect() {
+ if (cam.detectInterval != null) {
+ clearInterval(cam.detectInterval);
+ cam.detectInterval = null;
+ }
+ cam.detector = null;
+}
+
+/** @param {boolean} on */
+function setShutterEnabled(on) {
+ if (!camShutter) return;
+ if (on) camShutter.removeAttribute('disabled');
+ else camShutter.setAttribute('disabled', '');
}
function closeCamera() {
+ stopFaceDetect();
+ cancelCountdown();
if (cam.stream) {
cam.stream.getTracks().forEach((t) => t.stop());
cam.stream = null;
@@ -293,13 +484,13 @@ function closeCamera() {
camOverlay?.classList.remove('open');
clearPending();
cam.slot = null;
+ cam.faceLocked = false;
}
function clearPending() {
if (cam.pendingUrl) URL.revokeObjectURL(cam.pendingUrl);
cam.pendingUrl = null;
cam.pendingFile = null;
- // Remove any transient preview img in the stage.
document.querySelector('#cam-stage img.preview')?.remove();
}
@@ -308,9 +499,14 @@ function setCamMode(mode) {
if (mode === 'live') {
camActionsLive?.removeAttribute('hidden');
camActionsReview?.setAttribute('hidden', '');
+ // Re-show the oval while shooting.
+ camOval?.removeAttribute('hidden');
+ camHint?.removeAttribute('hidden');
} else {
camActionsLive?.setAttribute('hidden', '');
camActionsReview?.removeAttribute('hidden');
+ camOval?.setAttribute('hidden', '');
+ camHint?.setAttribute('hidden', '');
}
}
@@ -326,15 +522,51 @@ camOverlay?.addEventListener('click', (e) => {
const action = target.closest('[data-cam-action]')?.getAttribute('data-cam-action');
if (!action) return;
if (action === 'cancel') closeCamera();
- else if (action === 'shoot') shoot();
+ else if (action === 'shoot') startCountdown();
else if (action === 'retake') {
clearPending();
setCamMode('live');
+ if (cam.slot === REQUIRED_SLOT) startFaceDetect();
} else if (action === 'use') confirmCamShot();
});
+function startCountdown() {
+ if (camShutter?.hasAttribute('disabled')) return;
+ if (cam.countdownTimers.length) return;
+ setShutterEnabled(false);
+ camOval?.setAttribute('hidden', '');
+ camHint?.setAttribute('hidden', '');
+ const steps = ['3', '2', '1'];
+ camCountdown?.classList.add('show');
+ steps.forEach((s, i) => {
+ const t = window.setTimeout(() => {
+ if (camCountNum) {
+ camCountNum.textContent = s;
+ // retrigger animation by removing/adding
+ camCountNum.style.animation = 'none';
+ void camCountNum.offsetWidth;
+ camCountNum.style.animation = '';
+ }
+ }, i * 950);
+ cam.countdownTimers.push(t);
+ });
+ const fireT = window.setTimeout(() => {
+ camCountdown?.classList.remove('show');
+ shoot();
+ cam.countdownTimers = [];
+ }, steps.length * 950);
+ cam.countdownTimers.push(fireT);
+}
+
+function cancelCountdown() {
+ cam.countdownTimers.forEach((t) => clearTimeout(t));
+ cam.countdownTimers = [];
+ camCountdown?.classList.remove('show');
+}
+
async function shoot() {
if (!camVideo || !cam.stream) return;
+ if (camShutter?.hasAttribute('disabled')) return;
const w = camVideo.videoWidth;
const h = camVideo.videoHeight;
if (!w || !h) return;
@@ -347,6 +579,8 @@ async function shoot() {
// should match what the camera actually sees.
ctx.drawImage(camVideo, 0, 0, w, h);
+ stopFaceDetect();
+
const blob = await new Promise((res) => canvas.toBlob(res, 'image/jpeg', 0.92));
if (!blob) {
showCamError('Snapshot failed. Try again.');
@@ -356,7 +590,6 @@ async function shoot() {
cam.pendingFile = file;
cam.pendingUrl = URL.createObjectURL(file);
- // Show preview over the video feed.
const stage = document.getElementById('cam-stage');
if (stage) {
const img = document.createElement('img');
@@ -379,8 +612,8 @@ function confirmCamShot() {
// ── Utilities ──────────────────────────────────────────────────────────────
/** @param {string} slot */
function slotPretty(slot) {
- if (slot === 'frontal') return 'Frontal';
- if (slot === 'left') return 'Left';
- if (slot === 'right') return 'Right';
+ if (slot === 'frontal') return 'selfie';
+ if (slot === 'left') return 'left angle';
+ if (slot === 'right') return 'right angle';
return slot;
}
diff --git a/src/selfie-pipeline.js b/src/selfie-pipeline.js
index adabc710d..742e3b897 100644
--- a/src/selfie-pipeline.js
+++ b/src/selfie-pipeline.js
@@ -1,24 +1,29 @@
/**
- * Selfie pipeline — bridges the 3-photo capture UI on /create/selfie to the
- * native avatar reconstruction backend.
+ * Selfie pipeline — bridges the capture UI on /create/selfie to the native
+ * avatar reconstruction backend.
*
* Flow:
- * [selfie:submit] → downscale photos → POST /api/avatars/reconstruct
+ * [selfie:submit] → downscale photos (frontal required, sides optional)
+ * → dispatches selfie:preview { dataUrl } so the build view can show the
+ * user's own photo on a placeholder body while the real GLB renders
+ * → POST /api/avatars/reconstruct
* → dispatches selfie:building { jobId }
* → poll /api/avatars/regenerate-status?jobId=…
* → dispatches selfie:progress { label } on each poll tick
* → on { status: 'done', resultAvatarId } → dispatches selfie:done { avatarId }
- * → on { status: 'failed' } or timeout → dispatches selfie:build-error { message }
+ * → on { status: 'failed' } or timeout → dispatches selfie:build-error
+ * { message, slot? } where slot is the photo that likely caused the failure
*/
const SUBMIT_ENDPOINT = '/api/avatars/reconstruct';
const STATUS_ENDPOINT = '/api/avatars/regenerate-status';
-const MAX_DIM = 1024; // downscale so each base64 photo stays well under the 8MB string cap
+const MAX_DIM = 1024;
const JPEG_QUALITY = 0.88;
const POLL_INTERVAL_MS = 3000;
-const POLL_TIMEOUT_MS = 5 * 60 * 1000; // 5 minutes — image-to-3D models take 30-180s
+const POLL_TIMEOUT_MS = 5 * 60 * 1000;
let _building = false;
+let _lastSlotsSent = /** @type {string[]} */ ([]);
document.addEventListener('selfie:submit', (event) => {
const ev = /** @type {CustomEvent} */ (event);
@@ -31,7 +36,10 @@ document.addEventListener('selfie:submit', (event) => {
}
if (_building) {
document.dispatchEvent(new CustomEvent('selfie:build-error', {
- detail: { message: err.userMessage || 'Something went wrong. Try again.' },
+ detail: {
+ message: err.userMessage || 'Something went wrong. Try again.',
+ slot: err.slot || null,
+ },
}));
} else {
setStatus(err.userMessage || 'Something went wrong. Try again.', { error: true });
@@ -50,16 +58,26 @@ document.addEventListener('selfie:submit', (event) => {
*/
async function run(detail) {
_building = false;
- if (!detail?.files?.frontal || !detail.files.left || !detail.files.right) {
- throw withMessage(new Error('missing photos'), 'Please add all 3 photos.');
+ if (!detail?.files?.frontal) {
+ throw withMessage(new Error('missing frontal'), 'Add a front-facing photo to start.', 'frontal');
}
setStatus('Preparing photos…');
- const photos = [
- await fileToDataUrl(detail.files.frontal),
- await fileToDataUrl(detail.files.left),
- await fileToDataUrl(detail.files.right),
- ];
+ const slots = /** @type {const} */ (['frontal', 'left', 'right']);
+ _lastSlotsSent = [];
+ const photos = [];
+ for (const slot of slots) {
+ const file = detail.files[slot];
+ if (!file) continue;
+ photos.push(await fileToDataUrl(file));
+ _lastSlotsSent.push(slot);
+ }
+
+ // Emit the frontal photo immediately for the build view's fast preview —
+ // a real image, mapped to the placeholder body until the engine returns.
+ document.dispatchEvent(new CustomEvent('selfie:preview', {
+ detail: { dataUrl: photos[0] },
+ }));
setStatus('Submitting to avatar engine…');
const submitRes = await fetch(SUBMIT_ENDPOINT, {
@@ -141,6 +159,7 @@ async function pollUntilDone(jobId) {
throw withMessage(
new Error(job.error || 'reconstruct failed'),
friendlyJobError(job.error),
+ inferFailingSlot(job.error),
);
}
}
@@ -171,9 +190,32 @@ function friendlyJobError(raw) {
if (!raw) return 'Avatar reconstruction failed. Try clearer photos in better light.';
const lower = raw.toLowerCase();
if (lower.includes('face') && lower.includes('detect'))
- return 'We could not find a face in one of the photos. Try again with clearer shots.';
- if (lower.includes('nsfw')) return 'Photos were flagged. Try different shots.';
- return 'Avatar reconstruction failed. Try again with clearer photos.';
+ return 'We could not find a face in your front photo. Try a clearer, well-lit shot.';
+ if (lower.includes('nsfw')) return 'Your photo was flagged by content safety. Try a different shot.';
+ if (lower.includes('blur')) return 'Your photo looks blurry. Try again with a sharper shot in better light.';
+ if (lower.includes('timeout')) return 'The engine took too long. Try again in a moment.';
+ return 'Avatar reconstruction failed. Try again with a clearer photo.';
+}
+
+/**
+ * Server errors don't always tell us which photo caused the failure. Use the
+ * order we submitted (frontal first) plus error-text hints to guess so the UI
+ * can flag the right slot for retake. Returns null when there's nothing useful
+ * to infer.
+ * @param {string | null | undefined} raw
+ */
+function inferFailingSlot(raw) {
+ if (!_lastSlotsSent.length) return null;
+ if (!raw) {
+ // No detail — frontal is the most likely culprit and the one the user
+ // definitely supplied.
+ return _lastSlotsSent[0];
+ }
+ const lower = raw.toLowerCase();
+ if (lower.includes('left')) return _lastSlotsSent.includes('left') ? 'left' : null;
+ if (lower.includes('right')) return _lastSlotsSent.includes('right') ? 'right' : null;
+ if (lower.includes('front') || lower.includes('face')) return _lastSlotsSent[0];
+ return _lastSlotsSent[0];
}
function defaultAvatarName() {
@@ -278,9 +320,11 @@ function mapApiError(status, payload) {
/**
* @param {Error} err
* @param {string} userMessage
+ * @param {string | null} [slot]
*/
-function withMessage(err, userMessage) {
+function withMessage(err, userMessage, slot) {
/** @type {any} */ (err).userMessage = userMessage;
+ if (slot) /** @type {any} */ (err).slot = slot;
return err;
}
@@ -296,7 +340,11 @@ let errorBanner = /** @type {HTMLElement | null} */ (null);
/** @param {string} text @param {{ error?: boolean }} [opts] */
function setStatus(text, opts = {}) {
if (submitBtn) {
- submitBtn.textContent = text;
+ const labelEl = submitBtn.querySelector('.label');
+ const metaEl = submitBtn.querySelector('.meta');
+ if (labelEl) labelEl.textContent = text;
+ else submitBtn.textContent = text;
+ if (metaEl) metaEl.remove();
submitBtn.disabled = true;
submitBtn.classList.remove('ready');
}
@@ -320,6 +368,8 @@ function setStatus(text, opts = {}) {
function resetSubmit() {
if (!submitBtn) return;
submitBtn.disabled = false;
- submitBtn.textContent = 'Submit';
submitBtn.classList.add('ready');
+ const labelEl = submitBtn.querySelector('.label');
+ if (labelEl) labelEl.textContent = 'Build my avatar';
+ else submitBtn.textContent = 'Build my avatar';
}
diff --git a/src/viewer.js b/src/viewer.js
index 6f54fedde..6f4ecec4a 100644
--- a/src/viewer.js
+++ b/src/viewer.js
@@ -682,7 +682,7 @@ export class Viewer {
this.invalidate();
}
- load(url, rootPath, assetMap) {
+ load(url, rootPath, assetMap, onProgress) {
const baseURL = LoaderUtils.extractUrlBase(url);
// Load.
@@ -753,7 +753,18 @@ export class Viewer {
resolve(gltf);
},
- undefined,
+ // XHR progress events while the GLB streams down. The `total`
+ // field is only populated when the server sends a
+ // Content-Length header — R2 does, our blob URLs do not.
+ typeof onProgress === 'function'
+ ? (xhr) => {
+ try {
+ onProgress(xhr);
+ } catch (e) {
+ console.warn('[viewer] onProgress threw', e);
+ }
+ }
+ : undefined,
reject,
);
}, reject);
diff --git a/src/widgets/talking-agent.js b/src/widgets/talking-agent.js
index 42c807ef5..acd1f3816 100644
--- a/src/widgets/talking-agent.js
+++ b/src/widgets/talking-agent.js
@@ -35,6 +35,13 @@ export async function mountTalkingAgent(viewer, config, container, ctx) {
const history = [];
let destroyed = false;
+ // Cookieless visitor + thread identity (Vercel AI SDK / Intercom pattern):
+ // visitor_id — long-lived UUID in localStorage, lets the creator see
+ // "this is the same visitor returning across sessions"
+ // thread_id — sessionStorage so a new tab / new visit starts a new
+ // conversation bucket the creator can browse independently
+ const ids = isPreview ? { visitorId: null, threadId: null } : ensureVisitorThread(widgetId);
+
const agent = new NichAgent(container, protocol, null, identity, null, {
layout: 'embedded',
position: config.chatPosition || 'right',
@@ -50,7 +57,7 @@ export async function mountTalkingAgent(viewer, config, container, ctx) {
return { reply: 'Preview mode — save your widget to enable live chat.' };
}
try {
- const result = await dispatchChat(widgetId, text, history.slice(-20));
+ const result = await dispatchChat(widgetId, text, history.slice(-20), ids);
if (result.reply) {
history.push({ role: 'user', content: text });
history.push({ role: 'assistant', content: result.reply });
@@ -78,12 +85,16 @@ export async function mountTalkingAgent(viewer, config, container, ctx) {
// ── SSE round-trip ─────────────────────────────────────────────────────────
-async function dispatchChat(widgetId, message, history) {
+async function dispatchChat(widgetId, message, history, ids) {
+ const body = { message, history };
+ if (ids?.visitorId) body.visitor_id = ids.visitorId;
+ if (ids?.threadId) body.thread_id = ids.threadId;
+
const res = await fetch(`/api/widgets/${encodeURIComponent(widgetId)}/chat`, {
method: 'POST',
credentials: 'include',
headers: { 'content-type': 'application/json', accept: 'text/event-stream' },
- body: JSON.stringify({ message, history }),
+ body: JSON.stringify(body),
});
if (res.status === 429) {
@@ -129,6 +140,52 @@ function parseSse(text) {
return { reply, actions, error };
}
+// ── Visitor + thread identity ──────────────────────────────────────────────
+//
+// localStorage holds a long-lived per-widget UUID — same visitor across tabs
+// and visits. sessionStorage holds the current thread — a fresh tab or a
+// browser restart starts a new bucket so the creator can browse conversations
+// grouped by visit. Both fail gracefully when storage is blocked (private
+// browsing / sandboxed iframes); the server falls back to an anon thread id.
+function ensureVisitorThread(widgetId) {
+ const safeId = String(widgetId || '').replace(/[^A-Za-z0-9_-]/g, '');
+ const vKey = `3dws:visitor:${safeId}`;
+ const tKey = `3dws:thread:${safeId}`;
+
+ let visitorId = null;
+ let threadId = null;
+ try {
+ visitorId = localStorage.getItem(vKey);
+ if (!visitorId) {
+ visitorId = randomId('v_');
+ localStorage.setItem(vKey, visitorId);
+ }
+ } catch {
+ /* localStorage blocked */
+ }
+ try {
+ threadId = sessionStorage.getItem(tKey);
+ if (!threadId) {
+ threadId = randomId('wct_');
+ sessionStorage.setItem(tKey, threadId);
+ }
+ } catch {
+ /* sessionStorage blocked */
+ }
+
+ return { visitorId, threadId };
+}
+
+function randomId(prefix) {
+ const bytes = new Uint8Array(9);
+ (globalThis.crypto || window.crypto)?.getRandomValues?.(bytes);
+ let s = '';
+ for (let i = 0; i < bytes.length; i++) {
+ s += bytes[i].toString(16).padStart(2, '0');
+ }
+ return prefix + s.slice(0, 12);
+}
+
// ── Action dispatch ────────────────────────────────────────────────────────
function runActions(actions, getSceneCtrl, protocol) {
diff --git a/tests/api/avatars-upload-proxy.test.js b/tests/api/avatars-upload-proxy.test.js
new file mode 100644
index 000000000..5c7bda2cb
--- /dev/null
+++ b/tests/api/avatars-upload-proxy.test.js
@@ -0,0 +1,148 @@
+// Smoke tests for the /api/avatars/upload server-side proxy handler.
+//
+// Verifies the new handler in api/avatars/_actions.js — auth gate, content-type
+// validation, body-size limit, checksum-mismatch path, and a happy-path POST
+// that exercises the storage-key namespace and putObject contract. R2, DB,
+// rate-limit, quota, and auth modules are mocked so the test runs offline.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { Readable } from 'node:stream';
+
+vi.mock('../../api/_lib/zauth.js', () => ({ instrument: () => {}, drain: async () => {} }));
+vi.mock('../../api/_lib/sentry.js', () => ({ captureException: () => {} }));
+vi.mock('../../api/_lib/db.js', () => ({ sql: () => Promise.resolve([]) }));
+vi.mock('../../api/_lib/usage.js', () => ({ recordEvent: () => {} }));
+
+vi.mock('../../api/_lib/auth.js', () => ({
+ getSessionUser: async () => ({ id: 'user-test-1' }),
+ authenticateBearer: async () => null,
+ extractBearer: () => null,
+ hasScope: () => true,
+}));
+
+vi.mock('../../api/_lib/rate-limit.js', () => ({
+ limits: {
+ upload: async () => ({ success: true }),
+ avatarPatch: async () => ({ success: true }),
+ },
+ clientIp: () => '127.0.0.1',
+}));
+
+const putObjectMock = vi.fn(async () => undefined);
+vi.mock('../../api/_lib/r2.js', () => ({
+ presignUpload: async ({ key }) => `https://r2.test/upload/${key}?sig=mock`,
+ headObject: async () => null,
+ r2: {},
+ publicUrl: (key) => `https://cdn.test/${key}`,
+ putObject: putObjectMock,
+}));
+
+vi.mock('../../api/_lib/avatars.js', () => ({
+ storageKeyFor: ({ userId, slug }) => `u/${userId}/${slug}/abc123.glb`,
+ enforceQuotas: async () => undefined,
+ searchPublicAvatars: async () => ({ avatars: [], next_cursor: null }),
+ stripOwnerFor: (a) => a,
+ listAvatars: async () => ({ avatars: [], next_cursor: null }),
+ createAvatar: async (input) => ({ id: 'avatar-test', ...input }),
+}));
+
+// Use a real Readable so the handler's req.on('data')/('end') subscription
+// happens before the bytes flow (Node buffers until the consumer attaches).
+function makeReq({ body = Buffer.alloc(0), search = '', headers = {} } = {}) {
+ const stream = body.length ? Readable.from([body]) : Readable.from([]);
+ stream.method = 'POST';
+ stream.url = `/api/avatars/upload${search}`;
+ stream.headers = {
+ 'content-type': 'model/gltf-binary',
+ 'content-length': String(body.length),
+ ...headers,
+ };
+ return stream;
+}
+
+function makeRes() {
+ return {
+ statusCode: 200,
+ _h: {},
+ writableEnded: false,
+ setHeader(k, v) { this._h[k.toLowerCase()] = v; },
+ getHeader(k) { return this._h[k.toLowerCase()]; },
+ end(body) { this._body = body; this.writableEnded = true; },
+ };
+}
+
+async function dispatchUpload(req, res) {
+ const { dispatch } = await import('../../api/avatars/_actions.js');
+ await dispatch('upload', req, res);
+ return { res, body: res._body ? JSON.parse(res._body) : null };
+}
+
+beforeEach(() => {
+ putObjectMock.mockClear();
+});
+
+describe('POST /api/avatars/upload', () => {
+ it('happy path: stores GLB and returns storage_key + checksum', async () => {
+ const glbBytes = Buffer.from('GLB-FAKE-' + 'x'.repeat(128));
+ const { res, body } = await dispatchUpload(makeReq({ body: glbBytes }), makeRes());
+
+ expect(res.statusCode).toBe(200);
+ expect(body.storage_key).toMatch(/^u\/user-test-1\/draft-[a-z0-9]+\/abc123\.glb$/);
+ expect(body.size_bytes).toBe(glbBytes.length);
+ expect(body.content_type).toBe('model/gltf-binary');
+ expect(body.checksum_sha256).toMatch(/^[a-f0-9]{64}$/);
+
+ expect(putObjectMock).toHaveBeenCalledOnce();
+ const [call] = putObjectMock.mock.calls;
+ expect(call[0].body).toEqual(glbBytes);
+ expect(call[0].contentType).toBe('model/gltf-binary');
+ });
+
+ it('rejects empty body with 400 empty_body', async () => {
+ const { res, body } = await dispatchUpload(makeReq({ body: Buffer.alloc(0) }), makeRes());
+ expect(res.statusCode).toBe(400);
+ expect(body.error).toBe('empty_body');
+ expect(putObjectMock).not.toHaveBeenCalled();
+ });
+
+ it('rejects bogus content-type with 415', async () => {
+ const { res, body } = await dispatchUpload(
+ makeReq({ body: Buffer.from('hi'), search: '?content_type=text/plain' }),
+ makeRes(),
+ );
+ expect(res.statusCode).toBe(415);
+ expect(body.error).toBe('unsupported_media_type');
+ });
+
+ it('rejects checksum mismatch with 400', async () => {
+ const glb = Buffer.from('mismatch-bytes');
+ const { res, body } = await dispatchUpload(
+ makeReq({ body: glb, search: '?sha256=deadbeef' + 'a'.repeat(56) }),
+ makeRes(),
+ );
+ expect(res.statusCode).toBe(400);
+ expect(body.error).toBe('checksum_mismatch');
+ expect(putObjectMock).not.toHaveBeenCalled();
+ });
+
+ it('rejects declared content-length above 50 MB with 413', async () => {
+ const { res, body } = await dispatchUpload(
+ makeReq({
+ body: Buffer.from('x'),
+ headers: { 'content-length': String(60 * 1024 * 1024) },
+ }),
+ makeRes(),
+ );
+ expect(res.statusCode).toBe(413);
+ expect(body.error).toBe('payload_too_large');
+ });
+
+ it('honors caller-supplied slug', async () => {
+ const { res, body } = await dispatchUpload(
+ makeReq({ body: Buffer.from('hi'), search: '?slug=my-cool-avatar' }),
+ makeRes(),
+ );
+ expect(res.statusCode).toBe(200);
+ expect(body.storage_key).toBe('u/user-test-1/my-cool-avatar/abc123.glb');
+ });
+});
diff --git a/tests/api/widget-knowledge-helpers.test.js b/tests/api/widget-knowledge-helpers.test.js
new file mode 100644
index 000000000..14363d6b8
--- /dev/null
+++ b/tests/api/widget-knowledge-helpers.test.js
@@ -0,0 +1,119 @@
+// Unit tests for the pure helpers behind the widget-knowledge + transcripts
+// features. No DB, no network — these guarantee the chunker, redactor,
+// cosine + id helpers behave the way the chat/knowledge routes assume.
+
+import { describe, it, expect } from 'vitest';
+
+import { chunk, estimateTokens } from '../../api/_lib/chunker.js';
+import { redactPii } from '../../api/_lib/pii.js';
+import { cosine } from '../../api/_lib/embeddings.js';
+import { shortId, isShortId } from '../../api/_lib/ids.js';
+
+describe('chunker', () => {
+ it('returns one chunk for short text', () => {
+ const out = chunk('hello world');
+ expect(out).toHaveLength(1);
+ expect(out[0].content).toBe('hello world');
+ expect(out[0].token_count).toBeGreaterThan(0);
+ });
+
+ it('produces multiple overlapping chunks for long text', () => {
+ const para = 'Sentence one is here. ' + 'Sentence two follows. '.repeat(400);
+ const out = chunk(para);
+ expect(out.length).toBeGreaterThan(1);
+ // All chunks under ~the 512-token cap (chars / 4 ≈ tokens, with a
+ // little headroom for sentence-boundary slop).
+ for (const c of out) {
+ expect(c.token_count).toBeLessThanOrEqual(640);
+ }
+ });
+
+ it('normalizes runs of whitespace', () => {
+ const out = chunk('a\r\n\r\n\r\nb c\t\td');
+ expect(out[0].content).toMatch(/^a\n\nb c {0,2}d$/);
+ });
+
+ it('returns empty for empty input', () => {
+ expect(chunk('')).toEqual([]);
+ expect(chunk(' ')).toEqual([]);
+ });
+
+ it('estimateTokens scales with length', () => {
+ expect(estimateTokens('abcd'.repeat(100))).toBe(100);
+ expect(estimateTokens('')).toBe(0);
+ });
+});
+
+describe('pii redactor', () => {
+ it('replaces email addresses', () => {
+ const { content, redacted } = redactPii('reach me at [email protected] please');
+ expect(redacted).toBe(true);
+ expect(content).toBe('reach me at [email] please');
+ });
+
+ it('replaces credit card numbers', () => {
+ const { content, redacted } = redactPii('card is 4111 1111 1111 1111 right?');
+ expect(redacted).toBe(true);
+ expect(content).toContain('[card]');
+ });
+
+ it('replaces api keys', () => {
+ const { content, redacted } = redactPii('use sk_live_abc123xyz456 to call');
+ expect(redacted).toBe(true);
+ expect(content).toContain('[key]');
+ });
+
+ it('leaves clean text untouched', () => {
+ const { content, redacted } = redactPii('hello world');
+ expect(redacted).toBe(false);
+ expect(content).toBe('hello world');
+ });
+
+ it('handles null safely', () => {
+ const { content, redacted } = redactPii(null);
+ expect(redacted).toBe(false);
+ expect(content).toBe('');
+ });
+});
+
+describe('cosine similarity', () => {
+ it('returns 1 for identical vectors', () => {
+ const v = [0.1, 0.2, 0.3, 0.4];
+ expect(cosine(v, v)).toBeCloseTo(1, 6);
+ });
+
+ it('returns 0 for orthogonal vectors', () => {
+ expect(cosine([1, 0], [0, 1])).toBe(0);
+ });
+
+ it('returns 0 when either side is zero-length', () => {
+ expect(cosine([0, 0], [1, 1])).toBe(0);
+ expect(cosine([1, 1], [0, 0])).toBe(0);
+ });
+
+ it('handles plain arrays from JSONB and Float64Arrays interchangeably', () => {
+ const a = [1, 2, 3];
+ const b = Float64Array.from([1, 2, 3]);
+ expect(cosine(a, b)).toBeCloseTo(1, 6);
+ });
+});
+
+describe('shortId', () => {
+ it('mints prefixed url-safe ids', () => {
+ const id = shortId('wkd');
+ expect(id.startsWith('wkd_')).toBe(true);
+ expect(isShortId(id, 'wkd')).toBe(true);
+ expect(id).toMatch(/^wkd_[A-Za-z0-9_-]+$/);
+ });
+
+ it('two calls produce different ids', () => {
+ expect(shortId('x')).not.toBe(shortId('x'));
+ });
+
+ it('isShortId rejects mismatched prefixes', () => {
+ const id = shortId('a');
+ expect(isShortId(id, 'b')).toBe(false);
+ expect(isShortId('garbage', 'a')).toBe(false);
+ expect(isShortId(null, 'a')).toBe(false);
+ });
+});
diff --git a/tests/api/widgets.test.js b/tests/api/widgets.test.js
index 07fd7ad31..a60c543ae 100644
--- a/tests/api/widgets.test.js
+++ b/tests/api/widgets.test.js
@@ -46,6 +46,7 @@ vi.mock('../../api/_lib/rate-limit.js', () => ({
limits: {
widgetRead: vi.fn(async () => ({ success: rlState.success })),
widgetWrite: vi.fn(async () => ({ success: rlState.success })),
+ upload: vi.fn(async () => ({ success: rlState.success })),
},
clientIp: () => '127.0.0.1',
}));
@@ -67,6 +68,8 @@ const duplicateHandler = (await import('../../api/widgets/[id]/duplicate.js')).d
const statsHandler = (await import('../../api/widgets/[id]/stats.js')).default;
const viewHandler = (await import('../../api/widgets/view.js')).default;
const ogHandler = (await import('../../api/widgets/og.js')).default;
+const transcriptsHandler = (await import('../../api/widgets/[id]/transcripts.js')).default;
+const knowledgeHandler = (await import('../../api/widgets/[id]/knowledge.js')).default;
const { getAvatar } = await import('../../api/_lib/avatars.js');
@@ -572,3 +575,172 @@ describe('GET /api/widgets/og', () => {
expect(res._body).toContain('HOTSPOT TOUR');
});
});
+
+// ── GET /api/widgets/:id/transcripts ────────────────────────────────────────
+
+describe('GET /api/widgets/:id/transcripts', () => {
+ it('401s without auth', async () => {
+ const req = mockReq({ method: 'GET', url: '/api/widgets/wdgt_x/transcripts?id=wdgt_x' });
+ const res = mockRes();
+ await transcriptsHandler(req, res);
+ expect(res.statusCode).toBe(401);
+ });
+
+ it('404s when the caller does not own the widget', async () => {
+ authState.session = { id: 'user-1' };
+ sqlQueue.push([]); // ownership check returns no rows
+ const req = mockReq({ method: 'GET', url: '/api/widgets/wdgt_x/transcripts?id=wdgt_x' });
+ const res = mockRes();
+ await transcriptsHandler(req, res);
+ expect(res.statusCode).toBe(404);
+ });
+
+ it('returns threads + totals envelope', async () => {
+ authState.session = { id: 'user-1' };
+ sqlQueue.push([{ id: 'wdgt_x' }]); // ownership ok
+ sqlQueue.push([
+ {
+ id: 'wct_a',
+ visitor_id: 'v_abc',
+ referer_host: 'example.com',
+ country: 'US',
+ message_count: 4,
+ started_at: '2026-05-23T00:00:00Z',
+ last_message_at: '2026-05-24T00:00:00Z',
+ preview: 'hello there',
+ user_msgs: 2,
+ },
+ ]);
+ sqlQueue.push([{ total_threads: 1, total_messages: 4, unique_visitors: 1 }]);
+
+ const req = mockReq({ method: 'GET', url: '/api/widgets/wdgt_x/transcripts?id=wdgt_x' });
+ const res = mockRes();
+ await transcriptsHandler(req, res);
+ expect(res.statusCode).toBe(200);
+ const body = parseJson(res);
+ expect(body.threads).toHaveLength(1);
+ expect(body.threads[0].id).toBe('wct_a');
+ expect(body.threads[0].visitor_label).toMatch(/visitor/);
+ expect(body.totals.threads).toBe(1);
+ expect(body.totals.messages).toBe(4);
+ });
+
+ it('returns single thread when thread_id is in the query', async () => {
+ authState.session = { id: 'user-1' };
+ sqlQueue.push([{ id: 'wdgt_x' }]); // ownership ok
+ sqlQueue.push([
+ {
+ id: 'wct_a',
+ visitor_id: 'v_abc',
+ referer_host: null,
+ country: null,
+ message_count: 2,
+ started_at: 't',
+ last_message_at: 't',
+ },
+ ]);
+ sqlQueue.push([
+ { id: 1, role: 'user', content: 'hi', actions: null, provider: null, model: null, redacted: false, created_at: 't' },
+ { id: 2, role: 'assistant', content: 'hello back', actions: [], provider: 'anthropic', model: 'm', redacted: false, created_at: 't' },
+ ]);
+
+ const req = mockReq({
+ method: 'GET',
+ url: '/api/widgets/wdgt_x/transcripts?id=wdgt_x&thread_id=wct_a',
+ });
+ const res = mockRes();
+ await transcriptsHandler(req, res);
+ expect(res.statusCode).toBe(200);
+ const body = parseJson(res);
+ expect(body.thread.id).toBe('wct_a');
+ expect(body.messages).toHaveLength(2);
+ expect(body.messages[1].provider).toBe('anthropic');
+ });
+});
+
+// ── /api/widgets/:id/knowledge ──────────────────────────────────────────────
+
+describe('GET /api/widgets/:id/knowledge', () => {
+ it('401s without auth', async () => {
+ const req = mockReq({ method: 'GET', url: '/api/widgets/wdgt_x/knowledge?id=wdgt_x' });
+ const res = mockRes();
+ await knowledgeHandler(req, res);
+ expect(res.statusCode).toBe(401);
+ });
+
+ it('404s when the caller does not own the widget', async () => {
+ authState.session = { id: 'user-1' };
+ sqlQueue.push([]); // ownership check empty
+ const req = mockReq({ method: 'GET', url: '/api/widgets/wdgt_x/knowledge?id=wdgt_x' });
+ const res = mockRes();
+ await knowledgeHandler(req, res);
+ expect(res.statusCode).toBe(404);
+ });
+
+ it('lists docs for an owned widget', async () => {
+ authState.session = { id: 'user-1' };
+ sqlQueue.push([{ id: 'wdgt_x', type: 'talking-agent' }]); // ownership ok
+ sqlQueue.push([
+ {
+ id: 'wkd_a',
+ title: 'Docs',
+ source_type: 'url',
+ source_url: 'https://example.com',
+ byte_size: 1024,
+ chunk_count: 4,
+ token_count: 800,
+ status: 'ready',
+ error: null,
+ created_at: 't',
+ updated_at: 't',
+ },
+ ]);
+ const req = mockReq({ method: 'GET', url: '/api/widgets/wdgt_x/knowledge?id=wdgt_x' });
+ const res = mockRes();
+ await knowledgeHandler(req, res);
+ expect(res.statusCode).toBe(200);
+ const body = parseJson(res);
+ expect(body.docs).toHaveLength(1);
+ expect(body.docs[0].title).toBe('Docs');
+ });
+});
+
+describe('POST /api/widgets/:id/knowledge', () => {
+ it('rejects non-talking-agent widgets with 400', async () => {
+ authState.session = { id: 'user-1' };
+ sqlQueue.push([{ id: 'wdgt_x', type: 'turntable' }]); // ownership ok but wrong type
+ const req = mockReq({
+ method: 'POST',
+ url: '/api/widgets/wdgt_x/knowledge?id=wdgt_x',
+ body: { source_type: 'text', content: 'hi' },
+ });
+ const res = mockRes();
+ await knowledgeHandler(req, res);
+ expect(res.statusCode).toBe(400);
+ expect(parseJson(res).error).toBe('invalid_widget_type');
+ });
+});
+
+describe('DELETE /api/widgets/:id/knowledge', () => {
+ it('400s without doc_id', async () => {
+ authState.session = { id: 'user-1' };
+ sqlQueue.push([{ id: 'wdgt_x', type: 'talking-agent' }]); // ownership ok
+ const req = mockReq({ method: 'DELETE', url: '/api/widgets/wdgt_x/knowledge?id=wdgt_x' });
+ const res = mockRes();
+ await knowledgeHandler(req, res);
+ expect(res.statusCode).toBe(400);
+ });
+
+ it('404s when the doc is not on the widget', async () => {
+ authState.session = { id: 'user-1' };
+ sqlQueue.push([{ id: 'wdgt_x', type: 'talking-agent' }]); // ownership ok
+ sqlQueue.push([]); // delete returns nothing
+ const req = mockReq({
+ method: 'DELETE',
+ url: '/api/widgets/wdgt_x/knowledge?id=wdgt_x&doc_id=wkd_missing',
+ });
+ const res = mockRes();
+ await knowledgeHandler(req, res);
+ expect(res.statusCode).toBe(404);
+ });
+});
diff --git a/vercel.json b/vercel.json
index e25bbea80..e2ecb063c 100644
--- a/vercel.json
+++ b/vercel.json
@@ -1656,6 +1656,14 @@
"src": "/app-next",
"dest": "/app-next.html"
},
+ {
+ "src": "/embed-demo",
+ "dest": "/embed-demo.html"
+ },
+ {
+ "src": "/embed-demo/",
+ "dest": "/embed-demo.html"
+ },
{
"src": "/chat",
"dest": "/chat/index.html"
diff --git a/vite.config.js b/vite.config.js
index 7598c2a93..2c935ac82 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -119,6 +119,7 @@ const appConfig = {
'footer-bot': resolve(__dirname, 'src/footer-bot.js'),
app: resolve(__dirname, 'pages/app.html'),
'app-demo': resolve(__dirname, 'pages/app-demo.html'),
+ 'app-next': resolve(__dirname, 'pages/app-next.html'),
home: resolve(__dirname, 'pages/home.html'),
'home-v2': resolve(__dirname, 'pages/home-v2.html'),
features: resolve(__dirname, 'pages/features.html'),
@@ -126,6 +127,8 @@ const appConfig = {
tutorial: resolve(__dirname, 'pages/tutorial.html'),
playground: resolve(__dirname, 'pages/playground.html'),
embed: resolve(__dirname, 'pages/embed.html'),
+ 'embed-demo': resolve(__dirname, 'pages/embed-demo.html'),
+ widget: resolve(__dirname, 'pages/widget.html'),
launchpad: resolve(__dirname, 'pages/launchpad.html'),
create: resolve(__dirname, 'pages/create.html'),
'create-selfie': resolve(__dirname, 'pages/create-selfie.html'),
@@ -135,6 +138,8 @@ const appConfig = {
'agent-edit': resolve(__dirname, 'pages/agent-edit.html'),
'agent-embed': resolve(__dirname, 'pages/agent-embed.html'),
'agent-detail': resolve(__dirname, 'pages/agent-detail.html'),
+ 'avatar-embed': resolve(__dirname, 'pages/avatar-embed.html'),
+ handle: resolve(__dirname, 'pages/handle.html'),
'a-embed': resolve(__dirname, 'pages/a-embed.html'),
'a-edit': resolve(__dirname, 'pages/a-edit.html'),
'pump-live': resolve(__dirname, 'pages/pump-live.html'),
@@ -228,6 +233,8 @@ const appConfig = {
const fileMap = {
'/app': resolve(root, 'pages/app.html'),
'/app-demo': resolve(root, 'pages/app-demo.html'),
+ '/widget': resolve(root, 'pages/widget.html'),
+ '/widget/': resolve(root, 'pages/widget.html'),
'/login': resolve(root, 'public/login.html'),
'/deploy': resolve(root, 'pages/app.html'),
'/agents': resolve(root, 'public/agents/index.html'),
@@ -445,6 +452,13 @@ const appConfig = {
// /a/<chainId>/<agentId>/embed or /a/<chainId>/<registry>/<agentId>/embed → iframe viewer
else if (!filePath && /^\/a\/[^/]+(?:\/[^/]+){1,2}\/embed\/?$/.test(path))
filePath = resolve(root, 'pages/a-embed.html');
+ // /embed/avatar → portable avatar embed (?id= / ?model=)
+ // /embed/avatar/:handle → portable avatar embed by handle
+ else if (!filePath && /^\/embed\/avatar(\/[a-z0-9_-]{3,30})?\/?$/i.test(path))
+ filePath = resolve(root, 'pages/avatar-embed.html');
+ // /@<handle> → public live profile page
+ else if (!filePath && /^\/@[a-z0-9_-]{3,30}\/?$/i.test(path))
+ filePath = resolve(root, 'pages/handle.html');
// /a/<chainId>/<agentId> or /a/<chainId>/<registry>/<agentId>
else if (!filePath && /^\/a\/[^/]+(?:\/[^/]+){1,2}\/?$/.test(path))
filePath = resolve(root, 'pages/app.html');
@@ -655,6 +669,41 @@ const appConfig = {
cpSync(src, resolve(__dirname, 'dist/avatar-studio'), { recursive: true });
},
},
+ {
+ // Serve `/api/widgets/wdgt_demo_*` from the local fixture file in dev.
+ // Without this, those requests fall through to the `/api` proxy and hit
+ // production — which may not yet have new demo IDs, so the gallery
+ // renders dead iframes locally even though the fixture exists in source.
+ // Production resolves the same IDs via api/widgets/[id].js → fixtures.
+ name: 'widgets-demo-fixtures',
+ configureServer(server) {
+ server.middlewares.use(async (req, res, next) => {
+ const url = req.url || '';
+ const m = url.match(/^\/api\/widgets\/(wdgt_demo_[A-Za-z0-9_-]+)(?:[?#]|$)/);
+ if (!m) return next();
+ try {
+ const mod = await server.ssrLoadModule(
+ '/api/widgets/_demo-fixtures.js',
+ );
+ const widget = mod.getDemoWidget(m[1]);
+ if (!widget) {
+ res.statusCode = 404;
+ res.setHeader('content-type', 'application/json');
+ res.end(JSON.stringify({ error: 'not_found', message: 'widget not found' }));
+ return;
+ }
+ res.statusCode = 200;
+ res.setHeader('content-type', 'application/json');
+ res.setHeader('cache-control', 'public, max-age=60');
+ res.end(JSON.stringify({ widget }));
+ } catch (err) {
+ res.statusCode = 500;
+ res.setHeader('content-type', 'application/json');
+ res.end(JSON.stringify({ error: 'fixture_load_failed', message: err.message }));
+ }
+ });
+ },
+ },
{
// Serve /avatar-sdk/** in dev from the avatar-sdk/ directory at the repo
// root (Vite's publicDir only covers public/). In production, copy