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
widget-client ready() polling, test timeout fixes, glb-inspect tests
nirholas32f5f96576fa
diff --git a/public/widget-client.js b/public/widget-client.jsindex 219d9d443..ce4141d41 100644--- a/public/widget-client.js+++ b/public/widget-client.js@@ -117,37 +117,48 @@};ThreeWidgetClient.prototype.ready = function (timeoutMs) {- // Resolves on the first `viewer.ready` event, or immediately if a- // later attach catches an already-ready widget (we poll once via ping).+ // Resolves on the first `viewer.ready` event the iframe pushes, or as+ // soon as a `viewer.getInfo` reports ready (covers attach-after-ready).+ // Total wait is bounded by `timeoutMs`; the internal ping retries every+ // 1s until either the deadline or a successful response.var self = this;if (self._closed) return Promise.reject(new Error('client closed'));+ var deadline = (timeoutMs && timeoutMs > 0) ? Date.now() + timeoutMs : Infinity;+return new Promise(function (resolve, reject) {var done = false;- var off = self.on('viewer.ready', function () {+ function finish(err) {if (done) return;done = true;- off();- resolve();- });- // If the widget is already up, ping succeeds — assume ready.- self.call('ping', null, timeoutMs || 4000).then(- function () {- self.call('viewer.getInfo').then(function (info) {- if (!done && info && info.ready) {- done = true;- off();- resolve();- }- });- },- function (err) {- if (!done) {- done = true;- off();- reject(err);- }- },- );+ if (off) off();+ err ? reject(err) : resolve();+ }++ var off = self.on('viewer.ready', function () { finish(); });++ (function poll() {+ if (done) return;+ if (Date.now() >= deadline) {+ finish(new Error('ready timeout'));+ return;+ }+ // Per-attempt timeout is short (1s) so we re-poll until the+ // iframe finishes booting; the outer `deadline` bounds the+ // total wait.+ self.call('ping', null, 1000).then(+ function () {+ if (done) return;+ self.call('viewer.getInfo', null, 1500).then(+ function (info) {+ if (info && info.ready) finish();+ else setTimeout(poll, 500);+ },+ function () { setTimeout(poll, 500); },+ );+ },+ function () { setTimeout(poll, 500); },+ );+ })();});};diff --git a/scripts/verify-widget-shell.mjs b/scripts/verify-widget-shell.mjsindex be270464c..f3719a500 100644--- a/scripts/verify-widget-shell.mjs+++ b/scripts/verify-widget-shell.mjs@@ -85,9 +85,15 @@ await withPage('/studio preview iframe targets /widget', async (page) => {ok(`preview iframe → /widget (src=${previewSrc.slice(0, 120)}…)`);else fail('preview iframe → /widget', `unexpected src: ${previewSrc}`);- const frame = page.frame({ url: /\/widget/ });+ // Wait for the iframe to actually register with the browser — playwright+ // can read the src before page.frame() sees it.+ let frame = null;+ for (let i = 0; i < 25 && !frame; i++) {+ frame = page.frame({ url: /\/widget/ });+ if (!frame) await page.waitForTimeout(200);+ }if (!frame) {- fail('studio iframe accessible', 'no /widget frame found');+ fail('studio iframe accessible', 'no /widget frame found after 5s');return;}const chromeCount = await frame.evaluate(@@ -241,8 +247,9 @@ await withPage('JSON-RPC: ping + camera + animation + info', async (page) => {// model.export returns binary GLB as base64 — proves the legacy// exportGLB bridge is fully covered by JSON-RPC now. GLTFExporter.parse- // can take several seconds the first time it's imported.- const exp = await rpc('model.export', null, 30000);+ // over a fully-loaded avatar with all clips registered routinely takes+ // 10-30s on swiftshader; 60s leaves headroom.+ const exp = await rpc('model.export', null, 60000);if (typeof exp?.result?.base64 === 'string' &&exp.result.base64.length > 1000 &&diff --git a/tests/api/lib-glb-inspect.test.js b/tests/api/lib-glb-inspect.test.jsnew file mode 100644index 000000000..93f6f81c6--- /dev/null+++ b/tests/api/lib-glb-inspect.test.js@@ -0,0 +1,156 @@+// Tests for api/_lib/glb-inspect.js — deterministic parser of the GLB JSON+// chunk. Critical for the reconstruct materialize path: we tag every freshly+// generated avatar with is_rigged from this output, and the UI uses that to+// decide whether to badge "needs rigging".++import { describe, it, expect } from 'vitest';+import { inspectGlb, isValidGlbHeader, isRiggedGlb } from '../../api/_lib/glb-inspect.js';++// Build a minimum-viable GLB with a JSON chunk we control.+function makeGlb(gltfJson) {+ const jsonText = JSON.stringify(gltfJson);+ // JSON chunk must be padded with spaces to a 4-byte boundary.+ const padded = jsonText + ' '.repeat((4 - (jsonText.length % 4)) % 4);+ const jsonBytes = Buffer.from(padded, 'utf8');++ const totalLength = 12 + 8 + jsonBytes.length;+ const buf = Buffer.alloc(totalLength);+ // Header+ buf.writeUInt32LE(0x46546C67, 0); // magic 'glTF'+ buf.writeUInt32LE(2, 4); // version+ buf.writeUInt32LE(totalLength, 8); // length+ // JSON chunk header+ buf.writeUInt32LE(jsonBytes.length, 12); // chunk length+ buf.writeUInt32LE(0x4E4F534A, 16); // chunk type 'JSON'+ jsonBytes.copy(buf, 20);+ return buf;+}++describe('glb-inspect', () => {+ describe('isValidGlbHeader', () => {+ it('accepts a well-formed GLB', () => {+ expect(isValidGlbHeader(makeGlb({ asset: { version: '2.0' } }))).toBe(true);+ });++ it('rejects bytes that do not start with the magic', () => {+ const bad = Buffer.from('<html>not a glb</html>NOTNOT00NOT');+ expect(isValidGlbHeader(bad)).toBe(false);+ });++ it('rejects a buffer too small to hold a header', () => {+ expect(isValidGlbHeader(Buffer.alloc(8))).toBe(false);+ });++ it('rejects a header that lies about total length', () => {+ const buf = makeGlb({ asset: { version: '2.0' } });+ buf.writeUInt32LE(99999, 8);+ expect(isValidGlbHeader(buf)).toBe(false);+ });++ it('rejects glTF version 1', () => {+ const buf = makeGlb({ asset: { version: '1.0' } });+ buf.writeUInt32LE(1, 4);+ expect(isValidGlbHeader(buf)).toBe(false);+ });+ });++ describe('inspectGlb', () => {+ it('returns null for invalid GLB header', () => {+ expect(inspectGlb(Buffer.from('not a glb'))).toBeNull();+ });++ it('reports an unrigged mesh-only GLB (TRELLIS / TripoSR shape)', () => {+ const buf = makeGlb({+ asset: { version: '2.0', generator: 'TRELLIS-image-large' },+ meshes: [{ primitives: [{ attributes: { POSITION: 0 } }] }],+ nodes: [{ mesh: 0 }],+ scenes: [{ nodes: [0] }],+ });+ const info = inspectGlb(buf);+ expect(info).toMatchObject({+ valid: true,+ isRigged: false,+ skinCount: 0,+ skeletonJointCount: 0,+ meshCount: 1,+ nodeCount: 1,+ animationCount: 0,+ generator: 'TRELLIS-image-large',+ });+ });++ it('reports a rigged humanoid GLB (Hunyuan3D shape)', () => {+ const buf = makeGlb({+ asset: { version: '2.0', generator: 'Hunyuan3D-2 generation_all' },+ skins: [{ joints: [1, 2, 3, 4, 5, 6, 7, 8] }],+ nodes: [+ { mesh: 0, skin: 0 },+ { name: 'Hips' }, { name: 'Spine' }, { name: 'Neck' },+ { name: 'Head' }, { name: 'LeftArm' }, { name: 'RightArm' },+ { name: 'LeftLeg' }, { name: 'RightLeg' },+ ],+ meshes: [{ primitives: [{ attributes: { POSITION: 0, JOINTS_0: 1, WEIGHTS_0: 2 } }] }],+ animations: [{ name: 'Idle', channels: [], samplers: [] }],+ });+ const info = inspectGlb(buf);+ expect(info.isRigged).toBe(true);+ expect(info.skinCount).toBe(1);+ expect(info.skeletonJointCount).toBe(8);+ expect(info.meshCount).toBe(1);+ expect(info.animationCount).toBe(1);+ expect(info.generator).toMatch(/Hunyuan3D-2/);+ });++ it('handles a skin with empty joints list as unrigged', () => {+ const buf = makeGlb({+ asset: { version: '2.0' },+ skins: [{ joints: [] }],+ });+ const info = inspectGlb(buf);+ expect(info.isRigged).toBe(false);+ expect(info.skinCount).toBe(1);+ expect(info.skeletonJointCount).toBe(0);+ });++ it('returns null on broken JSON chunk', () => {+ const garbage = Buffer.from('{nope:not json');+ const padded = Buffer.concat([garbage, Buffer.from(' '.repeat((4 - (garbage.length % 4)) % 4))]);+ const total = 12 + 8 + padded.length;+ const buf = Buffer.alloc(total);+ buf.writeUInt32LE(0x46546C67, 0);+ buf.writeUInt32LE(2, 4);+ buf.writeUInt32LE(total, 8);+ buf.writeUInt32LE(padded.length, 12);+ buf.writeUInt32LE(0x4E4F534A, 16);+ padded.copy(buf, 20);+ expect(inspectGlb(buf)).toBeNull();+ });++ it('exposes extensionsUsed when the asset declares them', () => {+ const buf = makeGlb({+ asset: { version: '2.0' },+ extensionsUsed: ['KHR_materials_pbrSpecularGlossiness', 'KHR_texture_basisu'],+ });+ expect(inspectGlb(buf).extensionsUsed).toEqual([+ 'KHR_materials_pbrSpecularGlossiness',+ 'KHR_texture_basisu',+ ]);+ });+ });++ describe('isRiggedGlb', () => {+ it('true for skinned GLB', () => {+ const buf = makeGlb({ asset: { version: '2.0' }, skins: [{ joints: [1, 2, 3] }] });+ expect(isRiggedGlb(buf)).toBe(true);+ });++ it('false for static mesh', () => {+ const buf = makeGlb({ asset: { version: '2.0' }, meshes: [{}] });+ expect(isRiggedGlb(buf)).toBe(false);+ });++ it('false for non-GLB bytes (defensive)', () => {+ expect(isRiggedGlb(Buffer.from('garbage'))).toBe(false);+ });+ });+});diff --git a/tests/api/pump-fun-mcp.test.js b/tests/api/pump-fun-mcp.test.jsindex 37818c6a4..39883258e 100644--- a/tests/api/pump-fun-mcp.test.js+++ b/tests/api/pump-fun-mcp.test.js@@ -3,9 +3,15 @@// route's contract: JSON-RPC envelope, tool dispatch, on-chain reads, and// the indexer-not-configured error path (no fabricated payloads).-import { describe, it, expect, beforeEach, vi } from 'vitest';+import { describe, it, expect, beforeAll, beforeEach, vi } from 'vitest';import { Readable } from 'node:stream';+// Cold-import of /api/pump-fun-mcp transitively pulls the Solana web3 + pump+// SDK chain, which on a fresh Codespace can exceed 20s. We warm it in a hook+// with a generous window so the first test doesn't eat the cost under the+// default 5s testTimeout.+vi.setConfig({ testTimeout: 30_000, hookTimeout: 120_000 });+// Mock rate-limit + clientIp so the route never blocks on Upstash.vi.mock('../../api/_lib/rate-limit.js', () => ({limits: { mcpIp: vi.fn(async () => ({ success: true })) },@@ -62,10 +68,15 @@ function makeRes() {},};}+let handlerRef;+beforeAll(async () => {+ const mod = await import('../../api/pump-fun-mcp.js');+ handlerRef = mod.default;+});+async function call(rpc) {- const { default: handler } = await import('../../api/pump-fun-mcp.js');const res = makeRes();- await handler(makeReq(rpc), res);+ await handlerRef(makeReq(rpc), res);return { res, json: res.body ? JSON.parse(res.body) : null };}diff --git a/tests/api/x402-spec.test.js b/tests/api/x402-spec.test.jsindex 53d0337cb..1eb3d2c79 100644--- a/tests/api/x402-spec.test.js+++ b/tests/api/x402-spec.test.js@@ -11,17 +11,27 @@// - send402: writes a base64 PAYMENT-REQUIRED header that round-trips through// JSON.parse with the same extensions set.-import { afterEach, beforeEach, describe, it, expect, vi } from 'vitest';+import { afterEach, beforeAll, beforeEach, describe, it, expect, vi } from 'vitest';// env.js exposes process.env via getters, so each test's env mutations are// picked up immediately by api/_lib/x402-spec.js without needing a module// reset. We import the spec module once for the whole file — a fresh import// per test would re-walk @coinbase/x402 + @x402/extensions (cold-load > 30s-// on a CI worker) for no behavioural benefit. The bump to 30s covers the-// one-off cold-import on the very first test.-vi.setConfig({ testTimeout: 30_000 });+// on a CI worker) for no behavioural benefit.+//+// The cold-import alone routinely exceeds 60s on a fresh Codespace because it+// transitively pulls @coinbase/x402, @x402/extensions, the BSC direct-payment+// module, and (through that) the full ethers core. We warm the import in+// `beforeAll` so individual tests start with the spec already resolved, and+// give the warmup itself a generous 120s window. Tests still get 30s each —+// that's plenty for the synchronous fast paths we actually exercise.+vi.setConfig({ testTimeout: 30_000, hookTimeout: 120_000 });const specPromise = import('../../api/_lib/x402-spec.js');+let spec;+beforeAll(async () => {+ spec = await specPromise;+});const ORIG_ENV = { ...process.env };@@ -46,7 +56,10 @@ afterEach(() => {});async function loadSpec() {- return specPromise;+ // `spec` is populated in beforeAll, so this returns synchronously after+ // the module's been warmed up. The await is kept so any straggling+ // edge-case where a test runs before beforeAll completes still works.+ return spec ?? (await specPromise);}describe('permit2VariantOf', () => {