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: OG card fallback, brain provider fallback, pass refresh, colyseus fix

nirholas07937825e5d4
diff --git a/api/avatar-og.js b/api/avatar-og.js
index 38696de57..3aed4dca8 100644
--- a/api/avatar-og.js
+++ b/api/avatar-og.js
@@ -22,7 +22,6 @@
import { sql } from './_lib/db.js';
import { getAvatar } from './_lib/avatars.js';
import { DEMO_AVATARS } from './_lib/demo-avatars.js';
-import { env } from './_lib/env.js';
import { cors, wrap } from './_lib/http.js';
import { publicUrl, putObject } from './_lib/r2.js';
import { renderGlbToPng } from './_lib/render-glb.js';
@@ -35,8 +34,10 @@ const CACHE_FALLBACK = 'public, max-age=300';
// Anything bigger than this would dominate the 15s render budget — and
// Vercel's 30s function ceiling means a single oversized GLB risks killing
-// the request. Falls back to the site logo instead.
-const MAX_GLB_BYTES = 10 * 1024 * 1024;
+// the request. Falls back to the named avatar card instead. Set at 12 MB:
+// comfortably renders typical photoreal GLBs (which cluster just above 10 MB)
+// while still kicking the genuinely huge ones to the card before chromium.
+const MAX_GLB_BYTES = 12 * 1024 * 1024;
// Per-avatar lock so two simultaneous crawls don't both spin up chromium.
// In-memory only — multiple lambda containers may each render once, but
@@ -191,15 +192,6 @@ function extractIdFromPath(pathname) {
return m ? m[1] : null;
}
-function sendFallbackLogo(_req, res) {
- // 302 to the static brand logo. Anchor on env.APP_ORIGIN so a caller can't
- // craft an `x-forwarded-host` that redirects this 302 to an attacker site.
- res.statusCode = 302;
- res.setHeader('location', `${env.APP_ORIGIN}/assets/og-image.png`);
- res.setHeader('cache-control', CACHE_FALLBACK);
- res.end();
-}
-
function sendCardSvg(res, status, cacheControl, payload) {
res.statusCode = status;
res.setHeader('content-type', 'image/svg+xml; charset=utf-8');
diff --git a/api/brain/chat.js b/api/brain/chat.js
index 50e312a17..4631a502a 100644
--- a/api/brain/chat.js
+++ b/api/brain/chat.js
@@ -20,6 +20,11 @@ import { watsonxConfig, watsonxChatRequest } from '../_lib/watsonx.js';
export const maxDuration = 120;
+// Each spec declares its *native* provider model (built from a first-party key,
+// or null when that key is absent) and the OpenRouter model id that mirrors it.
+// buildPrimary() prefers the native model and falls back to routing through
+// OpenRouter; buildFallback() reuses the OpenRouter id to route *around* a native
+// provider outage (quota/billing/rate-limit) at request time.
const PROVIDERS = {
'gpt-oss-120b': {
label: 'GPT-OSS 120B',
@@ -27,10 +32,8 @@ const PROVIDERS = {
tier: 'balanced',
maxOutput: 8192,
description: "OpenAI's open-weight 120B. Fast, capable, free tier. Platform default.",
- build: () => {
- if (env.OPENROUTER_API_KEY) return openrouter()('openai/gpt-oss-120b:free');
- return null;
- },
+ // OpenRouter-only — no first-party key for the free tier.
+ openrouterModel: 'openai/gpt-oss-120b:free',
},
'claude-opus-4-7': {
label: 'Claude Opus 4.7',
@@ -38,11 +41,8 @@ const PROVIDERS = {
tier: 'flagship',
maxOutput: 16384,
description: 'Most capable. Extended thinking, complex reasoning.',
- build: () => {
- if (env.ANTHROPIC_API_KEY) return createAnthropic({ apiKey: env.ANTHROPIC_API_KEY })('claude-opus-4-7');
- if (env.OPENROUTER_API_KEY) return openrouter()('anthropic/claude-opus-4');
- return null;
- },
+ native: () => (env.ANTHROPIC_API_KEY ? createAnthropic({ apiKey: env.ANTHROPIC_API_KEY })('claude-opus-4-7') : null),
+ openrouterModel: 'anthropic/claude-opus-4',
},
'claude-sonnet-4-6': {
label: 'Claude Sonnet 4.6',
@@ -50,11 +50,8 @@ const PROVIDERS = {
tier: 'balanced',
maxOutput: 16384,
description: 'Balanced speed and intelligence. Best for most tasks.',
- build: () => {
- if (env.ANTHROPIC_API_KEY) return createAnthropic({ apiKey: env.ANTHROPIC_API_KEY })('claude-sonnet-4-6');
- if (env.OPENROUTER_API_KEY) return openrouter()('anthropic/claude-sonnet-4');
- return null;
- },
+ native: () => (env.ANTHROPIC_API_KEY ? createAnthropic({ apiKey: env.ANTHROPIC_API_KEY })('claude-sonnet-4-6') : null),
+ openrouterModel: 'anthropic/claude-sonnet-4',
},
'claude-haiku-4-5': {
label: 'Claude Haiku 4.5',
@@ -62,11 +59,8 @@ const PROVIDERS = {
tier: 'fast',
maxOutput: 8192,
description: 'Fastest Claude. Low latency, high throughput.',
- build: () => {
- if (env.ANTHROPIC_API_KEY) return createAnthropic({ apiKey: env.ANTHROPIC_API_KEY })('claude-haiku-4-5-20251001');
- if (env.OPENROUTER_API_KEY) return openrouter()('anthropic/claude-3.5-haiku');
- return null;
- },
+ native: () => (env.ANTHROPIC_API_KEY ? createAnthropic({ apiKey: env.ANTHROPIC_API_KEY })('claude-haiku-4-5-20251001') : null),
+ openrouterModel: 'anthropic/claude-3.5-haiku',
},
'gpt-4o': {
label: 'GPT-4o',
@@ -74,11 +68,8 @@ const PROVIDERS = {
tier: 'flagship',
maxOutput: 16384,
description: 'OpenAI flagship. Strong multimodal reasoning.',
- build: () => {
- if (env.OPENAI_API_KEY) return createOpenAI({ apiKey: env.OPENAI_API_KEY }).chat('gpt-4o');
- if (env.OPENROUTER_API_KEY) return openrouter()('openai/gpt-4o');
- return null;
- },
+ native: () => (env.OPENAI_API_KEY ? createOpenAI({ apiKey: env.OPENAI_API_KEY }).chat('gpt-4o') : null),
+ openrouterModel: 'openai/gpt-4o',
},
'gpt-4o-mini': {
label: 'GPT-4o-mini',
@@ -86,11 +77,8 @@ const PROVIDERS = {
tier: 'fast',
maxOutput: 16384,
description: 'Fast, affordable GPT. Great for simple tasks.',
- build: () => {
- if (env.OPENAI_API_KEY) return createOpenAI({ apiKey: env.OPENAI_API_KEY }).chat('gpt-4o-mini');
- if (env.OPENROUTER_API_KEY) return openrouter()('openai/gpt-4o-mini');
- return null;
- },
+ native: () => (env.OPENAI_API_KEY ? createOpenAI({ apiKey: env.OPENAI_API_KEY }).chat('gpt-4o-mini') : null),
+ openrouterModel: 'openai/gpt-4o-mini',
},
'o3-mini': {
label: 'o3-mini',
@@ -98,11 +86,8 @@ const PROVIDERS = {
tier: 'reasoning',
maxOutput: 16384,
description: 'Reasoning-optimized. Fast chain-of-thought.',
- build: () => {
- if (env.OPENAI_API_KEY) return createOpenAI({ apiKey: env.OPENAI_API_KEY }).chat('o3-mini');
- if (env.OPENROUTER_API_KEY) return openrouter()('openai/o3-mini');
- return null;
- },
+ native: () => (env.OPENAI_API_KEY ? createOpenAI({ apiKey: env.OPENAI_API_KEY }).chat('o3-mini') : null),
+ openrouterModel: 'openai/o3-mini',
},
'groq-llama': {
label: 'Llama 3.3 70B',
@@ -110,16 +95,11 @@ const PROVIDERS = {
tier: 'fast',
maxOutput: 8192,
description: 'Open-weight on Groq. Extremely fast inference.',
- build: () => {
- if (env.GROQ_API_KEY) {
- return createOpenAI({
- apiKey: env.GROQ_API_KEY,
- baseURL: 'https://api.groq.com/openai/v1',
- }).chat('llama-3.3-70b-versatile');
- }
- if (env.OPENROUTER_API_KEY) return openrouter()('meta-llama/llama-3.3-70b-instruct');
- return null;
- },
+ native: () =>
+ env.GROQ_API_KEY
+ ? createOpenAI({ apiKey: env.GROQ_API_KEY, baseURL: 'https://api.groq.com/openai/v1' }).chat('llama-3.3-70b-versatile')
+ : null,
+ openrouterModel: 'meta-llama/llama-3.3-70b-instruct',
},
'qwen-plus': {
label: 'Qwen Plus',
@@ -127,11 +107,8 @@ const PROVIDERS = {
tier: 'balanced',
maxOutput: 8192,
description: 'Qwen Plus on DashScope. Strong multilingual.',
- build: () => {
- if (env.DASHSCOPE_API_KEY) return createQwen({ apiKey: env.DASHSCOPE_API_KEY })('qwen-plus');
- if (env.OPENROUTER_API_KEY) return openrouter()('qwen/qwen-2.5-72b-instruct');
- return null;
- },
+ native: () => (env.DASHSCOPE_API_KEY ? createQwen({ apiKey: env.DASHSCOPE_API_KEY })('qwen-plus') : null),
+ openrouterModel: 'qwen/qwen-2.5-72b-instruct',
},
'modelscope-qwen': {
label: 'Qwen3-Coder 480B',
@@ -139,16 +116,11 @@ const PROVIDERS = {
tier: 'flagship',
maxOutput: 16384,
description: 'Largest Qwen coder. Exceptional code generation.',
- build: () => {
- if (env.MODELSCOPE_API_KEY) {
- return createOpenAI({
- apiKey: env.MODELSCOPE_API_KEY,
- baseURL: 'https://api-inference.modelscope.cn/v1',
- }).chat('Qwen/Qwen3-Coder-480B-A35B-Instruct');
- }
- if (env.OPENROUTER_API_KEY) return openrouter()('qwen/qwen3-coder');
- return null;
- },
+ native: () =>
+ env.MODELSCOPE_API_KEY
+ ? createOpenAI({ apiKey: env.MODELSCOPE_API_KEY, baseURL: 'https://api-inference.modelscope.cn/v1' }).chat('Qwen/Qwen3-Coder-480B-A35B-Instruct')
+ : null,
+ openrouterModel: 'qwen/qwen3-coder',
},
'deepseek-r1': {
label: 'DeepSeek R1',
@@ -156,21 +128,16 @@ const PROVIDERS = {
tier: 'reasoning',
maxOutput: 8192,
description: 'Open reasoning model. Strong at math and code.',
- build: () => {
- if (env.DEEPSEEK_API_KEY) {
- return createOpenAI({
- apiKey: env.DEEPSEEK_API_KEY,
- baseURL: 'https://api.deepseek.com/v1',
- }).chat('deepseek-reasoner');
- }
- if (env.OPENROUTER_API_KEY) return openrouter()('deepseek/deepseek-r1');
- return null;
- },
+ native: () =>
+ env.DEEPSEEK_API_KEY
+ ? createOpenAI({ apiKey: env.DEEPSEEK_API_KEY, baseURL: 'https://api.deepseek.com/v1' }).chat('deepseek-reasoner')
+ : null,
+ openrouterModel: 'deepseek/deepseek-r1',
},
// IBM watsonx.ai Granite. watsonx is not OpenAI-compatible at the API layer
// (IAM bearer token, project scoping, version param), so it can't be a
// Vercel AI SDK model object. The `watsonx` flag routes it to a dedicated
- // streaming path; build() only reports availability.
+ // streaming path; buildPrimary() only reports availability.
'ibm-granite': {
label: 'IBM Granite 3.8B',
network: 'IBM watsonx.ai',
@@ -178,10 +145,32 @@ const PROVIDERS = {
maxOutput: 4096,
description: 'IBM’s open, enterprise-governed foundation model on watsonx.ai.',
watsonx: true,
- build: () => (watsonxConfig().configured ? { watsonx: true } : null),
},
};
+// Resolve the primary route for a spec: native first-party model when its key is
+// present, otherwise the OpenRouter-routed equivalent, otherwise nothing. `via`
+// records which path won so buildFallback() knows whether OpenRouter is a
+// distinct escape hatch.
+function buildPrimary(spec) {
+ if (spec.watsonx) return watsonxConfig().configured ? { kind: 'watsonx' } : null;
+ const native = spec.native?.();
+ if (native) return { kind: 'model', model: native, via: 'native' };
+ if (spec.openrouterModel && env.OPENROUTER_API_KEY) {
+ return { kind: 'model', model: openrouter()(spec.openrouterModel), via: 'openrouter' };
+ }
+ return null;
+}
+
+// A distinct fallback exists only when the primary ran on a native provider key
+// AND an OpenRouter key is configured — then OpenRouter routes around a native
+// outage (quota exhausted, out of credits, rate-limited). When the primary was
+// already OpenRouter there's nowhere better to retry.
+function buildFallback(spec, primary) {
+ if (primary?.via !== 'native' || !spec.openrouterModel || !env.OPENROUTER_API_KEY) return null;
+ return openrouter()(spec.openrouterModel);
+}
+
function openrouter() {
const provider = createOpenAI({
apiKey: env.OPENROUTER_API_KEY,
@@ -286,7 +275,7 @@ function validateMessages(input) {
function getAvailableProviders() {
return Object.entries(PROVIDERS).map(([key, spec]) => {
- const available = Boolean(spec.build());
+ const available = Boolean(buildPrimary(spec));
return {
key,
label: spec.label,
@@ -327,11 +316,13 @@ export default wrap(async function handler(req, res) {
});
}
- const model = spec.build();
- if (!model) {
+ const primary = buildPrimary(spec);
+ if (!primary) {
return error(res, 503, 'provider_not_configured',
`No API key for ${spec.label}. Add your own key in Account → AI Provider Keys to unlock this model.`);
}
+ // OpenRouter escape hatch for a native-provider outage (quota/credits/rate).
+ const fallbackModel = buildFallback(spec, primary);
let messages;
try {
@@ -359,16 +350,24 @@ export default wrap(async function handler(req, res) {
let firstTokenMs = null;
- // Drains one streamText attempt to the SSE response. Returns true on success.
- // firstTokenMs is set on the first delta; once tokens have been written we are
- // committed and can no longer transparently retry (the client already has
- // partial output).
- const streamOnce = async (budget) => {
+ // Drains one streamText attempt to the SSE response. firstTokenMs is set on
+ // the first delta; once tokens have been written we are committed and can no
+ // longer transparently retry (the client already has partial output).
+ const streamOnce = async (budget, model) => {
+ // The SDK's default onError console.errors the entire provider error object
+ // (the giant 402/429 dumps in the logs). We own error handling via the
+ // retry/fallback chain below, so capture it here instead. Some providers
+ // report a pre-stream failure through onError rather than by throwing from
+ // textStream — surfacing the captured error keeps the chain working either way.
+ let streamErr = null;
const result = streamText({
model,
system,
messages,
maxOutputTokens: budget,
+ onError: ({ error }) => {
+ streamErr = error;
+ },
});
for await (const delta of result.textStream) {
@@ -379,6 +378,11 @@ export default wrap(async function handler(req, res) {
res.write(`data: ${JSON.stringify(delta)}\n\n`);
}
+ // Failure before any token streamed → hand to the retry/fallback logic.
+ // A failure *after* partial output isn't retryable, so we finish cleanly
+ // with whatever was produced.
+ if (streamErr && firstTokenMs === null) throw streamErr;
+
const usage = await result.usage.catch(() => null);
const elapsedMs = Date.now() - t0;
res.write(`event: done\ndata: ${JSON.stringify({
@@ -397,29 +401,44 @@ export default wrap(async function handler(req, res) {
try {
// watsonx.ai isn't an AI SDK model — stream it through the shared client,
// emitting the same first/chunk/done event protocol the page expects.
- if (spec.watsonx) {
+ if (primary.kind === 'watsonx') {
await streamWatsonx(res, { messages, system, maxTokens, t0 });
return;
}
try {
- await streamOnce(maxTokens);
+ await streamOnce(maxTokens, primary.model);
} catch (err) {
- // OpenRouter free tier: "requires more credits, or fewer max_tokens.
- // You requested up to 1024 tokens, but can only afford 788." The
- // upstream tells us the affordable ceiling — retry once at that budget
- // (with a small safety margin) instead of hard-failing. Only safe
- // before any token has been streamed.
- const m = /can only afford (\d+)/i.exec(err?.message || '');
- if (m && firstTokenMs === null && !res.writableEnded) {
- const affordable = Math.max(64, Math.floor(Number(m[1]) * 0.9));
- await streamOnce(affordable);
+ const canRetry = firstTokenMs === null && !res.writableEnded;
+ const affordable = affordableBudget(err);
+ if (affordable && canRetry) {
+ // OpenRouter free tier: "requires more credits, or fewer max_tokens.
+ // You requested up to 1024 tokens, but can only afford 788." Retry once
+ // at the affordable ceiling instead of hard-failing.
+ await streamOnce(affordable, primary.model);
+ } else if (fallbackModel && canRetry && isProviderOutage(err)) {
+ // Native provider is down (over quota, out of credits, rate-limited).
+ // Route the same request through OpenRouter so the user still gets a reply.
+ console.warn(`[brain:${providerKey}] native provider failed (${conciseReason(err)}); falling back to OpenRouter`);
+ try {
+ await streamOnce(maxTokens, fallbackModel);
+ } catch (err2) {
+ const affordable2 = affordableBudget(err2);
+ if (affordable2 && firstTokenMs === null && !res.writableEnded) {
+ await streamOnce(affordable2, fallbackModel);
+ } else {
+ throw err2;
+ }
+ }
} else {
throw err;
}
}
} catch (err) {
const elapsedMs = Date.now() - t0;
+ // The SDK no longer logs for us (onError is captured), so emit one concise
+ // server line for observability — not the multi-screen error object.
+ console.warn(`[brain:${providerKey}] stream failed: ${conciseReason(err)}`);
if (!res.writableEnded) {
try {
res.write(`event: error\ndata: ${JSON.stringify({
@@ -433,3 +452,28 @@ export default wrap(async function handler(req, res) {
}
}
});
+
+// OpenRouter (and some OpenAI-compatible backends) reject a request whose
+// max_tokens exceeds the caller's remaining credit, naming the affordable
+// ceiling: "...but can only afford 788." Returns that ceiling (with a safety
+// margin) so we can retry within budget, or null when the error isn't this.
+function affordableBudget(err) {
+ const m = /can only afford (\d+)/i.exec(err?.message || '');
+ return m ? Math.max(64, Math.floor(Number(m[1]) * 0.9)) : null;
+}
+
+// A provider-side outage we can route around (vs a caller/content error that
+// every provider would reject identically): rate-limit, quota exhaustion, out of
+// credits, or an upstream 5xx.
+function isProviderOutage(err) {
+ const status = Number(err?.statusCode || err?.cause?.statusCode || 0);
+ if (status === 429 || status === 402 || status >= 500) return true;
+ const msg = `${err?.message || ''} ${err?.cause?.message || ''}`;
+ return /quota|insufficient_quota|rate.?limit|too many requests|billing|exceeded your current|requires more credits|overloaded|temporarily unavailable|maxRetriesExceeded/i.test(msg);
+}
+
+// One-line, length-capped error summary for server logs.
+function conciseReason(err) {
+ const msg = (err?.message || String(err)).replace(/\s+/g, ' ').trim();
+ return msg.length > 160 ? `${msg.slice(0, 157)}…` : msg;
+}
diff --git a/package.json b/package.json
index 2b4d846ec..0d52d45e3 100644
--- a/package.json
+++ b/package.json
@@ -52,7 +52,7 @@
]
},
"scripts": {
- "postinstall": "(node scripts/build-cache.mjs check agent-payments-sdk agent-payments-sdk/src agent-payments-sdk/package.json || (npm run build --prefix agent-payments-sdk && node scripts/build-cache.mjs stamp agent-payments-sdk agent-payments-sdk/src agent-payments-sdk/package.json)) && (node scripts/fix-pump-sdk-esm.mjs & node scripts/fix-x402-extensions-esm.mjs & node scripts/copy-three-decoders.mjs & node scripts/setup-claude-skills.mjs & wait)",
+ "postinstall": "(node scripts/build-cache.mjs check agent-payments-sdk agent-payments-sdk/src agent-payments-sdk/package.json || (npm run build --prefix agent-payments-sdk && node scripts/build-cache.mjs stamp agent-payments-sdk agent-payments-sdk/src agent-payments-sdk/package.json)) && (node scripts/fix-pump-sdk-esm.mjs & node scripts/fix-x402-extensions-esm.mjs & node scripts/fix-colyseus-storage.mjs & node scripts/copy-three-decoders.mjs & node scripts/setup-claude-skills.mjs & wait)",
"dev": "vite --port 3000",
"dev:multi": "npm run dev --prefix multiplayer",
"dev:walk-all": "node scripts/dev-walk-all.mjs",
diff --git a/scripts/avatar-bg-probe-server.mjs b/scripts/avatar-bg-probe-server.mjs
new file mode 100644
index 000000000..ffff59b15
--- /dev/null
+++ b/scripts/avatar-bg-probe-server.mjs
@@ -0,0 +1,25 @@
+import http from 'node:http';
+import fs from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+const ROOT = path.resolve(__dirname, '..');
+const MIME = {
+ '.html': 'text/html', '.js': 'application/javascript', '.mjs': 'application/javascript',
+ '.json': 'application/json', '.glb': 'model/gltf-binary', '.png': 'image/png', '.jpg': 'image/jpeg',
+};
+
+http.createServer((req, res) => {
+ const url = (req.url || '/').split('?')[0];
+ let file;
+ if (url === '/' || url === '/probe') file = path.join(ROOT, 'scripts/avatar-bg-probe.html');
+ else if (url.startsWith('/agent-3d/')) file = path.join(ROOT, 'dist-lib', url.replace(/^\/agent-3d\/(latest|\d[\d.]*)\//, ''));
+ else if (url.startsWith('/avatars/')) file = path.join(ROOT, 'public', url);
+ else if (url.startsWith('/animations/')) file = path.join(ROOT, 'public', url);
+ else file = path.join(ROOT, 'public', url);
+ if (!fs.existsSync(file) || !fs.statSync(file).isFile()) { res.writeHead(404); res.end('nf: ' + url); return; }
+ res.setHeader('Content-Type', MIME[path.extname(file).toLowerCase()] || 'application/octet-stream');
+ res.setHeader('Access-Control-Allow-Origin', '*');
+ fs.createReadStream(file).pipe(res);
+}).listen(4599, () => console.log('probe server on http://localhost:4599'));
diff --git a/scripts/avatar-bg-probe.html b/scripts/avatar-bg-probe.html
new file mode 100644
index 000000000..af9497075
--- /dev/null
+++ b/scripts/avatar-bg-probe.html
@@ -0,0 +1,32 @@
+<!doctype html>
+<html>
+<head>
+ <meta charset="utf-8" />
+ <style>
+ html, body { margin: 0; background: #f3efe6; }
+ .wrap { padding: 40px; background: #f3efe6; }
+ /* Mirror Message.svelte avatar container */
+ .btn { display:flex; width:140px; height:280px; border-radius:6px; }
+ .span { width:100%; height:100%; overflow:hidden; display:inline-block; border-radius:inherit; }
+ </style>
+ <script type="module" src="/agent-3d/latest/agent-3d.js"></script>
+</head>
+<body>
+ <div class="wrap">
+ <div class="btn">
+ <span class="span">
+ <agent-3d
+ src="/avatars/cz.glb"
+ mode="inline"
+ width="140"
+ height="280"
+ background="transparent"
+ kiosk
+ name-plate="off"
+ style="width:100%;height:100%;display:block;"
+ ></agent-3d>
+ </span>
+ </div>
+ </div>
+</body>
+</html>
diff --git a/scripts/avatar-bg-probe.mjs b/scripts/avatar-bg-probe.mjs
new file mode 100644
index 000000000..02b8e19ec
--- /dev/null
+++ b/scripts/avatar-bg-probe.mjs
@@ -0,0 +1,40 @@
+import puppeteer from 'puppeteer';
+
+const browser = await puppeteer.launch({
+ headless: 'new',
+ args: ['--no-sandbox', '--use-gl=swiftshader', '--enable-webgl', '--ignore-gpu-blocklist', '--enable-unsafe-swiftshader'],
+});
+const page = await browser.newPage();
+await page.setViewport({ width: 400, height: 420, deviceScaleFactor: 2 });
+page.on('console', (m) => console.log('[page]', m.text()));
+page.on('pageerror', (e) => console.log('[pageerr]', e.message));
+await page.goto('http://localhost:4599/', { waitUntil: 'networkidle0', timeout: 30000 });
+// Give the GLB + WebGL time to render
+await new Promise((r) => setTimeout(r, 6000));
+
+const info = await page.evaluate(() => {
+ const el = document.querySelector('agent-3d');
+ const out = { found: !!el };
+ if (el) {
+ const cs = getComputedStyle(el);
+ out.hostBg = cs.backgroundColor;
+ const sr = el.shadowRoot;
+ out.hasShadow = !!sr;
+ if (sr) {
+ const canvas = sr.querySelector('canvas');
+ out.hasCanvas = !!canvas;
+ if (canvas) out.canvasBg = getComputedStyle(canvas).backgroundColor;
+ const stage = sr.querySelector('.stage');
+ if (stage) out.stageBg = getComputedStyle(stage).backgroundColor;
+ const poster = sr.querySelector('.poster');
+ if (poster) out.posterStyle = { bg: getComputedStyle(poster).backgroundColor, img: getComputedStyle(poster).backgroundImage, opacity: getComputedStyle(poster).opacity };
+ // list direct shadow children with their bg
+ out.children = [...sr.children].map((c) => ({ tag: c.tagName, cls: c.className, bg: getComputedStyle(c).backgroundColor, op: getComputedStyle(c).opacity }));
+ }
+ }
+ return out;
+});
+console.log(JSON.stringify(info, null, 2));
+await page.screenshot({ path: 'scripts/avatar-bg-probe.png' });
+console.log('screenshot saved');
+await browser.close();
diff --git a/scripts/fix-colyseus-storage.mjs b/scripts/fix-colyseus-storage.mjs
new file mode 100644
index 000000000..f9a3d4643
--- /dev/null
+++ b/scripts/fix-colyseus-storage.mjs
@@ -0,0 +1,108 @@
+// Patches colyseus.js after install to harden its IndexedDB storage fallback.
+//
+// Colyseus stores the room reconnection token in browser storage. It prefers
+// window.localStorage, but falls back to an IndexedDB store ('_colyseus_storage')
+// when localStorage access throws — which happens when site data is blocked, in
+// some privacy modes, and inside Web Workers.
+//
+// The shipped IndexedDBStorage is fragile in two ways that surface as a flood of
+// "Uncaught InvalidStateError: Failed to execute 'transaction' on 'IDBDatabase':
+// The database connection is closing.":
+// 1. tx() calls db.transaction(...) with no guard, so a connection that is
+// closing/closed during page teardown or a versionchange throws uncaught.
+// 2. The open promise only handles onsuccess; an onerror/onblocked open leaves
+// dbPromise pending forever, hanging every read/write that awaits it.
+//
+// We wrap the transaction in a try/catch (bail to a no-op on failure) and resolve
+// the open promise to null on error/blocked so awaiters never hang. Idempotent;
+// survives `npm ci` via postinstall.
+
+import { existsSync, readFileSync, writeFileSync } from 'node:fs';
+import { dirname, join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const root = dirname(fileURLToPath(import.meta.url));
+const repo = dirname(root);
+
+const TARGETS = [
+ 'node_modules/colyseus.js/build/esm/Storage.mjs',
+ 'node_modules/colyseus.js/build/cjs/Storage.js',
+ 'node_modules/colyseus.js/lib/Storage.js',
+];
+
+const MARKER = 'request.onblocked = () => resolve(null);';
+
+// Resolve the open promise on error/blocked, not just success, so awaiters of
+// dbPromise never hang when the database can't be opened. `\1` captures the
+// newline + indentation and is reused as the line separator.
+const OPEN_RE =
+ /(\n[ \t]*)request\.onupgradeneeded = \(\) => request\.result\.createObjectStore\('store'\);\1request\.onsuccess = \(\) => resolve\(request\.result\);/;
+
+// Guard db.transaction(): a closing/closed connection throws synchronously here.
+const TX_RE =
+ /(\n[ \t]*)const store = db\.transaction\('store', mode\)\.objectStore\('store'\);\1return fn\(store\);/;
+
+// getItem awaits tx(), which now yields undefined when the store is unreachable.
+// Guard the null request and resolve the read on error so it never hangs.
+const GET_RE =
+ /(\n[ \t]*)return new Promise\(\(resolve\) => \{(\n[ \t]*)request\.onsuccess = \(\) => resolve\(request\.result\);/;
+
+let patched = 0;
+let skipped = 0;
+
+for (const rel of TARGETS) {
+ const file = join(repo, rel);
+ if (!existsSync(file)) continue;
+
+ let src = readFileSync(file, 'utf8');
+ if (src.includes(MARKER)) {
+ skipped++;
+ continue;
+ }
+
+ const before = src;
+
+ src = src.replace(
+ OPEN_RE,
+ (_m, lead) =>
+ `${lead}request.onupgradeneeded = () => request.result.createObjectStore('store');` +
+ `${lead}request.onsuccess = () => resolve(request.result);` +
+ `${lead}request.onerror = () => resolve(null);` +
+ `${lead}request.onblocked = () => resolve(null);`,
+ );
+
+ src = src.replace(
+ TX_RE,
+ (_m, lead) =>
+ `${lead}let store;` +
+ `${lead}try { store = db && db.transaction('store', mode).objectStore('store'); }` +
+ `${lead}catch (e) { return undefined; }` +
+ `${lead}if (!store) return undefined;` +
+ `${lead}return fn(store);`,
+ );
+
+ src = src.replace(
+ GET_RE,
+ (_m, lead, inner) =>
+ `${lead}if (!request) return null;` +
+ `${lead}return new Promise((resolve) => {` +
+ `${inner}request.onsuccess = () => resolve(request.result);` +
+ `${inner}request.onerror = () => resolve(null);`,
+ );
+
+ if (src === before) {
+ console.warn(`[fix-colyseus-storage] no match in ${rel} — colyseus internals may have changed`);
+ continue;
+ }
+
+ writeFileSync(file, src);
+ patched++;
+}
+
+if (patched > 0) {
+ console.log(`[fix-colyseus-storage] hardened IndexedDB storage in ${patched} file(s)`);
+} else if (skipped > 0) {
+ console.log('[fix-colyseus-storage] already patched');
+} else {
+ console.log('[fix-colyseus-storage] colyseus.js not installed, skipping');
+}
diff --git a/scripts/webgltest.mjs b/scripts/webgltest.mjs
new file mode 100644
index 000000000..8201b3151
--- /dev/null
+++ b/scripts/webgltest.mjs
@@ -0,0 +1,10 @@
+import puppeteer from 'puppeteer';
+const b = await puppeteer.launch({headless:'new', args:['--no-sandbox','--use-gl=swiftshader','--enable-webgl','--ignore-gpu-blocklist','--enable-unsafe-swiftshader']});
+const p = await b.newPage();
+const r = await p.evaluate(() => {
+ const c = document.createElement('canvas');
+ const gl = c.getContext('webgl2') || c.getContext('webgl');
+ return { ok: !!gl, vendor: gl ? gl.getParameter(gl.VERSION) : null };
+});
+console.log(JSON.stringify(r));
+await b.close();
diff --git a/src/game/coincommunities.js b/src/game/coincommunities.js
index b9fe87b8e..080fac252 100644
--- a/src/game/coincommunities.js
+++ b/src/game/coincommunities.js
@@ -49,7 +49,7 @@ import { isServicePanelOpen } from './npc/npc-services.js';
import { VoiceChat, voiceSupported } from './voice-chat.js';
import { requestHolderPass, signInWithX, ensureSolanaWallet, relinkSolanaWallet, getSession, getWorldGate, setWorldGate } from '../community/town-auth.js';
import { ensurePlayAccess } from './play-gate.js';
-import { clearStoredPass, fetchPlayConfig, signInToPlay, loadStoredPass, storePass } from './play-auth.js';
+import { clearStoredPass, refreshPlayPass, loadStoredPass, storePass } from './play-auth.js';
import { PlaySystems } from './play-systems.js';
import { PlayOnboard } from './play-onboard.js';
import { WorldHudSystem } from './hud/index.js';
@@ -939,11 +939,11 @@ export class CoinCommunities {
}
// Silent mid-session pass refresh. Runs once the player is in a world; wakes
- // up 2 min before the pass expires, re-runs the sign+verify flow silently (no
- // UI), and updates this.playPass so the next reconnect uses the fresh token.
- // Re-checks the chain, so a wallet that offloaded its tokens gets evicted here
- // rather than on the next reconnect. Cancels automatically when leave() tears
- // the net down.
+ // up 2 min before the pass expires and renews it off the still-valid pass — no
+ // wallet prompt, since possession of an unexpired pass already proves the wallet.
+ // Updates this.playPass so the next reconnect uses the fresh token, and re-checks
+ // the chain, so a wallet that offloaded its tokens gets evicted here rather than
+ // on the next reconnect. Cancels automatically when leave() tears the net down.
_schedulePassRefresh() {
clearTimeout(this._passRefreshTimer);
if (!this.playPass || !this.account) return; // gate was off when we entered
@@ -955,11 +955,11 @@ export class CoinCommunities {
}
async _doPassRefresh() {
- if (this.phase !== 'world' || !this.account) return;
+ if (this.phase !== 'world' || !this.account || !this.playPass) return;
try {
- const cfg = await fetchPlayConfig();
- if (!cfg.required) return; // gate turned off — nothing to refresh
- const res = await signInToPlay({ nonce: cfg.nonce });
+ // Silent renewal: the current pass is still valid (we fire 2 min early), so
+ // the server re-issues off it after re-reading the chain — no wallet prompt.
+ const res = await refreshPlayPass(this.playPass);
if (res.ok && res.playPass) {
this.playPass = res.playPass;
storePass(res);
@@ -973,7 +973,18 @@ export class CoinCommunities {
this.leave();
this._playReady = this._ensurePlayAccess();
}
- } catch {
+ } catch (err) {
+ // The pass expired or was rejected (we missed the window): a silent renew is
+ // impossible now, so a fresh signed sign-in is the only way back. Surface the
+ // gate once rather than retrying a renewal that can never succeed.
+ if (err?.code === 'pass_invalid') {
+ clearStoredPass();
+ this.playPass = '';
+ this.ui.toast('Your session expired — sign in again to keep playing.', 'warn');
+ this.leave();
+ this._playReady = this._ensurePlayAccess();
+ return;
+ }
// Network hiccup — try again in 30 s rather than breaking the session.
clearTimeout(this._passRefreshTimer);
this._passRefreshTimer = setTimeout(() => this._doPassRefresh(), 30_000);
diff --git a/src/marketplace.js b/src/marketplace.js
index 89c8d77e1..7c9ca1334 100644
--- a/src/marketplace.js
+++ b/src/marketplace.js
@@ -688,7 +688,6 @@ function renderThemePicks() {
disable-zoom
disable-pan
disable-tap
- camera-controls
exposure="1.05"
shadow-intensity="0.5"
tone-mapping="aces"
diff --git a/tests/api/avatar-og.test.js b/tests/api/avatar-og.test.js
index 7f882e648..883f88c43 100644
--- a/tests/api/avatar-og.test.js
+++ b/tests/api/avatar-og.test.js
@@ -181,8 +181,8 @@ describe('GET /api/avatar/:id/og — server render path', () => {
expect(sqlArgs).toContain('a3');
});
- it('falls back to logo on GLB-too-large precheck', async () => {
- // 50 MB content-length triggers the 10 MB cap.
+ it('falls back to the named card on GLB-too-large precheck', async () => {
+ // 50 MB content-length triggers the 12 MB cap.
globalThis.fetch = vi.fn(async () => ({
ok: true,
headers: { get: (h) => (h.toLowerCase() === 'content-length' ? String(50 * 1024 * 1024) : null) },
@@ -199,13 +199,15 @@ describe('GET /api/avatar/:id/og — server render path', () => {
const res = mkRes();
await handler(req, res);
- expect(res.statusCode).toBe(302);
- expect(res._h.location).toMatch(/\/assets\/og-image\.png$/);
+ // A branded card naming the avatar beats the anonymous site logo for crawlers.
+ expect(res.statusCode).toBe(200);
+ expect(res._h['content-type']).toMatch(/image\/svg/);
+ expect(String(res._body)).toContain('Big');
expect(renderGlbToPngMock).not.toHaveBeenCalled();
expect(putObjectMock).not.toHaveBeenCalled();
});
- it('falls back to logo when the renderer throws', async () => {
+ it('falls back to the named card when the renderer throws', async () => {
getAvatarMock.mockResolvedValueOnce({
id: 'a5',
name: 'Err',
@@ -219,8 +221,9 @@ describe('GET /api/avatar/:id/og — server render path', () => {
const res = mkRes();
await handler(req, res);
- expect(res.statusCode).toBe(302);
- expect(res._h.location).toMatch(/\/assets\/og-image\.png$/);
+ expect(res.statusCode).toBe(200);
+ expect(res._h['content-type']).toMatch(/image\/svg/);
+ expect(String(res._body)).toContain('Err');
expect(putObjectMock).not.toHaveBeenCalled();
expect(sqlMock).not.toHaveBeenCalled();
});
@@ -263,11 +266,11 @@ describe('GET /api/avatar/:id/og — server render path', () => {
expect(res2.statusCode).toBe(200);
});
- it('ignores forwarded host and anchors the fallback redirect on APP_ORIGIN', async () => {
- // Previously this endpoint built the redirect from `x-forwarded-host`,
- // which let a caller redirect OG crawlers (or end users) to an
- // attacker-controlled host by spoofing the header. The handler now
- // always uses env.APP_ORIGIN.
+ it('serves the self-contained card on render failure, never an attacker-controllable redirect', async () => {
+ // The fallback used to 302 to a logo URL built from request host headers,
+ // which a spoofed `x-forwarded-host` could repoint at an attacker site. The
+ // failure path now renders a self-contained SVG card inline — no Location
+ // header, so the header can't influence where a crawler is sent.
getAvatarMock.mockResolvedValueOnce({
id: 'a7',
name: 'X',
@@ -286,7 +289,8 @@ describe('GET /api/avatar/:id/og — server render path', () => {
});
const res = mkRes();
await handler(req, res);
- expect(res.statusCode).toBe(302);
- expect(res._h.location).toBe('http://localhost:3000/assets/og-image.png');
+ expect(res.statusCode).toBe(200);
+ expect(res._h['content-type']).toMatch(/image\/svg/);
+ expect(res._h.location).toBeUndefined();
});
});