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
fix(render): pin one three.js version across the headless renderers and share its CDN fallback
nirholascd5d01bc6ac1
diff --git a/api/_lib/avatar-render.js b/api/_lib/avatar-render.jsindex 4d2d93954..c69344b66 100644--- a/api/_lib/avatar-render.js+++ b/api/_lib/avatar-render.js@@ -12,6 +12,7 @@ import { env } from './env.js';import { publicUrl, putObject, headObject } from './r2.js';import { poseRuntimeModules } from './pose-runtime.js';import { scriptJson, safeCssColor } from './render-safe.js';+import { DEFAULT_THREE_BASE, resolveThreeCdn, THREE_VERSION, threeImportMap } from './three-cdn.js';import { PRESETS } from '../../src/pose-presets.js';export const MIN_DIM = 64;@@ -297,7 +298,6 @@ export async function renderAvatarImage({ avatar, glbUrl, params, awaitUpload =const DEFAULT_CHROMIUM_PACK ='https://github.com/Sparticuz/chromium/releases/download/v148.0.0/chromium-v148.0.0-pack.x64.tar';const CHROMIUM_PACK = env.CHROMIUM_PACK_URL || DEFAULT_CHROMIUM_PACK;-const THREE_VERSION = '0.176.0';let _browserPromise = null;async function getBrowser() {@@ -327,7 +327,7 @@ async function getBrowser() {// from here.export { poseRuntimeModules };-export function sceneViewerHtml({ glbUrl, width, height, background, pose, cameraOrbit, expression, scenePreset }) {+export function sceneViewerHtml({ glbUrl, width, height, background, pose, cameraOrbit, expression, scenePreset, threeBase = DEFAULT_THREE_BASE }) {// Every value below is interpolated into a <script> block. scriptJson (not// JSON.stringify) is what keeps a caller-supplied string from closing the tag// and running its own code in a page with container network egress.@@ -344,8 +344,7 @@ export function sceneViewerHtml({ glbUrl, width, height, background, pose, camer</head><body><canvas id="c" width="${width}" height="${height}" style="display:block;width:${width}px;height:${height}px"></canvas><script type="importmap">{ "imports": {- "three": "https://unpkg.com/three@${THREE_VERSION}/build/three.module.js",- "three/addons/": "https://unpkg.com/three@${THREE_VERSION}/examples/jsm/",+ ${scriptJson(threeImportMap(threeBase)).slice(1, -1)},"glb-canonicalize": "${poseModules['glb-canonicalize']}","pose-mannequin": "${poseModules['pose-mannequin']}","pose-rig": "${poseModules['pose-rig']}"@@ -446,7 +445,7 @@ const preset = ${presetJson};// Pipeline GLBs ship Draco geometry, Meshopt buffers, and KTX2 textures;// a bare GLTFLoader throws "No DRACOLoader instance provided". Register// every standard compression decoder from the pinned three.js release.-const ADDONS = 'https://unpkg.com/three@${THREE_VERSION}/examples/jsm/';+const ADDONS = ${scriptJson(`${threeBase}examples/jsm/`)};const dracoLoader = new DRACOLoader().setDecoderPath(ADDONS + 'libs/draco/');const ktx2Loader = new KTX2Loader().setTranscoderPath(ADDONS + 'libs/basis/').detectSupport(renderer);@@ -499,10 +498,14 @@ export async function renderAvatarScene({const page = await browser.newPage();try {await page.setViewport({ width: W, height: H, deviceScaleFactor: 1 });+ // Pick a live three.js CDN first: an unpkg outage would otherwise hang+ // the page's module import until the watchdog fires and the render+ // comes back blank.+ const { base: threeBase } = await resolveThreeCdn(THREE_VERSION);const html = sceneViewerHtml({glbUrl, width: W, height: H, background,pose, cameraOrbit: cameraOrbit || { theta: 0, phi: 80, radius: null },- expression, scenePreset,+ expression, scenePreset, threeBase,});await page.setContent(html, { waitUntil: 'domcontentloaded' });await page.waitForFunction(diff --git a/api/_lib/render-clip.js b/api/_lib/render-clip.jsindex 8f52ecf3e..f111d0d89 100644--- a/api/_lib/render-clip.js+++ b/api/_lib/render-clip.js@@ -20,6 +20,7 @@import { env } from './env.js';import { fetchModel } from './fetch-model.js';import { scriptJson, safeCssColor } from './render-safe.js';+import { DEFAULT_THREE_BASE, resolveThreeCdn, THREE_VERSION, threeImportMap } from './three-cdn.js';import { poseRuntimeModules } from './pose-runtime.js';import { PRESETS } from '../../src/pose-presets.js';@@ -29,7 +30,6 @@ const DEFAULT_MAX_GLB_BYTES = 25 * 1024 * 1024;const DEFAULT_CHROMIUM_PACK ='https://github.com/Sparticuz/chromium/releases/download/v148.0.0/chromium-v148.0.0-pack.x64.tar';const CHROMIUM_PACK = env.CHROMIUM_PACK_URL || DEFAULT_CHROMIUM_PACK;-const THREE_VERSION = '0.176.0';let _browserPromise = null;async function getBrowser() {@@ -63,7 +63,7 @@ function poseById(id) {// working; the implementation is shared with render-glb.js in ./render-safe.js.export { scriptJson };-function viewerHtml({ glbBase64, width, height, background, pose, cameraOrbit, expression }) {+function viewerHtml({ glbBase64, width, height, background, pose, cameraOrbit, expression, threeBase = DEFAULT_THREE_BASE }) {const bg = background === 'transparent' ? 'null' : scriptJson(safeCssColor(background) || '#0a0a0a');const poseJson = pose ? scriptJson(pose.pose) : 'null';const orbitJson = scriptJson(cameraOrbit || { theta: 0, phi: 80, radius: null });@@ -76,8 +76,7 @@ function viewerHtml({ glbBase64, width, height, background, pose, cameraOrbit, e<canvas id="c" width="${width}" height="${height}" style="display:block;width:${width}px;height:${height}px"></canvas><script>window.__GLB_B64=${scriptJson(glbBase64)};</script><script type="importmap">{ "imports": {- "three": "https://unpkg.com/three@${THREE_VERSION}/build/three.module.js",- "three/addons/": "https://unpkg.com/three@${THREE_VERSION}/examples/jsm/",+ ${scriptJson(threeImportMap(threeBase)).slice(1, -1)},"glb-canonicalize": "${poseModules['glb-canonicalize']}","pose-mannequin": "${poseModules['pose-mannequin']}","pose-rig": "${poseModules['pose-rig']}"@@ -183,7 +182,7 @@ const expression = ${expressionJson};// Pipeline GLBs ship Draco geometry, Meshopt buffers, and KTX2 textures;// a bare GLTFLoader throws "No DRACOLoader instance provided". Register// every standard compression decoder from the pinned three.js release.-const ADDONS = 'https://unpkg.com/three@${THREE_VERSION}/examples/jsm/';+const ADDONS = ${scriptJson(`${threeBase}examples/jsm/`)};const dracoLoader = new DRACOLoader().setDecoderPath(ADDONS + 'libs/draco/');const ktx2Loader = new KTX2Loader().setTranscoderPath(ADDONS + 'libs/basis/').detectSupport(renderer);@@ -270,7 +269,11 @@ export async function renderClip({const page = await browser.newPage();try {await page.setViewport({ width: W, height: H, deviceScaleFactor: 1 });- const html = viewerHtml({ glbBase64, width: W, height: H, background, pose, cameraOrbit, expression });+ // Pick a live three.js CDN first: an unpkg outage would otherwise hang+ // the page's module import until the watchdog fires and the clip comes+ // back blank.+ const { base: threeBase } = await resolveThreeCdn(THREE_VERSION);+ const html = viewerHtml({ glbBase64, width: W, height: H, background, pose, cameraOrbit, expression, threeBase });await page.setContent(html, { waitUntil: 'domcontentloaded' });await page.waitForFunction('window.__renderDone === true || window.__renderError !== null',diff --git a/api/_lib/render-glb.js b/api/_lib/render-glb.jsindex 2fe7cbb52..98f6bba30 100644--- a/api/_lib/render-glb.js+++ b/api/_lib/render-glb.js@@ -13,6 +13,7 @@// so Vercel's NFT doesn't statically trace the chromium tree for every route// that transitively imports this module — that trace caused 45-min build hangs.import { env } from './env.js';+import { DEFAULT_THREE_BASE, resolveThreeCdn, THREE_VERSION, threeImportMap } from './three-cdn.js';import { fetchModel } from './fetch-model.js';import { scriptJson, safeCssColor } from './render-safe.js';@@ -31,10 +32,6 @@ const DEFAULT_CHROMIUM_PACK ='https://github.com/Sparticuz/chromium/releases/download/v148.0.0/chromium-v148.0.0-pack.x64.tar';const CHROMIUM_PACK = env.CHROMIUM_PACK_URL || DEFAULT_CHROMIUM_PACK;-// three.js version pinned in package-lock — must match what the in-app viewer-// renders so the server-side preview is faithful (camera, lighting, material-// behavior are all version-sensitive).-const THREE_VERSION = '0.176.0';// Poster composition. A 26° yaw reads as a natural 3/4 portrait without hiding// the front of the model; 1.22 leaves enough margin that a T-pose's fingertips@@ -145,7 +142,7 @@ function releaseRenderSlot() {// Inline viewer HTML — bundled into the function so the renderer needs no// extra static assets. three.js + GLTFLoader load from unpkg pinned to the// installed version. window.__renderDone signals readiness to puppeteer.-function viewerHtml({ glbBase64, width, height, background, backdrop }) {+function viewerHtml({ glbBase64, width, height, background, backdrop, threeBase = DEFAULT_THREE_BASE }) {// A gradient backdrop renders as page CSS behind a transparent canvas: the// screenshot composites the two, so the scene itself stays background-free.// `background` reaches here straight from a public handler, and both slots@@ -166,10 +163,7 @@ function viewerHtml({ glbBase64, width, height, background, backdrop }) {</head><body><canvas id="c" width="${width}" height="${height}" style="display:block;width:${width}px;height:${height}px"></canvas><script>window.__GLB_B64=${scriptJson(glbBase64)};</script>-<script type="importmap">{ "imports": {- "three": "https://unpkg.com/three@${THREE_VERSION}/build/three.module.js",- "three/addons/": "https://unpkg.com/three@${THREE_VERSION}/examples/jsm/"-}}</script>+<script type="importmap">{ "imports": ${scriptJson(threeImportMap(threeBase))} }</script><script type="module">import * as THREE from 'three';import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';@@ -217,7 +211,7 @@ const rim = new THREE.DirectionalLight(0xffffff, 1.1); rim.position.set(-1.5, 3,// model — register every standard compression decoder so the renderer// handles optimized GLBs instead of falling back to the SVG card. Decoder// assets load from the same pinned three.js release as the loaders.-const ADDONS = 'https://unpkg.com/three@${THREE_VERSION}/examples/jsm/';+const ADDONS = ${scriptJson(`${threeBase}examples/jsm/`)};const dracoLoader = new DRACOLoader().setDecoderPath(ADDONS + 'libs/draco/');const ktx2Loader = new KTX2Loader().setTranscoderPath(ADDONS + 'libs/basis/').detectSupport(renderer);@@ -372,9 +366,13 @@ async function renderOnce({ glbBase64, width, height, background, backdrop }) {const page = await browser.newPage();try {await page.setViewport({ width, height, deviceScaleFactor: 1 });- const html = viewerHtml({ glbBase64, width, height, background, backdrop });+ // Resolve which CDN still serves three.js before building the page. An+ // unpkg outage would otherwise hang the module import until the+ // watchdog below fires and every poster comes back blank.+ const { base: threeBase } = await resolveThreeCdn(THREE_VERSION);+ const html = viewerHtml({ glbBase64, width, height, background, backdrop, threeBase });// data: URL avoids needing a network fetch for the bootstrap page itself.- // importmap dependencies (three, GLTFLoader) still come from unpkg.+ // importmap dependencies (three, GLTFLoader) still come from the CDN.await page.setContent(html, { waitUntil: 'domcontentloaded' });await page.waitForFunction('window.__renderDone === true || window.__renderError !== null',diff --git a/api/_lib/three-cdn.js b/api/_lib/three-cdn.jsindex a41bf42d2..0d0a5e6a4 100644--- a/api/_lib/three-cdn.js+++ b/api/_lib/three-cdn.js@@ -8,11 +8,21 @@// is to check unpkg once (bounded HEAD), remember the answer for ten minutes,// and hand the renderers whichever host is up.+// The three.js release the headless renderers load. All three renderers share+// this pin so a bump lands everywhere at once instead of leaving one poster+// lane on an older release than the others.+export const THREE_VERSION = '0.176.0';+export const THREE_CDN_HOSTS = {unpkg: (version) => `https://unpkg.com/three@${version}/`,jsdelivr: (version) => `https://cdn.jsdelivr.net/npm/three@${version}/`,};+// The base a renderer uses when it has not resolved a host yet. Keeping the+// default on unpkg means a caller that skips the probe behaves exactly as the+// renderers did before the failover was wired in.+export const DEFAULT_THREE_BASE = THREE_CDN_HOSTS.unpkg(THREE_VERSION);+const PROBE_TIMEOUT_MS = 3_000;const PROBE_TTL_MS = 10 * 60_000;diff --git a/tests/api/three-cdn-wiring.test.js b/tests/api/three-cdn-wiring.test.jsnew file mode 100644index 000000000..a98b010c9--- /dev/null+++ b/tests/api/three-cdn-wiring.test.js@@ -0,0 +1,137 @@+// The three.js CDN failover, and the tripwire that keeps it wired in.+//+// api/_lib/three-cdn.js shipped fully written but imported by nobody: all+// three headless renderers still hardcoded `unpkg.com/three@…` in their import+// maps, so the failover it describes never ran. An unpkg outage would have+// hung each page's module import until the render watchdog fired, and every+// poster, avatar image and clip would have come back blank with no error to+// explain it. These tests cover the resolver itself and, more importantly,+// assert that the renderers still route through it.++import { describe, it, expect, beforeEach } from 'vitest';+import { readFile } from 'node:fs/promises';++import {+ DEFAULT_THREE_BASE,+ THREE_CDN_HOSTS,+ THREE_VERSION,+ _resetThreeCdnProbes,+ resolveThreeCdn,+ threeImportMap,+} from '../../api/_lib/three-cdn.js';++const RENDERERS = [+ 'api/_lib/render-glb.js',+ 'api/_lib/avatar-render.js',+ 'api/_lib/render-clip.js',+];++beforeEach(() => { _resetThreeCdnProbes(); });++describe('resolveThreeCdn', () => {+ it('stays on unpkg while unpkg answers the probe', async () => {+ const fetchImpl = async () => ({ ok: true, status: 200 });+ const { host, base, cached } = await resolveThreeCdn(THREE_VERSION, { fetchImpl });+ expect(host).toBe('unpkg');+ expect(base).toBe(THREE_CDN_HOSTS.unpkg(THREE_VERSION));+ expect(cached).toBe(false);+ });++ it('fails over to jsDelivr when unpkg errors', async () => {+ const fetchImpl = async () => { throw new Error('ECONNRESET'); };+ const { host, base } = await resolveThreeCdn(THREE_VERSION, { fetchImpl });+ expect(host).toBe('jsdelivr');+ expect(base).toBe(THREE_CDN_HOSTS.jsdelivr(THREE_VERSION));+ });++ it('fails over on a non-ok status, not just a thrown error', async () => {+ const fetchImpl = async () => ({ ok: false, status: 503 });+ const { host } = await resolveThreeCdn(THREE_VERSION, { fetchImpl });+ expect(host).toBe('jsdelivr');+ });++ it('probes once per TTL so a render burst pays one HEAD', async () => {+ let calls = 0;+ const fetchImpl = async () => { calls += 1; return { ok: true, status: 200 }; };+ await resolveThreeCdn(THREE_VERSION, { fetchImpl });+ const second = await resolveThreeCdn(THREE_VERSION, { fetchImpl });+ expect(calls).toBe(1);+ expect(second.cached).toBe(true);+ });++ it('re-probes past the TTL, so a recovered unpkg is picked back up', async () => {+ let ok = false;+ let now = 1_000_000;+ const fetchImpl = async () => { if (!ok) throw new Error('down'); return { ok: true, status: 200 }; };+ expect((await resolveThreeCdn(THREE_VERSION, { fetchImpl, now: () => now })).host).toBe('jsdelivr');+ ok = true;+ now += 11 * 60_000;+ expect((await resolveThreeCdn(THREE_VERSION, { fetchImpl, now: () => now })).host).toBe('unpkg');+ });++ it('builds an import map that resolves both three and its addons', () => {+ const map = threeImportMap(THREE_CDN_HOSTS.jsdelivr(THREE_VERSION));+ expect(map.three).toBe(`https://cdn.jsdelivr.net/npm/three@${THREE_VERSION}/build/three.module.js`);+ expect(map['three/addons/']).toBe(`https://cdn.jsdelivr.net/npm/three@${THREE_VERSION}/examples/jsm/`);+ });+});++describe('the renderers route through the resolver', () => {+ it('no renderer hardcodes a three.js CDN host', async () => {+ for (const path of RENDERERS) {+ const src = await readFile(new URL(`../../${path}`, import.meta.url), 'utf8');+ expect(src, `${path} hardcodes a CDN host instead of using resolveThreeCdn()`)+ .not.toMatch(/unpkg\.com\/three@|cdn\.jsdelivr\.net\/npm\/three@/);+ }+ });++ it('every renderer imports the shared resolver and pin', async () => {+ for (const path of RENDERERS) {+ const src = await readFile(new URL(`../../${path}`, import.meta.url), 'utf8');+ expect(src, `${path} does not import three-cdn.js`).toMatch(/from '\.\/three-cdn\.js'/);+ expect(src, `${path} never calls resolveThreeCdn`).toMatch(/resolveThreeCdn\(THREE_VERSION\)/);+ expect(src, `${path} keeps its own THREE_VERSION pin`).not.toMatch(/const THREE_VERSION\s*=/);+ }+ });+});++describe('sceneViewerHtml honors the resolved base', () => {+ function importMapOf(html) {+ const m = html.match(/<script type="importmap">([\s\S]*?)<\/script>/);+ expect(m, 'render page has no import map').toBeTruthy();+ return JSON.parse(m[1]).imports;+ }++ const args = {+ glbUrl: 'https://example.com/a.glb',+ width: 64, height: 64, background: '#000',+ pose: null, cameraOrbit: null, expression: null, scenePreset: null,+ };++ it('defaults to unpkg when the caller skips the probe', async () => {+ const { sceneViewerHtml } = await import('../../api/_lib/avatar-render.js');+ const imports = importMapOf(sceneViewerHtml(args));+ expect(imports.three).toBe(threeImportMap(DEFAULT_THREE_BASE).three);+ });++ it('emits a parseable import map that keeps the pose modules alongside three', async () => {+ const { sceneViewerHtml } = await import('../../api/_lib/avatar-render.js');+ const base = THREE_CDN_HOSTS.jsdelivr(THREE_VERSION);+ const html = sceneViewerHtml({ ...args, threeBase: base });+ const imports = importMapOf(html);+ expect(imports.three).toBe(threeImportMap(base).three);+ expect(imports['three/addons/']).toBe(threeImportMap(base)['three/addons/']);+ // The pose runtime is served as data: URLs from the same map; a+ // malformed splice of the three entries would have dropped them.+ expect(imports['glb-canonicalize']).toMatch(/^data:text\/javascript/);+ expect(imports['pose-rig']).toMatch(/^data:text\/javascript/);+ });++ it('switches the decoder-asset base too, not just the module imports', async () => {+ const { sceneViewerHtml } = await import('../../api/_lib/avatar-render.js');+ const base = THREE_CDN_HOSTS.jsdelivr(THREE_VERSION);+ const html = sceneViewerHtml({ ...args, threeBase: base });+ expect(html).toContain(`${base}examples/jsm/`);+ expect(html).not.toContain('unpkg.com');+ });+});