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(play): world entry in seconds instead of minutes, and a boot that can never strand the loader
nirholas995e116928aa
diff --git a/pages/play.html b/pages/play.htmlindex d145922d8..cc5ef7670 100644--- a/pages/play.html+++ b/pages/play.html@@ -68,6 +68,87 @@<canvas id="kx-canvas"></canvas>+ <script>+ /* Boot watchdog: inline on purpose so it works even when the app bundle+ itself is what failed (the classic stale-chunk 404 right after a deploy).+ While the #kx-loading card is still up, a failed script/stylesheet load,+ an uncaught boot error, or 45s of silence replaces the spinner with a+ real error card (mirroring renderBootError's markup) instead of leaving+ the loader sweeping forever with no recovery path. Once boot completes+ (the app adds .kx-hidden or removes the node) the watchdog disarms. */+ (function () {+ var fired = false;+ function bootPending() {+ var l = document.getElementById('kx-loading');+ return l && !l.classList.contains('kx-hidden') && !l.querySelector('.kx-boot-error');+ }+ function fail(title, body) {+ if (fired || !bootPending()) return;+ fired = true;+ var l = document.getElementById('kx-loading');+ var card = document.createElement('div');+ card.className = 'kx-loading-card kx-boot-error';+ card.setAttribute('role', 'alert');+ /* Inline fallback styling: if the stylesheet is what 404ed, the card+ must still be readable. */+ card.style.cssText = 'max-width:420px;padding:28px;text-align:center;color:#eee;font-family:system-ui,sans-serif;';+ var mark = document.createElement('div');+ mark.className = 'kx-loading-mark';+ mark.textContent = title;+ mark.style.cssText = 'font-weight:700;letter-spacing:.08em;margin-bottom:10px;';+ var msg = document.createElement('p');+ msg.className = 'kx-boot-error-msg';+ msg.textContent = body;+ msg.style.cssText = 'opacity:.8;font-size:14px;line-height:1.5;margin:0 0 18px;';+ var actions = document.createElement('div');+ actions.className = 'kx-boot-error-actions';+ var retry = document.createElement('button');+ retry.type = 'button';+ retry.className = 'kx-boot-error-btn';+ retry.textContent = 'Try again';+ retry.style.cssText = 'padding:10px 22px;border-radius:8px;border:1px solid #555;background:#191a1c;color:#fff;cursor:pointer;font-size:14px;';+ retry.addEventListener('click', function () {+ /* Hard reload: a stale cached HTML referencing dead chunks needs a+ revalidated document, not a memory-cache replay. */+ location.reload();+ });+ var home = document.createElement('a');+ home.className = 'kx-boot-error-link';+ home.href = '/';+ home.textContent = 'Back to three.ws';+ home.style.cssText = 'display:inline-block;margin-left:14px;color:#9ab;font-size:14px;';+ actions.appendChild(retry);+ actions.appendChild(home);+ card.appendChild(mark);+ card.appendChild(msg);+ card.appendChild(actions);+ l.replaceChildren(card);+ retry.focus();+ }+ /* A failed script/stylesheet is unambiguously boot-fatal: fail now.+ Runtime errors and unhandled rejections can also come from benign+ background work racing the boot, so they only arm a short grace+ timer; if boot completes first, bootPending() disarms the card. */+ function failSoon(title, body) {+ setTimeout(function () { fail(title, body); }, 8000);+ }+ window.addEventListener('error', function (e) {+ var t = e && e.target;+ if (t && (t.tagName === 'SCRIPT' || t.tagName === 'LINK')) {+ fail('Couldn’t load the world', 'A file failed to load. This usually fixes itself on a reload; the site may have just been updated.');+ } else if (e && (e.error || e.message)) {+ failSoon('Couldn’t load the world', 'Something went wrong while starting Coin Communities. Reload to try again.');+ }+ }, true);+ window.addEventListener('unhandledrejection', function () {+ failSoon('Couldn’t load the world', 'Something went wrong while starting Coin Communities. Reload to try again.');+ });+ setTimeout(function () {+ fail('Taking too long to load', 'The world hasn’t finished loading. Check your connection and try again.');+ }, 45000);+ })();+ </script>+<script type="module" src="/src/game/boot-avatar.js"></script><script type="module" src="/src/game/coincommunities.js"></script><script type="module" src="/src/game/ambient-crowd.js"></script>diff --git a/src/animation-manager.js b/src/animation-manager.jsindex 7e0193bb0..fc65c580f 100644--- a/src/animation-manager.js+++ b/src/animation-manager.js@@ -117,6 +117,16 @@ const LOWER_BODY_CANONICAL = Object.freeze([const DEFAULT_CROSSFADE = 0.35; // seconds+// Module-level cache of parsed base clips, keyed by URL. A world scene builds+// dozens of AnimationManagers (local player, remote players, NPCs, pedestrians)+// and every one of them used to re-fetch and re-parse the same clip JSON:+// megabytes of JSON and thousands of AnimationClip.parse calls per world entry.+// The base clip is never mutated (_retarget reads it and emits a new bound+// clip), so one parsed instance can back every rig. The cache stores the+// in-flight promise so concurrent loaders coalesce into a single fetch; a+// failed load is evicted so a retry can succeed.+const _clipCache = new Map();+export class AnimationManager {constructor() {/** @type {THREE.Object3D|null} */@@ -501,6 +511,20 @@ export class AnimationManager {async loadAnimation(name, url, opts = {}) {if (this.clips.has(name)) return this.clips.get(name);+ let pending = _clipCache.get(url);+ if (!pending) {+ pending = AnimationManager._fetchClip(name, url);+ _clipCache.set(url, pending);+ // Evict on failure so a transient network error doesn't poison the URL+ // for every future rig in the session.+ pending.catch(() => { if (_clipCache.get(url) === pending) _clipCache.delete(url); });+ }+ const clip = await pending;+ return this._registerParsedClip(name, clip, opts);+ }++ /** @private Fetch + parse one clip JSON into a shared base AnimationClip. */+ static async _fetchClip(name, url) {const isApiClip = url.includes('/api/animations/');const controller = new AbortController();const timeoutId = setTimeout(() => controller.abort(), 15_000);@@ -509,8 +533,8 @@ export class AnimationManager {res = await fetch(url, {signal: controller.signal,// API clips need auth; static clips are same-origin assets. Use- // 'same-origin' (not 'omit') so a credential-gated host proxy — e.g.- // a private-forwarded Codespaces port — still receives the auth cookie+ // 'same-origin' (not 'omit') so a credential-gated host proxy (e.g.+ // a private-forwarded Codespaces port) still receives the auth cookie// and serves the asset instead of 302-ing it to a login tunnel.credentials: isApiClip ? 'include' : 'same-origin',redirect: 'error',@@ -525,8 +549,7 @@ export class AnimationManager {if (!clipJson) throw new Error(`clip payload missing from ${url}`);const clip = AnimationClip.parse(clipJson);clip.name = name;-- return this._registerParsedClip(name, clip, opts);+ return clip;}/**diff --git a/src/game/agent-commerce.js b/src/game/agent-commerce.jsindex c5dbddd28..3ce021f00 100644--- a/src/game/agent-commerce.js+++ b/src/game/agent-commerce.js@@ -124,8 +124,10 @@ class Agent {this.bubble = null;this._bubbleTimer = null;+ // Locomotion clips only: _gesture() loads any named clip on demand from the+ // manifest, so the agents don't need the full library up front.resolveAvatarUrl(avatar)- .then((u) => buildAvatar(this.rig, u, this.anim))+ .then((u) => buildAvatar(this.rig, u, this.anim, { clips: 'locomotion' })).then(({ height }) => { if (!this._disposed) this.height = height; }).catch(() => {});}diff --git a/src/game/avatar-thumb.js b/src/game/avatar-thumb.jsindex 253076bb0..7e915172d 100644--- a/src/game/avatar-thumb.js+++ b/src/game/avatar-thumb.js@@ -43,7 +43,10 @@ function ensureRenderer() {_renderer.setPixelRatio(1); // fixed thumbnail resolution, independent of quality tier_renderer.setSize(SIZE, SIZE, false);_scene = new Scene();- loadEnvironment(_renderer, _scene, 'studio');+ // Procedural room environment, same call boot-avatar makes and for the+ // same reason: a 160px thumbnail cannot justify a 1.5MB studio HDRI+ // download racing the lobby's avatar GLBs for bandwidth.+ loadEnvironment(_renderer, _scene, null);_scene.add(new HemisphereLight(0xffffff, 0x404a5a, 1.15));const key = new DirectionalLight(0xffffff, 1.7);key.position.set(1.6, 2.4, 2.0);@@ -58,12 +61,24 @@ function ensureRenderer() {}}+// Snapshots share ONE offscreen scene (_scene), so they must run one at a+// time: the lobby fires 7 preset chips concurrently, and overlapping renders+// used to composite each other's avatars into the same PNG. A promise chain+// serializes them; each caller still gets its own result promise.+let _queue = Promise.resolve();+function enqueueSnapshot(url) {+ const run = _queue.then(() => _snapshot(url));+ // The queue itself must never reject or every later thumbnail dies with it.+ _queue = run.catch(() => {});+ return run;+}+// Render `url` to a PNG portrait data URL. Cached per URL (including the null// failure case) so repeated picker renders never re-load or re-render a model.export function renderAvatarThumb(url) {if (!url) return Promise.resolve(null);if (_cache.has(url)) return _cache.get(url);- const p = _snapshot(url).catch((err) => {+ const p = enqueueSnapshot(url).catch((err) => {log.warn('[avatar-thumb] preview failed:', url, err?.message);return null;});diff --git a/src/game/chart-screen.js b/src/game/chart-screen.jsindex 98bb9a802..06dabb216 100644--- a/src/game/chart-screen.js+++ b/src/game/chart-screen.js@@ -245,6 +245,14 @@ export function createChartScreen(scene, coin, opts = {}) {function poll() {if (destroyed) return;clearTimeout(pollTimer);+ // A hidden tab keeps its world alive but doesn't need a live tape: skip+ // the fetch and check back at the normal cadence. At event scale this is+ // the difference between N tabs and N*background-tabs of /api/pump/trades+ // traffic hitting the proxy.+ if (typeof document !== 'undefined' && document.hidden) {+ pollTimer = setTimeout(poll, POLL_MS);+ return;+ }fetchTrades().finally(() => {if (destroyed) return;pollTimer = setTimeout(poll, POLL_MS);diff --git a/src/game/coincommunities.js b/src/game/coincommunities.jsindex 75614ba43..1feb87f29 100644--- a/src/game/coincommunities.js+++ b/src/game/coincommunities.js@@ -244,7 +244,11 @@ class RemotePlayer {// lands on a cleared/removed rig (orphaned mesh, or two models at once).const token = (this._avatarToken = (this._avatarToken || 0) + 1);const anim = this.anim;- resolveAvatarUrl(url).then((u) => buildAvatar(this.rig, u, anim).then(({ height }) => {+ // Locomotion clips only: a room of peers must not each download the whole+ // emote library at join. Emotes still lazy-load on first use (playEmoteClip+ // fetches a missing clip on demand), and the parsed-clip cache makes the+ // idle/walk pair free after the first rig.+ resolveAvatarUrl(url).then((u) => buildAvatar(this.rig, u, anim, { clips: 'locomotion' }).then(({ height }) => {if (this._disposed || token !== this._avatarToken) return;this.height = height;anim.crossfadeTo(this.motion === 'walk' || this.motion === 'run' ? CLIP_WALK : CLIP_IDLE, 0);@@ -980,10 +984,16 @@ export class CoinCommunities {// ---------------------------------------------------------------- enter/leaveasync enter(coin, opts = {}) {if (this.phase !== 'lobby') return;+ // Claim the phase before the first await: a double-click on a coin card+ // used to start two concurrent enter() flows (both reads of 'lobby' passed+ // while the gate await was in flight), and the losing flow leaked its+ // meshes and chart poller into the scene. The gate/holder paths below+ // restore 'lobby' on cancel so the lobby stays usable.+ this.phase = 'loading';// Clear the platform sign-in gate before anything else. Resolves instantly// when /play is open (no token pinned) or when we already hold a fresh pass.if (this._playReady) { try { await this._playReady; } catch { /* gate self-heals */ } }- if (this.phase !== 'lobby') return; // backed out / re-entered while the gate was up+ if (this.phase !== 'loading') return; // torn down while the gate was upconst tier = opts.tier === 'holders' ? 'holders' : 'general';// Entry does several awaits (gate, manifest, avatar GLB, room connect) and// the Leave button goes live the moment the HUD shows — well before connect@@ -1001,13 +1011,13 @@ export class CoinCommunities {let holderMinTokens = 0;if (tier === 'holders') {const pass = await this._passHolderGate(coin);- if (!pass) return;+ if (!pass) { if (this.phase === 'loading') this.phase = 'lobby'; return; }holderPass = pass.holderPass;holderMinUsd = pass.minUsd;holderMinTokens = pass.minTokens || 0;+ if (this.phase !== 'loading') return; // torn down while the gate was up}- this.phase = 'loading';// A bare deep link (/play?coin=<home mint>) carries no name/art; backfill the// flagship town's identity so its totem, jumbotron, and HUD are never blank.if (isHomeTown(coin.mint)) {@@ -1131,22 +1141,12 @@ export class CoinCommunities {// otherwise use whatever they selected in the lobby (preset / paste / upload).const avatarInput = this._urlAvatar || this.ui.getAvatar();const url = await resolveAvatarUrl(avatarInput);- const { height: localHeight, fallback: avatarFallback } = await buildAvatar(this.localRig, url, this.localAnim);- // Backed out while the avatar GLB was loading — stop before we open a room.+ // Kick off the local avatar build (GLB + locomotion clips only; emotes+ // lazy-load on first use via playEmoteClip) WITHOUT awaiting it here. The+ // room join below runs concurrently, so a slow avatar download no longer+ // serializes ahead of the socket and delays the player's entry for everyone.if (epoch !== this._enterEpoch) return;- this.localHeight = localHeight;- // Dress the local avatar in the loadout the player last equipped (carried- // across sessions and worlds via the cc-cosmetics mirror). The server echoes- // the authoritative, ownership-validated loadout right after join — which- // re-applies here through _onCosmeticsProfile — but applying the cached wire- // now means the player sees their fit immediately, not a flash of bare avatar.- this._localCosWire = null;- this._applyLocalCosmetics(getPlayCosmetics());- // Don't silently swap a broken model for the stand-in — tell the player so- // they know to pick another avatar.- if (avatarFallback && avatarInput !== GUEST_SENTINEL) {- this.ui.toast('Couldn’t load that avatar — using a stand-in. Try another in the lobby.', 'warn');- }+ const avatarBuild = buildAvatar(this.localRig, url, this.localAnim, { clips: 'locomotion' });// Connect to this coin's room. A locally-staged guest avatar (just created,// not yet uploaded) can't be loaded by peers, so we join without one and@@ -1209,8 +1209,8 @@ export class CoinCommunities {this.net.on('synced', () => this._onRoomSynced());if (isGuest) uploadPendingGuestAvatar((publicUrl) => this.net?.setAvatar(publicUrl));- this.net.on('status', ({ status }) => {- this.ui.setStatus(status);+ this.net.on('status', ({ status, error }) => {+ this.ui.setStatus(status, error);this._updateOnline();// Reconnect exhausted: the player is now alone in a local-only world.// The small status pill alone is easy to miss, so explain the drop once —@@ -1353,11 +1353,33 @@ export class CoinCommunities {});this.buildHud.root.hidden = false;- await this.net.connect();- // Player backed out mid-connect: leave() already tore everything down and+ // Join the room and finish the local avatar in parallel. These used to run+ // serialized (avatar, then connect), which held the whole world entry on+ // "connecting" for the length of the avatar download; neither depends on+ // the other, so they overlap now and entry is gated on the slower of the+ // two, not the sum.+ const connectP = this.net.connect();+ const { height: localHeight, fallback: avatarFallback } = await avatarBuild;+ // Player backed out mid-load: leave() already tore everything down and// nulled this.net. Bail rather than dereference it / re-enter 'world'.if (epoch !== this._enterEpoch || !this.net) return;- this._initVoice();+ this.localHeight = localHeight;+ // Dress the local avatar in the loadout the player last equipped (carried+ // across sessions and worlds via the cc-cosmetics mirror). The server echoes+ // the authoritative, ownership-validated loadout right after join, which+ // re-applies through _onCosmeticsProfile; applying the cached wire now means+ // the player sees their fit immediately, not a flash of bare avatar.+ this._localCosWire = null;+ this._applyLocalCosmetics(getPlayCosmetics());+ // Don't silently swap a broken model for the stand-in: tell the player so+ // they know to pick another avatar.+ if (avatarFallback && avatarInput !== GUEST_SENTINEL) {+ this.ui.toast('Couldn’t load that avatar, so a stand-in is filling in. Try another in the lobby.', 'warn');+ }+ // The world is playable the moment the avatar stands. Don't freeze movement+ // behind the join handshake (up to 15s on a cold multiplayer instance):+ // everything below that touches the net only *subscribes*, so it works+ // while the join is still in flight, and the status pill narrates it.this.phase = 'world';this._initJoystick();this._restoreZen();@@ -1369,9 +1391,9 @@ export class CoinCommunities {// away instead of waiting on it itself. Torn down in leave().this.vehicles = new VehicleManager({ host: this });// W07: roaming PvE mobs, lootable tombstones, the danger-zone ground, and- // the GTA-style vitals HUD (health/armor/wanted). Built after the connect- // above so its net.on(...) subscriptions catch the join-time 'profile'- // re-send below. Torn down in leave().+ // the GTA-style vitals HUD (health/armor/wanted). Subscribed before the+ // join settles, so it catches the join-time 'profile' send directly; the+ // re-request after the join below stays as a backstop. Torn down in leave().// Defensive boundary: W07 is still under active concurrent development in// this shared worktree (CLAUDE.md "known traps") — a bug in it must never// take down the rest of world entry (NPCs, vehicles, economy) for every@@ -1389,9 +1411,6 @@ export class CoinCommunities {log.error('[coincommunities] CombatSystem failed to init — continuing without it:', e?.message);this.combat = null;}- // playSystems already cached a 'profile' snapshot before combat subscribed;- // re-request so the vitals HUD isn't blank until the next server-side change.- this.net.requestProfile();// The legacy gold purse HUD folds into WorldHud's unified money readout.this.playSystems?.setGoldVisible(false);// Every town hosts the live Agent Exchange: two NPC agents who pay each@@ -1470,6 +1489,16 @@ export class CoinCommunities {},radius: WORLD_RADIUS - 4,});+ // Everything visual is up; now settle the join. Voice needs the live+ // sessionId, and the profile re-request needs an open socket (it is a+ // silent no-op otherwise), so both wait for the connect started above.+ await connectP;+ if (epoch !== this._enterEpoch || !this.net) return;+ this._initVoice();+ // playSystems and combat cached a 'profile' snapshot at join; re-request so+ // the vitals HUD is current even if that send raced their subscriptions.+ this.net.requestProfile();+// Start the silent pass-refresh cycle. The play pass has a 10-min server// TTL; the server sweeps expired passes every minute. We refresh 2 min early// so a player in a long session is never evicted mid-build. The refreshdiff --git a/src/game/npc/ambient-life.js b/src/game/npc/ambient-life.jsindex 231305bf2..3b8267ee7 100644--- a/src/game/npc/ambient-life.js+++ b/src/game/npc/ambient-life.js@@ -61,7 +61,9 @@ class Pedestrian {this.bubble = null;this._bubbleTimer = null;- buildAvatar(this.rig, avatarUrl || DEFAULT_AVATAR, this.anim)+ // Locomotion clips only: pedestrians never emote, and each one with its own+ // AnimationManager would otherwise fetch the entire clip library.+ buildAvatar(this.rig, avatarUrl || DEFAULT_AVATAR, this.anim, { clips: 'locomotion' }).then(({ height }) => {if (this._disposed) return;this.height = height;diff --git a/src/game/npc/npc.js b/src/game/npc/npc.jsindex a9eb95914..a8be8ad57 100644--- a/src/game/npc/npc.js+++ b/src/game/npc/npc.js@@ -60,8 +60,10 @@ export class Npc {this.bubble = null;this._bubbleTimer = null;+ // Locomotion clips only: ~21 NPCs per world must not each pull the whole+ // emote library. emote() below lazy-loads any clip on demand.resolveAvatarUrl(def.avatar)- .then((u) => buildAvatar(this.rig, u, this.anim))+ .then((u) => buildAvatar(this.rig, u, this.anim, { clips: 'locomotion' })).then(({ height }) => { if (!this._disposed) this.height = height; }).catch(() => {});}diff --git a/src/game/play-auth.js b/src/game/play-auth.jsindex 1066d4746..0bba82dcb 100644--- a/src/game/play-auth.js+++ b/src/game/play-auth.js@@ -15,10 +15,18 @@// pass's lifetime doesn't re-prompt the wallet. All on-chain truth is computed// server-side; this module only orchestrates the wallet interaction.-// Side-effect import: on a Solana Mobile (Seeker/Saga) device running inside our-// TWA, this installs an MWA-backed wallet at window.solana that signs through the-// Seed Vault. A no-op on every other platform.-import '../../solana-mobile/src/index.js';+// On a Solana Mobile (Seeker/Saga) device running inside our TWA, install an+// MWA-backed wallet at window.solana that signs through the Seed Vault. The+// detector is a tiny dependency-free check; the actual boot module (which+// statically pulls @solana/web3.js, ~716KB pre-gzip) loads ONLY on that+// platform. A static side-effect import here used to put the whole Solana+// stack on /play's critical-path preloads for every desktop visitor.+import { isSolanaMobileTwa } from '../../solana-mobile/src/seeker-detect.js';+if (typeof window !== 'undefined' && isSolanaMobileTwa()) {+ import('../../solana-mobile/src/index.js').catch((err) => {+ console.error('[play-auth] Solana Mobile wallet boot failed:', err);+ });+}const NONCE_URL = '/api/play/nonce';const VERIFY_URL = '/api/play/verify';diff --git a/src/game/play-systems.js b/src/game/play-systems.jsindex 3fb7d8348..4f87c7625 100644--- a/src/game/play-systems.js+++ b/src/game/play-systems.js@@ -32,7 +32,6 @@ import { itemDisplay } from './items.js';import {COSMETICS, SLOTS, SLOT_LABELS, getCosmetic, DEFAULT_LOADOUT,} from '../../multiplayer/src/cosmetics-catalog.js';-import { buyBoutiqueItem } from './boutique-purchase.js';import './play-systems.css';// Rarity → display label + accent, shared by the inventory cards. Keeps the@@ -634,6 +633,11 @@ export class PlaySystems {settling: 'Confirming your unlock…',};try {+ // Lazy import: boutique-purchase drags in the whole Solana wallet stack+ // (~716KB pre-gzip via erc8004/solana-deploy), which no player needs+ // until the moment they actually buy. Keeping it off the static graph+ // keeps it out of /play's critical-path preloads.+ const { buyBoutiqueItem } = await import('./boutique-purchase.js');const res = await buyBoutiqueItem({net: this.net,item,diff --git a/src/game/x402-jumbotron.js b/src/game/x402-jumbotron.jsindex a5c6b38a8..df111bb73 100644--- a/src/game/x402-jumbotron.js+++ b/src/game/x402-jumbotron.js@@ -189,6 +189,11 @@ export function createX402Jumbotron(scene, opts = {}) {function poll() {if (destroyed) return;clearTimeout(pollTimer);+ // Hidden tab: skip the fetch, keep the cadence (see chart-screen.js).+ if (typeof document !== 'undefined' && document.hidden) {+ pollTimer = setTimeout(poll, POLL_MS);+ return;+ }fetchFeed().finally(() => {if (destroyed) return;pollTimer = setTimeout(poll, POLL_MS);