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
perf(pages): stop the home hero's 22 s teardown timer that froze the tab, pause offscreen viewers, and lazy-load the wallet stacks and the CDN bundle minifier fix
nirholasf64dc9b954d6
diff --git a/public/discover/discover.js b/public/discover/discover.jsindex a22ba658e..eb3a8a7fa 100644--- a/public/discover/discover.js+++ b/public/discover/discover.js@@ -231,6 +231,32 @@ if ('IntersectionObserver' in window && els.sentinel) {io.observe(els.sentinel);}+// Card previews render one frame and hold still; a card spins only while the+// visitor is on it. A continuously auto-rotating <model-viewer> re-renders and+// copies its pixels every frame for as long as the tab is open, and four of+// them in one grid cost 31 s of main-thread time in a 40 s Lighthouse run.+function setCardRotation(mv, on) {+ if (!mv) return;+ if (on) mv.setAttribute('auto-rotate', '');+ else mv.removeAttribute('auto-rotate');+}+const cardViewer = (target) => (target && target.closest ? target.closest('model-viewer.explore-card-mv') : null);+els.grid.addEventListener('pointerover', (e) => setCardRotation(cardViewer(e.target), true));+els.grid.addEventListener('pointerout', (e) => {+ const mv = cardViewer(e.target);+ if (mv && !(e.relatedTarget && mv.contains(e.relatedTarget))) setCardRotation(mv, false);+});+els.grid.addEventListener('focusin', (e) => {+ const card = e.target && e.target.closest ? e.target.closest('article') : null;+ setCardRotation(card && card.querySelector('model-viewer.explore-card-mv'), true);+});+els.grid.addEventListener('focusout', (e) => {+ const card = e.target && e.target.closest ? e.target.closest('article') : null;+ if (card && !(e.relatedTarget && card.contains(e.relatedTarget))) {+ setCardRotation(card.querySelector('model-viewer.explore-card-mv'), false);+ }+});+// Delegated copy-URI clickels.grid.addEventListener('click', (e) => {const btn = e.target.closest('[data-role="card-copy-uri"]');@@ -461,7 +487,6 @@ function renderThumb({ image, glbUrl, has3d, alt }) {disable-tapinteraction-prompt="none"camera-controls="false"- auto-rotaterotation-per-second="20deg"environment-image="neutral"shadow-intensity="0"diff --git a/src/home-bento.js b/src/home-bento.jsindex 58ca9bd57..96e6db275 100644--- a/src/home-bento.js+++ b/src/home-bento.js@@ -232,8 +232,25 @@canvas.focus();});+ // The arena redraws its grid and every visitor dot each frame. It used+ // to run from page load until the tab closed, offscreen included, which+ // cost ~1.5s of main-thread time per page view on a section most+ // visitors never scroll to. It now runs only while the canvas is on+ // screen and the tab is visible.+ var running = false;+ var rafId = 0;+ var onScreen = !('IntersectionObserver' in window);+ function setRunning(on) {+ if (on === running) return;+ running = on;+ if (on && !rafId) rafId = requestAnimationFrame(tick);+ }+ function syncRunning() {+ setRunning(onScreen && !document.hidden);+ }function tick() {- requestAnimationFrame(tick);+ if (!running) { rafId = 0; return; }+ rafId = requestAnimationFrame(tick);var speed = 0.006;if (keys['w'] || keys['arrowup']) player.y -= speed;if (keys['s'] || keys['arrowdown']) player.y += speed;@@ -282,7 +299,14 @@ctx.font = '8px monospace';ctx.fillText('you', player.x * W + 8, player.y * H + 3);}- tick();+ if ('IntersectionObserver' in window) {+ new IntersectionObserver(function(entries) {+ onScreen = entries.some(function(e) { return e.isIntersecting; });+ syncRunning();+ }, { rootMargin: '100px 0px' }).observe(canvas);+ }+ document.addEventListener('visibilitychange', syncRunning);+ syncRunning();})();// ── 4. x402 Payments: interactive flow ──────────────────────────diff --git a/src/home-live-agents.js b/src/home-live-agents.jsindex f23acb434..9687b03b9 100644--- a/src/home-live-agents.js+++ b/src/home-live-agents.js@@ -91,6 +91,21 @@if (!glb) throw new Error('no renderable avatar found');return glb;}+ function showHeroSlowNotice(heroInner) {+ const copy = heroInner.querySelector('.hero-stage-loading-copy');+ if (!copy || heroInner.querySelector('#hero-retry')) return;+ copy.textContent = 'Still loading the live agent ';+ const retry = document.createElement('button');+ retry.type = 'button';+ retry.className = 'btn btn--sm';+ retry.id = 'hero-retry';+ retry.textContent = 'Retry';+ retry.addEventListener('click', () => {+ heroInner.innerHTML = '';+ bootHeroAvatar();+ });+ copy.appendChild(retry);+ }function showHeroFallback(heroInner) {heroInner.innerHTML = '<div class="hero-stage-fallback" role="status">'+ '<p>The live preview couldn’t load right now.</p>'@@ -156,15 +171,25 @@// Append alongside the loading overlay (which sits on top via z-index// and fades out on ready), so the stage never blinks back to empty// between clearing the placeholder and the model's first frame.+ // A boot failure (GLB fetch or decode, renderer) is reported by the+ // element itself, and that is the only signal that retires a booting+ // hero. A 22-second wall-clock timer used to do it, and on a slow+ // device or connection it fired while the avatar was still loading:+ // the visitor saw "couldn't load" for a model that was about to+ // appear, and tearing down a mid-boot viewer forces a WebGL context+ // loss, which under Lighthouse froze the page for the rest of the run.+ heroEl.addEventListener('agent:error', () => {+ if (!ready) showHeroFallback(heroInner);+ }, { once: true });heroInner.appendChild(heroEl);initHeroWalk(heroEl);initHeroChips(heroEl);- // Safety net: if the element upgraded but never signals ready (an- // internal GLB decode / render failure), don't leave "Summoning…" up- // forever. Surface the retryable fallback the same as a hard failure.+ // Unusually slow but not failed: keep the element booting (a teardown+ // would discard the work already done) and hand the visitor the+ // choice to retry instead of making it for them.setTimeout(() => {- if (!ready && heroInner.querySelector('.hero-stage-loading')) showHeroFallback(heroInner);- }, 22000);+ if (!ready && heroInner.querySelector('.hero-stage-loading')) showHeroSlowNotice(heroInner);+ }, 45000);}} catch (e) {console.warn('[home] avatar boot failed', e);@@ -545,9 +570,16 @@btn.appendChild(initial);if (a.thumb) {var img = document.createElement('img');- img.src = a.thumb;- img.alt = a.name || '';+ // Lazy-load must be declared before src: setting src first starts+ // the fetch immediately, and the strip's full-size thumbnails+ // (100-300 KB each) were all downloading on page load for a row+ // three screens down.img.loading = 'lazy';+ img.decoding = 'async';+ img.width = 28;+ img.height = 28;+ img.alt = a.name || '';+ img.src = a.thumb;img.onerror = function() { this.style.display = 'none'; initial.style.display = 'flex'; };btn.appendChild(img);} else {@@ -809,12 +841,28 @@}});- fetchGlb(state.avatarId).then(function(glb) {- state.glbUrl = glb;- syncCode();- updatePreview();- loadAvatars();- }).catch(function() { showPreviewMessage(); });+ // The preview is a full <agent-3d> viewer (its own WebGL context, a GLB+ // decode, a shader compile) three screens below the hero. Booting it on+ // page load had it competing with the hero for the main thread while+ // nobody could see it; it boots as the playground scrolls near instead.+ function bootPlayground() {+ fetchGlb(state.avatarId).then(function(glb) {+ state.glbUrl = glb;+ syncCode();+ updatePreview();+ loadAvatars();+ }).catch(function() { showPreviewMessage(); });+ }+ if ('IntersectionObserver' in window) {+ var pgObs = new IntersectionObserver(function(entries) {+ if (!entries.some(function(e) { return e.isIntersecting; })) return;+ pgObs.disconnect();+ bootPlayground();+ }, { rootMargin: '400px 0px' });+ pgObs.observe(preview);+ } else {+ bootPlayground();+ }})();// ── Showcase 3D — live agent grid ──────────────────────────────diff --git a/src/three-access.js b/src/three-access.jsindex b90f90b11..657a810ba 100644--- a/src/three-access.js+++ b/src/three-access.js@@ -27,7 +27,6 @@// Everything degrades to a safe locked/anonymous state on any network failure —// the UI never throws and the server stays the only authority on eligibility.-import { getConnectedWallet, getConnectedWalletAddress } from './wallet.js';import { safeUrl } from './safe-url.js';import { track, trackFunnelStep, ANALYTICS_EVENTS } from './analytics.js';@@ -51,9 +50,23 @@ const PRICE_URL = '/three-token';// mobile), or null when none is connected — in which case every read falls back to// the session identity. Seeded on import and kept current by the wallet:changed// listener below. Reading is best-effort: a wallet module hiccup degrades to session.+// The wallet module (with the @solana/web3.js + Mobile Wallet Adapter bundle behind it)+// loads on demand. The connected address it publishes is mirrored onto the nav's+// connect button (`data-address`, see updateWalletState) and broadcast on+// wallet:changed, so reading it needs no import; only the signature path below,+// a connected holder minting a pass, pulls the module in. Before this the tier+// badge, which mounts on every page, dragged ~290 KB (gzipped) of wallet code+// onto pages that never touch a wallet.+let _walletModule = null;+function loadWalletModule() {+ if (!_walletModule) _walletModule = import('./wallet.js');+ return _walletModule;+}function readConnectedWallet() {try {- return getConnectedWalletAddress() || null;+ if (typeof document === 'undefined') return null;+ const btn = document.getElementById('connect-wallet-btn');+ return (btn && btn.dataset.address) || null;} catch {return null;}@@ -194,6 +207,7 @@ export async function getTierPass({ interactive = false } = {}) {// changed mid-mint, so a wallet switch can't leave a stale pass on the header.async function mintWalletTierPass(wallet) {try {+ const { getConnectedWallet } = await loadWalletModule();const provider = getConnectedWallet();if (!provider?.signMessage) return null;const message = buildTierPassMessage(wallet, new Date().toISOString());diff --git a/src/wallet-auth.js b/src/wallet-auth.jsindex 4d15fa422..13be312d2 100644--- a/src/wallet-auth.js+++ b/src/wallet-auth.js@@ -1,4 +1,3 @@-import { ensureWallet } from './erc8004/agent-registry.js';import {identifyUser,resetIdentity,@@ -30,6 +29,11 @@ export async function signInWithWallet() {let chainId;let address;try {+ // agent-registry carries ethers (140 KB gzipped). Only a real sign-in+ // click needs it, so it loads here rather than with the page: /create+ // imports this module for its sign-in button and was shipping the whole+ // EVM stack to every visitor who never pressed it.+ const { ensureWallet } = await import('./erc8004/agent-registry.js');const wallet = await ensureWallet();address = wallet.address;chainId = wallet.chainId;diff --git a/tests/three-access-client.test.js b/tests/three-access-client.test.jsindex 88357182f..c06c999c6 100644--- a/tests/three-access-client.test.js+++ b/tests/three-access-client.test.js@@ -11,8 +11,10 @@// • the session path still mints silently (no wallet, no body);// • mountTierBadge renders for a connected-wallet holder even when signed_in:false.//-// src/wallet.js is mocked so we drive the connected identity + provider directly; the-// live endpoint + signature verifier are covered by tests/three-tier-public.test.js.+// src/wallet.js is mocked for the provider (signature path); the connected address is+// read from the nav connect button's data-address mirror, exactly as wallet.js+// publishes it, so loadModule() seeds that from the same state. The live endpoint ++// signature verifier are covered by tests/three-tier-public.test.js.import { describe, it, expect, beforeEach, vi } from 'vitest';@@ -46,6 +48,12 @@ function jsonRes(body, { ok = true, status = 200 } = {}) {// Fresh module instance per test so the in-memory caches don't leak across cases.async function loadModule() {vi.resetModules();+ if (state.addr) {+ const btn = document.createElement('button');+ btn.id = 'connect-wallet-btn';+ btn.dataset.address = state.addr;+ document.body.appendChild(btn);+ }return import('../src/three-access.js');}@@ -144,6 +152,9 @@ describe('getTierPass — signature path for a connected wallet', () => {const a = getTierPass({ interactive: true });const b = getTierPass({ interactive: true });+ // The provider is reached through the lazily-loaded wallet module, so the+ // signature prompt lands a few microtasks after the calls, not synchronously.+ await vi.waitFor(() => expect(state.provider.signMessage).toHaveBeenCalled());resolveSig({ signature: new Uint8Array(64) });const [ra, rb] = await Promise.all([a, b]);expect(ra).toBe(rb);diff --git a/vite.config.js b/vite.config.jsindex fed226822..95fdd6c50 100644--- a/vite.config.js+++ b/vite.config.js@@ -3544,26 +3544,35 @@ const appConfig = {// `/*#__PURE__*/` annotations for their tree-shaker. Our lib output is not an// npm dependency: it is the CDN bundle browsers download from// /agent-3d/latest/agent-3d.js, and the option is forced, so no `build.minify`-// or `esbuild` setting can turn it back on. This renderChunk pass strips the-// whitespace esbuild left behind, which took the shipped bundle from 4.24 MB to-// 2.77 MB raw (1.03 MB → 792 KB gzipped) and cut the parse cost that dominated-// the homepage's blocking time. Identifiers and syntax are already minified by-// Vite's own pass, so only whitespace is touched here.+// or `esbuild` setting can turn it back on. This pass strips the whitespace+// esbuild leaves behind. Identifiers and syntax are already minified by Vite's+// own pass, so only whitespace is touched here.+//+// It has to run in generateBundle, not renderChunk. Vite's own esbuild+// transpile plugin is a renderChunk hook that runs AFTER user plugins and+// re-prints the chunk with indentation, so a renderChunk pass here was undone+// before the file was written: production shipped 3.46 MB / 69,759 lines of+// pretty-printed code as the "minified" CDN bundle (2026-09-01). generateBundle+// runs once every renderChunk hook is finished, so what it writes is what ships.function minifyLibWhitespace() {return {name: 'threews-lib-minify-whitespace',apply: 'build',- async renderChunk(code, chunk) {+ async generateBundle(_options, bundle) {const { transform } = await import('esbuild');- const res = await transform(code, {- loader: 'js',- minifyWhitespace: true,- minifyIdentifiers: false,- minifySyntax: false,- legalComments: 'none',- sourcefile: chunk.fileName,- });- return { code: res.code, map: null };+ for (const chunk of Object.values(bundle)) {+ if (chunk.type !== 'chunk') continue;+ const res = await transform(chunk.code, {+ loader: 'js',+ minifyWhitespace: true,+ minifyIdentifiers: false,+ minifySyntax: false,+ legalComments: 'none',+ sourcefile: chunk.fileName,+ });+ chunk.code = res.code;+ chunk.map = null;+ }},};}