Skip to content

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.

perf(pages): stop paying for a WebGL bundle and an oversized hero GLB on load

nirholasea6f1e708aa7
diff --git a/api/avatars/featured.js b/api/avatars/featured.js
index ace3525e1..7942b9527 100644
--- a/api/avatars/featured.js
+++ b/api/avatars/featured.js
@@ -22,7 +22,7 @@ export default wrap(async (req, res) => {
const limit = Math.min(Math.max(Number(url.searchParams.get('limit')) || 30, 1), 60);
const rows = await sql`
- SELECT id, name, slug, visibility, created_at, featured, view_count
+ SELECT id, name, slug, visibility, created_at, featured, view_count, size_bytes
FROM avatars
WHERE deleted_at IS NULL
AND visibility = 'public'
@@ -40,6 +40,13 @@ export default wrap(async (req, res) => {
visibility: r.visibility,
featured: r.featured === true,
has_thumbnail: true,
+ // The GLB's size on disk. A caller that renders one of these avatars
+ // pays for it on its own critical path (the homepage hero decodes the
+ // model while the page is still trying to become interactive), and this
+ // list mixes 90 KB props with 10 MB scans. Publishing the number here
+ // lets a caller choose within a performance budget from one request
+ // instead of fetching every candidate's detail record to find out.
+ size_bytes: r.size_bytes == null ? null : Number(r.size_bytes),
thumb_url: `${env.APP_ORIGIN}/api/avatars/${r.id}/thumb`,
created_at: r.created_at,
})),
diff --git a/pages/create.html b/pages/create.html
index 30f9fa4e3..f3dbcfa9c 100644
--- a/pages/create.html
+++ b/pages/create.html
@@ -483,6 +483,15 @@
height: 100%;
--poster-color: transparent;
}
+ /* Before the element bundle upgrades the tag, model-viewer cannot paint
+ its own `poster`, so the card would open as an empty box. Paint the
+ same poster image as the element's background for exactly that
+ window: the card looks finished from first paint, and the rule stops
+ applying the moment the element is defined. */
+ .hero-card-preview model-viewer:not(:defined) {
+ display: block;
+ background: center / contain no-repeat url('/avatars/default-poster.webp');
+ }
.recommended-badge {
position: absolute;
@@ -1234,16 +1243,19 @@
}
}
</style>
- <!-- Deferred, and placed BEFORE the model-viewer module: defer scripts and
- module scripts execute in document order, so the meshopt shim still
- registers its decoder before model-viewer's define runs. -->
+ <!-- The meshopt decoder shim stays eager: it is a 2 KB classic script that
+ intercepts customElements.define(), so it registers its decoder
+ whenever the element bundle turns up. -->
<script src="/model-viewer-meshopt.js" defer></script>
- <script
- type="module"
- src="https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js"
- integrity="sha384-sr9b4Ux0WhAUGclJ0ym0FSY2zSOMmNSn0bP/SA0e6bNCrpn/5W3QL8mm+LdlQMKw"
- crossorigin="anonymous"
- ></script>
+ <!-- The <model-viewer> element bundle is NOT loaded here. This page has one
+ viewer, in the hero card, and that viewer already defers its model with
+ `data-src` until someone hovers, focuses or taps the card. The 253 KB
+ bundle was still fetched and evaluated on every visit to build a WebGL
+ renderer for it: 8.2 s of main-thread time in a Lighthouse desktop
+ trace, spent on a card most visitors never touch. It now loads on the
+ same first attention that promotes `data-src`, through
+ src/shared/attended-rotation.js, and the poster below holds the card's
+ appearance until then. -->
<script>
(function () {
var cleared = false;
diff --git a/public/discover/discover.js b/public/discover/discover.js
index dba29f44a..a154b5115 100644
--- a/public/discover/discover.js
+++ b/public/discover/discover.js
@@ -17,6 +17,7 @@
*/
import { createListControls } from '../../src/shared/list-controls.js';
+import { ensureModelViewerOrFallback } from '../../src/shared/model-viewer-loader.js';
import { skeletonHTML, emptyStateHTML, errorStateHTML } from '../../src/shared/state-kit.js';
const CHAINS = [
@@ -231,8 +232,7 @@ if ('IntersectionObserver' in window && els.sentinel) {
io.observe(els.sentinel);
}
-// Attended rotation, the same policy as src/shared/attended-rotation.js (this
-// file ships from public/ verbatim, so it cannot import it). A card turns when
+// Attended rotation, the same policy as src/shared/attended-rotation.js. A card turns when
// it scrolls into view, settles once it has turned far enough to read as 3D,
// and turns again on hover or focus. Before this every card in the grid rotated
// for the life of the tab, and model-viewer blits each element's pixels every
@@ -291,6 +291,57 @@ function observeCardTurns() {
}
}
+// ── The <model-viewer> element bundle, fetched only when a 3D card needs it ──
+//
+// index.html no longer ships the 253 KB bundle on every visit. Most cards in
+// this directory are static R2 thumbnails, so on a typical page the element is
+// never used at all, and when it is used it is usually for a card the visitor
+// has to scroll to. Loading it up front cost the page its interactivity:
+// Lighthouse desktop attributed 29 s of main-thread time to the bundle and
+// scored /discover 47, against 81 for the same page measured with the bundle
+// absent.
+//
+// So the bundle is requested the first time a card that actually carries a GLB
+// comes within a screen of the viewport. Requesting it early relative to the
+// card keeps the upgrade invisible: the element is defined before the card is
+// close enough for its poster to matter, and `loading="lazy"` on the viewer
+// still decides when the GLB itself is fetched. The loader is shared, so
+// concurrent calls collapse into one request, and it carries the CDN failover
+// chain the hardcoded script tag never had.
+let viewerBundleRequested = false;
+function requestViewerBundle() {
+ if (viewerBundleRequested) return;
+ viewerBundleRequested = true;
+ ensureModelViewerOrFallback(els.grid);
+}
+const viewerLoadObserver =
+ 'IntersectionObserver' in window
+ ? new IntersectionObserver(
+ (entries) => {
+ for (const entry of entries) {
+ if (!entry.isIntersecting) continue;
+ viewerLoadObserver.unobserve(entry.target);
+ requestViewerBundle();
+ }
+ },
+ { rootMargin: '100% 0px' },
+ )
+ : null;
+function observeViewerLoads() {
+ // No IntersectionObserver: there is no way to tell which cards are near, so
+ // the first 3D card on the page is enough to justify the bundle.
+ if (!viewerLoadObserver) {
+ if (els.grid.querySelector(MV_SEL)) requestViewerBundle();
+ return;
+ }
+ if (viewerBundleRequested) return;
+ for (const mv of els.grid.querySelectorAll(MV_SEL)) {
+ if (mv.dataset.bundleObserved === '1') continue;
+ mv.dataset.bundleObserved = '1';
+ viewerLoadObserver.observe(mv);
+ }
+}
+
// Delegated copy-URI click
els.grid.addEventListener('click', (e) => {
const btn = e.target.closest('[data-role="card-copy-uri"]');
@@ -405,6 +456,7 @@ async function loadPage() {
els.grid.appendChild(renderCard(item));
}
observeCardTurns();
+ observeViewerLoads();
state.cursor = data.nextCursor;
els.loadMore.hidden = !state.cursor;
diff --git a/public/discover/index.html b/public/discover/index.html
index 7f7441b8f..2d8d1d73e 100644
--- a/public/discover/index.html
+++ b/public/discover/index.html
@@ -33,15 +33,34 @@
<link rel="stylesheet" href="/style.css" />
<link rel="stylesheet" href="/nav.css" />
<link rel="stylesheet" href="/fonts/fonts.css" />
- <!-- Deferred, and placed BEFORE the model-viewer module: defer scripts and
- module scripts execute in document order, so the meshopt shim still
- registers its decoder before model-viewer's define runs. -->
+ <!-- The meshopt decoder shim stays eager. It is a 2 KB classic script that
+ intercepts customElements.define(), so it wins the race against the
+ element bundle no matter when that bundle arrives, and every
+ server-baked GLB needs its decoder registered before the first load
+ starts. -->
<script src="/model-viewer-meshopt.js" defer></script>
- <script
- type="module"
- src="https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js" integrity="sha384-sr9b4Ux0WhAUGclJ0ym0FSY2zSOMmNSn0bP/SA0e6bNCrpn/5W3QL8mm+LdlQMKw" crossorigin="anonymous"
- ></script>
+ <!-- The <model-viewer> element bundle is NOT loaded here. It is 253 KB of
+ module JavaScript that builds a WebGL renderer on the main thread, and
+ most of this directory renders static R2 thumbnails: an entire page of
+ results can go by without one 3D card. Loading it on every visit cost
+ /discover its interactivity. Lighthouse desktop attributed 29 s of
+ main-thread time to it and scored the page 47, against 81 for the same
+ page measured without it. discover.js now asks
+ src/shared/model-viewer-loader.js for the element the moment a card
+ that actually has a GLB comes near the viewport, which also brings the
+ CDN failover chain this hardcoded tag never had. -->
<style>
+ /* Until the element bundle upgrades the tag, `model-viewer` is an unknown
+ inline element. Keep its box exactly the size the upgraded viewer will
+ occupy (the thumb is already aspect-ratio locked, so nothing shifts)
+ and fill it with the same surface tone the card uses, so a 3D card
+ reads as a loading tile rather than a hole. */
+ .explore-card-thumb model-viewer.explore-card-mv:not(:defined) {
+ display: block;
+ width: 100%;
+ height: 100%;
+ background: rgba(255, 255, 255, 0.03);
+ }
.explore-card-thumb model-viewer.explore-card-mv {
width: 100%;
height: 100%;
diff --git a/public/nav.js b/public/nav.js
index 9423767a2..864fe4df9 100644
--- a/public/nav.js
+++ b/public/nav.js
@@ -842,6 +842,26 @@ const WALK_AUTO_KEY = 'walk:companion:auto';
const WALK_AUTO_SKIP =
/^\/(play|walk|club|tour|world|scan|arena|pose|splat|capture|timeline)(\/|$)|^\/create\/(selfie|video)/;
+// How long the main thread has to stay clear of long tasks before the companion
+// is allowed to boot, and how long we keep waiting for that to happen.
+//
+// Summoning the companion means loading Three.js, an avatar GLB, the shared
+// clip library and a WebGL render loop. On a page that is still executing its
+// own long tasks that work does not run instead of the page's, it runs on top
+// of it, and both get slower: the companion took 3.4 s of /forge's total
+// blocking time and the page scored 43, against 71 for the same page measured
+// with the companion off. The old schedule made that collision the normal case,
+// because `requestIdleCallback(..., { timeout: 4000 })` fires the callback
+// whether or not the thread ever went idle.
+//
+// So wait for real quiet instead of a deadline. If the page never gets quiet
+// the companion simply is not summoned on it: the visitor's choice is still
+// unrecorded, so the next page they open (or the nav's Walk button) summons it
+// then. The feature's promise is that their agent shows up on its own, not that
+// it shows up while the page is still loading.
+const WALK_AUTO_QUIET_MS = 1200;
+const WALK_AUTO_GIVE_UP_MS = 20_000;
+
function initCompanionAutoStart() {
// Every check lives inside the deferred callback: boot() can run while this
// script is still evaluating (late injection), and the WALK_ENABLED_KEY
@@ -865,10 +885,53 @@ function initCompanionAutoStart() {
ensureWalkCompanion();
window.dispatchEvent(new CustomEvent('walk-companion:change'));
};
- const idle = () =>
- 'requestIdleCallback' in window ? requestIdleCallback(summon, { timeout: 4000 }) : setTimeout(summon, 1500);
- if (document.readyState === 'complete') setTimeout(idle, 2000);
- else window.addEventListener('load', () => setTimeout(idle, 2000), { once: true });
+
+ // Resolve once no `longtask` entry has been observed for WALK_AUTO_QUIET_MS,
+ // or reject by resolving false once WALK_AUTO_GIVE_UP_MS has passed. A
+ // browser without the longtask entry type (Safari) has no way to tell busy
+ // from idle, so it keeps the previous behaviour: one deferred idle callback.
+ const whenQuiet = (onQuiet) => {
+ const Observer = window.PerformanceObserver;
+ const types = (Observer && Observer.supportedEntryTypes) || [];
+ if (!Observer || types.indexOf('longtask') === -1) {
+ setTimeout(onQuiet, WALK_AUTO_QUIET_MS);
+ return;
+ }
+ let quietTimer = 0;
+ let giveUpTimer = 0;
+ let observer = null;
+ const stop = () => {
+ clearTimeout(quietTimer);
+ clearTimeout(giveUpTimer);
+ if (observer) observer.disconnect();
+ };
+ const armQuiet = () => {
+ clearTimeout(quietTimer);
+ quietTimer = setTimeout(() => {
+ stop();
+ onQuiet();
+ }, WALK_AUTO_QUIET_MS);
+ };
+ try {
+ observer = new Observer(armQuiet);
+ observer.observe({ type: 'longtask', buffered: true });
+ } catch (_) {
+ // Observing longtask can throw on browsers that list the type but do
+ // not implement it. Fall back to the timer rather than never booting.
+ setTimeout(onQuiet, WALK_AUTO_QUIET_MS);
+ return;
+ }
+ giveUpTimer = setTimeout(stop, WALK_AUTO_GIVE_UP_MS);
+ armQuiet();
+ };
+
+ const start = () =>
+ whenQuiet(() => {
+ if ('requestIdleCallback' in window) requestIdleCallback(summon, { timeout: 4000 });
+ else summon();
+ });
+ if (document.readyState === 'complete') start();
+ else window.addEventListener('load', start, { once: true });
}
function initWalkToggle(root) {
diff --git a/src/home-live-agents.js b/src/home-live-agents.js
index e9c41f20e..55889c142 100644
--- a/src/home-live-agents.js
+++ b/src/home-live-agents.js
@@ -71,19 +71,45 @@
if (!glb) throw new Error('no model url');
return glb;
}
+ // How large a GLB the hero is allowed to be. The hero avatar is fetched,
+ // parsed and uploaded to the GPU while the page is still trying to become
+ // interactive, so its file size is a first-order performance decision rather
+ // than a detail of whichever avatar happens to be curated first. The featured
+ // list mixes 90 KB props with a 10.7 MB scan, and taking its first entry put
+ // a 4.6 MB model on the critical path of every homepage visit: Lighthouse
+ // desktop measured 29.7 s of total blocking time, against 9.6 s for the same
+ // page with the GLB withheld. Two megabytes still buys a rigged, textured,
+ // animated humanoid; it does not buy a raw photogrammetry capture.
+ const HERO_GLB_BUDGET_BYTES = 2_500_000;
+
// The curated hero avatar can disappear (deleted, or a fresh deploy whose
// DB row hasn't been seeded yet) — fall back to a real featured avatar so
// the stage is never just an error card.
async function resolveFeaturedGlb() {
- // Preferred: a curated featured avatar via the detail endpoint (richest
- // metadata). Wrapped so a flaky/unavailable detail route never strands
- // the hero — we drop to the explore pool below instead.
+ // Preferred: a curated featured avatar. /api/avatars/featured reports each
+ // candidate's size_bytes, so the pick is made from that one response and
+ // only the winner's detail record is fetched. Within the budget we take
+ // the LARGEST candidate (the richest model the page can afford), and if
+ // nothing fits we take the smallest, because an over-budget hero that
+ // renders beats an empty stage. Wrapped so a flaky/unavailable route never
+ // strands the hero: we drop to the explore pool below instead.
try {
const r = await fetch(`${location.origin}/api/avatars/featured?limit=12`);
if (r.ok) {
const d = await r.json();
const list = Array.isArray(d.avatars) ? d.avatars : [];
- for (const a of list) {
+ const sized = list.filter((a) => Number(a.size_bytes) > 0);
+ let ordered = list;
+ if (sized.length) {
+ const affordable = sized.filter((a) => Number(a.size_bytes) <= HERO_GLB_BUDGET_BYTES);
+ // Candidates the API reported no size for keep their curated order
+ // at the back: unknown weight is worth trying, just not first.
+ ordered = affordable.length
+ ? affordable.slice().sort((a, b) => Number(b.size_bytes) - Number(a.size_bytes))
+ : sized.slice().sort((a, b) => Number(a.size_bytes) - Number(b.size_bytes));
+ ordered = ordered.concat(list.filter((a) => !ordered.includes(a)));
+ }
+ for (const a of ordered) {
try { return await fetchAvatarGlb(a.id); } catch (_) { /* try next */ }
}
}
diff --git a/src/shared/attended-rotation.js b/src/shared/attended-rotation.js
index cdb140696..44b32630d 100644
--- a/src/shared/attended-rotation.js
+++ b/src/shared/attended-rotation.js
@@ -22,6 +22,16 @@
//
// Only elements authored with `auto-rotate` are touched, so marking a viewer is
// opt-in and reversible.
+//
+// A `data-src` viewer also defers the <model-viewer> ELEMENT BUNDLE, not just
+// its model: a page whose only viewer is a decorative card has no reason to
+// build a WebGL renderer during load. First attention asks
+// model-viewer-loader.js for the element and sets `src` in the same breath, so
+// the bundle and the GLB arrive together and the card upgrades once. The loader
+// is shared and idempotent, so on a page that already loaded the element this
+// resolves without a request.
+
+import { ensureModelViewerOrFallback } from './model-viewer-loader.js';
// Long enough to read as a deliberate turn (a 20deg/s viewer sweeps ~240
// degrees), short enough that an unattended tab stops working.
@@ -54,10 +64,30 @@ export function attendRotation(el, { settleMs = DEFAULT_SETTLE_MS, attention = n
if (el.dataset.attendedRotateBound === '1') return noop;
el.dataset.attendedRotateBound = '1';
+ // A viewer can also defer its model until someone engages with it: author it
+ // with `data-src` instead of `src` and give it a poster. Decoding a GLB is
+ // one long, unbreakable main-thread task (852 ms for /create's 748 KB base
+ // avatar), so a card that may never be looked at should not spend it during
+ // page load. The poster shows the finished frame either way.
+ const promoteSource = () => {
+ if (!el.dataset.src || el.getAttribute('src')) return;
+ el.setAttribute('src', el.dataset.src);
+ delete el.dataset.src;
+ // The attribute is read when the element upgrades, so ordering is free:
+ // whether the bundle is already here or still in flight, this viewer ends
+ // up loading exactly the model it was authored with. On failure the loader
+ // swaps in the poster, which is the frame this card was showing anyway.
+ ensureModelViewerOrFallback(el.parentNode || document);
+ };
+
// Reduced motion: never spin. The model still renders, poses, and answers
- // camera controls; it just does not move on its own.
+ // camera controls; it just does not move on its own. That promise was only
+ // half true for a `data-src` viewer: nothing ever promoted its source, so a
+ // visitor who asks for reduced motion got a poster and no model, for good.
+ // Load it here instead: a still model is the whole point of the setting.
if (prefersReducedMotion()) {
el.removeAttribute('auto-rotate');
+ promoteSource();
return noop;
}
@@ -82,16 +112,6 @@ export function attendRotation(el, { settleMs = DEFAULT_SETTLE_MS, attention = n
if (settleMs > 0) timer = setTimeout(() => { settled = true; apply(); }, settleMs);
apply();
};
- // A viewer can also defer its model until someone engages with it: author it
- // with `data-src` instead of `src` and give it a poster. Decoding a GLB is
- // one long, unbreakable main-thread task (852 ms for /create's 748 KB base
- // avatar), so a card that may never be looked at should not spend it during
- // page load. The poster shows the finished frame either way.
- const promoteSource = () => {
- if (!el.dataset.src || el.getAttribute('src')) return;
- el.setAttribute('src', el.dataset.src);
- delete el.dataset.src;
- };
const attend = () => { attended = true; promoteSource(); arm(); };
const release = (e) => {
if (e?.relatedTarget && (attention || el).contains(e.relatedTarget)) return;