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.

x402 client, Replicate and forge tests, and changelog updates

nirholasbfd8ac95770a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8ee361fd1..30675c6b4 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -35,13 +35,14 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **Creator revenue splits — earn USDC when your coin's cosmetics sell** — When a player buys a premium avatar cosmetic inside one of your coin's /play worlds, a configurable share of the settled USDC is paid out to your wallet on-chain — no simulated balance, a real Solana transfer. Default split is 50 %; creators can sign a message to adjust their share (up to 90 %). The Monetize dashboard now includes a Creator Earnings panel showing lifetime + 30-day totals, per-cosmetic breakdown, and payout status with on-chain tx links. A new Rarest Fits leaderboard in the shop overlay ranks the scarcest cosmetics, top collectors by rarity-weighted flex score, and top earning creators. (`/play`) `[feature]`
- **Dance floor in /play worlds** — A synchronized dance floor pad now appears in /play worlds, near the coin totem. Step onto the glowing circular stage and a 🪩 Dance button appears in your HUD. Press it to arm — when the server's 4-second beat tick fires, everyone armed on the floor crossfades to the same dance clip at the same moment. Leave the floor or press again to stop. The pad features animated emissive tiles and pulsing coloured lights that react to every beat. (`/play`) `[feature]`
- **Drop in <agent-3d> and you get just the avatar — chat is now opt-in** — The one-line embed is cleaner by default. A plain <agent-3d> tag now ships only the 3D avatar on a transparent background — no chat box, no input bar, no debug color picker, no name-plate. That makes it perfect for dropping a living avatar onto a landing page, hero section, or card without any extra UI to hide. When you want the full talking agent, add the new chat attribute: <agent-3d chat body="...">. Published agents you embed by agent-id, manifest, or an agent:// link still chat automatically — they carry their own brain and persona — so existing agent embeds are unchanged. The reference docs and examples were updated to match. (`/docs/web-component`) `[feature, sdk]`
-- **Embeddable 3D agents now default to a clean, bare avatar** — The <agent-3d> embed tag now starts as the simplest thing it can be: a plain 3D avatar on a transparent background, with no chat box, text input, microphone, or name plate unless you ask for them. Drop the tag with a body and you get just the avatar — perfect for hero sections and decorative scenes. Everything richer is opt-in: add chat for a conversation panel, set background to dark, light, or any color, and theme it with CSS variables. Binding a live agent still turns chat on automatically, and you can now force a bare avatar even for a bound agent with chat="off". `[sdk, improvement]`
+- **Embeddable 3D agents now default to a clean, bare avatar** — The <agent-3d> embed tag now starts as the simplest thing it can be: a plain 3D avatar on a transparent background, with no chat box, controls, or name plate unless you ask for them. Drop the tag with a body and you get just the avatar — perfect for hero sections and decorative scenes. Everything richer is opt-in: add chat for a conversation panel, set background to dark, light, or any color, and theme it with CSS variables. Binding a live agent still turns chat on automatically, and you can now force a bare avatar even for a bound agent with chat="off". `[sdk, improvement]`
- **Embedded avatars: polished loading, seamless looping, and smarter framing** — The live 3D avatars dotted around the site — the ones in the home-page feature cards and anywhere an <agent-3d> embed appears — now feel intentional from the first frame. Each one fades in behind a soft skeleton placeholder while its model streams, instead of popping in cold. Animations no longer hard-snap: a one-shot gesture like a wave plays once and settles smoothly back into an idle stance rather than jumping at the loop boundary. A new framing option crops the avatar to head-to-mid-thigh so it fills its card instead of standing tiny and low. If a body ever fails to load, you get a tasteful silhouette rather than a blank or broken box. Avatars pause themselves when scrolled off-screen to save battery, and anyone who's asked their device to reduce motion gets a calm, held pose instead of looping animation. (`/embed`) `[improvement]`
- **Emoji reactions now float above avatars in every coin world** — Tap any of the 6 reaction buttons (🎉 😂 🔥 ❤️ 👏 🤔) to broadcast a floating emoji that rises above your avatar for everyone in the room to see. The 🎉 reaction also triggers a small confetti burst. Reactions are server-rate-limited so the world stays readable when multiple people react at once; the button dims briefly after each tap to signal that the next one is queued. Keyboard- and screen-reader-accessible; works on touch and desktop. (`/play`) `[feature]`
- **Emote wheel — all 70 animations at your fingertips** — Hold Q (or long-press the ⋯ button on mobile) to open the full emote wheel in any /play world. Five category arcs — Social, Dances, Flips, Combat, Poses — surface every animation in the library. Move the cursor (or left thumbstick on gamepad) to pick a category, choose a clip from the panel that slides up, then release Q to play it. The existing quick-tray keeps your top 6 one-tap emotes. All clips load lazily on first use so the initial load time is unchanged. (`/play`) `[feature]`
- **Every agent now has a dedicated wallet hub** — Each 3D agent's self-custodied Solana wallet now has one home: a tabbed Agent Wallet hub — Balance, Deposit, Trade, Snipe, Pay, and Withdraw — reachable from the agent's profile and right after you create one. The Balance tab is live now, showing the real on-chain SOL balance with a USD estimate and recent activity, refreshing on its own and degrading gracefully if the network is briefly unreachable. Behind the scenes every agent is guaranteed a wallet: older agents that predated automatic wallets are backfilled, and the agent API now reports whether each agent's wallet is ready. The remaining tabs are wired up across the next releases. `[feature]`
- **Everyone at a location now sees your IRL agent in the same real spot** — three.ws/irl agents now line up across phones. A placed agent renders from its own saved compass bearing and ground height instead of whichever way your phone happens to face, so two people standing in the same place see it standing in the same place, facing the same way. To keep it steady, your own GPS position is now smoothed so anchored agents stop drifting and swimming as your location jitters, and noisy fixes are ignored. Every agent now sits inside a ground ring whose size reflects the real GPS accuracy — honest about the fact that phone GPS is roughly 5–15 metres, and wider (and amber) when the signal is poor — so it never pretends to be pinpoint-perfect. And if an agent landed a little off, its owner can fine-tune it: long-press your own agent (or tap Calibrate position on its card) and drag to nudge it a few centimetres, twist with two fingers to rotate it, or step its floor height up and down. Saving the nudge updates the spot for everyone nearby. Only the owner can calibrate an agent, nudges are capped to small corrections so this can never be used to drag someone's agent across the map, and a failed save keeps your change on screen with a one-tap retry. (`/irl`) `[feature, improvement]`
- **Filter the marketplace by Free or Paid** — The marketplace now has working Free / Paid filters. "Paid" surfaces every agent that charges in any way — a one-time price to own it or per-call pricing on its skills — and "Free" shows the rest. Filtering happens on the server, so the result count and "load more" stay accurate no matter how many pages deep you browse, and your choice is saved in the URL so you can bookmark or share a filtered view. (`/marketplace`) `[feature, improvement]`
+- **Forge now generates on the free NVIDIA engine — faster, no throttling** — Paying to turn a sentence into a 3D model — on the IBM demo and the pay-per-call Forge API — now runs on the free NVIDIA NIM (Microsoft TRELLIS) engine instead of the previous paid pipeline. That removes the "request was throttled" errors some forges hit, and draft prompts often finish in seconds and return the model inline with no waiting. The same quality tiers and prices apply, and if the free engine is ever busy the call automatically falls back so a paid forge never dead-ends. Building a 3D model from your own uploaded photos still uses the reconstruction engine. (`/ibm/x402-demo`) `[improvement, fix]`
- **Forge resilience: HuggingFace fallback now covers text→3D; club-payout log noise reduced** — When the NVIDIA NIM free lane returns a 5xx and the Replicate TRELLIS lane is also unavailable, the forge now falls through to the HuggingFace Spaces fallback for text→3D requests (using the FLUX-synthesized intermediate image) instead of returning a 429 to the user. Previously this fallback only fired for image uploads. Club-payout cron warnings for dancers with no registered wallet are now emitted at most once per 24 hours instead of every 5-minute tick. `[fix, infra]`
- **Free text-to-3D over MCP — no payment, no key** — The three.ws MCP server now ships a free tool: forge_free turns a text prompt into a textured, downloadable 3D model with zero cost — no x402 payment, no wallet, no API key. It runs on the same free NVIDIA NIM (Microsoft TRELLIS) engine the /forge web page uses for drafts, and hands back a durable GLB plus a viewer link that renders the model in the browser. Drop your Claude/Cursor agent on it, type a prompt, get a 3D avatar. The paid tools (mesh_forge, text_to_avatar, rig_mesh) remain for image input, the Granite-directed model chain, and auto-rigging. `[sdk, feature]`
- **Game-Ready export in Forge — one click to engine-ready GLB + FBX** — Any model you generate or upload in Forge can now be turned into a clean, engine-ready asset in one click. Pick Quad retopology (field-aligned QuadriFlow edge loops that rig and animate well) or Tri low-poly (silhouette-preserving, with the texture re-baked), set a poly budget with 5k / 15k / 50k presets, and export a textured GLB plus an FBX for Unity and Unreal together. You see the before→after poly count (e.g. 28,400 → 5,012) and can flip on a live wireframe to inspect the new topology right in the viewer. Files are served from our own CDN. (`/forge`) `[feature]`
diff --git a/data/changelog.json b/data/changelog.json
index 5a34312f9..02ff62b8e 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,16 @@
{
"$comment": "Curated changelog entries for three.ws \u2014 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-17",
+ "title": "Forge now generates on the free NVIDIA engine — faster, no throttling",
+ "summary": "Paying to turn a sentence into a 3D model — on the IBM demo and the pay-per-call Forge API — now runs on the free NVIDIA NIM (Microsoft TRELLIS) engine instead of the previous paid pipeline. That removes the \"request was throttled\" errors some forges hit, and draft prompts often finish in seconds and return the model inline with no waiting. The same quality tiers and prices apply, and if the free engine is ever busy the call automatically falls back so a paid forge never dead-ends. Building a 3D model from your own uploaded photos still uses the reconstruction engine.",
+ "tags": [
+ "improvement",
+ "fix"
+ ],
+ "link": "/ibm/x402-demo"
+ },
{
"date": "2026-06-17",
"title": "Embeddable 3D agents now default to a clean, bare avatar",
diff --git a/public/changelog.json b/public/changelog.json
index a2fa27eea..885cb5eb6 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-17T22:52:45.827Z",
+ "generated_at": "2026-06-17T23:07:55.647Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -306,7 +306,7 @@
"date": "2026-06-17",
"type": "update",
"title": "Embeddable 3D agents now default to a clean, bare avatar",
- "summary": "The <agent-3d> embed tag now starts as the simplest thing it can be: a plain 3D avatar on a transparent background, with no chat box, text input, microphone, or name plate unless you ask for them. Drop the tag with a body and you get just the avatar — perfect for hero sections and decorative scenes. Everything richer is opt-in: add chat for a conversation panel, set background to dark, light, or any color, and theme it with CSS variables. Binding a live agent still turns chat on automatically, and you can now force a bare avatar even for a bound agent with chat=\"off\".",
+ "summary": "The <agent-3d> embed tag now starts as the simplest thing it can be: a plain 3D avatar on a transparent background, with no chat box, controls, or name plate unless you ask for them. Drop the tag with a body and you get just the avatar — perfect for hero sections and decorative scenes. Everything richer is opt-in: add chat for a conversation panel, set background to dark, light, or any color, and theme it with CSS variables. Binding a live agent still turns chat on automatically, and you can now force a bare avatar even for a bound agent with chat=\"off\".",
"link": null,
"tags": [
"sdk",
@@ -375,6 +375,17 @@
"improvement"
]
},
+ {
+ "date": "2026-06-17",
+ "type": "update",
+ "title": "Forge now generates on the free NVIDIA engine — faster, no throttling",
+ "summary": "Paying to turn a sentence into a 3D model — on the IBM demo and the pay-per-call Forge API — now runs on the free NVIDIA NIM (Microsoft TRELLIS) engine instead of the previous paid pipeline. That removes the \"request was throttled\" errors some forges hit, and draft prompts often finish in seconds and return the model inline with no waiting. The same quality tiers and prices apply, and if the free engine is ever busy the call automatically falls back so a paid forge never dead-ends. Building a 3D model from your own uploaded photos still uses the reconstruction engine.",
+ "link": "/ibm/x402-demo",
+ "tags": [
+ "improvement",
+ "fix"
+ ]
+ },
{
"date": "2026-06-17",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index 591d8a890..e578e523f 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -244,7 +244,7 @@
<guid isPermaLink="false">2026-06-17:Embeddable 3D agents now default to a clean, bare avatar</guid>
<pubDate>Wed, 17 Jun 2026 12:00:00 GMT</pubDate>
<category>sdk</category>
- <description>The &lt;agent-3d&gt; embed tag now starts as the simplest thing it can be: a plain 3D avatar on a transparent background, with no chat box, text input, microphone, or name plate unless you ask for them. Drop the tag with a body and you get just the avatar — perfect for hero sections and decorative scenes. Everything richer is opt-in: add chat for a conversation panel, set background to dark, light, or any color, and theme it with CSS variables. Binding a live agent still turns chat on automatically, and you can now force a bare avatar even for a bound agent with chat=&quot;off&quot;.</description>
+ <description>The &lt;agent-3d&gt; embed tag now starts as the simplest thing it can be: a plain 3D avatar on a transparent background, with no chat box, controls, or name plate unless you ask for them. Drop the tag with a body and you get just the avatar — perfect for hero sections and decorative scenes. Everything richer is opt-in: add chat for a conversation panel, set background to dark, light, or any color, and theme it with CSS variables. Binding a live agent still turns chat on automatically, and you can now force a bare avatar even for a bound agent with chat=&quot;off&quot;.</description>
</item>
<item>
<title>Embedded avatars: polished loading, seamless looping, and smarter framing</title>
@@ -294,6 +294,14 @@
<category>feature</category>
<description>The marketplace now has working Free / Paid filters. &quot;Paid&quot; surfaces every agent that charges in any way — a one-time price to own it or per-call pricing on its skills — and &quot;Free&quot; shows the rest. Filtering happens on the server, so the result count and &quot;load more&quot; stay accurate no matter how many pages deep you browse, and your choice is saved in the URL so you can bookmark or share a filtered view.</description>
</item>
+ <item>
+ <title>Forge now generates on the free NVIDIA engine — faster, no throttling</title>
+ <link>https://three.ws/ibm/x402-demo</link>
+ <guid isPermaLink="false">2026-06-17:Forge now generates on the free NVIDIA engine — faster, no throttling</guid>
+ <pubDate>Wed, 17 Jun 2026 12:00:00 GMT</pubDate>
+ <category>improvement</category>
+ <description>Paying to turn a sentence into a 3D model — on the IBM demo and the pay-per-call Forge API — now runs on the free NVIDIA NIM (Microsoft TRELLIS) engine instead of the previous paid pipeline. That removes the &quot;request was throttled&quot; errors some forges hit, and draft prompts often finish in seconds and return the model inline with no waiting. The same quality tiers and prices apply, and if the free engine is ever busy the call automatically falls back so a paid forge never dead-ends. Building a 3D model from your own uploaded photos still uses the reconstruction engine.</description>
+ </item>
<item>
<title>Forge resilience: HuggingFace fallback now covers text→3D; club-payout log noise reduced</title>
<link>https://three.ws/changelog</link>
diff --git a/public/features.json b/public/features.json
index 2bff7fd0b..093756c4c 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-17T22:52:45.808Z",
+ "generated_at": "2026-06-17T23:07:55.629Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/public/x402.js b/public/x402.js
index 67ff3beeb..feeb87c93 100644
--- a/public/x402.js
+++ b/public/x402.js
@@ -1103,8 +1103,10 @@ class CheckoutModal {
}
}
- async executePaid(xPayment) {
- this.renderProgress('verify', { text: 'Calling merchant endpoint…' });
+ async executePaid(xPayment, attempt = 0) {
+ this.renderProgress('verify', {
+ text: attempt ? 'Retrying after upstream throttle…' : 'Calling merchant endpoint…',
+ });
try {
const res = await fetch(this.opts.endpoint, {
method: this.opts.method || 'GET',
@@ -1128,6 +1130,16 @@ class CheckoutModal {
result = text;
}
if (!res.ok) {
+ // A 429 here is a transient upstream throttle (e.g. the generator's
+ // create-prediction rate limit). The payment is signed but NOT yet
+ // settled — the merchant runs the work before settling — so the same
+ // X-PAYMENT can be safely re-sent once the window resets, with no risk
+ // of a double charge. Auto-retry a couple of times, respecting the
+ // server's Retry-After, before surfacing the manual "Try again".
+ if (res.status === 429 && attempt < MAX_THROTTLE_RETRIES) {
+ await this.waitForThrottle(retryAfterSeconds(res, result));
+ return this.executePaid(xPayment, attempt + 1);
+ }
const msg = (result && typeof result === 'object' && (result.error_description || result.error)) || `HTTP ${res.status}`;
throw new Error(msg);
}
@@ -1145,6 +1157,19 @@ class CheckoutModal {
}
}
+ // Hold the verify step on a live countdown while an upstream throttle resets,
+ // then return so the caller re-sends the same signed payment. The reservation
+ // is deliberately left intact — this is the same payment, not a new one — so
+ // no rollback runs between attempts.
+ async waitForThrottle(seconds) {
+ const total = Math.max(1, Math.min(30, Math.round(seconds) || 6));
+ for (let left = total; left > 0; left--) {
+ this.renderProgress('verify', { text: `Generator is busy — retrying in ${left}s…` });
+ await new Promise((r) => setTimeout(r, 1000));
+ }
+ this.renderProgress('verify', { text: 'Retrying…' });
+ }
+
async runSiwxEvm(chain) {
this.renderProgress('connect', { text: 'Opening browser wallet…' });
try {
@@ -1310,6 +1335,21 @@ function headersToObject(headers) {
return out;
}
+// How many times executePaid silently re-sends a signed payment after a 429
+// throttle before falling back to the manual "Try again". The payment isn't
+// settled until the merchant call succeeds, so re-sending can't double-charge.
+const MAX_THROTTLE_RETRIES = 2;
+
+// Seconds to wait before re-sending after a 429. Prefers the standard
+// Retry-After header, then the body's `retry_after` hint, then a sane default.
+function retryAfterSeconds(res, result, fallback = 6) {
+ const header = Number.parseInt(res.headers.get('retry-after') || '', 10);
+ if (Number.isFinite(header) && header > 0) return header;
+ const body = result && typeof result === 'object' ? Number(result.retry_after) : NaN;
+ if (Number.isFinite(body) && body > 0) return body;
+ return fallback;
+}
+
function friendlyError(err) {
const msg = err?.shortMessage || err?.message || String(err);
// Trim ethers/viem long stacks, Phantom's RPC-error verbosity.
diff --git a/tests/api/providers-replicate.test.js b/tests/api/providers-replicate.test.js
index a200873d4..6241bfd57 100644
--- a/tests/api/providers-replicate.test.js
+++ b/tests/api/providers-replicate.test.js
@@ -183,6 +183,69 @@ describe('replicate provider — community-model 404 fallback', () => {
});
});
+describe('replicate provider — create-prediction throttle', () => {
+ // Replicate 429s prediction CREATION when the account is over its (credit-
+ // reduced) rate limit. The window resets in seconds and no prediction was
+ // created, so the provider must back off and retry rather than fail the call.
+ it('retries a 429 throttle and succeeds once the window resets', async () => {
+ let posts = 0;
+ globalThis.fetch = vi.fn(async (url) => {
+ posts++;
+ if (posts === 1) {
+ return new Response(
+ JSON.stringify({ detail: 'Request was throttled. Your rate limit resets in ~10s.' }),
+ // retry-after: 0 keeps the test instant; the backoff math is the same.
+ { status: 429, headers: { 'content-type': 'application/json', 'retry-after': '0' } },
+ );
+ }
+ return new Response(JSON.stringify({ id: 'pred_throttle_ok', status: 'starting' }), {
+ status: 201,
+ headers: { 'content-type': 'application/json' },
+ });
+ });
+
+ const provider = await freshProvider();
+ const job = await provider.submit({
+ mode: 'reconstruct',
+ params: { images: ['https://img/a.jpg'] },
+ sourceUrl: 'https://img/a.jpg',
+ });
+
+ expect(posts).toBe(2); // throttled once, then created
+ expect(job.extJobId).toBe('pred_throttle_ok');
+ });
+
+ it('surfaces an exhausted throttle as a retryable rate_limited error', async () => {
+ // No Retry-After header → the backoff + the surfaced hint are both parsed
+ // from the "resets in ~3s" body phrasing. Fake timers skip the real waits.
+ vi.useFakeTimers();
+ try {
+ globalThis.fetch = vi.fn(async () =>
+ new Response(
+ JSON.stringify({ detail: 'Request was throttled. Your rate limit resets in ~3s.' }),
+ { status: 429, headers: { 'content-type': 'application/json' } },
+ ),
+ );
+
+ const provider = await freshProvider();
+ const pending = provider.submit({
+ mode: 'reconstruct',
+ params: { images: ['https://img/a.jpg'] },
+ sourceUrl: 'https://img/a.jpg',
+ });
+ const assertion = expect(pending).rejects.toMatchObject({
+ code: 'rate_limited',
+ status: 429,
+ retryAfter: 3,
+ });
+ await vi.runAllTimersAsync(); // advance through the bounded backoff sleeps
+ await assertion;
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+});
+
describe('replicate provider — GLB extraction from status', () => {
function stubStatus(output) {
globalThis.fetch = vi.fn(async () =>
diff --git a/tests/api/x402-forge.test.js b/tests/api/x402-forge.test.js
index 5ec9a3be4..7a9563722 100644
--- a/tests/api/x402-forge.test.js
+++ b/tests/api/x402-forge.test.js
@@ -18,6 +18,8 @@ beforeAll(() => {
X402_PAY_TO_BASE: '0x0000000000000000000000000000000000000001',
X402_ASSET_ADDRESS_BASE: '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913',
REPLICATE_API_TOKEN: 'test-token',
+ // Signs the forge poll token the NVIDIA async path hands back.
+ JWT_SECRET: 'test-jwt-secret-for-forge-job-tokens',
});
});
@@ -37,10 +39,15 @@ vi.mock('../../api/_lib/x402-spec.js', async (importActual) => {
vi.mock('../../api/_mcp3d/text-to-image.js', () => ({
textToImage: vi.fn(async () => ({ imageUrl: 'https://cdn.example/ref.png', model: 'flux', predictionId: 'p1' })),
}));
+// Hoisted so a test can force the reconstruct submit to throw a throttle. The
+// shared `submit` mock defaults to a queued job; mockRejectedValueOnce lets the
+// 429 path exercise the endpoint's retryable rate-limit response.
+const replicateMock = vi.hoisted(() => {
+ const submit = vi.fn(async () => ({ extJobId: 'abcd1234efgh5678ij', jobId: 'abcd1234efgh5678ij', eta: 60 }));
+ return { submit, createRegenProvider: vi.fn(() => ({ submit })) };
+});
vi.mock('../../api/_providers/replicate.js', () => ({
- createRegenProvider: () => ({
- submit: vi.fn(async () => ({ extJobId: 'abcd1234efgh5678ij', jobId: 'abcd1234efgh5678ij', eta: 60 })),
- }),
+ createRegenProvider: replicateMock.createRegenProvider,
}));
// Free NVIDIA NIM TRELLIS lane — the primary text→3D engine. Hoisted so each test
@@ -146,11 +153,75 @@ describe('POST /api/x402/forge — validation', () => {
});
});
+describe('POST /api/x402/forge — free NVIDIA NIM text lane', () => {
+ it('routes a paid text prompt through the free NVIDIA lane and hands back a poll token (async)', async () => {
+ // NVCF accepted the job for async processing — returns a request id to poll.
+ nvidiaMock.createNvidiaProvider.mockReturnValueOnce({
+ textTo3d: vi.fn(async () => ({ kind: 'text-to-3d', taskId: 'nvcf-req-abc123' })),
+ });
+ const res = makeRes();
+ await handler(
+ makeReq({ headers: { 'x-payment': 'pay-nvidia-async' }, body: { prompt: 'a brass steampunk owl', tier: 'high' } }),
+ res,
+ );
+ expect(res.statusCode).toBe(200);
+ const body = JSON.parse(res.body);
+ expect(body.backend).toBe('nvidia');
+ expect(body.mode).toBe('text_to_3d');
+ expect(body.status).toBe('queued');
+ // The poll token is a signed forge token (f1.*) so the free poll endpoint
+ // routes the status check back to the NIM provider.
+ expect(body.job_id.startsWith('f1.')).toBe(true);
+ expect(body.poll_url).toBe('/api/forge?job=' + encodeURIComponent(body.job_id));
+ expect(body.price_usdc).toBe('0.50');
+ expect(res.headers['x-payment-response']).toBe('stub-payment-response');
+ });
+
+ it('returns the finished GLB inline when the NIM lane completes synchronously', async () => {
+ nvidiaMock.createNvidiaProvider.mockReturnValueOnce({
+ textTo3d: vi.fn(async () => ({
+ kind: 'text-to-3d',
+ taskId: null,
+ resultGlbUrl: 'https://cdn.three.ws/forge/nvidia/abc.glb',
+ })),
+ });
+ const res = makeRes();
+ await handler(
+ makeReq({ headers: { 'x-payment': 'pay-nvidia-sync' }, body: { prompt: 'a tiny red dragon', tier: 'draft' } }),
+ res,
+ );
+ expect(res.statusCode).toBe(200);
+ const body = JSON.parse(res.body);
+ expect(body.backend).toBe('nvidia');
+ expect(body.status).toBe('done');
+ expect(body.glb_url).toBe('https://cdn.three.ws/forge/nvidia/abc.glb');
+ expect(body.job_id).toBeNull();
+ // Settlement still ran — the buyer paid and received a model.
+ expect(res.headers['x-payment-response']).toBe('stub-payment-response');
+ });
+
+ it('degrades to the FLUX→TRELLIS reconstruct lane when the NIM lane is unavailable', async () => {
+ // Default nvidiaMock throws (no key) → submitGeneration falls back to Replicate.
+ const res = makeRes();
+ await handler(
+ makeReq({ headers: { 'x-payment': 'pay-fallback-trellis' }, body: { prompt: 'a brass owl', tier: 'standard' } }),
+ res,
+ );
+ expect(res.statusCode).toBe(200);
+ const body = JSON.parse(res.body);
+ expect(body.backend).toBe('trellis');
+ expect(body.job_id).toBe('abcd1234efgh5678ij');
+ expect(body.poll_url).toBe('/api/forge?job=abcd1234efgh5678ij');
+ });
+});
+
describe('POST /api/x402/forge — paid generation', () => {
- it('submits a job and returns a free poll_url after payment', async () => {
+ it('submits a job and returns a free poll_url after payment (Replicate reconstruct fallback)', async () => {
+ // NVIDIA unconfigured here (default mock throws), so this exercises the
+ // reconstruct lane — the engine for image→3D and the text fallback.
const res = makeRes();
await handler(
- makeReq({ headers: { 'x-payment': 'stub-payment-proof' }, body: { prompt: 'a brass steampunk owl', tier: 'standard' } }),
+ makeReq({ headers: { 'x-payment': 'pay-paid-standard' }, body: { prompt: 'a brass steampunk owl', tier: 'standard' } }),
res,
);
expect(res.statusCode).toBe(200);
@@ -171,4 +242,27 @@ describe('POST /api/x402/forge — paid generation', () => {
expect(res.statusCode).toBe(400);
expect(JSON.parse(res.body).error).toBe('missing_input');
});
+
+ it('answers a generator throttle with 429 + Retry-After and does not settle', async () => {
+ replicateMock.submit.mockRejectedValueOnce(
+ Object.assign(new Error('Request was throttled. Your rate limit resets in ~10s.'), {
+ code: 'rate_limited',
+ status: 429,
+ retryAfter: 10,
+ }),
+ );
+ // Force the reconstruct lane (NVIDIA already throws by default → falls through).
+ const res = makeRes();
+ await handler(
+ makeReq({ headers: { 'x-payment': 'stub-payment-proof' }, body: { prompt: 'a brass steampunk owl' } }),
+ res,
+ );
+ expect(res.statusCode).toBe(429);
+ const body = JSON.parse(res.body);
+ expect(body.error).toBe('rate_limited');
+ expect(body.retry_after).toBe(10);
+ expect(res.headers['retry-after']).toBe('10');
+ // Submit failed before settle → no settlement receipt was emitted.
+ expect(res.headers['x-payment-response']).toBeUndefined();
+ });
});