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.

feat: improve error handling for missing environment variables and optimize avatar frame loading

fudjia16fdeb9b525d
diff --git a/api/_lib/http.js b/api/_lib/http.js
index d2184af0b..a5fb32b4e 100644
--- a/api/_lib/http.js
+++ b/api/_lib/http.js
@@ -432,7 +432,14 @@ export function wrap(handler) {
// (api/cron/db-retention.js) rather than chase a phantom bug.
const dbFull = !dbDown && isDbCapacityError(err);
const dbDegraded = dbDown || dbFull;
- const status = dbDegraded ? 503 : (err.status || 500);
+ // A missing env var (api/_lib/env.js `req()`) is a deployment-configuration
+ // gap, not a code bug: the endpoint is down until the operator sets the
+ // secret. Surface it as 503 not_configured with a deduped alert naming the
+ // exact var — instead of one generic "unhandled 5xx" + Sentry event per hit
+ // (the July 2026 siwe/siws nonce incident: JWT_SECRET unset → hundreds of
+ // anonymous 500s that never said which var was missing).
+ const missingEnv = !dbDegraded && /^Missing required env var: /.test(err?.message || '');
+ const status = dbDegraded || missingEnv ? 503 : (err.status || 500);
if (status >= 500) {
const ref = correlationId();
if (dbDegraded) {
@@ -445,6 +452,13 @@ export function wrap(handler) {
sendOpsAlert(dbFull ? 'database at storage cap — retention needed' : 'database unavailable', `${err?.message || String(err)}\nref ${ref}`, {
signature: dbFull ? 'db:capacity' : 'db:unavailable',
});
+ } else if (missingEnv) {
+ // One concise line + one deduped alert per (route, var) — the fix is
+ // always the same: set the named var in the deployment env.
+ console.error(`[api] ${err.message} [ref ${ref}] — set it in the deployment env (${req.method} ${redactUrl(req.url)})`);
+ sendOpsAlert(`endpoint not configured: ${req.method} ${redactUrl(req.url)}`, `${err.message}\nSet the var in the Vercel env and redeploy.\nref ${ref}`, {
+ signature: `not-configured:${redactUrl(req.url)}:${err.message}`,
+ });
} else {
// Redact coordinates / device tokens so a 5xx on a geolocated read never
// spills the caller's position or credential to an off-box sink.
@@ -468,6 +482,14 @@ export function wrap(handler) {
// error page with their ref instead of a raw JSON blob. API and
// agent callers (no `Sec-Fetch-Mode: navigate`) keep the envelope.
redirect(res, serverErrorPageLocation(ref, req), 303);
+ } else if (missingEnv) {
+ // Don't name the missing var to the client — which secrets are
+ // unset is operator information; the ref ties it to the log line.
+ json(res, status, {
+ error: 'not_configured',
+ error_description: `this endpoint is not configured on this deployment — quote ref ${ref} to support`,
+ ref,
+ }, { 'cache-control': 'no-store' });
} else {
json(res, status, {
error: dbDegraded ? 'service_unavailable' : (err.code || 'internal_error'),
diff --git a/api/_lib/x402/ring-constants.js b/api/_lib/x402/ring-constants.js
index 142f5315b..990bf3ae9 100644
--- a/api/_lib/x402/ring-constants.js
+++ b/api/_lib/x402/ring-constants.js
@@ -9,21 +9,23 @@
// can import it without dragging the pipeline's load-time deps in.
/**
- * ring-settle default price in USDC atomic units ($35.00). Deliberately large so
- * the closed-loop ring carries real volume with FEW transactions (SOL fee scales
- * with tx count, not size). At the default one-settle-per-minute cadence this
- * targets ~$50k/day of settled ring volume (1440 ticks × $35). Lower it only if
- * you want more, smaller settlements; env `X402_PRICE_RING_SETTLE` overrides it.
+ * ring-settle default price in USDC atomic units ($1.00). The default must be
+ * affordable from the ring payer's REAL balance or every settle tick skips on
+ * `insufficient_payer_usdc` back-pressure and the whole visible ring economy
+ * flat-lines (this happened in production when the default was lifted to $35
+ * ahead of funding that never arrived). Scaling volume up is an env change, not
+ * a code change: fund the payer, then raise `X402_PRICE_RING_SETTLE` (and the
+ * caps below) together.
*/
-export const RING_SETTLE_DEFAULT_PRICE_ATOMICS = '35000000';
+export const RING_SETTLE_DEFAULT_PRICE_ATOMICS = '1000000';
/**
- * Volume-loop per-run cap default in USDC atomic units ($40.00). Must stay
+ * Volume-loop per-run cap default in USDC atomic units ($1.10). Must stay
* ≥ RING_SETTLE_DEFAULT_PRICE_ATOMICS or the config validator raises
* `ring_price_exceeds_run_cap` and the ring skips ring-settle every tick. Env
* `X402_VOLUME_PER_RUN_CAP_ATOMIC` overrides it.
*/
-export const VOLUME_PER_RUN_CAP_ATOMIC_DEFAULT = 40_000_000;
+export const VOLUME_PER_RUN_CAP_ATOMIC_DEFAULT = 1_100_000;
/** Resolve the per-run cap, honoring the env override. */
export function volumePerRunCapAtomic() {
diff --git a/public/embed.js b/public/embed.js
index d59f7b477..3f3b3d1ae 100644
--- a/public/embed.js
+++ b/public/embed.js
@@ -330,6 +330,7 @@
disconnectedCallback() {
this._destroyed = true;
+ if (avatarFrameIO) avatarFrameIO.unobserve(this);
window.removeEventListener('message', this._onMessage);
if (this._iframe) { this._iframe.remove(); this._iframe = null; }
if (this.bridge && typeof this.bridge.destroy === 'function') this.bridge.destroy();
@@ -410,10 +411,44 @@
}
}
+ // Boot avatar frames only when they approach the viewport, and unload
+ // non-driveable frames that scroll far away again. Every live frame is a
+ // full WebGL context plus a wasm decoder instance, so a long grid
+ // (dashboard avatars + infinite scroll) otherwise accumulates dozens of
+ // them until the renderer dies — the July 2026 "WebAssembly.instantiate():
+ // Out of memory" incident. `loading="lazy"` alone is not enough: Chromium's
+ // lazy-load distance thresholds boot iframes thousands of pixels before
+ // they are visible, and nothing ever unloads them.
+ var avatarFrameIO = typeof IntersectionObserver !== 'undefined'
+ ? new IntersectionObserver(function (entries) {
+ entries.forEach(function (entry) {
+ if (entry.isIntersecting) bootAvatarFrame(entry.target);
+ else unloadAvatarFrame(entry.target);
+ });
+ }, { rootMargin: '300px' })
+ : null;
+
+ function bootAvatarFrame(el) {
+ if (!el._iframe || el._frameLive || !el._frameSrc) return;
+ el._frameLive = true;
+ el._iframe.src = el._frameSrc;
+ if (isAvatarDriveable(el)) upgradeAvatarToBridge(el);
+ }
+
+ function unloadAvatarFrame(el) {
+ // Driveable frames hold live conversational state — never unload them.
+ if (!el._iframe || !el._frameLive || isAvatarDriveable(el)) return;
+ el._frameLive = false;
+ el._resetReady();
+ el._iframe.src = 'about:blank';
+ }
+
function mountAvatarFrame(el) {
if (el._iframe) { el._iframe.remove(); el._iframe = null; }
if (el.bridge && typeof el.bridge.destroy === 'function') el.bridge.destroy();
el.bridge = null;
+ el._frameLive = false;
+ el._frameSrc = null;
var oldErr = el.shadowRoot.querySelector('.error');
if (oldErr) oldErr.remove();
el._resetReady();
@@ -424,9 +459,9 @@
return;
}
el._origin = new URL(src, location.href).origin;
+ el._frameSrc = src;
var iframe = document.createElement('iframe');
- iframe.src = src;
iframe.allow = 'autoplay; camera; microphone; xr-spatial-tracking; clipboard-write';
if (isCrossOrigin(src)) {
iframe.setAttribute('sandbox', SANDBOX_VALUE);
@@ -438,7 +473,15 @@
el.shadowRoot.appendChild(iframe);
el._iframe = iframe;
- if (isAvatarDriveable(el)) upgradeAvatarToBridge(el);
+ if (avatarFrameIO) {
+ // Re-arming after an attribute-change remount: unobserve first so the
+ // fresh observe() delivers an initial visibility callback (a repeated
+ // observe() on an already-tracked target is silently ignored).
+ avatarFrameIO.unobserve(el);
+ avatarFrameIO.observe(el);
+ } else {
+ bootAvatarFrame(el);
+ }
}
function resolveAvatarIframeSrc(el) {