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.

Marketplace, forge game-ready, skill mint, avatar and animation updates

nirholas23c9f94e9b84
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 442a15b76..3a50d8c80 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,6 +6,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
## 2026-06-17
+- **Animation Studio** (`/pose`) — Pose any three.ws avatar or the built-in mannequin with FK/IK, keyframe a timeline, and preview the motion live. Export an animated GLB or clip JSON, save animations to your account, play them back across the platform, and sell them for USDC.
- **How location works on IRL** (`/irl-privacy`) — Placed agents are private by location: they appear only to people physically standing near them, never on a map or a list. What's shared, what isn't, and how your camera, motion, and location are used.
- **x402 Live Demo (IBM × three.ws)** (`/ibm/x402-demo`) — A self-contained x402 micropayment demo: pay $0.001 USDC from your own wallet — MetaMask on Base or Phantom on Solana — to call a real three.ws data API. Watch the live HTTP 402 challenge, sign a gasless authorization, and see the on-chain settlement receipt. No backend, no account; built as the public face of the IBM × three.ws partnership.
- **Agent profiles now show the agent's real avatar — no more stray model over the name** — On an agent's profile page, agents that ship their own 3D avatar were briefly showing the plain mannequin in the headshot while a second copy of their real avatar rendered loose over the agent's name. Both are fixed: the headshot now loads the agent's own model directly in place, and opening it full-screen shows that same model. Agents using the default body are unchanged. `[fix]`
diff --git a/api/_lib/forge-tiers.js b/api/_lib/forge-tiers.js
index ebd4f054c..216e5daee 100644
--- a/api/_lib/forge-tiers.js
+++ b/api/_lib/forge-tiers.js
@@ -247,6 +247,37 @@ export const BACKENDS = Object.freeze({
}),
});
+// Post-generation export options layered onto a finished model — surfaced in the
+// catalog alongside tiers/backends so the UI can advertise them on the result
+// view. Game-Ready drives the workers/remesh service (QuadriFlow quad retopology
+// or silhouette-preserving low-poly) to turn any generated or uploaded mesh into
+// an engine-ready asset, delivered as GLB + FBX. `baseEta` is wall-clock seconds
+// for a single format; `priceUsdcAtomics` is the flat retail price (6 decimals),
+// consistent with the tier pricing above.
+export const OUTPUTS = Object.freeze({
+ gameready: Object.freeze({
+ id: 'gameready',
+ label: 'Game-Ready',
+ blurb: 'Clean retopology to a poly budget with PBR re-bake. Quad (QuadriFlow) or silhouette-preserving low-poly, exported as GLB + rig-aware FBX for Unity & Unreal.',
+ topologies: Object.freeze(['quad', 'tri']),
+ formats: Object.freeze(['glb', 'fbx']),
+ // Poly-budget presets surfaced as slider stops in the UI (target faces).
+ polyPresets: Object.freeze([5_000, 15_000, 50_000]),
+ textureSizes: Object.freeze([1024, 2048]),
+ baseEta: 35,
+ priceUsdcAtomics: 100_000, // $0.10
+ requiresEnv: Object.freeze(['GCP_REMESH_URL', 'GCP_RECONSTRUCTION_KEY']),
+ }),
+});
+
+// A platform export is "live" only when its worker env is present — same rule as
+// the platform backends above.
+export function outputIsConfigured(outputId) {
+ const o = OUTPUTS[outputId];
+ if (!o) return false;
+ return o.requiresEnv.every((name) => Boolean(readEnv(name)));
+}
+
// Standing backend chosen when the caller doesn't name one, per path. The image
// path keeps the image-capable Replicate TRELLIS default — it accepts user
// photos and serves every tier. The free NVIDIA NIM lane (text-only) is layered
@@ -393,6 +424,20 @@ export function buildCatalog() {
return acc;
}, {}),
})),
+ // Post-generation export options (Game-Ready, …) the result view can offer.
+ outputs: Object.values(OUTPUTS).map((o) => ({
+ id: o.id,
+ label: o.label,
+ blurb: o.blurb,
+ topologies: o.topologies,
+ formats: o.formats,
+ poly_presets: o.polyPresets,
+ texture_sizes: o.textureSizes,
+ eta_seconds: o.baseEta,
+ price_usdc_atomics: o.priceUsdcAtomics,
+ price_usdc: (o.priceUsdcAtomics / 1_000_000).toFixed(2),
+ configured: outputIsConfigured(o.id),
+ })),
};
}
diff --git a/api/_lib/reconstruct-finalize.js b/api/_lib/reconstruct-finalize.js
index 4c572affa..f3eba4912 100644
--- a/api/_lib/reconstruct-finalize.js
+++ b/api/_lib/reconstruct-finalize.js
@@ -73,6 +73,20 @@ async function materializeReconstructAvatar({
? params.visibility
: 'private';
+ // Canonicalize bone names + up-axis orientation so generated avatars are
+ // stored in the canonical convention, matching user-uploaded avatars.
+ try {
+ const { canonicalizeGLBBones } = await import('../../src/glb-canonicalize.js');
+ const ab = glbBuf.buffer.slice(glbBuf.byteOffset, glbBuf.byteOffset + glbBuf.byteLength);
+ const canonical = canonicalizeGLBBones(ab);
+ if (canonical.renamed > 0 || canonical.orientationCorrected) {
+ glbBuf = Buffer.from(canonical.buffer);
+ console.log(`[reconstruct] canonicalize: renamed=${canonical.renamed} orientationCorrected=${canonical.orientationCorrected}`);
+ }
+ } catch (err) {
+ console.warn('[reconstruct] canonicalize skipped:', err?.message);
+ }
+
await putObject({
key: storageKey,
body: glbBuf,
diff --git a/api/admin/revenue.js b/api/admin/revenue.js
index d0fdbbe8f..dfa4e18d0 100644
--- a/api/admin/revenue.js
+++ b/api/admin/revenue.js
@@ -22,14 +22,18 @@ export default wrap(async (req, res) => {
if (isNaN(toDate.getTime()))
return error(res, 400, 'validation_error', 'to must be a valid ISO-8601 date');
- const [{ total_fee_collected }] = await sql`
- SELECT COALESCE(SUM(fee_amount), 0)::bigint AS total_fee_collected
+ // Platform income is the fee split on-chain to the treasury
+ // (platform_fee_amount). Referral commission (fee_amount) is money owed to
+ // referrers, not platform income, so it is reported separately.
+ const [{ total_fee_collected, total_referral_paid }] = await sql`
+ SELECT COALESCE(SUM(platform_fee_amount), 0)::bigint AS total_fee_collected,
+ COALESCE(SUM(fee_amount), 0)::bigint AS total_referral_paid
FROM agent_revenue_events
WHERE created_at BETWEEN ${fromDate} AND ${toDate}
`;
const byCurrency = await sql`
- SELECT currency_mint, chain, SUM(fee_amount)::bigint AS total
+ SELECT currency_mint, chain, SUM(platform_fee_amount)::bigint AS total
FROM agent_revenue_events
WHERE created_at BETWEEN ${fromDate} AND ${toDate}
GROUP BY currency_mint, chain
@@ -37,8 +41,8 @@ export default wrap(async (req, res) => {
`;
const byDay = await sql`
- SELECT date_trunc('day', created_at)::date AS date,
- SUM(fee_amount)::bigint AS fee_total
+ SELECT date_trunc('day', created_at)::date AS date,
+ SUM(platform_fee_amount)::bigint AS fee_total
FROM agent_revenue_events
WHERE created_at BETWEEN ${fromDate} AND ${toDate}
GROUP BY 1
@@ -47,6 +51,7 @@ export default wrap(async (req, res) => {
return json(res, 200, {
total_fee_collected: Number(total_fee_collected),
+ total_referral_paid: Number(total_referral_paid),
by_currency: byCurrency.map((r) => ({
currency_mint: r.currency_mint,
chain: r.chain,
diff --git a/api/avatars/_actions.js b/api/avatars/_actions.js
index 6f0e632b4..975f65eb3 100644
--- a/api/avatars/_actions.js
+++ b/api/avatars/_actions.js
@@ -127,6 +127,24 @@ const handleUpload = wrap(async (req, res) => {
return error(res, err.status || 402, err.code || 'plan_limit', err.message);
}
+ // Canonicalize bone names + up-axis orientation at ingest so every stored
+ // GLB shares the canonical convention. The client-body path sends already-
+ // canonical bytes (account.js canonicalizes before upload), so this is a
+ // no-op there; the source_url path fetches raw bytes that may still be
+ // Mixamo/FBX-oriented. Non-fatal: if the buffer isn't a recognised humanoid
+ // rig the canonicalizer returns it unchanged.
+ try {
+ const { canonicalizeGLBBones } = await import('../../src/glb-canonicalize.js');
+ const ab = buffer.buffer.slice(buffer.byteOffset, buffer.byteOffset + buffer.byteLength);
+ const canonical = canonicalizeGLBBones(ab);
+ if (canonical.renamed > 0 || canonical.orientationCorrected) {
+ buffer = Buffer.from(canonical.buffer);
+ console.log(`[avatar-upload] canonicalize: renamed=${canonical.renamed} orientationCorrected=${canonical.orientationCorrected}`);
+ }
+ } catch (err) {
+ console.warn('[avatar-upload] canonicalize skipped:', err?.message);
+ }
+
const rawSlug = url.searchParams.get('slug');
const slug = rawSlug ? slugSchema.parse(rawSlug) : `draft-${Math.random().toString(36).slice(2, 8)}`;
const key = storageKeyFor({ userId, slug });
diff --git a/api/forge-gameready.js b/api/forge-gameready.js
new file mode 100644
index 000000000..a1de93dce
--- /dev/null
+++ b/api/forge-gameready.js
@@ -0,0 +1,307 @@
+/**
+ * /api/forge-gameready — one-click engine-ready export for a forged or uploaded
+ * model. Drives the workers/remesh Cloud Run service to retopologize the mesh to
+ * a poly budget and bake PBR, then delivers the result in every requested format
+ * (GLB for inline preview, FBX for Unity/Unreal) in a single job.
+ *
+ * POST /api/forge-gameready {
+ * mesh_url: string,
+ * topology?: "quad"|"tri", // quad → QuadriFlow retopo; tri → smart low-poly
+ * poly_budget?: number, // 1000–500000 target faces
+ * texture_size?: 1024|2048,
+ * formats?: ("glb"|"fbx")[], // default ["glb","fbx"]
+ * preserve_rig?: boolean // keep the source skeleton on the FBX (skips
+ * // retopology for that file — original topology)
+ * } → 202 { job_id, status, topology, poly_budget, formats, preserve_rig, eta_seconds }
+ *
+ * GET /api/forge-gameready?job=<id>
+ * → { job_id, status, outputs?: { glb?: {url,format}, fbx?: {url,format} },
+ * face_count?, quad_ratio?, textured?, topology?, error? }
+ *
+ * The worker writes one format per task, so a multi-format request fans out into
+ * one remesh task per format; the job id packs every sub-task so a single poll
+ * resolves them all. Finished artifacts are mirrored into our R2 bucket so the
+ * download URLs are first-party and durable. Routes to workers/remesh when
+ * GCP_REMESH_URL is set.
+ */
+
+import { createHash } from 'node:crypto';
+import { cors, json, method, readJson, wrap, rateLimited } from './_lib/http.js';
+import { limits, clientIp } from './_lib/rate-limit.js';
+import { assertPublicHttpsUrl, SsrfError } from './_lib/ssrf.js';
+import { createRegenProvider } from './_providers/gcp.js';
+import { putObject, publicUrl } from './_lib/r2.js';
+
+// The composite job id is a base64url JSON envelope packing one upstream task per
+// requested format, so it is far longer than a raw worker task id.
+const JOB_ID_RE = /^[A-Za-z0-9_-]{24,16000}$/;
+const VALID_TOPOLOGIES = new Set(['quad', 'tri']);
+const VALID_FORMATS = new Set(['glb', 'fbx']);
+const VALID_TEXTURE_SIZES = new Set([1024, 2048]);
+const POLY_MIN = 1_000;
+const POLY_MAX = 500_000;
+
+// quad → field-aligned QuadriFlow retopology; tri → silhouette-preserving
+// quadric low-poly with UV re-unwrap + texture re-bake. Both are real worker
+// pipelines (workers/remesh); neither is faked here.
+const TOPOLOGY_TO_MODE = { quad: 'quad', tri: 'lowpoly' };
+
+const CONTENT_TYPE = {
+ glb: 'model/gltf-binary',
+ fbx: 'application/octet-stream',
+};
+
+function unconfigured(res) {
+ return json(res, 503, {
+ error: 'unconfigured',
+ message:
+ 'Game-Ready export is not configured. Set GCP_REMESH_URL and GCP_RECONSTRUCTION_KEY ' +
+ 'to the URL and bearer secret of your deployed workers/remesh Cloud Run service.',
+ });
+}
+
+function packJob(payload) {
+ return Buffer.from(JSON.stringify(payload), 'utf8').toString('base64url');
+}
+function unpackJob(jobId) {
+ try {
+ const parsed = JSON.parse(Buffer.from(jobId, 'base64url').toString('utf8'));
+ return parsed && parsed.v === 1 && parsed.sub && typeof parsed.sub === 'object' ? parsed : null;
+ } catch {
+ return null;
+ }
+}
+
+// Translate one requested format into the remesh worker params. The GLB (and any
+// other geometry format) carries the retopologized mesh. FBX optionally takes the
+// rig-preserving `convert` path: retopology rebuilds geometry and so cannot keep
+// skin weights, so a rigged FBX is delivered at the source topology — the honest
+// trade the worker actually supports.
+function workerParamsForFormat(format, { mode, polyBudget, textureSize, preserveRig }) {
+ if (format === 'fbx' && preserveRig) {
+ return {
+ remesh_mode: 'triangle',
+ operation: 'convert',
+ target_faces: polyBudget,
+ texture_size: textureSize,
+ output_format: 'fbx',
+ };
+ }
+ return {
+ remesh_mode: mode,
+ operation: 'full',
+ target_faces: polyBudget,
+ texture_size: textureSize,
+ output_format: format,
+ };
+}
+
+async function startJob(req, res) {
+ const ip = clientIp(req);
+ const rl = await limits.mcp3dGenerate(ip);
+ if (!rl.success) {
+ return rateLimited(res, rl);
+ }
+
+ const body = await readJson(req, 4_000).catch(() => null);
+ const rawMeshUrl = typeof body?.mesh_url === 'string' ? body.mesh_url.trim() : '';
+ // Resolve + validate the host our side (rejects private/loopback/metadata IPs)
+ // before handing the URL to the worker — SSRF defense in depth.
+ let meshUrl;
+ try {
+ meshUrl = await assertPublicHttpsUrl(rawMeshUrl);
+ } catch (err) {
+ return json(res, 400, {
+ error: 'invalid_mesh_url',
+ message: err instanceof SsrfError ? `mesh_url rejected: ${err.message}` : 'mesh_url must be a public https URL.',
+ });
+ }
+
+ const topology = VALID_TOPOLOGIES.has(body?.topology) ? body.topology : 'quad';
+ const mode = TOPOLOGY_TO_MODE[topology];
+ const polyBudget = Math.max(POLY_MIN, Math.min(POLY_MAX, Math.round(Number(body?.poly_budget) || 15_000)));
+ const textureSize = VALID_TEXTURE_SIZES.has(Number(body?.texture_size)) ? Number(body.texture_size) : 1024;
+ const preserveRig = body?.preserve_rig === true;
+
+ // De-duplicate + clamp the format list to what we support; default to both.
+ const requested = Array.isArray(body?.formats) ? body.formats : ['glb', 'fbx'];
+ const formats = [...new Set(requested.filter((f) => VALID_FORMATS.has(f)))];
+ if (formats.length === 0) {
+ return json(res, 400, {
+ error: 'invalid_formats',
+ message: 'formats must include at least one of "glb" or "fbx".',
+ });
+ }
+
+ let provider;
+ try {
+ provider = createRegenProvider();
+ if (!provider.supportsMode('remesh')) return unconfigured(res);
+ } catch {
+ return unconfigured(res);
+ }
+
+ const sub = {};
+ let maxEta = 0;
+ try {
+ // Fan out one worker task per format. The worker emits a single format per
+ // task, so both the GLB and FBX are produced concurrently upstream.
+ const submissions = await Promise.all(
+ formats.map(async (format) => {
+ const job = await provider.submit({
+ mode: 'remesh',
+ sourceUrl: meshUrl,
+ params: workerParamsForFormat(format, { mode, polyBudget, textureSize, preserveRig }),
+ });
+ return { format, job };
+ }),
+ );
+ for (const { format, job } of submissions) {
+ sub[format] = job.extJobId;
+ maxEta = Math.max(maxEta, Number(job.eta) || 0);
+ }
+ } catch (err) {
+ return json(res, 502, {
+ error: 'gameready_failed',
+ message: err?.message || 'Game-Ready export could not start.',
+ });
+ }
+
+ const jobId = packJob({
+ v: 1,
+ topology,
+ budget: polyBudget,
+ preserveRig,
+ // 12 hex of the source URL → a stable, collision-resistant R2 namespace so
+ // re-runs overwrite rather than orphan, without leaking the full URL.
+ h: createHash('sha256').update(meshUrl).digest('hex').slice(0, 12),
+ sub,
+ });
+
+ return json(res, 202, {
+ job_id: jobId,
+ status: 'queued',
+ topology,
+ poly_budget: polyBudget,
+ texture_size: textureSize,
+ formats,
+ preserve_rig: preserveRig,
+ eta_seconds: maxEta || 35,
+ });
+}
+
+// Copy a finished worker artifact into our R2 bucket so the download URL is
+// first-party and durable. Falls back to the worker URL if R2 is unconfigured or
+// the copy fails — a real, working result either way, never a faked one.
+async function mirrorToR2(sourceUrl, key, format) {
+ try {
+ const resp = await fetch(sourceUrl);
+ if (!resp.ok) throw new Error(`fetch result ${resp.status}`);
+ const buf = Buffer.from(await resp.arrayBuffer());
+ await putObject({
+ key,
+ body: buf,
+ contentType: CONTENT_TYPE[format] || 'application/octet-stream',
+ metadata: { source: 'forge-gameready' },
+ });
+ return { url: publicUrl(key), bytes: buf.length };
+ } catch {
+ return { url: sourceUrl, bytes: null };
+ }
+}
+
+async function pollJob(req, res, jobId) {
+ if (!JOB_ID_RE.test(jobId)) {
+ return json(res, 400, { error: 'invalid_job', message: 'Malformed job id.' });
+ }
+ const job = unpackJob(jobId);
+ if (!job) {
+ return json(res, 400, { error: 'invalid_job', message: 'Malformed job id.' });
+ }
+
+ const rl = await limits.mcp3dStatus(clientIp(req));
+ if (!rl.success) {
+ return rateLimited(res, rl);
+ }
+
+ let provider;
+ try {
+ provider = createRegenProvider();
+ } catch {
+ return unconfigured(res);
+ }
+
+ const formats = Object.keys(job.sub);
+ const results = await Promise.all(
+ formats.map(async (format) => ({ format, result: await provider.status(job.sub[format]) })),
+ );
+
+ // Aggregate the sub-task statuses: any failure fails the whole export; the
+ // export is done only when every requested format has landed.
+ const failed = results.find((r) => r.result.status === 'failed');
+ if (failed) {
+ return json(res, 200, {
+ job_id: jobId,
+ status: 'failed',
+ topology: job.topology,
+ poly_budget: job.budget,
+ error: `${failed.format.toUpperCase()} export failed: ${failed.result.error || 'unknown error'}`,
+ });
+ }
+
+ const allDone = results.every((r) => r.result.status === 'done' && r.result.resultGlbUrl);
+ if (!allDone) {
+ const running = results.some((r) => r.result.status === 'running');
+ return json(res, 200, {
+ job_id: jobId,
+ status: running ? 'running' : 'queued',
+ topology: job.topology,
+ poly_budget: job.budget,
+ });
+ }
+
+ // Every format finished — mirror each artifact into R2 under the model's
+ // namespace and surface the topology telemetry from the retopologized output.
+ const outputs = {};
+ let faceCount = null;
+ let quadRatio = null;
+ let textured = null;
+ await Promise.all(
+ results.map(async ({ format, result }) => {
+ const key = `forge/gameready/${job.h}/${job.topology}-${job.budget}.${format}`;
+ const mirrored = await mirrorToR2(result.resultGlbUrl, key, format);
+ outputs[format] = { url: mirrored.url, format, bytes: mirrored.bytes };
+ // Prefer the retopologized GLB's telemetry; a rig-preserving FBX reports
+ // the source topology, which would misrepresent the delta.
+ if (format !== 'fbx' || faceCount === null) {
+ if (typeof result.faceCount === 'number') faceCount = result.faceCount;
+ if (typeof result.quadRatio === 'number') quadRatio = result.quadRatio;
+ if (typeof result.textured === 'boolean') textured = result.textured;
+ }
+ }),
+ );
+
+ return json(res, 200, {
+ job_id: jobId,
+ status: 'done',
+ topology: job.topology,
+ poly_budget: job.budget,
+ preserve_rig: Boolean(job.preserveRig),
+ outputs,
+ face_count: faceCount,
+ quad_ratio: quadRatio,
+ textured,
+ });
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;
+ if (!method(req, res, ['GET', 'POST'])) return;
+
+ if (req.method === 'POST') return startJob(req, res);
+
+ const url = new URL(req.url, 'http://localhost');
+ const jobId = (url.searchParams.get('job') || '').trim();
+ if (!jobId) return json(res, 400, { error: 'missing_job', message: 'Pass ?job=<id> to poll.' });
+ return pollJob(req, res, jobId);
+});
diff --git a/data/pages.json b/data/pages.json
index fccf3581d..f9fe28fb3 100644
--- a/data/pages.json
+++ b/data/pages.json
@@ -183,6 +183,15 @@
"changefreq": "weekly",
"added": "2026-06-13"
},
+ {
+ "path": "/pose",
+ "title": "Animation Studio",
+ "description": "Pose any three.ws avatar or the built-in mannequin with FK/IK, keyframe a timeline, and preview the motion live. Export an animated GLB or clip JSON, save animations to your account, play them back across the platform, and sell them for USDC.",
+ "priority": 0.9,
+ "changefreq": "weekly",
+ "added": "2026-06-17",
+ "showcase": true
+ },
{
"path": "/validation",
"title": "glTF Validator",
diff --git a/pages/features.html b/pages/features.html
index 95764725d..0f1e6efda 100644
--- a/pages/features.html
+++ b/pages/features.html
@@ -199,6 +199,9 @@
<a href="/forge" class="btn-primary" style="display:inline-flex;align-items:center;gap:6px;margin-top:20px">
Generate your own avatar <span class="btn-arrow">→</span>
</a>
+ <a href="/pose" class="btn-ghost" style="display:inline-flex;align-items:center;gap:6px;margin-top:20px;margin-left:10px">
+ Author your own in the Animation Studio <span class="btn-arrow">→</span>
+ </a>
</div>
</div>
</section>
diff --git a/pages/forge.html b/pages/forge.html
index 6a3311cee..811521bea 100644
--- a/pages/forge.html
+++ b/pages/forge.html
@@ -2701,6 +2701,30 @@
title="Split this model into selectable parts"
>Split into parts</a
>
+ <button
+ class="btn btn-ghost"
+ type="button"
+ id="forge-gameready-btn"
+ aria-expanded="false"
+ title="Retopologize to a poly budget and export an engine-ready GLB + FBX"
+ >
+ <svg
+ width="15"
+ height="15"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ stroke-width="2"
+ stroke-linecap="round"
+ stroke-linejoin="round"
+ aria-hidden="true"
+ >
+ <polygon points="12 2 2 7 12 12 22 7 12 2" />
+ <polyline points="2 17 12 22 22 17" />
+ <polyline points="2 12 12 17 22 12" />
+ </svg>
+ Game-Ready
+ </button>
<button
class="btn btn-ghost"
type="button"
@@ -2935,6 +2959,7 @@
<script type="module" src="/src/forge-refine.js"></script>
<script type="module" src="/src/forge-stylize.js"></script>
<script type="module" src="/src/forge-optimize.js"></script>
+ <script type="module" src="/src/forge-gameready.js"></script>
<script type="module" src="/src/forge-export.js"></script>
<script type="module" src="/src/forge-embed-panel.js"></script>
<script type="module" src="/src/forge-ar.js"></script>
diff --git a/public/animations/robotexpressive.glb b/public/animations/robotexpressive.glb
index ec3423e3a..5c31d1fd4 100644
Binary files a/public/animations/robotexpressive.glb and b/public/animations/robotexpressive.glb differ
diff --git a/public/animations/soldier.glb b/public/animations/soldier.glb
index 2632ae74a..cc102c952 100644
Binary files a/public/animations/soldier.glb and b/public/animations/soldier.glb differ
diff --git a/public/avatars/cz.glb b/public/avatars/cz.glb
index 79648be49..6eb0a4994 100644
Binary files a/public/avatars/cz.glb and b/public/avatars/cz.glb differ
diff --git a/public/avatars/default.glb b/public/avatars/default.glb
index 23dd38e7f..3b71d688f 100644
Binary files a/public/avatars/default.glb and b/public/avatars/default.glb differ
diff --git a/public/changelog.json b/public/changelog.json
index c31eb0873..14c7d083b 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,11 +1,21 @@
{
- "generated_at": "2026-06-17T15:26:20.629Z",
+ "generated_at": "2026-06-17T15:32:17.593Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
"url": "https://three.ws"
},
"entries": [
+ {
+ "date": "2026-06-17",
+ "type": "launch",
+ "title": "Animation Studio",
+ "summary": "Pose any three.ws avatar or the built-in mannequin with FK/IK, keyframe a timeline, and preview the motion live. Export an animated GLB or clip JSON, save animations to your account, play them back across the platform, and sell them for USDC.",
+ "link": "/pose",
+ "tags": [
+ "launch"
+ ]
+ },
{
"date": "2026-06-17",
"type": "launch",
diff --git a/public/changelog.xml b/public/changelog.xml
index c30ab2087..9a40c2a8d 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -6,6 +6,14 @@
<atom:link href="https://three.ws/changelog.xml" rel="self" type="application/rss+xml"/>
<description>What's new on three.ws — features, improvements, and releases, newest first.</description>
<language>en</language>
+ <item>
+ <title>Animation Studio</title>
+ <link>https://three.ws/pose</link>
+ <guid isPermaLink="false">2026-06-17:Animation Studio</guid>
+ <pubDate>Wed, 17 Jun 2026 12:00:00 GMT</pubDate>
+ <category>launch</category>
+ <description>Pose any three.ws avatar or the built-in mannequin with FK/IK, keyframe a timeline, and preview the motion live. Export an animated GLB or clip JSON, save animations to your account, play them back across the platform, and sell them for USDC.</description>
+ </item>
<item>
<title>How location works on IRL</title>
<link>https://three.ws/irl-privacy</link>
diff --git a/public/features.json b/public/features.json
index ef53370e1..d39525807 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-17T15:26:20.414Z",
+ "generated_at": "2026-06-17T15:32:17.387Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
@@ -222,6 +222,16 @@
"tags": [],
"showcase": false
},
+ {
+ "path": "/pose",
+ "title": "Animation Studio",
+ "description": "Pose any three.ws avatar or the built-in mannequin with FK/IK, keyframe a timeline, and preview the motion live. Export an animated GLB or clip JSON, save animations to your account, play them back across the platform, and sell them for USDC.",
+ "added": "2026-06-17",
+ "auth": null,
+ "indexable": true,
+ "tags": [],
+ "showcase": true
+ },
{
"path": "/validation",
"title": "glTF Validator",
diff --git a/public/llms-full.txt b/public/llms-full.txt
index 26bde5d66..57f5774ae 100644
--- a/public/llms-full.txt
+++ b/public/llms-full.txt
@@ -138,6 +138,12 @@ URL: https://three.ws/compose
Real-time 3D scene composer: forge items from text, attach them to your avatar's skeleton bones, arrange and scale freely, then export your creation or save it as an outfit.
+### Animation Studio
+
+URL: https://three.ws/pose
+
+Pose any three.ws avatar or the built-in mannequin with FK/IK, keyframe a timeline, and preview the motion live. Export an animated GLB or clip JSON, save animations to your account, play them back across the platform, and sell them for USDC.
+
### glTF Validator
URL: https://three.ws/validation
diff --git a/public/llms.txt b/public/llms.txt
index 3e42c616a..1361fd062 100644
--- a/public/llms.txt
+++ b/public/llms.txt
@@ -35,6 +35,7 @@ Create and customize an agent.
- [Forge — Text to 3D](https://three.ws/forge): Type a prompt — or drop in photos or a sketch — and get a downloadable textured 3D model (GLB). Pick from multiple generation engines with live health status.
- [Scene Studio](https://three.ws/scene): Full 3D scene editor in the browser — import GLB models, arrange them with transform gizmos, edit materials and lights, and export complete scenes.
- [Scene Composer](https://three.ws/compose): Real-time 3D scene composer: forge items from text, attach them to your avatar's skeleton bones, arrange and scale freely, then export your creation or save it as an outfit.
+- [Animation Studio](https://three.ws/pose): Pose any three.ws avatar or the built-in mannequin with FK/IK, keyframe a timeline, and preview the motion live. Export an animated GLB or clip JSON, save animations to your account, play them back across the platform, and sell them for USDC.
- [glTF Validator](https://three.ws/validation): Khronos-spec validator for glTF/GLB files. Paste a URL or upload a model.
- [Widget Studio](https://three.ws/studio): Pick an avatar, configure embed options, copy a one-line snippet for your site.
- [Artifact Viewer](https://three.ws/artifact): Renders Claude artifact bundles as standalone embeddable apps.
diff --git a/public/sitemap/index.html b/public/sitemap/index.html
index 407beaf3e..7f1ea6323 100644
--- a/public/sitemap/index.html
+++ b/public/sitemap/index.html
@@ -65,7 +65,7 @@
<main class="sm-wrap">
<div class="sm-hero">
<h1>Sitemap</h1>
- <p>All 170 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p>
+ <p>All 171 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p>
<div class="sm-formats">
<a href="/sitemap.xml"><code>sitemap.xml</code> · for search engines</a>
<a href="/llms.txt"><code>llms.txt</code> · for AI agents</a>
@@ -77,7 +77,7 @@
</div>
<div class="sm-filter">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></svg>
- <input id="sm-filter-input" type="search" placeholder="Filter 170 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />
+ <input id="sm-filter-input" type="search" placeholder="Filter 171 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />
<kbd aria-hidden="true">/</kbd>
</div>
<p class="sm-filter-count" id="sm-filter-count" role="status" aria-live="polite"></p>
@@ -188,7 +188,7 @@
<section class="sm-section" id="build">
<header>
- <h2>Build<span class="sm-count" data-count>29</span></h2>
+ <h2>Build<span class="sm-count" data-count>30</span></h2>
<p class="sm-section-desc">Create and customize an agent.</p>
</header>
<ul class="sm-list">
@@ -248,6 +248,13 @@
<span class="sm-desc">Real-time 3D scene composer: forge items from text, attach them to your avatar's skeleton bones, arrange and scale freely, then export your creation or save it as an outfit.</span>
</a>
</li>
+ <li>
+ <a href="/pose">
+ <span class="sm-title">Animation Studio</span>
+ <span class="sm-path">/pose</span>
+ <span class="sm-desc">Pose any three.ws avatar or the built-in mannequin with FK/IK, keyframe a timeline, and preview the motion live. Export an animated GLB or clip JSON, save animations to your account, play them back across the platform, and sell them for USDC.</span>
+ </a>
+ </li>
<li>
<a href="/validation">
<span class="sm-title">glTF Validator</span>
diff --git a/scripts/create-agent-collection.mjs b/scripts/create-agent-collection.mjs
index 0e2184386..3843c084d 100644
--- a/scripts/create-agent-collection.mjs
+++ b/scripts/create-agent-collection.mjs
@@ -184,7 +184,6 @@ async function main() {
[AGENT_ID],
);
if (rows.length === 0) {
- await db.end();
fail(`Agent ${AGENT_ID} not found (or deleted).`);
}
agents = rows;
@@ -192,7 +191,6 @@ async function main() {
if (agents.length === 0) {
console.log('No agents need a skill collection. Nothing to do.');
- await db.end();
return;
}
diff --git a/src/marketplace.js b/src/marketplace.js
index 232e3f1f5..a0c83b747 100644
--- a/src/marketplace.js
+++ b/src/marketplace.js
@@ -6491,6 +6491,7 @@ async function openTimePassFlow(agentId, skill, durationHours, btn) {
$('payment-price-display').textContent = `${human} ${shortMintLabel(price.currency_mint)}`;
const qr = $('payment-qr'); if (qr) qr.innerHTML = '';
setStatus('');
+ clearFeeDisclosure();
$('payment-modal-overlay').hidden = false;
updateWalletUI();
@@ -6561,6 +6562,7 @@ async function openPurchaseFlow(agentId, skill) {
if (confirmBtn) confirmBtn.textContent = 'Confirm Purchase';
const qr = $('payment-qr'); if (qr) qr.innerHTML = '';
setStatus('');
+ clearFeeDisclosure();
$('payment-modal-overlay').hidden = false;
updateWalletUI();
}
@@ -6638,6 +6640,7 @@ function openAssetPurchaseFlow(asset) {
const qr = $('payment-qr'); if (qr) qr.innerHTML = '';
setStatus('');
+ clearFeeDisclosure();
$('payment-modal-overlay').hidden = false;
updateWalletUI();
}
diff --git a/tests/api/marketplace-platform-fee.test.js b/tests/api/marketplace-platform-fee.test.js
new file mode 100644
index 000000000..44f653ca7
--- /dev/null
+++ b/tests/api/marketplace-platform-fee.test.js
@@ -0,0 +1,90 @@
+// Unit tests for the marketplace platform-fee math + fail-safe config.
+//
+// Pure logic — no DB, no RPC. Verifies the fee ships INERT (0 bps by default),
+// activates only when both a rate and a treasury wallet are configured, splits
+// the price correctly, and is clamped to a sane ceiling.
+
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+
+const FRESH = () => import(`../../api/_lib/marketplace-platform-fee.js?cb=${Math.random()}`);
+
+const ENV_KEYS = [
+ 'MARKETPLACE_PLATFORM_FEE_BPS',
+ 'MARKETPLACE_PLATFORM_FEE_WALLET',
+ 'PLATFORM_TREASURY_KEYPAIR',
+ 'TREASURY_KEYPAIR',
+];
+
+describe('marketplace-platform-fee', () => {
+ let saved;
+ beforeEach(() => {
+ saved = {};
+ for (const k of ENV_KEYS) {
+ saved[k] = process.env[k];
+ delete process.env[k];
+ }
+ });
+ afterEach(() => {
+ for (const k of ENV_KEYS) {
+ if (saved[k] === undefined) delete process.env[k];
+ else process.env[k] = saved[k];
+ }
+ });
+
+ it('defaults to 0 bps (fee OFF) with no env set', async () => {
+ const m = await FRESH();
+ expect(m.marketplaceFeeBps()).toBe(0);
+ });
+
+ it('reads the configured rate and clamps to the ceiling', async () => {
+ process.env.MARKETPLACE_PLATFORM_FEE_BPS = '500';
+ let m = await FRESH();
+ expect(m.marketplaceFeeBps()).toBe(500);
+
+ process.env.MARKETPLACE_PLATFORM_FEE_BPS = '99999';
+ m = await FRESH();
+ expect(m.marketplaceFeeBps()).toBe(m.MAX_FEE_BPS);
+
+ process.env.MARKETPLACE_PLATFORM_FEE_BPS = '-5';
+ m = await FRESH();
+ expect(m.marketplaceFeeBps()).toBe(0);
+ });
+
+ it('computes floor(gross * bps / 10000) atomics', async () => {
+ const m = await FRESH();
+ // 5% of 1.000000 USDC = 0.05 USDC = 50_000 atomics
+ expect(m.marketplaceFeeAtomics(1_000_000n, 500)).toBe(50_000n);
+ // floor: 5% of 1 atomic = 0
+ expect(m.marketplaceFeeAtomics(1n, 500)).toBe(0n);
+ // 0 bps → 0
+ expect(m.marketplaceFeeAtomics(1_000_000n, 0)).toBe(0n);
+ // string input tolerated
+ expect(m.marketplaceFeeAtomics('2000000', 250)).toBe(50_000n);
+ });
+
+ it('resolveMarketplaceFee returns null when no rate is set', async () => {
+ process.env.MARKETPLACE_PLATFORM_FEE_WALLET = 'THREEsynthetic11111111111111111111111111111';
+ const m = await FRESH();
+ expect(await m.resolveMarketplaceFee({ grossAtomics: 1_000_000n })).toBeNull();
+ });
+
+ it('resolveMarketplaceFee returns null when rate is set but no treasury configured', async () => {
+ process.env.MARKETPLACE_PLATFORM_FEE_BPS = '500';
+ const m = await FRESH();
+ expect(await m.resolveMarketplaceFee({ grossAtomics: 1_000_000n })).toBeNull();
+ });
+
+ it('resolveMarketplaceFee splits the price when both rate + wallet are set', async () => {
+ process.env.MARKETPLACE_PLATFORM_FEE_BPS = '500';
+ // A valid base58 pubkey (System Program id) — only its format matters here.
+ process.env.MARKETPLACE_PLATFORM_FEE_WALLET = '11111111111111111111111111111111';
+ const m = await FRESH();
+ const fee = await m.resolveMarketplaceFee({ grossAtomics: 1_000_000n });
+ expect(fee).not.toBeNull();
+ expect(fee.bps).toBe(500);
+ expect(fee.feeAtomics).toBe(50_000n);
+ expect(fee.recipient.toBase58()).toBe('11111111111111111111111111111111');
+ // creator leg = gross - fee
+ expect(1_000_000n - fee.feeAtomics).toBe(950_000n);
+ });
+});
diff --git a/tests/api/skill-mint.test.js b/tests/api/skill-mint.test.js
new file mode 100644
index 000000000..fc56ce2e1
--- /dev/null
+++ b/tests/api/skill-mint.test.js
@@ -0,0 +1,265 @@
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+import { Readable } from 'node:stream';
+
+// ── Mocks ─────────────────────────────────────────────────────────────────
+
+const authState = { session: null, bearer: null };
+
+vi.mock('../../api/_lib/auth.js', () => ({
+ getSessionUser: vi.fn(async () => authState.session),
+ authenticateBearer: vi.fn(async () => authState.bearer),
+ extractBearer: vi.fn(() => null),
+}));
+
+const sqlState = { queue: [], calls: [] };
+
+vi.mock('../../api/_lib/db.js', () => ({
+ sql: vi.fn(async (strings, ...values) => {
+ sqlState.calls.push({ query: strings.join('?'), values });
+ if (sqlState.queue.length === 0) return [];
+ return sqlState.queue.shift();
+ }),
+}));
+
+const rlState = { success: true };
+vi.mock('../../api/_lib/rate-limit.js', () => ({
+ limits: { authIp: vi.fn(async () => ({ success: rlState.success })) },
+ clientIp: vi.fn(() => '127.0.0.1'),
+}));
+
+vi.mock('../../api/_lib/csrf.js', () => ({
+ requireCsrf: vi.fn(async () => true),
+}));
+
+const notifyState = { calls: [] };
+vi.mock('../../api/_lib/notify.js', () => ({
+ insertNotification: vi.fn(async (...a) => {
+ notifyState.calls.push(a);
+ }),
+}));
+
+const confirmState = { result: { status: 'confirmed' }, throws: null, calls: [] };
+vi.mock('../../api/_lib/purchase-confirm.js', () => ({
+ confirmSkillPurchase: vi.fn(async (...a) => {
+ confirmState.calls.push(a);
+ if (confirmState.throws) throw confirmState.throws;
+ return confirmState.result;
+ }),
+}));
+
+const mintState = {
+ calls: [],
+ result: {
+ mint: 'MINTpubkey1111111111111111111111111111111111',
+ signature: 'SIGsignature11111111111111111111111111111111111111111111111',
+ collection: 'COLLmint111111111111111111111111111111111111',
+ network: 'mainnet',
+ uri: 'https://three.ws/api/agents/solana/skill-nft-metadata?agent=a&skill=s',
+ explorer: 'https://solscan.io/token/MINTpubkey',
+ },
+ throws: null,
+};
+vi.mock('../../api/_lib/skill-nft.js', () => ({
+ mintSkillNft: vi.fn(async (...a) => {
+ mintState.calls.push(a);
+ if (mintState.throws) throw mintState.throws;
+ return mintState.result;
+ }),
+}));
+
+const { default: handler } = await import('../../api/skills/mint.js');
+
+// ── Helpers ─────────────────────────────────────────────────────────────────
+
+const AGENT = '11111111-1111-1111-1111-111111111111';
+const WALLET = 'So11111111111111111111111111111111111111112';
+const SIG = 'TXsig1111111111111111111111111111111111111111111111111111111111';
+
+function makeReq({ body } = {}) {
+ const base = body ? Readable.from([Buffer.from(JSON.stringify(body))]) : Readable.from([]);
+ base.method = 'POST';
+ base.url = '/api/skills/mint';
+ base.headers = { host: 'localhost', 'content-type': 'application/json' };
+ return base;
+}
+
+function makeRes() {
+ return {
+ statusCode: 200,
+ headers: {},
+ body: '',
+ writableEnded: false,
+ setHeader(k, v) {
+ this.headers[k.toLowerCase()] = v;
+ },
+ end(chunk) {
+ if (chunk !== undefined) this.body += chunk;
+ this.writableEnded = true;
+ },
+ };
+}
+
+async function invoke(body) {
+ const req = makeReq({ body });
+ const res = makeRes();
+ await handler(req, res);
+ return { status: res.statusCode, body: res.body ? JSON.parse(res.body) : null };
+}
+
+function purchase(over = {}) {
+ return {
+ id: 'pur-1',
+ user_id: 'user-1',
+ agent_id: AGENT,
+ skill: 'translate',
+ status: 'confirmed',
+ amount: '1000000',
+ currency_mint: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
+ chain: 'solana',
+ tx_signature: SIG,
+ skill_nft_mint: null,
+ skill_nft_signature: null,
+ skill_nft_network: null,
+ ...over,
+ };
+}
+
+beforeEach(() => {
+ authState.session = { id: 'user-1' };
+ authState.bearer = null;
+ sqlState.queue = [];
+ sqlState.calls = [];
+ rlState.success = true;
+ notifyState.calls = [];
+ confirmState.result = { status: 'confirmed' };
+ confirmState.throws = null;
+ confirmState.calls = [];
+ mintState.calls = [];
+ mintState.throws = null;
+});
+
+const body = (over = {}) => ({
+ agent_id: AGENT,
+ skill_name: 'translate',
+ user_wallet: WALLET,
+ ...over,
+});
+
+// ── Tests ─────────────────────────────────────────────────────────────────
+
+describe('POST /api/skills/mint', () => {
+ it('401 when not authenticated', async () => {
+ authState.session = null;
+ const { status } = await invoke(body());
+ expect(status).toBe(401);
+ expect(mintState.calls).toHaveLength(0);
+ });
+
+ it('400 on invalid agent_id', async () => {
+ const { status, body: b } = await invoke(body({ agent_id: 'not-a-uuid' }));
+ expect(status).toBe(400);
+ expect(b.error).toBe('validation_error');
+ });
+
+ it('400 when skill name missing', async () => {
+ const { status } = await invoke({ agent_id: AGENT, user_wallet: WALLET });
+ expect(status).toBe(400);
+ });
+
+ it('403 when recipient wallet is not linked to the user', async () => {
+ sqlState.queue = [[]]; // wallet lookup → none
+ const { status, body: b } = await invoke(body());
+ expect(status).toBe(403);
+ expect(b.error).toBe('wallet_not_linked');
+ expect(mintState.calls).toHaveLength(0);
+ });
+
+ it('404 when no purchase exists', async () => {
+ sqlState.queue = [[{ id: 'w' }], []]; // wallet ok, purchase none
+ const { status, body: b } = await invoke(body());
+ expect(status).toBe(404);
+ expect(b.error).toBe('no_purchase');
+ });
+
+ it('400 when provided signature contradicts the recorded one', async () => {
+ // txSig lookup misses, fallback returns a row carrying a different sig.
+ sqlState.queue = [
+ [{ id: 'w' }],
+ [], // tx_signature-scoped lookup
+ [purchase({ tx_signature: 'OTHERsig1111111111111111111111111111111111111111111111111111' })],
+ ];
+ const { status, body: b } = await invoke(body({ transaction_signature: SIG }));
+ expect(status).toBe(400);
+ expect(b.error).toBe('signature_mismatch');
+ expect(mintState.calls).toHaveLength(0);
+ });
+
+ it('mints when the purchase is already confirmed', async () => {
+ sqlState.queue = [
+ [{ id: 'w' }], // wallet
+ [purchase()], // purchase (confirmed, not yet minted)
+ [{ skill_nft_mint: mintState.result.mint }], // UPDATE … RETURNING
+ ];
+ const { status, body: b } = await invoke(body());
+ expect(status).toBe(201);
+ expect(b.data.nftMint).toBe(mintState.result.mint);
+ expect(b.data.collection).toBe(mintState.result.collection);
+ expect(b.data.network).toBe('mainnet');
+ expect(mintState.calls).toHaveLength(1);
+ expect(mintState.calls[0][0]).toMatchObject({
+ agentId: AGENT,
+ skill: 'translate',
+ ownerWallet: WALLET,
+ });
+ expect(notifyState.calls).toHaveLength(1);
+ });
+
+ it('is idempotent — returns the existing mint without re-minting', async () => {
+ sqlState.queue = [
+ [{ id: 'w' }],
+ [purchase({ skill_nft_mint: 'EXISTINGmint', skill_nft_network: 'mainnet' })],
+ ];
+ const { status, body: b } = await invoke(body());
+ expect(status).toBe(200);
+ expect(b.data.nftMint).toBe('EXISTINGmint');
+ expect(b.data.already_minted).toBe(true);
+ expect(mintState.calls).toHaveLength(0);
+ });
+
+ it('confirms a pending purchase before minting', async () => {
+ confirmState.result = { status: 'confirmed', tx_signature: SIG };
+ sqlState.queue = [
+ [{ id: 'w' }], // wallet
+ [purchase({ status: 'pending', tx_signature: null })], // pending purchase
+ [purchase({ status: 'confirmed' })], // re-read after confirm
+ [{ skill_nft_mint: mintState.result.mint }], // UPDATE … RETURNING
+ ];
+ const { status, body: b } = await invoke(body());
+ expect(status).toBe(201);
+ expect(confirmState.calls).toHaveLength(1);
+ expect(b.data.nftMint).toBe(mintState.result.mint);
+ });
+
+ it('402 when payment is still pending after confirm attempt', async () => {
+ confirmState.result = { status: 'pending' };
+ sqlState.queue = [
+ [{ id: 'w' }],
+ [purchase({ status: 'pending', tx_signature: null })],
+ ];
+ const { status, body: b } = await invoke(body());
+ expect(status).toBe(402);
+ expect(b.error).toBe('payment_pending');
+ expect(mintState.calls).toHaveLength(0);
+ });
+
+ it('surfaces a mint failure as a clean error', async () => {
+ mintState.throws = Object.assign(new Error('authority unconfigured'), {
+ status: 500,
+ code: 'authority_unconfigured',
+ });
+ sqlState.queue = [[{ id: 'w' }], [purchase()]];
+ const { status, body: b } = await invoke(body());
+ expect(status).toBe(500);
+ expect(b.error).toBe('authority_unconfigured');
+ });
+});
diff --git a/tests/glb-canonicalize.test.js b/tests/glb-canonicalize.test.js
index afd8f9215..60b2a2720 100644
--- a/tests/glb-canonicalize.test.js
+++ b/tests/glb-canonicalize.test.js
@@ -5,8 +5,13 @@
* build synthetic v2 GLB ArrayBuffers in-memory (no fixtures on disk), which
* keeps the suite fast and lets us assert exact byte-level behaviour: header
* checks, chunk-length update, BIN-chunk preservation, 4-byte padding.
+ *
+ * A separate section ("real-fixture tests") loads the actual cz.glb and
+ * michelle.glb from disk to verify idempotency on a canonical rig and full
+ * normalization on a Mixamo rig.
*/
+import { readFileSync } from 'node:fs';
import { describe, it, expect } from 'vitest';
import { Matrix4, Quaternion, Vector3 } from 'three';
import {
@@ -442,3 +447,110 @@ describe('canonicalizeArmatureOrientation', () => {
expect(dv.getUint32(8, true)).toBe(res.buffer.byteLength);
});
});
+
+// ── Real-fixture tests ────────────────────────────────────────────────────────
+// These load the actual cz.glb (reference canonical rig) and michelle.glb
+// (Mixamo rig with +90°X armature / −90°X Hips) from disk so we can verify
+// idempotency and appearance-invariant normalization on real production assets.
+//
+// Helper: collect joint-world matrices from a parsed glTF JSON.
+function jointWorldMatrices(json) {
+ const parentOf = new Map();
+ json.nodes.forEach((n, i) => {
+ if (Array.isArray(n.children)) for (const c of n.children) parentOf.set(c, i);
+ });
+ const local = (n) => {
+ const t = new Vector3(), r = new Quaternion(), s = new Vector3(1, 1, 1);
+ if (n.translation) t.fromArray(n.translation);
+ if (n.rotation) r.fromArray(n.rotation);
+ if (n.scale) s.fromArray(n.scale);
+ return new Matrix4().compose(t, r, s);
+ };
+ const cache = new Map();
+ const world = (i) => {
+ if (cache.has(i)) return cache.get(i);
+ const p = parentOf.get(i);
+ const m = p == null ? local(json.nodes[i]) : world(p).clone().multiply(local(json.nodes[i]));
+ cache.set(i, m);
+ return m;
+ };
+ const joints = new Set();
+ for (const sk of json.skins || []) for (const j of sk.joints || []) joints.add(j);
+ const out = new Map();
+ for (const j of joints) out.set(j, world(j).elements.slice());
+ return out;
+}
+
+function glbToAB(buf) {
+ // Node Buffer may be a view into a shared pool; .slice() always returns a
+ // fresh backing ArrayBuffer at offset 0.
+ return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
+}
+
+function readGlbJson(ab) {
+ const dv = new DataView(ab);
+ const jLen = dv.getUint32(12, true);
+ return JSON.parse(new TextDecoder().decode(new Uint8Array(ab, 20, jLen)).replace(/\s+$/, ''));
+}
+
+describe('real-fixture: cz.glb (reference canonical rig)', () => {
+ it('is a no-op — buffer returned by reference (idempotent)', () => {
+ const buf = readFileSync('public/avatars/cz.glb');
+ const ab = glbToAB(buf);
+ const res = canonicalizeGLBBones(ab);
+ expect(res.renamed).toBe(0);
+ expect(res.orientationCorrected).toBe(false);
+ // Original buffer reference returned — no unnecessary repack.
+ expect(res.buffer).toBe(ab);
+ });
+});
+
+describe('real-fixture: michelle.glb (Mixamo rig normalization)', () => {
+ let ab, res, beforeW, afterJson, afterW;
+
+ it('canonicalizes: bones renamed and orientation corrected', () => {
+ const buf = readFileSync('public/avatars/michelle.glb');
+ ab = glbToAB(buf);
+ const beforeJson = readGlbJson(ab);
+ beforeW = jointWorldMatrices(beforeJson);
+
+ res = canonicalizeGLBBones(ab);
+ expect(res.renamed).toBeGreaterThan(0); // mixamorig: prefix stripped
+ expect(res.orientationCorrected).toBe(true); // +90/−90 fold applied
+ expect(res.buffer).not.toBe(ab); // new buffer produced
+ });
+
+ it('Hips rest is near identity after normalization', () => {
+ if (!res) return; // guard if prior test skipped
+ afterJson = readGlbJson(res.buffer);
+ const hipsIdx = afterJson.nodes.findIndex((n) => n.name === 'Hips');
+ expect(hipsIdx).toBeGreaterThanOrEqual(0);
+ const hipsRot = afterJson.nodes[hipsIdx].rotation || [0, 0, 0, 1];
+ // |w| ≈ 1 means identity quaternion (axis ≈ zero, angle ≈ 0).
+ expect(Math.abs(hipsRot[3])).toBeCloseTo(1, 5);
+ });
+
+ it('joint world matrices are preserved — appearance is lossless', () => {
+ if (!res || !beforeW) return;
+ afterJson = afterJson || readGlbJson(res.buffer);
+ afterW = jointWorldMatrices(afterJson);
+ const EPS = 1e-3; // 1 mm in typical avatar units
+ for (const [idx, bEls] of beforeW) {
+ const aEls = afterW.get(idx);
+ if (!aEls) continue;
+ for (let k = 0; k < 16; k++) {
+ expect(Math.abs(bEls[k] - aEls[k])).toBeLessThan(EPS);
+ }
+ }
+ });
+
+ it('all joint names are canonical after normalization', () => {
+ if (!res) return;
+ afterJson = afterJson || readGlbJson(res.buffer);
+ const joints = new Set();
+ for (const sk of afterJson.skins || []) for (const j of sk.joints || []) joints.add(j);
+ const nonCanon = [...joints].map((j) => afterJson.nodes[j].name)
+ .filter((n) => canonicalizeBoneName(n) !== n && canonicalizeBoneName(n) !== null);
+ expect(nonCanon).toHaveLength(0);
+ });
+});