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): make Refine return the same model at higher quality, not a new one

nirholas80107612473d
diff --git a/api/_lib/forge-scale.js b/api/_lib/forge-scale.js
index b463d906d..0dcffb420 100644
--- a/api/_lib/forge-scale.js
+++ b/api/_lib/forge-scale.js
@@ -34,15 +34,31 @@ const INFLIGHT_TTL_S = 360; // ~ the longest a generation stays pollable end-to-
// normalized (trim + lowercase) and image lists are order-independent so the same
// multi-view set in any order collapses to one key. Truncated to 32 hex chars —
// 128 bits of collision resistance is ample for a 6-minute dedup window.
-export function forgeRequestHash({ path, tier, backend, prompt, images }) {
+//
+// The output-affecting options belong in the fingerprint for the same reason they
+// belong in the result-cache key (forge-cache.js forgeResultCacheKey, which lists
+// exactly these four): two requests are interchangeable only when every input that
+// changes the mesh matches. Leaving them out made `seed` unusable, which is the
+// whole point of a seed. Two submits of one prompt with different seeds are two
+// DIFFERENT models by definition, and the second was being handed the first's job
+// for the rest of the 360s window (the record is not cleared on success), so it
+// came back byte-identical. That also silently defeated Refine, which replays a
+// job's seed one tier up. A null option keeps the key identical to a request that
+// never sent options, so existing callers coalesce exactly as before.
+export function forgeRequestHash({ path, tier, backend, prompt, images, options }) {
const tierId = typeof tier === 'string' ? tier : tier?.id || '';
const imgs = Array.isArray(images) ? images.filter(Boolean).slice().sort() : [];
+ const opt = options || {};
const basis = JSON.stringify([
path || '',
tierId,
backend || '',
String(prompt || '').trim().toLowerCase(),
imgs,
+ opt.seed ?? null,
+ opt.outputFormat || 'glb',
+ opt.textureSize ?? null,
+ opt.targetPolycount ?? null,
]);
return createHash('sha256').update(basis).digest('hex').slice(0, 32);
}
diff --git a/api/forge.js b/api/forge.js
index 03a3bd8e9..5d7586a13 100644
--- a/api/forge.js
+++ b/api/forge.js
@@ -1830,6 +1830,14 @@ async function startJob(req, res) {
// whole FLUX→reconstruct pipeline a second time. Collapses double-clicks and
// viral-prompt bursts to one generation that N clients poll. Skipped for high
// tier (paid/gated per caller) so a payment is never shared across users.
+ // `force_regenerate` has to skip the coalescing read as well as the result
+ // cache read above, or it does not mean what it says: the in-flight record
+ // outlives the generation it points at (TTL only, never cleared on success),
+ // so within that window a "force a fresh run" submit was still handed the
+ // previous job. That is what made the daily smoke test's force_regenerate
+ // leg unable to prove generation was alive, and what stopped a user's Retry
+ // from ever producing a different model. The hash is still COMPUTED so the
+ // fresh job registers under it and later callers can coalesce onto this one.
if (tier.id !== 'high') {
requestHash = forgeRequestHash({
path,
@@ -1837,8 +1845,9 @@ async function startJob(req, res) {
backend: backendId,
prompt,
images: isImageMode ? imageUrls : null,
+ options: opts,
});
- const existing = await coalesceInFlight(requestHash);
+ const existing = forceRegenerate ? null : await coalesceInFlight(requestHash);
if (existing) {
return json(res, 200, {
job_id: existing,
diff --git a/src/forge.js b/src/forge.js
index 185dc1e22..0eb3b1b27 100644
--- a/src/forge.js
+++ b/src/forge.js
@@ -154,7 +154,29 @@ let aspectRatio = '1:1';
let elapsedTimer = null;
let pollAbort = false;
let mode = 'text'; // 'text' | 'image' | 'sketch' — input mode (prompt vs photos vs drawing)
-let lastJob = null; // { prompt, imageUrls } — for retry
+let lastJob = null; // { prompt, imageUrls, seed }: for retry and refine
+
+// Every user-initiated generation is stamped with a random seed, which then
+// rides along on every replay of that same job (Refine, Retry, an automatic
+// lane hop, "Generate anyway"). It is what makes Refine actually refine.
+//
+// Without it, bumping a draft to Standard re-ran the text lane from scratch: a
+// NEW reference image off the same prompt, and therefore a different object.
+// The user asked for "this model, better" and got "another model, better",
+// which is the one thing a refine must never do. /api/forge threads the seed
+// through the reference-image stage as well as reconstruction (api/forge.js
+// seedReferenceImage), so replaying it reproduces the same subject and the tier
+// bump is the only variable that moved.
+//
+// A fresh submit always mints a new one, so "Make another" on the same prompt
+// still explores instead of returning the identical model.
+const SEED_MAX = 2 ** 32 - 1;
+function mintSeed() {
+ if (globalThis.crypto?.getRandomValues) {
+ return globalThis.crypto.getRandomValues(new Uint32Array(1))[0];
+ }
+ return Math.floor(Math.random() * SEED_MAX);
+}
// Automatic engine hops taken for the current submission (lane_failed → switch
// to the first suggested backup and re-run). Budget of 1 per user submit; the
// server's own poll-time failover already walked the async lanes before this.
@@ -1460,7 +1482,7 @@ function forgeHeaders(extra) {
return h;
}
-async function startJob({ prompt, imageUrls, skipValidation, payment }) {
+async function startJob({ prompt, imageUrls, skipValidation, payment, seed }) {
const base = { path: selectedEngine.path, tier: selectedTier, backend: selectedEngine.backend };
const body =
Array.isArray(imageUrls) && imageUrls.length
@@ -1471,6 +1493,9 @@ async function startJob({ prompt, imageUrls, skipValidation, payment }) {
// only — the director rewrites a prompt, and an image submission has
// none to rewrite.
: { prompt, aspect_ratio: aspectRatio, director: true, ...base };
+ // Reproducibility: see mintSeed(). Absent on a job replayed from the gallery,
+ // where the original seed was never recorded, so that path stays as it was.
+ if (Number.isInteger(seed)) body.seed = seed;
// Caller already saw the vision warning and chose to proceed (Consumer 1).
if (skipValidation) body.skip_validation = true;
// Pay-per-use proof: a non-holder who paid $THREE for this High generation
@@ -2810,7 +2835,7 @@ function submit() {
// A fresh user-initiated generation resets the automatic lane-hop budget —
// the single silent hop belongs to one submission, never accumulates.
autoLaneHops = 0;
- if (cfg) run(cfg);
+ if (cfg) run({ ...cfg, seed: mintSeed() });
}
// Options handed to the gate modal / in-place lock so their "Pay per generation"
@@ -2835,7 +2860,7 @@ async function payThenGenerate(pay) {
if (selectedTier !== 'high') selectTier('high');
const result = await payForHighGeneration({ usd });
if (!result?.ok) return; // cancelled or failed — the modal explained why
- run({ ...cfg, payment: { paymentId: result.paymentId, refId: result.refId } });
+ run({ ...cfg, seed: mintSeed(), payment: { paymentId: result.paymentId, refId: result.refId } });
}
// Wiring ----------------------------------------------------------------------
diff --git a/tests/forge-scale.test.js b/tests/forge-scale.test.js
index 485dc5654..0f33ab3e3 100644
--- a/tests/forge-scale.test.js
+++ b/tests/forge-scale.test.js
@@ -57,6 +57,37 @@ describe('forgeRequestHash', () => {
const b = forgeRequestHash({ path: 'image', tier: 'standard', backend: 'trellis', prompt: 'cat' });
expect(a).toBe(b);
});
+
+ // Two submits of one prompt at different seeds are two different models, so
+ // they must never coalesce onto one job. This is what makes `seed` usable at
+ // all, and it is what Refine depends on to replay a job one tier up.
+ it('distinguishes every output-affecting option', () => {
+ const base = { path: 'image', tier: 'standard', backend: 'trellis', prompt: 'cat' };
+ const h = forgeRequestHash(base);
+ expect(forgeRequestHash({ ...base, options: { seed: 1 } })).not.toBe(h);
+ expect(forgeRequestHash({ ...base, options: { seed: 1 } })).not.toBe(
+ forgeRequestHash({ ...base, options: { seed: 2 } }),
+ );
+ expect(forgeRequestHash({ ...base, options: { outputFormat: 'glb-draco' } })).not.toBe(h);
+ expect(forgeRequestHash({ ...base, options: { textureSize: 2048 } })).not.toBe(h);
+ expect(forgeRequestHash({ ...base, options: { targetPolycount: 50_000 } })).not.toBe(h);
+ });
+
+ // Adding the options to the basis must not invalidate the fingerprint for the
+ // callers that never send any: an absent options bag, an empty one, and one
+ // holding only the defaults all describe the same generation.
+ it('keeps the key stable for callers that send no options', () => {
+ const base = { path: 'image', tier: 'standard', backend: 'trellis', prompt: 'cat' };
+ const h = forgeRequestHash(base);
+ expect(forgeRequestHash({ ...base, options: {} })).toBe(h);
+ expect(forgeRequestHash({ ...base, options: null })).toBe(h);
+ expect(
+ forgeRequestHash({
+ ...base,
+ options: { seed: null, outputFormat: 'glb', textureSize: null, targetPolycount: null },
+ }),
+ ).toBe(h);
+ });
});
describe('fail-open behavior without Redis', () => {