Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

fix(forge): recover orphaned generations unattended, and pin the studio contracts

nirholas69c92564458e
diff --git a/api/cron/forge-finalize.js b/api/cron/forge-finalize.js
index a2bd49336..f034a43c1 100644
--- a/api/cron/forge-finalize.js
+++ b/api/cron/forge-finalize.js
@@ -125,6 +125,39 @@ async function writeCronHop(replicateJobId, value) {
}
}
+/**
+ * Decide what this sweep may do with a self-host poll that came back FAILED.
+ * Pure: no clock, no I/O, no Redis - the caller supplies the resolved facts.
+ * Factored out (like decideSelfhostMissing in _lib/forge-selfhost-recovery.js)
+ * because the swarm-safety rule here is subtle enough to deserve its own tests:
+ * acting too early races a live browser into duplicate GPU work, and acting
+ * never is what made the orphan class permanent.
+ *
+ * @returns {'defer'|'redispatch'|'terminal'}
+ * - defer: an attended client may still handle it; leave the row alone.
+ * - redispatch: resubmit to the next healthy lane.
+ * - terminal: nothing left to try; mark it failed and notify.
+ */
+export function decideFailedSweep({
+ ageMinutes,
+ hop = 0,
+ hasReferenceImage = false,
+ path = null,
+ attendedBudgetMinutes = ATTENDED_POLL_BUDGET_MINUTES,
+ maxHops = MAX_FAILOVER_HOPS,
+} = {}) {
+ // Inside the attended window a live browser runs its own poll-time failover.
+ // Acting here would duplicate that GPU work on the same generation.
+ if (Number.isFinite(ageMinutes) && ageMinutes < attendedBudgetMinutes) return 'defer';
+ // A redispatch reconstructs from the stored reference view, so a job without
+ // one has nothing to resubmit. Sketch keeps its single purpose-built lane
+ // (reconstruct models do badly on drawings).
+ if (!hasReferenceImage || path === 'sketch') return 'terminal';
+ // Bounded chain, same cap as the attended path.
+ if (hop >= maxHops) return 'terminal';
+ return 'redispatch';
+}
+
// Unattended twin of the poll handler's automatic lane failover (api/forge.js
// pollJob). The 30-minute worker orphan class lands here by construction: the
// worker only declares an orphan long after every browser has stopped polling,
@@ -133,11 +166,16 @@ async function writeCronHop(replicateJobId, value) {
// resubmit to the next healthy lane instead. The successor gets its own
// creation row (same client/user), so this same cron sweeps it to completion
// and the completion notification still fires for a model, not a failure.
-async function tryCronRedispatch(row) {
- if (!row.preview_image_url || row.path === 'sketch') return false;
+async function tryCronRedispatch(row, ageMinutes) {
const prior = await readCronHop(row.replicate_job_id);
const hop = prior ? prior.hop : 0;
- if (hop >= MAX_FAILOVER_HOPS) return false;
+ const decision = decideFailedSweep({
+ ageMinutes,
+ hop,
+ hasReferenceImage: Boolean(row.preview_image_url),
+ path: row.path,
+ });
+ if (decision !== 'redispatch') return false;
const attempted = [...new Set([...(prior?.attempted || []), row.backend].filter(Boolean))];
const nextLane = await pickRedispatchLane({ attempted });
if (!nextLane) return false;
@@ -257,12 +295,12 @@ export default wrapCron(async (req, res) => {
// seconds from now and run its own failover; acting here would race
// it into duplicate GPU work. Leave the row: an attended client
// resolves it, and an abandoned one ages into the branch below.
- if (ageMinutes < ATTENDED_POLL_BUDGET_MINUTES) {
+ if (decideFailedSweep({ ageMinutes, hasReferenceImage: true }) === 'defer') {
out.still_running++;
continue;
}
if (row.backend) await markLaneUnhealthy(row.backend).catch(() => {});
- if (await tryCronRedispatch(row)) {
+ if (await tryCronRedispatch(row, ageMinutes)) {
await markFailed({
replicateJobId: row.replicate_job_id,
clientKey: row.client_key,
diff --git a/docs/mcp-studio.md b/docs/mcp-studio.md
index 9fbefa25c..15250af8f 100644
--- a/docs/mcp-studio.md
+++ b/docs/mcp-studio.md
@@ -60,15 +60,17 @@ launcher, living avatars, link unfurls) is documented end to end in
## Tools
-The server exposes **nine** tools: the six generation tools documented here, plus
-three persona/embodiment tools (`create_agent_persona`, `get_agent_persona`,
-`persona_say`) documented in the **Embodiment** section below. All nine are free
-and keyless.
+The server exposes **ten** tools: the six generation tools documented here, the
+`check_job` collector, plus three persona/embodiment tools
+(`create_agent_persona`, `get_agent_persona`, `persona_say`) documented in the
+**Embodiment** section below. All ten are free and keyless.
All six generation tools are free and run operator-funded on the platform's own
generation pipeline. Annotations: `readOnlyHint:false`, `destructiveHint:false`,
`idempotentHint:false`, `openWorldHint:true` (work runs against external model
-APIs; nothing is ever modified or deleted).
+APIs; nothing is ever modified or deleted). `check_job` is the exception: it is a
+pure status probe (`readOnlyHint:true`, `idempotentHint:true`) and never counts
+against the generation quota.
| Tool | Title | Input | Returns |
|---|---|---|---|
@@ -78,6 +80,7 @@ APIs; nothing is ever modified or deleted).
| `rig_mesh` | Rig a 3D model for animation | `glb_url` | rigged GLB |
| `forge_avatar` | Generate a rigged, animation-ready avatar | `prompt?` / `image_url?`, `allow_non_humanoid?` | rigged GLB avatar |
| `refine_model` | Refine a 3D model by describing a change | `glb_url`, `instruction`, `parent_prompt?`, `parent_lineage?`, `parent_index?` | refined GLB + version lineage |
+| `check_job` | Check a pending 3D generation and collect it | `job_id` | GLB model, or an updated pending state |
### Response shape
@@ -107,6 +110,42 @@ Rigged avatars additionally carry `irlUrl`, the living-agent handoff into
Every result also includes a `spatial` field, the open Spatial MCP artifact
(`specs/SPATIAL_MCP.md`) so any Spatial-MCP renderer can display the model.
+### Pending generations (`check_job`)
+
+A detailed model can take longer than a single tool call should block for. When
+that happens the generating tool does **not** fail: it returns a success result
+carrying a pollable handle, and the job keeps running server-side.
+
+```json
+{
+ "status": "pending",
+ "jobId": "f1.eyJwIjoiZ2NwIiw…",
+ "pollUrl": "https://three.ws/api/gpt-forge?job=f1.eyJwIjoiZ2NwIiw…",
+ "etaRemainingSeconds": 42,
+ "prompt": "a friendly round robot mascot, glossy white plastic"
+}
+```
+
+`etaRemainingSeconds` is the live estimate for the lane actually running the job
+(its typical duration minus time already elapsed), so the assistant knows how
+long to wait rather than retrying blind. Call `check_job` with that `jobId` to
+collect the result:
+
+- **done**: returns the ordinary success envelope (`glbUrl`, `viewerUrl`,
+ `arUrl`, …) and the model renders inline in the widget, exactly as if the
+ original call had finished in time.
+- **still rendering**: returns a fresh `pending` envelope with updated
+ `etaRemainingSeconds`. Call again after the suggested wait.
+- **failed**: returns a clean, actionable error.
+
+`check_job` is read-only and idempotent, and it does not consume generation
+quota, so collecting a model can never be rate-limited by the generation that
+created it. The inline widget renders the pending state as a designed
+"still rendering" panel with the live countdown, not an empty state.
+
+Any HTTP client can poll `pollUrl` directly instead; it is the same public,
+auth-free job handle the [3D API](/docs/3d-api) hands anonymous callers.
+
### Conversational refinement (`refine_model`)
Iterate on a model by describing the change in words — *"make it metallic"*,
diff --git a/prompts/store-submissions/_generated/openai-actions.yaml b/prompts/store-submissions/_generated/openai-actions.yaml
index b41af8940..22fa9a17f 100644
--- a/prompts/store-submissions/_generated/openai-actions.yaml
+++ b/prompts/store-submissions/_generated/openai-actions.yaml
@@ -239,7 +239,14 @@ components:
type: integer
description: >-
Rough estimate of remaining generation time in seconds (pending
- states only).
+ states only). Returned on both the initial submit and every
+ subsequent poll, recomputed from time already elapsed, so it
+ counts down as the job progresses. Use it to decide how long to
+ wait before calling checkModelJob again.
+ elapsedSeconds:
+ type: integer
+ description: >-
+ Seconds since the generation was submitted (pending states only).
job:
type: string
description: Job handle to pass to checkModelJob (present when pending).
diff --git a/public/.well-known/3d-studio-openapi.yaml b/public/.well-known/3d-studio-openapi.yaml
index b41af8940..22fa9a17f 100644
--- a/public/.well-known/3d-studio-openapi.yaml
+++ b/public/.well-known/3d-studio-openapi.yaml
@@ -239,7 +239,14 @@ components:
type: integer
description: >-
Rough estimate of remaining generation time in seconds (pending
- states only).
+ states only). Returned on both the initial submit and every
+ subsequent poll, recomputed from time already elapsed, so it
+ counts down as the job progresses. Use it to decide how long to
+ wait before calling checkModelJob again.
+ elapsedSeconds:
+ type: integer
+ description: >-
+ Seconds since the generation was submitted (pending states only).
job:
type: string
description: Job handle to pass to checkModelJob (present when pending).
diff --git a/tests/api/3d-studio.test.js b/tests/api/3d-studio.test.js
index 03148b256..2ede63d27 100644
--- a/tests/api/3d-studio.test.js
+++ b/tests/api/3d-studio.test.js
@@ -94,7 +94,7 @@ const SUBMIT_DONE = {
job_id: null,
creation_id: 'a1b2c3d4-0000-4000-8000-000000000001',
status: 'done',
- glb_url: 'https://cdn.three.ws/forge/anon/a1b2c3d4.glb',
+ glb_url: 'https://three.ws/cdn/forge/anon/a1b2c3d4.glb',
durable: true,
backend: 'nvidia',
tier: 'draft',
@@ -105,7 +105,7 @@ const SUBMIT_QUEUED = {
creation_id: 'a1b2c3d4-0000-4000-8000-000000000002',
status: 'queued',
};
-const POLL_DONE = { job_id: SUBMIT_QUEUED.job_id, status: 'done', glb_url: 'https://cdn.three.ws/forge/anon/done.glb', durable: true };
+const POLL_DONE = { job_id: SUBMIT_QUEUED.job_id, status: 'done', glb_url: 'https://three.ws/cdn/forge/anon/done.glb', durable: true };
const POLL_RUNNING = { job_id: SUBMIT_QUEUED.job_id, status: 'running' };
const POLL_FAILED = { job_id: SUBMIT_QUEUED.job_id, status: 'failed', error: 'the generator hit a snag' };
@@ -138,7 +138,7 @@ describe('shape helpers — Actions wire contract', () => {
it('shapeSubmit surfaces the painted concept image on done and pending states', async () => {
const { shapeSubmit } = await import('../../api/3d/studio.js');
- const preview = 'https://cdn.three.ws/forge/anon/ref-view.png';
+ const preview = 'https://three.ws/cdn/forge/anon/ref-view.png';
const done = shapeSubmit({ ...SUBMIT_DONE, preview_image_url: preview }, 'https://three.ws', 'a robot');
expect(done.previewImageUrl).toBe(preview);
const pending = shapeSubmit(
@@ -192,6 +192,45 @@ describe('shape helpers — Actions wire contract', () => {
expect(err.error).toBe(POLL_FAILED.error);
expectCleanWire(err);
});
+
+ // The published Actions contract (openai-actions.yaml) documents etaSeconds on
+ // pending states. Before this, only the SUBMIT carried one, so a GPT polling a
+ // long generation saw N identical frames with no sense of progress and no basis
+ // for choosing a retry delay.
+ it('shapePoll forwards live countdown timing on pending states', async () => {
+ const { shapePoll } = await import('../../api/3d/studio.js');
+
+ const pending = shapePoll(
+ { ...POLL_RUNNING, elapsed_seconds: 48, eta_remaining_seconds: 42, eta_seconds: 90 },
+ 'https://three.ws',
+ SUBMIT_QUEUED.job_id,
+ 'a tiny fox',
+ );
+ expect(pending.status).toBe('pending');
+ // The REMAINING estimate wins over the lane total: it is what a caller
+ // schedules its next poll against.
+ expect(pending.etaSeconds).toBe(42);
+ expect(pending.elapsedSeconds).toBe(48);
+ expectCleanWire(pending);
+
+ // An older server that only sends the lane total still yields an ETA.
+ const totalOnly = shapePoll({ ...POLL_RUNNING, eta_seconds: 90 }, 'https://three.ws', SUBMIT_QUEUED.job_id);
+ expect(totalOnly.etaSeconds).toBe(90);
+
+ // No timing at all: the fields are omitted, never emitted as null/NaN.
+ const bare = shapePoll(POLL_RUNNING, 'https://three.ws', SUBMIT_QUEUED.job_id);
+ expect('etaSeconds' in bare).toBe(false);
+ expect('elapsedSeconds' in bare).toBe(false);
+
+ // Terminal states never carry countdown timing.
+ const done = shapePoll(
+ { ...POLL_DONE, eta_remaining_seconds: 5, elapsed_seconds: 100 },
+ 'https://three.ws',
+ SUBMIT_QUEUED.job_id,
+ );
+ expect('etaSeconds' in done).toBe(false);
+ expect('elapsedSeconds' in done).toBe(false);
+ });
});
describe('POST /api/3d/studio — safety gate', () => {
diff --git a/tests/api/gpt-forge-clone.test.js b/tests/api/gpt-forge-clone.test.js
index ca3b53d2b..fad32cfdc 100644
--- a/tests/api/gpt-forge-clone.test.js
+++ b/tests/api/gpt-forge-clone.test.js
@@ -8,8 +8,10 @@
// 1. The clone client (gpt-forge-client.js) talks ONLY to /api/gpt-forge.
// 2. The ChatGPT surfaces import the clone client; the agent surfaces keep
// the original. Neither side silently re-couples to the other.
-// 3. The two clients expose an identical public API, so tools written
-// against one work against the other.
+// 3. The clone's public API is a SUPERSET of the original's, so anything
+// written against forge-client keeps working on the ChatGPT clone. The
+// clone may ADD exports (that is what "evolve independently" means); it
+// must never DROP one.
// 4. The cloned orchestrator actually serves: its public catalog is the
// SAME contract /api/forge serves (both read api/_lib/forge-tiers.js).
//
@@ -42,10 +44,26 @@ describe('gpt-forge-client — endpoint isolation', () => {
}
});
- it('exposes the exact same public API as forge-client', async () => {
+ it('exposes at least the same public API as forge-client', async () => {
const orig = await import('../../api/_mcp-studio/forge-client.js');
const clone = await import('../../api/_mcp-studio/gpt-forge-client.js');
- expect(Object.keys(clone).sort()).toEqual(Object.keys(orig).sort());
+ const cloneKeys = new Set(Object.keys(clone));
+ // Every original export survives on the clone: a tool written against
+ // forge-client runs unchanged against the ChatGPT pipeline.
+ for (const key of Object.keys(orig)) expect(cloneKeys.has(key)).toBe(true);
+ // Same shape for each shared export (all functions today): a name that
+ // survives as a different KIND of thing would break callers just as hard.
+ for (const key of Object.keys(orig)) expect(typeof clone[key]).toBe(typeof orig[key]);
+ });
+
+ it('ChatGPT-only additions are exported as callable functions', async () => {
+ const orig = await import('../../api/_mcp-studio/forge-client.js');
+ const clone = await import('../../api/_mcp-studio/gpt-forge-client.js');
+ const added = Object.keys(clone).filter((k) => !(k in orig));
+ // pollOnce backs the check_job tool: a single status probe with no loop,
+ // the collector for a generation that outlived a tool call's inline wait.
+ expect(added).toContain('pollOnce');
+ for (const key of added) expect(typeof clone[key]).toBe('function');
});
});
diff --git a/tests/forge-finalize.test.js b/tests/forge-finalize.test.js
index b296f38a9..ae6266790 100644
--- a/tests/forge-finalize.test.js
+++ b/tests/forge-finalize.test.js
@@ -4,7 +4,7 @@
// Importing the cron module is safe: db/neon clients are created lazily.
import { describe, it, expect } from 'vitest';
-import { decodeWorkerEnvelope } from '../api/cron/forge-finalize.js';
+import { decodeWorkerEnvelope, decideFailedSweep } from '../api/cron/forge-finalize.js';
function pack(obj) {
return Buffer.from(JSON.stringify(obj), 'utf8').toString('base64url');
@@ -42,3 +42,42 @@ describe('decodeWorkerEnvelope', () => {
expect(decodeWorkerEnvelope(Buffer.from('42').toString('base64url'))).toBeNull();
});
});
+
+// The unattended-failover decision. Evidence for why this exists: in a 7-day
+// production window, 8 of the trellis_selfhost failures were the literal
+// "task orphaned: no progress within 30 minutes (runner instance likely
+// restarted mid-job)". The worker only declares that orphan at 30 minutes, long
+// after the browser's 12-minute poll budget has expired, so the attended
+// failover in api/forge.js pollJob never saw them. The cron did see them, and
+// dead-ended every one. These jobs still had their prompt and reference image
+// on the row: fully recoverable work thrown away.
+describe('decideFailedSweep', () => {
+ it('defers while an attended client may still act, so no duplicate GPU work', () => {
+ expect(decideFailedSweep({ ageMinutes: 3, hasReferenceImage: true })).toBe('defer');
+ expect(decideFailedSweep({ ageMinutes: 12.9, hasReferenceImage: true })).toBe('defer');
+ });
+
+ it('redispatches an orphaned job once the attended window has passed', () => {
+ // The 30-minute worker orphan: exactly the class that used to die here.
+ expect(decideFailedSweep({ ageMinutes: 31, hasReferenceImage: true })).toBe('redispatch');
+ expect(decideFailedSweep({ ageMinutes: 13, hasReferenceImage: true })).toBe('redispatch');
+ });
+
+ it('has nothing to resubmit without a stored reference view', () => {
+ expect(decideFailedSweep({ ageMinutes: 31, hasReferenceImage: false })).toBe('terminal');
+ });
+
+ it('leaves sketch jobs on their purpose-built lane', () => {
+ expect(decideFailedSweep({ ageMinutes: 31, hasReferenceImage: true, path: 'sketch' })).toBe('terminal');
+ });
+
+ it('bounds the chain at the same hop cap as the attended failover', () => {
+ expect(decideFailedSweep({ ageMinutes: 31, hasReferenceImage: true, hop: 2 })).toBe('redispatch');
+ expect(decideFailedSweep({ ageMinutes: 31, hasReferenceImage: true, hop: 3 })).toBe('terminal');
+ expect(decideFailedSweep({ ageMinutes: 31, hasReferenceImage: true, hop: 99 })).toBe('terminal');
+ });
+
+ it('treats an unknowable age as past the attended window rather than deferring forever', () => {
+ expect(decideFailedSweep({ ageMinutes: undefined, hasReferenceImage: true })).toBe('redispatch');
+ });
+});
diff --git a/tests/forge-view-slots.test.js b/tests/forge-view-slots.test.js
new file mode 100644
index 000000000..12b8b7784
--- /dev/null
+++ b/tests/forge-view-slots.test.js
@@ -0,0 +1,88 @@
+// Reference-view slot invariants for the /forge composer.
+//
+// Production client-error logs carried a recurring uncaught TypeError from
+// /forge and /image-to-3d: "Cannot read properties of undefined (reading
+// 'state')", thrown out of a file-input change handler. Root cause was an
+// off-by-two between two constants that had to agree and didn't: MAX_VIEWS was
+// hardcoded to 6 while VIEW_LABELS (which builds the slot array AND the DOM)
+// had 4 entries. Filling the last slot ran nextFreeAfter(3), which walked to
+// slots[4] — undefined — and threw, aborting the upload mid-flight.
+//
+// The fix derives MAX_VIEWS from the labels and bounds the scan by the array,
+// so the two can never disagree again. These tests pin both halves, plus the
+// agreement with the server's own limit (api/forge.js MAX_VIEWS), since the
+// composer must never offer more views than the API accepts.
+
+import { describe, it, expect } from 'vitest';
+import { readFileSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+import { dirname, resolve } from 'node:path';
+
+const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
+const read = (p) => readFileSync(resolve(ROOT, p), 'utf8');
+
+const clientSrc = read('src/forge.js');
+
+function clientViewLabels() {
+ const m = clientSrc.match(/const VIEW_LABELS = \[([^\]]+)\]/);
+ if (!m) throw new Error('VIEW_LABELS not found in src/forge.js');
+ return m[1]
+ .split(',')
+ .map((s) => s.trim().replace(/^['"]|['"]$/g, ''))
+ .filter(Boolean);
+}
+
+function serverMaxViews() {
+ const m = read('api/forge.js').match(/const MAX_VIEWS = (\d+)/);
+ if (!m) throw new Error('MAX_VIEWS not found in api/forge.js');
+ return Number(m[1]);
+}
+
+describe('/forge reference-view slots', () => {
+ it('derives MAX_VIEWS from the labels instead of hardcoding a second number', () => {
+ expect(clientSrc).toContain('const MAX_VIEWS = VIEW_LABELS.length;');
+ // A second literal assignment would reintroduce the exact drift that crashed.
+ expect(clientSrc).not.toMatch(/const MAX_VIEWS = \d+/);
+ });
+
+ it('builds one real slot per advertised view', () => {
+ const labels = clientViewLabels();
+ expect(labels.length).toBeGreaterThan(0);
+ // slots is built from VIEW_LABELS, so array length tracks the labels and
+ // the DOM the same way, by construction.
+ expect(clientSrc).toContain('const slots = VIEW_LABELS.map(');
+ // Every label must be non-empty: it names the slot in its aria-label.
+ for (const label of labels) expect(label.length).toBeGreaterThan(0);
+ });
+
+ it('never offers more reference views than the API accepts', () => {
+ expect(clientViewLabels().length).toBeLessThanOrEqual(serverMaxViews());
+ });
+
+ it('scans for the next free slot within the array, not a separate constant', () => {
+ const fn = clientSrc.slice(clientSrc.indexOf('function nextFreeAfter'));
+ const body = fn.slice(0, fn.indexOf('\n}') + 2);
+ // The loop bound is the array itself: filling the LAST slot must return
+ // -1 ("no free slot"), never read one past the end.
+ expect(body).toContain('j < slots.length');
+ expect(body).not.toContain('j < MAX_VIEWS');
+ });
+
+ it('nextFreeAfter semantics: returns -1 past the end rather than throwing', () => {
+ // A faithful reimplementation of the fixed function, exercised against the
+ // real slot count — the exact call handleFiles makes after filling the
+ // final slot, which is what threw in production.
+ const slots = clientViewLabels().map(() => ({ state: 'uploaded' }));
+ const nextFreeAfter = (i) => {
+ for (let j = i + 1; j < slots.length; j++) {
+ if (slots[j].state === 'empty' || slots[j].state === 'error') return j;
+ }
+ return -1;
+ };
+ expect(() => nextFreeAfter(slots.length - 1)).not.toThrow();
+ expect(nextFreeAfter(slots.length - 1)).toBe(-1);
+
+ slots[slots.length - 1] = { state: 'empty' };
+ expect(nextFreeAfter(0)).toBe(slots.length - 1);
+ });
+});