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.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat: forge observability events, store flywheel, and scaling refinements
nirholasd43408342868
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 2e33c9d96..78c10745a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,8 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **$THREE buyback commitment is now public and verifiable on the token page** — The $THREE page now leads with the protocol's buyback commitment — the fixed share of all platform revenue routed into buying $THREE on the open market and sending it to the treasury — shown as revenue earned, dollars committed, dollars deployed on-chain, and how much of the commitment has been kept. Every individual buyback is listed with a one-click Solscan receipt, so the promise is provable, not just stated. No burn: supply is never destroyed. (`/three-token`) `[feature]`- **$THREE holder leaderboard loads faster from a shared snapshot** — The $THREE holder leaderboard, its share card, and the token stats panel used to rescan every holder on-chain on each page view. They now read from a holder snapshot that refreshes every few minutes, so the board and badges load faster and the same numbers stay consistent across all three surfaces. (`/leaderboard`) `[improvement, infra]`- **Authorize $THREE once, then pay with no wallet popups** — The $THREE page now lets you set a spending allowance: approve a cap once, and paid actions across the platform — forge, skills, names, cosmetics — debit it automatically without asking you to sign every time. It's non-custodial and built on Solana's native, audited Subscriptions & Allowances program: your tokens stay in your own wallet until a charge pulls them, never more than the cap you set, and you can let it expire or revoke it anytime. Set a cap, top it up, or leave it off and keep signing each payment — your choice. (`/three-token`) `[feature]`+- **Forge hardened for a traffic surge — faster loads, protected free lanes** — We scaled Forge for the influx of new users. The engine catalog and live health status now serve from the edge cache, so the page loads instantly even under heavy traffic instead of recomputing on every visit. We also added a platform-wide safety valve on paid generation: if demand ever spikes past the shared paid budget, the free engines (NVIDIA and Hugging Face) stay fully open and you get a clear 'try a free engine' message instead of a hard failure — your own bring-your-own-key engines are never affected. Net result: Forge stays fast and available as we grow, and free 3D generation never gets crowded out. (`/forge`) `[infra, improvement]`+- **Forge scales further — duplicate generations collapse, free lane protected, prices shown up front** — More headroom for the influx. Forge now recognizes when the same prompt or photo set is already generating and quietly hands everyone the same result instead of paying to build it twice — so a viral prompt or a double-click no longer multiplies cost or wait. The free Hugging Face engine is now capped to a safe number of simultaneous jobs so a rush can't tie up the servers and stall everyone; over the cap, your generation cleanly falls back to another engine instead of hanging. The composer now shows the real price before you generate — 'Free' for Draft and Standard, the exact dollar amount (or 'Free, you hold $THREE') for High, and 'billed to your own key' for bring-your-own-key engines — so there are no surprises. Finally, the 3D viewer shows a loading shimmer instead of a dark void while your model paints in. (`/forge`) `[improvement, infra]`- **forge_avatar — one call turns a prompt into a rigged, animation-ready avatar** — A new forge_avatar MCP tool collapses the old two-step flow (generate a mesh, then rig it) into a single call: describe a character in text — or pass reference images — and it generates the textured model, auto-rigs it with a humanoid skeleton, and returns an animation-ready GLB that drops straight into the pose studio and plays the idle/walk library. A built-in humanoid check runs first, so a non-character prompt (furniture, a vehicle, an animal) is turned away with no charge instead of wasting a paid rig. It bundles generation and rigging at their combined price ($0.45) with no hidden markup, and you are never charged if no rigged avatar is produced. (`/docs/mcp`) `[sdk, feature]`- **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]`diff --git a/api/_lib/forge-events.js b/api/_lib/forge-events.jsnew file mode 100644index 000000000..e4c57d8be--- /dev/null+++ b/api/_lib/forge-events.js@@ -0,0 +1,145 @@+// Forge generation observability — fail-open structured logs + rolling counters.+//+// Under an influx you have to be able to SEE the pipeline: success rate, latency,+// and which backend is carrying the load. This module records every terminal+// generation outcome two ways:+// 1. One structured JSON log line per event — ALWAYS on, zero infra. Vercel log+// drains / any aggregator can query `evt:"forge_gen"` for live throughput,+// per-backend failure spikes, and latency without a database.+// 2. Best-effort rolling counters in the shared Upstash Redis, bucketed by hour,+// surfaced in /api/forge?health=1 so the health dashboard shows real success+// rate + latency instead of just upstream auth probes.+//+// Both fail OPEN: a metrics hiccup must never affect a generation. This is+// instrumentation, not a gate. Never construct a Redis client here — use the+// shared singleton (redis.js); per-module clients caused the June 2026 quota+// blowout.++import { getRedis } from './redis.js';++const redis = getRedis();++const METRICS_PREFIX = 'fc:metrics:';+const BUCKET_TTL_S = 26 * 3600; // keep ~26h so a 24h read always has full data+const DEFAULT_WINDOW_HOURS = 24;+const MAX_WINDOW_HOURS = 48;++// Epoch hour — the counter bucket granularity. Cheap to aggregate (≤48 HGETALLs)+// and fine-grained enough to watch a spike develop over an afternoon.+function hourBucket(ts = Date.now()) {+ return Math.floor(ts / 3_600_000);+}++// Record one generation event. `phase` is 'start' | 'done' | 'failed'. 'start'+// only logs (no counters — we count terminal outcomes, not attempts, so the+// success rate denominator is meaningful). latencyMs/cacheHit apply to 'done'.+// Returns a promise the async terminal writers already await; the Redis write is+// a single pipelined round-trip, so awaiting adds negligible latency and makes+// the counter durable (an un-awaited promise can be frozen by the serverless+// runtime before it flushes).+export async function recordGenerationEvent({+ phase,+ backend = 'unknown',+ tier = null,+ path = null,+ latencyMs = null,+ cacheHit = false,+ source = null,+ errorCode = null,+} = {}) {+ // 1) Structured log line — unconditional, must never throw.+ try {+ console.log(+ JSON.stringify({+ evt: 'forge_gen',+ phase,+ backend,+ tier,+ path,+ latency_ms: typeof latencyMs === 'number' && latencyMs >= 0 ? Math.round(latencyMs) : null,+ cache_hit: Boolean(cacheHit),+ source,+ error_code: errorCode,+ }),+ );+ } catch {+ /* logging is best-effort */+ }++ // 2) Rolling counters — terminal phases only, best-effort.+ if (!redis || (phase !== 'done' && phase !== 'failed')) return;+ const ok = phase === 'done';+ const safeBackend = String(backend || 'unknown').replace(/[^a-z0-9_-]/gi, '') || 'unknown';+ const key = `${METRICS_PREFIX}${hourBucket()}`;+ const fields = {+ total: 1,+ [ok ? 'ok' : 'fail']: 1,+ [`b:${safeBackend}:total`]: 1,+ [`b:${safeBackend}:${ok ? 'ok' : 'fail'}`]: 1,+ };+ if (ok && typeof latencyMs === 'number' && latencyMs >= 0) {+ fields.lat_sum = Math.round(latencyMs);+ fields.lat_n = 1;+ }+ if (cacheHit) fields.cache_hit = 1;++ try {+ const pipe = redis.pipeline();+ for (const [field, by] of Object.entries(fields)) pipe.hincrby(key, field, by);+ pipe.expire(key, BUCKET_TTL_S);+ await pipe.exec();+ } catch {+ /* fail open — losing a counter never blocks a generation */+ }+}++// Aggregate the last `windowHours` hourly buckets into a single rollup for the+// health endpoint. Returns null when Redis is absent (the dashboard then simply+// omits the metrics block rather than showing zeros that look like an outage).+export async function readGenerationMetrics({ windowHours = DEFAULT_WINDOW_HOURS } = {}) {+ if (!redis) return null;+ const hours = Math.min(Math.max(Number(windowHours) || DEFAULT_WINDOW_HOURS, 1), MAX_WINDOW_HOURS);+ const now = hourBucket();+ const keys = [];+ for (let i = 0; i < hours; i += 1) keys.push(`${METRICS_PREFIX}${now - i}`);++ let buckets;+ try {+ buckets = await Promise.all(keys.map((k) => redis.hgetall(k).catch(() => null)));+ } catch {+ return null;+ }++ const agg = { total: 0, ok: 0, fail: 0, cache_hit: 0, lat_sum: 0, lat_n: 0, by_backend: {} };+ for (const bucket of buckets) {+ if (!bucket) continue;+ for (const [field, rawValue] of Object.entries(bucket)) {+ const value = Number(rawValue) || 0;+ if (field === 'total') agg.total += value;+ else if (field === 'ok') agg.ok += value;+ else if (field === 'fail') agg.fail += value;+ else if (field === 'cache_hit') agg.cache_hit += value;+ else if (field === 'lat_sum') agg.lat_sum += value;+ else if (field === 'lat_n') agg.lat_n += value;+ else if (field.startsWith('b:')) {+ const parts = field.split(':');+ const backend = parts[1];+ const kind = parts[2];+ if (!backend || !['total', 'ok', 'fail'].includes(kind)) continue;+ const slot = (agg.by_backend[backend] ||= { total: 0, ok: 0, fail: 0 });+ slot[kind] += value;+ }+ }+ }++ return {+ window_hours: hours,+ total: agg.total,+ ok: agg.ok,+ fail: agg.fail,+ cache_hits: agg.cache_hit,+ success_rate: agg.total > 0 ? Number((agg.ok / agg.total).toFixed(4)) : null,+ avg_latency_ms: agg.lat_n > 0 ? Math.round(agg.lat_sum / agg.lat_n) : null,+ by_backend: agg.by_backend,+ };+}diff --git a/api/_lib/forge-store.js b/api/_lib/forge-store.jsindex d74e844b0..f6d100498 100644--- a/api/_lib/forge-store.js+++ b/api/_lib/forge-store.js@@ -17,6 +17,7 @@ import { createHash } from 'node:crypto';import { randomUUID } from 'node:crypto';import { sql } from './db.js';import { putObject, publicUrl } from './r2.js';+import { recordGenerationEvent } from './forge-events.js';// Stable, non-secret salt so a leaked DB row can't be trivially reversed to the// raw browser-local id. The id is anonymous to begin with; this is hygiene, not@@ -97,6 +98,9 @@ export async function createCreation({${typeof multiview === 'boolean' ? multiview : null}, ${backend ?? null},${tier ?? null}, ${path ?? null}, 'generating', 'generated', ${category})`;+ // Funnel start — counts attempts so the health rollup can show how many+ // generations began vs. completed. Best-effort; never blocks the insert.+ await recordGenerationEvent({ phase: 'start', backend, tier, path, source: 'create' });return id;} catch (err) {console.error('[forge-store] createCreation failed:', err?.message);@@ -111,7 +115,8 @@ export async function findByJob({ replicateJobId, clientKey }) {try {const rows = await sql`select id, status, glb_url, glb_key, prompt, preview_image_url,- views_requested, views_used, multiview, backend, tier, path, model_category+ views_requested, views_used, multiview, backend, tier, path, model_category,+ created_atfrom forge_creationswhere replicate_job_id = ${replicateJobId} and client_key = ${clientKey}limit 1@@ -192,6 +197,20 @@ export async function materializeCreation({ replicateJobId, clientKey, glbUrl })updated_at = now()where id = ${existing.id} and client_key = ${clientKey}`;+ // Terminal success — the one universal completion writer every lane (free+ // HF, async Replicate poll, BYOK) flows through, so it's where the rolling+ // success/latency counters are recorded. Latency is wall-clock from the row's+ // created_at; null if the timestamp is unreadable rather than a bogus number.+ const startedAt = existing.created_at ? Date.parse(existing.created_at) : NaN;+ const latencyMs = Number.isFinite(startedAt) ? Date.now() - startedAt : null;+ await recordGenerationEvent({+ phase: 'done',+ backend: existing.backend,+ tier: existing.tier,+ path: existing.path,+ latencyMs,+ source: 'materialize',+ });return { id: existing.id, glbUrl: glb.publicUrl, previewImageUrl: preview.url };} catch (err) {console.error('[forge-store] materializeCreation failed:', err?.message);diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.jsindex 2e884d78f..10fe9f7e5 100644--- a/api/_lib/rate-limit.js+++ b/api/_lib/rate-limit.js@@ -11,6 +11,15 @@ const redis = getRedis();const IS_PRODUCTION = env.NODE_ENV === 'production' || env.VERCEL_ENV === 'production';const REDIS_CONFIGURED = Boolean(redis);+// Platform-wide hourly ceiling on PLATFORM-keyed paid 3D generations (the shared+// Replicate / self-host GPU budget). This is a circuit breaker, NOT a per-user+// limit: it stops the failure mode where an influx — or distributed abuse — sends+// many callers who each stay under their own 30/h cap but collectively drain real+// spend. Tunable via env without a code change; the default is generous enough+// that only a genuine surge or attack trips it, and when it does the free NVIDIA /+// HuggingFace lanes stay open, so paid capacity degrades instead of dead-ending.+const FORGE_PAID_GLOBAL_HOURLY = Math.max(1, Number(process.env.FORGE_PAID_GLOBAL_HOURLY) || 600);+// Loud, one-time startup warning when Redis is unconfigured in production. Without// Redis every limiter falls back to a PER-INSTANCE in-memory map, which is// effectively unbounded across serverless fan-out — fine for dev, dangerous for@@ -299,6 +308,17 @@ export const limits = {// hourly ceiling per principal. Status polling is cheap and frequent.mcp3dGenerate: (key) =>getLimiter('mcp3d:generate', { limit: 30, window: '1 h', critical: true }).limit(key),+ // Global circuit breaker on platform-keyed paid generation — the shared+ // Replicate/self-host budget. Keyed by 'global' (mirrors chatHostKeyGlobal /+ // x402PayGlobal): stops many accounts, each under their own mcp3dGenerate cap,+ // from collectively draining spend during an influx. Critical → fails closed in+ // prod without Redis, like the per-user paid bucket it backstops.+ mcp3dGenerateGlobal: () =>+ getLimiter('mcp3d:generate:global', {+ limit: FORGE_PAID_GLOBAL_HOURLY,+ window: '1 h',+ critical: true,+ }).limit('global'),// Free generation lane (NVIDIA NIM TRELLIS draft). No Replicate/vendor spend,// so it gets a much higher per-principal ceiling than the paid bucket and is// NON-critical: a Redis outage must never deny a zero-cost generation (faildiff --git a/api/_lib/x402-paid-endpoint.js b/api/_lib/x402-paid-endpoint.jsindex 9b232273a..583b4146e 100644--- a/api/_lib/x402-paid-endpoint.js+++ b/api/_lib/x402-paid-endpoint.js@@ -319,6 +319,24 @@ export function paidEndpoint(spec) {return error(res, 405, 'method_not_allowed', `use ${httpMethod}`);}+ const ip = clientIp(req);+ // Abuse guard, tier 1 — anonymous-flood protection on the discovery/probe+ // path. Authenticated and subscription callers (Bearer / SIWX / API key)+ // have their own access-control gating downstream, so they bypass this+ // per-IP cap; only unauthenticated traffic is bounded here. Non-critical:+ // a Redis outage must never block price discovery or a legitimate paid+ // retry — the fail-closed facilitator guard (tier 2) runs further down.+ const isAuthenticatedCaller =+ !!req.headers?.authorization ||+ !!req.headers?.['sign-in-with-x'] ||+ !!req.headers?.['x-api-key'];+ if (!isAuthenticatedCaller) {+ const probe = await limits.x402ProbeIp(ip);+ if (!probe.success) {+ return rateLimited(res, probe, 'too many requests — slow down and retry shortly');+ }+ }+const resourceUrl =typeof resourceUrlBuilder === 'function'? resourceUrlBuilder(req)@@ -660,6 +678,23 @@ export function paidEndpoint(spec) {if (!paymentHeader) return send402(res, challenge);+ // Abuse guard, tier 2 — only requests carrying an X-PAYMENT header reach the+ // facilitator /verify round-trip below, so this is where a junk-payment flood+ // would amplify one cheap inbound request into one outbound facilitator call+ // at our expense. Cap per-IP and globally; both CRITICAL (fail closed in+ // prod) — during a Redis outage, rejecting a payment retry (the buyer keeps+ // their funds and retries) beats letting the amplification run unbounded. The+ // global ceiling is a runaway/DDoS circuit breaker, tunable via+ // X402_VERIFY_GLOBAL_PER_HOUR as legitimate volume grows.+ const verifyIpLimit = await limits.x402VerifyIp(ip);+ if (!verifyIpLimit.success) {+ return rateLimited(res, verifyIpLimit, 'too many payment attempts — retry shortly');+ }+ const verifyGlobalLimit = await limits.x402VerifyGlobal();+ if (!verifyGlobalLimit.success) {+ return rateLimited(res, verifyGlobalLimit, 'payment system at capacity — retry shortly');+ }+// USE-15: required-mode rejects the call before we burn an RPC round-trip.try {enforceRequired({ paymentHeader, required: pidRequired });diff --git a/api/forge.js b/api/forge.jsindex 64b2c846f..3b58113be 100644--- a/api/forge.js+++ b/api/forge.js@@ -533,7 +533,8 @@ async function startJob(req, res) {}}- const isFreeLane = BACKENDS[backendId]?.free === true;+ const backendMeta = BACKENDS[backendId];+ const isFreeLane = backendMeta?.free === true;if (!isInternalSeedRequest(req)) {const rl = isFreeLane? await limits.mcp3dGenerateFreeTiered(ip, freeLaneMultiplier(req, body))@@ -541,6 +542,23 @@ async function startJob(req, res) {if (!rl.success) {return rateLimited(res, rl, 'Generation limit reached. Try again shortly.');}+ // Cost circuit breaker: a platform-wide hourly ceiling on PLATFORM-keyed paid+ // generation (the shared Replicate/self-host budget), on top of the per-IP cap+ // above. It stops the influx/abuse failure mode where many callers each stay+ // under their own cap but collectively drain spend. BYOK lanes spend the+ // caller's own key, so the platform-budget ceiling must never throttle them.+ // When it trips the free NVIDIA / HuggingFace lanes stay open — paid capacity+ // degrades, it never dead-ends.+ if (!isFreeLane && !backendMeta?.byok) {+ const globalRl = await limits.mcp3dGenerateGlobal();+ if (!globalRl.success) {+ return rateLimited(+ res,+ globalRl,+ 'Paid 3D generation is at capacity right now — switch to a free engine (NVIDIA or Hugging Face), or try again shortly.',+ );+ }+ }}if (isImageMode) {diff --git a/data/changelog.json b/data/changelog.jsonindex ac66224ef..bf5e496eb 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,26 @@{"$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": "Forge scales further — duplicate generations collapse, free lane protected, prices shown up front",+ "summary": "More headroom for the influx. Forge now recognizes when the same prompt or photo set is already generating and quietly hands everyone the same result instead of paying to build it twice — so a viral prompt or a double-click no longer multiplies cost or wait. The free Hugging Face engine is now capped to a safe number of simultaneous jobs so a rush can't tie up the servers and stall everyone; over the cap, your generation cleanly falls back to another engine instead of hanging. The composer now shows the real price before you generate — 'Free' for Draft and Standard, the exact dollar amount (or 'Free, you hold $THREE') for High, and 'billed to your own key' for bring-your-own-key engines — so there are no surprises. Finally, the 3D viewer shows a loading shimmer instead of a dark void while your model paints in.",+ "tags": [+ "improvement",+ "infra"+ ],+ "link": "/forge"+ },+ {+ "date": "2026-06-21",+ "title": "Forge hardened for a traffic surge — faster loads, protected free lanes",+ "summary": "We scaled Forge for the influx of new users. The engine catalog and live health status now serve from the edge cache, so the page loads instantly even under heavy traffic instead of recomputing on every visit. We also added a platform-wide safety valve on paid generation: if demand ever spikes past the shared paid budget, the free engines (NVIDIA and Hugging Face) stay fully open and you get a clear 'try a free engine' message instead of a hard failure — your own bring-your-own-key engines are never affected. Net result: Forge stays fast and available as we grow, and free 3D generation never gets crowded out.",+ "tags": [+ "infra",+ "improvement"+ ],+ "link": "/forge"+ },{"date": "2026-06-21","title": "Grind an agent's vanity wallet right on its page — with your CPU cores",diff --git a/pages/forge.html b/pages/forge.htmlindex 688b0ade8..abb64d462 100644--- a/pages/forge.html+++ b/pages/forge.html@@ -745,6 +745,14 @@color: var(--ink);font-weight: 600;}+ .fq-estimate .est-free {+ color: var(--success);+ font-weight: 700;+ }+ .fq-estimate .est-cost {+ color: var(--ink);+ font-weight: 700;+ }/* Mode switch — now lives inside .composer as the first element */.mode-switch-wrap {@@ -1462,6 +1470,58 @@opacity: 0;pointer-events: none;}+ /* Load skeleton — covers the dark void between a result being revealed and+ the GLB actually painting. Shown while .is-loading is set, removed on the+ model-viewer 'load' event (or on load error, which has its own panel). */+ .viewer-shell .viewer-skeleton {+ display: none;+ position: absolute;+ inset: 0;+ z-index: 3;+ align-items: center;+ justify-content: center;+ overflow: hidden;+ background: radial-gradient(120% 120% at 50% 0%, #1a1612 0%, #0b0a09 70%);+ }+ html[data-theme='light'] .viewer-shell .viewer-skeleton {+ background: radial-gradient(120% 120% at 50% 0%, #f3eee9 0%, #e7e2dc 70%);+ }+ .viewer-shell.is-loading .viewer-skeleton {+ display: flex;+ }+ .viewer-shell.is-loading.has-load-error .viewer-skeleton {+ display: none;+ }+ .viewer-skeleton-sheen {+ position: absolute;+ inset: 0;+ background: linear-gradient(+ 105deg,+ transparent 30%,+ color-mix(in srgb, var(--accent) 12%, transparent) 50%,+ transparent 70%+ );+ transform: translateX(-100%);+ animation: viewer-skeleton-sweep 1.6s ease-in-out infinite;+ }+ .viewer-skeleton-label {+ position: relative;+ z-index: 1;+ font-family: var(--font-mono);+ font-size: var(--text-xs);+ color: var(--ink-dim);+ letter-spacing: 0.04em;+ }+ @keyframes viewer-skeleton-sweep {+ to {+ transform: translateX(100%);+ }+ }+ @media (prefers-reduced-motion: reduce) {+ .viewer-skeleton-sheen {+ animation: none;+ }+ }.viewer-load-error-icon {font-size: 2rem;opacity: 0.5;@@ -2839,6 +2899,10 @@crossorigin="anonymous"alt="Generated 3D model"></model-viewer>+ <div class="viewer-skeleton" id="viewer-skeleton" aria-hidden="true">+ <span class="viewer-skeleton-sheen"></span>+ <span class="viewer-skeleton-label">Loading model…</span>+ </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>diff --git a/public/changelog.json b/public/changelog.jsonindex 9cf9aabf6..7cca71d46 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-21T05:13:39.232Z",+ "generated_at": "2026-06-21T05:23:11.939Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -37,6 +37,28 @@"feature"]},+ {+ "date": "2026-06-21",+ "type": "update",+ "title": "Forge hardened for a traffic surge — faster loads, protected free lanes",+ "summary": "We scaled Forge for the influx of new users. The engine catalog and live health status now serve from the edge cache, so the page loads instantly even under heavy traffic instead of recomputing on every visit. We also added a platform-wide safety valve on paid generation: if demand ever spikes past the shared paid budget, the free engines (NVIDIA and Hugging Face) stay fully open and you get a clear 'try a free engine' message instead of a hard failure — your own bring-your-own-key engines are never affected. Net result: Forge stays fast and available as we grow, and free 3D generation never gets crowded out.",+ "link": "/forge",+ "tags": [+ "infra",+ "improvement"+ ]+ },+ {+ "date": "2026-06-21",+ "type": "update",+ "title": "Forge scales further — duplicate generations collapse, free lane protected, prices shown up front",+ "summary": "More headroom for the influx. Forge now recognizes when the same prompt or photo set is already generating and quietly hands everyone the same result instead of paying to build it twice — so a viral prompt or a double-click no longer multiplies cost or wait. The free Hugging Face engine is now capped to a safe number of simultaneous jobs so a rush can't tie up the servers and stall everyone; over the cap, your generation cleanly falls back to another engine instead of hanging. The composer now shows the real price before you generate — 'Free' for Draft and Standard, the exact dollar amount (or 'Free, you hold $THREE') for High, and 'billed to your own key' for bring-your-own-key engines — so there are no surprises. Finally, the 3D viewer shows a loading shimmer instead of a dark void while your model paints in.",+ "link": "/forge",+ "tags": [+ "improvement",+ "infra"+ ]+ },{"date": "2026-06-21","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex 0c17cf0df..4fa295f2e 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -30,6 +30,22 @@<category>feature</category><description>The $THREE page now lets you set a spending allowance: approve a cap once, and paid actions across the platform — forge, skills, names, cosmetics — debit it automatically without asking you to sign every time. It's non-custodial and built on Solana's native, audited Subscriptions & Allowances program: your tokens stay in your own wallet until a charge pulls them, never more than the cap you set, and you can let it expire or revoke it anytime. Set a cap, top it up, or leave it off and keep signing each payment — your choice.</description></item>+ <item>+ <title>Forge hardened for a traffic surge — faster loads, protected free lanes</title>+ <link>https://three.ws/forge</link>+ <guid isPermaLink="false">2026-06-21:Forge hardened for a traffic surge — faster loads, protected free lanes</guid>+ <pubDate>Sun, 21 Jun 2026 12:00:00 GMT</pubDate>+ <category>infra</category>+ <description>We scaled Forge for the influx of new users. The engine catalog and live health status now serve from the edge cache, so the page loads instantly even under heavy traffic instead of recomputing on every visit. We also added a platform-wide safety valve on paid generation: if demand ever spikes past the shared paid budget, the free engines (NVIDIA and Hugging Face) stay fully open and you get a clear 'try a free engine' message instead of a hard failure — your own bring-your-own-key engines are never affected. Net result: Forge stays fast and available as we grow, and free 3D generation never gets crowded out.</description>+ </item>+ <item>+ <title>Forge scales further — duplicate generations collapse, free lane protected, prices shown up front</title>+ <link>https://three.ws/forge</link>+ <guid isPermaLink="false">2026-06-21:Forge scales further — duplicate generations collapse, free lane protected, prices shown up front</guid>+ <pubDate>Sun, 21 Jun 2026 12:00:00 GMT</pubDate>+ <category>improvement</category>+ <description>More headroom for the influx. Forge now recognizes when the same prompt or photo set is already generating and quietly hands everyone the same result instead of paying to build it twice — so a viral prompt or a double-click no longer multiplies cost or wait. The free Hugging Face engine is now capped to a safe number of simultaneous jobs so a rush can't tie up the servers and stall everyone; over the cap, your generation cleanly falls back to another engine instead of hanging. The composer now shows the real price before you generate — 'Free' for Draft and Standard, the exact dollar amount (or 'Free, you hold $THREE') for High, and 'billed to your own key' for bring-your-own-key engines — so there are no surprises. Finally, the 3D viewer shows a loading shimmer instead of a dark void while your model paints in.</description>+ </item><item><title>forge_avatar — one call turns a prompt into a rigged, animation-ready avatar</title><link>https://three.ws/docs/mcp</link>diff --git a/public/features.json b/public/features.jsonindex 12abfd083..39685d3af 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-21T05:13:39.187Z",+ "generated_at": "2026-06-21T05:23:11.921Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/src/forge.js b/src/forge.jsindex f6bb57871..d5034a2ed 100644--- a/src/forge.js+++ b/src/forge.js@@ -689,6 +689,9 @@ async function reflectHighAccess(tierId, { silent = false } = {}) {applyHighGate();// Keep the persistent button pill + note in sync with the fresh verdict.applyHighAffordances(access);+ // Reflect the resolved hold in the cost line too — High flips to "Free" for a+ // holder without a reload.+ updateEstimate();if (access.eligible) primeTierPass();}@@ -774,6 +777,21 @@ async function updatePerkLine() {}}+// The honest price for the current engine + tier, as a styled segment. The web+// gate charges only High tier (hold $THREE or pay per generation); Draft and+// Standard run free on the platform's rate-limited lanes; BYOK engines bill the+// caller's own provider key. `_highAccess.eligible` reflects a resolved $THREE+// hold, so a holder sees High as already unlocked.+function costSegment(backend, tierMeta) {+ if (backend.byok) return 'billed to your own key';+ if (tierMeta.id === 'high') {+ return _highAccess?.eligible+ ? '<span class="est-free">Free</span> · you hold $THREE'+ : `<span class="est-cost">$${tierMeta.price_usdc}</span> or hold $THREE`;+ }+ return '<span class="est-free">Free</span>';+}+// Render the honest time/cost/poly estimate for the current engine + tier from// the catalog. No fabricated numbers — everything comes from /api/forge?catalog.function updateEstimate() {@@ -790,7 +808,7 @@ function updateEstimate() {// Holder-readable, not pipeline-internal: say how long it usually takes and// what the engine does, in plain words. The mechanism ("builds from a// reference image") replaces jargon like "image-intermediate · fast path".- const parts = [`<strong>${tierMeta.label}</strong>`];+ const parts = [`<strong>${tierMeta.label}</strong>`, costSegment(backend, tierMeta)];if (est?.eta_seconds) parts.push(`usually ~${est.eta_seconds}s`);if (est && est.credits != null) parts.push(`~${est.credits} credits`);if (backend.poly_control) parts.push(`up to ${tierMeta.polycount.toLocaleString()} polygons`);@@ -1540,6 +1558,9 @@ function showResult(glbUrl, label, meta, { autoSaved = false } = {}) {resetCategoryPicker();if (els.categoryPicker) els.categoryPicker.hidden = false;els.viewerShell?.classList.remove('has-load-error');+ // Show the load skeleton over the dark viewport until the GLB paints. The+ // persistent 'load'/'error' listeners below clear it.+ els.viewerShell?.classList.add('is-loading');els.viewer.setAttribute('src', glbUrl);els.viewer.setAttribute('alt', `3D model: ${label}`);lastShownGlb = glbUrl;@@ -2121,7 +2142,14 @@ async function payThenGenerate(pay) {// Wiring ----------------------------------------------------------------------els.viewer.addEventListener('error', () => {- if (els.viewerShell) els.viewerShell.classList.add('has-load-error');+ if (els.viewerShell) {+ els.viewerShell.classList.add('has-load-error');+ els.viewerShell.classList.remove('is-loading');+ }+});+// The GLB finished painting — drop the load skeleton.+els.viewer.addEventListener('load', () => {+ els.viewerShell?.classList.remove('is-loading');});buildSlots();diff --git a/tests/forge-scale.test.js b/tests/forge-scale.test.jsnew file mode 100644index 000000000..a8b10424b--- /dev/null+++ b/tests/forge-scale.test.js@@ -0,0 +1,88 @@+import { describe, it, expect } from 'vitest';++import {+ forgeRequestHash,+ coalesceInFlight,+ registerInFlight,+ acquireBlockingSlot,+ providerSubmitAllowed,+ SCALE_LIMITS,+} from '../api/_lib/forge-scale.js';++// forge-scale provides the /forge pipeline's scaling throttles. Tests run with no+// Upstash Redis configured (the unit-test env), which is exactly the FAIL-OPEN+// contract these primitives promise: every gate must degrade to allow/no-op so+// generation keeps working when the limiter store is absent. We also lock the+// request-fingerprint semantics that in-flight coalescing depends on.++describe('forgeRequestHash', () => {+ it('is deterministic for identical inputs', () => {+ const a = forgeRequestHash({ path: 'image', tier: 'standard', backend: 'trellis', prompt: 'a red car' });+ const b = forgeRequestHash({ path: 'image', tier: 'standard', backend: 'trellis', prompt: 'a red car' });+ expect(a).toBe(b);+ expect(a).toMatch(/^[0-9a-f]{32}$/);+ });++ it('normalizes prompt whitespace and case', () => {+ const a = forgeRequestHash({ path: 'image', tier: 'standard', backend: 'trellis', prompt: 'A Red Car' });+ const b = forgeRequestHash({ path: 'image', tier: 'standard', backend: 'trellis', prompt: ' a red car ' });+ expect(a).toBe(b);+ });++ it('is order-independent across the multi-view image set', () => {+ const front = 'https://x/front.png';+ const back = 'https://x/back.png';+ const a = forgeRequestHash({ path: 'image', tier: 'high', backend: 'meshy', images: [front, back] });+ const b = forgeRequestHash({ path: 'image', tier: 'high', backend: 'meshy', images: [back, front] });+ expect(a).toBe(b);+ });++ it('distinguishes tier, backend, path, prompt, and images', () => {+ const base = { path: 'image', tier: 'standard', backend: 'trellis', prompt: 'cat' };+ const h = forgeRequestHash(base);+ expect(forgeRequestHash({ ...base, tier: 'high' })).not.toBe(h);+ expect(forgeRequestHash({ ...base, backend: 'meshy' })).not.toBe(h);+ expect(forgeRequestHash({ ...base, path: 'geometry' })).not.toBe(h);+ expect(forgeRequestHash({ ...base, prompt: 'dog' })).not.toBe(h);+ expect(forgeRequestHash({ ...base, images: ['https://x/a.png'] })).not.toBe(h);+ });++ it('accepts a tier object or a tier id interchangeably', () => {+ const a = forgeRequestHash({ path: 'image', tier: { id: 'standard' }, backend: 'trellis', prompt: 'cat' });+ const b = forgeRequestHash({ path: 'image', tier: 'standard', backend: 'trellis', prompt: 'cat' });+ expect(a).toBe(b);+ });+});++describe('fail-open behavior without Redis', () => {+ it('coalesceInFlight returns null (always a miss)', async () => {+ expect(await coalesceInFlight('deadbeef')).toBeNull();+ });++ it('registerInFlight is a no-op that never throws', async () => {+ await expect(registerInFlight('deadbeef', 'job-123')).resolves.toBeUndefined();+ });++ it('acquireBlockingSlot grants an unbounded, releasable slot', async () => {+ const slot = await acquireBlockingSlot('hf', { max: 1, ttlMs: 1000 });+ expect(slot.ok).toBe(true);+ // A second acquire still succeeds (no shared store to count against).+ const slot2 = await acquireBlockingSlot('hf', { max: 1, ttlMs: 1000 });+ expect(slot2.ok).toBe(true);+ await expect(slot.release()).resolves.toBeUndefined();+ await expect(slot.release()).resolves.toBeUndefined(); // idempotent+ });++ it('providerSubmitAllowed allows', async () => {+ expect(await providerSubmitAllowed('replicate', { limit: 1, windowS: 10 })).toBe(true);+ });+});++describe('SCALE_LIMITS', () => {+ it('exposes sane positive defaults', () => {+ expect(SCALE_LIMITS.hfConcurrent).toBeGreaterThan(0);+ expect(SCALE_LIMITS.hfSlotTtlMs).toBeGreaterThanOrEqual(300_000);+ expect(SCALE_LIMITS.replicateSubmitLimit).toBeGreaterThan(0);+ expect(SCALE_LIMITS.replicateSubmitWindowS).toBeGreaterThan(0);+ });+});