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): add Modly TripoSG and Hunyuan3D Mini Turbo as self-host image lanes
nirholas368293c678bc
diff --git a/api/_lib/forge-failover.js b/api/_lib/forge-failover.jsindex 18ff8efe1..59d72242f 100644--- a/api/_lib/forge-failover.js+++ b/api/_lib/forge-failover.js@@ -56,14 +56,21 @@ export const MAX_FAILOVER_HOPS = 3;// 2026-09-18..28 worker outage, which took Hunyuan3D and TRELLIS self-host// down together, ended roughly 400 photo jobs a day in a hard failure while// the TripoSG worker sat healthy.-const ASYNC_REDISPATCH_ORDER = ['trellis2', 'trellis_selfhost', 'hunyuan3d', 'trellis', 'triposg'];+//+// The Modly lanes (workers/modly) are geometry-only too, so they sit with+// TripoSG at the tail, ahead of it: the Modly worker repairs the mesh and+// decimates it to the tier's budget, and it is a separate service, so it still+// serves when the TripoSG sketch worker is the one that is down.+const ASYNC_REDISPATCH_ORDER = ['trellis2', 'trellis_selfhost', 'hunyuan3d', 'trellis', 'modly', 'modly_hunyuan', 'triposg'];// 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.// TripoSG is absent: its public lane is sketch-only, so a fresh photo POST// naming it would be refused. It serves photos only as the poll-time rung.-const SUGGESTION_ORDER_IMAGE = ['trellis2', 'trellis_selfhost', 'hunyuan3d', 'huggingface', 'trellis'];-const SUGGESTION_ORDER_TEXT = ['nvidia', 'trellis2', 'trellis_selfhost', 'hunyuan3d', 'huggingface', 'trellis'];+// The Modly lanes are public image lanes, so they close both lists: untextured+// geometry is the last thing to suggest, never the first.+const SUGGESTION_ORDER_IMAGE = ['trellis2', 'trellis_selfhost', 'hunyuan3d', 'huggingface', 'trellis', 'modly', 'modly_hunyuan'];+const SUGGESTION_ORDER_TEXT = ['nvidia', 'trellis2', 'trellis_selfhost', 'hunyuan3d', 'huggingface', 'trellis', 'modly', 'modly_hunyuan'];function client(override) {return override || getRedis();@@ -185,6 +192,18 @@ export async function submitFailoverJob({ backend, imageUrl, prompt, tierId, patreturn { extJobId: job.extJobId, handle: encodeJobToken({ provider: 'gcp', kind: null, taskId: job.extJobId }) };}+ if (backend === 'modly' || backend === 'modly_hunyuan') {+ const { createRegenProvider } = await import('../_providers/gcp.js');+ // The Modly worker (workers/modly); the mode picks TripoSG or Hunyuan3D 2+ // Mini Turbo, and the poly budget becomes its decimate target.+ const job = await createRegenProvider().submit({+ mode: backend,+ sourceUrl: imageUrl,+ params: { images: [imageUrl], tier: tier.id, target_polycount: tier.polycount },+ });+ return { extJobId: job.extJobId, handle: encodeJobToken({ provider: 'gcp', kind: null, taskId: job.extJobId }) };+ }+if (backend === 'trellis_selfhost') {const { createRegenProvider } = await import('../_providers/gcp.js');const job = await createRegenProvider().submit({diff --git a/api/_lib/forge-health.js b/api/_lib/forge-health.jsindex 9059e5500..5682960d2 100644--- a/api/_lib/forge-health.js+++ b/api/_lib/forge-health.js@@ -285,6 +285,11 @@ const PROBES = {// TRELLIS.2 is the default image lane for every tier. Same /health contract as// the other workers, so a latched model-load failure reads as down here too.trellis2: gcpWorkerProbe('trellis2', 'MODEL_TRELLIS2_URL'),+ // One Modly worker serves both Modly lanes, so both read the same /health.+ // The worker reports load_error per enabled model, so a latched bring-up+ // failure reads as down for both.+ modly: gcpWorkerProbe('modly', 'MODEL_MODLY_URL'),+ modly_hunyuan: gcpWorkerProbe('modly_hunyuan', 'MODEL_MODLY_URL'),};// The editing lanes: everything the result panel offers AFTER a mesh existsdiff --git a/api/_lib/forge-territory.js b/api/_lib/forge-territory.jsindex 15eaabb14..943bb1c26 100644--- a/api/_lib/forge-territory.js+++ b/api/_lib/forge-territory.js@@ -1,8 +1,8 @@/*** Forge territory router* ----------------------- * Some model licences exclude whole regions. The Hunyuan3D 2.1 community- * licence (Territory clause) does not grant any rights in the European Union,+ * Some model licences exclude whole regions. The Hunyuan3D 2.1 and 2.0+ * community licences (Territory clause) do not grant any rights in the European Union,* the United Kingdom or South Korea, for the model or for its output. three.ws* serves those regions, so a request that originates there must never be* routed to a lane that runs a Tencent model.@@ -16,11 +16,14 @@* Lanes that run a Tencent model:* - hunyuan3d our own Hunyuan3D 2.1 worker.* - huggingface the free Spaces lane, whose chain is Hunyuan Spaces.+ * - modly_hunyuan our own Modly worker running Hunyuan3D 2 Mini Turbo. Its+ * sibling lane `modly` runs TripoSG (MIT) on the same+ * worker and is served everywhere.*/import { clientCountry } from './client-geo.js';-export const TENCENT_LANES = Object.freeze(['hunyuan3d', 'huggingface']);+export const TENCENT_LANES = Object.freeze(['hunyuan3d', 'huggingface', 'modly_hunyuan']);// ISO 3166-1 alpha-2. EU member states, the UK and South Korea.export const RESTRICTED_COUNTRIES = Object.freeze([diff --git a/api/_lib/forge-tiers.js b/api/_lib/forge-tiers.jsindex d7c65b2e3..3329f0816 100644--- a/api/_lib/forge-tiers.js+++ b/api/_lib/forge-tiers.js@@ -296,6 +296,50 @@ export const BACKENDS = Object.freeze({free: true,blurb: 'Free native image→3D on our own TRELLIS worker — single-hop reconstruction (image → TRELLIS → GLB), textured GLB, no vendor cost.',}),+ modly: Object.freeze({+ id: 'modly',+ label: 'Modly TripoSG (self-host)',+ vendor: 'VAST AI TripoSG via Modly · self-host',+ paths: Object.freeze(['image']),+ byok: false,+ provider: 'gcp',+ // Our own Modly worker (workers/modly on Cloud Run, Modly by Lightning+ // Pixel, MIT) running VAST AI's TripoSG (MIT code and weights). It is a+ // geometry engine: the GLB is an untextured mesh, which the worker then+ // decimates to the tier's poly budget through Modly's mesh optimizer, so+ // the tier's polycount is a real target here. One worker serves this lane+ // and modly_hunyuan; MODEL_MODLY_URL gates both.+ requiresEnv: Object.freeze(['MODEL_MODLY_URL', 'GCP_RECONSTRUCTION_KEY']),+ polyControl: true,+ userImages: true,+ baseEta: 60,+ // Scale-to-zero worker: a cold instance copies its weights, starts Modly+ // and runs one warm-up generation before it takes the request.+ coldStartSeconds: 120,+ credits: null,+ free: true,+ blurb: 'Free image to 3D geometry on our own Modly worker running TripoSG: clean, watertight shapes at your poly budget, no vendor cost. Untextured; retexture or stylize after.',+ }),+ modly_hunyuan: Object.freeze({+ id: 'modly_hunyuan',+ label: 'Modly Hunyuan3D Mini Turbo (self-host)',+ vendor: 'Tencent Hunyuan3D 2 Mini Turbo via Modly · self-host',+ paths: Object.freeze(['image']),+ byok: false,+ provider: 'gcp',+ // The same Modly worker as `modly`, running Tencent's Hunyuan3D 2 Mini+ // Turbo (0.6B, few-step). Untextured geometry decimated to the tier's+ // budget. A Tencent model, so it is in TENCENT_LANES and never served to+ // the EU, the UK, South Korea or an unknown country (forge-territory.js).+ requiresEnv: Object.freeze(['MODEL_MODLY_URL', 'GCP_RECONSTRUCTION_KEY']),+ polyControl: true,+ userImages: true,+ baseEta: 45,+ coldStartSeconds: 120,+ credits: null,+ free: true,+ blurb: 'Free fast image to 3D geometry on our own Modly worker running Hunyuan3D 2 Mini Turbo, decimated to your poly budget, no vendor cost. Untextured; retexture or stylize after.',+ }),triposg: Object.freeze({id: 'triposg',label: 'TripoSG',@@ -436,7 +480,9 @@ export const FREE_DEFAULT_FOR_TIERS = Object.freeze({// of a paid engine. First configured + capable lane wins, and our OWN GPU workers// come first so the platform leans on the credits we control before any external// free lane: self-hosted TRELLIS.2, then self-hosted TRELLIS v1, then self-hosted-// Hunyuan3D, then the free HuggingFace Spaces lane. The two Tencent lanes are+// Hunyuan3D, then the free HuggingFace Spaces lane, then our self-hosted Modly+// worker (TripoSG, then Hunyuan3D 2 Mini Turbo), which returns untextured+// geometry and so ranks below every textured lane. The Tencent lanes are// dropped for requests from the EU, the UK, South Korea or an unknown country. The free NVIDIA NIM TRELLIS// lane trails as the final health-gated fallthrough so a text prompt still// returns a model when every GPU worker (and HuggingFace) is cold or down — this@@ -445,7 +491,7 @@ export const FREE_DEFAULT_FOR_TIERS = Object.freeze({// submission filters it out and stops at HuggingFace, exactly as before. Every// entry is env-gated, so the list degrades cleanly on partial deployments.export const FREE_FALLBACK_FOR_PATH = Object.freeze({- image: Object.freeze(['trellis2', 'trellis_selfhost', 'hunyuan3d', 'huggingface', 'nvidia']),+ image: Object.freeze(['trellis2', 'trellis_selfhost', 'hunyuan3d', 'huggingface', 'modly', 'modly_hunyuan', 'nvidia']),});// Realism subject classes. The two self-host PBR lanes have different strengths:@@ -746,6 +792,35 @@ export function backendIsConfigured(backendId) {return b.requiresEnv.every((name) => Boolean(readEnv(name)));}+// The self-host image lanes the forge handler drives through one async GCP+// block (api/forge.js, api/gpt-forge.js): the two TRELLIS workers and the two+// Modly lanes, which share one worker (workers/modly).+export const MODLY_LANES = Object.freeze(['modly', 'modly_hunyuan']);+const SELF_HOST_IMAGE_LANES = Object.freeze(['trellis2', 'trellis_selfhost', ...MODLY_LANES]);++export function isSelfHostImageLane(backendId) {+ return SELF_HOST_IMAGE_LANES.includes(backendId);+}++// Human name for a self-host image lane in a designed "not configured" error.+export function selfHostLaneName(backendId) {+ return MODLY_LANES.includes(backendId) ? BACKENDS[backendId].label : 'Self-hosted TRELLIS';+}++// Where a self-host image lane retries when its worker is down, before the+// handler leaves the self-host block for Hunyuan3D or the reconstruct chain.+// A Modly lane goes to TRELLIS.2, then TRELLIS v1 (the two Modly lanes share a+// worker, so one never rescues the other); TRELLIS.2 goes to TRELLIS v1. Null+// when no configured lane is left. Both TRELLIS lanes are territory-free.+export function nextSelfHostImageLane(backendId) {+ const after = MODLY_LANES.includes(backendId)+ ? ['trellis2', 'trellis_selfhost']+ : backendId === 'trellis2'+ ? ['trellis_selfhost']+ : [];+ return after.find((id) => backendIsConfigured(id)) || null;+}+// Estimated wall-clock seconds for a (backend, path, tier) combination —// used to populate the client progress estimate and the catalog. When `cold` is// true (the liveness probe reports a scale-to-zero self-host worker not warm), thediff --git a/api/_mcp3d/tools/studio.js b/api/_mcp3d/tools/studio.jsindex 18e336f97..42e2d0721 100644--- a/api/_mcp3d/tools/studio.js+++ b/api/_mcp3d/tools/studio.js@@ -329,6 +329,8 @@ const INTERNAL_TO_ENGINE = Object.freeze({nvidia: 'three-image',trellis2: 'three-image',trellis_selfhost: 'three-image',+ modly: 'three-image',+ modly_hunyuan: 'three-image',huggingface: 'three-image',replicate_byok: 'three-image',meshy: 'three-geometry',diff --git a/api/_providers/gcp.js b/api/_providers/gcp.jsindex c948ded51..ede3ce713 100644--- a/api/_providers/gcp.js+++ b/api/_providers/gcp.js@@ -13,6 +13,11 @@// shape: POST /infer → { task_id } GET /tasks/:id → result_gcs_url.//// trellis2 → MODEL_TRELLIS2_URL (workers/model-trellis2)+// modly → MODEL_MODLY_URL (workers/modly, TripoSG)+// modly_hunyuan → MODEL_MODLY_URL (workers/modly, Hunyuan3D 2 Mini Turbo)+// One Modly worker serves both; the request's `model` field+// picks the extension. Untextured geometry, repaired and+// decimated to the poly budget by Modly's mesh optimizer.// hunyuan → GCP_HUNYUAN3D_URL (workers/model-hunyuan3d)// Image→3D via Tencent Hunyuan3D-2 (shape DiT + multiview// paint). Same standard task shape as the TRELLIS worker:@@ -101,6 +106,11 @@ function serviceUrlForMode(mode) {// Self-hosted Microsoft TRELLIS.2 image→3D worker (workers/model-trellis2),// the default image lane. Same /infer + /tasks/:id task shape.return readEnv('MODEL_TRELLIS2_URL');+ case 'modly':+ case 'modly_hunyuan':+ // Self-hosted Modly worker (workers/modly): one service, two models.+ // Same /infer + /tasks/:id task shape as the TRELLIS workers.+ return readEnv('MODEL_MODLY_URL');case 'hunyuan':// Self-hosted Hunyuan3D-2 image→3D worker (workers/model-hunyuan3d).// Same standard /infer + /tasks/:id task shape as the TRELLIS worker.@@ -206,6 +216,10 @@ function buildWorkerRequest(request) {};}+ if (mode === 'modly' || mode === 'modly_hunyuan') {+ return buildModlyRequest(mode, sourceUrl, params);+ }+if (mode === 'hunyuan') {// Self-hosted Hunyuan3D-2 image→3D (workers/model-hunyuan3d). Shape DiT// conditions on the primary reference view; the worker isolates the@@ -437,12 +451,56 @@ function buildWorkerRequest(request) {return null;}+// The Modly worker's model id per forge mode, and the face budget its+// decimate step accepts (workers/modly request_policy.py DECIMATE_MIN/MAX).+export const MODLY_MODEL_FOR_MODE = Object.freeze({+ modly: 'triposg',+ modly_hunyuan: 'hunyuan3d-mini-turbo',+});+const MODLY_DECIMATE_MIN = 100;+const MODLY_DECIMATE_MAX = 1_000_000;++// Self-hosted Modly image to 3D (workers/modly). One reference view in, an+// untextured GLB out. The worker maps `tier` to its sampler budget; the+// post-process plan repairs the raw marching-cubes mesh and then decimates it to+// the caller's poly budget, so the tier's polycount is honoured. A budget outside+// the worker's bounds is clamped here rather than 422ing the whole generation.+function buildModlyRequest(mode, sourceUrl, params) {+ const photos = Array.isArray(params?.images) && params.images.length+ ? params.images+ : [sourceUrl].filter(Boolean);+ const body = {+ images: photos,+ body_type: params?.bodyType || 'neutral',+ model: MODLY_MODEL_FOR_MODE[mode],+ };+ if (params?.tier) body.tier = params.tier;+ if (Number.isFinite(Number(params?.seed))) body.seed = Math.floor(Number(params.seed));+ const postprocess = { repair: true };+ const target = Number(params?.target_polycount);+ if (Number.isFinite(target) && target > 0) {+ postprocess.decimate = {+ target_faces: Math.min(MODLY_DECIMATE_MAX, Math.max(MODLY_DECIMATE_MIN, Math.round(target))),+ };+ }+ body.postprocess = postprocess;+ return {+ path: '/infer',+ resultKey: 'result_gcs_url',+ body,+ };+}+// Expected wall-clock ETAs (seconds) per mode — used to populate the// progress indicator on the client side.const MODE_ETA = {reconstruct: 120,trellis: 60,trellis2: 75,+ // TripoSG's 20 to 50 flow steps plus repair and decimate on the L4.+ modly: 60,+ // Hunyuan3D 2 Mini Turbo is a few-step distilled sampler.+ modly_hunyuan: 45,// 50-step shape diffusion + multiview paint on the L4: much heavier than// TRELLIS's single pass.hunyuan: 300,@@ -549,7 +607,7 @@ export function createRegenProvider({ reconstructUrl } = {}) {// primary view only (report 1 so a multi-view request is never// silently claimed as fused); other modes are single-source.const viewsUsed =- mode === 'hunyuan' || mode === 'trellis2'+ mode === 'hunyuan' || mode === 'trellis2' || mode === 'modly' || mode === 'modly_hunyuan'? 1: (mode === 'reconstruct' || mode === 'trellis') && Array.isArray(workerReq.body.images)? workerReq.body.images.lengthdiff --git a/api/cron/gpu-keepwarm.js b/api/cron/gpu-keepwarm.jsindex a1f2cb3b7..a5419e6bb 100644--- a/api/cron/gpu-keepwarm.js+++ b/api/cron/gpu-keepwarm.js@@ -59,6 +59,28 @@ export const KEEPWARM_LANES = [// FORGE_KEEPWARM_LANES=trellis2 once the grant allows it.reason: 'us-central1 L4 grant is shared with trellis, rig and hunyuan3d; a warm floor here is a quota decision',},+ {+ // One Modly worker (workers/modly) serves both Modly lanes, so warming+ // either id keeps modly and modly_hunyuan resident together; both are+ // listed so each routed lane can be named in FORGE_KEEPWARM_LANES. Its cold+ // start is the fleet's longest (weights copy, Modly start and a warm-up+ // generation, BACKENDS.modly.coldStartSeconds), but these are late fallback+ // lanes, so the shared us-central1 L4 grant goes to the default lanes first.+ id: 'modly',+ urlEnv: 'MODEL_MODLY_URL',+ region: 'us-central1',+ accelerator: 'nvidia-l4',+ safeByDefault: false,+ reason: 'us-central1 L4 grant is shared with the default image lanes; a warm floor here is a quota decision',+ },+ {+ id: 'modly_hunyuan',+ urlEnv: 'MODEL_MODLY_URL',+ region: 'us-central1',+ accelerator: 'nvidia-l4',+ safeByDefault: false,+ reason: 'same Modly worker as the modly lane; warming either keeps both resident',+ },{id: 'hunyuan3d',urlEnv: 'GCP_HUNYUAN3D_URL',diff --git a/api/forge.js b/api/forge.jsindex 8d8e2bf4f..c009cc549 100644--- a/api/forge.js+++ b/api/forge.js@@ -81,6 +81,10 @@ import {backendAcceptsInlineViews,buildCatalog,selfhostQualityForTier,+ MODLY_LANES,+ isSelfHostImageLane,+ selfHostLaneName,+ nextSelfHostImageLane,} from './_lib/forge-tiers.js';import {laneHealthSnapshot,@@ -1886,8 +1890,8 @@ async function startJobWithBody(req, res, body) {// creates its own provider. We deliberately do NOT build a Replicate// client here: creating one would 503 on a deployment that has no// REPLICATE_API_TOKEN, breaking an explicitly-chosen free engine.- } else if (backendId === 'trellis2' || backendId === 'trellis_selfhost') {- // Driven by the dedicated self-host TRELLIS lane below, which builds+ } else if (isSelfHostImageLane(backendId)) {+ // Driven by the dedicated self-host image lane below, which builds// its own GCP provider. Same reasoning as huggingface, never build a// Replicate client here, or a deployment without REPLICATE_API_TOKEN// would 503 on an explicitly-chosen free self-hosted engine.@@ -2113,7 +2117,11 @@ async function startJobWithBody(req, res, body) {// sketch lane: returns a poll token that routes back through the gcp provider's// status(). Reached on an explicit pick OR as the preferred free image lane// (FREE_FALLBACK_FOR_PATH) when MODEL_TRELLIS_URL is configured.- if (backendId === 'trellis2' || backendId === 'trellis_selfhost') {+ //+ // The Modly lanes (workers/modly: TripoSG, Hunyuan3D 2 Mini Turbo) ride the+ // same block. They are explicit picks or late free fallbacks, and when their+ // worker is down the request retries on TRELLIS.2, then TRELLIS v1.+ if (isSelfHostImageLane(backendId)) {let gcp;try {gcp = createGcpProvider();@@ -2121,17 +2129,29 @@ async function startJobWithBody(req, res, body) {return json(res, 501, {error: 'backend_unconfigured',backend: backendId,- message: 'Self-hosted TRELLIS is not configured on this deployment.',+ message: `${selfHostLaneName(backendId)} is not configured on this deployment.`,});}let job;let selfHostTrellisFailed = false;// TRELLIS.2 leads; when it is unavailable the same request retries on the- // TRELLIS v1 worker, which holds the same reference views.+ // TRELLIS v1 worker, which holds the same reference views. A Modly lane+ // retries on TRELLIS.2 first.for (;;) {try {- job = await gcp.submit(backendId === 'trellis2' ? {+ job = await gcp.submit(MODLY_LANES.includes(backendId) ? {+ mode: backendId,+ sourceUrl: referenceImageUrl,+ params: {+ images: views,+ seed: opts.seed ?? undefined,+ // The worker maps the tier to its sampler budget and decimates+ // the mesh to this face count after a repair pass.+ tier: tier.id,+ target_polycount: opts.targetPolycount ?? tier.polycount,+ },+ } : backendId === 'trellis2' ? {mode: 'trellis2',sourceUrl: referenceImageUrl,params: {@@ -2183,7 +2203,7 @@ async function startJobWithBody(req, res, body) {error: 'backend_unconfigured',backend: backendId,message:- 'Self-hosted TRELLIS is not configured on this deployment (the worker URL is not set).',+ `${selfHostLaneName(backendId)} is not configured on this deployment (the worker URL is not set).`,});}// A genuine config/input fault surfaces as-is. An upstream blip (the@@ -2196,10 +2216,11 @@ async function startJobWithBody(req, res, body) {if (!isUpstreamUnavailable(err)) throw err;await markLaneUnhealthy(backendId);console.warn(- `[forge] self-host TRELLIS lane unavailable (${err?.providerStatus || err?.code}); failing over to the next image lane`,+ `[forge] self-host ${backendId} lane unavailable (${err?.providerStatus || err?.code}); failing over to the next image lane`,);- if (backendId === 'trellis2' && backendIsConfigured('trellis_selfhost')) {- backendId = 'trellis_selfhost';+ const nextLane = nextSelfHostImageLane(backendId);+ if (nextLane) {+ backendId = nextLane;continue;}selfHostTrellisFailed = true;@@ -2528,7 +2549,7 @@ async function startJobWithBody(req, res, body) {// token tag so polling re-resolves the caller's key (not the platform one).// Either way the upstream id is what the store keys on.const jobHandle =- backendId === 'hunyuan3d' || backendId === 'trellis2' || backendId === 'trellis_selfhost'+ backendId === 'hunyuan3d' || isSelfHostImageLane(backendId)? encodeJobToken({ provider: 'gcp', kind: null, taskId: job.extJobId }): backendId === 'replicate_byok'? encodeJobToken({ provider: 'replicate_byok', kind: null, taskId: job.extJobId })diff --git a/api/gpt-forge.js b/api/gpt-forge.jsindex a5abfe7e8..916dd9583 100644--- a/api/gpt-forge.js+++ b/api/gpt-forge.js@@ -86,6 +86,10 @@ import {laneAfterHfFailure,buildCatalog,selfhostQualityForTier,+ MODLY_LANES,+ isSelfHostImageLane,+ selfHostLaneName,+ nextSelfHostImageLane,} from './_lib/forge-tiers.js';import {laneHealthSnapshot,@@ -1899,8 +1903,8 @@ async function startJob(req, res) {// creates its own provider. We deliberately do NOT build a Replicate// client here: creating one would 503 on a deployment that has no// REPLICATE_API_TOKEN, breaking an explicitly-chosen free engine.- } else if (backendId === 'trellis2' || backendId === 'trellis_selfhost') {- // Driven by the dedicated self-host TRELLIS lane below, which builds+ } else if (isSelfHostImageLane(backendId)) {+ // Driven by the dedicated self-host image lane below, which builds// its own GCP provider. Same reasoning as huggingface, never build a// Replicate client here, or a deployment without REPLICATE_API_TOKEN// would 503 on an explicitly-chosen free self-hosted engine.@@ -2046,7 +2050,11 @@ async function startJob(req, res) {// sketch lane: returns a poll token that routes back through the gcp provider's// status(). Reached on an explicit pick OR as the preferred free image lane// (FREE_FALLBACK_FOR_PATH) when MODEL_TRELLIS_URL is configured.- if (backendId === 'trellis2' || backendId === 'trellis_selfhost') {+ //+ // The Modly lanes (workers/modly: TripoSG, Hunyuan3D 2 Mini Turbo) ride the+ // same block. They are explicit picks or late free fallbacks, and when their+ // worker is down the request retries on TRELLIS.2, then TRELLIS v1.+ if (isSelfHostImageLane(backendId)) {let gcp;try {gcp = createGcpProvider();@@ -2054,17 +2062,29 @@ async function startJob(req, res) {return json(res, 501, {error: 'backend_unconfigured',backend: backendId,- message: 'Self-hosted TRELLIS is not configured on this deployment.',+ message: `${selfHostLaneName(backendId)} is not configured on this deployment.`,});}let job;let selfHostTrellisFailed = false;// TRELLIS.2 leads; when it is unavailable the same request retries on the- // TRELLIS v1 worker, which holds the same reference views.+ // TRELLIS v1 worker, which holds the same reference views. A Modly lane+ // retries on TRELLIS.2 first.for (;;) {try {- job = await gcp.submit(backendId === 'trellis2' ? {+ job = await gcp.submit(MODLY_LANES.includes(backendId) ? {+ mode: backendId,+ sourceUrl: referenceImageUrl,+ params: {+ images: views,+ seed: opts.seed ?? undefined,+ // The worker maps the tier to its sampler budget and decimates+ // the mesh to this face count after a repair pass.+ tier: tier.id,+ target_polycount: opts.targetPolycount ?? tier.polycount,+ },+ } : backendId === 'trellis2' ? {mode: 'trellis2',sourceUrl: referenceImageUrl,params: {@@ -2109,7 +2129,7 @@ async function startJob(req, res) {error: 'backend_unconfigured',backend: backendId,message:- 'Self-hosted TRELLIS is not configured on this deployment (the worker URL is not set).',+ `${selfHostLaneName(backendId)} is not configured on this deployment (the worker URL is not set).`,});}// A genuine config/input fault surfaces as-is. An upstream blip (the@@ -2122,10 +2142,11 @@ async function startJob(req, res) {if (!isUpstreamUnavailable(err)) throw err;await markLaneUnhealthy(backendId);console.warn(- `[forge] self-host TRELLIS lane unavailable (${err?.providerStatus || err?.code}); failing over to the next image lane`,+ `[forge] self-host ${backendId} lane unavailable (${err?.providerStatus || err?.code}); failing over to the next image lane`,);- if (backendId === 'trellis2' && backendIsConfigured('trellis_selfhost')) {- backendId = 'trellis_selfhost';+ const nextLane = nextSelfHostImageLane(backendId);+ if (nextLane) {+ backendId = nextLane;continue;}selfHostTrellisFailed = true;@@ -2449,7 +2470,7 @@ async function startJob(req, res) {// token tag so polling re-resolves the caller's key (not the platform one).// Either way the upstream id is what the store keys on.const jobHandle =- backendId === 'hunyuan3d' || backendId === 'trellis2' || backendId === 'trellis_selfhost'+ backendId === 'hunyuan3d' || isSelfHostImageLane(backendId)? encodeJobToken({ provider: 'gcp', kind: null, taskId: job.extJobId }): backendId === 'replicate_byok'? encodeJobToken({ provider: 'replicate_byok', kind: null, taskId: job.extJobId })diff --git a/src/forge-showcase.js b/src/forge-showcase.jsindex 0c3228304..0b2bf609f 100644--- a/src/forge-showcase.js+++ b/src/forge-showcase.js@@ -104,6 +104,8 @@ const ENGINE_LABELS = {trellis: 'Fast',trellis2: 'TRELLIS.2',trellis_selfhost: 'TRELLIS',+ modly: 'Modly TripoSG',+ modly_hunyuan: 'Modly Hunyuan',meshy: 'Meshy',tripo: 'Tripo',rodin: 'Rodin',diff --git a/src/forge-studio/forge-showcase.js b/src/forge-studio/forge-showcase.jsindex 68524a5ce..419d326c1 100644--- a/src/forge-studio/forge-showcase.js+++ b/src/forge-studio/forge-showcase.js@@ -93,6 +93,8 @@ const ENGINE_LABELS = {trellis: 'Fast',trellis2: 'TRELLIS.2',trellis_selfhost: 'TRELLIS',+ modly: 'Modly TripoSG',+ modly_hunyuan: 'Modly Hunyuan',meshy: 'Meshy',tripo: 'Tripo',rodin: 'Rodin',diff --git a/src/forge.js b/src/forge.jsindex 4d912fcd1..43403d300 100644--- a/src/forge.js+++ b/src/forge.js@@ -282,6 +282,8 @@ const ENGINE_LABELS = {trellis: 'Fast',trellis2: 'TRELLIS.2',trellis_selfhost: 'TRELLIS',+ modly: 'Modly TripoSG',+ modly_hunyuan: 'Modly Hunyuan',meshy: 'Meshy',tripo: 'Tripo',rodin: 'Rodin',diff --git a/src/home-forge-controls.js b/src/home-forge-controls.jsindex ecdeb5d72..3fb5eefa4 100644--- a/src/home-forge-controls.js+++ b/src/home-forge-controls.js@@ -36,6 +36,8 @@ const ENGINE_LABELS = {trellis: 'Fast',trellis2: 'TRELLIS.2',trellis_selfhost: 'TRELLIS',+ modly: 'Modly TripoSG',+ modly_hunyuan: 'Modly Hunyuan',meshy: 'Meshy',tripo: 'Tripo',rodin: 'Rodin',diff --git a/src/shared/forge-frames.js b/src/shared/forge-frames.jsindex 5a3e561da..45c23b7ce 100644--- a/src/shared/forge-frames.js+++ b/src/shared/forge-frames.js@@ -55,6 +55,8 @@ const LANE_LABELS = {trellis: 'Fast',trellis2: 'TRELLIS.2',trellis_selfhost: 'TRELLIS',+ modly: 'Modly TripoSG',+ modly_hunyuan: 'Modly Hunyuan',meshy: 'Meshy',tripo: 'Tripo',rodin: 'Rodin',diff --git a/tests/api/forge-modly-handler.test.js b/tests/api/forge-modly-handler.test.jsnew file mode 100644index 000000000..55f8f4711--- /dev/null+++ b/tests/api/forge-modly-handler.test.js@@ -0,0 +1,201 @@+/**+ * The Modly lanes through the real forge handlers: api/forge.js and its+ * ChatGPT clone api/gpt-forge.js.+ *+ * tests/api/forge-modly.test.js pins the registry, routing and wire contract in+ * isolation. These tests drive a full POST through each handler with only the+ * network edges stubbed, so the wiring between them is what is under test: an+ * explicit Modly pick reaches the gcp provider in Modly's mode with the tier's+ * face budget, a worker outage cools the lane and retries the same request on+ * TRELLIS.2, a licence-restricted territory is refused with a reason, and a+ * deployment without the worker URL answers 501 naming the lane.+ */++import { describe, it, expect, vi, beforeAll, beforeEach } from 'vitest';++beforeAll(() => {+ Object.assign(process.env, {+ APP_ORIGIN: 'https://three.ws',+ // Both self-host image workers wired: Modly and the TRELLIS.2 retry target.+ MODEL_MODLY_URL: 'https://modly.example.run.app',+ MODEL_TRELLIS2_URL: 'https://trellis2.example.run.app',+ GCP_RECONSTRUCTION_KEY: 'test-gcp-key',+ // Satisfies the handler's global text-to-3D configured guard.+ NVIDIA_API_KEY: 'nvapi-test',+ // The lane wraps its job id in a signed forge token (encodeJobToken).+ JWT_SECRET: 'test-jwt-secret-at-least-32-characters-long',+ });+});++// The self-host GCP worker accepts the job and returns a poll handle. Tests+// override it once to simulate a cold, failing or unconfigured worker.+const gcpSubmit = vi.fn(async () => ({ extJobId: 'gcpjob-modly-01', viewsUsed: 1, multiview: false }));+vi.mock('../../api/_providers/gcp.js', () => ({+ createRegenProvider: () => ({ submit: gcpSubmit }),+}));++vi.mock('../../api/_mcp3d/text-to-image.js', () => ({+ textToImage: vi.fn(async () => ({ imageUrl: 'https://cdn.example/ref.png', model: 'flux' })),+ synthesizeTurnaroundViews: vi.fn(async () => []),+}));++// Store: no real DB. createCreation returns an id; failures are recorded.+vi.mock('../../api/_lib/forge-store.js', () => ({+ hashClient: (v) => `client:${v || 'anon'}`,+ hashIp: (v) => `ip:${v}`,+ createCreation: vi.fn(async () => 'creation-1'),+ materializeCreation: vi.fn(async ({ glbUrl }) => ({ id: 'creation-1', glbUrl })),+ markFailed: vi.fn(async () => {}),+ findByJob: vi.fn(async () => null),+ runWithCreationContext: (_facts, fn) => fn(),+}));++// Lane health: report everything unknown (fail-open), as a deployment with no+// telemetry would. markLaneUnhealthy is asserted on the failover path.+vi.mock('../../api/_lib/forge-lane-health.js', () => ({+ laneHealthSnapshot: vi.fn(async () => ({ statusMap: {}, byId: {} })),+ markLaneUnhealthy: vi.fn(async () => {}),+ laneCooldownKey: (id) => `forge-lane:${id}`,+}));++vi.mock('../../api/_lib/forge-image-validate.js', () => ({+ validateForgeImage: vi.fn(async () => ({ ok: true })),+}));++vi.mock('../../api/_lib/rate-limit.js', async (importActual) => {+ const actual = await importActual();+ return {+ ...actual,+ limits: {+ ...actual.limits,+ mcp3dGenerate: vi.fn(async () => ({ success: true, reset: Date.now() + 1000 })),+ mcp3dGenerateFree: vi.fn(async () => ({ success: true, reset: Date.now() + 1000 })),+ },+ clientIp: () => '203.0.113.9',+ };+});++const { default: forgeHandler } = await import('../../api/forge.js');+const { default: gptForgeHandler } = await import('../../api/gpt-forge.js');+const { markLaneUnhealthy } = await import('../../api/_lib/forge-lane-health.js');+const { decodeJobToken } = await import('../../api/_lib/forge-job-token.js');++function makeReq(url, body, headers = {}) {+ return {+ method: 'POST',+ url,+ headers: { 'content-type': 'application/json', 'x-forge-client': 'tester', ...headers },+ on(event, cb) {+ if (event === 'data') cb(Buffer.from(JSON.stringify(body)));+ if (event === 'end') cb();+ },+ };+}++function makeRes() {+ return {+ statusCode: 200,+ headers: {},+ body: null,+ setHeader(name, value) {+ this.headers[String(name).toLowerCase()] = value;+ },+ end(body) {+ this.body = body ? JSON.parse(body) : null;+ },+ };+}++const PHOTO = 'https://cdn.example/photo.png';++function photoBody(backend, tier = 'standard') {+ return { image_urls: [PHOTO], tier, path: 'image', backend, skip_validation: true };+}++beforeEach(() => {+ gcpSubmit.mockReset();+ gcpSubmit.mockResolvedValue({ extJobId: 'gcpjob-modly-01', viewsUsed: 1, multiview: false });+ markLaneUnhealthy.mockClear();+});++describe.each([+ ['/api/forge', forgeHandler],+ ['/api/gpt-forge', gptForgeHandler],+])('%s: Modly lanes', (url, handler) => {+ it('an explicit modly pick submits Modly mode with the tier face budget', async () => {+ const res = makeRes();+ await handler(makeReq(url, photoBody('modly')), res);++ expect(res.statusCode).toBe(200);+ expect(res.body.backend).toBe('modly');+ expect(res.body.status).toBe('queued');+ expect(gcpSubmit).toHaveBeenCalledTimes(1);+ const call = gcpSubmit.mock.calls[0][0];+ expect(call.mode).toBe('modly');+ expect(call.sourceUrl).toBe(PHOTO);+ expect(call.params.images).toEqual([PHOTO]);+ expect(call.params.tier).toBe('standard');+ expect(call.params.target_polycount).toBe(30000);+ // The job handle polls back through the gcp provider.+ expect(decodeJobToken(res.body.job_id)).toMatchObject({ provider: 'gcp', taskId: 'gcpjob-modly-01' });+ });++ it('an explicit modly_hunyuan pick submits its own mode in a licensed territory', async () => {+ const res = makeRes();+ // The Tencent lanes fail closed on an unknown territory, so the edge+ // country header is what admits this request.+ await handler(makeReq(url, photoBody('modly_hunyuan', 'draft'), { 'cf-ipcountry': 'US' }), res);++ expect(res.statusCode).toBe(200);+ expect(res.body.backend).toBe('modly_hunyuan');+ const call = gcpSubmit.mock.calls[0][0];+ expect(call.mode).toBe('modly_hunyuan');+ expect(call.params.tier).toBe('draft');+ });++ it('a worker outage cools the Modly lane and retries the same views on TRELLIS.2', async () => {+ gcpSubmit.mockRejectedValueOnce(Object.assign(new Error('worker 503'), { code: 'provider_error', providerStatus: 503 }));+ const res = makeRes();+ await handler(makeReq(url, photoBody('modly')), res);++ expect(res.statusCode).toBe(200);+ expect(markLaneUnhealthy).toHaveBeenCalledWith('modly');+ expect(gcpSubmit).toHaveBeenCalledTimes(2);+ expect(gcpSubmit.mock.calls[0][0].mode).toBe('modly');+ const retry = gcpSubmit.mock.calls[1][0];+ expect(retry.mode).toBe('trellis2');+ expect(retry.params.images).toEqual([PHOTO]);+ expect(res.body.backend).toBe('trellis2');+ });++ it('refuses modly_hunyuan where the Tencent licence excludes the territory', async () => {+ const res = makeRes();+ await handler(makeReq(url, photoBody('modly_hunyuan'), { 'cf-ipcountry': 'DE' }), res);++ expect(res.statusCode).toBe(403);+ expect(res.body.error).toBe('region_restricted');+ expect(res.body.backend).toBe('modly_hunyuan');+ expect(res.body.retry_backends).not.toContain('modly_hunyuan');+ expect(gcpSubmit).not.toHaveBeenCalled();+ });++ it('serves the TripoSG lane in the same territory', async () => {+ const res = makeRes();+ await handler(makeReq(url, photoBody('modly'), { 'cf-ipcountry': 'DE' }), res);++ expect(res.statusCode).toBe(200);+ expect(res.body.backend).toBe('modly');+ });++ it('answers 501 naming the lane when the worker URL is not set', async () => {+ gcpSubmit.mockRejectedValueOnce(Object.assign(new Error('MODEL_MODLY_URL unset'), { code: 'mode_unconfigured' }));+ const res = makeRes();+ await handler(makeReq(url, photoBody('modly')), res);++ expect(res.statusCode).toBe(501);+ expect(res.body.error).toBe('backend_unconfigured');+ expect(res.body.backend).toBe('modly');+ expect(res.body.message).toContain('Modly TripoSG (self-host)');+ expect(markLaneUnhealthy).not.toHaveBeenCalled();+ });+});diff --git a/tests/api/forge-modly.test.js b/tests/api/forge-modly.test.jsnew file mode 100644index 000000000..ed1d438bd--- /dev/null+++ b/tests/api/forge-modly.test.js@@ -0,0 +1,369 @@+// The Modly lanes: registration, env gating, free-first routing placement,+// territory, the gcp provider's `modly` / `modly_hunyuan` wire contract, the+// self-host retry order, the poll-time failover rung and the health probe.+//+// One Modly worker (workers/modly, Modly by Lightning Pixel, MIT) serves both+// lanes: `modly` runs VAST AI's TripoSG, `modly_hunyuan` runs Tencent's+// Hunyuan3D 2 Mini Turbo. Both return untextured geometry, repaired and then+// decimated to the tier's poly budget by Modly's own mesh optimizer, so they+// rank below every textured free lane and TRELLIS.2 stays the default.++import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import {+ BACKENDS,+ FREE_DEFAULT_FOR_TIERS,+ FREE_FALLBACK_FOR_PATH,+ MODLY_LANES,+ backendIsConfigured,+ buildCatalog,+ freeLaneCandidates,+ isSelfHostImageLane,+ nextSelfHostImageLane,+ resolveBackendId,+ selfHostLaneName,+} from '../../api/_lib/forge-tiers.js';+import { TENCENT_LANES, laneAllowedInTerritory } from '../../api/_lib/forge-territory.js';+import { MODLY_MODEL_FOR_MODE, createRegenProvider } from '../../api/_providers/gcp.js';+import { retryBackendSuggestions, submitFailoverJob } from '../../api/_lib/forge-failover.js';+import { KEEPWARM_LANES } from '../../api/cron/gpu-keepwarm.js';+import { decodeJobToken } from '../../api/_lib/forge-job-token.js';++const VARS = [+ 'MODEL_MODLY_URL',+ 'MODEL_TRELLIS_URL',+ 'MODEL_TRELLIS2_URL',+ 'GCP_HUNYUAN3D_URL',+ 'GCP_TRIPOSG_URL',+ 'GCP_RECONSTRUCTION_KEY',+ 'NVIDIA_API_KEY',+ 'HF_TOKEN',+ 'REPLICATE_API_TOKEN',+ 'FORGE_SELFHOST_PRIMARY',+ 'JWT_SECRET',+];+const saved = {};+const ORIGINAL_FETCH = globalThis.fetch;+const MODLY_URL = 'https://model-modly.example.run.app';++beforeEach(() => {+ for (const v of VARS) {+ saved[v] = process.env[v];+ delete process.env[v];+ }+});+afterEach(() => {+ for (const v of VARS) {+ if (saved[v] === undefined) delete process.env[v];+ else process.env[v] = saved[v];+ }+ globalThis.fetch = ORIGINAL_FETCH;+ vi.restoreAllMocks();+});++function captureInfer(taskId = 'task-modly') {+ const sent = [];+ globalThis.fetch = vi.fn(async (url, opts) => {+ sent.push({ url: String(url), body: JSON.parse(opts.body), headers: opts.headers });+ return new Response(JSON.stringify({ task_id: taskId, status: 'queued' }), {+ status: 202,+ headers: { 'content-type': 'application/json' },+ });+ });+ return sent;+}++describe('forge-tiers: Modly lane registration', () => {+ it('registers both lanes as free, image-path, poly-aware self-host lanes on the gcp provider', () => {+ for (const id of ['modly', 'modly_hunyuan']) {+ const b = BACKENDS[id];+ expect(b, id).toBeTruthy();+ expect(b.id).toBe(id);+ expect(b.provider).toBe('gcp');+ expect(b.paths).toEqual(['image']);+ expect(b.byok).toBe(false);+ expect(b.free).toBe(true);+ expect(b.credits).toBeNull();+ expect(b.userImages).toBe(true);+ expect(b.polyControl).toBe(true);+ expect(b.coldStartSeconds).toBeGreaterThan(0);+ expect(b.requiresEnv).toEqual(['MODEL_MODLY_URL', 'GCP_RECONSTRUCTION_KEY']);+ expect(b.blurb).toMatch(/Untextured/);+ }+ expect(MODLY_LANES).toEqual(['modly', 'modly_hunyuan']);+ });++ it('is configured only when both the worker URL and the shared worker key are set', () => {+ expect(backendIsConfigured('modly')).toBe(false);+ process.env.MODEL_MODLY_URL = MODLY_URL;+ expect(backendIsConfigured('modly')).toBe(false);+ expect(backendIsConfigured('modly_hunyuan')).toBe(false);+ process.env.GCP_RECONSTRUCTION_KEY = 'secret';+ expect(backendIsConfigured('modly')).toBe(true);+ expect(backendIsConfigured('modly_hunyuan')).toBe(true);+ });++ it('shows up in the catalog as configured once both vars are set', () => {+ const before = buildCatalog().backends.find((x) => x.id === 'modly');+ expect(before?.configured).toBe(false);+ process.env.MODEL_MODLY_URL = MODLY_URL;+ process.env.GCP_RECONSTRUCTION_KEY = 'secret';+ const after = buildCatalog().backends.find((x) => x.id === 'modly');+ expect(after?.configured).toBe(true);+ expect(after?.free).toBe(true);+ });+});++describe('forge-tiers: Modly routing placement', () => {+ it('never replaces TRELLIS.2 as a named tier default', () => {+ for (const tier of ['draft', 'standard', 'high']) {+ expect(FREE_DEFAULT_FOR_TIERS[tier].image).toBe('trellis2');+ }+ });++ it('ranks below every textured free lane and above the text-only NVIDIA fallthrough', () => {+ const chain = FREE_FALLBACK_FOR_PATH.image;+ const hf = chain.indexOf('huggingface');+ const modly = chain.indexOf('modly');+ const modlyHunyuan = chain.indexOf('modly_hunyuan');+ expect(hf).toBeGreaterThan(-1);+ expect(modly).toBe(hf + 1);+ expect(modlyHunyuan).toBe(modly + 1);+ expect(chain.indexOf('nvidia')).toBe(modlyHunyuan + 1);+ });++ it('serves a photo when the Modly worker is the only free lane configured', () => {+ process.env.MODEL_MODLY_URL = MODLY_URL;+ process.env.GCP_RECONSTRUCTION_KEY = 'secret';+ expect(resolveBackendId({ path: 'image', tier: 'standard', userImages: true, country: 'US' })).toBe('modly');+ expect(freeLaneCandidates('image', 'standard', true, null, 'US')).toEqual(['modly', 'modly_hunyuan']);+ });++ it('keeps TRELLIS.2 first when both workers are configured', () => {+ process.env.MODEL_MODLY_URL = MODLY_URL;+ process.env.MODEL_TRELLIS2_URL = 'https://trellis2.example.run.app';+ process.env.GCP_RECONSTRUCTION_KEY = 'secret';+ for (const tier of ['draft', 'standard', 'high']) {+ expect(resolveBackendId({ path: 'image', tier, userImages: true, country: 'US' })).toBe('trellis2');+ }+ expect(freeLaneCandidates('image', 'standard', true, null, 'US')).toEqual(['trellis2', 'modly', 'modly_hunyuan']);+ });++ it('honours an explicit pick of either lane', () => {+ process.env.MODEL_MODLY_URL = MODLY_URL;+ process.env.MODEL_TRELLIS2_URL = 'https://trellis2.example.run.app';+ process.env.GCP_RECONSTRUCTION_KEY = 'secret';+ expect(resolveBackendId({ path: 'image', tier: 'standard', backend: 'modly', userImages: true, country: 'US' })).toBe('modly');+ expect(+ resolveBackendId({ path: 'image', tier: 'standard', backend: 'modly_hunyuan', userImages: true, country: 'US' }),+ ).toBe('modly_hunyuan');+ });+});++describe('forge-territory: Modly lanes', () => {+ it('treats the Hunyuan3D lane as a Tencent lane and TripoSG as territory-free', () => {+ expect(TENCENT_LANES).toContain('modly_hunyuan');+ expect(TENCENT_LANES).not.toContain('modly');+ for (const country of ['DE', 'GB', 'KR', null]) {+ expect(laneAllowedInTerritory('modly', country)).toBe(true);+ expect(laneAllowedInTerritory('modly_hunyuan', country)).toBe(false);+ }+ expect(laneAllowedInTerritory('modly_hunyuan', 'US')).toBe(true);+ });++ it('drops the Hunyuan3D lane from restricted-territory free routing', () => {+ process.env.MODEL_MODLY_URL = MODLY_URL;+ process.env.GCP_RECONSTRUCTION_KEY = 'secret';+ expect(freeLaneCandidates('image', 'standard', true, null, 'FR')).toEqual(['modly']);+ expect(freeLaneCandidates('image', 'standard', true, null, null)).toEqual(['modly']);+ });+});++describe('gcp provider: Modly wire contract', () => {+ beforeEach(() => {+ process.env.MODEL_MODLY_URL = MODLY_URL;+ process.env.GCP_RECONSTRUCTION_KEY = 'secret';+ });++ it('maps each lane to the model id the worker serves', () => {+ expect(MODLY_MODEL_FOR_MODE).toEqual({ modly: 'triposg', modly_hunyuan: 'hunyuan3d-mini-turbo' });+ });++ it('submits TripoSG with tier, seed, a repair pass and the poly budget as the decimate target', async () => {+ const sent = captureInfer();+ const submitted = await createRegenProvider().submit({+ mode: 'modly',+ sourceUrl: 'https://three.ws/cdn/photo.png',+ params: {+ images: ['https://three.ws/cdn/photo.png'],+ tier: 'standard',+ seed: 42,+ target_polycount: 30000,+ },+ });+ expect(sent).toHaveLength(1);+ expect(sent[0].url).toBe(`${MODLY_URL}/infer`);+ expect(sent[0].headers.authorization).toBe('Bearer secret');+ expect(sent[0].body).toEqual({+ images: ['https://three.ws/cdn/photo.png'],+ body_type: 'neutral',+ model: 'triposg',+ tier: 'standard',+ seed: 42,+ postprocess: { repair: true, decimate: { target_faces: 30000 } },+ });+ expect(submitted.backend).toBe('gcp');+ expect(submitted.viewsUsed).toBe(1);+ expect(submitted.multiview).toBe(false);+ expect(submitted.eta).toBeGreaterThan(0);+ });++ it('routes the Hunyuan lane to the same worker with its own model id', async () => {+ const sent = captureInfer();+ await createRegenProvider().submit({+ mode: 'modly_hunyuan',+ sourceUrl: 'https://three.ws/cdn/photo.png',+ params: { images: ['https://three.ws/cdn/photo.png'], tier: 'draft', target_polycount: 12000 },+ });+ expect(sent[0].url).toBe(`${MODLY_URL}/infer`);+ expect(sent[0].body.model).toBe('hunyuan3d-mini-turbo');+ expect(sent[0].body.postprocess.decimate).toEqual({ target_faces: 12000 });+ });++ it('clamps the decimate target to the bounds the worker accepts', async () => {+ const sent = captureInfer();+ const provider = createRegenProvider();+ for (const target_polycount of [5_000_000, 12]) {+ await provider.submit({+ mode: 'modly',+ sourceUrl: 'https://three.ws/cdn/photo.png',+ params: { images: ['https://three.ws/cdn/photo.png'], target_polycount },+ });+ }+ expect(sent[0].body.postprocess.decimate.target_faces).toBe(1_000_000);+ expect(sent[1].body.postprocess.decimate.target_faces).toBe(100);+ });++ it('still repairs but skips decimation when no budget is given', async () => {+ const sent = captureInfer();+ await createRegenProvider().submit({+ mode: 'modly',+ sourceUrl: 'https://three.ws/cdn/photo.png',+ params: {},+ });+ expect(sent[0].body.images).toEqual(['https://three.ws/cdn/photo.png']);+ expect(sent[0].body.postprocess).toEqual({ repair: true });+ expect(sent[0].body).not.toHaveProperty('seed');+ expect(sent[0].body).not.toHaveProperty('tier');+ });++ it('polls /tasks/:id and surfaces result_gcs_url as the GLB on done', async () => {+ globalThis.fetch = vi.fn(async (url) => {+ if (String(url).endsWith('/infer')) {+ return new Response(JSON.stringify({ task_id: 'task-m1', status: 'queued' }), { status: 202 });+ }+ expect(String(url)).toBe(`${MODLY_URL}/tasks/task-m1`);+ return new Response(+ JSON.stringify({+ task_id: 'task-m1',+ status: 'done',+ result_gcs_url: 'https://storage.googleapis.com/bucket/raw-meshes/modly/task-m1.glb',+ }),+ { status: 200 },+ );+ });+ const provider = createRegenProvider();+ const submitted = await provider.submit({+ mode: 'modly',+ sourceUrl: 'https://three.ws/cdn/photo.png',+ params: { images: ['https://three.ws/cdn/photo.png'] },+ });+ const status = await provider.status(submitted.extJobId);+ expect(status.status).toBe('done');+ expect(status.resultGlbUrl).toBe('https://storage.googleapis.com/bucket/raw-meshes/modly/task-m1.glb');+ });++ it('reports both modes unsupported without the worker URL', () => {+ delete process.env.MODEL_MODLY_URL;+ const provider = createRegenProvider();+ expect(provider.supportsMode('modly')).toBe(false);+ expect(provider.supportsMode('modly_hunyuan')).toBe(false);+ });+});++describe('self-host image lane helpers', () => {+ it('covers both TRELLIS workers and both Modly lanes', () => {+ for (const id of ['trellis2', 'trellis_selfhost', 'modly', 'modly_hunyuan']) {+ expect(isSelfHostImageLane(id)).toBe(true);+ }+ for (const id of ['hunyuan3d', 'huggingface', 'trellis', 'triposg']) {+ expect(isSelfHostImageLane(id)).toBe(false);+ }+ });++ it('names each lane in its not-configured message', () => {+ expect(selfHostLaneName('trellis2')).toBe('Self-hosted TRELLIS');+ expect(selfHostLaneName('modly')).toBe(BACKENDS.modly.label);+ expect(selfHostLaneName('modly_hunyuan')).toBe(BACKENDS.modly_hunyuan.label);+ });++ it('retries a down Modly worker on TRELLIS.2, then TRELLIS v1, never on its sibling', () => {+ process.env.GCP_RECONSTRUCTION_KEY = 'secret';+ process.env.MODEL_MODLY_URL = MODLY_URL;+ expect(nextSelfHostImageLane('modly')).toBeNull();+ process.env.MODEL_TRELLIS_URL = 'https://trellis.example.run.app';+ expect(nextSelfHostImageLane('modly')).toBe('trellis_selfhost');+ expect(nextSelfHostImageLane('modly_hunyuan')).toBe('trellis_selfhost');+ process.env.MODEL_TRELLIS2_URL = 'https://trellis2.example.run.app';+ expect(nextSelfHostImageLane('modly')).toBe('trellis2');+ expect(nextSelfHostImageLane('trellis2')).toBe('trellis_selfhost');+ expect(nextSelfHostImageLane('trellis_selfhost')).toBeNull();+ });+});++describe('forge-failover: Modly lanes', () => {+ it('suggests the Modly lanes last, after every textured lane', () => {+ process.env.GCP_RECONSTRUCTION_KEY = 'secret';+ process.env.MODEL_MODLY_URL = MODLY_URL;+ process.env.MODEL_TRELLIS2_URL = 'https://trellis2.example.run.app';+ expect(retryBackendSuggestions({ hasImage: true, country: 'US' })).toEqual(['trellis2', 'modly', 'modly_hunyuan']);+ expect(retryBackendSuggestions({ hasImage: true, country: 'DE' })).toEqual(['trellis2', 'modly']);+ expect(retryBackendSuggestions({ hasImage: true, attempted: ['trellis2', 'modly'], country: 'US' })).toEqual([+ 'modly_hunyuan',+ ]);+ });++ it('redispatches a failed job to the Modly worker with the tier budget', async () => {+ process.env.GCP_RECONSTRUCTION_KEY = 'secret';+ process.env.MODEL_MODLY_URL = MODLY_URL;+ // The poll handle is a signed forge job token.+ process.env.JWT_SECRET = 'test-jwt-secret-at-least-32-characters-long';+ const sent = captureInfer('task-failover');+ const out = await submitFailoverJob({+ backend: 'modly_hunyuan',+ imageUrl: 'https://three.ws/cdn/ref.png',+ prompt: 'a ceramic teapot',+ tierId: 'standard',+ path: 'image',+ });+ expect(sent[0].url).toBe(`${MODLY_URL}/infer`);+ expect(sent[0].body).toMatchObject({+ images: ['https://three.ws/cdn/ref.png'],+ model: 'hunyuan3d-mini-turbo',+ tier: 'standard',+ postprocess: { repair: true, decimate: { target_faces: 30000 } },+ });+ expect(out.extJobId).toBeTruthy();+ expect(decodeJobToken(out.handle)).toMatchObject({ provider: 'gcp', taskId: out.extJobId });+ });+});++describe('gpu-keepwarm: Modly worker', () => {+ it('lists both lanes against the one worker URL, quota-gated', () => {+ for (const id of ['modly', 'modly_hunyuan']) {+ const lane = KEEPWARM_LANES.find((l) => l.id === id);+ expect(lane, id).toBeTruthy();+ expect(lane.urlEnv).toBe('MODEL_MODLY_URL');+ expect(lane.safeByDefault).toBe(false);+ }+ });+});