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
// Forge — text / image / multi-view → 3D generator (browser client).
import { ensureModelViewerOrFallback } from './shared/model-viewer-loader.js';
import { resizedImageUrl } from './shared/image-url.js';
import { skeletonHTML, errorStateHTML, ensureStateKitStyles } from './shared/state-kit.js';
import {
sleepUntilVisibleOrElapsed,
createHiddenClock,
fetchJobStatus,
nextBackoff,
} from './shared/resilient-poll.js';
import { showSharePanel } from './shared/share.js';
import { stampGlbAttribution } from './shared/glb-attribution.js';
import {
primeTierPass,
attachTierPass,
getTierPass,
getAccess,
onGate,
trackUpgradeConverted,
} from './three-access.js';
import { injectFestivePresets } from './shared/festive-presets.js';
import { renderLock, lockStateFromAccess } from './three-lock.js';
import { payForHighGeneration } from './forge-pay.js';
import { renderQuote, ensureKept } from './forge-keep.js';
import { initWalletButton, getConnectedWalletAddress } from './wallet.js';
import { generateForgePrompt } from './forge-prompt-gen.js';
import { createForgeTimeline } from './forge-timeline.js';
import { createCompare } from './forge-compare.js';
import { initForgeDestinationPicker, storedForgeDestination } from './shared/forge-destination-picker.js';
import { generateWithModly, defaultModlyParams } from './modly-local.js';
import { createModlyPanel, promoteModlyGlb, saveModlyResultToLibrary } from './forge-modly.js';
ensureStateKitStyles();
//
// Drives /api/forge. Three paths share one polling loop:
// • Text → 3D — POST a prompt; FLUX paints a reference image, then TRELLIS
// reconstructs the mesh.
// • Image / multi-view → 3D — the user adds 1–4 photos of one object from
// different angles. Each photo is uploaded straight to object storage via a
// presigned URL (/api/forge-upload), then their public URLs are POSTed as
// image_urls. With >1 view the backend fuses them (multi-view conditioning)
// and reports how many views it used + which backend handled it.
// • Sketch → 3D — one drawing + a required prompt naming what it depicts,
// generated by the self-host TripoSG scribble engine (path: 'sketch').
// The mode tab only appears when the catalog reports that engine live.
//
// State transitions are driven by real API responses; the only timer is the
// honest elapsed counter. Nothing fakes progress.
const POLL_INTERVAL_MS = 2500;
// Ceiling for a single reconstruction run. Max-tier texture bakes legitimately
// run past 10 minutes at full quality; the ceiling must sit above the slowest
// real generation, not the average one, or the client abandons jobs the server
// finishes. Queue wait does not count against this window (see pollUntilDone).
const MAX_POLL_MS = 12 * 60 * 1000;
// Flaky-network budget for the status poll. A phone on a train drops sockets,
// and an edge node answers the occasional 502: neither means the generation
// died, because all real job state lives server-side. The poll absorbs
// consecutive transport failures with exponential backoff and only surfaces an
// error once the network has been unusable for the whole window below. Anything
// shorter loses a finished model to a single dropped request.
const POLL_MAX_BACKOFF_MS = 20_000;
const POLL_TRANSPORT_GRACE_MS = 90_000;
// One slot per reference view the server accepts (api/forge.js MAX_VIEWS = 6).
// MAX_VIEWS is derived from the labels so the slot grid, the pips, the "N of M
// views" copy, and the fill logic can never disagree about how many exist.
const VIEW_LABELS = ['Front', 'Back', 'Left', 'Right', 'Top', '3/4'];
const MAX_VIEWS = VIEW_LABELS.length;
const MAX_UPLOAD_BYTES = 8 * 1024 * 1024;
const ACCEPTED_TYPES = new Set(['image/png', 'image/jpeg', 'image/webp']);
const els = {
form: document.getElementById('composer'),
prompt: document.getElementById('prompt'),
aspect: document.getElementById('aspect'),
generate: document.getElementById('generate'),
generateLabel: document.getElementById('generate-label'),
examples: document.getElementById('examples'),
stage: document.getElementById('stage'),
modeSwitch: document.getElementById('mode-switch'),
textPane: document.getElementById('text-pane'),
imagePane: document.getElementById('image-pane'),
// Your GPU (Modly) lane: the connect panel in the photos tab, the
// "Feel free to leave" line it must hide (a local run stops with the tab),
// and the explicit save row under a local result.
modlyPanel: document.getElementById('modly-panel'),
genLeaveHint: document.querySelector('#state-generating .gen-leave-hint'),
modlySave: document.getElementById('modly-save'),
modlySaveText: document.getElementById('modly-save-text'),
modlySaveBtn: document.getElementById('modly-save-btn'),
viewsGrid: document.getElementById('views-grid'),
fileInput: document.getElementById('view-file-input'),
imagePrompt: document.getElementById('image-prompt'),
sketchPane: document.getElementById('sketch-pane'),
sketchGrid: document.getElementById('sketch-grid'),
sketchFileInput: document.getElementById('sketch-file-input'),
sketchPrompt: document.getElementById('sketch-prompt'),
states: {
empty: document.getElementById('state-empty'),
generating: document.getElementById('state-generating'),
result: document.getElementById('state-result'),
error: document.getElementById('state-error'),
unconfigured: document.getElementById('state-unconfigured'),
},
genPreview: document.getElementById('gen-preview'),
genMeta: document.getElementById('gen-meta'),
genNote: document.getElementById('gen-note'),
genProgress: document.getElementById('gen-progress'),
genProgressFill: document.getElementById('gen-progress-fill'),
// Named stage timeline + the cold-start warming card. Both are rendered by
// src/forge-timeline.js from real /api/forge signals only.
genStages: document.getElementById('gen-stages'),
genWarming: document.getElementById('gen-warming'),
cancel: document.getElementById('cancel'),
viewer: document.getElementById('viewer'),
viewerShell: document.getElementById('viewer-shell'),
cinema: document.getElementById('cinema'),
resultLabel: document.getElementById('result-label'),
resultCreator: document.getElementById('result-creator'),
resultViews: document.getElementById('result-views'),
resultQuality: document.getElementById('result-quality'),
verdict: document.getElementById('verdict'),
download: document.getElementById('download'),
quote: document.getElementById('forge-quote'),
materialize: document.getElementById('materialize-it'),
again: document.getElementById('again'),
refine: document.getElementById('refine'),
refineLabel: document.getElementById('refine-label'),
retry: document.getElementById('retry'),
errorLanes: document.getElementById('error-lanes'),
viewsCounter: document.getElementById('views-counter'),
viewsCounterText: document.getElementById('views-counter-text'),
viewsPips: document.getElementById('views-pips'),
pixal3dPanel: document.getElementById('pixal3d-panel'),
pixal3dFillSides: document.getElementById('pixal3d-fill-sides'),
sketchReqTag: document.getElementById('sketch-req-tag'),
generateAnyway: document.getElementById('generate-anyway'),
refineLocally: document.getElementById('refine-locally'),
errorTitle: document.getElementById('error-title'),
errorMessage: document.getElementById('error-message'),
emptyStarters: document.getElementById('empty-starters'),
rollForge: document.getElementById('roll-forge'),
forgeShareBtn: document.getElementById('forge-share-btn'),
segmentBtn: document.getElementById('forge-segment-btn'),
openInComposer: document.getElementById('open-in-composer'),
irlBtn: document.getElementById('forge-irl-btn'),
categoryPicker: document.getElementById('forge-category-picker'),
destinationPicker: document.getElementById('forge-destination-picker'),
destinationStatus: document.getElementById('forge-destination-status'),
savedChip: document.getElementById('result-saved'),
creations: document.getElementById('creations'),
creationsGrid: document.getElementById('creations-grid'),
creationsCount: document.getElementById('creations-count'),
// Quality tier + generation engine + BYOK key.
tier: document.getElementById('tier'),
// Persistent inline hint under the Quality row — advertises that High is a
// $THREE holder feature (toggled locked/unlocked by the live access read).
holderNote: document.getElementById('fq-holder-note'),
engine: document.getElementById('engine'),
byokRow: document.getElementById('byok-row'),
byokLabel: document.getElementById('byok-label'),
byokHint: document.getElementById('byok-hint'),
providerKey: document.getElementById('provider-key'),
estimate: document.getElementById('estimate'),
// Holder free-quota perk line + the Forge-local wallet-connect chip (Part A).
perkRow: document.getElementById('forge-perk-row'),
perkLine: document.getElementById('forge-perk-line'),
connectBtn: document.getElementById('connect-wallet-btn'),
};
let aspectRatio = '1:1';
let elapsedTimer = null;
// Wall-clock origin of the running elapsed meter, and a handle to repaint it on
// demand. Module-level because anchorElapsed() re-points the origin at the
// server's own job age when a poll frame reports one.
let elapsedStart = 0;
let elapsedRetick = null;
let pollAbort = false;
let mode = 'text'; // 'text' | 'image' | 'sketch' — input mode (prompt vs photos vs drawing)
let lastJob = null; // { prompt, imageUrls, seed }: for retry and refine
// Every user-initiated generation is stamped with a random seed, which then
// rides along on every replay of that same job (Refine, Retry, an automatic
// lane hop, "Generate anyway"). It is what makes Refine actually refine.
//
// Without it, bumping a draft to Standard re-ran the text lane from scratch: a
// NEW reference image off the same prompt, and therefore a different object.
// The user asked for "this model, better" and got "another model, better",
// which is the one thing a refine must never do. /api/forge threads the seed
// through the reference-image stage as well as reconstruction (api/forge.js
// seedReferenceImage), so replaying it reproduces the same subject and the tier
// bump is the only variable that moved.
//
// A fresh submit always mints a new one, so "Make another" on the same prompt
// still explores instead of returning the identical model.
const SEED_MAX = 2 ** 32 - 1;
function mintSeed() {
if (globalThis.crypto?.getRandomValues) {
return globalThis.crypto.getRandomValues(new Uint32Array(1))[0];
}
return Math.floor(Math.random() * SEED_MAX);
}
// Automatic engine hops taken for the current submission (lane_failed → switch
// to the first suggested backup and re-run). Budget of 1 per user submit; the
// server's own poll-time failover already walked the async lanes before this.
let autoLaneHops = 0;
let currentCreationId = null;
// The rows currently rendered in "Your creations", kept so a delete can drop
// one card in place (count, compare state, empty state) without a refetch.
let galleryCreations = [];
// The quality tier the on-screen result was produced at — drives the "Refine"
// affordance, which re-runs the same job exactly one tier higher.
let currentResultTier = null;
// The GLB currently shown in the viewer (set on every result). Lets the
// rate-limit state know a model exists to refine locally as a fallback.
let lastShownGlb = '';
// Your GPU lane. `modly` is the connect panel (src/forge-modly.js); `modlyRun`
// is the generation in flight on the user's machine, whose real percent and
// step text drive the meter; `modlyResult` is the local model on screen.
let modly = null;
let modlyRun = null;
let modlyResult = null;
// Quality tiers, lowest → highest. Refine walks one step up this ladder.
const TIER_ORDER = ['draft', 'standard', 'high'];
const TIER_LABELS = { draft: 'Draft', standard: 'Standard', high: 'High' };
function nextTierAfter(tier) {
const i = TIER_ORDER.indexOf(tier);
return i >= 0 && i < TIER_ORDER.length - 1 ? TIER_ORDER[i + 1] : null;
}
// Generation route + quality. `genPath` is the task's image|geometry axis;
// `genBackend` names the provider; both come from the selected engine button.
// The catalog (tiers + backends + cost/time matrix) is fetched once on load.
let catalog = null;
// Live backend health (/api/forge?health) — probed upstream auth/quota, not
// just env presence. Null until the probe returns; the buttons render
// optimistically from the catalog and tighten when health lands.
let health = null;
let selectedTier = 'standard';
// What the composer submits before the catalog has rendered an engine button.
const DEFAULT_ENGINE = Object.freeze({
id: 'trellis',
path: 'image',
backend: 'trellis',
byok: null,
polyControl: false,
modly: false,
modelId: null,
});
let selectedEngine = { ...DEFAULT_ENGINE };
// Once the user deliberately picks an engine we stop auto-selecting the
// catalog's per-tier default (e.g. the free NVIDIA lane on draft) under them.
let userPickedEngine = false;
// BYOK key held only in memory for this session — sent per request, never stored
// by the page. Signed-in users can instead save it server-side in Account.
let providerKey = '';
// Cinema mode — distraction-free fullscreen turntable for recording/sharing.
// Toggled by the result-bar button or F; Esc always exits. Rotation slows so
// the loop reads as deliberate, not busy.
let cinemaOn = false;
function setCinema(on) {
if (!els.cinema || on === cinemaOn) return;
cinemaOn = on;
els.states.result.classList.toggle('is-cinema', on);
document.body.classList.toggle('forge-cinema', on);
els.cinema.setAttribute('aria-pressed', String(on));
els.viewer.setAttribute('rotation-per-second', on ? '10deg' : '18deg');
}
// Inline key glyph appended to BYOK engine buttons. Stroke = currentColor so it
// tracks the button's text color through hover/selected/disabled states.
const ENGINE_KEY_SVG =
'<svg class="eng-key" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="7.5" cy="15.5" r="4.5"/><path d="M10.7 12.3 21 2"/><path d="m15 7 3 3"/><path d="m18 4 3 3"/></svg>';
// Inline "FREE" pill appended to zero-cost engine buttons (catalog `free:true`).
// The free lanes are named by engine like every other button; this pill — not
// the label — is what marks them free, so two free lanes never both read "Free".
const ENGINE_FREE_PILL = '<span class="eng-free" aria-hidden="true">FREE</span>';
// Short engine labels for the picker buttons, keyed by backend id. Free lanes
// carry the FREE pill above, so they are labelled by engine name like the rest.
const ENGINE_LABELS = {
nvidia: 'NVIDIA',
huggingface: 'Hunyuan3D',
trellis: 'Fast',
trellis2: 'TRELLIS.2',
trellis_selfhost: 'TRELLIS',
modly: 'Modly TripoSG',
modly_hunyuan: 'Modly Hunyuan',
meshy: 'Meshy',
tripo: 'Tripo',
rodin: 'Rodin',
stability: 'Stability',
replicate_byok: 'Replicate',
hunyuan3d: 'Hunyuan3D',
triposg: 'TripoSG',
// Pixal3D fuses every reference photo pixel-aligned instead of hallucinating
// unseen sides from one view: "Match my photo" is what that buys the user,
// not the vendor name.
pixal3d: 'Match my photo',
// AniGen hands back a GLB that already carries a skeleton and skin weights:
// the result is drivable immediately, no separate rigging call needed.
anigen: 'Rig on generate',
// PartCrafter decodes named, separable part meshes in one pass instead of
// one fused shape: the result opens directly in Restyle Studio's part picker.
partcrafter: 'Editable parts',
};
// Where to mint a key per BYOK provider, keyed by the backend's `byok` name.
// Mirrors the canonical registry in api/_lib/provider-keys.js (BYOK_PROVIDERS)
// and the Account key manager (dashboard-next/pages/account.js) — keep in sync.
const KEY_HINTS = {
meshy: { label: 'Meshy AI', url: 'https://www.meshy.ai/settings/api' },
tripo: { label: 'Tripo AI', url: 'https://platform.tripo3d.ai/api-keys' },
rodin: { label: 'Rodin (Hyper3D)', url: 'https://developer.hyper3d.ai' },
stability: { label: 'Stability AI', url: 'https://platform.stability.ai/account/keys' },
replicate: { label: 'Replicate', url: 'https://replicate.com/account/api-tokens' },
};
// One entry per reference-view slot. `state` drives the slot's rendered region;
// `url` is the durable public URL (what we send); `objectUrl` is the local
// preview blob, revoked when the slot is cleared.
const slots = VIEW_LABELS.map(() => ({
state: 'empty',
url: null,
objectUrl: null,
errorMsg: '',
}));
// Most engines fuse up to MAX_VIEWS (6). Pixal3D's "Match my photo" lane caps
// at 4 (its worker only knows front/back/left/right, slots 0-3, the same
// four labels this grid already uses first) and the catalog is the only
// source of that number, never a hardcoded second constant here.
function activeMaxImages() {
const b = catalog?.backends?.find((x) => x.id === selectedEngine.backend);
const declared = Number(b?.max_images) > 0 ? Number(b.max_images) : MAX_VIEWS;
// Never exceed the slot grid itself: a backend can only tighten the cap,
// not widen it past the array nextFreeAfter/firstFreeSlot scan.
return Math.min(declared, MAX_VIEWS);
}
function slotEnabled(i) {
return i < activeMaxImages();
}
// Drop every slot beyond the active engine's cap so a switch from a 6-view
// engine to Pixal3D never silently ships a 400 for photos the user can still
// see sitting in the grid.
function pruneSlotsOverCap() {
const cap = activeMaxImages();
for (let i = cap; i < slots.length; i++) {
if (slots[i].state !== 'empty') clearSlot(i);
}
}
// File picker target: the slot index the picker was opened for, or null to fill
// from the first free slot.
let pickerTarget = null;
// Sketch mode input — one drawing, same lifecycle as a view slot.
const sketch = { state: 'empty', url: null, objectUrl: null, errorMsg: '' };
// Stable anonymous handle for this browser. /forge has no login, so durable
// creations + the gallery are scoped to this id (hashed server-side). Sent on
// every request via the x-forge-client header.
const CLIENT_ID = (() => {
const KEY = 'forge:cid';
try {
let id = localStorage.getItem(KEY);
if (!id) {
id =
crypto?.randomUUID?.() ||
`c-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
localStorage.setItem(KEY, id);
}
return id;
} catch {
// Private mode / storage blocked — fall back to an ephemeral per-load id.
return `c-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
}
})();
// `x-witness: handled` tells the session recorder (packages/witness) that this
// page renders a designed state for every status /api/forge can answer with: a
// rate limit, a lane failure, a storage outage. Without it the recorder counts
// each of those as an unhandled failure and the companion interrupts with
// "something just broke, want to report it?" ON TOP of the recovery buttons the
// page is already showing, which at 320px literally covered Try again. The call
// is still recorded, it just stops triggering that offer.
const CLIENT_HEADERS = { 'x-forge-client': CLIENT_ID, 'x-witness': 'handled' };
// Leave-the-page continuity. The active async job persists here so a reload,
// a navigation away, or a closed tab does not lose the generation: returning
// to /forge inside RESUME_WINDOW_MS resumes polling the same job id (all real
// state lives server-side). Cleared on completion, terminal failure, or
// cancel. Even a user who never comes back is covered: the server-side
// finalizer (api/cron/forge-finalize.js) completes the row into their gallery
// and notifies signed-in creators.
const INFLIGHT_KEY = 'forge:inflight';
const RESUME_WINDOW_MS = 30 * 60 * 1000;
function saveInflight(job, label) {
if (!job?.job_id) return;
try {
localStorage.setItem(
INFLIGHT_KEY,
JSON.stringify({
jobId: job.job_id,
creationId: job.creation_id || null,
label: label || '',
previewImageUrl: job.preview_image_url || null,
backend: job.backend || null,
tier: job.tier || null,
path: job.path || null,
startedAt: Date.now(),
}),
);
} catch {
// Private mode / storage blocked: resume simply won't be available.
}
}
function readInflight() {
try {
const raw = localStorage.getItem(INFLIGHT_KEY);
if (!raw) return null;
const j = JSON.parse(raw);
if (!j?.jobId || !Number.isFinite(j.startedAt)) {
clearInflight();
return null;
}
if (Date.now() - j.startedAt > RESUME_WINDOW_MS) {
clearInflight();
return null;
}
return j;
} catch {
return null;
}
}
function clearInflight() {
try {
localStorage.removeItem(INFLIGHT_KEY);
} catch {
/* storage blocked */
}
}
const REDUCED_MOTION =
typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;
function showState(name) {
// The 3D viewer only exists in the generating/result states, and the CDN
// bundle is 955 KB, so it is fetched the first time the page heads there
// rather than on arrival (see the head of pages/forge.html). Fire and
// forget: #viewer reads its attributes when the element finally upgrades,
// and the loader has its own CDN failover and error state.
if (name === 'generating' || name === 'result') {
ensureModelViewerOrFallback(els.states.result || document);
}
for (const [key, node] of Object.entries(els.states)) {
node.classList.toggle('is-hidden', key !== name);
}
// Leaving the result state always leaves cinema mode with it.
if (name !== 'result' && cinemaOn) setCinema(false);
}
// Bring the stage (the panel that holds the timeline, the viewer and the error
// states) into view when the page has just switched what it is showing there.
//
// On a wide screen the composer and the stage sit side by side and the stage is
// already on screen, so scrolling would be a pointless jolt. Below the layout's
// breakpoint they stack, and the stage starts a full viewport BELOW the Generate
// button: pressing Generate on a phone used to leave the user staring at the
// engine picker while the whole live timeline played out off-screen. So: scroll
// only when the stage genuinely is not in view, and respect a reduced-motion
// preference by jumping instead of animating.
function revealStage() {
const el = els.stage;
if (!el || typeof el.getBoundingClientRect !== 'function') return;
const rect = el.getBoundingClientRect();
const viewport = window.innerHeight || document.documentElement.clientHeight || 0;
if (!viewport) return;
// "In view" means its top edge is inside the upper two thirds of the window,
// which is where a side-by-side stage always is and a stacked one never is.
if (rect.top >= 0 && rect.top < viewport * 0.66) return;
const reduced = window.matchMedia?.('(prefers-reduced-motion: reduce)')?.matches;
el.scrollIntoView({ behavior: reduced ? 'auto' : 'smooth', block: 'start' });
}
// Human label for a backend id, from the short-label map or the live catalog.
function engineLabel(id) {
if (!id) return 'the engine';
if (isModlyEngine(id)) return modlyEngineLabel(id);
return ENGINE_LABELS[id] || catalog?.backends?.find((b) => b.id === id)?.label || id;
}
// The generation stage timeline. It owns the reference preview, the named
// stages, and the cold-start warming card inside #state-generating; every
// transition it renders comes from a real /api/forge response (see the module
// header for the signal→stage map).
const timeline = createForgeTimeline({
list: els.genStages,
preview: els.genPreview,
warming: els.genWarming,
engineLabel,
});
// Side-by-side compare over the creations gallery. It stays dormant until the
// gallery holds two models with a GLB, so a first-time visitor never sees a
// control that cannot do anything.
const compare = createCompare({ engineLabel });
// Lane-switch notice in the generating panel: makes a mid-flight engine
// failover (server poll-time redispatch, or the client's own automatic retry
// hop) visible instead of silent. Empty text hides the line.
function setLaneNote(text) {
if (!els.genNote) return;
els.genNote.textContent = text || '';
els.genNote.classList.toggle('is-hidden', !text);
}
// Set by the automatic lane-hop retry just before it re-runs the job, consumed
// by run() when it resets the generating panel, so the notice survives the
// panel reset that a re-run performs.
let pendingLaneNote = '';
// The typical end-to-end time for the current engine+tier, straight from the
// catalog's real estimate matrix (estimateEtaSeconds). Null when no catalog or
// estimate exists — the meter then runs indeterminate rather than inventing a
// duration.
function currentEtaSeconds() {
// Once the job is accepted the server's own estimate wins: it names the lane
// that actually ran and widens for a cold worker, which the catalog matrix
// (always warm, always the requested lane) cannot know.
const served = timeline.etaSeconds();
if (Number(served) > 0) return Number(served);
return warmEtaFor(selectedEngine.backend, selectedEngine.path, selectedTier);
}
// The catalog's warm estimate for a lane. Also the baseline the cold-start
// budget is measured against: (server ETA for a cold job) - (this) is the real
// boot allowance the warming card counts down.
function warmEtaFor(backendId, path, tierId) {
if (!catalog) return null;
const backend = catalog.backends?.find((b) => b.id === backendId);
const est = (backend?.estimates?.[path] || []).find((e) => e.tier === tierId);
return Number(est?.eta_seconds) > 0 ? Number(est.eta_seconds) : null;
}
// Map real elapsed seconds onto an honest fill fraction. The curve approaches
// 1 asymptotically and is capped below it, so the bar can never reach full on
// time alone — only a real finished GLB sets it to 100% (see markDone). At
// elapsed = typical the fill sits ~0.78; it keeps creeping past that but never
// claims completion.
function honestFill(elapsedS, typicalS) {
const frac = 1 - Math.exp(-elapsedS / (typicalS * 0.66));
return Math.min(frac, 0.95);
}
function setProgress(pct) {
if (!els.genProgressFill || !els.genProgress) return;
const clamped = Math.max(0, Math.min(100, pct));
els.genProgressFill.style.width = `${clamped}%`;
els.genProgress.setAttribute('aria-valuenow', String(Math.round(clamped)));
}
function startElapsed(offsetMs = 0) {
// `offsetMs` backdates the counter for a resumed job, so the elapsed line
// stays honest about how long the generation has really been running.
elapsedStart = performance.now() - Math.max(0, offsetMs);
stopElapsed();
// Reset the meter to a clean running state for this job.
if (els.genProgress) {
els.genProgress.dataset.done = 'false';
els.genProgress.dataset.over = 'false';
els.genProgress.dataset.indeterminate = currentEtaSeconds() ? 'false' : 'true';
}
setProgress(0);
const tick = () => {
const s = Math.floor((performance.now() - elapsedStart) / 1000);
// Re-read every tick: the accepted job replaces the catalog guess with the
// server's real ETA for the lane that actually ran (cold start included).
// A run on the user's own GPU reports a real percent and step, so the
// meter shows exactly that instead of a time-based estimate.
if (modlyRun) {
timeline.tick(s);
paintModlyProgress(s);
return;
}
const typical = currentEtaSeconds();
if (els.genProgress) els.genProgress.dataset.indeterminate = typical ? 'false' : 'true';
// The timeline's warming card counts real seconds against that same ETA.
timeline.tick(s);
if (typical) {
const over = s > typical;
setProgress(honestFill(s, typical) * 100);
if (els.genProgress) els.genProgress.dataset.over = String(over);
els.genMeta.innerHTML = over
? `Elapsed <strong>${s}s</strong> · longer than usual, still working`
: `Elapsed <strong>${s}s</strong> · ~${Math.max(1, typical - s)}s left`;
} else {
// Unknown duration — the bar travels (indeterminate) and we report only
// the honest elapsed count.
els.genMeta.innerHTML = `Elapsed <strong>${s}s</strong>`;
}
};
tick();
elapsedRetick = tick;
elapsedTimer = window.setInterval(tick, 1000);
}
// Re-anchor the running meter to the server's own age for this job.
//
// The meter interpolates between polls with a local 1s tick, which is what keeps
// it smooth, but the tick alone has no idea when the JOB started: only when this
// tab did. `elapsed_seconds` on every non-terminal poll frame is measured from
// the creation row, so it is the same number for every viewer of the same job.
// Snapping to it costs nothing when they already agree and is the difference
// between "3s in" and the truth on a resumed page.
//
// A drift under 2s is ignored, so an ordinary round-trip does not re-snap the
// display on every poll; past that the server wins in both directions, because
// the one case that matters (a resumed or coalesced job, where the local clock
// reads far too LOW) is a correction the meter has to make.
function anchorElapsed(serverElapsedS) {
const s = Number(serverElapsedS);
if (!Number.isFinite(s) || s < 0 || !elapsedTimer) return;
const localS = (performance.now() - elapsedStart) / 1000;
if (Math.abs(s - localS) < 2) return;
elapsedStart = performance.now() - s * 1000;
elapsedRetick?.();
}
// Snap the meter to a finished, successful state — the only path to 100%.
function markProgressDone() {
if (!els.genProgress) return;
els.genProgress.dataset.indeterminate = 'false';
els.genProgress.dataset.over = 'false';
els.genProgress.dataset.done = 'true';
setProgress(100);
}
function stopElapsed() {
elapsedRetick = null;
if (elapsedTimer) {
window.clearInterval(elapsedTimer);
elapsedTimer = null;
}
}
// ── Pre-submit progress watch ────────────────────────────────────────────────
// POST /api/forge is ONE long request: the art-director pass, the reference-view
// synthesis and (on the fusing lane) the turnaround views all complete inside
// it. Without a second channel the stage list could only report "art-directing
// your prompt" for that whole window, and the reference image the user is really
// waiting to watch appear arrived at the very END of it, with the job id.
//
// So the server records a crumb the moment each of those milestones genuinely
// finishes (api/_lib/forge-progress.js), keyed by a trace id this browser mints,
// and this poll reads them while the POST is still open. Every transition it
// causes is still a real server signal, never a timer. It is also completely
// optional: a poll that answers with nothing (no Redis, a different instance, an
// older deployment) leaves the panel behaving exactly as it did before.
const PROGRESS_POLL_MS = 2500;
let progressWatch = null;
function mintProgressId() {
const raw =
typeof crypto?.randomUUID === 'function'
? crypto.randomUUID()
: `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}-${Math.random().toString(36).slice(2)}`;
// The server accepts 16-64 url-safe characters; a UUID with its dashes removed
// sits comfortably inside that and stays a single token in a query string.
return raw.replace(/[^A-Za-z0-9_-]/g, '').slice(0, 48);
}
function stopProgressWatch() {
if (!progressWatch) return;
progressWatch.stopped = true;
window.clearTimeout(progressWatch.timer);
try {
progressWatch.controller?.abort();
} catch {
// An already-settled fetch has nothing to abort.
}
progressWatch = null;
}
function startProgressWatch(traceId) {
stopProgressWatch();
if (!traceId) return;
const watch = { stopped: false, timer: 0, controller: null };
progressWatch = watch;
const poll = async () => {
if (watch.stopped) return;
watch.controller = typeof AbortController === 'function' ? new AbortController() : null;
try {
const res = await fetch(`/api/forge?progress=${encodeURIComponent(traceId)}`, {
headers: CLIENT_HEADERS,
signal: watch.controller?.signal,
});
if (!watch.stopped && res.ok) {
const data = await res.json().catch(() => null);
if (Array.isArray(data?.progress) && data.progress.length) timeline.applyProgress(data.progress);
} else if (!res.ok && res.status !== 429) {
// This deployment does not serve the progress channel (or refused the
// trace). One answer is enough to know that: keep polling and we would
// just fill the console with the same failure for the whole request.
stopProgressWatch();
return;
}
} catch {
// A dropped progress poll is invisible on purpose: the submit response
// carries every one of these facts a moment later regardless.
}
if (watch.stopped) return;
watch.timer = window.setTimeout(poll, PROGRESS_POLL_MS);
};
watch.timer = window.setTimeout(poll, PROGRESS_POLL_MS);
}
function setBusy(busy) {
els.generate.dataset.busy = busy ? '1' : '0';
els.generate.disabled = busy;
els.generateLabel.textContent = busy ? 'Forging…' : 'Generate';
// When returning to idle, re-assert the High-tier $THREE gate (if active) so a
// finished/cancelled job doesn't leave the Generate button enabled for a tier
// the user can't use.
if (!busy) applyHighGate();
}
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
// Mode switching --------------------------------------------------------------
function setMode(next) {
if (next !== 'text' && next !== 'image' && next !== 'sketch') return;
mode = next;
els.textPane.classList.toggle('is-hidden', mode !== 'text');
els.imagePane.classList.toggle('is-hidden', mode !== 'image');
els.sketchPane?.classList.toggle('is-hidden', mode !== 'sketch');
els.examples.classList.toggle('is-hidden', mode !== 'text');
for (const b of els.modeSwitch.querySelectorAll('button')) {
const sel = b.dataset.mode === mode;
b.setAttribute('aria-selected', String(sel));
// Roving tabindex: only the active tab is in the tab order; the rest are
// reached with the arrow keys (see the keydown handler), per the ARIA
// tabs pattern.
b.tabIndex = sel ? 0 : -1;
}
// Sketch serves through its own engine set (TripoSG) — rebuild the selector
// so each mode only offers engines that can actually take its input.
refreshEnginePicker();
updateAspectVisibility();
// The estimate caption is tab-aware (text → "renders a preview"; photos →
// "builds from your reference photos"), so refresh it when the tab changes
// even if the selected engine stays put.
updateEstimate();
if (mode === 'text') els.prompt.focus();
if (mode === 'sketch' && sketch.state === 'empty') sketchSlotEl()?.focus();
}
// Aspect ratio only shapes the synthesized reference image — irrelevant when
// the user supplies their own photos OR uses the geometry-first path (which
// never paints an intermediate image).
function updateAspectVisibility() {
if (!els.aspect) return;
const relevant = mode === 'text' && selectedEngine.path === 'image';
els.aspect.classList.toggle('is-hidden', !relevant);
}
// Quality tier + engine ------------------------------------------------------
// Fetch the tier/backend/cost catalog once, then build the engine selector from
// the backends that are live (platform-configured) or BYOK (always selectable).
async function loadCatalog() {
try {
const res = await fetch('/api/forge?catalog=1', { headers: CLIENT_HEADERS });
catalog = await res.json().catch(() => null);
} catch {
catalog = null;
}
if (!catalog || !Array.isArray(catalog.backends)) {
// No catalog (older deploy) — hide the controls; defaults still work.
els.engine?.closest('#forge-quality')?.classList.add('is-hidden');
return;
}
buildEngineButtons();
selectTier(selectedTier);
revealSketchMode();
loadHealth();
}
// Sketch→3D needs the self-host TripoSG worker — the tab stays hidden unless
// the catalog reports that engine configured, so there is no dead mode on
// deployments without it.
function revealSketchMode() {
const tab = els.modeSwitch?.querySelector('button[data-mode="sketch"]');
if (!tab) return;
const live = catalog.backends.some((b) => b.paths?.includes('sketch') && b.configured);
tab.hidden = !live;
if (live) buildSketchSlot();
}
// Live-probe the backends in the background, then tighten the engine buttons:
// a lane whose upstream is down gets disabled with the real reason instead of
// failing after the user has already typed a prompt and clicked Generate.
// On failure, retries twice (at 30s then 60s) before giving up.
let healthRetryCount = 0;
async function loadHealth() {
try {
const res = await fetch('/api/forge?health=1', { headers: CLIENT_HEADERS });
const body = await res.json().catch(() => null);
health = body && body.backends ? body : null;
} catch {
health = null;
}
if (health) {
healthRetryCount = 0;
updateEngineAvailability();
} else if (healthRetryCount < 2) {
healthRetryCount += 1;
setTimeout(loadHealth, healthRetryCount * 30_000);
}
}
function buildEngineButtons() {
if (!els.engine) return;
// Each mode offers only the engines that take its input: sketch mode shows
// the sketch-path engines (TripoSG); text/photo modes hide sketch-only ones.
const usable = (catalog?.backends || []).filter((b) => {
if (!(b.configured || b.byok)) return false;
const sketchOnly = Array.isArray(b.paths) && b.paths.every((p) => p === 'sketch');
return mode === 'sketch' ? b.paths.includes('sketch') : !sketchOnly;
});
els.engine.innerHTML = '';
for (const b of usable) {
// Each backend exposes the geometry-first path when it supports it; the
// image-intermediate engines (TRELLIS, Hunyuan3D) keep the image path.
const path =
mode === 'sketch' ? 'sketch' : b.paths.includes('geometry') ? 'geometry' : 'image';
const btn = document.createElement('button');
btn.type = 'button';
btn.dataset.engine = b.id;
btn.dataset.path = path;
btn.dataset.backend = b.id;
btn.dataset.byok = b.byok || '';
btn.dataset.housekey = String(Boolean(b.house_key_available));
btn.dataset.poly = String(Boolean(b.poly_control));
// Text-only engines (the free NVIDIA TRELLIS preview) can't take photos;
// updateEngineAvailability() disables them while reference views are set.
btn.dataset.userimages = String(b.user_images !== false);
// BYOK engines carry a small key glyph so the picker shows at a glance
// which lanes run on the user's own API key vs the free/included ones.
const short = ENGINE_LABELS[b.id] || b.label;
btn.innerHTML = `<span class="eng-label">${short}</span> ${b.free ? ENGINE_FREE_PILL : ''}${b.byok && !b.house_key_available ? ENGINE_KEY_SVG : ''}`;
const keyNote = b.house_key_available
? ' · included, or bring your own key'
: b.byok
? ` · uses your own ${KEY_HINTS[b.byok]?.label || b.byok} key`
: '';
const freeNote = b.free ? ' · free, no API key' : '';
btn.title = `${b.label}: ${b.blurb}${freeNote}${keyNote}`;
// aria-label survives the dynamic title rewrites in updateEngineAvailability.
btn.setAttribute('aria-label', `${short}${freeNote}${keyNote}`);
btn.setAttribute('aria-pressed', String(b.id === selectedEngine.backend));
els.engine.appendChild(btn);
}
const modlyIds = appendModlyEngineButtons();
// Catalog loaded but no lane can serve this mode (every backend unconfigured,
// non-BYOK, or sketch-only in a text/photo tab) — say so rather than leave a
// blank pill. The catalog-missing case is handled separately in loadCatalog().
if (!els.engine.childElementCount) {
const note = document.createElement('span');
note.className = 'engine-empty';
note.setAttribute('role', 'status');
note.textContent = 'No engine available for this input yet — try another tab or refresh.';
els.engine.appendChild(note);
}
// If the previously-selected engine isn't usable, fall back to the first.
if (!usable.some((b) => b.id === selectedEngine.backend) && !modlyIds.includes(selectedEngine.backend)) {
const first = els.engine.querySelector('button');
if (first) selectEngine(first, true);
}
updateEngineAvailability();
}
// Keep the engine buttons honest about the current input mode, and keep the
// selection on the catalog's per-tier default until the user picks one.
// • With reference photos attached, text-only engines are disabled (the free
// NVIDIA TRELLIS preview rejects user images) and a selected one bounces to
// the default photo engine.
// • With no photos and no explicit user choice, the tier's default engine is
// applied — which is what routes draft prompts onto the free lane.
function updateEngineAvailability() {
if (!els.engine || !catalog) return;
const hasPhotos = slots.some((s) => s.state === 'uploaded' || s.state === 'uploading');
let bounceTo = null;
for (const btn of els.engine.querySelectorAll('button')) {
const textOnly = btn.dataset.userimages === 'false';
const b = catalog.backends?.find((x) => x.id === btn.dataset.backend);
// Live health beats the catalog's env-presence flag: a lane whose
// upstream auth/billing probe failed is disabled with the real reason.
const lane = health?.backends?.[btn.dataset.backend];
const laneDown = Boolean(lane && (lane.status === 'down' || lane.status === 'unconfigured'));
const laneBusy = lane && lane.status === 'degraded';
// Boolean-coerce: before health loads, `lane` is undefined and a raw
// `(false) || undefined` would write aria-disabled="undefined" — an
// invalid ARIA token value (axe aria-valid-attr-value, WCAG 4.1.2).
const blocked = Boolean((textOnly && hasPhotos) || laneDown);
btn.disabled = blocked;
btn.setAttribute('aria-disabled', String(blocked));
btn.dataset.health = lane ? lane.status : '';
if (laneDown) {
btn.title = `${b?.label || btn.dataset.backend} — temporarily unavailable: ${lane.message}`;
} else if (blocked) {
btn.title =
'This engine generates from text prompts only — clear the reference views to use it.';
} else if (b) {
btn.title = laneBusy
? `${b.label} — busy right now: ${lane.message}`
: `${b.label} — ${b.blurb}`;
}
if (blocked && btn.dataset.backend === selectedEngine.backend) bounceTo = true;
}
const defaultId =
catalog.default_backend_for_tier?.[selectedTier]?.[selectedEngine.path] ?? null;
if (bounceTo) {
// Forced move: the selected engine can't serve photos. Prefer the standing
// photo default, else the first enabled button.
const fallbackId = catalog.default_backend?.image || 'trellis';
const target =
els.engine.querySelector(`button[data-backend="${fallbackId}"]:not(:disabled)`) ||
els.engine.querySelector('button:not(:disabled)');
if (target) selectEngine(target);
} else if (
!userPickedEngine &&
!hasPhotos &&
defaultId &&
defaultId !== selectedEngine.backend
) {
const target = els.engine.querySelector(
`button[data-backend="${defaultId}"]:not(:disabled)`,
);
if (target) selectEngine(target);
}
}
// Flip the engine picker to a backend by id (used by the lane-failover retry
// affordances, so a switch is always VISIBLE in the composer — never silent).
// Returns false when that engine has no live button on this deployment.
function selectEngineByBackend(backendId) {
const btn = els.engine?.querySelector(`button[data-backend="${backendId}"]:not(:disabled)`);
if (!btn) return false;
userPickedEngine = true;
selectEngine(btn);
return true;
}
function selectEngine(btn, silent) {
if (!btn) return;
selectedEngine = {
id: btn.dataset.engine,
path: btn.dataset.path,
backend: btn.dataset.backend,
byok: btn.dataset.byok || null,
houseKeyAvailable: btn.dataset.housekey === 'true',
polyControl: btn.dataset.poly === 'true',
modly: btn.dataset.modly === '1',
modelId: btn.dataset.modelId || null,
};
// A Modly model runs with its own settings, so the cloud quality tiers do
// not apply to it: hide that row rather than offer a control that does nothing.
els.tier?.classList.toggle('is-hidden', selectedEngine.modly);
for (const b of els.engine.querySelectorAll('button')) {
b.setAttribute('aria-pressed', String(b === btn));
}
updateByokRow();
updateAspectVisibility();
if (!silent) updateEstimate();
// The engine decides whether High is $THREE-gated (platform) or exempt (BYOK), so
// re-evaluate the lock whenever the engine changes under High. Reuses the cached
// access verdict — no extra round-trip, no loading flash.
if (selectedTier === 'high') reflectHighAccess('high', { silent: true });
// A switch to a tighter-capped engine (Pixal3D: 4) drops any photos sitting
// in the slots it can't use, then every slot repaints against the new cap:
// enabled/disabled state, the pips denominator, and the fill-sides toggle.
pruneSlotsOverCap();
for (let i = 0; i < slots.length; i++) renderSlot(i);
}
// Show the key field for BYOK engines, with provider-specific hint + link. A
// house-key lane (Tripo, when the platform key is configured) shows the same
// field but as an optional override, since the job runs on platform credits
// when it's left blank.
function updateByokRow() {
if (!els.byokRow) return;
const byok = selectedEngine.byok;
els.byokRow.classList.toggle('is-hidden', !byok);
if (!byok) return;
const hint = KEY_HINTS[byok];
const name = hint?.label || byok;
if (selectedEngine.houseKeyAvailable) {
els.byokLabel.textContent = `${name} key (optional)`;
els.providerKey.placeholder = `Your own ${name} API key, to use it instead of the included lane`;
els.byokHint.innerHTML = `This engine is included, billed to your platform credits. Paste your own ${name} key here to use it instead${hint ? ` (<a href="${hint.url}" target="_blank" rel="noopener">get a key</a>)` : ''}.`;
return;
}
els.byokLabel.textContent = `${name} key`;
els.providerKey.placeholder = `Your ${name} API key (kept in this browser)`;
els.byokHint.innerHTML = hint
? `This engine runs on your own ${hint.label} key. <a href="${hint.url}" target="_blank" rel="noopener">Get a key →</a> Signed-in users can save it once in Account instead.`
: `This engine runs on your own ${name} key, kept in this browser. Signed-in users can save it in Account instead.`;
}
function selectTier(tierId) {
if (!['draft', 'standard', 'high'].includes(tierId)) return;
selectedTier = tierId;
for (const b of els.tier.querySelectorAll('button')) {
b.setAttribute('aria-pressed', String(b.dataset.tier === tierId));
}
// Tier changes can move the default engine (draft prefers the free lane).
updateEngineAvailability();
updateEstimate();
reflectHighAccess(tierId);
}
// The High tier is a $THREE holder perk (gated server-side). When the user picks
// it, surface their access up front — a frosted lock with a Get $THREE path for
// non-holders (and the Generate button disabled for High), an "Unlocked" ribbon
// for holders (pass primed so their request clears the gate without a round-trip
// stall). Draft and Standard clear the lock (they're free, never gated). Degrades
// safely: if the access read fails we show a retry but DON'T trap the user — the
// server stays the final authority and a 403 falls back to the upsell modal.
let _accessHost = null;
let highLocked = false; // true → High is selected but the holder isn't eligible
let _highAccess = null; // last resolved forge.high access payload (for the gate modal)
// The only combination the server actually $THREE-gates: High tier on a PLATFORM-keyed
// backend. BYOK engines run on the caller's own vendor key, so the server exempts BYOK
// High (key-gated, not hold-gated), and so must the client, or a non-holder with their
// own Meshy/Tripo/Rodin key would be wrongly blocked from High. The one exception is a
// house-key lane (Tripo, when TRIPO_API_KEY is set): the server bills that the same as
// any other platform lane even though the backend is flagged `byok`, because the key
// running the job is ours, not the caller's, so the client gate must match (a caller
// who typed their own key still stays exempt; see updateByokRow's providerKey check
// below). Draft/Standard are never gated. Every client gate check keys on this.
function highTierNeedsPass() {
if (selectedTier !== 'high' || selectedEngine.modly) return false;
if (!selectedEngine.byok) return true;
return Boolean(selectedEngine.houseKeyAvailable) && !providerKey;
}
function accessHost() {
if (_accessHost || !els.tier) return _accessHost;
const host = document.createElement('div');
host.className = 'fq-access';
host.hidden = true;
(els.estimate || els.tier).insertAdjacentElement('afterend', host);
_accessHost = host;
return host;
}
// Reflect the High-tier gate onto the Generate button: disabled + relabelled
// while High is selected and the user is ineligible. Only touches the button when
// not mid-job (setBusy owns the busy label).
function applyHighGate() {
if (!els.generate || els.generate.dataset.busy === '1') return;
const locked = highTierNeedsPass() && highLocked;
els.generate.disabled = locked;
els.generate.classList.toggle('is-gated', locked);
if (els.generateLabel) {
els.generateLabel.textContent = locked ? 'Hold $THREE for High' : 'Generate';
}
}
async function reflectHighAccess(tierId, { silent = false } = {}) {
const host = accessHost();
if (!host) return;
if (tierId !== 'high') {
highLocked = false;
_highAccess = null;
renderLock(host, { clear: true });
// High isn't selected — let the persistent hint advertise it again.
if (els.holderNote) els.holderNote.hidden = false;
applyHighGate();
return;
}
// High on a BYOK engine is server-exempt (the caller's own vendor key pays), so it's
// never $THREE-gated here either: clear any lock, drop the holder note, and let the
// BYOK key flow take over. This is the path that keeps BYOK High byte-for-byte free.
if (!highTierNeedsPass()) {
highLocked = false;
renderLock(host, { clear: true });
if (els.holderNote) els.holderNote.hidden = true;
applyHighGate();
return;
}
// Platform-keyed High — the real $THREE gate. The in-place lock panel takes over, so
// the small persistent hint stands down to avoid stacking two "holder feature" notes.
if (els.holderNote) els.holderNote.hidden = true;
// Re-evaluating after an engine switch (silent) reuses the last resolved verdict so
// the panel doesn't flash a loading state for a check we already made.
let access = silent && _highAccess ? _highAccess : null;
if (!access) {
renderLock(host, { loading: true });
const data = await getAccess('forge.high');
// User moved off High, or switched to a BYOK engine, while we fetched.
if (!highTierNeedsPass()) return;
access = data?.access || null;
}
if (!access) {
// Access read failed — show a retry, but don't lock (fail open; the server
// enforces and a real holder isn't trapped behind a transient hiccup).
_highAccess = null;
highLocked = false;
renderLock(host, { error: true, onRetry: () => reflectHighAccess('high') });
applyHighGate();
return;
}
_highAccess = access;
highLocked = !access.eligible;
renderLock(
host,
lockStateFromAccess(access, {
getThreeUrl: '/three',
onUseFree: () => selectTier('standard'),
useFreeLabel: 'Use Standard (free)',
// Working Pay-per-use CTA: pay $THREE for one High generation in place.
onPayPerUse: (pay) => payThenGenerate(pay),
}),
);
applyHighGate();
// Keep the persistent button pill + note in sync with the fresh verdict.
applyHighAffordances(access);
// Reflect the resolved hold in the cost line too — High flips to "Free" for a
// holder without a reload.
updateEstimate();
if (access.eligible) primeTierPass();
}
// Small lock glyph for the High-tier button pill. Stroke = currentColor so it
// tracks the pill's locked (gold) / unlocked (green) tone.
const TIER_LOCK_SVG =
'<svg class="tier-lock-ico" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="5" y="11" width="14" height="9" rx="2"/><path d="M8 11V7a4 4 0 0 1 8 0v4"/></svg>';
// Paint the persistent High-tier affordances — the lock pill on the High button
// and the inline holder note under the Quality row — from a single-feature access
// payload (the `.access` from getAccess('forge.high'), or a 403 gate body, which
// both carry `eligible`/`required`/`held`). Holders get the quiet unlocked
// treatment; everyone else (and the null/unknown case) keeps the $THREE lock so
// High reads as the premium lane before it's ever selected. Purely cosmetic — the
// server stays the only authority on eligibility.
function applyHighAffordances(access) {
const eligible = Boolean(access?.eligible);
const state = eligible ? 'unlocked' : 'locked';
const btn = els.tier?.querySelector('button[data-tier="high"]');
if (btn) {
btn.dataset.access = state;
btn.setAttribute(
'aria-label',
eligible ? 'High quality — unlocked, you hold $THREE' : 'High quality — $THREE holder feature',
);
const pill = btn.querySelector('.tier-lock');
if (pill) {
pill.dataset.state = state;
pill.title = eligible ? 'Unlocked — you hold $THREE' : 'High quality is a $THREE holder feature';
pill.innerHTML = eligible
? '<span class="tier-lock-ico" aria-hidden="true">✓</span><span class="tier-lock-txt">$THREE</span>'
: `${TIER_LOCK_SVG}<span class="tier-lock-txt">$THREE</span>`;
}
}
const note = els.holderNote;
if (note) {
note.dataset.state = state;
note.innerHTML = eligible
? '<span class="fq-holder-ico" aria-hidden="true">◆</span> High quality is unlocked — you hold <a href="/three-token">$THREE</a>.'
: '<span class="fq-holder-ico" aria-hidden="true">◆</span> High quality is a <a href="/three-token">$THREE holder</a> feature: hold to unlock, or pay per generation.';
}
}
// One-time read on load: reflect the viewer's forge.high access onto the High
// button pill + the inline note so the holder gate is legible before the tier is
// even selected. Seeds the gate cache and primes the tier pass for real holders so
// their first High submit clears the server gate without an RPC stall.
async function reflectHighButtonAccess() {
const data = await getAccess('forge.high');
const access = data?.access || null;
if (access) _highAccess = access;
applyHighAffordances(access);
if (access?.eligible) primeTierPass();
}
// $THREE holder free-generation multiplier by tier level — mirrors api/_lib/three-tier.js
// (rateMultiplier), which the free lane applies to a holder's quota via the tier pass.
const FREE_MULT_BY_LEVEL = { 1: 2, 2: 3, 3: 5, 4: 10 };
// The quiet holder line under Generate (Part A): a holder sees their active free-quota
// multiplier; everyone else sees a non-blocking upsell plus a reachable wallet-connect so
// a holder who hasn't connected can reveal their perk. Reads the shared, wallet-aware
// access matrix — never nags, never blocks the free base lane.
async function updatePerkLine() {
if (!els.perkRow || !els.perkLine) return;
const data = await getAccess();
const level = Number(data?.tier?.level) || 0;
const connected = Boolean(getConnectedWalletAddress());
// The row already ships visible in its default state (see pages/forge.html);
// this only has to correct it. Kept for the surfaces that clone this markup
// with the row hidden.
els.perkRow.hidden = false;
if (level >= 1) {
const mult = FREE_MULT_BY_LEVEL[level] || 1;
els.perkLine.dataset.state = 'perk';
els.perkLine.innerHTML =
'<span class="fq-perk-ico" aria-hidden="true">⚡</span> Holder perk: ' +
`<strong>${mult}× free quota</strong> · <a href="/three#tiers">your $THREE tier</a>`;
if (els.connectBtn) els.connectBtn.hidden = true;
} else {
els.perkLine.dataset.state = 'upsell';
els.perkLine.innerHTML =
'<a href="/three#tiers">Hold $THREE for up to 10× free generations →</a>';
// Offer connect only when there's no wallet in hand to read a tier from.
if (els.connectBtn) els.connectBtn.hidden = connected;
}
}
// The honest price for the current engine + tier, as a styled segment. The web
// gate charges only High tier (hold $THREE or pay per generation); Draft and
// Standard run free on the platform's rate-limited lanes; BYOK engines bill the
// caller's own provider key. `_highAccess.eligible` reflects a resolved $THREE
// hold, so a holder sees High as already unlocked.
function costSegment(backend, tierMeta) {
const houseLane = backend.house_key_available && !providerKey;
if (backend.byok && !houseLane) return 'billed to your own key';
if (tierMeta.id === 'high') {
return _highAccess?.eligible
? '<span class="est-free">Free</span> · you hold $THREE'
: `<span class="est-cost">$${tierMeta.price_usdc}</span> or hold $THREE`;
}
return '<span class="est-free">Free</span>';
}
// Render the honest time/cost/poly estimate for the current engine + tier from
// the catalog. No fabricated numbers — everything comes from /api/forge?catalog.
function updateEstimate() {
if (!els.estimate) return;
if (selectedEngine.modly) {
renderModlyEstimate();
return;
}
if (!catalog) return;
const backend = catalog.backends.find((b) => b.id === selectedEngine.backend);
const tierMeta = catalog.tiers.find((t) => t.id === selectedTier);
if (!backend || !tierMeta) {
els.estimate.textContent = '';
return;
}
const est = (backend.estimates?.[selectedEngine.path] || []).find(
(e) => e.tier === selectedTier,
);
// Holder-readable, not pipeline-internal: say how long it usually takes and
// what the engine does, in plain words — and stay honest to the active tab.
// On the "Describe it" (text) tab the image-path engines synthesize a preview
// from the prompt first, so "builds from a reference image" would be wrong —
// the user supplied no image. Only the photos tab builds from a real reference.
const parts = [`<strong>${tierMeta.label}</strong>`, costSegment(backend, tierMeta)];
if (est?.eta_seconds) parts.push(`usually ~${est.eta_seconds}s`);
// Credits are a real charge only on metered lanes (BYOK or the paid High tier).
// Never tack a credit figure onto a "Free" line — "Free · ~3 credits" reads as
// a contradiction. costSegment() owns the cost word; this stays consistent with it.
if (est?.credits != null && (backend.byok || tierMeta.id === 'high'))
parts.push(`~${est.credits} credits`);
if (backend.poly_control) parts.push(`up to ${tierMeta.polycount.toLocaleString()} polygons`);
if (selectedEngine.path === 'geometry') parts.push('shapes geometry straight from the prompt');
else if (selectedEngine.path === 'sketch') parts.push('untextured geometry from your sketch');
else if (mode === 'image') parts.push('builds from your reference photos');
else parts.push('renders a preview image, then builds 3D');
els.estimate.innerHTML = parts.join(' · ');
updateTierTitles();
renderQuote(els.quote, {
tier: selectedTier,
path: selectedEngine.path,
backend: selectedEngine.backend,
images: mode === 'image',
headers: CLIENT_HEADERS,
});
}
// Stamp each tier button's tooltip with the catalog's real blurb, the typical
// time on the currently selected engine, and the polygon budget, so the
// quality/time tradeoff is legible before a tier is ever selected. The static
// HTML titles remain as the pre-catalog fallback.
function updateTierTitles() {
if (!els.tier || !catalog) return;
const backend = catalog.backends?.find((b) => b.id === selectedEngine.backend);
for (const btn of els.tier.querySelectorAll('button[data-tier]')) {
const t = catalog.tiers?.find((x) => x.id === btn.dataset.tier);
if (!t) continue;
const est = (backend?.estimates?.[selectedEngine.path] || []).find((e) => e.tier === t.id);
const parts = [t.blurb];
if (est?.eta_seconds) parts.push(`usually ~${est.eta_seconds}s on ${backend.label}`);
if (Number(t.polycount) > 0) parts.push(`up to ${t.polycount.toLocaleString()} polygons`);
btn.title = `${t.label}: ${parts.filter(Boolean).join(' · ')}`;
}
}
// View slots ------------------------------------------------------------------
function buildSlots() {
els.viewsGrid.innerHTML = '';
slots.forEach((_, i) => {
const slot = document.createElement('div');
slot.className = 'view-slot';
slot.dataset.index = String(i);
slot.tabIndex = 0;
slot.setAttribute('role', 'button');
slot.innerHTML = `
<div class="vs-empty">
<span class="vs-icon" aria-hidden="true">+</span>
<span class="vs-label">${VIEW_LABELS[i]}</span>
</div>
<div class="vs-uploading">
<div class="shimmer" aria-hidden="true"></div>
<span>Uploading…</span>
</div>
<img loading="lazy" decoding="async" class="vs-thumb" alt="" />
<span class="vs-badge">${VIEW_LABELS[i]}</span>
<button type="button" class="vs-remove" aria-label="Remove ${VIEW_LABELS[i]} view">×</button>
<div class="vs-error">
<span class="vs-error-msg">Upload failed</span>
<button type="button" class="vs-retry">Retry</button>
</div>`;
// Remove (stop click from also re-opening the picker).
slot.querySelector('.vs-remove').addEventListener('click', (e) => {
e.stopPropagation();
clearSlot(i);
});
// Retry re-opens the picker for this slot.
slot.querySelector('.vs-retry').addEventListener('click', (e) => {
e.stopPropagation();
openPicker(i);
});
// Click empty/error → browse for this slot (never a slot past the active
// engine's cap, Pixal3D only reads the first four).
slot.addEventListener('click', () => {
if (slotEnabled(i) && (slots[i].state === 'empty' || slots[i].state === 'error')) openPicker(i);
});
slot.addEventListener('keydown', (e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
if (slotEnabled(i) && (slots[i].state === 'empty' || slots[i].state === 'error')) openPicker(i);
}
});
// Drag to reorder (uploaded slots only).
slot.addEventListener('dragstart', (e) => {
if (slots[i].state !== 'uploaded') {
e.preventDefault();
return;
}
e.dataTransfer.setData('application/x-forge-slot', String(i));
e.dataTransfer.effectAllowed = 'move';
slot.classList.add('dragging');
});
slot.addEventListener('dragend', () => slot.classList.remove('dragging'));
// Drop target — accepts files OR a dragged thumbnail (reorder).
slot.addEventListener('dragover', (e) => {
e.preventDefault();
e.dataTransfer.dropEffect = e.dataTransfer.types.includes('application/x-forge-slot')
? 'move'
: 'copy';
slot.classList.add('drop-target');
});
slot.addEventListener('dragleave', () => slot.classList.remove('drop-target'));
slot.addEventListener('drop', (e) => {
e.preventDefault();
slot.classList.remove('drop-target');
if (!slotEnabled(i)) return;
const from = e.dataTransfer.getData('application/x-forge-slot');
if (from !== '') {
swapSlots(Number(from), i);
} else if (e.dataTransfer.files?.length) {
handleFiles(i, e.dataTransfer.files);
}
});
els.viewsGrid.appendChild(slot);
renderSlot(i);
});
}
function slotEl(i) {
return els.viewsGrid.querySelector(`.view-slot[data-index="${i}"]`);
}
// One pip per possible reference view — filled as photos upload.
function buildViewsPips() {
if (!els.viewsPips || els.viewsPips.childElementCount) return;
for (let i = 0; i < MAX_VIEWS; i++) {
const pip = document.createElement('i');
pip.dataset.filled = 'false';
els.viewsPips.appendChild(pip);
}
}
// Live "N of 6 views" readout + pips. Teaches that more views sharpen the mesh,
// so users don't stop at a single photo thinking it's enough. The denominator
// tracks the selected engine's own cap (4 for Pixal3D, 6 otherwise); the pips
// grid is built once at MAX_VIEWS size, so pips past the active cap just hide.
function updateViewsCounter() {
if (!els.viewsCounter || !els.viewsCounterText) return;
const cap = activeMaxImages();
const n = slots.filter((s) => s.state === 'uploaded').length;
const pips = els.viewsPips ? els.viewsPips.children : [];
for (let i = 0; i < pips.length; i++) {
pips[i].dataset.filled = String(i < n);
pips[i].style.display = i < cap ? '' : 'none';
}
let tail;
if (n === 0) tail = ' — add a photo to begin';
else if (n < cap) tail = ' · <span class="vc-quality">more views = sharper</span>';
else tail = ' · <span class="vc-quality">full coverage</span>';
els.viewsCounterText.innerHTML = `<strong>${n}</strong> of ${cap} views${tail}`;
}
function renderSlot(i) {
const el = slotEl(i);
if (!el) return;
const s = slots[i];
const enabled = slotEnabled(i);
el.dataset.state = s.state;
el.dataset.disabled = String(!enabled);
el.tabIndex = enabled ? 0 : -1;
el.draggable = s.state === 'uploaded';
// Slot changes flip the input mode (prompt-only ↔ photo), which changes
// which engines may serve — keep the selector honest in the same frame.
updateEngineAvailability();
updateViewsCounter();
updatePixal3dPanel();
const img = el.querySelector('.vs-thumb');
if (s.objectUrl) {
img.src = s.objectUrl;
img.alt = `${VIEW_LABELS[i]} view`;
} else {
img.removeAttribute('src');
img.alt = '';
}
el.querySelector('.vs-error-msg').textContent = s.errorMsg || 'Upload failed';
const labels = {
empty: enabled
? `${VIEW_LABELS[i]} view, empty, add a photo`
: `${VIEW_LABELS[i]} view, not used by ${ENGINE_LABELS.pixal3d}`,
uploading: `${VIEW_LABELS[i]} view, uploading`,
uploaded: `${VIEW_LABELS[i]} view, uploaded — drag to reorder`,
error: `${VIEW_LABELS[i]} view, upload failed`,
};
el.setAttribute('aria-label', labels[s.state] || VIEW_LABELS[i]);
}
// Shows/hides the "fill in the other sides" opt-in beneath the drop zone.
// Only Pixal3D offers it, and only while at most one photo is uploaded. The
// worker's MV-Adapter rung synthesizes the other three sides from a single
// reference, so it has nothing to do once a second photo narrows the job to
// plain multi-view fusion.
function updatePixal3dPanel() {
if (!els.pixal3dPanel) return;
const isPixal3d = selectedEngine.backend === 'pixal3d';
els.pixal3dPanel.classList.toggle('is-hidden', !isPixal3d);
if (!els.pixal3dFillSides) return;
if (!isPixal3d) {
els.pixal3dFillSides.checked = false;
return;
}
const uploadedCount = slots.filter((s) => s.state === 'uploaded').length;
const eligible = uploadedCount <= 1;
els.pixal3dFillSides.disabled = !eligible;
if (!eligible) els.pixal3dFillSides.checked = false;
}
function clearSlot(i) {
const s = slots[i];
if (s.objectUrl) URL.revokeObjectURL(s.objectUrl);
slots[i] = { state: 'empty', url: null, objectUrl: null, errorMsg: '' };
renderSlot(i);
}
function swapSlots(a, b) {
if (a === b) return;
const tmp = slots[a];
slots[a] = slots[b];
slots[b] = tmp;
renderSlot(a);
renderSlot(b);
}
function firstFreeSlot() {
const cap = activeMaxImages();
return slots.findIndex((s, i) => i < cap && (s.state === 'empty' || s.state === 'error'));
}
function nextFreeAfter(i) {
const cap = activeMaxImages();
for (let j = i + 1; j < cap; j++) {
if (slots[j].state === 'empty' || slots[j].state === 'error') return j;
}
return -1;
}
function openPicker(index) {
pickerTarget = index;
els.fileInput.value = '';
els.fileInput.click();
}
// Distribute dropped/picked files into slots, starting at `startIndex` (or the
// first free slot when null), filling free slots up to the active engine's cap.
function handleFiles(startIndex, fileList) {
const files = Array.from(fileList).filter((f) => f && f.type && f.type.startsWith('image/'));
if (!files.length) return;
const cap = activeMaxImages();
let idx = startIndex == null || startIndex >= cap ? firstFreeSlot() : startIndex;
for (const file of files) {
if (idx < 0 || idx >= cap) idx = firstFreeSlot();
if (idx < 0) break; // all slots taken
uploadToSlot(idx, file);
idx = nextFreeAfter(idx);
}
}
// Presign → PUT to object storage → public URL. Shared by the view slots and
// the sketch uploader. Returns { ok: true, url } or { ok: false, message }.
async function presignAndPut(file) {
// Two legs, two catches on purpose. The presign leg is same-origin, so a
// throw there really is the user's connection. The PUT leg is cross-origin to
// the bucket, where a rejected credential or a missing CORS rule answers 403
// with no Access-Control-Allow-Origin, and the browser hands us a rejected
// promise with no status to read. Reporting that as a network fault (one
// shared catch, as this had until 2026-09-08) blames the user's phone for our
// outage and sends them into an endless Retry loop.
let presign;
let presignRes;
try {
presignRes = await fetch('/api/forge-upload', {
method: 'POST',
headers: { 'content-type': 'application/json', ...CLIENT_HEADERS },
body: JSON.stringify({ content_type: file.type, size_bytes: file.size }),
});
presign = await presignRes.json().catch(() => ({}));
} catch {
return { ok: false, message: 'No connection. Check your network.' };
}
if (presignRes.status === 503) {
// The server distinguishes "this deployment has no storage" from "our
// storage is refusing us right now"; only the second is worth asking the
// user to come back for.
return {
ok: false,
message:
presign.error === 'storage_unavailable'
? 'Uploads are down right now. Try again shortly.'
: 'Uploads unavailable on this deployment.',
};
}
if (presignRes.status === 429) return { ok: false, message: 'Rate limited. Retry shortly.' };
if (!presignRes.ok || !presign.upload_url || !presign.public_url) {
return { ok: false, message: presign.message || 'Upload failed.' };
}
try {
const putRes = await fetch(presign.upload_url, {
method: 'PUT',
headers: { 'content-type': file.type },
body: file,
});
if (!putRes.ok) return { ok: false, message: `Storage rejected the file (${putRes.status}).` };
return { ok: true, url: presign.public_url };
} catch {
return { ok: false, message: 'Storage refused the upload. Try again shortly.' };
}
}
// Upload one file into a slot: presign → PUT to object storage → record the
// public URL. The slot moves empty/error → uploading → uploaded|error, each a
// real, designed state. The local blob preview shows immediately.
async function uploadToSlot(index, file) {
if (!ACCEPTED_TYPES.has(file.type)) {
setSlotError(index, 'Use PNG, JPG, or WebP.');
return;
}
if (file.size === 0) {
setSlotError(index, 'File is empty.');
return;
}
if (file.size > MAX_UPLOAD_BYTES) {
setSlotError(index, 'Too large (max 8 MB).');
return;
}
const prev = slots[index];
if (prev.objectUrl) URL.revokeObjectURL(prev.objectUrl);
const objectUrl = URL.createObjectURL(file);
slots[index] = { state: 'uploading', url: null, objectUrl, errorMsg: '' };
renderSlot(index);
const up = await presignAndPut(file);
if (!up.ok) {
setSlotError(index, up.message);
return;
}
// Success — keep the local blob preview, remember the public URL.
slots[index] = { state: 'uploaded', url: up.url, objectUrl, errorMsg: '' };
renderSlot(index);
}
function setSlotError(index, message) {
const s = slots[index];
// Keep any local preview so the user sees what failed.
slots[index] = {
state: 'error',
url: null,
objectUrl: s.objectUrl || null,
errorMsg: message,
};
renderSlot(index);
}
function uploadedUrls() {
return slots.filter((s) => s.state === 'uploaded' && s.url).map((s) => s.url);
}
// Sketch slot ------------------------------------------------------------------
// One drawing, built from the same .view-slot kit as the photo slots so every
// state (empty / uploading / uploaded / error) is already designed.
function sketchSlotEl() {
return els.sketchGrid?.querySelector('.view-slot') || null;
}
function buildSketchSlot() {
if (!els.sketchGrid || els.sketchGrid.childElementCount) return;
const slot = document.createElement('div');
slot.className = 'view-slot';
slot.tabIndex = 0;
slot.setAttribute('role', 'button');
slot.innerHTML = `
<div class="vs-empty">
<span class="vs-icon" aria-hidden="true">✎</span>
<span class="vs-label">Sketch</span>
</div>
<div class="vs-uploading">
<div class="shimmer" aria-hidden="true"></div>
<span>Uploading…</span>
</div>
<img loading="lazy" decoding="async" class="vs-thumb" alt="" />
<span class="vs-badge">Sketch</span>
<button type="button" class="vs-remove" aria-label="Remove sketch">×</button>
<div class="vs-error">
<span class="vs-error-msg">Upload failed</span>
<button type="button" class="vs-retry">Retry</button>
</div>`;
slot.querySelector('.vs-remove').addEventListener('click', (e) => {
e.stopPropagation();
clearSketch();
});
slot.querySelector('.vs-retry').addEventListener('click', (e) => {
e.stopPropagation();
openSketchPicker();
});
slot.addEventListener('click', () => {
if (sketch.state === 'empty' || sketch.state === 'error') openSketchPicker();
});
slot.addEventListener('keydown', (e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
if (sketch.state === 'empty' || sketch.state === 'error') openSketchPicker();
}
});
slot.addEventListener('dragover', (e) => {
e.preventDefault();
e.dataTransfer.dropEffect = 'copy';
slot.classList.add('drop-target');
});
slot.addEventListener('dragleave', () => slot.classList.remove('drop-target'));
slot.addEventListener('drop', (e) => {
e.preventDefault();
slot.classList.remove('drop-target');
const file = e.dataTransfer.files?.[0];
if (file) uploadSketch(file);
});
els.sketchGrid.appendChild(slot);
renderSketchSlot();
}
function openSketchPicker() {
if (!els.sketchFileInput) return;
els.sketchFileInput.value = '';
els.sketchFileInput.click();
}
function renderSketchSlot() {
const el = sketchSlotEl();
if (!el) return;
el.dataset.state = sketch.state;
const img = el.querySelector('.vs-thumb');
if (sketch.objectUrl) {
img.src = sketch.objectUrl;
img.alt = 'Your sketch';
} else {
img.removeAttribute('src');
img.alt = '';
}
el.querySelector('.vs-error-msg').textContent = sketch.errorMsg || 'Upload failed';
const labels = {
empty: 'Sketch, empty — add a drawing',
uploading: 'Sketch, uploading',
uploaded: 'Sketch, uploaded',
error: 'Sketch, upload failed',
};
el.setAttribute('aria-label', labels[sketch.state] || 'Sketch');
}
function clearSketch() {
if (sketch.objectUrl) URL.revokeObjectURL(sketch.objectUrl);
Object.assign(sketch, { state: 'empty', url: null, objectUrl: null, errorMsg: '' });
renderSketchSlot();
}
async function uploadSketch(file) {
if (!ACCEPTED_TYPES.has(file.type)) {
Object.assign(sketch, { state: 'error', url: null, errorMsg: 'Use PNG, JPG, or WebP.' });
renderSketchSlot();
return;
}
if (file.size === 0) {
Object.assign(sketch, { state: 'error', url: null, errorMsg: 'File is empty.' });
renderSketchSlot();
return;
}
if (file.size > MAX_UPLOAD_BYTES) {
Object.assign(sketch, { state: 'error', url: null, errorMsg: 'Too large (max 8 MB).' });
renderSketchSlot();
return;
}
if (sketch.objectUrl) URL.revokeObjectURL(sketch.objectUrl);
Object.assign(sketch, {
state: 'uploading',
url: null,
objectUrl: URL.createObjectURL(file),
errorMsg: '',
});
renderSketchSlot();
const up = await presignAndPut(file);
if (up.ok) Object.assign(sketch, { state: 'uploaded', url: up.url, errorMsg: '' });
else Object.assign(sketch, { state: 'error', url: null, errorMsg: up.message });
renderSketchSlot();
}
function firstPreviewUrl() {
const s = slots.find((x) => x.state === 'uploaded' && (x.objectUrl || x.url));
return s ? s.objectUrl || s.url : null;
}
// Job submission --------------------------------------------------------------
// Headers for a forge request, including the BYOK provider key (geometry path)
// when the user has entered one. The key rides a header, never the URL.
function forgeHeaders(extra) {
const h = { ...CLIENT_HEADERS, ...extra };
if (providerKey) h['x-forge-provider-key'] = providerKey;
// Carry the holder's $THREE tier pass so an eligible holder clears the High-tier
// gate (and gets their free-lane multiplier). No-op for anonymous users — the
// request simply proceeds at the base entitlement.
attachTierPass(h);
return h;
}
async function startJob({ prompt, imageUrls, skipValidation, payment, seed, progressId }) {
const base = { path: selectedEngine.path, tier: selectedTier, backend: selectedEngine.backend };
const body =
Array.isArray(imageUrls) && imageUrls.length
? { image_urls: imageUrls, prompt: prompt || undefined, ...base }
// Granite art-director pass (server-side, fail-soft): rewrites the raw
// prompt into a richer single-subject spec with per-part PBR materials
// and photoreal cues before it drives the reference image. Text-to-3D
// only — the director rewrites a prompt, and an image submission has
// none to rewrite.
: { prompt, aspect_ratio: aspectRatio, director: true, ...base };
// Match my photo (Pixal3D): tag each uploaded view with the slot it actually
// sits in (Front/Back/Left/Right → front/back/left/right), so a user who
// drag-reordered or skipped a slot still gets the label they placed the
// photo under, not a blind 0/1/2/3 guess. One photo + the opt-in asks the
// worker to synthesize the other three sides instead (MV-Adapter).
if (selectedEngine.backend === 'pixal3d' && Array.isArray(imageUrls) && imageUrls.length) {
const pixal3dLabels = catalog?.backends?.find((b) => b.id === 'pixal3d')?.view_labels;
if (Array.isArray(pixal3dLabels)) {
const uploadedSlotIndexes = slots
.map((s, i) => (s.state === 'uploaded' && s.url ? i : -1))
.filter((i) => i >= 0);
body.view_labels = uploadedSlotIndexes.map((i) => pixal3dLabels[i] ?? null);
}
if (imageUrls.length === 1 && els.pixal3dFillSides?.checked) body.fill_other_sides = true;
}
// What this maker said they are building for, remembered from an earlier
// model. Absent until they answer once; the server ignores an unknown value.
const destination = storedForgeDestination();
if (destination) body.destination = destination;
// Reproducibility: see mintSeed(). Absent on a job replayed from the gallery,
// where the original seed was never recorded, so that path stays as it was.
if (Number.isInteger(seed)) body.seed = seed;
// Trace id for the pre-submit progress channel (see startProgressWatch). The
// server crumbs each finished milestone against it while this request is still
// open. Purely additive: omit it and the response is identical.
if (progressId) body.progress_id = progressId;
// Caller already saw the vision warning and chose to proceed (Consumer 1).
if (skipValidation) body.skip_validation = true;
// Pay-per-use proof: a non-holder who paid $THREE for this High generation
// presents the settled payment so the server's gate is satisfied per use.
if (payment?.paymentId && payment?.refId) {
body.payment_id = payment.paymentId;
body.ref_id = payment.refId;
}
// Platform-keyed High is the $THREE-gated combination — mint/refresh the holder's tier
// pass and AWAIT it so forgeHeaders attaches a fresh, RPC-free proof on this very
// request. An eligible holder then clears the server gate even if a live on-chain read
// would hiccup, and even when they submit faster than the background primeTierPass()
// could finish. An eligible *connected* wallet (no signed-in account) signs once here to
// prove ownership — interactive only when eligible so a non-holder is never popped a
// signature; a signed-in holder still mints silently via their session. No-op for
// anonymous callers, the free tiers, and BYOK High (server-exempt — no pass needed).
if (highTierNeedsPass()) await getTierPass({ interactive: Boolean(_highAccess?.eligible) });
const res = await fetch('/api/forge', {
method: 'POST',
headers: forgeHeaders({ 'content-type': 'application/json' }),
body: JSON.stringify(body),
});
const data = await res.json().catch(() => ({}));
// An explicitly picked free engine that could not serve the request (503
// provider_busy). Checked before the generic 503 handling below, which would
// misfile it. When the server names configured engines that can take the
// request, hop to one visibly (the lane_failed path flips the picker and says
// so) rather than count down into the same dead lane; otherwise it is the
// recoverable high-demand countdown.
if (data.error === 'provider_busy') {
const e = new Error(data.message || 'The free 3D engines are at capacity right now.');
if (Array.isArray(data.retry_backends) && data.retry_backends.length) {
e.kind = 'lane_failed';
e.retryBackends = data.retry_backends;
} else {
e.kind = 'busy';
e.retryAfter = Number(data.retry_after) > 0 ? Math.ceil(Number(data.retry_after)) : 15;
}
throw e;
}
// Only a genuine deployment gap earns the unconfigured panel: it names env
// vars and offers no retry, which is the right answer for an operator and the
// wrong one for a visitor. The other 503s (`generation_unavailable`) are
// transient upstream capacity - a worker still warming, or a free lane that
// shed the request - so they land in the recoverable countdown state carrying
// the server's own message and retry_after.
if (data.error === 'unconfigured') {
const e = new Error(data.message || 'unconfigured');
e.kind = 'unconfigured';
throw e;
}
// Object storage rejected the generation (a rotated credential, an unreachable
// endpoint). Nothing about the prompt is wrong, no engine switch routes around
// it, and unlike a quota pause it does not clear in seconds, so it gets its
// own designed state rather than a countdown that promises a fix it cannot
// deliver. Models already forged are served from the public CDN and are
// unaffected, which is the honest alternative to offer.
if (data.error === 'storage_unavailable') {
const e = new Error(
data.message || '3D generation is paused while our asset storage recovers.',
);
e.kind = 'storage_down';
e.retryAfter = Number(data.retry_after) > 0 ? Math.ceil(Number(data.retry_after)) : 60;
throw e;
}
if (res.status === 503) {
const e = new Error(
data.message || 'The generator is temporarily unavailable. Try again shortly.',
);
e.kind = 'rate_limited';
e.retryAfter = Number(data.retry_after) > 0 ? Math.ceil(Number(data.retry_after)) : 20;
e.unavailable = true;
throw e;
}
// Geometry path needs a BYOK key we don't have — a recoverable, designed state.
if (data.error === 'needs_key') {
const e = new Error(data.message || 'An API key is required for this engine.');
e.kind = 'needs_key';
e.provider = data.provider;
throw e;
}
if (data.error === 'invalid_key') {
const e = new Error(data.message || 'The provider rejected this API key.');
e.kind = 'invalid_key';
throw e;
}
if (data.error === 'insufficient_credits') {
const e = new Error(data.message || 'The provider account is out of credits.');
e.kind = 'credits';
throw e;
}
// Vision pre-check rejected the reference photo (Consumer 1). Recoverable:
// the user can swap the photo (Try again) or override (Generate anyway).
if (res.status === 422 && data.error === 'image_not_usable') {
const e = new Error(data.message || 'That photo doesn’t look usable for 3D.');
e.kind = 'not_usable';
throw e;
}
if (res.status === 429 || data.error === 'rate_limited') {
const headerReset = Number(res.headers.get('ratelimit-reset'));
const secs =
Number(data.retry_after) > 0
? Math.ceil(Number(data.retry_after))
: headerReset > 0
? Math.ceil(headerReset)
: 10;
// `rate_limiter_unavailable` means the distributed limiter (Redis) is down
// and the paid lane is failing closed — not that the user spent their quota.
const unavailable = data.reason === 'rate_limiter_unavailable';
const e = new Error(
data.message ||
(unavailable
? 'The generator is temporarily unavailable. Refine your current model locally, or try again shortly.'
: `You've hit the generation limit. It resets in about ${secs}s.`),
);
e.kind = 'rate_limited';
e.retryAfter = secs;
e.unavailable = unavailable;
throw e;
}
// High-tier hold-to-access gate ($THREE) — a hold-OR-pay 402 (three_hold_required).
// Recoverable: the user can hold $THREE (Get $THREE) or drop to Draft/Standard.
// Carries the full gate payload (held vs required, usd_to_go, acquire, pay_per_use)
// straight to the upsell modal.
if (res.status === 402 && data.error === 'three_hold_required') {
const e = new Error(data.message || 'High-quality generation is a $THREE holder perk.');
e.kind = 'hold_required';
e.gate = data;
throw e;
}
// Pay-per-use proof was rejected (bad/expired payment) or already spent — both
// recoverable by paying again. payment_invalid/expired re-offer Pay; an already
// used payment also clears the stale proof so a retry doesn't replay it.
if (
res.status === 402 &&
(data.error === 'payment_invalid' || data.error === 'payment_expired')
) {
const e = new Error(data.message || 'That $THREE payment could not be verified.');
e.kind = 'payment_invalid';
e.gate = data;
throw e;
}
if (res.status === 409 && data.error === 'payment_already_used') {
const e = new Error(data.message || 'That payment was already used. Pay again to generate.');
e.kind = 'payment_used';
e.gate = data;
throw e;
}
// Free lane shed this request at the fleet concurrency cap — an influx of
// demand, not the user's quota. Recoverable with a short auto-retry, framed as
// "high demand" rather than a failure the user caused. (provider_busy comes
// from an explicit free-engine pick at capacity; free_lane_unavailable from the
// Spaces chain being briefly all-down.)
if (data.error === 'provider_busy' || data.error === 'free_lane_unavailable') {
const e = new Error(data.message || 'The free 3D engines are at capacity right now.');
e.kind = 'busy';
e.retryAfter = Number(data.retry_after) > 0 ? Math.ceil(Number(data.retry_after)) : 15;
throw e;
}
if (!res.ok) {
throw new Error(data.message || `The generator returned ${res.status}.`);
}
return data;
}
const QUEUE_NOTE =
'The engine is finishing earlier jobs. Yours is queued and will run at full quality, nothing is downgraded.';
const PATCHY_NETWORK_NOTE =
'Your connection dropped. Still holding this generation, it keeps running on the server.';
async function pollUntilDone(jobId) {
const hidden = createHiddenClock();
// Foreground time only: a backgrounded tab must not burn the run budget.
const runNow = () => performance.now() - hidden.hiddenMs();
let deadline = runNow() + MAX_POLL_MS;
// Queue-state tracking: when the engine reports the job is waiting for a GPU
// (healthy but busy, one generation per instance), say so instead of showing
// a silent spinner that reads as a hang. Restored when the job starts running.
// A short grace (a few polls) filters out dispatch latency: every job passes
// through "queued" for a beat even when a GPU is free.
let queuedPolls = 0;
let inQueue = false;
// Flaky-network state: when the first transport failure lands, back off
// exponentially and tell the user the job is safe rather than killing it.
let backoffMs = POLL_INTERVAL_MS;
let offlineSince = 0;
try {
return await runPollLoop();
} finally {
hidden.stop();
}
async function runPollLoop() {
while (!pollAbort && runNow() < deadline) {
await sleepUntilVisibleOrElapsed(backoffMs);
if (pollAbort) return null;
let data;
try {
data = await fetchJobStatus(`/api/forge?job=${encodeURIComponent(jobId)}`, {
headers: forgeHeaders(),
});
} catch (err) {
if (err?.kind !== 'transport') throw err;
if (!offlineSince) offlineSince = runNow();
if (runNow() - offlineSince > POLL_TRANSPORT_GRACE_MS) {
// The job is alive on the server and the inflight record is the
// only handle this browser has on it, so this branch must NOT be
// treated like a failed generation. `kind` says so: the catch in
// run() keeps the record instead of clearing it, which is what
// makes the "reopen /forge" instruction below actually true.
const e = new Error(
'Lost the connection to the generator. Your model is still being built and will keep going. Reopen /forge to pick it back up.',
);
e.kind = 'transport_lost';
throw e;
}
setLaneNote(PATCHY_NETWORK_NOTE);
backoffMs = nextBackoff(backoffMs, POLL_MAX_BACKOFF_MS);
continue;
}
if (offlineSince) {
// Back online: drop the patchy-network notice and restore whatever the
// job state itself has to say.
offlineSince = 0;
backoffMs = POLL_INTERVAL_MS;
setLaneNote(inQueue ? QUEUE_NOTE : '');
}
if (data.error === 'unconfigured') {
const e = new Error(data.message || 'unconfigured');
e.kind = 'unconfigured';
throw e;
}
// A malformed or missing handle can never resolve: fail immediately
// instead of spinning out the full run budget on a stale resume.
if (data.error === 'invalid_job' || data.error === 'missing_job') {
throw new Error(data.message || 'That generation is no longer available.');
}
// The server's elapsed is the JOB's age, measured from the row's
// created_at; the local meter only knows when THIS tab started counting.
// Those agree for a job submitted here and diverge for every other case:
// a resumed session, a coalesced job that joined work already in flight,
// or a failover successor. Re-anchor the meter to the server's figure so
// the elapsed readout and the cold-start countdown describe the
// generation rather than the tab, while the 1s tick keeps them moving
// smoothly between polls.
anchorElapsed(data.elapsed_seconds);
// One place folds the poll into the stage timeline: queued vs running, the
// lane a poll-time failover moved to, and a reference view that only
// becomes visible now (coalesced job, resumed session, failover successor).
timeline.applyPoll(data);
if (data.status === 'done' && data.glb_url) return data;
if (data.status === 'failed') {
// The server names the configured lanes that can still serve a fresh
// retry of this request (retry_backends), carry them so the catch can
// auto-hop to a backup engine instead of dead-ending.
const e = new Error(data.error || 'Generation failed.');
if (data.retryable && Array.isArray(data.retry_backends) && data.retry_backends.length) {
e.kind = 'lane_failed';
e.retryBackends = data.retry_backends;
}
throw e;
}
if (data.status === 'queued') {
// Time spent in line must not consume the run budget: a queued job is
// alive and will get the full window once a GPU picks it up.
deadline = runNow() + MAX_POLL_MS;
queuedPolls += 1;
// A cold worker has its own designed state in the timeline; the queue
// notice is for a warm lane that is simply busy, so it never doubles up.
if (!inQueue && queuedPolls >= 3 && !timeline.isCold()) {
inQueue = true;
setLaneNote(QUEUE_NOTE);
}
}
if (data.status === 'running') {
queuedPolls = 0;
if (inQueue) {
inQueue = false;
setLaneNote('');
}
// Poll-time failover: the server moved this job onto a backup lane and
// keeps it running under the same id. Surface the switch so the user
// sees which engine is now serving, rather than a silent swap.
if (data.failover_from && data.backend && data.backend !== data.failover_from) {
// TripoSG is the last-resort photo lane and returns shape only, so
// say so now rather than let an untextured result read as a bug.
const shapeOnly =
data.backend === 'triposg' ? ' It returns the shape without textures.' : '';
setLaneNote(
`${engineLabel(data.failover_from)} hit a snag. Continuing on ${engineLabel(data.backend)}, no action needed.${shapeOnly}`,
);
}
}
}
if (pollAbort) return null;
throw new Error(
'Generation timed out. The model may be too complex, try fewer views or a simpler prompt.',
);
}
}
// Post the human verdict on a creation — the labeled half of the data flywheel.
function sendFeedback(payload) {
if (!currentCreationId) return;
fetch('/api/forge-feedback', {
method: 'POST',
headers: { 'content-type': 'application/json', ...CLIENT_HEADERS },
body: JSON.stringify({ creation_id: currentCreationId, ...payload }),
keepalive: true,
}).catch(() => {});
}
function resetVerdict() {
if (!els.verdict) return;
for (const b of els.verdict.querySelectorAll('button')) {
b.setAttribute('aria-pressed', 'false');
}
}
// "Making this for" chips (src/shared/forge-destination-picker.js). The answer is
// written onto the model on screen and remembered for later generations.
const destinationPicker = initForgeDestinationPicker({
picker: els.destinationPicker,
status: els.destinationStatus,
onChoose: (id) => sendFeedback({ destination: id }),
});
function resetCategoryPicker() {
if (!els.categoryPicker) return;
els.categoryPicker.querySelectorAll('.forge-cat-btn').forEach((b) => b.classList.remove('active'));
}
function sendCategory(modelCategory) {
if (!currentCreationId) return;
fetch('/api/forge-categorize', {
method: 'POST',
headers: { 'content-type': 'application/json', ...CLIENT_HEADERS },
body: JSON.stringify({ creation_id: currentCreationId, model_category: modelCategory }),
keepalive: true,
}).catch(() => {});
}
// Poster capture — the visual half of every creation card. Image-intermediate
// engines store their flux reference image as the preview, but geometry-first
// and sketch lanes paint no image at all, so their gallery/showcase cards used
// to render as glyph placeholders. Once the finished mesh is standing in the
// viewer, render it onto a small studio-backdrop canvas and attach it to the
// creation row (POST /api/forge-poster — fill-only, owner-scoped, best-effort).
const POSTER_MAX_DIM = 640;
const postedPosters = new Set();
function renderPosterFrame(sourceDataUrl) {
return new Promise((resolve) => {
const img = new Image();
img.onload = () => {
const scale = Math.min(1, POSTER_MAX_DIM / Math.max(img.width, img.height, 1));
const w = Math.max(1, Math.round(img.width * scale));
const h = Math.max(1, Math.round(img.height * scale));
const canvas = document.createElement('canvas');
canvas.width = w;
canvas.height = h;
const ctx = canvas.getContext('2d');
if (!ctx) return resolve(null);
// Same studio backdrop as the live viewer, so mesh posters read as a
// consistent set next to flux reference images in the galleries.
const backdrop = ctx.createRadialGradient(w / 2, 0, 0, w / 2, 0, Math.max(w, h) * 1.2);
backdrop.addColorStop(0, '#1a1612');
backdrop.addColorStop(0.7, '#0b0a09');
backdrop.addColorStop(1, '#0b0a09');
ctx.fillStyle = backdrop;
ctx.fillRect(0, 0, w, h);
ctx.drawImage(img, 0, 0, w, h);
const webp = canvas.toDataURL('image/webp', 0.85);
// Browsers without webp encoding silently hand back PNG — send what we got.
resolve(webp.startsWith('data:image/webp') ? webp : canvas.toDataURL('image/png'));
};
img.onerror = () => resolve(null);
img.src = sourceDataUrl;
});
}
async function capturePoster(creationId) {
if (!creationId || postedPosters.has(creationId) || !els.viewer?.toDataURL) return;
postedPosters.add(creationId);
try {
if (!els.viewer.loaded) {
await new Promise((resolve) =>
els.viewer.addEventListener('load', resolve, { once: true }),
);
}
// Let the materialize entrance settle so the capture is a steady frame.
await sleep(REDUCED_MOTION ? 300 : 1500);
// A newer generation or an opened creation replaced the model — skip.
if (currentCreationId !== creationId) return;
const frame = await renderPosterFrame(els.viewer.toDataURL('image/png'));
if (!frame) return;
const res = await fetch('/api/forge-poster', {
method: 'POST',
headers: { 'content-type': 'application/json', ...CLIENT_HEADERS },
body: JSON.stringify({ creation_id: creationId, image: frame }),
});
const data = await res.json().catch(() => ({}));
// The card for this creation is already on screen with a placeholder —
// refresh the strip so the new poster shows without a reload.
if (data?.stored) loadGallery();
} catch {
// Best-effort: a missed poster never disturbs the result flow.
}
}
// Render the provenance badge from job metadata: how the mesh was produced
// (engine + tier + path) plus any multi-view conditioning. Shows whatever is
// known — the geometry-first path has no reference views, the image path does.
function setViewsBadge(meta) {
if (!els.resultViews) return;
const parts = [];
const used = Number(meta?.views_used);
if (Number.isFinite(used) && used >= 1) {
parts.push(`${used} ${used === 1 ? 'view' : 'views'}`);
if (meta.multiview) parts.push('multi-view');
}
if (meta?.backend) parts.push(engineLabel(meta.backend));
if (meta?.tier) parts.push(meta.tier);
if (meta?.path === 'geometry') parts.push('geometry-first');
if (meta?.path === 'sketch') parts.push('sketch→3D');
if (meta?.rigged) parts.push('already rigged');
if (parts.length === 0) {
els.resultViews.classList.add('is-hidden');
els.resultViews.textContent = '';
return;
}
els.resultViews.textContent = parts.join(' · ');
els.resultViews.classList.remove('is-hidden');
}
// Surface the automated quality signal the server attached to this generation.
// Two sources, in order of confidence:
// • quality_gate: the vision-QA verdict (semantic: does it look like the
// prompt). A pass with a numeric score reads "Verified NN%"; a fail that
// nonetheless shipped (best-of retry kept the top roll) reads a low-band
// warning so the user knows to regenerate.
// • quality: the fast deterministic scorer (structural). Used only when no
// vision verdict exists (the trusted fast-lane path), shown as a quiet
// "Checked" so a good draft still gets a confidence cue without a score.
// Anything unscored (QA unavailable / older gallery model) shows nothing rather
// than a fabricated number.
function setQualityBadge(meta) {
const el = els.resultQuality;
if (!el) return;
const hide = () => {
el.classList.add('is-hidden');
el.removeAttribute('data-band');
el.textContent = '';
el.title = 'Automated quality check';
};
const gate = meta?.quality_gate;
// A real vision verdict: qa_available and a numeric score.
if (gate && gate.qa_available !== false && Number.isFinite(Number(gate.score))) {
const score = Math.round(Number(gate.score));
if (gate.pass === true) {
el.dataset.band = 'verified';
el.textContent = `Verified ${score}%`;
el.title = gate.reason ? `Quality check passed: ${gate.reason}` : 'Passed the automated quality check';
} else {
el.dataset.band = 'low';
el.textContent = `Low ${score}%`;
el.title = gate.reason
? `Below the quality bar: ${gate.reason}. Try Regenerate.`
: 'Below the automated quality bar: try Regenerate.';
}
el.classList.remove('is-hidden');
return;
}
// No vision verdict: fall back to the fast structural scorer if it vouched.
const q = meta?.quality;
if (q && q.flag === 'ok') {
el.removeAttribute('data-band');
el.textContent = 'Checked';
el.title = 'Passed the fast quality check';
el.classList.remove('is-hidden');
return;
}
hide();
}
// Materialize entrance — conceal the standing viewer, play the WebGL dissolve
// reveal over it (src/forge-reveal.js), then crossfade back and hand the
// final camera angle to model-viewer so the turntable continues seamlessly.
// Presentation only: any failure restores the viewer immediately.
let revealSeq = 0;
async function playMaterialize(glbUrl) {
if (REDUCED_MOTION || !els.viewerShell) return;
const seq = ++revealSeq;
els.viewer.style.opacity = '0';
try {
const { playForgeReveal } = await import('./forge-reveal.js');
const viewerLoaded = new Promise((resolve) => {
if (els.viewer.loaded) return resolve();
els.viewer.addEventListener('load', resolve, { once: true });
});
const end = await playForgeReveal({
container: els.viewerShell,
glbUrl,
waitFor: viewerLoaded,
});
if (seq === revealSeq && end && Number.isFinite(end.azimuthDeg)) {
els.viewer.cameraOrbit = `${end.azimuthDeg.toFixed(1)}deg ${end.polarDeg.toFixed(1)}deg auto`;
}
} catch {
// The standing viewer is the fallback — nothing to surface.
} finally {
if (seq === revealSeq) els.viewer.style.opacity = '1';
}
}
// Show "Refine → <next tier>" only when a higher tier exists and the current
// result came from a job we can re-run (a prompt and/or reference images).
function updateRefineButton() {
if (!els.refine) return;
const next = nextTierAfter(currentResultTier);
const reRunnable =
lastJob &&
(lastJob.prompt || (Array.isArray(lastJob.imageUrls) && lastJob.imageUrls.length));
const show = Boolean(next && reRunnable);
els.refine.classList.toggle('is-hidden', !show);
if (show) {
els.refineLabel.textContent = `Refine → ${TIER_LABELS[next]}`;
els.refine.title = `Re-run this exact ${
lastJob.imageUrls?.length ? 'reconstruction' : 'prompt'
} at ${TIER_LABELS[next]} quality`;
}
}
// Point the cross-page result actions at this model. Also called when a local
// (Modly) result gains its public copy after it was first shown.
function linkResultTools(glbUrl) {
// Deep-link the physical lane at THIS generation. A creation id is the
// better handle (it carries the prompt and the creator through to the
// print), but a model that has not been persisted yet still materializes
// from its own URL, so the action is never dead.
if (els.materialize) {
const handle = currentCreationId
? `?creation=${encodeURIComponent(currentCreationId)}`
: glbUrl && !glbUrl.startsWith('blob:')
? `?glb=${encodeURIComponent(glbUrl)}`
: '';
els.materialize.href = `/materialize${handle}`;
els.materialize.hidden = false;
}
// Cross-link into Parts Studio with this exact model pre-loaded.
if (els.segmentBtn) els.segmentBtn.href = `/segment?mesh=${encodeURIComponent(glbUrl)}`;
if (els.openInComposer) els.openInComposer.href = `/compose?glb=${encodeURIComponent(glbUrl)}`;
if (els.irlBtn) els.irlBtn.href = `/irl?avatar=${encodeURIComponent(glbUrl)}`;
}
// `glbUrl` is what the VIEWER loads and `downloadUrl` is what the Download
// button hands over. They differ for a re-opened creation that has a delivery
// variant (api/_lib/forge-store.js): the viewer takes the phone-sized meshopt +
// WebP build, the download always takes the full-resolution original. For a
// fresh generation there is only one URL and they are the same.
function showResult(glbUrl, label, meta, { autoSaved = false, downloadUrl = null } = {}) {
stopElapsed();
// Every entry into the result state starts with no directed-prompt reveal:
// only a fresh generation whose response carried one re-opens it (run()
// dispatches it right after this). A gallery card or a share link has no
// recorded rewrite, so it must not inherit the previous model's.
document.dispatchEvent(
new CustomEvent('forge:directed-prompt', { detail: { prompt: '', directedPrompt: null } }),
);
resetVerdict();
resetCategoryPicker();
if (els.categoryPicker) els.categoryPicker.hidden = false;
destinationPicker.show();
els.viewerShell?.classList.remove('has-load-error');
// Show the load skeleton over the dark viewport until the GLB paints. The
// persistent 'load'/'error' listeners below clear it.
els.viewerShell?.classList.add('is-loading');
els.viewer.setAttribute('src', glbUrl);
els.viewer.setAttribute('alt', `3D model: ${label}`);
// A turntable that never stops is exactly the motion prefers-reduced-motion
// exists to silence, and it is the largest moving thing on the page. Drop it
// for a reader who asked for less motion: camera-controls stays, so the model
// is still fully inspectable by drag, pinch and arrow key, on their terms.
if (REDUCED_MOTION) els.viewer.removeAttribute('auto-rotate');
lastShownGlb = glbUrl;
els.resultLabel.textContent = label;
// Real, opt-in attribution only: a byline + link to the creator's public
// portfolio appears when this creation was forged while signed in
// (meta.creatorUsername, set server-side). Anonymous generations — the
// large majority — show no byline, never a fabricated one.
if (els.resultCreator) {
if (meta?.creatorUsername) {
els.resultCreator.href = `/u/${encodeURIComponent(meta.creatorUsername)}`;
els.resultCreator.textContent = `by @${meta.creatorUsername}`;
els.resultCreator.classList.remove('is-hidden');
} else {
els.resultCreator.classList.add('is-hidden');
}
}
// Hide the saved chip by default; caller re-shows it for fresh generations.
if (els.savedChip) els.savedChip.classList.add('is-hidden');
setViewsBadge(meta);
setQualityBadge(meta);
if (autoSaved && els.savedChip) {
// Re-trigger the animation by forcing a reflow.
els.savedChip.classList.remove('is-hidden');
void els.savedChip.offsetWidth;
els.savedChip.style.animation = 'none';
void els.savedChip.offsetWidth;
els.savedChip.style.animation = '';
// Hide after animation completes (3s).
setTimeout(() => els.savedChip?.classList.add('is-hidden'), 3100);
}
linkResultTools(glbUrl);
els.download.href = downloadUrl || glbUrl;
// Carried to the download click handler below so the exported file's
// metadata can name the exact engine (and, for Tripo, model version) that
// produced it, deterministically rather than sniffed from the upstream GLB.
els.download.dataset.engine = meta?.backend || '';
els.download.dataset.engineVersion = meta?.engine_version || '';
els.download.setAttribute(
'download',
`${
label
.replace(/[^a-z0-9]+/gi, '-')
.slice(0, 48)
.replace(/^-|-$/g, '') || 'forge'
}.glb`,
);
// Offer "Refine" when a higher tier exists and this job can be re-run. Use the
// tier the result was actually produced at (meta), falling back to the current
// selection for re-opened gallery models that don't carry tier metadata.
currentResultTier = meta?.tier || selectedTier;
updateRefineButton();
showState('result');
revealStage();
// Manage focus across the async transition: land on the primary next action
// (Download), but never steal focus from a user already working elsewhere,
// e.g. a gallery card click or someone mid-typing a new prompt.
const ax = document.activeElement;
if (els.download && (!ax || ax === document.body || ax === els.generate)) {
els.download.focus({ preventScroll: true });
}
playMaterialize(glbUrl);
// Hand the live model to the Stylize panel (src/forge-stylize.js) so its
// one-click geometric filters operate on the current source mesh.
// creationId lets the slicer handoff address the creation directly instead
// of parsing it out of a storage URL a lane may not have produced.
document.dispatchEvent(
new CustomEvent('forge:model-ready', { detail: { glbUrl, label, creationId: currentCreationId } }),
);
document.dispatchEvent(
new CustomEvent('tws:feature-done', {
detail: { feature: 'forge', model: { glbUrl, label } },
}),
);
if (els.forgeShareBtn) {
els.forgeShareBtn.dataset.sharePrompt = label;
}
if (!meta?.modly) hideModlySave();
}
// Deterministic gradient from prompt text — same prompt → same colours.
function promptGradient(str) {
let h = 0;
for (let i = 0; i < (str || '').length; i++) h = (Math.imul(31, h) + str.charCodeAt(i)) | 0;
const hue = Math.abs(h) % 360;
return `linear-gradient(135deg,hsl(${hue},28%,14%) 0%,hsl(${(hue + 40) % 360},22%,10%) 100%)`;
}
function makeGradientThumb(prompt) {
const ph = document.createElement('span');
ph.className = 'thumb gradient-ph';
ph.style.background = promptGradient(prompt);
if (prompt) {
const label = document.createElement('span');
label.className = 'gradient-ph-text';
label.textContent = prompt;
ph.appendChild(label);
}
return ph;
}
// Load (or reload) the "Your creations" strip from durable storage.
async function loadGallery() {
if (!els.creations) return;
els.creations.classList.remove('is-hidden');
els.creationsGrid.setAttribute('aria-busy', 'true');
els.creationsGrid.innerHTML = skeletonHTML(4, 'card');
let data;
try {
const res = await fetch('/api/forge-gallery?limit=24', { headers: CLIENT_HEADERS });
data = await res.json().catch(() => ({}));
} catch {
els.creationsGrid.removeAttribute('aria-busy');
els.creationsGrid.innerHTML = errorStateHTML({
title: "Couldn't load your creations",
body: 'Check your connection — your models are still saved.',
});
els.creationsGrid.querySelector('[data-sk-retry]')?.addEventListener('click', loadGallery);
return;
}
els.creationsGrid.removeAttribute('aria-busy');
const creations = Array.isArray(data?.creations) ? data.creations : [];
if (!data?.enabled || creations.length === 0) {
els.creations.classList.add('is-hidden');
// An empty gallery must also drop any compare state left from a previous
// load, or the toggle survives into a section the user cannot see.
compare.setCreations([]);
return;
}
els.creationsGrid.innerHTML = '';
galleryCreations = creations;
for (const c of creations) {
const card = document.createElement('button');
card.type = 'button';
card.className = 'creation';
card.title = c.prompt || 'Forged model';
card.setAttribute('aria-label', `Open: ${c.prompt || 'forged model'}`);
if (c.id) card.dataset.creationId = c.id;
if (c.preview_image_url) {
const img = document.createElement('img');
img.className = 'thumb';
img.loading = 'lazy';
img.decoding = 'async';
img.alt = '';
// The stored preview is a full-resolution render; the card box is a
// few hundred pixels wide. Fetch it at the box's size (2x for retina).
img.src = resizedImageUrl(c.preview_image_url, 480);
img.onerror = () => {
// Thumbnail URL broken — show gradient fallback.
img.replaceWith(makeGradientThumb(c.prompt));
};
card.appendChild(img);
} else {
card.appendChild(makeGradientThumb(c.prompt));
}
if (c.outcome === 'accepted' || c.outcome === 'rejected') {
const badge = document.createElement('span');
badge.className = 'badge';
badge.dataset.outcome = c.outcome;
badge.textContent = c.outcome === 'accepted' ? '👍' : '👎';
card.appendChild(badge);
}
// Surface multi-view provenance so the gallery reflects how each model
// was conditioned.
if (Number(c.views_used) > 1) {
const mv = document.createElement('span');
mv.className = 'badge';
mv.style.left = '6px';
mv.style.right = 'auto';
mv.textContent = `${c.views_used}×`;
mv.title = `${c.views_used} reference views`;
card.appendChild(mv);
}
// Engine · tier provenance, so the gallery reflects how each was made.
if (c.backend || c.tier) {
const prov = document.createElement('span');
prov.className = 'badge';
prov.style.left = '6px';
prov.style.right = 'auto';
prov.style.top = Number(c.views_used) > 1 ? '28px' : '6px';
prov.textContent = [ENGINE_LABELS[c.backend] || c.backend, c.tier]
.filter(Boolean)
.join(' ');
prov.title =
`${c.path === 'geometry' ? 'Geometry-first' : c.path === 'sketch' ? 'Sketch→3D' : 'Image path'} · ${c.backend || ''}${c.engine_version ? ` ${c.engine_version}` : ''} · ${c.tier || ''}`.trim();
card.appendChild(prov);
}
const meta = document.createElement('span');
meta.className = 'meta';
meta.textContent = c.prompt || 'Untitled';
card.appendChild(meta);
// In compare mode a click picks the card instead of opening it; compare
// reports whether it consumed the click.
card.addEventListener('click', () => {
if (compare.handleCardClick(c)) return;
openCreation(c);
});
// The card is itself a <button>, so the delete control lives beside it in
// a positioning wrapper rather than nested inside (invalid HTML).
const cell = document.createElement('div');
cell.className = 'creation-wrap';
cell.appendChild(card);
if (c.id) cell.appendChild(makeDeleteButton(c, cell));
els.creationsGrid.appendChild(cell);
}
els.creationsCount.textContent = `${creations.length} saved`;
els.creations.classList.remove('is-hidden');
compare.setCreations(creations);
}
// Two-tap delete for a gallery card: the first tap arms a visible "Delete?"
// confirm state, the second (within 4s) permanently deletes the creation
// server-side (the stored model, its preview, and any uploaded reference
// photos) and drops the card in place. Blur, Escape, or the timeout disarms.
function makeDeleteButton(c, cell) {
const del = document.createElement('button');
del.type = 'button';
del.className = 'creation-del';
del.textContent = '×';
del.title = 'Delete this creation';
del.setAttribute('aria-label', `Delete: ${c.prompt || 'forged model'}`);
let armed = false;
let disarmTimer = 0;
const disarm = () => {
armed = false;
clearTimeout(disarmTimer);
del.classList.remove('is-armed');
del.textContent = '×';
del.title = 'Delete this creation';
del.setAttribute('aria-label', `Delete: ${c.prompt || 'forged model'}`);
};
del.addEventListener('blur', disarm);
del.addEventListener('keydown', (e) => {
if (e.key === 'Escape') disarm();
});
del.addEventListener('click', async (e) => {
// The wrapper sits inside the card's click target visually; never let a
// delete tap open (or compare-pick) the model underneath.
e.stopPropagation();
if (!armed) {
armed = true;
del.classList.add('is-armed');
del.textContent = 'Delete?';
del.title = 'Click again to permanently delete';
del.setAttribute('aria-label', 'Confirm permanent delete');
disarmTimer = setTimeout(disarm, 4000);
return;
}
clearTimeout(disarmTimer);
del.disabled = true;
del.textContent = '…';
let ok = false;
try {
const res = await fetch(`/api/forge-creation?id=${encodeURIComponent(c.id)}`, {
method: 'DELETE',
headers: CLIENT_HEADERS,
});
const body = await res.json().catch(() => ({}));
// A 404 means the row is already gone (deleted from another tab); the
// card should disappear either way.
ok = (res.ok && body?.deleted === true) || res.status === 404;
} catch {
ok = false;
}
if (!ok) {
del.disabled = false;
disarm();
del.title = "Couldn't delete. Check your connection and try again.";
return;
}
removeCreationFromGallery(c.id, cell);
});
return del;
}
// Drop a deleted creation's card in place: no refetch, no skeleton flash.
// Keeps the count, compare state, and empty state truthful, and clears the
// feedback handle so a verdict can't target the deleted row.
function removeCreationFromGallery(id, cell) {
cell.remove();
galleryCreations = galleryCreations.filter((x) => String(x.id) !== String(id));
compare.setCreations(galleryCreations);
if (els.creationsCount) els.creationsCount.textContent = `${galleryCreations.length} saved`;
if (galleryCreations.length === 0) els.creations.classList.add('is-hidden');
if (String(currentCreationId) === String(id)) currentCreationId = null;
}
// Load a creation into the viewer — shared by gallery card clicks and the
// share-link path. `c` is a creation row from /api/forge-gallery or
// /api/forge-creation; both return the same shape.
function openCreation(c, { scroll = true } = {}) {
currentCreationId = c.id;
lastJob = { prompt: c.prompt || '', imageUrls: [] };
showResult(
c.web_glb_url || c.glb_url,
c.prompt || 'Forged model',
{
views_used: c.views_used,
multiview: c.multiview,
backend: c.backend,
tier: c.tier,
path: c.path,
creatorUsername: c.creatorUsername || null,
},
{ downloadUrl: c.glb_url },
);
if (els.verdict) {
for (const b of els.verdict.querySelectorAll('button')) {
b.setAttribute('aria-pressed', String(b.dataset.outcome === c.outcome));
}
}
if (scroll) els.stage.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
// Open a creation from a share link. The model belongs to whoever forged it, so
// it won't be in this browser's gallery — fetch it directly by id. If the card
// is already present (the owner re-opening their own share link), reuse it.
async function openSharedCreation(shareId) {
const card = els.creationsGrid?.querySelector(`[data-creation-id="${shareId}"]`);
if (card) {
card.click();
card.scrollIntoView({ behavior: 'smooth', block: 'center' });
return;
}
let creation = null;
try {
const res = await fetch(`/api/forge-creation?id=${encodeURIComponent(shareId)}`, {
headers: CLIENT_HEADERS,
});
const data = await res.json().catch(() => ({}));
creation = data?.creation || null;
} catch {
creation = null;
}
if (creation?.glb_url) {
openCreation(creation);
} else {
showError(
"This shared creation isn't available — it may have been removed or is still generating.",
);
}
}
function showError(message, { allowOverride = false, title = 'Generation failed' } = {}) {
stopElapsed();
// Freeze the timeline where it really got to and drop the warming card: the
// job is over, so nothing may keep implying work is still happening.
timeline.fail();
stopRateLimitCountdown();
if (els.errorTitle) els.errorTitle.textContent = title;
els.errorMessage.textContent = message;
// The "Generate anyway" affordance only exists for the vision pre-check
// rejection; every other error hides it so it can't leak across states.
if (els.generateAnyway) els.generateAnyway.classList.toggle('is-hidden', !allowOverride);
// The local-refine escape hatch belongs only to the rate-limit state.
if (els.refineLocally) els.refineLocally.classList.add('is-hidden');
// Lane-switch buttons belong only to the lane-failed state (showLaneFailed
// re-reveals them after this reset).
if (els.errorLanes) {
els.errorLanes.classList.add('is-hidden');
els.errorLanes.innerHTML = '';
// showStorageDown relabels this group for its own contents; every other
// state that reveals it fills it with engine switches, so reset the name.
els.errorLanes.setAttribute('aria-label', 'Retry on another engine');
}
if (els.retry) els.retry.disabled = false;
showState('error');
// A failure the user cannot see is a hang. On a stacked layout the stage sits
// below the fold, so bring it up before moving focus into it.
revealStage();
// The async flow just landed on an error: put keyboard focus on the primary
// recovery action, unless the user is already typing somewhere else.
const ax = document.activeElement;
if (els.retry && (!ax || ax === document.body || ax === els.generate)) {
els.retry.focus({ preventScroll: true });
}
}
// Every automatic backup lane is exhausted — the one moment the user may see
// an error, so it must not be a dead end. Alongside Try again, render a
// one-click button per remaining configured engine: clicking flips the picker
// (visible switch) and re-runs the same composer inputs, nothing re-entered.
function showLaneFailed(message, backends) {
showError(message || 'That engine hit a snag mid-generation.', {
title: 'Engine hit a snag',
});
if (!els.errorLanes || !lastJob) return;
const buttons = (backends || []).filter((id) => ENGINE_LABELS[id] || catalog?.backends?.some((b) => b.id === id));
if (!buttons.length) return;
for (const id of buttons) {
const info = catalog?.backends?.find((b) => b.id === id);
const label = ENGINE_LABELS[id] || info?.label || id;
const btn = document.createElement('button');
btn.type = 'button';
btn.className = 'btn btn-ghost';
btn.textContent = info?.free ? `Try on ${label} (free)` : `Try on ${label}`;
btn.addEventListener('click', () => {
if (!lastJob) return;
// The picker flip is the affordance: the user sees exactly which engine
// serves the retry. Fall back to a plain same-lane retry if the button
// for that engine isn't live on this deployment.
selectEngineByBackend(id);
run(lastJob);
});
els.errorLanes.appendChild(btn);
}
els.errorLanes.classList.remove('is-hidden');
}
// Object storage is rejecting us, so no lane can finish a generation: every one
// of them has to park a reference image or a finished mesh in the bucket. This
// is the one failure class where "try another engine" is a lie, so instead of
// offering it we tell the user plainly what broke, that it is ours and not
// theirs, and what still works right now: every model they already forged is
// served from the public CDN and opens, downloads and refines exactly as before.
// Retry stays, on the same live countdown as the quota state, because a fixed
// credential recovers within seconds without a redeploy.
function showStorageDown({ retryAfter = 60, message = '' } = {}) {
stopElapsed();
timeline.fail();
stopRateLimitCountdown();
if (els.generateAnyway) els.generateAnyway.classList.add('is-hidden');
const canRefineLocally = Boolean(lastShownGlb && els.viewer.getAttribute('src'));
if (els.refineLocally) els.refineLocally.classList.toggle('is-hidden', !canRefineLocally);
if (els.errorTitle) els.errorTitle.textContent = 'Our storage is down, not your prompt';
// The alternative that genuinely works while the bucket is unreachable. This
// row is normally the engine-switch group, so it says what it holds now.
if (els.errorLanes) {
els.errorLanes.innerHTML = '';
els.errorLanes.setAttribute('aria-label', 'What still works while storage recovers');
const seeSaved = document.createElement('button');
seeSaved.type = 'button';
seeSaved.className = 'btn btn-ghost';
seeSaved.textContent = 'Open a saved model';
seeSaved.addEventListener('click', () => {
els.creations?.scrollIntoView({ behavior: 'smooth', block: 'start' });
els.creationsGrid?.querySelector('button, [tabindex]')?.focus?.({ preventScroll: true });
});
els.errorLanes.appendChild(seeSaved);
els.errorLanes.classList.remove('is-hidden');
}
let remaining = Math.max(1, Math.ceil(retryAfter));
const base =
message ||
'3D generation is paused while our asset storage recovers. Nothing you did caused this and nothing was charged.';
const tail = canRefineLocally ? ' Your current model is still here: refine it locally, no storage needed.' : '';
const render = () => {
els.errorMessage.textContent =
remaining > 0
? `${base} Retrying is available in ${remaining}s.${tail}`
: `${base} You can try again now.${tail}`;
};
if (els.retry) els.retry.disabled = remaining > 0;
render();
showState('error');
revealStage();
rateLimitTimer = setInterval(() => {
remaining -= 1;
if (remaining <= 0) {
stopRateLimitCountdown();
if (els.retry) els.retry.disabled = false;
}
render();
}, 1000);
}
// Rate-limit state: a designed, recoverable treatment for a 429. Instead of a
// dead-end "busy, try again", we (1) show a live countdown to the reset and
// re-enable Retry automatically when it elapses, and (2) — when a model is
// already on screen — offer the local Refine path, which needs no API and never
// throttles, so the user is never fully blocked. Distinguishes a genuine quota
// hit from a temporarily-unavailable limiter (Redis degraded → fail-closed).
let rateLimitTimer = null;
function stopRateLimitCountdown() {
if (rateLimitTimer) {
clearInterval(rateLimitTimer);
rateLimitTimer = null;
}
}
function showRateLimited({ retryAfter = 10, unavailable = false, busy = false }) {
stopElapsed();
timeline.fail();
stopRateLimitCountdown();
if (els.generateAnyway) els.generateAnyway.classList.add('is-hidden');
// Offer local refinement whenever a model is already loaded — that's exactly
// the case after the Refine button 429s, and the one moment the user most
// wants to keep improving without waiting on the paid lane.
const canRefineLocally = Boolean(lastShownGlb && els.viewer.getAttribute('src'));
if (els.refineLocally) els.refineLocally.classList.toggle('is-hidden', !canRefineLocally);
// This is a wait state, not a failure. The heading must say so, or a quota
// pause reads as a broken product.
if (els.errorTitle) {
els.errorTitle.textContent = busy
? 'High demand right now'
: unavailable
? 'Temporarily unavailable'
: 'Generation limit reached';
}
let remaining = Math.max(1, Math.ceil(retryAfter));
const base = busy
? 'High demand — the free 3D engines are all busy right now.'
: unavailable
? 'The generator is temporarily unavailable.'
: 'You’ve hit the generation limit.';
const tail = canRefineLocally ? ' Or refine your current model now — instant and unlimited.' : '';
const render = () => {
els.errorMessage.textContent =
remaining > 0 ? `${base} Retrying is available in ${remaining}s.${tail}` : `${base} You can try again now.${tail}`;
};
// While counting down, Retry is disabled (it would just 429 again); it
// re-enables the moment the window resets.
if (els.retry) els.retry.disabled = remaining > 0;
render();
showState('error');
revealStage();
rateLimitTimer = setInterval(() => {
remaining -= 1;
if (remaining <= 0) {
stopRateLimitCountdown();
if (els.retry) els.retry.disabled = false;
}
render();
}, 1000);
}
// Run a job (text or image/multi-view). `cfg` = { prompt, imageUrls }.
async function run(cfg) {
stopRateLimitCountdown();
// Capture before the single-use payment proof is stripped below — it tells the
// upgrade-funnel conversion which path (pay-per-use vs. hold) closed the loop.
const wasPaidGeneration = !!cfg.payment;
lastJob = cfg;
pollAbort = false;
currentCreationId = null;
setBusy(true);
const isImage = Array.isArray(cfg.imageUrls) && cfg.imageUrls.length > 0;
const isGeometry = selectedEngine.path === 'geometry';
const isSketch = selectedEngine.path === 'sketch';
// Open the timeline on what we genuinely know before the request goes out:
// which input the run starts from, which lane was picked, and whether that
// lane paints a reference view at all. Geometry-first engines and the free
// NVIDIA NIM lane emit the mesh straight from the prompt, so they never get a
// reference stage. Everything after this comes from the server's answers.
timeline.begin({
mode: isSketch ? 'sketch' : isImage ? 'image' : 'text',
backend: selectedEngine.backend,
viewCount: isImage ? cfg.imageUrls.length : 0,
localPreviewUrl: isSketch ? sketch.objectUrl || sketch.url : isImage ? firstPreviewUrl() : null,
usesReference: !isGeometry && selectedEngine.backend !== 'nvidia',
});
// A fresh panel starts with no lane notice, unless an automatic engine hop
// queued one for this very re-run.
setLaneNote(pendingLaneNote);
pendingLaneNote = '';
startElapsed();
showState('generating');
revealStage();
const label = cfg.prompt || (isImage ? 'Multi-view reconstruction' : '');
// Watch the server's pre-submit milestones for THIS submission while the POST
// below is still open, so the director's rewrite and the reference view land
// on the stage list the moment each one genuinely finishes, not at the end.
const progressId = mintProgressId();
startProgressWatch(progressId);
try {
const job = await startJob({ ...cfg, progressId });
// The POST answered, so it now carries every fact the crumbs were standing
// in for. Nothing left to watch.
stopProgressWatch();
if (job.creation_id) currentCreationId = job.creation_id;
// Fold every real signal the submit response carries into the timeline: the
// lane that actually ran, the art-directed prompt, the reference view (shown
// the moment it exists), the honest ETA, and the cold-start flag. The warm
// baseline is the catalog estimate for that same lane, so the warming card
// counts down a real difference rather than an invented number.
timeline.applySubmit(job, {
warmEtaSeconds: warmEtaFor(job.backend || selectedEngine.backend, job.path || selectedEngine.path, job.tier || selectedTier),
});
// The free draft lane (NVIDIA NIM) completes synchronously — the POST
// itself returns the finished model with a null job_id. Polling that
// null id would loop on invalid_job until the timeout, losing a result
// that already succeeded.
const isAsync = !(job.status === 'done' && job.glb_url);
if (isAsync) saveInflight(job, label);
const done = !isAsync ? job : await pollUntilDone(job.job_id);
if (pollAbort || !done) return; // cancelled
clearInflight();
// A pay-per-use proof is single-use and now redeemed on the server — drop it
// so a later Retry/Refine of this job never replays a spent payment.
if (lastJob) delete lastJob.payment;
if (done.creation_id) currentCreationId = done.creation_id;
// The mesh is delivered; the remaining work (durable copy already done
// server-side, viewer load here) is the finalizing stage.
timeline.finalizing();
markProgressDone();
// Prefer the poll's recorded meta; fall back to the submit response.
showResult(
done.glb_url,
label || 'Forged model',
{
views_used: done.views_used ?? job.views_used,
multiview: done.multiview ?? job.multiview,
backend: done.backend ?? job.backend,
tier: done.tier ?? job.tier,
path: done.path ?? job.path,
quality: done.quality ?? job.quality,
quality_gate: done.quality_gate ?? job.quality_gate,
rigged: done.rigged ?? job.rigged,
},
{ autoSaved: !!done.creation_id },
);
timeline.complete();
// What the model was actually asked for. Only the reference-image lanes run
// the art director, so `directed_prompt` is absent on every other lane and
// the reveal stays hidden rather than showing a reconstructed guess.
document.dispatchEvent(
new CustomEvent('forge:directed-prompt', {
detail: {
prompt: cfg.prompt || '',
directedPrompt: done.directed_prompt ?? job.directed_prompt ?? null,
model: done.text_to_image_model ?? job.text_to_image_model ?? null,
},
}),
);
loadGallery();
// Geometry-first and sketch lanes have no reference image — render the
// finished mesh itself as the creation's card visual.
if (!(done.preview_image_url ?? job.preview_image_url)) {
capturePoster(currentCreationId);
}
// Conversion: if this run followed an upgrade gate, the gated High lane just
// produced a model — close the upgrade funnel. No-op unless a gate was shown
// recently, and fires once per gate. Only the High tier is gated.
if ((done.tier ?? job.tier) === 'high') {
trackUpgradeConverted({
feature: 'forge_high',
path: wasPaidGeneration ? 'pay_per_use' : 'hold',
usd: wasPaidGeneration ? Number(_highAccess?.pay_per_use?.usd) || undefined : undefined,
});
}
} catch (err) {
if (pollAbort) return;
// Every catch path either terminates this job with a designed state or
// re-runs (which writes a fresh inflight record), so the old record is
// dead either way. The server-side finalizer still completes the row
// into the gallery if the lane actually finished after our timeout.
//
// One exception: a connection we gave up waiting on. The generation is
// still running server-side and the inflight record is the only handle
// this browser has on it, so clearing it here is what used to make the
// error's own "reopen /forge to pick it back up" a lie. Keep it and the
// resume path in boot() picks the same job back up.
if (err?.kind !== 'transport_lost') clearInflight();
// This job is over on every branch below (a designed error state, a gate,
// or an automatic lane hop that starts a fresh timeline of its own), so the
// stage list stops here rather than sitting on a spinning row.
timeline.fail();
if (err.kind === 'unconfigured') {
stopElapsed();
showState('unconfigured');
return;
}
// Recoverable BYOK problems — reveal + focus the key field so the user can
// fix it and hit Retry, rather than hitting a dead end.
if (err.kind === 'needs_key' || err.kind === 'invalid_key') {
stopElapsed();
els.byokRow?.classList.remove('is-hidden');
if (els.providerKey) {
els.providerKey.setAttribute('aria-invalid', 'true');
els.providerKey.focus();
}
showError(err.message || 'Add your API key to use this engine, then retry.');
return;
}
if (err.kind === 'credits') {
stopElapsed();
showError(err.message || 'The provider account is out of credits.');
return;
}
// The reference photo failed the vision pre-check. Offer "Generate anyway"
// so a confident user is never permanently blocked by a cautious verdict.
if (err.kind === 'not_usable') {
showError(err.message, { allowOverride: true });
return;
}
// Rate limited (or the limiter is temporarily unavailable). Designed,
// recoverable state with a live countdown + the local-refine escape hatch.
if (err.kind === 'rate_limited') {
showRateLimited({ retryAfter: err.retryAfter, unavailable: err.unavailable });
return;
}
// Object storage is refusing us. Designed, honest, and pointed at the thing
// that still works, instead of a raw signing complaint from the store.
if (err.kind === 'storage_down') {
showStorageDown({ retryAfter: err.retryAfter, message: err.message });
return;
}
// Free lane at capacity under load — same recoverable countdown UI, framed as
// high demand. Auto-retry lands the user in line as slots free up, and the
// local-refine escape hatch still applies when a model is already on screen.
if (err.kind === 'busy') {
showRateLimited({ retryAfter: err.retryAfter, busy: true });
return;
}
// High-tier $THREE gate: open the designed upsell (Get $THREE / what you hold
// vs. need — plus the working Pay-per-use CTA) and reset to the idle composer
// so the user can switch tier, hold, or pay.
if (err.kind === 'hold_required') {
stopElapsed();
showState('empty');
// Reflect the server's verdict back onto the composer (lock the High
// option + the button pill/note) before opening the upsell, so the gate is
// felt in place too — not only in the modal.
highLocked = true;
_highAccess = err.gate || _highAccess;
applyHighGate();
applyHighAffordances(err.gate);
onGate(err.gate, gateOpts());
return;
}
// A lane died mid-generation and the server has no async lane left to
// continue on itself — but it told us which configured engines can still
// serve this request. Hop automatically once (visible: the picker flips)
// so a backup kicks in with zero user action; if the hop also fails,
// surface one-click engine switches. The user never dead-ends.
if (err.kind === 'lane_failed' && Array.isArray(err.retryBackends) && err.retryBackends.length) {
stopElapsed();
if (lastJob && autoLaneHops < 1) {
const failedId = selectedEngine.backend;
if (selectEngineByBackend(err.retryBackends[0])) {
autoLaneHops += 1;
// Queue the switch notice for the re-run's generating panel, so the
// automatic hop is visible (picker flip + an in-panel line), never silent.
pendingLaneNote = `${engineLabel(failedId)} hit a snag. Retrying on ${engineLabel(err.retryBackends[0])}, no action needed.`;
run(lastJob);
return;
}
}
showLaneFailed(err.message, err.retryBackends);
return;
}
// A presented pay-per-use proof was already spent — drop the stale payment so
// Retry doesn't replay it, and re-open the pay flow for a fresh generation.
if (err.kind === 'payment_used') {
stopElapsed();
if (lastJob) delete lastJob.payment;
showState('empty');
showError(err.message || 'That payment was already used. Pay again to generate.');
return;
}
// The proof was rejected (bad/expired) before any model — drop it and surface
// the gate's Pay-per-use path again so the user can pay cleanly.
if (err.kind === 'payment_invalid') {
stopElapsed();
if (lastJob) delete lastJob.payment;
showState('empty');
if (err.gate) onGate(err.gate, gateOpts());
else showError(err.message || 'That $THREE payment could not be verified.');
return;
}
showError(
err.message ||
'Something went wrong. Try a simpler, single-subject prompt or cleaner photos.',
);
} finally {
// Every exit from this job (delivered, cancelled, errored, gated) ends the
// pre-submit watch, so a poll can never outlive the run that started it.
stopProgressWatch();
setBusy(false);
}
}
// Your GPU (Modly) -----------------------------------------------------------
// An opt-in lane that runs image-to-3D on the visitor's own graphics card
// through Modly (src/modly-local.js, src/forge-modly.js). Its models join the
// engine picker as `modly:<id>` engines, the run reports Modly's real percent
// and step text, and the finished GLB enters the same result path as a cloud
// generation once it has a public copy (rig, optimize and AR need a URL).
function isModlyEngine(id) {
return typeof id === 'string' && id.startsWith('modly:');
}
function modlyEngineLabel(id) {
const modelId = id.slice('modly:'.length);
return `Your GPU (${modly?.modelById(modelId)?.name || modelId})`;
}
// Models that can serve the current tab: Modly takes a photo, so only the
// photos tab offers them.
function modlyReadyModels() {
return mode === 'image' && modly ? modly.readyModels() : [];
}
function appendModlyEngineButtons() {
const ids = [];
for (const m of modlyReadyModels()) {
const id = `modly:${m.id}`;
const btn = document.createElement('button');
btn.type = 'button';
Object.assign(btn.dataset, {
engine: id,
path: 'modly',
backend: id,
byok: '',
poly: 'false',
userimages: 'true',
modly: '1',
modelId: m.id,
});
const name = document.createElement('span');
name.className = 'eng-label';
name.textContent = m.name;
const pill = document.createElement('span');
pill.className = 'eng-free eng-local';
pill.setAttribute('aria-hidden', 'true');
pill.textContent = 'Your GPU, free';
btn.append(name, ' ', pill);
const vram = m.vramGb ? ` · needs about ${m.vramGb} GB of graphics memory` : '';
btn.title = `${m.name}: runs in Modly on your own graphics card, free${vram}`;
btn.setAttribute('aria-label', `${m.name}, runs on your GPU, free`);
btn.setAttribute('aria-pressed', String(id === selectedEngine.backend));
els.engine.appendChild(btn);
ids.push(id);
}
return ids;
}
// Rebuild the engine picker from whatever can serve right now: the cloud
// catalog, the connected Modly models, or both. With no catalog (an older
// deployment) the picker still appears for Modly alone.
function refreshEnginePicker() {
if (!els.engine) return;
if (!catalog) {
const local = modlyReadyModels().length > 0;
els.engine.closest('#forge-quality')?.classList.toggle('is-hidden', !local);
if (!local) {
els.engine.innerHTML = '';
if (selectedEngine.modly) {
selectedEngine = { ...DEFAULT_ENGINE };
els.tier?.classList.remove('is-hidden');
}
return;
}
}
buildEngineButtons();
}
function onModlyChange(state) {
if (state.status === 'probing') return;
if (state.status !== 'connected' && selectedEngine.modly) userPickedEngine = false;
refreshEnginePicker();
// Connecting is an explicit opt-in, so a first connect puts a local model in
// the selection. A Refresh keeps whichever Modly model was already picked.
if (state.status === 'connected' && mode === 'image' && !selectedEngine.modly) {
const btn = els.engine?.querySelector('button[data-modly="1"]:not(:disabled)');
if (btn) {
userPickedEngine = true;
selectEngine(btn);
}
}
updateEstimate();
}
function renderModlyEstimate() {
const model = modly?.modelById(selectedEngine.modelId);
const parts = [
'<strong>Your GPU</strong>',
'<span class="est-free">Free</span>',
'runs in Modly on this computer',
'builds from your first photo',
];
if (model?.vramGb) parts.push(`needs about ${Number(model.vramGb)} GB of graphics memory`);
els.estimate.innerHTML = parts.join(' · ');
}
function paintModlyProgress(elapsedS) {
const pending = modlyRun.state === 'pending';
if (els.genProgress) {
els.genProgress.dataset.indeterminate = String(pending);
els.genProgress.dataset.over = 'false';
}
if (!pending) setProgress(modlyRun.pct);
const strong = document.createElement('strong');
strong.textContent = `${elapsedS}s`;
els.genMeta.replaceChildren('Elapsed ', strong, pending ? '' : ` · ${modlyRun.pct}%`);
if (modlyRun.step) els.genMeta.append(` · ${modlyRun.step}`);
}
// The photo Modly builds from: the first view the user added. Modly takes a
// single image, so extra views are named as unused rather than silently dropped.
function modlySourceSlot() {
const index = slots.findIndex(
(s) => (s.state === 'uploaded' || s.state === 'uploading') && s.objectUrl,
);
return index < 0 ? null : { index, slot: slots[index] };
}
function modlyErrorCopy(err, modelName) {
switch (err?.code) {
case 'GENERATION_FAILED':
return {
title: `${modelName} couldn't finish`,
message: `Modly reported: ${err.message} The full trace is in Modly's log.`,
};
case 'CANCELLED':
return {
title: 'Cancelled in Modly',
message: 'The generation was stopped from inside the Modly app. Press Try again to run it again.',
};
case 'NOT_RUNNING':
case 'BLOCKED':
case 'TIMEOUT':
return {
title: 'Modly stopped answering',
message: `${err.message} Make sure Modly is still open, then press Try again.`,
};
case 'UNKNOWN_MODEL':
return {
title: 'Model not available in Modly',
message: `${err.message} Press Refresh under "Use your GPU" to reload the model list.`,
};
default:
return {
title: 'Modly couldn’t finish',
message: err?.message || 'Modly could not finish this generation.',
};
}
}
async function runModly(modelId) {
if (modlyRun) return;
stopRateLimitCountdown();
lastJob = { modly: true, modelId };
// A Retry after Modly restarted: look for it again before giving up.
if (modly && modly.state.status !== 'connected') await modly.connect();
const origin = modly?.state.status === 'connected' ? modly.state.origin : null;
const model = origin ? modly.readyModels().find((m) => m.id === modelId) : null;
if (!origin) {
showError(
'Forge could not reach Modly on this computer. Start Modly, then press Try again. The "Use your GPU" panel in the photos tab shows what the browser saw.',
{ title: 'Modly is not reachable' },
);
return;
}
if (!model) {
showError(
`${modelId} is no longer downloaded in Modly. Pick another engine, or download it again in Modly's Models page.`,
{ title: 'Model not available in Modly' },
);
return;
}
const source = modlySourceSlot();
if (!source) {
const first = slotEl(0);
first?.focus();
first?.classList.add('drop-target');
setTimeout(() => first?.classList.remove('drop-target'), 600);
return;
}
let image;
try {
image = await (await fetch(source.slot.objectUrl)).blob();
} catch {
showError('Forge could not read your photo. Add it again, then press Try again.', {
title: 'Photo unavailable',
});
return;
}
const backend = `modly:${modelId}`;
const controller = new AbortController();
modlyRun = { controller, pct: 0, step: 'Sending your photo to Modly', state: 'pending' };
currentCreationId = null;
pollAbort = false;
setBusy(true);
timeline.begin({
mode: 'image',
backend,
viewCount: 1,
localPreviewUrl: source.slot.objectUrl,
usesReference: false,
local: true,
});
const views = slots.filter((s) => s.state === 'uploaded' || s.state === 'uploading').length;
setLaneNote(
views > 1
? `Modly builds from a single photo, so only your ${VIEW_LABELS[source.index]} view is used.`
: '',
);
// A local run lives in this tab: leaving the page would stop following it.
if (els.genLeaveHint) els.genLeaveHint.hidden = true;
startElapsed();
showState('generating');
revealStage();
const prompt = els.imagePrompt?.value.trim() || '';
const label = prompt || `${model.name} model`;
try {
const result = await generateWithModly(origin, {
image,
modelId,
params: defaultModlyParams(model.paramsSchema),
signal: controller.signal,
onStarted: () => timeline.applySubmit({ backend, status: 'queued' }),
onProgress: (pct, step, state) => {
if (modlyRun?.controller !== controller) return;
Object.assign(modlyRun, { pct, step, state: state || modlyRun.state });
if (state === 'done') {
timeline.finalizing();
} else {
timeline.applyPoll({ status: state === 'running' ? 'running' : 'queued' });
timeline.setStepText(step);
}
elapsedRetick?.();
},
});
// The mesh is on this machine. Give it a public copy so every downstream
// tool (rig, optimize, AR, embed, save) can fetch it like a cloud result.
Object.assign(modlyRun, { pct: 100, step: 'Copying the model to three.ws storage' });
elapsedRetick?.();
markProgressDone();
const objectUrl = URL.createObjectURL(result.blob);
let publicUrl = '';
let storageError = '';
try {
publicUrl = await promoteModlyGlb(result.blob, { signal: controller.signal });
} catch (err) {
if (controller.signal.aborted) {
URL.revokeObjectURL(objectUrl);
throw err;
}
storageError = err?.message || 'Storage is unavailable.';
}
releaseModlyResult();
modlyResult = {
objectUrl,
publicUrl,
storageError,
blob: result.blob,
label,
prompt,
modelName: model.name,
};
showResult(
publicUrl || objectUrl,
label,
{ backend, views_used: 1, modly: true },
{ downloadUrl: objectUrl },
);
timeline.complete();
// Not a server-side creation: the creation-scoped feedback controls
// (verdict, category, destination) would have nothing to write to.
if (els.verdict) els.verdict.hidden = true;
if (els.categoryPicker) els.categoryPicker.hidden = true;
destinationPicker.hide();
renderModlySave();
} catch (err) {
const ours = controller.signal.aborted;
if (ours) {
// The person pressed Cancel; generateWithModly already told Modly to stop.
stopElapsed();
timeline.fail();
showState('empty');
modly?.notify('Cancelled. Modly stopped the generation.');
els.imagePrompt?.focus();
return;
}
const copy = modlyErrorCopy(err, model.name);
showError(copy.message, { title: copy.title });
} finally {
if (modlyRun?.controller === controller) modlyRun = null;
if (els.genLeaveHint) els.genLeaveHint.hidden = false;
setBusy(false);
}
}
function releaseModlyResult() {
if (modlyResult?.objectUrl) URL.revokeObjectURL(modlyResult.objectUrl);
modlyResult = null;
}
// Any non-local result replaces the local one: drop its save row and blob.
function hideModlySave() {
if (els.modlySave) els.modlySave.hidden = true;
if (els.verdict) els.verdict.hidden = false;
releaseModlyResult();
}
// The save row under a local result. `phase` is one of: ready, saving,
// signin, saved, error.
function renderModlySave(phase = 'ready', detail = {}) {
if (!els.modlySave || !modlyResult) return;
const r = modlyResult;
const text = els.modlySaveText;
const btn = els.modlySaveBtn;
els.modlySave.hidden = false;
text.dataset.tone = phase === 'saved' ? 'ok' : phase === 'error' || phase === 'signin' ? 'error' : '';
btn.hidden = phase === 'saved';
btn.disabled = phase === 'saving';
btn.setAttribute('aria-busy', String(phase === 'saving'));
btn.textContent = r.publicUrl ? 'Save to my avatars' : 'Upload and save';
const strong = (s) => {
const el = document.createElement('strong');
el.textContent = s;
return el;
};
const link = (href, s) => {
const a = document.createElement('a');
a.href = href;
a.textContent = s;
return a;
};
if (phase === 'saving') {
text.replaceChildren(r.publicUrl ? 'Saving to your avatars…' : 'Uploading, then saving to your avatars…');
} else if (phase === 'saved') {
text.replaceChildren(strong('Saved to your avatars.'), ' ');
if (detail.viewUrl) text.append(link(detail.viewUrl, 'Open it'));
} else if (phase === 'signin') {
text.replaceChildren(
strong('Sign in to save it.'),
' ',
link(`/login?next=${encodeURIComponent('/forge')}`, 'Sign in'),
' in a new tab if you want to keep this model on screen, then press Save again. Download works without an account.',
);
} else if (phase === 'error') {
text.replaceChildren(strong('Not saved.'), ` ${detail.message || 'Try again.'}`);
} else if (r.publicUrl) {
text.replaceChildren(
`Made on your GPU with ${r.modelName}. It is not in Your creations: save it to your avatars to keep it in your library.`,
);
} else {
text.replaceChildren(
strong('Only on this computer.'),
` Copying it to three.ws failed (${r.storageError}), so rigging, optimizing and saving need an upload first. Download keeps the GLB either way.`,
);
}
}
async function saveModlyResult() {
const r = modlyResult;
if (!r) return;
renderModlySave('saving');
if (!r.publicUrl) {
try {
r.publicUrl = await promoteModlyGlb(r.blob);
r.storageError = '';
} catch (err) {
r.storageError = err?.message || 'Storage is unavailable.';
renderModlySave('error', { message: `Upload failed: ${r.storageError}` });
return;
}
if (modlyResult !== r) return;
// The model now has a public URL: hand it to the result tools that need one.
linkResultTools(r.publicUrl);
lastShownGlb = r.publicUrl;
document.dispatchEvent(
new CustomEvent('forge:model-ready', { detail: { glbUrl: r.publicUrl, label: r.label } }),
);
}
const out = await saveModlyResultToLibrary({
glbUrl: r.publicUrl,
name: r.label,
sourcePrompt: r.prompt,
modelName: r.modelName,
});
if (modlyResult !== r) return;
if (out.ok) renderModlySave('saved', { viewUrl: out.viewUrl });
else if (out.status === 401) renderModlySave('signin');
else renderModlySave('error', { message: out.message });
}
els.modlySaveBtn?.addEventListener('click', saveModlyResult);
modly = createModlyPanel({ root: els.modlyPanel, onChange: onModlyChange });
// Resume an in-flight generation persisted before a reload/navigation. The
// server holds all job state, so picking it back up is just polling the same
// job id; the panel restores in its mesh phase with an honest elapsed count.
async function resumeInflight() {
const inflight = readInflight();
if (!inflight) return false;
pollAbort = false;
currentCreationId = inflight.creationId || null;
setBusy(true);
// Restore the timeline in its mesh phase: the earlier stages provably
// finished (the job exists, and the reference view was recorded with it), and
// the next real poll refines the rest. A resumed job whose reference view was
// never captured locally still gets it: the poll response carries it.
timeline.resume({
mode: inflight.path === 'sketch' ? 'sketch' : 'text',
backend: inflight.backend,
referenceUrl: inflight.previewImageUrl || null,
elapsedS: Math.max(0, Math.round((Date.now() - inflight.startedAt) / 1000)),
});
setLaneNote('Welcome back. This generation kept running while you were away.');
startElapsed(Date.now() - inflight.startedAt);
showState('generating');
try {
const done = await pollUntilDone(inflight.jobId);
if (pollAbort || !done) return true;
clearInflight();
if (done.creation_id) currentCreationId = done.creation_id;
timeline.finalizing();
markProgressDone();
// No directed-prompt reveal on a resumed job: the submit response is long
// gone and the rewrite is not persisted with the creation, so showResult's
// own reset leaves the panel hidden rather than showing a stale prompt.
showResult(
done.glb_url,
inflight.label || 'Forged model',
{
views_used: done.views_used,
multiview: done.multiview,
backend: done.backend ?? inflight.backend,
tier: done.tier ?? inflight.tier,
path: done.path ?? inflight.path,
quality: done.quality,
quality_gate: done.quality_gate,
rigged: done.rigged,
},
{ autoSaved: !!done.creation_id },
);
timeline.complete();
loadGallery();
if (!done.preview_image_url && !inflight.previewImageUrl) {
capturePoster(currentCreationId);
}
} catch (err) {
if (pollAbort) return true;
clearInflight();
showError(
err.message ||
'Something went wrong resuming your generation. Check your gallery: finished models land there automatically.',
);
} finally {
setBusy(false);
}
return true;
}
// Gather + validate the active mode's composer inputs into a run cfg, or null
// when something's missing (focusing/flagging the offending field as a side
// effect, exactly as submit always has). Shared by the Generate button and the
// pay-per-use path so both build the job identically.
function collectComposerCfg() {
if (mode === 'text') {
const prompt = els.prompt.value.trim();
if (prompt.length < 3) {
els.prompt.focus();
return null;
}
return { prompt, imageUrls: [] };
}
// Sketch mode — one drawing + a required prompt naming what it depicts.
if (mode === 'sketch') {
if (sketch.state === 'uploading') {
els.generateLabel.textContent = 'Waiting for upload…';
setTimeout(() => {
if (!els.generate.disabled) els.generateLabel.textContent = 'Generate';
}, 1600);
return null;
}
if (sketch.state !== 'uploaded' || !sketch.url) {
const slot = sketchSlotEl();
slot?.focus();
slot?.classList.add('drop-target');
setTimeout(() => slot?.classList.remove('drop-target'), 600);
return null;
}
const prompt = els.sketchPrompt.value.trim();
if (prompt.length < 3) {
// Make the required-input contract unmissable: flag the field and tint
// the "Required" tag until the user types a description.
els.sketchPrompt.setAttribute('aria-invalid', 'true');
if (els.sketchReqTag) els.sketchReqTag.dataset.missing = 'true';
els.sketchPrompt.focus();
return null;
}
return { prompt, imageUrls: [sketch.url] };
}
// Image / multi-view mode.
if (slots.some((s) => s.state === 'uploading')) {
els.generateLabel.textContent = 'Waiting for uploads…';
setTimeout(() => {
if (!els.generate.disabled) els.generateLabel.textContent = 'Generate';
}, 1600);
return null;
}
const urls = uploadedUrls();
if (urls.length === 0) {
const first = slotEl(0);
first?.focus();
first?.classList.add('drop-target');
setTimeout(() => first?.classList.remove('drop-target'), 600);
return null;
}
return { prompt: els.imagePrompt.value.trim(), imageUrls: urls };
}
function submit() {
// Your GPU lane: the run happens in Modly on this computer, not /api/forge.
if (selectedEngine.modly && mode === 'image') {
runModly(selectedEngine.modelId);
return;
}
// Platform-keyed High is a $THREE holder perk. The Generate button is disabled
// when locked, but a keyboard submit (⌘↵) can still reach here — open the upsell
// (with the working Pay-per-use path) instead of firing a request the server will
// gate. BYOK High is exempt, so highTierNeedsPass() lets it through untouched.
if (highTierNeedsPass() && highLocked) {
if (_highAccess) onGate(_highAccess, gateOpts());
else reflectHighAccess('high');
return;
}
const cfg = collectComposerCfg();
// A fresh user-initiated generation resets the automatic lane-hop budget —
// the single silent hop belongs to one submission, never accumulates.
autoLaneHops = 0;
if (cfg) run({ ...cfg, seed: mintSeed() });
}
// Options handed to the gate modal / in-place lock so their "Pay per generation"
// CTA actually works: pay $THREE for one High generation, then run the current
// composer inputs with the settled proof attached.
function gateOpts() {
return { onPayPerUse: (pay) => payThenGenerate(pay) };
}
// The consumption lever, end to end: price comes from the gate's pay_per_use (or
// the resolved access), the user pays $THREE through the designed modal, and the
// generation re-fires immediately with { paymentId, refId } so the server's gate
// is satisfied per use. No-op if the composer inputs are incomplete (the field is
// focused) or the user cancels the payment.
async function payThenGenerate(pay) {
const usd = Number(pay?.usd) || Number(_highAccess?.pay_per_use?.usd) || 0;
if (!(usd > 0)) return;
const cfg = collectComposerCfg();
if (!cfg) return;
// Ensure the job runs at High (the tier the payment buys) even if the click
// came from the in-place lock before any submit.
if (selectedTier !== 'high') selectTier('high');
const result = await payForHighGeneration({ usd });
if (!result?.ok) return; // cancelled or failed — the modal explained why
run({ ...cfg, seed: mintSeed(), payment: { paymentId: result.paymentId, refId: result.refId } });
}
// Wiring ----------------------------------------------------------------------
els.viewer.addEventListener('error', () => {
if (els.viewerShell) {
els.viewerShell.classList.add('has-load-error');
els.viewerShell.classList.remove('is-loading');
}
});
// Retry a failed GLB fetch in place — a transient network blip on the file (the
// common cause) shouldn't dead-end at download-only. Clearing then re-setting src
// on the next frame forces model-viewer to refetch the same URL.
document.getElementById('viewer-retry')?.addEventListener('click', () => {
const src = els.viewer.getAttribute('src');
if (!src) return;
els.viewerShell?.classList.remove('has-load-error');
els.viewerShell?.classList.add('is-loading');
els.viewer.setAttribute('src', '');
requestAnimationFrame(() => els.viewer.setAttribute('src', src));
});
// The GLB finished painting — drop the load skeleton.
els.viewer.addEventListener('load', () => {
els.viewerShell?.classList.remove('is-loading');
});
buildSlots();
buildViewsPips();
updateViewsCounter();
els.modeSwitch.addEventListener('click', (e) => {
const btn = e.target.closest('button[data-mode]');
if (btn) setMode(btn.dataset.mode);
});
// Arrow-key navigation across the tablist (ARIA tabs pattern). Moves focus and
// activates as it goes, wrapping at the ends and skipping the hidden sketch tab
// when its engine isn't deployed.
els.modeSwitch.addEventListener('keydown', (e) => {
if (!['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(e.key)) return;
const tabs = [...els.modeSwitch.querySelectorAll('button[data-mode]')].filter(
(b) => !b.hidden,
);
const i = tabs.indexOf(document.activeElement);
if (i < 0) return;
e.preventDefault();
const next =
e.key === 'Home'
? tabs[0]
: e.key === 'End'
? tabs[tabs.length - 1]
: tabs[(i + (e.key === 'ArrowRight' ? 1 : tabs.length - 1)) % tabs.length];
next.focus();
setMode(next.dataset.mode);
});
els.fileInput.addEventListener('change', () => {
handleFiles(pickerTarget, els.fileInput.files);
pickerTarget = null;
els.fileInput.value = '';
});
els.form.addEventListener('submit', (e) => {
e.preventDefault();
submit();
});
// Enter submits from any prompt box. Shift+Enter inserts a newline, and an
// in-progress IME composition is never hijacked. Cmd/Ctrl+Enter still submits
// too, so the long-standing shortcut keeps working.
function submitOnEnter(e) {
if (e.key !== 'Enter' || e.isComposing || e.shiftKey || e.altKey) return;
e.preventDefault();
submit();
}
els.prompt.addEventListener('keydown', submitOnEnter);
els.imagePrompt.addEventListener('keydown', submitOnEnter);
els.sketchPrompt?.addEventListener('keydown', submitOnEnter);
// Typing into the sketch prompt clears the "required" warning state.
els.sketchPrompt?.addEventListener('input', () => {
els.sketchPrompt.removeAttribute('aria-invalid');
if (els.sketchReqTag) els.sketchReqTag.dataset.missing = 'false';
});
els.sketchFileInput?.addEventListener('change', () => {
const file = els.sketchFileInput.files?.[0];
if (file) uploadSketch(file);
els.sketchFileInput.value = '';
});
els.aspect.addEventListener('click', (e) => {
const btn = e.target.closest('button[data-aspect]');
if (!btn) return;
aspectRatio = btn.dataset.aspect;
for (const b of els.aspect.querySelectorAll('button')) {
b.setAttribute('aria-pressed', String(b === btn));
}
});
// Fill the prompt with an example and generate immediately. Shared by the
// composer's example chips and the empty-stage starter prompts.
function runExamplePrompt(text) {
if (!text) return;
setMode('text');
els.prompt.value = text;
els.prompt.focus();
submit();
}
els.examples.addEventListener('click', (e) => {
const chip = e.target.closest('.chip');
if (chip) runExamplePrompt(chip.textContent.trim());
});
// Starter prompts inside the empty stage: a first-time visitor's one-click
// path from a blank canvas to a real model.
els.emptyStarters?.addEventListener('click', (e) => {
const chip = e.target.closest('.chip');
if (chip) runExamplePrompt(chip.textContent.trim());
});
// Let decoupled result-panel modules (e.g. "More like this") request a fresh
// generation from a derived prompt, reusing the exact example-chip path. Ignore
// while a generation is already in flight, mirroring the Roll & Forge guard.
document.addEventListener('forge:run-prompt', (e) => {
if (els.generate?.dataset.busy === '1') return;
const text = typeof e.detail?.prompt === 'string' ? e.detail.prompt.trim() : '';
if (text) runExamplePrompt(text);
});
// Roll & Forge is the zero-typing path. One click picks a curated random prompt
// (the same slot grammars behind "Surprise me", every one shaped to reconstruct
// cleanly) and generates it immediately, so a first-timer reaches a real model
// without ever facing a blank prompt box. The die spins for feedback (motion-safe).
els.rollForge?.addEventListener('click', () => {
if (els.rollForge.dataset.busy === '1' || els.generate?.dataset.busy === '1') return;
els.rollForge.classList.remove('is-rolling');
void els.rollForge.offsetWidth; // reflow so the spin restarts on rapid clicks
els.rollForge.classList.add('is-rolling');
runExamplePrompt(generateForgePrompt());
});
// Independence Day (July 1–5): a few festive single-object prompts so the
// seasonal moment reaches the Forge too. They carry the `.chip` class, so the
// delegation above generates them one-click; the `.chip--festive` modifier both
// styles them and keeps "More ideas" from shuffling their text away
// (forge-prompt-studio.js excludes it). Self-retires out of season.
injectFestivePresets({
container: els.examples,
chipClass: 'chip',
festiveClass: 'chip--festive',
prompts: [
'a bald eagle statue, wings spread, patriotic pose',
'a rippling American flag on a golden pole',
'a cracked liberty bell, aged bronze, wooden yoke',
'a glossy firework rocket, red white and blue',
],
});
// Quality tier + engine + BYOK key wiring.
els.tier?.addEventListener('click', (e) => {
const btn = e.target.closest('button[data-tier]');
if (btn) selectTier(btn.dataset.tier);
});
els.engine?.addEventListener('click', (e) => {
const btn = e.target.closest('button[data-engine]');
if (btn && !btn.disabled) {
userPickedEngine = true;
selectEngine(btn);
}
});
els.providerKey?.addEventListener('input', () => {
providerKey = els.providerKey.value.trim();
els.providerKey.removeAttribute('aria-invalid');
// Typing/clearing a key on a house-key lane (Tripo) flips whether High is
// $THREE-gated for this request, so re-run the same check a tier/engine
// switch triggers.
if (selectedEngine.houseKeyAvailable && selectedTier === 'high') {
reflectHighAccess('high', { silent: true });
}
});
els.cancel.addEventListener('click', () => {
// Aborting a local run makes generateWithModly call Modly's own cancel
// endpoint, so the GPU stops working too; runModly shows the outcome.
if (modlyRun) {
modlyRun.controller.abort();
return;
}
pollAbort = true;
clearInflight();
stopElapsed();
// The user ended the job: the stage list stops claiming anything is running.
timeline.fail();
setBusy(false);
if (els.categoryPicker) els.categoryPicker.hidden = true;
destinationPicker.hide();
showState('empty');
// Return focus to the composer so the keyboard flow continues where it began.
if (mode === 'text') els.prompt.focus();
else if (mode === 'sketch') els.sketchPrompt?.focus();
else els.imagePrompt?.focus();
});
els.again.addEventListener('click', () => {
stopRateLimitCountdown();
if (els.categoryPicker) els.categoryPicker.hidden = true;
destinationPicker.hide();
showState('empty');
if (mode === 'text') {
els.prompt.focus();
els.prompt.select();
} else if (mode === 'sketch') {
(sketch.state === 'uploaded' ? els.sketchPrompt : sketchSlotEl())?.focus();
} else {
slotEl(0)?.focus();
}
});
els.retry.addEventListener('click', () => {
if (els.retry.disabled) return; // mid-countdown; Retry re-enables at reset
stopRateLimitCountdown();
if (els.categoryPicker) els.categoryPicker.hidden = true;
destinationPicker.hide();
if (lastJob?.modly) {
runModly(lastJob.modelId);
} else if (lastJob && (lastJob.prompt || (lastJob.imageUrls && lastJob.imageUrls.length))) {
run(lastJob);
} else {
showState('empty');
els.prompt.focus();
}
});
// Rate-limit escape hatch: drop straight back to the loaded model and open the
// local Refine panel — no API, no waiting on the throttled generation lane.
els.refineLocally?.addEventListener('click', () => {
stopRateLimitCountdown();
showState('result');
els.stage?.scrollIntoView({ behavior: 'smooth', block: 'start' });
document.dispatchEvent(new CustomEvent('forge:refine-here'));
});
// Refine — re-run the same prompt/views one quality tier higher. Bumping the
// tier syncs the selector (and the tier's default engine), then replays the
// stored job, so the higher-fidelity model lands in the same viewer.
els.refine?.addEventListener('click', async () => {
const next = nextTierAfter(currentResultTier);
if (!next || !lastJob) return;
selectTier(next);
// Refining into platform-keyed High runs the same $THREE pre-flight as selecting
// it: resolve the holder's eligibility first and open the upsell instead of firing
// a job the server would 402. BYOK High is exempt (highTierNeedsPass() is false);
// a transient access failure leaves highLocked false so the request proceeds and
// the server stays the authority.
if (highTierNeedsPass()) {
await reflectHighAccess('high', { silent: true });
if (highLocked) {
if (_highAccess) onGate(_highAccess, gateOpts());
return;
}
}
run(lastJob);
});
// "Generate anyway" — re-run the same job with the vision pre-check bypassed.
els.generateAnyway?.addEventListener('click', () => {
if (!lastJob) return;
run({ ...lastJob, skipValidation: true });
});
if (els.verdict) {
els.verdict.addEventListener('click', (e) => {
const btn = e.target.closest('button[data-outcome]');
if (!btn || !currentCreationId) return;
const outcome = btn.dataset.outcome;
for (const b of els.verdict.querySelectorAll('button')) {
b.setAttribute('aria-pressed', String(b === btn));
}
sendFeedback({ outcome });
});
}
if (els.categoryPicker) {
els.categoryPicker.addEventListener('click', (e) => {
const btn = e.target.closest('.forge-cat-btn[data-cat]');
if (!btn || !currentCreationId) return;
const cat = btn.dataset.cat;
// Toggle: click the active cat again to deselect (back to 'other').
const isActive = btn.classList.contains('active');
els.categoryPicker.querySelectorAll('.forge-cat-btn').forEach((b) => b.classList.remove('active'));
if (!isActive) {
btn.classList.add('active');
sendCategory(cat);
} else {
sendCategory('other');
}
});
}
// Downloads route through a provenance pass: fetch the GLB, stamp
// asset.generator + asset.extras (source, prompt) into the JSON chunk, and
// hand the user the stamped file. Any failure falls back to the raw provider
// file — stamping must never block a download.
els.download.addEventListener('click', async (e) => {
const glbUrl = els.download.href;
if (els.download.dataset.stamping) return;
// Pay-to-keep (off unless the owner enables it): a generation that is not yet
// kept needs a holder or a $THREE payment before the original file is released.
// Only a fresh or reopened durable creation can be gated; a local blob cannot.
if (!glbUrl || glbUrl.startsWith('blob:')) {
sendFeedback({ downloaded: true });
return;
}
e.preventDefault();
els.download.dataset.stamping = '1';
els.download.setAttribute('aria-busy', 'true');
const originalText = els.download.textContent;
els.download.textContent = 'Preparing…';
const filename = els.download.getAttribute('download') || 'forge.glb';
try {
if (currentCreationId) {
const keep = await ensureKept(currentCreationId, { headers: CLIENT_HEADERS });
if (!keep.ok) {
if (els.quote) {
els.quote.textContent = keep.message;
els.quote.hidden = false;
}
return;
}
}
sendFeedback({ downloaded: true });
const res = await fetch(glbUrl);
if (!res.ok) throw new Error(`fetch ${res.status}`);
const stamped = stampGlbAttribution(await res.arrayBuffer(), {
prompt: els.resultLabel?.textContent || '',
engine: ENGINE_LABELS[els.download.dataset.engine] || els.download.dataset.engine || undefined,
engineVersion: els.download.dataset.engineVersion || undefined,
});
const blobUrl = URL.createObjectURL(new Blob([stamped], { type: 'model/gltf-binary' }));
const a = document.createElement('a');
a.href = blobUrl;
a.download = filename;
a.click();
setTimeout(() => URL.revokeObjectURL(blobUrl), 30_000);
} catch {
const a = document.createElement('a');
a.href = glbUrl;
a.download = filename;
a.click();
} finally {
delete els.download.dataset.stamping;
els.download.removeAttribute('aria-busy');
els.download.textContent = originalText;
}
});
els.cinema?.addEventListener('click', () => setCinema(!cinemaOn));
// ── Escape collapses the panel you just opened ───────────────────────────────
// The result column stacks a lot of disclosures (Materials, Optimize, Split
// into parts, Game-Ready, Embed, Stylize, and the art-direction details), each
// owned by its own module with its own open/close logic. None of them listened
// for Escape, so the only way back out of one was to find its trigger again.
//
// Rather than duplicate seven modules' state here, this watches the triggers
// themselves: after a click inside the result panel, whatever now reports
// aria-expanded="true" (or a <details open>) goes on a stack, and Escape pops
// the top and re-clicks it, which runs that module's own close path. A panel
// added later needs no wiring at all, and focus returns to the trigger so a
// keyboard user is not dropped at the top of the document.
const openPanels = [];
function panelTriggerState(el) {
if (!el) return null;
const details = el.closest('details');
if (details && el.closest('summary')) return { el: details, open: !details.open };
const trigger = el.closest('[aria-expanded]');
if (!trigger) return null;
return { el: trigger, open: trigger.getAttribute('aria-expanded') === 'true' };
}
els.states.result.addEventListener('click', (e) => {
// Bubble phase on purpose: the owning module's handler has already run, so
// the attribute read here is the panel's new state, not its old one.
const state = panelTriggerState(e.target);
if (!state) return;
const at = openPanels.indexOf(state.el);
if (at !== -1) openPanels.splice(at, 1);
if (state.open) openPanels.push(state.el);
});
function collapseTopPanel() {
while (openPanels.length) {
const el = openPanels.pop();
// A panel closed by its own UI (or torn down on a new generation) is stale.
const stillOpen =
el.isConnected &&
(el.tagName === 'DETAILS' ? el.open : el.getAttribute('aria-expanded') === 'true');
if (!stillOpen) continue;
if (el.tagName === 'DETAILS') {
el.open = false;
el.querySelector('summary')?.focus();
} else {
el.click();
el.focus();
}
return true;
}
return false;
}
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape') {
if (cinemaOn) {
setCinema(false);
return;
}
// Escape cancels an in-flight generation, same path as the Cancel button.
if (!els.states.generating.classList.contains('is-hidden')) {
els.cancel.click();
return;
}
// Nothing in flight: back out of the last result panel that was opened.
if (collapseTopPanel()) return;
}
if (e.metaKey || e.ctrlKey || e.altKey) return;
const active = document.activeElement;
if (active?.tagName === 'INPUT' || active?.tagName === 'TEXTAREA' || active?.isContentEditable)
return;
// "/" jumps to the prompt for the current mode — the standard quick-focus.
if (e.key === '/') {
e.preventDefault();
const box =
mode === 'sketch' ? els.sketchPrompt : mode === 'image' ? els.imagePrompt : els.prompt;
box?.focus();
return;
}
if (e.key !== 'f' && e.key !== 'F') return;
if (els.states.result.classList.contains('is-hidden')) return;
e.preventDefault();
setCinema(!cinemaOn);
});
if (els.forgeShareBtn) {
els.forgeShareBtn.addEventListener('click', () => {
const origin = location.origin;
const prompt = els.forgeShareBtn.dataset.sharePrompt || lastJob?.prompt || '';
const id = currentCreationId;
const remixUrl = prompt
? `${origin}/forge?prompt=${encodeURIComponent(prompt)}`
: `${origin}/forge`;
// A share is only a real, unfurlable permalink when the creation was
// persisted server-side (has an id). Without one, share the remix link,
// which actually rebuilds the model for whoever opens it, never a bare
// /forge that unfurls to nothing.
const shareUrl = id ? `${origin}/forge/share/${id}` : remixUrl;
showSharePanel(
{
kind: 'forge',
id: id || '',
title: prompt || 'Forged creation',
description: 'A 3D model generated with text / image → 3D on three.ws',
shareUrl,
remixUrl,
// Show the exact OG card the link unfurls as (forge-og 302s to the
// real preview image, or renders an SVG card). Only meaningful with a
// permalink; the remix-link fallback has no per-creation card.
previewImage: id ? `${origin}/api/forge-og?id=${id}` : undefined,
},
els.forgeShareBtn,
);
});
}
// Handle ?prompt= (pre-fill from a remix link) and ?share= (open a creation).
(function handleQueryParams() {
const params = new URLSearchParams(location.search);
const promptParam = params.get('prompt');
const shareParam = params.get('share');
if (promptParam && els.prompt) {
setMode('text');
// Match the textarea's own maxlength (1000) — a remix link must not silently
// drop the tail of a long prompt the user is trying to carry over.
els.prompt.value = decodeURIComponent(promptParam).slice(0, 1000);
els.prompt.focus();
els.prompt.dispatchEvent(new Event('input', { bubbles: true }));
}
if (shareParam) {
window.__forgeShareId = shareParam;
}
})();
// Deep links: the /image-to-3d route alias and ?mode=image both land straight
// on the photo tab, making "image to 3D" a first-class destination instead of
// a second tab hidden behind a text-first title. The alias also gets its own
// document title so history/tabs read as what the user searched for.
// A route alias owns the tab title: the <title> tag carries data-i18n, so the
// locale loader would retranslate it back to the Forge default after load
// unless the attribute comes off first.
function claimDocumentTitle(title) {
document.querySelector('title')?.removeAttribute('data-i18n');
document.title = title;
}
(() => {
const path = location.pathname.replace(/\/+$/, '');
const wanted = new URLSearchParams(location.search).get('mode') || (path === '/image-to-3d' ? 'image' : '');
if (wanted === 'image') setMode('image');
if (path === '/image-to-3d') claimDocumentTitle('Image to 3D — Turn a Photo into a 3D Model · three.ws');
})();
// Quality deep links: /forge-max is the designated maximum-quality lane. It
// lands on the Forge with the High tier pinned (200k-poly target, 4K PBR + HD
// textures, subject-aware engine routing), so "the best the platform can
// produce" has a stable URL instead of living behind a selector. ?tier=draft|
// standard|high presets the selector on any forge URL the same way. selectTier
// validates its input, so an unknown ?tier= value is a no-op; the High-tier
// $THREE gate still applies exactly as if the user clicked the button.
(() => {
const path = location.pathname.replace(/\/+$/, '');
const isMax = path === '/forge-max';
const tierParam = (new URLSearchParams(location.search).get('tier') || '').toLowerCase();
const wanted = tierParam || (isMax ? 'high' : '');
if (wanted) selectTier(wanted);
if (!isMax) return;
claimDocumentTitle('Forge Max: Highest-Quality Text & Image to 3D · three.ws');
// Re-brand the header for the dedicated destination. Dropping the i18n
// attributes keeps the locale loader from clobbering the swapped copy.
const h1 = document.querySelector('.forge-head h1');
const tag = document.querySelector('.forge-head p');
if (h1) {
h1.removeAttribute('data-i18n');
h1.textContent = 'Forge Max';
}
if (tag) {
tag.removeAttribute('data-i18n-html');
tag.textContent =
'The highest-quality lane: 200k-poly geometry, 4K PBR textures, subject-aware engine routing. A $THREE holder perk.';
}
})();
// Hooks for the companion modules (forge-dropzone.js, forge-showcase.js) —
// a CustomEvent contract keeps them decoupled from this file's internals.
// Images captured anywhere on the page (clipboard paste, page-level drop).
// In sketch mode a single image becomes the sketch; otherwise we switch to
// photo mode and distribute into free view slots.
document.addEventListener('forge:add-images', (e) => {
const files = Array.isArray(e.detail?.files) ? e.detail.files : [];
if (!files.length) return;
if (mode === 'sketch' && files.length === 1) {
uploadSketch(files[0]);
return;
}
if (mode !== 'image') setMode('image');
handleFiles(null, files);
});
// A community-showcase card asks to open its creation in the main viewer, so
// the full result bar (download, share, stylize, optimize, split) works on it.
document.addEventListener('forge:open-creation', (e) => {
const creation = e.detail?.creation;
if (creation?.glb_url) openCreation(creation);
});
// Build the quality/engine controls from the live catalog (tiers, backends,
// cost/time matrix). Falls back silently to the defaults if it can't load.
loadCatalog();
// Surface the $THREE holder gate on the High control up front (pill + note),
// independent of the catalog so the affordance lands even on older deploys.
reflectHighButtonAccess();
// Forge-local wallet connect (Part A): wire the connect chip + auto-connect a trusted
// wallet so a connected holder's High unlock + free-quota perk surface with no reload.
// Re-read the gate + perk line whenever the wallet connects or disconnects.
initWalletButton();
updatePerkLine();
window.addEventListener('wallet:changed', () => {
reflectHighButtonAccess();
if (selectedTier === 'high') reflectHighAccess('high');
updatePerkLine();
});
// Surface any previously forged models for this browser on load, then pick an
// interrupted generation back up. A share link wins over a resume: the visitor
// explicitly asked to see that creation, and the resumed job stays pollable in
// storage for the next plain visit.
loadGallery().then(() => {
const shareId = window.__forgeShareId;
if (shareId) {
openSharedCreation(shareId);
return;
}
resumeInflight();
});