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
demo-economy(page): frame the scene on narrow viewports and offer a real retry
nirholasec115144c980
diff --git a/pages/demo-economy.html b/pages/demo-economy.htmlindex f04289f54..adc8ec22c 100644--- a/pages/demo-economy.html+++ b/pages/demo-economy.html@@ -103,6 +103,19 @@/* ── Canvas ── */#canvas-wrap { grid-area: canvas; position: relative; overflow: hidden; }#scene { width: 100%; height: 100%; display: block; }+ /* WebGL can be unavailable (old GPU, blocklisted driver, hardened browser).+ The narrated economy still runs in the sidebar, so say what is missing+ instead of leaving a black rectangle. */+ #scene-fallback {+ display: none;+ position: absolute; inset: 0;+ flex-direction: column; align-items: center; justify-content: center;+ gap: 8px; padding: 24px; text-align: center;+ background: radial-gradient(circle at 50% 40%, rgba(78,140,255,0.08), transparent 60%), #05070d;+ }+ #scene-fallback.show { display: flex; }+ #scene-fallback .sf-title { font-size: 15px; font-weight: 700; }+ #scene-fallback .sf-body { font-size: 12px; color: var(--muted); max-width: 42ch; line-height: 1.6; }/* ── Sidebar ── */#sidebar {@@ -142,6 +155,22 @@color: #f0a030; background: rgba(240,160,48,0.12); border: 1px solid rgba(240,160,48,0.28);}+ /* Run error: actionable, never a bare "see console" */+ #run-error { display: none; padding: 12px 14px; border-bottom: 1px solid rgba(255,99,99,0.28); background: rgba(255,99,99,0.06); }+ #run-error.show { display: block; }+ #run-error .re-title { font-size: 12px; font-weight: 700; color: #ff8a8a; }+ #run-error .re-body { font-size: 11px; color: var(--muted); margin: 4px 0 9px; line-height: 1.5; }+ #retry-btn {+ display: inline-flex; align-items: center;+ padding: 6px 12px; border-radius: 8px; cursor: pointer;+ background: rgba(255,99,99,0.12); color: #ff8a8a;+ border: 1px solid rgba(255,99,99,0.35);+ font: 700 11px -apple-system,system-ui,sans-serif;+ transition: background .15s, border-color .15s;+ }+ #retry-btn:hover { background: rgba(255,99,99,0.2); border-color: rgba(255,99,99,0.55); }+ #retry-btn:focus-visible { outline: 2px solid #ff8a8a; outline-offset: 2px; }+/* Activity log */#steps-wrap { flex: 1; overflow-y: auto; }.step {@@ -182,6 +211,30 @@#sheet-toggle:hover { background: rgba(255,255,255,0.05); border-color: rgba(255,255,255,0.18); }#sheet-toggle:focus-visible { outline: 2px solid var(--nova); outline-offset: 2px; }+ /* Narrow viewports: the topbar carried five items and pushed "Run demo"+ off-screen at 320px, making the page's only action unreachable. Drop the+ decorative pieces (the agent pills repeat in the Wallets panel, the tech+ chips and mode line repeat in the Transaction panel) so the brand, the+ sheet toggle and the primary button always fit. */+ @media (max-width: 560px) {+ #topbar { padding: 0 10px; gap: 8px; }+ .pills { display: none; }+ .brand a { font-size: 14px; }+ .brand .page { font-size: 12px; }+ #run-btn { padding: 8px 12px; font-size: 12px; }+ #sheet-toggle { padding: 6px 10px; font-size: 11px; }+ #botbar { padding: 0 12px; gap: 8px; }+ #botbar .bot-sep, #botline, .chips { display: none; }+ #status { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+ }+ @media (max-width: 430px) {+ .brand .sep { display: none; }+ .brand .page {+ position: absolute; width: 1px; height: 1px;+ overflow: hidden; clip-path: inset(50%); white-space: nowrap;+ }+ }+@media (max-width: 680px) {#root { grid-template-columns: 1fr; grid-template-areas: "top" "canvas" "bot"; }/* The payment proof is the point of the demo — keep it reachable on@@ -213,7 +266,7 @@<div class="brand"><a href="/" data-i18n="demo_economy.three_ws">three.ws</a><span class="sep">/</span>- <span class="page" data-i18n="demo_economy.agent_economy">Agent Economy</span>+ <h1 class="page" data-i18n="demo_economy.agent_economy">Agent Economy</h1></div><div class="pills"><span class="pill nova" data-i18n-html="demo_economy.nova_payer"><span class="dot"></span>NOVA · payer</span>@@ -227,7 +280,13 @@<button id="run-btn" type="button" data-i18n-html="demo_economy.run_demo"><span id="run-label">Run demo</span></button></header>- <div id="canvas-wrap"><canvas id="scene"></canvas></div>+ <div id="canvas-wrap">+ <canvas id="scene" role="img" aria-label="3D scene: the agents NOVA and ORACLE either side of a screen that shows the x402 bazaar, the payment, and the delivered market briefing" data-i18n-attr="aria-label:demo_economy.scene_arialabel"></canvas>+ <div id="scene-fallback">+ <div class="sf-title" data-i18n="demo_economy.scene_unavailable">3D scene unavailable</div>+ <p class="sf-body" data-i18n="demo_economy.scene_unavailable_body">This browser could not start WebGL, so the world is not rendering. The demo still runs: press Run demo and follow the payment and the market briefing in the panel beside it.</p>+ </div>+ </div><aside id="sidebar"><div class="sb-block">@@ -261,13 +320,19 @@</div></div>+ <div id="run-error" role="alert">+ <div class="re-title" data-i18n="demo_economy.demo_could_not_run">Demo could not run</div>+ <p class="re-body" id="re-body"></p>+ <button id="retry-btn" type="button" data-i18n="demo_economy.retry">Retry</button>+ </div>+<div class="sb-label" style="padding:10px 14px 4px">Activity</div>- <div id="steps-wrap"><div id="steps"></div></div>+ <div id="steps-wrap"><div id="steps" role="log" aria-live="polite" aria-relevant="additions"></div></div></aside><footer id="botbar">- <span id="status" data-i18n="demo_economy.ready_click_run_demo">Ready — click Run demo</span>- <span style="color:var(--muted)">·</span>+ <span id="status" aria-live="polite" data-i18n="demo_economy.ready_click_run_demo">Ready. Click Run demo</span>+ <span class="bot-sep" style="color:var(--muted)">·</span><span id="botline" style="color:var(--muted)" data-i18n="demo_economy.real_solana_infrastructure_x402_protocol">Real Solana infrastructure · x402 protocol</span><div class="chips"><span class="chip" data-i18n="demo_economy.x402">x402</span>@@ -304,7 +369,12 @@ let world = null;try {world = createScene(canvas);} catch (err) {- console.error('Scene failed:', err);+ // WebGL unavailable or the context was refused. The narrated economy is the+ // substance of this page and it does not need the renderer, so surface the+ // missing piece and keep the run path working.+ document.getElementById('scene-fallback').classList.add('show');+ canvas.style.display = 'none';+ console.warn('3D scene unavailable:', err?.message || err);}// ── Utilities ──────────────────────────────────────────────────────────────@@ -330,6 +400,25 @@ function updateWallet(side, { name, address, balance_sol }) {if (balance_sol != null) balEl.textContent = balance_sol + ' SOL';}+// ── Error surface ──────────────────────────────────────────────────────────+// A run can fail for reasons the visitor can act on (offline, a blocked+// EventSource, an upstream blip), so name the cause and offer the retry rather+// than pointing at the developer console.+const errorCard = document.getElementById('run-error');+const errorBody = document.getElementById('re-body');+const retryBtn = document.getElementById('retry-btn');++function showError(message) {+ errorBody.textContent = message;+ errorCard.classList.add('show');+ openSheetOnMobile();+}++function clearError() {+ errorCard.classList.remove('show');+ errorBody.textContent = '';+}+// ── Demo runner ────────────────────────────────────────────────────────────let running = false;@@ -341,6 +430,7 @@ function runDemo() {runLabel.textContent = 'Running…';stepsEl.innerHTML = '';statusEl.textContent = 'Starting demo…';+ clearError();bazaarOk = true;botLineEl.textContent = 'Real Solana infrastructure · x402 protocol';@@ -352,13 +442,17 @@ function runDemo() {world?.nova?.setState('idle');world?.oracle?.setState('idle');world?.tv?.setPhase('idle');+ world?.tv?.setPayment(null);+ world?.tv?.setBriefing(null);world?.beam?.deactivate();const es = new EventSource('/api/demo-economy');let settled = false;+ let timeoutId = 0;function finish() {if (settled) return; settled = true;+ clearTimeout(timeoutId);es.close();runBtn.disabled = false;runBtn.querySelector('.spinner')?.remove();@@ -417,6 +511,7 @@ function runDemo() {} else {sigEl.innerHTML = `<span style="color:var(--muted)">no on-chain tx — simulated</span>`;}+ world?.tv?.setPayment(d);updateBotLine(d.simulated);openSheetOnMobile();});@@ -428,20 +523,39 @@ function runDemo() {});es.addEventListener('done', () => finish());++ // EventSource delivers BOTH a server-sent `error` event (which carries data)+ // and its own transport failure under the same event name, so branch on+ // whether a payload came with it.es.addEventListener('error', e => {- try { addStep('❌', 'Error', JSON.parse(e.data).message); } catch {}- statusEl.textContent = 'Error — see console';+ if (settled) return;+ let serverMessage = null;+ try { serverMessage = JSON.parse(e.data).message; } catch {}+ if (serverMessage) {+ addStep('⚠️', 'Run failed', serverMessage);+ statusEl.textContent = 'Run failed';+ showError(serverMessage + ' Nothing was paid. Retry when you are ready.');+ } else {+ statusEl.textContent = 'Connection lost';+ showError(navigator.onLine === false+ ? 'You appear to be offline. The demo streams live from three.ws, so reconnect and retry.'+ : 'The connection to the demo stream dropped before it finished. No payment was made. Retry to start a fresh run.');+ }finish();});- es.onerror = () => {- if (!settled) { statusEl.textContent = 'Connection lost'; finish(); }- };- // Hard timeout- setTimeout(finish, 35000);+ // Hard timeout: a stream that stalls mid-run leaves the button spinning+ // forever otherwise.+ timeoutId = setTimeout(() => {+ if (settled) return;+ statusEl.textContent = 'Run timed out';+ showError('The run did not finish within 35 seconds. No payment was made. Retry to start a fresh run.');+ finish();+ }, 35000);}runBtn.addEventListener('click', runDemo);+retryBtn.addEventListener('click', runDemo);// Mobile sheet — surface the payment proof instead of hiding it on small screens.const sheetToggle = document.getElementById('sheet-toggle');diff --git a/src/demo-economy.js b/src/demo-economy.jsindex 64e0d668e..c72ae5ad3 100644--- a/src/demo-economy.js+++ b/src/demo-economy.js@@ -21,7 +21,13 @@ const ORACLE_X = 3.8;export function createScene(canvas) {const renderer = new THREE.WebGLRenderer({ canvas, antialias: true, alpha: false });renderer.setPixelRatio(Math.min(devicePixelRatio, 2));- renderer.setSize(canvas.clientWidth, canvas.clientHeight);+ // `false` keeps three.js from writing inline px width/height onto the canvas.+ // With inline sizes the canvas stops obeying its `width:100%` CSS, so it can+ // never shrink again: the ResizeObserver below watches an element whose size+ // three.js just pinned, so it never fires and the scene stays clipped at its+ // widest observed size on every narrower viewport.+ const viewport = canvas.parentElement || canvas;+ renderer.setSize(viewport.clientWidth, viewport.clientHeight, false);renderer.toneMapping = THREE.ACESFilmicToneMapping;renderer.toneMappingExposure = 0.95;renderer.outputColorSpace = THREE.SRGBColorSpace;@@ -30,10 +36,21 @@ export function createScene(canvas) {scene.background = new THREE.Color(0x05070d);scene.fog = new THREE.FogExp2(0x05070d, 0.08);- const camera = new THREE.PerspectiveCamera(48, canvas.clientWidth / canvas.clientHeight, 0.1, 100);+ const camera = new THREE.PerspectiveCamera(48, viewport.clientWidth / viewport.clientHeight, 0.1, 100);camera.position.set(0, 2.8, 8);camera.lookAt(0, 1.2, 0);+ // NOVA and ORACLE stand 7.6 world units apart, so a portrait viewport frames+ // empty floor between two off-screen agents unless the camera pulls back.+ // Dolly by the horizontal shortfall instead of widening the FOV, which keeps+ // the perspective identical on phone and desktop.+ function frameCamera(aspect) {+ const halfV = Math.tan((camera.fov * Math.PI) / 360);+ const needed = 4.6 / Math.max(halfV * Math.max(aspect, 0.2), 0.001);+ camera.position.set(0, 2.8, Math.max(8, Math.min(needed, 20)));+ camera.lookAt(0, 1.2, 0);+ }+// ── Lights ──────────────────────────────────────────────────────────────const ambient = new THREE.AmbientLight(0xffffff, 0.15);scene.add(ambient);@@ -76,15 +93,22 @@ export function createScene(canvas) {// ── Resize observer ──────────────────────────────────────────────────────const ro = new ResizeObserver(() => {- const w = canvas.clientWidth, h = canvas.clientHeight;- renderer.setSize(w, h);+ const w = viewport.clientWidth, h = viewport.clientHeight;+ if (!w || !h) return;+ renderer.setSize(w, h, false);camera.aspect = w / h;+ frameCamera(camera.aspect);camera.updateProjectionMatrix();});- ro.observe(canvas);+ ro.observe(viewport);+ frameCamera(camera.aspect);+ camera.updateProjectionMatrix();// ── Render loop ──────────────────────────────────────────────────────────- let raf;+ // Paused while the tab is hidden: this scene redraws a full canvas texture+ // every frame, and there is no reason to burn a background tab's GPU on a TV+ // nobody is looking at.+ let raf = 0;let t = 0;function tick() {raf = requestAnimationFrame(tick);@@ -97,7 +121,16 @@ export function createScene(canvas) {renderer.render(scene, camera);}- tick();+ function start() {+ if (!raf) tick();+ }+ function stop() {+ cancelAnimationFrame(raf);+ raf = 0;+ }+ const onVisibility = () => (document.hidden ? stop() : start());+ document.addEventListener('visibilitychange', onVisibility);+ start();return {nova,@@ -105,7 +138,8 @@ export function createScene(canvas) {tv,beam,dispose() {- cancelAnimationFrame(raf);+ stop();+ document.removeEventListener('visibilitychange', onVisibility);ro.disconnect();renderer.dispose();},@@ -241,6 +275,10 @@ function createTV(scene) {let phase = 'idle'; // idle | browsing | paying | contentlet briefing = null;let services = null;+ // The settled transfer, as reported by the SSE `payment` event. The TV used+ // to print a hardcoded "PAID 0.001 SOL" badge, which contradicted both the+ // real amount and the simulated runs that move no funds at all.+ let payment = null;let scrollY = 0;let animT = 0;@@ -257,7 +295,7 @@ function createTV(scene) {if (phase === 'idle') drawIdle(ctx, CW, CH, t);else if (phase === 'browsing') drawBazaar(ctx, CW, CH, services, t);else if (phase === 'paying') drawPaying(ctx, CW, CH, t);- else if (phase === 'content') drawContent(ctx, CW, CH, briefing, t);+ else if (phase === 'content') drawContent(ctx, CW, CH, briefing, payment, t);texture.needsUpdate = true;}@@ -272,6 +310,7 @@ function createTV(scene) {setPhase(p) { phase = p; },setServices(s) { services = s; },setBriefing(b) { briefing = b; },+ setPayment(p) { payment = p; },};}@@ -421,8 +460,12 @@ function drawPaying(ctx, W, H, t) {ctx.restore();}-function drawContent(ctx, W, H, briefing, t) {+function drawContent(ctx, W, H, briefing, payment, t) {if (!briefing) return;+ if (briefing.type === 'market_unavailable' || !briefing.headline) {+ drawMarketUnavailable(ctx, W, H, t);+ return;+ }ctx.save();// Scanlines@@ -443,20 +486,31 @@ function drawContent(ctx, W, H, briefing, t) {ctx.textAlign = 'left';ctx.fillText('ORACLE · LIVE MARKET BRIEFING', 50, 38);- ctx.fillStyle = 'rgba(255,255,255,0.4)';+ // Timestamp, and whether this is a fresh read or the last-known-good copy the+ // API serves when the upstream market feed is throttled.+ const stale = briefing.stale === true;+ const stamp = stale ? briefing.as_of || briefing.fetchedAt : briefing.fetchedAt;+ const ts = stamp ? new Date(stamp).toLocaleTimeString() : '';+ ctx.fillStyle = stale ? 'rgba(240,160,48,0.75)' : 'rgba(255,255,255,0.4)';ctx.font = '22px -apple-system,system-ui,sans-serif';- const ts = briefing.fetchedAt ? new Date(briefing.fetchedAt).toLocaleTimeString() : '';ctx.textAlign = 'right';- ctx.fillText(`fetched ${ts}`, W - 50, 38);-- // Paid badge- ctx.fillStyle = 'rgba(34,209,122,0.2)';- roundRect(ctx, W - 230, 54, 180, 36, 10);- ctx.fill();- ctx.fillStyle = '#22d17a';+ ctx.fillText(ts ? (stale ? `cached ${ts}` : `fetched ${ts}`) : '', W - 50, 38);++ // Settlement badge, driven by the real payment event. A simulated run says so+ // rather than claiming an on-chain payment that never happened.+ const simulated = payment?.simulated === true;+ const amount = payment?.amount_sol ? `${payment.amount_sol} SOL` : '';+ const badge = simulated+ ? `SIMULATED · ${amount || 'no funds moved'}`+ : `✓ PAID · ${amount || 'on-chain'}`;ctx.font = 'bold 22px -apple-system,system-ui,sans-serif';+ const badgeW = Math.max(180, ctx.measureText(badge).width + 34);+ ctx.fillStyle = simulated ? 'rgba(240,160,48,0.2)' : 'rgba(34,209,122,0.2)';+ roundRect(ctx, W - 50 - badgeW, 54, badgeW, 36, 10);+ ctx.fill();+ ctx.fillStyle = simulated ? '#f0a030' : '#22d17a';ctx.textAlign = 'center';- ctx.fillText('✓ PAID · 0.001 SOL', W - 140, 78);+ ctx.fillText(badge, W - 50 - badgeW / 2, 78);// Headlinectx.textAlign = 'left';@@ -522,6 +576,29 @@ function drawContent(ctx, W, H, briefing, t) {ctx.restore();}+// The market feed is a live third party. When it does not answer, the API says+// so explicitly instead of inventing prices, and the TV has to render that+// answer as a designed screen rather than an empty briefing frame.+function drawMarketUnavailable(ctx, W, H, t) {+ ctx.save();+ for (let y = 0; y < H; y += 3) {+ ctx.fillStyle = 'rgba(240,160,48,0.014)';+ ctx.fillRect(0, y, W, 1);+ }+ ctx.textAlign = 'center';+ ctx.textBaseline = 'middle';+ ctx.fillStyle = 'rgba(240,160,48,0.85)';+ ctx.font = 'bold 44px -apple-system,system-ui,sans-serif';+ ctx.fillText('Market feed unavailable', W / 2, H / 2 - 46);+ ctx.fillStyle = 'rgba(255,255,255,0.45)';+ ctx.font = '28px -apple-system,system-ui,sans-serif';+ ctx.fillText('ORACLE could not reach live Solana market data.', W / 2, H / 2 + 10);+ ctx.fillText('Run the demo again in a moment.', W / 2, H / 2 + 54);+ ctx.fillStyle = `rgba(240,160,48,${0.35 + 0.25 * Math.sin(t * 2)})`;+ ctx.fillRect(W / 2 - 40, H / 2 + 104, 80, 3);+ ctx.restore();+}+// ─── Payment beam (animated arc between agents) ─────────────────────────────function createBeam(scene) {