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): tell every client a GPU worker is booting instead of "still rendering"
nirholas77d71d80f1d7
diff --git a/api/_mcp-studio/tools.js b/api/_mcp-studio/tools.jsindex f41273d8a..17076f732 100644--- a/api/_mcp-studio/tools.js+++ b/api/_mcp-studio/tools.js@@ -1,10 +1,11 @@// three.ws 3D Studio (free) — tool catalog + handlers.//-// This module holds eight of the connector's eleven tools: five generators +-// refine_model + check_job + look_at_model. The other three-// (create_agent_persona, get_agent_persona, persona_say) live in+// This module holds eight of the connector's eleven tools: the six generation+// tools (five generators plus refine_model) + check_job + look_at_model. The+// other three (create_agent_persona, get_agent_persona, persona_say) live in// ./persona-tools.js, and dispatch.js merges both catalogs into the single-// tools/list the endpoint serves.+// tools/list the endpoint serves. docs/mcp-studio.md splits the catalog the+// same way, and tests/mcp-studio.test.js pins the total at eleven.//// All eight are FREE (no x402, no// wallet, no API key): the platform's server-side keys cover provider cost via@@ -141,6 +142,20 @@ function toolError(message) {};}+// Lift the timing/warmth facts a poll payload carries into the shape+// pendingResult() reads. One helper rather than seven inline spreads, so a new+// field reaches every tool at once instead of the six that got remembered.+// Every value is passed straight through; nothing here is derived from a local+// clock, so a job handed back after a client reconnect reports the JOB's age.+function pendingTiming(job) {+ return {+ etaRemainingSeconds: job?.eta_remaining_seconds,+ coldStart: Boolean(job?.cold_start),+ coldStartSeconds: job?.cold_start_seconds ?? null,+ elapsedSeconds: job?.elapsed_seconds ?? null,+ };+}+// Success envelope for a job that outlived the inline wait budget but IS still// running. This used to be an error, which threw away real work: with the// self-host TRELLIS lane as forge primary a generation takes 4-6 minutes, the@@ -148,15 +163,56 @@ function toolError(message) {// quietly finished minutes later and the caller never learned. The job handle// is public (the free /api/forge poll endpoint takes it with no auth), so hand// it over and let the caller collect the result.-function pendingResult({ base, jobId, what, prompt, etaRemainingSeconds, stage = 'mesh' }) {+function pendingResult({+ base,+ jobId,+ what,+ prompt,+ etaRemainingSeconds,+ stage = 'mesh',+ coldStart = false,+ coldStartSeconds = null,+ elapsedSeconds = null,+}) {// The ChatGPT pipeline's own endpoint, not /api/forge: the whole point of// the clone is that this surface can evolve independently.const pollUrl = `${base}/api/gpt-forge?job=${encodeURIComponent(jobId)}`;- const eta = Number.isFinite(etaRemainingSeconds) && etaRemainingSeconds > 0 ? Math.round(etaRemainingSeconds) : null;+ const num = (v) => (Number.isFinite(Number(v)) && Number(v) > 0 ? Math.round(Number(v)) : null);+ const eta = num(etaRemainingSeconds);+ // Guard the null BEFORE the numeric compare: Number(null) is 0, which passes+ // `>= 0` and would report a job with no known age as "0s in".+ const elapsed =+ elapsedSeconds == null || !Number.isFinite(Number(elapsedSeconds)) || Number(elapsedSeconds) < 0+ ? null+ : Math.round(Number(elapsedSeconds));+ const coldTotal = num(coldStartSeconds);+ // A queued job on a scale-to-zero worker is a container boot, not a slow+ // render, and saying so is the difference between a client that waits and a+ // client that retries into the same boot. Every number here comes off the+ // poll payload; when the API reports the boot without a budget we name the+ // state and promise no time rather than inventing one.+ const bootLeft = coldStart && coldTotal != null && elapsed != null ? coldTotal - elapsed : null;+ let head;+ if (coldStart) {+ const budget =+ bootLeft != null+ ? bootLeft > 0+ ? ` (about ${bootLeft}s of boot left`+ : ` (past its usual ${coldTotal}s boot`+ : coldTotal != null+ ? ` (about ${coldTotal}s`+ : '';+ const elapsedNote = budget && elapsed != null && elapsed >= 5 ? `, ${elapsed}s in)` : budget ? ')' : '';+ head =+ `The GPU worker for this ${what} is waking up${budget}${elapsedNote}. ` ++ 'The job is accepted and rendering starts the moment it answers';+ } else {+ head = `The ${what} is still rendering (heavier scenes take a few minutes)${eta ? ` (roughly ${eta}s to go)` : ''}`;+ }+ const retryIn = coldStart && bootLeft != null && bootLeft > 0 ? bootLeft : eta;const message =- `The ${what} is still rendering (heavier scenes take a few minutes)` +- `${eta ? ` (roughly ${eta}s to go)` : ''}. ` +- `It keeps running: call the check_job tool with this job_id${eta ? ` in ~${eta}s` : ' shortly'} to collect it, ` ++ `${head}. ` ++ `It keeps running: call the check_job tool with this job_id${retryIn ? ` in ~${retryIn}s` : ' shortly'} to collect it, ` +`or poll ${pollUrl} until status is "done", then use its glb_url ` +`(view at ${base}/viewer?src=<glb_url>).`;return {@@ -171,6 +227,16 @@ function pendingResult({ base, jobId, what, prompt, etaRemainingSeconds, stage =// costs the data-minimization rule nothing.stage,...(eta ? { etaRemainingSeconds: eta } : {}),+ // Machine-readable twin of the sentence above, so a client can render+ // its own "waking up" state instead of parsing prose.+ ...(coldStart+ ? {+ coldStart: true,+ ...(coldTotal != null ? { coldStartSeconds: coldTotal } : {}),+ ...(bootLeft != null && bootLeft > 0 ? { coldStartRemainingSeconds: bootLeft } : {}),+ }+ : {}),+ ...(elapsed != null ? { elapsedSeconds: elapsed } : {}),...(prompt ? { prompt } : {}),},};@@ -320,7 +386,7 @@ async function handleForgeFree(args, _auth, req) {} catch (err) {return toolError(failureMessage(err));}- if (job._timedOut && job.job_id) return pendingResult({ base, jobId: job.job_id, what: 'model', prompt, etaRemainingSeconds: job.eta_remaining_seconds });+ if (job._timedOut && job.job_id) return pendingResult({ base, jobId: job.job_id, what: 'model', prompt, ...pendingTiming(job) });if (job._timedOut || !job.glb_url) return toolError('Generation is taking longer than expected. Please try again.');return ok({ glbUrl: job.glb_url, base, kind: 'model', prompt, referenceImageUrl: job.preview_image_url });}@@ -358,7 +424,7 @@ async function handleTextToAvatar(args, _auth, req) {} catch (err) {return toolError(failureMessage(err));}- if (job._timedOut && job.job_id) return pendingResult({ base, jobId: job.job_id, what: 'avatar', prompt: prompt || undefined, etaRemainingSeconds: job.eta_remaining_seconds });+ if (job._timedOut && job.job_id) return pendingResult({ base, jobId: job.job_id, what: 'avatar', prompt: prompt || undefined, ...pendingTiming(job) });if (job._timedOut || !job.glb_url) return toolError('Generation is taking longer than expected. Please try again.');return ok({ glbUrl: job.glb_url, base, kind: 'avatar', prompt: prompt || undefined, referenceImageUrl: job.preview_image_url });}@@ -410,7 +476,7 @@ async function handleMeshForge(args, _auth, req) {} catch (err) {return toolError(failureMessage(err));}- if (job._timedOut && job.job_id) return pendingResult({ base, jobId: job.job_id, what: 'mesh', prompt: prompt || undefined, etaRemainingSeconds: job.eta_remaining_seconds });+ if (job._timedOut && job.job_id) return pendingResult({ base, jobId: job.job_id, what: 'mesh', prompt: prompt || undefined, ...pendingTiming(job) });if (job._timedOut || !job.glb_url) return toolError('Generation is taking longer than expected. Please try again.');return ok({ glbUrl: job.glb_url, base, kind: 'mesh', prompt: prompt || undefined, referenceImageUrl: job.preview_image_url });}@@ -430,7 +496,7 @@ async function handleRigMesh(args, _auth, req) {} catch (err) {return toolError(failureMessage(err));}- if (job._timedOut && job.job_id) return pendingResult({ base, jobId: job.job_id, what: 'rigged model', etaRemainingSeconds: job.eta_remaining_seconds, stage: 'rig' });+ if (job._timedOut && job.job_id) return pendingResult({ base, jobId: job.job_id, what: 'rigged model', ...pendingTiming(job), stage: 'rig' });if (job._timedOut || !job.glb_url) return toolError('Rigging is taking longer than expected. Please try again.');return ok({ glbUrl: job.glb_url, base, kind: 'rigged model', rigged: true });}@@ -471,7 +537,7 @@ async function handleForgeAvatar(args, _auth, req) {} catch (err) {return toolError(failureMessage(err));}- if (gen._timedOut && gen.job_id) return pendingResult({ base, jobId: gen.job_id, what: 'avatar mesh (rig it with rig_mesh once done)', prompt: prompt || undefined, etaRemainingSeconds: gen.eta_remaining_seconds, stage: 'mesh' });+ if (gen._timedOut && gen.job_id) return pendingResult({ base, jobId: gen.job_id, what: 'avatar mesh (rig it with rig_mesh once done)', prompt: prompt || undefined, ...pendingTiming(gen), stage: 'mesh' });if (gen._timedOut || !gen.glb_url) return toolError('Generation is taking longer than expected. Please try again.');// Stage 2 — auto-rig the generated mesh.@@ -500,7 +566,7 @@ async function handleForgeAvatar(args, _auth, req) {],};}- if (rigged._timedOut && rigged.job_id) return pendingResult({ base, jobId: rigged.job_id, what: 'avatar rig', prompt: prompt || undefined, etaRemainingSeconds: rigged.eta_remaining_seconds, stage: 'rig' });+ if (rigged._timedOut && rigged.job_id) return pendingResult({ base, jobId: rigged.job_id, what: 'avatar rig', prompt: prompt || undefined, ...pendingTiming(rigged), stage: 'rig' });if (rigged._timedOut || !rigged.glb_url) return toolError('Rigging is taking longer than expected. Please try again.');return ok({ glbUrl: rigged.glb_url, base, kind: 'avatar', prompt: prompt || undefined, rigged: true, referenceImageUrl: gen.preview_image_url });}@@ -590,7 +656,7 @@ async function handleRefineModel(args, _auth, req) {jobId: job.job_id,what: 'refined model',prompt: composed || undefined,- etaRemainingSeconds: job.eta_remaining_seconds,+ ...pendingTiming(job),});if (job._timedOut || !job.glb_url) return toolError('Refinement is taking longer than expected. Please try again.');@@ -638,7 +704,7 @@ async function handleCheckJob(args, _auth, req) {jobId,what: 'model',prompt: typeof data.prompt === 'string' && data.prompt ? data.prompt : undefined,- etaRemainingSeconds: data.eta_remaining_seconds,+ ...pendingTiming(data),});}diff --git a/api/gpt-forge.js b/api/gpt-forge.jsindex 36c101a60..a36f541b2 100644--- a/api/gpt-forge.js+++ b/api/gpt-forge.js@@ -171,6 +171,29 @@ const NIM_TRELLIS_COOLDOWN_KEY = 'forge-nim-trellis';const NIM_FORGE_COOLDOWN_SECONDS = 120;const NIM_FORGE_GATEWAY_COOLDOWN_SECONDS = 30;+// Honest cold-start signal for a self-host lane: true only when the liveness+// probe reached the worker but it answered slowly (a scale-to-zero container+// spinning up). Reuses the cached lane-health snapshot, so the common path pays+// no extra probe. Used to widen the ETA + flag `cold_start`, never to fabricate+// progress; the client's real polling still drives actual status.+//+// Module-level because BOTH ends of a job need it, exactly as in api/forge.js.+// This lived only as a closure inside the submit handler until now, so only the+// submit response could say a worker was booting. ChatGPT and every other MCP+// client sees ONLY poll frames after submit, which meant the one surface that+// depends entirely on polling was the one surface that could never explain a+// container boot: it showed "still rendering" for the whole spin-up.+async function laneColdStart(backendId) {+ if (!backendId || !isSelfHostBackend(backendId) || !coldStartSecondsFor(backendId)) return false;+ try {+ const snap = await laneHealthSnapshot([backendId]);+ const rec = snap.byId[backendId];+ return Boolean(rec && rec.status === 'ok' && rec.warm === false);+ } catch {+ return false;+ }+}+// The platform-keyed paid reconstruct lane (Replicate TRELLIS) recorded as down.// Set only on an out-of-credit/billing failure: which won't self-heal until ops// tops the account up, so the window is long (reason 'auth'). The NIM-cooldown@@ -1171,21 +1194,10 @@ async function startJob(req, res) {}}- // Honest cold-start signal for a chosen self-host lane: true only when the- // liveness probe reached the worker but it answered slowly (a scale-to-zero- // container spinning up). Reuses the cached snapshot, so the common path pays no- // extra probe. Used to widen the ETA + flag `cold_start` in the response, never- // to fabricate progress; the client's real polling still drives actual status.- const coldStartFor = async (id) => {- if (!isSelfHostBackend(id) || !coldStartSecondsFor(id)) return false;- try {- const snap = await laneHealthSnapshot([id]);- const rec = snap.byId[id];- return Boolean(rec && rec.status === 'ok' && rec.warm === false);- } catch {- return false;- }- };+ // Honest cold-start signal for a chosen self-host lane. The implementation is+ // the module-level laneColdStart above, so the submit and poll ends of a job+ // answer this question identically instead of drifting.+ const coldStartFor = laneColdStart;// Content-addressed result cache (see _lib/forge-cache.js): a text→3D request// on a platform-keyed lane (never BYOK: that spends the caller's own account,@@ -3053,9 +3065,17 @@ async function pollJob(req, res, jobId) {? Math.max(0, Math.round((Date.now() - Date.parse(meta.created_at)) / 1000)): null;const etaSeconds = meta?.backend ? estimateEtaSeconds({ backendId: meta.backend, tier: meta.tier }) : null;+ // A job still QUEUED on a scale-to-zero self-host worker is waiting on a+ // container boot, and that is the one wait a client can explain instead of+ // showing an unmoving "still rendering". Resolved from the cached lane-health+ // snapshot (one probe per 20s per instance, shared across every concurrent+ // poll), and only while queued: a worker that answered "running" is up by+ // definition, so the flag clears on a real signal rather than on a timer.+ const pendingStatus = result.status || 'running';+ const cold = pendingStatus === 'queued' ? await laneColdStart(meta?.backend) : false;return json(res, 200, {job_id: jobId,- status: result.status || 'running',+ status: pendingStatus,...metaFields,...(elapsedSeconds != null ? { elapsed_seconds: elapsedSeconds } : {}),...(etaSeconds != null@@ -3065,6 +3085,7 @@ async function pollJob(req, res, jobId) {elapsedSeconds != null ? Math.max(5, etaSeconds - elapsedSeconds) : etaSeconds,}: {}),+ ...(cold ? { cold_start: true, cold_start_seconds: coldStartSecondsFor(meta?.backend) } : {}),});}diff --git a/docs/mcp-3d-studio.md b/docs/mcp-3d-studio.mdindex 1b1138eb4..841ec9d80 100644--- a/docs/mcp-3d-studio.md+++ b/docs/mcp-3d-studio.md@@ -45,6 +45,7 @@ analyze: inspect_model · optimize_model preview: preview_3d| `animation_signature(clip, slot?)` | A clip's measured motion: energy, tempo, leading region, loop seam, travel. Pass `slot` for an ok/warn fit verdict against a runtime slot. || `find_similar_animations(clip, limit?)` | The library ranked by measured-motion distance from a reference clip: "more like this" for animations. || `apply_animation(model_url, animation, format?, speed?)` | Retarget a preset clip onto a rigged GLB — returns the retargeted `AnimationClip` JSON (or a baked animated GLB). |+| `text_to_animation(prompt, model_url?, duration_seconds?, format?, speed?)` | Generate a brand-new motion from a prompt ("waving confidently", "a slow tai-chi sweep") with a motion-diffusion model, then retarget it onto a rigged humanoid GLB with the same engine `apply_animation` uses. || `pose_model(prompt)` | Map a pose description to a deterministic seed + full Euler joint-rotation map from the in-repo preset library. Deterministic: the same prompt always returns the same seed. Priced at $0.01 (see the table below). |### Edit & process the mesh@@ -57,6 +58,7 @@ analyze: inspect_model · optimize_model preview: preview_3d| `retexture_model(mesh_url, prompt, num_views?, texture_size?)` | Paint a fresh texture from a prompt (SDXL + ControlNet depth, multi-view back-projection). || `retexture_region(mesh_url, mask_url, prompt?, color?, …)` | Magic-brush: repaint only a masked UV region, feathering the seam. || `generate_material(description, name?)` | IBM Granite → a glTF 2.0 PBR material (base color, metallic, roughness, emissive). |+| `remove_background(image_url, model?)` | Strip the background from a photo or illustration, returning a transparent PNG: a clean input for `image_to_3d`. |### Assist, analyze & preview@@ -67,6 +69,13 @@ analyze: inspect_model · optimize_model preview: preview_3d| `optimize_model(url)` | Actionable size/perf suggestions: Draco/Meshopt, KTX2, triangle budget. || `preview_3d(glb_url, …)` | Render any public GLB as an interactive `<model-viewer>` artifact (orbit, AR, auto-rotate). || `export_ar(glb_url, title?, kind?)` | Read-only: turn any public GLB into the device-aware AR link set (`arLaunchUrl`, `sceneViewerUrl`, `viewerUrl`, plus `irlUrl` when `kind: "avatar"`) and a [Spatial MCP](./spatial-mcp.md) artifact. Free. See [AR & WebXR](./ar.md#one-tap-ar-for-any-glb--get-apiar--export_ar). |+| `getting_started(section?)` | Free, no credentials: an overview of every tool, how to get access, and the useful links. Call it first to orient. |+| `save_avatar(glb_url, name, visibility?, source_prompt?, tags?)` | Copy a generated GLB into three.ws storage (so it survives the provider URL expiring) and register it as a named avatar you own. Free. |+| `capture_scene(video_url, mode?, fps?, …)` | Reconstruct a real space from a video walkaround into an explorable 3D point cloud (LingBot-Map streaming reconstructor, drift-corrected across the clip). |+| `grade_sim_readiness(glb_url, hash?)` | Free: can this GLB be dropped into a physics simulator (MuJoCo, Isaac, Bullet, a game engine) and behave? Returns `simulation_ready`, `needs_scale`, `needs_repair`, or `unusable`, plus the measurements behind the verdict. |+| `anchor_provenance(glb_url, creator?, prompt?, …)` | Issue a signed content credential for a generated GLB and anchor its hash on Solana, so anyone can later check authenticity for free. |+| `verify_provenance(glb_url, hash?)` | Free: recompute the model’s content hash, check the signed credential and its on-chain anchor, and answer `verified`, `tampered`, or `unknown`. |+| `validate_spatial_response(artifact)` | Free: check a structured-content payload against the open [Spatial MCP](./spatial-mcp.md) artifact shape before you ship it. || `x402_preflight(origin, network?)` | Read-only, free: fetch an x402 seller's signed payability attestation from `<origin>/.well-known/x402-preflight`, verify its ed25519 signature, expiry, and subject, and answer whether that seller can actually settle before you pay it. An attestation that does not verify is reported as unverified, never as health. Spec: [`specs/x402-preflight.md`](../specs/x402-preflight.md). |Generation, rigging, and most mesh ops are **asynchronous**: the tool returns a@@ -155,9 +164,26 @@ key per poll.## Access & pricing-Discovery is free for everyone: `initialize`, `tools/list`, `ping`, and the-`getting_started` tool answer with no credentials, so any agent or crawler can-read the catalog before deciding to pay.+Discovery is free: a discovery-only batch (`initialize`, `tools/list`, `ping`)+and the public `getting_started` tool answer with no credentials, so any x402+agent, registry validator, or crawler can read the catalog before deciding to+pay.++```bash+curl -s https://three.ws/api/mcp-3d \+ -H 'content-type: application/json' \+ -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'+```++One deliberate exception: an **MCP protocol client** still gets `401` on+discovery. A request carrying `mcp-protocol-version`, `mcp-session-id`, or an+`Accept` of `text/event-stream` (the MCP TS SDK, the Inspector, the claude.ai+connector) is answered with a `WWW-Authenticate` challenge instead, because the+MCP authorization spec (RFC 9728) requires a 401 for the client to find the+protected-resource metadata and start the OAuth flow. That branch is+`isMcpProtocolClient` in [`api/_mcp/auth.js`](../api/_mcp/auth.js). So adding the+connector and signing in works; a plain `curl` that sets the SSE accept header+sees a challenge rather than the catalog, and should drop that header to browse.For tool calls there are two lanes:diff --git a/pages/home.html b/pages/home.htmlindex e2ef1d08e..815e6dbe6 100644--- a/pages/home.html+++ b/pages/home.html@@ -227,6 +227,11 @@<div class="hf-step" data-hf-step="mesh" data-state="pending"><span class="dot" aria-hidden="true"></span><span data-i18n="home.reconstructing_textured_mesh">Reconstructing textured mesh</span></div><div class="hf-step" data-hf-step="finish" data-state="pending"><span class="dot" aria-hidden="true"></span><span data-i18n="home.finalizing_glb">Finalizing GLB</span></div></div>+ <!-- Cold-start honesty: shown only while /api/forge reports cold_start+ for the chosen self-hosted GPU lane, and cleared by the first real+ "running" poll, never by a timer. Its text is written from the+ poll payload's own numbers (see src/home-forge.js). -->+ <p class="hf-warming" data-hf-warming role="status" hidden></p><button type="button" class="hf-btn" data-hf-cancel data-i18n="home.cancel">Cancel</button></div>@@ -1883,6 +1888,15 @@ import { attendRotation } from '/src/shared/attended-rotation.js';#home-forge .hf-step[data-state='done'] { color: var(--text-2); }#home-forge .hf-step[data-state='done'] .dot { background: #58d68d; border-color: #58d68d; }@keyframes hf-spin { to { transform: rotate(360deg); } }+ /* Cold start: a GPU booting is a nameable wait, so it reads as information+ rather than as an error. Sits under the steps it explains. */+ #home-forge .hf-warming { display: flex; align-items: center; gap: 8px; margin: 10px 0 0; max-width: 34ch; font-family: var(--font-mono); font-size: 11px; line-height: 1.5; letter-spacing: 0.03em; color: var(--text-2); }+ #home-forge .hf-warming[hidden] { display: none; }+ #home-forge .hf-warming::before { content: ''; width: 7px; height: 7px; border-radius: 50%; background: #ffb454; flex: none; animation: hf-warm-pulse 1.6s ease-in-out infinite; }+ @keyframes hf-warm-pulse { 0%, 100% { opacity: 0.35; transform: scale(0.85); } 50% { opacity: 1; transform: scale(1); } }+ @media (prefers-reduced-motion: reduce) {+ #home-forge .hf-warming::before { animation: none; opacity: 1; }+ }#home-forge .hf-preview { width: 132px; aspect-ratio: 1 / 1; border-radius: 12px; border: 1px solid var(--hairline); overflow: hidden; display: none; }#home-forge .hf-preview img { width: 100%; height: 100%; object-fit: cover; display: block; }#home-forge .hf-preview.is-on { display: block; }diff --git a/src/forge-studio/forge.js b/src/forge-studio/forge.jsindex a70a08295..1c8a1b185 100644--- a/src/forge-studio/forge.js+++ b/src/forge-studio/forge.js@@ -1467,6 +1467,24 @@ async function startJob({ prompt, imageUrls, skipValidation, payment }) {return data;}+// A queued job on a scale-to-zero GPU worker is a container boot, not a queue,+// and the two deserve different words: "In line for a GPU" tells someone their+// job is behind other work, which is wrong and unfixable-sounding, when in fact+// nothing is ahead of them and the wait has a known end. Returns null when the+// API does not report a cold start, so the caller keeps its queue wording.+// Every number comes off the poll payload; nothing is timed locally.+function coldStartLabel(job) {+ if (!job?.cold_start) return null;+ const num = (v) => (Number.isFinite(Number(v)) && Number(v) > 0 ? Math.round(Number(v)) : null);+ const budget = num(job.cold_start_seconds);+ const elapsed = num(job.elapsed_seconds);+ const bootLeft = budget != null && elapsed != null ? budget - elapsed : null;+ if (bootLeft != null && bootLeft > 0) return `Waking up a GPU: about ${bootLeft}s of boot left`;+ // Past the stated budget: say so rather than counting into negatives.+ if (bootLeft != null) return 'Still waking the GPU: it starts the moment the worker answers';+ return budget ? `Waking up a GPU (about ${budget}s)` : 'Waking up a GPU';+}+async function pollUntilDone(jobId) {let deadline = performance.now() + MAX_POLL_MS;// Queue-state tracking: a job waiting for a GPU is alive, so say so (after a@@ -1503,7 +1521,18 @@ async function pollUntilDone(jobId) {setStep('mesh', 'active');deadline = performance.now() + MAX_POLL_MS;queuedPolls += 1;- if (!inQueue && queuedPolls >= 3) {+ // A cold start is stated by the API, not guessed from how long we have+ // been waiting, so it skips the 3-poll grace and names itself on the+ // first frame that reports it. The label is rewritten every poll, so the+ // boot countdown actually moves instead of freezing on its first value.+ const coldLabel = coldStartLabel(data);+ if (coldLabel) {+ if (!inQueue) {+ inQueue = true;+ preQueueMeshLabel = els.steps?.mesh?.querySelector('span:last-child')?.textContent || null;+ }+ setStepLabel('mesh', coldLabel);+ } else if (!inQueue && queuedPolls >= 3) {inQueue = true;preQueueMeshLabel = els.steps?.mesh?.querySelector('span:last-child')?.textContent || null;setStepLabel('mesh', 'In line for a GPU');diff --git a/src/game/forge-prop.js b/src/game/forge-prop.jsindex 2c3aafcae..21795584c 100644--- a/src/game/forge-prop.js+++ b/src/game/forge-prop.js@@ -109,9 +109,41 @@ async function uploadReferenceImage(file, { onStatus, signal } = {}) {return grant.public_url;}-function statusLine(state, etaSeconds) {- const eta = Number.isFinite(etaSeconds) && etaSeconds > 0 ? ` (~${Math.round(etaSeconds)}s)` : '';- return state === 'queued' ? `Forging: waiting for a slot${eta}…` : `Forging your model${eta}…`;+// One progress line from a real /api/forge frame. Every number here is read off+// the payload; nothing is timed locally, so a slow job reports its own age+// rather than the tab's.+//+// Two states this used to flatten into "waiting for a slot":+// • A scale-to-zero GPU worker booting. That is a nameable wait with a stated+// budget (`cold_start` + `cold_start_seconds`), not an anonymous queue.+// • The countdown. It printed `eta_seconds`, the lane's static TOTAL, on every+// frame, so a two-minute wait read as a bar stuck at the same "~60s" the+// whole time. `eta_remaining_seconds` is the live figure and leads now.+function statusLine(job = {}) {+ const num = (v) => (Number.isFinite(Number(v)) && Number(v) > 0 ? Math.round(Number(v)) : null);+ const remaining = num(job.eta_remaining_seconds) ?? num(job.eta_seconds);+ const elapsed = num(job.elapsed_seconds);+ // Elapsed is only worth showing once it means something; under 5s it just+ // flickers as the first polls land.+ const notes = [elapsed && elapsed >= 5 ? `${elapsed}s in` : null, remaining ? `~${remaining}s left` : null].filter(+ Boolean,+ );+ const suffix = notes.length ? ` (${notes.join(', ')})` : '';+ if (job.cold_start) {+ const budget = num(job.cold_start_seconds);+ const bootLeft = budget != null && elapsed != null ? budget - elapsed : null;+ if (bootLeft != null && bootLeft > 0) {+ return `Waking up a GPU: about ${bootLeft}s of boot left${elapsed >= 5 ? ` (${elapsed}s in)` : ''}…`;+ }+ // Past the stated budget: say so rather than counting into negatives.+ if (bootLeft != null) {+ return `Still waking the GPU${elapsed >= 5 ? ` (${elapsed}s in)` : ''}. Forging starts the moment it answers…`;+ }+ return budget ? `Waking up a GPU (about ${budget}s), then forging…` : 'Waking up a GPU, then forging…';+ }+ return job.status === 'queued'+ ? `Forging: waiting for a slot${suffix}…`+ : `Forging your model${suffix}…`;}/**@@ -157,7 +189,7 @@ export async function forgeWorldProp({ prompt = '', file = null, onStatus, signa}if (!data.job_id) throw new ForgeError('The forge did not accept that request. Try rephrasing it.');- onStatus?.(statusLine('queued', data.eta_seconds));+ onStatus?.(statusLine({ ...data, status: 'queued' }));const deadline = Date.now() + MAX_WAIT_MS;while (Date.now() < deadline) {throwIfAborted(signal);@@ -182,7 +214,7 @@ export async function forgeWorldProp({ prompt = '', file = null, onStatus, signaconst detail = typeof job.error === 'string' && job.error.length < 200 ? job.error : '';throw new ForgeError(detail ? `The forge could not build that: ${detail}` : 'The forge could not build that. Try different wording.');}- onStatus?.(statusLine(job.status === 'queued' ? 'queued' : 'running', job.eta_seconds));+ onStatus?.(statusLine(job));}throw new ForgeError('The forge is taking too long. Your item may still finish in the /forge gallery.');}diff --git a/src/home-forge.js b/src/home-forge.jsindex f6ef0b7c3..be7b42316 100644--- a/src/home-forge.js+++ b/src/home-forge.js@@ -97,6 +97,7 @@ const els = root && {finish: root.querySelector('[data-hf-step="finish"]'),},elapsed: root.querySelector('[data-hf-elapsed]'),+ warming: root.querySelector('[data-hf-warming]'),cancel: root.querySelector('[data-hf-cancel]'),resultRegion: root.querySelector('[data-hf-result-region]'),resultMeta: root.querySelector('[data-hf-result-meta]'),@@ -208,6 +209,40 @@ function setStep(name, state) {els.steps[name].dataset.state = state;}+// Cold-start line, written from a real /api/forge poll frame and nothing else.+// A queued job on a scale-to-zero worker is a container boot: the one wait the+// page can name instead of showing a step that spins with no explanation. The+// API states both the flag and the lane's boot budget (`cold_start`,+// `cold_start_seconds`), and `elapsed_seconds` is the JOB's age, so a page+// resumed mid-generation counts from the submit, not from the reload.+// Passing a frame that is not cold clears the line: it is dismissed by the+// first real "running" poll, never by a timer.+function setWarming(job) {+ if (!els.warming) return;+ if (!job?.cold_start) {+ els.warming.hidden = true;+ els.warming.textContent = '';+ return;+ }+ const num = (v) => (Number.isFinite(Number(v)) && Number(v) > 0 ? Math.round(Number(v)) : null);+ const budget = num(job.cold_start_seconds);+ const elapsed = num(job.elapsed_seconds);+ const bootLeft = budget != null && elapsed != null ? budget - elapsed : null;+ let text;+ if (bootLeft != null && bootLeft > 0) {+ text = `Waking up a GPU: about ${bootLeft}s of boot left. Sculpting starts the moment it answers.`;+ } else if (bootLeft != null) {+ // Past the stated budget: say so rather than counting into negatives.+ text = `Still waking the GPU (${elapsed}s in). Your job is accepted and starts the moment it answers.`;+ } else if (budget != null) {+ text = `Waking up a GPU (about ${budget}s), then sculpting starts.`;+ } else {+ text = 'Waking up a GPU, then sculpting starts.';+ }+ els.warming.textContent = text;+ els.warming.hidden = false;+}+function startElapsed() {const t0 = performance.now();stopElapsed();@@ -468,12 +503,20 @@ async function pollUntilDone(jobId, seq) {// A queued job is alive and waiting for a GPU: keep the step live and// never spend the run budget on line time.setStep('mesh', 'active');+ setWarming(data);deadline = runNow() + MAX_POLL_MS;}- if (data.status === 'running') setStep('mesh', 'active');+ if (data.status === 'running') {+ setStep('mesh', 'active');+ // The worker answered: the boot is over by definition.+ setWarming(null);+ }}} finally {hidden.stop();+ // Never leave the boot line standing over a finished, failed, cancelled or+ // timed-out run.+ setWarming(null);}if (pollAbort || seq !== runSeq) return null;throw new Error('Generation timed out — try a simpler, single-subject prompt.');diff --git a/tests/mcp-studio-coldstart.test.js b/tests/mcp-studio-coldstart.test.jsnew file mode 100644index 000000000..c9d52ceaa--- /dev/null+++ b/tests/mcp-studio-coldstart.test.js@@ -0,0 +1,96 @@+// A pending studio job whose GPU worker is still BOOTING must say so.+//+// The MCP surfaces (ChatGPT and any other client) see only poll frames after+// submit, so they are the surfaces most dependent on the poll payload telling+// the truth, and they were the ones it did not reach: /api/gpt-forge computed+// `cold_start` inside a closure in its submit handler only, so a queued job on a+// scale-to-zero worker polled back as a plain "still rendering". A caller was+// told to retry in the render ETA while the real wait was a container spin-up,+// and nothing in the response distinguished a 75s Hunyuan3D boot from a slow+// model. api/forge.js already hoisted the same helper to module scope for+// exactly this reason; these tests pin the clone's behaviour to it.+//+// Every number asserted here comes off the poll payload. Nothing is timed+// locally, so a job collected after a client reconnect reports the JOB's age.++import { describe, it, expect, vi } from 'vitest';++const poll = vi.fn();++vi.mock('../api/_mcp-studio/gpt-forge-client.js', async (importOriginal) => {+ const real = await importOriginal();+ return {+ ...real,+ generate: vi.fn(async () => ({ status: 'queued', _timedOut: true, job_id: 'job-cold' })),+ pollOnce: (...args) => poll(...args),+ directPrompt: vi.fn(async () => null),+ };+});++import { dispatch } from '../api/_mcp-studio/dispatch.js';++const req = { headers: { host: 'three.ws', 'x-forwarded-proto': 'https' } };++async function checkJob(frame) {+ poll.mockResolvedValueOnce(frame);+ const res = await dispatch(+ { jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'check_job', arguments: { job_id: 'job-cold' } } },+ {},+ req,+ );+ return res.result;+}++describe('studio cold-start honesty', () => {+ it('names the boot and counts the remaining spin-up from the payload', async () => {+ const r = await checkJob({+ status: 'queued',+ cold_start: true,+ cold_start_seconds: 75,+ elapsed_seconds: 20,+ eta_remaining_seconds: 180,+ });+ expect(r.isError).toBeFalsy();+ expect(r.structuredContent.status).toBe('pending');+ expect(r.structuredContent.coldStart).toBe(true);+ expect(r.structuredContent.coldStartSeconds).toBe(75);+ // 75s budget minus 20s already elapsed, straight from the frame.+ expect(r.structuredContent.coldStartRemainingSeconds).toBe(55);+ expect(r.content[0].text).toContain('waking up');+ expect(r.content[0].text).toContain('55s of boot left');+ // The retry hint tracks the BOOT, not the render ETA: telling a caller to+ // come back in 180s when the worker answers in 55 wastes two minutes.+ expect(r.content[0].text).toContain('in ~55s');+ });++ it('a boot past its budget says so instead of counting into negatives', async () => {+ const r = await checkJob({+ status: 'queued',+ cold_start: true,+ cold_start_seconds: 75,+ elapsed_seconds: 200,+ eta_remaining_seconds: 60,+ });+ expect(r.content[0].text).toContain('past its usual 75s boot');+ expect(r.content[0].text).not.toMatch(/-\d+s/);+ expect(r.structuredContent.coldStartRemainingSeconds).toBeUndefined();+ });++ it('a cold lane with no stated budget names the state and promises no number', async () => {+ const r = await checkJob({ status: 'queued', cold_start: true });+ expect(r.content[0].text).toContain('waking up');+ expect(r.content[0].text).not.toMatch(/\d+s of boot/);+ expect(r.structuredContent.coldStart).toBe(true);+ expect(r.structuredContent.coldStartSeconds).toBeUndefined();+ // No elapsed in the frame must not become "0s in": Number(null) is 0.+ expect(r.structuredContent.elapsedSeconds).toBeUndefined();+ });++ it('a warm job keeps the plain rendering copy and carries no cold flag', async () => {+ const r = await checkJob({ status: 'running', elapsed_seconds: 40, eta_remaining_seconds: 75 });+ expect(r.content[0].text).toContain('still rendering');+ expect(r.content[0].text).not.toContain('waking up');+ expect(r.structuredContent.coldStart).toBeUndefined();+ expect(r.structuredContent.etaRemainingSeconds).toBe(75);+ });+});