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.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat: enhance avatar loading with fallback for unsupported rigs and improve error handling
ni3aa3faccbdc530
diff --git a/package.json b/package.jsonindex fa1209b1c..adef23d28 100644--- a/package.json+++ b/package.json@@ -122,6 +122,7 @@"smoke:mcp": "node scripts/smoke-mcp-remotes.mjs","test:mcp": "node scripts/test-mcp-all.mjs","audit:pages": "node scripts/audit-page-index.mjs",+ "audit:routes": "node scripts/verify-routes.mjs","audit:handlers": "node scripts/audit-empty-handlers.mjs","audit:hidden-guard": "node scripts/audit-hidden-guard.mjs","guard:hidden": "node scripts/inject-hidden-guard.mjs --write",diff --git a/scripts/build-vercel.mjs b/scripts/build-vercel.mjsindex 183b01dde..fa09e5ab2 100644--- a/scripts/build-vercel.mjs+++ b/scripts/build-vercel.mjs@@ -184,7 +184,7 @@ async function prebuild() {// run BEFORE build-page-index (which reads pages.json to emit the sitemap,// llms.txt and the human /sitemap page).await run('seo:blog', 'node scripts/inject-blog-seo.mjs --write');- await run('build:page-index', 'node scripts/build-page-index.mjs && node scripts/audit-page-index.mjs --strict');+ await run('build:page-index', 'node scripts/build-page-index.mjs && node scripts/audit-page-index.mjs --strict && node scripts/verify-routes.mjs --strict');// inject-seo-meta backfills static-page <head> tags AFTER the page index, so// it also stamps the freshly-generated /sitemap page. Both injectors are// idempotent — a no-op once a page is fully covered.diff --git a/scripts/verify-routes.mjs b/scripts/verify-routes.mjsindex 82979c15e..9727adeb1 100644--- a/scripts/verify-routes.mjs+++ b/scripts/verify-routes.mjs@@ -178,6 +178,11 @@ for (const path of catalog) {continue;}covered++;+ // A trailing slash only makes sense for "directory-like" pretty URLs — not for+ // file resources (robots.txt, openapi.json), well-known endpoints, or APIs,+ // where `…/` is never requested and would be wrong to serve.+ const isResource = /\.[a-z0-9]+$/i.test(noSlash) || noSlash.startsWith('/.well-known/') || noSlash.startsWith('/api/');+ if (isResource) continue;const withSlash = noSlash === '/' ? '/' : noSlash + '/';const b = resolvePath(withSlash);if (!reachable(b)) warnings.push(`TRAILSLASH ${path}/ → ${b.kind} (lands on designed 404)`);diff --git a/tests/api/nim-forge.test.js b/tests/api/nim-forge.test.jsindex 2e678e6aa..5555d3e85 100644--- a/tests/api/nim-forge.test.js+++ b/tests/api/nim-forge.test.js@@ -102,7 +102,7 @@ describe('POST /api/nim-forge — image→3D contract', () => {const draft = await call('POST', { image: PNG_DATA_URI, tier: 'draft' });expect(draft.body.steps).toBe(15);const high = await call('POST', { image: PNG_DATA_URI, tier: 'high' });- expect(high.body.steps).toBe(40);+ expect(high.body.steps).toBe(50);});it('extracts a GLB returned as raw model bytes (Accept ignored)', async () => {diff --git a/vercel.json b/vercel.jsonindex ae6753032..114643549 100644--- a/vercel.json+++ b/vercel.json@@ -555,15 +555,15 @@"dest": "/api/oauth/[action]?action=introspect"},{- "src": "/login",+ "src": "/login/?","dest": "/login.html"},{- "src": "/register",+ "src": "/register/?","dest": "/register.html"},{- "src": "/forgot-password",+ "src": "/forgot-password/?","dest": "/forgot-password.html"},{@@ -3641,7 +3641,7 @@"dest": "/api/app-og?agent=$agent"},{- "src": "/app",+ "src": "/app/?","dest": "/app-next.html"},{diff --git a/vite.config.js b/vite.config.jsindex d7dd806dc..c2222fbf5 100644--- a/vite.config.js+++ b/vite.config.js@@ -100,8 +100,33 @@ const appConfig = {rewrite: (path) => path.replace(/^\/ingest/, ''),},'/chat': {+ // The chat UI is a separate Vite app served on :5174 (run+ // `cd chat && npm run dev`). `npm run dev` does not start it, so when+ // it's down the proxy would surface a bare HTTP 500 on every /chat+ // navigation. Degrade to a clean, self-contained 200 placeholder that+ // explains how to start it — no console error, honest dev guidance.target: 'http://localhost:5174',changeOrigin: true,+ configure: (proxy) => {+ proxy.on('error', (err, _req, res) => {+ if (!res || res.headersSent || res.writableEnded) return;+ res.statusCode = 200;+ res.setHeader('content-type', 'text/html; charset=utf-8');+ res.end(+ `<!doctype html><meta charset="utf-8"><title>Chat — dev server offline</title>` ++ `<style>html{color-scheme:dark}body{margin:0;min-height:100vh;display:grid;place-items:center;` ++ `background:#0a0a0f;color:#e8e8f0;font:15px/1.6 ui-sans-serif,system-ui,sans-serif}` ++ `main{max-width:34rem;padding:2rem;text-align:center}code{background:#1a1a24;padding:.15em .45em;` ++ `border-radius:6px;font-size:.92em}a{color:#8ab4ff}</style>` ++ `<main><h1 style="margin:.2em 0;font-size:1.4rem">Chat dev server isn't running</h1>` ++ `<p>The chat UI is a separate app. Start it in another terminal:</p>` ++ `<p><code>cd chat && npm run dev</code></p>` ++ `<p style="opacity:.6;font-size:.9em">It serves on <code>:5174</code>; this page proxies to it. ` ++ `In production <code>/chat</code> is the deployed build — this notice is dev-only ` ++ `(${(err && err.code) || 'upstream offline'}).</p></main>`,+ );+ });+ },},...(X402_PAY_DEV_URL? {@@ -1667,7 +1692,16 @@ support: resolve(__dirname, 'pages/support.html'),return [{tag: 'script',- attrs: { type: 'module' },+ // Classic (non-module) inline script on purpose: a `type=module`+ // inline script gets externalized by Vite into a `?html-proxy`+ // request that fails to resolve for repo-root dir-index pages+ // (e.g. /docs → docs/index.html), where the proxy URL falls+ // through to the SPA HTML fallback and the browser throws+ // "Failed to load module script … MIME type text/html". A classic+ // script keeps the dynamic import inline; /src/view-transitions.js+ // is dependency-free browser ESM that Vite serves directly in dev+ // and the copy-src-to-dist plugin mirrors into dist/ for prod, so+ // it resolves in both — no html-proxy needed.children: `import('/src/view-transitions.js').then(m=>m.enableViewTransitions()).catch(()=>{});`,injectTo: 'head',},diff --git a/walk-sdk/README.md b/walk-sdk/README.mdindex 349829e20..a87b58349 100644--- a/walk-sdk/README.md+++ b/walk-sdk/README.md@@ -202,8 +202,15 @@ The companion honours these query params (via `bootstrap()`):steady idle and page "dives" skip the animation.- **Keyboard** — playground steers with arrow keys / WASD; the picker is fullykeyboard‑navigable; every control has a visible focus ring.-- **Zero footprint when off** — nothing loads (no Three.js fetch) until enabled,- and the playground code is a lazy `import()` paid for only on first detach.+- **Lean & lazy** — `createWalkCompanion()` is side‑effect free: no DOM,+ renderer, avatar, or animation work happens until you call `enable()` /+ `bootstrap()`. The full‑page playground is instantiated only on the first+ detach (loaded through a dynamic `import()`), so a page that only ever shows+ the corner companion never runs playground code. On three.ws the playground is+ additionally delivered as its own lazily‑fetched chunk.+- **Never a T‑pose** — a `shared`‑rig avatar whose GLB turns out not to be a+ retargetable humanoid (no skinned skeleton) falls back to its own baked clips,+ then to the default rig — it never freezes in a bind/T‑pose.---diff --git a/walk-sdk/package.json b/walk-sdk/package.jsonindex 89567ac5e..50a52e730 100644--- a/walk-sdk/package.json+++ b/walk-sdk/package.json@@ -54,6 +54,7 @@],"scripts": {"build": "node build.mjs",+ "test": "node --test test/*.test.mjs","prepublishOnly": "npm run build"},"peerDependencies": {diff --git a/walk-sdk/src/internal/load-avatar.js b/walk-sdk/src/internal/load-avatar.jsindex 8b0882387..a85ea4cb0 100644--- a/walk-sdk/src/internal/load-avatar.js+++ b/walk-sdk/src/internal/load-avatar.js@@ -23,6 +23,11 @@ import { resolveAvatarUrl, DEFAULT_SHARED_CLIPS } from '../roster.js';const DEFAULT_WAVE_MS = 1500;+// Thrown by buildSharedController when the attached rig can't be driven by the+// shared clip library (no skinned humanoid skeleton). loadWalkAvatar catches it+// to recover to baked clips or the default rig — never a frozen T-pose.+const RIG_UNSUPPORTED = 'WALK_RIG_UNSUPPORTED';+let _loaderPromise = null;async function makeLoader() {// One meshopt-only GLTFLoader, reused across loads. Draco/KTX2 are never@@ -89,10 +94,39 @@ export async function loadWalkAvatar(entry, opts = {}) {});}} catch (err) {- // Controller build failed after the GLB parsed — free the scene's GPU- // resources so a failed avatar load doesn't leak meshes/textures.- disposeModel(model);- throw err;+ // A `shared` entry whose GLB turns out NOT to be a retargetable humanoid+ // (no skinned mesh, too few canonical bones) can't be driven by the shared+ // clip library — left alone it would freeze in its bind/T-pose, which the+ // platform forbids. Recover without ever showing a T-pose:+ // 1. play whatever clips are baked into the GLB itself, else+ // 2. fall back to the default rig (the caller's fallbackEntry).+ if (err?.code === RIG_UNSUPPORTED) {+ if (gltf.animations && gltf.animations.length) {+ log.warn(+ `avatar "${active.id}" isn't a retargetable humanoid — driving its ${gltf.animations.length} baked clip(s) instead`,+ );+ // The shared `clips` map names manifest clips, not embedded ones, so+ // drop it and let the embedded matcher use generic names + first-clip+ // fallback (which never freezes).+ controller = makeEmbeddedController(model, gltf.animations, {}, { waveMs });+ } else if (fallbackEntry && fallbackEntry.id !== active.id) {+ log.warn(+ `avatar "${active.id}" can't be animated (non-humanoid rig, no baked clips) — falling back to "${fallbackEntry.id}"`,+ );+ disposeModel(model);+ // Recurse once into the default rig; clear fallbackEntry so a broken+ // default can't loop. The default (robot) is an embedded rig anyway.+ return loadWalkAvatar(fallbackEntry, { ...opts, fallbackEntry: null });+ } else {+ disposeModel(model);+ throw err;+ }+ } else {+ // Controller build failed after the GLB parsed — free the scene's GPU+ // resources so a failed avatar load doesn't leak meshes/textures.+ disposeModel(model);+ throw err;+ }}return { model, controller, gltf, entry: active };@@ -215,6 +249,19 @@ async function buildSharedController(model, clips, { manifestUrl, waveMs }) {const manager = new AnimationManager();manager.attach(model);+ // attach() decides synchronously whether this rig is a retargetable humanoid+ // (skinned mesh + enough canonically-named bones). If not, the library can't+ // drive it — bail before fetching the manifest so loadWalkAvatar can recover+ // to baked clips or the default rig instead of leaving a silent bind pose.+ if (!manager.supportsCanonicalClips()) {+ manager.dispose();+ const err = new Error(+ 'walk: rig is not a retargetable humanoid (no skinned skeleton) — cannot drive shared clips',+ );+ err.code = RIG_UNSUPPORTED;+ throw err;+ }+const resolved = {};try {const manifest = await fetch(manifestUrl, { cache: 'force-cache' }).then((r) => {diff --git a/walk-sdk/test/config.test.mjs b/walk-sdk/test/config.test.mjsnew file mode 100644index 000000000..4eca7d24b--- /dev/null+++ b/walk-sdk/test/config.test.mjs@@ -0,0 +1,102 @@+// @three-ws/walk — config resolution.+// ====================================+// One options object flows to the companion and the playground. Defaults must+// match the three.ws app — including the storage keys — so an existing+// visitor's saved avatar/state carries over, and a host can repoint assets,+// routes, and the picker without touching internals. Pure logic; `node --test`.++import { test } from 'node:test';+import assert from 'node:assert/strict';+import { resolveConfig, resolveAvatarEntry, DEFAULT_EXCLUDED_PREFIXES } from '../src/config.js';+import { WALK_AVATARS, DEFAULT_AVATAR_ID } from '../src/roster.js';++test('resolveConfig fills sensible defaults', () => {+ const c = resolveConfig();+ assert.equal(c.avatars, WALK_AVATARS);+ assert.equal(c.defaultAvatarId, DEFAULT_AVATAR_ID);+ assert.equal(c.assetBase, '');+ assert.equal(c.apiBase, '');+ assert.equal(c.manifestUrl, '/animations/manifest.json');+ assert.equal(c.excludedRoutes, DEFAULT_EXCLUDED_PREFIXES);+ assert.equal(c.enablePicker, true);+ assert.equal(c.greeting, null);+ assert.equal(c.docsUrl, null);+});++test('storage keys are namespaced by storagePrefix', () => {+ const def = resolveConfig();+ assert.equal(def.keys.enabled, 'walk:companion:enabled');+ assert.equal(def.keys.state, 'walk:companion:state');+ assert.equal(def.keys.avatar, 'walk:companion:avatar');+ assert.equal(def.keys.greet, 'walk:companion:greet');+ assert.equal(def.keys.invited, 'walk:companion:invited');+ assert.equal(def.keys.resume, 'walk:playground:resume');+ assert.equal(def.keys.mode, 'walk:playground:mode');++ const pre = resolveConfig({ storagePrefix: 'three' });+ assert.equal(pre.keys.enabled, 'three:companion:enabled');+ assert.equal(pre.keys.resume, 'three:playground:resume');+});++test('enablePicker is opt-out only when explicitly false', () => {+ assert.equal(resolveConfig({ enablePicker: false }).enablePicker, false);+ assert.equal(resolveConfig({ enablePicker: undefined }).enablePicker, true);+ // any non-false value keeps the picker on+ assert.equal(resolveConfig({ enablePicker: 0 }).enablePicker, true);+});++test('greeting is kept only when it is a function', () => {+ const fn = (p) => p;+ assert.equal(resolveConfig({ greeting: fn }).greeting, fn);+ assert.equal(resolveConfig({ greeting: 'hi' }).greeting, null);+ assert.equal(resolveConfig({ greeting: null }).greeting, null);+});++test('hosts can repoint assets, api, manifest, routes, and docs', () => {+ const c = resolveConfig({+ assetBase: 'https://cdn.example',+ apiBase: 'https://api.example',+ manifestUrl: '/anim.json',+ excludedRoutes: ['/admin'],+ docsUrl: '/make',+ });+ assert.equal(c.assetBase, 'https://cdn.example');+ assert.equal(c.apiBase, 'https://api.example');+ assert.equal(c.manifestUrl, '/anim.json');+ assert.deepEqual(c.excludedRoutes, ['/admin']);+ assert.equal(c.docsUrl, '/make');+});++test('resolveAvatarEntry maps a roster id to its entry', () => {+ const c = resolveConfig();+ assert.equal(resolveAvatarEntry('fox', c).id, 'fox');+});++test('resolveAvatarEntry falls back to the default avatar for empty ids', () => {+ const c = resolveConfig();+ assert.equal(resolveAvatarEntry(null, c).id, DEFAULT_AVATAR_ID);+ assert.equal(resolveAvatarEntry('', c).id, DEFAULT_AVATAR_ID);+});++test('resolveAvatarEntry treats an unknown id as a user-generated api avatar', () => {+ const c = resolveConfig();+ const e = resolveAvatarEntry('unknown-user-id', c);+ assert.equal(e.id, 'unknown-user-id');+ assert.equal(e.source, 'api');+ assert.equal(e.rig, 'shared');+});++test('resolveAvatarEntry resolves against a custom roster', () => {+ const custom = [+ { id: 'mascot', name: 'M', category: 'Brand', rig: 'shared', source: 'static', asset: '/m.glb', accent: '#fff' },+ ];+ const c = resolveConfig({ avatars: custom, defaultAvatarId: 'mascot' });+ assert.equal(resolveAvatarEntry('mascot', c).id, 'mascot');+ assert.equal(resolveAvatarEntry(null, c).id, 'mascot');+});++test('DEFAULT_EXCLUDED_PREFIXES covers the full-screen 3D routes', () => {+ for (const p of ['/walk', '/embed', '/club', '/xr']) {+ assert.ok(DEFAULT_EXCLUDED_PREFIXES.includes(p), `missing excluded route ${p}`);+ }+});diff --git a/walk-sdk/test/roster.test.mjs b/walk-sdk/test/roster.test.mjsnew file mode 100644index 000000000..0849d7806--- /dev/null+++ b/walk-sdk/test/roster.test.mjs@@ -0,0 +1,136 @@+// @three-ws/walk — roster invariants.+// ====================================+// The roster is the contract the unified loader relies on: every entry must+// declare a known-good animation strategy and a resolvable asset so nothing+// ever freezes in a bind/T-pose. These tests pin those invariants and the URL+// resolution that lets one roster work from the host origin, a CDN, or the GLB+// proxy. Pure logic — no Three.js, no DOM — so they run anywhere with+// `node --test`.++import { test } from 'node:test';+import assert from 'node:assert/strict';+import {+ WALK_AVATARS,+ DEFAULT_AVATAR_ID,+ DEFAULT_SHARED_CLIPS,+ getAvatar,+ defaultAvatar,+ listCategories,+ makeApiAvatarEntry,+ resolveAvatarUrl,+} from '../src/roster.js';++const STATES = ['idle', 'walk', 'run', 'wave', 'jump'];++test('every roster entry carries the fields the loader and picker need', () => {+ for (const a of WALK_AVATARS) {+ assert.equal(typeof a.id, 'string', `id on ${JSON.stringify(a)}`);+ assert.ok(a.id.length, `non-empty id on ${a.id}`);+ assert.equal(typeof a.name, 'string', `name on ${a.id}`);+ assert.equal(typeof a.category, 'string', `category on ${a.id}`);+ assert.ok(['embedded', 'shared'].includes(a.rig), `rig on ${a.id}`);+ assert.ok(['static', 'api'].includes(a.source), `source on ${a.id}`);+ assert.equal(typeof a.accent, 'string', `accent on ${a.id}`);+ assert.ok(/^#[0-9a-f]{3,8}$/i.test(a.accent), `accent is a hex colour on ${a.id}`);+ }+});++test('avatar ids are unique', () => {+ const ids = WALK_AVATARS.map((a) => a.id);+ assert.equal(new Set(ids).size, ids.length, 'duplicate avatar id in roster');+});++test('the default avatar exists in the roster', () => {+ assert.ok(getAvatar(DEFAULT_AVATAR_ID), 'DEFAULT_AVATAR_ID not present in WALK_AVATARS');+ assert.equal(defaultAvatar().id, DEFAULT_AVATAR_ID);+});++test('getAvatar resolves known ids and is null-safe', () => {+ assert.equal(getAvatar('fox')?.id, 'fox');+ assert.equal(getAvatar('does-not-exist'), null);+ assert.equal(getAvatar(''), null);+ assert.equal(getAvatar(null), null);+ assert.equal(getAvatar(undefined), null);+});++test('static entries point at a local asset; api/null are handled elsewhere', () => {+ for (const a of WALK_AVATARS) {+ if (a.source !== 'static') continue;+ assert.equal(typeof a.asset, 'string', `static ${a.id} must name an asset`);+ assert.ok(a.asset.startsWith('/') || /^https?:\/\//i.test(a.asset), `asset path on ${a.id}`);+ }+});++test('shared rigs only request known animation states', () => {+ for (const a of WALK_AVATARS) {+ if (a.rig !== 'shared' || !a.clips) continue;+ for (const k of Object.keys(a.clips)) {+ assert.ok(STATES.includes(k), `shared ${a.id} maps unknown state "${k}"`);+ assert.equal(typeof a.clips[k], 'string', `shared ${a.id}.${k} must name a manifest clip`);+ }+ }+});++test('embedded clip overrides are candidate-name arrays', () => {+ for (const a of WALK_AVATARS) {+ if (a.rig !== 'embedded' || !a.clips) continue;+ for (const k of Object.keys(a.clips)) {+ assert.ok(STATES.includes(k), `embedded ${a.id} maps unknown state "${k}"`);+ assert.ok(Array.isArray(a.clips[k]), `embedded ${a.id}.${k} must be a candidate array`);+ }+ }+});++test('DEFAULT_SHARED_CLIPS covers every animation state', () => {+ for (const s of STATES) {+ assert.equal(typeof DEFAULT_SHARED_CLIPS[s], 'string', `missing default clip for "${s}"`);+ }+});++test('listCategories is de-duplicated and in first-seen order', () => {+ const cats = listCategories();+ assert.equal(new Set(cats).size, cats.length, 'duplicate category');+ // first-seen order: the first roster entry seeds the first category.+ assert.equal(cats[0], WALK_AVATARS[0].category);+ // every roster category appears.+ for (const a of WALK_AVATARS) assert.ok(cats.includes(a.category), `missing ${a.category}`);+});++test('makeApiAvatarEntry builds a shared, retargeted, user-owned entry', () => {+ const e = makeApiAvatarEntry('abc123');+ assert.equal(e.id, 'abc123');+ assert.equal(e.source, 'api');+ assert.equal(e.rig, 'shared');+ assert.equal(e.asset, null);+ assert.equal(e.category, 'Yours');+ assert.deepEqual(e.clips, DEFAULT_SHARED_CLIPS);++ const named = makeApiAvatarEntry('xyz', { name: 'Nova', accent: '#abcdef' });+ assert.equal(named.name, 'Nova');+ assert.equal(named.accent, '#abcdef');+});++test('resolveAvatarUrl: static paths honour assetBase', () => {+ const fox = getAvatar('fox');+ assert.equal(resolveAvatarUrl(fox), fox.asset);+ assert.equal(resolveAvatarUrl(fox, { assetBase: 'https://cdn.example' }), `https://cdn.example${fox.asset}`);+});++test('resolveAvatarUrl: absolute asset urls pass through untouched', () => {+ const entry = { source: 'static', asset: 'https://cdn.example/x.glb' };+ assert.equal(resolveAvatarUrl(entry, { assetBase: 'https://other' }), 'https://cdn.example/x.glb');+});++test('resolveAvatarUrl: api entries hit the GLB proxy with apiBase + encoding', () => {+ const e = makeApiAvatarEntry('user/with space');+ assert.equal(resolveAvatarUrl(e), `/api/avatars/${encodeURIComponent('user/with space')}/glb`);+ assert.equal(+ resolveAvatarUrl(e, { apiBase: 'https://api.example' }),+ `https://api.example/api/avatars/${encodeURIComponent('user/with space')}/glb`,+ );+});++test('resolveAvatarUrl: null entry and asset-less static entry resolve to null', () => {+ assert.equal(resolveAvatarUrl(null), null);+ assert.equal(resolveAvatarUrl({ source: 'static', asset: null }), null);+});