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): celebrate a visitor's first 3D creation
nirholascb24c1826523
diff --git a/pages/forge.html b/pages/forge.htmlindex e6dd04737..2d3a93f8b 100644--- a/pages/forge.html+++ b/pages/forge.html@@ -3442,6 +3442,7 @@<script type="module" src="/src/forge-ar.js"></script><script type="module" src="/src/forge-showcase.js"></script><script type="module" src="/src/forge-dropzone.js"></script>+ <script type="module" src="/src/forge-more-like-this.js"></script><div id="footer-container"></div><script src="/footer.js"></script></body>diff --git a/public/forge-celebrate.js b/public/forge-celebrate.jsnew file mode 100644index 000000000..cb1b5a68f--- /dev/null+++ b/public/forge-celebrate.js@@ -0,0 +1,250 @@+// three.ws first-creation celebration — closes the reward loop at the one moment+// that matters: the first time a visitor forges a 3D model on this device.+//+// The forge machinery mints a "first creation" server-side badge only for+// signed-in users (api/_lib/streaks.js), but the large majority of generations+// are anonymous — so that milestone passed with a silent 3-second "Saved" chip.+// This layer gives every first-time creator, signed in or not, a real moment:+// a confetti burst and a glass card acknowledging what they just made.+//+// Self-mounting + idempotent (loaded by nav.js on every page, like the glossary+// and discovery layers). It listens for the universal `tws:feature-done` signal+// that BOTH the full Forge page (src/forge.js) and the home inline Forge+// (src/home-forge.js) emit on a fresh generation, so it covers every surface+// without touching those files. Fires at most once per device.+//+// Opt out per page with <html data-celebrate="off">. Honours reduced-motion:+// no confetti, the card still appears (a fade, no slide).++(function () {+ 'use strict';++ if (window.__twsForgeCelebrate) return;+ window.__twsForgeCelebrate = true;+ if (typeof document === 'undefined') return;+ if (document.documentElement.getAttribute('data-celebrate') === 'off') return;++ var CELEBRATED_KEY = 'tws:first-forge-celebrated';+ var HOME_HISTORY_KEY = 'forge:home:history';+ var AUTO_DISMISS_MS = 7000;++ function lsGet(k) { try { return localStorage.getItem(k); } catch (e) { return null; } }+ function lsSet(k, v) { try { localStorage.setItem(k, v); } catch (e) { /* private mode */ } }++ // True if this device has already forged before — so we never congratulate a+ // returning creator. We check our own once-flag plus the home Forge's saved+ // history list (a veteran who used the inline Forge has entries there).+ function hasForgedBefore() {+ if (lsGet(CELEBRATED_KEY)) return true;+ try {+ var raw = localStorage.getItem(HOME_HISTORY_KEY);+ if (raw) {+ var arr = JSON.parse(raw);+ if (Array.isArray(arr) && arr.length > 0) return true;+ }+ } catch (e) { /* unreadable history — treat as first */ }+ return false;+ }++ var prefersReducedMotion = false;+ try {+ prefersReducedMotion = window.matchMedia &&+ window.matchMedia('(prefers-reduced-motion: reduce)').matches;+ } catch (e) { /* no matchMedia — assume motion ok */ }++ var firedThisSession = false;++ document.addEventListener('tws:feature-done', function (e) {+ var detail = e && e.detail;+ if (!detail || detail.feature !== 'forge') return;+ if (firedThisSession) return;+ if (hasForgedBefore()) return;+ firedThisSession = true;+ lsSet(CELEBRATED_KEY, '1');+ // Let the result render/settle first so the moment lands on the model, not+ // mid-transition.+ setTimeout(celebrate, 450);+ });++ function ensureStyles() {+ if (document.getElementById('twfc-styles')) return;+ var css = [+ '#twfc-confetti{position:fixed;inset:0;width:100%;height:100%;pointer-events:none;z-index:9997}',+ '.twfc-card{position:fixed;left:50%;bottom:32px;transform:translateX(-50%) translateY(16px);',+ 'z-index:9998;display:flex;align-items:center;gap:14px;max-width:min(440px,calc(100vw - 32px));',+ 'padding:14px 16px;border-radius:16px;opacity:0;',+ 'background:var(--surface-glass,rgba(20,20,22,0.72));backdrop-filter:blur(18px) saturate(1.4);',+ '-webkit-backdrop-filter:blur(18px) saturate(1.4);',+ 'border:1px solid var(--border-strong,rgba(255,255,255,0.14));',+ 'box-shadow:0 18px 50px rgba(0,0,0,0.5),0 0 0 1px rgba(255,255,255,0.04) inset,',+ '0 0 32px -6px color-mix(in srgb,var(--accent,#fff) 45%,transparent);',+ 'transition:opacity .5s cubic-bezier(.2,.7,.2,1),transform .5s cubic-bezier(.2,.7,.2,1)}',+ '.twfc-card.twfc-in{opacity:1;transform:translateX(-50%) translateY(0)}',+ '.twfc-spark{flex:none;width:40px;height:40px;border-radius:12px;display:grid;place-items:center;',+ 'font-size:20px;color:var(--bg-0,#0a0a0a);',+ 'background:linear-gradient(135deg,var(--accent,#fff),color-mix(in srgb,var(--accent,#fff) 60%,#8b5cf6));',+ 'box-shadow:0 4px 16px -2px color-mix(in srgb,var(--accent,#fff) 55%,transparent)}',+ '.twfc-body{display:flex;flex-direction:column;gap:2px;min-width:0}',+ '.twfc-title{font-family:var(--font-display,"Space Grotesk",system-ui,sans-serif);',+ 'font-weight:650;font-size:15px;letter-spacing:-.01em;color:var(--text,#fff);line-height:1.25}',+ '.twfc-sub{font-size:12.5px;color:var(--text-3,rgba(255,255,255,0.62));line-height:1.35}',+ '.twfc-close{flex:none;margin-left:2px;width:26px;height:26px;border-radius:8px;border:0;cursor:pointer;',+ 'background:transparent;color:var(--text-3,rgba(255,255,255,0.55));font-size:18px;line-height:1;',+ 'display:grid;place-items:center;transition:background .15s,color .15s}',+ '.twfc-close:hover{background:rgba(255,255,255,0.08);color:var(--text,#fff)}',+ '.twfc-close:focus-visible{outline:2px solid var(--accent,#fff);outline-offset:2px}',+ '@media (prefers-reduced-motion: reduce){',+ '.twfc-card{transition:opacity .3s ease;transform:translateX(-50%)}',+ '.twfc-card.twfc-in{transform:translateX(-50%)}}',+ ].join('');+ var style = document.createElement('style');+ style.id = 'twfc-styles';+ style.textContent = css;+ document.head.appendChild(style);+ }++ function accentColor() {+ try {+ var c = getComputedStyle(document.documentElement).getPropertyValue('--accent').trim();+ if (c) return c;+ } catch (e) { /* fall through */ }+ return '#ffffff';+ }++ function celebrate() {+ ensureStyles();+ if (!prefersReducedMotion) burstConfetti();+ showCard();+ }++ function showCard() {+ var card = document.createElement('div');+ card.className = 'twfc-card';+ card.setAttribute('role', 'status');+ card.setAttribute('aria-live', 'polite');++ var spark = document.createElement('div');+ spark.className = 'twfc-spark';+ spark.setAttribute('aria-hidden', 'true');+ spark.textContent = '✦'; // ✦++ var body = document.createElement('div');+ body.className = 'twfc-body';+ var title = document.createElement('strong');+ title.className = 'twfc-title';+ title.textContent = 'Your first 3D creation';+ var sub = document.createElement('span');+ sub.className = 'twfc-sub';+ sub.textContent = 'Saved on this device. Spin it, download it, or forge another.';+ body.appendChild(title);+ body.appendChild(sub);++ var close = document.createElement('button');+ close.className = 'twfc-close';+ close.type = 'button';+ close.setAttribute('aria-label', 'Dismiss');+ close.textContent = '×'; // ×++ card.appendChild(spark);+ card.appendChild(body);+ card.appendChild(close);+ document.body.appendChild(card);++ // Next frame → transition in.+ requestAnimationFrame(function () {+ requestAnimationFrame(function () { card.classList.add('twfc-in'); });+ });++ var dismissed = false;+ var timer = null;+ function dismiss() {+ if (dismissed) return;+ dismissed = true;+ if (timer) clearTimeout(timer);+ document.removeEventListener('keydown', onKey);+ card.classList.remove('twfc-in');+ setTimeout(function () { if (card.parentNode) card.parentNode.removeChild(card); }, 520);+ }+ function onKey(ev) { if (ev.key === 'Escape') dismiss(); }++ close.addEventListener('click', dismiss);+ document.addEventListener('keydown', onKey);+ timer = setTimeout(dismiss, AUTO_DISMISS_MS);+ }++ // Self-contained canvas confetti — no dependency, no network. A single short+ // burst from the lower third, gravity + drag + fade, cleaned up when spent.+ function burstConfetti() {+ var accent = accentColor();+ var colors = [accent, '#8b5cf6', '#22d3ee', '#ffffff'];+ var canvas = document.createElement('canvas');+ canvas.id = 'twfc-confetti';+ canvas.setAttribute('aria-hidden', 'true');+ var dpr = Math.min(window.devicePixelRatio || 1, 2);+ function size() {+ canvas.width = Math.floor(window.innerWidth * dpr);+ canvas.height = Math.floor(window.innerHeight * dpr);+ }+ size();+ document.body.appendChild(canvas);+ var ctx = canvas.getContext('2d');+ if (!ctx) { if (canvas.parentNode) canvas.parentNode.removeChild(canvas); return; }++ var W = function () { return canvas.width; };+ var H = function () { return canvas.height; };+ var cx = W() / 2;+ var originY = H() * 0.72;+ var count = 90;+ var parts = [];+ for (var i = 0; i < count; i++) {+ var angle = -Math.PI / 2 + (Math.random() - 0.5) * 1.9;+ var speed = (7 + Math.random() * 9) * dpr;+ parts.push({+ x: cx + (Math.random() - 0.5) * 120 * dpr,+ y: originY,+ vx: Math.cos(angle) * speed,+ vy: Math.sin(angle) * speed,+ w: (5 + Math.random() * 6) * dpr,+ h: (7 + Math.random() * 8) * dpr,+ rot: Math.random() * Math.PI,+ vr: (Math.random() - 0.5) * 0.4,+ color: colors[(Math.random() * colors.length) | 0],+ life: 0,+ ttl: 90 + Math.random() * 40,+ });+ }+ var gravity = 0.32 * dpr;+ var drag = 0.985;+ var raf = null;+ function frame() {+ ctx.clearRect(0, 0, W(), H());+ var alive = 0;+ for (var j = 0; j < parts.length; j++) {+ var p = parts[j];+ if (p.life >= p.ttl) continue;+ alive++;+ p.life++;+ p.vx *= drag;+ p.vy = p.vy * drag + gravity;+ p.x += p.vx;+ p.y += p.vy;+ p.rot += p.vr;+ var fade = 1 - p.life / p.ttl;+ ctx.save();+ ctx.globalAlpha = Math.max(0, fade);+ ctx.translate(p.x, p.y);+ ctx.rotate(p.rot);+ ctx.fillStyle = p.color;+ ctx.fillRect(-p.w / 2, -p.h / 2, p.w, p.h);+ ctx.restore();+ }+ if (alive > 0) {+ raf = requestAnimationFrame(frame);+ } else {+ cancelAnimationFrame(raf);+ if (canvas.parentNode) canvas.parentNode.removeChild(canvas);+ }+ }+ raf = requestAnimationFrame(frame);+ }+})();diff --git a/public/nav.js b/public/nav.jsindex 33b3b4a91..9b47d4361 100644--- a/public/nav.js+++ b/public/nav.js@@ -90,6 +90,20 @@ function loadDiscovery() {document.head.appendChild(s);}+// Load the site-wide first-creation celebration (public/forge-celebrate.js):+// the confetti + card moment when a visitor forges their first 3D model.+// Listens for the same `tws:feature-done` signal the discovery layer uses, so+// it covers every generation surface. Self-mounting + idempotent; fires at most+// once per device; honours <html data-celebrate="off">.+function loadForgeCelebrate() {+ if (document.documentElement.getAttribute('data-celebrate') === 'off') return;+ if (document.querySelector('script[src="/forge-celebrate.js"]')) return;+ const s = document.createElement('script');+ s.src = '/forge-celebrate.js';+ s.defer = true;+ document.head.appendChild(s);+}+// Load the site-wide theme switcher (public/theme-switcher.js): owns the// dark ⇄ light toggle wired to the nav button, persistence and cross-tab sync.// Self-mounting + idempotent. The inline boot script already applied the theme@@ -186,6 +200,7 @@ function boot() {loadSearch();loadAgentBusDebug();loadDiscovery();+ loadForgeCelebrate();loadGettingStarted();loadThemeSwitcher();initCompanionAutoStart();diff --git a/src/forge-more-like-this.js b/src/forge-more-like-this.jsnew file mode 100644index 000000000..58ecac889--- /dev/null+++ b/src/forge-more-like-this.js@@ -0,0 +1,135 @@+// Forge — "More like this" (browser client).+//+// After a text→3D result lands, forge.js dispatches `forge:model-ready` with the+// prompt that produced it (as `label`). This module reads that prompt and offers+// a compact row of one-tap variations that keep the same subject but restyle its+// material or finish (see ./shared/forge-variations.js). Tapping a chip fires+// `forge:run-prompt`, which forge.js turns into an immediate generation using the+// exact same path as the example chips — so exploring a design space is a single+// tap, with no retyping.+//+// Fully decoupled: no imports from forge.js, no changes to its state. It only+// listens for the public event, reads the public `#prompt`/`#tab-text` elements,+// and dispatches a public event back. Degrades to nothing when the result did+// not come from a text prompt (e.g. photo or sketch mode).++import { deriveVariations } from './shared/forge-variations.js';++const result = document.getElementById('state-result');+if (result) {+ const STYLE_ID = 'mlt-styles';+ if (!document.getElementById(STYLE_ID)) {+ const style = document.createElement('style');+ style.id = STYLE_ID;+ style.textContent = `+.mlt{display:flex;align-items:center;gap:var(--space-xs);flex-wrap:wrap;+ margin-top:var(--space-sm);padding-top:var(--space-sm);+ border-top:1px solid var(--stroke);animation:mlt-in .38s ease both;}+.mlt-label{font-size:var(--text-2xs);letter-spacing:.09em;text-transform:uppercase;+ color:var(--ink-dim);font-family:var(--font-mono);margin-right:var(--space-3xs);}+.mlt-chip{display:inline-flex;align-items:center;gap:var(--space-2xs);+ font-family:var(--font-body);font-size:var(--text-xs);color:var(--ink);+ background:var(--surface-2);border:1px solid var(--stroke);+ border-radius:var(--radius-pill);padding:var(--space-3xs) var(--space-sm);+ cursor:pointer;transition:background .15s ease,border-color .15s ease,transform .15s ease;}+.mlt-chip:hover{background:var(--surface-3);border-color:var(--stroke-strong);transform:translateY(-1px);}+.mlt-chip:active{transform:translateY(0);}+.mlt-chip:focus-visible{outline:2px solid var(--accent);outline-offset:2px;}+.mlt-dot{width:10px;height:10px;border-radius:var(--radius-pill);+ background:var(--dot,#888);box-shadow:0 0 0 1px rgba(255,255,255,.14) inset;flex:none;}+.mlt-reshuffle{display:inline-flex;align-items:center;justify-content:center;+ width:26px;height:26px;color:var(--ink-dim);background:transparent;+ border:1px solid var(--stroke);border-radius:var(--radius-pill);cursor:pointer;+ transition:color .15s ease,border-color .15s ease,transform .3s ease;}+.mlt-reshuffle:hover{color:var(--ink);border-color:var(--stroke-strong);}+.mlt-reshuffle:active{transform:rotate(180deg);}+.mlt-reshuffle:focus-visible{outline:2px solid var(--accent);outline-offset:2px;}+@keyframes mlt-in{from{opacity:0;transform:translateY(4px);}to{opacity:1;transform:none;}}+@media (prefers-reduced-motion:reduce){+ .mlt{animation:none;}+ .mlt-chip,.mlt-reshuffle{transition:none;}+ .mlt-reshuffle:active{transform:none;}+}`;+ document.head.appendChild(style);+ }++ // Build the row's DOM once and insert it just under the result action bar,+ // above the deeper tool panels (stylize/optimize).+ const row = document.createElement('div');+ row.className = 'mlt is-hidden';+ row.setAttribute('aria-label', 'Generate a variation of this model');+ row.hidden = true;++ const bar = result.querySelector('.result-bar');+ if (bar && bar.parentNode) bar.parentNode.insertBefore(row, bar.nextSibling);+ else result.appendChild(row);++ let currentPrompt = '';++ function isTextMode() {+ const tab = document.getElementById('tab-text');+ // Default to true when the tab is absent, but require it to be selected+ // when present, so photo/sketch results don't offer material restyles.+ return !tab || tab.getAttribute('aria-selected') === 'true';+ }++ function pickVariation(prompt) {+ document.dispatchEvent(new CustomEvent('forge:run-prompt', { detail: { prompt } }));+ }++ function renderChips() {+ const variations = deriveVariations(currentPrompt, { count: 3 });+ if (!variations.length) {+ row.hidden = true;+ row.classList.add('is-hidden');+ return;+ }+ row.innerHTML = '';++ const label = document.createElement('span');+ label.className = 'mlt-label';+ label.textContent = 'More like this';+ row.appendChild(label);++ for (const v of variations) {+ const chip = document.createElement('button');+ chip.type = 'button';+ chip.className = 'mlt-chip';+ chip.title = v.prompt;+ chip.innerHTML =+ `<span class="mlt-dot" style="--dot:${v.swatch}" aria-hidden="true"></span>` ++ `<span class="mlt-text"></span>`;+ chip.querySelector('.mlt-text').textContent = v.label;+ chip.addEventListener('click', () => pickVariation(v.prompt));+ row.appendChild(chip);+ }++ const reshuffle = document.createElement('button');+ reshuffle.type = 'button';+ reshuffle.className = 'mlt-reshuffle';+ reshuffle.setAttribute('aria-label', 'Show different variations');+ reshuffle.title = 'Show different variations';+ reshuffle.textContent = '↻';+ reshuffle.addEventListener('click', renderChips);+ row.appendChild(reshuffle);++ row.hidden = false;+ row.classList.remove('is-hidden');+ // Restart the entrance animation on each refresh.+ row.style.animation = 'none';+ void row.offsetWidth;+ row.style.animation = '';+ }++ document.addEventListener('forge:model-ready', (e) => {+ const label = typeof e.detail?.label === 'string' ? e.detail.label.trim() : '';+ if (!label || !isTextMode()) {+ currentPrompt = '';+ row.hidden = true;+ row.classList.add('is-hidden');+ return;+ }+ currentPrompt = label;+ renderChips();+ });+}diff --git a/src/forge.js b/src/forge.jsindex 40cb2bf3c..be2cb2a04 100644--- a/src/forge.js+++ b/src/forge.js@@ -2747,6 +2747,13 @@ els.emptyStarters?.addEventListener('click', (e) => {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.+document.addEventListener('forge:run-prompt', (e) => {+ const text = typeof e.detail?.prompt === 'string' ? e.detail.prompt.trim() : '';+ if (text) runExamplePrompt(text);+});+// 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 bothdiff --git a/src/shared/forge-variations.js b/src/shared/forge-variations.jsnew file mode 100644index 000000000..0faa74df5--- /dev/null+++ b/src/shared/forge-variations.js@@ -0,0 +1,72 @@+// Forge — "More like this" variation grammar (pure, shared, testable).+//+// Given the prompt that produced a result, derive a few one-tap variations that+// keep the SAME subject but restyle its material or finish. This preserves the+// single-subject shape the free draft lane (TRELLIS) models best, while letting+// a creator explore the design space of their idea without retyping anything.+//+// Deliberately dependency-free and deterministic when a seeded rng is supplied,+// so the behaviour is unit-testable and the client stays trivial.++// Each facet: a stable key, a short chip label, the natural-language phrase+// appended to the base prompt, a swatch colour for the chip dot, and `match`+// keywords that suppress the facet when the prompt already names that material.+export const VARIATION_FACETS = [+ { key: 'brass', label: 'Brass', phrase: 'in brushed brass', swatch: '#b08d57', match: ['brass'] },+ { key: 'chrome', label: 'Chrome', phrase: 'in polished chrome', swatch: '#c8ccd0', match: ['chrome', 'stainless'] },+ { key: 'glass', label: 'Glass', phrase: 'as translucent glass', swatch: '#9fd3e0', match: ['glass'] },+ { key: 'oak', label: 'Oak', phrase: 'carved from oak', swatch: '#8a5a2b', match: ['oak', 'wooden', 'wood'] },+ { key: 'walnut', label: 'Walnut', phrase: 'carved from dark walnut', swatch: '#5b3a29', match: ['walnut'] },+ { key: 'ceramic', label: 'Ceramic', phrase: 'in glazed ceramic', swatch: '#e8e2d5', match: ['ceramic', 'porcelain'] },+ { key: 'bronze', label: 'Bronze', phrase: 'in weathered bronze', swatch: '#7d5a3c', match: ['bronze'] },+ { key: 'copper', label: 'Copper', phrase: 'in hammered copper', swatch: '#b87333', match: ['copper'] },+ { key: 'marble', label: 'Marble', phrase: 'carved from white marble', swatch: '#e6e6e6', match: ['marble'] },+ { key: 'obsidian', label: 'Obsidian', phrase: 'in polished black obsidian', swatch: '#2b2b30', match: ['obsidian'] },+ { key: 'clay', label: 'Clay', phrase: 'in matte terracotta clay', swatch: '#b5651d', match: ['clay', 'terracotta'] },+ { key: 'crystal', label: 'Crystal', phrase: 'as a faceted crystal', swatch: '#bfe6ff', match: ['crystal'] },+ { key: 'gold', label: 'Gold', phrase: 'in gleaming gold', swatch: '#ffd479', match: ['gold', 'golden'] },+ { key: 'jade', label: 'Jade', phrase: 'carved from green jade', swatch: '#5cab7d', match: ['jade'] },+ { key: 'iron', label: 'Iron', phrase: 'in blackened cast iron', swatch: '#3a3a3f', match: ['iron'] },+ { key: 'neon', label: 'Neon', phrase: 'in glowing cyberpunk neon', swatch: '#ff3df0', match: ['neon'] },+ { key: 'lowpoly', label: 'Low-poly', phrase: 'as a low-poly sculpt', swatch: '#9aa0ff', match: ['low-poly', 'lowpoly', 'low poly'] },+ { key: 'holo', label: 'Holographic', phrase: 'in iridescent holographic acrylic', swatch: '#c0a0ff', match: ['holographic', 'iridescent'] },+ { key: 'rattan', label: 'Rattan', phrase: 'woven from rattan', swatch: '#c9a56a', match: ['rattan', 'wicker'] },+ { key: 'granite', label: 'Granite', phrase: 'carved from speckled granite', swatch: '#8f9095', match: ['granite', 'stone'] },+];++// Strip a trailing separator so the appended phrase reads cleanly.+function cleanBase(prompt) {+ return String(prompt || '').trim().replace(/[.,;\s]+$/u, '');+}++// Compose one variation prompt: same subject, restyled by the facet.+export function composeVariation(prompt, facet) {+ const base = cleanBase(prompt);+ if (!base) return '';+ return `${base}, ${facet.phrase}`;+}++// Fisher-Yates using an injectable rng (defaults to Math.random) so callers can+// seed it for deterministic tests.+function shuffled(list, rng) {+ const a = list.slice();+ for (let i = a.length - 1; i > 0; i--) {+ const j = Math.floor(rng() * (i + 1));+ [a[i], a[j]] = [a[j], a[i]];+ }+ return a;+}++// Derive up to `count` distinct variations for a prompt. Facets whose material+// the prompt already names are excluded so the suggestions always feel fresh.+// Returns [{ key, label, swatch, prompt }]. Empty prompt yields [].+export function deriveVariations(prompt, { count = 3, rng = Math.random } = {}) {+ const base = cleanBase(prompt);+ if (!base) return [];+ const lower = base.toLowerCase();+ const eligible = VARIATION_FACETS.filter((f) => !f.match.some((m) => lower.includes(m)));+ const pool = eligible.length ? eligible : VARIATION_FACETS;+ return shuffled(pool, rng)+ .slice(0, Math.max(0, count))+ .map((f) => ({ key: f.key, label: f.label, swatch: f.swatch, prompt: composeVariation(prompt, f) }));+}diff --git a/tests/forge-more-like-this.test.js b/tests/forge-more-like-this.test.jsnew file mode 100644index 000000000..35f800020--- /dev/null+++ b/tests/forge-more-like-this.test.js@@ -0,0 +1,154 @@+// @vitest-environment jsdom+//+// "More like this" turns one result into a one-tap exploration of its material+// space. Two things must hold: the variation grammar keeps the same subject+// while never re-offering a material the prompt already names, and the decoupled+// client only shows for text-mode results and hands a real prompt back to+// forge.js via `forge:run-prompt`. Both are pinned here.++import { describe, expect, it, beforeEach, vi } from 'vitest';+import {+ deriveVariations,+ composeVariation,+ VARIATION_FACETS,+} from '../src/shared/forge-variations.js';++// Deterministic rng: cycles through a fixed sequence so selections are stable.+function seededRng(seq) {+ let i = 0;+ return () => seq[i++ % seq.length];+}++describe('deriveVariations', () => {+ it('returns the requested count of distinct variations', () => {+ const v = deriveVariations('a glazed ceramic teapot', { count: 3, rng: seededRng([0.1, 0.4, 0.7, 0.2]) });+ expect(v).toHaveLength(3);+ expect(new Set(v.map((x) => x.key)).size).toBe(3);+ for (const x of v) {+ expect(x.prompt.startsWith('a glazed ceramic teapot,')).toBe(true);+ expect(typeof x.label).toBe('string');+ expect(x.swatch).toMatch(/^#[0-9a-f]{6}$/i);+ }+ });++ it('never re-offers a material the prompt already names', () => {+ // Try every facet's own keyword; that facet must be absent from results.+ for (const facet of VARIATION_FACETS) {+ const prompt = `a small ${facet.match[0]} figurine`;+ const keys = deriveVariations(prompt, { count: 8 }).map((x) => x.key);+ expect(keys).not.toContain(facet.key);+ }+ });++ it('is deterministic for a given seed', () => {+ const a = deriveVariations('a red fox', { count: 3, rng: seededRng([0.3, 0.6, 0.9, 0.1]) });+ const b = deriveVariations('a red fox', { count: 3, rng: seededRng([0.3, 0.6, 0.9, 0.1]) });+ expect(a.map((x) => x.key)).toEqual(b.map((x) => x.key));+ });++ it('returns nothing for an empty or whitespace prompt', () => {+ expect(deriveVariations('')).toEqual([]);+ expect(deriveVariations(' ')).toEqual([]);+ expect(deriveVariations(null)).toEqual([]);+ });+});++describe('composeVariation', () => {+ it('appends the facet phrase and strips a trailing separator', () => {+ const facet = VARIATION_FACETS.find((f) => f.key === 'brass');+ expect(composeVariation('a sci-fi helmet.', facet)).toBe('a sci-fi helmet, in brushed brass');+ expect(composeVariation('a sci-fi helmet, ', facet)).toBe('a sci-fi helmet, in brushed brass');+ });+});++describe('forge-more-like-this client', () => {+ // The module reads #state-result at import time, so build the DOM first, then+ // re-execute the module fresh for each test.+ async function mountFreshModule() {+ vi.resetModules();+ return import('../src/forge-more-like-this.js');+ }++ function buildDom({ textMode = true } = {}) {+ document.head.innerHTML = '';+ document.body.innerHTML = `+ <button id="tab-text" role="tab" aria-selected="${textMode ? 'true' : 'false'}"></button>+ <div id="state-result">+ <div class="result-bar"><span class="label"></span></div>+ </div>`;+ }++ beforeEach(() => {+ document.head.innerHTML = '';+ document.body.innerHTML = '';+ });++ it('renders three chips + a reshuffle when a text result lands', async () => {+ buildDom({ textMode: true });+ await mountFreshModule();+ document.dispatchEvent(+ new CustomEvent('forge:model-ready', { detail: { label: 'a glazed ceramic teapot' } }),+ );+ const row = document.querySelector('#state-result .mlt');+ expect(row).toBeTruthy();+ expect(row.hidden).toBe(false);+ expect(row.querySelectorAll('.mlt-chip')).toHaveLength(3);+ expect(row.querySelector('.mlt-reshuffle')).toBeTruthy();+ expect(row.querySelector('.mlt-label').textContent).toBe('More like this');+ });++ it('hands a real derived prompt back via forge:run-prompt on tap', async () => {+ buildDom({ textMode: true });+ await mountFreshModule();+ document.dispatchEvent(+ new CustomEvent('forge:model-ready', { detail: { label: 'a low-poly red fox' } }),+ );+ const spy = vi.fn();+ document.addEventListener('forge:run-prompt', (e) => spy(e.detail.prompt));+ const chip = document.querySelector('.mlt-chip');+ chip.click();+ expect(spy).toHaveBeenCalledTimes(1);+ const sent = spy.mock.calls[0][0];+ expect(sent.startsWith('a low-poly red fox,')).toBe(true);+ // The tapped chip's title carries the exact prompt it dispatches.+ expect(sent).toBe(chip.title);+ });++ it('reshuffle swaps in a new set of chips', async () => {+ buildDom({ textMode: true });+ await mountFreshModule();+ document.dispatchEvent(+ new CustomEvent('forge:model-ready', { detail: { label: 'a brass astrolabe' } }),+ );+ const before = [...document.querySelectorAll('.mlt-chip')].map((c) => c.title);+ // Reshuffle enough times that at least one draw differs from the first.+ let changed = false;+ for (let i = 0; i < 12 && !changed; i++) {+ document.querySelector('.mlt-reshuffle').click();+ const after = [...document.querySelectorAll('.mlt-chip')].map((c) => c.title);+ if (after.join('|') !== before.join('|')) changed = true;+ }+ expect(changed).toBe(true);+ });++ it('stays hidden for a non-text-mode result', async () => {+ buildDom({ textMode: false });+ await mountFreshModule();+ document.dispatchEvent(+ new CustomEvent('forge:model-ready', { detail: { label: 'uploaded-photo.png' } }),+ );+ const row = document.querySelector('#state-result .mlt');+ expect(row.hidden).toBe(true);+ });++ it('hides when a later result has no usable prompt', async () => {+ buildDom({ textMode: true });+ await mountFreshModule();+ document.dispatchEvent(+ new CustomEvent('forge:model-ready', { detail: { label: 'a glazed ceramic teapot' } }),+ );+ expect(document.querySelector('.mlt').hidden).toBe(false);+ document.dispatchEvent(new CustomEvent('forge:model-ready', { detail: { label: '' } }));+ expect(document.querySelector('.mlt').hidden).toBe(true);+ });+});