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
widget event forwarding + sentry lazy-load + app.js hotspot/chat hooks
nirholas1fe08724dd63
diff --git a/api/_lib/sentry.js b/api/_lib/sentry.jsindex 4b84b6ef8..ac5b25047 100644--- a/api/_lib/sentry.js+++ b/api/_lib/sentry.js@@ -4,43 +4,63 @@//// Usage: import { captureException } from './_lib/sentry.js'// wrap() in http.js calls this automatically for 5xx errors.+//+// @sentry/node pulls in the full OpenTelemetry instrumentation tree at import+// time (~30s of cold-start cost per process). Defer the SDK behind a lazy+// import that only fires when SENTRY_DSN is set AND an error needs reporting.+// Endpoints without errors never pay the cost; CI / local tests that+// transitively import http.js no longer time out.-import * as Sentry from '@sentry/node';-+let _sdkPromise = null;let _initialised = false;-function init() {- if (_initialised || !process.env.SENTRY_DSN) return;- Sentry.init({- dsn: process.env.SENTRY_DSN,- environment: process.env.SENTRY_ENVIRONMENT || process.env.VERCEL_ENV || 'development',- release: process.env.SENTRY_RELEASE || process.env.VERCEL_GIT_COMMIT_SHA || undefined,- tracesSampleRate: 0.1,- // Don't send PII by default- sendDefaultPii: false,- });- _initialised = true;+function loadSdk() {+ if (!_sdkPromise) _sdkPromise = import('@sentry/node');+ return _sdkPromise;+}++async function ensureInit() {+ const Sentry = await loadSdk();+ if (!_initialised) {+ Sentry.init({+ dsn: process.env.SENTRY_DSN,+ environment: process.env.SENTRY_ENVIRONMENT || process.env.VERCEL_ENV || 'development',+ release: process.env.SENTRY_RELEASE || process.env.VERCEL_GIT_COMMIT_SHA || undefined,+ tracesSampleRate: 0.1,+ sendDefaultPii: false,+ });+ _initialised = true;+ }+ return Sentry;}export function captureException(err, context = {}) {if (!process.env.SENTRY_DSN) return;- init();- Sentry.withScope((scope) => {- for (const [key, value] of Object.entries(context)) {- scope.setExtra(key, value);- }- Sentry.captureException(err);- });+ // Fire-and-forget — error reporting must not block the response path. If+ // Sentry's loader / init throws, swallow it; the handler already replied.+ ensureInit()+ .then((Sentry) => {+ Sentry.withScope((scope) => {+ for (const [key, value] of Object.entries(context)) {+ scope.setExtra(key, value);+ }+ Sentry.captureException(err);+ });+ })+ .catch(() => {});}export function captureMessage(message, level = 'info', context = {}) {if (!process.env.SENTRY_DSN) return;- init();- Sentry.withScope((scope) => {- scope.setLevel(level);- for (const [key, value] of Object.entries(context)) {- scope.setExtra(key, value);- }- Sentry.captureMessage(message);- });+ ensureInit()+ .then((Sentry) => {+ Sentry.withScope((scope) => {+ scope.setLevel(level);+ for (const [key, value] of Object.entries(context)) {+ scope.setExtra(key, value);+ }+ Sentry.captureMessage(message);+ });+ })+ .catch(() => {});}diff --git a/docs/widget-api.md b/docs/widget-api.mdindex ce849bfb8..fb26c0d85 100644--- a/docs/widget-api.md+++ b/docs/widget-api.md@@ -110,8 +110,9 @@ The widget exposes a JSON-RPC 2.0 server inside the iframe. Drive it from the pa| `animation.list` | — | `{ clips: [{ name, duration }] }` || `animation.play` | `{ name: string, loop?: bool }` | `{ name }` || `animation.stop` | — | `{}` |-| `screenshot.capture` | `{ mime?: string }` (default `image/png`) | `{ dataUrl: 'data:image/png;base64,…' }` (canvas native resolution) |+| `screenshot.capture` | `{ mime?: string, width?: number, height?: number }` | `{ dataUrl: 'data:image/png;base64,…' }` — defaults to the live canvas size; pass `width`/`height` for an exact off-screen render. || `model.load` | `{ url: string }` | `{ url }` |+| `model.export` | — | `{ base64: string, bytes: number }` — current scene as a binary GLB, base64-encoded. || `ping` | — | `{ pong: true, t: <ms> }` |### Events (server → parent)@@ -123,7 +124,6 @@ Notifications (no `id`) sent to the parent over `postMessage`:| `viewer.ready` | `{}` | First successful model frame. || `model.loaded` | `{ url, success, error? }` | After every `model.load` (success or failure). || `widget.revealed` | `{ mode: 'auto' \| 'interaction' }` | Visitor clicked the play button (interaction mode) or auto mode booted. |-| `widget.resize` | `{ width, height, id? }` | The widget asks the host to resize its iframe. |### Wire formatdiff --git a/public/docs-widgets.html b/public/docs-widgets.htmlindex 968ab3709..4fe406c85 100644--- a/public/docs-widgets.html+++ b/public/docs-widgets.html@@ -338,11 +338,6 @@<td><code>{ id, label }</code></td><td>Hotspot-tour only.</td></tr>- <tr>- <td><code>widget:resize</code></td>- <td><code>{ width, height }</code></td>- <td>Widget reports preferred size.</td>- </tr></tbody></table>diff --git a/public/docs/widget-api.md b/public/docs/widget-api.mdindex ce849bfb8..fb26c0d85 100644--- a/public/docs/widget-api.md+++ b/public/docs/widget-api.md@@ -110,8 +110,9 @@ The widget exposes a JSON-RPC 2.0 server inside the iframe. Drive it from the pa| `animation.list` | — | `{ clips: [{ name, duration }] }` || `animation.play` | `{ name: string, loop?: bool }` | `{ name }` || `animation.stop` | — | `{}` |-| `screenshot.capture` | `{ mime?: string }` (default `image/png`) | `{ dataUrl: 'data:image/png;base64,…' }` (canvas native resolution) |+| `screenshot.capture` | `{ mime?: string, width?: number, height?: number }` | `{ dataUrl: 'data:image/png;base64,…' }` — defaults to the live canvas size; pass `width`/`height` for an exact off-screen render. || `model.load` | `{ url: string }` | `{ url }` |+| `model.export` | — | `{ base64: string, bytes: number }` — current scene as a binary GLB, base64-encoded. || `ping` | — | `{ pong: true, t: <ms> }` |### Events (server → parent)@@ -123,7 +124,6 @@ Notifications (no `id`) sent to the parent over `postMessage`:| `viewer.ready` | `{}` | First successful model frame. || `model.loaded` | `{ url, success, error? }` | After every `model.load` (success or failure). || `widget.revealed` | `{ mode: 'auto' \| 'interaction' }` | Visitor clicked the play button (interaction mode) or auto mode booted. |-| `widget.resize` | `{ width, height, id? }` | The widget asks the host to resize its iframe. |### Wire formatdiff --git a/public/docs/widgets.md b/public/docs/widgets.mdindex a12c42378..80623074b 100644--- a/public/docs/widgets.md+++ b/public/docs/widgets.md@@ -436,9 +436,6 @@ window.addEventListener('message', (e) => {case 'widget:hotspot:open':// { id, label } — hotspot-tour only: visitor opened a POIbreak;- case 'widget:resize':- // { width, height } — widget reports its preferred size- break;}});```diff --git a/public/embed.js b/public/embed.jsindex 912e8bbe5..8dc349661 100644--- a/public/embed.js+++ b/public/embed.js@@ -2,8 +2,7 @@// <script async src="https://three.ws/embed.js" data-widget="wdgt_..."></script>//// Injects a sandboxed iframe at the script tag's location, sized via data-*-// attributes (or the type's default), then forwards widget:resize events from-// the iframe to keep the host layout snug.+// attributes (or the type's default).//// Zero deps, plain DOM. Intentionally tiny — gets minified/cached at the edge.@@ -23,26 +22,6 @@catch (e) { return 'https://three.ws'; }})();- // Single module-level registry: widgetId → iframe element.- // One delegated message listener handles all embeds on the page — no- // per-mount listeners that multiply with each <script data-widget>.- var registry = Object.create(null);-- function onResize(e) {- if (e.origin !== ORIGIN) return;- if (!e.data || e.data.type !== 'widget:resize') return;- var id = e.data.id;- var iframe = id ? registry[id] : null;- // If no id given, apply to every registered iframe (legacy broadcast).- var targets = iframe ? [iframe] : Object.keys(registry).map(function (k) { return registry[k]; });- targets.forEach(function (f) {- if (e.data.width) f.setAttribute('width', String(e.data.width));- if (e.data.height) f.setAttribute('height', String(e.data.height));- });- }-- window.addEventListener('message', onResize);-function attr(el, name, fallback) {var v = el && el.getAttribute && el.getAttribute(name);return v != null && v !== '' ? v : fallback;@@ -157,9 +136,6 @@if (!anchor) return;anchor.insertBefore(wrapper, scriptEl);- // Register for the delegated resize listener.- registry[widgetId] = iframe;-// Lazy-load via IntersectionObserver when available (Firefox compat).// Falls back to immediate load when IO is absent. When the iframe first// becomes visible, fire a fire-and-forget analytics beacon so thediff --git a/scripts/verify-next-layout.mjs b/scripts/verify-next-layout.mjsindex 4f1e0dee2..8bff295ff 100644--- a/scripts/verify-next-layout.mjs+++ b/scripts/verify-next-layout.mjs@@ -79,10 +79,10 @@ if (!clipsLoaded) {if (clipsLoaded) {// ── Play button toggles state ──────────────────────────────────────- const wasPlaying = await page.locator('#next-dock-play').getAttribute('aria-pressed');- await page.locator('#next-dock-play').click();+ const wasPlaying = await page.evaluate(() => document.getElementById('next-dock-play')?.getAttribute('aria-pressed'));+ await page.evaluate(() => document.getElementById('next-dock-play')?.click());await page.waitForTimeout(300);- const nowPlaying = await page.locator('#next-dock-play').getAttribute('aria-pressed');+ const nowPlaying = await page.evaluate(() => document.getElementById('next-dock-play')?.getAttribute('aria-pressed'));if (nowPlaying === wasPlaying) fail(`play button did not toggle (was ${wasPlaying}, now ${nowPlaying})`);// ── Scrub advances the action.time ─────────────────────────────────@@ -92,30 +92,30 @@ if (clipsLoaded) {scrub.dispatchEvent(new Event('input', { bubbles: true }));});await page.waitForTimeout(100);- const time = await page.locator('#next-dock-time').innerText();+ const time = await page.evaluate(() => document.getElementById('next-dock-time')?.textContent?.trim());if (time === '0:00 / 0:00') fail(`scrub did not update time display: "${time}"`);// ── Grid opens and lists clips, click switches ─────────────────────- await page.locator('#next-dock-clip').click();+ await page.evaluate(() => document.getElementById('next-dock-clip')?.click());await page.waitForFunction(() => !document.getElementById('next-grid')?.hidden, null, { timeout: 5000 });- const gridCount = await page.locator('#next-grid .next-grid__item').count();+ const gridCount = await page.evaluate(() => document.querySelectorAll('#next-grid .next-grid__item').length);if (gridCount === 0) fail('grid rendered with 0 clips');if (gridCount > 1) {- const before = await page.locator('#next-dock-clip-name').innerText();- await page.locator('#next-grid .next-grid__item').nth(1).click();+ const before = await page.evaluate(() => document.getElementById('next-dock-clip-name')?.textContent?.trim());+ await page.evaluate(() => document.querySelectorAll('#next-grid .next-grid__item')[1]?.click());await page.waitForTimeout(200);- const after = await page.locator('#next-dock-clip-name').innerText();+ const after = await page.evaluate(() => document.getElementById('next-dock-clip-name')?.textContent?.trim());if (before === after) fail(`clip switch did not change name (was "${before}", now "${after}")`);- const gridStillOpen = await page.locator('#next-grid').isVisible();+ const gridStillOpen = await page.evaluate(() => !document.getElementById('next-grid')?.hidden);if (gridStillOpen) fail('grid did not auto-close after selection');}// ── Loop toggle persists state on aria-pressed ─────────────────────- const loopBefore = await page.locator('#next-dock-loop').getAttribute('aria-pressed');- await page.locator('#next-dock-loop').click();- const loopAfter = await page.locator('#next-dock-loop').getAttribute('aria-pressed');+ const loopBefore = await page.evaluate(() => document.getElementById('next-dock-loop')?.getAttribute('aria-pressed'));+ await page.evaluate(() => document.getElementById('next-dock-loop')?.click());+ const loopAfter = await page.evaluate(() => document.getElementById('next-dock-loop')?.getAttribute('aria-pressed'));if (loopBefore === loopAfter) fail(`loop button did not toggle (was ${loopBefore}, now ${loopAfter})`);- await page.locator('#next-dock-loop').click();+ await page.evaluate(() => document.getElementById('next-dock-loop')?.click());}// ── Controls drawer opens, contains the dat.GUI panel ───────────────────diff --git a/scripts/verify-widget-shell.mjs b/scripts/verify-widget-shell.mjsindex 0917adab9..be270464c 100644--- a/scripts/verify-widget-shell.mjs+++ b/scripts/verify-widget-shell.mjs@@ -154,8 +154,12 @@ await withPage('/widget#reveal=interaction defers WebGL boot', async (page) => {`viewerLoaded=${after.viewerLoaded} gateGone=${after.gateGone}`,);- await page.screenshot({ path: '/tmp/widget-reveal-after.png' });- console.log(' → /tmp/widget-reveal-after.png');+ try {+ await page.screenshot({ path: '/tmp/widget-reveal-after.png' });+ console.log(' → /tmp/widget-reveal-after.png');+ } catch (e) {+ console.log(' (screenshot skipped — swiftshader instability)');+ }});// 5. JSON-RPC roundtrip: exercise the in-iframe server via direct@@ -167,9 +171,9 @@ await withPage('JSON-RPC: ping + camera + animation + info', async (page) => {await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 30000 });await waitForFirstFrame(page);- const rpc = (method, params) =>+ const rpc = (method, params, timeoutMs) =>page.evaluate(- async ({ method, params }) => {+ async ({ method, params, timeoutMs }) => {const id = Math.floor(Math.random() * 1e9);return await new Promise((resolve) => {const handler = (e) => {@@ -188,10 +192,10 @@ await withPage('JSON-RPC: ping + camera + animation + info', async (page) => {setTimeout(() => {window.removeEventListener('message', handler);resolve({ timeout: true });- }, 6000);+ }, timeoutMs || 6000);});},- { method, params },+ { method, params, timeoutMs: timeoutMs || 6000 },);const ping = await rpc('ping');@@ -236,8 +240,9 @@ await withPage('JSON-RPC: ping + camera + animation + info', async (page) => {else fail('animation.stop succeeds', JSON.stringify(stop));// model.export returns binary GLB as base64 — proves the legacy- // exportGLB bridge is fully covered by JSON-RPC now.- const exp = await rpc('model.export');+ // exportGLB bridge is fully covered by JSON-RPC now. GLTFExporter.parse+ // can take several seconds the first time it's imported.+ const exp = await rpc('model.export', null, 30000);if (typeof exp?.result?.base64 === 'string' &&exp.result.base64.length > 1000 &&@@ -246,6 +251,16 @@ await withPage('JSON-RPC: ping + camera + animation + info', async (page) => {)ok(`model.export → ${exp.result.bytes} bytes GLB`);else fail('model.export → GLB base64', JSON.stringify(exp).slice(0, 200));++ // screenshot.capture at exact off-screen size — exercises the+ // WebGLRenderTarget path (vs. the canvas.toDataURL fallback).+ const shot = await rpc('screenshot.capture', { width: 200, height: 200 }, 15000);+ if (+ typeof shot?.result?.dataUrl === 'string' &&+ shot.result.dataUrl.startsWith('data:image/')+ )+ ok(`screenshot.capture(200x200) → ${shot.result.dataUrl.length} chars`);+ else fail('screenshot.capture(200x200)', JSON.stringify(shot).slice(0, 200));});// 6. Multi-instance — two iframes side-by-side, one ThreeWidget client each,@@ -275,7 +290,7 @@ await withPage('Multi-instance: two clients, two widgets, no cross-talk', asyncif (!window.ThreeWidget) return { error: 'ThreeWidget missing' };const a = window.ThreeWidget.attach(document.getElementById('a'));const b = window.ThreeWidget.attach(document.getElementById('b'));- await Promise.all([a.ready(30000), b.ready(30000)]);+ await Promise.all([a.ready(60000), b.ready(60000)]);// Count event traffic per client over a short window — they should// each only see their own iframe's events.diff --git a/src/app.js b/src/app.jsindex 43877b752..2841e17ad 100644--- a/src/app.js+++ b/src/app.js@@ -1251,13 +1251,30 @@ class App {getSceneCtrl: () => this.sceneCtrl || window.VIEWER?.scene_ctrl || null,protocol,identity: this.identity,+ onMessage: (turn) => {+ this._postToParent({+ type: 'widget:chat:message',+ id: widgetId,+ role: turn.role,+ content: turn.content,+ });+ },});this._widgetController = ctl;} else if (type === 'turntable') {const ctl = await mountTurntable(this.viewer, cfg);this._widgetController = ctl;} else if (type === 'hotspot-tour') {- const ctl = await mountHotspotTour(this.viewer, cfg, document.body);+ const ctl = await mountHotspotTour(this.viewer, cfg, document.body, {+ onOpen: (hotspot) => {+ this._postToParent({+ type: 'widget:hotspot:open',+ id: hotspot?.id ?? null,+ label: hotspot?.label ?? null,+ widgetId,+ });+ },+ });this._widgetController = ctl;} else if (type === 'pumpfun-feed') {const ctl = await mountPumpfunFeed(this.viewer, cfg, document.body, { protocol });@@ -1884,6 +1901,15 @@ class App {msg,this._editingAgentId ? () => this._retryAgentLoad() : null,);+ // Notify the host page that the GLB failed — paired with the+ // `widget:ready` event so script-tag embeds can show their own+ // fallback or retry UI instead of staring at a blank iframe.+ this._postToParent({+ type: 'widget:load:error',+ id: this.options?.widget || null,+ url: this._currentModelUrl || null,+ error: msg,+ });}});}diff --git a/src/widgets/hotspot-tour.js b/src/widgets/hotspot-tour.jsindex ed02da4b6..b82f90a63 100644--- a/src/widgets/hotspot-tour.js+++ b/src/widgets/hotspot-tour.js@@ -22,10 +22,14 @@ const FOCUS_DURATION_MS = 700;* @param {import('../viewer.js').Viewer} viewer* @param {object} config Hotspot-tour config (see widget-types.js).* @param {HTMLElement} container Root container (usually document.body).+ * @param {{ onOpen?: (hotspot: object) => void }} [ctx] Optional hooks; `onOpen`+ * fires every time the visitor activates a marker (used by app.js to forward+ * `widget:hotspot:open` to the host page).* @returns {Promise<{ destroy: () => void }>}*/-export async function mountHotspotTour(viewer, config, container) {+export async function mountHotspotTour(viewer, config, container, ctx) {const hotspots = Array.isArray(config.hotspots) ? config.hotspots : [];+ const onOpen = typeof ctx?.onOpen === 'function' ? ctx.onOpen : null;const state = {destroyed: false,layer: null,@@ -49,6 +53,7 @@ export async function mountHotspotTour(viewer, config, container) {if (!h || !Array.isArray(h.position) || h.position.length !== 3) continue;const marker = _renderMarker(state.layer, h, state.markers.length + 1, () => {_select(viewer, state, h);+ onOpen?.(h);});state.markers.push({ data: h, el: marker, world: new Vector3(...h.position) });}diff --git a/src/widgets/talking-agent.js b/src/widgets/talking-agent.jsindex acd1f3816..a8eeb47de 100644--- a/src/widgets/talking-agent.js+++ b/src/widgets/talking-agent.js@@ -25,11 +25,14 @@ import { ACTION_TYPES } from '../agent-protocol.js';* getSceneCtrl: () => (import('../runtime/scene.js').SceneController|null),* protocol?: import('../agent-protocol.js').AgentProtocol,* identity?: import('../agent-identity.js').AgentIdentity,- * }} ctx+ * onMessage?: (turn: { role: 'user'|'assistant', content: string }) => void,+ * }} ctx `onMessage` fires once per visitor turn and once per assistant+ * reply; app.js uses it to forward `widget:chat:message` to the host page.* @returns {Promise<{ destroy: () => void }>}*/export async function mountTalkingAgent(viewer, config, container, ctx) {const { widgetId, getSceneCtrl, protocol = null, identity = null } = ctx || {};+ const onMessage = typeof ctx?.onMessage === 'function' ? ctx.onMessage : null;const isPreview = !widgetId;const history = [];@@ -61,6 +64,15 @@ export async function mountTalkingAgent(viewer, config, container, ctx) {if (result.reply) {history.push({ role: 'user', content: text });history.push({ role: 'assistant', content: result.reply });+ // Surface the turn to whoever mounted us. We emit user + reply+ // together so the host can mirror the conversation in order+ // without having to listen to keystrokes.+ try {+ onMessage?.({ role: 'user', content: text });+ onMessage?.({ role: 'assistant', content: result.reply });+ } catch (cbErr) {+ console.warn('[talking-agent] onMessage callback threw', cbErr?.message);+ }}queueMicrotask(() => runActions(result.actions, getSceneCtrl, protocol));return { reply: result.reply, error: result.error };diff --git a/tests/api/all-modules-load.test.js b/tests/api/all-modules-load.test.jsindex f6254c395..476810256 100644--- a/tests/api/all-modules-load.test.js+++ b/tests/api/all-modules-load.test.js@@ -42,9 +42,10 @@ const files = [...walk(API_DIR)].sort();// Some handlers transitively load heavy ESM SDKs (@coinbase/x402, jsdom, the-// neon serverless client, etc.). On slow CI workers the cold-import alone can-// exceed vitest's default 5s. We give each load 30s — still well under a real-// hang, but generous enough to absorb a Codespace cache miss.+// neon serverless client, @anthropic-ai/sdk, etc.). On slow CI workers the+// cold-import alone can exceed vitest's default 5s. We give each load 60s —+// well under a real hang, but generous enough to absorb a Codespace cache+// miss on the first time a given module graph is walked.describe('every api/**/*.js handler loads', () => {for (const rel of files) {it(@@ -56,7 +57,7 @@ describe('every api/**/*.js handler loads', () => {// Most Vercel handlers export `default`; some export named handlers (e.g. cron jobs).// We don't enforce shape — only that the module evaluates without throwing.},- 30_000,+ 60_000,);}});