Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(forge): compare two generations of one prompt side by side
nirholasca0a3449d535
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex cb38fc45f..a78767c8e 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -39,6 +39,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Tutorial · Ship an avatar manifest** (`/tutorials/ship-an-avatar-manifest`) — Turn a raw GLB into a signed-off, hash-anchored manifest: one document that names the avatar, records the exact bytes of its mesh, declares its skeleton, and fails your build if the model ever silently changes.- **Tutorial · Write a repository guard** (`/tutorials/write-a-guard`) — This repo has no CI, so a guard is the only thing between a mistake and production. Build one that fails the build when an API handler forgets its error boundary, wire it into the gate, cover it with tests, and register it.- **Tutorial · Write a repository guard** (`/docs/tutorials/write-a-guard`) — Build a real guard end to end: write the checker, give it an npm script, register it in data/guards.json, wire it into a stage, and cover it with a test that includes the false positive it must never report.+- **Tutorial: build a 3D asset pipeline** (`/tutorials/build-a-3d-asset-pipeline`) — Four stages from one prompt to a CI gate: generate a model on the command line, fan a prompt list out in parallel with a manifest and a gallery, refuse to ship anything over its triangle or size budget, then hand the whole pipeline to an AI assistant as an MCP tool. Standard library only, no API key.- **Tutorial: Make Your Avatar Sign (ASL)** (`/tutorials/sign-with-your-avatar`) — Step-by-step tutorial for signing avatars: type a phrase and watch it signed in ASL, share it as a link, export a spelled word as an animated GLB, turn on signed chat replies, and fingerspell back with your webcam.- **Your master wallet** (`/wallet`) — One custodial wallet for your account, separate from your agents'. Hold SOL and USDC across Solana and Base, top up any agent you own, send to any Solana address, and read every transaction straight from chain.- **87 documentation pages that search engines could not see are now discoverable** — The platform serves a page for every documentation file, but only pages listed in the site's page index reach the sitemap, the machine-readable llms.txt, and the feature list. 87 docs had never been listed, which meant they answered normally if you had the link and were invisible to every search engine and AI crawler otherwise. Each one now carries a real title and summary written from the doc itself, covering the API reference, the avatar and animation pipeline, memory, permissions, security, self-hosting, the MCP servers, and the troubleshooting guide. A new check in the documentation audit fails the build if a future doc lands unlisted, so this cannot silently happen again. `[docs, improvement]`@@ -57,6 +58,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **An underfunded trading bot now sits out instead of failing every trade** — A trading strategy whose wallet ran low could get stuck in a loop: it looked funded enough to place a shrunken buy, but not funded enough to run the safety simulation that has to pass before anything is broadcast. So it tried every candidate coin, failed at the same step every time, and filled its history with failures while never actually trading. One live strategy did this 82 times in a day without placing a single buy. Strategies now compare their balance against the amount a trade genuinely needs end to end, including the pre-trade safety checks, and quietly wait for a top-up instead. No trade behavior changes for a properly funded strategy. (`/trades`) `[fix]`- **Avatar optimize endpoint works again for saved avatars** — Asking the optimize endpoint to shrink one of your saved avatars failed every time with a transcode error. Saved avatars are stored geometry-compressed, and the endpoint was reading them without the matching decoder loaded, so it rejected the file before doing any work. Requesting Draco output was broken separately: that code called a compression function that no longer exists in the library, so it threw for every request that asked for it. Both are fixed and the endpoint now returns a valid model for saved avatars and for any model URL you pass it. `[fix]`- **Buying a skill bundle now unlocks the skills you paid for** — Paying for a bundle took the money, recorded the purchase as confirmed, and then failed while granting access, so the request errored and trying again was refused as already processed. The skills stayed locked and there was no way to recover them. The unlock now writes complete records and files them as access rather than as extra sales, so one bundle purchase is still reported as one sale instead of several. `[fix]`+- **Compare two generations of the same prompt side by side** — The Forge lets you pick which engine builds your model, but until now the only way to judge that choice was to remember what the last one looked like. Once your gallery holds two models, a Compare control appears above it: turn it on, pick any two, and they open in two viewers side by side, each labelled with the engine and quality tier that produced it. Turning one model turns the other, so a difference in shape reads as a difference in shape rather than a difference in camera angle. Only the viewing angle is shared, never the zoom, because two versions of one prompt often differ in size and each needs its own framing distance to stay in view. If you have run the same prompt on two different engines, a note above the gallery points that pair out, since that is the comparison actually worth making. (`/forge`) `[feature, improvement]`- **Docs for agent vaults, your master wallet, and copy trading** — Three money surfaces now have real references. Agent vaults explains NAV-priced deposits and redemptions, the drawdown breaker, performance fees, and the public audit ledger. The master wallet doc covers funding it, sending SOL or USDC, and topping up an agent. Copy trading explains both ways to follow a leader, the leaderboard weighting, and the Smart Money directory. All three spell out exactly which requests move real money. (`/docs/vaults`) `[docs]`- **Docs World: read the documentation inside a walkable 3D world** — The docs now come in two forms with one content source. The classic reader at three.ws/docs stays exactly as it was, and a new immersive surface at three.ws/docs/world turns the same documentation into a place: all fourteen sections of the sidebar become glowing pavilions on a ring, you walk an avatar between them (keyboard, or a joystick on phones), and picking a page opens the live doc right inside the scene. Deep links carry over both ways, any rigged GLB can be your body via the avatar parameter, and devices without 3D support are routed to the classic docs with nothing missing. (`/docs/world`) `[feature, docs]`- **Documented the quality bar for models the platform adds to its own catalog** — The platform generates and publishes 3D models into the public character and object catalogs on its own. Every one of them passes an automated quality check first, and that check now has a written explanation: what it measures, why a model gets turned away, and why rejected models are kept rather than deleted so the bar can be tuned against real failures. The check also gained a full test suite covering each way a model can fail. (`/docs/seed-quality`) `[docs, improvement]`diff --git a/data/changelog.json b/data/changelog.jsonindex d946fca1f..b4351a45d 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,16 @@{"$comment": "Curated changelog entries for three.ws, the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-07-30",+ "title": "Compare two generations of the same prompt side by side",+ "summary": "The Forge lets you pick which engine builds your model, but until now the only way to judge that choice was to remember what the last one looked like. Once your gallery holds two models, a Compare control appears above it: turn it on, pick any two, and they open in two viewers side by side, each labelled with the engine and quality tier that produced it. Turning one model turns the other, so a difference in shape reads as a difference in shape rather than a difference in camera angle. Only the viewing angle is shared, never the zoom, because two versions of one prompt often differ in size and each needs its own framing distance to stay in view. If you have run the same prompt on two different engines, a note above the gallery points that pair out, since that is the comparison actually worth making.",+ "tags": [+ "feature",+ "improvement"+ ],+ "link": "/forge"+ },{"date": "2026-07-30","title": "Server errors no longer reveal internal failure codes",diff --git a/docs/forge.md b/docs/forge.mdindex 060677f61..df5b32b57 100644--- a/docs/forge.md+++ b/docs/forge.md@@ -50,6 +50,27 @@ Health is real. The UI fetches `/api/forge?health=1` after load and disables anyGeneration is a job. `POST /api/forge` returns a `job_id`; the client polls `GET /api/forge?job=<id>` until the status is `done` or `failed`. The lanes that complete inline within one request (free NVIDIA NIM, HuggingFace Spaces, BYOK-sync) can instead answer the POST directly with `status:'done'`, the `glb_url`, and a null `job_id`, and they retry once automatically on a failed result. Because the in-flight job id is written to `localStorage`, closing the tab or navigating away does not lose the generation: returning to Forge within a 30-minute window resumes polling the same job. Finished models for your browser are surfaced from a gallery on load, and a share link always wins over a resume.+### Comparing two engines on one prompt++The engine grid is only useful if you can see what choosing an engine actually+changes. Once your gallery holds two models, a **Compare** control appears above+it. Turn it on, pick any two creations, and they open side by side in two+viewers, each labelled with the engine and tier that produced it.++Camera orbit is synced across both panes, so turning one turns the other. Only+the orbit angles are shared, never the distance: two generations of one prompt+routinely differ in scale, and model-viewer frames each at its own radius, so+copying an absolute distance across would zoom one model into its own interior.+Each pane keeps the distance that frames it and turns in lockstep. Untick **Sync+cameras** to inspect one model on its own.++When your gallery contains the same prompt run on two *different* engines, a+hint above the grid points it out, because that is the comparison worth making.+Two runs of one prompt on one engine is a re-roll, not an engine comparison, and+the hint deliberately stays quiet for it (`findComparablePrompts` in+[src/forge-compare.js](../src/forge-compare.js), covered by+[tests/forge-compare.test.js](../tests/forge-compare.test.js)).+## Walkthrough1. Open [/forge](https://three.ws/forge). No login, no wallet, no key required.diff --git a/pages/forge.html b/pages/forge.htmlindex 0b8364065..9d79bd4a5 100644--- a/pages/forge.html+++ b/pages/forge.html@@ -2558,6 +2558,215 @@grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));gap: 12px;}+ /* Compare mode ------------------------------------------------- */+ .compare-toggle {+ margin-left: auto;+ background: transparent;+ border: 1px solid var(--stroke-strong);+ color: var(--ink-dim);+ border-radius: var(--radius-pill);+ padding: 0.25rem 0.7rem;+ font-family: var(--font-mono);+ font-size: var(--text-xs);+ cursor: pointer;+ transition:+ color 0.15s,+ border-color 0.15s,+ background 0.15s;+ }+ .compare-toggle:hover {+ color: var(--ink);+ border-color: var(--ink-dim);+ }+ .compare-toggle:focus-visible {+ outline: 2px solid var(--accent);+ outline-offset: 2px;+ }+ .compare-toggle[aria-pressed='true'] {+ background: var(--accent-soft);+ border-color: var(--accent);+ color: var(--ink);+ }+ .compare-hint {+ margin: 0 0 var(--space-sm);+ font-size: var(--text-xs);+ color: var(--ink-dim);+ }+ /* In compare mode a card is a selectable target, not a link to the+ viewer, so it reads differently and shows its selection order. */+ .creations-grid.is-comparing .creation {+ cursor: copy;+ }+ .creations-grid.is-comparing .creation[aria-pressed='true'] {+ border-color: var(--accent);+ box-shadow: 0 0 0 2px var(--accent-soft);+ }+ .creation .pick {+ position: absolute;+ top: 6px;+ right: 6px;+ width: 22px;+ height: 22px;+ border-radius: 50%;+ display: grid;+ place-items: center;+ background: var(--accent);+ color: var(--btn-primary-fg, #000);+ font-family: var(--font-mono);+ font-size: 11px;+ font-weight: 700;+ line-height: 1;+ }+ .compare-tray {+ position: sticky;+ bottom: 12px;+ margin-top: var(--space-md);+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: var(--space-sm);+ flex-wrap: wrap;+ padding: 0.6rem 0.85rem;+ background: var(--surface-1);+ border: 1px solid var(--stroke-strong);+ border-radius: var(--radius-md);+ box-shadow: 0 16px 40px -20px rgba(0, 0, 0, 0.8);+ }+ .compare-tray-label {+ font-family: var(--font-mono);+ font-size: var(--text-xs);+ color: var(--ink-dim);+ }+ .compare-tray-actions {+ display: flex;+ gap: 8px;+ }+ .compare-go {+ background: var(--btn-primary-bg);+ border-color: transparent;+ color: var(--btn-primary-fg);+ }+ /* Compare modal ------------------------------------------------ */+ .compare-modal {+ position: fixed;+ inset: 0;+ z-index: 90;+ background: rgba(0, 0, 0, 0.72);+ backdrop-filter: blur(6px);+ display: grid;+ place-items: center;+ padding: clamp(8px, 3vw, 32px);+ animation: compare-fade 0.18s ease-out;+ }+ @keyframes compare-fade {+ from {+ opacity: 0;+ }+ }+ .compare-modal-inner {+ width: min(1180px, 100%);+ max-height: 100%;+ overflow-y: auto;+ background: var(--surface-1);+ border: 1px solid var(--stroke-strong);+ border-radius: var(--radius-lg);+ padding: clamp(14px, 2.5vw, 22px);+ }+ .compare-modal-head {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: var(--space-sm);+ }+ .compare-modal-head h2 {+ font-family: var(--font-display);+ font-size: var(--text-lg);+ margin: 0;+ }+ .compare-modal-tools {+ display: flex;+ align-items: center;+ gap: 14px;+ }+ .compare-sync {+ display: flex;+ align-items: center;+ gap: 6px;+ font-family: var(--font-mono);+ font-size: var(--text-xs);+ color: var(--ink-dim);+ cursor: pointer;+ }+ .compare-close {+ background: transparent;+ border: 1px solid var(--stroke-strong);+ color: var(--ink);+ border-radius: var(--radius-sm);+ width: 30px;+ height: 30px;+ font-size: 20px;+ line-height: 1;+ cursor: pointer;+ }+ .compare-close:hover {+ background: var(--surface-2);+ }+ .compare-close:focus-visible,+ .compare-sync input:focus-visible {+ outline: 2px solid var(--accent);+ outline-offset: 2px;+ }+ .compare-prompt {+ margin: 6px 0 14px;+ color: var(--ink-dim);+ font-size: var(--text-sm);+ }+ .compare-panes {+ display: grid;+ grid-template-columns: 1fr 1fr;+ gap: 14px;+ }+ .compare-pane {+ border: 1px solid var(--stroke);+ border-radius: var(--radius-md);+ overflow: hidden;+ background: var(--surface-2);+ display: flex;+ flex-direction: column;+ }+ .compare-pane model-viewer {+ width: 100%;+ aspect-ratio: 1 / 1;+ background: var(--surface-2);+ display: block;+ }+ .compare-pane-meta {+ padding: 10px 12px;+ border-top: 1px solid var(--stroke);+ display: flex;+ flex-direction: column;+ gap: 3px;+ }+ .compare-pane-engine {+ font-family: var(--font-mono);+ font-size: var(--text-xs);+ color: var(--ink);+ }+ .compare-pane-sub {+ font-family: var(--font-mono);+ font-size: var(--text-xs);+ color: var(--ink-dim);+ }+ @media (max-width: 720px) {+ .compare-panes {+ grid-template-columns: 1fr;+ }+ }+ @media (prefers-reduced-motion: reduce) {+ .compare-modal {+ animation: none;+ }+ }/* Showcase uses larger cards — the section spans full width */#showcase .creations-grid {grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));@@ -3802,10 +4011,64 @@<div class="creations-head"><h2 data-i18n="forge.your_creations">Your creations</h2><span class="count" id="creations-count"></span>+ <button+ type="button"+ class="compare-toggle is-hidden"+ id="compare-toggle"+ aria-pressed="false"+ >+ Compare+ </button></div>+ <!-- Same-prompt hint: appears only when the gallery actually holds two+ generations of one prompt, which is the comparison worth making. -->+ <p class="compare-hint is-hidden" id="compare-hint"></p><div class="creations-grid" id="creations-grid"></div>+ <!-- Selection tray, visible only in compare mode -->+ <div class="compare-tray is-hidden" id="compare-tray" role="status">+ <span class="compare-tray-label" id="compare-tray-label"></span>+ <div class="compare-tray-actions">+ <button type="button" class="btn btn-ghost" id="compare-clear">Clear</button>+ <button type="button" class="btn compare-go" id="compare-open" disabled>+ Compare+ </button>+ </div>+ </div></section>+ <!-- Side-by-side compare: two generations of one prompt, engine A vs+ engine B. Camera orbit is synced across both viewers so a shape+ difference reads as a shape difference, not a camera difference. -->+ <div+ class="compare-modal is-hidden"+ id="compare-modal"+ role="dialog"+ aria-modal="true"+ aria-labelledby="compare-modal-title"+ >+ <div class="compare-modal-inner">+ <div class="compare-modal-head">+ <h2 id="compare-modal-title">Compare generations</h2>+ <div class="compare-modal-tools">+ <label class="compare-sync">+ <input type="checkbox" id="compare-sync" checked />+ <span>Sync cameras</span>+ </label>+ <button+ type="button"+ class="compare-close"+ id="compare-close"+ aria-label="Close compare"+ >+ ×+ </button>+ </div>+ </div>+ <p class="compare-prompt" id="compare-prompt"></p>+ <div class="compare-panes" id="compare-panes"></div>+ </div>+ </div>+<!-- Fresh from the Forge — newest community models (src/forge-showcase.js).Hidden until the public feed returns real rows, so deployments withouta durable store never show a hollow strip. -->diff --git a/public/changelog.json b/public/changelog.jsonindex bdc07a672..3a5000c23 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-30T23:13:00.142Z",+ "generated_at": "2026-07-30T23:27:23.421Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -336,6 +336,16 @@"launch"]},+ {+ "date": "2026-07-30",+ "type": "launch",+ "title": "Tutorial: build a 3D asset pipeline",+ "summary": "Four stages from one prompt to a CI gate: generate a model on the command line, fan a prompt list out in parallel with a manifest and a gallery, refuse to ship anything over its triangle or size budget, then hand the whole pipeline to an AI assistant as an MCP tool. Standard library only, no API key.",+ "link": "/tutorials/build-a-3d-asset-pipeline",+ "tags": [+ "launch"+ ]+ },{"date": "2026-07-30","type": "launch",@@ -528,6 +538,17 @@"fix"]},+ {+ "date": "2026-07-30",+ "type": "update",+ "title": "Compare two generations of the same prompt side by side",+ "summary": "The Forge lets you pick which engine builds your model, but until now the only way to judge that choice was to remember what the last one looked like. Once your gallery holds two models, a Compare control appears above it: turn it on, pick any two, and they open in two viewers side by side, each labelled with the engine and quality tier that produced it. Turning one model turns the other, so a difference in shape reads as a difference in shape rather than a difference in camera angle. Only the viewing angle is shared, never the zoom, because two versions of one prompt often differ in size and each needs its own framing distance to stay in view. If you have run the same prompt on two different engines, a note above the gallery points that pair out, since that is the comparison actually worth making.",+ "link": "/forge",+ "tags": [+ "feature",+ "improvement"+ ]+ },{"date": "2026-07-30","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex 87c9bc661..24dc67e08 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -270,6 +270,14 @@<category>launch</category><description>Build a real guard end to end: write the checker, give it an npm script, register it in data/guards.json, wire it into a stage, and cover it with a test that includes the false positive it must never report.</description></item>+ <item>+ <title>Tutorial: build a 3D asset pipeline</title>+ <link>https://three.ws/tutorials/build-a-3d-asset-pipeline</link>+ <guid isPermaLink="false">2026-07-30:Tutorial: build a 3D asset pipeline</guid>+ <pubDate>Thu, 30 Jul 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>Four stages from one prompt to a CI gate: generate a model on the command line, fan a prompt list out in parallel with a manifest and a gallery, refuse to ship anything over its triangle or size budget, then hand the whole pipeline to an AI assistant as an MCP tool. Standard library only, no API key.</description>+ </item><item><title>Tutorial: Make Your Avatar Sign (ASL)</title><link>https://three.ws/tutorials/sign-with-your-avatar</link>@@ -414,6 +422,14 @@<category>fix</category><description>Paying for a bundle took the money, recorded the purchase as confirmed, and then failed while granting access, so the request errored and trying again was refused as already processed. The skills stayed locked and there was no way to recover them. The unlock now writes complete records and files them as access rather than as extra sales, so one bundle purchase is still reported as one sale instead of several.</description></item>+ <item>+ <title>Compare two generations of the same prompt side by side</title>+ <link>https://three.ws/forge</link>+ <guid isPermaLink="false">2026-07-30:Compare two generations of the same prompt side by side</guid>+ <pubDate>Thu, 30 Jul 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>The Forge lets you pick which engine builds your model, but until now the only way to judge that choice was to remember what the last one looked like. Once your gallery holds two models, a Compare control appears above it: turn it on, pick any two, and they open in two viewers side by side, each labelled with the engine and quality tier that produced it. Turning one model turns the other, so a difference in shape reads as a difference in shape rather than a difference in camera angle. Only the viewing angle is shared, never the zoom, because two versions of one prompt often differ in size and each needs its own framing distance to stay in view. If you have run the same prompt on two different engines, a note above the gallery points that pair out, since that is the comparison actually worth making.</description>+ </item><item><title>Docs for agent vaults, your master wallet, and copy trading</title><link>https://three.ws/docs/vaults</link>diff --git a/src/forge-compare.js b/src/forge-compare.jsnew file mode 100644index 000000000..93eee5c5a--- /dev/null+++ b/src/forge-compare.js@@ -0,0 +1,272 @@+/**+ * Side-by-side compare for two forge generations.+ *+ * The forge can produce the same prompt on several different engines, and the+ * only honest way to tell whether "TRELLIS or Hunyuan3D?" matters for a given+ * subject is to look at both meshes at the same camera angle. This module adds+ * that: a compare mode over the "Your creations" gallery, a two-pane viewer,+ * and synced camera orbit so a difference in shape reads as a difference in+ * shape rather than a difference in framing.+ *+ * It owns no data. `forge.js` hands it the creation rows it already fetched+ * from /api/forge-gallery, and hands back a click when a card is picked while+ * compare mode is active. Nothing here fabricates a model, a label, or an+ * engine name: a row with no `glb_url` is never offered for comparison.+ */++/**+ * Normalise a prompt for grouping.+ *+ * Two generations count as "the same prompt" when the text matches after case+ * and whitespace are ignored. This is deliberately strict: a near-match is a+ * different prompt, and claiming otherwise would make the engine comparison+ * dishonest.+ */+function promptKey(text) {+ return String(text || '')+ .trim()+ .toLowerCase()+ .replace(/\s+/g, ' ');+}++/**+ * Find prompts that appear on two or more DIFFERENT engines.+ *+ * Two runs of one prompt on one engine is a re-roll, which is worth looking at+ * but is not the engine comparison this feature is for, so the hint only fires+ * on a genuine A/B.+ */+export function findComparablePrompts(creations) {+ const groups = new Map();+ for (const c of creations) {+ if (!c?.glb_url || !c?.prompt) continue;+ const key = promptKey(c.prompt);+ if (!key) continue;+ if (!groups.has(key)) groups.set(key, []);+ groups.get(key).push(c);+ }+ const out = [];+ for (const [key, rows] of groups) {+ const engines = new Set(rows.map((r) => r.backend).filter(Boolean));+ if (rows.length >= 2 && engines.size >= 2) out.push({ key, rows });+ }+ return out;+}++export function createCompare({ engineLabel }) {+ const els = {+ toggle: document.getElementById('compare-toggle'),+ hint: document.getElementById('compare-hint'),+ grid: document.getElementById('creations-grid'),+ tray: document.getElementById('compare-tray'),+ trayLabel: document.getElementById('compare-tray-label'),+ clear: document.getElementById('compare-clear'),+ open: document.getElementById('compare-open'),+ modal: document.getElementById('compare-modal'),+ modalClose: document.getElementById('compare-close'),+ panes: document.getElementById('compare-panes'),+ modalPrompt: document.getElementById('compare-prompt'),+ sync: document.getElementById('compare-sync'),+ };++ // Without the markup (an older cached page, or a trimmed build) every entry+ // point below turns into a no-op rather than throwing into the gallery.+ if (!els.toggle || !els.grid || !els.modal) {+ return { setCreations() {}, isActive: () => false, handleCardClick: () => false };+ }++ let active = false;+ let picked = [];+ let rows = [];+ let lastFocused = null;+ const viewers = [];++ const label = (c) =>+ [engineLabel?.(c.backend) || c.backend || 'Unknown engine', c.tier].filter(Boolean).join(' · ');++ function syncTray() {+ els.trayLabel.textContent =+ picked.length === 0+ ? 'Pick two models to compare'+ : picked.length === 1+ ? 'Pick one more'+ : `${label(picked[0])} vs ${label(picked[1])}`;+ els.open.disabled = picked.length !== 2;+ }++ function paintCards() {+ for (const card of els.grid.querySelectorAll('.creation')) {+ const id = card.dataset.creationId;+ const idx = picked.findIndex((p) => String(p.id) === String(id));+ card.querySelector('.pick')?.remove();+ if (active) {+ card.setAttribute('aria-pressed', String(idx >= 0));+ } else {+ card.removeAttribute('aria-pressed');+ }+ if (idx >= 0) {+ const badge = document.createElement('span');+ badge.className = 'pick';+ badge.textContent = String(idx + 1);+ card.appendChild(badge);+ }+ }+ }++ function setActive(next) {+ active = next;+ els.toggle.setAttribute('aria-pressed', String(active));+ els.grid.classList.toggle('is-comparing', active);+ els.tray.classList.toggle('is-hidden', !active);+ if (!active) picked = [];+ syncTray();+ paintCards();+ }++ /**+ * Keep both viewers on one camera ANGLE so only the geometry differs.+ *+ * Only theta and phi are shared. Radius is deliberately not: model-viewer+ * frames each model at its own distance, and two generations of one prompt+ * routinely differ in scale, so copying an absolute radius across would zoom+ * one model into its own interior. Each pane keeps the distance that frames+ * it, and turns in lockstep with the other.+ */+ function wireSync() {+ let echo = false;+ for (const viewer of viewers) {+ viewer.addEventListener('camera-change', () => {+ if (echo || !els.sync?.checked) return;+ const orbit = viewer.getCameraOrbit?.();+ if (!orbit) return;+ echo = true;+ for (const other of viewers) {+ if (other === viewer) continue;+ const own = other.getCameraOrbit?.();+ const radius = own ? own.radius : orbit.radius;+ other.cameraOrbit = `${orbit.theta}rad ${orbit.phi}rad ${radius}m`;+ }+ // Release on the next frame: the orbit we just wrote fires its own+ // camera-change on each peer, and those must not bounce back.+ requestAnimationFrame(() => {+ echo = false;+ });+ });+ }+ }++ function closeModal() {+ els.modal.classList.add('is-hidden');+ els.panes.innerHTML = '';+ viewers.length = 0;+ document.removeEventListener('keydown', onKeydown);+ lastFocused?.focus?.();+ }++ function onKeydown(e) {+ if (e.key === 'Escape') closeModal();+ }++ function openModal() {+ if (picked.length !== 2) return;+ lastFocused = document.activeElement;+ els.panes.innerHTML = '';+ viewers.length = 0;++ const samePrompt = promptKey(picked[0].prompt) === promptKey(picked[1].prompt);+ els.modalPrompt.textContent = samePrompt+ ? picked[0].prompt || ''+ : `Different prompts: "${picked[0].prompt || 'untitled'}" vs "${picked[1].prompt || 'untitled'}"`;++ for (const c of picked) {+ const pane = document.createElement('div');+ pane.className = 'compare-pane';++ const viewer = document.createElement('model-viewer');+ viewer.setAttribute('src', c.glb_url);+ viewer.setAttribute('alt', `3D model: ${c.prompt || 'forged model'}`);+ viewer.setAttribute('camera-controls', '');+ viewer.setAttribute('touch-action', 'pan-y');+ viewer.setAttribute('shadow-intensity', '1');+ viewer.setAttribute('exposure', '1');+ pane.appendChild(viewer);+ viewers.push(viewer);++ const meta = document.createElement('div');+ meta.className = 'compare-pane-meta';+ const engine = document.createElement('span');+ engine.className = 'compare-pane-engine';+ engine.textContent = label(c);+ const sub = document.createElement('span');+ sub.className = 'compare-pane-sub';+ sub.textContent = [+ c.path === 'geometry' ? 'geometry-first' : c.path === 'sketch' ? 'sketch to 3D' : 'image path',+ Number(c.views_used) > 1 ? `${c.views_used} views` : null,+ ]+ .filter(Boolean)+ .join(' · ');+ meta.append(engine, sub);+ pane.appendChild(meta);++ els.panes.appendChild(pane);+ }++ wireSync();+ els.modal.classList.remove('is-hidden');+ document.addEventListener('keydown', onKeydown);+ els.modalClose.focus();+ }++ els.toggle.addEventListener('click', () => setActive(!active));+ els.clear.addEventListener('click', () => {+ picked = [];+ syncTray();+ paintCards();+ });+ els.open.addEventListener('click', openModal);+ els.modalClose.addEventListener('click', closeModal);+ els.modal.addEventListener('click', (e) => {+ if (e.target === els.modal) closeModal();+ });++ return {+ isActive: () => active,++ /**+ * Called by the gallery on every card click. Returns true when compare+ * mode consumed the click, so the caller knows not to open the viewer.+ */+ handleCardClick(creation) {+ if (!active) return false;+ if (!creation?.glb_url) return true;+ const at = picked.findIndex((p) => String(p.id) === String(creation.id));+ if (at >= 0) picked.splice(at, 1);+ else if (picked.length < 2) picked.push(creation);+ else picked = [picked[1], creation];+ syncTray();+ paintCards();+ return true;+ },++ /** Refresh after the gallery reloads: offer compare only when it is possible. */+ setCreations(list) {+ rows = Array.isArray(list) ? list.filter((c) => c?.glb_url) : [];+ const possible = rows.length >= 2;+ els.toggle.classList.toggle('is-hidden', !possible);+ if (!possible && active) setActive(false);++ const comparable = findComparablePrompts(rows);+ if (comparable.length > 0) {+ const engines = new Set(comparable[0].rows.map((r) => r.backend).filter(Boolean));+ els.hint.textContent = `You forged "${comparable[0].rows[0].prompt}" on ${engines.size} engines. Compare them side by side.`;+ els.hint.classList.remove('is-hidden');+ } else {+ els.hint.classList.add('is-hidden');+ }+ // Drop selections whose rows are gone after a reload.+ picked = picked.filter((p) => rows.some((r) => String(r.id) === String(p.id)));+ syncTray();+ paintCards();+ },+ };+}diff --git a/src/forge.js b/src/forge.jsindex 71e06760c..ddd33fbc6 100644--- a/src/forge.js+++ b/src/forge.js@@ -16,6 +16,7 @@ import { payForHighGeneration } from './forge-pay.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';ensureStateKitStyles();//// Drives /api/forge. Three paths share one polling loop:@@ -355,6 +356,11 @@ const timeline = createForgeTimeline({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.@@ -1988,6 +1994,9 @@ async function loadGallery() {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 = '';@@ -2054,12 +2063,18 @@ async function loadGallery() {meta.textContent = c.prompt || 'Untitled';card.appendChild(meta);- card.addEventListener('click', () => openCreation(c));+ // 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);+ });els.creationsGrid.appendChild(card);}els.creationsCount.textContent = `${creations.length} saved`;els.creations.classList.remove('is-hidden');+ compare.setCreations(creations);}// Load a creation into the viewer — shared by gallery card clicks and thediff --git a/tests/forge-compare.test.js b/tests/forge-compare.test.jsnew file mode 100644index 000000000..125cce91b--- /dev/null+++ b/tests/forge-compare.test.js@@ -0,0 +1,81 @@+// The compare feature's one piece of judgement: deciding when an A/B is worth+// offering. The rule is strict on purpose. Two runs of one prompt on one engine+// is a re-roll, not an engine comparison, and offering it as one would make the+// side-by-side dishonest. These tests pin that boundary.+import { describe, it, expect } from 'vitest';+import { findComparablePrompts } from '../src/forge-compare.js';++const row = (over = {}) => ({+ id: Math.random().toString(36).slice(2),+ prompt: 'a knight in armor',+ glb_url: 'https://example.test/model.glb',+ backend: 'trellis_selfhost',+ ...over,+});++describe('findComparablePrompts', () => {+ it('finds one prompt generated on two different engines', () => {+ const found = findComparablePrompts([row(), row({ backend: 'hunyuan3d' })]);+ expect(found).toHaveLength(1);+ expect(found[0].rows).toHaveLength(2);+ });++ it('ignores case and surrounding whitespace when grouping', () => {+ const found = findComparablePrompts([+ row({ prompt: ' A Knight In Armor ' }),+ row({ prompt: 'a knight in armor', backend: 'triposg' }),+ ]);+ expect(found).toHaveLength(1);+ });++ it('treats collapsed inner whitespace as the same prompt', () => {+ const found = findComparablePrompts([+ row({ prompt: 'a knight in armor' }),+ row({ prompt: 'a knight in armor', backend: 'triposg' }),+ ]);+ expect(found).toHaveLength(1);+ });++ it('does not offer a re-roll: same prompt, same engine, twice', () => {+ expect(findComparablePrompts([row(), row()])).toEqual([]);+ });++ it('does not group two different prompts', () => {+ expect(+ findComparablePrompts([row(), row({ prompt: 'a red sports car', backend: 'hunyuan3d' })]),+ ).toEqual([]);+ });++ it('skips rows with no model to show', () => {+ expect(+ findComparablePrompts([row({ glb_url: null }), row({ backend: 'hunyuan3d' })]),+ ).toEqual([]);+ });++ it('skips rows with a missing or empty prompt', () => {+ expect(+ findComparablePrompts([+ row({ prompt: '' }),+ row({ prompt: undefined, backend: 'hunyuan3d' }),+ ]),+ ).toEqual([]);+ });++ it('does not count a missing backend as a distinct engine', () => {+ expect(findComparablePrompts([row({ backend: null }), row({ backend: null })])).toEqual([]);+ });++ it('handles an empty gallery', () => {+ expect(findComparablePrompts([])).toEqual([]);+ });++ it('reports every comparable prompt, not just the first', () => {+ const found = findComparablePrompts([+ row(),+ row({ backend: 'hunyuan3d' }),+ row({ prompt: 'a red sports car' }),+ row({ prompt: 'a red sports car', backend: 'triposg' }),+ ]);+ expect(found).toHaveLength(2);+ });+});