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.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(forge): never-dead-end generation — poll-time lane failover + one-click engine switching
nirholas74a59e37b06c
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 1cd057b38..ee67c0dca 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,7 +6,10 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr## 2026-07-16+- **3D generation now switches engines by itself when one fails** — A 3D generation that dies mid-flight no longer dead-ends. The platform now re-runs the same job on the next available engine automatically (up to three backups, free engines first) while your progress bar just keeps going — most failures become invisible. In the rare case every automatic backup is exhausted, the error screen on /forge now offers one-click "Try on …" buttons for the engines still available, so you never have to re-enter your prompt or photos. Avatar tools got the same treatment: a rig step that fails no longer throws away the finished 3D model, and the avatar generator falls back to the platform's own free engines when its primary vendor is down. (`/forge`) `[improvement]`+- **Creation tools now hand off down the pipeline** — Finishing one creation step now offers the next one instead of dropping you at a dead end. A fresh selfie avatar gets a "Turn this into an agent" button that carries the 3D body straight into the agent builder. The agent builder's success screen adds a "Take it further" row: give it a voice, embed it anywhere, put it in a world, or launch its token. And a freshly cloned voice now offers "Add to an agent". Avatar to agent to deploy, with no manual re-navigation. (`/create`) `[improvement]`- **Fewer dead ends in the creation flow** — Every generic "create an agent" button (marketplace, memory tab, search) now points at the guided /create-agent wizard instead of a stale /agent/new link; that route stays reserved for the avatar hand-off it powers. The search page's avatar CTA no longer points at a route that never existed. /scan and /create/selfie (the two photo-to-avatar paths) now cross-link each other, and Build > Start here in the nav leads with "Create anything" straight to the /create hub. (`/create`) `[improvement]`+- **Free 3D generation got a lot more reliable** — Text-to-3D on /forge was intermittently failing with a generic error even though the model had actually finished. The free NVIDIA lane's results are single-collection: two overlapping status checks could race, one collecting the model and the other reporting failure. Status checks are now coordinated, a finished model that a racing check already saved is returned instead of an error, and a genuinely lost result is silently regenerated on the same job. The free community GPU fallback also recovered: one Space reports a broken download address for its finished models, and the fetch now falls back to the address that works. (`/forge`) `[fix]`## 2026-07-15diff --git a/api/_lib/forge-failover.js b/api/_lib/forge-failover.jsnew file mode 100644index 000000000..6805b4d4f--- /dev/null+++ b/api/_lib/forge-failover.js@@ -0,0 +1,196 @@+// Poll-time lane failover for /api/forge generation jobs.+//+// Submit-time failover (api/forge.js startJob) already walks the free-first+// lane chain when a SUBMIT is rejected. But a self-host worker can accept a+// task and then fail it asynchronously — the failure only surfaces on a later+// GET ?job=<id> poll, in a separate invocation that no longer holds the+// request. Before this module, that poll dead-ended: the user got a terminal+// "hit a snag" with the original inputs still sitting in forge_creations.+//+// This module closes that gap in two layers:+// 1. Automatic re-dispatch. The failed poll recovers the original inputs+// (prompt + reference image) from the creation row, resubmits to the next+// configured lane, and binds old-handle → new-handle in Redis. The client+// keeps polling the SAME job id and simply sees status:"running" with a+// new `backend` — the failure is invisible. Capped at MAX_FAILOVER_HOPS+// successors, so a request tries at most 1 primary + 3 backup lanes.+// 2. Designed terminal failure. When no successor is possible (nothing+// configured, cap reached, no stored inputs, Redis off), the failed+// response carries `retryable: true` + `retry_backends: [...]` — the+// ordered, configured lanes a client can one-click resubmit to — instead+// of a bare error string.+//+// Ordering policy mirrors forge-tiers.js exactly: our own GPU workers first+// (zero vendor cost), then free external lanes, then the paid platform default+// last. HuggingFace Spaces cannot be auto-redispatched from a poll (its+// provider blocks through the whole generation), so it appears only in the+// retry_backends suggestions, where the client's fresh POST can ride it.+//+// Everything here is best-effort and fail-open: without Redis the successor+// chain silently disables and callers fall back to the suggestion layer;+// without the DB store there are no recoverable inputs and only suggestions+// apply. A failover must never turn a clean failure into a hang — bind first,+// respond "running" only once the successor handle is durably chased.++import { getRedis } from './redis.js';+import { BACKENDS, backendIsConfigured, resolveTier } from './forge-tiers.js';+import { laneHealthSnapshot } from './forge-lane-health.js';+import { encodeJobToken } from './forge-job-token.js';++const PREFIX = 'fr:successor:';+// Outlive the polling window of a slow cold-start generation, with margin.+const TTL_S = 2 * 3600;++// Successor hops per original job: primary lane + up to 3 automatic backups.+export const MAX_FAILOVER_HOPS = 3;++// Lanes that can be re-dispatched FROM A POLL: async submit/status providers+// only, ordered self-host free → paid last resort. HuggingFace is excluded+// (blocking submit — see module header); NVIDIA is excluded (text-only, and a+// poll-time redispatch always reconstructs from a stored reference image).+const ASYNC_REDISPATCH_ORDER = ['trellis_selfhost', 'hunyuan3d', 'trellis'];++// Lanes a CLIENT can retry with a fresh POST, per input mode. A fresh POST may+// ride blocking lanes too, so HuggingFace joins here; NVIDIA only serves text.+const SUGGESTION_ORDER_IMAGE = ['trellis_selfhost', 'hunyuan3d', 'huggingface', 'trellis'];+const SUGGESTION_ORDER_TEXT = ['nvidia', 'trellis_selfhost', 'hunyuan3d', 'huggingface', 'trellis'];++function client(override) {+ return override || getRedis();+}++/**+ * Durably record that `originalHandle`'s generation continues on a new lane.+ * Returns true only when the binding is confirmed written — the caller must+ * NOT report status:"running" for a successor that isn't chaseable, or the+ * client would poll a dead handle forever.+ */+export async function bindJobSuccessor(originalHandle, { handle, backend, hop, attempted }, { redis } = {}) {+ const r = client(redis);+ if (!r || !originalHandle || !handle) return false;+ try {+ await r.set(+ `${PREFIX}${originalHandle}`,+ JSON.stringify({ handle, backend, hop, attempted: attempted || [] }),+ { ex: TTL_S },+ );+ return true;+ } catch {+ return false;+ }+}++async function successorFor(handle, redis) {+ try {+ const raw = await redis.get(`${PREFIX}${handle}`);+ if (!raw) return null;+ const value = typeof raw === 'string' ? JSON.parse(raw) : raw;+ return value && typeof value.handle === 'string' ? value : null;+ } catch {+ return null;+ }+}++/**+ * Chase the successor chain from the handle the client is polling to the live+ * job. Returns null when no failover ever happened (the overwhelmingly common+ * case), else { handle, backend, hop, attempted } of the newest successor.+ */+export async function resolveLiveJob(originalHandle, { redis } = {}) {+ const r = client(redis);+ if (!r || !originalHandle) return null;+ let current = null;+ let cursor = originalHandle;+ // Cap chase depth defensively at one past MAX_FAILOVER_HOPS — the bind cap+ // makes deeper chains unwritable, this just bounds the loop against a+ // corrupt record.+ for (let i = 0; i <= MAX_FAILOVER_HOPS; i++) {+ const next = await successorFor(cursor, r);+ if (!next) break;+ current = next;+ cursor = next.handle;+ }+ return current;+}++/**+ * The next lane an automatic poll-time redispatch should try, or null. Skips+ * lanes already attempted for this job, lanes not configured on this+ * deployment, and lanes the health snapshot marks down/cooled.+ */+export async function pickRedispatchLane({ attempted = [] } = {}) {+ const candidates = ASYNC_REDISPATCH_ORDER.filter(+ (id) => !attempted.includes(id) && BACKENDS[id] && backendIsConfigured(id),+ );+ if (!candidates.length) return null;+ try {+ const snap = await laneHealthSnapshot(candidates);+ for (const id of candidates) {+ if (snap.byId?.[id]?.status !== 'down') return id;+ }+ return null;+ } catch {+ // No telemetry → first configured candidate; a bad pick fails over again.+ return candidates[0];+ }+}++/**+ * Ordered, configured lanes for the terminal-failure `retry_backends` hint.+ * `hasImage` scopes to reconstruct-capable lanes (NVIDIA's hosted preview is+ * text-only and would 4xx a photo).+ */+export function retryBackendSuggestions({ attempted = [], hasImage = false } = {}) {+ const order = hasImage ? SUGGESTION_ORDER_IMAGE : SUGGESTION_ORDER_TEXT;+ return order.filter((id) => !attempted.includes(id) && BACKENDS[id] && backendIsConfigured(id));+}++/**+ * Resubmit a failed generation to `backend` from its stored inputs. Returns+ * { extJobId, handle } — `handle` is what polling routes on (a gcp/replicate+ * job token, or Replicate's bare prediction id for the paid default lane).+ * Providers are dynamic-imported so an unused SDK never loads in the poll path.+ */+export async function submitFailoverJob({ backend, imageUrl, prompt, tierId, path }) {+ if (!imageUrl) throw new Error('failover needs a stored reference image');+ const tier = resolveTier(tierId);++ if (backend === 'trellis_selfhost') {+ const { createRegenProvider } = await import('../_providers/gcp.js');+ const job = await createRegenProvider().submit({+ mode: 'trellis',+ sourceUrl: imageUrl,+ params: { images: [imageUrl], prompt: prompt || undefined },+ });+ return { extJobId: job.extJobId, handle: encodeJobToken({ provider: 'gcp', kind: null, taskId: job.extJobId }) };+ }++ if (backend === 'hunyuan3d') {+ const { createRegenProvider } = await import('../_providers/gcp.js');+ const job = await createRegenProvider({ reconstructUrl: process.env.GCP_HUNYUAN3D_URL }).submit({+ mode: 'reconstruct',+ sourceUrl: imageUrl,+ params: {+ images: [imageUrl],+ prompt: prompt || undefined,+ target_polycount: tier.polycount,+ tier: tier.id,+ path: path || 'image',+ },+ });+ return { extJobId: job.extJobId, handle: encodeJobToken({ provider: 'gcp', kind: null, taskId: job.extJobId }) };+ }++ if (backend === 'trellis') {+ const { createRegenProvider } = await import('../_providers/replicate.js');+ const job = await createRegenProvider().submit({+ mode: 'reconstruct',+ sourceUrl: imageUrl,+ params: { images: [imageUrl], prompt: prompt || undefined },+ });+ // The paid default lane keeps Replicate's bare prediction id as its handle.+ return { extJobId: job.extJobId, handle: job.extJobId };+ }++ throw new Error(`lane ${backend} cannot be redispatched from a poll`);+}diff --git a/api/_studio/tools.js b/api/_studio/tools.jsindex 06d12eadb..2b4a69bc8 100644--- a/api/_studio/tools.js+++ b/api/_studio/tools.js@@ -350,21 +350,29 @@ const forgeAvatar = {allow_non_humanoid: args.allow_non_humanoid,});if (r.ok === false) return fail(r);+ // A rig-stage failure degrades to the unrigged mesh (rigged:false in the+ // shared core) instead of discarding finished work — reflect it honestly:+ // the caller still gets a viewable GLB, flagged not-animation-ready, with+ // the rig error attached so they can rig_mesh it once the lane recovers.+ const rigged = r.rigged !== false;+ const glbUrl = r.riggedGlbUrl || r.meshGlbUrl;const structured = {ok: true,- kind: 'rigged_avatar',+ kind: rigged ? 'rigged_avatar' : 'avatar_mesh',mode: r.mode,- glbUrl: r.riggedGlbUrl,+ glbUrl,meshGlbUrl: r.meshGlbUrl,- viewerUrl: viewerUrl(r.riggedGlbUrl),- arUrl: arUrl(r.riggedGlbUrl, true),- irlUrl: irlUrl(r.riggedGlbUrl),- poseStudioUrl: poseUrl(r.riggedGlbUrl),+ viewerUrl: viewerUrl(glbUrl),+ arUrl: arUrl(glbUrl, rigged),+ irlUrl: irlUrl(glbUrl),+ ...(rigged+ ? { poseStudioUrl: poseUrl(glbUrl) }+ : { rigError: r.rigError?.message || 'rigging failed — retry with rig_mesh' }),prompt: r.prompt,- animationReady: true,+ animationReady: rigged,durationMs: r.durationMs,};- return ok(structured, r.riggedGlbUrl, args.prompt || 'avatar', { live: true });+ return ok(structured, glbUrl, args.prompt || 'avatar', { live: true });},};diff --git a/api/forge.js b/api/forge.jsindex cadb49c04..de6e20406 100644--- a/api/forge.js+++ b/api/forge.js@@ -127,6 +127,14 @@ import {cacheKeyForJob,} from './_lib/forge-cache.js';import { shouldRetryForQuality } from './_lib/glb-quality.js';+import {+ resolveLiveJob,+ bindJobSuccessor,+ pickRedispatchLane,+ retryBackendSuggestions,+ submitFailoverJob,+ MAX_FAILOVER_HOPS,+} from './_lib/forge-failover.js';import { directPrompt } from './_mcp-studio/forge-client.js';import { MESH_DIRECTOR, resolveLogoPrompt } from './_lib/forge-director-prompts.js';@@ -2298,8 +2306,17 @@ async function pollJob(req, res, jobId) {return pollPipeline(res, token.taskId, jobId);}- const provider = token?.provider || 'replicate';- const upstreamId = token?.taskId || jobId;+ // Poll-time failover may have re-dispatched this generation onto another+ // lane during an earlier poll (see _lib/forge-failover.js). The client keeps+ // polling the ORIGINAL id; chase the successor chain to the live handle+ // before resolving which provider owns the job. No failover (the common+ // case) leaves everything as decoded above.+ const live = await resolveLiveJob(jobId);+ const liveHandle = live?.handle || jobId;+ const liveToken = live ? decodeJobToken(liveHandle) : token;++ const provider = liveToken?.provider || 'replicate';+ const upstreamId = liveToken?.taskId || liveHandle;const clientKey = clientKeyFrom(req);// How this job was conditioned (path + tier + backend + view count), recorded@@ -2332,7 +2349,7 @@ async function pollJob(req, res, jobId) {});}const gp = BYOK_PROVIDER_FACTORIES[provider](key);- result = await gp.status({ kind: token.kind, taskId: upstreamId });+ result = await gp.status({ kind: liveToken.kind, taskId: upstreamId });} else if (provider === 'replicate_byok') {// Replicate BYOK polls the caller's own account (key name 'replicate').const key = await resolveProviderKey(req, null, 'replicate');@@ -2382,7 +2399,9 @@ async function pollJob(req, res, jobId) {} catch {return unconfigured(res);}- result = await rep.status(jobId);+ // liveHandle, not jobId: a failover successor on the paid default lane+ // keeps Replicate's bare prediction id as its handle.+ result = await rep.status(liveHandle);}} catch {// A transient poll error shouldn't fail the job — report running so the@@ -2440,11 +2459,93 @@ async function pollJob(req, res, jobId) {// adapter strings can name the vendor ("meshy task not found"), its billing// state, a task id, an IP, or a leaked key. Mask to neutral copy on the wire.await markFailed({ replicateJobId: upstreamId, clientKey, error: result.error });++ // Cool the platform lane that actually failed so health-aware routing+ // steers new submits away immediately — the poll-time twin of the+ // submit-side cooldown. BYOK lanes are excluded (never auto-selected).+ const failedBackend = meta?.backend || null;+ const platformLaneFailed = Boolean(failedBackend && BACKENDS[failedBackend] && !BACKENDS[failedBackend].byok);+ if (platformLaneFailed) await markLaneUnhealthy(failedBackend);++ // Automatic redispatch (see _lib/forge-failover.js): recover the original+ // inputs from the creation row and continue the SAME job on the next+ // configured lane — the client keeps polling this id and sees+ // status:"running" with a new backend instead of a dead end. Scoped to+ // platform image-path jobs with a stored reference view; sketch stays on+ // its purpose-built lane and BYOK vendors are never silently swapped.+ const attempted = [...new Set([...(live?.attempted || []), failedBackend].filter(Boolean))];+ const hop = live?.hop || 0;+ const redispatchable =+ platformLaneFailed && hop < MAX_FAILOVER_HOPS && meta?.preview_image_url && meta?.path !== 'sketch';+ if (redispatchable) {+ const nextLane = await pickRedispatchLane({ attempted });+ if (nextLane) {+ try {+ const submitted = await submitFailoverJob({+ backend: nextLane,+ imageUrl: meta.preview_image_url,+ prompt: meta.prompt,+ tierId: meta.tier,+ path: meta.path,+ });+ // Provenance row for the successor so later polls resolve its meta+ // and the success path materializes into the store as usual. The+ // redispatch reconstructs from the primary stored view, so a+ // multi-view original degrades visibly (views_used: 1), never silently.+ await createCreation({+ clientKey,+ userId: await sessionUserIdFromReq(req),+ ipHash: hashIp(clientIp(req)),+ prompt: meta.prompt,+ previewImageUrl: meta.preview_image_url,+ replicateJobId: submitted.extJobId,+ viewsRequested: 1,+ viewsUsed: 1,+ multiview: false,+ backend: nextLane,+ tier: meta.tier,+ path: meta.path,+ });+ // Report "running" ONLY once the successor is durably chaseable —+ // otherwise the client would poll a dead handle forever.+ const bound = await bindJobSuccessor(jobId, {+ handle: submitted.handle,+ backend: nextLane,+ hop: hop + 1,+ attempted,+ });+ if (bound) {+ console.warn(+ `[forge] job failed on ${failedBackend}; auto-failover #${hop + 1} → ${nextLane}`,+ );+ return json(res, 200, {+ job_id: jobId,+ status: 'running',+ ...metaFields,+ backend: nextLane,+ failover_from: failedBackend,+ });+ }+ } catch (err) {+ console.warn(`[forge] poll-time failover redispatch failed: ${err?.message || err}`);+ }+ }+ }++ // Terminal — but never a bare dead end: name the configured lanes that can+ // still serve a fresh retry of this request, so a client can offer a+ // one-click engine switch instead of a bare error. Sketch keeps its single+ // purpose-built lane (reconstruct models do badly on drawings).+ const suggestions =+ meta?.path === 'sketch'+ ? []+ : retryBackendSuggestions({ attempted, hasImage: Boolean(meta?.preview_image_url) });return json(res, 200, {job_id: jobId,status: 'failed',error: sanitizeJobError(result.error) || '3D generation hit a snag — please try again.',...metaFields,+ ...(suggestions.length ? { retryable: true, retry_backends: suggestions } : {}),});}return json(res, 200, { job_id: jobId, status: result.status || 'running', ...metaFields });diff --git a/data/changelog.json b/data/changelog.jsonindex c46582d70..b0b14b826 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,33 @@{"$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-07-16",+ "title": "3D generation now switches engines by itself when one fails",+ "summary": "A 3D generation that dies mid-flight no longer dead-ends. The platform now re-runs the same job on the next available engine automatically (up to three backups, free engines first) while your progress bar just keeps going — most failures become invisible. In the rare case every automatic backup is exhausted, the error screen on /forge now offers one-click \"Try on …\" buttons for the engines still available, so you never have to re-enter your prompt or photos. Avatar tools got the same treatment: a rig step that fails no longer throws away the finished 3D model, and the avatar generator falls back to the platform's own free engines when its primary vendor is down.",+ "tags": [+ "improvement"+ ],+ "link": "/forge"+ },+ {+ "date": "2026-07-16",+ "title": "Free 3D generation got a lot more reliable",+ "summary": "Text-to-3D on /forge was intermittently failing with a generic error even though the model had actually finished. The free NVIDIA lane's results are single-collection: two overlapping status checks could race, one collecting the model and the other reporting failure. Status checks are now coordinated, a finished model that a racing check already saved is returned instead of an error, and a genuinely lost result is silently regenerated on the same job. The free community GPU fallback also recovered: one Space reports a broken download address for its finished models, and the fetch now falls back to the address that works.",+ "tags": [+ "fix"+ ],+ "link": "/forge"+ },+ {+ "date": "2026-07-16",+ "title": "Creation tools now hand off down the pipeline",+ "summary": "Finishing one creation step now offers the next one instead of dropping you at a dead end. A fresh selfie avatar gets a \"Turn this into an agent\" button that carries the 3D body straight into the agent builder. The agent builder's success screen adds a \"Take it further\" row: give it a voice, embed it anywhere, put it in a world, or launch its token. And a freshly cloned voice now offers \"Add to an agent\". Avatar to agent to deploy, with no manual re-navigation.",+ "tags": [+ "improvement"+ ],+ "link": "/create"+ },{"date": "2026-07-16","title": "Fewer dead ends in the creation flow",diff --git a/docs/api-reference.md b/docs/api-reference.mdindex 97f5f126f..c546c0611 100644--- a/docs/api-reference.md+++ b/docs/api-reference.md@@ -715,6 +715,15 @@ silently.Poll with `GET /api/forge?job=<job>` — it returns `{ status: "queued" | "done" | "failed", glb_url? }`.+A generation that fails mid-flight on one engine is automatically re-dispatched+to the next configured free lane (up to 3 backups); the poll keeps reporting+`status: "running"` with the new `backend` plus a `failover_from` field, so the+switch is visible but never terminal. Only when every automatic lane is+exhausted does the poll return `status: "failed"` — and when other configured+engines could still serve a fresh retry, it carries `retryable: true` and+`retry_backends: ["huggingface", …]` so a client can resubmit the same request+with an explicit `backend` instead of dead-ending.+**Example**```bashdiff --git a/docs/ops/gcp-model-workers.md b/docs/ops/gcp-model-workers.mdindex 40dcae11f..5b89ecd29 100644--- a/docs/ops/gcp-model-workers.md+++ b/docs/ops/gcp-model-workers.md@@ -101,6 +101,23 @@ so a TripoSG failure returns a designed, retryable `503` rather than a dead erroEvery response reports the `backend` that actually served it, so a failover isnever silent.+### Poll-time failover++A worker can also accept a task and then fail it asynchronously — the failure+only surfaces on a later `GET /api/forge?job=<id>` poll. That poll+(`api/_lib/forge-failover.js`) cools the failed lane, recovers the original+inputs from the creation row (prompt + reference image), resubmits to the next+configured async lane (`trellis_selfhost` → `hunyuan3d` → paid Replicate, up to+3 backups per job), and binds old-handle → new-handle in Redis. The client+keeps polling the same id and sees `status: "running"` with the new `backend`+plus `failover_from` — the failure never reaches the user. When no automatic+lane remains, the terminal `failed` response names the still-configured lanes+in `retry_backends` so the forge UI offers one-click engine switches (and hops+to the first one automatically). HuggingFace can't be driven from a poll (its+provider blocks through the generation), so it appears only in the+suggestions, served by the client's fresh resubmit. Without Redis the+successor chain disables cleanly and only the suggestion layer applies.+### Cold startWhen the liveness probe reaches a self-host worker but it answers slowly (adiff --git a/mcp-server/src/tools/_studio-core.js b/mcp-server/src/tools/_studio-core.jsindex f728e393e..6389e0193 100644--- a/mcp-server/src/tools/_studio-core.js+++ b/mcp-server/src/tools/_studio-core.js@@ -749,18 +749,42 @@ export async function runForgeAvatar({const meshGlbUrl = gen.glb_url;const generationMs = Date.now() - genStarted;- // Stage 2 — auto-rig. Failures still surface meshGlbUrl so generation is not lost.+ // Rig-stage degrade: the mesh is real, finished work — a rig failure must+ // never discard it. Mirror the embody chain's behavior (forge-client.js+ // runEmbodyChain): deliver the unrigged mesh as a SUCCESS with rigged:false+ // and the rig error attached, so the caller keeps the asset and can retry+ // rigging alone (rig_mesh) once the rig lane recovers.+ const meshOnlyResult = (rigError) => ({+ ok: true,+ mode: imageMode ? 'image_to_avatar' : 'text_to_avatar',+ riggedGlbUrl: null,+ meshGlbUrl,+ viewerUrl: `${base}/viewer?src=${encodeURIComponent(meshGlbUrl)}`,+ animationReady: false,+ rigged: false,+ rigError,+ prompt: trimmedPrompt || null,+ imageUrls: imageMode ? views : null,+ viewsUsed: (gen.views_used ?? genJob.views_used) ?? (imageMode ? views.length : 0),+ backend: (gen.backend ?? genJob.backend) ?? null,+ directedPrompt: directedPrompt || null,+ directed: Boolean(directedPrompt),+ humanoid: humanoidInfo,+ meshCreationId: gen.creation_id ?? genJob.creation_id ?? null,+ generationMs,+ durationMs: Date.now() - started,+ fetchedAt: new Date().toISOString(),+ });++ // Stage 2 — auto-rig. Failures degrade to the unrigged mesh, never a dead end.const rigStarted = Date.now();let rigJob;try {rigJob = await startRig({ base, glbUrl: meshGlbUrl });} catch (err) {- return coreError(err.code || 'provider_error', `rigging could not start: ${err.message}`, {- stage: 'rig',- meshGlbUrl,- meshViewerUrl: `${base}/viewer?src=${encodeURIComponent(meshGlbUrl)}`,- generationMs,- durationMs: Date.now() - started,+ return meshOnlyResult({+ code: err.code || 'provider_error',+ message: `rigging could not start: ${err.message}`,...(err.retryAfter ? { retryAfter: err.retryAfter } : {}),});}@@ -775,24 +799,18 @@ export async function runForgeAvatar({failCode: 'rig_failed',});} catch (err) {- return coreError(err.code || 'provider_error', `rigging failed: ${err.message}`, {- stage: 'rig',- meshGlbUrl,- meshViewerUrl: `${base}/viewer?src=${encodeURIComponent(meshGlbUrl)}`,+ return meshOnlyResult({+ code: err.code || 'provider_error',+ message: `rigging failed: ${err.message}`,rigJobId: rigJob.job_id,- generationMs,- durationMs: Date.now() - started,});}if (rig._timedOut) {- return coreError('timeout', `rigging did not finish within ${rigTimeout}ms`, {- stage: 'rig',- meshGlbUrl,- meshViewerUrl: `${base}/viewer?src=${encodeURIComponent(meshGlbUrl)}`,+ return meshOnlyResult({+ code: 'timeout',+ message: `rigging did not finish within ${rigTimeout}ms — it may still complete; poll resumeUrl`,rigJobId: rigJob.job_id,resumeUrl: `${base}/api/forge?job=${rigJob.job_id}`,- generationMs,- durationMs: Date.now() - started,});}@@ -802,6 +820,7 @@ export async function runForgeAvatar({mode: imageMode ? 'image_to_avatar' : 'text_to_avatar',riggedGlbUrl,meshGlbUrl,+ rigged: true,poseStudioUrl: `${base}/pose?src=${encodeURIComponent(riggedGlbUrl)}`,viewerUrl: `${base}/viewer?src=${encodeURIComponent(riggedGlbUrl)}`,animationReady: true,@@ -930,17 +949,58 @@ async function rehostIfRequested(glbUrl, { prompt, images }) {}}-export async function runTextToAvatar({ prompt, images, seed, texture }) {- const version = env('REPLICATE_TEXT_TO_AVATAR_MODEL');- if (!version) {- return coreError(- 'not_configured',- 'REPLICATE_TEXT_TO_AVATAR_MODEL is not set on the server. Pin a commercial-OK image/text-to-3D version (e.g. tencent/hunyuan-3d-3.1 latest).',- );+// The platform's own free-first forge chain (mesh + auto-rig via /api/forge) —+// the standing backup when the pinned Replicate lane is unconfigured or fails+// mid-flight. Maps the chain result onto text_to_avatar's output shape with the+// lane switch reported honestly (`lane`, `fallback_from`, `fallbackReason`);+// when the rig stage succeeds the caller even gets a RIGGED avatar — strictly+// more than the Replicate lane's raw mesh, never less.+async function textToAvatarViaForgeChain({ prompt, images, reason }) {+ const chain = await runForgeAvatar({+ prompt,+ image_urls: images && images.length ? images : undefined,+ // text_to_avatar has no humanoid restriction (Hunyuan reconstructs any+ // subject), so the chain's humanoid gate must not narrow it.+ allow_non_humanoid: true,+ });+ if (!chain.ok) {+ // Both lanes down. Lead with the Replicate failure (it names what an+ // operator must fix); attach the chain's own error for completeness.+ return coreError('all_lanes_failed', `${reason}; forge-chain fallback also failed: ${chain.message || chain.error}`, {+ fallbackError: chain.error || null,+ });}+ const glbUrl = chain.riggedGlbUrl || chain.meshGlbUrl;+ return {+ ok: true,+ glbUrl,+ rigged: Boolean(chain.riggedGlbUrl),+ lane: 'three-ws-forge-chain',+ fallback_from: 'replicate',+ fallbackReason: reason,+ prompt: prompt || null,+ images: images && images.length ? images : null,+ model: chain.backend ? `three-ws/${chain.backend}` : 'three-ws/forge',+ durationMs: chain.durationMs ?? null,+ preview: chain.viewerUrl || `https://three.ws/viewer?src=${encodeURIComponent(glbUrl)}`,+ fetchedAt: new Date().toISOString(),+ };+}++export async function runTextToAvatar({ prompt, images, seed, texture }) {if (!prompt && (!images || images.length === 0)) {return coreError('invalid_input', 'Provide either prompt or images[].');}+ const version = env('REPLICATE_TEXT_TO_AVATAR_MODEL');+ if (!version || !env('REPLICATE_API_TOKEN')) {+ // The pinned Replicate lane isn't configured — serve the request on the+ // platform's own forge chain instead of dead-ending a paid tool.+ return textToAvatarViaForgeChain({+ prompt,+ images,+ reason: !version ? 'REPLICATE_TEXT_TO_AVATAR_MODEL is not set' : 'REPLICATE_API_TOKEN is not set',+ });+ }const input = {prompt: prompt || undefined,image: images && images.length ? images[0] : undefined,@@ -955,7 +1015,9 @@ export async function runTextToAvatar({ prompt, images, seed, texture }) {try {submitted = await submitPrediction({ version, input });} catch (err) {- return coreError(err.code || 'provider_error', err.message);+ // Replicate rejected the submit (auth, quota, outage) — hop to the forge+ // chain rather than dead-ending a paid tool on a vendor problem.+ return textToAvatarViaForgeChain({ prompt, images, reason: `replicate submit failed: ${err.message}` });}const timeoutMs = Number(env('MCP_TEXT_TO_AVATAR_TIMEOUT_MS', '110000'));@@ -964,11 +1026,18 @@ export async function runTextToAvatar({ prompt, images, seed, texture }) {try {finalState = await pollPrediction(submitted.id, { timeoutMs, intervalMs });} catch (err) {- return coreError(err.code || 'provider_error', err.message, { predictionId: submitted.id });+ return textToAvatarViaForgeChain({+ prompt,+ images,+ reason: `replicate poll failed (prediction ${submitted.id}): ${err.message}`,+ });}const durationMs = Date.now() - started;if (finalState._timedOut) {+ // The prediction may still complete — resumeUrl lets the caller pick it+ // up, so a timeout is NOT "nothing" and does not trigger a second full+ // generation on the fallback chain.return coreError('timeout', `prediction did not finish within ${timeoutMs}ms`, {predictionId: submitted.id,status: finalState.status,@@ -977,19 +1046,19 @@ export async function runTextToAvatar({ prompt, images, seed, texture }) {});}if (finalState.status === 'failed' || finalState.status === 'canceled') {- return coreError(- 'prediction_failed',- finalState.error || `prediction ended with status ${finalState.status}`,- { predictionId: submitted.id, durationMs },- );+ return textToAvatarViaForgeChain({+ prompt,+ images,+ reason: `replicate prediction ${finalState.status}: ${finalState.error || 'no detail'}`,+ });}const glbUrl = extractGlbUrl(finalState.output);if (!glbUrl) {- return coreError('no_glb_in_output', 'prediction succeeded but no GLB url was found in output', {- rawOutput: finalState.output,- predictionId: submitted.id,- durationMs,+ return textToAvatarViaForgeChain({+ prompt,+ images,+ reason: `replicate prediction ${submitted.id} succeeded but returned no GLB`,});}diff --git a/mcp-server/src/tools/forge-avatar.js b/mcp-server/src/tools/forge-avatar.jsindex 545e686a0..109967bac 100644--- a/mcp-server/src/tools/forge-avatar.js+++ b/mcp-server/src/tools/forge-avatar.js@@ -104,7 +104,30 @@ export async function buildForgeAvatarTool() {durationMs: 144000,},},- (args) => runForgeAvatar(args),+ async (args) => {+ const r = await runForgeAvatar(args);+ // The shared core degrades a rig-stage failure to a mesh-only SUCCESS —+ // right for the free hosted studio lane, but on this PAID transport the+ // advertised contract is "you are not charged if no rigged avatar is+ // produced". Remap that degrade to the no-charge error envelope with the+ // mesh still attached, so the caller keeps the asset without settling.+ if (r?.ok === true && r.rigged === false) {+ return {+ ok: false,+ error: r.rigError?.code || 'rig_failed',+ message:+ `The mesh generated but rigging failed (${r.rigError?.message || 'no detail'}). ` ++ 'You were NOT charged. The unrigged mesh URL is attached — rig it separately with rig_mesh once the rig lane recovers.',+ meshGlbUrl: r.meshGlbUrl,+ viewerUrl: r.viewerUrl,+ backend: r.backend ?? null,+ meshCreationId: r.meshCreationId ?? null,+ ...(r.rigError?.rigJobId ? { rigJobId: r.rigError.rigJobId } : {}),+ ...(r.rigError?.resumeUrl ? { resumeUrl: r.rigError.resumeUrl } : {}),+ };+ }+ return r;+ },);return {diff --git a/mcp-server/src/tools/text-to-avatar.js b/mcp-server/src/tools/text-to-avatar.jsindex 124b70a0c..daa39d261 100644--- a/mcp-server/src/tools/text-to-avatar.js+++ b/mcp-server/src/tools/text-to-avatar.js@@ -32,7 +32,7 @@ import { runTextToAvatar } from './_studio-core.js';const TOOL_NAME = 'text_to_avatar';const TOOL_DESCRIPTION =- 'Generate a textured 3D GLB avatar from a text prompt or one or more reference image URLs. Drives Replicate (Hunyuan-3D 3.1 by default, configurable) and polls the prediction synchronously until a GLB is produced or the timeout fires. Returns the GLB URL, the source prompt/images, the picked model version, the prediction id, and timing metadata. Paid: $0.15 USDC.';+ 'Generate a textured 3D GLB avatar from a text prompt or one or more reference image URLs. Drives Replicate (Hunyuan-3D 3.1 by default, configurable) and polls the prediction synchronously until a GLB is produced or the timeout fires. When the Replicate lane is unconfigured or fails, the request automatically falls over to the platform forge chain (free lanes + auto-rig) and reports the switch via lane/fallback_from — the result may then arrive rigged. Returns the GLB URL, the source prompt/images, the picked model version, the prediction id, and timing metadata. Paid: $0.15 USDC.';// Single source of truth: Zod shape carries descriptions + bounds; JSON Schema// derived. (No required fields — the handler enforces "prompt OR images".)diff --git a/pages/forge-studio.html b/pages/forge-studio.htmlindex 2bc3e1099..eada57c9f 100644--- a/pages/forge-studio.html+++ b/pages/forge-studio.html@@ -3778,6 +3778,9 @@<p id="error-message">Something went wrong. Try a simpler, single-subject prompt.</p>+ <!-- One-click engine switches, populated only when a lane failed and+ other configured engines can still serve the same request. -->+ <div class="actions is-hidden" id="error-lanes" role="group" aria-label="Retry on another engine"></div><div class="actions"><button class="btn" type="button" id="retry">Try again</button><button class="btn btn-ghost is-hidden" type="button" id="refine-locally">Refine current model instead</button>diff --git a/pages/forge.html b/pages/forge.htmlindex 652abf339..a073ec8f1 100644--- a/pages/forge.html+++ b/pages/forge.html@@ -3294,6 +3294,9 @@<p id="error-message">Something went wrong. Try a simpler, single-subject prompt.</p>+ <!-- One-click engine switches, populated only when a lane failed and+ other configured engines can still serve the same request. -->+ <div class="actions is-hidden" id="error-lanes" role="group" aria-label="Retry on another engine"></div><div class="actions"><button class="btn" type="button" id="retry">Try again</button><button class="btn btn-ghost is-hidden" type="button" id="refine-locally">Refine current model instead</button>diff --git a/public/changelog.json b/public/changelog.jsonindex a9861d276..afff47865 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,11 +1,31 @@{- "generated_at": "2026-07-16T16:49:59.121Z",+ "generated_at": "2026-07-16T18:05:12.321Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws","url": "https://three.ws"},"entries": [+ {+ "date": "2026-07-16",+ "type": "update",+ "title": "3D generation now switches engines by itself when one fails",+ "summary": "A 3D generation that dies mid-flight no longer dead-ends. The platform now re-runs the same job on the next available engine automatically (up to three backups, free engines first) while your progress bar just keeps going — most failures become invisible. In the rare case every automatic backup is exhausted, the error screen on /forge now offers one-click \"Try on …\" buttons for the engines still available, so you never have to re-enter your prompt or photos. Avatar tools got the same treatment: a rig step that fails no longer throws away the finished 3D model, and the avatar generator falls back to the platform's own free engines when its primary vendor is down.",+ "link": "/forge",+ "tags": [+ "improvement"+ ]+ },+ {+ "date": "2026-07-16",+ "type": "update",+ "title": "Creation tools now hand off down the pipeline",+ "summary": "Finishing one creation step now offers the next one instead of dropping you at a dead end. A fresh selfie avatar gets a \"Turn this into an agent\" button that carries the 3D body straight into the agent builder. The agent builder's success screen adds a \"Take it further\" row: give it a voice, embed it anywhere, put it in a world, or launch its token. And a freshly cloned voice now offers \"Add to an agent\". Avatar to agent to deploy, with no manual re-navigation.",+ "link": "/create",+ "tags": [+ "improvement"+ ]+ },{"date": "2026-07-16","type": "update",@@ -16,6 +36,16 @@"improvement"]},+ {+ "date": "2026-07-16",+ "type": "update",+ "title": "Free 3D generation got a lot more reliable",+ "summary": "Text-to-3D on /forge was intermittently failing with a generic error even though the model had actually finished. The free NVIDIA lane's results are single-collection: two overlapping status checks could race, one collecting the model and the other reporting failure. Status checks are now coordinated, a finished model that a racing check already saved is returned instead of an error, and a genuinely lost result is silently regenerated on the same job. The free community GPU fallback also recovered: one Space reports a broken download address for its finished models, and the fetch now falls back to the address that works.",+ "link": "/forge",+ "tags": [+ "fix"+ ]+ },{"date": "2026-07-15","type": "launch",diff --git a/public/changelog.xml b/public/changelog.xmlindex 17d630074..577a2760c 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -6,6 +6,22 @@<atom:link href="https://three.ws/changelog.xml" rel="self" type="application/rss+xml"/><description>What's new on three.ws — features, improvements, and releases, newest first.</description><language>en</language>+ <item>+ <title>3D generation now switches engines by itself when one fails</title>+ <link>https://three.ws/forge</link>+ <guid isPermaLink="false">2026-07-16:3D generation now switches engines by itself when one fails</guid>+ <pubDate>Thu, 16 Jul 2026 12:00:00 GMT</pubDate>+ <category>improvement</category>+ <description>A 3D generation that dies mid-flight no longer dead-ends. The platform now re-runs the same job on the next available engine automatically (up to three backups, free engines first) while your progress bar just keeps going — most failures become invisible. In the rare case every automatic backup is exhausted, the error screen on /forge now offers one-click "Try on …" buttons for the engines still available, so you never have to re-enter your prompt or photos. Avatar tools got the same treatment: a rig step that fails no longer throws away the finished 3D model, and the avatar generator falls back to the platform's own free engines when its primary vendor is down.</description>+ </item>+ <item>+ <title>Creation tools now hand off down the pipeline</title>+ <link>https://three.ws/create</link>+ <guid isPermaLink="false">2026-07-16:Creation tools now hand off down the pipeline</guid>+ <pubDate>Thu, 16 Jul 2026 12:00:00 GMT</pubDate>+ <category>improvement</category>+ <description>Finishing one creation step now offers the next one instead of dropping you at a dead end. A fresh selfie avatar gets a "Turn this into an agent" button that carries the 3D body straight into the agent builder. The agent builder's success screen adds a "Take it further" row: give it a voice, embed it anywhere, put it in a world, or launch its token. And a freshly cloned voice now offers "Add to an agent". Avatar to agent to deploy, with no manual re-navigation.</description>+ </item><item><title>Fewer dead ends in the creation flow</title><link>https://three.ws/create</link>@@ -14,6 +30,14 @@<category>improvement</category><description>Every generic "create an agent" button (marketplace, memory tab, search) now points at the guided /create-agent wizard instead of a stale /agent/new link; that route stays reserved for the avatar hand-off it powers. The search page's avatar CTA no longer points at a route that never existed. /scan and /create/selfie (the two photo-to-avatar paths) now cross-link each other, and Build > Start here in the nav leads with "Create anything" straight to the /create hub.</description></item>+ <item>+ <title>Free 3D generation got a lot more reliable</title>+ <link>https://three.ws/forge</link>+ <guid isPermaLink="false">2026-07-16:Free 3D generation got a lot more reliable</guid>+ <pubDate>Thu, 16 Jul 2026 12:00:00 GMT</pubDate>+ <category>fix</category>+ <description>Text-to-3D on /forge was intermittently failing with a generic error even though the model had actually finished. The free NVIDIA lane's results are single-collection: two overlapping status checks could race, one collecting the model and the other reporting failure. Status checks are now coordinated, a finished model that a racing check already saved is returned instead of an error, and a genuinely lost result is silently regenerated on the same job. The free community GPU fallback also recovered: one Space reports a broken download address for its finished models, and the fetch now falls back to the address that works.</description>+ </item><item><title>Docs · AR in ChatGPT</title><link>https://three.ws/docs/chatgpt-ar</link>diff --git a/src/forge-studio/forge.js b/src/forge-studio/forge.jsindex 60ed0da71..506517507 100644--- a/src/forge-studio/forge.js+++ b/src/forge-studio/forge.js@@ -91,6 +91,7 @@ const els = {refine: document.getElementById('refine'),refineLabel: document.getElementById('refine-label'),retry: document.getElementById('retry'),+ errorLanes: document.getElementById('error-lanes'),viewsCounter: document.getElementById('views-counter'),viewsCounterText: document.getElementById('views-counter-text'),viewsPips: document.getElementById('views-pips'),@@ -128,6 +129,10 @@ 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+// 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.+let autoLaneHops = 0;let currentCreationId = null;// The quality tier the on-screen result was produced at — drives the "Refine"// affordance, which re-runs the same job exactly one tier higher.@@ -196,6 +201,7 @@ const ENGINE_LABELS = {nvidia: 'NVIDIA',huggingface: 'Hunyuan3D',trellis: 'Fast',+ trellis_selfhost: 'TRELLIS',meshy: 'Meshy',tripo: 'Tripo',rodin: 'Rodin',@@ -554,6 +560,17 @@ function updateEngineAvailability() {}}+// Flip the engine picker to a backend by id (used by the lane-failover retry+// affordances, so a switch is always VISIBLE in the composer — never silent).+// Returns false when that engine has no live button on this deployment.+function selectEngineByBackend(backendId) {+ const btn = els.engine?.querySelector(`button[data-backend="${backendId}"]:not(:disabled)`);+ if (!btn) return false;+ userPickedEngine = true;+ selectEngine(btn);+ return true;+}+function selectEngine(btn, silent) {if (!btn) return;selectedEngine = {@@ -1396,7 +1413,17 @@ async function pollUntilDone(jobId) {throw e;}if (data.status === 'done' && data.glb_url) return data;- if (data.status === 'failed') throw new Error(data.error || 'Generation failed.');+ if (data.status === 'failed') {+ // The server names the configured lanes that can still serve a fresh+ // retry of this request (retry_backends) — carry them so the catch can+ // auto-hop to a backup engine instead of dead-ending.+ const e = new Error(data.error || 'Generation failed.');+ if (data.retryable && Array.isArray(data.retry_backends) && data.retry_backends.length) {+ e.kind = 'lane_failed';+ e.retryBackends = data.retry_backends;+ }+ throw e;+ }if (data.status === 'running') setStep('mesh', 'active');}if (pollAbort) return null;@@ -1825,10 +1852,45 @@ function showError(message, { allowOverride = false } = {}) {if (els.generateAnyway) els.generateAnyway.classList.toggle('is-hidden', !allowOverride);// The local-refine escape hatch belongs only to the rate-limit state.if (els.refineLocally) els.refineLocally.classList.add('is-hidden');+ // Lane-switch buttons belong only to the lane-failed state (showLaneFailed+ // re-reveals them after this reset).+ if (els.errorLanes) {+ els.errorLanes.classList.add('is-hidden');+ els.errorLanes.innerHTML = '';+ }if (els.retry) els.retry.disabled = false;showState('error');}+// Every automatic backup lane is exhausted — the one moment the user may see+// an error, so it must not be a dead end. Alongside Try again, render a+// one-click button per remaining configured engine: clicking flips the picker+// (visible switch) and re-runs the same composer inputs, nothing re-entered.+function showLaneFailed(message, backends) {+ showError(message || 'That engine hit a snag mid-generation.');+ if (!els.errorLanes || !lastJob) return;+ const buttons = (backends || []).filter((id) => ENGINE_LABELS[id] || catalog?.backends?.some((b) => b.id === id));+ if (!buttons.length) return;+ for (const id of buttons) {+ const info = catalog?.backends?.find((b) => b.id === id);+ const label = ENGINE_LABELS[id] || info?.label || id;+ const btn = document.createElement('button');+ btn.type = 'button';+ btn.className = 'btn btn-ghost';+ btn.textContent = info?.free ? `Try on ${label} (free)` : `Try on ${label}`;+ btn.addEventListener('click', () => {+ if (!lastJob) return;+ // The picker flip is the affordance: the user sees exactly which engine+ // serves the retry. Fall back to a plain same-lane retry if the button+ // for that engine isn't live on this deployment.+ selectEngineByBackend(id);+ run(lastJob);+ });+ els.errorLanes.appendChild(btn);+ }+ els.errorLanes.classList.remove('is-hidden');+}+// Rate-limit state: a designed, recoverable treatment for a 429. Instead of a// dead-end "busy, try again", we (1) show a live countdown to the reset and// re-enable Retry automatically when it elapses, and (2) — when a model is@@ -2067,6 +2129,21 @@ async function run(cfg) {onGate(err.gate, gateOpts());return;}+ // A lane died mid-generation and the server has no async lane left to+ // continue on itself — but it told us which configured engines can still+ // serve this request. Hop automatically once (visible: the picker flips)+ // so a backup kicks in with zero user action; if the hop also fails,+ // surface one-click engine switches. The user never dead-ends.+ if (err.kind === 'lane_failed' && Array.isArray(err.retryBackends) && err.retryBackends.length) {+ stopElapsed();+ if (lastJob && autoLaneHops < 1 && selectEngineByBackend(err.retryBackends[0])) {+ autoLaneHops += 1;+ run(lastJob);+ return;+ }+ showLaneFailed(err.message, err.retryBackends);+ return;+ }// A presented pay-per-use proof was already spent — drop the stale payment so// Retry doesn't replay it, and re-open the pay flow for a fresh generation.if (err.kind === 'payment_used') {@@ -2167,6 +2244,9 @@ function submit() {return;}const cfg = collectComposerCfg();+ // 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);}diff --git a/src/forge.js b/src/forge.jsindex 18c362f0d..b104ad665 100644--- a/src/forge.js+++ b/src/forge.js@@ -85,6 +85,7 @@ const els = {refine: document.getElementById('refine'),refineLabel: document.getElementById('refine-label'),retry: document.getElementById('retry'),+ errorLanes: document.getElementById('error-lanes'),viewsCounter: document.getElementById('views-counter'),viewsCounterText: document.getElementById('views-counter-text'),viewsPips: document.getElementById('views-pips'),@@ -122,6 +123,10 @@ 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+// 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.+let autoLaneHops = 0;let currentCreationId = null;// The quality tier the on-screen result was produced at — drives the "Refine"// affordance, which re-runs the same job exactly one tier higher.@@ -190,6 +195,7 @@ const ENGINE_LABELS = {nvidia: 'NVIDIA',huggingface: 'Hunyuan3D',trellis: 'Fast',+ trellis_selfhost: 'TRELLIS',meshy: 'Meshy',tripo: 'Tripo',rodin: 'Rodin',@@ -570,6 +576,17 @@ function updateEngineAvailability() {}}+// Flip the engine picker to a backend by id (used by the lane-failover retry+// affordances, so a switch is always VISIBLE in the composer — never silent).+// Returns false when that engine has no live button on this deployment.+function selectEngineByBackend(backendId) {+ const btn = els.engine?.querySelector(`button[data-backend="${backendId}"]:not(:disabled)`);+ if (!btn) return false;+ userPickedEngine = true;+ selectEngine(btn);+ return true;+}+function selectEngine(btn, silent) {if (!btn) return;selectedEngine = {@@ -1422,7 +1439,17 @@ async function pollUntilDone(jobId) {throw e;}if (data.status === 'done' && data.glb_url) return data;- if (data.status === 'failed') throw new Error(data.error || 'Generation failed.');+ if (data.status === 'failed') {+ // The server names the configured lanes that can still serve a fresh+ // retry of this request (retry_backends) — carry them so the catch can+ // auto-hop to a backup engine instead of dead-ending.+ const e = new Error(data.error || 'Generation failed.');+ if (data.retryable && Array.isArray(data.retry_backends) && data.retry_backends.length) {+ e.kind = 'lane_failed';+ e.retryBackends = data.retry_backends;+ }+ throw e;+ }if (data.status === 'running') setStep('mesh', 'active');}if (pollAbort) return null;@@ -1857,10 +1884,45 @@ function showError(message, { allowOverride = false } = {}) {if (els.generateAnyway) els.generateAnyway.classList.toggle('is-hidden', !allowOverride);// The local-refine escape hatch belongs only to the rate-limit state.if (els.refineLocally) els.refineLocally.classList.add('is-hidden');+ // Lane-switch buttons belong only to the lane-failed state (showLaneFailed+ // re-reveals them after this reset).+ if (els.errorLanes) {+ els.errorLanes.classList.add('is-hidden');+ els.errorLanes.innerHTML = '';+ }if (els.retry) els.retry.disabled = false;showState('error');}+// Every automatic backup lane is exhausted — the one moment the user may see+// an error, so it must not be a dead end. Alongside Try again, render a+// one-click button per remaining configured engine: clicking flips the picker+// (visible switch) and re-runs the same composer inputs, nothing re-entered.+function showLaneFailed(message, backends) {+ showError(message || 'That engine hit a snag mid-generation.');+ if (!els.errorLanes || !lastJob) return;+ const buttons = (backends || []).filter((id) => ENGINE_LABELS[id] || catalog?.backends?.some((b) => b.id === id));+ if (!buttons.length) return;+ for (const id of buttons) {+ const info = catalog?.backends?.find((b) => b.id === id);+ const label = ENGINE_LABELS[id] || info?.label || id;+ const btn = document.createElement('button');+ btn.type = 'button';+ btn.className = 'btn btn-ghost';+ btn.textContent = info?.free ? `Try on ${label} (free)` : `Try on ${label}`;+ btn.addEventListener('click', () => {+ if (!lastJob) return;+ // The picker flip is the affordance: the user sees exactly which engine+ // serves the retry. Fall back to a plain same-lane retry if the button+ // for that engine isn't live on this deployment.+ selectEngineByBackend(id);+ run(lastJob);+ });+ els.errorLanes.appendChild(btn);+ }+ els.errorLanes.classList.remove('is-hidden');+}+// Rate-limit state: a designed, recoverable treatment for a 429. Instead of a// dead-end "busy, try again", we (1) show a live countdown to the reset and// re-enable Retry automatically when it elapses, and (2) — when a model is@@ -2103,6 +2165,21 @@ async function run(cfg) {onGate(err.gate, gateOpts());return;}+ // A lane died mid-generation and the server has no async lane left to+ // continue on itself — but it told us which configured engines can still+ // serve this request. Hop automatically once (visible: the picker flips)+ // so a backup kicks in with zero user action; if the hop also fails,+ // surface one-click engine switches. The user never dead-ends.+ if (err.kind === 'lane_failed' && Array.isArray(err.retryBackends) && err.retryBackends.length) {+ stopElapsed();+ if (lastJob && autoLaneHops < 1 && selectEngineByBackend(err.retryBackends[0])) {+ autoLaneHops += 1;+ run(lastJob);+ return;+ }+ showLaneFailed(err.message, err.retryBackends);+ return;+ }// A presented pay-per-use proof was already spent — drop the stale payment so// Retry doesn't replay it, and re-open the pay flow for a fresh generation.if (err.kind === 'payment_used') {@@ -2203,6 +2280,9 @@ function submit() {return;}const cfg = collectComposerCfg();+ // 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);}diff --git a/tests/forge-failover.test.js b/tests/forge-failover.test.jsnew file mode 100644index 000000000..b200aa673--- /dev/null+++ b/tests/forge-failover.test.js@@ -0,0 +1,157 @@+// Poll-time lane failover — api/_lib/forge-failover.js.+//+// Covers the successor-chain store (fake Redis), the terminal-failure lane+// suggestions (env-driven), and the redispatch dispatcher's guard rails. The+// live network paths (provider submits, health snapshot probes) are exercised+// end-to-end against production; these tests pin the pure contracts the poll+// handler depends on.++import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import {+ bindJobSuccessor,+ resolveLiveJob,+ retryBackendSuggestions,+ pickRedispatchLane,+ submitFailoverJob,+ MAX_FAILOVER_HOPS,+} from '../api/_lib/forge-failover.js';++function fakeRedis() {+ const store = new Map();+ return {+ store,+ async get(key) {+ return store.get(key) ?? null;+ },+ async set(key, value) {+ store.set(key, value);+ },+ };+}++const LANE_ENV = [+ 'NVIDIA_API_KEY',+ 'HF_TOKEN',+ 'REPLICATE_API_TOKEN',+ 'MODEL_TRELLIS_URL',+ 'GCP_HUNYUAN3D_URL',+ 'GCP_RECONSTRUCTION_KEY',+];+const saved = {};++beforeEach(() => {+ for (const k of LANE_ENV) {+ saved[k] = process.env[k];+ delete process.env[k];+ }+});+afterEach(() => {+ for (const k of LANE_ENV) {+ if (saved[k] === undefined) delete process.env[k];+ else process.env[k] = saved[k];+ }+});++describe('successor chain', () => {+ it('resolves null when no failover happened', async () => {+ const redis = fakeRedis();+ expect(await resolveLiveJob('job-a', { redis })).toBeNull();+ });++ it('binds and resolves a successor, overwriting on the next hop', async () => {+ const redis = fakeRedis();+ expect(+ await bindJobSuccessor('job-a', { handle: 'job-b', backend: 'trellis_selfhost', hop: 1, attempted: ['nvidia'] }, { redis }),+ ).toBe(true);+ let live = await resolveLiveJob('job-a', { redis });+ expect(live).toMatchObject({ handle: 'job-b', backend: 'trellis_selfhost', hop: 1 });++ // Second failover rebinds the ORIGINAL id — one record per job, no chains+ // to walk or corrupt.+ await bindJobSuccessor(+ 'job-a',+ { handle: 'job-c', backend: 'hunyuan3d', hop: 2, attempted: ['nvidia', 'trellis_selfhost'] },+ { redis },+ );+ live = await resolveLiveJob('job-a', { redis });+ expect(live).toMatchObject({ handle: 'job-c', backend: 'hunyuan3d', hop: 2 });+ expect(live.attempted).toEqual(['nvidia', 'trellis_selfhost']);+ });++ it('fails open without Redis: bind reports false, resolve reports null', async () => {+ expect(await bindJobSuccessor('job-a', { handle: 'job-b', backend: 'x', hop: 1 }, { redis: null })).toBe(false);+ expect(await resolveLiveJob('job-a', { redis: null })).toBeNull();+ });++ it('never reports running for an unbindable successor (bind returns false on write error)', async () => {+ const redis = {+ async get() {+ return null;+ },+ async set() {+ throw new Error('redis down');+ },+ };+ expect(await bindJobSuccessor('job-a', { handle: 'job-b', backend: 'x', hop: 1 }, { redis })).toBe(false);+ });+});++describe('retryBackendSuggestions', () => {+ it('returns only configured lanes, free-first, minus attempted', () => {+ process.env.MODEL_TRELLIS_URL = 'https://model-trellis.example';+ process.env.GCP_RECONSTRUCTION_KEY = 'k';+ process.env.HF_TOKEN = 'hf';+ process.env.REPLICATE_API_TOKEN = 'r8';++ const all = retryBackendSuggestions({ hasImage: true });+ expect(all).toEqual(['trellis_selfhost', 'huggingface', 'trellis']);++ const minusFailed = retryBackendSuggestions({ hasImage: true, attempted: ['trellis_selfhost'] });+ expect(minusFailed).toEqual(['huggingface', 'trellis']);+ });++ it('offers the text-only NVIDIA lane for text jobs but never for photo input', () => {+ process.env.NVIDIA_API_KEY = 'nv';+ expect(retryBackendSuggestions({ hasImage: false })).toEqual(['nvidia']);+ expect(retryBackendSuggestions({ hasImage: true })).toEqual([]);+ });++ it('returns [] when nothing is configured — the caller omits the retry affordance', () => {+ expect(retryBackendSuggestions({ hasImage: true })).toEqual([]);+ });+});++describe('pickRedispatchLane', () => {+ it('returns null with no configured async lane', async () => {+ expect(await pickRedispatchLane({ attempted: [] })).toBeNull();+ });++ it('skips attempted lanes even when configured', async () => {+ process.env.MODEL_TRELLIS_URL = 'https://model-trellis.example';+ process.env.GCP_RECONSTRUCTION_KEY = 'k';+ expect(await pickRedispatchLane({ attempted: ['trellis_selfhost'] })).toBeNull();+ });+});++describe('submitFailoverJob guard rails', () => {+ it('refuses a redispatch with no stored reference image', async () => {+ await expect(submitFailoverJob({ backend: 'trellis_selfhost', imageUrl: null })).rejects.toThrow(+ /reference image/,+ );+ });++ it('refuses lanes that cannot be driven from a poll (blocking or text-only)', async () => {+ await expect(+ submitFailoverJob({ backend: 'huggingface', imageUrl: 'https://x/img.png' }),+ ).rejects.toThrow(/cannot be redispatched/);+ await expect(submitFailoverJob({ backend: 'nvidia', imageUrl: 'https://x/img.png' })).rejects.toThrow(+ /cannot be redispatched/,+ );+ });+});++describe('failover budget', () => {+ it('allows exactly one primary + three backup lanes', () => {+ expect(MAX_FAILOVER_HOPS).toBe(3);+ });+});