Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(home): home forge module, discovery wiring, and changelog sync
nirholas3a37853d39d8
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 845f8f62f..9c3cdb252 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Agent Launches** (`/launches`) — Live public feed of every coin launched by a three.ws agent — market caps, graduation status, and the agent behind each launch.- **Cosmetics shop purchases now work** — Buying a premium skin or emote in the /play Cosmetics shop actually opens the payment flow now. Previously the Buy buttons failed because the in-world shop never loaded the payment widget — now it loads on demand the moment you tap Buy, the USDC checkout opens with the item priced by rarity, and a sale made inside a coin's world still credits that coin's creator. Pay once on Base or Solana and the item is yours forever. (`/play`) `[fix]`+- **Forge a 3D model right on the homepage** — The homepage now has a live slice of Forge. Type a description of an object — or tap an example — and the real generation pipeline paints a reference image, reconstructs a textured mesh, and drops an interactive 3D model into the page that you can orbit and download as GLB. Anything you forge there also shows up in the full Forge gallery on the same device. (`/forge`) `[feature]`- **New /launches page: every agent-launched coin in one live feed** — There is now a public feed of every coin launched by a three.ws agent at /launches — live market caps, graduation badges, buyback rates, and a card linking straight to the agent behind each launch. Agent profile pages also gained a launch history: every coin an agent has ever launched is listed on its page with a live market cap and a link into the public feed. Find it in the nav under Discover → Agent Launches. (`/launches`) `[feature]`- **Pay a real x402 oracle inside the $THREE town** — The $THREE town in /play now has an Intel Kiosk by the plaza: walk up, press E, and buy live $THREE market intel — price, 24 h change, market cap, and a bullish/bearish/neutral signal — for $0.01 USDC paid from your own wallet over x402, settled on-chain on Solana. The oracle behind it (/api/x402/three-intel) is also listed in the bazaar, so any agent can buy the same feed. The Agent Wallet demo is now linked from the /play menu too. (`/play`) `[feature]`- **Reliability sweep: faster galleries, working voices, sturdier pages** — A pass over every error in the production logs. Avatar thumbnails and 3D models now load through three.ws itself instead of a rate-limited storage domain, so gallery pages stop dropping images under load. Text-to-speech voices are back (the upstream voice service had changed its protocol). Leaving a world on /play no longer hits a crash that could leave the session connected in the background. The homepage 3D demos politely step aside on devices without WebGL instead of breaking, payment demo requests get more time to settle on-chain, and the $THREE market stats failover stops hammering an exhausted data provider. `[fix, improvement, infra]`diff --git a/data/changelog.json b/data/changelog.jsonindex 44cdc10ce..c47eab04e 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1079,6 +1079,15 @@"security","infra"]+ },+ {+ "date": "2026-06-12",+ "title": "Forge a 3D model right on the homepage",+ "summary": "The homepage now has a live slice of Forge. Type a description of an object — or tap an example — and the real generation pipeline paints a reference image, reconstructs a textured mesh, and drops an interactive 3D model into the page that you can orbit and download as GLB. Anything you forge there also shows up in the full Forge gallery on the same device.",+ "tags": [+ "feature"+ ],+ "link": "/forge"}]}diff --git a/pages/home.html b/pages/home.htmlindex b392054ce..41a329096 100644--- a/pages/home.html+++ b/pages/home.html@@ -2940,6 +2940,158 @@</div></section>+<!-- ── FORGE — LITE DEMO ─────────────────────────────────────────── -->+<style>+ #home-forge .hf-wrap { display: grid; grid-template-columns: 1.35fr 0.9fr; gap: 28px; align-items: stretch; }+ #home-forge .hf-stage-card {+ position: relative; border: 1px solid var(--hairline); border-radius: 16px; overflow: hidden;+ background: radial-gradient(120% 100% at 50% 0%, #121214 0%, #09090a 70%); min-height: 460px;+ }+ #home-forge .hf-stage-hud {+ position: absolute; left: 16px; top: 16px; display: flex; gap: 8px; align-items: center;+ font-family: var(--font-mono); font-size: 11px; letter-spacing: 0.08em; text-transform: uppercase;+ color: var(--text-3); pointer-events: none; z-index: 3;+ }+ #home-forge .hf-stage-hud .dot { width: 6px; height: 6px; border-radius: 50%; background: #ffb454; box-shadow: 0 0 8px #ffb454; }+ #home-forge .hf-state { position: absolute; inset: 0; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 10px; text-align: center; padding: 28px; }+ #home-forge .hf-state[hidden] { display: none; }+ #home-forge .hf-glyph { font-size: 38px; opacity: 0.5; line-height: 1; }+ #home-forge .hf-state h3 { font-family: var(--font-display); font-size: 19px; font-weight: 600; letter-spacing: -0.01em; color: var(--text); margin: 0; }+ #home-forge .hf-state p { font-size: 13.5px; color: var(--text-3); line-height: 1.55; margin: 0; max-width: 42ch; }+ #home-forge .hf-state--error h3 { color: #ff7a7a; }+ #home-forge .hf-preview {+ position: relative; width: min(46%, 240px); aspect-ratio: 1 / 1; border-radius: 12px;+ border: 1px solid var(--hairline); background: #0e0e10; overflow: hidden; flex: none;+ }+ #home-forge .hf-preview img { width: 100%; height: 100%; object-fit: cover; display: block; }+ #home-forge .hf-shimmer {+ position: absolute; inset: 0;+ background: linear-gradient(100deg, transparent 20%, rgba(255,255,255,0.06) 50%, transparent 80%);+ background-size: 200% 100%; animation: hf-shimmer 1.4s linear infinite;+ }+ @keyframes hf-shimmer { to { background-position: -200% 0; } }+ #home-forge .hf-steps { display: flex; flex-direction: column; gap: 9px; align-items: flex-start; }+ #home-forge .hf-step { display: flex; align-items: center; gap: 9px; font-size: 13px; color: var(--text-3); }+ #home-forge .hf-step .dot { width: 12px; height: 12px; border-radius: 50%; border: 2px solid var(--hairline-strong); flex: none; }+ #home-forge .hf-step[data-state='active'] { color: var(--text); }+ #home-forge .hf-step[data-state='active'] .dot { border-color: #ffb454; border-top-color: transparent; animation: hf-spin 0.8s linear infinite; }+ #home-forge .hf-step[data-state='done'] { color: var(--text); }+ #home-forge .hf-step[data-state='done'] .dot { background: #58d68d; border-color: #58d68d; }+ @keyframes hf-spin { to { transform: rotate(360deg); } }+ #home-forge .hf-elapsed { font-family: var(--font-mono); font-size: 11.5px; color: var(--text-3); }+ #home-forge .hf-result-stage { position: absolute; inset: 0; display: flex; flex-direction: column; }+ #home-forge .hf-result-stage[hidden] { display: none; }+ #home-forge [data-hf-viewer-slot] { flex: 1; min-height: 0; }+ #home-forge [data-hf-viewer-slot] model-viewer { width: 100%; height: 100%; --poster-color: transparent; background: transparent; }+ #home-forge .hf-result-bar {+ display: flex; align-items: center; justify-content: space-between; gap: 10px; flex-wrap: wrap;+ padding: 12px 16px; border-top: 1px solid var(--hairline); background: rgba(10,10,12,0.7); backdrop-filter: blur(8px);+ }+ #home-forge .hf-result-meta { font-size: 12.5px; color: var(--text-3); min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; flex: 1 1 120px; }+ #home-forge .hf-result-actions { display: flex; gap: 8px; flex: none; }+ #home-forge .hf-panel { display: flex; flex-direction: column; gap: 18px; }+ #home-forge .hf-panel-card { border: 1px solid var(--hairline); border-radius: 16px; background: var(--surface-1); padding: 22px; display: flex; flex-direction: column; gap: 14px; }+ #home-forge .hf-panel-label { font-family: var(--font-mono); font-size: 11px; letter-spacing: 0.16em; text-transform: uppercase; color: var(--text-3); margin: 0; }+ #home-forge .hf-prompt {+ width: 100%; min-height: 72px; resize: vertical; background: rgba(0,0,0,0.25);+ border: 1px solid var(--hairline); border-radius: 10px; outline: none; color: var(--text);+ font-family: inherit; font-size: 14.5px; line-height: 1.5; padding: 11px 13px;+ transition: border-color .16s, box-shadow .16s;+ }+ #home-forge .hf-prompt::placeholder { color: var(--text-3); }+ #home-forge .hf-prompt:focus-visible { border-color: #ffb454; box-shadow: 0 0 0 3px rgba(255,180,84,0.18); }+ #home-forge .hf-chips { display: flex; flex-wrap: wrap; gap: 8px; }+ #home-forge .hf-chip {+ font-size: 12.5px; color: var(--text-2); background: transparent; border: 1px solid var(--hairline);+ border-radius: 999px; padding: 6px 12px; cursor: pointer; transition: border-color .16s, color .16s, transform .16s;+ }+ #home-forge .hf-chip:hover { color: var(--text); border-color: var(--hairline-strong); transform: translateY(-1px); }+ #home-forge .hf-chip:focus-visible { outline: 2px solid #ffb454; outline-offset: 2px; }+ #home-forge .hf-note { font-size: 12px; color: var(--text-3); line-height: 1.5; margin: 0; }+ #home-forge .hf-btn {+ text-align: center; font-family: var(--font-mono); font-size: 12.5px; padding: 11px 14px;+ border-radius: 10px; border: 1px solid var(--hairline); background: transparent; color: var(--text-2);+ cursor: pointer; text-decoration: none; transition: border-color .16s, color .16s, background .16s;+ }+ #home-forge .hf-btn:hover { color: var(--text); border-color: var(--hairline-strong); }+ #home-forge .hf-btn:focus-visible { outline: 2px solid #ffb454; outline-offset: 2px; }+ #home-forge .hf-btn[disabled] { opacity: 0.45; cursor: not-allowed; }+ #home-forge .hf-btn-primary { display: block; background: var(--text); color: #09090a; border-color: var(--text); font-weight: 600; }+ #home-forge .hf-btn-primary:hover { color: #09090a; background: #e2e2e2; }+ #home-forge .hf-btn-sm { padding: 7px 12px; font-size: 12px; border-radius: 8px; }+ #home-forge .sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0,0,0,0); white-space: nowrap; border: 0; }+ @media (max-width: 880px) {+ #home-forge .hf-wrap { grid-template-columns: 1fr; }+ #home-forge .hf-stage-card { min-height: 400px; }+ }+</style>+<section class="block" id="home-forge">+ <div class="wrap-1280">+ <div class="block-head reveal">+ <p class="block-eyebrow"><span class="num">•</span>Forge</p>+ <h2 class="block-h">Type it. <em>Hold it in 3D.</em></h2>+ <p class="block-lede">+ A live slice of <a href="/forge">Forge</a> — the same FLUX → TRELLIS pipeline that powers the full page. Describe an object and watch a textured, downloadable GLB take shape, right here. The full Forge adds photo input, multi-view fusion, stylize filters, and retopology.+ </p>+ </div>+ <div class="hf-wrap reveal reveal-d1">+ <div class="hf-stage-card" data-hf-stage>+ <div class="hf-stage-hud"><span class="dot"></span>Live pipeline</div>++ <div class="hf-state" data-hf-idle>+ <span class="hf-glyph" aria-hidden="true">◓</span>+ <h3>Nothing forged yet</h3>+ <p>Type a description — or tap an example — and a real textured mesh lands here in 30–90 seconds.</p>+ </div>++ <div class="hf-state" data-hf-generating hidden>+ <div class="hf-preview" data-hf-preview></div>+ <div class="hf-steps" aria-live="polite">+ <div class="hf-step" data-hf-step="image" data-state="pending"><span class="dot" aria-hidden="true"></span><span>Painting reference image</span></div>+ <div class="hf-step" data-hf-step="mesh" data-state="pending"><span class="dot" aria-hidden="true"></span><span>Reconstructing textured mesh</span></div>+ </div>+ <span class="hf-elapsed" data-hf-elapsed>Elapsed 0s</span>+ <button type="button" class="hf-btn hf-btn-sm" data-hf-cancel>Cancel</button>+ </div>++ <div class="hf-result-stage" data-hf-result hidden>+ <div data-hf-viewer-slot></div>+ <div class="hf-result-bar">+ <span class="hf-result-meta" data-hf-result-meta></span>+ <div class="hf-result-actions">+ <a class="hf-btn hf-btn-sm" data-hf-download download>Download GLB</a>+ <button type="button" class="hf-btn hf-btn-sm" data-hf-again>Make another</button>+ </div>+ </div>+ </div>++ <div class="hf-state hf-state--error" data-hf-error hidden>+ <span class="hf-glyph" aria-hidden="true">⚠</span>+ <h3>Generation failed</h3>+ <p data-hf-error-message>Something went wrong. Try a simpler, single-subject prompt.</p>+ <button type="button" class="hf-btn hf-btn-sm" data-hf-retry>Try again</button>+ </div>+ </div>+ <div class="hf-panel">+ <form class="hf-panel-card" data-hf-form autocomplete="off">+ <p class="hf-panel-label">Describe an object</p>+ <label class="sr-only" for="hf-prompt-input">Describe the object to generate</label>+ <textarea id="hf-prompt-input" class="hf-prompt" data-hf-prompt maxlength="1000" placeholder="a glazed ceramic teapot, studio lighting"></textarea>+ <div class="hf-chips" data-hf-chips role="group" aria-label="Example prompts">+ <button type="button" class="hf-chip" data-prompt="a low-poly red fox, sitting">low-poly fox</button>+ <button type="button" class="hf-chip" data-prompt="a sci-fi combat helmet, brushed metal">sci-fi helmet</button>+ <button type="button" class="hf-chip" data-prompt="a potted monstera plant">monstera plant</button>+ <button type="button" class="hf-chip" data-prompt="a vintage film camera">film camera</button>+ </div>+ <button class="hf-btn hf-btn-primary" data-hf-generate type="submit"><span data-hf-generate-label>Forge it</span></button>+ <p class="hf-note">Free to try · no sign-up · your forged models also appear in the full Forge gallery on this device.</p>+ </form>+ <a class="hf-btn hf-btn-primary" href="/forge">Open the full Forge →</a>+ </div>+ </div>+ </div>+</section>+<!-- ── FEATURE BENTO ─────────────────────────────────────────────── --><section class="block"><div class="wrap-1280">@@ -5048,6 +5200,19 @@}, { rootMargin: '200px' });io.observe(poseRoot);}++ // Mini Forge — same deal: the module (and, once a job runs, model-viewer)+ // stays off the critical path until the section approaches the viewport.+ const forgeRoot = document.getElementById('home-forge');+ if (forgeRoot) {+ const io = new IntersectionObserver(entries => {+ if (entries[0].isIntersecting) {+ io.disconnect();+ import('/src/home-forge.js');+ }+ }, { rootMargin: '200px' });+ io.observe(forgeRoot);+ }</script><script type="module" src="/dragon-section.js"></script><script>diff --git a/public/changelog.json b/public/changelog.jsonindex 31ad212e6..12b376fb9 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-12T01:44:15.440Z",+ "generated_at": "2026-06-12T01:46:38.351Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -26,6 +26,16 @@"fix"]},+ {+ "date": "2026-06-12",+ "type": "update",+ "title": "Forge a 3D model right on the homepage",+ "summary": "The homepage now has a live slice of Forge. Type a description of an object — or tap an example — and the real generation pipeline paints a reference image, reconstructs a textured mesh, and drops an interactive 3D model into the page that you can orbit and download as GLB. Anything you forge there also shows up in the full Forge gallery on the same device.",+ "link": "/forge",+ "tags": [+ "feature"+ ]+ },{"date": "2026-06-12","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex 791794086..f726f29a1 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -22,6 +22,14 @@<category>fix</category><description>Buying a premium skin or emote in the /play Cosmetics shop actually opens the payment flow now. Previously the Buy buttons failed because the in-world shop never loaded the payment widget — now it loads on demand the moment you tap Buy, the USDC checkout opens with the item priced by rarity, and a sale made inside a coin's world still credits that coin's creator. Pay once on Base or Solana and the item is yours forever.</description></item>+ <item>+ <title>Forge a 3D model right on the homepage</title>+ <link>https://three.ws/forge</link>+ <guid isPermaLink="false">2026-06-12:Forge a 3D model right on the homepage</guid>+ <pubDate>Fri, 12 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>The homepage now has a live slice of Forge. Type a description of an object — or tap an example — and the real generation pipeline paints a reference image, reconstructs a textured mesh, and drops an interactive 3D model into the page that you can orbit and download as GLB. Anything you forge there also shows up in the full Forge gallery on the same device.</description>+ </item><item><title>New /launches page: every agent-launched coin in one live feed</title><link>https://three.ws/launches</link>diff --git a/public/feature-discovery.js b/public/feature-discovery.jsindex 51836ab04..cc8b53ceb 100644--- a/public/feature-discovery.js+++ b/public/feature-discovery.js@@ -166,7 +166,26 @@}// ── "New" badges on in-page links to new features ──────────────────────────+ // Not every page loads style.css (home, create, launches… carry their own+ // inline design systems), so the badge ships its own fallback rule. It is+ // PREPENDED to <head> so any page stylesheet still wins the cascade.+ function ensureBadgeStyle() {+ if (document.getElementById('tws-disc-new-css')) return;+ var s = document.createElement('style');+ s.id = 'tws-disc-new-css';+ s.textContent =+ '.tws-disc-new{display:inline-block;margin-left:6px;padding:1px 6px;' ++ 'font-size:10px;font-weight:600;line-height:1.5;letter-spacing:0.02em;' ++ 'text-transform:uppercase;vertical-align:middle;' ++ 'color:var(--ink,var(--text,#e8e8e8));' ++ 'background:var(--surface-3,rgba(255,255,255,0.08));' ++ 'border:1px solid var(--stroke-strong,rgba(255,255,255,0.14));' ++ 'border-radius:var(--radius-pill,999px);}';+ document.head.insertBefore(s, document.head.firstChild);+ }+function decorateNewBadges(newSet) {+ ensureBadgeStyle();var visited = visitedSet();var anchors = document.querySelectorAll('a[href]');for (var i = 0; i < anchors.length; i++) {diff --git a/public/features.json b/public/features.jsonindex 6481f7719..4aa7136c4 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-12T01:11:40.390Z",+ "generated_at": "2026-06-12T01:46:38.342Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/scripts/home-forge-probe.mjs b/scripts/home-forge-probe.mjsnew file mode 100644index 000000000..2bfcdb506--- /dev/null+++ b/scripts/home-forge-probe.mjs@@ -0,0 +1,54 @@+// One-off browser probe for the homepage mini Forge section.+// Usage: node scripts/home-forge-probe.mjs [--generate]+// --generate runs a real text→3D job against the proxied production API.+import { chromium } from 'playwright';++const BASE = process.env.BASE_URL || 'http://localhost:3171';+const doGenerate = process.argv.includes('--generate');++const browser = await chromium.launch();+const page = await browser.newPage({ viewport: { width: 1440, height: 960 } });++const consoleErrors = [];+page.on('console', (msg) => {+ if (msg.type() === 'error') consoleErrors.push(msg.text());+});+page.on('pageerror', (err) => consoleErrors.push(`pageerror: ${err.message}`));++await page.goto(`${BASE}/`, { waitUntil: 'domcontentloaded' });+await page.locator('#home-forge').scrollIntoViewIfNeeded();+await page.waitForTimeout(1500); // let the lazy module import + boot++const section = page.locator('#home-forge');+console.log('section visible:', await section.isVisible());+console.log('idle state visible:', await section.locator('[data-hf-idle]').isVisible());+console.log('chips:', await section.locator('.hf-chip').count());+console.log('full-forge CTA href:', await section.locator('a[href="/forge"]').first().getAttribute('href'));++await page.screenshot({ path: 'reports/home-forge-idle.png', clip: (await section.boundingBox()) || undefined });++if (doGenerate) {+ await section.locator('[data-hf-prompt]').fill('a glazed ceramic teapot, studio lighting');+ await section.locator('[data-hf-generate]').click();+ console.log('generating state visible:', await section.locator('[data-hf-generating]').isVisible());+ await page.screenshot({ path: 'reports/home-forge-generating.png', clip: (await section.boundingBox()) || undefined });++ // Wait up to 4 minutes for a result or error.+ const outcome = await Promise.race([+ section.locator('[data-hf-result]:not([hidden])').waitFor({ timeout: 240000 }).then(() => 'result'),+ section.locator('[data-hf-error]:not([hidden])').waitFor({ timeout: 240000 }).then(() => 'error'),+ ]).catch(() => 'timeout');+ console.log('outcome:', outcome);+ if (outcome === 'result') {+ await page.waitForTimeout(4000); // let model-viewer render the GLB+ console.log('download href:', await section.locator('[data-hf-download]').getAttribute('href'));+ console.log('meta:', await section.locator('[data-hf-result-meta]').textContent());+ }+ if (outcome === 'error') {+ console.log('error message:', await section.locator('[data-hf-error-message]').textContent());+ }+ await page.screenshot({ path: 'reports/home-forge-final.png', clip: (await section.boundingBox()) || undefined });+}++console.log('console errors:', JSON.stringify(consoleErrors.filter((e) => !/ajax\.googleapis|_vercel/.test(e)), null, 1));+await browser.close();diff --git a/src/home-forge.js b/src/home-forge.jsnew file mode 100644index 000000000..5754c84ec--- /dev/null+++ b/src/home-forge.js@@ -0,0 +1,280 @@+// Mini Forge — homepage slice of /forge (text → 3D, real pipeline).+//+// Drives the same /api/forge endpoint as the full page: POST a prompt, FLUX+// paints a reference image, TRELLIS reconstructs a textured GLB, and the+// result renders in a <model-viewer> right in the section. Omitting+// path/tier/backend lets the server pick its standard lane, so this stays+// correct if the catalog defaults change. The only timer is the honest+// elapsed counter — progress states come from real API responses.+//+// Creations are scoped to the same x-forge-client id as /forge (shared+// localStorage key), so anything forged here appears in the full page's+// "Your creations" gallery.++const POLL_INTERVAL_MS = 2500;+const MAX_POLL_MS = 5 * 60 * 1000;+const MODEL_VIEWER_SRC =+ 'https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js';++const root = document.getElementById('home-forge');++const els = root && {+ form: root.querySelector('[data-hf-form]'),+ prompt: root.querySelector('[data-hf-prompt]'),+ generate: root.querySelector('[data-hf-generate]'),+ generateLabel: root.querySelector('[data-hf-generate-label]'),+ chips: root.querySelector('[data-hf-chips]'),+ stage: root.querySelector('[data-hf-stage]'),+ states: {+ idle: root.querySelector('[data-hf-idle]'),+ generating: root.querySelector('[data-hf-generating]'),+ result: root.querySelector('[data-hf-result]'),+ error: root.querySelector('[data-hf-error]'),+ },+ preview: root.querySelector('[data-hf-preview]'),+ steps: {+ image: root.querySelector('[data-hf-step="image"]'),+ mesh: root.querySelector('[data-hf-step="mesh"]'),+ },+ elapsed: root.querySelector('[data-hf-elapsed]'),+ cancel: root.querySelector('[data-hf-cancel]'),+ resultMeta: root.querySelector('[data-hf-result-meta]'),+ download: root.querySelector('[data-hf-download]'),+ again: root.querySelector('[data-hf-again]'),+ errorMessage: root.querySelector('[data-hf-error-message]'),+ retry: root.querySelector('[data-hf-retry]'),+};++// Same anonymous handle as src/forge.js — keep the storage key in sync so the+// full page's gallery picks up models forged here.+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 {+ return `c-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;+ }+})();++const CLIENT_HEADERS = { 'x-forge-client': CLIENT_ID };++let busy = false;+let pollAbort = false;+let elapsedTimer = null;+let lastPrompt = '';+let modelViewerReady = null;+// Monotonic run token: cancel-then-regenerate must not let the first run's+// poll loop wake up and fight the new one over the shared stage.+let runSeq = 0;++const sleep = (ms) => new Promise((r) => setTimeout(r, ms));++// model-viewer carries its own renderer (~700 KB) — fetch it only once a+// generation is actually running, so it's registered by the time the GLB lands.+function ensureModelViewer() {+ if (modelViewerReady) return modelViewerReady;+ modelViewerReady = customElements.get('model-viewer')+ ? Promise.resolve()+ : new Promise((resolve, reject) => {+ const s = document.createElement('script');+ s.type = 'module';+ s.src = MODEL_VIEWER_SRC;+ s.crossOrigin = 'anonymous';+ s.onload = () => resolve();+ s.onerror = () => reject(new Error('Failed to load the 3D viewer.'));+ document.head.appendChild(s);+ });+ return modelViewerReady;+}++function showState(name) {+ for (const [key, node] of Object.entries(els.states)) {+ node.hidden = key !== name;+ }+}++function setStep(name, state) {+ els.steps[name].dataset.state = state;+}++function startElapsed() {+ const t0 = performance.now();+ stopElapsed();+ els.elapsed.textContent = 'Elapsed 0s';+ elapsedTimer = setInterval(() => {+ els.elapsed.textContent = `Elapsed ${Math.round((performance.now() - t0) / 1000)}s`;+ }, 1000);+}++function stopElapsed() {+ if (elapsedTimer) clearInterval(elapsedTimer);+ elapsedTimer = null;+}++function setBusy(b) {+ busy = b;+ els.generate.disabled = b;+ els.generateLabel.textContent = b ? 'Forging…' : 'Forge it';+}++function showError(message) {+ stopElapsed();+ els.errorMessage.textContent = message;+ showState('error');+}++async function startJob(prompt) {+ const res = await fetch('/api/forge', {+ method: 'POST',+ headers: { 'content-type': 'application/json', ...CLIENT_HEADERS },+ body: JSON.stringify({ prompt, aspect_ratio: '1:1' }),+ });+ const data = await res.json().catch(() => ({}));+ if (res.status === 503 || data.error === 'unconfigured') {+ throw new Error('The generator is offline right now — try again in a bit.');+ }+ if (res.status === 429 || data.error === 'rate_limited') {+ const secs = Number(data.retry_after) > 0 ? Math.ceil(Number(data.retry_after)) : 10;+ throw new Error(data.message || `The forge is busy. Try again in about ${secs} seconds.`);+ }+ if (!res.ok) throw new Error(data.message || `The generator returned ${res.status}.`);+ return data;+}++async function pollUntilDone(jobId, seq) {+ const deadline = performance.now() + MAX_POLL_MS;+ while (!pollAbort && seq === runSeq && performance.now() < deadline) {+ await sleep(POLL_INTERVAL_MS);+ if (pollAbort || seq !== runSeq) return null;+ const res = await fetch(`/api/forge?job=${encodeURIComponent(jobId)}`, {+ headers: CLIENT_HEADERS,+ });+ const data = await res.json().catch(() => ({}));+ if (data.status === 'done' && data.glb_url) return data;+ if (data.status === 'failed') throw new Error(data.error || 'Generation failed.');+ if (data.status === 'running') setStep('mesh', 'active');+ }+ if (pollAbort || seq !== runSeq) return null;+ throw new Error('Generation timed out — try a simpler, single-subject prompt.');+}++function showResult(glbUrl, prompt) {+ stopElapsed();+ const viewer = document.createElement('model-viewer');+ viewer.setAttribute('src', glbUrl);+ viewer.setAttribute('alt', `3D model: ${prompt}`);+ viewer.setAttribute('camera-controls', '');+ viewer.setAttribute('auto-rotate', '');+ viewer.setAttribute('auto-rotate-delay', '0');+ viewer.setAttribute('rotation-per-second', '18deg');+ viewer.setAttribute('shadow-intensity', '1');+ viewer.setAttribute('interaction-prompt', 'none');+ const slot = els.states.result.querySelector('[data-hf-viewer-slot]');+ slot.innerHTML = '';+ slot.appendChild(viewer);+ els.resultMeta.textContent = prompt;+ els.download.href = glbUrl;+ els.download.setAttribute(+ 'download',+ `${prompt.replace(/[^a-z0-9]+/gi, '-').slice(0, 48).replace(/^-|-$/g, '') || 'forge'}.glb`,+ );+ showState('result');+ // Same signal the full page emits — the discovery layer turns it into a+ // "what's next?" card (embed it, drop it in a world, …).+ document.dispatchEvent(new CustomEvent('tws:feature-done', { detail: { feature: 'forge' } }));+}++async function run(prompt) {+ if (busy) return;+ lastPrompt = prompt;+ pollAbort = false;+ const seq = ++runSeq;+ setBusy(true);+ setStep('image', 'active');+ setStep('mesh', 'pending');+ els.preview.innerHTML = '<div class="hf-shimmer" aria-hidden="true"></div>';+ startElapsed();+ showState('generating');+ // Fetch the viewer in parallel with the job — a failure surfaces only if a+ // model actually arrives.+ const viewerLoad = ensureModelViewer().catch((err) => err);++ try {+ const job = await startJob(prompt);+ if (seq !== runSeq) return; // cancelled while the POST was in flight++ if (job.preview_image_url) {+ setStep('image', 'done');+ setStep('mesh', 'active');+ const img = new Image();+ img.alt = 'Reference image';+ img.src = job.preview_image_url;+ img.onload = () => {+ els.preview.innerHTML = '';+ els.preview.appendChild(img);+ };+ }++ const done = await pollUntilDone(job.job_id, seq);+ if (pollAbort || seq !== runSeq || !done) return; // cancelled+ setStep('mesh', 'done');++ const viewerErr = await viewerLoad;+ if (viewerErr instanceof Error) throw viewerErr;+ showResult(done.glb_url, prompt);+ } catch (err) {+ if (!pollAbort && seq === runSeq) {+ showError(err.message || 'Something went wrong. Try a simpler prompt.');+ }+ } finally {+ if (seq === runSeq) setBusy(false);+ }+}++function reset() {+ pollAbort = true;+ stopElapsed();+ setBusy(false);+ showState('idle');+ els.prompt.focus();+}++function boot() {+ els.form.addEventListener('submit', (e) => {+ e.preventDefault();+ const prompt = els.prompt.value.trim();+ if (prompt) run(prompt);+ else els.prompt.focus();+ });++ // Cmd/Ctrl+Enter submits — same convention as the full page.+ els.prompt.addEventListener('keydown', (e) => {+ if ((e.metaKey || e.ctrlKey) && e.key === 'Enter') {+ e.preventDefault();+ els.form.requestSubmit();+ }+ });++ els.chips.addEventListener('click', (e) => {+ const chip = e.target.closest('button[data-prompt]');+ if (!chip || busy) return;+ els.prompt.value = chip.dataset.prompt;+ run(chip.dataset.prompt);+ });++ els.cancel.addEventListener('click', reset);+ els.again.addEventListener('click', reset);+ els.retry.addEventListener('click', () => {+ if (lastPrompt) run(lastPrompt);+ else reset();+ });+}++if (root && els.form) boot();