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
test(create): pin the consolidation route contract and the two panels it extracted
nirholas1a0a3e42c4c5
diff --git a/tests/avatar-walk-panel.test.js b/tests/avatar-walk-panel.test.jsnew file mode 100644index 000000000..5589d82af--- /dev/null+++ b/tests/avatar-walk-panel.test.js@@ -0,0 +1,183 @@+// @vitest-environment jsdom+//+// The Walk tab is mounted by two editors: /avatars/:id/edit and the Avatar+// Studio. Extracting it into one module (creation-consolidation, Avatar Studio+// edit-mode parity) is only safe if both hosts get identical behaviour and the+// module stops assuming either page's chrome. Three things it must own:+//+// 1. Its own CSS. Avatar Studio never declared `.ae-walk-*`, and the module's+// first version put a backtick-quoted class name inside the CSS template+// literal, which closed the string early and threw "walk is not defined"+// the moment the tab was opened. That failure mode is why injectCss is+// exercised here rather than assumed.+// 2. The host's button class, so the CTA is not an unstyled default button on+// whichever page did not happen to define `.ae-btn`.+// 3. An honest degraded state. The "Open in Walk page" handoff stashes a+// draft against a SAVED avatar (api/avatars/draft/[id].js presigns that+// avatar's private base GLB), which an unsaved Studio draft does not have.+// Studio passes no `openWalkUrl` in create mode and the panel must replace+// the button with a reason, never render a control that would 400.++import { describe, it, expect, beforeEach, vi } from 'vitest';++// The preview drives a live three.js scene; the panel's contract with it is+// small enough to state exactly, and stating it here is what keeps a change to+// that contract from silently disabling the tab.+const previewCalls = [];+vi.mock('../src/avatar-edit-walk.js', () => ({+ AvatarWalkPreview: class {+ constructor(opts) {+ this.opts = opts;+ this.active = false;+ this.envName = 'void';+ previewCalls.push(opts);+ }+ onStatus(cb) { this._status = cb; }+ async enter() { this.active = true; }+ exit() { this.active = false; }+ setEnvironment(name) { this.envName = name; }+ async listEnvironments() {+ return [+ { name: 'void', label: 'Void' },+ { name: 'beach', label: 'Beach' },+ ];+ }+ remeasureProportions() { this.remeasured = true; }+ },+}));++const { createWalkPanel } = await import('../src/avatar-walk-panel.js');++const fakeScene = { root: { name: 'Armature' } };++function mount(overrides = {}) {+ const panel = document.createElement('div');+ document.body.appendChild(panel);+ const ctl = createWalkPanel({+ getScene: () => fakeScene,+ getStageEl: () => document.getElementById('stage'),+ pauseAmbient: () => {},+ resumeAmbient: () => {},+ ...overrides,+ });+ ctl.render(panel);+ return { panel, ctl };+}++// document.head is deliberately NOT reset between tests: the module injects its+// stylesheet once per document, which is exactly the behaviour under test.+beforeEach(() => {+ document.body.innerHTML = '<div id="stage"></div>';+ previewCalls.length = 0;+});++describe('walk panel chrome', () => {+ it('injects its own stylesheet once, whole, however many panels mount', () => {+ mount();+ mount();+ expect(document.querySelectorAll('#ae-walk-css')).toHaveLength(1);+ const style = document.getElementById('ae-walk-css');+ // A stray backtick inside the CSS closes the template literal early and+ // truncates the sheet, so assert the last rule actually made it out.+ expect(style.textContent).toContain('.ae-walk-savehint');+ expect(style.textContent).toContain('.ae-walk-lede kbd');+ });++ it('does not reuse .ae-walk-hint, which the preview overlay already owns', () => {+ const { panel } = mount({ openWalkUrl: null, saveHint: 'Save first.' });+ expect(panel.querySelector('.ae-walk-hint')).toBeNull();+ expect(panel.querySelector('.ae-walk-savehint').textContent).toBe('Save first.');+ });+});++describe('the handoff into /walk', () => {+ it('renders the CTA in the host page button class when a URL builder is given', () => {+ const { panel } = mount({ openWalkUrl: async () => '/walk?x=1', buttonClass: 'as-btn' });+ const btn = panel.querySelector('.ae-walk-open');+ expect(btn).not.toBeNull();+ expect(btn.className).toContain('as-btn');+ expect(panel.querySelector('.ae-walk-savehint')).toBeNull();+ });++ it('replaces the CTA with the reason when there is nothing to hand off', () => {+ const { panel } = mount({+ openWalkUrl: null,+ saveHint: 'Save this avatar to open it in the full Walk page.',+ });+ expect(panel.querySelector('.ae-walk-open')).toBeNull();+ expect(panel.querySelector('.ae-walk-savehint').textContent).toContain('Save this avatar');+ });++ it('passes the selected environment to the URL builder and opens the result', async () => {+ const seen = [];+ const opened = [];+ window.open = (url) => { opened.push(url); return null; };+ const { panel } = mount({+ openWalkUrl: async (env) => { seen.push(env); return `/walk?env=${env}`; },+ });+ // The real environment list backfills after the manifest resolves.+ await Promise.resolve();+ await Promise.resolve();+ const select = panel.querySelector('.ae-walk-select');+ select.value = 'beach';+ select.dispatchEvent(new Event('change'));+ panel.querySelector('.ae-walk-open').click();+ await new Promise((r) => setTimeout(r, 0));+ expect(seen).toEqual(['beach']);+ expect(opened).toEqual(['/walk?env=beach']);+ expect(panel.querySelector('.ae-walk-status').textContent).toBe('Opened in a new tab.');+ });++ it('surfaces a failed handoff in the status line instead of throwing', async () => {+ window.open = () => null;+ const { panel } = mount({+ openWalkUrl: async () => { throw new Error('Could not save draft (403)'); },+ });+ panel.querySelector('.ae-walk-open').click();+ await new Promise((r) => setTimeout(r, 0));+ expect(panel.querySelector('.ae-walk-status').textContent).toBe('Could not save draft (403)');+ expect(panel.querySelector('.ae-walk-open').disabled).toBe(false);+ });+});++describe('locomotion lifecycle', () => {+ it('enters the preview on render and reports active', async () => {+ const { ctl } = mount();+ await new Promise((r) => setTimeout(r, 0));+ expect(ctl.active).toBe(true);+ });++ it('re-rendering the same panel does not rebuild it (the env choice survives)', async () => {+ const { panel, ctl } = mount();+ await new Promise((r) => setTimeout(r, 0));+ const select = panel.querySelector('.ae-walk-select');+ select.value = 'beach';+ ctl.render(panel);+ expect(panel.querySelector('.ae-walk-select')).toBe(select);+ expect(panel.querySelector('.ae-walk-select').value).toBe('beach');+ // One preview for one panel, not one per render.+ expect(previewCalls).toHaveLength(1);+ });++ it('exit is idempotent so leaving the tab is always safe', async () => {+ const { ctl } = mount();+ await new Promise((r) => setTimeout(r, 0));+ ctl.exit();+ ctl.exit();+ expect(ctl.active).toBe(false);+ });++ it('waits for the avatar rather than mounting a preview on an empty scene', () => {+ const panel = document.createElement('div');+ const ctl = createWalkPanel({+ getScene: () => null,+ getStageEl: () => null,+ pauseAmbient: () => {},+ resumeAmbient: () => {},+ emptyClass: 'as-empty',+ });+ ctl.render(panel);+ expect(panel.querySelector('.as-empty')).not.toBeNull();+ expect(previewCalls).toHaveLength(0);+ });+});diff --git a/tests/creation-surface-redirects.test.js b/tests/creation-surface-redirects.test.jsnew file mode 100644index 000000000..816b8bbba--- /dev/null+++ b/tests/creation-surface-redirects.test.js@@ -0,0 +1,108 @@+/**+ * Route contract for the creation-surface consolidation.+ *+ * Every merged surface is a live URL people have bookmarked, linked from other+ * sites, and pasted into docs. `server/index.mjs` matches `vercel.json` routes+ * against the PATHNAME only and emits `Location` verbatim, so a status-only+ * route silently DROPS the query string. A retired route that carried+ * meaningful configuration therefore needs two rules: a `has`-gated rewrite for+ * the parameter-carrying form (a rewrite keeps the query) and a 301 for the+ * bare path.+ *+ * These assertions run against the production resolver itself+ * (server/route-resolve.mjs), not a re-implementation, so they cannot drift+ * away from what actually serves traffic.+ */++import { describe, it, expect } from 'vitest';+import { fileURLToPath } from 'node:url';+import { loadRouteTable, resolvePhase1 } from '../server/route-resolve.mjs';++const { phase1Routes } = loadRouteTable(fileURLToPath(new URL('../vercel.json', import.meta.url)));++function resolve(target) {+ const url = new URL(`http://three.ws${target}`);+ const r = resolvePhase1(phase1Routes, { headers: {} }, url);+ const location = r.headers?.Location || r.headers?.location || null;+ return { status: r.status || null, location, path: r.path, external: r.external };+}++describe('retired creation surfaces redirect to a live destination', () => {+ it.each([+ ['/embed', '/studio'],+ ['/embed/', '/studio'],+ ['/scan', '/create/selfie'],+ ['/agent/new', '/create-agent'],+ ['/create/character', '/play'],+ ['/create-character', '/play'],+ ])('%s 301s to %s', (from, to) => {+ const r = resolve(from);+ expect(r.status).toBe(301);+ expect(r.location).toBe(to);+ });++ it('the retired /avatar-edit landing 301s to a live page', () => {+ const r = resolve('/avatar-edit');+ expect(r.status).toBe(301);+ // The destination is the avatar library rather than the Studio: a bare+ // /avatar-edit means "edit one of my avatars", and Studio's create mode+ // would answer a different question.+ expect(r.location).toBe('/dashboard/avatars');+ });+});++describe('parameter-carrying forms survive as rewrites, not redirects', () => {+ // A rewrite keeps the query string; a 301 would drop it and lose the whole+ // configuration the link was written to carry.+ it.each([+ '/embed?mode=walking&avatar=abc&env=beach&ground=false',+ '/embed?mode=chat&avatar=ada',+ '/embed?avatar=abc',+ '/embed?id=abc',+ '/embed/?mode=idle&avatar=abc',+ ])('%s rewrites into the Widget Studio', (target) => {+ const r = resolve(target);+ expect(r.status).toBeNull();+ expect(r.path).toBe('/studio/index.html');+ });++ it('the avatar handoff into the agent wizard keeps its params', () => {+ expect(resolve('/agent/new?avatar_id=abc').path).toBe('/create-agent.html');+ expect(resolve('/agent/new?avatar_glb=https%3A%2F%2Fx%2Fa.glb').path).toBe('/create-agent.html');+ });++ it('the legacy /avatar-edit?id= form still renders the customizer', () => {+ expect(resolve('/avatar-edit?id=abc').path).toBe('/avatar-edit.html');+ });+});++describe('the /embed merge does not shadow the other /embed/* runtimes', () => {+ // These are separate, live embed runtimes that happen to share the prefix.+ // A `/embed/(.*)`-shaped rule would have swallowed every one of them.+ it.each([+ ['/embed/v1.js', '/embed/v1.js'],+ ['/embed/v1/preview/', '/embed/v1/preview.html'],+ ['/embed/avatar', '/avatar-embed.html'],+ ['/embed/walk/', '/embed-walk.html'],+ ['/embed-demo', '/embed-demo.html'],+ ])('%s still resolves to %s', (from, to) => {+ const r = resolve(from);+ expect(r.status).toBeNull();+ expect(r.path).toBe(to);+ });+});++describe('the surfaces the merge kept are still directly reachable', () => {+ it.each([+ ['/studio', '/studio/index.html'],+ ['/avatar-studio', '/avatar-studio.html'],+ ['/avatars/abc/edit', '/avatar-edit.html'],+ ['/create-agent', '/create-agent.html'],+ ['/start', '/start.html'],+ ['/pose', '/pose.html'],+ ])('%s serves %s', (from, to) => {+ const r = resolve(from);+ expect(r.status).toBeNull();+ expect(r.path).toBe(to);+ });+});diff --git a/tests/garment-closet-export.test.js b/tests/garment-closet-export.test.jsnew file mode 100644index 000000000..93aab0f7f--- /dev/null+++ b/tests/garment-closet-export.test.js@@ -0,0 +1,122 @@+/**+ * GarmentCloset#withGarmentsOff: the guard that keeps Avatar Studio's+ * create-mode save from dressing an avatar twice.+ *+ * Two different things carry a garment: the live scene (skinned meshes bound to+ * the avatar's skeleton, plus the skin occlusion they impose) and the appearance+ * record's `garments` array. Studio's create-mode save uploads a GLTFExporter+ * dump of the live scene as the new avatar's BASE model and PATCHes the+ * appearance beside it, and the server bake replays `appearance.garments` onto+ * that base (api/_lib/bake-garments.js). Export the dressed scene and every+ * garment lands on the avatar twice, on top of a base the owner can never get+ * back. That is the same class of bug the edit-mode save already had to fix.+ *+ * So the export runs with the garments off the rig and the record untouched.+ * The invariants: the scene is stripped, `working.garments` is NOT, and the+ * outfit is back on the body afterwards, whatever the callback did.+ */++import { describe, it, expect, vi } from 'vitest';++// The closet's real attach path parses GLB bytes through GLTFLoader and the+// meshopt decoder. That is covered by tests/avatar-garment.test.js against real+// geometry; here the subject is the detach/restore bookkeeping around it, so the+// scene-graph collaborators are stubbed to keep the contract legible.+const detached = [];+const attached = [];+vi.mock('../src/avatar-garment.js', () => ({+ attachGarment: (root, scene, opts) => {+ attached.push(opts.slot);+ return { ok: true, slot: opts.slot, meshes: [], coverage: 1 };+ },+ detachSlot: (root, slot) => { detached.push(slot); },+ supportsWardrobe: () => true,+ applySkinOcclusion: () => {},+ restoreSkin: () => {},+ findAvatarSkeleton: () => null,+ GARMENT_SLOTS: ['top', 'bottom', 'footwear', 'outerwear', 'hair', 'headwear', 'glasses', 'accessory'],+}));++const { GarmentCloset } = await import('../src/garment-closet.js');++function makeCloset(working) {+ const closet = new GarmentCloset({+ getRoot: () => ({ name: 'Armature' }),+ getWorking: () => working,+ });+ // Stand in for the download + parse: everything after it is what is on test.+ closet._fetchModel = async () => new ArrayBuffer(8);+ closet._getLoader = async () => ({ parseAsync: async () => ({ scene: {} }) });+ return closet;+}++const SHIRT = { id: 'oxford-shirt', slot: 'top', name: 'Oxford shirt', model: { uri: 'shirt.glb' } };+const BOOTS = { id: 'boots', slot: 'footwear', name: 'Boots', model: { uri: 'boots.glb' } };++// verifyModelBytes hashes the download against the manifest; there is no real+// download here, so the integrity gate is satisfied directly.+vi.mock('../src/garment-catalog.js', async (importOriginal) => ({+ ...(await importOriginal()),+ verifyModelBytes: async () => true,+}));++describe('withGarmentsOff', () => {+ it('takes every garment off the rig for the callback and puts it back after', async () => {+ const working = { garments: [] };+ const closet = makeCloset(working);+ await closet.attach(SHIRT);+ await closet.attach(BOOTS);+ expect([...closet.attached().keys()].sort()).toEqual(['footwear', 'top']);++ detached.length = 0;+ attached.length = 0;+ let sawDuringCallback = null;+ await closet.withGarmentsOff(async () => {+ sawDuringCallback = [...closet.attached().keys()];+ });++ // Stripped for the export...+ expect(sawDuringCallback).toEqual([]);+ // attach() also evicts its own slot before binding, so count distinct slots.+ expect([...new Set(detached)].sort()).toEqual(['footwear', 'top']);+ // ...and dressed again afterwards.+ expect([...closet.attached().keys()].sort()).toEqual(['footwear', 'top']);+ expect(attached.sort()).toEqual(['footwear', 'top']);+ });++ it('leaves the appearance record alone, because the bake replays it', async () => {+ const working = { garments: [] };+ const closet = makeCloset(working);+ await closet.attach(SHIRT);+ const recorded = JSON.stringify(working.garments);+ expect(recorded).toBe(JSON.stringify([{ slot: 'top', id: 'oxford-shirt' }]));++ await closet.withGarmentsOff(async () => {+ // The export reads the record too; it must still describe the outfit.+ expect(JSON.stringify(working.garments)).toBe(recorded);+ });+ expect(JSON.stringify(working.garments)).toBe(recorded);+ });++ it('returns what the callback returned', async () => {+ const closet = makeCloset({ garments: [] });+ await closet.attach(SHIRT);+ await expect(closet.withGarmentsOff(async () => 'glb-blob')).resolves.toBe('glb-blob');+ });++ it('re-dresses the avatar even when the export throws', async () => {+ const closet = makeCloset({ garments: [] });+ await closet.attach(SHIRT);+ await expect(+ closet.withGarmentsOff(async () => { throw new Error('export failed'); }),+ ).rejects.toThrow('export failed');+ expect([...closet.attached().keys()]).toEqual(['top']);+ });++ it('is a straight pass-through when nothing is worn', async () => {+ const closet = makeCloset({ garments: [] });+ detached.length = 0;+ await expect(closet.withGarmentsOff(async () => 'ok')).resolves.toBe('ok');+ expect(detached).toEqual([]);+ });+});