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.

feat(forge): realism routing, quality gate, and reference-image pipeline updates

nirholas0540437c08a4
diff --git a/api/_lib/forge-quality-gate.js b/api/_lib/forge-quality-gate.js
index 0894faf25..ea43b171a 100644
--- a/api/_lib/forge-quality-gate.js
+++ b/api/_lib/forge-quality-gate.js
@@ -1,4 +1,4 @@
-// Forge realism / quality gate — the vision-model half of "raise the floor".
+// Forge realism / quality gate - the vision-model half of "raise the floor".
//
// glb-quality.js (scoreGlbQuality) answers the CHEAP, deterministic question
// from the glTF JSON chunk alone: is this a valid, dense, textured mesh, or a
@@ -21,8 +21,8 @@
// "ship what we have".
//
// ── Provider order ────────────────────────────────────────────────────────────
-// 1. Vertex Gemini (gemini-2.5-flash) — the intended lane, bills GCP credits.
-// 2. Platform vision chain (describeImageJson: free NVIDIA NIM VLMs) — used
+// 1. Vertex Gemini (gemini-2.5-flash) - the intended lane, bills GCP credits.
+// 2. Platform vision chain (describeImageJson: free NVIDIA NIM VLMs) - used
// when Vertex is unconfigured or errors, so the gate still functions off the
// free lanes rather than silently disabling itself.
// 3. Neither available → fail-open pass with qa_available:false.
@@ -128,22 +128,30 @@ function rubricPrompt(subject, prompt) {
? `The model was generated from this request: "${String(prompt).slice(0, 400)}".`
: 'No source prompt was provided.';
return [
- 'You are a strict quality inspector for an AI 3D-model generator. You are shown a render of ONE generated 3D model.',
+ 'You are a quality inspector for an AI 3D-model generator (text-to-3D). You are shown a render of ONE generated 3D model.',
promptLine,
`This model is a ${subject}. For this subject, a good result shows: ${rule.cues}.`,
'',
- 'OUR BAR is photoreal: the render should look like a real photograph of a real physical object or being, not a video-game asset, not a plastic toy, not a clay sculpt.',
+ 'Your job is to RAISE THE FLOOR: catch and reject genuinely broken output while passing clean, complete, correctly-proportioned models. Photorealism is the aspiration, but do NOT hold generated 3D assets to the standard of a literal photograph. A clean, complete model of the correct subject is GOOD even if its materials look slightly matte or game-ready.',
'',
- 'Reject (low score) any of these failure modes if present: blobby/melted/undefined geometry; a plastic or toy-like look when the subject should be real; incomplete or partial mesh (missing parts, holes, cut-off body); duplicated or fused parts (two heads, extra limbs, merged copies); floating disconnected fragments; garbled or smeared textures; flat untextured gray/white surfaces; wildly wrong proportions.',
+ 'IMPORTANT: the render uses fixed studio lighting on a plain gray backdrop, and the subject may look dark. Do NOT lower the score for the render\'s exposure, brightness, shadows, or background. If the geometry and proportions are correct and complete, that alone earns a passing score even when fine surface detail is hard to see.',
'',
- 'Reply with ONLY this JSON object and nothing else:',
+ 'Score the OVERALL quality on this calibrated 0-100 scale:',
+ ' 85-100 = excellent: complete, clean, correct proportions, convincingly real materials.',
+ ' 65-84 = good: complete, correct subject and proportions, decent materials (may be slightly matte or low-detail). THIS IS A PASS.',
+ ' 45-64 = borderline: recognizable and mostly complete but noticeably coarse, or missing a requested part, or a plastic-toy look on something that should be real.',
+ ' 20-44 = poor: badly wrong proportions, largely incomplete, or unrecognizable as the intended subject.',
+ ' 0-19 = broken: a blob, melted or fused mass, duplicated parts, floating disconnected fragments, or an unrecognizable mess.',
+ 'Reserve scores under 30 for genuinely broken output. A complete, correctly-shaped object of the right subject should score 65 or higher.',
+ '',
+ 'Reply with ONLY this JSON object and nothing else. Keep "reason" under 30 words and "retry_hint" under 15 words:',
'{',
- ' "score": <int 0-100, overall how photoreal and correct this is>,',
+ ' "score": <int 0-100, overall quality on the calibrated scale above>,',
' "realism": <int 0-100, how photographic vs toy/plastic/CG the materials and shading look>,',
' "completeness": <int 0-100, how complete and single-subject the geometry is (100 = one whole subject, low = missing/partial/duplicated/fragmented)>,',
' "is_photoreal": <true|false>,',
' "subject_detected": "<what you actually see>",',
- ' "defects": [<zero or more short tags from: blob, melted, plastic, toy, incomplete, partial, holes, duplicated, fused, extra_limbs, floating_fragments, garbled_texture, untextured, wrong_proportions, low_detail>],',
+ ' "defects": [<zero or more short tags, ONLY for issues actually present, from: blob, melted, plastic, toy, incomplete, partial, holes, duplicated, fused, extra_limbs, floating_fragments, garbled_texture, untextured, wrong_proportions, low_detail>],',
' "reason": "<one concrete sentence on the main quality issue, or why it is good>",',
' "retry_hint": "<one short instruction to improve a regeneration, or empty string if it is already good>"',
'}',
@@ -175,7 +183,7 @@ function assertSafeUrl(rawUrl) {
return url;
}
-// Fetch an image URL and return { base64, mimeType }. Guarded + size-capped.
+// Fetch an image URL and return { imageBase64, mimeType }. Guarded + size-capped.
async function fetchImageBase64(rawUrl, timeoutMs) {
assertSafeUrl(rawUrl);
const res = await fetch(rawUrl, { signal: AbortSignal.timeout(timeoutMs) });
@@ -183,22 +191,26 @@ async function fetchImageBase64(rawUrl, timeoutMs) {
const ct = (res.headers.get('content-type') || 'image/png').split(';')[0].trim();
const buf = Buffer.from(await res.arrayBuffer());
if (buf.byteLength > 16 * 1024 * 1024) throw new Error('render image exceeds 16 MB');
- return { base64: buf.toString('base64'), mimeType: ct.startsWith('image/') ? ct : 'image/png' };
+ return { imageBase64: buf.toString('base64'), mimeType: ct.startsWith('image/') ? ct : 'image/png' };
}
-// Render a GLB to a PNG and return { base64, mimeType }. Uses the shared headless
-// pipeline (avatar-render.js) with a full-body framing on a neutral dark
-// background so the whole subject is judged, not a cropped portrait.
+// Render a GLB to a PNG and return { imageBase64, mimeType }. Uses the shared
+// headless pipeline (avatar-render.js) with a full-body framing so the whole
+// subject is judged, not a cropped portrait. A neutral mid-gray studio backdrop
+// (not black) gives the vision model contrast against dark subjects - a dark GLB
+// on a dark background reads as "underexposed" and skews the verdict. The
+// pipeline's lighting is fixed, so the rubric explicitly tells the model to judge
+// the mesh, not the render's exposure.
async function renderGlbBase64(glbUrl, size) {
assertSafeUrl(glbUrl);
const { png } = await renderAvatarScene({
glbUrl,
width: size,
height: size,
- background: '#101014',
+ background: '#6a6d75',
scenePreset: SCENE_PRESETS['full-body'],
});
- return { base64: Buffer.from(png).toString('base64'), mimeType: 'image/png' };
+ return { imageBase64: Buffer.from(png).toString('base64'), mimeType: 'image/png' };
}
// Resolve a GCP OAuth bearer token. Primary path is the shared service-account /
@@ -220,7 +232,7 @@ export function vertexQualityConfigured() {
return Boolean(readEnv('GOOGLE_CLOUD_PROJECT'));
}
-// True when the gate can score at all — Vertex OR the free platform vision chain.
+// True when the gate can score at all - Vertex OR the free platform vision chain.
// Use to decide whether to bother rendering (a cheap pre-check the router can run).
export function qualityGateConfigured() {
return vertexQualityConfigured() || visionConfigured();
@@ -246,7 +258,19 @@ async function scoreViaVertex({ imageBase64, mimeType, prompt, subject, timeoutM
],
},
],
- generationConfig: { temperature: 0, responseMimeType: 'application/json', maxOutputTokens: 700 },
+ // thinkingBudget:0 disables gemini-2.5 extended reasoning. It is essential
+ // here: the thinking tokens count against maxOutputTokens but are NOT returned
+ // as text, so on a complex render the model can burn the whole budget thinking
+ // and hit MAX_TOKENS with the JSON reply truncated mid-object (finishReason
+ // MAX_TOKENS at ~49 visible tokens). A deterministic scoring rubric needs no
+ // chain-of-thought, so turning it off makes the reply complete, cheaper, and
+ // faster. temperature:0 for a stable verdict; JSON mime for a clean parse.
+ generationConfig: {
+ temperature: 0,
+ responseMimeType: 'application/json',
+ maxOutputTokens: 800,
+ thinkingConfig: { thinkingBudget: 0 },
+ },
};
const res = await fetch(endpoint, {
@@ -276,7 +300,7 @@ async function scoreViaPlatformVision({ imageBase64, mimeType, prompt, subject,
prompt: rubricPrompt(subject, prompt),
imageBase64,
mimeType,
- maxTokens: 700,
+ maxTokens: 1536,
timeoutMs,
deadlineMs: timeoutMs + 4000,
track: { ...(track || {}), tool: 'api/_lib/forge-quality-gate' },
@@ -284,12 +308,17 @@ async function scoreViaPlatformVision({ imageBase64, mimeType, prompt, subject,
return { json: out.json, provider: out.provider, model: out.model };
}
-// Normalize a raw model reply into the public verdict shape, applying our pass
-// threshold. A model that flags a critical structural defect fails even if it
-// reported a generous score, because those defects are exactly what users must
-// never see.
-const CRITICAL_DEFECTS = new Set(['blob', 'melted', 'incomplete', 'partial', 'holes', 'duplicated', 'fused', 'extra_limbs', 'floating_fragments']);
-
+// The structural-failure floor: below this completeness the mesh is broken
+// (incomplete, duplicated, fragmented) regardless of a generous overall score, so
+// it fails the gate. Env-tunable alongside the pass score.
+const COMPLETENESS_FLOOR = intEnv('FORGE_QUALITY_COMPLETENESS_FLOOR', 40);
+
+// Normalize a raw model reply into the public verdict shape and apply our pass
+// decision. The decision trusts the recalibrated overall score (which already
+// folds in structure and materials) plus a hard completeness floor that catches
+// broken geometry even if the model was generous on the headline number. Defect
+// tags are informational and drive the retry hint; a single over-eager tag does
+// NOT by itself fail an otherwise-complete, well-scored model.
function normalizeVerdict(raw, { subject, provider, model, passScore, renderSource }) {
const score = score100(raw?.score);
const realism = score100(raw?.realism);
@@ -297,13 +326,13 @@ function normalizeVerdict(raw, { subject, provider, model, passScore, renderSour
const defects = Array.isArray(raw?.defects)
? raw.defects.map((d) => String(d).toLowerCase().trim().replace(/\s+/g, '_')).filter(Boolean).slice(0, 12)
: [];
- const hasCritical = defects.some((d) => CRITICAL_DEFECTS.has(d));
const hint = typeof raw?.retry_hint === 'string' ? raw.retry_hint.trim() : '';
- // Pass requires clearing the score threshold AND not carrying a critical
- // structural defect. A null score (unparseable field) fails closed to a retry
- // only if the provider still answered; a total outage is handled upstream by
- // fail-open.
- const pass = score != null && score >= passScore && !hasCritical;
+ // Pass requires clearing the score threshold AND not being structurally broken
+ // (completeness below the floor). A null score (unparseable field) means the
+ // provider answered but malformed - fail closed to a retry rather than pass a
+ // blind result; a total provider/render outage is handled upstream by fail-open.
+ const structurallyBroken = completeness != null && completeness < COMPLETENESS_FLOOR;
+ const pass = score != null && score >= passScore && !structurallyBroken;
return {
pass,
score,
@@ -323,7 +352,7 @@ function normalizeVerdict(raw, { subject, provider, model, passScore, renderSour
}
// A fail-open pass verdict, returned whenever scoring cannot run. The router MUST
-// ship this (qa_available:false) rather than retry — a QA outage is not a quality
+// ship this (qa_available:false) rather than retry - a QA outage is not a quality
// failure of the model.
function failOpen(reason, { subject = 'object', renderSource = 'none' } = {}) {
return {
@@ -360,7 +389,7 @@ function failOpen(reason, { subject = 'object', renderSource = 'none' } = {}) {
* @param {string} [opts.subject] explicit subject category override
* @param {number} [opts.passScore] override the pass threshold
* @param {object} [opts.track] spend-ledger attribution passed to platform vision
- * @returns {Promise<object>} verdict (never throws — fail-open on any error)
+ * @returns {Promise<object>} verdict (never throws - fail-open on any error)
*/
export async function runQualityGate({
glbUrl = null,
@@ -384,7 +413,7 @@ export async function runQualityGate({
try {
if (renderBase64) {
const m = String(renderBase64).match(/^data:(image\/[a-z+]+);base64,(.*)$/i);
- image = { base64: m ? m[2] : String(renderBase64).replace(/^data:[^,]*,/, ''), mimeType: m ? m[1].toLowerCase() : mimeType };
+ image = { imageBase64: m ? m[2] : String(renderBase64).replace(/^data:[^,]*,/, ''), mimeType: m ? m[1].toLowerCase() : mimeType };
renderSource = 'provided_base64';
} else if (renderUrl) {
image = await fetchImageBase64(renderUrl, QUALITY_GATE_DEFAULTS.timeoutMs);
@@ -396,7 +425,7 @@ export async function runQualityGate({
return failOpen('no glbUrl, renderUrl, or renderBase64 supplied', { subject: subj });
}
} catch (e) {
- // A render / fetch failure is a QA outage, not a model failure — fail open.
+ // A render / fetch failure is a QA outage, not a model failure - fail open.
return failOpen(`could not obtain a render: ${e?.message || e}`, { subject: subj });
}
@@ -490,7 +519,7 @@ export function buildRetryDirective(verdict, base = {}) {
const tier = wantsMoreGeometry ? nextTier(base.tier || 'standard') : (base.tier || 'standard');
// Switch to the image path on a structural failure: a reference image grounds
// the reconstruction and cuts blob/duplication failure modes. Leave a non-
- // structural (material-only) failure on its current path — a tighter prompt
+ // structural (material-only) failure on its current path - a tighter prompt
// alone usually fixes plastic/toy looks.
const path = wantsMoreGeometry ? 'image' : (base.path || 'image');
diff --git a/api/_lib/forge-reference-image.js b/api/_lib/forge-reference-image.js
index 7c2020cdd..527d4c4e5 100644
--- a/api/_lib/forge-reference-image.js
+++ b/api/_lib/forge-reference-image.js
@@ -21,7 +21,7 @@
//
// It is ADDITIVE and never a gate: if the Vertex lane is unconfigured or fails
// for any reason, it falls through to the existing reference-image provider
-// (api/_mcp3d/text-to-image.js — NIM FLUX free lane, Vertex Imagen, Replicate
+// (api/_mcp3d/text-to-image.js - NIM FLUX free lane, Vertex Imagen, Replicate
// backstop), so nothing regresses relative to today's behavior.
//
// ── Router seam ──────────────────────────────────────────────────────────────
@@ -34,7 +34,7 @@
// });
//
// The router agent (which owns forge.js) can drop this module in as a direct
-// replacement — the return shape { imageUrl, model } is identical, so nothing
+// replacement - the return shape { imageUrl, model } is identical, so nothing
// else in that function changes:
//
// import { generateReferenceImage } from './_lib/forge-reference-image.js';
@@ -104,8 +104,8 @@ export function buildReferenceInstruction(prompt, negativePrompt) {
const subject = String(prompt || '').trim();
// The instruction never names the downstream use ("for 3D reconstruction"):
// telling an image model its output feeds a reconstructor measurably nudges it
- // toward a CGI/render aesthetic. It only ever describes the desired LOOK — a
- // real studio photograph — and the composition a reconstructor happens to need.
+ // toward a CGI/render aesthetic. It only ever describes the desired LOOK - a
+ // real studio photograph - and the composition a reconstructor happens to need.
const lines = [
'A single photorealistic studio photograph of the following subject, shot on a professional camera.',
`Subject: ${subject}.`,
@@ -213,7 +213,7 @@ async function generateViaVertex({ instruction, aspectRatio }) {
//
// Vertex-first (high-res, reference-tuned), then automatic fallthrough to the
// existing provider chain. Returns { imageUrl, model, lane }. Never throws for a
-// recoverable Vertex issue — only the fallthrough's terminal error surfaces when
+// recoverable Vertex issue - only the fallthrough's terminal error surfaces when
// every lane is exhausted, exactly as textToImage does today.
export async function generateReferenceImage(
prompt,
@@ -233,7 +233,7 @@ export async function generateReferenceImage(
return { imageUrl, model, lane: 'vertex-reference' };
} catch (err) {
// Any Vertex failure (unconfigured token, safety block, throttle, tier
- // change) degrades to the existing chain — the reference image still gets
+ // change) degrades to the existing chain - the reference image still gets
// made, just on the prior path. Warn, don't error.
console.warn(`[forge-reference-image] vertex lane failed, falling through: ${err?.message}`);
}
diff --git a/api/forge-enhance.js b/api/forge-enhance.js
index 14c77f100..13417fa75 100644
--- a/api/forge-enhance.js
+++ b/api/forge-enhance.js
@@ -208,7 +208,7 @@ export function buildSystem(style, subject = 'object') {
? `\n- Apply this target aesthetic to every prompt you write: ${STYLE_PRESETS[style]}.`
: '';
const realismBlock = isRealistic ? DEFAULT_REALISM_BLOCK : '';
- // Subject-specific realism guidance only when the result should look real —
+ // Subject-specific realism guidance only when the result should look real:
// for an opted-in non-real style the subject hint would fight the user's ask.
const subjectBlock =
isRealistic && SUBJECT_REALISM_HINT[subject] ? `\n- ${SUBJECT_REALISM_HINT[subject]}` : '';
@@ -222,14 +222,14 @@ A great prompt for this pipeline describes a SINGLE, SOLID physical subject (an
person/creature) with clear geometry, CENTERED on a plain seamless background as if shot for a \
product or portrait catalog. Rewrite the user's idea following every rule:
- Exactly one subject, centered and fully in frame. If the user named several things, pick the \
-most central one — for a person or character, that means the person themselves, not props \
+most central one; for a person or character, that means the person themselves, not props \
scattered around them.
- Add concrete REAL-WORLD material, surface and color cues that photograph well AND reconstruct \
well, e.g. “brushed aluminium with visible machining marks”, “worn oak with tight grain”, \
“matte ceramic with slight subsurface glow”, “cast iron with rust-speckled patina”, or for a \
person: “weathered tan skin with faint freckles”, “close-cropped grey stubble”, “fine wool knit \
-with visible stitching”. Name the surface micro-detail (grain, weave, pores, brush marks, wear) \
-— it is what makes the reconstruction bake dense, clean geometry and a convincing, true-to-life \
+with visible stitching”. Name the surface micro-detail (grain, weave, pores, brush marks, wear): \
+it is what makes the reconstruction bake dense, clean geometry and a convincing, true-to-life \
texture rather than a smooth plastic one.
- Prefer opaque, solid materials (metal, wood, stone, ceramic, hard plastic, skin, hair, cloth). \
AVOID transparent, translucent, or mirror-reflective surfaces (glass, crystal, mirror, water) — \
@@ -335,7 +335,7 @@ export default wrap(async (req, res) => {
const userPrompt = raw.slice(0, MAX_IN);
let result;
- // Preferred lane: Vertex Gemini on GCP credits for a higher-quality rewrite —
+ // Preferred lane: Vertex Gemini on GCP credits for a higher-quality rewrite,
// but only when the caller did not opt into the Nemotron lane, and always with
// automatic fallthrough to the free-first chain below. A Vertex failure here is
// swallowed so it can never regress the endpoint.
diff --git a/api/forge-quality-check.js b/api/forge-quality-check.js
index a8bc7c9de..98cf041c7 100644
--- a/api/forge-quality-check.js
+++ b/api/forge-quality-check.js
@@ -1,9 +1,9 @@
-// POST /api/forge-quality-check — score a generated 3D model's realism / quality.
+// POST /api/forge-quality-check - score a generated 3D model's realism / quality.
//
// A thin HTTP surface over the reusable gate in api/_lib/forge-quality-gate.js.
// All provider policy (Vertex Gemini first, free NVIDIA NIM vision backup),
// rendering, the subject-aware rubric, fail-open behavior, and the retry-directive
-// logic live in the lib — this file only reads the request, meters it, and shapes
+// logic live in the lib - this file only reads the request, meters it, and shapes
// the response. The generation router (api/forge.js) imports the lib directly; this
// endpoint exists so a client, an external agent, or an ops probe can score any
// GLB (or an existing render) on demand.
@@ -20,7 +20,7 @@
// buildRetryDirective() object (or null). A GET returns a capability probe.
//
// Fail-open: a scoring/render/provider outage returns 200 with
-// verdict.qa_available:false and verdict.pass:true — the gate never blocks a
+// verdict.qa_available:false and verdict.pass:true - the gate never blocks a
// generation, and neither does this endpoint.
import { cors, method, readJson, error, json, wrap, rateLimited } from './_lib/http.js';
@@ -43,7 +43,7 @@ export default wrap(async function handler(req, res) {
if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;
if (!method(req, res, ['GET', 'POST'])) return;
- // Capability probe — lets a UI decide whether to surface a "check quality"
+ // Capability probe - lets a UI decide whether to surface a "check quality"
// affordance, and reports which lane will serve.
if (req.method === 'GET' || req.method === 'HEAD') {
return json(
diff --git a/api/forge.js b/api/forge.js
index aedf4ce9c..9aefa9c0d 100644
--- a/api/forge.js
+++ b/api/forge.js
@@ -360,7 +360,7 @@ function readForgeEnv(name) {
// falls back to the standing text→image provider (the FLUX/Imagen/NIM chain) when
// the module is absent or Vertex is unavailable. Returns { imageUrl, model } —
// exactly textToImage()'s shape — so the call site is a drop-in swap.
-async function seedReferenceImage({ prompt, aspect, seed, skipNim }) {
+export async function seedReferenceImage({ prompt, aspect, seed, skipNim }) {
if (readForgeEnv('FORGE_REFERENCE_IMAGE') !== 'off') {
try {
const mod = await import('./_lib/forge-reference-image.js');
@@ -368,19 +368,20 @@ async function seedReferenceImage({ prompt, aspect, seed, skipNim }) {
mod.generateReferenceImage ||
mod.reconstructionReferenceImage ||
mod.photorealReferenceImage ||
- mod.referenceImageForPrompt ||
(typeof mod.default === 'function' ? mod.default : null);
if (typeof fn === 'function') {
- const out = await fn({ prompt, aspect, aspectRatio: aspect, seed, skipNim });
- const imageUrl =
- (out && (out.imageUrl || out.image_url || out.url)) ||
- (typeof out === 'string' ? out : null);
+ // Positional signature: (prompt, { aspectRatio, seed, skipNim }). The module
+ // itself falls through to the standing text→image provider on a Vertex
+ // failure, so a returned result already reflects the best available lane.
+ const out = await fn(prompt, { aspectRatio: aspect, seed, skipNim });
+ const imageUrl = out && (out.imageUrl || out.image_url || out.url);
if (imageUrl) {
- return { imageUrl, model: (out && (out.model || out.provider)) || 'vertex-reference', referenceModule: true };
+ return { imageUrl, model: out.model || 'vertex-reference', referenceModule: true };
}
}
} catch (err) {
- // Module not landed yet, or Vertex down — fall through to the standing lane.
+ // Module not landed yet, or both Vertex AND its internal fallthrough failed.
+ // Make one more standing-provider attempt below so this path never dead-ends.
console.warn(`[forge] reference-image module unavailable, using standing provider: ${err?.message || err}`);
}
}
@@ -392,11 +393,11 @@ async function seedReferenceImage({ prompt, aspect, seed, skipNim }) {
// vision-QA latency, so the free draft/standard default lane is left untouched),
// 'all' (score every tier), or 'off'. Env-tunable so ops widen/disable with no
// code change.
-function qualityGateScope() {
+export function qualityGateScope() {
const v = (readForgeEnv('FORGE_QUALITY_GATE') || 'high').toLowerCase();
return v === 'all' || v === 'off' ? v : 'high';
}
-function qualityGateAppliesTo(tierId) {
+export function qualityGateAppliesTo(tierId) {
const s = qualityGateScope();
if (s === 'off') return false;
if (s === 'all') return true;
@@ -404,8 +405,10 @@ function qualityGateAppliesTo(tierId) {
}
// Bounded retry cap — default 1, clamped 0..2 so a quality retry can never turn one
// generation into an unbounded credit/latency sink.
-function qualityGateMaxRetries() {
- const n = Number(readForgeEnv('FORGE_QUALITY_GATE_MAX_RETRIES'));
+export function qualityGateMaxRetries() {
+ const raw = readForgeEnv('FORGE_QUALITY_GATE_MAX_RETRIES');
+ if (raw == null) return 1; // unset → default 1 (Number(null) is 0, so guard first)
+ const n = Number(raw);
if (!Number.isFinite(n)) return 1;
return Math.max(0, Math.min(2, Math.floor(n)));
}
@@ -414,34 +417,36 @@ function qualityGateMaxRetries() {
// absent module or a vision outage returns a passing verdict, so scoring can never
// block or fail a delivered model. Returns the module's verdict object
// ({ score, pass, defects, suggested_retry_hint, ... }) or a skipped pass.
-async function scoreQualityGate({ glbUrl, prompt, tier, backend, referenceImageUrl }) {
+export async function scoreQualityGate({ glbUrl, prompt, tier, backend, referenceImageUrl }) {
try {
const mod = await import('./_lib/forge-quality-gate.js');
const fn =
+ mod.runQualityGate ||
mod.scoreForgeQuality ||
mod.scoreGeneration ||
mod.qualityGateScore ||
- mod.gradeGeneration ||
(typeof mod.default === 'function' ? mod.default : null);
if (typeof fn === 'function') {
+ // runQualityGate renders the delivered GLB itself and scores exactly one
+ // view of it; it never throws (fail-open) and returns a verdict carrying
+ // pass / score / defects / suggested_retry_hint / qa_available. Score the
+ // OUTPUT model (glbUrl), never the input reference, so the gate judges what
+ // was actually produced.
const verdict = await fn({
glbUrl,
- glb_url: glbUrl,
prompt: prompt || null,
- tier: tier?.id || tier || null,
- backend: backend || null,
- referenceImageUrl: referenceImageUrl || null,
+ subject: null,
});
if (verdict && typeof verdict === 'object') return verdict;
}
} catch (err) {
console.warn(`[forge] quality-gate scoring unavailable (fail-open pass): ${err?.message || err}`);
}
- return { pass: true, skipped: true };
+ return { pass: true, skipped: true, qa_available: false };
}
// True only for an explicit failing verdict — a skipped/absent gate never retries.
-function qualityGateFailed(verdict) {
+export function qualityGateFailed(verdict) {
return Boolean(verdict) && verdict.skipped !== true && verdict.pass === false;
}
// Numeric quality score used to keep the best result across retries. A passing
@@ -460,7 +465,7 @@ function qualityScoreValue(verdict) {
// the module exposes its own auto-retry helper it owns the loop instead (it holds
// the hint interpretation); either way this is fail-open and never discards a
// delivered model for a worse one. Returns { durable, verdict, retried }.
-async function qualityGateFinalize({ tierId, prompt, backend, referenceImageUrl, durable, regenerate }) {
+async function qualityGateFinalize({ tierId, prompt, path, backend, referenceImageUrl, durable, regenerate }) {
if (!qualityGateAppliesTo(tierId) || !durable?.glbUrl) {
return { durable, verdict: null, retried: false };
}
@@ -470,56 +475,43 @@ async function qualityGateFinalize({ tierId, prompt, backend, referenceImageUrl,
let retried = false;
const maxRetries = qualityGateMaxRetries();
- // Prefer the module's own auto-retry helper when present — it owns the cap +
- // hint interpretation. It receives the verdict, context, the same bounded
- // regenerate closure, and the cap; a returned improved result is adopted.
+ // The module's buildRetryDirective owns the retry decision: it returns the next
+ // adjusted directive ({ prompt, tier, path, attempt }) or null when a retry must
+ // NOT happen (verdict passed, QA outage, or the cap is reached), so it enforces
+ // both the hint (tightened prompt / negative guidance) and the cap. Absent module
+ // falls back to the verdict's suggested_retry_hint under our own env cap.
+ let buildDirective = null;
try {
const mod = await import('./_lib/forge-quality-gate.js');
- const helper =
- mod.autoRetryForQuality || mod.withQualityRetry || mod.runQualityRetry || mod.qualityAutoRetry || null;
- if (typeof helper === 'function' && qualityGateFailed(bestVerdict) && maxRetries > 0) {
- const out = await helper({
- verdict: bestVerdict,
- glbUrl: bestDurable.glbUrl,
- prompt: prompt || null,
- tier: tierId,
- backend,
- referenceImageUrl: referenceImageUrl || null,
- maxRetries,
- regenerate,
- });
- if (out && (out.glbUrl || out.durable)) {
- return {
- durable: out.durable || bestDurable,
- verdict: out.verdict || bestVerdict,
- retried: Boolean(out.retried ?? true),
- };
- }
- }
+ if (typeof mod.buildRetryDirective === 'function') buildDirective = mod.buildRetryDirective;
} catch {
- // No helper / module absent — fall through to the local bounded loop below.
+ // Module absent: the local hint path below drives the (bounded) retry.
}
- let attempts = 0;
- while (qualityGateFailed(bestVerdict) && attempts < maxRetries && typeof regenerate === 'function') {
- attempts += 1;
+ let attempt = 0;
+ while (attempt < maxRetries && typeof regenerate === 'function') {
+ let directive;
+ if (buildDirective) {
+ directive = buildDirective(bestVerdict, { prompt, tier: tierId, path, attempt, maxRetries });
+ if (!directive) break; // module says stop (passed / QA outage / cap reached)
+ } else {
+ if (!qualityGateFailed(bestVerdict)) break;
+ directive = { prompt, hint: bestVerdict?.suggested_retry_hint || null };
+ }
+ attempt += 1;
+ const retryPrompt = directive.prompt || prompt;
let next;
try {
- next = await regenerate({ hint: bestVerdict?.suggested_retry_hint || null });
+ next = await regenerate({ prompt: retryPrompt, hint: directive.hint || bestVerdict?.suggested_retry_hint || null });
} catch (err) {
console.warn(`[forge] quality-gate retry regenerate failed, keeping best result: ${err?.message || err}`);
break;
}
if (!next?.durable?.glbUrl) break;
retried = true;
- const nextVerdict = await scoreQualityGate({
- glbUrl: next.durable.glbUrl,
- prompt,
- tier: tierId,
- backend,
- referenceImageUrl,
- });
+ const nextVerdict = await scoreQualityGate({ glbUrl: next.durable.glbUrl, prompt: retryPrompt, tier: tierId, backend, referenceImageUrl });
const nextScore = qualityScoreValue(nextVerdict);
+ // Keep the higher-scoring result; a passing verdict always wins and ends the loop.
if (nextVerdict?.pass === true || nextScore > bestScore) {
bestDurable = next.durable;
bestVerdict = nextVerdict;
@@ -643,6 +635,42 @@ async function runNvidiaTextLane({ req, res, ip, prompt, aspect, tier, path, opt
}
}
+ // Vision-QA quality gate (High/realism tier by default; env-tunable via
+ // FORGE_QUALITY_GATE). Score the delivered model and, on a failing verdict,
+ // run a bounded best-of retry on this same free lane keeping the higher-
+ // scoring result. Dormant for draft/standard by default, so the free default
+ // lane pays no extra latency. Fail-open end to end.
+ const gated = await qualityGateFinalize({
+ tierId: tier.id,
+ prompt,
+ path,
+ backend: backendId,
+ referenceImageUrl: null,
+ durable,
+ regenerate: async ({ prompt: retryPrompt } = {}) => {
+ const useP = retryPrompt || prompt;
+ const nvr = await loadNvidiaProvider();
+ const r = await nvr.textTo3d({ prompt: useP, tier, seed: opts?.seed ?? undefined });
+ if (r.taskId || !r.resultGlbUrl) return null;
+ const rj = randomUUID().replace(/-/g, '');
+ await createCreation({
+ clientKey, userId: await sessionUserIdFromReq(req), ipHash: hashIp(ip),
+ prompt: useP, aspect, previewImageUrl: null, replicateJobId: rj,
+ textToImageModel: null, viewsRequested: 0, viewsUsed: null, multiview: false,
+ backend: backendId, tier: tier.id, path,
+ });
+ const rd = await materializeCreation({
+ replicateJobId: rj, clientKey, userId: await sessionUserIdFromReq(req),
+ glbUrl: r.resultGlbUrl, quality: true,
+ compress: opts?.compression && opts.compression !== 'none' ? opts.compression : null,
+ });
+ return rd ? { glbUrl: rd.glbUrl, durable: rd } : null;
+ },
+ });
+ if (gated.durable) durable = gated.durable;
+ if (gated.retried) retried = true;
+ const qualityGate = gated.verdict;
+
if (cacheKey && durable?.glbUrl) {
await putCachedForgeResult(cacheKey, {
glb_url: durable.glbUrl,
@@ -661,6 +689,7 @@ async function runNvidiaTextLane({ req, res, ip, prompt, aspect, tier, path, opt
durable: Boolean(durable),
quality: durable?.quality || null,
quality_retried: retried,
+ quality_gate: qualityGate || undefined,
compression: durable?.compression || null,
options: opts?.hasOptions ? summarizeForgeOptions(opts) : undefined,
...provenance,
@@ -880,6 +909,52 @@ async function runHfImageLane({
}
}
+ // Vision-QA quality gate (High/realism tier by default; env-tunable). Bounded
+ // best-of retry on this same free lane. Each retry must claim a free
+ // concurrency slot first, so a busy fleet keeps the first result rather than
+ // starving other callers. Fail-open end to end.
+ const gated = await qualityGateFinalize({
+ tierId: tier.id,
+ prompt,
+ path,
+ backend: backendId,
+ referenceImageUrl: preview,
+ durable,
+ regenerate: async ({ prompt: retryPrompt } = {}) => {
+ const useP = retryPrompt || prompt;
+ const rslot = await acquireBlockingSlot('hf', { max: SCALE_LIMITS.hfConcurrent, ttlMs: SCALE_LIMITS.hfSlotTtlMs });
+ if (!rslot.ok) return null;
+ try {
+ const rs = await provider.submit({
+ mode: 'reconstruct',
+ sourceUrl: imageUrls[0],
+ params: { images: imageUrls, prompt: useP || undefined, seed: opts?.seed ?? undefined },
+ });
+ const rf = await provider.status(rs.extJobId);
+ if (!rf?.resultGlbUrl) return null;
+ const rj = randomUUID().replace(/-/g, '');
+ await createCreation({
+ clientKey, userId: await sessionUserIdFromReq(req), ipHash: hashIp(ip),
+ prompt: useP || (isImageMode ? 'image-to-3d' : ''), aspect,
+ previewImageUrl: preview, replicateJobId: rj,
+ textToImageModel: isImageMode ? null : textToImageModel,
+ viewsRequested: imageUrls.length, viewsUsed: imageUrls.length,
+ multiview: imageUrls.length > 1, backend: backendId, tier: tier.id, path,
+ });
+ const rd = await materializeCreation({
+ replicateJobId: rj, clientKey, userId: await sessionUserIdFromReq(req),
+ glbUrl: rf.resultGlbUrl, quality: true, compress: wantCompress,
+ });
+ return rd ? { glbUrl: rd.glbUrl, durable: rd } : null;
+ } finally {
+ await rslot.release();
+ }
+ },
+ });
+ if (gated.durable) durable = gated.durable;
+ if (gated.retried) retried = true;
+ const qualityGate = gated.verdict;
+
if (cacheKey && !isImageMode && durable?.glbUrl) {
await putCachedForgeResult(cacheKey, {
glb_url: durable.glbUrl,
@@ -898,6 +973,7 @@ async function runHfImageLane({
durable: Boolean(durable),
quality: durable?.quality || null,
quality_retried: retried,
+ quality_gate: qualityGate || undefined,
compression: durable?.compression || null,
options: opts?.hasOptions ? summarizeForgeOptions(opts) : undefined,
mode,
@@ -2683,6 +2759,22 @@ async function pollJob(req, res, jobId) {
quality: durable.quality || null,
});
}
+ // Post-generation vision-QA verdict for the async self-host lanes: the
+ // High/MAX realism path (self-host TRELLIS / Hunyuan3D) completes here.
+ // Tier-scoped (default High only) and fail-open, so draft/standard pay no
+ // scoring latency and a vision outage never withholds the delivered model.
+ // Surfaced so the client can show the score and offer a one-click regenerate
+ // on a failing verdict.
+ let qualityGate;
+ if (durable?.glbUrl && qualityGateAppliesTo(meta?.tier)) {
+ qualityGate = await scoreQualityGate({
+ glbUrl: durable.glbUrl,
+ prompt: meta?.prompt || null,
+ tier: meta?.tier || null,
+ backend: meta?.backend || null,
+ referenceImageUrl: meta?.preview_image_url || null,
+ });
+ }
return json(res, 200, {
job_id: jobId,
creation_id: durable?.id ?? meta?.id ?? null,
@@ -2690,6 +2782,7 @@ async function pollJob(req, res, jobId) {
glb_url: durable?.glbUrl ?? result.resultGlbUrl,
durable: Boolean(durable),
quality: durable?.quality || null,
+ quality_gate: qualityGate || undefined,
compression: durable?.compression || null,
...metaFields,
});
diff --git a/docs/ux-flows/02-forge-text-to-3d.md b/docs/ux-flows/02-forge-text-to-3d.md
index 45a6c22f4..d0799f710 100644
--- a/docs/ux-flows/02-forge-text-to-3d.md
+++ b/docs/ux-flows/02-forge-text-to-3d.md
@@ -70,6 +70,9 @@ Routing facts (from `vercel.json`):
- Payment: `forge-pay.js` → `src/token-pay.js` → `/api/token/quote` + `/api/token/settle` ($THREE)
- Access/tier pass: `/api/three/access` (read) + tier-pass mint (referenced via `attachTierPass`/`getTierPass`)
- Generation engines: FLUX (image) → TRELLIS (mesh) free lane; BYOK Meshy / Tripo / Rodin / Stability / Replicate; Hunyuan3D / TripoSG (sketch). Hosted on NVIDIA NIM / providers; same pipeline exposed to agents over MCP at `/api/mcp-3d`.
+ - **Photoreal reference-image path (the realism lever):** the final mesh reads as real only if the reference image the reconstructor sees is a photoreal, single-subject, plain-seamless-background, evenly-lit photograph. Two pieces drive that:
+ - `POST /api/forge-enhance` (director): rewrites the raw prompt into one centered real-world subject with material + surface micro-detail + neutral studio-lighting cues. It classifies the subject (person / animal / vehicle / food / object) and returns a `subject`-aware `negative_prompt` targeting that class's failure modes (hands/faces for people, wheel-count/panel symmetry for vehicles, plastic-replica sheen for food). It prefers a Vertex Gemini rewrite (GCP credits) and falls through to the free-first LLM chain automatically, so it never hard-depends on Vertex. Response schema is unchanged apart from the additive `subject` field.
+ - `api/_lib/forge-reference-image.js` → `generateReferenceImage(directedPrompt, { aspectRatio, negativePrompt?, seed, skipNim })`: generates the reconstruction reference image on the Vertex Gemini 2.5 Flash Image lane (`imageConfig.imageSize:"2K"`), tuned as a plain-background studio photo, with the director's negatives folded in as natural-language avoidance. Additive with automatic fallthrough to the existing provider chain (`textToImage`: NIM FLUX free → Vertex Imagen → Replicate), returning the same `{ imageUrl, model }` shape. When `negativePrompt` is omitted it derives subject-aware negatives from the prompt itself, so a caller gets them for free. The `api/forge.js` text→3D path can adopt it as a drop-in replacement for its `textToImage(directedPrompt, …)` call.
- 3rd-party viewer: model-viewer 4.0.0 (googleapis CDN).
- **Success state:** A textured **GLB** standing in the in-page `<model-viewer>` (orbit/AR), auto-saved to "Your creations", with a downloadable file and all post-processing/export/embed/share actions enabled. Optional converted formats (OBJ/STL/PLY/USDZ/FBX) and a community showcase entry.
- **Empty / error states:**
diff --git a/pages/forge-embed.html b/pages/forge-embed.html
index 13e51ec94..c03e7ddc3 100644
--- a/pages/forge-embed.html
+++ b/pages/forge-embed.html
@@ -199,6 +199,7 @@
shadow-softness="0.9"
exposure="1.05"
tone-mapping="aces"
+ environment-image="/environments/gallery/env.hdr"
ar
ar-modes="webxr scene-viewer quick-look"
alt="Interactive 3D model forged on three.ws"
diff --git a/pages/forge-studio.html b/pages/forge-studio.html
index eada57c9f..af6d7b4bf 100644
--- a/pages/forge-studio.html
+++ b/pages/forge-studio.html
@@ -3500,6 +3500,7 @@
shadow-softness="0.9"
exposure="1.5"
tone-mapping="aces"
+ environment-image="/environments/gallery/env.hdr"
ar
ar-modes="webxr scene-viewer quick-look"
interaction-prompt="none"
diff --git a/pages/forge.html b/pages/forge.html
index 8daa7443f..534a29480 100644
--- a/pages/forge.html
+++ b/pages/forge.html
@@ -3001,6 +3001,7 @@
shadow-softness="0.9"
exposure="1.5"
tone-mapping="aces"
+ environment-image="/environments/gallery/env.hdr"
ar
ar-modes="webxr scene-viewer quick-look"
interaction-prompt="none"
diff --git a/tests/api/forge-realism-routing.test.js b/tests/api/forge-realism-routing.test.js
new file mode 100644
index 000000000..28cd574ae
--- /dev/null
+++ b/tests/api/forge-realism-routing.test.js
@@ -0,0 +1,191 @@
+// High/MAX realism tier restructure: self-host PBR lanes lead, subject-aware
+// ordering (Hunyuan3D-2.1 for organics, self-host TRELLIS for hard-surface), and
+// a health-gated fallthrough to the free NVIDIA NIM lane so the realism path never
+// dead-ends on a cold GPU worker. Every assertion drives the PURE resolvers with
+// injected env + health maps - no network. The draft/standard free-default lane
+// ordering must stay exactly as it was (no latency regression on the free path).
+
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import {
+ classifyForgeSubject,
+ freeLaneCandidates,
+ resolveBackendId,
+ resolveBackendIdWithHealth,
+ isSelfHostBackend,
+ coldStartSecondsFor,
+ estimateEtaSeconds,
+} from '../../api/_lib/forge-tiers.js';
+
+const LANE_VARS = [
+ 'MODEL_TRELLIS_URL',
+ 'GCP_HUNYUAN3D_URL',
+ 'GCP_TRIPOSG_URL',
+ 'GCP_RECONSTRUCTION_KEY',
+ 'HF_TOKEN',
+ 'NVIDIA_API_KEY',
+ 'REPLICATE_API_TOKEN',
+ 'FORGE_SELFHOST_PRIMARY',
+];
+const saved = {};
+
+function configureAllLanes() {
+ process.env.MODEL_TRELLIS_URL = 'https://trellis.example.run.app';
+ process.env.GCP_HUNYUAN3D_URL = 'https://hunyuan.example.run.app';
+ process.env.GCP_TRIPOSG_URL = 'https://triposg.example.run.app';
+ process.env.GCP_RECONSTRUCTION_KEY = 'secret';
+ process.env.HF_TOKEN = 'hf_test';
+ process.env.NVIDIA_API_KEY = 'nvapi-test';
+}
+
+beforeEach(() => {
+ for (const v of LANE_VARS) {
+ saved[v] = process.env[v];
+ delete process.env[v];
+ }
+});
+afterEach(() => {
+ for (const v of LANE_VARS) {
+ if (saved[v] === undefined) delete process.env[v];
+ else process.env[v] = saved[v];
+ }
+});
+
+describe('classifyForgeSubject', () => {
+ it('classifies people / creatures / organics as organic', () => {
+ expect(classifyForgeSubject('a knight in shining armor')).toBe('organic');
+ expect(classifyForgeSubject('a fluffy cat')).toBe('organic');
+ expect(classifyForgeSubject('portrait of a woman')).toBe('organic');
+ expect(classifyForgeSubject('a fierce dragon')).toBe('organic');
+ });
+ it('classifies hard-surface / mechanical subjects as hardsurface', () => {
+ expect(classifyForgeSubject('a sci-fi drone')).toBe('hardsurface');
+ expect(classifyForgeSubject('a red sports car')).toBe('hardsurface');
+ expect(classifyForgeSubject('a chrome coffee machine')).toBe('hardsurface');
+ });
+ it('returns null for an ambiguous or empty prompt', () => {
+ expect(classifyForgeSubject('a thing')).toBeNull();
+ expect(classifyForgeSubject('')).toBeNull();
+ expect(classifyForgeSubject(null)).toBeNull();
+ });
+ it('prefers organic when a prompt trips both signals', () => {
+ // "knight" (organic) + "armor/mech" (hard-surface) → organic wins (Hunyuan first).
+ expect(classifyForgeSubject('a knight in mecha armor')).toBe('organic');
+ });
+});
+
+describe('High realism tier - self-host lanes lead, NIM is the last free fallthrough', () => {
+ it('text prompt: Hunyuan3D first, self-host TRELLIS next, HF then free NIM last', () => {
+ configureAllLanes();
+ expect(freeLaneCandidates('image', 'high', false)).toEqual([
+ 'hunyuan3d',
+ 'trellis_selfhost',
+ 'huggingface',
+ 'nvidia',
+ ]);
+ });
+
+ it('hard-surface subject hoists self-host TRELLIS ahead of Hunyuan3D', () => {
+ configureAllLanes();
+ expect(freeLaneCandidates('image', 'high', false, 'hardsurface')).toEqual([
+ 'trellis_selfhost',
+ 'hunyuan3d',
+ 'huggingface',
+ 'nvidia',
+ ]);
+ });
+
+ it('organic subject keeps the default Hunyuan3D-first order', () => {
+ configureAllLanes();
+ expect(freeLaneCandidates('image', 'high', false, 'organic')).toEqual([
+ 'hunyuan3d',
+ 'trellis_selfhost',
+ 'huggingface',
+ 'nvidia',
+ ]);
+ });
+
+ it('photo submission at high excludes the text-only NIM lane', () => {
+ configureAllLanes();
+ expect(freeLaneCandidates('image', 'high', true)).toEqual([
+ 'hunyuan3d',
+ 'trellis_selfhost',
+ 'huggingface',
+ ]);
+ expect(freeLaneCandidates('image', 'high', true, 'hardsurface')).toEqual([
+ 'trellis_selfhost',
+ 'hunyuan3d',
+ 'huggingface',
+ ]);
+ });
+
+ it('resolveBackendId picks a self-host lane at high tier', () => {
+ configureAllLanes();
+ expect(resolveBackendId({ path: 'image', tier: 'high', userImages: false })).toBe('hunyuan3d');
+ expect(
+ resolveBackendId({ path: 'image', tier: 'high', userImages: false, subjectClass: 'hardsurface' }),
+ ).toBe('trellis_selfhost');
+ });
+});
+
+describe('High realism tier - health-gated fallthrough to the free NIM lane', () => {
+ it('falls through to NVIDIA NIM when every GPU worker and HF are down', () => {
+ configureAllLanes();
+ const health = { hunyuan3d: 'down', trellis_selfhost: 'down', huggingface: 'down' };
+ expect(
+ resolveBackendIdWithHealth({ path: 'image', tier: 'high', userImages: false, health }),
+ ).toBe('nvidia');
+ });
+
+ it('skips a cold self-host lane for the next healthy self-host lane', () => {
+ configureAllLanes();
+ const health = { hunyuan3d: 'down' };
+ expect(
+ resolveBackendIdWithHealth({ path: 'image', tier: 'high', userImages: false, health }),
+ ).toBe('trellis_selfhost');
+ });
+});
+
+describe('Self-host lane health + cold-start coverage (triposg + hunyuan3d)', () => {
+ it('recognizes triposg and hunyuan3d as self-host lanes (health-probed)', () => {
+ expect(isSelfHostBackend('triposg')).toBe(true);
+ expect(isSelfHostBackend('hunyuan3d')).toBe(true);
+ expect(isSelfHostBackend('trellis_selfhost')).toBe(true);
+ // The external free lanes are not self-host probed.
+ expect(isSelfHostBackend('nvidia')).toBe(false);
+ expect(isSelfHostBackend('huggingface')).toBe(false);
+ });
+
+ it('carries a cold-start budget for both scale-to-zero GPU workers', () => {
+ expect(coldStartSecondsFor('triposg')).toBeGreaterThan(0);
+ expect(coldStartSecondsFor('hunyuan3d')).toBeGreaterThan(0);
+ });
+
+ it('widens the ETA by the cold-start budget when the worker is cold', () => {
+ const warm = estimateEtaSeconds({ backendId: 'hunyuan3d', tier: 'high', cold: false });
+ const cold = estimateEtaSeconds({ backendId: 'hunyuan3d', tier: 'high', cold: true });
+ expect(cold).toBe(warm + coldStartSecondsFor('hunyuan3d'));
+ const tWarm = estimateEtaSeconds({ backendId: 'triposg', tier: 'standard', cold: false });
+ const tCold = estimateEtaSeconds({ backendId: 'triposg', tier: 'standard', cold: true });
+ expect(tCold).toBe(tWarm + coldStartSecondsFor('triposg'));
+ });
+});
+
+describe('Free/default tier is unchanged (no regression)', () => {
+ it('draft text prompt still leads with native NVIDIA NIM', () => {
+ configureAllLanes();
+ expect(freeLaneCandidates('image', 'draft', false)).toEqual([
+ 'nvidia',
+ 'trellis_selfhost',
+ 'hunyuan3d',
+ 'huggingface',
+ ]);
+ });
+
+ it('standard tier ordering is subject-invariant (reorder is high-only)', () => {
+ configureAllLanes();
+ const plain = freeLaneCandidates('image', 'standard', false);
+ expect(freeLaneCandidates('image', 'standard', false, 'hardsurface')).toEqual(plain);
+ expect(freeLaneCandidates('image', 'standard', false, 'organic')).toEqual(plain);
+ expect(plain[0]).toBe('nvidia');
+ });
+});