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.

chore: avatar-og key repair, NVIDIA NIM flux probe, security/test CI + renovate, changelog refresh

nirholas4969912e2443
diff --git a/.github/workflows/security-scan.yml b/.github/workflows/security-scan.yml
new file mode 100644
index 000000000..19b6fbe89
--- /dev/null
+++ b/.github/workflows/security-scan.yml
@@ -0,0 +1,33 @@
+# Dependency vulnerability scanning. OSV-Scanner checks every lockfile in the
+# monorepo against the OSV database (npm advisories, GHSA, CVEs) on each push,
+# PR, and a weekly schedule — so a vulnerable transitive dependency becomes a
+# red check instead of a silent liability. Complements (does not replace)
+# updating dependencies: Renovate proposes the bumps, this catches the gaps.
+
+name: Security scan
+
+on:
+ push:
+ branches: [main]
+ pull_request:
+ schedule:
+ # Weekly sweep: catches advisories published against versions already
+ # pinned in the lockfiles, with no commit needed to trigger it.
+ - cron: '17 6 * * 1'
+
+permissions:
+ contents: read
+
+jobs:
+ osv-scan:
+ runs-on: ubuntu-latest
+ timeout-minutes: 15
+ steps:
+ - uses: actions/checkout@v6
+
+ - name: Run OSV-Scanner
+ uses: google/osv-scanner-action/osv-scanner-action@v2
+ with:
+ scan-args: |-
+ --recursive
+ ./
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
new file mode 100644
index 000000000..458b2107f
--- /dev/null
+++ b/.github/workflows/test.yml
@@ -0,0 +1,93 @@
+# CI test gate — the check that keeps main shippable.
+#
+# Lighthouse/page-audit run against Vercel preview deploys *after* a build;
+# this workflow is the pre-merge gate that runs the actual test suites on
+# every push and PR, so a commit that breaks a handler, an SDK, or an e2e
+# flow fails a required check instead of reaching production. With multiple
+# concurrent agents committing to main, this is the only thing that makes
+# "tests pass" a property of the repo rather than of whoever last ran them.
+
+name: Tests
+
+on:
+ push:
+ branches: [main]
+ pull_request:
+
+concurrency:
+ group: tests-${{ github.workflow }}-${{ github.ref }}
+ cancel-in-progress: ${{ github.event_name == 'pull_request' }}
+
+jobs:
+ vitest:
+ runs-on: ubuntu-latest
+ timeout-minutes: 45
+ steps:
+ - uses: actions/checkout@v6
+
+ - uses: actions/setup-node@v6
+ with:
+ node-version: 24
+ cache: npm
+
+ # Root install also builds agent-payments-sdk via postinstall.
+ - name: Install dependencies
+ run: npm ci
+
+ # solana-agent-sdk is file:-linked but not an npm workspace, so the root
+ # install neither installs its devDependencies nor builds its dist/ —
+ # both are required before any test that imports @three-ws/solana-agent.
+ - name: Build solana-agent-sdk
+ run: |
+ npm ci --prefix solana-agent-sdk
+ npm run build --prefix solana-agent-sdk
+
+ # data/_generated/* is gitignored build output that several api/ handlers
+ # read at import time. Only the network-free generators are needed here.
+ - name: Generate data artifacts
+ run: |
+ node scripts/build-skill-metadata.mjs
+ node scripts/build-local-skill-packs.mjs
+
+ - name: Run vitest
+ run: npx vitest run
+
+ e2e:
+ runs-on: ubuntu-latest
+ timeout-minutes: 30
+ steps:
+ - uses: actions/checkout@v6
+
+ - uses: actions/setup-node@v6
+ with:
+ node-version: 24
+ cache: npm
+
+ - name: Install dependencies
+ run: npm ci
+
+ - name: Build solana-agent-sdk
+ run: |
+ npm ci --prefix solana-agent-sdk
+ npm run build --prefix solana-agent-sdk
+
+ - name: Generate data artifacts
+ run: |
+ node scripts/build-skill-metadata.mjs
+ node scripts/build-local-skill-packs.mjs
+
+ - name: Install Playwright Chromium
+ run: npx playwright install --with-deps chromium
+
+ # playwright.config.js starts the Vite dev server itself (webServer) and
+ # budgets for the cold three.js transform on a CI box.
+ - name: Run Playwright e2e
+ run: npx playwright test
+
+ - name: Upload traces on failure
+ if: failure()
+ uses: actions/upload-artifact@v7
+ with:
+ name: playwright-traces
+ path: test-results/
+ if-no-files-found: ignore
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e06467942..bd86e96f5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **Accurate uptime on the x402 Provider Hub** — The payment directory was counting every unpaid x402 discovery request (the protocol's standard 402 challenge) as a failed call, dragging three.ws endpoint success rates down even when every endpoint was healthy. Telemetry now reports only real payment attempts, so the published uptime reflects actual service health. `[fix, infra]`
- **Avatar pages back online after image-engine outage** — Fetching an individual avatar was failing with a server error, which also broke the walking avatar on the home page. The image-processing engine the avatar dress-up baker relies on failed to load in production and took the whole endpoint down with it. Avatar lookups now load independently of the baker, and the missing image libraries ship with the deployment, so avatar pages and the home hero are back. `[fix, infra]`
+- **Avatar preview images load reliably** — Fixed a bug where some community avatars — including the pinned home-town cast — showed a broken preview image in the /play lobby and gallery instead of their portrait. The shareable social-card image for those avatars now generates and serves correctly too, so links posted to X and Discord render a proper preview. (`/play`) `[fix]`
- **Built-in AI stays up when a provider runs dry** — The platform's built-in AI (chat, the Brain model workbench, embedded site widgets, tutor, fact-checker, persona tools, agent talk, the transaction explainer) now runs on a deeper safety net. Three independent free lanes — Groq, OpenRouter (with automatic rotation across multiple accounts when one runs out of credits or hits a rate limit), and NVIDIA-hosted models — always serve first, and if every one of them fails, the request quietly falls through to a paid backstop instead of showing you an error. Paid x402 endpoints that previously returned errors during a provider outage now degrade the same way. Agent memory search now runs on a free embeddings lane with the paid provider demoted to backup, and embedded agents configured for a paid model degrade to the free lanes instead of erroring when that provider's key is dead. `[improvement, infra]`
- **Embedded avatar chat replies again** — Avatars embedded straight from their public profile — the one-line widget on the homepage and anywhere else the avatar URL is dropped in — went silent when you typed a message: the chat box accepted your text but the avatar never answered. The built-in AI now recognizes a plain public avatar and serves it the free we-pay model with the same per-avatar rate and usage limits, so embedded chat responds out of the box. `[fix]`
- **Faster, quieter agents directory and site-wide page polish** — The on-chain agents directory now loads from our server-side index instead of contacting every agent's metadata host from your browser — pages render faster and no longer spray network errors. Also: the pump.fun cockpit's sidebar pages are now shareable deep links, mobile nav and footer links meet touch-target guidelines, anonymous visitors no longer trigger failed sign-in requests on Walk and Create, and assorted dead links were removed. (`/agents`) `[improvement, fix]`
diff --git a/api/_lib/alerts.js b/api/_lib/alerts.js
new file mode 100644
index 000000000..149715ed7
--- /dev/null
+++ b/api/_lib/alerts.js
@@ -0,0 +1,89 @@
+// Real-time ops alerts → Telegram. Errors should find the operator, not wait
+// to be hunted: serverError()/wrap() report 5xx server faults here and
+// api/client-errors.js reports browser errors, so production failures surface
+// in an ops channel seconds after they happen.
+//
+// Env (both required, else every call is a silent no-op — dev and tests need
+// no config):
+// TELEGRAM_BOT_TOKEN — same bot the changelog pusher uses
+// TELEGRAM_ALERTS_CHAT_ID — PRIVATE ops chat/channel id. Never the public
+// holders' channel: alerts carry stack traces,
+// URLs, and IPs.
+//
+// Noise control, because an alert channel that floods gets muted and then it
+// protects nothing:
+// - per-signature dedup: one alert per unique error signature per hour
+// - global ceiling: max 20 alerts per hour, then one "throttled" notice
+// Both windows live in the shared cache (Upstash Redis when configured, so
+// dedup holds across serverless instances; in-memory otherwise).
+//
+// Fire-and-forget like sentry.js: a hard 2.5s abort, every failure swallowed.
+// An alerting pipeline must never delay or break the request it's reporting on.
+
+import { createHash } from 'node:crypto';
+import { cacheGet, cacheSet } from './cache.js';
+
+const DEDUP_TTL_S = 60 * 60;
+const GLOBAL_LIMIT_PER_HOUR = 20;
+
+function config() {
+ const token = process.env.TELEGRAM_BOT_TOKEN;
+ const chatId = process.env.TELEGRAM_ALERTS_CHAT_ID;
+ return token && chatId ? { token, chatId } : null;
+}
+
+function signatureOf(text) {
+ return createHash('sha256').update(text).digest('hex').slice(0, 16);
+}
+
+function post(cfg, text) {
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(), 2500);
+ fetch(`https://api.telegram.org/bot${cfg.token}/sendMessage`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({
+ chat_id: cfg.chatId,
+ text: text.slice(0, 4000), // Telegram message hard limit is 4096
+ disable_web_page_preview: true,
+ }),
+ signal: controller.signal,
+ keepalive: true,
+ })
+ .catch(() => {})
+ .finally(() => clearTimeout(timer));
+}
+
+/**
+ * Send an ops alert. Deduped and throttled; safe to call on every error path.
+ * @param {string} title one-line summary, e.g. "5xx in /api/chat"
+ * @param {string} [detail] body lines (message, ref, page, stack head)
+ * @param {{ signature?: string }} [opts] override the dedup signature when
+ * the title/detail contain per-event noise (ids, refs) that would
+ * defeat dedup.
+ */
+export async function sendOpsAlert(title, detail = '', opts = {}) {
+ const cfg = config();
+ if (!cfg) return;
+ try {
+ const sig = signatureOf(opts.signature || `${title}\n${detail}`);
+ if (await cacheGet(`alert:dedup:${sig}`)) return;
+ await cacheSet(`alert:dedup:${sig}`, 1, DEDUP_TTL_S);
+
+ const hourBucket = `alert:global:${Math.floor(Date.now() / 3_600_000)}`;
+ const sent = Number((await cacheGet(hourBucket)) || 0);
+ if (sent >= GLOBAL_LIMIT_PER_HOUR) {
+ if (sent === GLOBAL_LIMIT_PER_HOUR) {
+ await cacheSet(hourBucket, sent + 1, DEDUP_TTL_S);
+ post(cfg, `⚠️ three.ws alerts throttled — over ${GLOBAL_LIMIT_PER_HOUR}/h. Check the logs directly.`);
+ }
+ return;
+ }
+ await cacheSet(hourBucket, sent + 1, DEDUP_TTL_S);
+
+ const env = process.env.VERCEL_ENV || 'development';
+ post(cfg, `🔴 three.ws [${env}] ${title}${detail ? `\n${detail}` : ''}`);
+ } catch {
+ /* alerting is best-effort, never throws into the caller */
+ }
+}
diff --git a/api/_lib/elevenlabs.js b/api/_lib/elevenlabs.js
index 121f8a77c..273ee9bf3 100644
--- a/api/_lib/elevenlabs.js
+++ b/api/_lib/elevenlabs.js
@@ -5,7 +5,6 @@
// proxy (api/tts/*) and the agent-voice endpoints (api/agents/:id/voice) don't
// each reimplement them. Lazy: nothing here touches the network at import time.
-import { ElevenLabsClient } from '@elevenlabs/elevenlabs-js';
import { env } from './env.js';
export const ELEVEN_BASE = 'https://api.elevenlabs.io/v1';
@@ -130,6 +129,10 @@ export async function createClonedVoice({ name, description, files }) {
const apiKey = elevenApiKey();
if (!apiKey) throw upstreamError('ElevenLabs is not configured', 503);
+ // Dynamic import: the official SDK's module graph takes ~5s to evaluate,
+ // which would otherwise be paid on every cold start of every handler that
+ // imports this lib — only the clone path actually needs it.
+ const { ElevenLabsClient } = await import('@elevenlabs/elevenlabs-js');
const client = new ElevenLabsClient({ apiKey });
let result;
try {
diff --git a/api/_lib/r2.js b/api/_lib/r2.js
index 95e91289d..e9a72d78e 100644
--- a/api/_lib/r2.js
+++ b/api/_lib/r2.js
@@ -114,6 +114,15 @@ function isAbsoluteUrl(key) {
return typeof key === 'string' && /^https?:\/\//i.test(key);
}
+// A thumbnail_key written by the pre-fix avatar-OG cache (it derived `_og.png`
+// from an absolute storage_key, so the "key" was a full origin URL that
+// publicUrl() passes through verbatim — pointing at the site instead of the R2
+// CDN, where no object exists). Such keys 404; callers use this to drop or
+// self-heal them rather than surface a broken image.
+export function isLegacyOgThumbnailKey(thumbnailKey) {
+ return /^https?:\/\/.*_og\.png$/i.test(String(thumbnailKey || ''));
+}
+
function encodeR2Key(key) {
return key.split('/').map(encodeURIComponent).join('/');
}
diff --git a/api/_mcp3d/text-to-image.js b/api/_mcp3d/text-to-image.js
index 530721c6b..acbf7203a 100644
--- a/api/_mcp3d/text-to-image.js
+++ b/api/_mcp3d/text-to-image.js
@@ -15,7 +15,7 @@
// REPLICATE_TXT2IMG_MODEL — optional Replicate model override
//
// NIM lane: black-forest-labs/flux.1-schnell — Apache-2.0, commercial-OK, served
-// free on the NVIDIA NIM catalog as a base64 PNG (no poll; returns inline).
+// free on the NVIDIA NIM catalog as base64 JPEG (no poll; returns inline).
// Replicate backstop: black-forest-labs/flux-schnell — same family, $0.003/run.
const REPLICATE_BASE = 'https://api.replicate.com/v1';
@@ -74,14 +74,22 @@ function parseRetryAfter(headers, message) {
return 10;
}
-// Persist a base64 PNG to object storage and return a durable https URL.
+// Persist a base64 image to object storage and return a durable https URL.
// Downstream image-to-3D providers take URLs (Replicate caps inline data URIs at
-// ~256 KB — a 1024px PNG blows straight past that), so neither the Vertex inline
+// ~256 KB — a 1024px image blows straight past that), so neither the Vertex inline
// data URI nor the NIM base64 artifact can be forwarded as-is.
-async function persistPngBase64(b64) {
+//
+// Format is sniffed from the magic bytes so the object key extension and
+// Content-Type always match the real payload: NIM FLUX returns JPEG artifacts
+// (probed live — see tasks/nvidia-nim/probes/flux.md) while Vertex Imagen
+// returns PNG. Unknown bytes keep the PNG label (legacy behavior).
+async function persistImageBase64(b64) {
const { putObject, publicUrl } = await import('../_lib/r2.js');
- const key = `forge/refs/${globalThis.crypto.randomUUID()}.png`;
- await putObject({ key, body: Buffer.from(b64, 'base64'), contentType: 'image/png' });
+ const body = Buffer.from(b64, 'base64');
+ const isJpeg = body.length > 2 && body[0] === 0xff && body[1] === 0xd8 && body[2] === 0xff;
+ const ext = isJpeg ? 'jpg' : 'png';
+ const key = `forge/refs/${globalThis.crypto.randomUUID()}.${ext}`;
+ await putObject({ key, body, contentType: isJpeg ? 'image/jpeg' : 'image/png' });
return publicUrl(key);
}
@@ -90,7 +98,7 @@ async function persistPngBase64(b64) {
async function persistDataUriImage(result) {
if (!result?.imageUrl?.startsWith('data:')) return result;
const b64 = result.imageUrl.split(',')[1] || '';
- return { ...result, imageUrl: await persistPngBase64(b64) };
+ return { ...result, imageUrl: await persistImageBase64(b64) };
}
// Free lane: FLUX.1-schnell on NVIDIA NIM. Synchronous invoke — the artifact
@@ -112,10 +120,11 @@ async function nimFluxImage(prompt, aspectRatio) {
accept: 'application/json',
'content-type': 'application/json',
},
+ // No cfg_scale: schnell is guidance-distilled and the endpoint enforces
+ // cfg_scale <= 0 for it (sending 3.5 422s — verified live 2026-06-11).
body: JSON.stringify({
prompt,
mode: 'base',
- cfg_scale: 3.5,
width,
height,
seed: 0,
@@ -147,7 +156,7 @@ async function nimFluxImage(prompt, aspectRatio) {
const data = await res.json().catch(() => ({}));
const b64 = data?.artifacts?.[0]?.base64;
if (!b64) throw new Error('nim flux finished but produced no image');
- return { imageUrl: await persistPngBase64(b64), model: NIM_FLUX_MODEL };
+ return { imageUrl: await persistImageBase64(b64), model: NIM_FLUX_MODEL };
}
// Generate a single image from a text prompt.
diff --git a/api/avatar-og.js b/api/avatar-og.js
index 3aed4dca8..32f76a417 100644
--- a/api/avatar-og.js
+++ b/api/avatar-og.js
@@ -23,7 +23,7 @@ import { sql } from './_lib/db.js';
import { getAvatar } from './_lib/avatars.js';
import { DEMO_AVATARS } from './_lib/demo-avatars.js';
import { cors, wrap } from './_lib/http.js';
-import { publicUrl, putObject } from './_lib/r2.js';
+import { publicUrl, putObject, isLegacyOgThumbnailKey } from './_lib/r2.js';
import { renderGlbToPng } from './_lib/render-glb.js';
const CACHE_CARD_OK = 'public, max-age=3600, s-maxage=86400, stale-while-revalidate=604800';
@@ -84,12 +84,22 @@ export default wrap(async (req, res) => {
// Cached thumbnail — either client-uploaded (customizer save) or a
// previous server render. Either way it's a real R2 object; redirect.
+ // Exception: a legacy poisoned key (absolute, origin-pointing, written by the
+ // pre-fix ogKeyFor) would 302 to a 404, so clear it and fall through to a
+ // fresh render that writes the corrected bucket key.
if (avatar.thumbnail_url) {
- res.statusCode = 302;
- res.setHeader('location', avatar.thumbnail_url);
- res.setHeader('cache-control', CACHE_REDIR);
- res.end();
- return;
+ if (isLegacyOgThumbnailKey(avatar.thumbnail_url)) {
+ await sql`
+ update avatars set thumbnail_key = null, updated_at = now()
+ where id = ${avatar.id} and deleted_at is null
+ `.catch(() => {});
+ } else {
+ res.statusCode = 302;
+ res.setHeader('location', avatar.thumbnail_url);
+ res.setHeader('cache-control', CACHE_REDIR);
+ res.end();
+ return;
+ }
}
// Private avatars have no public model_url, so headless chromium can't
@@ -178,10 +188,21 @@ async function renderAndCache({ avatar }) {
}
}
-// OG cache key: lives alongside the GLB in the user's namespace so it
-// shares lifetime + deletion semantics. _og.png distinguishes from
-// _thumb.jpg (the client-uploaded customizer snapshot).
+// OG cache key. For bucket-backed avatars (the `u/{owner}/…/file.glb` form) it
+// lives alongside the GLB so it shares lifetime + deletion semantics; the
+// `_og.png` suffix distinguishes it from `_thumb.jpg` (the client-uploaded
+// customizer snapshot).
+//
+// First-party / externally-hosted avatars store an ABSOLUTE URL in
+// `storage_key` (e.g. https://three.ws/avatars/michelle.glb). That is not a
+// writable bucket key — deriving `_og.png` from it yields a URL-shaped "key"
+// (https://three.ws/avatars/michelle_og.png) that putObject can't serve and
+// that 404s the instant it's surfaced as a thumbnail. Cache those under a
+// deterministic bucket path keyed by the avatar id instead.
function ogKeyFor(avatar) {
+ if (/^https?:\/\//i.test(avatar.storage_key || '')) {
+ return `og/avatar/${avatar.id}.png`;
+ }
return avatar.storage_key.replace(/\.glb$/i, '') + '_og.png';
}
diff --git a/api/explore.js b/api/explore.js
index 508c565e2..7df5b7a1d 100644
--- a/api/explore.js
+++ b/api/explore.js
@@ -28,9 +28,18 @@ import { sql } from './_lib/db.js';
import { cors, json, method, wrap, error, rateLimited } from './_lib/http.js';
import { limits, clientIp } from './_lib/rate-limit.js';
import { CHAIN_BY_ID, tokenExplorerUrl, addressExplorerUrl } from './_lib/erc8004-chains.js';
-import { publicUrl } from './_lib/r2.js';
+import { publicUrl, isLegacyOgThumbnailKey } from './_lib/r2.js';
import { DEMO_AVATARS } from './_lib/demo-avatars.js';
+// A stored thumbnail_key only resolves to a real image when it's a relative R2
+// key. Legacy poisoned keys (absolute, origin-pointing `*_og.png`) 404, so drop
+// them rather than surface a broken <img>; the avatar self-heals on its next OG
+// crawl, after which a corrected thumbnail appears.
+function thumbnailUrl(thumbnailKey) {
+ if (!thumbnailKey || isLegacyOgThumbnailKey(thumbnailKey)) return null;
+ return publicUrl(thumbnailKey);
+}
+
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
if (!method(req, res, ['GET'])) return;
@@ -51,7 +60,11 @@ export default wrap(async (req, res) => {
.trim()
.slice(0, 80);
const cursor = url.searchParams.get('cursor');
- const limit = Math.min(Math.max(parseInt(url.searchParams.get('limit') || '24', 10), 1), 250);
+ // parseInt('test') is NaN, and Math.min/max propagate NaN — which then reaches
+ // the LIMIT bigint parameter and throws 22P02 ("invalid input syntax for type
+ // bigint: NaN") on this public endpoint. Coerce non-numeric input to the default.
+ const limitRaw = parseInt(url.searchParams.get('limit') || '24', 10);
+ const limit = Number.isFinite(limitRaw) ? Math.min(Math.max(limitRaw, 1), 250) : 24;
const sourceFilter = url.searchParams.get('source') || 'all';
const quality = url.searchParams.get('quality') === 'all' ? 'all' : 'high';
@@ -208,7 +221,7 @@ export default wrap(async (req, res) => {
slug: r.slug,
name: r.name,
description: r.description || '',
- image: r.thumbnail_key ? publicUrl(r.thumbnail_key) : null,
+ image: thumbnailUrl(r.thumbnail_key),
glbUrl: glb,
has3d: true,
tags: r.tags || [],
diff --git a/api/marketplace/asset-price.js b/api/marketplace/asset-price.js
index 68f47508c..c92c12543 100644
--- a/api/marketplace/asset-price.js
+++ b/api/marketplace/asset-price.js
@@ -71,6 +71,11 @@ async function handleGet(req, res) {
if (!ITEM_TYPES.includes(itemType) || !itemId) {
return error(res, 400, 'validation_error', 'item_type and item_id required');
}
+ // item_id is a uuid column — reject malformed ids here so the query never
+ // reaches Postgres with bad input (which throws 22P02 → an unhandled 500).
+ if (!postBody.shape.item_id.safeParse(itemId).success) {
+ return error(res, 400, 'validation_error', 'item_id must be a valid uuid');
+ }
const rl = await limits.widgetRead(clientIp(req));
if (!rl.success) return rateLimited(res, rl);
diff --git a/data/changelog.json b/data/changelog.json
index d22e63a74..0d169d083 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,15 @@
{
"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-06-11",
+ "title": "Avatar preview images load reliably",
+ "summary": "Fixed a bug where some community avatars — including the pinned home-town cast — showed a broken preview image in the /play lobby and gallery instead of their portrait. The shareable social-card image for those avatars now generates and serves correctly too, so links posted to X and Discord render a proper preview.",
+ "tags": [
+ "fix"
+ ],
+ "link": "/play"
+ },
{
"date": "2026-06-11",
"title": "Free 3D drafts on Forge",
diff --git a/package-lock.json b/package-lock.json
index 93fac9184..a128b7115 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -45,6 +45,8 @@
"@gltf-transform/core": "^4.4.0",
"@gltf-transform/extensions": "^4.4.0",
"@gltf-transform/functions": "^4.4.0",
+ "@grpc/grpc-js": "^1.14.4",
+ "@grpc/proto-loader": "^0.8.1",
"@jup-ag/api": "^6.0.48",
"@mediapipe/tasks-vision": "^0.10.35",
"@metaplex-foundation/js": "^0.20.1",
@@ -8701,6 +8703,37 @@
"graphql": "^0.8.0 || ^0.9.0 || ^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^14.0.0 || ^15.0.0 || ^16.0.0 || ^17.0.0"
}
},
+ "node_modules/@grpc/grpc-js": {
+ "version": "1.14.4",
+ "resolved": "https://registry.npmjs.org/@grpc/grpc-js/-/grpc-js-1.14.4.tgz",
+ "integrity": "sha512-k9Dj3DV/itK9D06Y8f190Qgop7/Ui+D0njFV3LHMPwPT75DpXLQohE9Wmz0QElrJnzsjB7KPWiKJbOl7IPDArQ==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@grpc/proto-loader": "^0.8.0",
+ "@js-sdsl/ordered-map": "^4.4.2"
+ },
+ "engines": {
+ "node": ">=12.10.0"
+ }
+ },
+ "node_modules/@grpc/proto-loader": {
+ "version": "0.8.1",
+ "resolved": "https://registry.npmjs.org/@grpc/proto-loader/-/proto-loader-0.8.1.tgz",
+ "integrity": "sha512-wtF6h+DY6M3YaDBPAmvuuA6jV8Sif9MjtOI5euKFWRgCDl5PeDpPsHR9u2l6St5ceY8AZgoNDww5+HvEsXFsGg==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "lodash.camelcase": "^4.3.0",
+ "long": "^5.0.0",
+ "protobufjs": "^7.5.5",
+ "yargs": "^17.7.2"
+ },
+ "bin": {
+ "proto-loader-gen-types": "build/bin/proto-loader-gen-types.js"
+ },
+ "engines": {
+ "node": ">=6"
+ }
+ },
"node_modules/@helia/bitswap": {
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/@helia/bitswap/-/bitswap-2.2.0.tgz",
@@ -10559,6 +10592,16 @@
"@jridgewell/sourcemap-codec": "^1.4.14"
}
},
+ "node_modules/@js-sdsl/ordered-map": {
+ "version": "4.4.2",
+ "resolved": "https://registry.npmjs.org/@js-sdsl/ordered-map/-/ordered-map-4.4.2.tgz",
+ "integrity": "sha512-iUKgm52T8HOE/makSxjqoWhe95ZJA1/G1sYsGev2JDKUSS14KAgg1LHb+Ba+IPow0xflbnSkOsZcO08C7w1gYw==",
+ "license": "MIT",
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/js-sdsl"
+ }
+ },
"node_modules/@jup-ag/api": {
"version": "6.0.48",
"resolved": "https://registry.npmjs.org/@jup-ag/api/-/api-6.0.48.tgz",
@@ -15912,6 +15955,69 @@
"@privy-io/api-types": "0.15.0"
}
},
+ "node_modules/@protobufjs/aspromise": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/@protobufjs/aspromise/-/aspromise-1.1.2.tgz",
+ "integrity": "sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ==",
+ "license": "BSD-3-Clause"
+ },
+ "node_modules/@protobufjs/base64": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/@protobufjs/base64/-/base64-1.1.2.tgz",
+ "integrity": "sha512-AZkcAA5vnN/v4PDqKyMR5lx7hZttPDgClv83E//FMNhR2TMcLUhfRUBHCmSl0oi9zMgDDqRUJkSxO3wm85+XLg==",
+ "license": "BSD-3-Clause"
+ },
+ "node_modules/@protobufjs/codegen": {
+ "version": "2.0.5",
+ "resolved": "https://registry.npmjs.org/@protobufjs/codegen/-/codegen-2.0.5.tgz",
+ "integrity": "sha512-zgXFLzW3Ap33e6d0Wlj4MGIm6Ce8O89n/apUaGNB/jx+hw+ruWEp7EwGUshdLKVRCxZW12fp9r40E1mQrf/34g==",
+ "license": "BSD-3-Clause"
+ },
+ "node_modules/@protobufjs/eventemitter": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/@protobufjs/eventemitter/-/eventemitter-1.1.1.tgz",
+ "integrity": "sha512-vW1GmwMZNnL+gMRaovlh9yZX74kc+TTU3FObkkurpMaRtBfLP3ldjS9KQWlwZgraRE0+dheEEoAxdzcJQ8eXZg==",
+ "license": "BSD-3-Clause"
+ },
+ "node_modules/@protobufjs/fetch": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/@protobufjs/fetch/-/fetch-1.1.1.tgz",
+ "integrity": "sha512-GpptLrs57adMSuHi3VNj0mAF8dwh36LMaYF6XyJ6JMWlVsc+t42tm1HSEDmOs3A8fC9yyeisgLhsTVQokOZ0zw==",
+ "license": "BSD-3-Clause",
+ "dependencies": {
+ "@protobufjs/aspromise": "^1.1.1"
+ }
+ },
+ "node_modules/@protobufjs/float": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/@protobufjs/float/-/float-1.0.2.tgz",
+ "integrity": "sha512-Ddb+kVXlXst9d+R9PfTIxh1EdNkgoRe5tOX6t01f1lYWOvJnSPDBlG241QLzcyPdoNTsblLUdujGSE4RzrTZGQ==",
+ "license": "BSD-3-Clause"
+ },
+ "node_modules/@protobufjs/inquire": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/@protobufjs/inquire/-/inquire-1.1.2.tgz",
+ "integrity": "sha512-pa0vFRuws4wkvaXKK1uXZMAwAX4/t8ANaJo45iw/oQHNQ9q5xUzwgFmVJGXiga2BeN+zpX7Vf9vmsiIa2J+MUw==",
+ "license": "BSD-3-Clause"
+ },
+ "node_modules/@protobufjs/path": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/@protobufjs/path/-/path-1.1.2.tgz",
+ "integrity": "sha512-6JOcJ5Tm08dOHAbdR3GrvP+yUUfkjG5ePsHYczMFLq3ZmMkAD98cDgcT2iA1lJ9NVwFd4tH/iSSoe44YWkltEA==",
+ "license": "BSD-3-Clause"
+ },
+ "node_modules/@protobufjs/pool": {
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/@protobufjs/pool/-/pool-1.1.0.tgz",
+ "integrity": "sha512-0kELaGSIDBKvcgS4zkjz1PeddatrjYcmMWOlAuAPwAeccUrPHdUqo/J6LiymHHEiJT5NrF1UVwxY14f+fy4WQw==",
+ "license": "BSD-3-Clause"
+ },
+ "node_modules/@protobufjs/utf8": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/@protobufjs/utf8/-/utf8-1.1.1.tgz",
+ "integrity": "sha512-oOAWABowe8EAbMyWKM0tYDKi8Yaox52D+HWZhAIJqQXbqe0xI/GV7FhLWqlEKreMkfDjshR5FKgi3mnle0h6Eg==",
+ "license": "BSD-3-Clause"
+ },
"node_modules/@pump-fun/agent-payments-sdk": {
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/@pump-fun/agent-payments-sdk/-/agent-payments-sdk-3.0.3.tgz",
@@ -40055,6 +40161,12 @@
"url": "https://tidelift.com/funding/github/npm/loglevel"
}
},
+ "node_modules/long": {
+ "version": "5.3.2",
+ "resolved": "https://registry.npmjs.org/long/-/long-5.3.2.tgz",
+ "integrity": "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==",
+ "license": "Apache-2.0"
+ },
"node_modules/loose-envify": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz",
@@ -43006,6 +43118,30 @@
"integrity": "sha512-AvPcP7XECNWy4LGmFQ77k7un4lSKM4eS29PTvW4ck95uYeLxXPWJM7hLuBqK91FaHqCcgJvIUCuNJjjxKE7VKQ==",
"license": "MIT"
},
+ "node_modules/protobufjs": {
+ "version": "7.6.3",
+ "resolved": "https://registry.npmjs.org/protobufjs/-/protobufjs-7.6.3.tgz",
+ "integrity": "sha512-+k0vdJKNdW+Vu+dYe8tZA/VvQb6XKNWexC6URwBFXxNnjLJz9nQJCemGyNgRAWD+B7+nGNc9qMPGwcD7s4nzUw==",
+ "hasInstallScript": true,
+ "license": "BSD-3-Clause",
+ "dependencies": {
+ "@protobufjs/aspromise": "^1.1.2",
+ "@protobufjs/base64": "^1.1.2",
+ "@protobufjs/codegen": "^2.0.5",
+ "@protobufjs/eventemitter": "^1.1.1",
+ "@protobufjs/fetch": "^1.1.1",
+ "@protobufjs/float": "^1.0.2",
+ "@protobufjs/inquire": "^1.1.2",
+ "@protobufjs/path": "^1.1.2",
+ "@protobufjs/pool": "^1.1.0",
+ "@protobufjs/utf8": "^1.1.1",
+ "@types/node": ">=13.7.0",
+ "long": "^5.3.2"
+ },
+ "engines": {
+ "node": ">=12.0.0"
+ }
+ },
"node_modules/protons-runtime": {
"version": "5.6.0",
"resolved": "https://registry.npmjs.org/protons-runtime/-/protons-runtime-5.6.0.tgz",
diff --git a/package.json b/package.json
index ed4d9cd39..233df2f1e 100644
--- a/package.json
+++ b/package.json
@@ -140,6 +140,8 @@
"@gltf-transform/core": "^4.4.0",
"@gltf-transform/extensions": "^4.4.0",
"@gltf-transform/functions": "^4.4.0",
+ "@grpc/grpc-js": "^1.14.4",
+ "@grpc/proto-loader": "^0.8.1",
"@jup-ag/api": "^6.0.48",
"@mediapipe/tasks-vision": "^0.10.35",
"@metaplex-foundation/js": "^0.20.1",
diff --git a/public/changelog.json b/public/changelog.json
index a2c21f8d1..fd44c861f 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-11T10:46:25.045Z",
+ "generated_at": "2026-06-11T10:47:52.613Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -28,6 +28,16 @@
"infra"
]
},
+ {
+ "date": "2026-06-11",
+ "type": "update",
+ "title": "Avatar preview images load reliably",
+ "summary": "Fixed a bug where some community avatars — including the pinned home-town cast — showed a broken preview image in the /play lobby and gallery instead of their portrait. The shareable social-card image for those avatars now generates and serves correctly too, so links posted to X and Discord render a proper preview.",
+ "link": "/play",
+ "tags": [
+ "fix"
+ ]
+ },
{
"date": "2026-06-11",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index f892c782e..2d5706b8d 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -22,6 +22,14 @@
<category>fix</category>
<description>Fetching an individual avatar was failing with a server error, which also broke the walking avatar on the home page. The image-processing engine the avatar dress-up baker relies on failed to load in production and took the whole endpoint down with it. Avatar lookups now load independently of the baker, and the missing image libraries ship with the deployment, so avatar pages and the home hero are back.</description>
</item>
+ <item>
+ <title>Avatar preview images load reliably</title>
+ <link>https://three.ws/play</link>
+ <guid isPermaLink="false">2026-06-11:Avatar preview images load reliably</guid>
+ <pubDate>Thu, 11 Jun 2026 12:00:00 GMT</pubDate>
+ <category>fix</category>
+ <description>Fixed a bug where some community avatars — including the pinned home-town cast — showed a broken preview image in the /play lobby and gallery instead of their portrait. The shareable social-card image for those avatars now generates and serves correctly too, so links posted to X and Discord render a proper preview.</description>
+ </item>
<item>
<title>Built-in AI stays up when a provider runs dry</title>
<link>https://three.ws/changelog</link>
diff --git a/public/error-reporter.js b/public/error-reporter.js
index 912fa6a5a..dc0515f28 100644
--- a/public/error-reporter.js
+++ b/public/error-reporter.js
@@ -32,6 +32,12 @@
'ResizeObserver loop limit exceeded',
'ResizeObserver loop completed with undelivered notifications.',
];
+ // Analytics/telemetry endpoints that privacy extensions (uBlock, Brave,
+ // Ghostery…) routinely block. A blocked tracker is the client's choice, not
+ // a site fault — the underlying SDKs degrade silently, so the only artifact
+ // is a noisy "failed to load script" we don't want flooding the logs.
+ const IGNORED_RESOURCE_SOURCES =
+ /\/_vercel\/(insights|speed-insights)\/|\/ingest\/|\.i\.posthog\.com\//;
const truncate = (value, max) => {
if (typeof value !== 'string' || !value) return undefined;
@@ -103,9 +109,24 @@
return true;
}
if (report.message && IGNORED_MESSAGES.includes(report.message)) return true;
+ if (report.type === 'resource' && report.source) {
+ // Privacy-blocker-killed analytics — expected, not actionable.
+ if (IGNORED_RESOURCE_SOURCES.test(report.source)) return true;
+ // An <img src=""> (or a src that resolves to the page itself) is an
+ // element with no real source, not a missing asset. The browser still
+ // fires a load error for it; classify it as benign rather than a 404.
+ if (isCurrentPage(report.source)) return true;
+ }
return false;
}
+ // True when `url` is the current document URL ignoring the fragment — the
+ // resolved value of an element whose src/href attribute is empty.
+ function isCurrentPage(url) {
+ const strip = (u) => String(u).split('#')[0];
+ return strip(url) === strip(location.href);
+ }
+
function enqueue(report) {
if (totalAccepted >= MAX_EVENTS_PER_PAGE || shouldIgnore(report)) return;
const signature = [report.type, report.message, report.source, report.line].join('|');
diff --git a/public/features.json b/public/features.json
index 108a12ca9..6abe28dbc 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-11T10:24:49.450Z",
+ "generated_at": "2026-06-11T10:47:52.603Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/public/sitemap/index.html b/public/sitemap/index.html
index 5b4fd2858..d0803f7b3 100644
--- a/public/sitemap/index.html
+++ b/public/sitemap/index.html
@@ -42,20 +42,6 @@
.sm-brand img { width: 24px; height: 24px; border-radius: 5px; }
.sm-brand:hover { text-decoration: none; }
</style>
-
- <meta property="og:type" content="website">
- <meta property="og:site_name" content="three.ws">
- <meta property="og:title" content="Sitemap · three.ws">
- <meta property="og:description" content="Human-readable index of every page on three.ws.">
- <meta property="og:url" content="https://three.ws/sitemap">
- <meta property="og:image" content="https://three.ws/og-image.png">
- <meta property="og:image:width" content="1200">
- <meta property="og:image:height" content="630">
- <meta name="twitter:card" content="summary_large_image">
- <meta name="twitter:title" content="Sitemap · three.ws">
- <meta name="twitter:description" content="Human-readable index of every page on three.ws.">
- <meta name="twitter:image" content="https://three.ws/og-image.png">
- <script type="application/ld+json">{"@context":"https://schema.org","@type":"WebPage","name":"Sitemap","description":"Human-readable index of every page on three.ws.","url":"https://three.ws/sitemap","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"}}</script>
</head>
<body>
<header class="sm-topbar">
diff --git a/renovate.json b/renovate.json
new file mode 100644
index 000000000..9ee1dee0d
--- /dev/null
+++ b/renovate.json
@@ -0,0 +1,43 @@
+{
+ "$schema": "https://docs.renovatebot.com/renovate-schema.json",
+ "description": "Grouped, scheduled dependency updates gated by the Tests workflow. Dependabot was removed after ungated bumps broke the cron jobs and avatar baker; every Renovate PR now has to pass vitest + e2e before it can merge.",
+ "extends": ["config:recommended", ":semanticCommitsDisabled"],
+ "timezone": "America/New_York",
+ "schedule": ["before 8am on monday"],
+ "prConcurrentLimit": 3,
+ "prHourlyLimit": 2,
+ "rangeStrategy": "bump",
+ "minimumReleaseAge": "7 days",
+ "lockFileMaintenance": {
+ "enabled": true,
+ "schedule": ["before 8am on the first day of the month"]
+ },
+ "packageRules": [
+ {
+ "description": "Group all non-major updates into one weekly PR — one CI run, one review.",
+ "matchUpdateTypes": ["minor", "patch"],
+ "groupName": "weekly non-major dependencies"
+ },
+ {
+ "description": "Majors stay individual PRs — they need real review, not a rubber stamp.",
+ "matchUpdateTypes": ["major"],
+ "dependencyDashboardApproval": true
+ },
+ {
+ "description": "Solana/web3 + pump.fun SDKs move APIs aggressively and touch money paths; never auto-group, always wait longer.",
+ "matchPackagePatterns": ["^@solana/", "^@pump-fun/", "^@coinbase/", "^@x402/"],
+ "groupName": null,
+ "minimumReleaseAge": "14 days"
+ },
+ {
+ "description": "three.js minor releases routinely break examples/jsm imports — treat like majors.",
+ "matchPackageNames": ["three"],
+ "dependencyDashboardApproval": true
+ }
+ ],
+ "vulnerabilityAlerts": {
+ "enabled": true,
+ "schedule": ["at any time"],
+ "minimumReleaseAge": null
+ }
+}
diff --git a/scripts/repair-avatar-og-keys.mjs b/scripts/repair-avatar-og-keys.mjs
new file mode 100644
index 000000000..fccf14b86
--- /dev/null
+++ b/scripts/repair-avatar-og-keys.mjs
@@ -0,0 +1,70 @@
+/**
+ * Repair poisoned avatar OG thumbnail keys.
+ *
+ * The pre-fix avatar-OG cache derived its key from `storage_key` with a naive
+ * `.glb → _og.png` swap. For first-party / externally-hosted avatars the
+ * storage_key is an ABSOLUTE URL (https://three.ws/avatars/michelle.glb), so
+ * the derived "key" became a full origin URL (https://three.ws/avatars/
+ * michelle_og.png). publicUrl() passes absolute keys through verbatim, so that
+ * value pointed at the site instead of the R2 CDN — where no object exists. The
+ * result was a broken <img> in the lobby/gallery and a 302-to-404 for social
+ * crawlers (the michelle_og.png "failed to load img" runtime errors).
+ *
+ * ogKeyFor() now caches those under `og/avatar/<id>.png`. This script clears the
+ * already-poisoned `thumbnail_key`s so the corrected key regenerates on the next
+ * OG crawl. Safe + idempotent: it only nulls absolute, origin-pointing `_og.png`
+ * keys (relative R2 keys and customizer `_thumb.jpg` snapshots are untouched).
+ *
+ * Usage:
+ * DATABASE_URL=... node scripts/repair-avatar-og-keys.mjs --dry-run # plan
+ * DATABASE_URL=... node scripts/repair-avatar-og-keys.mjs # apply
+ */
+
+import { neon } from '@neondatabase/serverless';
+
+const DRY_RUN = process.argv.includes('--dry-run');
+
+if (!process.env.DATABASE_URL) {
+ console.error('Missing DATABASE_URL');
+ process.exit(1);
+}
+
+const sql = neon(process.env.DATABASE_URL);
+
+// Poisoned ⇔ thumbnail_key is an absolute URL ending in `_og.png`. A correct OG
+// key is always a relative bucket key, so this never matches a healthy row.
+const POISON_PATTERN = '^https?://.*_og\\.png$';
+
+const affected = await sql`
+ select id, name, slug, thumbnail_key
+ from avatars
+ where deleted_at is null
+ and thumbnail_key ~* ${POISON_PATTERN}
+ order by created_at asc
+`;
+
+console.log(`repair-avatar-og-keys — dry-run=${DRY_RUN}`);
+console.log(`${affected.length} avatar(s) with poisoned OG thumbnail keys\n`);
+
+for (const a of affected) {
+ console.log(` ${DRY_RUN ? '~' : '✓'} ${String(a.slug || a.id).padEnd(24)} ${a.thumbnail_key}`);
+}
+
+if (!affected.length) {
+ console.log('Nothing to repair.');
+ process.exit(0);
+}
+
+if (DRY_RUN) {
+ console.log('\nDry run — no changes written.');
+ process.exit(0);
+}
+
+const result = await sql`
+ update avatars set thumbnail_key = null, updated_at = now()
+ where deleted_at is null
+ and thumbnail_key ~* ${POISON_PATTERN}
+`;
+
+console.log(`\nCleared ${result.length ?? affected.length} poisoned key(s). They regenerate on the next OG crawl.`);
+process.exit(0);
diff --git a/scripts/verify-nim-flux.mjs b/scripts/verify-nim-flux.mjs
new file mode 100644
index 000000000..13b5ab3cd
--- /dev/null
+++ b/scripts/verify-nim-flux.mjs
@@ -0,0 +1,135 @@
+// Live verification for the NIM FLUX text→image lane (task T1.3).
+//
+// node scripts/verify-nim-flux.mjs "a teapot" # live generation via NIM
+// node scripts/verify-nim-flux.mjs --degrade # NIM→Vertex→Replicate order check
+//
+// Live mode runs a real FLUX.1-schnell generation through textToImage(), lets
+// the module persist the artifact via the shared R2 helper, re-fetches the
+// persisted object, and asserts it is a real image (JPEG/PNG magic bytes +
+// plausible dimensions). Needs NVIDIA_API_KEY plus S3_* creds; when prod R2
+// creds are absent (this Codespace), point S3_* at a throwaway local MinIO:
+//
+// docker run -d --name minio -p 9000:9000 -e MINIO_ROOT_USER=verify \
+// -e MINIO_ROOT_PASSWORD=verify-secret minio/minio server /data
+// export S3_ENDPOINT=http://127.0.0.1:9000 S3_BUCKET=verify \
+// S3_ACCESS_KEY_ID=verify S3_SECRET_ACCESS_KEY=verify-secret \
+// S3_PUBLIC_DOMAIN=http://127.0.0.1:9000/verify
+//
+// (.env.local values never override variables already exported in the shell.)
+//
+// Degrade mode deliberately breaks the NIM lane (invalid key) and gives the
+// Vertex and Replicate lanes synthetic config so the chain has somewhere to
+// fall: it asserts the attempt ORDER (NIM → Vertex → Replicate) and clean
+// error propagation — the downstream lanes are not expected to succeed.
+// No scratch files are written; nothing is committed by this script.
+
+import { config as dotenv } from 'dotenv';
+dotenv({ path: new URL('../.env.local', import.meta.url) });
+
+const DEGRADE = process.argv.includes('--degrade');
+const prompt = process.argv.filter((a) => !a.startsWith('--'))[2] || 'a teapot';
+
+function fail(msg) {
+ console.error(`[nim-flux] FAIL — ${msg}`);
+ process.exit(1);
+}
+
+function sniffImage(buf) {
+ if (buf.length > 2 && buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff) return 'jpeg';
+ if (buf.length > 7 && buf.readUInt32BE(0) === 0x89504e47) return 'png';
+ return null;
+}
+
+// Walk JPEG markers to the first SOF segment, which carries the frame size.
+function jpegDimensions(buf) {
+ let i = 2;
+ while (i + 9 < buf.length) {
+ if (buf[i] !== 0xff) return null;
+ const marker = buf[i + 1];
+ if (marker >= 0xc0 && marker <= 0xcf && ![0xc4, 0xc8, 0xcc].includes(marker)) {
+ return { height: buf.readUInt16BE(i + 5), width: buf.readUInt16BE(i + 7) };
+ }
+ i += 2 + buf.readUInt16BE(i + 2);
+ }
+ return null;
+}
+
+function pngDimensions(buf) {
+ return { width: buf.readUInt32BE(16), height: buf.readUInt32BE(20) };
+}
+
+if (DEGRADE) {
+ // Break NIM, ensure two downstream lanes look configured (synthetic creds —
+ // they are expected to fail too; we are asserting order, not success).
+ process.env.NVIDIA_API_KEY = 'nvapi-invalid-degrade-check';
+ if (!process.env.GOOGLE_CLOUD_PROJECT) process.env.GOOGLE_CLOUD_PROJECT = 'degrade-check-project';
+ if (!process.env.REPLICATE_API_TOKEN) process.env.REPLICATE_API_TOKEN = 'r8_invalid_degrade_check';
+
+ const fallbackLogs = [];
+ const realError = console.error.bind(console);
+ console.error = (...args) => {
+ fallbackLogs.push(args.join(' '));
+ realError(...args);
+ };
+
+ const { textToImage } = await import('../api/_mcp3d/text-to-image.js');
+ let finalError = null;
+ try {
+ await textToImage(prompt);
+ fail('degrade run unexpectedly succeeded — every lane had invalid creds');
+ } catch (err) {
+ finalError = err;
+ } finally {
+ console.error = realError;
+ }
+
+ console.log(`[nim-flux] final surfaced error: ${finalError.message}`);
+ const nimIdx = fallbackLogs.findIndex((l) => l.includes('nim flux failed, falling back'));
+ const vertexIdx = fallbackLogs.findIndex((l) => l.includes('vertex imagen failed, falling back to replicate'));
+ if (nimIdx === -1) fail('NIM lane was never attempted / never handed off');
+ if (vertexIdx === -1) fail('Vertex lane was never attempted after NIM');
+ if (vertexIdx < nimIdx) fail('Vertex was attempted before NIM — order is wrong');
+ if (!finalError?.message) fail('last lane did not propagate a clean Error');
+ console.log('[nim-flux] ✓ degrade order verified: NIM → Vertex → Replicate, last lane error surfaced');
+ console.log('[nim-flux] PASS (degrade)');
+ process.exit(0);
+}
+
+if (!process.env.NVIDIA_API_KEY) fail('NVIDIA_API_KEY missing — set it in .env.local');
+if (!process.env.S3_ENDPOINT || !process.env.S3_BUCKET) {
+ fail('S3_* creds missing — point them at prod R2 or the MinIO recipe in this header');
+}
+
+const { textToImage } = await import('../api/_mcp3d/text-to-image.js');
+
+console.log(`[nim-flux] generating via NIM FLUX.1-schnell: "${prompt}"`);
+const started = Date.now();
+const result = await textToImage(prompt);
+const elapsedMs = Date.now() - started;
+
+console.log(`[nim-flux] model: ${result.model}`);
+console.log(`[nim-flux] persisted: ${result.imageUrl}`);
+console.log(`[nim-flux] end-to-end latency: ${(elapsedMs / 1000).toFixed(1)}s`);
+if (result.model !== 'black-forest-labs/flux.1-schnell') {
+ fail(`served by ${result.model}, not the NIM lane — check NVIDIA_API_KEY`);
+}
+
+// Re-fetch the persisted object and prove it is a real image.
+const res = await fetch(result.imageUrl);
+if (!res.ok) fail(`persisted image fetch returned ${res.status}`);
+const buf = Buffer.from(await res.arrayBuffer());
+const kind = sniffImage(buf);
+if (!kind) fail(`persisted bytes are neither JPEG nor PNG (first bytes: ${buf.subarray(0, 4).toString('hex')})`);
+const dims = kind === 'jpeg' ? jpegDimensions(buf) : pngDimensions(buf);
+if (!dims || dims.width < 256 || dims.height < 256) {
+ fail(`implausible dimensions: ${JSON.stringify(dims)}`);
+}
+const extension = result.imageUrl.split('.').pop();
+const expectedExt = kind === 'jpeg' ? 'jpg' : 'png';
+if (extension !== expectedExt) fail(`persisted as .${extension} but bytes are ${kind}`);
+const contentType = res.headers.get('content-type');
+console.log(
+ `[nim-flux] ✓ valid ${kind.toUpperCase()} — ${dims.width}x${dims.height}, ${buf.byteLength} bytes, ` +
+ `content-type ${contentType}, .${extension} key matches bytes`,
+);
+console.log('[nim-flux] PASS');
diff --git a/src/components/screenshot-modal.js b/src/components/screenshot-modal.js
index e145d3dc6..c530cd5f0 100644
--- a/src/components/screenshot-modal.js
+++ b/src/components/screenshot-modal.js
@@ -19,7 +19,7 @@ export class ScreenshotModal {
<button class="screenshot-modal-close" title="Close">&times;</button>
</div>
<div class="screenshot-modal-body">
- <img src="" alt="Screenshot preview" />
+ <img alt="Screenshot preview" />
</div>
<div class="screenshot-modal-footer">
<button class="btn screenshot-modal-copy">Copy</button>
diff --git a/src/dashboard-next/pages/agents.js b/src/dashboard-next/pages/agents.js
index f3c58b31f..eca78d67d 100644
--- a/src/dashboard-next/pages/agents.js
+++ b/src/dashboard-next/pages/agents.js
@@ -434,6 +434,7 @@ function agentCard(a, avatars) {
const avatarThumb = avatar?.thumbnail_url || avatar?.url || '';
const created = a.created_at ? relTime(a.created_at) : '—';
const onchainBadge = onchainBadgeHTML(a);
+ const onchain = a.onchain || a.meta?.onchain || null;
const pumpMint = a.meta?.pumpfun?.mint || a.meta?.token?.mint || a.meta?.token?.ca;
const brain = brainLabel(a);
diff --git a/src/footer-bot.js b/src/footer-bot.js
index c531cacf0..c1e3debab 100644
--- a/src/footer-bot.js
+++ b/src/footer-bot.js
@@ -13,121 +13,136 @@ import {
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';
import { reserveWebGLContext } from './webgl-budget.js';
-const canvas = document.getElementById('footer-bot-canvas');
-if (!canvas) throw new Error('[footer-bot] canvas not found');
-
-const parent = canvas.parentElement;
-const w = parent?.clientWidth || 300;
-const h = parent?.clientHeight || 400;
-
-const renderer = new WebGLRenderer({ canvas, alpha: true, antialias: true });
-renderer.setSize(w, h);
-renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
-renderer.toneMapping = ACESFilmicToneMapping;
-renderer.toneMappingExposure = 0.7;
-renderer.outputColorSpace = SRGBColorSpace;
-// Count this context against the shared budget so <agent-3d> grids on the same
-// page leave room for it (see webgl-budget.js / element.js).
-reserveWebGLContext();
-
-const scene = new Scene();
-
-// Match model-viewer camera-orbit="0deg 80deg 9m" field-of-view="35deg"
-const camera = new PerspectiveCamera(35, w / h, 0.1, 100);
-const phi = MathUtils.degToRad(80);
-camera.position.set(0, 9 * Math.cos(phi), 9 * Math.sin(phi));
-camera.lookAt(0, 0, 0);
-
-// Neutral environment (exposure 0.7, no shadows)
-scene.add(new AmbientLight(0xffffff, 1.5));
-const sun = new DirectionalLight(0xffffff, 2.0);
-sun.position.set(1, 2, 3);
-scene.add(sun);
-const fill = new DirectionalLight(0xffffff, 0.5);
-fill.position.set(-1, 1, -2);
-scene.add(fill);
-
-let mixer = null;
-const clock = new Clock();
-let robot = null;
-
-// The footer bot is decorative: a transient CDN/network blip on the primary
-// asset must never leave an empty canvas or throw. Walk a fallback chain —
-// the expressive robot, retried once for transient failures, then a static
-// avatar that ships in the same bundle — and give up silently only if every
-// source is unreachable. A model with no clips simply renders without motion.
-const BOT_ASSETS = ['/animations/robotexpressive.glb', '/avatars/default.glb'];
-
-function mountBot(gltf) {
- robot = gltf.scene;
- scene.add(robot);
- if (gltf.animations.length > 0) {
- mixer = new AnimationMixer(robot);
- mixer.clipAction(gltf.animations[0]).play();
+// The footer bot is purely decorative. Every failure mode here — no mount
+// point, a browser that refuses a WebGL context (context budget exhausted, GPU
+// blocklist, headless/locked-down environment) — must degrade to an empty
+// canvas, never an uncaught error. The whole init is wrapped so a throw on any
+// page leaves the rest of the page untouched.
+(function initFooterBot() {
+ const canvas = document.getElementById('footer-bot-canvas');
+ if (!canvas) return; // no mount point on this page — nothing to render
+
+ const parent = canvas.parentElement;
+ const w = parent?.clientWidth || 300;
+ const h = parent?.clientHeight || 400;
+
+ let renderer;
+ try {
+ renderer = new WebGLRenderer({ canvas, alpha: true, antialias: true });
+ } catch {
+ // Context creation throws when the page already holds the browser's max
+ // number of live WebGL contexts, or the GPU is unavailable. Decorative —
+ // skip silently rather than surface "Error creating WebGL context".
+ return;
}
-}
-
-function loadBot(index = 0, retried = false) {
- if (index >= BOT_ASSETS.length) return; // every source exhausted — leave the canvas empty
- const url = BOT_ASSETS[index];
- new GLTFLoader().load(url, mountBot, undefined, () => {
- // Retry the same source once (transient fetch failures usually clear),
- // then advance to the next fallback asset.
- if (!retried) loadBot(index, true);
- else loadBot(index + 1, false);
- });
-}
-
-loadBot();
-
-// 20deg/sec auto-rotate, matching model-viewer rotation-per-second="20deg"
-const rotSpeed = MathUtils.degToRad(20);
-
-// The footer sits at the bottom of long pages, so it is offscreen most of the
-// time. Only render while it is actually visible and the tab is focused —
-// otherwise it burns a GPU context and a RAF loop for nothing.
-let running = false;
-let onScreen = true;
-
-function animate() {
- if (!running) return;
- requestAnimationFrame(animate);
- const dt = clock.getDelta();
- if (mixer) mixer.update(dt);
- if (robot) robot.rotation.y += rotSpeed * dt;
- renderer.render(scene, camera);
-}
-
-function syncRunning() {
- const next = onScreen && document.visibilityState !== 'hidden';
- if (next === running) return;
- running = next;
- if (running) {
- clock.getDelta();
- animate();
+ renderer.setSize(w, h);
+ renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
+ renderer.toneMapping = ACESFilmicToneMapping;
+ renderer.toneMappingExposure = 0.7;
+ renderer.outputColorSpace = SRGBColorSpace;
+ // Count this context against the shared budget so <agent-3d> grids on the same
+ // page leave room for it (see webgl-budget.js / element.js).
+ reserveWebGLContext();
+
+ const scene = new Scene();
+
+ // Match model-viewer camera-orbit="0deg 80deg 9m" field-of-view="35deg"
+ const camera = new PerspectiveCamera(35, w / h, 0.1, 100);
+ const phi = MathUtils.degToRad(80);
+ camera.position.set(0, 9 * Math.cos(phi), 9 * Math.sin(phi));
+ camera.lookAt(0, 0, 0);
+
+ // Neutral environment (exposure 0.7, no shadows)
+ scene.add(new AmbientLight(0xffffff, 1.5));
+ const sun = new DirectionalLight(0xffffff, 2.0);
+ sun.position.set(1, 2, 3);
+ scene.add(sun);
+ const fill = new DirectionalLight(0xffffff, 0.5);
+ fill.position.set(-1, 1, -2);
+ scene.add(fill);
+
+ let mixer = null;
+ const clock = new Clock();
+ let robot = null;
+
+ // A transient CDN/network blip on the primary asset must never leave an empty
+ // canvas. Walk a fallback chain — the expressive robot, retried once for
+ // transient failures, then a static avatar that ships in the same bundle —
+ // and give up silently only if every source is unreachable. A model with no
+ // clips simply renders without motion.
+ const BOT_ASSETS = ['/animations/robotexpressive.glb', '/avatars/default.glb'];
+
+ function mountBot(gltf) {
+ robot = gltf.scene;
+ scene.add(robot);
+ if (gltf.animations.length > 0) {
+ mixer = new AnimationMixer(robot);
+ mixer.clipAction(gltf.animations[0]).play();
+ }
}
-}
-
-if (typeof IntersectionObserver !== 'undefined') {
- new IntersectionObserver(
- (entries) => {
- onScreen = entries[0].isIntersecting;
- syncRunning();
- },
- { threshold: 0 },
- ).observe(canvas);
-} else {
- onScreen = true;
-}
-document.addEventListener('visibilitychange', syncRunning);
-syncRunning();
-
-if (typeof ResizeObserver !== 'undefined' && parent) {
- new ResizeObserver(() => {
- const pw = parent.clientWidth || 300;
- const ph = parent.clientHeight || 400;
- camera.aspect = pw / ph;
- camera.updateProjectionMatrix();
- renderer.setSize(pw, ph);
- }).observe(parent);
-}
+
+ function loadBot(index = 0, retried = false) {
+ if (index >= BOT_ASSETS.length) return; // every source exhausted — leave the canvas empty
+ const url = BOT_ASSETS[index];
+ new GLTFLoader().load(url, mountBot, undefined, () => {
+ // Retry the same source once (transient fetch failures usually clear),
+ // then advance to the next fallback asset.
+ if (!retried) loadBot(index, true);
+ else loadBot(index + 1, false);
+ });
+ }
+
+ loadBot();
+
+ // 20deg/sec auto-rotate, matching model-viewer rotation-per-second="20deg"
+ const rotSpeed = MathUtils.degToRad(20);
+
+ // The footer sits at the bottom of long pages, so it is offscreen most of the
+ // time. Only render while it is actually visible and the tab is focused —
+ // otherwise it burns a GPU context and a RAF loop for nothing.
+ let running = false;
+ let onScreen = true;
+
+ function animate() {
+ if (!running) return;
+ requestAnimationFrame(animate);
+ const dt = clock.getDelta();
+ if (mixer) mixer.update(dt);
+ if (robot) robot.rotation.y += rotSpeed * dt;
+ renderer.render(scene, camera);
+ }
+
+ function syncRunning() {
+ const next = onScreen && document.visibilityState !== 'hidden';
+ if (next === running) return;
+ running = next;
+ if (running) {
+ clock.getDelta();
+ animate();
+ }
+ }
+
+ if (typeof IntersectionObserver !== 'undefined') {
+ new IntersectionObserver(
+ (entries) => {
+ onScreen = entries[0].isIntersecting;
+ syncRunning();
+ },
+ { threshold: 0 },
+ ).observe(canvas);
+ } else {
+ onScreen = true;
+ }
+ document.addEventListener('visibilitychange', syncRunning);
+ syncRunning();
+
+ if (typeof ResizeObserver !== 'undefined' && parent) {
+ new ResizeObserver(() => {
+ const pw = parent.clientWidth || 300;
+ const ph = parent.clientHeight || 400;
+ camera.aspect = pw / ph;
+ camera.updateProjectionMatrix();
+ renderer.setSize(pw, ph);
+ }).observe(parent);
+ }
+})();
diff --git a/src/game/coincommunities-ui.js b/src/game/coincommunities-ui.js
index 177a545b9..160779745 100644
--- a/src/game/coincommunities-ui.js
+++ b/src/game/coincommunities-ui.js
@@ -613,7 +613,13 @@ export class CommunityUI {
onclick: () => this._setAvatar(value, false),
}, [
a.thumbnail_url
- ? el('img', { src: a.thumbnail_url, alt: a.name || 'Avatar', loading: 'lazy' })
+ ? el('img', {
+ src: a.thumbnail_url, alt: a.name || 'Avatar', loading: 'lazy',
+ // A stale thumbnail (e.g. a legacy OG key that 404s before the
+ // avatar self-heals) shouldn't leave a broken-image icon — drop
+ // it; _renderChipPreview paints the live model over this anyway.
+ onerror: (e) => e.target.remove(),
+ })
: el('span', { class: 'cc-avatar-glyph', text: '🧑' }),
]);
chip._url = value;
@@ -643,7 +649,10 @@ export class CommunityUI {
// emoji) so the chip is never empty, then render the real model and swap
// it in. The chip carries a loading shimmer until a preview resolves.
const fallback = p.thumb
- ? el('img', { src: p.thumb, alt: p.label, loading: 'lazy' })
+ ? el('img', {
+ src: p.thumb, alt: p.label, loading: 'lazy',
+ onerror: (e) => e.target.remove(), // broken thumb → let the model preview stand in
+ })
: el('span', { class: 'cc-avatar-glyph', text: p.icon || '🙂' });
const chip = el('button', {
class: 'cc-avatar-chip cc-avatar-loading' + (p.url === this.avatar ? ' cc-on' : ''),
diff --git a/src/view-transitions.js b/src/view-transitions.js
index b6ffd8656..991e0ceaf 100644
--- a/src/view-transitions.js
+++ b/src/view-transitions.js
@@ -36,9 +36,15 @@ function handleClick(e) {
if (!a || !isInternalLink(a)) return;
e.preventDefault();
const dest = a.href;
- document.startViewTransition(() => {
+ const transition = document.startViewTransition(() => {
location.href = dest;
});
+ // A rapid second navigation (double-tap, link spammed before the first
+ // settles) aborts the in-flight transition; its `ready`/`finished` promises
+ // then reject with an AbortError. That's expected, not a fault — swallow it
+ // so it doesn't surface as an unhandled rejection in the error logs.
+ transition?.ready?.catch(() => {});
+ transition?.finished?.catch(() => {});
}
export function enableViewTransitions() {
diff --git a/tasks/nvidia-nim/probes/flux.md b/tasks/nvidia-nim/probes/flux.md
index faf40669c..942117919 100644
--- a/tasks/nvidia-nim/probes/flux.md
+++ b/tasks/nvidia-nim/probes/flux.md
@@ -29,7 +29,7 @@ POST https://ai.api.nvidia.com/v1/genai/black-forest-labs/flux.1-dev
|-------------|--------|-------------------------------|-------------------------------|-------|
| `prompt` | string | required | required | |
| `steps` | int | **1–4** (≤4 enforced) | **≥5** (≥5 enforced) | schnell is the 4-step distilled model |
-| `cfg_scale` | float | accepted | accepted (used 3.5) | guidance scale |
+| `cfg_scale` | float | **must be ≤ 0 — omit it** | accepted (used 3.5) | schnell is guidance-distilled; sending `3.5` → `422 less_than_equal` (`ctx.le: 0.0`) — verified live in T1.3 |
| `width` | enum | one of the size set below | same | |
| `height` | enum | one of the size set below | same | |
| `seed` | int | accepted, echoed back | accepted, echoed back | deterministic |
diff --git a/tests/api/avatar-og.test.js b/tests/api/avatar-og.test.js
index 883f88c43..4a0bac46d 100644
--- a/tests/api/avatar-og.test.js
+++ b/tests/api/avatar-og.test.js
@@ -16,7 +16,11 @@ const publicUrlMock = vi.fn((k) => `https://cdn.test/${k}`);
vi.mock('../../api/_lib/db.js', () => ({ sql: sqlMock }));
vi.mock('../../api/_lib/avatars.js', () => ({ getAvatar: getAvatarMock }));
vi.mock('../../api/_lib/render-glb.js', () => ({ renderGlbToPng: renderGlbToPngMock }));
-vi.mock('../../api/_lib/r2.js', () => ({ putObject: putObjectMock, publicUrl: publicUrlMock }));
+vi.mock('../../api/_lib/r2.js', () => ({
+ putObject: putObjectMock,
+ publicUrl: publicUrlMock,
+ isLegacyOgThumbnailKey: (k) => /^https?:\/\/.*_og\.png$/i.test(String(k || '')),
+}));
vi.mock('../../api/_lib/env.js', () => ({
env: { APP_ORIGIN: 'http://localhost:3000' },
@@ -128,6 +132,40 @@ describe('GET /api/avatar/:id/og — cached thumbnail path', () => {
expect(renderGlbToPngMock).not.toHaveBeenCalled();
expect(putObjectMock).not.toHaveBeenCalled();
});
+
+ it('self-heals a legacy poisoned thumbnail_url instead of 302-ing to a 404', async () => {
+ // Stub the GLB HEAD request so the fall-through render path can run.
+ globalThis.fetch = vi.fn(async () => ({
+ ok: true,
+ headers: { get: (h) => (h.toLowerCase() === 'content-length' ? '1024' : null) },
+ }));
+ const PNG = Buffer.from([0x89, 0x50, 0x4e, 0x47]);
+ getAvatarMock.mockResolvedValueOnce({
+ id: 'a9',
+ name: 'Michelle',
+ // Absolute, origin-pointing _og.png — the pre-fix poisoned key.
+ thumbnail_url: 'https://three.ws/avatars/michelle_og.png',
+ model_url: 'https://three.ws/avatars/michelle.glb',
+ storage_key: 'https://three.ws/avatars/michelle.glb',
+ tags: [],
+ });
+ renderGlbToPngMock.mockResolvedValueOnce(PNG);
+
+ const req = mkReq({ url: '/api/avatar/a9/og' });
+ const res = mkRes();
+ await handler(req, res);
+
+ // No 302 to the dead URL — it renders fresh and streams the PNG.
+ expect(res.statusCode).toBe(200);
+ expect(res._body).toEqual(PNG);
+ // The poisoned key was cleared, then the corrected bucket key was written.
+ const clearCall = sqlMock.mock.calls.find(
+ (c) => c[0].join('?').match(/thumbnail_key = null/) && c.includes('a9'),
+ );
+ expect(clearCall).toBeTruthy();
+ expect(putObjectMock).toHaveBeenCalledTimes(1);
+ expect(putObjectMock.mock.calls[0][0].key).toBe('og/avatar/a9.png');
+ });
});
describe('GET /api/avatar/:id/og — server render path', () => {
diff --git a/tests/api/text-to-image.test.js b/tests/api/text-to-image.test.js
index 49e171caf..6393ebbf9 100644
--- a/tests/api/text-to-image.test.js
+++ b/tests/api/text-to-image.test.js
@@ -52,7 +52,11 @@ function stubFetch(routes) {
return calls;
}
-function nimSuccessResponse(b64 = Buffer.from('nim-png-bytes').toString('base64')) {
+// NIM FLUX artifacts are JPEG (probed live — tasks/nvidia-nim/probes/flux.md),
+// so the fixture carries real JPEG magic bytes (ff d8 ff) for the format sniff.
+const NIM_JPEG_BYTES = Buffer.concat([Buffer.from([0xff, 0xd8, 0xff, 0xe0]), Buffer.from('nim-jpeg-bytes')]);
+
+function nimSuccessResponse(b64 = NIM_JPEG_BYTES.toString('base64')) {
return new Response(JSON.stringify({ artifacts: [{ base64: b64, finishReason: 'SUCCESS' }] }), {
status: 200,
headers: { 'content-type': 'application/json' },
@@ -99,13 +103,21 @@ describe('textToImage — NIM FLUX free lane (first)', () => {
const result = await textToImage('a red teapot');
expect(result.model).toBe('black-forest-labs/flux.1-schnell');
- expect(result.imageUrl).toMatch(/^https:\/\/cdn\.example\/forge\/refs\/.+\.png$/);
+ // NIM output is JPEG — persisted bytes, key extension, and Content-Type
+ // must all say jpeg, not png (regression cover for the probe finding).
+ expect(result.imageUrl).toMatch(/^https:\/\/cdn\.example\/forge\/refs\/.+\.jpg$/);
// NIM artifact persisted to R2; Vertex and Replicate left untouched.
expect(r2State.puts).toHaveLength(1);
+ expect(r2State.puts[0].contentType).toBe('image/jpeg');
+ expect(r2State.puts[0].key).toMatch(/\.jpg$/);
+ expect(Buffer.compare(r2State.puts[0].body, NIM_JPEG_BYTES)).toBe(0);
expect(vertexState.generate).not.toHaveBeenCalled();
expect(calls).toHaveLength(1);
expect(calls[0].url).toContain('flux.1-schnell');
expect(calls[0].body).toMatchObject({ prompt: 'a red teapot', steps: 4 });
+ // schnell is guidance-distilled: the endpoint 422s on cfg_scale > 0
+ // (verified live), so the request must not send it at all.
+ expect(calls[0].body).not.toHaveProperty('cfg_scale');
});
it('maps aspect ratio to FLUX pixel dimensions', async () => {