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.

Forge resilience + MCP/x402 interop hardening

nirholas48623e0046d4
diff --git a/api/_lib/mcp-dispatch.js b/api/_lib/mcp-dispatch.js
index 15a15bb6d..a56e0600e 100644
--- a/api/_lib/mcp-dispatch.js
+++ b/api/_lib/mcp-dispatch.js
@@ -109,7 +109,12 @@ export function makeDispatcher({ serverInfo, instructions, catalog, tools, logNa
const isNotification = id === undefined;
try {
- if (msg.jsonrpc !== '2.0') throw rpcError(-32600, 'invalid Request');
+ // Tolerate an absent `jsonrpc` version — minimal/legacy MCP clients
+ // omit it on discovery calls; auth and pricing still gate every call.
+ // Only reject a version that is present and not "2.0".
+ if (msg.jsonrpc != null && msg.jsonrpc !== '2.0') {
+ throw rpcError(-32600, 'invalid Request');
+ }
const method = msg.method;
if (method === 'initialize') {
diff --git a/api/_lib/zauth.js b/api/_lib/zauth.js
index dd26b67ca..f6000399e 100644
--- a/api/_lib/zauth.js
+++ b/api/_lib/zauth.js
@@ -65,8 +65,12 @@ function trackZauthFetch() {
if (url.includes(ZAUTH_HOST)) {
_inflight.add(promise);
promise.then(
- () => { _inflight.delete(promise); console.log('[zauth] Batch submitted'); },
- (err) => { _inflight.delete(promise); console.error('[zauth] Batch submit failed:', err.message); },
+ () => { _inflight.delete(promise); if (env.ZAUTH_DEBUG === '1') console.log('[zauth] Batch submitted'); },
+ // Telemetry is fire-and-forget: a transient network blip reaching
+ // back.zauthx402.com (or the lambda freezing mid-POST) must never be
+ // logged at error level — it isn't a request failure and was
+ // drowning genuine errors in the function logs. Warn, not error.
+ (err) => { _inflight.delete(promise); console.warn('[zauth] telemetry delivery failed (non-fatal):', err?.message || err); },
);
}
return promise;
diff --git a/api/_mcp/dispatch.js b/api/_mcp/dispatch.js
index ee7e431b8..f41097228 100644
--- a/api/_mcp/dispatch.js
+++ b/api/_mcp/dispatch.js
@@ -33,7 +33,14 @@ export async function dispatch(msg, auth, req) {
const isNotification = id === undefined;
try {
- if (msg.jsonrpc !== '2.0') throw rpcError(-32600, 'invalid Request');
+ // Spec-compliant clients send `jsonrpc: "2.0"`, but minimal/legacy MCP
+ // clients routinely omit it on discovery calls (tools/list, initialize).
+ // Rejecting those with -32600 broke interop and spammed the logs for no
+ // security gain — auth and pricing still gate every call. Tolerate an
+ // absent version; only reject a version that is present and wrong.
+ if (msg.jsonrpc != null && msg.jsonrpc !== '2.0') {
+ throw rpcError(-32600, 'invalid Request');
+ }
const method = msg.method;
if (method === 'initialize') return ok(id, await onInitialize(msg.params, auth));
diff --git a/api/_mcp3d/vertex-imagen.js b/api/_mcp3d/vertex-imagen.js
index 7bec96c7d..19967be08 100644
--- a/api/_mcp3d/vertex-imagen.js
+++ b/api/_mcp3d/vertex-imagen.js
@@ -89,12 +89,50 @@ async function getAccessToken() {
// or base64-encoded. Accept every common mangling; reject with a designed
// `unconfigured` error (instead of a raw JSON.parse crash) so callers can
// branch to a fallback provider.
+// Escape raw control characters (newline, carriage return, tab) that appear
+// *inside* JSON string literals, leaving structural whitespace and already-
+// escaped sequences untouched. Walks the string tracking in-string state so it
+// never mangles the JSON between tokens. Lets a multi-line key-file paste parse.
+function escapeJsonControlChars(s) {
+ let out = '';
+ let inString = false;
+ let escaped = false;
+ for (let i = 0; i < s.length; i++) {
+ const ch = s[i];
+ if (escaped) {
+ out += ch;
+ escaped = false;
+ continue;
+ }
+ if (ch === '\\') {
+ out += ch;
+ escaped = true;
+ continue;
+ }
+ if (ch === '"') {
+ inString = !inString;
+ out += ch;
+ continue;
+ }
+ if (inString && ch === '\n') out += '\\n';
+ else if (inString && ch === '\r') out += '\\r';
+ else if (inString && ch === '\t') out += '\\t';
+ else out += ch;
+ }
+ return out;
+}
+
function parseServiceAccount(raw) {
let v = raw.trim();
if ((v.startsWith('"') && v.endsWith('"')) || (v.startsWith("'") && v.endsWith("'"))) {
v = v.slice(1, -1).trim();
}
const candidates = [v, v.replace(/\\"/g, '"')];
+ // A multi-line paste of the raw key file leaves literal newlines/tabs/CRs
+ // *inside* the private_key string — valid in a file, but `JSON.parse` rejects
+ // raw control characters in a string literal ("Bad control character"). Add a
+ // candidate that escapes only those control chars so the paste parses cleanly.
+ candidates.push(escapeJsonControlChars(v), escapeJsonControlChars(v.replace(/\\"/g, '"')));
if (/^[A-Za-z0-9+/=\s]+$/.test(v)) {
try {
candidates.push(Buffer.from(v, 'base64').toString('utf8'));
diff --git a/api/forge.js b/api/forge.js
index 955c827ef..4effb5304 100644
--- a/api/forge.js
+++ b/api/forge.js
@@ -146,6 +146,104 @@ function unconfigured(res) {
});
}
+// Free NVIDIA NIM TRELLIS text→3D lane, extracted so it serves two callers:
+// 1. the draft default (backendId === 'nvidia'), and
+// 2. the never-dead-end fallback the paid image-intermediate TRELLIS lane
+// degrades to when Replicate is unreachable / over-quota (HTTP 429/5xx).
+// Returns true once it has written a 200 response, or false when the lane is
+// itself unavailable (so the caller can fall through to the next lane). Prompt
+// is required — NVCF is text-only; photo submissions never reach here.
+async function runNvidiaTextLane({ req, res, ip, prompt, aspect, tier, path }) {
+ let submitted;
+ try {
+ const nv = await loadNvidiaProvider();
+ submitted = await nv.textTo3d({ prompt, tier });
+ } catch (err) {
+ console.warn(`[forge] free NVIDIA NIM lane unavailable: ${err?.message || err}`);
+ return false;
+ }
+
+ const backendId = 'nvidia';
+ const provenance = {
+ mode: 'text_to_3d',
+ path,
+ tier: tier.id,
+ backend: backendId,
+ prompt: prompt || null,
+ preview_image_url: null,
+ reference_image_urls: [],
+ eta_seconds: estimateEtaSeconds({ backendId, tier }),
+ estimated_credits: estimateCredits({ backendId, path, tier }),
+ };
+
+ const clientKey = clientKeyFrom(req);
+ // Synchronous completion: NVCF already persisted the GLB to R2. Record a
+ // finished creation (a synthetic handle lets materialize copy + flip it to
+ // done) and return it so the client skips polling entirely.
+ if (!submitted.taskId && submitted.resultGlbUrl) {
+ const syntheticJob = randomUUID().replace(/-/g, '');
+ const creationId = await createCreation({
+ clientKey,
+ ipHash: hashIp(ip),
+ prompt,
+ aspect,
+ previewImageUrl: null,
+ replicateJobId: syntheticJob,
+ textToImageModel: null,
+ viewsRequested: 0,
+ viewsUsed: null,
+ multiview: false,
+ backend: backendId,
+ tier: tier.id,
+ path,
+ });
+ const durable = await materializeCreation({
+ replicateJobId: syntheticJob,
+ clientKey,
+ glbUrl: submitted.resultGlbUrl,
+ });
+ json(res, 200, {
+ job_id: null,
+ creation_id: durable?.id ?? creationId,
+ status: 'done',
+ glb_url: durable?.glbUrl ?? submitted.resultGlbUrl,
+ durable: Boolean(durable),
+ ...provenance,
+ });
+ return true;
+ }
+
+ // Async: wrap the NVCF request id in a forge token so the poll routes back to
+ // the NIM provider, and store it as the job handle.
+ const token = encodeJobToken({
+ provider: 'nvidia',
+ kind: submitted.kind,
+ taskId: submitted.taskId,
+ });
+ const creationId = await createCreation({
+ clientKey,
+ ipHash: hashIp(ip),
+ prompt,
+ aspect,
+ previewImageUrl: null,
+ replicateJobId: submitted.taskId,
+ textToImageModel: null,
+ viewsRequested: 0,
+ viewsUsed: null,
+ multiview: false,
+ backend: backendId,
+ tier: tier.id,
+ path,
+ });
+ json(res, 200, {
+ job_id: token,
+ creation_id: creationId,
+ status: 'queued',
+ ...provenance,
+ });
+ return true;
+}
+
async function startJob(req, res) {
const ip = clientIp(req);
const body = await readJson(req, 8_000).catch(() => null);
@@ -169,6 +267,11 @@ async function startJob(req, res) {
let path = parsePath(body);
const tier = resolveTier(parseTier(body));
let backendId = resolveBackendId({ path, tier, backend: body?.backend, userImages: isImageMode });
+ // Tracks whether the free NVIDIA NIM lane has already been attempted this
+ // request, so the paid-lane fallback below never retries a lane that just
+ // failed (draft already tries nvidia first; standard/high reach it only as a
+ // last-resort fallback when Replicate is down).
+ let nvidiaTried = false;
// The geometry path is BYOK-only — no free model does native text→geometry.
// So when the caller didn't explicitly pick a backend and has no key for the
@@ -496,109 +599,20 @@ async function startJob(req, res) {
// intermediate view) and needs no BYOK key. It serves prompt submissions
// on the image path as the free draft default; photo submissions never
// resolve here (hosted preview is text-only — see the provider header).
- // NVCF normally returns a poll handle; on the rare synchronous completion
- // the GLB is already in R2.
+ // The free NVIDIA NIM lane is a flaky synchronous upstream — NVCF can be
+ // unreachable, accept the job but drop the request id, or finish with no
+ // artifact, and a missing module/key throws on load. Per the free-first
+ // "AI must never fail" policy none of these may surface as a dead 502: a
+ // failure here transparently degrades to the platform image-intermediate
+ // TRELLIS lane so the zero-setup free default still returns a model. Only
+ // the unit cost changes, and only when NIM is down. Provenance reports the
+ // lane that actually ran (trellis below), so the downgrade is never silent.
if (backendId === 'nvidia') {
- // The free NVIDIA NIM lane is a flaky synchronous upstream — NVCF can be
- // unreachable, accept the job but drop the request id, or finish with no
- // artifact (each throws status 502 in api/_providers/nvidia.js), and a
- // missing module/key throws on load. Per the free-first "AI must never
- // fail" policy none of these may surface as a dead 502: any failure here
- // transparently degrades to the platform image-intermediate TRELLIS lane
- // so the zero-setup free default still returns a model. Only the unit
- // cost changes, and only when NIM is down. Provenance reports the lane
- // that actually ran (trellis below), so the downgrade is never silent.
- let submitted = null;
- try {
- const nv = await loadNvidiaProvider();
- submitted = await nv.textTo3d({ prompt, tier });
- } catch (err) {
- console.warn(
- `[forge] free NVIDIA NIM lane unavailable, falling back to TRELLIS: ${err?.message || err}`,
- );
- backendId = 'trellis';
- }
-
- if (submitted) {
- const provenance = {
- mode: 'text_to_3d',
- path,
- tier: tier.id,
- backend: backendId,
- prompt: prompt || null,
- preview_image_url: null,
- reference_image_urls: [],
- eta_seconds: estimateEtaSeconds({ backendId, tier }),
- estimated_credits: estimateCredits({ backendId, path, tier }),
- };
-
- const clientKey = clientKeyFrom(req);
- // Synchronous completion: NVCF already persisted the GLB to R2. Record a
- // finished creation (a synthetic handle lets materialize copy + flip it
- // to done) and return it so the client skips polling entirely.
- if (!submitted.taskId && submitted.resultGlbUrl) {
- const syntheticJob = randomUUID().replace(/-/g, '');
- const creationId = await createCreation({
- clientKey,
- ipHash: hashIp(ip),
- prompt,
- aspect,
- previewImageUrl: null,
- replicateJobId: syntheticJob,
- textToImageModel: null,
- viewsRequested: 0,
- viewsUsed: null,
- multiview: false,
- backend: backendId,
- tier: tier.id,
- path,
- });
- const durable = await materializeCreation({
- replicateJobId: syntheticJob,
- clientKey,
- glbUrl: submitted.resultGlbUrl,
- });
- return json(res, 200, {
- job_id: null,
- creation_id: durable?.id ?? creationId,
- status: 'done',
- glb_url: durable?.glbUrl ?? submitted.resultGlbUrl,
- durable: Boolean(durable),
- ...provenance,
- });
- }
-
- // Async: wrap the NVCF request id in a forge token so the poll routes
- // back to the NIM provider, and store it as the job handle.
- const token = encodeJobToken({
- provider: 'nvidia',
- kind: submitted.kind,
- taskId: submitted.taskId,
- });
- const creationId = await createCreation({
- clientKey,
- ipHash: hashIp(ip),
- prompt,
- aspect,
- previewImageUrl: null,
- replicateJobId: submitted.taskId,
- textToImageModel: null,
- viewsRequested: 0,
- viewsUsed: null,
- multiview: false,
- backend: backendId,
- tier: tier.id,
- path,
- });
- return json(res, 200, {
- job_id: token,
- creation_id: creationId,
- status: 'queued',
- ...provenance,
- });
- }
- // nvidia failed → backendId is now 'trellis'; fall through to the
- // image-intermediate path below, which serves the same free draft prompt.
+ nvidiaTried = true;
+ if (await runNvidiaTextLane({ req, res, ip, prompt, aspect, tier, path })) return;
+ // nvidia failed → fall through to the image-intermediate TRELLIS path
+ // below, which serves the same free draft prompt on Replicate.
+ backendId = 'trellis';
}
// ── Image-intermediate path (TRELLIS default, or Hunyuan3D self-host) ────
@@ -744,6 +758,33 @@ async function startJob(req, res) {
message: err.message || 'The provider account is out of credits.',
});
}
+ // Last-resort free fallback: when the paid image-intermediate TRELLIS lane
+ // (Replicate) is throttled, over-quota, or unreachable, a text prompt must
+ // never dead-end — degrade to the free NVIDIA NIM lane so the default
+ // "type a prompt → get a model" flow always returns something. Honors the
+ // free-first "AI must never fail" policy; provenance reports backend:nvidia
+ // so the downgrade is visible, not silent. Image uploads have no free
+ // reconstruct fallback (NVCF is text-only), so they fall through to the
+ // designed states below. `nvidiaTried` guards against re-running a lane that
+ // already failed this request (the draft nvidia→trellis→nvidia loop).
+ const upstreamUnavailable =
+ err?.code === 'rate_limited' ||
+ err?.providerStatus === 429 ||
+ err?.code === 'provider_error' ||
+ err?.code === 'provider_unreachable' ||
+ (typeof err?.providerStatus === 'number' && err.providerStatus >= 500);
+ if (upstreamUnavailable && !isImageMode && !nvidiaTried && prompt) {
+ nvidiaTried = true;
+ console.warn(
+ `[forge] paid TRELLIS lane unavailable (${err?.providerStatus || err?.code}); degrading text→3D to free NVIDIA NIM`,
+ );
+ try {
+ if (await runNvidiaTextLane({ req, res, ip, prompt, aspect, tier, path })) return;
+ } catch (fallbackErr) {
+ console.warn(`[forge] NVIDIA NIM fallback also failed: ${fallbackErr?.message || fallbackErr}`);
+ }
+ }
+
// Upstream throttling is a transient 429, not a server fault — return it as
// such with a retry hint so the page can show a "busy, try again" state.
if (err?.code === 'rate_limited' || err?.providerStatus === 429) {
diff --git a/pages/home.html b/pages/home.html
index e19ad9e0a..ea6d0050e 100644
--- a/pages/home.html
+++ b/pages/home.html
@@ -3086,6 +3086,14 @@
mv.setAttribute('exposure', '0.92');
mv.setAttribute('environment-image', 'neutral');
mv.setAttribute('camera-controls', '');
+ // Defer the ~1.5MB GLB fetch until the card nears the viewport instead
+ // of pulling every model on first paint — that eager burst was failing
+ // on mobile (aborted loads under memory/network pressure) and flooding
+ // the error reporter. The poster (the lightweight forge preview image)
+ // shows instantly and remains as a graceful fallback if the mesh can't
+ // load, so a card is never blank.
+ mv.setAttribute('loading', 'lazy');
+ if (c.preview_image_url) mv.setAttribute('poster', c.preview_image_url);
mv.setAttribute('aria-label', c.prompt || 'Forged 3D model');
mv.style.cssText = 'width:100%;height:100%;--poster-color:transparent;background:transparent;';
wrap.appendChild(mv);
diff --git a/public/error-reporter.js b/public/error-reporter.js
index 628d9de5a..7c375f86a 100644
--- a/public/error-reporter.js
+++ b/public/error-reporter.js
@@ -175,13 +175,27 @@
) {
return true;
}
- // A failed service-worker *registration* ("Script …/sw.js load failed") is
- // a transient network/iOS-Safari hiccup; VitePWA's autoUpdate re-registers
- // on the next visit, so it self-heals — noise, not an actionable fault.
- if (report.message && /sw\.js\b[^]*load failed|load failed[^]*\bsw\.js\b/i.test(report.message)) {
+ // A failed service-worker *registration* is a transient network/iOS-Safari
+ // hiccup; VitePWA's autoUpdate re-registers on the next visit, so it
+ // self-heals — noise, not an actionable fault. iOS Safari surfaces it two
+ // ways: "Script …/sw.js load failed" and "Failed to register a
+ // ServiceWorker … An unknown error occurred when fetching the script."
+ if (
+ report.message &&
+ (/sw\.js\b[^]*load failed|load failed[^]*\bsw\.js\b/i.test(report.message) ||
+ /failed to register a serviceworker/i.test(report.message) ||
+ /error occurred when fetching the script/i.test(report.message))
+ ) {
return true;
}
if (report.type === 'resource' && report.source) {
+ // A <model-viewer> whose mesh fails to load (slow/aborted GLB fetch
+ // under mobile memory or network pressure, a lost WebGL context) fires
+ // a resource error but degrades to its poster on its own — the user
+ // still sees the model's image. The object itself is served fine (the
+ // gallery only lists rows with a stored GLB); this is a transient,
+ // self-healing client condition, not a missing asset. Drop the noise.
+ if (report.tag === 'model-viewer') return true;
// Privacy-blocker-killed analytics — expected, not actionable.
if (IGNORED_RESOURCE_SOURCES.test(report.source)) return true;
// Expired signed URLs on third-party user-content — transient by design.
diff --git a/public/x402-pay-core.js b/public/x402-pay-core.js
index a24d51454..eb2c011f5 100644
--- a/public/x402-pay-core.js
+++ b/public/x402-pay-core.js
@@ -180,8 +180,12 @@ export function buildEip3009TypedData({ accept, payerAddress, chainId, nowSecond
from: payerAddress,
to: accept.payTo,
value: accept.amount,
- validAfter,
- validBefore,
+ // CDP facilitator /verify requires the EIP-3009 time bounds as decimal
+ // strings, not JSON numbers — a numeric validAfter/validBefore is
+ // rejected with "'paymentPayload' is invalid". The signature is
+ // unaffected: uint256 0 and "0" encode to the same 32 bytes.
+ validAfter: String(validAfter),
+ validBefore: String(validBefore),
nonce: authNonce,
},
};
diff --git a/public/x402.js b/public/x402.js
index fd220b6b1..01e5bb268 100644
--- a/public/x402.js
+++ b/public/x402.js
@@ -1081,7 +1081,11 @@ class CheckoutModal {
accepted: accept,
payload: {
signature,
- authorization: { from: payerAddress, to: accept.payTo, value: accept.amount, validAfter, validBefore, nonce },
+ // CDP facilitator /verify requires the EIP-3009 time bounds as
+ // decimal strings, not JSON numbers — a numeric validAfter/
+ // validBefore is rejected with "'paymentPayload' is invalid".
+ // The signature is unaffected: uint256 0 and "0" encode identically.
+ authorization: { from: payerAddress, to: accept.payTo, value: accept.amount, validAfter: String(validAfter), validBefore: String(validBefore), nonce },
},
};
const builderCodeBlock = buildBuilderCodeEcho(this.challenge);
diff --git a/tests/api/forge-fallback.test.js b/tests/api/forge-fallback.test.js
new file mode 100644
index 000000000..a6f77ee58
--- /dev/null
+++ b/tests/api/forge-fallback.test.js
@@ -0,0 +1,138 @@
+/**
+ * Resilience tests for the free-first fallback in api/forge.js.
+ *
+ * The default forge flow — type a prompt, Standard tier — routes to the paid
+ * image-intermediate TRELLIS lane on Replicate. When that upstream is throttled
+ * or over-quota (HTTP 429/5xx) a text prompt must NEVER dead-end: it degrades to
+ * the free NVIDIA NIM lane so the user always gets a model. These tests stub the
+ * provider boundaries and assert the degraded request still returns a finished
+ * model with provenance reporting the lane that actually ran (backend:nvidia),
+ * so the downgrade is visible rather than silent.
+ */
+
+import { describe, it, expect, vi, beforeAll } from 'vitest';
+
+beforeAll(() => {
+ Object.assign(process.env, {
+ APP_ORIGIN: 'https://three.ws',
+ REPLICATE_API_TOKEN: 'test-token',
+ NVIDIA_API_KEY: 'test-nvidia-key',
+ });
+});
+
+// Replicate (paid TRELLIS lane) is over-quota — every submit throws a 429 the
+// same way api/_providers/replicate.js does on a non-ok response.
+vi.mock('../../api/_providers/replicate.js', () => ({
+ createRegenProvider: () => ({
+ submit: vi.fn(async () => {
+ throw Object.assign(new Error('replicate returned 429'), {
+ code: 'provider_error',
+ status: 502,
+ providerStatus: 429,
+ });
+ }),
+ }),
+}));
+
+// FLUX text-to-image (the standard-tier intermediate view) succeeds — the
+// failure under test is the reconstruction submit, not image synthesis.
+vi.mock('../../api/_mcp3d/text-to-image.js', () => ({
+ textToImage: vi.fn(async () => ({ imageUrl: 'https://cdn.example/ref.png', model: 'flux' })),
+}));
+
+// Free NVIDIA NIM lane completes synchronously with a durable GLB.
+const nvidiaTextTo3d = vi.fn(async () => ({ taskId: null, resultGlbUrl: 'https://cdn.example/free.glb' }));
+vi.mock('../../api/_providers/nvidia.js', () => ({
+ createNvidiaProvider: () => ({ textTo3d: nvidiaTextTo3d }),
+}));
+
+// Store: no real DB. createCreation returns an id; materialize echoes a durable url.
+vi.mock('../../api/_lib/forge-store.js', () => ({
+ hashClient: (v) => `client:${v || 'anon'}`,
+ hashIp: (v) => `ip:${v}`,
+ createCreation: vi.fn(async () => 'creation-1'),
+ materializeCreation: vi.fn(async ({ glbUrl }) => ({ id: 'creation-1', glbUrl })),
+ markFailed: vi.fn(async () => {}),
+ findByJob: vi.fn(async () => null),
+}));
+
+// Vision pre-check is a no-op pass (irrelevant to text→3D anyway).
+vi.mock('../../api/_lib/forge-image-validate.js', () => ({
+ validateForgeImage: vi.fn(async () => ({ ok: true })),
+}));
+
+// Rate limiter: deterministic success so the lane logic — not the limiter — is
+// what the test exercises.
+vi.mock('../../api/_lib/rate-limit.js', async (importActual) => {
+ const actual = await importActual();
+ return {
+ ...actual,
+ limits: {
+ ...actual.limits,
+ mcp3dGenerate: vi.fn(async () => ({ success: true, reset: Date.now() + 1000 })),
+ mcp3dGenerateFree: vi.fn(async () => ({ success: true, reset: Date.now() + 1000 })),
+ },
+ clientIp: () => '203.0.113.9',
+ };
+});
+
+const { default: handler } = await import('../../api/forge.js');
+
+function makeReq(body) {
+ return {
+ method: 'POST',
+ url: '/api/forge',
+ headers: { 'content-type': 'application/json', 'x-forge-client': 'tester' },
+ on(event, cb) {
+ if (event === 'data') cb(Buffer.from(JSON.stringify(body)));
+ if (event === 'end') cb();
+ },
+ };
+}
+
+function makeRes() {
+ return {
+ statusCode: 200,
+ headers: {},
+ body: null,
+ setHeader(name, value) {
+ this.headers[String(name).toLowerCase()] = value;
+ },
+ end(body) {
+ this.body = body ? JSON.parse(body) : null;
+ },
+ };
+}
+
+describe('forge free-first fallback when the paid lane is over-quota', () => {
+ it('degrades a Standard text prompt to the free NVIDIA lane instead of 429ing', async () => {
+ const req = makeReq({ prompt: 'a red ceramic coffee mug', tier: 'standard', path: 'image' });
+ const res = makeRes();
+ await handler(req, res);
+
+ expect(res.statusCode).toBe(200);
+ expect(res.body.status).toBe('done');
+ expect(res.body.backend).toBe('nvidia');
+ expect(res.body.glb_url).toBe('https://cdn.example/free.glb');
+ expect(nvidiaTextTo3d).toHaveBeenCalled();
+ });
+
+ it('still surfaces a busy state for an image upload (no free reconstruct fallback)', async () => {
+ nvidiaTextTo3d.mockClear();
+ const req = makeReq({
+ image_urls: ['https://cdn.example/photo.png'],
+ prompt: 'a mug',
+ tier: 'standard',
+ path: 'image',
+ skip_validation: true,
+ });
+ const res = makeRes();
+ await handler(req, res);
+
+ // Image→3D has no free fallback (NVCF is text-only), so it does NOT silently
+ // produce an unrelated prompt-based model — it returns the honest busy state.
+ expect(res.statusCode).toBe(429);
+ expect(res.body.error).toBe('rate_limited');
+ expect(nvidiaTextTo3d).not.toHaveBeenCalled();
+ });
+});