Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat: avatar edit/rig, RPM import, account + avatar actions updates

nirholas999d56ccfc6f
diff --git a/api/agents/x402/[action].js b/api/agents/x402/[action].js
index 4926df288..db9eab6df 100644
--- a/api/agents/x402/[action].js
+++ b/api/agents/x402/[action].js
@@ -5,7 +5,7 @@ import { sql } from '../../_lib/db.js';
import { getSessionUser, authenticateBearer, extractBearer } 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 { parse, isUuid } from '../../_lib/validate.js';
import { emit402, verifyPaid, consumeIntent, manifestOnly } from '../../_lib/x402.js';
import { calculateFee } from '../../_lib/fee.js';
import { insertNotification } from '../../_lib/notify.js';
diff --git a/api/avatars/_actions.js b/api/avatars/_actions.js
index cda88bd92..42eb79768 100644
--- a/api/avatars/_actions.js
+++ b/api/avatars/_actions.js
@@ -82,16 +82,30 @@ const handleUpload = wrap(async (req, res) => {
return error(res, 415, 'unsupported_media_type', `content_type must be one of: ${[...PROXY_CONTENT_TYPES].join(', ')}`);
}
- const declaredLength = Number(req.headers['content-length']);
- if (Number.isFinite(declaredLength) && declaredLength > MAX_PROXY_UPLOAD_BYTES) {
- return error(res, 413, 'payload_too_large', `body exceeds ${MAX_PROXY_UPLOAD_BYTES} bytes — use presigned upload for larger GLBs`);
- }
-
+ // Two body modes:
+ // • source_url=<http(s) GLB URL> — we fetch the bytes server-side. This is
+ // the URL-import path: the browser can't fetch most avatar CDNs directly
+ // (CloudFront/Arweave/etc. send no CORS headers), so we pull it here where
+ // same-origin policy doesn't apply. SSRF-guarded against internal targets.
+ // • raw octet-stream body — the CORS-fallback path for client-held blobs.
+ const sourceUrl = url.searchParams.get('source_url');
let buffer;
- try {
- buffer = await readRawBody(req, MAX_PROXY_UPLOAD_BYTES);
- } catch (err) {
- return error(res, err.status || 400, err.code || 'invalid_body', err.message || 'failed to read body');
+ if (sourceUrl) {
+ try {
+ buffer = await fetchRemoteGlb(sourceUrl, MAX_PROXY_UPLOAD_BYTES);
+ } catch (err) {
+ return error(res, err.status || 502, err.code || 'fetch_failed', err.message || 'failed to fetch source URL');
+ }
+ } else {
+ const declaredLength = Number(req.headers['content-length']);
+ if (Number.isFinite(declaredLength) && declaredLength > MAX_PROXY_UPLOAD_BYTES) {
+ return error(res, 413, 'payload_too_large', `body exceeds ${MAX_PROXY_UPLOAD_BYTES} bytes — use presigned upload for larger GLBs`);
+ }
+ try {
+ buffer = await readRawBody(req, MAX_PROXY_UPLOAD_BYTES);
+ } catch (err) {
+ return error(res, err.status || 400, err.code || 'invalid_body', err.message || 'failed to read body');
+ }
}
if (!buffer.length) return error(res, 400, 'empty_body', 'no bytes received');
@@ -131,6 +145,122 @@ const handleUpload = wrap(async (req, res) => {
});
});
+// Fetch a remote GLB server-side for the URL-import flow. Guards against SSRF:
+// the URL is attacker-controlled (any signed-in user can submit one), so we
+// resolve every redirect hop's hostname to its IPs and reject anything that
+// points at loopback, private, link-local, or cloud-metadata ranges before a
+// single byte is read. Streamed with a hard byte cap and a wall-clock timeout.
+const REMOTE_FETCH_TIMEOUT_MS = 20_000;
+const MAX_REMOTE_REDIRECTS = 5;
+
+async function fetchRemoteGlb(rawUrl, maxBytes) {
+ let target;
+ try {
+ target = new URL(rawUrl);
+ } catch {
+ throw fetchError(400, 'invalid_url', 'source_url is not a valid URL');
+ }
+ const ac = new AbortController();
+ const timer = setTimeout(() => ac.abort(), REMOTE_FETCH_TIMEOUT_MS);
+ try {
+ let resp;
+ for (let hop = 0; hop <= MAX_REMOTE_REDIRECTS; hop++) {
+ if (!['http:', 'https:'].includes(target.protocol)) {
+ throw fetchError(400, 'unsupported_scheme', 'only http(s) URLs can be imported');
+ }
+ await assertPublicHost(target.hostname);
+ resp = await fetch(target.href, {
+ redirect: 'manual',
+ signal: ac.signal,
+ headers: { accept: 'model/gltf-binary,application/octet-stream,*/*' },
+ });
+ if (resp.status >= 300 && resp.status < 400 && resp.headers.get('location')) {
+ if (hop === MAX_REMOTE_REDIRECTS) throw fetchError(502, 'too_many_redirects', 'source URL redirected too many times');
+ target = new URL(resp.headers.get('location'), target);
+ continue;
+ }
+ break;
+ }
+ if (!resp.ok) throw fetchError(502, 'fetch_failed', `source URL returned HTTP ${resp.status}`);
+
+ const declared = Number(resp.headers.get('content-length'));
+ if (Number.isFinite(declared) && declared > maxBytes) {
+ throw fetchError(413, 'payload_too_large', `source file is ${declared} bytes — max ${maxBytes}`);
+ }
+
+ const reader = resp.body?.getReader();
+ if (!reader) throw fetchError(502, 'empty_body', 'source URL returned no body');
+ const chunks = [];
+ let total = 0;
+ for (;;) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ total += value.length;
+ if (total > maxBytes) {
+ await reader.cancel();
+ throw fetchError(413, 'payload_too_large', `source file exceeds ${maxBytes} bytes`);
+ }
+ chunks.push(value);
+ }
+ return Buffer.concat(chunks.map((c) => Buffer.from(c)));
+ } catch (err) {
+ if (err.code && err.status) throw err;
+ if (err.name === 'AbortError') throw fetchError(504, 'fetch_timeout', 'source URL timed out');
+ throw fetchError(502, 'fetch_failed', err.message || 'failed to fetch source URL');
+ } finally {
+ clearTimeout(timer);
+ }
+}
+
+function fetchError(status, code, message) {
+ const err = new Error(message);
+ err.status = status;
+ err.code = code;
+ return err;
+}
+
+// Reject hostnames that resolve to non-public address space (SSRF defense).
+async function assertPublicHost(hostname) {
+ const host = hostname.replace(/^\[|\]$/g, '').toLowerCase();
+ if (host === 'localhost' || host.endsWith('.localhost') || host.endsWith('.internal') || host.endsWith('.local')) {
+ throw fetchError(400, 'blocked_host', 'source_url host is not allowed');
+ }
+ const { lookup } = await import('dns/promises');
+ let records;
+ try {
+ records = await lookup(host, { all: true });
+ } catch {
+ throw fetchError(400, 'dns_failure', 'could not resolve source_url host');
+ }
+ for (const { address } of records) {
+ if (isPrivateAddress(address)) {
+ throw fetchError(400, 'blocked_host', 'source_url resolves to a non-public address');
+ }
+ }
+}
+
+function isPrivateAddress(ip) {
+ if (ip.includes(':')) {
+ const v6 = ip.toLowerCase();
+ if (v6 === '::1' || v6 === '::') return true;
+ if (v6.startsWith('fe80') || v6.startsWith('fc') || v6.startsWith('fd')) return true;
+ // IPv4-mapped IPv6 (::ffff:a.b.c.d) — unwrap and re-check.
+ const mapped = v6.match(/::ffff:(\d+\.\d+\.\d+\.\d+)$/);
+ if (mapped) return isPrivateAddress(mapped[1]);
+ return false;
+ }
+ const p = ip.split('.').map(Number);
+ if (p.length !== 4 || p.some((n) => !Number.isInteger(n) || n < 0 || n > 255)) return true;
+ const [a, b] = p;
+ if (a === 0 || a === 10 || a === 127) return true;
+ if (a === 169 && b === 254) return true; // link-local incl. 169.254.169.254 metadata
+ if (a === 172 && b >= 16 && b <= 31) return true;
+ if (a === 192 && b === 168) return true;
+ if (a === 100 && b >= 64 && b <= 127) return true; // CGNAT
+ if (a >= 224) return true; // multicast / reserved
+ return false;
+}
+
function readRawBody(req, limit) {
return new Promise((resolve, reject) => {
const chunks = [];
diff --git a/pages/avatar-edit.html b/pages/avatar-edit.html
index 92f5f5163..9ee8c1d25 100644
--- a/pages/avatar-edit.html
+++ b/pages/avatar-edit.html
@@ -663,6 +663,53 @@
gap: 8px;
justify-content: flex-end;
}
+ /* ── Animate / rig panel ───────────────────────────────── */
+ .ae-rig { display: flex; flex-direction: column; gap: 16px; padding: 4px 2px; }
+ .ae-rig-pill {
+ display: inline-flex;
+ align-items: center;
+ gap: 8px;
+ align-self: flex-start;
+ padding: 5px 12px;
+ border-radius: 999px;
+ font-size: 12px;
+ font-weight: 600;
+ letter-spacing: 0.01em;
+ border: 1px solid var(--border-2);
+ color: var(--text-2);
+ }
+ .ae-rig-dot { width: 8px; height: 8px; border-radius: 50%; background: var(--text-3); }
+ .ae-rig-pill.ok { color: #34d399; border-color: rgba(52, 211, 153, 0.35); }
+ .ae-rig-pill.ok .ae-rig-dot { background: #34d399; box-shadow: 0 0 8px rgba(52, 211, 153, 0.6); }
+ .ae-rig-pill.warn { color: #fbbf24; border-color: rgba(251, 191, 36, 0.35); }
+ .ae-rig-pill.warn .ae-rig-dot { background: #fbbf24; }
+ .ae-rig-pill.unknown { color: var(--text-3); }
+ .ae-rig-detail { margin: 0; font-size: 13px; line-height: 1.5; color: var(--text-2); }
+ .ae-rig-action { display: flex; flex-direction: column; gap: 10px; }
+ .ae-rig-action .ae-btn { align-self: flex-start; }
+ .ae-rig-note { margin: 0; font-size: 12px; line-height: 1.5; color: var(--text-3); }
+ .ae-rig-error {
+ font-size: 13px;
+ line-height: 1.5;
+ color: var(--danger);
+ padding: 10px 12px;
+ border: 1px solid rgba(244, 63, 94, 0.3);
+ border-radius: 10px;
+ background: rgba(244, 63, 94, 0.06);
+ }
+ .ae-rig-busy { display: flex; flex-direction: column; align-items: center; gap: 14px; padding: 28px 8px; text-align: center; }
+ .ae-rig-spinner {
+ width: 28px; height: 28px;
+ border-radius: 50%;
+ border: 3px solid var(--border-2);
+ border-top-color: var(--text);
+ animation: ae-spin 0.9s linear infinite;
+ }
+ .ae-rig-busy-msg { margin: 0; font-size: 14px; font-weight: 600; color: var(--text); }
+ .ae-rig-busy-hint { margin: 0; font-size: 12px; color: var(--text-3); }
+ .ae-rig-bar { width: 100%; height: 6px; border-radius: 999px; background: var(--panel-2); overflow: hidden; }
+ .ae-rig-bar-fill { height: 100%; background: var(--text); border-radius: 999px; transition: width 0.4s ease; }
+ .ae-rig-done { display: flex; flex-direction: column; gap: 14px; padding: 8px 2px; }
</style>
</head>
<body>
diff --git a/pages/import-rpm.html b/pages/import-rpm.html
index b4a857d53..fb6b65127 100644
--- a/pages/import-rpm.html
+++ b/pages/import-rpm.html
@@ -381,10 +381,10 @@
<div class="warn-banner">
<span class="warn-banner-icon">⚠</span>
<span>
- <strong>The original avatar CDN 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.
+ <strong>Paste any live GLB URL</strong> — we fetch it on our servers,
+ so CORS-restricted CDNs (CloudFront, Arweave, your own storage) all
+ work. If the original host is gone, or you already have the file on
+ disk, use the <em>Upload GLB</em> tab instead.
</span>
</div>
diff --git a/src/account.js b/src/account.js
index 816e52964..bef2fd468 100644
--- a/src/account.js
+++ b/src/account.js
@@ -103,7 +103,11 @@ export async function saveRemoteGlbToAccount(source, meta = {}, opts = {}) {
}
if (me === null) throw stageError('auth', 'Not signed in', { code: 'not_signed_in' });
- let blob;
+ // `serverFetched` is set when we couldn't pull the GLB in the browser and let
+ // the API fetch it instead — in that branch the bytes already live in R2, so
+ // we skip the local canonicalize/presign/upload steps and commit directly.
+ let blob = null;
+ let serverFetched = null;
if (source instanceof Blob) {
blob = source;
} else {
@@ -114,81 +118,103 @@ export async function saveRemoteGlbToAccount(source, meta = {}, opts = {}) {
blob = await resp.blob();
} catch (err) {
if (err.stage) throw err;
- throw stageError('fetch', err.message || 'failed to fetch source GLB');
+ // Most avatar CDNs (RPM CloudFront, Arweave, arbitrary storage) serve
+ // no CORS headers, so a browser fetch is blocked. Fall back to a
+ // server-side fetch: the API pulls the file for us — no CORS, no SSRF
+ // exposure — and stores it directly. This is the normal URL-import path.
+ log.warn('[account] client-side GLB fetch blocked; fetching via server', err?.message);
+ onProgress?.(0);
+ try {
+ serverFetched = await fetchRemoteViaProxy(String(source), { onProgress, signal });
+ } catch (proxyErr) {
+ proxyErr.stage = proxyErr.stage || 'fetch';
+ throw proxyErr;
+ }
}
}
- // Canonicalize humanoid bone names before upload so the pre-baked Mixamo
- // animation library plays out of the box. Non-fatal — if the buffer isn't
- // a valid GLB or the rig isn't humanoid, fall through with the original.
let retargetedBoneCount = 0;
- try {
- const { canonicalizeGLBBones } = await import('./glb-canonicalize.js');
- const buf = await blob.arrayBuffer();
- const result = canonicalizeGLBBones(buf);
- if (result.renamed > 0) {
- blob = new Blob([result.buffer], { type: 'model/gltf-binary' });
- retargetedBoneCount = result.renamed;
- }
- } catch (err) {
- log.warn('[account] canonicalize failed; uploading original', err);
- }
-
- const size = blob.size;
- const contentType = blob.type || 'model/gltf-binary';
- const checksum = await sha256Hex(blob);
-
- // Presign + direct browser→R2 PUT is the happy path: cheapest, doesn't
- // route bytes through our function. When the deploy origin isn't in the
- // bucket CORS allowlist (ephemeral Codespaces hosts, branch deploys with a
- // new hostname), the preflight fails. In that case fall through to the
- // server-side proxy upload so the save always completes regardless of
- // bucket CORS state.
let storageKey = null;
- let presign = null;
-
- try {
- presign = await postJson('/api/avatars/presign', {
- size_bytes: size,
- content_type: contentType,
- checksum_sha256: checksum,
- });
- } catch (err) {
- err.stage = err.stage || 'presign';
- throw err;
- }
+ let size;
+ let contentType;
+ let checksum;
+
+ if (serverFetched) {
+ storageKey = serverFetched.storage_key;
+ size = serverFetched.size_bytes;
+ contentType = serverFetched.content_type || 'model/gltf-binary';
+ checksum = serverFetched.checksum_sha256;
+ onProgress?.(100);
+ } else {
+ // Canonicalize humanoid bone names before upload so the pre-baked Mixamo
+ // animation library plays out of the box. Non-fatal — if the buffer isn't
+ // a valid GLB or the rig isn't humanoid, fall through with the original.
+ try {
+ const { canonicalizeGLBBones } = await import('./glb-canonicalize.js');
+ const buf = await blob.arrayBuffer();
+ const result = canonicalizeGLBBones(buf);
+ if (result.renamed > 0) {
+ blob = new Blob([result.buffer], { type: 'model/gltf-binary' });
+ retargetedBoneCount = result.renamed;
+ }
+ } catch (err) {
+ log.warn('[account] canonicalize failed; uploading original', err);
+ }
- try {
- await putToR2({
- url: presign.upload_url,
- blob,
- contentType,
- onProgress,
- signal,
- });
- storageKey = presign.storage_key;
- } catch (err) {
- if (err.code === 'upload_aborted') throw err;
- if (err.code !== 'upload_blocked') {
- err.stage = err.stage || 'upload';
+ size = blob.size;
+ contentType = blob.type || 'model/gltf-binary';
+ checksum = await sha256Hex(blob);
+
+ // Presign + direct browser→R2 PUT is the happy path: cheapest, doesn't
+ // route bytes through our function. When the deploy origin isn't in the
+ // bucket CORS allowlist (ephemeral Codespaces hosts, branch deploys with a
+ // new hostname), the preflight fails. In that case fall through to the
+ // server-side proxy upload so the save always completes regardless of
+ // bucket CORS state.
+ let presign = null;
+ try {
+ presign = await postJson('/api/avatars/presign', {
+ size_bytes: size,
+ content_type: contentType,
+ checksum_sha256: checksum,
+ });
+ } catch (err) {
+ err.stage = err.stage || 'presign';
throw err;
}
- log.warn('[account] direct R2 PUT blocked; retrying via server proxy');
- // Reset progress so the proxy attempt restarts visibly at 0% rather than
- // looking stuck at whatever the direct PUT reached before failing.
- onProgress?.(0);
+
try {
- const proxied = await uploadViaProxy({
+ await putToR2({
+ url: presign.upload_url,
blob,
contentType,
- checksum,
onProgress,
signal,
});
- storageKey = proxied.storage_key;
- } catch (proxyErr) {
- proxyErr.stage = proxyErr.stage || 'upload';
- throw proxyErr;
+ storageKey = presign.storage_key;
+ } catch (err) {
+ if (err.code === 'upload_aborted') throw err;
+ if (err.code !== 'upload_blocked') {
+ err.stage = err.stage || 'upload';
+ throw err;
+ }
+ log.warn('[account] direct R2 PUT blocked; retrying via server proxy');
+ // Reset progress so the proxy attempt restarts visibly at 0% rather than
+ // looking stuck at whatever the direct PUT reached before failing.
+ onProgress?.(0);
+ try {
+ const proxied = await uploadViaProxy({
+ blob,
+ contentType,
+ checksum,
+ onProgress,
+ signal,
+ });
+ storageKey = proxied.storage_key;
+ } catch (proxyErr) {
+ proxyErr.stage = proxyErr.stage || 'upload';
+ throw proxyErr;
+ }
}
}
@@ -229,7 +255,7 @@ export async function saveRemoteGlbToAccount(source, meta = {}, opts = {}) {
// /demos/usdz-ar passes generateCompanions:true). The live /create flow
// stays untouched — those derivations run client-side and add several
// seconds of CPU on every save, so they don't ship to all users yet.
- if (meta.generateCompanions) {
+ if (meta.generateCompanions && blob) {
generateAndSaveCompanions(avatar.id, blob).catch((err) => {
log.warn('[account] usdz/halfbody pipeline failed silently', err?.message);
});
@@ -539,6 +565,42 @@ async function uploadViaProxy({ blob, contentType, checksum, onProgress, signal
});
}
+// Server-side fetch for URL imports: the API pulls the GLB from `sourceUrl`
+// itself (where same-origin/CORS doesn't apply) and stores it in R2, returning
+// the storage_key + verified size/checksum to commit with. Used when the
+// browser can't fetch the source directly — the common case for avatar CDNs
+// that send no CORS headers. The request body is empty; the URL is passed as a
+// query param and validated server-side against SSRF.
+async function fetchRemoteViaProxy(sourceUrl, { onProgress, signal } = {}) {
+ if (signal?.aborted) {
+ throw stageError('fetch', 'Import aborted', { code: 'upload_aborted' });
+ }
+ const qs = new URLSearchParams({ content_type: 'model/gltf-binary', source_url: sourceUrl });
+ // The browser shows indeterminate progress while the server fetches+stores.
+ // apiFetch attaches the CSRF token for us on POST.
+ onProgress?.(50);
+ const res = await apiFetch(`${API}/api/avatars/upload?${qs.toString()}`, {
+ method: 'POST',
+ headers: { 'content-type': 'model/gltf-binary' },
+ signal,
+ });
+ const data = res.headers.get('content-type')?.includes('application/json')
+ ? await res.json()
+ : null;
+ if (res.status === 401) {
+ throw stageError('fetch', 'session expired', { status: 401, code: 'not_signed_in' });
+ }
+ if (!res.ok || !data?.storage_key) {
+ throw stageError(
+ 'fetch',
+ data?.error_description || `server fetch failed: ${res.status}`,
+ { code: data?.error || 'fetch_failed', status: res.status },
+ );
+ }
+ onProgress?.(100);
+ return data;
+}
+
function stageError(stage, message, extras = {}) {
const err = new Error(message);
err.stage = stage;
diff --git a/src/avatar-edit.js b/src/avatar-edit.js
index 88bb78ed8..e697766e7 100644
--- a/src/avatar-edit.js
+++ b/src/avatar-edit.js
@@ -24,6 +24,7 @@ import { uploadAvatarSnapshot } from './voice/avatar-snapshot.js';
import { IdleAnimation } from './idle-animation.js';
import { renderSculptPanel } from './avatar-sculpt.js';
import { renderWardrobePanel } from './avatar-wardrobe.js';
+import { renderRigPanel } from './avatar-rig.js';
import { playAs } from './game/play-handoff.js';
import { log } from './shared/log.js';
@@ -87,6 +88,7 @@ const TABS = [
{ id: 'glasses', label: 'Glasses', kinds: ['glasses'], emoji: '🕶️', single: true },
{ id: 'earrings', label: 'Earrings', kinds: ['earrings'], emoji: '💎', single: false },
{ id: 'sculpt', label: 'Sculpt', kinds: [], emoji: '✨', single: true, sculpt: true },
+ { id: 'rig', label: 'Animate', kinds: [], emoji: '🦴', rig: true },
];
const KIND_EMOJI = {
outfit: '👕',
@@ -302,6 +304,22 @@ function renderActivePanel() {
return;
}
+ // Animate tab: rig status + one-click auto-rig. Turns a static mesh into an
+ // animation-ready avatar via the regenerate(mode:'rerig') backend. Rigging is
+ // non-destructive — it mints a new sibling avatar — so on success we hand the
+ // owner straight into that new avatar's editor.
+ if (tab.rig) {
+ renderRigPanel({
+ container: panel,
+ avatar,
+ onRigged: (newAvatar) => {
+ if (!newAvatar?.id) return;
+ location.href = `/avatars/${encodeURIComponent(newAvatar.id)}/edit`;
+ },
+ });
+ return;
+ }
+
const q = searchQuery.trim().toLowerCase();
const items = presets.filter(
(p) => tab.kinds.includes(p.kind) && (!q || p.name.toLowerCase().includes(q)),
diff --git a/src/avatar-rig.js b/src/avatar-rig.js
new file mode 100644
index 000000000..a8ac40d55
--- /dev/null
+++ b/src/avatar-rig.js
@@ -0,0 +1,303 @@
+/**
+ * Avatar rigging panel — /avatars/:id/edit → "Animate" tab.
+ *
+ * A static (un-rigged) mesh can't play the pre-baked animation library: it has
+ * no skeleton to drive. This panel turns such a mesh into an animation-ready
+ * avatar by routing it through the platform's auto-rig backend (UniRig on the
+ * GCP pipeline, or a Replicate rerig model) via the existing regenerate API.
+ *
+ * Flow (client side of the documented REGENERATE.md contract):
+ * 1. POST /api/avatars/regenerate { sourceAvatarId, mode: 'rerig' } → jobId
+ * 2. Poll GET /api/avatars/regenerate-status?jobId=… until done|failed
+ * 3. On done → fetch resultGlbUrl, canonicalize bones, register it as a new
+ * owned avatar (parent = source) via saveRemoteGlbToAccount.
+ * 4. Hand the new rigged avatar back to the editor via onRigged().
+ *
+ * Non-destructive by design: rigging produces a new sibling avatar so the
+ * original static mesh is never overwritten.
+ */
+
+import { saveRemoteGlbToAccount } from './account.js';
+import { log } from './shared/log.js';
+
+const POLL_INTERVAL_MS = 2500;
+const POLL_TIMEOUT_MS = 5 * 60 * 1000; // auto-rig backends finish well within 5 min
+
+// ── Rig status ─────────────────────────────────────────────────────────
+
+/**
+ * Derive a human-meaningful rig status from an avatar's source_meta. The
+ * reconstruct pipeline stamps is_rigged / skeleton_joint_count when it
+ * inspects a delivered GLB (api/_lib/glb-inspect.js); uploads that were never
+ * inspected leave it unknown.
+ * @returns {{ rigged: boolean, known: boolean, jointCount: number|null }}
+ */
+export function getRigStatus(avatar) {
+ const meta = avatar?.source_meta || {};
+ const flag = meta.is_rigged;
+ const jointCount =
+ typeof meta.skeleton_joint_count === 'number' ? meta.skeleton_joint_count : null;
+ if (flag === true || (jointCount != null && jointCount > 0)) {
+ return { rigged: true, known: true, jointCount };
+ }
+ if (flag === false) {
+ return { rigged: false, known: true, jointCount: jointCount ?? 0 };
+ }
+ // is_rigged absent — an upload we never skeleton-inspected. Treat as unknown
+ // so the UI offers to rig rather than falsely claiming "static".
+ return { rigged: false, known: false, jointCount };
+}
+
+// /api/config is small and stable for the session — fetch once.
+let _riggingAvailable = null;
+async function isRiggingAvailable() {
+ if (_riggingAvailable !== null) return _riggingAvailable;
+ try {
+ const r = await fetch('/api/config', { credentials: 'omit' });
+ const j = await r.json();
+ _riggingAvailable = j?.features?.avatarRigging === true;
+ } catch (err) {
+ log.warn('[rig] config probe failed; assuming rigging unavailable', err?.message);
+ _riggingAvailable = false;
+ }
+ return _riggingAvailable;
+}
+
+// ── Panel ──────────────────────────────────────────────────────────────
+
+/**
+ * Mount the rig panel into a container.
+ * @param {Object} options
+ * @param {HTMLElement} options.container
+ * @param {Object} options.avatar - the avatar being edited
+ * @param {(newAvatar: Object) => void} options.onRigged - called with the new rigged avatar
+ */
+export function renderRigPanel({ container, avatar, onRigged }) {
+ const status = getRigStatus(avatar);
+ const state = { phase: 'idle', message: null, progress: 0, jobId: null };
+ let cancelled = false;
+ let pollTimer = null;
+
+ function setState(patch) {
+ Object.assign(state, patch);
+ paint();
+ }
+
+ function cleanup() {
+ cancelled = true;
+ if (pollTimer) clearTimeout(pollTimer);
+ pollTimer = null;
+ }
+
+ async function startRigging() {
+ setState({ phase: 'submitting', message: 'Submitting your model to the rigging backend…', progress: 0.05 });
+ let jobId;
+ try {
+ const res = await fetch('/api/avatars/regenerate', {
+ method: 'POST',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ sourceAvatarId: avatar.id, mode: 'rerig' }),
+ });
+ const body = await res.json().catch(() => ({}));
+ if (!res.ok) {
+ const msg =
+ res.status === 501
+ ? "Auto-rigging isn't enabled on this deployment yet."
+ : body.error_description || body.error || `Couldn't start rigging (${res.status}).`;
+ setState({ phase: 'error', message: msg });
+ return;
+ }
+ jobId = body.jobId;
+ } catch (err) {
+ setState({ phase: 'error', message: err?.message || 'Network error starting the rig job.' });
+ return;
+ }
+ setState({ phase: 'rigging', message: 'Building skeleton and binding skin weights…', progress: 0.2, jobId });
+ pollUntilDone(jobId, Date.now());
+ }
+
+ function pollUntilDone(jobId, startedAt) {
+ if (cancelled) return;
+ pollTimer = setTimeout(async () => {
+ if (cancelled) return;
+ if (Date.now() - startedAt > POLL_TIMEOUT_MS) {
+ setState({ phase: 'error', message: 'Rigging is taking longer than expected. Try again in a few minutes.' });
+ return;
+ }
+ let body;
+ try {
+ const r = await fetch(`/api/avatars/regenerate-status?jobId=${encodeURIComponent(jobId)}`, {
+ credentials: 'include',
+ });
+ body = await r.json().catch(() => ({}));
+ if (!r.ok) throw new Error(body.error_description || body.error || `status ${r.status}`);
+ } catch (err) {
+ // Transient poll failure — keep waiting, surface only on timeout.
+ log.warn('[rig] status poll failed; retrying', err?.message);
+ pollUntilDone(jobId, startedAt);
+ return;
+ }
+
+ if (body.status === 'failed') {
+ setState({ phase: 'error', message: body.error || 'The rigging backend could not rig this model.' });
+ return;
+ }
+ if (body.status === 'done' && body.resultGlbUrl) {
+ await materialize(body.resultGlbUrl);
+ return;
+ }
+ // queued | running | rigging — nudge the progress bar forward and keep polling.
+ const elapsed = (Date.now() - startedAt) / POLL_TIMEOUT_MS;
+ setState({ progress: Math.min(0.9, 0.2 + elapsed * 0.7) });
+ pollUntilDone(jobId, startedAt);
+ }, POLL_INTERVAL_MS);
+ }
+
+ async function materialize(glbUrl) {
+ setState({ phase: 'saving', message: 'Saving your rigged, animation-ready avatar…', progress: 0.95 });
+ try {
+ const newAvatar = await saveRemoteGlbToAccount(glbUrl, {
+ name: `${avatar.name || 'Avatar'} (rigged)`,
+ visibility: avatar.visibility || 'private',
+ tags: Array.from(new Set([...(avatar.tags || []), 'rigged'])),
+ source: 'upload',
+ source_meta: {
+ rigged_from: avatar.id,
+ parent_avatar_id: avatar.id,
+ is_rigged: true,
+ rig_provider: 'auto-rig',
+ },
+ });
+ setState({ phase: 'done', message: null, progress: 1 });
+ onRigged?.(newAvatar);
+ } catch (err) {
+ const code = err?.code;
+ const msg =
+ code === 'not_signed_in'
+ ? 'Your session expired. Sign in again and retry.'
+ : err?.message || 'Rigging finished but saving the result failed. Try again.';
+ setState({ phase: 'error', message: msg });
+ }
+ }
+
+ function paint() {
+ container.innerHTML = '';
+ container.appendChild(buildView());
+ }
+
+ function buildView() {
+ const root = document.createElement('div');
+ root.className = 'ae-rig';
+
+ // Busy phases share one progress view.
+ if (['submitting', 'rigging', 'saving'].includes(state.phase)) {
+ root.appendChild(busyView(state));
+ return root;
+ }
+ if (state.phase === 'done') {
+ root.appendChild(doneView());
+ return root;
+ }
+ root.appendChild(statusView());
+ if (state.phase === 'error' && state.message) root.appendChild(errorView(state.message));
+ root.appendChild(actionView());
+ return root;
+ }
+
+ function statusView() {
+ const el = document.createElement('div');
+ el.className = 'ae-rig-status';
+ const rigged = status.rigged;
+ const dotClass = rigged ? 'ok' : status.known ? 'warn' : 'unknown';
+ const label = rigged
+ ? 'Animation-ready'
+ : status.known
+ ? 'Static mesh'
+ : 'Rig status unknown';
+ const detail = rigged
+ ? status.jointCount
+ ? `This avatar has a skeleton (${status.jointCount} joints) and can play the animation library.`
+ : 'This avatar already has a skeleton and can play the animation library.'
+ : status.known
+ ? 'This is a static mesh — no skeleton, so it can’t walk, wave, or emote. Rig it to unlock animations.'
+ : 'We haven’t detected a skeleton on this model. Rig it to make sure it can animate.';
+ el.innerHTML = `
+ <div class="ae-rig-pill ${dotClass}">
+ <span class="ae-rig-dot"></span>${label}
+ </div>
+ <p class="ae-rig-detail">${detail}</p>
+ `;
+ return el;
+ }
+
+ function actionView() {
+ const el = document.createElement('div');
+ el.className = 'ae-rig-action';
+
+ if (status.rigged) {
+ // Already rigged — offer a (clearly secondary) re-rig for broken/partial rigs.
+ const note = document.createElement('p');
+ note.className = 'ae-rig-note';
+ note.textContent = 'Already animation-ready. You only need to re-rig if animations look broken.';
+ el.appendChild(note);
+ }
+
+ const btn = document.createElement('button');
+ btn.className = `ae-btn ${status.rigged ? '' : 'primary'}`.trim();
+ btn.textContent = status.rigged ? 'Re-rig anyway' : 'Rig this model';
+ el.appendChild(btn);
+
+ // Gate the action on backend availability — checked lazily so the panel
+ // paints instantly. If unavailable, swap in an honest disabled state.
+ isRiggingAvailable().then((available) => {
+ if (cancelled) return;
+ if (!available) {
+ btn.disabled = true;
+ btn.textContent = 'Auto-rigging unavailable';
+ const hint = document.createElement('p');
+ hint.className = 'ae-rig-note';
+ hint.textContent =
+ 'Auto-rigging isn’t enabled on this deployment. Upload an already-rigged GLB to animate it.';
+ el.appendChild(hint);
+ } else {
+ btn.addEventListener('click', startRigging);
+ }
+ });
+
+ return el;
+ }
+
+ function busyView(s) {
+ const el = document.createElement('div');
+ el.className = 'ae-rig-busy';
+ const pct = Math.round((s.progress || 0) * 100);
+ el.innerHTML = `
+ <div class="ae-rig-spinner" aria-hidden="true"></div>
+ <p class="ae-rig-busy-msg">${s.message || 'Working…'}</p>
+ <div class="ae-rig-bar"><div class="ae-rig-bar-fill" style="width:${pct}%"></div></div>
+ <p class="ae-rig-busy-hint">Rigging usually takes 30–90 seconds. You can keep editing other tabs.</p>
+ `;
+ return el;
+ }
+
+ function doneView() {
+ const el = document.createElement('div');
+ el.className = 'ae-rig-done';
+ el.innerHTML = `
+ <div class="ae-rig-pill ok"><span class="ae-rig-dot"></span>Rigged</div>
+ <p class="ae-rig-detail">Your model now has a skeleton and is loading in the editor. It can play the full animation library.</p>
+ `;
+ return el;
+ }
+
+ function errorView(message) {
+ const el = document.createElement('div');
+ el.className = 'ae-rig-error';
+ el.textContent = message;
+ return el;
+ }
+
+ paint();
+ return { unmount: cleanup };
+}