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.

Add avatar thumbnail backfill cron plus MCP/test coverage follow-ups

nirholase2d36d31610f
diff --git a/api/_lib/avatar-thumbs.js b/api/_lib/avatar-thumbs.js
new file mode 100644
index 000000000..01cda5b2f
--- /dev/null
+++ b/api/_lib/avatar-thumbs.js
@@ -0,0 +1,283 @@
+// api/_lib/avatar-thumbs.js
+//
+// Avatar thumbnail coverage — the single owner of "how does an avatar get a
+// thumbnail, and how do we know it really has one".
+//
+// Background: `avatars.thumbnail_key` was NULL for ~79% of public avatars, so
+// every gallery fell back to an initial-letter chip. Worse, callers used to
+// *guess* a `thumb/<avatarId>.png` URL to paper over the null — the object had
+// never been written, R2 answered 404 with a `text/plain` body, and Chrome
+// blocked the response for an <img> request (net::ERR_BLOCKED_BY_ORB).
+//
+// The invariant this module enforces, and the reason it is the only place that
+// writes `thumbnail_key`:
+//
+// ** A thumbnail_key is only ever persisted after the object behind it has
+// been confirmed to exist in R2. **
+//
+// Two ways an avatar gets one, cheapest first:
+//
+// 1. adoptForgePreviews() — an avatar forged from a `forge_creations` row can
+// point straight at that creation's already-uploaded preview image
+// (`forge_creations.preview_key`, a relative R2 key with a correct
+// Content-Type). Zero new bytes, zero render. This is what /forge's own
+// gallery has always displayed.
+//
+// 2. renderThumbnail() — everything else (studio avatars, uploads, forge rows
+// whose creation predates preview capture) boots headless chromium, renders
+// the GLB to a square PNG, and uploads it to `thumb/<avatarId>.png`.
+// ~6s per avatar, so it runs in bounded batches off a claim ledger.
+//
+// Consumers: api/cron/avatar-thumbnail-backfill.js (steady-state drain) and
+// scripts/backfill-avatar-thumbnails.mjs (operator-driven bulk run). Both share
+// the claim ledger, so they are safe to run at the same time.
+
+import { sql } from './db.js';
+import { presignGet, putObject, headObject, publicUrl, isLegacyOgThumbnailKey } from './r2.js';
+
+// Square posters — matches api/cron/avatar-thumbnail-render.js so a marketplace
+// re-render and a backfill render produce interchangeable images.
+export const THUMB_SIZE = 768;
+export const THUMB_BACKGROUND = '#0a0a0a';
+
+// A GLB that fails to render this many times is almost certainly structurally
+// broken (corrupt, >25MB, non-glTF bytes). Stop paying chromium for it.
+export const MAX_ATTEMPTS = 3;
+
+// A claimed-but-unresolved row (container OOM'd mid-render) frees up after this.
+export const LEASE_MINUTES = 15;
+
+// Source GLB presign lifetime — chromium must fetch the bytes within it.
+const SOURCE_TTL_SECONDS = 120;
+
+export function thumbKeyFor(avatarId) {
+ return `thumb/${avatarId}.png`;
+}
+
+// `thumbnail_key` is meant to be a *relative* R2 key. Rows written by older code
+// paths hold an absolute URL instead (e.g. the legacy `_og.png` cache), which
+// publicUrl() passes through verbatim to an origin where no object lives. Treat
+// those exactly like a missing thumbnail so the backfill replaces them.
+const MISSING_THUMB_SQL = `(thumbnail_key IS NULL OR thumbnail_key ~ '^https?://')`;
+
+let schemaReady = false;
+
+// Idempotent schema provisioning, mirroring
+// api/_lib/migrations/20260709120000_avatar_thumbnail_backfill.sql, so a deploy
+// that lands ahead of the migration still works. Cached per warm container.
+export async function ensureBackfillSchema() {
+ if (schemaReady) return;
+ await sql`
+ CREATE TABLE IF NOT EXISTS avatar_thumbnail_backfill (
+ avatar_id uuid PRIMARY KEY REFERENCES avatars(id) ON DELETE CASCADE,
+ attempts int NOT NULL DEFAULT 0,
+ last_error text,
+ claimed_at timestamptz,
+ updated_at timestamptz NOT NULL DEFAULT now(),
+ created_at timestamptz NOT NULL DEFAULT now()
+ )
+ `;
+ await sql`
+ CREATE INDEX IF NOT EXISTS avatar_thumbnail_backfill_claim_idx
+ ON avatar_thumbnail_backfill (attempts, claimed_at)
+ `;
+ schemaReady = true;
+}
+
+// ── Coverage reporting ───────────────────────────────────────────────────────
+
+export async function coverage() {
+ const [row] = await sql`
+ SELECT
+ count(*) FILTER (WHERE storage_key IS NOT NULL)::int AS total,
+ count(*) FILTER (WHERE storage_key IS NOT NULL
+ AND thumbnail_key IS NOT NULL
+ AND thumbnail_key !~ '^https?://')::int AS covered,
+ count(*) FILTER (WHERE storage_key IS NOT NULL
+ AND (thumbnail_key IS NULL
+ OR thumbnail_key ~ '^https?://'))::int AS missing
+ FROM avatars
+ WHERE deleted_at IS NULL AND visibility = 'public'
+ `;
+ const exhausted = await sql`
+ SELECT count(*)::int AS n FROM avatar_thumbnail_backfill WHERE attempts >= ${MAX_ATTEMPTS}
+ `.catch(() => [{ n: 0 }]);
+ return { ...row, exhausted: exhausted[0]?.n ?? 0 };
+}
+
+// ── 1. Zero-copy adoption from forge_creations.preview_key ───────────────────
+//
+// The preview image already sits in our bucket with the right Content-Type — the
+// /forge gallery renders it directly. Pointing the avatar's thumbnail_key at the
+// same key costs nothing and needs no render.
+//
+// Each candidate is HEAD-checked before we persist it. A preview_key whose object
+// was pruned would otherwise reintroduce the exact 404→ORB bug this module exists
+// to prevent.
+export async function adoptForgePreviews({ limit = 200 } = {}) {
+ const candidates = await sql`
+ SELECT a.id, f.preview_key
+ FROM avatars a
+ JOIN forge_creations f
+ ON f.id = (a.source_meta->>'forge_creation_id')::uuid
+ WHERE a.deleted_at IS NULL
+ AND a.storage_key IS NOT NULL
+ AND (a.thumbnail_key IS NULL OR a.thumbnail_key ~ '^https?://')
+ AND a.source_meta->>'forge_creation_id' ~ '^[0-9a-fA-F-]{36}$'
+ AND f.preview_key IS NOT NULL
+ AND f.preview_key !~ '^https?://'
+ ORDER BY a.featured DESC, a.view_count DESC NULLS LAST, a.created_at DESC
+ LIMIT ${limit}
+ `;
+ if (!candidates.length) return { adopted: 0, missing: 0 };
+
+ let adopted = 0;
+ let missing = 0;
+ for (const c of candidates) {
+ // Confirm the bytes are really there before we advertise them.
+ const head = await headObject(c.preview_key).catch(() => null);
+ if (!head) {
+ missing++;
+ continue;
+ }
+ await sql`
+ UPDATE avatars
+ SET thumbnail_key = ${c.preview_key}, updated_at = now()
+ WHERE id = ${c.id}
+ AND (thumbnail_key IS NULL OR thumbnail_key ~ '^https?://')
+ `;
+ await releaseClaim(c.id);
+ adopted++;
+ }
+ return { adopted, missing };
+}
+
+// ── 2. Claim + render ────────────────────────────────────────────────────────
+
+// Atomically select and claim the most-visible avatars still missing a thumbnail.
+// Candidate selection and the claim upsert run as ONE statement so two concurrent
+// runners (the cron and an operator's bulk script) never claim the same avatar:
+// `FOR UPDATE ... SKIP LOCKED` holds the row locks for the statement's duration.
+export async function claimAvatars(limit = 5) {
+ await ensureBackfillSchema();
+ const rows = await sql`
+ WITH candidates AS (
+ SELECT a.id, a.storage_key, a.name
+ FROM avatars a
+ LEFT JOIN avatar_thumbnail_backfill b ON b.avatar_id = a.id
+ WHERE a.deleted_at IS NULL
+ AND a.storage_key IS NOT NULL
+ AND (a.thumbnail_key IS NULL OR a.thumbnail_key ~ '^https?://')
+ AND (
+ b.avatar_id IS NULL
+ OR (b.attempts < ${MAX_ATTEMPTS}
+ AND (b.claimed_at IS NULL
+ OR b.claimed_at < now() - (${LEASE_MINUTES} * interval '1 minute')))
+ )
+ ORDER BY a.featured DESC,
+ (a.visibility = 'public') DESC,
+ a.view_count DESC NULLS LAST,
+ a.created_at DESC
+ LIMIT ${limit}
+ FOR UPDATE OF a SKIP LOCKED
+ ), claimed AS (
+ INSERT INTO avatar_thumbnail_backfill (avatar_id, attempts, claimed_at, updated_at)
+ SELECT id, 1, now(), now() FROM candidates
+ ON CONFLICT (avatar_id) DO UPDATE
+ SET attempts = avatar_thumbnail_backfill.attempts + 1,
+ claimed_at = now(),
+ updated_at = now()
+ RETURNING avatar_id
+ )
+ SELECT c.id, c.storage_key, c.name
+ FROM candidates c
+ JOIN claimed k ON k.avatar_id = c.id
+ `;
+ return rows;
+}
+
+async function releaseClaim(avatarId) {
+ await sql`DELETE FROM avatar_thumbnail_backfill WHERE avatar_id = ${avatarId}`.catch(() => {});
+}
+
+async function failClaim(avatarId, message) {
+ await sql`
+ UPDATE avatar_thumbnail_backfill
+ SET last_error = ${String(message).slice(0, 500)}, claimed_at = NULL, updated_at = now()
+ WHERE avatar_id = ${avatarId}
+ `.catch(() => {});
+}
+
+// Render one claimed avatar's GLB to a PNG, upload it, and commit the key.
+//
+// The render import is lazy: chromium + puppeteer are a heavy dependency tree and
+// callers that only adopt forge previews should never pay for loading it.
+export async function renderThumbnail({ id, storage_key: storageKey }) {
+ const t0 = Date.now();
+ const { renderGlbToPng } = await import('./render-glb.js');
+
+ // storage_key is normally a bucket key; first-party avatars store an absolute
+ // URL. presignGet() passes those through untouched.
+ const glbUrl = await presignGet({ key: storageKey, expiresIn: SOURCE_TTL_SECONDS });
+
+ const png = await renderGlbToPng({
+ glbUrl,
+ width: THUMB_SIZE,
+ height: THUMB_SIZE,
+ background: THUMB_BACKGROUND,
+ });
+ if (!png?.length) throw new Error('renderer returned no bytes');
+
+ const key = thumbKeyFor(id);
+ await putObject({ key, body: png, contentType: 'image/png', metadata: { 'avatar-id': String(id) } });
+
+ // Only now — object confirmed written — does the key become public.
+ await sql`UPDATE avatars SET thumbnail_key = ${key}, updated_at = now() WHERE id = ${id}`;
+ await releaseClaim(id);
+
+ return { key, url: publicUrl(key), bytes: png.length, ms: Date.now() - t0 };
+}
+
+// Drain `limit` claimed avatars, `concurrency` at a time. Renders share one
+// chromium instance (a page per call), so concurrency is cheap up to the point
+// the container runs out of RAM — 2–4 is the sweet spot on a Cloud Run instance.
+export async function renderBatch({ limit = 5, concurrency = 1, onResult } = {}) {
+ const jobs = await claimAvatars(limit);
+ if (!jobs.length) return { claimed: 0, rendered: 0, failed: 0, results: [] };
+
+ const results = [];
+ const queue = jobs.slice();
+ const workers = Array.from({ length: Math.max(1, Math.min(concurrency, jobs.length)) }, async () => {
+ for (let job = queue.shift(); job; job = queue.shift()) {
+ try {
+ const r = await renderThumbnail(job);
+ const ok = { id: job.id, name: job.name, status: 'done', ...r };
+ results.push(ok);
+ onResult?.(ok);
+ } catch (err) {
+ const msg = err?.message || 'render_failed';
+ await failClaim(job.id, msg);
+ const bad = { id: job.id, name: job.name, status: 'failed', error: msg };
+ results.push(bad);
+ onResult?.(bad);
+ }
+ }
+ });
+ await Promise.all(workers);
+
+ return {
+ claimed: jobs.length,
+ rendered: results.filter((r) => r.status === 'done').length,
+ failed: results.filter((r) => r.status === 'failed').length,
+ results,
+ };
+}
+
+// Exported for tests: the predicate the whole module agrees on.
+export function isMissingThumbnail(thumbnailKey) {
+ if (!thumbnailKey) return true;
+ if (isLegacyOgThumbnailKey(thumbnailKey)) return true;
+ return /^https?:\/\//i.test(thumbnailKey);
+}
+
+export const __sqlMissingThumb = MISSING_THUMB_SQL;
diff --git a/api/_lib/migrations/20260709120000_avatar_thumbnail_backfill.sql b/api/_lib/migrations/20260709120000_avatar_thumbnail_backfill.sql
new file mode 100644
index 000000000..89d1bfc88
--- /dev/null
+++ b/api/_lib/migrations/20260709120000_avatar_thumbnail_backfill.sql
@@ -0,0 +1,35 @@
+-- Avatar thumbnail backfill — claim + retry ledger.
+--
+-- `avatars.thumbnail_key` is the source of truth for "does this avatar have a
+-- thumbnail". This table exists only to make the backfill *bounded*: without it
+-- a handful of un-renderable GLBs would sit at the head of the priority order
+-- and every cron tick would retry them forever, starving the 10k avatars behind
+-- them.
+--
+-- One row per avatar the backfill has attempted. Rows are DELETEd on success
+-- (the avatars row now carries the key, so the avatar drops out of the candidate
+-- set on its own) and retained with a bumped `attempts` + `last_error` on
+-- failure. Once attempts hits the runner's cap the avatar is skipped for good.
+--
+-- `claimed_at` doubles as a lease: a row claimed but never resolved (container
+-- killed mid-render) becomes eligible again after the runner's lease window.
+
+CREATE TABLE IF NOT EXISTS avatar_thumbnail_backfill (
+ avatar_id uuid PRIMARY KEY REFERENCES avatars(id) ON DELETE CASCADE,
+ attempts int NOT NULL DEFAULT 0,
+ last_error text,
+ claimed_at timestamptz,
+ updated_at timestamptz NOT NULL DEFAULT now(),
+ created_at timestamptz NOT NULL DEFAULT now()
+);
+
+-- The claim query filters on (attempts, claimed_at) for every candidate join.
+CREATE INDEX IF NOT EXISTS avatar_thumbnail_backfill_claim_idx
+ ON avatar_thumbnail_backfill (attempts, claimed_at);
+
+-- The candidate scan is `thumbnail_key IS NULL` over live avatars, ordered by
+-- how visible the avatar is. A partial index keeps that scan off the 12k-row
+-- heap once most avatars have healed.
+CREATE INDEX IF NOT EXISTS avatars_missing_thumbnail_idx
+ ON avatars (featured DESC, view_count DESC, created_at DESC)
+ WHERE thumbnail_key IS NULL AND deleted_at IS NULL AND storage_key IS NOT NULL;
diff --git a/api/cron/avatar-thumbnail-backfill.js b/api/cron/avatar-thumbnail-backfill.js
new file mode 100644
index 000000000..535539b5a
--- /dev/null
+++ b/api/cron/avatar-thumbnail-backfill.js
@@ -0,0 +1,121 @@
+// GET /api/cron/avatar-thumbnail-backfill
+//
+// Steady-state drain of the avatar thumbnail coverage gap.
+//
+// ~79% of public avatars shipped with `thumbnail_key = NULL` because nothing
+// generated a thumbnail when an avatar was forged or built in the studio. The
+// only existing renderer (api/cron/avatar-thumbnail-render.js) is fed by the
+// x402 spend loop and only ever touches *marketplace listings*, so the other
+// ~10k avatars were never going to heal on their own.
+//
+// Each tick:
+// 1. Adopts forge previews — an avatar forged from a forge_creations row points
+// its thumbnail_key straight at that creation's already-uploaded preview
+// image. Zero new bytes, no chromium. Hundreds per tick.
+// 2. Renders the rest — claims the most-visible avatars still missing a
+// thumbnail, renders each GLB to a 768² PNG, uploads it, commits the key.
+// Bounded by RENDER_BATCH because chromium costs ~6s per model.
+//
+// Both steps only ever persist a thumbnail_key after confirming the object exists
+// in R2 (see api/_lib/avatar-thumbs.js) — a key pointing at a missing object is
+// what produced net::ERR_BLOCKED_BY_ORB on the homepage in the first place.
+//
+// Sibling cron (avatar-thumbnail-render) re-renders *stale* marketplace
+// thumbnails; this one fills in *absent* ones. They share the render helper and
+// the thumb/<avatarId>.png key space, and each is a no-op on the other's rows.
+//
+// Env:
+// CRON_SECRET required (Bearer)
+// THUMBNAIL_BACKFILL_RENDER_BATCH models rendered per tick (default 4)
+// THUMBNAIL_BACKFILL_ADOPT_BATCH forge previews adopted per tick (default 200)
+// THUMBNAIL_BACKFILL_CONCURRENCY parallel renders (default 2)
+
+import { json, wrapCron } from '../_lib/http.js';
+import { env } from '../_lib/env.js';
+import { constantTimeEquals } from '../_lib/crypto.js';
+import { logger } from '../_lib/usage.js';
+import {
+ ensureBackfillSchema,
+ adoptForgePreviews,
+ renderBatch,
+ coverage,
+} from '../_lib/avatar-thumbs.js';
+
+export const maxDuration = 120;
+
+const log = logger('avatar-thumbnail-backfill');
+
+const RENDER_BATCH = Math.max(0, Number(process.env.THUMBNAIL_BACKFILL_RENDER_BATCH || 4));
+const ADOPT_BATCH = Math.max(0, Number(process.env.THUMBNAIL_BACKFILL_ADOPT_BATCH || 200));
+const CONCURRENCY = Math.max(1, Number(process.env.THUMBNAIL_BACKFILL_CONCURRENCY || 2));
+
+function requireCron(req, res) {
+ const secret = process.env.CRON_SECRET || env.CRON_SECRET;
+ if (!secret) {
+ json(res, 503, { error: 'CRON_SECRET unset' });
+ return false;
+ }
+ const auth = req.headers['authorization'] || '';
+ const token = auth.startsWith('Bearer ') ? auth.slice(7) : '';
+ if (!constantTimeEquals(token, secret)) {
+ json(res, 401, { error: 'unauthorized' });
+ return false;
+ }
+ return true;
+}
+
+export default wrapCron(async (req, res) => {
+ if (req.method !== 'GET') return json(res, 405, { error: 'method_not_allowed' });
+ if (!requireCron(req, res)) return;
+
+ try {
+ await ensureBackfillSchema();
+ } catch (err) {
+ return json(res, 200, { ok: false, reason: `schema_unavailable: ${err?.message}` });
+ }
+
+ // Step 1 — free coverage. Cheap enough to always run first and to run to
+ // completion before we spend a single chromium second.
+ let adopt = { adopted: 0, missing: 0 };
+ if (ADOPT_BATCH > 0) {
+ try {
+ adopt = await adoptForgePreviews({ limit: ADOPT_BATCH });
+ if (adopt.adopted) log.info('forge_previews_adopted', adopt);
+ } catch (err) {
+ log.warn('adopt_failed', { message: err?.message });
+ }
+ }
+
+ // Step 2 — render what's left, most-visible first.
+ let render = { claimed: 0, rendered: 0, failed: 0, results: [] };
+ if (RENDER_BATCH > 0) {
+ try {
+ render = await renderBatch({ limit: RENDER_BATCH, concurrency: CONCURRENCY });
+ } catch (err) {
+ log.warn('render_batch_failed', { message: err?.message });
+ return json(res, 200, { ok: false, reason: `render_failed: ${err?.message}`, adopted: adopt.adopted });
+ }
+ }
+
+ for (const r of render.results) {
+ if (r.status === 'done') log.info('thumbnail_rendered', { avatar_id: r.id, bytes: r.bytes, ms: r.ms });
+ else log.warn('thumbnail_render_failed', { avatar_id: r.id, message: r.error });
+ }
+
+ const cov = await coverage().catch(() => null);
+
+ return json(res, 200, {
+ ok: true,
+ adopted: adopt.adopted,
+ adopt_missing_objects: adopt.missing,
+ claimed: render.claimed,
+ rendered: render.rendered,
+ failed: render.failed,
+ coverage: cov,
+ results: render.results.map((r) => ({
+ id: r.id,
+ status: r.status,
+ ...(r.status === 'done' ? { url: r.url, bytes: r.bytes, ms: r.ms } : { error: r.error }),
+ })),
+ });
+});
diff --git a/src/irl/privacy-center.js b/src/irl/privacy-center.js
index a9e28763e..adc3808b2 100644
--- a/src/irl/privacy-center.js
+++ b/src/irl/privacy-center.js
@@ -441,7 +441,7 @@ export function openMyDataPanel({ onChanged } = {}) {
<div class="irlpc-sec">
<h4>What we hold</h4>
<div class="irlpc-stats">
- <div class="irlpc-stat"><div class="n">${totalPins}</div><div class="l">placed agent${totalPins === 1 ? '' : 's'}${pins.unpublished ? ` · ${pins.unpublished} hidden` : ''}</div></div>
+ <div class="irlpc-stat"><div class="n">${totalPins}</div><div class="l">placed agent${totalPins === 1 ? '' : 's'}${pins.unpublished ? ` · ${pins.unpublished} private` : ''}</div></div>
<div class="irlpc-stat"><div class="n">${ix.onYourPins || 0}</div><div class="l">encounters on your agents</div></div>
<div class="irlpc-stat"><div class="n">${ix.youLeftElsewhere || 0}</div><div class="l">taps you left elsewhere</div></div>
<div class="irlpc-stat"><div class="n">${pins.permanent || 0}</div><div class="l">permanent · ${pins.expiring || 0} auto-expiring</div></div>
diff --git a/tests/api-img-proxy.test.js b/tests/api-img-proxy.test.js
index 74478f9dd..599e65596 100644
--- a/tests/api-img-proxy.test.js
+++ b/tests/api-img-proxy.test.js
@@ -128,3 +128,109 @@ describe('api/img metadata resolution', () => {
expect(res.statusCode).toBe(400);
});
});
+
+// Serve `doc` as a JSON response and `art` as image bytes, keyed by URL, so a
+// single mock can satisfy both hops of the follow.
+function mockUpstream({ jsonAt = {}, imageAt = {} } = {}) {
+ fetchModel.mockImplementation(async (url) => {
+ if (url in jsonAt) {
+ return {
+ bytes: new TextEncoder().encode(JSON.stringify(jsonAt[url])),
+ url,
+ contentType: 'application/json; charset=utf-8',
+ filename: 'token.json',
+ };
+ }
+ if (url in imageAt) {
+ return { bytes: imageAt[url], url, contentType: 'image/png', filename: 'art.png' };
+ }
+ throw new Error(`upstream 404 ${url}`);
+ });
+}
+
+describe('api/img ?url= metadata follow', () => {
+ const DOC = 'https://meta.example/token.json';
+ const ART = 'https://cdn.example/art.png';
+
+ it('follows a JSON document at ?url= to its .image and proxies the artwork', async () => {
+ mockUpstream({ jsonAt: { [DOC]: { name: 'VOID', image: ART } }, imageAt: { [ART]: new Uint8Array([7, 8, 9]) } });
+
+ const res = mockRes();
+ await handler(mockReq(`?url=${encodeURIComponent(DOC)}&seed=VOID`), res);
+
+ expect(fetchModel).toHaveBeenCalledWith(DOC, expect.any(Object));
+ expect(fetchModel).toHaveBeenCalledWith(ART, expect.any(Object));
+ expect(res.statusCode).toBe(200);
+ expect(res.headers['content-type']).toBe('image/png');
+ expect([...res.body]).toEqual([7, 8, 9]);
+ });
+
+ it('follows only one hop — a document naming another document yields the placeholder', async () => {
+ const DOC2 = 'https://meta.example/nested.json';
+ mockUpstream({ jsonAt: { [DOC]: { image: DOC2 }, [DOC2]: { image: ART } }, imageAt: { [ART]: new Uint8Array([1]) } });
+
+ const res = mockRes();
+ await handler(mockReq(`?url=${encodeURIComponent(DOC)}&seed=DEEP`), res);
+
+ expect(fetchModel).toHaveBeenCalledWith(DOC2, expect.any(Object));
+ expect(fetchModel).not.toHaveBeenCalledWith(ART, expect.any(Object));
+ expect(res.headers['content-type']).toMatch(/image\/svg\+xml/);
+ expect(String(res.body)).toContain('<svg');
+ });
+
+ it('rejects a data: image inside a followed document', async () => {
+ mockUpstream({ jsonAt: { [DOC]: { image: 'data:image/svg+xml,<svg onload=alert(1)>' } } });
+
+ const res = mockRes();
+ await handler(mockReq(`?url=${encodeURIComponent(DOC)}&seed=EVIL`), res);
+
+ expect(fetchModel).toHaveBeenCalledTimes(1); // the doc only — never the data: URI
+ expect(res.headers['content-type']).toMatch(/image\/svg\+xml/);
+ expect(String(res.body)).toContain('<svg');
+ });
+
+ it('serves a direct image at ?url= without taking the JSON path', async () => {
+ mockUpstream({ imageAt: { [ART]: new Uint8Array([4, 2]) } });
+
+ const res = mockRes();
+ await handler(mockReq(`?url=${encodeURIComponent(ART)}&seed=ART`), res);
+
+ expect(fetchModel).toHaveBeenCalledTimes(1);
+ expect(res.headers['content-type']).toBe('image/png');
+ expect([...res.body]).toEqual([4, 2]);
+ });
+
+ it('does not treat a JSON body as artwork on the ?meta= path', async () => {
+ safeFetchJson.mockResolvedValue({ ok: true, data: { image: DOC } });
+ mockUpstream({ jsonAt: { [DOC]: { image: ART } }, imageAt: { [ART]: new Uint8Array([5]) } });
+
+ const res = mockRes();
+ await handler(mockReq(`?meta=${encodeURIComponent(DOC)}&seed=META`), res);
+
+ expect(fetchModel).not.toHaveBeenCalledWith(ART, expect.any(Object));
+ expect(res.headers['content-type']).toMatch(/image\/svg\+xml/);
+ });
+
+ it('races every IPFS gateway for a metadata CID and follows the winner', async () => {
+ const CID = 'bafkreitest';
+ const art = 'https://ipfs.io/ipfs/bafkreiart';
+ fetchModel.mockImplementation(async (url) => {
+ if (url.endsWith(`/ipfs/${CID}`)) {
+ return { bytes: new TextEncoder().encode(JSON.stringify({ image: art })), url, contentType: 'application/json', filename: 'x' };
+ }
+ if (url.includes('bafkreiart')) {
+ return { bytes: new Uint8Array([3]), url, contentType: 'image/webp', filename: 'a' };
+ }
+ throw new Error('nope');
+ });
+
+ const res = mockRes();
+ await handler(mockReq(`?url=${encodeURIComponent(`https://ipfs.io/ipfs/${CID}`)}&seed=CID`), res);
+
+ // Every gateway in the fallback list is attempted for the document.
+ const tried = fetchModel.mock.calls.map((c) => c[0]).filter((u) => u.endsWith(`/ipfs/${CID}`));
+ expect(tried.length).toBeGreaterThan(1);
+ expect(res.headers['content-type']).toBe('image/webp');
+ expect([...res.body]).toEqual([3]);
+ });
+});
diff --git a/tests/api/mcp-memory.test.js b/tests/api/mcp-memory.test.js
index f7be4dff4..255d14593 100644
--- a/tests/api/mcp-memory.test.js
+++ b/tests/api/mcp-memory.test.js
@@ -65,6 +65,26 @@ class MockX402Error extends Error {
vi.mock('../../api/_lib/x402-spec.js', () => ({
X402Error: MockX402Error,
X402_VERSION: 2,
+ // Network constants + pure helpers bound at import time by the wider graph
+ // (a2a-server, paid-endpoint, dev-tools). Values mirror the real module;
+ // payment behavior stays inert via the function overrides below.
+ NETWORK_BASE_MAINNET: 'eip155:8453',
+ NETWORK_BASE_SEPOLIA: 'eip155:84532',
+ NETWORK_ARBITRUM_MAINNET: 'eip155:42161',
+ NETWORK_BSC_MAINNET: 'eip155:56',
+ NETWORK_XLAYER_MAINNET: 'eip155:196',
+ NETWORK_SOLANA_MAINNET: 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp',
+ NETWORK_SOLANA_DEVNET: 'solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1',
+ BUILDER_CODE: 'builder-code',
+ permit2VariantOf: vi.fn(() => null),
+ baseSettleable: vi.fn(() => false),
+ solanaSettleable: vi.fn(() => false),
+ buildExactRequirements: vi.fn(() => []),
+ decodePaymentHeader: vi.fn(() => null),
+ decodeSignedAmount: vi.fn(() => null),
+ decodeSignedRecipient: vi.fn(() => null),
+ probeFacilitators: vi.fn(async () => ({})),
+ buildBazaarSchema: vi.fn(() => ({})),
paymentRequirements: vi.fn(() => [{ scheme: 'exact', network: 'eip155:8453', amount: '1000' }]),
bazaarExtension: vi.fn(() => ({})),
verifyPayment: vi.fn(async () => {
diff --git a/tests/api/mcp.test.js b/tests/api/mcp.test.js
index b4a5ecf02..51a29dddf 100644
--- a/tests/api/mcp.test.js
+++ b/tests/api/mcp.test.js
@@ -67,6 +67,26 @@ const x402State = { verifyOk: false, verifyResult: null };
vi.mock('../../api/_lib/x402-spec.js', () => ({
X402Error: MockX402Error,
X402_VERSION: 2,
+ // Network constants + pure helpers bound at import time by the wider graph
+ // (a2a-server, paid-endpoint, dev-tools). Values mirror the real module;
+ // payment behavior stays inert via the function overrides below.
+ NETWORK_BASE_MAINNET: 'eip155:8453',
+ NETWORK_BASE_SEPOLIA: 'eip155:84532',
+ NETWORK_ARBITRUM_MAINNET: 'eip155:42161',
+ NETWORK_BSC_MAINNET: 'eip155:56',
+ NETWORK_XLAYER_MAINNET: 'eip155:196',
+ NETWORK_SOLANA_MAINNET: 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp',
+ NETWORK_SOLANA_DEVNET: 'solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1',
+ BUILDER_CODE: 'builder-code',
+ permit2VariantOf: vi.fn(() => null),
+ baseSettleable: vi.fn(() => false),
+ solanaSettleable: vi.fn(() => false),
+ buildExactRequirements: vi.fn(() => []),
+ decodePaymentHeader: vi.fn(() => null),
+ decodeSignedAmount: vi.fn(() => null),
+ decodeSignedRecipient: vi.fn(() => null),
+ probeFacilitators: vi.fn(async () => ({})),
+ buildBazaarSchema: vi.fn(() => ({})),
paymentRequirements: vi.fn(() => [
{
scheme: 'exact',
diff --git a/tests/mcp-tool-result.test.js b/tests/mcp-tool-result.test.js
index ca1ab0d4a..5f1ffba0d 100644
--- a/tests/mcp-tool-result.test.js
+++ b/tests/mcp-tool-result.test.js
@@ -170,6 +170,7 @@ describe('MCP tool surface', () => {
'rig_mesh',
'forge_avatar',
'refine_model',
+ 'restyle_material',
'agent_delegate_action',
'agent_hire',
];
diff --git a/vercel.json b/vercel.json
index 2f982389e..7b09ef5d9 100644
--- a/vercel.json
+++ b/vercel.json
@@ -5133,6 +5133,10 @@
"path": "/api/cron/avatar-thumbnail-render",
"schedule": "*/10 * * * *"
},
+ {
+ "path": "/api/cron/avatar-thumbnail-backfill",
+ "schedule": "*/5 * * * *"
+ },
{
"path": "/api/cron/coin-intel-observe",
"schedule": "*/2 * * * *"