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.

perf: lazy-load images sitewide, forge tiers/health, and endpoint resilience

nirholasf4092a4bf4cc
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8b725d667..cbb6fc660 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -17,10 +17,13 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **Free photo → 3D is now a one-click engine in Forge** — Turning a photo into a 3D model is free — and now you can pick it directly. Forge's engine selector has a new 'Hunyuan3D / TRELLIS' lane marked with a FREE badge that reconstructs your uploaded photo (or 2–4 angles) into a textured GLB at no cost and with no API key, running on community GPU Spaces with automatic failover across Hunyuan3D, TRELLIS, and TripoSR. Until now the free photo lane only kicked in behind the scenes; it's a first-class choice in the picker, shows live availability, and never silently falls back to a paid engine. The FREE badge also marks every other no-cost lane so you can always see which engines cost nothing. (`/forge`) `[feature, improvement]`
- **Grind an agent's vanity wallet right on its page — with your CPU cores** — Giving an agent a custom wallet address used to run on our servers, so it was capped at short patterns and would time out and error on anything harder. Now the agent's Wallet → Vanity tab grinds the address in your own browser, exactly like the standalone /vanity-wallet tool: choose how many CPU cores to spend, match case-insensitively for a faster find, watch the live tries-per-second and ETA, and pause or resume anytime. Longer, rarer patterns are now possible with no timeouts. When a match is found, any SOL or tokens in the old wallet are still automatically swept to the new address before the key is swapped — funds are never stranded — and the server verifies the new address truly matches your pattern before storing it. `[fix, feature, improvement]`
- **Hardened on-chain confirmations and faster profile loads** — Two reliability fixes for everyone trading, launching, and browsing. First: every on-chain action that moves funds — coin launches, buys and sells, buybacks, payouts, transfers — now treats a transaction that lands but reverts as a real failure instead of quietly reporting success. You'll see an accurate error and your spending limit won't be charged for a trade that didn't go through. Second: public profile and creator pages are now cacheable at the edge, so they load noticeably faster under load. No action needed — these apply automatically. `[fix, security, improvement]`
+- **Live market feed stays up through provider blips** — The trending-tokens feed that powers the home card, communities, the token constellation, and the 3D visualizer is now resilient to upstream outages. If a market data provider goes down or rate-limits us, we transparently fall back to a second source; if both are briefly unavailable, the surfaces keep showing the last good data (clearly marked as a moment stale) instead of going blank. We also added a fast-fail circuit breaker so a slow provider can't drag the feed down during a traffic spike. Net effect: the live market views stay populated and snappy even when a data provider hiccups. `[infra, improvement]`
+- **Platform-wide hardening: payment integrity, security, and scale** — A broad reliability pass across the parts of three.ws that move real money and serve heavy traffic. On the money side: bundle purchases and agent payments are now verified on-chain before anything unlocks, each payment is credited exactly once, withdrawals can't be processed twice, and recurring subscriptions can't be double-billed. On the security side: a set of input-handling and link-safety fixes across pages, stronger protection for custodial keys at rest, and tighter checks on outbound agent payments so funds only ever move in the expected asset. On the scale side: the busiest directory, profile, and feed pages now ride a short cache and run far fewer database queries, so they stay fast as the community grows. Most of this is invisible by design — it's the plumbing that keeps the platform correct and quick under load. `[security, improvement, infra]`
- **Provably-fair vanity grinder now listed in the x402 bazaar** — The provably-fair Solana vanity grinder — which returns a signed, independently-verifiable receipt proving the key was ground fresh and never kept — is now published in the x402 discovery catalog, so paying agents and bazaar crawlers can find and call it directly. (`/vanity/verify`) `[feature, sdk]`
- **Regrinding an agent's vanity wallet no longer risks its funds** — The compact "Vanity address" card on an agent's page used to replace a wallet by deleting the old one and creating the new one separately — so if the old wallet held SOL or tokens, they could be left behind. It now uses the same money-safe path as the rest of the platform: any balance is automatically swept to the new vanity address first, and the switch only completes once the funds have moved (and only after the server confirms the new address really matches your pattern). Same one-click experience, but your funds follow the wallet. `[fix, security]`
- **Smoother landing page on hover** — The homepage's parallax hero and 3D stack-card glow used to read the page layout on every pointer move, which could make the cursor feel sticky on the first page new visitors see. Those effects now batch their work to one frame at a time, so hover and tilt stay buttery on any device. (`/`) `[improvement]`
- **Solana is now the default payment network** — Solana is now the default everywhere you pick a chain — the dashboard's Default payment network setting, x402 merchant settlement, and the monetization payout wallet all default to Solana for every user, with Solana listed first. Base and Polygon remain available if you prefer an EVM chain. (`/dashboard`) `[improvement]`
+- **The $THREE page now spells out why to hold — four real utility pillars** — The $THREE page leads with a clear "Why hold $THREE" section: revenue buybacks (a fixed, live share of platform revenue buys $THREE on the open market), holder rewards (every paid action reflects $THREE back to holders pro-rata), hold-to-access (discounts, higher quotas, and pro perks), and real usage (deploying agents, forging avatars, and trading the marketplace all run on $THREE). Each pillar maps to a mechanism that actually exists on the platform, and the buyback figure is wired to the live commitment. The page's market data also now rides a shared cache, so it stays fast and reliable under heavy traffic. (`/three-token`) `[feature, improvement]`
## 2026-06-20
diff --git a/api/_lib/agent-wallet.js b/api/_lib/agent-wallet.js
index f606327a9..f1e1305c2 100644
--- a/api/_lib/agent-wallet.js
+++ b/api/_lib/agent-wallet.js
@@ -60,9 +60,45 @@ export async function generateAgentWallet() {
/**
* Recover an agent wallet's private key from its encrypted form.
* Only call this when the agent needs to sign a transaction.
+ *
+ * Audit hook (mirrors recoverSolanaAgentKeypair): pass
+ * `audit: { agentId, userId, reason, meta }` and a usage_events row + an
+ * owner-viewable custody event are written fire-and-forget, so every decrypt of
+ * a custodial EVM key is traceable with its reason — parity with the Solana path.
*/
-export async function recoverAgentKey(encryptedKey) {
- return decrypt(encryptedKey);
+export async function recoverAgentKey(encryptedKey, audit = null) {
+ const pkHex = await decrypt(encryptedKey);
+ if (audit && audit.agentId) {
+ let address = null;
+ try {
+ const { computeAddress } = await import('ethers');
+ address = computeAddress(pkHex);
+ } catch { /* address is decoration on the audit row */ }
+ import('./usage.js')
+ .then(({ recordEvent }) =>
+ recordEvent({
+ userId: audit.userId ?? null,
+ agentId: audit.agentId,
+ kind: 'evm_key_use',
+ tool: audit.reason || 'sign',
+ status: 'ok',
+ meta: { address, ...(audit.meta || {}) },
+ }),
+ )
+ .catch(() => {});
+ import('./agent-trade-guards.js')
+ .then(({ recordCustodyEvent }) =>
+ recordCustodyEvent({
+ agentId: audit.agentId,
+ userId: audit.userId ?? null,
+ eventType: 'key_recover',
+ reason: audit.reason || 'sign',
+ meta: { address, chain: 'evm', ...(audit.meta || {}) },
+ }),
+ )
+ .catch(() => {});
+ }
+ return pkHex;
}
/**
diff --git a/api/_lib/cache.js b/api/_lib/cache.js
index 76d26f846..900752278 100644
--- a/api/_lib/cache.js
+++ b/api/_lib/cache.js
@@ -140,6 +140,47 @@ export function cacheBackend() {
return redisConfigured() ? 'upstash' : 'memory';
}
+/**
+ * Best-effort cross-instance lock built on Redis `SET key val NX EX`. Returns
+ * true if THIS caller acquired the lock, false if someone else holds it. Use to
+ * coordinate an expensive recompute (a full on-chain scan, a snapshot rebuild)
+ * across serverless instances so a traffic spike against a cold cache fans out
+ * into ONE recompute platform-wide instead of N.
+ *
+ * The TTL is a safety valve: if the lock holder's lambda dies mid-work, the lock
+ * auto-expires so the work isn't wedged forever — size it longer than the work
+ * takes. When Redis is unavailable we return true (degrade to "no cross-instance
+ * coordination"); pair with an in-process single-flight for the common case.
+ *
+ * @param {string} key
+ * @param {number} ttlSeconds
+ * @returns {Promise<boolean>}
+ */
+export async function acquireLock(key, ttlSeconds) {
+ if (!redisConfigured()) return true;
+ try {
+ const res = await redisCmd(['SET', key, '1', 'NX', 'EX', String(ttlSeconds)]);
+ return res === 'OK';
+ } catch (err) {
+ console.warn('[cache] acquireLock failed, proceeding without lock:', err?.message);
+ return true;
+ }
+}
+
+/**
+ * Release a lock taken with acquireLock. Best-effort — a failed release just
+ * leaves the lock to expire on its TTL.
+ * @param {string} key
+ */
+export async function releaseLock(key) {
+ if (!redisConfigured()) return;
+ try {
+ await redisCmd(['DEL', key]);
+ } catch {
+ /* lock will expire on its own TTL */
+ }
+}
+
/**
* Read-through cache: return the cached value for `key`, or compute it with
* `fn()`, store it for `ttlSeconds`, and return it. Use to shield expensive but
diff --git a/api/_lib/coin/three-holders.js b/api/_lib/coin/three-holders.js
index 68371d75c..32771537c 100644
--- a/api/_lib/coin/three-holders.js
+++ b/api/_lib/coin/three-holders.js
@@ -18,6 +18,7 @@
import { sql } from '../db.js';
import { TOKEN_MINT as THREE_MINT } from '../token/config.js';
import { fetchHolderBalances } from './holders.js';
+import { acquireLock, releaseLock } from '../cache.js';
const UPSERT_CHUNK = 2000; // rows per batched upsert — mirrors persistHolderSnapshot
// A snapshot older than this is treated as missing: the reader falls back to a
@@ -138,16 +139,64 @@ export async function readThreeHolderSnapshot() {
return balances.size > 0 ? balances : null;
}
+// Cross-instance lock + TTL for the cold-fallback scan. The full DAS walk takes
+// several seconds; 90s is comfortably longer so a slow scan keeps the lock, and
+// it auto-expires if the holder's lambda dies mid-scan.
+const COLD_SCAN_LOCK_KEY = 'three:holders:coldscan';
+const COLD_SCAN_LOCK_TTL = 90;
+// In-process single-flight: coalesce concurrent cold scans within ONE warm
+// lambda so a burst of cache-miss requests on the same instance shares one scan.
+let _inflightColdScan = null;
+
/**
* The drop-in replacement for fetchHolderBalances({ mint: THREE_MINT }) on public
* read paths: serve the cached snapshot, falling back to a single live scan only
* on a cold start (snapshot missing/stale). Same Map<wallet, bigint> shape, so
* callers' downstream ranking/tier/percentage logic is unchanged.
+ *
+ * The cold fallback is stampede-guarded. Without it, a traffic spike against a
+ * missing/stale snapshot (cold deploy, or a stalled cron) had EVERY uncached
+ * request to the leaderboard, token stats, and OG card independently fire a full
+ * multi-second Helius DAS walk — N concurrent scans burning credits. Now: an
+ * in-process single-flight collapses concurrent callers on one instance, and a
+ * cross-instance Redis lock ensures only one lambda platform-wide runs the scan
+ * — and the winner refreshes the shared snapshot so the fallback self-heals and
+ * everyone else reads from cache.
*/
export async function threeHolderBalances() {
const snap = await readThreeHolderSnapshot();
if (snap) return snap;
- // Cold start or stalled cron — one live scan keeps the page correct. This is
- // the rare path now, not the per-request default.
- return fetchHolderBalances({ mint: THREE_MINT });
+ if (_inflightColdScan) return _inflightColdScan;
+ _inflightColdScan = coldFallbackScan().finally(() => { _inflightColdScan = null; });
+ return _inflightColdScan;
+}
+
+async function coldFallbackScan() {
+ const gotLock = await acquireLock(COLD_SCAN_LOCK_KEY, COLD_SCAN_LOCK_TTL);
+ if (!gotLock) {
+ // Another instance is scanning. Wait briefly for it to refresh the snapshot,
+ // then serve from cache. If it never appears (slow/dead holder), scan
+ // ourselves rather than hanging the request.
+ for (let i = 0; i < 12; i++) {
+ await new Promise((r) => setTimeout(r, 500));
+ const snap = await readThreeHolderSnapshot();
+ if (snap) return snap;
+ }
+ return fetchHolderBalances({ mint: THREE_MINT });
+ }
+ try {
+ // Winner: refresh the shared snapshot so subsequent reads hit cache instead
+ // of scanning. Fall back to a read-only scan if the refresh can't persist
+ // (e.g. snapshot table not migrated yet) so the page still renders.
+ try {
+ await refreshThreeHolderSnapshot();
+ const snap = await readThreeHolderSnapshot();
+ if (snap) return snap;
+ } catch (err) {
+ console.warn('[three-holders] cold refresh failed, serving live scan:', err?.message || err);
+ }
+ return fetchHolderBalances({ mint: THREE_MINT });
+ } finally {
+ await releaseLock(COLD_SCAN_LOCK_KEY);
+ }
}
diff --git a/api/_lib/forge-health.js b/api/_lib/forge-health.js
index 614441b77..112792af3 100644
--- a/api/_lib/forge-health.js
+++ b/api/_lib/forge-health.js
@@ -23,6 +23,7 @@ import { BACKENDS, backendIsConfigured } from './forge-tiers.js';
import { env } from './env.js';
import { getRedisBurn } from './redis-usage.js';
import { probeLlmHealth } from './llm-health.js';
+import { readGenerationMetrics } from './forge-events.js';
const PROBE_TIMEOUT_MS = 4_000;
const CACHE_TTL_MS = 60_000;
@@ -264,7 +265,7 @@ export async function probeForgeHealth({ force = false } = {}) {
return { ...cache.payload, cached: true };
}
- const [entries, limiter, llm, world, redis] = await Promise.all([
+ const [entries, limiter, llm, world, redis, metrics] = await Promise.all([
Promise.all(
Object.values(BACKENDS).map(async (b) => {
if (b.byok) return byokResult(b.id);
@@ -292,6 +293,12 @@ export async function probeForgeHealth({ force = false } = {}) {
// out of quota?" — the slow failure that took the platform down in June
// 2026 while every reachability check still read green.
getRedisBurn(),
+ // Real generation outcomes over the last 24h (success rate, latency, per-backend
+ // load) from the rolling counters forge-events.js writes. This is what a probe
+ // can't tell you: the upstream can authenticate fine while real user generations
+ // are quietly failing. Null when Redis is absent — the block is then omitted
+ // rather than shown as a misleading all-zero outage.
+ readGenerationMetrics().catch(() => null),
]);
const backends = Object.fromEntries(entries.map((e) => [e.id, e]));
@@ -300,9 +307,21 @@ export async function probeForgeHealth({ force = false } = {}) {
// functions when the world is offline), which the cap below already enforces.
// A critical Redis burn rate degrades overall too: it predicts the limiters
// failing closed before they actually do, so it warns rather than waits.
+ // A real success rate below 75% over a meaningful sample (≥20 terminal outcomes)
+ // is a live outage the upstream auth probes can't see — surface it in the overall
+ // verdict. Below the volume floor the rate is too noisy to act on, so it's ignored.
+ const generationUnhealthy =
+ metrics && metrics.total >= 20 && metrics.success_rate != null && metrics.success_rate < 0.75;
+
const statuses = entries
.map((e) => e.status)
- .concat(limiter.status, llm.overall, world.status, redis.status === 'critical' ? 'down' : 'ok');
+ .concat(
+ limiter.status,
+ llm.overall,
+ world.status,
+ redis.status === 'critical' ? 'down' : 'ok',
+ generationUnhealthy ? 'degraded' : 'ok',
+ );
const overall = statuses.includes('down') || statuses.includes('degraded') ? 'degraded' : 'ok';
const payload = {
@@ -313,6 +332,8 @@ export async function probeForgeHealth({ force = false } = {}) {
llm,
world,
redis,
+ // Live generation outcomes (omitted when Redis is absent).
+ ...(metrics ? { metrics } : {}),
};
cache = { at: Date.now(), payload };
return { ...payload, cached: false };
diff --git a/api/_lib/forge-scale.js b/api/_lib/forge-scale.js
index 6d62497a5..eede3ae43 100644
--- a/api/_lib/forge-scale.js
+++ b/api/_lib/forge-scale.js
@@ -170,3 +170,82 @@ export const SCALE_LIMITS = Object.freeze({
replicateSubmitLimit: intEnv('FORGE_REPLICATE_SUBMIT_LIMIT', 40),
replicateSubmitWindowS: 10,
});
+
+// ── Shared circuit breaker ────────────────────────────────────────────────────
+// A consecutive-failure breaker whose state lives in Redis so EVERY serverless
+// instance sees the same open/closed decision. Without it each instance
+// rediscovers a provider outage independently — e.g. the seed cron burns N× the
+// retry latency before N instances each open their own in-memory breaker. Falls
+// back to a per-instance object when Redis is absent (the behavior callers had
+// before this was shared). Counters self-expire so a long-idle breaker clears.
+
+const CIRCUIT_PREFIX = 'fc:circuit:';
+const CIRCUIT_TTL_S = 24 * 3600;
+const _circuitMem = new Map(); // name -> { failures, openUntil }
+
+function memCircuit(name) {
+ let c = _circuitMem.get(name);
+ if (!c) {
+ c = { failures: 0, openUntil: 0 };
+ _circuitMem.set(name, c);
+ }
+ return c;
+}
+
+// Current breaker state: { open, failures, openUntil }.
+export async function circuitState(name) {
+ if (!redis) {
+ const c = memCircuit(name);
+ return { open: c.openUntil > Date.now(), failures: c.failures, openUntil: c.openUntil };
+ }
+ try {
+ const [failures, openUntil] = await Promise.all([
+ redis.get(`${CIRCUIT_PREFIX}${name}:failures`),
+ redis.get(`${CIRCUIT_PREFIX}${name}:openUntil`),
+ ]);
+ const o = Number(openUntil) || 0;
+ return { open: o > Date.now(), failures: Number(failures) || 0, openUntil: o };
+ } catch {
+ // Blind breaker → fail open (treat as closed) so an outage of the limiter
+ // store doesn't itself silence the cron.
+ return { open: false, failures: 0, openUntil: 0 };
+ }
+}
+
+// Record one failure; opens the breaker for (failures × baseMs) once threshold is
+// reached. Returns the new consecutive-failure count.
+export async function circuitRecordFailure(name, { threshold, baseMs }) {
+ if (!redis) {
+ const c = memCircuit(name);
+ c.failures++;
+ if (c.failures >= threshold) c.openUntil = Date.now() + c.failures * baseMs;
+ return c.failures;
+ }
+ try {
+ const failures = await redis.incr(`${CIRCUIT_PREFIX}${name}:failures`);
+ await redis.expire(`${CIRCUIT_PREFIX}${name}:failures`, CIRCUIT_TTL_S);
+ if (failures >= threshold) {
+ await redis.set(`${CIRCUIT_PREFIX}${name}:openUntil`, String(Date.now() + failures * baseMs), {
+ ex: CIRCUIT_TTL_S,
+ });
+ }
+ return failures;
+ } catch {
+ return 0;
+ }
+}
+
+// Clear the breaker on a success.
+export async function circuitRecordSuccess(name) {
+ if (!redis) {
+ const c = memCircuit(name);
+ c.failures = 0;
+ c.openUntil = 0;
+ return;
+ }
+ try {
+ await redis.del(`${CIRCUIT_PREFIX}${name}:failures`, `${CIRCUIT_PREFIX}${name}:openUntil`);
+ } catch {
+ /* best-effort */
+ }
+}
diff --git a/api/_lib/forge-tiers.js b/api/_lib/forge-tiers.js
index fa3c303cf..271b75038 100644
--- a/api/_lib/forge-tiers.js
+++ b/api/_lib/forge-tiers.js
@@ -141,7 +141,7 @@ export const BACKENDS = Object.freeze({
// Free image→3D — no vendor credit cost (HF Spaces' free GPU). One HF_TOKEN
// unlocks the whole chain; this is what makes photo→3D free for users.
free: true,
- blurb: 'Free photo→3D on community GPU Spaces — Hunyuan3D / TRELLIS / TripoSR with automatic failover. No vendor cost; queue waits vary.',
+ blurb: 'Free photo→3D and the High-tier engine on community GPU Spaces — Hunyuan3D / TRELLIS / TripoSR with automatic failover, textured GLB. No vendor cost; queue waits vary.',
}),
trellis: Object.freeze({
id: 'trellis',
@@ -154,7 +154,7 @@ export const BACKENDS = Object.freeze({
polyControl: false,
baseEta: 60,
credits: null,
- blurb: 'Image-intermediate reconstruction. The fast default; no poly target.',
+ blurb: 'Image-intermediate reconstruction on Replicate. A paid platform lane — selectable explicitly, and the last-resort fallback only on deployments with no free engine configured. Free deployments never route here automatically.',
}),
meshy: Object.freeze({
id: 'meshy',
@@ -301,46 +301,68 @@ export function outputIsConfigured(outputId) {
return o.requiresEnv.every((name) => Boolean(readEnv(name)));
}
-// Standing backend chosen when the caller doesn't name one, per path. The image
-// path keeps the image-capable Replicate TRELLIS default — it accepts user
-// photos and serves every tier. The free NVIDIA NIM lane (text-only) is layered
-// on top of this for prompt-only drafts via FREE_DEFAULT_FOR_DRAFT below, so it
-// must NOT be the standing default: a photo upload or a standard/high request
-// would otherwise route to a backend that can't serve it. Geometry → Meshy.
+// Standing per-path backend, used ONLY as a last resort when no FREE lane is
+// configured for the path (e.g. a deployment with a Replicate key but no
+// NVIDIA_API_KEY / HF_TOKEN). On a free-configured deployment the resolver below
+// never returns these — every tier routes to a zero-vendor-cost lane first, per
+// the platform's free-for-us policy. The image last-resort is the Replicate
+// TRELLIS lane (which itself free-firsts to HF when it runs); geometry is Meshy
+// (BYOK — the caller's own key, never ours); sketch is the self-host TripoSG worker.
export const DEFAULT_BACKEND_FOR_PATH = Object.freeze({
image: 'trellis',
geometry: 'meshy',
sketch: 'triposg',
});
-// Free-first override: when the caller asks for draft or standard tier without
-// naming a backend, prefer the free NVIDIA NIM lane (platform LLM/free-first
-// policy) on the paths it serves — but only when it's actually configured, so a
-// deployment without NVIDIA_API_KEY transparently keeps the standing per-path
-// default. Paid backends (Replicate/Meshy/Tripo) stay fully selectable at every
-// tier. High tier always goes to the full-quality paid lane.
+// Free-for-us routing: every tier defaults to a zero-vendor-cost engine. The
+// tier picks WHICH free engine, so quality (and the price we charge the user)
+// scales without us ever spending on a paid API:
+// • draft / standard → NVIDIA NIM TRELLIS — fast, free, native text→mesh.
+// • high → HuggingFace Hunyuan3D — textured, higher-fidelity, free.
+// These apply to text prompts and to the FLUX-synthesized reference the free
+// lanes reconstruct from. Photo submissions can't use the text-only NVIDIA lane,
+// so they fall to the free HuggingFace lane via FREE_FALLBACK_FOR_PATH below.
+// Charging is orthogonal: the High tier stays $THREE hold-or-pay gated in the
+// handler regardless of which free engine serves it — we charge for quality, not
+// to recover vendor cost. Paid backends (Replicate/Meshy/Tripo) stay explicitly
+// selectable at every tier.
export const FREE_DEFAULT_FOR_TIERS = Object.freeze({
draft: Object.freeze({ image: 'nvidia' }),
standard: Object.freeze({ image: 'nvidia' }),
+ high: Object.freeze({ image: 'huggingface' }),
});
-// Resolve the default backend for a (path, tier) when the caller didn't name
-// one. Draft and standard route to the free lane first when it's configured;
-// `userImages` matters because a free lane that can't take user photos
-// (BACKENDS[id].userImages === false) must not be defaulted for them.
+// Free lanes to fall back to per path when the tier's named free engine can't
+// serve this request — chiefly a photo submission at draft/standard (NVIDIA's
+// hosted preview is text-only), which routes to the free HuggingFace Spaces lane
+// instead of a paid engine. First configured + capable lane wins.
+export const FREE_FALLBACK_FOR_PATH = Object.freeze({
+ image: Object.freeze(['huggingface']),
+});
+
+// Whether a free lane can serve this (path, userImages) request right now: it
+// exists, is marked free (zero vendor cost), serves the path, is configured on
+// this deployment, and — for photo submissions — accepts user images.
+function freeLaneUsable(id, p, userImages) {
+ const b = id && BACKENDS[id];
+ return Boolean(
+ b &&
+ b.free === true &&
+ b.paths.includes(p) &&
+ backendIsConfigured(id) &&
+ (!userImages || b.userImages !== false),
+ );
+}
+
+// Resolve the default backend for a (path, tier) when the caller didn't name one.
+// Free-for-us policy: try the tier's named free engine, then any other configured
+// free lane for the path, and only fall to the paid standing default when NO free
+// lane is live on this deployment.
function defaultBackendFor(p, tierId, userImages) {
- const freeMap = FREE_DEFAULT_FOR_TIERS[tierId];
- if (freeMap) {
- const free = freeMap[p];
- const b = free && BACKENDS[free];
- if (
- b &&
- b.paths.includes(p) &&
- backendIsConfigured(free) &&
- (!userImages || b.userImages !== false)
- ) {
- return free;
- }
+ const named = FREE_DEFAULT_FOR_TIERS[tierId]?.[p];
+ if (freeLaneUsable(named, p, userImages)) return named;
+ for (const id of FREE_FALLBACK_FOR_PATH[p] || []) {
+ if (freeLaneUsable(id, p, userImages)) return id;
}
return DEFAULT_BACKEND_FOR_PATH[p];
}
diff --git a/api/_lib/x402/idempotency-cache.js b/api/_lib/x402/idempotency-cache.js
index 841b0ab80..242d89478 100644
--- a/api/_lib/x402/idempotency-cache.js
+++ b/api/_lib/x402/idempotency-cache.js
@@ -151,9 +151,16 @@ export async function reserve(route, paymentId, ttlSec) {
// Upstash returns 'OK' on success, null when the key already existed.
return ok === 'OK' || ok === true;
} catch (err) {
- // On a Redis error, fail OPEN (allow the request) rather than wedging a
- // legitimate payment — the always-on proof-hash dedup still bounds replay.
- console.error('[idempotency-cache] reserve failed:', err?.message || err);
+ // On a Redis error, fall back to the IN-PROCESS claim rather than blindly
+ // allowing the request. This de-dupes the common case — a client double-
+ // submit landing on the same warm instance — so a Redis outage can't turn
+ // into concurrent double-execution of paid work, while still not wedging a
+ // legitimate payment (a hard fail-closed would 5xx every paid call during a
+ // Redis blip). Cross-instance races during the outage remain bounded by the
+ // always-on proof-hash dedup.
+ console.error('[idempotency-cache] reserve failed, using in-process claim:', err?.message || err);
+ if (memoryGet(key) != null) return false;
+ memorySet(key, INFLIGHT, ttl);
return true;
}
}
diff --git a/api/_mcp3d/tools/studio.js b/api/_mcp3d/tools/studio.js
index 9bdcbd5c7..ca9c12af3 100644
--- a/api/_mcp3d/tools/studio.js
+++ b/api/_mcp3d/tools/studio.js
@@ -204,12 +204,23 @@ const PATH_PROP = {
description:
'Generation path: "image" (FLUX→TRELLIS reference-image reconstruction, the platform-keyed default) or "geometry" (native text/image→mesh via Meshy/Tripo/Rodin — cleaner topology, but BYOK: needs your own provider key).',
};
-const BACKEND_PROP = {
- type: 'string',
+const MCP_UNSELECTABLE_BACKENDS = new Set([
// replicate_byok runs on the platform reconstruction path with the caller's
// own Replicate account; that BYOK-token routing only exists on /api/forge, so
- // it isn't offered over MCP. Every other backend is selectable here.
- enum: Object.keys(BACKENDS).filter((id) => id !== 'replicate_byok'),
+ // it isn't offered over MCP.
+ 'replicate_byok',
+ // huggingface is the free Spaces image→3D lane, but it is wired ONLY on
+ // /api/forge (runHfImageLane). The MCP studio path reconstructs via Replicate/GCP
+ // (regenProvider), so selecting it here would silently run a DIFFERENT, paid
+ // engine. Hide it until the free Spaces lane is wired into the MCP path rather
+ // than advertise a free engine that doesn't run here. Free text→3D over MCP is
+ // the separate forge_free tool, which targets the NVIDIA lane via /api/forge.
+ 'huggingface',
+]);
+const BACKEND_PROP = {
+ type: 'string',
+ // Every other backend is selectable here.
+ enum: Object.keys(BACKENDS).filter((id) => !MCP_UNSELECTABLE_BACKENDS.has(id)),
description:
'Force a specific backend (trellis, meshy, tripo, rodin, stability, hunyuan3d). Defaults to the best one for the chosen path. Backends outside the path are ignored.',
};
diff --git a/api/agents/_id/_sub.js b/api/agents/_id/_sub.js
index daafe2fc6..a62522c62 100644
--- a/api/agents/_id/_sub.js
+++ b/api/agents/_id/_sub.js
@@ -435,7 +435,11 @@ export const handleSign = wrap(async (req, res, id) => {
let signature;
try {
- const pkHex = await recoverAgentKey(encryptedKey);
+ const pkHex = await recoverAgentKey(encryptedKey, {
+ agentId: row.id,
+ userId: auth.userId,
+ reason: 'sign_message',
+ });
signature = await new Wallet(pkHex).signMessage(body.message);
} catch (e) {
console.error('[agents/sign] signing failed', e);
diff --git a/api/cron/forge-seed-cron.js b/api/cron/forge-seed-cron.js
index 674b5105b..aaadaa1f4 100644
--- a/api/cron/forge-seed-cron.js
+++ b/api/cron/forge-seed-cron.js
@@ -22,6 +22,7 @@ import { env } from '../_lib/env.js';
import { sql } from '../_lib/db.js';
import { constantTimeEquals } from '../_lib/crypto.js';
import { SEED_PROMPTS, OG_USERNAMES } from '../_lib/seed-prompts.js';
+import { circuitState, circuitRecordFailure, circuitRecordSuccess } from '../_lib/forge-scale.js';
import { randomUUID } from 'node:crypto';
const ORIGIN = () => env.APP_ORIGIN || 'https://three.ws';
@@ -34,12 +35,16 @@ const FETCH_TIMEOUT_MS = 48_000;
const MAX_CONCURRENT_PENDING = 3;
const MIN_JOB_AGE_SECONDS = 20;
-// Circuit breaker — survives warm lambda invocations; resets on cold start / redeploy.
-// When CIRCUIT_THRESHOLD consecutive forge submits fail the circuit opens for
+// Circuit breaker — state is shared across instances via Redis (forge-scale.js) so
+// every cron lambda sees the same open/closed decision; without that, each instance
+// would rediscover a provider outage on its own and keep submitting into a dead
+// lane. When CIRCUIT_THRESHOLD consecutive forge submits fail the circuit opens for
// (failures × CIRCUIT_BASE_MS) so the cron goes quiet during provider outages.
+const CIRCUIT_NAME = 'forge-seed';
const CIRCUIT_THRESHOLD = 3;
const CIRCUIT_BASE_MS = 10 * 60_000; // 10 min × consecutive failures
-const _circuit = { failures: 0, openUntil: 0 };
+const noteCircuitFailure = () =>
+ circuitRecordFailure(CIRCUIT_NAME, { threshold: CIRCUIT_THRESHOLD, baseMs: CIRCUIT_BASE_MS });
function requireCron(req, res) {
const secret = process.env.CRON_SECRET || env.CRON_SECRET;
@@ -182,11 +187,12 @@ async function startNextJob(origin) {
return { skipped: true, reason: `${count} jobs already pending` };
}
- if (_circuit.openUntil > Date.now()) {
- const minsLeft = Math.ceil((_circuit.openUntil - Date.now()) / 60_000);
+ const circuit = await circuitState(CIRCUIT_NAME);
+ if (circuit.open) {
+ const minsLeft = Math.ceil((circuit.openUntil - Date.now()) / 60_000);
return {
skipped: true,
- reason: `circuit open for ${minsLeft}m more (${_circuit.failures} consecutive failures)`,
+ reason: `circuit open for ${minsLeft}m more (${circuit.failures} consecutive failures)`,
};
}
@@ -235,19 +241,13 @@ async function startNextJob(origin) {
});
if (submit.timedOut) {
- _circuit.failures++;
- if (_circuit.failures >= CIRCUIT_THRESHOLD) {
- _circuit.openUntil = Date.now() + _circuit.failures * CIRCUIT_BASE_MS;
- }
+ await noteCircuitFailure();
await sql`delete from users where id = ${user.id}`.catch(() => {});
return { ok: false, reason: 'forge submit timed out — will retry next tick' };
}
if (submit.status !== 200) {
- _circuit.failures++;
- if (_circuit.failures >= CIRCUIT_THRESHOLD) {
- _circuit.openUntil = Date.now() + _circuit.failures * CIRCUIT_BASE_MS;
- }
+ await noteCircuitFailure();
await sql`delete from users where id = ${user.id}`.catch(() => {});
return {
ok: false,
@@ -272,8 +272,7 @@ async function startNextJob(origin) {
await sql`delete from users where id = ${user.id}`.catch(() => {});
return { ok: false, reason: `avatar insert failed: ${err?.message}` };
}
- _circuit.failures = 0;
- _circuit.openUntil = 0;
+ await circuitRecordSuccess(CIRCUIT_NAME);
await sql`
insert into forge_seed_jobs
(user_id, raw_client_id, job_id, prompt, model_category,
@@ -295,8 +294,7 @@ async function startNextJob(origin) {
// Otherwise the lane is asynchronous — record the job so the next tick polls it.
if (submit.body?.job_id) {
- _circuit.failures = 0;
- _circuit.openUntil = 0;
+ await circuitRecordSuccess(CIRCUIT_NAME);
await sql`
insert into forge_seed_jobs (user_id, raw_client_id, job_id, prompt, model_category)
values (${user.id}, ${rawClientId}, ${submit.body.job_id}, ${chosen.prompt}, ${chosen.category})
@@ -312,10 +310,7 @@ async function startNextJob(origin) {
}
// Neither a finished model nor a poll token — a genuine failure.
- _circuit.failures++;
- if (_circuit.failures >= CIRCUIT_THRESHOLD) {
- _circuit.openUntil = Date.now() + _circuit.failures * CIRCUIT_BASE_MS;
- }
+ await noteCircuitFailure();
await sql`delete from users where id = ${user.id}`.catch(() => {});
return {
ok: false,
diff --git a/api/forge.js b/api/forge.js
index 3b58113be..fd9255346 100644
--- a/api/forge.js
+++ b/api/forge.js
@@ -490,11 +490,13 @@ async function startJob(req, res) {
}
// $THREE hold-to-access gate (Token Utility v1) — the High tier (200k poly +
- // PBR) spends real GPU/vendor budget on a PLATFORM-keyed backend, so it's the
- // first real $THREE-gated feature: reserved for holders (Bronze+, $25 hold) or
- // a presented tier pass, otherwise a hold-or-pay 402. BYOK backends are exempt
- // (the caller pays their own vendor key — key-gated, not hold-gated). Draft and
- // Standard are never gated, and internal cron seed jobs bypass it entirely.
+ // PBR, textured) is the platform's premium quality tier. It now runs on a
+ // free-for-us engine (HuggingFace Hunyuan3D) like every other tier, so this is
+ // a pure monetization gate — we charge for higher quality, not to recover
+ // vendor spend: reserved for holders (Bronze+, $25 hold) or a presented tier
+ // pass, otherwise a hold-or-pay 402. BYOK backends are exempt (the caller pays
+ // their own vendor key — key-gated, not hold-gated). Draft and Standard are
+ // never gated, and internal cron seed jobs bypass it entirely.
// requireFeatureAccess writes the 402 (three_hold_required) itself and returns
// { ok:false }; on a holder it writes nothing and lets the job proceed.
if (tier.id === 'high' && BACKENDS[backendId]?.byok === false && !isInternalSeedRequest(req)) {
diff --git a/api/galaxy.js b/api/galaxy.js
index 698f29da9..3ba7b9117 100644
--- a/api/galaxy.js
+++ b/api/galaxy.js
@@ -19,6 +19,7 @@
*/
import { sql } from './_lib/db.js';
+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';
@@ -218,7 +219,12 @@ async function handleSearch(req, res, cfg) {
// the most active agents. Wallet + token surface the on-chain identity layer in the
// viewer; both are public-safe.
async function loadPublishedAgents(limit) {
- const rows = await sql`
+ // This is the same public feed for every viewer, and its `chat_count`
+ // correlated subquery + `ORDER BY chat_count` forces a COUNT(*) over
+ // usage_events for EVERY published agent on each load — the dominant cost
+ // here. Cache the result for 60s so that expensive ranking runs at most once
+ // a minute regardless of traffic.
+ const rows = await cacheWrap(`galaxy:published:${limit}`, 60, async () => await sql`
SELECT
i.id,
i.name,
@@ -240,7 +246,7 @@ async function loadPublishedAgents(limit) {
AND length(trim(i.name)) > 0
ORDER BY chat_count DESC, i.created_at DESC
LIMIT ${limit}
- `;
+ `);
return rows.map((row) => {
const meta = row.meta || {};
diff --git a/api/portfolio/[action].js b/api/portfolio/[action].js
index babb35131..4b0fb8c18 100644
--- a/api/portfolio/[action].js
+++ b/api/portfolio/[action].js
@@ -253,7 +253,11 @@ async function sendEvm({ agent, asset, recipient, amount, memo }) {
}
const chainId = agent.chain_id || 8453;
- const pkHex = await recoverAgentKey(encryptedKey);
+ const pkHex = await recoverAgentKey(encryptedKey, {
+ agentId: agent.id,
+ userId: agent.user_id ?? null,
+ reason: `portfolio_send_${asset}`,
+ });
const { Wallet, parseEther, Contract } = await import('ethers');
const provider = await evmFallbackProvider(chainId);
const signer = new Wallet(pkHex, provider);
diff --git a/api/pump/trending.js b/api/pump/trending.js
index 58782883a..033fd7976 100644
--- a/api/pump/trending.js
+++ b/api/pump/trending.js
@@ -19,16 +19,42 @@ const PUMP_FRONTEND_BASE = 'https://frontend-api-v3.pump.fun';
// Process-local cache. Trending shifts slowly; many tabs polling on nav into the
// dashboard would otherwise hammer the upstreams. Warm-starts share this map.
-let _cache = { value: null, expiresAt: 0, limit: 0 };
+// `storedAt` lets us serve the value as STALE (past its TTL) when every live
+// upstream is down — a slowly-changing market feed is far better shown a few
+// minutes old than blanked out with a 502 during an upstream blip.
+let _cache = { value: null, storedAt: 0, expiresAt: 0, limit: 0 };
// Separate cache slot for the rich (full-coin) payload — it carries far more per
// token than the thin projection, so it must not collide with `_cache`.
-let _richCache = { value: null, expiresAt: 0, limit: 0 };
+let _richCache = { value: null, storedAt: 0, expiresAt: 0, limit: 0 };
const TTL_MS = 30_000;
+// How long a cached feed may be served as a stale fallback after every live
+// upstream has failed. Bounds how old the market data can get during an outage.
+const STALE_MAX_MS = 10 * 60_000;
+// Upstream fetch timeout. Trending is a fast feed behind a 30s cache + stale
+// fallback, so a long wait buys nothing — fail fast and fall through.
+const UPSTREAM_TIMEOUT_MS = 5000;
+// Birdeye circuit breaker: after a failure, skip Birdeye entirely for a cooldown
+// so an influx during a Birdeye outage stops paying the per-request timeout on
+// the way to the pump.fun fallback. Auto-recovers when the cooldown elapses.
+const BIRDEYE_COOLDOWN_MS = 60_000;
+let _birdeyeCooldownUntil = 0;
+
+// Serve a cached feed past its TTL when live upstreams are down. Returns the
+// sliced value if the slot holds enough items and is within the stale window,
+// else null. Keyed by the same `limit >=` rule as the fresh-cache check.
+function serveStale(slot, limit, now) {
+ if (!slot.value || slot.limit < limit) return null;
+ if (now - slot.storedAt > STALE_MAX_MS) return null;
+ return slot.value.slice(0, limit);
+}
// Primary: Birdeye trending feed. Returns null (not throws) on any failure so the
// caller can transparently fall back.
async function fetchBirdeye(limit) {
if (!BIRDEYE_API_KEY) return null;
+ // Circuit open: a recent Birdeye failure put it in cooldown — skip straight to
+ // the fallback instead of paying the timeout again.
+ if (Date.now() < _birdeyeCooldownUntil) return null;
const url =
`https://public-api.birdeye.so/defi/token_trending` +
`?sort_by=rank&sort_type=asc&offset=0&limit=${limit}`;
@@ -36,12 +62,17 @@ async function fetchBirdeye(limit) {
try {
upstream = await fetch(url, {
headers: { 'X-API-KEY': BIRDEYE_API_KEY, 'x-chain': 'solana', accept: 'application/json' },
- signal: AbortSignal.timeout(8000),
+ signal: AbortSignal.timeout(UPSTREAM_TIMEOUT_MS),
});
} catch {
+ _birdeyeCooldownUntil = Date.now() + BIRDEYE_COOLDOWN_MS;
+ return null;
+ }
+ if (!upstream.ok) {
+ // 429 / 5xx — trip the breaker so the next requests skip the timeout.
+ _birdeyeCooldownUntil = Date.now() + BIRDEYE_COOLDOWN_MS;
return null;
}
- if (!upstream.ok) return null;
const payload = await upstream.json().catch(() => null);
const tokens = payload?.data?.tokens;
if (!Array.isArray(tokens)) return null;
@@ -70,7 +101,7 @@ async function fetchPumpFun(limit) {
url.searchParams.set('includeNsfw', 'false');
let upstream;
try {
- upstream = await fetch(url, { headers: { accept: 'application/json' }, signal: AbortSignal.timeout(8000) });
+ upstream = await fetch(url, { headers: { accept: 'application/json' }, signal: AbortSignal.timeout(UPSTREAM_TIMEOUT_MS) });
} catch {
return null;
}
@@ -116,7 +147,7 @@ async function fetchPumpFunRich(limit) {
url.searchParams.set('includeNsfw', 'false');
let upstream;
try {
- upstream = await fetch(url, { headers: { accept: 'application/json' }, signal: AbortSignal.timeout(8000) });
+ upstream = await fetch(url, { headers: { accept: 'application/json' }, signal: AbortSignal.timeout(UPSTREAM_TIMEOUT_MS) });
} catch {
return null;
}
@@ -152,9 +183,17 @@ export default wrap(async (req, res) => {
}
const richData = await fetchPumpFunRich(limit);
if (!richData) {
+ // Upstream down — serve the last good payload as stale rather than blanking
+ // the visualizer. Shorter edge cache so we retry the live source soon.
+ const stale = serveStale(_richCache, limit, now);
+ if (stale) {
+ return json(res, 200, { data: stale, stale: true }, {
+ 'cache-control': 'public, max-age=10, s-maxage=20',
+ });
+ }
return error(res, 502, 'upstream_error', 'Trending market data is temporarily unavailable');
}
- _richCache = { value: richData, expiresAt: now + TTL_MS, limit };
+ _richCache = { value: richData, storedAt: now, expiresAt: now + TTL_MS, limit };
return json(res, 200, { data: richData }, { 'cache-control': 'public, max-age=15, s-maxage=30' });
}
@@ -167,9 +206,18 @@ export default wrap(async (req, res) => {
let data = await fetchBirdeye(limit);
if (!data) data = await fetchPumpFun(limit);
if (!data) {
+ // Both live sources are down — serve the last good feed as stale so the home
+ // card, communities, constellation, and visualizer keep rendering through the
+ // blip instead of dead-ending on a 502. Shorter edge cache so we retry soon.
+ const stale = serveStale(_cache, limit, now);
+ if (stale) {
+ return json(res, 200, { data: stale, stale: true }, {
+ 'cache-control': 'public, max-age=10, s-maxage=20',
+ });
+ }
return error(res, 502, 'upstream_error', 'Trending market data is temporarily unavailable');
}
- _cache = { value: data, expiresAt: now + TTL_MS, limit };
+ _cache = { value: data, storedAt: now, expiresAt: now + TTL_MS, limit };
return json(res, 200, { data }, { 'cache-control': 'public, max-age=15, s-maxage=30' });
});
diff --git a/data/changelog.json b/data/changelog.json
index 4dcae7fc6..a807d9726 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,35 @@
{
"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-06-21",
+ "title": "Live market feed stays up through provider blips",
+ "summary": "The trending-tokens feed that powers the home card, communities, the token constellation, and the 3D visualizer is now resilient to upstream outages. If a market data provider goes down or rate-limits us, we transparently fall back to a second source; if both are briefly unavailable, the surfaces keep showing the last good data (clearly marked as a moment stale) instead of going blank. We also added a fast-fail circuit breaker so a slow provider can't drag the feed down during a traffic spike. Net effect: the live market views stay populated and snappy even when a data provider hiccups.",
+ "tags": [
+ "infra",
+ "improvement"
+ ]
+ },
+ {
+ "date": "2026-06-21",
+ "title": "Platform-wide hardening: payment integrity, security, and scale",
+ "summary": "A broad reliability pass across the parts of three.ws that move real money and serve heavy traffic. On the money side: bundle purchases and agent payments are now verified on-chain before anything unlocks, each payment is credited exactly once, withdrawals can't be processed twice, and recurring subscriptions can't be double-billed. On the security side: a set of input-handling and link-safety fixes across pages, stronger protection for custodial keys at rest, and tighter checks on outbound agent payments so funds only ever move in the expected asset. On the scale side: the busiest directory, profile, and feed pages now ride a short cache and run far fewer database queries, so they stay fast as the community grows. Most of this is invisible by design — it's the plumbing that keeps the platform correct and quick under load.",
+ "tags": [
+ "security",
+ "improvement",
+ "infra"
+ ]
+ },
+ {
+ "date": "2026-06-21",
+ "title": "The $THREE page now spells out why to hold — four real utility pillars",
+ "summary": "The $THREE page leads with a clear \"Why hold $THREE\" section: revenue buybacks (a fixed, live share of platform revenue buys $THREE on the open market), holder rewards (every paid action reflects $THREE back to holders pro-rata), hold-to-access (discounts, higher quotas, and pro perks), and real usage (deploying agents, forging avatars, and trading the marketplace all run on $THREE). Each pillar maps to a mechanism that actually exists on the platform, and the buyback figure is wired to the live commitment. The page's market data also now rides a shared cache, so it stays fast and reliable under heavy traffic.",
+ "tags": [
+ "feature",
+ "improvement"
+ ],
+ "link": "/three-token"
+ },
{
"date": "2026-06-21",
"title": "Regrinding an agent's vanity wallet no longer risks its funds",
diff --git a/package.json b/package.json
index 4609376ea..68c6a0062 100644
--- a/package.json
+++ b/package.json
@@ -138,6 +138,7 @@
"mixamo:all": "node scripts/mixamo-all.mjs",
"test": "vitest run && playwright test",
"test:core": "vitest run --maxWorkers=1",
+ "test:gate": "node scripts/test-gate.mjs",
"test:e2e": "playwright test",
"test:pages": "node scripts/test-pages.mjs",
"verify:ibm": "node scripts/verify-ibm-pages.mjs",
diff --git a/pages/forge.html b/pages/forge.html
index abb64d462..9ebeeecb6 100644
--- a/pages/forge.html
+++ b/pages/forge.html
@@ -226,6 +226,54 @@
.aspect button:disabled .eng-free {
opacity: 0.5;
}
+ /* Static legend decoding the engine-button affordances (FREE pill, key
+ glyph, health dots) so the picker is self-explanatory at a glance. */
+ .engine-legend {
+ display: flex;
+ flex-wrap: wrap;
+ gap: var(--space-xs) var(--space-md);
+ margin: var(--space-2xs) 0 0;
+ font-size: var(--text-xs);
+ color: var(--ink-dim);
+ }
+ .engine-legend .el-item {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.4em;
+ white-space: nowrap;
+ }
+ .engine-legend .el-free {
+ padding: 0.05em 0.4em;
+ border-radius: 999px;
+ font-size: 0.85em;
+ font-weight: 700;
+ letter-spacing: 0.04em;
+ color: #4ade80;
+ background: rgba(34, 197, 94, 0.14);
+ border: 1px solid rgba(74, 222, 128, 0.38);
+ }
+ html[data-theme='light'] .engine-legend .el-free {
+ color: #0a7d33;
+ background: rgba(34, 197, 94, 0.16);
+ border-color: rgba(34, 197, 94, 0.32);
+ }
+ .engine-legend .el-key {
+ width: 0.92em;
+ height: 0.92em;
+ opacity: 0.6;
+ }
+ .engine-legend .el-dot {
+ width: 0.5em;
+ height: 0.5em;
+ border-radius: 50%;
+ }
+ .engine-legend .el-dot-busy {
+ background: var(--warning, #e0a93e);
+ }
+ .engine-legend .el-dot-down {
+ background: var(--danger, #e05a5a);
+ opacity: 0.7;
+ }
.aspect button:focus-visible,
.chip:focus-visible,
.btn:focus-visible {
@@ -2756,6 +2804,15 @@
id="engine"
></div>
</div>
+ <p class="engine-legend" id="engine-legend">
+ <span class="el-item"><span class="el-free">FREE</span> no API key</span>
+ <span class="el-item"
+ ><svg class="el-key" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="8" cy="15" r="4"/><path d="M10.85 12.15 19 4"/><path d="m18 5 2 2"/><path d="m15 8 2 2"/></svg>
+ your own key</span
+ >
+ <span class="el-item"><span class="el-dot el-dot-busy"></span> busy</span>
+ <span class="el-item"><span class="el-dot el-dot-down"></span> unavailable</span>
+ </p>
<div class="byok-row is-hidden" id="byok-row">
<label class="fq-label" for="provider-key" id="byok-label">API key</label>
<input
@@ -2905,7 +2962,8 @@
</div>
<div class="viewer-load-error" id="viewer-load-error" role="alert" aria-live="polite">
<span class="viewer-load-error-icon" aria-hidden="true">⚠</span>
- <p>Model failed to load. Use the download button below to save the file directly.</p>
+ <p>Model failed to load — often a brief network hiccup on the file. Retry, or use the download button below to save it directly.</p>
+ <button type="button" class="btn ghost" id="viewer-retry">Retry loading</button>
</div>
</div>
<div class="result-bar">
diff --git a/public/changelog.json b/public/changelog.json
index 3d5a592f3..b696a4e0d 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-21T06:08:08.925Z",
+ "generated_at": "2026-06-21T06:14:10.120Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -126,6 +126,29 @@
"improvement"
]
},
+ {
+ "date": "2026-06-21",
+ "type": "update",
+ "title": "Live market feed stays up through provider blips",
+ "summary": "The trending-tokens feed that powers the home card, communities, the token constellation, and the 3D visualizer is now resilient to upstream outages. If a market data provider goes down or rate-limits us, we transparently fall back to a second source; if both are briefly unavailable, the surfaces keep showing the last good data (clearly marked as a moment stale) instead of going blank. We also added a fast-fail circuit breaker so a slow provider can't drag the feed down during a traffic spike. Net effect: the live market views stay populated and snappy even when a data provider hiccups.",
+ "link": null,
+ "tags": [
+ "infra",
+ "improvement"
+ ]
+ },
+ {
+ "date": "2026-06-21",
+ "type": "update",
+ "title": "Platform-wide hardening: payment integrity, security, and scale",
+ "summary": "A broad reliability pass across the parts of three.ws that move real money and serve heavy traffic. On the money side: bundle purchases and agent payments are now verified on-chain before anything unlocks, each payment is credited exactly once, withdrawals can't be processed twice, and recurring subscriptions can't be double-billed. On the security side: a set of input-handling and link-safety fixes across pages, stronger protection for custodial keys at rest, and tighter checks on outbound agent payments so funds only ever move in the expected asset. On the scale side: the busiest directory, profile, and feed pages now ride a short cache and run far fewer database queries, so they stay fast as the community grows. Most of this is invisible by design — it's the plumbing that keeps the platform correct and quick under load.",
+ "link": null,
+ "tags": [
+ "security",
+ "improvement",
+ "infra"
+ ]
+ },
{
"date": "2026-06-21",
"type": "update",
@@ -168,6 +191,17 @@
"improvement"
]
},
+ {
+ "date": "2026-06-21",
+ "type": "update",
+ "title": "The $THREE page now spells out why to hold — four real utility pillars",
+ "summary": "The $THREE page leads with a clear \"Why hold $THREE\" section: revenue buybacks (a fixed, live share of platform revenue buys $THREE on the open market), holder rewards (every paid action reflects $THREE back to holders pro-rata), hold-to-access (discounts, higher quotas, and pro perks), and real usage (deploying agents, forging avatars, and trading the marketplace all run on $THREE). Each pillar maps to a mechanism that actually exists on the platform, and the buyback figure is wired to the live commitment. The page's market data also now rides a shared cache, so it stays fast and reliable under heavy traffic.",
+ "link": "/three-token",
+ "tags": [
+ "feature",
+ "improvement"
+ ]
+ },
{
"date": "2026-06-20",
"type": "launch",
diff --git a/public/changelog.xml b/public/changelog.xml
index 31374813a..1ee0b8474 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -94,6 +94,22 @@
<category>fix</category>
<description>Two reliability fixes for everyone trading, launching, and browsing. First: every on-chain action that moves funds — coin launches, buys and sells, buybacks, payouts, transfers — now treats a transaction that lands but reverts as a real failure instead of quietly reporting success. You'll see an accurate error and your spending limit won't be charged for a trade that didn't go through. Second: public profile and creator pages are now cacheable at the edge, so they load noticeably faster under load. No action needed — these apply automatically.</description>
</item>
+ <item>
+ <title>Live market feed stays up through provider blips</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-06-21:Live market feed stays up through provider blips</guid>
+ <pubDate>Sun, 21 Jun 2026 12:00:00 GMT</pubDate>
+ <category>infra</category>
+ <description>The trending-tokens feed that powers the home card, communities, the token constellation, and the 3D visualizer is now resilient to upstream outages. If a market data provider goes down or rate-limits us, we transparently fall back to a second source; if both are briefly unavailable, the surfaces keep showing the last good data (clearly marked as a moment stale) instead of going blank. We also added a fast-fail circuit breaker so a slow provider can't drag the feed down during a traffic spike. Net effect: the live market views stay populated and snappy even when a data provider hiccups.</description>
+ </item>
+ <item>
+ <title>Platform-wide hardening: payment integrity, security, and scale</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-06-21:Platform-wide hardening: payment integrity, security, and scale</guid>
+ <pubDate>Sun, 21 Jun 2026 12:00:00 GMT</pubDate>
+ <category>security</category>
+ <description>A broad reliability pass across the parts of three.ws that move real money and serve heavy traffic. On the money side: bundle purchases and agent payments are now verified on-chain before anything unlocks, each payment is credited exactly once, withdrawals can't be processed twice, and recurring subscriptions can't be double-billed. On the security side: a set of input-handling and link-safety fixes across pages, stronger protection for custodial keys at rest, and tighter checks on outbound agent payments so funds only ever move in the expected asset. On the scale side: the busiest directory, profile, and feed pages now ride a short cache and run far fewer database queries, so they stay fast as the community grows. Most of this is invisible by design — it's the plumbing that keeps the platform correct and quick under load.</description>
+ </item>
<item>
<title>Provably-fair vanity grinder now listed in the x402 bazaar</title>
<link>https://three.ws/vanity/verify</link>
@@ -126,6 +142,14 @@
<category>improvement</category>
<description>Solana is now the default everywhere you pick a chain — the dashboard's Default payment network setting, x402 merchant settlement, and the monetization payout wallet all default to Solana for every user, with Solana listed first. Base and Polygon remain available if you prefer an EVM chain.</description>
</item>
+ <item>
+ <title>The $THREE page now spells out why to hold — four real utility pillars</title>
+ <link>https://three.ws/three-token</link>
+ <guid isPermaLink="false">2026-06-21:The $THREE page now spells out why to hold — four real utility pillars</guid>
+ <pubDate>Sun, 21 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>The $THREE page leads with a clear &quot;Why hold $THREE&quot; section: revenue buybacks (a fixed, live share of platform revenue buys $THREE on the open market), holder rewards (every paid action reflects $THREE back to holders pro-rata), hold-to-access (discounts, higher quotas, and pro perks), and real usage (deploying agents, forging avatars, and trading the marketplace all run on $THREE). Each pillar maps to a mechanism that actually exists on the platform, and the buyback figure is wired to the live commitment. The page's market data also now rides a shared cache, so it stays fast and reliable under heavy traffic.</description>
+ </item>
<item>
<title>Grind-Bounty Market</title>
<link>https://three.ws/vanity/bounties</link>
diff --git a/public/features.json b/public/features.json
index a0b060f9a..d42006538 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-21T06:04:18.418Z",
+ "generated_at": "2026-06-21T06:14:09.858Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/public/pay/calls/index.html b/public/pay/calls/index.html
index 3e6aae158..4e0866fbd 100644
--- a/public/pay/calls/index.html
+++ b/public/pay/calls/index.html
@@ -157,22 +157,9 @@
</head>
<body>
-<header>
- <div id="nav-container"></div>
-</header>
+<div id="nav-container"></div>
<script src="/nav.js"></script>
-<header class="page-header">
- <div class="brand">
- <a href="/pay"><div class="logo"></div></a>
- <div>
- <div class="title">three.ws · pay-per-call</div>
- <div class="sub">paid x402 call · permalink</div>
- </div>
- </div>
- <a href="/pay" style="font-size: 13px;">← back to demo</a>
-</header>
-
<main id="main">
<div class="skeleton">loading paid call…</div>
</main>
@@ -181,6 +168,16 @@
const main = document.getElementById('main');
function escape(s) { return String(s).replace(/[<>&]/g, c => ({'<':'&lt;','>':'&gt;','&':'&amp;'}[c])); }
+// Map the settled network (CAIP-2 id or short name, as persisted on the call
+// record) to its display label + block-explorer. Keeps the receipt honest for
+// every chain the payment flow can settle on instead of hardcoding Solana.
+function networkMeta(network) {
+ const n = String(network || '').toLowerCase();
+ if (n.startsWith('eip155:8453') || n === 'base') return { label: 'Base mainnet', explorerTx: tx => `https://basescan.org/tx/${tx}` };
+ if (n.startsWith('eip155:42161') || n === 'arbitrum') return { label: 'Arbitrum One', explorerTx: tx => `https://arbiscan.io/tx/${tx}` };
+ if (n.startsWith('eip155:56') || n === 'bsc' || n === 'bnb') return { label: 'BNB Chain', explorerTx: tx => `https://bscscan.com/tx/${tx}` };
+ return { label: 'Solana mainnet', explorerTx: tx => `https://solscan.io/tx/${tx}` };
+}
function formatBytes(n) {
if (!Number.isFinite(n)) return '—';
if (n < 1024) return `${n} B`;
@@ -268,7 +265,8 @@ function renderResultBlock(record) {
function render(record) {
const tx = record.tx;
- const explorer = `https://solscan.io/tx/${tx}`;
+ const net = networkMeta(record.network);
+ const explorer = record.explorer || net.explorerTx(tx);
const amount = (Number(record.amount || 1000) / 1e6).toFixed(6);
const ts = new Date(record.ts || Date.now()).toUTCString();
const url = record.args?.url;
@@ -280,7 +278,7 @@ function render(record) {
document.querySelector('meta[property="og:title"]').content =
`three.ws · ${record.tool} (${amount} USDC) · x402 paid call`;
document.querySelector('meta[name="description"]').content =
- `${record.tool}${record.argsSummary ? ' · ' + record.argsSummary : ''} — paid ${amount} USDC on Solana, settled on-chain. View the receipt + result.`;
+ `${record.tool}${record.argsSummary ? ' · ' + record.argsSummary : ''} — paid ${amount} USDC on ${net.label}, settled on-chain. View the receipt + result.`;
const ogUrl = `${location.origin}/api/x402-pay/og?tx=${encodeURIComponent(tx)}`;
document.getElementById('ogImage').content = ogUrl;
document.getElementById('twImage').content = ogUrl;
@@ -294,7 +292,7 @@ function render(record) {
<h1><code style="background: rgba(255,255,255,0.06); padding: 4px 10px; border-radius: 6px; font-family: var(--mono); font-size: 18px;">${escape(record.tool)}</code>${record.argsSummary ? ' · ' + escape(record.argsSummary) : ''}</h1>
<div class="meta-grid" style="margin-top:14px">
${chip('amount', amount + ' USDC')}
- ${chip('network', 'Solana mainnet')}
+ ${chip('network', net.label)}
${chip('payer', `${(record.payer||'').slice(0,4)}…${(record.payer||'').slice(-4)}`)}
${chip('payTo', `${(record.payTo||'').slice(0,4)}…${(record.payTo||'').slice(-4)}`)}
</div>
@@ -308,7 +306,7 @@ function render(record) {
</div>
<div class="cta">
- <div class="text"><strong>Try it yourself.</strong> Pay $0.001 USDC for any MCP tool, settled per call on Solana — no API keys, no signup.</div>
+ <div class="text"><strong>Try it yourself.</strong> Pay per call in USDC for any MCP tool, settled on-chain — no API keys, no signup.</div>
<a class="btn" href="/pay${url ? `?validate=${encodeURIComponent(url)}` : ''}">Open the demo →</a>
</div>
`;
diff --git a/public/style.css b/public/style.css
index 4bb66c93b..a84d306d8 100644
--- a/public/style.css
+++ b/public/style.css
@@ -5526,6 +5526,94 @@ body[data-viewer-mode='explore'] #layout-switch {
max-width: 180px;
}
+/* ── First-agent empty state (no agent created yet) ──────────────────────── */
+
+.agent-home-empty-panel {
+ padding: var(--space-lg) var(--space-md);
+}
+
+.agent-home-empty-cta {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ text-align: center;
+ gap: var(--space-xs);
+}
+
+.agent-home-empty-ring {
+ width: 48px;
+ height: 48px;
+ border-radius: 50%;
+ display: grid;
+ place-items: center;
+ background: var(--accent-soft, rgba(123, 97, 255, 0.16));
+ border: 1px solid rgba(255, 255, 255, 0.1);
+ margin-bottom: var(--space-xs);
+}
+
+.agent-home-empty-emoji {
+ font-size: 22px;
+ line-height: 1;
+ color: var(--accent, #8a73ff);
+}
+
+.agent-home-empty-title {
+ font-size: 14px;
+ font-weight: 600;
+ letter-spacing: -0.01em;
+ color: var(--ink, rgba(255, 255, 255, 0.95));
+}
+
+.agent-home-empty-sub {
+ margin: 0 0 var(--space-xs);
+ max-width: 210px;
+ font-size: 11px;
+ line-height: 1.5;
+ color: rgba(255, 255, 255, 0.5);
+}
+
+.agent-home-empty-btn {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ padding: 8px 16px;
+ border-radius: var(--radius-control, 10px);
+ background: var(--accent, #7b61ff);
+ color: #fff;
+ font-size: 12px;
+ font-weight: 600;
+ text-decoration: none;
+ box-shadow: 0 4px 16px rgba(123, 97, 255, 0.3);
+ transition: transform 0.12s ease, filter 0.12s ease, box-shadow 0.12s ease;
+}
+
+.agent-home-empty-btn:hover {
+ filter: brightness(1.08);
+ transform: translateY(-1px);
+ box-shadow: 0 6px 20px rgba(123, 97, 255, 0.4);
+}
+
+.agent-home-empty-btn:active {
+ transform: translateY(0);
+}
+
+.agent-home-empty-btn:focus-visible {
+ outline: 2px solid var(--focus-ring-color, #8a73ff);
+ outline-offset: 2px;
+}
+
+.agent-home-empty-link {
+ margin-top: 4px;
+ font-size: 10px;
+ color: rgba(255, 255, 255, 0.4);
+ text-decoration: none;
+ transition: color 0.12s ease;
+}
+
+.agent-home-empty-link:hover {
+ color: rgba(255, 255, 255, 0.7);
+}
+
.agent-timeline-item {
display: flex;
align-items: flex-start;
diff --git a/scripts/build-vercel.mjs b/scripts/build-vercel.mjs
index 0157cb821..e574b3026 100644
--- a/scripts/build-vercel.mjs
+++ b/scripts/build-vercel.mjs
@@ -210,6 +210,12 @@ try {
// undeclared api/ imports — the classes behind the 2026-06-11 outage —
// instead of 18 minutes into NFT tracing or, worse, at runtime.
run('audit:deploy', 'node scripts/audit-deploy-artifacts.mjs'),
+ // Critical-path test gate: a curated, offline-safe subset of money/auth
+ // unit tests (see scripts/test-gate.mjs). With GitHub Actions unavailable,
+ // this is the only place a regression in confirmation handling, the HTTP
+ // cache/error boundary, or custody spend guards fails the deploy instead
+ // of shipping. ~7s; the full suite still runs via `npm test` locally.
+ run('test:gate', 'node scripts/test-gate.mjs'),
// Solana address parity + on-chain provenance: fails the build on a
// hardcoded non-$THREE coin or a drifted program ID/mint across the repo,
// and confirms the canonical accounts are the right kind on mainnet
diff --git a/scripts/codemod-lazy-images.mjs b/scripts/codemod-lazy-images.mjs
new file mode 100644
index 000000000..bbdb82d57
--- /dev/null
+++ b/scripts/codemod-lazy-images.mjs
@@ -0,0 +1,50 @@
+#!/usr/bin/env node
+/**
+ * codemod-lazy-images.mjs — add `loading="lazy" decoding="async"` to the
+ * JS-rendered <img> tags that lack them.
+ *
+ * Scope: src/ only. These are remote thumbnail / avatar / coin images injected
+ * into lists, grids, modals and sidebars — off-fold content that should defer
+ * its network fetch and decode off the main thread. Static-HTML <img> tags are
+ * deliberately NOT touched: those are mostly above-the-fold logos/wordmarks
+ * (the LCP image) where lazy-loading would HURT perceived load.
+ *
+ * Idempotent: skips any tag that already declares `loading=`. Prints every edit.
+ *
+ * node scripts/codemod-lazy-images.mjs # apply
+ * node scripts/codemod-lazy-images.mjs --dry-run # preview only
+ */
+
+import { readFileSync, writeFileSync } from 'node:fs';
+import { execSync } from 'node:child_process';
+
+const dryRun = process.argv.includes('--dry-run');
+const files = execSync('grep -rlE "<img\\b" src/', { encoding: 'utf8' })
+ .trim()
+ .split('\n')
+ .filter(Boolean);
+
+let totalEdits = 0;
+const touched = [];
+
+for (const file of files) {
+ const src = readFileSync(file, 'utf8');
+ let edits = 0;
+ // Match a REAL <img tag: `<img` + whitespace + an attribute name (a letter).
+ // This excludes bare `<img>` that appears as literal text inside code
+ // comments. Skip any tag that already declares loading=. We insert the two
+ // attributes immediately after `<img`, preserving the original whitespace
+ // and all existing attributes verbatim.
+ const out = src.replace(/<img(?![^>]*\bloading=)(\s+[a-zA-Z])/g, (_m, next) => {
+ edits++;
+ return `<img loading="lazy" decoding="async"${next}`;
+ });
+ if (edits > 0) {
+ totalEdits += edits;
+ touched.push(`${edits.toString().padStart(3)} ${file}`);
+ if (!dryRun) writeFileSync(file, out);
+ }
+}
+
+console.log(touched.sort((a, b) => parseInt(b) - parseInt(a)).join('\n'));
+console.log(`\n${dryRun ? '[dry-run] would add' : 'added'} loading="lazy" decoding="async" to ${totalEdits} <img> tag(s) across ${touched.length} file(s)`);
diff --git a/scripts/probe-app-empty-state.mjs b/scripts/probe-app-empty-state.mjs
index 0474ece67..76fea9582 100644
--- a/scripts/probe-app-empty-state.mjs
+++ b/scripts/probe-app-empty-state.mjs
@@ -13,8 +13,13 @@ page.on('pageerror', (e) => errors.push('PAGEERROR: ' + e.message));
// Fresh user: no localStorage, no session.
await page.addInitScript(() => { try { localStorage.clear(); sessionStorage.clear(); } catch {} });
-await page.goto(URL, { waitUntil: 'networkidle', timeout: 45000 }).catch((e) => errors.push('GOTO: ' + e.message));
-await page.waitForTimeout(4000);
+await page.goto(URL, { waitUntil: 'domcontentloaded', timeout: 45000 }).catch((e) => errors.push('GOTO: ' + e.message));
+// The agent-home container is populated asynchronously after the app boots —
+// poll for it rather than relying on networkidle (the 3D app holds connections open).
+await page.waitForFunction(() => {
+ const el = document.getElementById('agent-home-container');
+ return el && (el.innerHTML || '').trim().length > 0;
+}, { timeout: 20000 }).catch((e) => errors.push('WAIT_CONTAINER: ' + e.message));
const report = await page.evaluate(() => {
const home = document.getElementById('agent-home-container');
diff --git a/scripts/test-gate.mjs b/scripts/test-gate.mjs
new file mode 100644
index 000000000..25a62fa46
--- /dev/null
+++ b/scripts/test-gate.mjs
@@ -0,0 +1,46 @@
+#!/usr/bin/env node
+/**
+ * Critical-path test gate for the deploy build.
+ *
+ * GitHub Actions is unavailable on this account, so the Vercel deploy build is
+ * the only automated checkpoint (see scripts/build-vercel.mjs). The full vitest
+ * suite (`npm test`) drives a real browser via Playwright and includes specs
+ * that need live DB/RPC credentials — too heavy and too environment-dependent to
+ * gate every deploy on. This runs a curated subset of fast, offline-safe,
+ * mock-backed unit tests that cover the highest-consequence logic — money-path
+ * confirmation handling, the HTTP cache/error boundary, custody spend guards,
+ * payment verification — so a regression in any of them FAILS THE DEPLOY instead
+ * of shipping silently.
+ *
+ * Keep this list tight and green-offline. When you add a unit test that protects
+ * a money/auth invariant and runs without external credentials, add it here.
+ * Anything needing a live DB/RPC/browser belongs in `npm test`, not the gate.
+ */
+import { execFileSync } from 'child_process';
+import { resolve, dirname } from 'path';
+import { fileURLToPath } from 'url';
+
+const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
+
+const GATE_TESTS = [
+ 'tests/solana-confirm.test.js', // reverted-tx → throw (no false-success money path)
+ 'tests/http-cache-control.test.js', // cache/no-store boundary; errors never cached
+ 'tests/agent-custody-guards.test.js', // custodial ownership / spend guards
+ 'tests/agent-wallet-vanity.test.js', // vanity flow guards
+ 'tests/api/x402.test.js', // x402 payment manifest/verify surface
+ 'tests/api/three-token-leaderboard.test.js', // holder snapshot read path
+ 'tests/api/healthz.test.js', // smoke
+];
+
+console.log(`[test-gate] running ${GATE_TESTS.length} critical-path test files…`);
+try {
+ execFileSync('npx', ['vitest', 'run', ...GATE_TESTS], {
+ cwd: ROOT,
+ stdio: 'inherit',
+ env: process.env,
+ });
+ console.log('[test-gate] ✓ all critical-path tests passed');
+} catch {
+ console.error('[test-gate] ✗ critical-path tests failed — blocking deploy');
+ process.exit(1);
+}
diff --git a/src/agent-home.js b/src/agent-home.js
index 1979780ba..96becd499 100644
--- a/src/agent-home.js
+++ b/src/agent-home.js
@@ -81,8 +81,42 @@ export class AgentHome {
// ── Identity Card ─────────────────────────────────────────────────────────
+ // Brand-new owner with no agent yet — the activation call-to-action that
+ // replaces the empty identity card, so the sidebar always tells a first-time
+ // user what to do next instead of rendering a placeholder "Agent / no wallet".
+ _buildEmptyState() {
+ const panel = document.createElement('div');
+ panel.className = 'agent-home-panel agent-home-empty-panel';
+ panel.innerHTML = `
+ <div class="agent-home-empty-cta" role="region" aria-label="Get started">
+ <div class="agent-home-empty-ring" aria-hidden="true">
+ <span class="agent-home-empty-emoji">◎</span>
+ </div>
+ <div class="agent-home-empty-title">Create your first agent</div>
+ <p class="agent-home-empty-sub">Give a 3D character a name, a brain, and its own on-chain wallet — live in under a minute.</p>
+ <a class="agent-home-empty-btn" href="/create">
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true" focusable="false"><path d="M11 11V5h2v6h6v2h-6v6h-2v-6H5v-2z"/></svg>
+ Create your agent
+ </a>
+ <a class="agent-home-empty-link" href="/discover">or explore what others built →</a>
+ </div>
+ `;
+ this.container.appendChild(panel);
+ this._panel = panel;
+ }
+
_buildPanel() {
const id = this.identity;
+
+ // No real agent id yet (a freshly signed-in owner who hasn't created one):
+ // the normal identity card would render a meaningless "Agent / no wallet"
+ // phantom. Show the create-your-first-agent CTA instead. Real agents and
+ // visitor-viewed agents always carry an id, so they are unaffected.
+ if (!id.id) {
+ this._buildEmptyState();
+ return;
+ }
+
const skills = id.skills || [];
// Shared agent-wallet chip for the identity card. Default-deny ownership:
diff --git a/src/autopilot.js b/src/autopilot.js
index fc7a4d195..b0070df71 100644
--- a/src/autopilot.js
+++ b/src/autopilot.js
@@ -90,7 +90,7 @@ function narrate(activity, coinsById, agentImage) {
const a = activity.find((x) => x.status !== 'skipped');
const avatarEl = $('#narratorAvatar');
if (agentImage && avatarEl && !avatarEl.querySelector('img')) {
- avatarEl.insertAdjacentHTML('afterbegin', `<img src="${esc(agentImage)}" alt="">`);
+ avatarEl.insertAdjacentHTML('afterbegin', `<img loading="lazy" decoding="async" src="${esc(agentImage)}" alt="">`);
const nf = avatarEl.querySelector('.nf');
if (nf) nf.style.display = 'none';
}
@@ -129,7 +129,7 @@ function coinCard(c) {
const on = p.enabled;
const initials = (c.symbol || c.name || 'A').slice(0, 2).toUpperCase();
const img = c.image
- ? `<img src="${esc(c.image)}" alt="" onerror="this.remove()">`
+ ? `<img loading="lazy" decoding="async" src="${esc(c.image)}" alt="" onerror="this.remove()">`
: '';
const gradPill = c.stats.graduated
? `<span class="pill grad"><span class="dot"></span>Graduated</span>`
diff --git a/src/character.js b/src/character.js
index 044cbf293..9d00f4988 100644
--- a/src/character.js
+++ b/src/character.js
@@ -282,7 +282,7 @@ function renderMemes(agent) {
const createCard = `
<a class="ch-meme-create" href="/agent/${agent.id}?meme=1" title="Create meme">
<div class="ch-meme-create-icon">
- <img src="${agent.meta?.profile_image_url || agent.avatar_thumbnail_url || ''}"
+ <img loading="lazy" decoding="async" src="${agent.meta?.profile_image_url || agent.avatar_thumbnail_url || ''}"
onerror="this.style.display='none'"
alt="${agent.name}" />
</div>
diff --git a/src/characters.js b/src/characters.js
index 118dc17a6..6c585083b 100644
--- a/src/characters.js
+++ b/src/characters.js
@@ -50,7 +50,7 @@ function cardHtml(ch) {
const name = escHtml(ch.name);
const imgSrc = safeUrl(ch.image_url);
const avatarEl = imgSrc
- ? `<img class="chs-card-avatar" src="${imgSrc}" alt="${name}"
+ ? `<img loading="lazy" decoding="async" class="chs-card-avatar" src="${imgSrc}" alt="${name}"
onerror="this.style.display='none';this.nextElementSibling.style.display='flex'" />
<div class="chs-card-avatar-ph" style="display:none;background:${color}">${letter}</div>`
: `<div class="chs-card-avatar-ph" style="background:${color}">${letter}</div>`;
diff --git a/src/claim-wallet.js b/src/claim-wallet.js
index c3c0e9935..3e7916491 100644
--- a/src/claim-wallet.js
+++ b/src/claim-wallet.js
@@ -327,7 +327,7 @@ function cardHtml({ wallet, profile, coins, summary }, state = {}) {
const coinsHtml = coins.slice(0, 15).map((c) => {
const sym = esc((c.symbol || c.mint?.slice(0, 6) || '?').toUpperCase());
- const img = c.image_uri ? `<img src="${esc(c.image_uri)}" alt="" class="cw-coin-img" style="width:32px;height:32px;border-radius:8px;object-fit:cover" onerror="this.outerHTML='<div class=cw-coin-img>${sym.slice(0,2)}</div>'" loading="lazy" />` : `<div class="cw-coin-img">${sym.slice(0, 2)}</div>`;
+ const img = c.image_uri ? `<img loading="lazy" decoding="async" src="${esc(c.image_uri)}" alt="" class="cw-coin-img" style="width:32px;height:32px;border-radius:8px;object-fit:cover" onerror="this.outerHTML='<div class=cw-coin-img>${sym.slice(0,2)}</div>'" loading="lazy" />` : `<div class="cw-coin-img">${sym.slice(0, 2)}</div>`;
const pnl = c.pnl_sol != null ? fmtSol(c.pnl_sol) : '—';
const pnlCls = c.pnl_sol != null && c.pnl_sol > 0 ? 'pos' : c.pnl_sol != null && c.pnl_sol < 0 ? 'neg' : 'neu';
const creator = c.is_creator ? '<span class="cw-creator-badge">creator</span>' : '';
diff --git a/src/communities.js b/src/communities.js
index 7aa000da6..560f394be 100644
--- a/src/communities.js
+++ b/src/communities.js
@@ -50,7 +50,7 @@ function avatarChip({ kind, value, label, thumb, id }) {
chip.title = label;
chip.innerHTML = `
<span class="avatar-thumb">${thumb
- ? `<img src="${escAttr(thumb)}" alt="" referrerpolicy="no-referrer" onerror="this.style.display='none'" />`
+ ? `<img loading="lazy" decoding="async" src="${escAttr(thumb)}" alt="" referrerpolicy="no-referrer" onerror="this.style.display='none'" />`
: `<span class="avatar-glyph">🧍</span>`}</span>
<span class="avatar-name">${esc(label)}</span>`;
chip.addEventListener('click', () => {
diff --git a/src/components/screenshot-modal.js b/src/components/screenshot-modal.js
index c530cd5f0..119f4c858 100644
--- a/src/components/screenshot-modal.js
+++ b/src/components/screenshot-modal.js
@@ -19,7 +19,7 @@ export class ScreenshotModal {
<button class="screenshot-modal-close" title="Close">&times;</button>
</div>
<div class="screenshot-modal-body">
- <img alt="Screenshot preview" />
+ <img loading="lazy" decoding="async" alt="Screenshot preview" />
</div>
<div class="screenshot-modal-footer">
<button class="btn screenshot-modal-copy">Copy</button>
diff --git a/src/create-review-features.js b/src/create-review-features.js
index ab46eabcc..4e44b654c 100644
--- a/src/create-review-features.js
+++ b/src/create-review-features.js
@@ -345,7 +345,7 @@ export async function openIdentityModal(ctx = {}) {
}
const avatarHtml = thumbSrc
- ? `<img class="fm-id-avatar" src="${thumbSrc}" alt="${displayName}" />`
+ ? `<img loading="lazy" decoding="async" class="fm-id-avatar" src="${thumbSrc}" alt="${displayName}" />`
: `<div class="fm-id-avatar fm-id-avatar--fallback">${displayName.charAt(0).toUpperCase()}</div>`;
const body = document.createElement('div');
@@ -631,7 +631,7 @@ export default function Page() {
<div class="fm-browser-url">three.ws/@${escapeHtml(handle)}</div>
</div>
<div class="fm-browser-stage" data-stage>
- <img class="fm-browser-shot" alt="" data-shot hidden />
+ <img loading="lazy" decoding="async" class="fm-browser-shot" alt="" data-shot hidden />
<div class="fm-browser-skeleton" data-skel>Rendering live preview…</div>
</div>
</div>
diff --git a/src/create-review.js b/src/create-review.js
index 501bd82ed..8188a4d78 100644
--- a/src/create-review.js
+++ b/src/create-review.js
@@ -724,7 +724,7 @@ function showSaveOverlay(label, sublabel, opts = {}) {
el.setAttribute('aria-live', 'polite');
el.setAttribute('aria-busy', 'true');
el.innerHTML = `
- <img src="/three.svg" alt="" />
+ <img loading="lazy" decoding="async" src="/three.svg" alt="" />
<div class="label"></div>
<div class="sublabel"></div>
<div class="progress" hidden>
diff --git a/src/create.js b/src/create.js
index 0e38104e6..59c44dcef 100644
--- a/src/create.js
+++ b/src/create.js
@@ -403,7 +403,7 @@ function showSaveOverlay(label, sublabel) {
el.setAttribute('aria-live', 'polite');
el.setAttribute('aria-busy', 'true');
el.innerHTML = `
- <img src="/three.svg" alt="" />
+ <img loading="lazy" decoding="async" src="/three.svg" alt="" />
<div class="dots">...</div>
<div class="label"></div>
<div class="sublabel"></div>
diff --git a/src/dashboard-next/components/sidebar.js b/src/dashboard-next/components/sidebar.js
index 6718a3d99..ae069e776 100644
--- a/src/dashboard-next/components/sidebar.js
+++ b/src/dashboard-next/components/sidebar.js
@@ -41,8 +41,8 @@ export function renderSidebar(pathname) {
<aside class="dn-rail" data-component="rail">
<div class="dn-rail-head">
<a href="/dashboard" aria-label="Dashboard home">
- <img class="dn-rail-full" src="/three.svg" alt="three.ws" />
- <img class="dn-rail-mark" src="/favicon.ico" alt="three.ws" style="width:22px;height:22px;border-radius:5px" />
+ <img loading="lazy" decoding="async" class="dn-rail-full" src="/three.svg" alt="three.ws" />
+ <img loading="lazy" decoding="async" class="dn-rail-mark" src="/favicon.ico" alt="three.ws" style="width:22px;height:22px;border-radius:5px" />
</a>
</div>
<nav class="dn-rail-scroll" aria-label="Dashboard sections">
diff --git a/src/dashboard-next/pages/agents.js b/src/dashboard-next/pages/agents.js
index 43730a07f..5b96868fe 100644
--- a/src/dashboard-next/pages/agents.js
+++ b/src/dashboard-next/pages/agents.js
@@ -720,7 +720,7 @@ function openCreateModal(host, agents, avatars) {
const thumbEl = overlay.querySelector('[data-slot="avatar-thumb"]');
const labelEl = overlay.querySelector('[data-slot="avatar-label"]');
if (picked.thumbnail_url) {
- thumbEl.innerHTML = `<img src="${esc(picked.thumbnail_url)}" alt="${esc(picked.name || picked.id || 'Avatar')}" style="width:100%;height:100%;object-fit:cover" />`;
+ thumbEl.innerHTML = `<img loading="lazy" decoding="async" src="${esc(picked.thumbnail_url)}" alt="${esc(picked.name || picked.id || 'Avatar')}" style="width:100%;height:100%;object-fit:cover" />`;
}
labelEl.textContent = picked.name || picked.id;
}
@@ -807,7 +807,7 @@ function openEditModal(host, agent, avatars, allAgents) {
${(() => {
const av = avatars.find((x) => x.id === currentAvatarId);
return av?.thumbnail_url
- ? `<img src="${esc(av.thumbnail_url)}" alt="${esc(av.name || av.id || 'Avatar')}" style="width:100%;height:100%;object-fit:cover" />`
+ ? `<img loading="lazy" decoding="async" src="${esc(av.thumbnail_url)}" alt="${esc(av.name || av.id || 'Avatar')}" style="width:100%;height:100%;object-fit:cover" />`
: `<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round" style="color:var(--nxt-ink-dim)"><circle cx="12" cy="8" r="4"/><path d="M4 21c1.5-4.5 4.5-7 8-7s6.5 2.5 8 7"/></svg>`;
})()}
</span>
@@ -859,7 +859,7 @@ function openEditModal(host, agent, avatars, allAgents) {
const thumbEl = overlay.querySelector('[data-slot="avatar-thumb"]');
const labelEl = overlay.querySelector('[data-slot="avatar-label"]');
if (picked.thumbnail_url) {
- thumbEl.innerHTML = `<img src="${esc(picked.thumbnail_url)}" alt="${esc(picked.name || picked.id || 'Avatar')}" style="width:100%;height:100%;object-fit:cover" />`;
+ thumbEl.innerHTML = `<img loading="lazy" decoding="async" src="${esc(picked.thumbnail_url)}" alt="${esc(picked.name || picked.id || 'Avatar')}" style="width:100%;height:100%;object-fit:cover" />`;
}
labelEl.textContent = picked.name || picked.id;
}
diff --git a/src/dashboard-next/pages/copy.js b/src/dashboard-next/pages/copy.js
index daaad0879..54990f54e 100644
--- a/src/dashboard-next/pages/copy.js
+++ b/src/dashboard-next/pages/copy.js
@@ -131,7 +131,7 @@ function intentRow(e) {
const mintAttr = e.mint ? ` data-oracle-mint="${esc(e.mint)}"` : '';
return `
<div class="cp-item" data-id="${esc(e.id)}"${mintAttr}>
- <img class="cp-av" src="${esc(img(e))}" alt="" onerror="this.style.visibility='hidden'" />
+ <img loading="lazy" decoding="async" class="cp-av" src="${esc(img(e))}" alt="" onerror="this.style.visibility='hidden'" />
<div class="cp-mid">
<div class="cp-title">
<span class="cp-tag ${isBuy ? 'buy' : 'sell'}">${isBuy ? 'BUY' : 'SELL'}</span>
@@ -154,7 +154,7 @@ function subRow(s) {
const paused = s.status === 'paused';
return `
<div class="cp-item" data-sub="${esc(s.id)}">
- <img class="cp-av" src="${esc(img(s))}" alt="" onerror="this.style.visibility='hidden'" />
+ <img loading="lazy" decoding="async" class="cp-av" src="${esc(img(s))}" alt="" onerror="this.style.visibility='hidden'" />
<div class="cp-mid">
<div class="cp-title">
<a href="${traderHref(s.leader_agent_id)}" style="color:inherit;text-decoration:none">${esc(s.leader_name || 'trader')}</a>
@@ -177,7 +177,7 @@ function earningsSection(earnings) {
const total = Number(earnings.total_fee_owed_sol) || 0;
const rows = owing.map((i) => `
<div class="cp-item" data-earn-sub="${esc(i.subscription_id)}">
- <img class="cp-av" src="${esc(i.leader_image || '/favicon.ico')}" alt="" onerror="this.style.visibility='hidden'" />
+ <img loading="lazy" decoding="async" class="cp-av" src="${esc(i.leader_image || '/favicon.ico')}" alt="" onerror="this.style.visibility='hidden'" />
<div class="cp-mid">
<div class="cp-title">${esc(i.leader_name || 'trader')}</div>
<div class="cp-sub">${fmtSol(i.cumulative_profit_sol)} profit copied · ${(i.perf_fee_bps / 100).toFixed(0)}% fee</div>
@@ -239,7 +239,7 @@ function historyRow(e) {
const label = status === 'skipped' ? (SKIP_LABEL[e.skip_reason] || 'Skipped') : status[0].toUpperCase() + status.slice(1);
return `
<div class="cp-item">
- <img class="cp-av" src="${esc(img(e))}" alt="" onerror="this.style.visibility='hidden'" />
+ <img loading="lazy" decoding="async" class="cp-av" src="${esc(img(e))}" alt="" onerror="this.style.visibility='hidden'" />
<div class="cp-mid">
<div class="cp-title">${esc(e.symbol || e.name || 'coin')} <span class="cp-sub" style="margin:0">via ${esc(e.leader_name || 'trader')}</span></div>
<div class="cp-sub">${relTime(e.created_at)} · ${e.direction === 'buy' && e.planned_sol ? fmtSol(e.planned_sol) : e.direction}</div>
@@ -287,7 +287,7 @@ function discoverRow(t) {
].filter(Boolean).join(' · ');
return `
<div class="cp-item">
- <img class="cp-av" src="${esc(imgSrc)}" alt="" onerror="this.style.visibility='hidden'" />
+ <img loading="lazy" decoding="async" class="cp-av" src="${esc(imgSrc)}" alt="" onerror="this.style.visibility='hidden'" />
<div class="cp-mid">
<div class="cp-title"><a href="/trader/${esc(t.agent_id)}" style="color:inherit;text-decoration:none">${esc(t.agent_name || 'agent')}</a></div>
<div class="cp-sub">${esc(meta)}</div>
diff --git a/src/dashboard-next/pages/holders.js b/src/dashboard-next/pages/holders.js
index c157fcda2..ed371c855 100644
--- a/src/dashboard-next/pages/holders.js
+++ b/src/dashboard-next/pages/holders.js
@@ -55,7 +55,7 @@ function tierFor(pctOfSupply) {
main.innerHTML = `
<div style="margin-bottom:6px">
<div style="display:flex;align-items:center;gap:12px;margin-bottom:4px">
- <div style="width:36px;height:36px;border-radius:10px;background:#111116;border:1px solid #232329;display:grid;place-items:center;flex-shrink:0;overflow:hidden"><img src="/favicon.svg" alt="three.ws" width="26" height="26" style="display:block" /></div>
+ <div style="width:36px;height:36px;border-radius:10px;background:#111116;border:1px solid #232329;display:grid;place-items:center;flex-shrink:0;overflow:hidden"><img loading="lazy" decoding="async" src="/favicon.svg" alt="three.ws" width="26" height="26" style="display:block" /></div>
<div>
<h1 class="dn-h1" style="margin:0">$THREE Holders</h1>
<p class="dn-h1-sub" style="margin:0">The on-chain holder leaderboard for the protocol token</p>
diff --git a/src/dashboard-next/pages/irl-placements.js b/src/dashboard-next/pages/irl-placements.js
index 9e9c0e4db..022240587 100644
--- a/src/dashboard-next/pages/irl-placements.js
+++ b/src/dashboard-next/pages/irl-placements.js
@@ -1149,7 +1149,7 @@ function openLocationMap({ pins, focusId, onSaved, onRemoved }) {
// ── Markers ────────────────────────────────────────────────────────────
function makeIcon(p, focused) {
const av = p.avatar_url
- ? `<img src="${esc(p.avatar_url)}" alt="" onerror="this.remove()" />`
+ ? `<img loading="lazy" decoding="async" src="${esc(p.avatar_url)}" alt="" onerror="this.remove()" />`
: '📍';
return L.divIcon({
className: 'irlmap-pin',
diff --git a/src/dashboard-next/pages/portfolio.js b/src/dashboard-next/pages/portfolio.js
index f159a2e34..16d1c4e0d 100644
--- a/src/dashboard-next/pages/portfolio.js
+++ b/src/dashboard-next/pages/portfolio.js
@@ -866,7 +866,7 @@ function renderDrawerContent(host, data, token = null) {
const symbol = data.symbol || '?';
const chain = CHAIN[data.chain] || CHAIN.solana;
const logoHtml = data.logo
- ? `<img src="${esc(data.logo)}" alt="" class="pf-drawer-logo" />`
+ ? `<img loading="lazy" decoding="async" src="${esc(data.logo)}" alt="" class="pf-drawer-logo" />`
: `<div class="pf-drawer-logo pf-token-logo-ph" style="width:44px;height:44px;font-size:20px">${esc(symbol[0])}</div>`;
const hasChart = data.chart?.points?.length >= 2;
diff --git a/src/dashboard-next/pages/referrals.js b/src/dashboard-next/pages/referrals.js
index be3193228..613e7f869 100644
--- a/src/dashboard-next/pages/referrals.js
+++ b/src/dashboard-next/pages/referrals.js
@@ -205,7 +205,7 @@ function frontFace(card, refUrl) {
<div class="ref-face front" data-face="front">
<div class="ref-sheen"></div>
<div class="ref-row">
- <div class="ref-brand"><img src="/favicon.ico" alt="" />three.ws</div>
+ <div class="ref-brand"><img loading="lazy" decoding="async" src="/favicon.ico" alt="" />three.ws</div>
<div class="ref-chip" aria-hidden="true"></div>
</div>
<div class="ref-row" style="margin-top:14px;align-items:flex-start;gap:14px">
@@ -250,7 +250,7 @@ function backFace(card, refUrl) {
</div>
<div class="ref-divider" style="margin-top:12px"></div>
<div class="ref-row" style="margin-top:10px;color:rgba(255,255,255,.5);font-size:11px">
- <div class="ref-brand" style="font-size:13px;opacity:.85"><img src="/favicon.ico" alt="" />three.ws</div>
+ <div class="ref-brand" style="font-size:13px;opacity:.85"><img loading="lazy" decoding="async" src="/favicon.ico" alt="" />three.ws</div>
<span>© ${new Date().getFullYear()} three.ws</span>
</div>
</div>`;
diff --git a/src/dashboard-next/pages/sniper.js b/src/dashboard-next/pages/sniper.js
index 1af355435..ebaf4700c 100644
--- a/src/dashboard-next/pages/sniper.js
+++ b/src/dashboard-next/pages/sniper.js
@@ -305,7 +305,7 @@ function stratCard(s) {
return `<div class="sn-card ${armed ? 'armed' : ''}" data-agent="${esc(s.agent_id)}">
<div class="sn-card-head" data-toggle="card">
- <img class="sn-av" src="${esc(img)}" alt="" onerror="this.style.visibility='hidden'" />
+ <img loading="lazy" decoding="async" class="sn-av" src="${esc(img)}" alt="" onerror="this.style.visibility='hidden'" />
<div class="sn-info">
<div class="sn-name">${esc(s.agent_name || s.agent_id)}</div>
<div class="sn-meta">
diff --git a/src/dashboard-next/pages/three-token.js b/src/dashboard-next/pages/three-token.js
index 2e00560e1..e059a7bd6 100644
--- a/src/dashboard-next/pages/three-token.js
+++ b/src/dashboard-next/pages/three-token.js
@@ -87,7 +87,7 @@ function toast(msg) {
main.innerHTML = `
<div style="margin-bottom:6px">
<div style="display:flex;align-items:center;gap:12px;margin-bottom:4px">
- <div style="width:36px;height:36px;border-radius:10px;background:#111116;border:1px solid #232329;display:grid;place-items:center;flex-shrink:0;overflow:hidden"><img src="/favicon.svg" alt="three.ws" width="26" height="26" style="display:block" /></div>
+ <div style="width:36px;height:36px;border-radius:10px;background:#111116;border:1px solid #232329;display:grid;place-items:center;flex-shrink:0;overflow:hidden"><img loading="lazy" decoding="async" src="/favicon.svg" alt="three.ws" width="26" height="26" style="display:block" /></div>
<div>
<h1 class="dn-h1" style="margin:0">$THREE</h1>
<p class="dn-h1-sub" style="margin:0">The protocol token powering the three.ws agent economy</p>
diff --git a/src/dashboard/dashboard.js b/src/dashboard/dashboard.js
index f069b0aa5..e357645a9 100644
--- a/src/dashboard/dashboard.js
+++ b/src/dashboard/dashboard.js
@@ -3004,7 +3004,7 @@ function renderAgentRows(list, onchainAgents, dbAgents) {
'gap:12px; padding:10px; border:1px solid #2a2a34; border-radius:10px; align-items:flex-start';
el.innerHTML = `
<div style="flex:0 0 64px; width:64px; height:64px; border-radius:8px; background:#0f0f17; overflow:hidden; display:flex; align-items:center; justify-content:center">
- ${img ? `<img src="${attr(img)}" alt="" style="max-width:100%;max-height:100%;object-fit:cover" onerror="this.remove()">` : '<span class="muted" style="font-size:10px">no image</span>'}
+ ${img ? `<img loading="lazy" decoding="async" src="${attr(img)}" alt="" style="max-width:100%;max-height:100%;object-fit:cover" onerror="this.remove()">` : '<span class="muted" style="font-size:10px">no image</span>'}
</div>
<div style="flex:1 1 auto; min-width:0">
<div class="row" style="justify-content:space-between; gap:8px; flex-wrap:wrap">
diff --git a/src/erc8004/register-ui.js b/src/erc8004/register-ui.js
index f92a3a697..2bc41b7fd 100644
--- a/src/erc8004/register-ui.js
+++ b/src/erc8004/register-ui.js
@@ -961,7 +961,7 @@ export class RegisterUI {
_previewThumbHtml(thumb) {
if (thumb.kind === 'img') {
- return `<img src="${esc(thumb.src)}" alt="" onerror="this.style.display='none';this.nextElementSibling.style.display='flex'" />
+ return `<img loading="lazy" decoding="async" src="${esc(thumb.src)}" alt="" onerror="this.style.display='none';this.nextElementSibling.style.display='flex'" />
<div class="deploy-preview-ph" style="display:none">Image failed to load</div>`;
}
if (thumb.kind === 'glb') {
@@ -2105,7 +2105,7 @@ export class RegisterUI {
_imageSummaryHtml() {
const url = (this.form.imageUrl || '').trim();
if (!url) return '';
- const thumb = `<img src="${esc(url)}" alt="Agent image" class="erc8004-img-thumb"
+ const thumb = `<img loading="lazy" decoding="async" src="${esc(url)}" alt="Agent image" class="erc8004-img-thumb"
onerror="this.style.display='none'" />`;
if (url.startsWith('data:')) {
const kb = Math.round((url.length * 0.75) / 1024);
diff --git a/src/erc8004/user-profile.js b/src/erc8004/user-profile.js
index 4e7cc1721..7bcf9d69e 100644
--- a/src/erc8004/user-profile.js
+++ b/src/erc8004/user-profile.js
@@ -214,7 +214,7 @@ function renderCard({ chainId, agentId, name, description, image, glb, solanaAdd
const thumbContent = glb
? '' // filled lazily
: image
- ? `<img src="${esc(image)}" alt="${esc(name)} thumbnail" style="width:100%;height:100%;object-fit:cover">`
+ ? `<img loading="lazy" decoding="async" src="${esc(image)}" alt="${esc(name)} thumbnail" style="width:100%;height:100%;object-fit:cover">`
: `<div class="up-card-thumb-placeholder">◎</div>`;
const editUrl = `/a/${chainId}/${agentId}/edit`;
diff --git a/src/forge.js b/src/forge.js
index d5034a2ed..b8361bb3a 100644
--- a/src/forge.js
+++ b/src/forge.js
@@ -838,7 +838,7 @@ function buildSlots() {
<div class="shimmer" aria-hidden="true"></div>
<span>Uploading…</span>
</div>
- <img class="vs-thumb" alt="" />
+ <img loading="lazy" decoding="async" class="vs-thumb" alt="" />
<span class="vs-badge">${VIEW_LABELS[i]}</span>
<button type="button" class="vs-remove" aria-label="Remove ${VIEW_LABELS[i]} view">×</button>
<div class="vs-error">
@@ -1113,7 +1113,7 @@ function buildSketchSlot() {
<div class="shimmer" aria-hidden="true"></div>
<span>Uploading…</span>
</div>
- <img class="vs-thumb" alt="" />
+ <img loading="lazy" decoding="async" class="vs-thumb" alt="" />
<span class="vs-badge">Sketch</span>
<button type="button" class="vs-remove" aria-label="Remove sketch">×</button>
<div class="vs-error">
@@ -2147,6 +2147,17 @@ els.viewer.addEventListener('error', () => {
els.viewerShell.classList.remove('is-loading');
}
});
+// Retry a failed GLB fetch in place — a transient network blip on the file (the
+// common cause) shouldn't dead-end at download-only. Clearing then re-setting src
+// on the next frame forces model-viewer to refetch the same URL.
+document.getElementById('viewer-retry')?.addEventListener('click', () => {
+ const src = els.viewer.getAttribute('src');
+ if (!src) return;
+ els.viewerShell?.classList.remove('has-load-error');
+ els.viewerShell?.classList.add('is-loading');
+ els.viewer.setAttribute('src', '');
+ requestAnimationFrame(() => els.viewer.setAttribute('src', src));
+});
// The GLB finished painting — drop the load skeleton.
els.viewer.addEventListener('load', () => {
els.viewerShell?.classList.remove('is-loading');
diff --git a/src/game/play-gate.js b/src/game/play-gate.js
index 37beed45b..ae6116b12 100644
--- a/src/game/play-gate.js
+++ b/src/game/play-gate.js
@@ -208,7 +208,7 @@ class Gate {
const card = (inner) => `
<div class="pg-backdrop"></div>
<div class="pg-card">
- <div class="pg-brand"><img src="/three.svg" alt="" width="30" height="30"><span>COIN COMMUNITIES</span></div>
+ <div class="pg-brand"><img loading="lazy" decoding="async" src="/three.svg" alt="" width="30" height="30"><span>COIN COMMUNITIES</span></div>
${inner}
</div>`;
diff --git a/src/marketplace.js b/src/marketplace.js
index 8fee9436d..61a6adcc0 100644
--- a/src/marketplace.js
+++ b/src/marketplace.js
@@ -3643,7 +3643,7 @@ async function openAnimationPurchase(id) {
<button class="anim-buy-close" type="button" aria-label="Close">✕</button>
<div class="anim-buy-media">
${item.thumbnail_url
- ? `<img src="${escapeHtml(item.thumbnail_url)}" alt="" />`
+ ? `<img loading="lazy" decoding="async" src="${escapeHtml(item.thumbnail_url)}" alt="" />`
: `<div class="anim-buy-media-empty">🎬</div>`}
<span class="anim-listing-price ${item.free ? 'free' : 'paid'}">${escapeHtml(priceLabel)}</span>
</div>
diff --git a/src/memory-seed.js b/src/memory-seed.js
index 5601ce80a..ce8cebe0f 100644
--- a/src/memory-seed.js
+++ b/src/memory-seed.js
@@ -261,7 +261,7 @@ export function mountSeedWidget(host, opts = {}) {
if (gh) {
panels.push(`<div class="msw-panel">
<div class="msw-panel-head">
- ${gh.avatar_url ? `<img class="msw-panel-av" src="${esc(gh.avatar_url)}" alt="" referrerpolicy="no-referrer"/>` : ''}
+ ${gh.avatar_url ? `<img loading="lazy" decoding="async" class="msw-panel-av" src="${esc(gh.avatar_url)}" alt="" referrerpolicy="no-referrer"/>` : ''}
<div><div class="msw-panel-name">${esc(gh.name || gh.handle)}</div><div class="msw-panel-sub">@${esc(gh.handle)}</div></div>
</div>
<div class="msw-panel-stats"><span><b>${gh.public_repos}</b> repos</span><span><b>${gh.followers}</b> followers</span></div>
@@ -271,7 +271,7 @@ export function mountSeedWidget(host, opts = {}) {
if (x) {
panels.push(`<div class="msw-panel">
<div class="msw-panel-head">
- ${x.avatar_url ? `<img class="msw-panel-av" src="${esc(x.avatar_url)}" alt="" referrerpolicy="no-referrer"/>` : ''}
+ ${x.avatar_url ? `<img loading="lazy" decoding="async" class="msw-panel-av" src="${esc(x.avatar_url)}" alt="" referrerpolicy="no-referrer"/>` : ''}
<div><div class="msw-panel-name">${esc(x.name || x.handle)}</div><div class="msw-panel-sub">@${esc(x.handle)}</div></div>
</div>
<div class="msw-panel-stats"><span><b>${x.follower_count}</b> followers</span><span><b>${x.tweet_count}</b> posts</span></div>
@@ -281,7 +281,7 @@ export function mountSeedWidget(host, opts = {}) {
if (fc) {
panels.push(`<div class="msw-panel">
<div class="msw-panel-head">
- ${fc.avatar_url ? `<img class="msw-panel-av" src="${esc(fc.avatar_url)}" alt="" referrerpolicy="no-referrer"/>` : ''}
+ ${fc.avatar_url ? `<img loading="lazy" decoding="async" class="msw-panel-av" src="${esc(fc.avatar_url)}" alt="" referrerpolicy="no-referrer"/>` : ''}
<div><div class="msw-panel-name">${esc(fc.display_name || fc.handle)}</div><div class="msw-panel-sub">@${esc(fc.handle)}</div></div>
</div>
<div class="msw-panel-stats"><span><b>${fc.follower_count}</b> followers</span></div>
diff --git a/src/play/arena.js b/src/play/arena.js
index 9656e13c9..e9057ab8d 100644
--- a/src/play/arena.js
+++ b/src/play/arena.js
@@ -223,7 +223,7 @@ function createLabel(agent) {
el.type = 'button';
el.innerHTML = `
<span class="lbl-rank">#${agent.label.rank ?? '?'}</span>
- ${agent.label.thumbnail ? `<img class="lbl-av" src="${esc(agent.label.thumbnail)}" alt="" onerror="this.remove()"/>` : ''}
+ ${agent.label.thumbnail ? `<img loading="lazy" decoding="async" class="lbl-av" src="${esc(agent.label.thumbnail)}" alt="" onerror="this.remove()"/>` : ''}
<span class="lbl-meta">
<span class="lbl-name">${esc(agent.label.name)}</span>
<span class="lbl-pnl ${agent.label.pnlUp ? 'up' : 'down'}">${esc(agent.label.pnlText)}</span>
@@ -378,7 +378,7 @@ function renderAgentDrawer(data, id) {
$('drawerBody').innerHTML = `
<div class="dw-head">
- ${a.image ? `<img src="${esc(a.image)}" alt="" onerror="this.remove()"/>` : '<span class="dw-av-fallback"></span>'}
+ ${a.image ? `<img loading="lazy" decoding="async" src="${esc(a.image)}" alt="" onerror="this.remove()"/>` : '<span class="dw-av-fallback"></span>'}
<div>
<div class="dw-name">${esc(a.name || 'Agent')}</div>
<div class="dw-sub">${verified}</div>
@@ -447,7 +447,7 @@ function renderBoard(rows) {
const onerr = `this.outerHTML='<span class=&quot;r-av r-av-fb&quot;>${initial}</span>'`;
return `<button class="row no-orbit" data-id="${esc(r.agent_id)}">
<span class="r-rank">${r.rank}</span>
- <img class="r-av" src="${esc(r.image || '/avatars/thumbs/default.png')}" alt="" onerror="${onerr}"/>
+ <img loading="lazy" decoding="async" class="r-av" src="${esc(r.image || '/avatars/thumbs/default.png')}" alt="" onerror="${onerr}"/>
<span class="r-name">${esc(name)}<small>${r.open_positions} open · ${r.closed ? wr + '% win' : 'new'}</small></span>
<span class="r-pnl ${up ? 'up' : 'down'}">${fmtSol(r.realized_pnl_sol)}</span>
</button>`;
diff --git a/src/pump/launch-token-modal.js b/src/pump/launch-token-modal.js
index 5c9e28f16..d0a107a17 100644
--- a/src/pump/launch-token-modal.js
+++ b/src/pump/launch-token-modal.js
@@ -407,7 +407,7 @@ export class LaunchTokenModal {
const d = this._d;
const initials = (d.symbol || d.name || 'A').slice(0, 3).toUpperCase();
const img = d.image
- ? `<img class="ltm-pc-img" src="${_esc(d.image)}" alt="" onerror="this.style.display='none';this.nextElementSibling.style.display='flex'">
+ ? `<img loading="lazy" decoding="async" class="ltm-pc-img" src="${_esc(d.image)}" alt="" onerror="this.style.display='none';this.nextElementSibling.style.display='flex'">
<div class="ltm-pc-fallback" style="display:none">${_esc(initials)}</div>`
: `<div class="ltm-pc-fallback">${_esc(initials)}</div>`;
return `
@@ -437,7 +437,7 @@ export class LaunchTokenModal {
if (media) {
const initials = (symbol || name || 'A').slice(0, 3).toUpperCase();
media.innerHTML = image
- ? `<img class="ltm-pc-img" src="${_esc(image)}" alt="" onerror="this.style.display='none';this.nextElementSibling.style.display='flex'">
+ ? `<img loading="lazy" decoding="async" class="ltm-pc-img" src="${_esc(image)}" alt="" onerror="this.style.display='none';this.nextElementSibling.style.display='flex'">
<div class="ltm-pc-fallback" style="display:none">${_esc(initials)}</div>`
: `<div class="ltm-pc-fallback">${_esc(initials)}</div>`;
}
diff --git a/src/selfie-modal.js b/src/selfie-modal.js
index 4bf5518e2..3f71bdcb6 100644
--- a/src/selfie-modal.js
+++ b/src/selfie-modal.js
@@ -107,7 +107,7 @@ class SelfieModal {
<div class="sfm-stage" data-sfm-stage>
<video class="sfm-video" data-sfm-video autoplay playsinline muted></video>
<canvas class="sfm-canvas" data-sfm-canvas></canvas>
- <img class="sfm-preview-img" data-sfm-preview alt="Captured selfie preview" hidden />
+ <img loading="lazy" decoding="async" class="sfm-preview-img" data-sfm-preview alt="Captured selfie preview" hidden />
<div class="sfm-badges" data-sfm-badges></div>
<div class="sfm-hint" data-sfm-hint>Loading face mesh...</div>
</div>
diff --git a/src/share-panel.js b/src/share-panel.js
index ec61ab7f2..391df07ed 100644
--- a/src/share-panel.js
+++ b/src/share-panel.js
@@ -142,7 +142,7 @@ export class SharePanel {
<div class="share-panel-row" data-section="og">
<div class="share-panel-label">OG preview</div>
- <img class="share-panel-og-img" src="${_esc(ogUrl)}"
+ <img loading="lazy" decoding="async" class="share-panel-og-img" src="${_esc(ogUrl)}"
alt="OG preview for ${_esc(name || id)}"
style="aspect-ratio:1200/630;">
<div class="share-panel-field" style="margin-top:6px;">
diff --git a/src/shared/agent-tip-modal.js b/src/shared/agent-tip-modal.js
index 8aea0b5e0..e70a92971 100644
--- a/src/shared/agent-tip-modal.js
+++ b/src/shared/agent-tip-modal.js
@@ -163,7 +163,7 @@ export function openTipModal(agent, opts = {}) {
backdrop.innerHTML = `
<div class="ttm">
<div class="ttm-hd">
- ${avatar ? `<img class="ttm-av" src="${esc(avatar)}" alt="" onerror="this.remove()"/>` : '<div class="ttm-av"></div>'}
+ ${avatar ? `<img loading="lazy" decoding="async" class="ttm-av" src="${esc(avatar)}" alt="" onerror="this.remove()"/>` : '<div class="ttm-av"></div>'}
<div class="ttm-hd-txt">
<div class="ttm-hd-k">${esc(accepted.length ? 'Pay' : 'Tip')}</div>
<div class="ttm-hd-n" title="${esc(name)}">${esc(name)}</div>
@@ -198,7 +198,7 @@ export function openTipModal(agent, opts = {}) {
backdrop.innerHTML = `
<div class="ttm">
<div class="ttm-hd">
- ${avatar ? `<img class="ttm-av" src="${esc(avatar)}" alt="" onerror="this.remove()"/>` : '<div class="ttm-av"></div>'}
+ ${avatar ? `<img loading="lazy" decoding="async" class="ttm-av" src="${esc(avatar)}" alt="" onerror="this.remove()"/>` : '<div class="ttm-av"></div>'}
<div class="ttm-hd-txt">
<div class="ttm-hd-k">Sent</div>
<div class="ttm-hd-n" title="${esc(name)}">${esc(name)}</div>
diff --git a/src/three-token-page.js b/src/three-token-page.js
index 10933a675..5dac2ddca 100644
--- a/src/three-token-page.js
+++ b/src/three-token-page.js
@@ -329,7 +329,7 @@ function boot() {
wrap.className = 'tk-wrap';
wrap.innerHTML = `
<div class="tk-head">
- <div class="tk-logo"><img src="/favicon.svg" alt="three.ws" width="32" height="32" /></div>
+ <div class="tk-logo"><img loading="lazy" decoding="async" src="/favicon.svg" alt="three.ws" width="32" height="32" /></div>
<div style="flex:1;min-width:0">
<h1 class="tk-title">$THREE</h1>
<p class="tk-sub">The protocol token powering the three.ws agent economy</p>
diff --git a/src/trader.js b/src/trader.js
index 57c352727..b49a40563 100644
--- a/src/trader.js
+++ b/src/trader.js
@@ -219,7 +219,7 @@ function render(data) {
content.innerHTML = `
<section class="tp-hero">
<div class="tp-avatar-wrap">
- <img class="tp-avatar" src="${escapeHtml(img)}" alt="" onerror="this.src='${identicon(a.id || '?')}'" />
+ <img loading="lazy" decoding="async" class="tp-avatar" src="${escapeHtml(img)}" alt="" onerror="this.src='${identicon(a.id || '?')}'" />
</div>
<div class="tp-id">
<div class="tp-name">${escapeHtml(a.name || 'Unnamed agent')}${verifiedBadge(m.verified)}</div>
@@ -576,7 +576,7 @@ function renderWalletProfile(data) {
content.innerHTML = `
<section class="tp-hero">
<div class="tp-avatar-wrap">
- <img class="tp-avatar" src="${identicon(addr)}" alt="" />
+ <img loading="lazy" decoding="async" class="tp-avatar" src="${identicon(addr)}" alt="" />
</div>
<div class="tp-id">
<div class="tp-name"><span style="color:${color}">${escapeHtml(a.title || 'Unproven wallet')}</span></div>
diff --git a/src/trades.js b/src/trades.js
index 599b56733..e19db0a85 100644
--- a/src/trades.js
+++ b/src/trades.js
@@ -325,7 +325,7 @@ function cardHtml(t) {
const coinHref = t.mint && t.oracle_score != null ? `/oracle?mint=${escapeHtml(t.mint)}` : (pumpUrl || '#');
const coinTarget = t.oracle_score != null ? '' : ' target="_blank" rel="noopener"';
const imgHtml = `<a href="${coinHref}"${coinTarget} class="tf-coin-img-link" aria-label="View ${sym} conviction on Oracle" style="display:block;line-height:0">${imgSrc
- ? `<img src="${imgSrc}" alt="" class="tf-coin-img" style="width:48px;height:48px;border-radius:12px;object-fit:cover" onerror="this.outerHTML='<div class=tf-coin-img>${sym.slice(0, 2)}</div>'" loading="lazy" />`
+ ? `<img loading="lazy" decoding="async" src="${imgSrc}" alt="" class="tf-coin-img" style="width:48px;height:48px;border-radius:12px;object-fit:cover" onerror="this.outerHTML='<div class=tf-coin-img>${sym.slice(0, 2)}</div>'" loading="lazy" />`
: `<div class="tf-coin-img">${sym.slice(0, 2)}</div>`}</a>`;
const agentImgHtml = agentImg
diff --git a/src/walk.js b/src/walk.js
index 6de019f61..26b25c9b5 100644
--- a/src/walk.js
+++ b/src/walk.js
@@ -4070,7 +4070,7 @@ if (import.meta.env?.DEV) {
].join(';');
const imgHtml = COIN_PARAMS.image
- ? `<img src="${escAttr(COIN_PARAMS.image)}" alt="" referrerpolicy="no-referrer" onerror="this.replaceWith(Object.assign(document.createElement('span'),{textContent:'${escAttr(initials(COIN_PARAMS.symbol, COIN_PARAMS.name))}',className:'coin-fallback'}))" style="width:34px;height:34px;border-radius:50%;object-fit:cover;border:1px solid ${accent.css};flex:0 0 34px;background:#0e0e16" />`
+ ? `<img loading="lazy" decoding="async" src="${escAttr(COIN_PARAMS.image)}" alt="" referrerpolicy="no-referrer" onerror="this.replaceWith(Object.assign(document.createElement('span'),{textContent:'${escAttr(initials(COIN_PARAMS.symbol, COIN_PARAMS.name))}',className:'coin-fallback'}))" style="width:34px;height:34px;border-radius:50%;object-fit:cover;border:1px solid ${accent.css};flex:0 0 34px;background:#0e0e16" />`
: `<span class="coin-fallback">${esc(initials(COIN_PARAMS.symbol, COIN_PARAMS.name))}</span>`;
const title = COIN_PARAMS.symbol ? `$${esc(COIN_PARAMS.symbol)}` : 'Coin';
diff --git a/tests/api/forge-events.test.js b/tests/api/forge-events.test.js
new file mode 100644
index 000000000..0cea151e8
--- /dev/null
+++ b/tests/api/forge-events.test.js
@@ -0,0 +1,63 @@
+// Forge observability — structured logs always emit; counters are fail-open.
+//
+// readGenerationMetrics aggregates hourly Redis buckets into a rollup. With no
+// Redis configured (the unit-test default) every primitive must degrade to a
+// no-op: events still log, metrics read as null, and nothing throws. That
+// fail-open contract is what keeps instrumentation from ever breaking a
+// generation, so it's the core of what we assert here.
+
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import { recordGenerationEvent, readGenerationMetrics } from '../../api/_lib/forge-events.js';
+
+describe('forge-events — fail-open without Redis', () => {
+ let logSpy;
+ beforeEach(() => {
+ logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
+ });
+ afterEach(() => {
+ logSpy.mockRestore();
+ });
+
+ it('emits one structured forge_gen log line per event', async () => {
+ await recordGenerationEvent({
+ phase: 'done',
+ backend: 'huggingface',
+ tier: 'standard',
+ path: 'image',
+ latencyMs: 4200,
+ });
+ expect(logSpy).toHaveBeenCalledTimes(1);
+ const payload = JSON.parse(logSpy.mock.calls[0][0]);
+ expect(payload).toMatchObject({
+ evt: 'forge_gen',
+ phase: 'done',
+ backend: 'huggingface',
+ tier: 'standard',
+ path: 'image',
+ latency_ms: 4200,
+ cache_hit: false,
+ });
+ });
+
+ it('clamps a negative/invalid latency to null rather than logging a bogus number', async () => {
+ await recordGenerationEvent({ phase: 'done', backend: 'trellis', latencyMs: -5 });
+ const payload = JSON.parse(logSpy.mock.calls[0][0]);
+ expect(payload.latency_ms).toBeNull();
+ });
+
+ it('records cache hits in the log line', async () => {
+ await recordGenerationEvent({ phase: 'done', backend: 'trellis', cacheHit: true });
+ const payload = JSON.parse(logSpy.mock.calls[0][0]);
+ expect(payload.cache_hit).toBe(true);
+ });
+
+ it('never throws on any phase', async () => {
+ await expect(recordGenerationEvent({ phase: 'start', backend: 'nvidia' })).resolves.toBeUndefined();
+ await expect(recordGenerationEvent({ phase: 'failed', backend: 'trellis' })).resolves.toBeUndefined();
+ await expect(recordGenerationEvent({})).resolves.toBeUndefined();
+ });
+
+ it('reads metrics as null when Redis is absent (block omitted, not a fake outage)', async () => {
+ await expect(readGenerationMetrics()).resolves.toBeNull();
+ });
+});
diff --git a/tests/api/forge-tiers.test.js b/tests/api/forge-tiers.test.js
index f5eef1512..8c5b15d8b 100644
--- a/tests/api/forge-tiers.test.js
+++ b/tests/api/forge-tiers.test.js
@@ -17,9 +17,18 @@ import {
describe('forge-tiers — NVIDIA NIM backend registration', () => {
const prevKey = process.env.NVIDIA_API_KEY;
+ const prevHf = process.env.HF_TOKEN;
+ // Default routing now consults free-lane config (NVIDIA + HF). Start every test
+ // with HF unset so the "no free image lane → paid last resort" assertions are
+ // deterministic; tests that exercise the HF default opt in explicitly.
+ beforeEach(() => {
+ delete process.env.HF_TOKEN;
+ });
afterEach(() => {
if (prevKey === undefined) delete process.env.NVIDIA_API_KEY;
else process.env.NVIDIA_API_KEY = prevKey;
+ if (prevHf === undefined) delete process.env.HF_TOKEN;
+ else process.env.HF_TOKEN = prevHf;
});
it('registers a platform-keyed, free image-path backend', () => {
@@ -42,10 +51,12 @@ describe('forge-tiers — NVIDIA NIM backend registration', () => {
});
describe('free-tier default routing', () => {
- it('keeps the Replicate TRELLIS default when NIM is unconfigured', () => {
+ it('falls to the paid TRELLIS last resort only when no free image lane is configured', () => {
delete process.env.NVIDIA_API_KEY;
+ delete process.env.HF_TOKEN;
expect(resolveBackendId({ path: 'image', tier: 'draft' })).toBe('trellis');
expect(resolveBackendId({ path: 'image', tier: 'standard' })).toBe('trellis');
+ expect(resolveBackendId({ path: 'image', tier: 'high' })).toBe('trellis');
});
it('routes draft and standard tiers to the free NIM lane when configured', () => {
@@ -54,9 +65,11 @@ describe('forge-tiers — NVIDIA NIM backend registration', () => {
expect(resolveBackendId({ path: 'image', tier: 'standard' })).toBe('nvidia');
});
- it('never disturbs the high tier or the geometry path', () => {
+ it('routes the high tier to the free textured engine, geometry stays BYOK Meshy', () => {
process.env.NVIDIA_API_KEY = 'nvapi-test';
- expect(resolveBackendId({ path: 'image', tier: 'high' })).toBe('trellis');
+ process.env.HF_TOKEN = 'hf_test';
+ // High is free-for-us too — the higher-quality HuggingFace engine, not paid Replicate.
+ expect(resolveBackendId({ path: 'image', tier: 'high' })).toBe('huggingface');
expect(resolveBackendId({ path: 'geometry', tier: 'draft' })).toBe('meshy');
expect(resolveBackendId({ path: 'geometry', tier: 'standard' })).toBe('meshy');
});
diff --git a/tests/api/pump-trending-resilience.test.js b/tests/api/pump-trending-resilience.test.js
new file mode 100644
index 000000000..7d066b986
--- /dev/null
+++ b/tests/api/pump-trending-resilience.test.js
@@ -0,0 +1,145 @@
+/**
+ * Resilience of GET /api/pump/trending — the feed behind the home card,
+ * communities, constellation, and the 3D visualizer.
+ *
+ * Pins three load/outage behaviours so they can't regress:
+ * 1. Birdeye down → transparent pump.fun fallback (same shape).
+ * 2. A Birdeye failure trips a cooldown breaker, so the next cache-miss skips
+ * Birdeye instead of re-paying its timeout during an outage.
+ * 3. When BOTH live sources are down, a recent-enough cached feed is served as
+ * `stale: true` rather than dead-ending on a 502.
+ *
+ * fetch + the rate limiter are stubbed; module state is reset per test via
+ * resetModules so the process-local cache/breaker start clean.
+ */
+
+import { describe, it, expect, beforeAll, beforeEach, afterEach, vi } from 'vitest';
+
+beforeAll(() => {
+ process.env.BIRDEYE_API_KEY = 'test-birdeye-key';
+});
+
+vi.mock('../../api/_lib/rate-limit.js', async (importActual) => {
+ const actual = await importActual();
+ return {
+ ...actual,
+ limits: { ...actual.limits, publicIp: vi.fn(async () => ({ success: true, reset: Date.now() + 1000 })) },
+ clientIp: () => '203.0.113.9',
+ };
+});
+
+function birdeyeBody() {
+ return JSON.stringify({
+ data: { tokens: [{ address: 'A'.repeat(40), symbol: 'BIRD', name: 'Bird', price: 1.5, rank: 1 }] },
+ });
+}
+function pumpBody() {
+ return JSON.stringify([{ mint: 'B'.repeat(40), symbol: 'PUMP', name: 'Pump', image_uri: '' }]);
+}
+
+function mockFetch({ birdeyeOk = true, pumpOk = true } = {}) {
+ global.fetch = vi.fn(async (url) => {
+ const u = String(url);
+ if (u.includes('birdeye.so')) {
+ return birdeyeOk ? new Response(birdeyeBody(), { status: 200 }) : new Response('x', { status: 500 });
+ }
+ if (u.includes('pump.fun')) {
+ return pumpOk ? new Response(pumpBody(), { status: 200 }) : new Response('x', { status: 500 });
+ }
+ throw new Error(`unrouted fetch: ${u}`);
+ });
+}
+
+function makeReq(url) {
+ return { method: 'GET', url, headers: {}, on() {} };
+}
+function makeRes() {
+ return {
+ statusCode: 200,
+ headers: {},
+ body: null,
+ setHeader(n, v) {
+ this.headers[String(n).toLowerCase()] = v;
+ },
+ getHeader(n) {
+ return this.headers[String(n).toLowerCase()];
+ },
+ end(b) {
+ this.body = b ? JSON.parse(b) : null;
+ },
+ };
+}
+
+async function freshHandler() {
+ vi.resetModules();
+ return (await import('../../api/pump/trending.js')).default;
+}
+
+let savedFetch;
+beforeEach(() => {
+ savedFetch = global.fetch;
+});
+afterEach(() => {
+ global.fetch = savedFetch;
+ vi.useRealTimers();
+});
+
+describe('pump/trending resilience', () => {
+ it('falls back to pump.fun when Birdeye fails', async () => {
+ const handler = await freshHandler();
+ mockFetch({ birdeyeOk: false, pumpOk: true });
+ const res = makeRes();
+ await handler(makeReq('/api/pump/trending?limit=5'), res);
+
+ expect(res.statusCode).toBe(200);
+ expect(Array.isArray(res.body.data)).toBe(true);
+ expect(res.body.data[0].symbol).toBe('PUMP');
+ });
+
+ it('trips the Birdeye breaker so the next cache-miss skips it', async () => {
+ const handler = await freshHandler();
+ mockFetch({ birdeyeOk: false, pumpOk: true });
+ // First call: Birdeye fails (trips breaker), pump serves it, caches at limit=5.
+ await handler(makeReq('/api/pump/trending?limit=5'), makeRes());
+ global.fetch.mockClear();
+ // limit=40 misses the limit=5 cache → refetch; breaker open → Birdeye skipped.
+ await handler(makeReq('/api/pump/trending?limit=40'), makeRes());
+
+ const urls = global.fetch.mock.calls.map((c) => String(c[0]));
+ expect(urls.some((u) => u.includes('birdeye.so'))).toBe(false);
+ expect(urls.some((u) => u.includes('pump.fun'))).toBe(true);
+ });
+
+ it('serves the last good feed as stale when BOTH sources are down', async () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date('2026-06-21T00:00:00Z'));
+ const handler = await freshHandler();
+
+ // Prime the cache with a good pump.fun feed at limit=25.
+ mockFetch({ birdeyeOk: false, pumpOk: true });
+ const primed = makeRes();
+ await handler(makeReq('/api/pump/trending?limit=25'), primed);
+ expect(primed.body.data[0].symbol).toBe('PUMP');
+
+ // Advance past the 30s fresh TTL but within the 10-min stale window, and take
+ // BOTH live sources down.
+ vi.setSystemTime(new Date('2026-06-21T00:01:00Z')); // +60s
+ mockFetch({ birdeyeOk: false, pumpOk: false });
+ const res = makeRes();
+ await handler(makeReq('/api/pump/trending?limit=25'), res);
+
+ expect(res.statusCode).toBe(200);
+ expect(res.body.stale).toBe(true);
+ expect(res.body.data[0].symbol).toBe('PUMP');
+ });
+
+ it('502s only when both are down and there is no usable cache', async () => {
+ const handler = await freshHandler();
+ mockFetch({ birdeyeOk: false, pumpOk: false });
+ const res = makeRes();
+ await handler(makeReq('/api/pump/trending?limit=25'), res);
+
+ expect(res.statusCode).toBe(502);
+ expect(res.body.error).toBe('upstream_error');
+ });
+});
diff --git a/x402-payment-modal/server/vercel.js b/x402-payment-modal/server/vercel.js
index 9590719df..70dd7409a 100644
--- a/x402-payment-modal/server/vercel.js
+++ b/x402-payment-modal/server/vercel.js
@@ -27,7 +27,7 @@ async function readJsonBody(req) {
}
/**
- * @param {object} [options] { rpcUrl, devnetRpcUrl, origin }
+ * @param {object} [options] { rpcUrl, rpcUrls, devnetRpcUrl, devnetRpcUrls, logger, origin }
* @returns {(req: any, res: any) => Promise<void>}
*/
export function createVercelCheckoutHandler(options = {}) {
@@ -35,7 +35,7 @@ export function createVercelCheckoutHandler(options = {}) {
return async function handler(req, res) {
res.setHeader('Access-Control-Allow-Origin', allowOrigin);
res.setHeader('Access-Control-Allow-Methods', 'POST,OPTIONS');
- res.setHeader('Access-Control-Allow-Headers', 'content-type');
+ res.setHeader('Access-Control-Allow-Headers', 'content-type, x-idempotency-key');
if (req.method === 'OPTIONS') {
res.status(204).end();
return;
diff --git a/x402-payment-modal/src/index.js b/x402-payment-modal/src/index.js
index 3e730d709..99d518f50 100644
--- a/x402-payment-modal/src/index.js
+++ b/x402-payment-modal/src/index.js
@@ -58,15 +58,33 @@ const CONFIG = {
// ERC-8021 builder-code self-attribution echoed back when the 402 challenge
// declares a builder-code extension. Set either field to '' to disable it.
builderCode: { wallet: '3d_agent', service: '3d_agent_modal' },
- // CDN URLs for the crypto helpers loaded on demand (only when a Solana or an
- // EVM sign-in payment is actually attempted). Repoint these at a self-hosted
- // mirror to satisfy a strict Content-Security-Policy.
+ // Primary CDN URLs for the crypto helpers loaded on demand (only when a Solana
+ // or EVM sign-in payment is actually attempted). Each is tried first, then the
+ // loader falls back across additional independent CDNs (see ESM_FALLBACKS) so a
+ // single CDN outage during a traffic spike can't break payments. Repoint these
+ // at a self-hosted mirror to satisfy a strict Content-Security-Policy — your URL
+ // is always tried first.
esm: {
solanaWeb3: 'https://esm.sh/@solana/[email protected]?bundle',
nobleHashesSha3: 'https://esm.sh/@noble/[email protected]/sha3?bundle',
},
};
+// Independent CDN fallbacks tried (in order, after the configured primary) if the
+// primary is slow or down. Three uncorrelated providers ≈ no single point of
+// failure for the dynamic crypto-helper import that the Solana path depends on.
+const ESM_FALLBACKS = {
+ solanaWeb3: [
+ 'https://cdn.jsdelivr.net/npm/@solana/[email protected]/+esm',
+ 'https://cdn.skypack.dev/@solana/[email protected]',
+ ],
+ nobleHashesSha3: [
+ 'https://cdn.jsdelivr.net/npm/@noble/[email protected]/sha3/+esm',
+ 'https://cdn.skypack.dev/@noble/[email protected]/sha3',
+ ],
+};
+const ESM_IMPORT_TIMEOUT_MS = 12_000;
+
/**
* Merge caller overrides into CONFIG. Shallow-merges the nested `brand`,
* `builderCode`, and `esm` objects so you can override a single field. Call
@@ -456,7 +474,7 @@ function base58encode(bytes) {
let _evmChecksum = null;
async function loadEvmChecksum() {
if (_evmChecksum) return _evmChecksum;
- const sha3 = await import(/* @vite-ignore */ CONFIG.esm.nobleHashesSha3);
+ const sha3 = await importWithFallback(CONFIG.esm.nobleHashesSha3, ESM_FALLBACKS.nobleHashesSha3, '@noble/hashes/sha3');
const keccak = sha3.keccak_256;
_evmChecksum = (addr) => {
const a = String(addr).toLowerCase().replace(/^0x/, '');
@@ -1107,6 +1125,9 @@ class CheckoutModal {
async start() {
this.bodyEl.innerHTML = this.renderSteps('discover');
+ // Pre-warm the Solana web3 import now (while the user reads the modal and we
+ // fetch the challenge) so a slow CDN doesn't stall at sign time. Best-effort.
+ loadSolanaWeb3().catch(() => {});
try {
const challenge = await discoverChallenge(this.opts);
this.challenge = challenge;
@@ -1586,12 +1607,35 @@ function randomHex(bytes) {
return Array.from(arr).map((b) => b.toString(16).padStart(2, '0')).join('');
}
+// Try the configured primary URL, then each independent CDN fallback, racing
+// every attempt against a timeout so a hung CDN doesn't stall the payment — it
+// just moves on to the next. Returns the first module that imports; throws only
+// if every candidate fails.
+async function importWithFallback(primary, fallbacks, label) {
+ const seen = new Set();
+ const candidates = [primary, ...fallbacks].filter((u) => u && !seen.has(u) && seen.add(u));
+ let lastErr;
+ for (const url of candidates) {
+ try {
+ return await Promise.race([
+ import(/* @vite-ignore */ url),
+ new Promise((_, reject) =>
+ setTimeout(() => reject(new Error(`timed out loading ${label} from ${url}`)), ESM_IMPORT_TIMEOUT_MS),
+ ),
+ ]);
+ } catch (err) {
+ lastErr = err;
+ }
+ }
+ throw lastErr || new Error(`could not load ${label} from any CDN`);
+}
+
let _solanaWeb3 = null;
async function loadSolanaWeb3() {
if (_solanaWeb3) return _solanaWeb3;
- // Dynamic import from esm.sh keeps the drop-in script tiny — Solana web3.js
- // is only fetched when a Solana payment is actually attempted.
- _solanaWeb3 = await import(/* @vite-ignore */ CONFIG.esm.solanaWeb3);
+ // Loaded on demand (only when a Solana payment is attempted) and cached. The
+ // fallback chain means one CDN being down doesn't break Solana checkout.
+ _solanaWeb3 = await importWithFallback(CONFIG.esm.solanaWeb3, ESM_FALLBACKS.solanaWeb3, '@solana/web3.js');
return _solanaWeb3;
}