Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat: add friends panel with unread message notifications and social presence

fudjia6ead800e7ad2
diff --git a/api/_lib/avatar-thumbs.js b/api/_lib/avatar-thumbs.js
index a73b62246..41de3e37c 100644
--- a/api/_lib/avatar-thumbs.js
+++ b/api/_lib/avatar-thumbs.js
@@ -54,12 +54,6 @@ 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
@@ -334,5 +328,3 @@ export function isMissingThumbnail(thumbnailKey) {
if (isLegacyOgThumbnailKey(thumbnailKey)) return true;
return /^https?:\/\//i.test(thumbnailKey);
}
-
-export const __sqlMissingThumb = MISSING_THUMB_SQL;
diff --git a/api/_lib/avatars.js b/api/_lib/avatars.js
index 3046147d2..0feaada89 100644
--- a/api/_lib/avatars.js
+++ b/api/_lib/avatars.js
@@ -3,7 +3,7 @@
import { createHash } from 'node:crypto';
import { sql } from './db.js';
-import { publicUrl, presignGet, deleteObject } from './r2.js';
+import { publicUrl, thumbnailUrl, presignGet, deleteObject } from './r2.js';
import { defaultStorageMode } from './storage-mode.js';
import { isUuid } from './validate.js';
@@ -390,7 +390,7 @@ export async function listForks({ avatarId, limit = 24, cursor }) {
visibility: r.visibility,
fork_count: Number(r.fork_count || 0),
created_at: r.created_at,
- thumbnail_url: r.thumbnail_key ? publicUrl(r.thumbnail_key) : null,
+ thumbnail_url: thumbnailUrl(r.thumbnail_key),
model_url:
r.visibility === 'public' || r.visibility === 'unlisted'
? publicUrl(r.storage_key)
@@ -498,7 +498,7 @@ function decorate(row) {
? publicUrl(row.storage_key)
: null,
parent_avatar_id: row.parent_avatar_id || null,
- thumbnail_url: row.thumbnail_key ? publicUrl(row.thumbnail_key) : null,
+ thumbnail_url: thumbnailUrl(row.thumbnail_key),
usdz_url: row.usdz_key ? publicUrl(row.usdz_key) : null,
halfbody_url: row.halfbody_key ? publicUrl(row.halfbody_key) : null,
appearance: row.appearance || null,
diff --git a/api/_lib/embed-asset.js b/api/_lib/embed-asset.js
index bf8c3b112..2649ee7a9 100644
--- a/api/_lib/embed-asset.js
+++ b/api/_lib/embed-asset.js
@@ -15,7 +15,7 @@
import { sql } from './db.js';
import { CHAIN_BY_ID } from './erc8004-chains.js';
-import { publicUrl } from './r2.js';
+import { publicUrl, thumbnailUrl } from './r2.js';
import { isUuid } from './validate.js';
export const ONCHAIN_RE = /^(?:eip155:)?(\d{1,9})[:/](\d{1,12})$/;
@@ -88,7 +88,7 @@ export async function resolveEmbedAsset(id) {
name: r.name,
description: r.description || '',
glbUrl: publicUrl(r.storage_key),
- poster: r.thumbnail_key ? publicUrl(r.thumbnail_key) : null,
+ poster: thumbnailUrl(r.thumbnail_key),
has3d: true,
x402: false,
passportUrl: `/avatars/${r.id}`,
diff --git a/api/_lib/r2.js b/api/_lib/r2.js
index 58b89b5f6..ba7d24fc2 100644
--- a/api/_lib/r2.js
+++ b/api/_lib/r2.js
@@ -154,6 +154,22 @@ export function isLegacyOgThumbnailKey(thumbnailKey) {
return /^https?:\/\/.*_og\.png$/i.test(String(thumbnailKey || ''));
}
+// The ONE way to turn a stored thumbnail_key into a URL for an <img>.
+//
+// A thumbnail_key only resolves to a real image when it is a relative R2 key.
+// Legacy poisoned keys (absolute, origin-pointing `*_og.png`) 404 — and a 404
+// answered with a `text/plain` body is refused by Chrome's Opaque Response
+// Blocking when it was requested as an image (net::ERR_BLOCKED_BY_ORB), so the
+// browser logs an error instead of quietly showing nothing. Return null and let
+// the caller render its designed placeholder.
+//
+// Every read path that surfaces a thumbnail to a browser must go through this,
+// not bare publicUrl(). See docs/avatar-thumbnails.md.
+export function thumbnailUrl(thumbnailKey) {
+ if (!thumbnailKey || isLegacyOgThumbnailKey(thumbnailKey)) return null;
+ return publicUrl(thumbnailKey);
+}
+
function encodeR2Key(key) {
return key.split('/').map(encodeURIComponent).join('/');
}
diff --git a/api/agents.js b/api/agents.js
index 0f200f710..d7958afc3 100644
--- a/api/agents.js
+++ b/api/agents.js
@@ -18,7 +18,7 @@ import { requireCsrf } from './_lib/csrf.js';
import { limits, clientIp } from './_lib/rate-limit.js';
import { generateAgentWallet, generateSolanaAgentWallet } from './_lib/agent-wallet.js';
import { checkIdentityIntegrity } from './_lib/identity-integrity.js';
-import { publicUrl } from './_lib/r2.js';
+import { publicUrl, thumbnailUrl } from './_lib/r2.js';
import { pedigreeScore } from './_lib/genome.js';
import { pingIndexNow } from './_lib/indexnow.js';
import { publishFeedEvent } from './_lib/feed.js';
@@ -794,7 +794,7 @@ function decorate(row, isOwner = true) {
// characters.js / galaxy.js) — private avatars must not leak via thumbnails.
const avatarThumbnailUrl =
row.avatar_thumbnail_key && avatarPubliclyReadable
- ? publicUrl(row.avatar_thumbnail_key)
+ ? thumbnailUrl(row.avatar_thumbnail_key)
: null;
const base = {
diff --git a/api/agents/featured.js b/api/agents/featured.js
index 354d919d8..110574d3a 100644
--- a/api/agents/featured.js
+++ b/api/agents/featured.js
@@ -15,7 +15,7 @@
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 { publicUrl } from '../_lib/r2.js';
+import { publicUrl, thumbnailUrl } from '../_lib/r2.js';
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
@@ -60,7 +60,7 @@ export default wrap(async (req, res) => {
const avatar_url =
row.avatar_url ||
row.profile_image_url ||
- (row.avatar_thumbnail_key ? publicUrl(row.avatar_thumbnail_key) : null) ||
+ (row.avatar_thumbnail_key ? thumbnailUrl(row.avatar_thumbnail_key) : null) ||
(row.avatar_storage_key && avatarPublic ? publicUrl(row.avatar_storage_key) : null) ||
null;
diff --git a/api/agents/onchain/[action].js b/api/agents/onchain/[action].js
index 27806ab1a..07e4fa483 100644
--- a/api/agents/onchain/[action].js
+++ b/api/agents/onchain/[action].js
@@ -26,7 +26,7 @@ import { cors, json, method, readJson, wrap, error, rateLimited, serverError, re
import { limits, clientIp } from '../../_lib/rate-limit.js';
import { parse } from '../../_lib/validate.js';
import { randomToken } from '../../_lib/crypto.js';
-import { r2, publicUrl } from '../../_lib/r2.js';
+import { r2, publicUrl, thumbnailUrl } from '../../_lib/r2.js';
import { env } from '../../_lib/env.js';
import { publishFeedEvent } from '../../_lib/feed.js';
import {
@@ -328,7 +328,7 @@ async function handlePrep(req, res) {
limit 1
`;
if (!av) return error(res, 404, 'not_found', 'avatar not found');
- if (av.thumbnail_key) avatarImage = publicUrl(av.thumbnail_key);
+ avatarImage = thumbnailUrl(av.thumbnail_key) || avatarImage;
if (av.storage_key) avatarAnimationUrl = publicUrl(av.storage_key);
}
diff --git a/api/agents/public.js b/api/agents/public.js
index a10bbb59d..5bf4e7619 100644
--- a/api/agents/public.js
+++ b/api/agents/public.js
@@ -31,7 +31,7 @@
import { cors, json, method, wrap, rateLimited } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
import { sql } from '../_lib/db.js';
-import { publicUrl } from '../_lib/r2.js';
+import { thumbnailUrl } from '../_lib/r2.js';
const SORTS = new Set(['newest', 'popular', 'name', 'live']);
@@ -44,7 +44,7 @@ function mapAgent(r) {
const meta = r.meta || {};
const onchain = meta.onchain || null;
const thumbPub = r.avatar_visibility === 'public' || r.avatar_visibility === 'unlisted';
- const thumbnail = r.avatar_thumbnail_key && thumbPub ? publicUrl(r.avatar_thumbnail_key) : null;
+ const thumbnail = r.avatar_thumbnail_key && thumbPub ? thumbnailUrl(r.avatar_thumbnail_key) : null;
return {
id: r.id,
diff --git a/api/agents/solana/_handlers.js b/api/agents/solana/_handlers.js
index 3972ef363..7b664a660 100644
--- a/api/agents/solana/_handlers.js
+++ b/api/agents/solana/_handlers.js
@@ -14,7 +14,7 @@ import { getSessionUser } from '../../_lib/auth.js';
import { parse } from '../../_lib/validate.js';
import { randomToken } from '../../_lib/crypto.js';
import { env } from '../../_lib/env.js';
-import { publicUrl } from '../../_lib/r2.js';
+import { publicUrl, thumbnailUrl } from '../../_lib/r2.js';
import { buildAgentManifest, buildAgentOnchainAttributes, agentRoyaltyConfig, skillCollectionSymbol, THREE_WS } from '../../_lib/three-brand.js';
import {
getAgentCollection,
@@ -351,7 +351,7 @@ export const handleMetadata = wrap(async (req, res) => {
avatarId = a.avatar_id || null;
if (a.avatar_id) {
const [av] = await sql`select storage_key, thumbnail_key from avatars where id = ${a.avatar_id} and deleted_at is null limit 1`;
- if (av?.thumbnail_key) image = publicUrl(av.thumbnail_key);
+ image = thumbnailUrl(av?.thumbnail_key) || image;
if (av?.storage_key) animationUrl = publicUrl(av.storage_key);
}
}
@@ -552,7 +552,7 @@ export const handleRegisterPrep = wrap(async (req, res) => {
if (avatar_id) {
const [av] = await sql`select id, storage_key, thumbnail_key from avatars where id=${avatar_id} and owner_id=${user.id} and deleted_at is null limit 1`;
if (!av) return error(res, 404, 'not_found', 'avatar not found');
- if (av.thumbnail_key) avatarImg = publicUrl(av.thumbnail_key);
+ avatarImg = thumbnailUrl(av.thumbnail_key) || avatarImg;
if (av.storage_key) avatarAnim = publicUrl(av.storage_key);
}
@@ -808,7 +808,7 @@ export const handleSkillCollectionMetadata = wrap(async (req, res) => {
let image = THREE_WS.ogImage;
if (agent.avatar_id) {
const [av] = await sql`select thumbnail_key from avatars where id = ${agent.avatar_id} and deleted_at is null limit 1`;
- if (av?.thumbnail_key) image = publicUrl(av.thumbnail_key);
+ image = thumbnailUrl(av?.thumbnail_key) || image;
}
const name = `${agent.name} — Skills`;
@@ -862,7 +862,7 @@ export const handleSkillNftMetadata = wrap(async (req, res) => {
let image = THREE_WS.ogImage;
if (agent.avatar_id) {
const [av] = await sql`select thumbnail_key from avatars where id = ${agent.avatar_id} and deleted_at is null limit 1`;
- if (av?.thumbnail_key) image = publicUrl(av.thumbnail_key);
+ image = thumbnailUrl(av?.thumbnail_key) || image;
}
const name = `${agent.name}: ${skill}`;
diff --git a/api/agents/suggest.js b/api/agents/suggest.js
index 753380af8..9d0563818 100644
--- a/api/agents/suggest.js
+++ b/api/agents/suggest.js
@@ -2,7 +2,7 @@
// Public autocomplete for @-mention surfaces. Returns ranked agents matching q.
import { sql } from '../_lib/db.js';
-import { publicUrl } from '../_lib/r2.js';
+import { thumbnailUrl } from '../_lib/r2.js';
import { cors, json, method, wrap, rateLimited } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
@@ -51,7 +51,7 @@ export default wrap(async (req, res) => {
id: r.id,
name: r.name,
slug: r.name.toLowerCase().replace(/[^a-z0-9-]/g, '-'),
- thumbnailUrl: r.thumbnail_key ? publicUrl(r.thumbnail_key) : null,
+ thumbnailUrl: thumbnailUrl(r.thumbnail_key),
...(r.chain_id != null ? { chainId: r.chain_id } : {}),
onChain: r.erc8004_agent_id != null,
}));
diff --git a/api/animations/[id].js b/api/animations/[id].js
index 84caea61c..ea4534ba6 100644
--- a/api/animations/[id].js
+++ b/api/animations/[id].js
@@ -9,7 +9,7 @@
import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';
import { sql } from '../_lib/db.js';
import { cors, json, method, readJson, wrap, error } from '../_lib/http.js';
-import { getObjectBuffer, publicUrl } from '../_lib/r2.js';
+import { getObjectBuffer, thumbnailUrl } from '../_lib/r2.js';
import { clipSchema, editorDocSchema, validateClipTrackStrides, materializeClip } from './clips.js';
import { z } from 'zod';
@@ -112,7 +112,7 @@ async function handleGet(req, res, auth, id) {
tags: row.tags || [],
visibility: row.visibility,
avatar_id: row.avatar_id,
- thumbnail_url: row.thumbnail_key ? publicUrl(row.thumbnail_key) : null,
+ thumbnail_url: thumbnailUrl(row.thumbnail_key),
play_count: Number(row.play_count || 0),
purchase_count: Number(row.purchase_count || 0),
listed: !!row.listed,
diff --git a/api/animations/clips.js b/api/animations/clips.js
index 1ed00ffd1..767142198 100644
--- a/api/animations/clips.js
+++ b/api/animations/clips.js
@@ -12,7 +12,7 @@
import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';
import { sql } from '../_lib/db.js';
import { cors, json, method, readJson, wrap, error, rateLimited } from '../_lib/http.js';
-import { putObject, publicUrl } from '../_lib/r2.js';
+import { putObject, thumbnailUrl } from '../_lib/r2.js';
import { limits } from '../_lib/rate-limit.js';
import { z } from 'zod';
@@ -244,7 +244,7 @@ function listItem(row, auth) {
tags: row.tags || [],
visibility: row.visibility,
avatar_id: row.avatar_id,
- thumbnail_url: row.thumbnail_key ? publicUrl(row.thumbnail_key) : null,
+ thumbnail_url: thumbnailUrl(row.thumbnail_key),
play_count: Number(row.play_count || 0),
purchase_count: Number(row.purchase_count || 0),
listed: !!row.listed,
diff --git a/api/animations/sell.js b/api/animations/sell.js
index 713a57f62..fd2b9762b 100644
--- a/api/animations/sell.js
+++ b/api/animations/sell.js
@@ -23,7 +23,7 @@ import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../
import { sql } from '../_lib/db.js';
import { cors, json, method, readJson, wrap, error, rateLimited } from '../_lib/http.js';
import { limits } from '../_lib/rate-limit.js';
-import { publicUrl } from '../_lib/r2.js';
+import { thumbnailUrl } from '../_lib/r2.js';
import { z } from 'zod';
// USDC only for now — the x402 facilitator settles USDC on Base + Solana.
@@ -196,7 +196,7 @@ function shape(row, payto) {
price: row.price_amount ? { amount: String(row.price_amount), currency: row.price_currency } : null,
artifact_bytes: row.artifact_bytes != null ? Number(row.artifact_bytes) : null,
artifact_mime: row.artifact_mime || null,
- thumbnail_url: row.thumbnail_key ? publicUrl(row.thumbnail_key) : null,
+ thumbnail_url: thumbnailUrl(row.thumbnail_key),
purchase_count: Number(row.purchase_count || 0),
payout: { base: payto.base || null, solana: payto.solana || null, bsc: payto.bsc || null },
};
diff --git a/api/app-og.js b/api/app-og.js
index 17f5376ea..3c87f2b9e 100644
--- a/api/app-og.js
+++ b/api/app-og.js
@@ -13,7 +13,7 @@
*/
import { sql } from './_lib/db.js';
-import { publicUrl } from './_lib/r2.js';
+import { thumbnailUrl } from './_lib/r2.js';
import { env } from './_lib/env.js';
import { cors, wrap } from './_lib/http.js';
@@ -46,7 +46,7 @@ export default wrap(async (req, res) => {
const desc = agent.description || 'An embodied AI agent on three.ws — with a body, a place, and an identity.';
const thumbnailUrl = agent.avatar_thumbnail_key
- ? publicUrl(agent.avatar_thumbnail_key)
+ ? thumbnailUrl(agent.avatar_thumbnail_key)
: null;
const ogImage = thumbnailUrl
|| `${origin}/api/agent/${agentId}/og`;
diff --git a/api/auth/persona/[action].js b/api/auth/persona/[action].js
index 26559cd7f..e380c30c4 100644
--- a/api/auth/persona/[action].js
+++ b/api/auth/persona/[action].js
@@ -35,7 +35,7 @@ import { SignJWT, jwtVerify, importPKCS8, importSPKI, exportJWK } from 'jose';
import { getSessionUser } from '../../_lib/auth.js';
import { sql } from '../../_lib/db.js';
import { env } from '../../_lib/env.js';
-import { publicUrl } from '../../_lib/r2.js';
+import { publicUrl, thumbnailUrl } from '../../_lib/r2.js';
import { randomToken } from '../../_lib/crypto.js';
import { cors, json, error, method, readJson, wrap } from '../../_lib/http.js';
@@ -132,7 +132,7 @@ async function loadAvatarForUser(userId, avatarId) {
id: row.id,
name: row.name,
url: publicUrl(row.storage_key),
- thumbnail_url: row.thumbnail_key ? publicUrl(row.thumbnail_key) : null,
+ thumbnail_url: thumbnailUrl(row.thumbnail_key),
};
}
@@ -271,7 +271,7 @@ async function handleMe(req, res) {
id: r.id,
name: r.name,
url: publicUrl(r.storage_key),
- thumbnail_url: r.thumbnail_key ? publicUrl(r.thumbnail_key) : null,
+ thumbnail_url: thumbnailUrl(r.thumbnail_key),
created_at: r.created_at,
visibility: r.visibility,
}));
diff --git a/api/avatars/[id]/[action].js b/api/avatars/[id]/[action].js
index a332c8e33..cf9d09452 100644
--- a/api/avatars/[id]/[action].js
+++ b/api/avatars/[id]/[action].js
@@ -14,7 +14,7 @@ import { limits, clientIp } from '../../_lib/rate-limit.js';
import { parse, isUuid } from '../../_lib/validate.js';
import { readStorageMode, storageModeSchema, defaultStorageMode } from '../../_lib/storage-mode.js';
import { getAvatar, resolveAvatarUrl } from '../../_lib/avatars.js';
-import { r2, publicUrl } from '../../_lib/r2.js';
+import { r2, publicUrl, thumbnailUrl } from '../../_lib/r2.js';
import { env } from '../../_lib/env.js';
const PINATA_ENDPOINT = 'https://api.pinata.cloud/pinning/pinFileToIPFS';
@@ -553,7 +553,7 @@ async function handleThumbnail(req, res) {
if (!row.thumbnail_key) return error(res, 404, 'not_found', 'avatar has no thumbnail');
- return redirect(res, publicUrl(row.thumbnail_key));
+ return redirect(res, thumbnailUrl(row.thumbnail_key));
}
function redirect(res, url) {
@@ -591,7 +591,7 @@ async function handleThumb(req, res) {
if (!row) return error(res, 404, 'not_found', 'avatar not found');
if (!row.thumbnail_key) return error(res, 404, 'not_found', 'avatar has no thumbnail');
- return redirect(res, publicUrl(row.thumbnail_key));
+ return redirect(res, thumbnailUrl(row.thumbnail_key));
}
// ── glb (same-origin CORS-friendly proxy) ─────────────────────────────────
diff --git a/api/avatars/_actions.js b/api/avatars/_actions.js
index aa266181f..7a74e7bdc 100644
--- a/api/avatars/_actions.js
+++ b/api/avatars/_actions.js
@@ -919,8 +919,18 @@ const handleAutoTag = wrap(async (req, res) => {
}
// Fetch the thumbnail from R2 for vision.
- const { publicUrl } = await import('../_lib/r2.js');
+ const { publicUrl, headObject } = await import('../_lib/r2.js');
const { env } = await import('../_lib/env.js');
+
+ // `thumb_key` is caller-supplied. Ownership was checked above, but nothing has
+ // checked that an object actually lives there — the caller may never have
+ // completed the upload. Confirm it before we (a) spend a vision call on a URL
+ // that 404s and (b) write the key into avatars.thumbnail_key, from where
+ // decorate() would publish it into an <img> that Chrome blocks as ORB.
+ // The invariant: a thumbnail_key is persisted only after its object exists.
+ if (!(await headObject(thumbKey))) {
+ return error(res, 404, 'thumbnail_not_found', 'no object stored at thumb_key — upload the thumbnail first');
+ }
const thumbUrl = publicUrl(thumbKey);
// Image classification needs a vision-capable model. Per platform policy
diff --git a/api/avatars/fork.js b/api/avatars/fork.js
index 4d6390ddb..5154d691d 100644
--- a/api/avatars/fork.js
+++ b/api/avatars/fork.js
@@ -96,13 +96,23 @@ export default wrap(async (req, res) => {
const copiedGlb = await copyObject({ fromKey: src.storage_key, toKey: newStorageKey });
if (!copiedGlb) newStorageKey = src.storage_key; // hosted URL — pass through
- // Best-effort thumbnail copy. Never fatal — the gallery falls back to the name.
+ // Best-effort thumbnail copy. Never fatal — the gallery falls back to its
+ // initial-letter placeholder and the backfill cron renders a real thumbnail
+ // for the fork later. Two rules, both load-bearing (docs/avatar-thumbnails.md):
+ //
+ // • copyObject() returns false when the source key is an absolute URL —
+ // there is no bucket object to copy. Adopting that URL as the fork's
+ // thumbnail_key would clone a key publicUrl() resolves against an origin
+ // that holds no object.
+ // • A thumbnail_key is persisted only after its object is confirmed present.
+ // A silently-failed copy would otherwise leave the fork pointing at a 404,
+ // which the browser blocks as ORB rather than rendering.
let newThumbKey = null;
if (src.thumbnail_key) {
try {
const candidate = `u/${auth.userId}/${slugBase}/${Date.now().toString(36)}-thumb.png`;
const copiedThumb = await copyObject({ fromKey: src.thumbnail_key, toKey: candidate });
- newThumbKey = copiedThumb ? candidate : src.thumbnail_key;
+ if (copiedThumb && (await headObject(candidate))) newThumbKey = candidate;
} catch (e) {
console.warn('[fork] thumbnail copy failed', e?.message);
}
diff --git a/api/characters.js b/api/characters.js
index 35f87375d..e9fd11469 100644
--- a/api/characters.js
+++ b/api/characters.js
@@ -12,7 +12,7 @@ import { sql } from './_lib/db.js';
import { cors, json, method, wrap, rateLimited } from './_lib/http.js';
import { clampInt } from './_lib/http-params.js';
import { limits, clientIp } from './_lib/rate-limit.js';
-import { publicUrl } from './_lib/r2.js';
+import { thumbnailUrl } from './_lib/r2.js';
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
@@ -78,7 +78,7 @@ export default wrap(async (req, res) => {
const meta = row.meta || {};
const avatarThumbnail =
row.avatar_thumbnail_key && (row.avatar_visibility === 'public' || row.avatar_visibility === 'unlisted')
- ? publicUrl(row.avatar_thumbnail_key)
+ ? thumbnailUrl(row.avatar_thumbnail_key)
: null;
const imageUrl =
diff --git a/api/creators/[id].js b/api/creators/[id].js
index 3bda0b014..e26ec5caf 100644
--- a/api/creators/[id].js
+++ b/api/creators/[id].js
@@ -11,7 +11,7 @@
import { sql } from '../_lib/db.js';
import { cors, error, json, method, wrap, rateLimited } from '../_lib/http.js';
-import { publicUrl } from '../_lib/r2.js';
+import { publicUrl, thumbnailUrl } from '../_lib/r2.js';
import { clientIp, limits } from '../_lib/rate-limit.js';
import { isUuid } from '../_lib/validate.js';
@@ -75,7 +75,7 @@ export default wrap(async (req, res) => {
description: a.description,
category: a.category,
tags: a.tags || [],
- thumbnail_url: a.thumbnail_key ? publicUrl(a.thumbnail_key) : null,
+ thumbnail_url: thumbnailUrl(a.thumbnail_key),
skills: a.skills || [],
forks_count: a.forks_count || 0,
views_count: a.views_count || 0,
@@ -90,7 +90,7 @@ export default wrap(async (req, res) => {
slug: a.slug,
name: a.name,
description: a.description,
- thumbnail_url: a.thumbnail_key ? publicUrl(a.thumbnail_key) : null,
+ thumbnail_url: thumbnailUrl(a.thumbnail_key),
glb_url: a.storage_key ? publicUrl(a.storage_key) : null,
tags: a.tags || [],
created_at: a.created_at,
diff --git a/api/discover-detail.js b/api/discover-detail.js
index 464753ffd..1fe77b918 100644
--- a/api/discover-detail.js
+++ b/api/discover-detail.js
@@ -15,7 +15,7 @@
import { sql } from './_lib/db.js';
import { cors, method, wrap } from './_lib/http.js';
import { CHAIN_BY_ID, tokenExplorerUrl, addressExplorerUrl } from './_lib/erc8004-chains.js';
-import { publicUrl } from './_lib/r2.js';
+import { publicUrl, thumbnailUrl } from './_lib/r2.js';
import { env } from './_lib/env.js';
export default wrap(async (req, res) => {
@@ -94,7 +94,7 @@ export default wrap(async (req, res) => {
if (rows.length) {
const r = rows[0];
const network = r.meta?.network || 'mainnet';
- const thumb = r.avatar_thumb ? publicUrl(r.avatar_thumb) : null;
+ const thumb = thumbnailUrl(r.avatar_thumb);
item = {
kind: 'solana',
asset,
@@ -144,7 +144,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/explore-item.js b/api/explore-item.js
index 84ada38c3..347ef54da 100644
--- a/api/explore-item.js
+++ b/api/explore-item.js
@@ -10,7 +10,7 @@ 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, thumbnailUrl } from './_lib/r2.js';
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
@@ -106,7 +106,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 || [],
@@ -145,7 +145,7 @@ export default wrap(async (req, res) => {
const r = rows[0];
const asset = r.meta?.sol_mint_address;
const network = r.meta?.network || 'mainnet';
- const thumb = r.avatar_thumb ? publicUrl(r.avatar_thumb) : null;
+ const thumb = thumbnailUrl(r.avatar_thumb);
const item = {
kind: 'solana',
asset,
diff --git a/api/explore.js b/api/explore.js
index be36f7483..c655c1cc6 100644
--- a/api/explore.js
+++ b/api/explore.js
@@ -29,16 +29,9 @@ import { cacheWrap } from './_lib/cache.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, isLegacyOgThumbnailKey } from './_lib/r2.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);
-}
+// thumbnailUrl() drops keys that can't resolve to a real image (see r2.js) so a
+// gallery renders its placeholder instead of a 404 the browser blocks as ORB.
+import { publicUrl, thumbnailUrl } from './_lib/r2.js';
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
@@ -221,7 +214,7 @@ export default wrap(async (req, res) => {
const solanaItems = solanaRows.map((r) => {
const asset = r.meta?.sol_mint_address;
- const thumb = r.avatar_thumb ? publicUrl(r.avatar_thumb) : null;
+ const thumb = thumbnailUrl(r.avatar_thumb);
return {
kind: 'solana',
source: 'three.ws',
diff --git a/api/galaxy.js b/api/galaxy.js
index 2fb63a34a..112ac382c 100644
--- a/api/galaxy.js
+++ b/api/galaxy.js
@@ -23,7 +23,7 @@ import { cacheWrap } from './_lib/cache.js';
import { cors, json, method, readJson, wrap, error, rateLimited } from './_lib/http.js';
import { clampInt } from './_lib/http-params.js';
import { limits, clientIp } from './_lib/rate-limit.js';
-import { publicUrl } from './_lib/r2.js';
+import { thumbnailUrl } from './_lib/r2.js';
import { watsonxConfig, watsonxEmbed, watsonxChatComplete } from './_lib/watsonx.js';
import { ensureAgentEmbeddings, readAgentVectors } from './_lib/agent-embeddings.js';
import {
@@ -253,7 +253,7 @@ async function loadPublishedAgents(limit) {
const thumbnail =
row.avatar_thumbnail_key &&
(row.avatar_visibility === 'public' || row.avatar_visibility === 'unlisted')
- ? publicUrl(row.avatar_thumbnail_key)
+ ? thumbnailUrl(row.avatar_thumbnail_key)
: meta.profile_image_url || meta.thumbnail_url || meta.avatar_url || null;
const token = meta.token || null;
return {
diff --git a/api/ibm/vision.js b/api/ibm/vision.js
index 1c12df3a5..9f84a2d77 100644
--- a/api/ibm/vision.js
+++ b/api/ibm/vision.js
@@ -21,7 +21,7 @@
import { sql } from '../_lib/db.js';
import { cors, method, readJson, error, json, wrap, rateLimited } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
-import { publicUrl } from '../_lib/r2.js';
+import { publicUrl, thumbnailUrl } from '../_lib/r2.js';
import { watsonxConfig, watsonxChatComplete } from '../_lib/watsonx.js';
import { assertSafePublicUrl } from '../_lib/ssrf-guard.js';
@@ -139,7 +139,7 @@ async function handleSubjects(req, res) {
id: r.id,
name: r.name || 'Avatar',
slug: r.slug || null,
- thumbnail: publicUrl(r.thumbnail_key),
+ thumbnail: thumbnailUrl(r.thumbnail_key),
model_url: publicUrl(r.storage_key),
}));
// Subjects list changes at most once an hour; cache aggressively so the demo
diff --git a/api/irl/agent-card.js b/api/irl/agent-card.js
index 8b63e803a..2cb7cde8c 100644
--- a/api/irl/agent-card.js
+++ b/api/irl/agent-card.js
@@ -36,7 +36,7 @@
import { cors, json, error, method, wrap, rateLimited } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
import { sql } from '../_lib/db.js';
-import { publicUrl } from '../_lib/r2.js';
+import { thumbnailUrl } from '../_lib/r2.js';
import { getRedis } from '../_lib/redis.js';
import { atomicsToUsdc, serviceResourceUrl } from '../_lib/agent-paid-services.js';
@@ -184,7 +184,7 @@ async function buildCard(agentId, fallback = {}) {
id: agent.id,
name: agent.name || fallback.name || 'Agent',
bio: bio || fallback.description || null,
- thumbnail_url: agent.avatar_thumbnail_key && thumbPub ? publicUrl(agent.avatar_thumbnail_key) : null,
+ thumbnail_url: agent.avatar_thumbnail_key && thumbPub ? thumbnailUrl(agent.avatar_thumbnail_key) : null,
profile_url: agent.home_url || `/agents/${agent.id}`,
// Public custodial wallet (same value GET /api/agents/:id/solana serves
// anonymously) so the IRL inspect card can render the wallet chip + Tip.
diff --git a/api/marketplace/[action].js b/api/marketplace/[action].js
index 974f790e7..c74423d15 100644
--- a/api/marketplace/[action].js
+++ b/api/marketplace/[action].js
@@ -20,7 +20,7 @@
import { sql, isDbUnavailableError } from '../_lib/db.js';
import { authenticateBearer, extractBearer, getSessionUser } from '../_lib/auth.js';
import { cors, error, json, method, readJson, wrap, rateLimited } from '../_lib/http.js';
-import { publicUrl } from '../_lib/r2.js';
+import { publicUrl, thumbnailUrl } from '../_lib/r2.js';
import { pedigreeScore } from '../_lib/genome.js';
import { clientIp, limits } from '../_lib/rate-limit.js';
import { markProviderCooldown, AUTH_COOLDOWN_SECONDS } from '../_lib/provider-health.js';
@@ -270,7 +270,7 @@ async function handleTheme(req, res) {
forks_count: row.forks_count || 0,
rating_avg: Number(row.rating_avg || 0),
rating_count: row.rating_count || 0,
- thumbnail_url: row.thumbnail_key ? publicUrl(row.thumbnail_key) : null,
+ thumbnail_url: thumbnailUrl(row.thumbnail_key),
avatar_glb_url: row.avatar_storage_key ? publicUrl(row.avatar_storage_key) : null,
published_at: row.published_at,
}));
@@ -1426,7 +1426,7 @@ function toCard(row) {
category: row.category,
tags: row.tags || [],
avatar_id: row.avatar_id,
- thumbnail_url: row.thumbnail_key ? publicUrl(row.thumbnail_key) : null,
+ thumbnail_url: thumbnailUrl(row.thumbnail_key),
avatar_glb_url: row.avatar_storage_key && avatarPublic ? publicUrl(row.avatar_storage_key) : null,
author_id: row.user_id,
skills: row.skills || [],
diff --git a/api/marketplace/animations.js b/api/marketplace/animations.js
index b381d2a35..039b71086 100644
--- a/api/marketplace/animations.js
+++ b/api/marketplace/animations.js
@@ -16,7 +16,7 @@
import { sql } from '../_lib/db.js';
import { cors, error, json, method, wrap } from '../_lib/http.js';
-import { publicUrl } from '../_lib/r2.js';
+import { thumbnailUrl } from '../_lib/r2.js';
import { isUuid } from '../_lib/validate.js';
const SORTS = {
@@ -145,7 +145,7 @@ function shape(row) {
fps: row.fps,
loop: row.loop,
tags: row.tags || [],
- thumbnail_url: row.thumbnail_key ? publicUrl(row.thumbnail_key) : null,
+ thumbnail_url: thumbnailUrl(row.thumbnail_key),
price: paid ? { amount: String(row.price_amount), currency: row.price_currency || 'USDC' } : null,
free: !paid,
size_bytes: row.artifact_bytes != null ? Number(row.artifact_bytes) : null,
diff --git a/api/me.js b/api/me.js
index bb351778f..cd8ae6e1b 100644
--- a/api/me.js
+++ b/api/me.js
@@ -11,7 +11,7 @@ import { getSessionUser, authenticateBearer, extractBearer } from './_lib/auth.j
import { sql } from './_lib/db.js';
import { cors, error, json, method, wrap, rateLimited } from './_lib/http.js';
import { limits, clientIp } from './_lib/rate-limit.js';
-import { publicUrl } from './_lib/r2.js';
+import { thumbnailUrl } from './_lib/r2.js';
async function resolveAuth(req) {
const session = await getSessionUser(req);
@@ -54,7 +54,7 @@ export default wrap(async (req, res) => {
username: handle,
display_name: user.display_name || handle || 'three.ws user',
handle: handle ? `@${handle}` : (user.display_name || 'signed in'),
- avatar_url: user.thumbnail_key ? publicUrl(user.thumbnail_key) : null,
+ avatar_url: thumbnailUrl(user.thumbnail_key),
created_at: user.created_at,
},
});
diff --git a/api/reputation/leaderboard.js b/api/reputation/leaderboard.js
index f2e67a5d3..049a28546 100644
--- a/api/reputation/leaderboard.js
+++ b/api/reputation/leaderboard.js
@@ -16,7 +16,7 @@
import { cors, json, method, wrap, rateLimited } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
import { sql } from '../_lib/db.js';
-import { publicUrl } from '../_lib/r2.js';
+import { thumbnailUrl } from '../_lib/r2.js';
import { getRedis } from '../_lib/redis.js';
import { scoreAgentsLite } from '../_lib/trust/wallet-reputation.js';
@@ -78,7 +78,7 @@ export default wrap(async (req, res) => {
rank: idx + 1,
id,
name: r.name || null,
- avatar_thumbnail_url: r.avatar_thumbnail_key && thumbPub ? publicUrl(r.avatar_thumbnail_key) : null,
+ avatar_thumbnail_url: r.avatar_thumbnail_key && thumbPub ? thumbnailUrl(r.avatar_thumbnail_key) : null,
solana_address: typeof r.solana_address === 'string' ? r.solana_address : null,
score: rep.score,
tier: rep.tier,
diff --git a/api/trending.js b/api/trending.js
index 16f846544..8a3d8e6eb 100644
--- a/api/trending.js
+++ b/api/trending.js
@@ -21,7 +21,7 @@
import { cors, json, method, wrap, rateLimited } from './_lib/http.js';
import { limits, clientIp } from './_lib/rate-limit.js';
import { sql } from './_lib/db.js';
-import { publicUrl } from './_lib/r2.js';
+import { thumbnailUrl } from './_lib/r2.js';
const WINDOWS = new Set(['24h', '7d', 'all']);
const WINDOW_INTERVAL = { '24h': '1 day', '7d': '7 days' };
@@ -99,7 +99,7 @@ export default wrap(async (req, res) => {
const meta = r.meta || {};
const isOnchain = Boolean(meta.onchain || meta.sol_mint_address);
const thumbPub = r.avatar_visibility === 'public' || r.avatar_visibility === 'unlisted';
- const thumb = r.avatar_thumbnail_key && thumbPub ? publicUrl(r.avatar_thumbnail_key) : null;
+ const thumb = r.avatar_thumbnail_key && thumbPub ? thumbnailUrl(r.avatar_thumbnail_key) : null;
return {
rank: idx + 1,
id: r.id,
diff --git a/api/users/[username].js b/api/users/[username].js
index 2d6a6844f..52e4799ae 100644
--- a/api/users/[username].js
+++ b/api/users/[username].js
@@ -1,7 +1,7 @@
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 { publicUrl } from '../_lib/r2.js';
+import { publicUrl, thumbnailUrl } from '../_lib/r2.js';
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,OPTIONS', credentials: false })) return;
@@ -177,7 +177,7 @@ export default wrap(async (req, res) => {
slug: a.slug,
name: a.name,
description: a.description,
- thumbnail_url: a.thumbnail_key ? publicUrl(a.thumbnail_key) : null,
+ thumbnail_url: thumbnailUrl(a.thumbnail_key),
model_url: a.storage_key ? publicUrl(a.storage_key) : null,
size_bytes: Number(a.size_bytes || 0),
source: a.source,
@@ -233,9 +233,7 @@ export default wrap(async (req, res) => {
const isAgent = r.item_type === 'agent';
const name = r.avatar_name || r.agent_name || r.plugin_name || 'Item';
const image = isAvatar
- ? r.thumbnail_key
- ? publicUrl(r.thumbnail_key)
- : null
+ ? thumbnailUrl(r.thumbnail_key)
: isAgent
? r.profile_image_url || r.avatar_url || null
: null;
diff --git a/api/users/[username]/avatar.js b/api/users/[username]/avatar.js
index 57d2c44a9..f4ad2cfb5 100644
--- a/api/users/[username]/avatar.js
+++ b/api/users/[username]/avatar.js
@@ -29,7 +29,7 @@
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 { publicUrl } from '../../_lib/r2.js';
+import { publicUrl, thumbnailUrl } from '../../_lib/r2.js';
import { env } from '../../_lib/env.js';
const VALID_LOD = new Set(['0', '1', '2']);
@@ -155,7 +155,7 @@ export default wrap(async (req, res) => {
slug: avatar.slug,
name: avatar.name,
description: avatar.description,
- thumbnail_url: avatar.thumbnail_key ? publicUrl(avatar.thumbnail_key) : null,
+ thumbnail_url: thumbnailUrl(avatar.thumbnail_key),
model_url: modelUrl,
base_model_url: baseModelUrl,
size_bytes: Number(avatar.size_bytes || 0),
diff --git a/api/users/me/bookmarks.js b/api/users/me/bookmarks.js
index 4bbfd2bba..46d07dfe3 100644
--- a/api/users/me/bookmarks.js
+++ b/api/users/me/bookmarks.js
@@ -8,7 +8,7 @@ import { sql } from '../../_lib/db.js';
import { authenticateBearer, extractBearer, getSessionUser } from '../../_lib/auth.js';
import { cors, error, json, method, wrap, rateLimited } from '../../_lib/http.js';
import { clientIp, limits } from '../../_lib/rate-limit.js';
-import { publicUrl } from '../../_lib/r2.js';
+import { thumbnailUrl } from '../../_lib/r2.js';
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
@@ -43,7 +43,7 @@ export default wrap(async (req, res) => {
agent_name: r.agent_name,
agent_description: r.agent_description,
agent_category: r.agent_category,
- agent_thumbnail: r.thumbnail_key ? publicUrl(r.thumbnail_key) : null,
+ agent_thumbnail: thumbnailUrl(r.thumbnail_key),
}));
return json(
diff --git a/api/users/me/feed.js b/api/users/me/feed.js
index 7d7600b90..d5d6a29aa 100644
--- a/api/users/me/feed.js
+++ b/api/users/me/feed.js
@@ -17,7 +17,7 @@ import { sql } from '../../_lib/db.js';
import { cors, json, method, wrap, error, rateLimited } from '../../_lib/http.js';
import { getSessionUser } from '../../_lib/auth.js';
import { limits, clientIp } from '../../_lib/rate-limit.js';
-import { publicUrl } from '../../_lib/r2.js';
+import { publicUrl, thumbnailUrl } from '../../_lib/r2.js';
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
@@ -96,7 +96,7 @@ export default wrap(async (req, res) => {
actor: actor(r),
title: r.name,
href: `/avatars/${r.id}`,
- image: r.thumbnail_key ? publicUrl(r.thumbnail_key) : null,
+ image: thumbnailUrl(r.thumbnail_key),
});
}
diff --git a/api/walk/leaderboard.js b/api/walk/leaderboard.js
index d278c282c..f45a495e6 100644
--- a/api/walk/leaderboard.js
+++ b/api/walk/leaderboard.js
@@ -21,7 +21,7 @@ import { cors, method, json, wrap, rateLimited, error } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
import { sql } from '../_lib/db.js';
import { getSessionUser, extractBearer, authenticateBearer } from '../_lib/auth.js';
-import { publicUrl } from '../_lib/r2.js';
+import { thumbnailUrl } from '../_lib/r2.js';
export const maxDuration = 10;
@@ -192,7 +192,7 @@ export default wrap(async (req, res) => {
handle,
profileUrl: prof?.username ? `/u/${prof.username}` : null,
avatarId: prof?.avatar_id || null,
- avatar: prof?.thumbnail_key ? publicUrl(prof.thumbnail_key) : null,
+ avatar: thumbnailUrl(prof?.thumbnail_key),
value: Math.round(w.value * 100) / 100,
deltaFromYesterday: Math.round((metricNow(key) - metricPrev(key)) * 100) / 100,
};
diff --git a/docs/avatar-thumbnails.md b/docs/avatar-thumbnails.md
index ee80e075b..f9b24ce71 100644
--- a/docs/avatar-thumbnails.md
+++ b/docs/avatar-thumbnails.md
@@ -29,6 +29,32 @@ and render the designed initial-letter placeholder instead.
**Never synthesise a thumbnail URL on the client.** If the API gives you `null`,
that avatar has no thumbnail; show a placeholder.
+### The read side: always `thumbnailUrl()`, never bare `publicUrl()`
+
+The write paths guarantee that a key we store has an object behind it. The read
+paths have to survive the keys that predate that guarantee. `publicUrl()` passes an
+absolute value straight through, so a legacy `*_og.png` key becomes a URL pointing
+at an origin that holds no object — a 404 the browser blocks as ORB.
+
+So every read path goes through one helper in
+[`api/_lib/r2.js`](../api/_lib/r2.js):
+
+```js
+import { thumbnailUrl } from './_lib/r2.js';
+
+thumbnailUrl(null) // → null
+thumbnailUrl('https://three.ws/avatars/x_og.png') // → null (legacy, always 404s)
+thumbnailUrl('thumb/abc.png') // → https://<cdn>/thumb/abc.png
+```
+
+Return `null` and let the surface render its designed placeholder. There were 43
+bare `publicUrl(<thumbnail key>)` call sites across 32 files — agent cards, the
+marketplace, explore, user profiles, leaderboards, and the image baked into on-chain
+token metadata. All now route through `thumbnailUrl()`, and
+[`tests/thumbnail-url-guard.test.js`](../tests/thumbnail-url-guard.test.js) walks
+`api/` to fail the build if a new one appears. Two files are allow-listed there,
+each for a stated reason.
+
## Where a thumbnail comes from
`avatars.thumbnail_key` holds a **relative** R2 key. An absolute URL in that column
diff --git a/public/features.json b/public/features.json
index fe33d3bd6..e6cfa428a 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-07-10T06:07:10.762Z",
+ "generated_at": "2026-07-10T06:16:54.233Z",
"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 6b5374d9a..be840ace7 100644
--- a/public/sitemap/index.html
+++ b/public/sitemap/index.html
@@ -56,25 +56,6 @@
.sm-brand img { width: 24px; height: 24px; border-radius: 5px; }
.sm-brand:hover { text-decoration: none; }
</style>
-
- <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1">
- <meta property="og:type" content="website">
- <meta property="og:site_name" content="three.ws">
- <meta property="og:locale" content="en_US">
- <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/api/page-og?s=main&amp;t=Sitemap&amp;d=Human-readable+index+of+every+page+on+three.ws.&amp;p=%2Fsitemap">
- <meta property="og:image:width" content="1200">
- <meta property="og:image:height" content="630">
- <meta property="og:image:type" content="image/png">
- <meta property="og:image:alt" content="Sitemap — three.ws">
- <meta name="twitter:card" content="summary_large_image">
- <meta name="twitter:site" content="@trythreews">
- <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/api/page-og?s=main&amp;t=Sitemap&amp;d=Human-readable+index+of+every+page+on+three.ws.&amp;p=%2Fsitemap">
- <script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@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"},"primaryImageOfPage":"https://three.ws/api/page-og?s=main&t=Sitemap&d=Human-readable+index+of+every+page+on+three.ws.&p=%2Fsitemap"}]}</script>
</head>
<body>
<header class="sm-topbar">
diff --git a/src/game/coincommunities-ui.js b/src/game/coincommunities-ui.js
index 700885d0f..398f917ea 100644
--- a/src/game/coincommunities-ui.js
+++ b/src/game/coincommunities-ui.js
@@ -952,6 +952,28 @@ export class CommunityUI {
if (this.gateBtn) this.gateBtn.hidden = !isCreator;
}
+ // Friends HUD state (W09). The badge shows unread DMs (capped at 9+ so it never
+ // widens the button); `setFriendsOpen` keeps aria-expanded honest for screen
+ // readers and lets CSS mark the button active while the panel is up.
+ setFriendsUnread(count) {
+ if (!this.friendsBadge) return;
+ const n = Number(count) || 0;
+ this.friendsBadge.textContent = n > 9 ? '9+' : String(n);
+ this.friendsBadge.hidden = n <= 0;
+ if (this.friendsBtn) {
+ this.friendsBtn.setAttribute(
+ 'aria-label',
+ n > 0 ? `Open friends panel, ${n} unread message${n === 1 ? '' : 's'}` : 'Open friends panel',
+ );
+ }
+ }
+
+ setFriendsOpen(open) {
+ if (!this.friendsBtn) return;
+ this.friendsBtn.setAttribute('aria-expanded', String(!!open));
+ this.friendsBtn.classList.toggle('is-active', !!open);
+ }
+
// Creator gate config (R24). A small modal where the coin's creator sets the
// token amount a wallet must hold to enter the Holders world, or removes the
// requirement. `onSave(minTokens)` returns a promise that resolves to the saved
@@ -1171,6 +1193,21 @@ export class CommunityUI {
'aria-label': 'Open the jobs board',
onclick: () => this.h.onJobs?.(),
}, [el('span', { class: 'cc-jobs-btn-ico', 'aria-hidden': 'true', text: '🎯' }), el('span', { class: 'cc-jobs-btn-text', text: 'Jobs' })]);
+ // Friends panel (W09) — the account-level social graph: requests, live
+ // presence across every coin world, and DM threads. The badge carries the
+ // unread-DM count so a message landing while the panel is closed still
+ // shows; the button is also the touch equivalent of the J hotkey, since
+ // mobile has no keyboard.
+ this.friendsBadge = el('span', { class: 'cc-friends-badge', hidden: true });
+ this.friendsBtn = el('button', {
+ class: 'cc-friends-btn', type: 'button', title: 'Friends — presence and messages (J)',
+ 'aria-label': 'Open friends panel', 'aria-expanded': 'false',
+ onclick: () => this.h.onFriends?.(),
+ }, [
+ el('span', { class: 'cc-friends-btn-ico', 'aria-hidden': 'true', text: '👥' }),
+ el('span', { class: 'cc-friends-btn-text', text: 'Friends' }),
+ this.friendsBadge,
+ ]);
const banner = el('div', { class: 'cc-coin-banner' }, [
this.coinImg,
el('div', { class: 'cc-coin-info' }, [
@@ -1181,6 +1218,7 @@ export class CommunityUI {
this.tierBadge,
]),
]),
+ this.friendsBtn,
this.jobsBtn,
this.wardrobeBtn,
this.shopBtn,
diff --git a/src/game/coincommunities.css b/src/game/coincommunities.css
index d0c3748c8..e2f086e7e 100644
--- a/src/game/coincommunities.css
+++ b/src/game/coincommunities.css
@@ -1955,6 +1955,84 @@ html[data-bg="transparent"] #cc-lobby {
.cc-jobs-btn-ico { font-size: 14px; line-height: 1; }
@media (max-width: 480px) { .cc-jobs-btn-text { display: none; } }
+/* "Friends" button (W09) — mirrors the jobs/shop/wardrobe buttons, plus an
+ unread-DM badge and an active state while the panel is open. */
+.cc-friends-btn {
+ position: relative;
+ flex: none; pointer-events: auto;
+ display: inline-flex; align-items: center; gap: 7px;
+ margin-left: 4px; padding: 9px 13px;
+ background: rgba(255, 255, 255, 0.04); color: var(--cc-text);
+ border: 1px solid var(--cc-edge); border-radius: var(--cc-radius);
+ font-weight: 700; font-size: 12px; letter-spacing: 0.04em; text-transform: uppercase;
+ cursor: pointer; white-space: nowrap; appearance: none; -webkit-appearance: none; font-family: inherit;
+ transition: border-color 0.14s ease, background 0.14s ease, transform 0.1s ease;
+}
+.cc-friends-btn:hover { border-color: var(--cc-edge-hi); background: rgba(255, 255, 255, 0.08); transform: translateY(-1px); }
+.cc-friends-btn:active { transform: translateY(1px); }
+.cc-friends-btn:focus-visible { outline: 2px solid #fff; outline-offset: 2px; }
+.cc-friends-btn.is-active { border-color: var(--cc-edge-hi); background: rgba(255, 255, 255, 0.12); }
+.cc-friends-btn-ico { font-size: 14px; line-height: 1; }
+@media (max-width: 480px) { .cc-friends-btn-text { display: none; } }
+
+/* Unread badge — absolutely positioned so it never reflows the button (and so it
+ survives the 480px breakpoint that hides the label). */
+.cc-friends-badge {
+ position: absolute; top: -5px; right: -5px;
+ min-width: 17px; height: 17px; padding: 0 4px; box-sizing: border-box;
+ display: inline-flex; align-items: center; justify-content: center;
+ background: #ff4d4d; color: #fff;
+ border-radius: 999px;
+ font-size: 10px; font-weight: 800; line-height: 1; letter-spacing: 0;
+ box-shadow: 0 0 0 2px var(--cc-bg, #10131a);
+}
+
+/* Friends panel shell (W09). A right-docked drawer over the world; the panel's own
+ styling ships with friends-panel.css, so this only owns the frame + motion. */
+.cc-friends-panel {
+ position: fixed; top: 0; right: 0; z-index: 40;
+ width: min(380px, 100vw);
+ height: 100dvh;
+ display: flex; flex-direction: column;
+ background: var(--cc-bg, #10131a);
+ border-left: 1px solid var(--cc-edge);
+ box-shadow: -18px 0 48px rgba(0, 0, 0, 0.45);
+ pointer-events: auto;
+ transform: translateX(100%);
+ transition: transform 0.22s cubic-bezier(0.22, 1, 0.36, 1);
+ will-change: transform;
+}
+.cc-friends-panel.is-open { transform: translateX(0); }
+@media (prefers-reduced-motion: reduce) { .cc-friends-panel { transition: none; } }
+
+.cc-friends-panel-head {
+ flex: none;
+ display: flex; align-items: center; justify-content: space-between; gap: 10px;
+ padding: 14px 14px 10px;
+ border-bottom: 1px solid var(--cc-edge);
+}
+.cc-friends-panel-title {
+ font-weight: 800; font-size: 13px; letter-spacing: 0.06em; text-transform: uppercase;
+ color: var(--cc-text);
+}
+.cc-friends-panel-close {
+ flex: none; width: 30px; height: 30px;
+ display: inline-flex; align-items: center; justify-content: center;
+ background: transparent; color: var(--cc-text);
+ border: 1px solid var(--cc-edge); border-radius: 8px;
+ font-size: 15px; line-height: 1; cursor: pointer;
+ transition: border-color 0.14s ease, background 0.14s ease;
+}
+.cc-friends-panel-close:hover { border-color: var(--cc-edge-hi); background: rgba(255, 255, 255, 0.08); }
+.cc-friends-panel-close:focus-visible { outline: 2px solid #fff; outline-offset: 2px; }
+/* The FriendsPanel renders its own scrolling list into this body. */
+.cc-friends-panel-body { flex: 1 1 auto; min-height: 0; overflow: hidden; display: flex; flex-direction: column; }
+.cc-friends-panel-hint {
+ flex: none; padding: 8px 14px 12px;
+ color: var(--cc-dim, #8b93a3); font-size: 11px; letter-spacing: 0.02em;
+ border-top: 1px solid var(--cc-edge);
+}
+
/* Creator-only holders-gate button (R24) — mirrors the shop button, accented. */
.cc-gate-cfg-btn {
flex: none; pointer-events: auto;
diff --git a/src/game/coincommunities.js b/src/game/coincommunities.js
index 7e299d90d..109f66ed4 100644
--- a/src/game/coincommunities.js
+++ b/src/game/coincommunities.js
@@ -44,6 +44,8 @@ import {
CLIP_IDLE, CLIP_WALK,
} from './avatar-rig.js';
import { GUEST_SENTINEL, uploadPendingGuestAvatar, getPlayCosmetics, setPlayCosmetics } from './play-handoff.js';
+import { getPresenceTicket, friendsClient } from '../friends.js';
+import { FriendsPanel } from './friends-panel.js';
import { applyLoadout } from './cosmetics-loadout.js';
import { serializeLoadout, getCosmetic } from '../../multiplayer/src/cosmetics-catalog.js';
import { AccessoryManager } from '../agent-accessories.js';
@@ -78,6 +80,18 @@ import { CombatSystem } from './combat-system.js';
function lsGet(k) { try { return localStorage.getItem(k); } catch { return null; } }
function lsSet(k, v) { try { localStorage.setItem(k, v); } catch { /* storage disabled */ } }
+// True when the keystroke belongs to an editable surface — a DM input in the
+// friends panel, a search box, a modal field. World hotkeys must never fire
+// there: `b` would toggle build mode mid-word and Space would be swallowed
+// before it reached the caret. `chatFocused` covers only the in-world chat bar,
+// so this is the general guard for every other input the HUD can open.
+function isTypingTarget(t) {
+ if (!t || t.nodeType !== 1) return false;
+ if (t.isContentEditable) return true;
+ const tag = t.tagName;
+ return tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT';
+}
+
// Reaction bar (R04): the 6 emoji available to all players.
const REACTIONS = [
{ emoji: '🎉', label: 'Celebrate' },
@@ -427,6 +441,8 @@ export class CoinCommunities {
onShop: () => this._toggleShop(),
onWardrobe: () => this._toggleWardrobe(),
onJobs: () => this._toggleQuests(),
+ // Friends panel (W09) — presence + DMs across every coin world.
+ onFriends: () => this._toggleFriends(),
// Creator-only (R24): set/clear the token threshold for the Holders world.
onConfigureGate: () => this._configureGate(),
onVoiceToggle: () => this._toggleVoice(),
@@ -1038,6 +1054,11 @@ export class CoinCommunities {
// what the account owns before publishing it, so it can't dress us in
// anything unowned.
cosmetics: getPlayCosmetics(),
+ // Friends presence (W09): a signed, short-lived account ticket. WalkRoom
+ // verifies it and registers this account with the social hub under this
+ // coin world's name, so friends see the player as "Online · <coin>" and
+ // DMs route straight to this socket. Resolves to null when anonymous.
+ getPresence: getPresenceTicket,
});
// Generic networked-object layer for this coin (R02): mirrors the server's
// authoritative `objects` map into the scene — build props (R18), and any
@@ -1157,6 +1178,15 @@ export class CoinCommunities {
this.net.on('xpgain', (g) => this.playSystems?.onXpGain(g));
this.net.on('levelup', (l) => this.playSystems?.onLevelup(l));
this.net.on('notice', (n) => this.playSystems?.onNotice(n));
+ // Friends (W09): live DMs + request/accept pushed by the social hub over this
+ // world's socket. The FriendsClient owns all social state — it updates its
+ // threads/unread counts and notifies the panel, open or not, so a DM that
+ // arrives while the panel is closed still lights the badge.
+ this.net.on('social', (m) => {
+ friendsClient().handleSocial(m);
+ if (m?.type === 'dm') this._bumpFriendsBadge();
+ });
+ this._initFriends();
// Job completion has no generic 'notice' twin (WalkRoom sends only
// 'questComplete') — toast it globally so a payout lands even when the
// Jobs Board panel isn't open, the same way every other reward does.
@@ -1508,6 +1538,7 @@ export class CoinCommunities {
if (this.combat) { this.combat.dispose(); this.combat = null; }
if (this.playSystems) { this.playSystems.dispose(); this.playSystems = null; }
if (this.playActivities) { this.playActivities.dispose(); this.playActivities = null; }
+ this._disposeFriends();
if (this.agentCommerce) { this.agentCommerce.dispose(); this.agentCommerce = null; }
if (this.intelKiosk) { this.intelKiosk.dispose(); this.intelKiosk = null; }
if (this.worldLife) { this.worldLife.dispose(); this.worldLife = null; }
@@ -1879,6 +1910,110 @@ export class CoinCommunities {
this._shop.toggle();
}
+ // ── Friends (W09) ─────────────────────────────────────────────────────────
+ // The account-level social graph inside the world: who's online, which coin
+ // world they're standing in, and DM threads. `FriendsPanel` is a pure view over
+ // the shared `friendsClient`, so the same graph backs /play, /walk and the
+ // standalone /friends page — a DM read here is read everywhere.
+ //
+ // Presence is published by the room, not this panel: CommunityNet now carries a
+ // signed presence ticket into the join, so a player is visible to friends the
+ // moment they enter a world, whether or not they ever open this panel.
+
+ // Seed the graph once per world entry so the unread badge is honest before the
+ // panel is ever opened, and keep it live from the client's change signal. Silent
+ // no-op when signed out — `refresh()` short-circuits without a request.
+ _initFriends() {
+ const fc = friendsClient();
+ this._offFriends = fc.subscribe(() => this._bumpFriendsBadge());
+ fc.refresh();
+ this._bumpFriendsBadge();
+ }
+
+ _bumpFriendsBadge() {
+ this.ui?.setFriendsUnread?.(friendsClient().totalUnread);
+ }
+
+ _toggleFriends() {
+ if (this._friendsOpen) this._closeFriends();
+ else this._openFriends();
+ }
+
+ _openFriends() {
+ if (this._friendsOpen) return;
+ if (!this._friendsEl) {
+ // Right-docked drawer. The panel renders its own tabs/list/threads into
+ // `body`; we own only the frame, the close affordance and the hotkey hint.
+ const close = document.createElement('button');
+ close.className = 'cc-friends-panel-close';
+ close.type = 'button';
+ close.setAttribute('aria-label', 'Close friends panel');
+ close.textContent = '✕';
+ close.addEventListener('click', () => this._closeFriends());
+
+ const title = document.createElement('div');
+ title.className = 'cc-friends-panel-title';
+ title.textContent = 'Friends';
+
+ const head = document.createElement('div');
+ head.className = 'cc-friends-panel-head';
+ head.append(title, close);
+
+ const body = document.createElement('div');
+ body.className = 'cc-friends-panel-body';
+
+ const hint = document.createElement('div');
+ hint.className = 'cc-friends-panel-hint';
+ hint.textContent = 'Press J to toggle · Esc to close';
+
+ const root = document.createElement('aside');
+ root.className = 'cc-friends-panel';
+ root.setAttribute('role', 'dialog');
+ root.setAttribute('aria-modal', 'false');
+ root.setAttribute('aria-label', 'Friends');
+ root.append(head, body, hint);
+ document.body.appendChild(root);
+
+ this._friendsEl = root;
+ this._friendsBodyEl = body;
+ this._friendsCloseEl = close;
+ this._friends = new FriendsPanel(body);
+ }
+ this._friends.mount();
+ this._friendsOpen = true;
+ // Next frame, so the transform transition runs from its closed state rather
+ // than being collapsed into the same style recalculation as the insert.
+ requestAnimationFrame(() => this._friendsEl?.classList.add('is-open'));
+ this.ui?.setFriendsOpen?.(true);
+ // The world swallows WASD/F/X while the panel has focus; releasing the held
+ // keys stops the avatar sliding when focus moves into a DM input.
+ this.keys.clear();
+ this._friendsCloseEl?.focus();
+ }
+
+ _closeFriends() {
+ if (!this._friendsOpen) return;
+ this._friendsOpen = false;
+ this._friendsEl?.classList.remove('is-open');
+ this._friends?.unmount();
+ this.ui?.setFriendsOpen?.(false);
+ this._bumpFriendsBadge();
+ }
+
+ // Full teardown — the panel and its client subscription must not outlive the
+ // world (a coin switch rebuilds both, and a stale subscription would repaint a
+ // disposed HUD).
+ _disposeFriends() {
+ if (this._offFriends) { try { this._offFriends(); } catch {} this._offFriends = null; }
+ this._friends?.unmount();
+ this._friends = null;
+ this._friendsEl?.remove();
+ this._friendsEl = null;
+ this._friendsBodyEl = null;
+ this._friendsCloseEl = null;
+ this._friendsOpen = false;
+ }
+
// Open/close the "My Cosmetics" wardrobe panel (R23). Lazy-built on first open;
// each profile echo from the server keeps it fresh so the equipped state always
// reflects the server-authoritative result.
@@ -2272,6 +2407,11 @@ export class CoinCommunities {
_bindInput() {
window.addEventListener('keydown', (e) => {
if (this.ui.chatFocused) return;
+ // Typing anywhere else (friends DM box, search fields, modal inputs) must
+ // reach the caret untouched — no hotkeys, no Enter hijack, no Space eaten.
+ if (isTypingTarget(e.target)) return;
+ // Esc closes the friends drawer before anything else claims the key.
+ if (e.key === 'Escape' && this._friendsOpen) { e.preventDefault(); this._closeFriends(); return; }
if (e.key === 'Enter' && this.phase === 'world') { e.preventDefault(); this.ui.focusChat(); return; }
// Space jumps on foot; while driving it's the handbrake instead (held,
// released in the keyup handler below) — never scrolls the page either way.
@@ -2337,6 +2477,14 @@ export class CoinCommunities {
this._inspectNearest();
return;
}
+ // J toggles the friends drawer (W09). F — the /walk binding — is already
+ // this world's contextual action key (drive / gather / cast), so /play
+ // takes the next free slot; the HUD button carries the same hint.
+ if (k === 'j' && !this.buildHud.active && !e.repeat) {
+ e.preventDefault();
+ this._toggleFriends();
+ return;
+ }
// C cycles the camera: follow → cinematic → first person → top down.
if (k === 'c' && !this.buildHud.active && !e.repeat) {
e.preventDefault();
diff --git a/src/game/community-net.js b/src/game/community-net.js
index 2542b3361..f557ea4a3 100644
--- a/src/game/community-net.js
+++ b/src/game/community-net.js
@@ -168,7 +168,14 @@ export class CommunityNet {
tag: new Set(), // ({event, itId, leaderboard}) — tag mini-game state (R08)
floorBeat: new Set(), // ({clip}) — disco-pad beat tick (R06): pulses the floor + aligns standing dancers
king: new Set(), // ({event, phase, endsAt, scores, kingId, winner, zone}) — King of the Totem state (R07)
+ social: new Set(), // ({type, ...}) — friends events: live DM, request/accept (W09)
};
+ // Optional async presence-ticket supplier (W09). When provided, its resolved
+ // token rides the join so this coin world publishes the player's account
+ // presence to their friends and can deliver DMs here live. Without it the
+ // player is connected but invisible to the social graph — the /walk surface
+ // has always passed one; /play now does too.
+ this.getPresence = typeof opts.getPresence === 'function' ? opts.getPresence : null;
this.ping = null; // smoothed RTT in ms, null until the first echo
this._pingSentAt = 0; // perf-clock stamp of the last move awaiting an echo
this._lastSent = null;
@@ -233,6 +240,11 @@ export class CommunityNet {
try {
this.client = new Client(this.url);
const mint = this.coin.mint || '';
+ // Resolve the presence ticket before the join so it can ride the options.
+ // Anonymous players resolve to null (nothing to publish) and a failed mint
+ // must never block play — hence the catch: the world still joins, the
+ // player is simply offline to their friends until the next reconnect.
+ const presence = this.getPresence ? await this.getPresence().catch(() => null) : null;
const options = {
// filterBy('coin','tier') isolates each coin into its own instance and
// splits the open General world from the gated Holders world; the
@@ -255,6 +267,11 @@ export class CommunityNet {
// Stable persistence key for the off-schema economy (used only when the
// server hasn't verified a wallet account of its own — i.e. un-gated/dev).
pid: this.pid,
+ // Signed presence ticket (W09). WalkRoom verifies it and registers the
+ // account with the social hub under this world's name, so friends see
+ // "Online · <coin> Town" and DMs route to this socket. Omitted entirely
+ // when anonymous — the server treats its absence as "don't publish".
+ ...(presence ? { presence } : {}),
};
// Holder worlds require a signed pass the server verifies in onAuth; carry
// it (and the floor it gated on, for the seed room's HUD) only for holders.
@@ -279,6 +296,9 @@ export class CommunityNet {
this.room.onMessage('chat', (msg) => this._emit('chat', msg));
this.room.onMessage('interact', (msg) => this._emit('interact', msg));
+ // Friends (W09): live DM + request/accept events pushed by the social hub
+ // to whichever realm room the account is currently registered in.
+ this.room.onMessage('social', (msg) => this._emit('social', msg));
this.room.onMessage('voice-signal', (msg) => this._emit('voiceSignal', msg));
// The server replies here when it refuses one of our place/break edits
// (budget full, rate limited, …) so the HUD can explain the no-op.
diff --git a/tests/api/ibm-vision.test.js b/tests/api/ibm-vision.test.js
index 635232a70..a74d7a3d2 100644
--- a/tests/api/ibm-vision.test.js
+++ b/tests/api/ibm-vision.test.js
@@ -63,6 +63,10 @@ vi.mock('../../api/_lib/watsonx.js', () => ({
vi.mock('../../api/_lib/r2.js', () => ({
publicUrl: vi.fn((key) => `https://cdn.example.com/${key}`),
+ // thumbnailUrl mirrors r2.js: null for a missing key or the legacy *_og.png form.
+ thumbnailUrl: vi.fn((key) =>
+ !key || /^https?:\/\/.*_og\.png$/i.test(key) ? null : `https://cdn.example.com/${key}`,
+ ),
}));
// Mock global fetch for server-side image fetching.
diff --git a/tests/api/irl-agent-card.test.js b/tests/api/irl-agent-card.test.js
index 5ff989d14..a1ac79cd4 100644
--- a/tests/api/irl-agent-card.test.js
+++ b/tests/api/irl-agent-card.test.js
@@ -57,7 +57,11 @@ vi.mock('../../api/_lib/rate-limit.js', () => ({
// No cache in tests — exercise the live fan-out every call, not a HIT.
vi.mock('../../api/_lib/redis.js', () => ({ getRedis: vi.fn(async () => null) }));
-vi.mock('../../api/_lib/r2.js', () => ({ publicUrl: (key) => `/cdn/${key}` }));
+vi.mock('../../api/_lib/r2.js', () => ({
+ publicUrl: (key) => `/cdn/${key}`,
+ // thumbnailUrl mirrors r2.js: null for a missing key or the legacy *_og.png form.
+ thumbnailUrl: (key) => (!key || /^https?:\/\/.*_og\.png$/i.test(key) ? null : `/cdn/${key}`),
+}));
const { default: handler } = await import('../../api/irl/agent-card.js');
diff --git a/tests/api/marketplace-agent-detail-prices.test.js b/tests/api/marketplace-agent-detail-prices.test.js
index fed6b1595..e68a51c4e 100644
--- a/tests/api/marketplace-agent-detail-prices.test.js
+++ b/tests/api/marketplace-agent-detail-prices.test.js
@@ -43,7 +43,11 @@ vi.mock('../../api/_lib/rate-limit.js', () => ({
// publicUrl is only hit when a storage key is present; the fixtures keep keys
// null, but mock it so the test never depends on R2 env config.
-vi.mock('../../api/_lib/r2.js', () => ({ publicUrl: (k) => (k ? `https://cdn.test/${k}` : null) }));
+vi.mock('../../api/_lib/r2.js', () => ({
+ publicUrl: (k) => (k ? `https://cdn.test/${k}` : null),
+ // thumbnailUrl mirrors r2.js: null for a missing key or the legacy *_og.png form.
+ thumbnailUrl: (k) => (!k || /^https?:\/\/.*_og\.png$/i.test(k) ? null : `https://cdn.test/${k}`),
+}));
// Force the skill-price cache to always miss → every detail read re-queries the
// (mocked) DB. Without this, the module-level cache would carry case 1's prices
diff --git a/tests/api/marketplace-agent-detail-subscriptions.test.js b/tests/api/marketplace-agent-detail-subscriptions.test.js
index 04329327e..88479f2d3 100644
--- a/tests/api/marketplace-agent-detail-subscriptions.test.js
+++ b/tests/api/marketplace-agent-detail-subscriptions.test.js
@@ -68,7 +68,11 @@ vi.mock('../../api/_lib/rate-limit.js', () => ({
clientIp: vi.fn(() => '127.0.0.1'),
}));
-vi.mock('../../api/_lib/r2.js', () => ({ publicUrl: (k) => (k ? `https://cdn.test/${k}` : null) }));
+vi.mock('../../api/_lib/r2.js', () => ({
+ publicUrl: (k) => (k ? `https://cdn.test/${k}` : null),
+ // thumbnailUrl mirrors r2.js: null for a missing key or the legacy *_og.png form.
+ thumbnailUrl: (k) => (!k || /^https?:\/\/.*_og\.png$/i.test(k) ? null : `https://cdn.test/${k}`),
+}));
// Always-miss cache so getSkillPrices re-queries the mocked DB each read.
vi.mock('../../api/_lib/cache.js', () => ({
diff --git a/tests/api/persona.test.js b/tests/api/persona.test.js
index 2d40d5d73..f27f5fd56 100644
--- a/tests/api/persona.test.js
+++ b/tests/api/persona.test.js
@@ -28,6 +28,9 @@ vi.mock('../../api/_lib/db.js', () => ({
vi.mock('../../api/_lib/r2.js', () => ({
publicUrl: (key) => `https://cdn.three.ws/${key}`,
+ // thumbnailUrl mirrors r2.js: null for a missing key or the legacy *_og.png form.
+ thumbnailUrl: (key) =>
+ !key || /^https?:\/\/.*_og\.png$/i.test(key) ? null : `https://cdn.three.ws/${key}`,
}));
vi.mock('../../api/_lib/crypto.js', () => ({
diff --git a/tests/play-friends-presence.test.js b/tests/play-friends-presence.test.js
new file mode 100644
index 000000000..bc40eb677
--- /dev/null
+++ b/tests/play-friends-presence.test.js
@@ -0,0 +1,146 @@
+// @vitest-environment jsdom
+//
+// /play friends presence + social relay (W09).
+//
+// `/play` joins the same authoritative WalkRoom that `/walk` does, but for a long
+// time it never carried a presence ticket into the join and never forwarded the
+// server's `social` push. The consequence was silent and user-visible: a player
+// standing in a coin world showed as **Offline** to every friend, and a DM sent
+// to them was dropped on the floor rather than delivered to their open socket.
+//
+// These tests pin both halves of the contract at the seam that regressed:
+// 1. the resolved presence ticket rides the join options (and is omitted, not
+// sent as null/undefined, when the player is anonymous or the mint fails);
+// 2. a `social` room message is re-emitted on CommunityNet's own event bus so
+// the FriendsClient can route DMs and friend-graph events.
+//
+// The colyseus transport is mocked at the two module seams CommunityNet uses, so
+// this exercises the real CommunityNet code path without a live server.
+
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+
+globalThis.self = globalThis;
+
+// A minimal stand-in for a joined Colyseus room: records the handlers registered
+// against each message type so a test can push a server message through them.
+function makeFakeRoom() {
+ const handlers = new Map();
+ return {
+ sessionId: 'sess-1',
+ // Only the scalar fields connect() reads directly. The mocked
+ // getStateCallbacks returns undefined for every collection, which sends the
+ // `if ($players)` guards down the same skip path an older server schema does.
+ state: { persistent: false, worldTime: 0, coin: '', coinName: '', coinSymbol: '', coinImage: '' },
+ onMessage(type, cb) { handlers.set(type, cb); },
+ onLeave() {},
+ onError() {},
+ leave() {},
+ removeAllListeners() {},
+ // test helper — deliver a message as the server would
+ __emit(type, payload) { handlers.get(type)?.(payload); },
+ __handlers: handlers,
+ };
+}
+
+let lastJoinOptions = null;
+let fakeRoom = null;
+
+vi.mock('colyseus.js', () => ({
+ Client: class { constructor(url) { this.url = url; } },
+ // `$(room.state)` → undefined means every collection guard skips, which is the
+ // same shape CommunityNet already tolerates against an older server schema.
+ getStateCallbacks: () => () => undefined,
+}));
+
+vi.mock('../src/shared/colyseus-connect.js', () => ({
+ CONNECT_TIMEOUT_MS: 15_000,
+ joinRoomWithTimeout: vi.fn(async (_client, _roomName, options) => {
+ lastJoinOptions = options;
+ return fakeRoom;
+ }),
+}));
+
+const { CommunityNet } = await import('../src/game/community-net.js');
+
+const COIN = { mint: 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump', name: 'THREE', symbol: 'THREE', image: '' };
+
+function newNet(opts = {}) {
+ return new CommunityNet({ url: 'ws://test.invalid', coin: COIN, name: 'tester', ...opts });
+}
+
+beforeEach(() => {
+ lastJoinOptions = null;
+ fakeRoom = makeFakeRoom();
+});
+
+describe('CommunityNet presence ticket (W09)', () => {
+ it('carries the resolved presence ticket into the join options', async () => {
+ const net = newNet({ getPresence: async () => 'signed.presence.token' });
+ await net.connect();
+ expect(lastJoinOptions.presence).toBe('signed.presence.token');
+ net.destroy();
+ });
+
+ it('omits `presence` entirely when the player is anonymous', async () => {
+ // getPresenceTicket() resolves null for a signed-out player. Sending an
+ // explicit `presence: null` would make the server verify (and reject) a
+ // ticket that was never minted — the key must be absent.
+ const net = newNet({ getPresence: async () => null });
+ await net.connect();
+ expect('presence' in lastJoinOptions).toBe(false);
+ net.destroy();
+ });
+
+ it('joins the world anyway when the ticket mint throws', async () => {
+ // A failing /api/friends/presence-ticket must never block play: the player
+ // enters the world, simply invisible to the social graph until reconnect.
+ const net = newNet({ getPresence: async () => { throw new Error('502'); } });
+ await net.connect();
+ expect(lastJoinOptions).not.toBeNull();
+ expect('presence' in lastJoinOptions).toBe(false);
+ expect(net.status).toBe('online');
+ net.destroy();
+ });
+
+ it('omits `presence` when no supplier is configured at all', async () => {
+ const net = newNet();
+ await net.connect();
+ expect('presence' in lastJoinOptions).toBe(false);
+ net.destroy();
+ });
+});
+
+describe('CommunityNet social relay (W09)', () => {
+ it('registers a `social` room handler and re-emits it on the event bus', async () => {
+ const net = newNet({ getPresence: async () => 'tok' });
+ await net.connect();
+
+ const seen = [];
+ net.on('social', (msg) => seen.push(msg));
+
+ expect(fakeRoom.__handlers.has('social')).toBe(true);
+ const dm = { type: 'dm', message: { id: 'm1', from: 'u2', body: 'gm' } };
+ fakeRoom.__emit('social', dm);
+
+ expect(seen).toEqual([dm]);
+ net.destroy();
+ });
+
+ it('forwards friend-graph events, not just DMs', async () => {
+ const net = newNet();
+ await net.connect();
+ const seen = [];
+ net.on('social', (msg) => seen.push(msg));
+ fakeRoom.__emit('social', { type: 'friend_request', from: 'u9' });
+ fakeRoom.__emit('social', { type: 'friend_accept', from: 'u9' });
+ expect(seen.map((m) => m.type)).toEqual(['friend_request', 'friend_accept']);
+ net.destroy();
+ });
+
+ it('exposes `social` as a known event (on() rejects unknown names)', () => {
+ const net = newNet();
+ expect(() => net.on('social', () => {})).not.toThrow();
+ expect(() => net.on('definitely-not-an-event', () => {})).toThrow(/unknown event/);
+ net.destroy();
+ });
+});
diff --git a/tests/thumbnail-url-guard.test.js b/tests/thumbnail-url-guard.test.js
new file mode 100644
index 000000000..639a4867e
--- /dev/null
+++ b/tests/thumbnail-url-guard.test.js
@@ -0,0 +1,125 @@
+// thumbnailUrl() — the one way a stored thumbnail_key becomes a URL for an <img>.
+//
+// A thumbnail_key only resolves to a real image when it is a relative R2 key.
+// Legacy poisoned keys (absolute, origin-pointing `*_og.png`, written by the
+// pre-fix avatar-OG cache) resolve to an origin that holds no object. R2/the
+// origin answers 404 with a `text/plain` body, and because the request was made
+// for an <img>, Chrome refuses it under Opaque Response Blocking and logs
+// net::ERR_BLOCKED_BY_ORB — a console error on a page that should simply have
+// shown a placeholder.
+//
+// Before this helper existed, ~30 read paths called bare `publicUrl(thumbnail_key)`
+// and would happily publish such a key: agent cards, the marketplace, the explore
+// feed, user profiles, leaderboards — and the image baked into on-chain token
+// metadata. This suite pins both the helper's behaviour and the fact that no read
+// path bypasses it.
+
+import { describe, it, expect, beforeAll } from 'vitest';
+import { readFileSync, readdirSync, statSync } from 'node:fs';
+import { resolve, join } from 'node:path';
+
+const root = resolve(__dirname, '..');
+
+describe('thumbnailUrl() behaviour', () => {
+ let thumbnailUrl;
+ beforeAll(async () => {
+ // r2.js reads S3_* lazily (the client is built on first use), so importing it
+ // without credentials is safe; publicUrl() only needs S3_PUBLIC_DOMAIN.
+ process.env.S3_PUBLIC_DOMAIN ||= 'https://cdn.test';
+ ({ thumbnailUrl } = await import('../api/_lib/r2.js'));
+ });
+
+ it('returns null for a missing key so the caller renders its placeholder', () => {
+ expect(thumbnailUrl(null)).toBeNull();
+ expect(thumbnailUrl(undefined)).toBeNull();
+ expect(thumbnailUrl('')).toBeNull();
+ });
+
+ it('drops the legacy origin-pointing *_og.png key that always 404s', () => {
+ expect(thumbnailUrl('https://three.ws/avatars/michelle_og.png')).toBeNull();
+ expect(thumbnailUrl('http://three.ws/avatars/selfie-girl_OG.PNG')).toBeNull();
+ });
+
+ it('resolves a relative bucket key against the CDN', () => {
+ expect(thumbnailUrl('thumb/abc.png')).toBe('https://cdn.test/thumb/abc.png');
+ expect(thumbnailUrl('forge/deadbeef/x-poster.webp')).toBe('https://cdn.test/forge/deadbeef/x-poster.webp');
+ });
+
+ it('percent-encodes each path segment, like publicUrl', () => {
+ expect(thumbnailUrl('u/1/my thumb.png')).toBe('https://cdn.test/u/1/my%20thumb.png');
+ });
+});
+
+// Walk api/ and assert nobody reintroduces a bare publicUrl() on a thumbnail key.
+// The two legitimate exceptions are called out by name.
+describe('no read path bypasses thumbnailUrl()', () => {
+ const ALLOWED = new Set([
+ // The helper itself.
+ 'api/_lib/r2.js',
+ // Publishes a key it JUST wrote via putObject in the same function — the
+ // object provably exists, and it is a log line, not an <img> src.
+ 'api/cron/avatar-thumbnail-render.js',
+ // HEAD-checks the key before calling publicUrl (auto-tag vision fetch).
+ 'api/avatars/_actions.js',
+ ]);
+
+ // Matches publicUrl(<anything containing thumb/Thumb>) — the bug shape.
+ const BARE = /publicUrl\(\s*[A-Za-z_$][\w$?.]*(?:thumb|Thumb)[\w$]*\s*\)/;
+
+ function walk(dir, out = []) {
+ for (const name of readdirSync(dir)) {
+ const p = join(dir, name);
+ const st = statSync(p);
+ if (st.isDirectory()) walk(p, out);
+ else if (name.endsWith('.js')) out.push(p);
+ }
+ return out;
+ }
+
+ it('every api/ file resolves thumbnail keys through thumbnailUrl()', () => {
+ const offenders = [];
+ for (const file of walk(resolve(root, 'api'))) {
+ const rel = file.slice(root.length + 1);
+ if (ALLOWED.has(rel)) continue;
+ const src = readFileSync(file, 'utf8');
+ for (const [i, line] of src.split('\n').entries()) {
+ if (BARE.test(line)) offenders.push(`${rel}:${i + 1} → ${line.trim()}`);
+ }
+ }
+ expect(offenders, `use thumbnailUrl() from api/_lib/r2.js instead:\n${offenders.join('\n')}`).toEqual([]);
+ });
+});
+
+// Write-side counterpart of the same invariant: a thumbnail_key is persisted only
+// after its object is confirmed present.
+describe('write paths confirm the object exists before persisting a key', () => {
+ const read = (p) => readFileSync(resolve(root, p), 'utf8');
+
+ it('fork.js HEAD-checks the copied thumbnail and never clones an absolute key', () => {
+ const src = read('api/avatars/fork.js');
+ // The fork only adopts the key it copied, and only once headObject confirms it.
+ expect(src).toMatch(/if \(copiedThumb && \(await headObject\(candidate\)\)\) newThumbKey = candidate;/);
+ // The old fallback cloned src.thumbnail_key — reachable only when copyObject
+ // returned false, i.e. exactly when the source key was an absolute URL.
+ expect(src).not.toMatch(/newThumbKey = copiedThumb \? candidate : src\.thumbnail_key/);
+ });
+
+ it('auto-tag rejects a thumb_key with no object behind it', () => {
+ const src = read('api/avatars/_actions.js');
+ expect(src).toMatch(/await headObject\(thumbKey\)/);
+ expect(src).toMatch(/thumbnail_not_found/);
+ });
+
+ it('renderThumbnail uploads before it commits the key', () => {
+ const src = read('api/_lib/avatar-thumbs.js');
+ const put = src.indexOf('await putObject({ key, body: png');
+ const commit = src.indexOf('UPDATE avatars SET thumbnail_key = ${key}');
+ expect(put, 'putObject call not found').toBeGreaterThan(-1);
+ expect(commit, 'thumbnail_key commit not found').toBeGreaterThan(-1);
+ expect(put).toBeLessThan(commit);
+ });
+
+ it('forge-seed adopts only a relative preview_key', () => {
+ expect(read('api/cron/forge-seed-cron.js')).toMatch(/case when fc\.preview_key !~ '\^https\?:\/\/' then fc\.preview_key end/);
+ });
+});