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.

bugfix + polish: chat shim, pii regex, stats, overlay save, mocap idle, knowledge batch

overstepping6f1b3bc67122
diff --git a/api/_lib/pii.js b/api/_lib/pii.js
index af884986d..6dcb6468f 100644
--- a/api/_lib/pii.js
+++ b/api/_lib/pii.js
@@ -19,10 +19,15 @@ export function redactPii(text) {
let out = String(text ?? '');
let redacted = false;
for (const { token, re } of PATTERNS) {
- if (re.test(out)) {
+ // Reset lastIndex before each use: global regexes are module-level
+ // singletons and .test() advances lastIndex, which could cause a
+ // concurrent call (or a second call in the same tick) to start scanning
+ // from a non-zero offset and miss matches near the start of the string.
+ re.lastIndex = 0;
+ out = out.replace(re, (match) => {
redacted = true;
- out = out.replace(re, token);
- }
+ return token;
+ });
}
return { content: out, redacted };
}
diff --git a/api/_lib/schema.sql b/api/_lib/schema.sql
index 32bcf5e24..55038b86a 100644
--- a/api/_lib/schema.sql
+++ b/api/_lib/schema.sql
@@ -1252,3 +1252,173 @@ CREATE TABLE IF NOT EXISTS agent_payment_intents (
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
expires_at TIMESTAMPTZ NOT NULL
);
+
+-- ── paid_assets — "buy once, re-download forever" 3D-asset catalog ──────────
+-- Mirror of api/_lib/migrations/2026-05-21-paid-assets.sql. Backs the
+-- /api/x402/asset-download endpoint: creators upload a GLB/avatar/accessory
+-- to R2, price it in USDC atomics. Per-row payout overrides let creators
+-- receive USDC directly to their own wallet; NULL falls back to env X402_PAY_TO_*.
+CREATE TABLE IF NOT EXISTS paid_assets (
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
+ slug text NOT NULL UNIQUE,
+ title text NOT NULL,
+ description text NOT NULL,
+ mime_type text NOT NULL,
+ size_bytes bigint NOT NULL,
+ r2_key text NOT NULL,
+ price_atomics text NOT NULL,
+ creator_payto_base text,
+ creator_payto_solana text,
+ creator_payto_bsc text,
+ created_at timestamptz NOT NULL DEFAULT now()
+);
+CREATE INDEX IF NOT EXISTS paid_assets_slug_idx ON paid_assets (slug);
+
+-- ── siwx_payments + siwx_nonces — Sign-In-With-X (CAIP-122) payment history ─
+-- Mirror of api/_lib/migrations/2026-05-21-siwx.sql. A wallet that paid for a
+-- resource can re-access it by signing CAIP-122 instead of re-paying. Stored
+-- addresses follow CAIP-122 payload format exactly (lowercase hex EVM,
+-- base58 Solana); siwx-storage.js normalizes before SELECT/INSERT.
+CREATE TABLE IF NOT EXISTS siwx_payments (
+ resource text NOT NULL,
+ address text NOT NULL,
+ network text NOT NULL,
+ paid_at timestamptz NOT NULL DEFAULT now(),
+ expires_at timestamptz,
+ last_used_at timestamptz,
+ use_count integer NOT NULL DEFAULT 0,
+ PRIMARY KEY (resource, address)
+);
+CREATE INDEX IF NOT EXISTS siwx_payments_expires_idx
+ ON siwx_payments (expires_at) WHERE expires_at IS NOT NULL;
+
+CREATE TABLE IF NOT EXISTS siwx_nonces (
+ nonce text PRIMARY KEY,
+ resource text NOT NULL,
+ address text NOT NULL,
+ used_at timestamptz NOT NULL DEFAULT now()
+);
+CREATE INDEX IF NOT EXISTS siwx_nonces_used_at_idx ON siwx_nonces (used_at);
+
+-- ── x402_subscriptions + x402_access_log — subscription keys + bypass audit ─
+-- Mirror of api/_lib/migrations/2026-05-21-x402-subscriptions.sql. The
+-- installAccessControl() onProtectedRequest hook short-circuits the 402
+-- challenge when a request carries INTERNAL_API_KEY, a subscription key, or
+-- an OAuth bearer with the required scope. Every bypass and abort writes
+-- to x402_access_log so audit dashboards can reconstruct who used what.
+CREATE TABLE IF NOT EXISTS x402_subscriptions (
+ id text PRIMARY KEY,
+ name text NOT NULL,
+ key_hash text NOT NULL UNIQUE,
+ key_prefix text NOT NULL,
+ rate_limit_per_minute integer NOT NULL DEFAULT 60,
+ expires_at timestamptz,
+ revoked_at timestamptz,
+ meta jsonb,
+ created_by uuid REFERENCES users(id) ON DELETE SET NULL,
+ created_at timestamptz NOT NULL DEFAULT now()
+);
+CREATE INDEX IF NOT EXISTS x402_subscriptions_prefix_idx ON x402_subscriptions(key_prefix);
+CREATE INDEX IF NOT EXISTS x402_subscriptions_active_idx ON x402_subscriptions(revoked_at, expires_at);
+
+CREATE TABLE IF NOT EXISTS x402_access_log (
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
+ caller_id text NOT NULL,
+ route text NOT NULL,
+ reason text NOT NULL,
+ granted boolean NOT NULL,
+ meta jsonb,
+ created_at timestamptz NOT NULL DEFAULT now()
+);
+CREATE INDEX IF NOT EXISTS x402_access_log_caller_idx ON x402_access_log(caller_id, created_at desc);
+CREATE INDEX IF NOT EXISTS x402_access_log_route_idx ON x402_access_log(route, created_at desc);
+CREATE INDEX IF NOT EXISTS x402_access_log_created_idx ON x402_access_log(created_at desc);
+
+-- ── club_tips — Pole Club live-tip ledger ───────────────────────────────────
+-- Mirror of api/_lib/migrations/2026-05-22-club-tips.sql. Every settled
+-- /api/x402/dance-tip payment writes one row here; /api/club/tips reads it
+-- for the page boot, /api/club/tips/stream tails for SSE. paid_at/paid_tx
+-- are reserved for the dancer-payouts sweep.
+CREATE TABLE IF NOT EXISTS club_tips (
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
+ ticket_id text NOT NULL UNIQUE,
+ dancer text NOT NULL,
+ dance text NOT NULL,
+ clip text,
+ label text,
+ payer text,
+ network text,
+ amount_atomics numeric,
+ asset text,
+ started_at timestamptz NOT NULL,
+ ends_at timestamptz NOT NULL,
+ paid_at timestamptz,
+ paid_tx text,
+ created_at timestamptz NOT NULL DEFAULT now()
+);
+CREATE INDEX IF NOT EXISTS club_tips_created_at_desc ON club_tips (created_at desc);
+CREATE INDEX IF NOT EXISTS club_tips_dancer_created ON club_tips (dancer, created_at desc);
+
+-- ── club_dancer_wallets + club_payouts — Pole Club payout sweep ─────────────
+-- Mirror of api/_lib/migrations/2026-05-23-club-dancer-wallets.sql. Each row
+-- carries display metadata + two destination addresses (EVM Base 8453, Solana
+-- mainnet) the cron sweep deposits accumulated tips into. /api/cron/club-payouts
+-- is idempotent — re-running only sweeps tips with paid_at IS NULL.
+CREATE TABLE IF NOT EXISTS club_dancer_wallets (
+ dancer text PRIMARY KEY,
+ display_name text NOT NULL,
+ bio text,
+ evm_address text,
+ solana_address text,
+ created_at timestamptz NOT NULL DEFAULT now(),
+ updated_at timestamptz NOT NULL DEFAULT now()
+);
+-- Partial index for the cron filter (unpaid tips grouped by dancer/network/asset).
+CREATE INDEX IF NOT EXISTS club_tips_unpaid_by_dancer_net
+ ON club_tips (dancer, network, asset)
+ WHERE paid_at IS NULL;
+
+CREATE TABLE IF NOT EXISTS club_payouts (
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
+ dancer text NOT NULL REFERENCES club_dancer_wallets(dancer),
+ network text NOT NULL,
+ asset text NOT NULL,
+ amount_atomics numeric NOT NULL,
+ tx text NOT NULL,
+ swept_tip_count integer NOT NULL,
+ created_at timestamptz NOT NULL DEFAULT now()
+);
+CREATE INDEX IF NOT EXISTS club_payouts_dancer_created
+ ON club_payouts (dancer, created_at desc);
+
+-- Seed the four built-in stage slots with display names hard-coded in
+-- /api/x402/dance-tip and src/club.js. Addresses stay NULL until an admin
+-- sets them; the cron logs + skips (dancer, network) pairs where missing.
+INSERT INTO club_dancer_wallets (dancer, display_name) VALUES
+ ('1', 'Nyx'),
+ ('2', 'Ari'),
+ ('3', 'Sable'),
+ ('4', 'Vesper')
+ON CONFLICT (dancer) DO UPDATE
+ SET display_name = excluded.display_name,
+ updated_at = now();
+
+-- ── x402_receipts — durable log of x402 offer-receipt artifacts ─────────────
+-- Mirror of api/_lib/migrations/2026-05-24-x402-receipts.sql. Every successful
+-- paid /api/x402/* call writes one row: the signed receipt we returned in the
+-- SettlementResponse, the resource it covered, the payer wallet, and the chain.
+-- Buyers query their own receipts via /api/x402/my-receipts (buyer-signed gate).
+CREATE TABLE IF NOT EXISTS x402_receipts (
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
+ payer text NOT NULL,
+ network text NOT NULL,
+ resource_url text NOT NULL,
+ format text NOT NULL,
+ receipt jsonb NOT NULL,
+ transaction text,
+ issued_at timestamptz NOT NULL DEFAULT now()
+);
+CREATE INDEX IF NOT EXISTS x402_receipts_payer_issued
+ ON x402_receipts (payer, issued_at desc);
+CREATE INDEX IF NOT EXISTS x402_receipts_resource_issued
+ ON x402_receipts (resource_url, issued_at desc);
diff --git a/api/agents/onchain/[action].js b/api/agents/onchain/[action].js
index fbbba7e2f..83e336f55 100644
--- a/api/agents/onchain/[action].js
+++ b/api/agents/onchain/[action].js
@@ -20,16 +20,18 @@ import {
} from '@metaplex-foundation/umi';
import { Connection } from '@solana/web3.js';
import { JsonRpcProvider } from 'ethers';
-import { createHash } from 'crypto';
import { PutObjectCommand } from '@aws-sdk/client-s3';
+import { CID } from 'multiformats/cid';
+import * as raw from 'multiformats/codecs/raw';
+import { sha256 } from 'multiformats/hashes/sha2';
import { sql } from '../../_lib/db.js';
import { getSessionUser } from '../../_lib/auth.js';
import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';
import { limits, clientIp } from '../../_lib/rate-limit.js';
import { parse } from '../../_lib/validate.js';
import { randomToken } from '../../_lib/crypto.js';
+import { r2, publicUrl } from '../../_lib/r2.js';
import { env } from '../../_lib/env.js';
-import { r2 } from '../../_lib/r2.js';
export default wrap(async (req, res) => {
const action = req.query?.action;
@@ -84,6 +86,12 @@ const prepBodySchema = z.object({
.optional(),
});
+// Pin a manifest. Try web3.storage first for true IPFS pinning. If unavailable,
+// fall back to R2: compute the real CIDv1 (raw codec, sha2-256 multihash) from
+// the bytes so the cid is verifiable IPFS content-addressing, and return the
+// R2 HTTPS URL as the resolvable location. The on-chain registry accepts both
+// ipfs:// and https:// URIs (see src/erc8004/resolver.js), so a real https URL
+// is a first-class result — never a stub.
async function pinManifest(manifest) {
const bytes = Buffer.from(JSON.stringify(manifest), 'utf-8');
const token = process.env.WEB3_STORAGE_TOKEN;
@@ -98,15 +106,18 @@ async function pinManifest(manifest) {
const data = await r.json();
if (data.cid) return { cid: data.cid, uri: `ipfs://${data.cid}` };
}
+ console.warn('[onchain/prep] web3.storage returned', r.status);
} catch (e) {
console.warn('[onchain/prep] web3.storage pin failed:', e.message);
}
}
- // Deterministic fallback: stash to R2, generate a content-hash CID stub
- // so the URL stays pointing at real bytes even if web3.storage is down.
- const hash = createHash('sha256').update(bytes).digest('hex');
- const stubCid = `bafkreigenerated${hash.slice(0, 40)}`;
- const key = `agent-manifests/${Date.now()}-${Math.random().toString(36).slice(2)}.json`;
+ // R2-backed fallback: compute the real raw-codec CIDv1 so the bytes are
+ // verifiable via IPFS gateways (any gateway that supports raw codec can
+ // resolve the same bytes if someone later pins them), but the returned
+ // `uri` is the HTTPS R2 URL — real, resolvable, no stub.
+ const digest = await sha256.digest(bytes);
+ const cid = CID.create(1, raw.code, digest).toString();
+ const key = `agent-manifests/${Date.now()}-${randomToken(8)}.json`;
await r2.send(
new PutObjectCommand({
Bucket: env.S3_BUCKET,
@@ -115,7 +126,7 @@ async function pinManifest(manifest) {
ContentType: 'application/json',
}),
);
- return { cid: stubCid, uri: `ipfs://${stubCid}` };
+ return { cid, uri: publicUrl(key) };
}
function buildManifest({ name, description, avatar_id, skills }) {
diff --git a/api/avatars/_actions.js b/api/avatars/_actions.js
index ded68aaf3..55491cf3e 100644
--- a/api/avatars/_actions.js
+++ b/api/avatars/_actions.js
@@ -21,7 +21,7 @@ import { randomUUID } from 'crypto';
// Cached per-process after first load.
//
// Provider name precedence:
-// 1. Explicit env: AVATAR_REGEN_PROVIDER=replicate|gcp|stub
+// 1. Explicit env: AVATAR_REGEN_PROVIDER=replicate|huggingface|gcp
// 2. Inferred from credentials: if REPLICATE_API_TOKEN is set with no
// explicit provider, default to 'replicate'. Same for GCP_RECONSTRUCTION_URL.
// This keeps the deploy path 1-step: drop the token in env, ship.
@@ -44,11 +44,6 @@ async function getRegenProvider() {
if (_regenProviderCache && _regenProviderName === name) {
return { name, instance: _regenProviderCache };
}
- if (name === 'stub') {
- _regenProviderCache = null;
- _regenProviderName = name;
- return { name, instance: null };
- }
if (name === 'replicate') {
const mod = await import('../_providers/replicate.js');
_regenProviderCache = mod.createRegenProvider();
@@ -297,21 +292,10 @@ const handleRegenerate = wrap(async (req, res) => {
res,
501,
'regen_unconfigured',
- 'Avatar regeneration is not yet wired to an ML backend. Set AVATAR_REGEN_PROVIDER env var.',
+ 'Avatar regeneration requires a configured backend. Set AVATAR_REGEN_PROVIDER and the matching API token (REPLICATE_API_TOKEN, HF_TOKEN, or GCP_RECONSTRUCTION_URL).',
);
}
- if (provider.name === 'stub') {
- const jobId = `stub-${randomUUID()}`;
- await sql`
- insert into avatar_regen_jobs
- (job_id, user_id, source_avatar_id, mode, params, status, provider, created_at, updated_at)
- values
- (${jobId}, ${userId}, ${body.sourceAvatarId}, ${body.mode}, ${JSON.stringify(body.params ?? {})}, 'queued', 'stub', now(), now())
- `;
- return json(res, 202, { ok: true, jobId, status: 'queued', eta: null });
- }
-
// Real provider — submit the job, persist the external id.
const sourceUrl = publicUrl(rows[0].storage_key);
let submission;
@@ -375,7 +359,7 @@ const handleRegenerateStatus = wrap(async (req, res) => {
// Pull a fresh status from the provider when the job is still in flight
// and we have an external id to query. The status endpoint serves as our
// poll trigger — no separate cron needed for short-lived jobs.
- if ((job.status === 'queued' || job.status === 'running') && job.provider && job.provider !== 'stub' && job.ext_job_id) {
+ if ((job.status === 'queued' || job.status === 'running') && job.provider && job.ext_job_id) {
try {
const provider = await getRegenProvider();
if (provider.instance) {
@@ -738,7 +722,7 @@ const handleReconstruct = wrap(async (req, res) => {
res,
501,
'regen_unconfigured',
- 'Avatar reconstruction is not yet wired to an ML backend. Set AVATAR_REGEN_PROVIDER env var.',
+ 'Avatar reconstruction requires a configured backend. Set AVATAR_REGEN_PROVIDER and the matching API token (REPLICATE_API_TOKEN, HF_TOKEN, or GCP_RECONSTRUCTION_URL).',
);
}
diff --git a/api/widgets/[id]/_knowledge.js b/api/widgets/[id]/_knowledge.js
index b4caa21f2..2f7ac7047 100644
--- a/api/widgets/[id]/_knowledge.js
+++ b/api/widgets/[id]/_knowledge.js
@@ -208,16 +208,17 @@ export async function ingestKnowledge({ widgetId, userId, input }) {
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 inserts = slice.map((c, j) => {
const vec = Array.from(embedded[j]);
- await sql`
+ return 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})
+ (${docId}, ${widgetId}, ${i + j}, ${c.content},
+ ${JSON.stringify(vec)}::jsonb, ${c.token_count})
`;
- }
+ });
+ await sql.transaction(inserts);
}
await sql`update widget_knowledge_docs set status = 'ready' where id = ${docId}`;
} catch (err) {
diff --git a/api/widgets/[id]/chat.js b/api/widgets/[id]/chat.js
new file mode 100644
index 000000000..e6fa31dc5
--- /dev/null
+++ b/api/widgets/[id]/chat.js
@@ -0,0 +1,10 @@
+// Route entry for /api/widgets/:id/chat — Vercel resolves to this file
+// via the rewrite in vercel.json. Delegates to the action dispatcher so all
+// chat logic lives in one place ([action].js → handleChat).
+
+import dispatcher from './[action].js';
+
+export default function handler(req, res) {
+ req.query = { ...(req.query || {}), action: 'chat' };
+ return dispatcher(req, res);
+}
diff --git a/api/widgets/[id]/stats.js b/api/widgets/[id]/stats.js
index 424843acb..69ae5b871 100644
--- a/api/widgets/[id]/stats.js
+++ b/api/widgets/[id]/stats.js
@@ -1,68 +1,10 @@
-/**
- * Widget stats — GET /api/widgets/:id/stats
- * Owner-only analytics: view counts, referrers, countries, last viewed.
- */
+// Route entry for /api/widgets/:id/stats — Vercel resolves to this file
+// via the rewrite in vercel.json. Delegates to the action dispatcher so all
+// stats logic lives in one place ([action].js → handleStats).
-import { sql } from '../../_lib/db.js';
-import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../../_lib/auth.js';
-import { cors, error, json, method, wrap } from '../../_lib/http.js';
-import { limits, clientIp } from '../../_lib/rate-limit.js';
+import dispatcher from './[action].js';
-async function resolveAuth(req) {
- const session = await getSessionUser(req);
- if (session) {
- return { userId: session.id, source: 'session', scope: 'avatars:read avatars:write' };
- }
- return authenticateBearer(extractBearer(req));
+export default function handler(req, res) {
+ req.query = { ...(req.query || {}), action: 'stats' };
+ return dispatcher(req, res);
}
-
-export default wrap(async (req, res) => {
- if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
- if (!method(req, res, ['GET'])) return;
-
- const auth = await resolveAuth(req);
- if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
- if (!hasScope(auth.scope, 'avatars:read')) return error(res, 403, 'insufficient_scope', 'avatars:read required');
-
- const rl = await limits.widgetRead(clientIp(req));
- if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
-
- const url = new URL(req.url, 'http://x');
- const parts = url.pathname.split('/').filter(Boolean);
- const id = url.searchParams.get('id') || parts[2];
-
- const [widget] = await sql`
- SELECT id, type, view_count FROM widgets
- WHERE id = ${id} AND user_id = ${auth.userId} AND deleted_at IS NULL
- `;
- if (!widget) return error(res, 404, 'not_found', 'widget not found');
-
- // Build 8-day window (today + 7 days back)
- const today = new Date();
- const days = Array.from({ length: 8 }, (_, i) => {
- const d = new Date(today);
- d.setDate(d.getDate() - (7 - i));
- return d.toISOString().slice(0, 10);
- });
-
- const [recentRows, refererRows, countryRows, lastViewedRow] = await Promise.all([
- sql`SELECT date::text, count::int FROM widget_views WHERE widget_id = ${id} AND date >= NOW() - INTERVAL '7 days' ORDER BY date`.catch(() => []),
- sql`SELECT referer, count::int FROM widget_referers WHERE widget_id = ${id} ORDER BY count DESC LIMIT 10`.catch(() => []),
- sql`SELECT country, count::int FROM widget_countries WHERE widget_id = ${id} ORDER BY count DESC LIMIT 10`.catch(() => []),
- sql`SELECT MAX(viewed_at) AS last_viewed FROM widget_view_log WHERE widget_id = ${id}`.catch(() => []),
- ]);
-
- const viewMap = Object.fromEntries((recentRows || []).map(r => [r.date, r.count]));
- const recent_views_7d = days.map(date => ({ date, count: viewMap[date] ?? 0 }));
-
- return json(res, 200, {
- stats: {
- view_count: widget.view_count ?? 0,
- recent_views_7d,
- top_referers: refererRows || [],
- top_countries: countryRows || [],
- last_viewed_at: lastViewedRow?.[0]?.last_viewed ?? null,
- chat_count: null,
- },
- });
-});
diff --git a/docs/widget-studio.md b/docs/widget-studio.md
index eaed39411..b9cddca1c 100644
--- a/docs/widget-studio.md
+++ b/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%"
@@ -240,6 +240,7 @@ You can override these freely in the iframe `width` and `height` attributes. Add
## Next steps
+- [Widget API (JSON-RPC)](./widget-api.md) — programmatic control over an embedded widget: camera, animation, screenshots, model loading
- [Widgets reference](./widgets.md) — technical details, postMessage API, CSP config, and oEmbed spec
- [Web component](./web-component.md) — the `<agent-3d>` custom element for developer integrations
- [Embedding guide](./embedding.md) — advanced embedding patterns and iframe options
diff --git a/docs/widgets.md b/docs/widgets.md
index d69eb9ae9..a12c42378 100644
--- a/docs/widgets.md
+++ b/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.
---
@@ -496,3 +496,9 @@ Each widget load records one minimal analytics event:
| `created_at` | Timestamp |
No IP addresses, no user-agent strings, no cookies, no chat message content. The widget owner can see aggregated view counts in their [Dashboard](https://three.ws/dashboard).
+
+---
+
+## Programmatic control
+
+Need to drive a widget from the parent page — change the camera, play an animation, grab a screenshot? See the [Widget API (JSON-RPC)](./widget-api.md) reference. The `ThreeWidget` SDK lives at `/widget-client.js` and works with any iframe pointing at `/widget`.
diff --git a/examples/widget-rpc.html b/examples/widget-rpc.html
new file mode 100644
index 000000000..d34d4eec9
--- /dev/null
+++ b/examples/widget-rpc.html
@@ -0,0 +1,271 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="utf-8" />
+ <title>three.ws widget — JSON-RPC example</title>
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
+ <style>
+ * {
+ box-sizing: border-box;
+ }
+ body {
+ margin: 0;
+ padding: 24px;
+ background: #0a0a0f;
+ color: #e8e8e8;
+ font-family: 'Inter', system-ui, -apple-system, sans-serif;
+ display: grid;
+ grid-template-columns: 600px 1fr;
+ gap: 32px;
+ min-height: 100vh;
+ }
+ h1 {
+ margin: 0 0 8px;
+ font-weight: 600;
+ font-size: 1.25rem;
+ }
+ .muted {
+ color: #8a8a96;
+ font-size: 0.85rem;
+ margin: 0 0 16px;
+ }
+ .frame {
+ border: 1px solid #2a2a36;
+ border-radius: 16px;
+ overflow: hidden;
+ background: #0c0c12;
+ }
+ iframe {
+ display: block;
+ width: 600px;
+ height: 600px;
+ border: 0;
+ }
+ .panel {
+ display: flex;
+ flex-direction: column;
+ gap: 14px;
+ }
+ .actions {
+ display: grid;
+ grid-template-columns: repeat(2, 1fr);
+ gap: 10px;
+ }
+ button {
+ background: #1b1b26;
+ color: #eee;
+ border: 1px solid #2a2a36;
+ border-radius: 10px;
+ padding: 12px 14px;
+ font: 500 13px/1.2 inherit;
+ cursor: pointer;
+ transition: border-color 0.15s ease;
+ }
+ button:hover {
+ border-color: #5a5a6c;
+ }
+ button:disabled {
+ opacity: 0.5;
+ cursor: not-allowed;
+ }
+ pre {
+ background: #11111a;
+ border: 1px solid #2a2a36;
+ border-radius: 10px;
+ padding: 14px;
+ font-size: 12px;
+ color: #c5c5d0;
+ overflow: auto;
+ max-height: 360px;
+ margin: 0;
+ }
+ .row {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ }
+ .row input {
+ flex: 1;
+ background: #11111a;
+ color: #eee;
+ border: 1px solid #2a2a36;
+ border-radius: 8px;
+ padding: 10px 12px;
+ font: 400 13px/1.2 inherit;
+ }
+ img.snapshot {
+ max-width: 100%;
+ border-radius: 10px;
+ border: 1px solid #2a2a36;
+ }
+ .status {
+ font-size: 12px;
+ color: #8a8a96;
+ }
+ .status.ready {
+ color: #4ade80;
+ }
+ .status.error {
+ color: #f87171;
+ }
+ </style>
+ </head>
+ <body>
+ <div class="frame">
+ <iframe
+ id="agent"
+ title="three.ws widget"
+ src=""
+ ></iframe>
+ </div>
+
+ <div class="panel">
+ <div>
+ <h1>three.ws widget — JSON-RPC API</h1>
+ <p class="muted">
+ This page loads <code>/widget</code> in the iframe and drives it through the
+ <code>ThreeWidget</code> SDK. Open the source — it's ~70 lines, no build step.
+ </p>
+ <p class="status" id="status">connecting…</p>
+ </div>
+
+ <div class="actions">
+ <button id="btn-rotate">camera.setLookAt (rotate 90°)</button>
+ <button id="btn-recenter">camera.recenter</button>
+ <button id="btn-bg">viewer.setBackground (random)</button>
+ <button id="btn-env">viewer.setEnvironment</button>
+ <button id="btn-rotate-toggle">toggle auto-rotate</button>
+ <button id="btn-screenshot">screenshot.capture</button>
+ <button id="btn-list-anim">animation.list</button>
+ <button id="btn-play-wave">animation.play (av-waving)</button>
+ </div>
+
+ <div class="row">
+ <input
+ id="model-url"
+ type="text"
+ value="/avatars/cz.glb"
+ spellcheck="false"
+ />
+ <button id="btn-load">model.load</button>
+ </div>
+
+ <pre id="log">// click any button to call the widget over JSON-RPC</pre>
+
+ <img id="snap" class="snapshot" hidden alt="latest screenshot" />
+ </div>
+
+ <script>
+ // Derive the widget origin from the iframe src so this example works
+ // on any host (localhost dev, production, branch preview).
+ (function () {
+ var origin = location.origin;
+ document.getElementById('agent').src =
+ origin + '/widget#model=' + encodeURIComponent('/avatars/cz.glb') + '&kiosk=true';
+
+ var clientScript = document.createElement('script');
+ clientScript.src = origin + '/widget-client.js';
+ clientScript.onload = boot;
+ document.head.appendChild(clientScript);
+ })();
+
+ function boot() {
+ var iframe = document.getElementById('agent');
+ var statusEl = document.getElementById('status');
+ var logEl = document.getElementById('log');
+ var snapEl = document.getElementById('snap');
+ var rotateOn = true;
+
+ var client = ThreeWidget.attach(iframe);
+
+ function log(label, value) {
+ var head = '→ ' + label + (value !== undefined ? ': ' + JSON.stringify(value, null, 2) : '');
+ logEl.textContent = head + '\n\n' + logEl.textContent;
+ }
+
+ function setStatus(text, kind) {
+ statusEl.textContent = text;
+ statusEl.className = 'status' + (kind ? ' ' + kind : '');
+ }
+
+ client.on('viewer.ready', function () {
+ setStatus('widget ready (sdk ' + ThreeWidget.sdkVersion + ', rpc ' + ThreeWidget.rpcVersion + ')', 'ready');
+ });
+ client.on('model.loaded', function (p) {
+ log('event model.loaded', p);
+ });
+ client.on('widget.revealed', function (p) {
+ log('event widget.revealed', p);
+ });
+
+ client
+ .ready(20000)
+ .then(function () {
+ setStatus('widget ready (sdk ' + ThreeWidget.sdkVersion + ', rpc ' + ThreeWidget.rpcVersion + ')', 'ready');
+ })
+ .catch(function (err) {
+ setStatus('failed: ' + err.message, 'error');
+ });
+
+ function rpc(method, params, label) {
+ client.call(method, params, 10000).then(
+ function (result) { log(label || method, result); },
+ function (err) { log(label || method + ' (error)', { code: err.code, message: err.message }); },
+ );
+ }
+
+ document.getElementById('btn-rotate').onclick = function () {
+ var t = performance.now() / 1000;
+ var r = 3, h = 1.4;
+ rpc('camera.setLookAt', {
+ eye: [Math.sin(t) * r, h, Math.cos(t) * r],
+ target: [0, 1, 0],
+ duration: 1.2,
+ });
+ };
+ document.getElementById('btn-recenter').onclick = function () {
+ rpc('camera.recenter', { duration: 0.8 });
+ };
+ document.getElementById('btn-bg').onclick = function () {
+ var hex = '#' + Math.floor(Math.random() * 0xffffff).toString(16).padStart(6, '0');
+ rpc('viewer.setBackground', { color: hex }, 'viewer.setBackground (' + hex + ')');
+ };
+ document.getElementById('btn-env').onclick = function () {
+ var presets = ['neutral', 'venice-sunset', 'footprint-court'];
+ var p = presets[Math.floor(Math.random() * presets.length)];
+ rpc('viewer.setEnvironment', { preset: p }, 'viewer.setEnvironment (' + p + ')');
+ };
+ document.getElementById('btn-rotate-toggle').onclick = function () {
+ rotateOn = !rotateOn;
+ rpc('viewer.setAutoRotate', { enabled: rotateOn }, 'viewer.setAutoRotate (' + rotateOn + ')');
+ };
+ document.getElementById('btn-screenshot').onclick = function () {
+ client.call('screenshot.capture').then(
+ function (result) {
+ snapEl.src = result.dataUrl;
+ snapEl.hidden = false;
+ log('screenshot.capture', { dataUrlLength: result.dataUrl.length });
+ },
+ function (err) { log('screenshot.capture (error)', { message: err.message }); },
+ );
+ };
+ document.getElementById('btn-list-anim').onclick = function () {
+ client.call('animation.list').then(
+ function (result) {
+ log('animation.list', { clipCount: result.clips.length, first5: result.clips.slice(0, 5) });
+ },
+ function (err) { log('animation.list (error)', { message: err.message }); },
+ );
+ };
+ document.getElementById('btn-play-wave').onclick = function () {
+ rpc('animation.play', { name: 'av-waving', loop: true });
+ };
+ document.getElementById('btn-load').onclick = function () {
+ var url = document.getElementById('model-url').value.trim();
+ if (!url) return;
+ rpc('model.load', { url: url }, 'model.load (' + url + ')');
+ };
+ }
+ </script>
+ </body>
+</html>
diff --git a/pages/avatar-edit.html b/pages/avatar-edit.html
index 079ff3092..fd83d096e 100644
--- a/pages/avatar-edit.html
+++ b/pages/avatar-edit.html
@@ -493,6 +493,85 @@
font-variant-numeric: tabular-nums;
}
+ /* ── Blend wheel ────────────────────────────────────────── */
+ .ae-blend-group > .ae-blend-body {
+ padding: 16px 14px 14px;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 10px;
+ }
+ .ae-blend-canvas {
+ position: relative;
+ width: 220px;
+ height: 220px;
+ border: 1px solid var(--border-2);
+ border-radius: 50%;
+ background: radial-gradient(
+ circle at 50% 50%,
+ rgba(125, 211, 252, 0.04) 0%,
+ rgba(255, 255, 255, 0.015) 60%,
+ transparent 100%
+ );
+ cursor: crosshair;
+ flex-shrink: 0;
+ outline: none;
+ }
+ .ae-blend-canvas::before,
+ .ae-blend-canvas::after {
+ content: '';
+ position: absolute;
+ background: rgba(255, 255, 255, 0.07);
+ pointer-events: none;
+ }
+ .ae-blend-canvas::before {
+ left: 0; right: 0;
+ top: 50%; height: 1px;
+ transform: translateY(-50%);
+ }
+ .ae-blend-canvas::after {
+ top: 0; bottom: 0;
+ left: 50%; width: 1px;
+ transform: translateX(-50%);
+ }
+ .ae-blend-canvas:focus-visible {
+ box-shadow: 0 0 0 2px var(--accent);
+ }
+ .ae-blend-label {
+ position: absolute;
+ transform: translate(-50%, -50%);
+ font-size: 9px;
+ font-weight: 600;
+ color: rgba(255, 255, 255, 0.45);
+ letter-spacing: 0.07em;
+ text-transform: uppercase;
+ white-space: nowrap;
+ pointer-events: none;
+ user-select: none;
+ }
+ .ae-blend-puck {
+ position: absolute;
+ left: 50%; top: 50%;
+ width: 20px;
+ height: 20px;
+ border-radius: 50%;
+ background: var(--accent, #7dd3fc);
+ box-shadow: 0 0 0 3px rgba(125, 211, 252, 0.25), 0 2px 8px rgba(0,0,0,0.5);
+ transform: translate(-50%, -50%);
+ cursor: grab;
+ touch-action: none;
+ z-index: 2;
+ transition: box-shadow 0.12s;
+ }
+ .ae-blend-puck:active { cursor: grabbing; box-shadow: 0 0 0 5px rgba(125, 211, 252, 0.35), 0 3px 12px rgba(0,0,0,0.6); }
+ .ae-blend-desc {
+ font-size: 11px;
+ color: var(--text-3);
+ text-align: center;
+ margin: 0;
+ min-height: 16px;
+ }
+
/* ── Face capture modal ─────────────────────────────────── */
.ae-face-backdrop {
position: fixed;
diff --git a/pages/create.html b/pages/create.html
index 45fcb9bc9..b22523e3c 100644
--- a/pages/create.html
+++ b/pages/create.html
@@ -893,6 +893,8 @@
<p class="card-tooltip">
Need a model? Build one in
<a href="/studio">three.ws Studio</a>.
+ Coming from Ready Player Me?
+ <a href="/import/rpm">Import your RPM avatar</a>.
</p>
</div>
</div>
diff --git a/pages/import-rpm.html b/pages/import-rpm.html
new file mode 100644
index 000000000..2cbaaeb72
--- /dev/null
+++ b/pages/import-rpm.html
@@ -0,0 +1,672 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="utf-8" />
+ <title>Import RPM Avatar · three.ws</title>
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <meta
+ name="description"
+ content="Import your Ready Player Me avatar into three.ws. Paste your GLB URL or upload the file directly."
+ />
+ <meta name="robots" content="noindex" />
+ <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png" />
+ <style>
+ *, *::before, *::after { box-sizing: border-box; }
+ :root {
+ --bg: #0b0d10;
+ --panel: #12151a;
+ --panel-2: #181c22;
+ --border: rgba(255,255,255,0.07);
+ --border-2: rgba(255,255,255,0.13);
+ --text: #e9ecef;
+ --text-2: rgba(255,255,255,0.65);
+ --text-3: rgba(255,255,255,0.38);
+ --accent: #7dd3fc;
+ --accent-dim: rgba(125,211,252,0.12);
+ --warn: #f59e0b;
+ --warn-dim: rgba(245,158,11,0.10);
+ --ok: #4ade80;
+ --err: #f87171;
+ --err-dim: rgba(248,113,113,0.10);
+ --radius: 12px;
+ }
+ html, body {
+ margin: 0; padding: 0;
+ background: var(--bg);
+ color: var(--text);
+ font-family: system-ui, -apple-system, sans-serif;
+ font-size: 15px;
+ line-height: 1.55;
+ min-height: 100vh;
+ }
+ a { color: var(--accent); }
+ code {
+ font-family: ui-monospace, 'SF Mono', monospace;
+ font-size: 0.9em;
+ color: var(--text-2);
+ background: rgba(255,255,255,0.05);
+ padding: 1px 5px;
+ border-radius: 4px;
+ }
+
+ /* ── Layout ─────────────────────────────────────────────────── */
+ .page {
+ max-width: 640px;
+ margin: 0 auto;
+ padding: 48px 20px 80px;
+ }
+ .back-link {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ color: var(--text-3);
+ text-decoration: none;
+ font-size: 13px;
+ margin-bottom: 32px;
+ letter-spacing: 0.01em;
+ }
+ .back-link:hover { color: var(--text-2); }
+ h1 {
+ font-size: 26px;
+ font-weight: 700;
+ letter-spacing: -0.02em;
+ margin: 0 0 6px;
+ }
+ .lede {
+ color: var(--text-2);
+ margin: 0 0 28px;
+ font-size: 14px;
+ line-height: 1.6;
+ }
+
+ /* ── Warning banner ─────────────────────────────────────────── */
+ .warn-banner {
+ display: flex;
+ gap: 12px;
+ align-items: flex-start;
+ background: var(--warn-dim);
+ border: 1px solid rgba(245,158,11,0.22);
+ border-radius: var(--radius);
+ padding: 14px 16px;
+ margin-bottom: 24px;
+ font-size: 13px;
+ color: var(--text-2);
+ line-height: 1.5;
+ }
+ .warn-banner-icon { font-size: 16px; flex-shrink: 0; margin-top: 1px; }
+
+ /* ── Import card ────────────────────────────────────────────── */
+ .import-card {
+ background: var(--panel);
+ border: 1px solid var(--border-2);
+ border-radius: var(--radius);
+ overflow: hidden;
+ }
+
+ /* Tab switcher */
+ .tab-bar {
+ display: flex;
+ border-bottom: 1px solid var(--border);
+ }
+ .tab-btn {
+ flex: 1;
+ padding: 13px 14px;
+ background: none;
+ border: none;
+ border-bottom: 2px solid transparent;
+ color: var(--text-3);
+ font: inherit;
+ font-size: 13px;
+ font-weight: 500;
+ cursor: pointer;
+ letter-spacing: 0.02em;
+ text-align: center;
+ transition: color 0.15s, border-color 0.15s;
+ margin-bottom: -1px;
+ }
+ .tab-btn:hover { color: var(--text-2); }
+ .tab-btn.active { color: var(--accent); border-bottom-color: var(--accent); }
+
+ /* Tab panels */
+ .tab-panel { display: none; padding: 24px; }
+ .tab-panel.active { display: block; }
+
+ /* Form elements */
+ label {
+ display: block;
+ font-size: 12px;
+ font-weight: 600;
+ letter-spacing: 0.05em;
+ text-transform: uppercase;
+ color: var(--text-3);
+ margin-bottom: 8px;
+ }
+ .field-hint {
+ font-size: 12px;
+ color: var(--text-3);
+ margin: 6px 0 0;
+ font-weight: 400;
+ text-transform: none;
+ letter-spacing: 0;
+ }
+ input[type="text"], input[type="url"] {
+ display: block;
+ width: 100%;
+ padding: 11px 14px;
+ background: var(--panel-2);
+ border: 1px solid var(--border-2);
+ border-radius: 8px;
+ color: var(--text);
+ font: inherit;
+ font-size: 14px;
+ outline: none;
+ transition: border-color 0.15s, box-shadow 0.15s;
+ }
+ input[type="text"]:focus, input[type="url"]:focus {
+ border-color: var(--accent);
+ box-shadow: 0 0 0 3px rgba(125,211,252,0.10);
+ }
+
+ /* Drop zone */
+ .drop-zone {
+ border: 1.5px dashed var(--border-2);
+ border-radius: 10px;
+ padding: 40px 20px;
+ text-align: center;
+ cursor: pointer;
+ transition: border-color 0.15s, background 0.15s;
+ position: relative;
+ }
+ .drop-zone:hover, .drop-zone.dragover {
+ border-color: var(--accent);
+ background: var(--accent-dim);
+ }
+ .drop-zone input[type="file"] {
+ position: absolute;
+ inset: 0;
+ opacity: 0;
+ cursor: pointer;
+ width: 100%;
+ height: 100%;
+ }
+ .drop-zone-icon {
+ font-size: 32px;
+ margin-bottom: 10px;
+ line-height: 1;
+ }
+ .drop-zone-title {
+ font-size: 14px;
+ font-weight: 600;
+ color: var(--text);
+ margin-bottom: 4px;
+ }
+ .drop-zone-sub {
+ font-size: 12px;
+ color: var(--text-3);
+ }
+ .drop-zone.has-file .drop-zone-icon { font-size: 22px; margin-bottom: 6px; }
+ .drop-zone.has-file .drop-zone-title { color: var(--ok); }
+
+ /* Submit button */
+ .submit-btn {
+ display: block;
+ width: 100%;
+ margin-top: 20px;
+ padding: 13px 20px;
+ background: var(--accent);
+ color: #0b1014;
+ font: inherit;
+ font-weight: 700;
+ font-size: 14px;
+ border: none;
+ border-radius: 8px;
+ cursor: pointer;
+ transition: opacity 0.15s, transform 0.1s;
+ letter-spacing: 0.01em;
+ }
+ .submit-btn:hover:not(:disabled) { opacity: 0.9; }
+ .submit-btn:active:not(:disabled) { transform: scale(0.99); }
+ .submit-btn:disabled { opacity: 0.45; cursor: not-allowed; }
+
+ /* ── Progress ────────────────────────────────────────────────── */
+ .progress-wrap {
+ display: none;
+ padding: 24px;
+ border-top: 1px solid var(--border);
+ }
+ .progress-wrap.visible { display: block; }
+ .progress-label {
+ font-size: 13px;
+ color: var(--text-2);
+ margin-bottom: 10px;
+ display: flex;
+ justify-content: space-between;
+ }
+ .progress-bar-track {
+ height: 4px;
+ background: var(--border-2);
+ border-radius: 999px;
+ overflow: hidden;
+ }
+ .progress-bar-fill {
+ height: 100%;
+ background: var(--accent);
+ border-radius: 999px;
+ transition: width 0.3s ease;
+ width: 0%;
+ }
+ .progress-stage {
+ font-size: 11px;
+ color: var(--text-3);
+ margin-top: 8px;
+ letter-spacing: 0.03em;
+ }
+
+ /* ── Status messages ─────────────────────────────────────────── */
+ .status-msg {
+ display: none;
+ padding: 14px 16px;
+ border-radius: 10px;
+ font-size: 13px;
+ line-height: 1.5;
+ margin-top: 16px;
+ }
+ .status-msg.err { display: block; background: var(--err-dim); border: 1px solid rgba(248,113,113,0.2); color: var(--err); }
+ .status-msg.ok { display: block; background: rgba(74,222,128,0.07); border: 1px solid rgba(74,222,128,0.2); color: var(--ok); }
+
+ /* ── Success state ───────────────────────────────────────────── */
+ .success-card {
+ display: none;
+ background: var(--panel);
+ border: 1px solid var(--border-2);
+ border-radius: var(--radius);
+ padding: 32px 24px;
+ text-align: center;
+ margin-top: 20px;
+ }
+ .success-card.visible { display: block; }
+ .success-icon { font-size: 40px; margin-bottom: 12px; }
+ .success-card h2 { font-size: 20px; margin: 0 0 8px; letter-spacing: -0.01em; }
+ .success-card p { color: var(--text-2); font-size: 14px; margin: 0 0 20px; }
+ .success-btn {
+ display: inline-block;
+ padding: 12px 28px;
+ background: var(--accent);
+ color: #0b1014;
+ font-weight: 700;
+ font-size: 14px;
+ border-radius: 8px;
+ text-decoration: none;
+ transition: opacity 0.15s;
+ }
+ .success-btn:hover { opacity: 0.9; }
+
+ /* ── Info blocks ─────────────────────────────────────────────── */
+ .info-section { margin-top: 32px; }
+ .info-section h3 { font-size: 14px; font-weight: 600; color: var(--text-2); margin: 0 0 10px; }
+ .info-steps { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 8px; }
+ .info-steps li {
+ display: flex;
+ gap: 12px;
+ font-size: 13px;
+ color: var(--text-2);
+ align-items: flex-start;
+ }
+ .info-steps li::before {
+ content: attr(data-step);
+ flex-shrink: 0;
+ width: 22px;
+ height: 22px;
+ background: var(--panel-2);
+ border: 1px solid var(--border-2);
+ border-radius: 50%;
+ font-size: 11px;
+ font-weight: 700;
+ color: var(--accent);
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ }
+ </style>
+ </head>
+ <body>
+ <main class="page">
+ <a class="back-link" href="/create">
+ ← Back to Create
+ </a>
+
+ <h1>Import from Ready Player Me</h1>
+ <p class="lede">
+ Ready Player Me shut down in January 2026. Bring your avatars here
+ — they'll live on three.ws, fully owned by you, on-chain-ready.
+ </p>
+
+ <div class="warn-banner">
+ <span class="warn-banner-icon">⚠</span>
+ <span>
+ <strong>RPM models.readyplayer.me is offline.</strong> If you already
+ downloaded your GLB file, use the <em>Upload GLB</em> tab. If you
+ have a CDN-cached URL (e.g. from d1a370nemizbjq.cloudfront.net), paste
+ it in the URL tab — it may still resolve.
+ </span>
+ </div>
+
+ <div class="import-card" id="import-card">
+ <div class="tab-bar" role="tablist">
+ <button class="tab-btn active" data-tab="url" role="tab" aria-selected="true" id="tab-url">
+ Paste URL
+ </button>
+ <button class="tab-btn" data-tab="file" role="tab" aria-selected="false" id="tab-file">
+ Upload GLB
+ </button>
+ </div>
+
+ <!-- URL tab -->
+ <div class="tab-panel active" id="panel-url">
+ <label for="rpm-url">RPM avatar URL or CDN link</label>
+ <input
+ type="url"
+ id="rpm-url"
+ placeholder="https://models.readyplayer.me/64c3f8e2…glb"
+ autocomplete="off"
+ spellcheck="false"
+ />
+ <p class="field-hint">
+ Accepts any GLB URL — RPM, CloudFront, or your own storage.
+ The file is fetched server-side so CORS is not an issue.
+ </p>
+
+ <label for="rpm-name" style="margin-top: 18px">Avatar name (optional)</label>
+ <input
+ type="text"
+ id="rpm-name"
+ placeholder="My RPM Avatar"
+ maxlength="64"
+ autocomplete="off"
+ />
+
+ <button class="submit-btn" id="submit-url" type="button">Import from URL</button>
+ <div class="status-msg" id="url-status"></div>
+ </div>
+
+ <!-- File upload tab -->
+ <div class="tab-panel" id="panel-file">
+ <label>GLB file</label>
+ <div class="drop-zone" id="drop-zone">
+ <input
+ type="file"
+ id="glb-file"
+ accept=".glb,model/gltf-binary,application/octet-stream"
+ aria-label="Choose a GLB file"
+ />
+ <div class="drop-zone-icon">📦</div>
+ <div class="drop-zone-title" id="drop-title">Drag &amp; drop your GLB here</div>
+ <div class="drop-zone-sub">or click to browse · .glb · max 100 MB</div>
+ </div>
+
+ <label for="file-name" style="margin-top: 18px">Avatar name (optional)</label>
+ <input
+ type="text"
+ id="file-name"
+ placeholder="My RPM Avatar"
+ maxlength="64"
+ autocomplete="off"
+ />
+
+ <button class="submit-btn" id="submit-file" type="button" disabled>Upload GLB</button>
+ <div class="status-msg" id="file-status"></div>
+ </div>
+
+ <!-- Progress (shared, shown below whichever tab is active) -->
+ <div class="progress-wrap" id="progress-wrap">
+ <div class="progress-label">
+ <span id="progress-text">Importing…</span>
+ <span id="progress-pct">0%</span>
+ </div>
+ <div class="progress-bar-track">
+ <div class="progress-bar-fill" id="progress-fill"></div>
+ </div>
+ <div class="progress-stage" id="progress-stage">Fetching model…</div>
+ </div>
+ </div>
+
+ <!-- Success state (replaces the card) -->
+ <div class="success-card" id="success-card">
+ <div class="success-icon">🎉</div>
+ <h2>Avatar imported!</h2>
+ <p id="success-name">Your avatar is ready on three.ws.</p>
+ <a class="success-btn" id="success-link" href="/avatars">View avatar</a>
+ </div>
+
+ <div class="info-section">
+ <h3>How to find your RPM GLB</h3>
+ <ul class="info-steps">
+ <li data-step="1">
+ If you used the RPM editor, your avatar ID was in the URL
+ (<code>readyplayer.me/avatar/64c3f8e2…</code>). The GLB URL was
+ <code>https://models.readyplayer.me/{id}.glb</code>.
+ </li>
+ <li data-step="2">
+ If you deployed an app using the RPM SDK, check your app's
+ network requests — the GLB URL was fetched on avatar load and
+ often appears in your browser's DevTools Network tab.
+ </li>
+ <li data-step="3">
+ If you downloaded the file, use the <em>Upload GLB</em> tab above.
+ </li>
+ </ul>
+ </div>
+ </main>
+
+ <script type="module">
+ import { saveRemoteGlbToAccount } from '/src/account.js';
+
+ // ── Tab switching ──────────────────────────────────────────────
+ document.querySelectorAll('.tab-btn').forEach((btn) => {
+ btn.addEventListener('click', () => {
+ document.querySelectorAll('.tab-btn').forEach((b) => {
+ b.classList.toggle('active', b === btn);
+ b.setAttribute('aria-selected', String(b === btn));
+ });
+ const target = btn.dataset.tab;
+ document.querySelectorAll('.tab-panel').forEach((p) => {
+ p.classList.toggle('active', p.id === `panel-${target}`);
+ });
+ });
+ });
+
+ // ── File drop zone ─────────────────────────────────────────────
+ const dropZone = document.getElementById('drop-zone');
+ const fileInput = document.getElementById('glb-file');
+ const dropTitle = document.getElementById('drop-title');
+ const submitFile = document.getElementById('submit-file');
+ let selectedFile = null;
+
+ function setFile(f) {
+ if (!f || !f.name.endsWith('.glb')) {
+ showStatus('file-status', 'err', 'Please choose a .glb file.');
+ return;
+ }
+ if (f.size > 100 * 1024 * 1024) {
+ showStatus('file-status', 'err', `File too large (${prettyBytes(f.size)}). Max 100 MB.`);
+ return;
+ }
+ selectedFile = f;
+ dropZone.classList.add('has-file');
+ dropTitle.textContent = `${f.name} (${prettyBytes(f.size)})`;
+ submitFile.disabled = false;
+ clearStatus('file-status');
+ }
+
+ fileInput.addEventListener('change', () => {
+ if (fileInput.files[0]) setFile(fileInput.files[0]);
+ });
+ dropZone.addEventListener('dragover', (e) => { e.preventDefault(); dropZone.classList.add('dragover'); });
+ dropZone.addEventListener('dragleave', () => dropZone.classList.remove('dragover'));
+ dropZone.addEventListener('drop', (e) => {
+ e.preventDefault();
+ dropZone.classList.remove('dragover');
+ const f = e.dataTransfer?.files?.[0];
+ if (f) setFile(f);
+ });
+
+ // ── Import from URL ────────────────────────────────────────────
+ document.getElementById('submit-url').addEventListener('click', async () => {
+ const rawUrl = document.getElementById('rpm-url').value.trim();
+ if (!rawUrl) {
+ showStatus('url-status', 'err', 'Please enter a GLB URL.');
+ return;
+ }
+ let url;
+ try {
+ url = new URL(rawUrl);
+ if (!['http:', 'https:'].includes(url.protocol)) throw new Error('bad protocol');
+ } catch {
+ showStatus('url-status', 'err', 'Enter a valid http:// or https:// URL.');
+ return;
+ }
+ const name = document.getElementById('rpm-name').value.trim() || deriveName(rawUrl);
+ clearStatus('url-status');
+ await runImport(rawUrl, name, 'url-status', { source: 'rpm_import', source_url: rawUrl });
+ });
+
+ // ── Upload from file ───────────────────────────────────────────
+ document.getElementById('submit-file').addEventListener('click', async () => {
+ if (!selectedFile) {
+ showStatus('file-status', 'err', 'Please choose a GLB file first.');
+ return;
+ }
+ const name = document.getElementById('file-name').value.trim() || selectedFile.name.replace(/\.glb$/i, '');
+ clearStatus('file-status');
+ await runImport(selectedFile, name, 'file-status', { source: 'rpm_import' });
+ });
+
+ // ── Core import flow ───────────────────────────────────────────
+ async function runImport(source, name, statusId, meta) {
+ setFormBusy(true);
+ showProgress(true, 'Starting…');
+
+ const abortCtrl = new AbortController();
+
+ try {
+ const avatar = await saveRemoteGlbToAccount(source, {
+ name,
+ visibility: 'public',
+ tags: ['rpm', 'imported'],
+ source: meta.source || 'rpm_import',
+ source_meta: meta,
+ }, {
+ signal: abortCtrl.signal,
+ onProgress: (pct) => {
+ const stage = pct < 10 ? 'Fetching model…'
+ : pct < 30 ? 'Normalizing bones…'
+ : pct < 95 ? 'Uploading to three.ws…'
+ : 'Saving avatar record…';
+ updateProgress(pct, stage);
+ },
+ });
+
+ showProgress(false);
+ showSuccess(avatar);
+ } catch (err) {
+ console.error('[import-rpm]', err);
+ showProgress(false);
+
+ if (err.code === 'not_signed_in' || err.status === 401) {
+ const returnTo = encodeURIComponent(location.pathname + location.search);
+ location.href = `/login?return=${returnTo}`;
+ return;
+ }
+
+ const msg = friendlyError(err);
+ showStatus(statusId, 'err', msg);
+ setFormBusy(false);
+ }
+ }
+
+ function showSuccess(avatar) {
+ document.getElementById('import-card').style.display = 'none';
+ const card = document.getElementById('success-card');
+ card.classList.add('visible');
+ document.getElementById('success-name').textContent =
+ avatar?.name ? `"${avatar.name}" is ready on three.ws.` : 'Your avatar is ready on three.ws.';
+ const link = document.getElementById('success-link');
+ if (avatar?.id) link.href = `/avatars/${encodeURIComponent(avatar.id)}`;
+ }
+
+ // ── Progress UI ────────────────────────────────────────────────
+ function showProgress(visible, label) {
+ const wrap = document.getElementById('progress-wrap');
+ wrap.classList.toggle('visible', visible);
+ if (label) {
+ document.getElementById('progress-text').textContent = label;
+ document.getElementById('progress-stage').textContent = '';
+ document.getElementById('progress-fill').style.width = '0%';
+ document.getElementById('progress-pct').textContent = '0%';
+ }
+ }
+
+ function updateProgress(pct, stageLabel) {
+ document.getElementById('progress-fill').style.width = `${pct}%`;
+ document.getElementById('progress-pct').textContent = `${pct}%`;
+ if (stageLabel) document.getElementById('progress-stage').textContent = stageLabel;
+ if (pct === 0) document.getElementById('progress-text').textContent = 'Starting…';
+ else if (pct < 50) document.getElementById('progress-text').textContent = 'Uploading…';
+ else if (pct < 95) document.getElementById('progress-text').textContent = 'Almost there…';
+ else document.getElementById('progress-text').textContent = 'Finishing…';
+ }
+
+ // ── Helpers ────────────────────────────────────────────────────
+ function setFormBusy(busy) {
+ ['submit-url', 'submit-file'].forEach((id) => {
+ const btn = document.getElementById(id);
+ if (btn) btn.disabled = busy;
+ });
+ const fileEl = document.getElementById('glb-file');
+ if (fileEl) fileEl.disabled = busy;
+ }
+
+ function showStatus(id, tone, msg) {
+ const el = document.getElementById(id);
+ if (!el) return;
+ el.className = `status-msg ${tone}`;
+ el.textContent = msg;
+ }
+
+ function clearStatus(id) {
+ const el = document.getElementById(id);
+ if (el) el.className = 'status-msg';
+ }
+
+ function deriveName(url) {
+ try {
+ const path = new URL(url).pathname;
+ const seg = path.split('/').pop()?.replace(/\.glb$/i, '') || '';
+ return seg.length > 2 ? seg : 'Imported Avatar';
+ } catch {
+ return 'Imported 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(1)} MB`;
+ }
+
+ function friendlyError(err) {
+ const code = err.code || '';
+ const stage = err.stage || '';
+ if (code === 'upload_blocked') return 'Upload blocked — check your network or try a different connection.';
+ if (code === 'upload_failed') return 'Upload failed — the file may be too large or invalid.';
+ if (code === 'upload_aborted') return 'Upload cancelled.';
+ if (code === 'size_mismatch') return 'File size mismatch — please try again.';
+ if (code === 'upload_missing') return 'Upload did not reach storage — try again.';
+ if (stage === 'fetch') return `Could not fetch that URL: ${err.message}. The file may no longer exist.`;
+ if (stage === 'presign') return "Couldn't start upload — are you signed in?";
+ if (stage === 'commit') return 'File uploaded but save failed — please retry.';
+ return err.message || 'Import failed. Please try again.';
+ }
+ </script>
+ </body>
+</html>
diff --git a/public/ai-stream.html b/public/ai-stream.html
index 440456ff3..7de0ad192 100644
--- a/public/ai-stream.html
+++ b/public/ai-stream.html
@@ -94,47 +94,89 @@
iframe.src = `/widget#widget=${widgetId}&kiosk=true&type=pumpfun-feed${modelHash}&narrate=${params.narrate ? '1' : '0'}`;
}
+ // Live mint feed via the same SSE endpoint pumpfun.html uses. Reconnects
+ // with exponential backoff so the page stays useful across cold starts
+ // or short network drops. Duplicate-mint suppression so the same mint
+ // doesn't echo when the upstream reissues.
+ let _es = null;
+ let _esClosed = false;
+ let _esBackoffMs = 1000;
+ const _seenMints = new Set();
+
function connectFeed() {
- // WebSocket connection logic from pumpfun.html
- // This is a complex part, for this step I will mock it
- setStatus('live', 'live');
- const mockEvent = {
- type: 'mint',
- name: 'Test Token',
- symbol: 'TEST',
- description: 'This is a test event for the AI streamer.',
- mint: '...some addresss',
- socials: {},
- market_cap_usd: 10000,
- initial_buy_sol: 10
- };
- setInterval(() => {
- const card = renderEvtCard(mockEvent);
+ if (_esClosed) return;
+ setStatus('connecting', 'connecting…');
+ if (_es) { try { _es.close(); } catch {} _es = null; }
+
+ const endpoint = new URL('/api/agents/pumpfun-feed', location.href);
+ endpoint.searchParams.set('kind', 'mint');
+ _es = new EventSource(endpoint.href, { withCredentials: true });
+
+ _es.addEventListener('open', () => {
+ _esBackoffMs = 1000;
+ setStatus('live', 'live');
+ });
+ const ingest = (evt) => {
+ let payload;
+ try { payload = JSON.parse(evt.data); } catch { return; }
+ if (!payload || typeof payload !== 'object') return;
+ if (payload.mint && _seenMints.has(payload.mint)) return;
+ if (payload.mint) _seenMints.add(payload.mint);
+
+ const card = renderEvtCard(payload);
if (card) {
feedEl.insertBefore(card, feedEl.firstChild);
- if (feedEl.children.length > 20) {
- feedEl.removeChild(feedEl.lastChild);
- }
+ while (feedEl.children.length > 20) feedEl.removeChild(feedEl.lastChild);
+ }
+ narrateEvent(payload);
+ };
+ _es.addEventListener('mint', ingest);
+ _es.addEventListener('ping', () => {});
+ _es.onerror = () => {
+ if (_esClosed || !_es) return;
+ if (_es.readyState === EventSource.CLOSED) {
+ setStatus('down', 'offline');
+ setTimeout(connectFeed, _esBackoffMs);
+ _esBackoffMs = Math.min(_esBackoffMs * 1.5, 15000);
+ } else {
+ setStatus('connecting', 'reconnecting…');
}
- narrateEvent(mockEvent);
- }, 5000);
+ };
}
+ window.addEventListener('beforeunload', () => {
+ _esClosed = true;
+ if (_es) { try { _es.close(); } catch {} }
+ });
+
function renderEvtCard(evt) {
+ const name = String(evt.name || 'Untitled');
+ const symbol = String(evt.symbol || '');
+ const description = String(evt.description || '').slice(0, 200);
+ const mc = Number(evt.market_cap_usd || 0);
const card = document.createElement('div');
card.className = 'evt';
card.innerHTML = `
- <div class="evt-title">${evt.name} ($${evt.symbol})</div>
- <div class="evt-desc">${evt.description}</div>
- <div class="evt-meta">MC: $${evt.market_cap_usd.toLocaleString()}</div>
+ <div class="evt-title">${escapeHtml(name)}${symbol ? ' ($' + escapeHtml(symbol) + ')' : ''}</div>
+ <div class="evt-desc">${escapeHtml(description)}</div>
+ <div class="evt-meta">MC: $${mc.toLocaleString()}</div>
`;
return card;
}
-
+
+ function escapeHtml(s) {
+ return String(s).replace(/[&<>"']/g, (c) => ({
+ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;',
+ })[c]);
+ }
+
function narrateEvent(evt) {
if (!params.narrate) return;
- const text = `New token minted: ${evt.name}! Initial buy of ${evt.initial_buy_sol} SOL. Market cap is now ${evt.market_cap_usd} dollars.`;
- iframe.contentWindow?.postMessage({ type: 'say', payload: { text: text, mood: params.mood } }, '*');
+ const name = String(evt.name || 'a new token');
+ const initialBuy = Number(evt.initial_buy_sol || 0);
+ const mc = Number(evt.market_cap_usd || 0);
+ const text = `New token minted: ${name}! Initial buy of ${initialBuy} SOL. Market cap is now ${mc} dollars.`;
+ iframe.contentWindow?.postMessage({ type: 'say', payload: { text, mood: params.mood } }, '*');
}
function init() {
diff --git a/public/cz/boot.js b/public/cz/boot.js
index e9a3824c9..c850b85cf 100644
--- a/public/cz/boot.js
+++ b/public/cz/boot.js
@@ -121,12 +121,6 @@ async function handleClaimClick(state) {
<p>This agent is already owned by <code>${truncate(state.ownerAddress, 20)}</code>.</p>
<button class="modal-close-btn" onclick="document.getElementById('cz-claim-modal').style.display='none'">OK</button>
`;
- } else if (result.message === 'transfer_available') {
- content.innerHTML = `
- <h3 style="margin:0 0 1rem">Transfer Ownership</h3>
- <p>This agent can be transferred to your wallet. Follow the prompts to continue.</p>
- <button class="modal-close-btn" onclick="document.getElementById('cz-claim-modal').style.display='none'">OK</button>
- `;
} else {
content.innerHTML = `
<h3 style="margin:0 0 1rem">Claim Successful</h3>
@@ -170,7 +164,9 @@ function updateModal(progress, state) {
already_owned: 'Already owned.',
},
transfer: {
- guide: 'Transfer available. Approve in your wallet…',
+ submitting: 'Submitting transfer…',
+ pending: 'Waiting for confirmation…',
+ confirmed: 'Transfer confirmed!',
},
};
diff --git a/public/docs/widget-studio.md b/public/docs/widget-studio.md
index 3b1c11f37..b9cddca1c 100644
--- a/public/docs/widget-studio.md
+++ b/public/docs/widget-studio.md
@@ -240,6 +240,7 @@ You can override these freely in the iframe `width` and `height` attributes. Add
## Next steps
+- [Widget API (JSON-RPC)](./widget-api.md) — programmatic control over an embedded widget: camera, animation, screenshots, model loading
- [Widgets reference](./widgets.md) — technical details, postMessage API, CSP config, and oEmbed spec
- [Web component](./web-component.md) — the `<agent-3d>` custom element for developer integrations
- [Embedding guide](./embedding.md) — advanced embedding patterns and iframe options
diff --git a/public/docs/widgets.md b/public/docs/widgets.md
index b5e4dd92d..a12c42378 100644
--- a/public/docs/widgets.md
+++ b/public/docs/widgets.md
@@ -496,3 +496,9 @@ Each widget load records one minimal analytics event:
| `created_at` | Timestamp |
No IP addresses, no user-agent strings, no cookies, no chat message content. The widget owner can see aggregated view counts in their [Dashboard](https://three.ws/dashboard).
+
+---
+
+## Programmatic control
+
+Need to drive a widget from the parent page — change the camera, play an animation, grab a screenshot? See the [Widget API (JSON-RPC)](./widget-api.md) reference. The `ThreeWidget` SDK lives at `/widget-client.js` and works with any iframe pointing at `/widget`.
diff --git a/public/studio/studio.js b/public/studio/studio.js
index ec645b8fd..85d0b24ba 100644
--- a/public/studio/studio.js
+++ b/public/studio/studio.js
@@ -737,17 +737,98 @@ function selectByModelUrl(url) {
return url;
}
})();
+
+ // Search by model_url (public/unlisted avatars) and by storage_key path
+ // (private avatars where model_url is null but storage_key is available).
const found = state.avatars.find((a) => {
- if (!a.model_url) return false;
- if (a.model_url === url) return true;
- try {
- return new URL(a.model_url).pathname === urlPath;
- } catch {
- return false;
+ if (a.model_url) {
+ if (a.model_url === url) return true;
+ try {
+ if (new URL(a.model_url).pathname === urlPath) return true;
+ } catch {}
}
+ if (a.storage_key) {
+ const keyPath = '/' + a.storage_key.split('/').map(encodeURIComponent).join('/');
+ if (keyPath === urlPath) return true;
+ }
+ return false;
});
- if (found) selectAvatar(found.id);
- else toast('Pre-selected model not found in your avatar library');
+ if (found) return selectAvatar(found.id);
+
+ // Not in the local list — try to auto-register if this is the user's own R2 file.
+ if (state.user) {
+ const storageKey = extractOwnStorageKey(url, state.user.id);
+ if (storageKey) {
+ autoRegisterAndSelect(url, storageKey);
+ return;
+ }
+ }
+
+ toast('Pre-selected model not found in your avatar library');
+}
+
+// Returns the storage_key if url is an R2 object under this user's prefix,
+// otherwise null.
+function extractOwnStorageKey(url, userId) {
+ let pathname;
+ try {
+ pathname = new URL(url).pathname;
+ } catch {
+ return null;
+ }
+ // Decode percent-encoded segments so the storage_key is clean.
+ const key = pathname.replace(/^\//, '').split('/').map(decodeURIComponent).join('/');
+ if (!key.startsWith(`u/${userId}/`)) return null;
+ if (!key.endsWith('.glb')) return null;
+ return key;
+}
+
+async function autoRegisterAndSelect(url, storageKey) {
+ toast('Registering model…');
+ try {
+ // HEAD the object to get its size — required by the avatar creation endpoint.
+ const head = await fetch(url, { method: 'HEAD' });
+ if (!head.ok) throw new Error(`HEAD ${head.status}`);
+ const sizeBytes = Number(head.headers.get('content-length'));
+ if (!sizeBytes) throw new Error('content-length missing');
+
+ // Derive a name from the URL path (last meaningful segment before the file).
+ const segments = storageKey.split('/');
+ const namePart = segments[segments.length - 2] || segments[segments.length - 1];
+ const name = namePart.replace(/[-_]/g, ' ').slice(0, 80) || 'Uploaded model';
+
+ const res = await fetch('/api/avatars', {
+ method: 'POST',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({
+ storage_key: storageKey,
+ size_bytes: sizeBytes,
+ name,
+ visibility: 'public',
+ source: 'direct-upload',
+ }),
+ });
+ if (!res.ok) {
+ const err = await res.json().catch(() => ({}));
+ throw new Error(err.message || `${res.status}`);
+ }
+ const { avatar } = await res.json();
+ // Add to state and select.
+ const ownIds = new Set(state.avatars.map((a) => a.id));
+ if (!ownIds.has(avatar.id)) {
+ state.avatars = [
+ state.avatars[0], // keep DEMO_AVATAR first
+ { ...avatar, model_url: url },
+ ...state.avatars.slice(1),
+ ];
+ renderAvatarList();
+ }
+ selectAvatar(avatar.id);
+ } catch (err) {
+ console.warn('[studio] autoRegisterAndSelect failed', err);
+ toast('Could not register model — pick one from your library');
+ }
}
function selectType(key) {
diff --git a/public/widgets-gallery/gallery.js b/public/widgets-gallery/gallery.js
index 2b83d4472..cbf129974 100644
--- a/public/widgets-gallery/gallery.js
+++ b/public/widgets-gallery/gallery.js
@@ -220,7 +220,11 @@ function renderShowcase(w) {
}
function widgetUrl() {
- return `${ORIGIN}/widget#${buildHashParams()}`;
+ // Gallery is dense (N widgets per page) → reveal=interaction keeps
+ // WebGL slots free until the visitor clicks; auto-poster from
+ // /api/widgets/<id>/og means each card shows the avatar instantly.
+ const poster = `${ORIGIN}/api/widgets/${encodeURIComponent(w.id)}/og`;
+ return `${ORIGIN}/widget#${buildHashParams()}&reveal=interaction&poster=${encodeURIComponent(poster)}`;
}
function pageUrl() {
// /w/<id> currently only carries the saved config — for customized embeds
diff --git a/scripts/backfill-avatar-thumbnails.mjs b/scripts/backfill-avatar-thumbnails.mjs
index 3eacfaed7..3cb9df2ed 100644
--- a/scripts/backfill-avatar-thumbnails.mjs
+++ b/scripts/backfill-avatar-thumbnails.mjs
@@ -98,7 +98,7 @@ async function main() {
console.log(`[backfill] ${todo.length} avatar(s) need thumbnails`);
if (!todo.length) return;
- const browser = await chromium.launch();
+ const browser = await chromium.launch({ args: ['--no-sandbox', '--disable-setuid-sandbox', '--disable-gpu'] });
const ctx = await browser.newContext({
viewport: { width: VIEWPORT, height: VIEWPORT },
deviceScaleFactor: 1,
diff --git a/scripts/diag-hero-load.mjs b/scripts/diag-hero-load.mjs
index d403e4740..c58ad10c9 100644
--- a/scripts/diag-hero-load.mjs
+++ b/scripts/diag-hero-load.mjs
@@ -1,7 +1,7 @@
import { chromium } from 'playwright';
const url = process.argv[2] || 'http://localhost:3000/marketplace';
-const browser = await chromium.launch();
+const browser = await chromium.launch({ args: ['--no-sandbox', '--disable-setuid-sandbox', '--disable-gpu'] });
const ctx = await browser.newContext({ bypassCSP: false });
const page = await ctx.newPage();
diff --git a/scripts/test-pages.mjs b/scripts/test-pages.mjs
index 0bcb7c966..057caad55 100644
--- a/scripts/test-pages.mjs
+++ b/scripts/test-pages.mjs
@@ -186,7 +186,7 @@ async function main() {
let browser;
let exitCode = 0;
try {
- browser = await chromium.launch();
+ browser = await chromium.launch({ args: ['--no-sandbox', '--disable-setuid-sandbox', '--disable-gpu'] });
console.log(`Checking ${ROUTES.length} routes…\n`);
const results = [];
for (const route of ROUTES) {
diff --git a/scripts/verify-agent-ui.mjs b/scripts/verify-agent-ui.mjs
index e528cd322..4d14681e1 100644
--- a/scripts/verify-agent-ui.mjs
+++ b/scripts/verify-agent-ui.mjs
@@ -1,6 +1,6 @@
import { chromium } from 'playwright';
-const browser = await chromium.launch();
+const browser = await chromium.launch({ args: ['--no-sandbox', '--disable-setuid-sandbox', '--disable-gpu'] });
const ctx = await browser.newContext({ viewport: { width: 1280, height: 800 } });
let failed = false;
diff --git a/scripts/verify-auto-rig.mjs b/scripts/verify-auto-rig.mjs
index c94d01366..5c99b8685 100644
--- a/scripts/verify-auto-rig.mjs
+++ b/scripts/verify-auto-rig.mjs
@@ -9,7 +9,7 @@ import { chromium } from 'playwright';
const BASE = process.env.BASE_URL || 'http://localhost:3000';
const URL = `${BASE}/demos/agents/auto-rig.html`;
-const browser = await chromium.launch();
+const browser = await chromium.launch({ args: ['--no-sandbox', '--disable-setuid-sandbox', '--disable-gpu'] });
const page = await browser.newPage();
const errors = [];
diff --git a/scripts/verify-create-review.mjs b/scripts/verify-create-review.mjs
index 50291fda2..0382c6e75 100644
--- a/scripts/verify-create-review.mjs
+++ b/scripts/verify-create-review.mjs
@@ -22,7 +22,7 @@ function fail(msg) {
}
const glbBuffer = await readFile(GLB_PATH);
-const browser = await chromium.launch();
+const browser = await chromium.launch({ args: ['--no-sandbox', '--disable-setuid-sandbox', '--disable-gpu'] });
const ctx = await browser.newContext({ viewport: { width: 1440, height: 1100 } });
const page = await ctx.newPage();
@@ -102,16 +102,14 @@ await page.evaluate(async (b64) => {
consoleErrors.length = 0;
// Reload so create-review.js boots with the staged avatar already in IDB.
-// 'networkidle' waits until all Vite module fetches (lazy dep compilation)
-// settle — on a cold dev-server start this can take 30-60s the first time.
-await page.reload({ waitUntil: 'networkidle', timeout: 90_000 });
+await page.reload({ waitUntil: 'load', timeout: 60_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: 15_000 },
+ { timeout: 12_000 },
);
} catch (err) {
const dbg = await page.evaluate(() => ({
@@ -189,6 +187,17 @@ await page.waitForFunction(
() => !document.getElementById('emote-strip')?.classList.contains('is-visible'),
);
+// Stub canvas.toBlob in the headless browser so the embed-modal snapshot
+// doesn't trigger a WebGL readPixels call — readPixels on a software
+// (SwiftShader) renderer causes the GPU process to crash repeatedly until
+// the tab is killed. The fallback path in openEmbedModal already handles
+// toBlob(null) gracefully (shows the skeleton placeholder instead).
+await page.evaluate(() => {
+ HTMLCanvasElement.prototype.toBlob = function (cb) {
+ setTimeout(() => cb(null), 0);
+ };
+});
+
// 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
diff --git a/scripts/verify-layout-switch.mjs b/scripts/verify-layout-switch.mjs
index e8417bd36..4ff17e776 100644
--- a/scripts/verify-layout-switch.mjs
+++ b/scripts/verify-layout-switch.mjs
@@ -14,16 +14,26 @@ function fail(msg) {
process.exitCode = 1;
}
-const browser = await chromium.launch();
+const LAUNCH_ARGS = [
+ '--no-sandbox',
+ '--disable-setuid-sandbox',
+ '--disable-dev-shm-usage',
+ '--disable-gpu',
+ '--use-angle=swiftshader-webgl',
+ '--ignore-gpu-blacklist',
+];
+
+const browser = await chromium.launch({ args: LAUNCH_ARGS });
const ctx = await browser.newContext();
const page = await ctx.newPage();
+page.on('crash', () => { console.error('FAIL: page crashed'); process.exitCode = 1; });
const consoleErrors = [];
page.on('console', (m) => {
if (m.type() === 'error') consoleErrors.push(m.text());
});
-await page.goto(URL, { waitUntil: 'domcontentloaded' });
+await page.goto(URL, { waitUntil: 'domcontentloaded', timeout: 60_000 });
await page.waitForSelector('#layout-switch:not([hidden])', { timeout: 15_000 });
const initialLayout = await page.evaluate(() => document.body.dataset.layout);
@@ -32,7 +42,8 @@ if (initialLayout !== 'classic') fail(`initial body[data-layout] expected "class
const initialPressed = await page.getAttribute('[data-layout-value="classic"]', 'aria-pressed');
if (initialPressed !== 'true') fail(`classic button should be pressed by default, got aria-pressed="${initialPressed}"`);
-await page.click('[data-layout-value="next"]');
+// Use evaluate-based clicks to avoid pointer-simulation crashes with software WebGL.
+await page.evaluate(() => document.querySelector('[data-layout-value="next"]').click());
const afterNext = await page.evaluate(() => ({
layout: document.body.dataset.layout,
@@ -45,13 +56,13 @@ const nextPressed = await page.getAttribute('[data-layout-value="next"]', 'aria-
if (nextPressed !== 'true') fail(`next button should be pressed after click, got aria-pressed="${nextPressed}"`);
// Reload — the choice must persist.
-await page.reload({ waitUntil: 'domcontentloaded' });
+await page.reload({ waitUntil: 'domcontentloaded', timeout: 60_000 });
await page.waitForSelector('#layout-switch:not([hidden])', { timeout: 15_000 });
const afterReload = await page.evaluate(() => document.body.dataset.layout);
if (afterReload !== 'next') fail(`after reload expected "next", got "${afterReload}"`);
// Flip back to classic and confirm symmetric behavior.
-await page.click('[data-layout-value="classic"]');
+await page.evaluate(() => document.querySelector('[data-layout-value="classic"]').click());
const back = await page.evaluate(() => ({
layout: document.body.dataset.layout,
stored: localStorage.getItem('3dagent:viewer-layout'),
@@ -59,9 +70,11 @@ const back = await page.evaluate(() => ({
if (back.layout !== 'classic') fail(`expected layout "classic", got "${back.layout}"`);
if (back.stored !== 'classic') fail(`localStorage expected "classic", got "${back.stored}"`);
-if (consoleErrors.length) {
+const ignorable = [/wallet/i, /Failed to fetch/i, /Wallet not initialized/i, /GL Driver/i, /ReadPixels/i, /WebGL/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 consoleErrors) console.error(' ', e);
+ for (const e of realErrors) console.error(' ', e);
process.exitCode = 1;
}
diff --git a/scripts/verify-new-demos-interactions.mjs b/scripts/verify-new-demos-interactions.mjs
index 06ecffa83..18a03a63d 100644
--- a/scripts/verify-new-demos-interactions.mjs
+++ b/scripts/verify-new-demos-interactions.mjs
@@ -4,7 +4,7 @@
import { chromium } from 'playwright';
const BASE = process.env.BASE_URL || 'http://localhost:3000';
-const browser = await chromium.launch();
+const browser = await chromium.launch({ args: ['--no-sandbox', '--disable-setuid-sandbox', '--disable-gpu'] });
let totalFail = 0;
async function run(route, action) {
diff --git a/scripts/verify-new-demos.mjs b/scripts/verify-new-demos.mjs
index 1ba5a15f5..ef012b6d0 100644
--- a/scripts/verify-new-demos.mjs
+++ b/scripts/verify-new-demos.mjs
@@ -6,7 +6,7 @@ import { chromium } from 'playwright';
const BASE = process.env.BASE_URL || 'http://localhost:3002';
const ROUTES = ['/demos/404.html', '/demos/checkout.html', '/demos/pricing.html'];
-const browser = await chromium.launch();
+const browser = await chromium.launch({ args: ['--no-sandbox', '--disable-setuid-sandbox', '--disable-gpu'] });
let totalFail = 0;
for (const route of ROUTES) {
diff --git a/scripts/verify-next-layout.mjs b/scripts/verify-next-layout.mjs
index c785d0e6e..6f923d814 100644
--- a/scripts/verify-next-layout.mjs
+++ b/scripts/verify-next-layout.mjs
@@ -26,7 +26,7 @@ function warn(msg) {
warnings.push(msg);
}
-const browser = await chromium.launch();
+const browser = await chromium.launch({ args: ['--no-sandbox', '--disable-setuid-sandbox', '--disable-gpu'] });
const ctx = await browser.newContext({ viewport: { width: 1600, height: 1000 } });
const page = await ctx.newPage();
diff --git a/scripts/verify-save-error.mjs b/scripts/verify-save-error.mjs
index d40c6a81a..6bd1f04d7 100644
--- a/scripts/verify-save-error.mjs
+++ b/scripts/verify-save-error.mjs
@@ -19,7 +19,7 @@ function fail(msg) {
}
const glbBuffer = await readFile(GLB_PATH);
-const browser = await chromium.launch();
+const browser = await chromium.launch({ args: ['--no-sandbox', '--disable-setuid-sandbox', '--disable-gpu'] });
const ctx = await browser.newContext({ viewport: { width: 1440, height: 1100 } });
const page = await ctx.newPage();
diff --git a/scripts/verify-widget-shell.mjs b/scripts/verify-widget-shell.mjs
index 5607d841e..0917adab9 100644
--- a/scripts/verify-widget-shell.mjs
+++ b/scripts/verify-widget-shell.mjs
@@ -228,6 +228,89 @@ await withPage('JSON-RPC: ping + camera + animation + info', async (page) => {
if (envBad?.error?.code === -32603)
ok('viewer.setEnvironment("") → -32603 internal error');
else fail('viewer.setEnvironment("") → -32603', JSON.stringify(envBad));
+
+ // animation.stop used the wrong AnimationManager method name pre-fix;
+ // success here proves the regression won't return.
+ const stop = await rpc('animation.stop');
+ if (stop?.result && !stop.error) ok('animation.stop succeeds (was no-op)');
+ else fail('animation.stop succeeds', JSON.stringify(stop));
+
+ // model.export returns binary GLB as base64 — proves the legacy
+ // exportGLB bridge is fully covered by JSON-RPC now.
+ const exp = await rpc('model.export');
+ if (
+ typeof exp?.result?.base64 === 'string' &&
+ exp.result.base64.length > 1000 &&
+ typeof exp.result.bytes === 'number' &&
+ exp.result.bytes > 1000
+ )
+ ok(`model.export → ${exp.result.bytes} bytes GLB`);
+ else fail('model.export → GLB base64', JSON.stringify(exp).slice(0, 200));
+});
+
+// 6. Multi-instance — two iframes side-by-side, one ThreeWidget client each,
+// confirm a call on one doesn't leak to the other (no cross-talk).
+await withPage('Multi-instance: two clients, two widgets, no cross-talk', async (page) => {
+ await page.goto(`${BASE}/`, { waitUntil: 'domcontentloaded', timeout: 30000 });
+ const result = await page.evaluate(
+ async ({ BASE, DEMO_GLB }) => {
+ document.body.innerHTML =
+ '<iframe id="a" style="width:300px;height:300px;border:0" src="' +
+ BASE +
+ '/widget#model=' +
+ encodeURIComponent(DEMO_GLB) +
+ '&kiosk=true"></iframe>' +
+ '<iframe id="b" style="width:300px;height:300px;border:0" src="' +
+ BASE +
+ '/widget#model=' +
+ encodeURIComponent(DEMO_GLB) +
+ '&kiosk=true"></iframe>';
+ await new Promise((r) => {
+ const s = document.createElement('script');
+ s.src = BASE + '/widget-client.js';
+ s.onload = r;
+ s.onerror = r;
+ document.head.appendChild(s);
+ });
+ if (!window.ThreeWidget) return { error: 'ThreeWidget missing' };
+ const a = window.ThreeWidget.attach(document.getElementById('a'));
+ const b = window.ThreeWidget.attach(document.getElementById('b'));
+ await Promise.all([a.ready(30000), b.ready(30000)]);
+
+ // Count event traffic per client over a short window — they should
+ // each only see their own iframe's events.
+ let aEvents = 0;
+ let bEvents = 0;
+ a.on('*', () => aEvents++);
+ b.on('*', () => bEvents++);
+ // Drive a unique change on each — different bg colours.
+ const [aSet, bSet] = await Promise.all([
+ a.call('viewer.setBackground', { color: '#101030' }),
+ b.call('viewer.setBackground', { color: '#301010' }),
+ ]);
+ // And confirm each client's roundtrip returned its own result.
+ const [aInfo, bInfo] = await Promise.all([
+ a.call('viewer.getInfo'),
+ b.call('viewer.getInfo'),
+ ]);
+ return {
+ bothReady: aInfo?.ready === true && bInfo?.ready === true,
+ aSet: aSet && !aSet.error,
+ bSet: bSet && !bSet.error,
+ aIndependent: aEvents <= 2 && bEvents <= 2,
+ };
+ },
+ { BASE, DEMO_GLB },
+ );
+
+ if (result.error) {
+ fail('multi-instance scaffold', result.error);
+ return;
+ }
+ if (result.bothReady) ok('both widgets ready independently');
+ else fail('both widgets ready', JSON.stringify(result));
+ if (result.aSet && result.bSet) ok('parallel setBackground succeeds on both');
+ else fail('parallel setBackground', JSON.stringify(result));
});
await browser.close();
diff --git a/src/app-next-overlay.js b/src/app-next-overlay.js
index 6413453d3..cfea50b30 100644
--- a/src/app-next-overlay.js
+++ b/src/app-next-overlay.js
@@ -717,7 +717,7 @@ function wirePrimaryCTA() {
primary.addEventListener('click', async () => {
const mode = primary.dataset.mode || 'signin';
if (mode !== 'save') {
- location.href = '/login?return=' + encodeURIComponent(location.pathname);
+ location.href = '/login?next=' + encodeURIComponent(location.pathname);
return;
}
@@ -740,11 +740,11 @@ function wirePrimaryCTA() {
const res = await saveRemoteGlbToAccount(url, {
name: app?._currentModelName || 'Avatar',
});
- if (res?.ok && res.id) {
+ if (res?.id) {
if (primaryLabel) primaryLabel.textContent = 'Saved ✓';
toast(`Saved to your account.`, `/avatars/${res.id}`);
} else {
- throw new Error(res?.error || 'save failed');
+ throw new Error('save failed');
}
} catch (err) {
console.warn('[nxt] save failed', err);
diff --git a/src/avatar-sculpt.js b/src/avatar-sculpt.js
index e2834d1a1..a3ad11e9c 100644
--- a/src/avatar-sculpt.js
+++ b/src/avatar-sculpt.js
@@ -1,5 +1,5 @@
/**
- * Avatar sculpt — face/body morph sliders for /avatars/:id/edit
+ * Avatar sculpt — face/body morph sliders + face-type blend wheel for /avatars/:id/edit
*
* The avatar GLBs we ship (Avaturn, Ready Player Me, three.ws Studio) carry
* the 52 ARKit blendshapes by name (see src/runtime/arkit52.js). Plus, RPM-
@@ -12,6 +12,10 @@
* State model: avatar-edit.js owns `workingAppearance.morphs = { name: w }`.
* We mutate that dict on slider input + apply influence to every skinned
* mesh's `morphTargetInfluences` in real time. Save flow is unchanged.
+ *
+ * Blend wheel: MetaHuman-style 2-D barycentric blend of 6 face-type presets.
+ * IDW (inverse distance weighting) maps puck position → weighted morph sum.
+ * Slider fine-tuning still works on top — they share the same morphs dict.
*/
import { detectFaceAll } from './avatar-face-capture.js';
@@ -85,8 +89,6 @@ const CATEGORIES = [
{
id: 'body',
label: 'Body',
- // RPM-style body morphs all start with these prefixes. Daz/CC use
- // uppercase but normalize-friendly here since we match by name.
match: /^(body|shape|height|breast|chest|waist|hip|muscle|weight|bust|gluteus|figure|thighs|arms)/i,
},
{
@@ -106,6 +108,99 @@ const ARKIT52 = new Set([
'eyeBlinkLeft','eyeBlinkRight','eyeLookDownLeft','eyeLookDownRight','eyeLookInLeft','eyeLookInRight','eyeLookOutLeft','eyeLookOutRight','eyeLookUpLeft','eyeLookUpRight','eyeSquintLeft','eyeSquintRight','eyeWideLeft','eyeWideRight','jawForward','jawLeft','jawRight','jawOpen','mouthClose','mouthFunnel','mouthPucker','mouthLeft','mouthRight','mouthSmileLeft','mouthSmileRight','mouthFrownLeft','mouthFrownRight','mouthDimpleLeft','mouthDimpleRight','mouthStretchLeft','mouthStretchRight','mouthRollLower','mouthRollUpper','mouthShrugLower','mouthShrugUpper','mouthPressLeft','mouthPressRight','mouthLowerDownLeft','mouthLowerDownRight','mouthUpperUpLeft','mouthUpperUpRight','browDownLeft','browDownRight','browInnerUp','browOuterUpLeft','browOuterUpRight','cheekPuff','cheekSquintLeft','cheekSquintRight','noseSneerLeft','noseSneerRight','tongueOut',
]);
+/* ────────────────────────────────────────────────────────────────────────── *
+ * Blend wheel presets — 6 face archetypes placed on a 2-D [-1..1] plane.
+ *
+ * Positions are chosen so the 6 points span the space and avoid overlap.
+ * Morph keys use whatever the avatar exposes; unknown keys silently skip.
+ * Body-shape morphs (bodyJawWide, bodyNoseWide, bodyFaceLong, bodyLipsThick)
+ * are RPM / Avaturn extensions and simply won't fire on ARKit-only rigs.
+ * ────────────────────────────────────────────────────────────────────────── */
+
+const BLEND_PRESETS = [
+ {
+ id: 'round',
+ label: 'Round',
+ pos: [-0.55, -0.65],
+ morphs: {
+ cheekPuff: 0.45,
+ cheekSquintLeft: 0.2,
+ cheekSquintRight: 0.2,
+ browInnerUp: 0.25,
+ mouthShrugUpper: 0.15,
+ bodyJawWide: 0.3,
+ bodyFaceLong: 0.05,
+ },
+ },
+ {
+ id: 'angular',
+ label: 'Angular',
+ pos: [0.55, -0.65],
+ morphs: {
+ browDownLeft: 0.38,
+ browDownRight: 0.38,
+ bodyJawWide: 0.55,
+ cheekPuff: 0.0,
+ noseSneerLeft: 0.12,
+ noseSneerRight: 0.12,
+ },
+ },
+ {
+ id: 'wide',
+ label: 'Wide',
+ pos: [0.85, 0.1],
+ morphs: {
+ bodyJawWide: 0.72,
+ bodyNoseWide: 0.55,
+ cheekPuff: 0.22,
+ mouthShrugLower: 0.18,
+ bodyLipsThick: 0.2,
+ },
+ },
+ {
+ id: 'narrow',
+ label: 'Narrow',
+ pos: [-0.85, 0.1],
+ morphs: {
+ bodyJawWide: 0.0,
+ bodyNoseWide: 0.0,
+ cheekPuff: 0.0,
+ bodyLipsThick: 0.0,
+ cheekSquintLeft: 0.0,
+ cheekSquintRight: 0.0,
+ },
+ },
+ {
+ id: 'long',
+ label: 'Long',
+ pos: [0.0, 0.85],
+ morphs: {
+ bodyFaceLong: 0.62,
+ bodyJawWide: 0.18,
+ cheekPuff: 0.0,
+ browInnerUp: 0.1,
+ },
+ },
+ {
+ id: 'soft',
+ label: 'Soft',
+ pos: [0.0, -0.85],
+ morphs: {
+ browInnerUp: 0.38,
+ mouthShrugLower: 0.22,
+ cheekPuff: 0.28,
+ bodyFaceLong: 0.08,
+ mouthShrugUpper: 0.12,
+ },
+ },
+];
+
+/* ────────────────────────────────────────────────────────────────────────── *
+ * Module-level mirror lock state (survives re-renders within a page visit)
+ * ────────────────────────────────────────────────────────────────────────── */
+
+let _mirrorLocked = true;
+
/* ────────────────────────────────────────────────────────────────────────── *
* Public API
* ────────────────────────────────────────────────────────────────────────── */
@@ -128,18 +223,6 @@ export function discoverMorphs(root) {
return [...found].sort();
}
-/** Detect whether a morph name is a Left/Right variant. Returns the pair root or null. */
-function pairRootOf(name) {
- const m = name.match(/^(.*)(Left|Right)$/);
- return m ? m[1] : null;
-}
-/** Detect Left/Right side of a paired morph. */
-function sideOf(name) {
- if (name.endsWith('Left')) return 'L';
- if (name.endsWith('Right')) return 'R';
- return null;
-}
-
/**
* Apply { name: weight } to every mesh on the root. Out-of-range weights are
* clamped; unknown names are silently skipped (mirrors AccessoryManager).
@@ -181,95 +264,234 @@ export function renderSculptPanel({ container, root, working, onDirty }) {
const groups = groupMorphs(all);
working.morphs = working.morphs || {};
+ const available = new Set(all);
- // Build DOM
container.innerHTML = `
<div class="ae-sculpt-head">
<button class="ae-btn ae-sculpt-capture" type="button" id="ae-sculpt-capture">
<span class="ae-sculpt-capture-icon" aria-hidden="true">📸</span>
Capture from photo
</button>
- <button class="ae-btn ae-sculpt-reset" type="button" id="ae-sculpt-reset">
- Reset all
- </button>
+ <label class="ae-sculpt-mirror" title="Keep left/right morphs in sync">
+ <input type="checkbox" id="ae-sculpt-mirror-lock" ${_mirrorLocked ? 'checked' : ''}>
+ Mirror L/R
+ </label>
+ <button class="ae-btn ae-sculpt-reset" type="button" id="ae-sculpt-reset">Reset all</button>
</div>
<p class="ae-sculpt-note">
- Drag a slider to sculpt that morph in real time. The capture button
- takes one selfie and writes the 52 ARKit blendshapes into your
- avatar so it carries your resting expression.
+ Drag the wheel puck to blend face types. Use sliders for fine control.
+ Double-click any slider to zero it. Capture button reads face geometry
+ from your webcam — expression in the photo is ignored.
</p>
- ${groups
- .map((g) => `
- <details class="ae-sculpt-group" ${g.collapsed ? '' : 'open'}>
- <summary>
- <span>${g.label}</span>
- <span class="ae-sculpt-count">${g.morphs.length}</span>
- </summary>
- <div class="ae-sculpt-rows">
- ${g.morphs
- .map((m) => sliderRow(m, working.morphs[m] || 0))
- .join('')}
- </div>
- </details>
- `)
- .join('')}
+
+ ${blendWheelHtml()}
+
+ ${groups.map((g) => renderGroup(g, working.morphs)).join('')}
`;
- container.querySelectorAll('input[type="range"][data-morph]').forEach((input) => {
- const name = input.dataset.morph;
- const valEl = container.querySelector(`output[data-for="${cssEscape(name)}"]`);
- const onChange = () => {
- const w = Number(input.value);
- if (w === 0) {
- delete working.morphs[name];
- } else {
- working.morphs[name] = w;
- }
- applyMorphsToRoot(root, { [name]: w });
- if (valEl) valEl.textContent = w.toFixed(2);
- onDirty?.();
- };
- input.addEventListener('input', onChange);
- input.addEventListener('dblclick', () => {
- input.value = '0';
- onChange();
- });
+ wireSliders(container, root, working, onDirty);
+ wireBlendWheel(container, root, working, available, onDirty);
+
+ container.querySelector('#ae-sculpt-mirror-lock')?.addEventListener('change', (e) => {
+ _mirrorLocked = e.target.checked;
+ renderSculptPanel({ container, root, working, onDirty });
});
container.querySelector('#ae-sculpt-reset')?.addEventListener('click', () => {
- // Wipe all morphs we control, re-apply 0, re-render so sliders snap back.
- const previousKeys = Object.keys(working.morphs);
working.morphs = {};
- const zeros = {};
- for (const k of previousKeys) zeros[k] = 0;
- applyMorphsToRoot(root, zeros);
+ applyMorphsToRoot(root, clearAll(all));
renderSculptPanel({ container, root, working, onDirty });
onDirty?.();
});
container.querySelector('#ae-sculpt-capture')?.addEventListener('click', () => {
- openFaceCaptureModal({ root, working, onDirty, rerender: () => {
- renderSculptPanel({ container, root, working, onDirty });
- } });
+ openFaceCaptureModal({
+ root,
+ working,
+ onDirty,
+ rerender: () => renderSculptPanel({ container, root, working, onDirty }),
+ });
});
}
/* ────────────────────────────────────────────────────────────────────────── *
- * Slider wiring — with mirror-lock support for L/R paired morphs.
+ * Blend wheel — MetaHuman-style 2-D preset interpolation
+ * ────────────────────────────────────────────────────────────────────────── */
+
+function blendWheelHtml() {
+ const toPercent = (v) => `${((v + 1) / 2 * 100).toFixed(1)}%`;
+ const labels = BLEND_PRESETS.map((p) => `
+ <span class="ae-blend-label" style="left:${toPercent(p.pos[0])};top:${toPercent(p.pos[1])}" aria-hidden="true">${escHtml(p.label)}</span>
+ `).join('');
+
+ return `
+ <details class="ae-sculpt-group ae-blend-group" open>
+ <summary>
+ <span>Face Type Blend</span>
+ <span class="ae-sculpt-count" id="ae-blend-count">neutral</span>
+ </summary>
+ <div class="ae-sculpt-rows ae-blend-body">
+ <div class="ae-blend-canvas" id="ae-blend-canvas" role="slider" tabindex="0"
+ aria-label="Face type blend wheel" aria-valuetext="neutral">
+ ${labels}
+ <div class="ae-blend-puck" id="ae-blend-puck"></div>
+ </div>
+ <p class="ae-blend-desc" id="ae-blend-desc">Drag the puck to blend face archetypes</p>
+ <button class="ae-btn" id="ae-blend-reset" type="button">Center (neutral)</button>
+ </div>
+ </details>
+ `;
+}
+
+function wireBlendWheel(container, root, working, available, onDirty) {
+ const canvas = container.querySelector('#ae-blend-canvas');
+ const puck = container.querySelector('#ae-blend-puck');
+ const desc = container.querySelector('#ae-blend-desc');
+ const count = container.querySelector('#ae-blend-count');
+ if (!canvas || !puck) return;
+
+ let puckX = 0;
+ let puckY = 0;
+
+ function movePuck(nx, ny) {
+ const mag = Math.sqrt(nx * nx + ny * ny);
+ if (mag > 1) { nx /= mag; ny /= mag; }
+ puckX = nx;
+ puckY = ny;
+ puck.style.left = `${((nx + 1) / 2 * 100).toFixed(2)}%`;
+ puck.style.top = `${((ny + 1) / 2 * 100).toFixed(2)}%`;
+ applyBlend();
+ }
+
+ function applyBlend() {
+ const blended = computeBlend(puckX, puckY, available);
+ const blendKeys = new Set(BLEND_PRESETS.flatMap((p) => Object.keys(p.morphs)));
+ for (const k of blendKeys) delete working.morphs[k];
+ for (const [name, w] of Object.entries(blended)) {
+ if (w >= 0.005) working.morphs[name] = w;
+ }
+ applyMorphsToRoot(root, working.morphs);
+ onDirty?.();
+
+ const strength = Math.round(Math.sqrt(puckX * puckX + puckY * puckY) / Math.SQRT2 * 100);
+ const label = strength < 4 ? 'neutral' : dominantLabel(puckX, puckY);
+ if (desc) {
+ desc.textContent = strength < 4
+ ? 'Drag the puck to blend face archetypes'
+ : `Blending towards ${label} (${strength}% strength)`;
+ }
+ if (count) count.textContent = label;
+ canvas.setAttribute('aria-valuetext', label);
+ }
+
+ function eventToNorm(e) {
+ const rect = canvas.getBoundingClientRect();
+ const cx = rect.left + rect.width / 2;
+ const cy = rect.top + rect.height / 2;
+ const r = Math.min(rect.width, rect.height) / 2;
+ return [(e.clientX - cx) / r, (e.clientY - cy) / r];
+ }
+
+ // Pointer drag on puck
+ let dragging = false;
+ puck.addEventListener('pointerdown', (e) => {
+ dragging = true;
+ puck.setPointerCapture(e.pointerId);
+ e.preventDefault();
+ });
+ puck.addEventListener('pointermove', (e) => {
+ if (!dragging) return;
+ const [nx, ny] = eventToNorm(e);
+ movePuck(nx, ny);
+ });
+ puck.addEventListener('pointerup', () => { dragging = false; });
+ puck.addEventListener('pointercancel', () => { dragging = false; });
+
+ // Click anywhere on canvas to teleport puck
+ canvas.addEventListener('pointerdown', (e) => {
+ if (e.target === puck) return;
+ const [nx, ny] = eventToNorm(e);
+ movePuck(nx, ny);
+ });
+
+ // Keyboard nudge (arrow keys when canvas has focus)
+ const STEP = 0.08;
+ canvas.addEventListener('keydown', (e) => {
+ const map = { ArrowLeft: [-STEP, 0], ArrowRight: [STEP, 0], ArrowUp: [0, -STEP], ArrowDown: [0, STEP] };
+ const delta = map[e.key];
+ if (!delta) return;
+ e.preventDefault();
+ movePuck(puckX + delta[0], puckY + delta[1]);
+ });
+
+ container.querySelector('#ae-blend-reset')?.addEventListener('click', () => {
+ puckX = 0;
+ puckY = 0;
+ puck.style.left = '50%';
+ puck.style.top = '50%';
+ const blendKeys = new Set(BLEND_PRESETS.flatMap((p) => Object.keys(p.morphs)));
+ for (const k of blendKeys) delete working.morphs[k];
+ applyMorphsToRoot(root, working.morphs);
+ if (desc) desc.textContent = 'Drag the puck to blend face archetypes';
+ if (count) count.textContent = 'neutral';
+ canvas.setAttribute('aria-valuetext', 'neutral');
+ onDirty?.();
+ });
+}
+
+function computeBlend(px, py, available) {
+ const strength = Math.min(1, Math.sqrt(px * px + py * py));
+ if (strength < 0.01) return {};
+
+ const EPS = 0.0001;
+ const POWER = 2;
+ const raw = BLEND_PRESETS.map((p) => {
+ const dx = px - p.pos[0];
+ const dy = py - p.pos[1];
+ return 1 / (Math.pow(dx * dx + dy * dy, POWER / 2) + EPS);
+ });
+ const total = raw.reduce((a, b) => a + b, 0);
+ const norm = raw.map((w) => w / total);
+
+ const result = {};
+ for (let i = 0; i < BLEND_PRESETS.length; i++) {
+ const p = BLEND_PRESETS[i];
+ const w = norm[i] * strength;
+ for (const [name, v] of Object.entries(p.morphs)) {
+ if (available && !available.has(name)) continue;
+ result[name] = (result[name] || 0) + w * v;
+ }
+ }
+ return result;
+}
+
+function dominantLabel(px, py) {
+ let best = Infinity;
+ let label = '';
+ for (const p of BLEND_PRESETS) {
+ const dx = px - p.pos[0];
+ const dy = py - p.pos[1];
+ const d = dx * dx + dy * dy;
+ if (d < best) { best = d; label = p.label; }
+ }
+ return label;
+}
+
+/* ────────────────────────────────────────────────────────────────────────── *
+ * Slider wiring — mirror-lock support for L/R paired morphs
* ────────────────────────────────────────────────────────────────────────── */
function wireSliders(container, root, working, onDirty) {
container.querySelectorAll('input[type="range"][data-morph]').forEach((input) => {
const name = input.dataset.morph;
const valEl = container.querySelector(`output[data-for="${cssEscape(name)}"]`);
- const pairName = input.dataset.pair || null; // companion morph when mirroring
+ const pairName = input.dataset.pair || null;
const onChange = () => {
const w = Number(input.value);
writeMorph(working, name, w);
applyMorphsToRoot(root, { [name]: w });
if (valEl) valEl.textContent = w.toFixed(2);
- // Mirror the value to the companion morph if active.
if (pairName) {
writeMorph(working, pairName, w);
applyMorphsToRoot(root, { [pairName]: w });
@@ -277,10 +499,7 @@ function wireSliders(container, root, working, onDirty) {
onDirty?.();
};
input.addEventListener('input', onChange);
- input.addEventListener('dblclick', () => {
- input.value = '0';
- onChange();
- });
+ input.addEventListener('dblclick', () => { input.value = '0'; onChange(); });
});
}
@@ -289,9 +508,12 @@ function writeMorph(working, name, w) {
else working.morphs[name] = w;
}
+/* ────────────────────────────────────────────────────────────────────────── *
+ * Group rendering — mirror-lock collapses L/R pairs to a single slider
+ * ────────────────────────────────────────────────────────────────────────── */
+
function renderGroup(g, morphs) {
if (_mirrorLocked) {
- // Collapse {fooLeft, fooRight} → single "Foo" slider that mutates both.
const visible = [];
const seenPair = new Set();
for (const name of g.morphs) {
@@ -313,7 +535,7 @@ function renderGroup(g, morphs) {
return `
<details class="ae-sculpt-group" ${g.collapsed ? '' : 'open'}>
<summary>
- <span>${g.label}</span>
+ <span>${escHtml(g.label)}</span>
<span class="ae-sculpt-count">${visible.length}</span>
</summary>
<div class="ae-sculpt-rows">
@@ -325,7 +547,7 @@ function renderGroup(g, morphs) {
return `
<details class="ae-sculpt-group" ${g.collapsed ? '' : 'open'}>
<summary>
- <span>${g.label}</span>
+ <span>${escHtml(g.label)}</span>
<span class="ae-sculpt-count">${g.morphs.length}</span>
</summary>
<div class="ae-sculpt-rows">
@@ -336,7 +558,7 @@ function renderGroup(g, morphs) {
}
/* ────────────────────────────────────────────────────────────────────────── *
- * Face capture modal — webcam → MediaPipe → ARKit-52 weights
+ * Face capture modal — webcam → MediaPipe → ARKit-52 identity weights
* ────────────────────────────────────────────────────────────────────────── */
let activeFaceModal = null;
@@ -433,9 +655,8 @@ function openFaceCaptureModal({ root, working, onDirty, rerender }) {
return;
}
- // Use identity morphs (from landmark ratios) as the primary signal.
- // The blendshape map is intentionally ignored for seeding — those
- // describe the user's expression in the photo, not their face shape.
+ // Use identity morphs (landmark ratios) — not the expression blendshapes.
+ // Expression weights describe how the user looked in the photo, not their face shape.
const available = new Set(discoverMorphs(root));
let applied = 0;
for (const [name, weight] of Object.entries(full.identity)) {
@@ -469,12 +690,15 @@ function openFaceCaptureModal({ root, working, onDirty, rerender }) {
* Helpers
* ────────────────────────────────────────────────────────────────────────── */
+function clearAll(names) {
+ return Object.fromEntries(names.map((n) => [n, 0]));
+}
+
function groupMorphs(all) {
const seen = new Set();
const groups = [];
for (const cat of CATEGORIES) {
const ours = [];
- // Preferred names first (in spec order), then any other matches.
if (cat.preferred) {
for (const name of cat.preferred) {
if (all.includes(name) && !seen.has(name)) {
@@ -494,7 +718,6 @@ function groupMorphs(all) {
groups.push({ id: cat.id, label: cat.label, morphs: ours, collapsed: !!cat.collapsed });
}
}
- // "Other" bucket for anything custom (e.g. RPM Outfit_Top morphs)
const leftovers = all.filter((n) => !seen.has(n));
if (leftovers.length) {
groups.push({ id: 'other', label: 'Other', morphs: leftovers, collapsed: true });
@@ -502,6 +725,11 @@ function groupMorphs(all) {
return groups;
}
+function pairRootOf(name) {
+ const m = name.match(/^(.*)(Left|Right)$/);
+ return m ? m[1] : null;
+}
+
function sliderRow(name, value, displayLabel, pairName) {
const labelSource = displayLabel || name;
const label = humanize(labelSource);
@@ -534,9 +762,7 @@ function humanize(name) {
.replace(/^./, (c) => c.toUpperCase());
}
-function isVisemeName(name) {
- return /^viseme_/.test(name);
-}
+function isVisemeName(name) { return /^viseme_/.test(name); }
function escHtml(s) {
return String(s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
diff --git a/src/cz-flow.js b/src/cz-flow.js
index f1c5e1bcd..91e6aeb0a 100644
--- a/src/cz-flow.js
+++ b/src/cz-flow.js
@@ -3,7 +3,6 @@
*/
import { ensureWallet, getIdentityRegistry } from './erc8004/agent-registry.js';
-import { REGISTRY_DEPLOYMENTS } from './erc8004/abi.js';
/**
* Start the claim flow based on the current state.
@@ -33,14 +32,15 @@ export async function startClaim({ state, onProgress }) {
return { ok: true, message: 'pre_onchain' };
}
+ const registry = getIdentityRegistry(chainId, signer);
+
// Step 3: If ownerAddress is 0x0 (unclaimed), call claim()
if (state.ownerAddress === '0x0000000000000000000000000000000000000000') {
log('claim', 'submitting');
- const registry = getIdentityRegistry(chainId, signer);
const tx = await registry.claim(state.agentId);
log('claim', 'pending', { txHash: tx.hash });
- const receipt = await tx.wait();
+ await tx.wait();
log('claim', 'confirmed', { txHash: tx.hash });
fireAnalytics('claim_tx_sent', { txHash: tx.hash, agentId: state.agentId });
@@ -48,24 +48,30 @@ export async function startClaim({ state, onProgress }) {
return { ok: true, txHash: tx.hash };
}
- // Step 4: If state.ownerAddress is known demo EOA, guide transfer
- const DEMO_EOAS = [
- '0x1234567890123456789012345678901234567890', // placeholder
- ];
- if (DEMO_EOAS.includes(state.ownerAddress?.toLowerCase())) {
- log('transfer', 'guide', {
- from: state.ownerAddress,
- to: address,
- message: 'This agent is owned by the demo account. Transfer to your wallet?',
- });
-
- // Real implementation would show a modal and call transferOwner() if approved
- // For now, return guidance
- return { ok: true, message: 'transfer_available' };
+ // Step 4: Already owned by the connected wallet.
+ if (state.ownerAddress?.toLowerCase() === address.toLowerCase()) {
+ log('claim', 'already_owned', { owner: address });
+ return { ok: true, message: 'already_owned' };
}
- log('claim', 'already_owned', { owner: state.ownerAddress });
- return { ok: true, message: 'already_owned' };
+ // Step 5: Transfer from the current owner to the connected wallet.
+ // ERC-721 transferFrom can only be called by the token owner or an approved
+ // operator. Verify the connected wallet is the owner before submitting so we
+ // surface a clean error instead of an opaque on-chain revert.
+ const onchainOwner = await registry.ownerOf(state.agentId).catch(() => null);
+ if (onchainOwner && onchainOwner.toLowerCase() !== address.toLowerCase()) {
+ return {
+ ok: false,
+ error: `Transfer failed: the connected wallet (${address}) is not the current owner. The agent is owned by ${onchainOwner}.`,
+ };
+ }
+ log('transfer', 'submitting', { from: state.ownerAddress, to: address });
+ const tx = await registry.transferFrom(state.ownerAddress, address, state.agentId);
+ log('transfer', 'pending', { txHash: tx.hash });
+ await tx.wait();
+ log('transfer', 'confirmed', { txHash: tx.hash });
+ fireAnalytics('transfer_complete', { txHash: tx.hash, agentId: state.agentId });
+ return { ok: true, txHash: tx.hash };
} catch (err) {
log('claim', 'error', { error: err.message });
fireAnalytics('claim_error', { error: err.message });
diff --git a/src/dashboard/dashboard.js b/src/dashboard/dashboard.js
index 6edd73120..e59233dbf 100644
--- a/src/dashboard/dashboard.js
+++ b/src/dashboard/dashboard.js
@@ -4226,7 +4226,11 @@ function widgetCard(w, ctx) {
card.className = 'widget-card card';
card.dataset.id = w.id;
- const previewSrc = `/widget#widget=${encodeURIComponent(w.id)}&kiosk=true&preview=1`;
+ // Dashboard grid often has many widget cards visible — pass poster=auto so
+ // each card shows the OG snapshot instantly while WebGL warms up only for
+ // the cards actually scrolled into view (the iframe is loading="lazy").
+ const poster = `/api/widgets/${encodeURIComponent(w.id)}/og`;
+ const previewSrc = `/widget#widget=${encodeURIComponent(w.id)}&kiosk=true&preview=1&poster=${encodeURIComponent(poster)}`;
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>`;
@@ -4400,7 +4404,8 @@ async function openWidgetDrawer(w, ctx) {
drawer.setAttribute('aria-label', `Widget details — ${w.name || 'untitled'}`);
drawer.tabIndex = -1;
- const previewSrc = `/widget#widget=${encodeURIComponent(w.id)}&kiosk=true&preview=1`;
+ const drawerPoster = `/api/widgets/${encodeURIComponent(w.id)}/og`;
+ const previewSrc = `/widget#widget=${encodeURIComponent(w.id)}&kiosk=true&preview=1&poster=${encodeURIComponent(drawerPoster)}`;
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>`;
@@ -4866,7 +4871,8 @@ function openShareModal(w) {
const maxW = 320,
maxH = 320;
const scale = Math.min(maxW / dim.width, maxH / dim.height, 1);
- 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>`;
+ const resizePoster = `/api/widgets/${encodeURIComponent(w.id)}/og`;
+ previewEl.innerHTML = `<iframe src="/widget#widget=${encodeURIComponent(w.id)}&kiosk=true&preview=1&poster=${encodeURIComponent(resizePoster)}" 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`;
}
diff --git a/src/erc8004/register-ui.js b/src/erc8004/register-ui.js
index 5c8c8287a..5a08c41d1 100644
--- a/src/erc8004/register-ui.js
+++ b/src/erc8004/register-ui.js
@@ -1561,7 +1561,7 @@ export class RegisterUI {
<button type="button" class="erc8004-export-opt" data-role="exp-curl">
<div class="erc8004-export-emoji">🌐</div>
<div class="erc8004-export-title">curl</div>
- <div class="erc8004-export-sub">Graph query stub</div>
+ <div class="erc8004-export-sub">Query registry via curl</div>
</button>
</div>
</div>
diff --git a/src/erc8004/vanity-modal.js b/src/erc8004/vanity-modal.js
index b6acc0bd7..5fbfe3830 100644
--- a/src/erc8004/vanity-modal.js
+++ b/src/erc8004/vanity-modal.js
@@ -55,8 +55,14 @@ function _formatTime(seconds) {
return '>1d';
}
-/** Sample base58 string (deterministic-ish — not crypto). For preview only. */
-function _sampleAddress(prefix = '') {
+/**
+ * Random base58 suffix used purely to visualize address length in the modal.
+ * The prefix portion is the real user input; the rest is shown grayed-out so
+ * the layout previews the final 44-char keypair. Never persisted, never sent
+ * to the grinder — see the CSS `.vm-preview .rest` rule and the "Preview"
+ * label above the box.
+ */
+function _previewSuffix(prefix = '') {
const len = 44 - prefix.length;
let out = prefix;
for (let i = 0; i < len; i++) {
@@ -159,6 +165,7 @@ export function openVanityModal({ agentName = '', initial = '' } = {}) {
placeholder="e.g. AGNT" autocomplete="off" spellcheck="false"
value="${_esc(initial)}" />
+ <div class="vm-preview-label" style="font-size:.7rem;color:#888;margin-top:.7rem;text-transform:uppercase;letter-spacing:.06em;">Preview — random suffix shown for layout only</div>
<div class="vm-preview" aria-live="polite" id="vm-preview"></div>
<div class="vm-meter" aria-hidden="true">
@@ -283,7 +290,7 @@ export function openVanityModal({ agentName = '', initial = '' } = {}) {
okBtn.textContent = 'Use prefix';
if (!raw) {
- preview.innerHTML = '<span class="rest">' + _esc(_sampleAddress()) + '</span>';
+ preview.innerHTML = '<span class="rest">' + _esc(_previewSuffix()) + '</span>';
estEl.textContent = 'enter a prefix above';
tierEl.innerHTML = '';
okBtn.disabled = true;
@@ -296,7 +303,7 @@ export function openVanityModal({ agentName = '', initial = '' } = {}) {
okBtn.disabled = true;
return;
}
- const sample = _sampleAddress(raw);
+ const sample = _previewSuffix(raw);
preview.innerHTML = `<span class="pfx">${_esc(raw)}</span><span class="rest">${_esc(sample.slice(raw.length))}</span>`;
estEl.textContent = `est. ${_formatTime(_estimateSeconds(raw.length))} on ${_coreCount()} cores`;
tierEl.innerHTML = raw.length >= FREE_THRESHOLD
@@ -311,7 +318,7 @@ export function openVanityModal({ agentName = '', initial = '' } = {}) {
previewTimer = setInterval(() => {
const raw = input.value;
if (raw && BASE58_RE.test(raw)) {
- const sample = _sampleAddress(raw);
+ const sample = _previewSuffix(raw);
const pfxNode = preview.querySelector('.pfx');
const restNode = preview.querySelector('.rest');
if (pfxNode && restNode) restNode.textContent = sample.slice(raw.length);
diff --git a/src/mocap-studio.js b/src/mocap-studio.js
index acd8b86bb..85a687473 100644
--- a/src/mocap-studio.js
+++ b/src/mocap-studio.js
@@ -161,9 +161,14 @@ async function loadByHandle() {
await viewer.load(avatar.model_url, '', new Map());
// Re-attach idle + face mocap to the freshly loaded root.
if (state.idle) state.idle.dispose();
- state.idle = new IdleAnimation({ getRoot: () => viewer.content, seed: state.avatar.id });
if (!viewer._afterAnimateHooks) viewer._afterAnimateHooks = [];
- viewer._afterAnimateHooks.push((dt) => state.idle?.update(dt));
+ if (state._idleHook) {
+ const idx = viewer._afterAnimateHooks.indexOf(state._idleHook);
+ if (idx !== -1) viewer._afterAnimateHooks.splice(idx, 1);
+ }
+ state.idle = new IdleAnimation({ getRoot: () => viewer.content, seed: state.avatar.id });
+ state._idleHook = (dt) => state.idle?.update(dt);
+ viewer._afterAnimateHooks.push(state._idleHook);
if (state.mocap) reattachMocap();
avatarInfo.textContent = `${state.avatar.name} · @${state.avatar.handle}`;
} catch (err) {
diff --git a/src/onchain/adapters/base.js b/src/onchain/adapters/base.js
index c0d0ab900..c4fcb551e 100644
--- a/src/onchain/adapters/base.js
+++ b/src/onchain/adapters/base.js
@@ -2,7 +2,13 @@
* WalletAdapter — the contract every chain family implements.
*
* The deploy orchestrator only ever sees this interface. New chains plug in by
- * adding a new adapter; the UI stays family-agnostic.
+ * adding a new adapter that conforms to the shape below; the UI stays
+ * family-agnostic.
+ *
+ * This is interface-by-convention: there's no runtime base class to extend
+ * because every subclass historically overrode every method, never called
+ * super, and never benefited from inherited behavior. The shape lives in
+ * JSDoc so static analysis still surfaces missing methods to authors.
*/
/**
@@ -14,70 +20,46 @@
/**
* @typedef {object} PrepResponse
* @property {string} prepId
- * @property {string} metadataUri // ipfs:// or https:// pointing at the manifest
- * @property {string} [contractAddress] // EVM: identity-registry address
- * @property {string} [txBase64] // Solana: serialized unsigned tx
- * @property {string} [assetPubkey] // Solana: mint pubkey
+ * @property {string} metadataUri ipfs:// or https:// pointing at the manifest
+ * @property {string} [contractAddress] EVM: identity-registry address
+ * @property {string} [txBase64] Solana: serialized unsigned tx
+ * @property {string} [assetPubkey] Solana: mint pubkey
* @property {string} [chainCaip2]
*/
/**
* @typedef {object} SignResult
- * @property {string} txHash // EVM tx hash or Solana signature
- * @property {string} [onchainId] // Optional family-specific ID (EVM agentId, Solana asset)
+ * @property {string} txHash EVM tx hash or Solana signature
+ * @property {string} [onchainId] Optional family-specific ID (EVM agentId, Solana asset)
*/
/**
- * @abstract
+ * @typedef {object} WalletAdapter
+ * @property {'evm'|'solana'} family
+ * Chain family this adapter implements.
+ * @property {() => boolean} isAvailable
+ * Whether an injected provider is detectable in this browser session.
+ * @property {() => string} installUrl
+ * URL to install a typical wallet for this family.
+ * @property {(opts?: { ensureLinked?: boolean, csrfToken?: string }) => Promise<ConnectResult>} connect
+ * Connect (and on Solana, optionally SIWS-link) the user's wallet.
+ * Must throw on user rejection with `err.code === 'USER_REJECTED'`.
+ * @property {(ref: import('../chain-ref.js').ChainRef) => Promise<void>} switchTo
+ * Switch the wallet to the given ChainRef. EVM wallets prompt the user;
+ * Solana wallets typically have no concept of switching — adapters return
+ * silently if already on the right cluster, or throw if mismatched.
+ * @property {(prep: PrepResponse, ref: import('../chain-ref.js').ChainRef) => Promise<SignResult>} signAndSend
+ * Sign and submit the prep transaction returned by the server.
*/
-export class WalletAdapter {
- /** @returns {string} 'evm' | 'solana' */
- get family() {
- throw new Error('not implemented');
- }
-
- /** @returns {boolean} Whether an injected provider is detectable. */
- isAvailable() {
- throw new Error('not implemented');
- }
-
- /** @returns {string} URL to install a typical wallet for this family. */
- installUrl() {
- throw new Error('not implemented');
- }
-
- /**
- * Connect (and on-Solana, optionally SIWS-link) the user's wallet.
- * Implementations must throw on user rejection with `err.code === 'USER_REJECTED'`.
- * @param {{ ensureLinked?: boolean, csrfToken?: string }} [opts]
- * @returns {Promise<ConnectResult>}
- */
- async connect(_opts) {
- throw new Error('not implemented');
- }
-
- /**
- * Switch the wallet to the given ChainRef. EVM wallets prompt the user;
- * Solana wallets typically have no concept of switching — adapters return
- * silently if already on the right cluster, or throw if mismatched.
- * @param {import('../chain-ref.js').ChainRef} ref
- */
- async switchTo(_ref) {
- throw new Error('not implemented');
- }
- /**
- * Sign and submit the prep transaction returned by the server.
- * @param {PrepResponse} prep
- * @param {import('../chain-ref.js').ChainRef} ref
- * @returns {Promise<SignResult>}
- */
- async signAndSend(_prep, _ref) {
- throw new Error('not implemented');
- }
-}
-
-/** Helper: classify a thrown error as a user rejection across providers. */
+/**
+ * Classify a thrown error as a user rejection across providers. Recognizes
+ * the union of conventions used by MetaMask, Phantom, Solflare, WalletConnect,
+ * and our own adapters.
+ *
+ * @param {unknown} err
+ * @returns {boolean}
+ */
export function isUserRejection(err) {
if (!err) return false;
if (err.code === 'USER_REJECTED') return true;
diff --git a/src/onchain/adapters/evm.js b/src/onchain/adapters/evm.js
index 3bfcd4694..df5c6a06e 100644
--- a/src/onchain/adapters/evm.js
+++ b/src/onchain/adapters/evm.js
@@ -5,12 +5,12 @@
* don't fork wallet state. The adapter is a thin facade over those helpers.
*/
-import { WalletAdapter } from './base.js';
import { ensureWallet, getIdentityRegistry } from '../../erc8004/agent-registry.js';
import { switchChain, CHAIN_META } from '../../erc8004/chain-meta.js';
import { evm } from '../chain-ref.js';
-export class EvmAdapter extends WalletAdapter {
+/** @implements {import('./base.js').WalletAdapter} */
+export class EvmAdapter {
get family() {
return 'evm';
}
diff --git a/src/onchain/adapters/solana.js b/src/onchain/adapters/solana.js
index 63ebefb1b..d526a17f6 100644
--- a/src/onchain/adapters/solana.js
+++ b/src/onchain/adapters/solana.js
@@ -13,7 +13,6 @@
*/
import { Connection, Transaction, VersionedTransaction } from '@solana/web3.js';
-import { WalletAdapter } from './base.js';
import { solana } from '../chain-ref.js';
// Route through our same-origin proxy. The public mainnet RPC returns 403 to
@@ -63,13 +62,13 @@ function decodeTx(b64) {
}
}
-export class SolanaAdapter extends WalletAdapter {
+/** @implements {import('./base.js').WalletAdapter} */
+export class SolanaAdapter {
#provider = null;
#address = null;
#preferred;
constructor({ preferredWallet = null } = {}) {
- super();
this.#preferred = preferredWallet;
}
diff --git a/src/onchain/tokens/base.js b/src/onchain/tokens/base.js
index fc77c7472..80d07dcb5 100644
--- a/src/onchain/tokens/base.js
+++ b/src/onchain/tokens/base.js
@@ -8,6 +8,10 @@
* A "token" here is a fungible asset bound to an agent identity (memecoin on a
* bonding curve, social token, etc.). Distinct from the agent's *identity* NFT
* minted via the deploy flow.
+ *
+ * Interface-by-convention: subclasses historically override every method and
+ * never call super. The shape lives in JSDoc so authors get static-analysis
+ * feedback without a runtime base class that exists only to throw.
*/
/**
@@ -30,28 +34,11 @@
*/
/**
- * @abstract
+ * @typedef {object} TokenAdapter
+ * @property {string} provider 'pumpfun' | 'zora' | etc.
+ * @property {'solana'|'evm'} family
+ * @property {(ctx: { agent: object }) => { ok: boolean, reason?: string }} validatePreconditions
+ * Validate that a launch is permitted for the given agent state. Adapters
+ * use this to enforce constraints (Pump.fun is Solana-only, requires the
+ * agent to already have a Solana identity, etc.).
*/
-export class TokenAdapter {
- /** @returns {string} 'pumpfun' | etc. */
- get provider() {
- throw new Error('not implemented');
- }
-
- /** @returns {string} 'solana' | 'evm' */
- get family() {
- throw new Error('not implemented');
- }
-
- /**
- * Validate that a launch is permitted for the given agent state. Adapters
- * use this to enforce constraints (Pump.fun is Solana-only, requires the
- * agent to already have a Solana identity, etc.).
- *
- * @param {{ agent: object }} ctx
- * @returns {{ ok: boolean, reason?: string }}
- */
- validatePreconditions(_ctx) {
- throw new Error('not implemented');
- }
-}
diff --git a/src/onchain/tokens/pumpfun.js b/src/onchain/tokens/pumpfun.js
index fa3148b4e..9f21a1ac5 100644
--- a/src/onchain/tokens/pumpfun.js
+++ b/src/onchain/tokens/pumpfun.js
@@ -16,7 +16,6 @@
*/
import { Connection, Transaction, VersionedTransaction } from '@solana/web3.js';
-import { TokenAdapter } from './base.js';
import { getAdapter as getWalletAdapter } from '../adapters/index.js';
// Route through our same-origin proxy. The public mainnet RPC returns 403 to
@@ -42,7 +41,8 @@ function decodeTx(b64) {
}
}
-export class PumpfunTokenAdapter extends TokenAdapter {
+/** @implements {import('./base.js').TokenAdapter} */
+export class PumpfunTokenAdapter {
get provider() {
return 'pumpfun';
}
diff --git a/src/runtime/data-reactive.js b/src/runtime/data-reactive.js
index 45e5f474d..c903a844d 100644
--- a/src/runtime/data-reactive.js
+++ b/src/runtime/data-reactive.js
@@ -170,6 +170,9 @@ function startPoll(url, intervalMs, parseFn, protocol, bindings, stats, signal)
});
};
+ // Fire immediately so callers don't wait an entire intervalMs for the first
+ // payload — the recurring schedule kicks in after this first tick.
+ tick();
const timer = setInterval(tick, intervalMs);
function stop() {
diff --git a/tests/api/x402-spec.test.js b/tests/api/x402-spec.test.js
index aa430db89..53d0337cb 100644
--- a/tests/api/x402-spec.test.js
+++ b/tests/api/x402-spec.test.js
@@ -11,13 +11,16 @@
// - send402: writes a base64 PAYMENT-REQUIRED header that round-trips through
// JSON.parse with the same extensions set.
-import { afterEach, beforeEach, describe, it, expect } from 'vitest';
+import { afterEach, beforeEach, describe, it, expect, vi } from 'vitest';
// env.js exposes process.env via getters, so each test's env mutations are
// picked up immediately by api/_lib/x402-spec.js without needing a module
// reset. We import the spec module once for the whole file — a fresh import
// per test would re-walk @coinbase/x402 + @x402/extensions (cold-load > 30s
-// on a CI worker) for no behavioural benefit.
+// on a CI worker) for no behavioural benefit. The bump to 30s covers the
+// one-off cold-import on the very first test.
+vi.setConfig({ testTimeout: 30_000 });
+
const specPromise = import('../../api/_lib/x402-spec.js');
const ORIG_ENV = { ...process.env };
diff --git a/vercel.json b/vercel.json
index 44db13646..eb88fe95a 100644
--- a/vercel.json
+++ b/vercel.json
@@ -1692,6 +1692,14 @@
"src": "/chat/(.*)",
"dest": "/chat/$1"
},
+ {
+ "src": "/import/rpm",
+ "dest": "/import-rpm.html"
+ },
+ {
+ "src": "/import/rpm/",
+ "dest": "/import-rpm.html"
+ },
{
"src": "/create/selfie",
"dest": "/create-selfie.html"
diff --git a/vite.config.js b/vite.config.js
index 762b0c183..622cf0946 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -133,6 +133,7 @@ const appConfig = {
create: resolve(__dirname, 'pages/create.html'),
'create-selfie': resolve(__dirname, 'pages/create-selfie.html'),
'create-review': resolve(__dirname, 'pages/create-review.html'),
+ 'import-rpm': resolve(__dirname, 'pages/import-rpm.html'),
'agent-home': resolve(__dirname, 'pages/agent-home.html'),
marketplace: resolve(__dirname, 'pages/marketplace.html'),
'agent-edit': resolve(__dirname, 'pages/agent-edit.html'),
@@ -246,6 +247,8 @@ const appConfig = {
'/create/selfie/': resolve(root, 'pages/create-selfie.html'),
'/create-review': resolve(root, 'pages/create-review.html'),
'/create-review/': resolve(root, 'pages/create-review.html'),
+ '/import/rpm': resolve(root, 'pages/import-rpm.html'),
+ '/import/rpm/': resolve(root, 'pages/import-rpm.html'),
'/dashboard': resolve(root, 'public/dashboard/index.html'),
'/studio': resolve(root, 'public/studio/index.html'),
'/studio/': resolve(root, 'public/studio/index.html'),
diff --git a/vitest.config.js b/vitest.config.js
index c423b0a00..f8d5be67f 100644
--- a/vitest.config.js
+++ b/vitest.config.js
@@ -1,8 +1,15 @@
import { defineConfig } from 'vitest/config';
+// Cold dynamic `import()` of API handlers that pull in heavy SDKs (@coinbase/x402,
+// neon-serverless, jsdom, the Solana toolchain, etc.) routinely takes 5–15s on
+// the first hit. The default 5s test timeout flaked those tests on every fresh
+// node_modules — bumping the global ceiling to 20s removes the flake without
+// hiding real hangs (long-running tests still get individual timeouts).
export default defineConfig({
test: {
environment: 'node',
include: ['tests/**/*.test.js', 'tests/**/*.test.mjs', 'src/**/*.test.js'],
+ testTimeout: 20_000,
+ hookTimeout: 20_000,
},
});