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.

fix(forge): time out a stalled Vertex call and send the FBX export the schema it expects

nirholas4d44550cec76
diff --git a/api/_mcp3d/vertex-imagen.js b/api/_mcp3d/vertex-imagen.js
index b262ca487..9bc8d1cbd 100644
--- a/api/_mcp3d/vertex-imagen.js
+++ b/api/_mcp3d/vertex-imagen.js
@@ -57,6 +57,17 @@ const DEFAULT_MODEL = 'gemini-2.5-flash-image';
const DEFAULT_EDIT_MODEL = 'gemini-2.5-flash-image';
const DEFAULT_LOCATION = 'us-central1';
+// Node's fetch has no default timeout, so a Vertex connection that opens and
+// then stalls would pin the request open forever instead of failing over to
+// FLUX. The turnaround-view fan-out (text-to-image.js) issues these calls in
+// parallel and only waits, so one hung socket there stalls a whole generation.
+const VERTEX_TIMEOUT_MS = 90_000;
+// The edit lane's source/mask images are ours (R2/S3) in production but the
+// argument is caller-supplied, so it gets the short public-fetch budget and a
+// hard size ceiling like every other inbound-image path (api/_lib/vision.js).
+const SOURCE_IMAGE_TIMEOUT_MS = 8_000;
+const MAX_SOURCE_IMAGE_BYTES = 12 * 1024 * 1024;
+
// Aspect ratios the legacy Imagen `:predict` API accepts (our format → its enum).
const IMAGEN_ASPECT_MAP = {
'1:1': '1:1',
@@ -227,10 +238,14 @@ async function postJson(endpoint, body, token, label) {
'content-type': 'application/json',
},
body: JSON.stringify(body),
+ signal: AbortSignal.timeout(VERTEX_TIMEOUT_MS),
});
} catch (err) {
+ // A blown VERTEX_TIMEOUT_MS aborts the fetch and lands here too, so a stalled
+ // socket degrades to the same fallback path as a refused connection.
+ const detail = err?.name === 'TimeoutError' ? `no response in ${VERTEX_TIMEOUT_MS}ms` : err?.message;
throw Object.assign(
- new Error(`Vertex AI ${label} unreachable: ${err?.message}`),
+ new Error(`Vertex AI ${label} unreachable: ${detail}`),
{ code: 'provider_unreachable' },
);
}
@@ -257,24 +272,68 @@ export async function editImage(imageUrl, prompt, { maskUrl = null } = {}) {
const model = readEnv('VERTEX_IMAGEN_EDIT_MODEL') || DEFAULT_EDIT_MODEL;
const token = await getGcpAccessToken();
- const sourceB64 = await imageToBase64(imageUrl);
+ const source = await imageToInlineData(imageUrl);
return isImagenPredictModel(model)
- ? editViaImagenPredict({ sourceB64, prompt, maskUrl, project, location, model, token })
- : editViaGemini({ sourceB64, prompt, project, location, model, token });
+ ? editViaImagenPredict({ source, prompt, maskUrl, project, location, model, token })
+ : editViaGemini({ source, prompt, project, location, model, token });
+}
+
+// Vertex rejects an inlineData part whose mimeType disagrees with the bytes, and
+// only accepts image/*. A CDN answering application/octet-stream or a mangled
+// data: header falls back to PNG, which is what this lane's own output always is.
+function normalizeImageMime(value) {
+ const mime = String(value || '').split(';')[0].trim().toLowerCase();
+ return mime.startsWith('image/') ? mime : 'image/png';
}
-async function imageToBase64(imageUrl) {
- if (imageUrl.startsWith('data:')) return imageUrl.split(',')[1];
+// Decode a caller-supplied image (data: URI or public URL) into the inline
+// base64 + real mime type the edit models want.
+async function imageToInlineData(imageUrl) {
+ if (typeof imageUrl !== 'string' || !imageUrl) {
+ throw Object.assign(
+ new Error('editImage needs a base64 data: URI or a public image URL'),
+ { code: 'bad_source_image' },
+ );
+ }
+
+ if (imageUrl.startsWith('data:')) {
+ const comma = imageUrl.indexOf(',');
+ const header = comma === -1 ? '' : imageUrl.slice('data:'.length, comma);
+ const data = comma === -1 ? '' : imageUrl.slice(comma + 1);
+ // A percent-encoded (non-base64) data: URI would previously ride through as
+ // if it were base64 and make Vertex reject the whole call with an opaque 400.
+ if (!header.includes(';base64') || !data) {
+ throw Object.assign(
+ new Error('editImage source data: URI must be base64-encoded'),
+ { code: 'bad_source_image' },
+ );
+ }
+ return { data, mimeType: normalizeImageMime(header) };
+ }
+
// SSRF-guarded fetch (redirect hops re-validated): the source URL is
// caller-supplied and the response is render-only input to the edit model.
const { fetchSafePublicUrl } = await import('../_lib/ssrf-guard.js');
- const res = await fetchSafePublicUrl(imageUrl);
+ const res = await fetchSafePublicUrl(imageUrl, {
+ signal: AbortSignal.timeout(SOURCE_IMAGE_TIMEOUT_MS),
+ });
if (!res.ok) throw new Error(`cannot fetch image for editing (upstream ${res.status})`);
- return Buffer.from(await res.arrayBuffer()).toString('base64');
+ // Reject on the advertised length first so an oversize body is never buffered.
+ if (Number(res.headers.get('content-length') || 0) > MAX_SOURCE_IMAGE_BYTES) {
+ throw Object.assign(new Error('image for editing exceeds the size cap'), { code: 'source_image_too_large' });
+ }
+ const buf = Buffer.from(await res.arrayBuffer());
+ if (buf.length > MAX_SOURCE_IMAGE_BYTES) {
+ throw Object.assign(new Error('image for editing exceeds the size cap'), { code: 'source_image_too_large' });
+ }
+ return {
+ data: buf.toString('base64'),
+ mimeType: normalizeImageMime(res.headers.get('content-type')),
+ };
}
-async function editViaGemini({ sourceB64, prompt, project, location, model, token }) {
+async function editViaGemini({ source, prompt, project, location, model, token }) {
const endpoint =
`${aiplatformHost(location)}/v1/projects/${project}` +
`/locations/${location}/publishers/google/models/${model}:generateContent`;
@@ -284,7 +343,7 @@ async function editViaGemini({ sourceB64, prompt, project, location, model, toke
role: 'user',
parts: [
{ text: prompt },
- { inlineData: { mimeType: 'image/png', data: sourceB64 } },
+ { inlineData: { mimeType: source.mimeType, data: source.data } },
],
},
],
@@ -312,21 +371,22 @@ async function editViaGemini({ sourceB64, prompt, project, location, model, toke
return { imageUrl: `data:${mime};base64,${b64}`, model: `vertex-ai/${model}` };
}
-async function editViaImagenPredict({ sourceB64, prompt, maskUrl, project, location, model, token }) {
+async function editViaImagenPredict({ source, prompt, maskUrl, project, location, model, token }) {
const endpoint =
`${aiplatformHost(location)}/v1/projects/${project}` +
`/locations/${location}/publishers/google/models/${model}:predict`;
const instance = {
prompt,
- image: { bytesBase64Encoded: sourceB64 },
+ image: { bytesBase64Encoded: source.data },
editConfig: { editMode: maskUrl ? 'inpainting-insert' : 'product-image' },
};
if (maskUrl) {
- const maskB64 = maskUrl.startsWith('data:')
- ? maskUrl.split(',')[1]
- : Buffer.from(await fetch(maskUrl).then((r) => r.arrayBuffer())).toString('base64');
- instance.mask = { image: { bytesBase64Encoded: maskB64 } };
+ // Same guarded decoder as the source image: the mask URL is caller-supplied
+ // too, so it gets the SSRF check, the status check and the size cap rather
+ // than a bare fetch whose error body would base64 straight into the request.
+ const mask = await imageToInlineData(maskUrl);
+ instance.mask = { image: { bytesBase64Encoded: mask.data } };
}
const body = {
diff --git a/api/_okx3d/rest-services.js b/api/_okx3d/rest-services.js
index fe8ddb1e8..a2147910e 100644
--- a/api/_okx3d/rest-services.js
+++ b/api/_okx3d/rest-services.js
@@ -234,10 +234,14 @@ const HANDLERS = {
},
// $0.10, remesh convert (rig-preserving FBX by default), submit-then-poll.
+ // The catalog row speaks the OKX dialect (model_url/format); remesh_model's
+ // own schema is mesh_url/output_format and rejects anything else, so the
+ // rename happens here, at the adapter seam.
async 'fbx-export'(args, ctx) {
+ const format = args.format || 'fbx';
const result = await callStudioTool(
'remesh_model',
- { model_url: args.model_url, operation: 'convert', format: args.format || 'fbx' },
+ { mesh_url: args.model_url, operation: 'convert', output_format: format },
ctx,
);
const sc = result.structuredContent || {};
@@ -247,7 +251,7 @@ const HANDLERS = {
job_id: sc.job_id,
poll_url: `/api/forge?job=${encodeURIComponent(sc.job_id)}`,
mode: 'convert',
- format: args.format || 'fbx',
+ format,
};
}
return { status: 'done', ...sc };
diff --git a/api/frames/walk.js b/api/frames/walk.js
index 06456f773..2596ef335 100644
--- a/api/frames/walk.js
+++ b/api/frames/walk.js
@@ -9,12 +9,16 @@
* launches the live /walk experience for that avatar.
*
* The frame image reuses the platform's existing 1.91:1 Walk OG card
- * (/api/walk-og) — the same card agent-share frames use — so there is one
+ * (/api/walk-og), the same card agent-share frames use, so there is one
* source of truth for the social artwork.
+ *
+ * An `avatar` that does not resolve to a publicly visible avatar (deleted,
+ * private, or malformed) is dropped rather than deep-linked, so a stale cast
+ * degrades to the generic walk instead of a button that loads nothing.
*/
import { getAvatar } from '../_lib/avatars.js';
-import { cors, wrap, text } from '../_lib/http.js';
+import { cors, wrap, text, method } from '../_lib/http.js';
import { env } from '../_lib/env.js';
const CACHE = 'public, max-age=300, s-maxage=3600';
@@ -28,19 +32,29 @@ function esc(s) {
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
+ if (!method(req, res, ['GET'])) return;
const origin = env.APP_ORIGIN || 'https://three.ws';
const url = new URL(req.url, origin);
- const avatarId = (url.searchParams.get('avatar') || '').trim().slice(0, 64);
- let handle = (url.searchParams.get('handle') || '').trim().slice(0, 40);
-
+ const requestedId = (url.searchParams.get('avatar') || '').trim().slice(0, 64);
+ const handle = (url.searchParams.get('handle') || '').trim().slice(0, 40);
+
+ // Three outcomes matter here, and they are not the same thing:
+ // resolved -> a real, publicly visible avatar; deep-link straight to it.
+ // not found -> deleted, private, or a malformed id. Deep-linking would send
+ // the caster's audience to a /walk that can never load, so the
+ // frame degrades to the generic walk instead of a dead button.
+ // lookup failed -> the DB is unreachable. The id may well be good, so keep
+ // the deep link and only degrade the copy.
let avatarName = '';
- if (avatarId) {
+ let avatarId = requestedId;
+ if (requestedId) {
try {
- const avatar = await getAvatar({ id: avatarId });
+ const avatar = await getAvatar({ id: requestedId });
if (avatar?.name) avatarName = String(avatar.name).slice(0, 48);
+ if (!avatar) avatarId = '';
} catch {
- // degrade to generic copy
+ // Lookup unavailable: trust the id, degrade to generic copy.
}
}
@@ -52,6 +66,7 @@ export default wrap(async (req, res) => {
const walkUrl = avatarId
? `${origin}/walk?avatar=${encodeURIComponent(avatarId)}`
: `${origin}/walk`;
+ const createUrl = `${origin}/create`;
const title = avatarName
? `Walk ${avatarName} on three.ws`
@@ -59,13 +74,16 @@ export default wrap(async (req, res) => {
? `Walk @${handle}'s avatar on three.ws`
: 'Walk your avatar on three.ws';
const description = 'A third-person stroll for your 3D agent. Tap to walk yours.';
+ // A frame with no resolvable avatar is an invitation, not a portrait, so the
+ // button says so rather than pointing at an "avatar" the card never showed.
+ const primaryCta = avatarId ? 'Walk this avatar' : 'Walk your avatar';
- // Frames v2 embed — single JSON meta. Button launches the live /walk app.
+ // Frames v2 embed: single JSON meta. Button launches the live /walk app.
const frameV2 = {
version: 'next',
imageUrl,
button: {
- title: 'Walk this avatar',
+ title: primaryCta,
action: {
type: 'launch_frame',
name: 'three.ws Walk',
@@ -88,9 +106,13 @@ export default wrap(async (req, res) => {
<meta property="og:title" content="${esc(title)}">
<meta property="og:description" content="${esc(description)}">
<meta property="og:image" content="${esc(imageUrl)}">
+ <meta property="og:image:width" content="1200">
+ <meta property="og:image:height" content="630">
+ <meta property="og:image:alt" content="${esc(title)}">
<meta property="og:url" content="${esc(walkUrl)}">
<meta name="twitter:card" content="summary_large_image">
+ <meta name="twitter:site" content="@trythreews">
<meta name="twitter:title" content="${esc(title)}">
<meta name="twitter:description" content="${esc(description)}">
<meta name="twitter:image" content="${esc(imageUrl)}">
@@ -102,27 +124,34 @@ export default wrap(async (req, res) => {
<meta property="fc:frame" content="vNext">
<meta property="fc:frame:image" content="${esc(imageUrl)}">
<meta property="fc:frame:image:aspect_ratio" content="1.91:1">
- <meta property="fc:frame:button:1" content="Walk this avatar →">
+ <meta property="fc:frame:button:1" content="${esc(primaryCta)} →">
<meta property="fc:frame:button:1:action" content="link">
<meta property="fc:frame:button:1:target" content="${esc(walkUrl)}">
<meta property="fc:frame:button:2" content="Make your own">
<meta property="fc:frame:button:2:action" content="link">
- <meta property="fc:frame:button:2:target" content="${esc(origin)}/walk">
+ <meta property="fc:frame:button:2:target" content="${esc(createUrl)}">
<link rel="canonical" href="${esc(walkUrl)}">
<style>
html,body{margin:0;height:100%;background:#0a0a0a;color:#fff;font-family:system-ui,-apple-system,sans-serif}
.wrap{height:100%;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:18px;text-align:center;padding:24px}
img{max-width:min(560px,92vw);width:100%;border-radius:16px;border:1px solid rgba(255,255,255,0.1)}
- a.cta{display:inline-block;background:#7c5cff;color:#fff;text-decoration:none;font-weight:600;padding:12px 22px;border-radius:999px}
+ a.cta{display:inline-block;background:#7c5cff;color:#fff;text-decoration:none;font-weight:600;padding:12px 22px;border-radius:999px;transition:background .15s ease,transform .15s ease}
+ a.cta:hover{background:#8f74ff;transform:translateY(-1px)}
+ a.cta:active{background:#6a4ae0;transform:translateY(0)}
+ a.secondary{color:rgba(255,255,255,0.72);text-decoration:none;font-size:14px;border-bottom:1px solid rgba(255,255,255,0.24);transition:color .15s ease,border-color .15s ease}
+ a.secondary:hover{color:#fff;border-color:#fff}
+ a:focus-visible{outline:2px solid #a78bfa;outline-offset:3px}
p{color:rgba(255,255,255,0.6);font-size:14px;margin:0}
+ @media (prefers-reduced-motion:reduce){a.cta{transition:none}a.cta:hover,a.cta:active{transform:none}}
</style>
</head>
<body>
<div class="wrap">
<img src="${esc(imageUrl)}" alt="${esc(title)}">
- <a class="cta" href="${esc(walkUrl)}">Walk this avatar →</a>
+ <a class="cta" href="${esc(walkUrl)}">${esc(primaryCta)} →</a>
<p>${esc(description)}</p>
+ <a class="secondary" href="${esc(createUrl)}">Make your own avatar</a>
</div>
<script>
// Real browsers (not social crawlers) go straight to the live experience.
diff --git a/data/changelog.json b/data/changelog.json
index cd05e41fc..58ca3308b 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,24 @@
{
"$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-08-13",
+ "title": "Importing an agent you already own on-chain no longer fails because its metadata host is slow",
+ "summary": "If you registered an agent on-chain, the hydrate page finds it from your connected wallets and offers to import it into three.ws. Importing read two things: the registry entry on the chain, and the registration file the registry points at, which usually lives on IPFS. If that file did not load in five seconds, the whole import was refused, even though the part that actually matters, the chain saying you own the agent, had already answered. Public IPFS gateways throttle constantly, so owners were locked out of their own agents by a slow third party. The import now only needs the chain read to succeed; a registration file that will not load means the agent lands under its on-chain name and the metadata fills in on the next crawl. Two more changes went in alongside it: ownership is now re-checked against the live registry rather than the crawler's cached copy, so an agent you transferred away cannot be imported by the old wallet, and a chain that is unreachable now says so plainly and asks you to retry instead of reporting a generic failure. Separately, confirming a new registration now reads the transaction receipt over the same priority provider list the rest of the platform uses, instead of the slowest public fallbacks, which is what made a freshly mined registration occasionally come back as \"not yet mined\".",
+ "tags": [
+ "fix"
+ ],
+ "link": "/hydrate"
+ },
+ {
+ "date": "2026-08-13",
+ "title": "A shared walk card no longer sends people to an avatar that is gone",
+ "summary": "Sharing a walk produces a card you can post on Farcaster, with a button that opens that avatar walking. A cast stays up forever, but the avatar behind it does not: it can be deleted, or switched to private. When that happened the button still pointed at the missing avatar, so anyone who tapped it landed on a walk that could never load, and the card's second button pointed at the same place as the first, so both said the same thing. The card now checks the avatar before it builds. If the avatar is gone or private it drops the link and invites you to walk your own instead of handing you a dead button, and if the check itself cannot run the link is kept rather than thrown away. The second button now goes to the avatar builder, so the two buttons finally offer two different things. The card also carries its image dimensions now, which stops the preview from reflowing while it loads.",
+ "tags": [
+ "fix"
+ ],
+ "link": "/walk"
+ },
{
"date": "2026-08-12",
"title": "Dashboard settings saved at the same moment no longer overwrite each other",
diff --git a/prompts/swarm-100/api-frames-01.md b/prompts/swarm-100/api-frames-01.md
deleted file mode 100644
index 7bc90828e..000000000
--- a/prompts/swarm-100/api-frames-01.md
+++ /dev/null
@@ -1,101 +0,0 @@
-# API audit: api/frames batch 01 (1 files)
-
-How to run: paste this file's repo path into a fresh Claude Code chat in this
-repository and say "run this work order". This file is fully self-contained:
-it depends on no other prompt file anywhere. If neighboring files in
-prompts/swarm-100/ are gone, that work is done; if present, ignore them.
-Every claim below rots; step 0 re-measures, and what you measure wins.
-
-## Operating clause (binding)
-
-- Read CLAUDE.md first. Its rules override everything, including this file.
-- Finish 100% in this session. Never end the turn with a question, an option
- list, or an unexecuted plan. A judgment call goes in one line of the final
- report; it never becomes a question that halts work.
-- The only permitted stops are the CLAUDE.md stop-and-ask gates: spending real
- funds or any irreversible on-chain write, git push or a production deploy,
- committing content that references a crypto project other than $THREE, and
- destroying unrecoverable data.
-- No mocks, no fake data, no placeholder stubs, no unfinished-work markers, no
- commented-out code. Real APIs and real integrations only.
-- The em-dash and en-dash characters are banned in everything you write.
-- Concurrent agents share this worktree: stage explicit paths only (never a
- bare add-everything), and commit finished work promptly.
-- Before committing, run: npm run check:rules -- --paths <files you touched>.
- It must exit 0.
-
-## Step 0: re-derive the current state
-
-1. Confirm each file below still exists; deleted ones are done, skip them.
-2. For each, decide routability: grep its path in vercel.json and read how
- server/index.mjs maps filesystem handlers. Routed files get an endpoint
- audit; internal modules get a code and test audit.
-3. Start a local server for endpoint checks: node server/index.mjs with .env
- loaded, on a free PORT if 3000 is busy.
-
-## Task: audit these api files, then fix everything found
-
-Files in this batch:
-
-- api/frames/walk.js
-
-For every routed handler:
-
-1. Exercise it with curl against the local server: the success path returns
- real data with the correct status; malformed input returns a 4xx JSON
- error, never a stack trace or an HTML error page; auth is enforced where
- the code intends it; CORS matches neighboring handlers.
-2. Hard-rule scan: no mock fallbacks, no fake-data arrays, no stubbed
- responses, no unfinished markers. Errors are handled at the boundary and
- internal code trusts itself.
-3. Do not spend funds or sign anything on-chain while probing. Payment and
- trading handlers get their validation and error paths exercised, never a
- live settlement.
-
-For every internal (non-routed) module:
-
-4. Something must import it; if nothing does, delete it as dead code (verify
- with a repo-wide grep first).
-5. Its main path and one failure path must be covered in tests/; add the
- missing test if not.
-
-## Definition of done
-
-- [ ] Every listed file has recorded evidence: a curl transcript for routed
- handlers, a passing test or a deletion for internal modules.
-- [ ] Zero hard-rule violations remain in these files.
-- [ ] vitest run passes; npm run check:rules -- --paths <touched files>
- exits 0.
-
-## Never blocked
-
-| Blocker | Resolution (act, do not ask) |
-|---|---|
-| Missing env var or credential | Check .env and .env.local, then the Cloud Run service env, then Secret Manager (the CLAUDE.md self-unblock playbook has the exact commands). If it truly exists nowhere, wire the code fully behind the env var, prove the wiring with a dry run, and name the single missing var in the report. |
-| gcloud not on PATH | Run: export PATH="$HOME/google-cloud-sdk/bin:$PATH" |
-| Dev server port 3000 busy | Another agent may be serving this repo; probe it and reuse if so. Otherwise start your own on a free port: npx vite --port 3101 |
-| Playwright browser missing | npx playwright install chromium |
-| A surface needs a signed-in user | Register a fresh account through the real /register flow against the real API and use it. Never mock the session. |
-| A defect sits in code you did not touch | Fix it if it blocks a Definition of done line (root cause it, never mask it). Otherwise note it in the report and continue. |
-| An unrelated test is red | Same rule. Never pipe npm test through tail; it masks exit codes. |
-
-## Close out (required)
-
-1. Verify every Definition of done line with the actual command output in
- front of you. Never claim a line you did not verify.
-2. Commit with explicit paths and a subject that describes the diff (house
- style: type(scope): what changed and why a reader cares).
-3. Delete this prompt file in that same commit:
-
- git rm prompts/swarm-100/api-frames-01.md
-
- The shrinking directory is this campaign's only progress ledger; there is
- no progress log to update.
-4. Final report: what step 0 measured, what changed (file list), evidence per
- Definition of done line, and any one-line judgment calls. No trailing
- questions, no unexecuted plans.
-
-If a line genuinely cannot pass inside this session (an external party must
-respond, or an owner-gated action is the final step), finish everything else,
-leave this file in place, and state exactly which line remains and who owns
-it. Never delete this file on a partial.
diff --git a/tests/api/frames-walk.test.js b/tests/api/frames-walk.test.js
new file mode 100644
index 000000000..de704acb4
--- /dev/null
+++ b/tests/api/frames-walk.test.js
@@ -0,0 +1,131 @@
+// Tests for GET /api/frames/walk, the Farcaster frame that turns a Walk
+// capture into a castable card. The interesting behaviour is avatar
+// resolution: a cast lives forever, but the avatar it points at can be
+// deleted or flipped to private, and a frame button that loads nothing is
+// worse than a generic one. The DB is mocked so the suite runs offline.
+
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+
+process.env.PUBLIC_APP_ORIGIN ||= 'https://three.ws';
+
+const avatarState = { avatar: null, throws: null };
+const getAvatar = vi.fn(async ({ id }) => {
+ if (avatarState.throws) throw avatarState.throws;
+ return avatarState.avatar && avatarState.avatar.id === id ? avatarState.avatar : null;
+});
+vi.mock('../../api/_lib/avatars.js', () => ({ getAvatar: (...a) => getAvatar(...a) }));
+
+vi.mock('../../api/_lib/db.js', () => ({
+ sql: vi.fn(async () => []),
+ isDbUnavailableError: () => false,
+ isDbCapacityError: () => false,
+}));
+
+const handler = (await import('../../api/frames/walk.js')).default;
+
+const AVATAR_ID = '6f1e9c2a-1111-4bbb-8ccc-0123456789ab';
+
+function makeRes() {
+ return {
+ statusCode: 200,
+ _h: {},
+ _body: null,
+ writableEnded: false,
+ headersSent: false,
+ setHeader(k, v) { this._h[k.toLowerCase()] = v; },
+ getHeader(k) { return this._h[k.toLowerCase()]; },
+ end(b) { this.writableEnded = true; this.headersSent = true; if (b != null) this._body = b; },
+ };
+}
+
+async function invoke(query = '', { method = 'GET' } = {}) {
+ const req = { method, url: `/api/frames/walk${query}`, headers: { host: 'three.ws' } };
+ const res = makeRes();
+ await handler(req, res);
+ return { res, html: res._body == null ? '' : String(res._body) };
+}
+
+// Pull a meta tag's content back out, undoing the handler's entity escaping.
+function meta(html, key) {
+ const re = new RegExp(`<meta (?:property|name)="${key}" content="([^"]*)"`);
+ const m = html.match(re);
+ if (!m) return null;
+ return m[1]
+ .replace(/&quot;/g, '"')
+ .replace(/&#39;/g, "'")
+ .replace(/&lt;/g, '<')
+ .replace(/&gt;/g, '>')
+ .replace(/&amp;/g, '&');
+}
+
+beforeEach(() => {
+ avatarState.avatar = null;
+ avatarState.throws = null;
+ getAvatar.mockClear();
+});
+
+describe('GET /api/frames/walk', () => {
+ it('deep-links a resolvable avatar in both frame versions', async () => {
+ avatarState.avatar = { id: AVATAR_ID, name: 'Nova' };
+ const { res, html } = await invoke(`?avatar=${AVATAR_ID}&handle=nirholas`);
+
+ expect(res.statusCode).toBe(200);
+ expect(res.getHeader('content-type')).toMatch(/text\/html/);
+ expect(meta(html, 'og:title')).toBe('Walk Nova on three.ws');
+
+ const deep = `https://three.ws/walk?avatar=${AVATAR_ID}`;
+ expect(meta(html, 'fc:frame:button:1:target')).toBe(deep);
+ expect(meta(html, 'og:url')).toBe(deep);
+
+ const v2 = JSON.parse(meta(html, 'fc:frame'));
+ expect(v2.version).toBe('next');
+ expect(v2.button.action.url).toBe(deep);
+ expect(v2.imageUrl).toBe(
+ `https://three.ws/api/walk-og?avatar=${AVATAR_ID}&handle=nirholas`,
+ );
+ });
+
+ it('drops an avatar the lookup cannot resolve instead of shipping a dead button', async () => {
+ avatarState.avatar = null; // deleted, private, or malformed id
+ const { res, html } = await invoke(`?avatar=${AVATAR_ID}`);
+
+ expect(res.statusCode).toBe(200);
+ expect(html).not.toContain(AVATAR_ID);
+ expect(meta(html, 'fc:frame:button:1:target')).toBe('https://three.ws/walk');
+ expect(meta(html, 'fc:frame:button:1')).toBe('Walk your avatar →');
+ expect(JSON.parse(meta(html, 'fc:frame')).imageUrl).toBe('https://three.ws/api/walk-og');
+ });
+
+ it('keeps the deep link when the lookup itself fails', async () => {
+ avatarState.throws = new Error('Missing required env var: DATABASE_URL');
+ const { res, html } = await invoke(`?avatar=${AVATAR_ID}`);
+
+ expect(res.statusCode).toBe(200);
+ expect(meta(html, 'fc:frame:button:1:target')).toBe(
+ `https://three.ws/walk?avatar=${AVATAR_ID}`,
+ );
+ expect(meta(html, 'og:title')).toBe('Walk your avatar on three.ws');
+ });
+
+ it('gives the two frame buttons distinct destinations', async () => {
+ const { html } = await invoke('');
+ expect(meta(html, 'fc:frame:button:1:target')).toBe('https://three.ws/walk');
+ expect(meta(html, 'fc:frame:button:2:target')).toBe('https://three.ws/create');
+ });
+
+ it('rejects a non-GET method with a JSON 405', async () => {
+ const { res, html } = await invoke('', { method: 'POST' });
+ expect(res.statusCode).toBe(405);
+ expect(res.getHeader('allow')).toBe('GET, HEAD');
+ expect(JSON.parse(html).error).toBe('method_not_allowed');
+ expect(getAvatar).not.toHaveBeenCalled();
+ });
+
+ it('escapes a hostile handle instead of breaking out of the meta attribute', async () => {
+ const { html } = await invoke('?handle=%22%3E%3Cscript%3Ealert(1)%3C%2Fscript%3E');
+ expect(html).not.toContain('<script>alert(1)</script>');
+ expect(meta(html, 'og:title')).toBe(
+ 'Walk @"><script>alert(1)</script>\'s avatar on three.ws',
+ );
+ });
+});
diff --git a/tests/api/providers-meshy.test.js b/tests/api/providers-meshy.test.js
new file mode 100644
index 000000000..8f13dd937
--- /dev/null
+++ b/tests/api/providers-meshy.test.js
@@ -0,0 +1,248 @@
+// Meshy BYOK provider (api/_providers/meshy.js) — wire contract + failure paths.
+//
+// Meshy backs two forge paths on two different API versions:
+// text→geometry POST /openapi/v2/text-to-3d (mode "preview", no intermediate image)
+// image→3D POST /openapi/v1/image-to-3d (native geometry + PBR)
+// Both are async: submit returns a task id, status polls the matching GET route.
+//
+// global fetch is stubbed to model Meshy's real wire protocol (verified against
+// their published API shapes); no network and no mocked product data.
+
+import { describe, it, expect, vi, afterEach } from 'vitest';
+import { createMeshyProvider } from '../../api/_providers/meshy.js';
+
+const ORIGINAL_FETCH = globalThis.fetch;
+afterEach(() => {
+ globalThis.fetch = ORIGINAL_FETCH;
+ vi.restoreAllMocks();
+});
+
+const TIER = { id: 'standard', polycount: 30_000, pbr: false, hd: false };
+
+describe('meshy provider — construction', () => {
+ it('refuses to construct without an API key', () => {
+ expect(() => createMeshyProvider('')).toThrowError(/key is required/i);
+ try {
+ createMeshyProvider(null);
+ } catch (err) {
+ expect(err.code).toBe('missing_key');
+ }
+ });
+});
+
+describe('meshy provider — text→geometry submit', () => {
+ it('posts the v2 preview body and returns the text-to-3d poll handle', async () => {
+ let captured;
+ globalThis.fetch = vi.fn(async (url, opts) => {
+ captured = { url: String(url), body: JSON.parse(opts.body), headers: opts.headers };
+ return { ok: true, status: 200, json: async () => ({ result: 'task-abc' }) };
+ });
+
+ const provider = createMeshyProvider('msy_test');
+ const out = await provider.textToGeometry({ prompt: 'a brass telescope', tier: TIER });
+
+ expect(captured.url).toBe('https://api.meshy.ai/openapi/v2/text-to-3d');
+ expect(captured.headers.authorization).toBe('Bearer msy_test');
+ expect(captured.body.mode).toBe('preview');
+ expect(captured.body.prompt).toBe('a brass telescope');
+ expect(captured.body.target_polycount).toBe(30_000);
+ expect(captured.body.target_formats).toEqual(['glb']);
+ expect(out).toEqual({ kind: 'text-to-3d', taskId: 'task-abc' });
+ });
+
+ it('clamps a tier poly budget into Meshy\'s accepted 100–300,000 window', async () => {
+ const bodies = [];
+ globalThis.fetch = vi.fn(async (url, opts) => {
+ bodies.push(JSON.parse(opts.body));
+ return { ok: true, status: 200, json: async () => ({ result: 't' }) };
+ });
+
+ const provider = createMeshyProvider('msy_test');
+ await provider.textToGeometry({ prompt: 'x', tier: { polycount: 5_000_000 } });
+ await provider.textToGeometry({ prompt: 'x', tier: { polycount: 0 } });
+
+ expect(bodies[0].target_polycount).toBe(300_000);
+ expect(bodies[1].target_polycount).toBe(100);
+ });
+});
+
+describe('meshy provider — image→3D submit', () => {
+ it('posts the v1 image body with the tier\'s PBR/HD knobs and an optional texture prompt', async () => {
+ let captured;
+ globalThis.fetch = vi.fn(async (url, opts) => {
+ captured = { url: String(url), body: JSON.parse(opts.body) };
+ // Some Meshy endpoints answer with { id } rather than { result }.
+ return { ok: true, status: 200, json: async () => ({ id: 'img-task-1' }) };
+ });
+
+ const provider = createMeshyProvider('msy_test');
+ const out = await provider.imageTo3d({
+ imageUrl: 'https://cdn.example.com/reference.png',
+ prompt: 'weathered bronze',
+ tier: { id: 'high', polycount: 120_000, pbr: true, hd: true },
+ });
+
+ expect(captured.url).toBe('https://api.meshy.ai/openapi/v1/image-to-3d');
+ expect(captured.body.image_url).toBe('https://cdn.example.com/reference.png');
+ expect(captured.body.enable_pbr).toBe(true);
+ expect(captured.body.hd_texture).toBe(true);
+ expect(captured.body.should_texture).toBe(true);
+ expect(captured.body.texture_prompt).toBe('weathered bronze');
+ expect(out).toEqual({ kind: 'image-to-3d', taskId: 'img-task-1' });
+ });
+
+ it('omits texture_prompt entirely when the caller supplies no prompt', async () => {
+ let body;
+ globalThis.fetch = vi.fn(async (url, opts) => {
+ body = JSON.parse(opts.body);
+ return { ok: true, status: 200, json: async () => ({ result: 't' }) };
+ });
+
+ const provider = createMeshyProvider('msy_test');
+ await provider.imageTo3d({ imageUrl: 'https://cdn.example.com/r.png', tier: TIER });
+ expect('texture_prompt' in body).toBe(false);
+ });
+});
+
+describe('meshy provider — normalized submit errors', () => {
+ const CASES = [
+ { status: 401, code: 'invalid_key', mapped: 401 },
+ { status: 403, code: 'invalid_key', mapped: 401 },
+ { status: 402, code: 'insufficient_credits', mapped: 402 },
+ { status: 429, code: 'rate_limited', mapped: 429 },
+ { status: 500, code: 'provider_error', mapped: 502 },
+ ];
+
+ for (const c of CASES) {
+ it(`maps HTTP ${c.status} → ${c.code}`, async () => {
+ globalThis.fetch = vi.fn(async () => ({
+ ok: c.status < 400,
+ status: c.status,
+ json: async () => ({ message: 'upstream said no' }),
+ }));
+ const provider = createMeshyProvider('msy_test');
+ await expect(provider.textToGeometry({ prompt: 'x', tier: TIER })).rejects.toMatchObject({
+ code: c.code,
+ status: c.mapped,
+ providerStatus: c.status,
+ });
+ });
+ }
+
+ it('maps a network throw to provider_unreachable', async () => {
+ globalThis.fetch = vi.fn(async () => {
+ throw new Error('ECONNRESET');
+ });
+ const provider = createMeshyProvider('msy_test');
+ await expect(provider.imageTo3d({ imageUrl: 'https://x/a.png', tier: TIER })).rejects.toMatchObject({
+ code: 'provider_unreachable',
+ status: 502,
+ });
+ });
+
+ it('rejects an accepted task that carries no id', async () => {
+ globalThis.fetch = vi.fn(async () => ({ ok: true, status: 200, json: async () => ({}) }));
+ const provider = createMeshyProvider('msy_test');
+ await expect(provider.textToGeometry({ prompt: 'x', tier: TIER })).rejects.toMatchObject({
+ code: 'provider_error',
+ status: 502,
+ });
+ });
+});
+
+describe('meshy provider — status polling', () => {
+ it('polls the endpoint matching the task kind and resolves the GLB when SUCCEEDED', async () => {
+ let polled;
+ globalThis.fetch = vi.fn(async (url) => {
+ polled = String(url);
+ return {
+ ok: true,
+ status: 200,
+ json: async () => ({
+ status: 'SUCCEEDED',
+ progress: 100,
+ consumed_credits: 5,
+ model_urls: { glb: 'https://assets.meshy.ai/task-abc/model.glb' },
+ }),
+ };
+ });
+
+ const provider = createMeshyProvider('msy_test');
+ const res = await provider.status({ kind: 'text-to-3d', taskId: 'task-abc' });
+
+ expect(polled).toBe('https://api.meshy.ai/openapi/v2/text-to-3d/task-abc');
+ expect(res.status).toBe('done');
+ expect(res.progress).toBe(100);
+ expect(res.credits).toBe(5);
+ expect(res.resultGlbUrl).toBe('https://assets.meshy.ai/task-abc/model.glb');
+ });
+
+ it('maps PENDING/IN_PROGRESS onto the queued/running states', async () => {
+ const provider = createMeshyProvider('msy_test');
+ for (const [upstream, expected] of [['PENDING', 'queued'], ['IN_PROGRESS', 'running']]) {
+ globalThis.fetch = vi.fn(async () => ({
+ ok: true,
+ status: 200,
+ json: async () => ({ status: upstream, progress: 42 }),
+ }));
+ const res = await provider.status({ kind: 'image-to-3d', taskId: 't' });
+ expect(res.status).toBe(expected);
+ expect(res.progress).toBe(42);
+ }
+ });
+
+ it('surfaces the upstream task error text when Meshy reports FAILED', async () => {
+ globalThis.fetch = vi.fn(async () => ({
+ ok: true,
+ status: 200,
+ json: async () => ({ status: 'FAILED', task_error: { message: 'mesh generation diverged' } }),
+ }));
+ const provider = createMeshyProvider('msy_test');
+ const res = await provider.status({ kind: 'text-to-3d', taskId: 't' });
+ expect(res.status).toBe('failed');
+ expect(res.error).toBe('mesh generation diverged');
+ });
+
+ it('reports failed when a finished task carries no GLB', async () => {
+ globalThis.fetch = vi.fn(async () => ({
+ ok: true,
+ status: 200,
+ json: async () => ({ status: 'SUCCEEDED', model_urls: {} }),
+ }));
+ const provider = createMeshyProvider('msy_test');
+ const res = await provider.status({ kind: 'text-to-3d', taskId: 't' });
+ expect(res.status).toBe('done');
+ expect(res.resultGlbUrl).toBeUndefined();
+ expect(res.error).toMatch(/no GLB/i);
+ });
+
+ it('keeps the job alive on a transient poll failure, but fails on 404', async () => {
+ const provider = createMeshyProvider('msy_test');
+
+ globalThis.fetch = vi.fn(async () => {
+ throw new Error('socket hang up');
+ });
+ const thrown = await provider.status({ kind: 'text-to-3d', taskId: 't' });
+ expect(thrown.status).toBe('running');
+
+ globalThis.fetch = vi.fn(async () => ({ ok: false, status: 503, json: async () => ({}) }));
+ const flaky = await provider.status({ kind: 'text-to-3d', taskId: 't' });
+ expect(flaky.status).toBe('running');
+
+ globalThis.fetch = vi.fn(async () => ({ ok: false, status: 404, json: async () => ({}) }));
+ const gone = await provider.status({ kind: 'text-to-3d', taskId: 't' });
+ expect(gone.status).toBe('failed');
+ expect(gone.error).toMatch(/not found/i);
+ });
+
+ it('fails fast on an unknown task kind without touching the network', async () => {
+ globalThis.fetch = vi.fn(async () => {
+ throw new Error('should not be called');
+ });
+ const provider = createMeshyProvider('msy_test');
+ const res = await provider.status({ kind: 'video-to-3d', taskId: 't' });
+ expect(res.status).toBe('failed');
+ expect(res.error).toMatch(/unknown meshy task kind/i);
+ expect(globalThis.fetch).not.toHaveBeenCalled();
+ });
+});
diff --git a/tests/api/providers-nvidia-cosmos.test.js b/tests/api/providers-nvidia-cosmos.test.js
new file mode 100644
index 000000000..30c18219e
--- /dev/null
+++ b/tests/api/providers-nvidia-cosmos.test.js
@@ -0,0 +1,329 @@
+// NVIDIA Cosmos provider (api/_providers/nvidia-cosmos.js) — the free
+// text→world VIDEO lane behind the platform NVIDIA_API_KEY.
+//
+// Same NVCF async gateway as the TRELLIS provider (202 + NVCF-REQID → poll
+// pexec/status), so the contract under test is: the KServe `command` invoke
+// body, the 202-then-poll loop, the several result shapes the hosted preview
+// ships the MP4 in, the R2 persist, and the normalized error codes callers
+// route a dead lane around on.
+//
+// global fetch is stubbed and R2 is intercepted — no network, no live NVCF
+// spend, and no mocked product data.
+
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+import {
+ createNvidiaCosmosProvider,
+ nvidiaCosmosConfigured,
+} from '../../api/_providers/nvidia-cosmos.js';
+
+const DEFAULT_INVOKE = 'https://ai.api.nvidia.com/v1/cosmos/nvidia/cosmos-predict1-7b';
+const NVCF_STATUS = 'https://api.nvcf.nvidia.com/v2/nvcf/pexec/status';
+
+const ORIGINAL_FETCH = globalThis.fetch;
+const ENV_KEYS = ['NVIDIA_API_KEY', 'NVIDIA_COSMOS_INVOKE_URL'];
+const ORIGINAL_ENV = Object.fromEntries(ENV_KEYS.map((k) => [k, process.env[k]]));
+
+// persistVideo dynamically imports ../_lib/r2.js; intercept it so the decoded
+// MP4 bytes and the returned public URL are assertable without object storage.
+const putObjectMock = vi.fn(async () => ({}));
+const publicUrlMock = vi.fn((key) => `https://three.ws/cdn/${key}`);
+vi.mock('../../api/_lib/r2.js', () => ({
+ putObject: (...args) => putObjectMock(...args),
+ publicUrl: (...args) => publicUrlMock(...args),
+}));
+
+// A base64 blob only counts as inline video above the module's 64-char floor.
+const MP4_BYTES = Buffer.from('x'.repeat(256), 'utf8');
+const MP4_B64 = MP4_BYTES.toString('base64');
+
+function jsonResponse(body, status = 200, headers = {}) {
+ return new Response(JSON.stringify(body), {
+ status,
+ headers: { 'content-type': 'application/json', ...headers },
+ });
+}
+
+beforeEach(() => {
+ process.env.NVIDIA_API_KEY = 'nvapi-test-key';
+ delete process.env.NVIDIA_COSMOS_INVOKE_URL;
+ putObjectMock.mockClear();
+ publicUrlMock.mockClear();
+});
+
+afterEach(() => {
+ globalThis.fetch = ORIGINAL_FETCH;
+ for (const k of ENV_KEYS) {
+ if (ORIGINAL_ENV[k] === undefined) delete process.env[k];
+ else process.env[k] = ORIGINAL_ENV[k];
+ }
+ vi.restoreAllMocks();
+});
+
+describe('nvidia-cosmos provider — configuration', () => {
+ it('reports configured only while NVIDIA_API_KEY is present', () => {
+ expect(nvidiaCosmosConfigured()).toBe(true);
+ delete process.env.NVIDIA_API_KEY;
+ expect(nvidiaCosmosConfigured()).toBe(false);
+ });
+
+ it('refuses to construct without NVIDIA_API_KEY', () => {
+ delete process.env.NVIDIA_API_KEY;
+ expect(() => createNvidiaCosmosProvider()).toThrow(/NVIDIA_API_KEY/);
+ try {
+ createNvidiaCosmosProvider();
+ } catch (err) {
+ expect(err.code).toBe('missing_key');
+ expect(err.status).toBe(503);
+ }
+ });
+});
+
+describe('nvidia-cosmos provider — text→world submit', () => {
+ function stubAccept() {
+ const calls = [];
+ globalThis.fetch = vi.fn(async (url, opts = {}) => {
+ calls.push({ url: String(url), headers: opts.headers || {}, body: JSON.parse(opts.body) });
+ return jsonResponse({}, 202, { 'nvcf-reqid': 'req-world-1' });
+ });
+ return calls;
+ }
+
+ it('builds the KServe text2world command body and returns the poll handle', async () => {
+ const calls = stubAccept();
+ const provider = createNvidiaCosmosProvider();
+ const job = await provider.textToWorld({ prompt: 'a rainy tokyo alley', seed: 11 });
+
+ expect(calls).toHaveLength(1);
+ expect(calls[0].url).toBe(DEFAULT_INVOKE);
+ expect(calls[0].headers.authorization).toBe('Bearer nvapi-test-key');
+ // The gateway must cap its synchronous hold, or a slow render burns our
+ // socket and the pollable request id is lost with it.
+ expect(calls[0].headers['nvcf-poll-seconds']).toBe('30');
+
+ const input = calls[0].body.inputs[0];
+ expect(input.name).toBe('command');
+ expect(input.datatype).toBe('BYTES');
+ const command = input.data[0];
+ expect(command.startsWith('text2world ')).toBe(true);
+ expect(command).toContain('a rainy tokyo alley');
+ // A styleless prompt gets the cinematic suffix so the backdrop is not muted.
+ expect(command).toContain('cinematic lighting');
+ expect(command).toContain('--seed=11');
+
+ expect(job).toEqual({ taskId: 'req-world-1' });
+ });
+
+ it('leaves a prompt that already carries style cues alone and omits an absent seed', async () => {
+ const calls = stubAccept();
+ const provider = createNvidiaCosmosProvider();
+ await provider.textToWorld({ prompt: 'neon skyline at golden hour' });
+
+ const command = calls[0].body.inputs[0].data[0];
+ expect(command).toContain('neon skyline at golden hour');
+ expect(command).not.toContain('cinematic lighting');
+ expect(command).not.toContain('--seed');
+ });
+
+ it('escapes double quotes so the command line stays parseable', async () => {
+ const calls = stubAccept();
+ const provider = createNvidiaCosmosProvider();
+ await provider.textToWorld({ prompt: 'a sign reading "OPEN"' });
+
+ const command = calls[0].body.inputs[0].data[0];
+ expect(command).toContain("a sign reading 'OPEN'");
+ expect(command.match(/"/g)).toHaveLength(2); // only the --prompt="…" wrapper
+ });
+
+ it('persists the MP4 and returns a durable URL when NVCF completes synchronously', async () => {
+ globalThis.fetch = vi.fn(
+ async () =>
+ new Response(MP4_BYTES, { status: 200, headers: { 'content-type': 'video/mp4' } }),
+ );
+
+ const provider = createNvidiaCosmosProvider();
+ const job = await provider.textToWorld({ prompt: 'a desert storm' });
+
+ expect(job.taskId).toBeNull();
+ expect(job.resultVideoUrl).toMatch(/^https:\/\/three\.ws\/cdn\/forge\/cosmos\/.*\.mp4$/);
+ const stored = putObjectMock.mock.calls[0][0];
+ expect(stored.contentType).toBe('video/mp4');
+ expect(Buffer.from(stored.body).equals(MP4_BYTES)).toBe(true);
+ });
+
+ it('falls through to the poll path when a 200 carries a request id but no video', async () => {
+ globalThis.fetch = vi.fn(async () => jsonResponse({ outputs: [] }, 200, { 'nvcf-reqid': 'req-late' }));
+ const provider = createNvidiaCosmosProvider();
+ const job = await provider.textToWorld({ prompt: 'a quiet harbour' });
+ expect(job).toEqual({ taskId: 'req-late' });
+ expect(putObjectMock).not.toHaveBeenCalled();
+ });
+
+ it('errors cleanly when NVCF accepts the job but omits the NVCF-REQID', async () => {
+ globalThis.fetch = vi.fn(async () => jsonResponse({}, 202));
+ const provider = createNvidiaCosmosProvider();
+ await expect(provider.textToWorld({ prompt: 'x' })).rejects.toMatchObject({
+ code: 'provider_error',
+ status: 502,
+ });
+ });
+
+ it('honors NVIDIA_COSMOS_INVOKE_URL so the gateway path moves without a redeploy', async () => {
+ process.env.NVIDIA_COSMOS_INVOKE_URL = 'https://nim.internal.test/v1/cosmos';
+ const calls = stubAccept();
+ const provider = createNvidiaCosmosProvider();
+ await provider.textToWorld({ prompt: 'x' });
+ expect(calls[0].url).toBe('https://nim.internal.test/v1/cosmos');
+ });
+});
+
+describe('nvidia-cosmos provider — normalized submit errors', () => {
+ const CASES = [
+ { status: 401, code: 'invalid_key', mapped: 401 },
+ { status: 403, code: 'invalid_key', mapped: 401 },
+ { status: 402, code: 'insufficient_credits', mapped: 402 },
+ { status: 429, code: 'rate_limited', mapped: 429 },
+ { status: 400, code: 'provider_error', mapped: 502 },
+ ];
+
+ for (const c of CASES) {
+ it(`maps HTTP ${c.status} → ${c.code}`, async () => {
+ globalThis.fetch = vi.fn(async () => jsonResponse({ detail: 'upstream said no' }, c.status));
+ const provider = createNvidiaCosmosProvider();
+ await expect(provider.textToWorld({ prompt: 'x' })).rejects.toMatchObject({
+ code: c.code,
+ status: c.mapped,
+ providerStatus: c.status,
+ });
+ });
+ }
+
+ it('attaches retryAfter (seconds) from a 429 Retry-After header', async () => {
+ globalThis.fetch = vi.fn(async () =>
+ jsonResponse({ detail: 'slow down' }, 429, { 'retry-after': '9' }),
+ );
+ const provider = createNvidiaCosmosProvider();
+ await expect(provider.textToWorld({ prompt: 'x' })).rejects.toMatchObject({
+ code: 'rate_limited',
+ retryAfter: 9,
+ });
+ });
+
+ it('treats a submit timeout as terminal instead of stacking another full window', async () => {
+ globalThis.fetch = vi.fn(async () => {
+ throw Object.assign(new Error('The operation was aborted due to timeout'), {
+ name: 'TimeoutError',
+ });
+ });
+ const provider = createNvidiaCosmosProvider();
+ await expect(provider.textToWorld({ prompt: 'x' })).rejects.toMatchObject({
+ code: 'provider_unreachable',
+ status: 502,
+ });
+ expect(globalThis.fetch).toHaveBeenCalledTimes(1);
+ });
+
+ it('retries once through a transient gateway 503 and then succeeds', async () => {
+ let attempt = 0;
+ globalThis.fetch = vi.fn(async () => {
+ attempt += 1;
+ if (attempt === 1) return new Response('cold start', { status: 503 });
+ return jsonResponse({}, 202, { 'nvcf-reqid': 'req-warm' });
+ });
+ const provider = createNvidiaCosmosProvider();
+ const job = await provider.textToWorld({ prompt: 'x' });
+ expect(attempt).toBe(2);
+ expect(job).toEqual({ taskId: 'req-warm' });
+ });
+});
+
+describe('nvidia-cosmos provider — 202-then-poll loop', () => {
+ it('reports running while NVCF returns 202', async () => {
+ globalThis.fetch = vi.fn(async (url) => {
+ expect(String(url)).toBe(`${NVCF_STATUS}/req-world-1`);
+ return new Response(null, { status: 202 });
+ });
+ const provider = createNvidiaCosmosProvider();
+ expect(await provider.status({ taskId: 'req-world-1' })).toEqual({ status: 'running' });
+ });
+
+ it('decodes the KServe base64 output, persists it, and reports done', async () => {
+ globalThis.fetch = vi.fn(async () =>
+ jsonResponse({ outputs: [{ name: 'video', datatype: 'BYTES', data: [MP4_B64] }] }),
+ );
+ const provider = createNvidiaCosmosProvider();
+ const res = await provider.status({ taskId: 'req-world-1' });
+
+ expect(res.status).toBe('done');
+ expect(res.resultVideoUrl).toMatch(/^https:\/\/three\.ws\/cdn\/forge\/cosmos\/.*\.mp4$/);
+ expect(Buffer.from(putObjectMock.mock.calls[0][0].body).equals(MP4_BYTES)).toBe(true);
+ });
+
+ it('fetches an artifact URL result and persists those bytes instead', async () => {
+ const cdn = 'https://assets.nvidia.test/cosmos/world.mp4';
+ globalThis.fetch = vi.fn(async (url) => {
+ if (String(url) === cdn) {
+ return new Response(MP4_BYTES, { status: 200, headers: { 'content-type': 'video/mp4' } });
+ }
+ return jsonResponse({ artifacts: [{ url: cdn }] });
+ });
+ const provider = createNvidiaCosmosProvider();
+ const res = await provider.status({ taskId: 'req-world-1' });
+
+ expect(res.status).toBe('done');
+ expect(Buffer.from(putObjectMock.mock.calls[0][0].body).equals(MP4_BYTES)).toBe(true);
+ });
+
+ it('reports failed when a finished poll carries no recognizable video', async () => {
+ vi.spyOn(console, 'warn').mockImplementation(() => {});
+ globalThis.fetch = vi.fn(async () => jsonResponse({ status: 'complete' }));
+ const provider = createNvidiaCosmosProvider();
+ const res = await provider.status({ taskId: 'req-world-1' });
+ expect(res.status).toBe('failed');
+ expect(res.error).toMatch(/no video/i);
+ expect(putObjectMock).not.toHaveBeenCalled();
+ });
+
+ it('reports failed when the persist throws mid-poll', async () => {
+ putObjectMock.mockRejectedValueOnce(new Error('bucket unreachable'));
+ globalThis.fetch = vi.fn(async () => jsonResponse({ b64_video: MP4_B64 }));
+ const provider = createNvidiaCosmosProvider();
+ const res = await provider.status({ taskId: 'req-world-1' });
+ expect(res.status).toBe('failed');
+ expect(res.error).toMatch(/failed to persist video: bucket unreachable/);
+ });
+
+ it('fails terminally on 401/404 but keeps polling on 429 and 5xx', async () => {
+ const provider = createNvidiaCosmosProvider();
+
+ for (const status of [401, 403, 404]) {
+ globalThis.fetch = vi.fn(async () => new Response(null, { status }));
+ expect((await provider.status({ taskId: 't' })).status, `status ${status}`).toBe('failed');
+ }
+ for (const status of [429, 500, 503]) {
+ globalThis.fetch = vi.fn(async () => new Response(null, { status }));
+ expect((await provider.status({ taskId: 't' })).status, `status ${status}`).toBe('running');
+ }
+ });
+
+ it('keeps the job alive on a poll network throw', async () => {
+ globalThis.fetch = vi.fn(async () => {
+ throw new Error('socket hang up');
+ });
+ const provider = createNvidiaCosmosProvider();
+ const res = await provider.status({ taskId: 't' });
+ expect(res.status).toBe('running');
+ expect(res.error).toMatch(/poll failed: socket hang up/);
+ });
+
+ it('fails fast when asked to poll with no request id', async () => {
+ globalThis.fetch = vi.fn(async () => {
+ throw new Error('should not be called');
+ });
+ const provider = createNvidiaCosmosProvider();
+ expect(await provider.status({})).toEqual({
+ status: 'failed',
+ error: 'missing NVCF request id',
+ });
+ expect(globalThis.fetch).not.toHaveBeenCalled();
+ });
+});
diff --git a/tests/api/vertex-imagen.test.js b/tests/api/vertex-imagen.test.js
index 83e164972..80008e2c7 100644
--- a/tests/api/vertex-imagen.test.js
+++ b/tests/api/vertex-imagen.test.js
@@ -17,6 +17,12 @@ vi.mock('../../api/_lib/gcp-auth.js', () => ({
getGcpAccessToken: vi.fn(async () => 'fake-access-token'),
}));
+// The edit lane decodes caller-supplied source/mask URLs through the SSRF guard.
+// Mocking it lets the tests assert that BOTH images take the guarded path (a bare
+// fetch on the mask was a live SSRF hole) without reaching the network.
+const { safeFetch } = vi.hoisted(() => ({ safeFetch: vi.fn() }));
+vi.mock('../../api/_lib/ssrf-guard.js', () => ({ fetchSafePublicUrl: safeFetch }));
+
import { generateImage, editImage, isConfigured } from '../../api/_mcp3d/vertex-imagen.js';
const ORIGINAL_FETCH = globalThis.fetch;
@@ -185,4 +191,68 @@ describe('vertex-imagen — editImage routing', () => {
expect(body.contents[0].parts[1].inlineData.data).toBe(Buffer.from('source').toString('base64'));
expect(result.model).toBe('vertex-ai/gemini-2.5-flash-image');
});
+
+ it('declares the source image its real mime type, not a hardcoded PNG', async () => {
+ const calls = stubFetch(() => geminiImageResponse());
+ await editImage(`data:image/jpeg;base64,${Buffer.from('jpg-source').toString('base64')}`, 'rotate it');
+ expect(calls[0].body.contents[0].parts[1].inlineData.mimeType).toBe('image/jpeg');
+ });
+
+ it('carries the fetched content-type through for an http(s) source', async () => {
+ safeFetch.mockResolvedValueOnce(
+ new Response(Buffer.from('webp-bytes'), { status: 200, headers: { 'content-type': 'image/webp' } }),
+ );
+ const calls = stubFetch(() => geminiImageResponse());
+ await editImage('https://cdn.example.com/ref.webp', 'rotate it');
+
+ expect(safeFetch).toHaveBeenCalledWith('https://cdn.example.com/ref.webp', expect.objectContaining({ signal: expect.anything() }));
+ const part = calls[0].body.contents[0].parts[1].inlineData;
+ expect(part.mimeType).toBe('image/webp');
+ expect(part.data).toBe(Buffer.from('webp-bytes').toString('base64'));
+ });
+
+ it('rejects a non-base64 data: URI instead of forwarding garbage to Vertex', async () => {
+ const calls = stubFetch(() => geminiImageResponse());
+ await expect(editImage('data:image/svg+xml,%3Csvg/%3E', 'x')).rejects.toMatchObject({
+ code: 'bad_source_image',
+ });
+ expect(calls).toHaveLength(0);
+ });
+
+ it('surfaces an unreachable source image instead of editing an error body', async () => {
+ safeFetch.mockResolvedValueOnce(new Response('nope', { status: 404 }));
+ const calls = stubFetch(() => geminiImageResponse());
+ await expect(editImage('https://cdn.example.com/gone.png', 'x')).rejects.toThrow(/upstream 404/);
+ expect(calls).toHaveLength(0);
+ });
+
+ it('refuses a source image past the inline size cap', async () => {
+ safeFetch.mockResolvedValueOnce(
+ new Response('x', { status: 200, headers: { 'content-type': 'image/png', 'content-length': String(64 * 1024 * 1024) } }),
+ );
+ stubFetch(() => geminiImageResponse());
+ await expect(editImage('https://cdn.example.com/huge.png', 'x')).rejects.toMatchObject({
+ code: 'source_image_too_large',
+ });
+ });
+
+ it('routes the legacy :predict mask through the SSRF guard, not a bare fetch', async () => {
+ process.env.VERTEX_IMAGEN_EDIT_MODEL = 'imagen-3.0-capability-001';
+ safeFetch.mockResolvedValueOnce(
+ new Response(Buffer.from('mask-bytes'), { status: 200, headers: { 'content-type': 'image/png' } }),
+ );
+ const calls = stubFetch(() => imagenPredictResponse());
+ const src = `data:image/png;base64,${Buffer.from('source').toString('base64')}`;
+ await editImage(src, 'inpaint', { maskUrl: 'https://cdn.example.com/mask.png' });
+
+ // The only guarded fetch is the mask (the source is an inline data: URI),
+ // and the raw fetch stub saw the Vertex call alone.
+ expect(safeFetch).toHaveBeenCalledTimes(1);
+ expect(safeFetch.mock.calls[0][0]).toBe('https://cdn.example.com/mask.png');
+ expect(calls).toHaveLength(1);
+ expect(calls[0].url).toContain(':predict');
+ const instance = calls[0].body.instances[0];
+ expect(instance.editConfig.editMode).toBe('inpainting-insert');
+ expect(instance.mask.image.bytesBase64Encoded).toBe(Buffer.from('mask-bytes').toString('base64'));
+ });
});