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
build: refuse to build a tree carrying unresolved merge-conflict markers
nirholas018d85a8786d
diff --git a/package.json b/package.jsonindex 23685f76d..4028ba4df 100644--- a/package.json+++ b/package.json@@ -144,7 +144,7 @@"audit:routes": "node scripts/verify-routes.mjs","audit:handlers": "node scripts/audit-empty-handlers.mjs","audit:x402-catalog": "node scripts/audit-x402-catalog.mjs",- "gate": "npm run check:claude && npm run test:gate && npm run test:gate-3d && npm run audit:mcp && npm run audit:mcp-golden && npm run audit:routes && npm run audit:handlers && npm run audit:pages && npm run audit:hidden-guard && npm run audit:x402-catalog && npm run audit:tokens",+ "gate": "npm run check:conflicts && npm run check:claude && npm run test:gate && npm run test:gate-3d && npm run audit:mcp && npm run audit:mcp-golden && npm run audit:routes && npm run audit:handlers && npm run audit:pages && npm run audit:hidden-guard && npm run audit:x402-catalog && npm run audit:tokens","test:gate-3d": "vitest run tests/glb-canonicalize.test.js tests/animation-retarget.test.js tests/animation-retarget-rest-pollution.test.js tests/viewer-framing.test.js","audit:mcp-golden": "node scripts/audit-mcp-golden.mjs","audit:hidden-guard": "node scripts/audit-hidden-guard.mjs",@@ -237,7 +237,7 @@"deploy": "npm run build:all && npm run check:dist && vercel --local-config vercel.json --prod","build:info": "node scripts/write-build-info.mjs","build:info:snapshot": "node scripts/write-build-info.mjs --snapshot",- "build:gcp": "npm run ensure:avatar-studio && npm run build:info:snapshot && npm run build:chat && npm run build && npm run build:lib:full && npm run publish:lib && npm run build:info && npm run check:dist && npm run check:pages",+ "build:gcp": "npm run check:conflicts && npm run ensure:avatar-studio && npm run build:info:snapshot && npm run build:chat && npm run build && npm run build:lib:full && npm run publish:lib && npm run build:info && npm run check:dist && npm run check:pages","ensure:avatar-studio": "test -f character-studio/build/index.html || npm run build:avatar-studio","deploy:gcp": "npm run check:dist && npm run check:pages && npm run db:check && gcloud builds submit --config server/cloudbuild.yaml --region us-central1 --project aerial-vehicle-466722-p5 && npm run deploy:gcp:purge-cdn && npm run smoke:prod","deploy:gcp:full": "npm run build:gcp && npm run deploy:gcp",@@ -264,7 +264,8 @@"install:sdk": "npm install --prefix agent-payments-sdk && npm run build --prefix agent-payments-sdk && npm install ./agent-payments-sdk","claude": "./scripts/claude.sh","typecheck": "tsc -p jsconfig.json",- "okx:bot": "node scripts/okx-bot-revive.mjs"+ "okx:bot": "node scripts/okx-bot-revive.mjs",+ "check:conflicts": "node scripts/check-merge-conflicts.mjs"},"dependencies": {"@0xsplits/splits-sdk": "^6.5.0",diff --git a/public/changelog.json b/public/changelog.jsonindex 90091009e..54cb22361 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-29T05:34:35.007Z",+ "generated_at": "2026-07-29T05:37:48.122Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -190,6 +190,17 @@"infra"]},+ {+ "date": "2026-07-29",+ "type": "update",+ "title": "The fact checker stops timing out, and reads its sources properly",+ "summary": "Paid fact checks had started failing outright with a server error instead of returning a verdict. The cause was in how we try our AI providers: when the first provider accepted a request and then went quiet, we kept waiting on it (and on two more sign-ins to the same provider) until the whole time budget for the check was gone, so the providers that were healthy and ready to answer were never reached. We now stop re-trying a provider that has already gone quiet, and no single provider can eat more than a third of the remaining time while others are still waiting. Checks that used to die at 46 seconds now come back with a real, sourced answer. Alongside that, the checker reads evidence far better: its free Wikipedia source now returns the article's actual opening text instead of a 150-character fragment around a keyword, all three search angles are represented in the sources we examine rather than just the first, and a verdict is now decided by the sources that genuinely address the claim, so evidence that never mentions the claim returns an honest \"not enough evidence\" instead of a misleading \"mixed\". The published accuracy figure on the fact-check page has been cleared until a clean measurement can be taken, because the last one was recorded during the outage above and measured that outage rather than the product.",+ "link": "/fact-check",+ "tags": [+ "fix",+ "improvement"+ ]+ },{"date": "2026-07-29","type": "update",diff --git a/public/features.json b/public/features.jsonindex 6bbe852f4..ef6ec999a 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-29T05:34:34.983Z",+ "generated_at": "2026-07-29T05:37:48.107Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/scripts/check-merge-conflicts.mjs b/scripts/check-merge-conflicts.mjsnew file mode 100644index 000000000..67d766418--- /dev/null+++ b/scripts/check-merge-conflicts.mjs@@ -0,0 +1,93 @@+#!/usr/bin/env node+/**+ * Refuse to build or deploy a tree carrying unresolved merge-conflict markers.+ *+ * Why this exists+ * ---------------+ * This worktree is shared by concurrent agents. On 2026-07-29 one of them ran a+ * `git stash pop`, hit conflicts in seven files, and committed the result+ * wholesale — `<<<<<<< Updated upstream` and friends landed in HEAD across+ * production source (`api/chat/config.js`, `src/avatar-garment.js`,+ * `src/walk-net.js`, `src/garment-taxonomy.js`,+ * `public/studio/launch-panel.js`) and two test files.+ *+ * Nothing caught it. A conflict marker is not a lint rule violation, it is a+ * SYNTAX error, so eslint and vitest report it as an unparseable file rather+ * than as the obvious thing it is — and neither runs on commit. The frontend+ * build would have failed on the `src/` files, but only after the load-bearing+ * step order had already wiped `dist/`, and `api/` handlers are not bundled at+ * build time at all: `api/chat/config.js` would have shipped to Cloud Run and+ * 500'd every chat request at runtime.+ *+ * The check is one `git grep` over tracked files, so it costs milliseconds and+ * runs in `build:gcp` before anything is built. Both the opening and the+ * closing marker must be present for a file to be reported, which is what keeps+ * it quiet: a bare `=======` is an ordinary markdown rule, and `<<<<<<<` at the+ * start of a line is never legitimate source.+ *+ * Usage:+ * node scripts/check-merge-conflicts.mjs # exits 1 on any marker+ */++import { execFileSync } from 'node:child_process';+import { basename } from 'node:path';++// Deliberately built at runtime: a literal in this file would make the script+// match itself, and a self-exclusion by filename is the kind of hole that stops+// working the moment the file is renamed.+const OPEN = '<'.repeat(7);+const CLOSE = '>'.repeat(7);++function git(args) {+ try {+ return execFileSync('git', args, { encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 });+ } catch (err) {+ // `git grep` exits 1 with no output when nothing matches — not an error.+ if (err?.status === 1 && !err.stdout) return '';+ throw err;+ }+}++/** Tracked files carrying `marker` at the start of a line, as a Set of paths. */+function filesWithMarker(marker) {+ const out = git(['grep', '-l', '-F', `${marker} `, '--', '.']);+ return new Set(out.split('\n').filter(Boolean));+}++const self = basename(new URL(import.meta.url).pathname);++// The opening marker alone is the trigger, not the OPEN/CLOSE pair. The same+// 2026-07-29 stash-pop left `character-studio/.gitignore` with two nested+// opening markers, two `=======` separators and NO closing marker at all — a+// pair-matching check calls that file clean, which is precisely backwards: an+// unterminated conflict means the merge was interrupted, so even MORE of the+// file is unaccounted for. `<{7} ` at the start of a line is not valid syntax+// in any language we ship, so matching it alone needs no suppression list.+const opened = filesWithMarker(OPEN);+const closed = filesWithMarker(CLOSE);+const conflicted = [...opened].filter((f) => basename(f) !== self).sort();++if (!conflicted.length) {+ console.log('check:conflicts — no unresolved merge-conflict markers in tracked files');+ process.exit(0);+}++console.error(`\ncheck:conflicts — ${conflicted.length} file(s) carry unresolved merge-conflict markers:\n`);+for (const file of conflicted) {+ const hits = git(['grep', '-n', '-F', `${OPEN} `, '--', file])+ .split('\n')+ .filter(Boolean)+ .map((line) => line.slice(file.length + 1).split(':')[0]);+ // An opening marker with no closing one means the merge stopped partway:+ // call that out, because the missing side is not visible in the diff.+ const truncated = closed.has(file) ? '' : ' [no closing marker — merge left partway]';+ console.error(` ${file} (line${hits.length > 1 ? 's' : ''} ${hits.join(', ')})${truncated}`);+}+console.error(`+Resolve every conflict before building. For each file, open it, pick the+correct side (or merge both), and delete all three marker lines. Verify with:++ node --check <file> # for .js / .mjs+ node scripts/check-merge-conflicts.mjs # re-run this check+`);+process.exit(1);diff --git a/scripts/mobile-touch-audit.mjs b/scripts/mobile-touch-audit.mjsnew file mode 100644index 000000000..69bfac522--- /dev/null+++ b/scripts/mobile-touch-audit.mjs@@ -0,0 +1,390 @@+#!/usr/bin/env node+/**+ * Mobile input-ergonomics audit (prompts/quality-bar/08 task 4).+ *+ * Loads pages in a real mobile Playwright context (default Pixel 5) and reads+ * the LIVE, computed DOM. Nothing here is inferred from source greps, so every+ * finding is a measured box or a resolved computed style.+ *+ * It reports four classes of defect:+ *+ * 1. Touch targets below 44x44 CSS px. Per WCAG 2.5.5 / the Apple and Material+ * guidance, control targets need ~44 px. Inline links that sit inside a run+ * of text are exempt (WCAG 2.5.8 "inline" exception) and are counted+ * separately as `inlineExempt` rather than reported as defects.+ * 2. Canvases and viewer containers whose computed `touch-action` is `auto`.+ * A WebGL viewer that calls preventDefault on pointer moves while+ * touch-action stays `auto` makes orbit gestures fight page scroll; the fix+ * is an explicit `touch-action` (`none` for full orbit control, `pan-y` for+ * a viewer embedded in a scrolling page).+ * 3. Safe-area handling: whether the viewport meta opts into+ * `viewport-fit=cover` (without it `env(safe-area-inset-*)` always resolves+ * to 0), and which bottom-anchored fixed/sticky bars have no CSS rule+ * mentioning `safe-area-inset` applying to them. Those bars land under the+ * iOS home indicator.+ * 4. Horizontal overflow at the mobile viewport width (scrollWidth > clientWidth).+ *+ * Usage:+ * node scripts/mobile-touch-audit.mjs # top-15 preset+ * node scripts/mobile-touch-audit.mjs --pages /,/forge+ * node scripts/mobile-touch-audit.mjs --json out.json --md out.md+ * node scripts/mobile-touch-audit.mjs --base http://localhost:3000+ */++import { mkdirSync, writeFileSync } from 'node:fs';+import { dirname, join, resolve } from 'node:path';+import { fileURLToPath } from 'node:url';+import { chromium, devices } from 'playwright';++const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');++const C = {+ g: (s) => `\x1b[32m${s}\x1b[0m`,+ r: (s) => `\x1b[31m${s}\x1b[0m`,+ y: (s) => `\x1b[33m${s}\x1b[0m`,+ d: (s) => `\x1b[2m${s}\x1b[0m`,+ b: (s) => `\x1b[1m${s}\x1b[0m`,+ c: (s) => `\x1b[36m${s}\x1b[0m`,+};++const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';++const DEFAULT_PAGES = [+ '/',+ '/forge',+ '/markets',+ '/news',+ '/marketplace',+ `/coin/${THREE_MINT}`,+ '/dashboard',+ '/walk',+ '/irl',+ '/ar',+ '/play',+ '/launches',+ '/changelog',+ '/docs/start-here',+];++const MIN_TARGET = 44;++function parseArgs(argv) {+ const out = {+ base: 'https://three.ws',+ pages: null,+ device: 'Pixel 5',+ settle: 6000,+ timeout: 60000,+ json: null,+ md: null,+ label: '',+ };+ for (let i = 2; i < argv.length; i++) {+ const a = argv[i];+ const next = () => argv[++i];+ if (a === '--base') out.base = next().replace(/\/+$/, '');+ else if (a === '--pages') out.pages = next();+ else if (a === '--device') out.device = next();+ else if (a === '--settle') out.settle = Math.max(0, Number(next()) || 0);+ else if (a === '--timeout') out.timeout = Math.max(5000, Number(next()) || 5000);+ else if (a === '--json') out.json = next();+ else if (a === '--md') out.md = next();+ else if (a === '--label') out.label = next();+ }+ return out;+}++// ── Runs inside the page ─────────────────────────────────────────────────────+function auditDom(minTarget) {+ const describe = (el) => {+ const id = el.id ? `#${el.id}` : '';+ const cls =+ typeof el.className === 'string' && el.className.trim()+ ? `.${el.className.trim().split(/\s+/).slice(0, 3).join('.')}`+ : '';+ return `${el.tagName.toLowerCase()}${id}${cls}`;+ };++ const isVisible = (el, cs, box) =>+ cs.display !== 'none' &&+ cs.visibility !== 'hidden' &&+ Number(cs.opacity) > 0.01 &&+ box.width > 0 &&+ box.height > 0;++ // Collect same-origin CSS rules once so we can ask "does any rule that+ // matches this element mention safe-area-inset?".+ const rules = [];+ for (const sheet of Array.from(document.styleSheets)) {+ let list;+ try {+ list = sheet.cssRules;+ } catch {+ continue; // cross-origin sheet, not readable+ }+ const walk = (ruleList) => {+ for (const rule of Array.from(ruleList || [])) {+ if (rule.cssRules) walk(rule.cssRules);+ else if (rule.selectorText && rule.cssText) rules.push(rule);+ }+ };+ walk(list);+ }+ const safeAreaRules = rules.filter((r) => /safe-area-inset/.test(r.cssText));+ const matchesSafeArea = (el) =>+ safeAreaRules.some((r) => {+ try {+ return el.matches(r.selectorText);+ } catch {+ return false;+ }+ });++ const INTERACTIVE =+ 'a[href], button, input, select, textarea, summary, [role="button"], [role="link"], [role="tab"], [role="switch"], [role="checkbox"], [role="menuitem"], [onclick], [tabindex]:not([tabindex="-1"])';++ const smallTargets = [];+ let inlineExempt = 0;+ let checked = 0;++ for (const el of Array.from(document.querySelectorAll(INTERACTIVE))) {+ const cs = getComputedStyle(el);+ const box = el.getBoundingClientRect();+ if (!isVisible(el, cs, box)) continue;+ if (el.closest('[aria-hidden="true"]')) continue;+ checked++;+ const w = box.width;+ const h = box.height;+ if (w >= minTarget && h >= minTarget) continue;++ // WCAG 2.5.8 inline exception: a link inside a sentence.+ const inlineDisplay = cs.display.startsWith('inline');+ const parent = el.parentElement;+ const parentHasText =+ !!parent &&+ Array.from(parent.childNodes).some((n) => n.nodeType === 3 && n.textContent.trim().length > 0);+ if (el.tagName === 'A' && inlineDisplay && parentHasText) {+ inlineExempt++;+ continue;+ }++ smallTargets.push({+ sel: describe(el),+ w: Math.round(w),+ h: Math.round(h),+ text: (el.getAttribute('aria-label') || el.textContent || '').trim().slice(0, 40),+ inNav: !!el.closest('nav, header, footer, [role="navigation"]'),+ fixed: cs.position === 'fixed' || cs.position === 'sticky',+ path: (() => {+ const chain = [];+ let n = el.parentElement;+ for (let i = 0; n && i < 3; i++, n = n.parentElement) chain.unshift(describe(n));+ return chain.join(' > ');+ })(),+ });+ }++ // Canvases and their scroll-gesture posture.+ const canvases = Array.from(document.querySelectorAll('canvas')).map((el) => {+ const cs = getComputedStyle(el);+ const box = el.getBoundingClientRect();+ const wrap = el.parentElement;+ return {+ sel: describe(el),+ w: Math.round(box.width),+ h: Math.round(box.height),+ visible: isVisible(el, cs, box),+ touchAction: cs.touchAction,+ parentSel: wrap ? describe(wrap) : '',+ parentTouchAction: wrap ? getComputedStyle(wrap).touchAction : '',+ };+ });++ // Bottom-anchored bars and their safe-area posture.+ const viewportMeta = document.querySelector('meta[name="viewport"]')?.getAttribute('content') || '';+ const bottomBars = [];+ for (const el of Array.from(document.body.querySelectorAll('*'))) {+ const cs = getComputedStyle(el);+ if (cs.position !== 'fixed' && cs.position !== 'sticky') continue;+ const box = el.getBoundingClientRect();+ if (!isVisible(el, cs, box)) continue;+ const distanceFromBottom = window.innerHeight - box.bottom;+ if (distanceFromBottom > 4 || box.height < 24 || box.width < window.innerWidth * 0.5) continue;+ bottomBars.push({+ sel: describe(el),+ h: Math.round(box.height),+ paddingBottom: cs.paddingBottom,+ bottom: cs.bottom,+ hasSafeAreaRule: matchesSafeArea(el),+ });+ }++ const doc = document.documentElement;+ return {+ title: document.title,+ checked,+ inlineExempt,+ smallTargets,+ canvases,+ viewportMeta,+ viewportFitCover: /viewport-fit\s*=\s*cover/.test(viewportMeta),+ safeAreaRuleCount: safeAreaRules.length,+ bottomBars,+ overflowX: Math.max(0, doc.scrollWidth - doc.clientWidth),+ innerWidth: window.innerWidth,+ };+}++async function auditPage(browser, deviceDescriptor, url, opts) {+ const context = await browser.newContext({ ...deviceDescriptor, serviceWorkers: 'block' });+ const page = await context.newPage();+ let error = null;+ let status = 0;+ try {+ const res = await page.goto(url, { waitUntil: 'domcontentloaded', timeout: opts.timeout });+ status = res?.status() ?? 0;+ await page.waitForLoadState('load', { timeout: 15000 }).catch(() => {});+ await page.waitForTimeout(opts.settle);+ } catch (err) {+ error = String(err.message).split('\n')[0].slice(0, 200);+ }+ let dom = null;+ if (!error) {+ try {+ dom = await page.evaluate(auditDom, MIN_TARGET);+ } catch (err) {+ error = `audit failed: ${String(err.message).slice(0, 160)}`;+ }+ }+ await context.close().catch(() => {});+ return { url, status, error, ...(dom || {}) };+}++function renderMarkdown(report) {+ const { config, results } = report;+ const rows = [...results]+ .sort((a, b) => (b.smallTargets?.length ?? 0) - (a.smallTargets?.length ?? 0))+ .map((r) => {+ const canvasNoTouch = (r.canvases || []).filter((c) => c.visible && c.touchAction === 'auto').length;+ const barsNoSafe = (r.bottomBars || []).filter((b) => !b.hasSafeAreaRule).length;+ return `| \`${r.path}\` | ${r.smallTargets?.length ?? '-'} | ${r.checked ?? '-'} | ${+ r.inlineExempt ?? '-'+ } | ${canvasNoTouch}/${(r.canvases || []).filter((c) => c.visible).length} | ${+ r.viewportFitCover ? 'yes' : 'NO'+ } | ${barsNoSafe}/${(r.bottomBars || []).length} | ${r.overflowX ?? '-'} px |`;+ });++ const detail = [...results]+ .sort((a, b) => (b.smallTargets?.length ?? 0) - (a.smallTargets?.length ?? 0))+ .filter((r) => (r.smallTargets?.length || 0) > 0 || (r.bottomBars?.length || 0) > 0 || r.overflowX > 0)+ .map((r) => {+ const groups = new Map();+ for (const t of r.smallTargets || []) {+ const key = `${t.sel} ${t.w}x${t.h}`;+ groups.set(key, (groups.get(key) || 0) + 1);+ }+ const lines = [...groups.entries()]+ .sort((a, b) => b[1] - a[1])+ .slice(0, 12)+ .map(([k, n]) => ` - ${n}x \`${k}\``);+ const bars = (r.bottomBars || []).map(+ (b) => ` - \`${b.sel}\` h=${b.h} padding-bottom=${b.paddingBottom} safe-area-rule=${b.hasSafeAreaRule}`,+ );+ const cans = (r.canvases || [])+ .filter((c) => c.visible)+ .map((c) => ` - \`${c.sel}\` ${c.w}x${c.h} touch-action=${c.touchAction} (parent ${c.parentTouchAction})`);+ return `### \`${r.path}\`++${lines.length ? `- undersized targets:\n${lines.join('\n')}\n` : '- undersized targets: none\n'}${+ cans.length ? `- visible canvases:\n${cans.join('\n')}\n` : ''+ }${bars.length ? `- bottom-anchored bars:\n${bars.join('\n')}\n` : ''}${+ r.overflowX > 0 ? `- horizontal overflow: ${r.overflowX} px beyond ${r.innerWidth} px viewport\n` : ''+ }`;+ });++ return `# Mobile input-ergonomics audit${config.label ? ` - ${config.label}` : ''}++Measured with \`scripts/mobile-touch-audit.mjs\` against ${config.base} in a real+${config.device} Playwright context (Chromium). Every value below is a live computed style or a+measured bounding box, not a source grep.++- Minimum target size checked: ${MIN_TARGET}x${MIN_TARGET} CSS px+- Inline text links are exempt (WCAG 2.5.8) and counted separately+- Measured: ${config.startedAt}++| path | undersized targets | interactive checked | inline-exempt | canvases touch-action:auto / visible | viewport-fit=cover | bottom bars w/o safe-area / total | overflow-x |+|---|---|---|---|---|---|---|---|+${rows.join('\n')}++## Detail++${detail.join('\n')}+`;+}++async function main() {+ const opts = parseArgs(process.argv);+ const deviceDescriptor = devices[opts.device];+ if (!deviceDescriptor) {+ console.error(C.r(`unknown --device "${opts.device}"`));+ process.exit(2);+ }+ const paths = (opts.pages ? opts.pages.split(',').map((p) => p.trim()).filter(Boolean) : DEFAULT_PAGES).map((p) =>+ p.startsWith('/') ? p : `/${p}`,+ );++ const config = {+ base: opts.base,+ device: opts.device,+ label: opts.label,+ startedAt: new Date().toISOString(),+ harness: 'scripts/mobile-touch-audit.mjs',+ minTarget: MIN_TARGET,+ };++ console.log(C.b('\nmobile-touch-audit') + C.d(` ${config.base} @ ${config.device}\n`));+ const browser = await chromium.launch({ headless: true });+ const results = [];+ try {+ for (const path of paths) {+ const r = await auditPage(browser, deviceDescriptor, `${opts.base}${path}`, opts);+ r.path = path;+ results.push(r);+ if (r.error) {+ console.log(` ${C.c(path.padEnd(52))} ${C.r(r.error)}`);+ } else {+ const canvasNoTouch = (r.canvases || []).filter((c) => c.visible && c.touchAction === 'auto').length;+ const barsNoSafe = (r.bottomBars || []).filter((b) => !b.hasSafeAreaRule).length;+ const bad = r.smallTargets.length + canvasNoTouch + barsNoSafe + (r.overflowX > 0 ? 1 : 0);+ console.log(+ ` ${C.c(path.padEnd(52))} ${bad === 0 ? C.g('clean') : C.y(`${r.smallTargets.length} small targets`)}` ++ C.d(+ ` canvas-auto ${canvasNoTouch} bottombars-unsafe ${barsNoSafe} overflowX ${r.overflowX} vfc ${r.viewportFitCover}`,+ ),+ );+ }+ }+ } finally {+ await browser.close().catch(() => {});+ }++ const report = { config, results };+ if (opts.json) {+ const p = resolve(ROOT, opts.json);+ mkdirSync(dirname(p), { recursive: true });+ writeFileSync(p, JSON.stringify(report, null, 2));+ console.log(C.g(`\n wrote ${p}`));+ }+ if (opts.md) {+ const p = resolve(ROOT, opts.md);+ mkdirSync(dirname(p), { recursive: true });+ writeFileSync(p, renderMarkdown(report));+ console.log(C.g(` wrote ${p}`));+ }+ process.exit(results.some((r) => !r.error) ? 0 : 1);+}++main().catch((err) => {+ console.error(C.r(`mobile-touch-audit failed: ${err.stack || err.message}`));+ process.exit(1);+});diff --git a/src/forge-timeline.js b/src/forge-timeline.jsnew file mode 100644index 000000000..3893b0648--- /dev/null+++ b/src/forge-timeline.js@@ -0,0 +1,494 @@+// Forge generation timeline: the named, evidence-driven stage list shown while+// a model is being made (#state-generating on /forge).+//+// The rule this module exists to enforce: EVERY stage transition is caused by a+// real signal from /api/forge, never by a timer. The pipeline reports exactly+// these things and nothing more:+//+// POST /api/forge → { status, backend, tier, path, mode, prompt,+// directed_prompt?, preview_image_url?,+// reference_image_urls?, text_to_image_model?,+// cold_start?, eta_seconds?, coalesced? }+// GET /api/forge?job=… → { status: queued|running|done|failed, backend,+// tier, path, preview_image_url?, failover_from? }+//+// So the honest mapping is:+// • "Art-directing your prompt": the server runs the Granite director before+// the POST resolves; proof of completion is `directed_prompt` on the response+// (or its absence, which means the model got the prompt verbatim).+// • "Painting the reference view": proof is `preview_image_url`. It can arrive+// on the POST, or later on a poll (coalesced job, resumed job, failover+// successor), and is revealed the moment it exists.+// • "Sculpting the mesh": `status: queued` vs `running`. The GPU+// workers report no sub-steps, so this stays ONE stage: no invented+// "texturing" phase, just the queue/running distinction plus the honest+// elapsed meter that forge.js drives.+// • "Finalizing": the done payload landed and the viewer is+// loading the GLB. Completed when the model is on screen.+//+// A lane that skips a stage never shows it: the free NVIDIA NIM lane emits the+// mesh straight from the prompt (no director, no reference view), so its+// timeline has three rows, not five.+//+// Cold starts get their own designed state instead of a silent stall: `cold_start`+// on the submit response means the chosen self-host worker was reached but+// answered slowly (scale-to-zero container booting). The warm-up budget shown is+// the real difference between the response's cold ETA and the catalog's warm ETA+// and it ends on a real signal (the first `running` poll), never on the clock.++const STAGE_ORDER = ['direct', 'reference', 'input', 'mesh', 'finish'];++// A tiny inline "open in a new tab" affordance is overkill for a 30px thumb; the+// anchor itself is the affordance and carries its own aria-label.+function thumbHTML(url, alt) {+ return `<img src="${url}" alt="${alt}" loading="lazy" decoding="async" />`;+}++function plural(n, one, many) {+ return n === 1 ? one : many;+}++export function createForgeTimeline({ list, preview, warming, engineLabel = (id) => id }) {+ // Facts accumulated from real responses. Nothing here is ever guessed.+ let f = blankFacts();+ // Rendered rows keyed by stage id, so a re-render updates text in place+ // instead of rebuilding the list (no flicker, no re-announcing every row to+ // a screen reader, and CSS transitions survive).+ const rows = new Map();+ let previewUrlShown = null;++ function blankFacts() {+ return {+ mode: 'text', // text | image | sketch+ viewCount: 0,+ localPreviewUrl: null, // user's own photo/sketch, known before submit+ plannedBackend: null,+ backend: null,+ plannedReference: true, // does this lane paint a reference view?+ hasReference: false,+ referenceUrl: null,+ directedPrompt: null,+ directorRan: false, // the submit response came back, so the pass is over+ submitted: false,+ resumed: false,+ status: 'submitting', // submitting | queued | running | finalizing | done | failed+ coldStart: false,+ coldSeconds: null,+ etaSeconds: null,+ queuedSeconds: 0,+ failoverFrom: null,+ elapsedS: 0,+ };+ }++ // ── Stage model ──────────────────────────────────────────────────────────+ function stages() {+ const out = [];+ const meshRunning = f.status === 'running';+ const meshQueued = f.status === 'queued';+ const meshStarted = f.submitted || f.resumed;+ const terminal = f.status === 'done' || f.status === 'finalizing';++ if (f.mode === 'sketch') {+ out.push({+ id: 'input',+ label: 'Your drawing',+ detail: 'Uploaded and used as the reference, no image is synthesized',+ state: 'done',+ thumb: f.localPreviewUrl,+ thumbAlt: 'Your uploaded drawing',+ });+ } else if (f.mode === 'image') {+ const n = Math.max(1, f.viewCount);+ out.push({+ id: 'input',+ label: `Conditioning on ${n} reference ${plural(n, 'view', 'views')}`,+ detail: n > 1 ? 'The engine fuses every view into one mesh' : 'Reconstructing straight from your photo',+ state: 'done',+ thumb: f.localPreviewUrl || f.referenceUrl,+ thumbAlt: 'Your uploaded reference view',+ });+ } else if (f.plannedReference || f.hasReference) {+ // Text → 3D through a reference view: the director rewrites the prompt,+ // then a text-to-image model paints the view the mesh is built from.+ out.push({+ id: 'direct',+ label: f.directorRan+ ? f.directedPrompt+ ? 'Prompt art-directed'+ : 'Prompt used as you wrote it'+ : 'Art-directing your prompt',+ detail: f.directorRan+ ? f.directedPrompt+ ? 'Expanded with materials, lighting and composition cues. See it with your model'+ : 'The director left it unchanged, so the model saw your exact words'+ : 'Rewriting it into a single-subject brief with material and lighting cues',+ state: f.directorRan ? 'done' : 'active',+ });+ out.push({+ id: 'reference',+ label: f.hasReference ? 'Reference view painted' : 'Painting the reference view',+ detail: f.hasReference+ ? 'This is the image the mesh is reconstructed from'+ : 'A photoreal single view the reconstructor can read cleanly',+ state: f.hasReference ? 'done' : f.directorRan ? 'active' : 'pending',+ thumb: f.hasReference ? f.referenceUrl : null,+ thumbAlt: 'The reference view painted from your prompt',+ });+ } else {+ out.push({+ id: 'input',+ label: f.submitted ? 'Prompt accepted' : 'Sending your prompt',+ detail: `${engineLabel(f.backend || f.plannedBackend)} builds the mesh straight from text, with no reference image in this lane`,+ state: f.submitted ? 'done' : 'active',+ });+ }++ out.push({+ id: 'mesh',+ label: meshLabel(),+ detail: meshDetail(),+ state: terminal ? 'done' : meshStarted && (meshQueued || meshRunning) ? 'active' : meshStarted ? 'active' : 'pending',+ });++ out.push({+ id: 'finish',+ label: f.status === 'done' ? 'Model ready' : 'Finalizing the GLB',+ detail:+ f.status === 'done'+ ? 'Saved to your creations and loaded in the viewer'+ : f.status === 'finalizing'+ ? 'Compressing, scoring quality and loading it into the viewer'+ : 'Durable copy, quality score, then straight into the viewer',+ state: f.status === 'done' ? 'done' : f.status === 'finalizing' ? 'active' : 'pending',+ });++ return out.sort((a, b) => STAGE_ORDER.indexOf(a.id) - STAGE_ORDER.indexOf(b.id));+ }++ function meshLabel() {+ const engine = engineLabel(f.backend || f.plannedBackend);+ if (f.mode === 'sketch') return `Sculpting geometry from your drawing on ${engine}`;+ return `Sculpting the textured mesh on ${engine}`;+ }++ function meshDetail() {+ if (f.status === 'failed') return 'The lane reported a failure';+ if (f.failoverFrom) {+ return `${engineLabel(f.failoverFrom)} hit a snag, so ${engineLabel(f.backend)} picked the job up`;+ }+ if (f.status === 'queued') {+ if (f.coldStart) return 'Waiting on a GPU worker that is still booting';+ return f.queuedSeconds >= 8+ ? 'In line for a GPU. Earlier jobs finish first, nothing is downgraded'+ : 'Accepted, waiting for a GPU slot';+ }+ if (f.status === 'running') {+ // The workers expose queued/running only (no per-step progress), so this+ // says what the stage covers rather than pretending to track it.+ return 'Geometry and textures in one pass. The engine reports no sub-steps, so the elapsed meter below is the real signal.';+ }+ if (f.status === 'done' || f.status === 'finalizing') return 'Mesh delivered';+ return 'Starts as soon as the job is accepted';+ }++ // ── Rendering ────────────────────────────────────────────────────────────+ function render() {+ if (!list) return;+ const wanted = stages();+ const seen = new Set();+ for (const st of wanted) {+ seen.add(st.id);+ let row = rows.get(st.id);+ if (!row) {+ row = buildRow(st.id);+ rows.set(st.id, row);+ list.appendChild(row.el);+ }+ if (row.el.dataset.state !== st.state) row.el.dataset.state = st.state;+ if (row.label.textContent !== st.label) row.label.textContent = st.label;+ const detail = st.detail || '';+ if (row.detail.textContent !== detail) row.detail.textContent = detail;+ row.detail.hidden = !detail;+ renderThumb(row, st);+ }+ for (const [id, row] of rows) {+ if (seen.has(id)) continue;+ row.el.remove();+ rows.delete(id);+ }+ // Keep DOM order in sync with the stage order after an insert.+ for (const st of wanted) {+ const row = rows.get(st.id);+ if (row) list.appendChild(row.el);+ }+ }++ function buildRow(id) {+ const el = document.createElement('li');+ el.className = 'step';+ el.dataset.stage = id;+ el.dataset.state = 'pending';+ el.innerHTML =+ '<span class="dot" aria-hidden="true"></span>' ++ '<span class="step-body"><span class="step-label"></span><span class="step-detail"></span></span>';+ return {+ el,+ label: el.querySelector('.step-label'),+ detail: el.querySelector('.step-detail'),+ thumb: null,+ };+ }++ function renderThumb(row, st) {+ if (!st.thumb) {+ if (row.thumb) {+ row.thumb.remove();+ row.thumb = null;+ }+ return;+ }+ if (!row.thumb) {+ const a = document.createElement('a');+ a.className = 'step-thumb';+ a.target = '_blank';+ a.rel = 'noopener noreferrer';+ row.thumb = a;+ row.el.appendChild(a);+ }+ if (row.thumb.dataset.src !== st.thumb) {+ row.thumb.dataset.src = st.thumb;+ row.thumb.href = st.thumb;+ row.thumb.setAttribute('aria-label', `${st.thumbAlt || 'Reference view'}. Opens the full image in a new tab`);+ row.thumb.title = 'Open the full reference view';+ row.thumb.innerHTML = thumbHTML(st.thumb, st.thumbAlt || 'Reference view');+ }+ }++ // The big square preview above the stage list. Shows the shimmer skeleton+ // until a real image exists, then paints it in (CSS handles the motion-safe+ // reveal) and runs the reconstruction scanline while the mesh stage is live.+ function renderPreview() {+ if (!preview) return;+ const url = f.referenceUrl || f.localPreviewUrl || null;+ const meshLive = (f.status === 'queued' || f.status === 'running') && (f.submitted || f.resumed);+ preview.classList.toggle('is-reconstructing', Boolean(meshLive));+ if (!url) {+ if (previewUrlShown !== null) {+ previewUrlShown = null;+ preview.innerHTML = '<div class="shimmer" aria-hidden="true"></div>';+ } else if (!preview.firstChild) {+ preview.innerHTML = '<div class="shimmer" aria-hidden="true"></div>';+ }+ return;+ }+ if (previewUrlShown === url) return;+ previewUrlShown = url;+ const img = new Image();+ img.alt = f.mode === 'sketch' ? 'Your drawing' : f.hasReference ? 'Reference view painted from your prompt' : 'Your reference photo';+ img.src = url;+ img.onload = () => {+ if (previewUrlShown !== url) return;+ preview.replaceChildren(img);+ };+ img.onerror = () => {+ // A broken reference URL must not leave a half-state: fall back to the+ // skeleton and let the stage row keep the honest label.+ if (previewUrlShown !== url) return;+ previewUrlShown = null;+ preview.innerHTML = '<div class="shimmer" aria-hidden="true"></div>';+ };+ }++ // ── Cold-start warming state ─────────────────────────────────────────────+ function renderWarming() {+ if (!warming) return;+ const active = f.coldStart && (f.status === 'queued' || f.status === 'submitting');+ warming.classList.toggle('is-hidden', !active);+ if (!active) {+ warming.dataset.phase = 'off';+ return;+ }+ const title = warming.querySelector('.gen-warming-title');+ const body = warming.querySelector('.gen-warming-body');+ const count = warming.querySelector('.gen-warming-count');+ const budget = f.coldSeconds;+ const left = budget ? Math.round(budget - f.elapsedS) : null;+ const over = left != null && left <= 0;+ warming.dataset.phase = over ? 'over' : 'warming';+ const engine = engineLabel(f.backend || f.plannedBackend);+ const nextTitle = over ? 'Still waking the GPU' : 'Waking up a GPU';+ if (title.textContent !== nextTitle) title.textContent = nextTitle;+ const nextBody = over+ ? `${engine} is taking longer than its usual boot. Your job is accepted and queued: it starts the moment the worker answers, and nothing is lost in the meantime.`+ : `${engine} scales to zero when nobody is using it, so this request is booting a container. Your job is already accepted and starts the second the worker is up.`;+ if (body.textContent !== nextBody) body.textContent = nextBody;+ const nextCount = over+ ? 'Past the usual boot time. Still waiting on the worker'+ : left != null+ ? `~${left}s of warm-up left, then sculpting starts`+ : 'First request after an idle spell, so the worker is booting';+ if (count.textContent !== nextCount) count.textContent = nextCount;+ }++ function paint() {+ render();+ renderPreview();+ renderWarming();+ }++ // ── Public API ───────────────────────────────────────────────────────────+ return {+ /**+ * Start a fresh timeline for a submission. Everything passed here is known+ * client-side before the request goes out; the server's answer refines it.+ */+ begin({ mode, backend, viewCount = 0, localPreviewUrl = null, usesReference = true }) {+ f = blankFacts();+ f.mode = mode;+ f.plannedBackend = backend;+ f.backend = backend;+ f.viewCount = viewCount;+ f.localPreviewUrl = localPreviewUrl;+ f.plannedReference = mode === 'text' ? usesReference : false;+ previewUrlShown = null;+ rows.forEach((row) => row.el.remove());+ rows.clear();+ if (preview) preview.innerHTML = '<div class="shimmer" aria-hidden="true"></div>';+ paint();+ },++ /** Restore the timeline for a job that survived a reload (resumeInflight). */+ resume({ backend, referenceUrl = null, mode = 'text', elapsedS = 0 }) {+ f = blankFacts();+ f.mode = mode;+ f.plannedBackend = backend;+ f.backend = backend;+ f.resumed = true;+ f.submitted = true;+ f.directorRan = true;+ f.status = 'running';+ f.elapsedS = elapsedS;+ f.plannedReference = Boolean(referenceUrl);+ if (referenceUrl) {+ f.hasReference = true;+ f.referenceUrl = referenceUrl;+ }+ previewUrlShown = null;+ rows.forEach((row) => row.el.remove());+ rows.clear();+ paint();+ return f.etaSeconds;+ },++ /**+ * Apply the POST /api/forge response. `warmEtaSeconds` is the catalog's+ * warm estimate for the lane that actually ran, so the cold-start budget is+ * a real difference of two real numbers rather than a made-up countdown.+ */+ applySubmit(job, { warmEtaSeconds = null } = {}) {+ f.submitted = true;+ f.directorRan = true;+ if (job?.backend) f.backend = job.backend;+ if (typeof job?.directed_prompt === 'string' && job.directed_prompt.trim()) {+ f.directedPrompt = job.directed_prompt.trim();+ }+ const ref =+ (typeof job?.preview_image_url === 'string' && job.preview_image_url) ||+ (Array.isArray(job?.reference_image_urls) && job.reference_image_urls[0]) ||+ null;+ if (ref && f.mode === 'text') {+ f.hasReference = true;+ f.referenceUrl = ref;+ f.plannedReference = true;+ } else if (f.mode === 'text' && job?.status && !ref && !job?.coalesced) {+ // The lane answered without a reference view: it generates the mesh+ // straight from the prompt. Drop the reference stages rather than+ // leaving a row that will never complete.+ f.plannedReference = false;+ }+ if (Number(job?.eta_seconds) > 0) f.etaSeconds = Math.round(Number(job.eta_seconds));+ f.coldStart = Boolean(job?.cold_start);+ if (f.coldStart) {+ const warm = Number(warmEtaSeconds) > 0 ? Number(warmEtaSeconds) : null;+ const gap = warm && f.etaSeconds ? f.etaSeconds - warm : null;+ f.coldSeconds = gap && gap > 0 ? Math.round(gap) : null;+ }+ f.status = job?.status === 'done' ? 'finalizing' : job?.status === 'running' ? 'running' : 'queued';+ paint();+ return { etaSeconds: f.etaSeconds, directedPrompt: f.directedPrompt, referenceUrl: f.referenceUrl };+ },++ /** Apply one GET /api/forge?job=… poll payload. */+ applyPoll(data) {+ if (!data) return;+ if (data.backend) f.backend = data.backend;+ if (data.failover_from && data.backend && data.failover_from !== data.backend) {+ f.failoverFrom = data.failover_from;+ }+ // The reference view can first become visible here: a coalesced job, a+ // resumed session, or a failover successor never saw the submit payload.+ if (typeof data.preview_image_url === 'string' && data.preview_image_url && !f.hasReference) {+ f.hasReference = true;+ f.referenceUrl = data.preview_image_url;+ if (f.mode === 'text') f.plannedReference = true;+ }+ if (data.status === 'queued') {+ f.status = 'queued';+ f.queuedSeconds += 1;+ } else if (data.status === 'running') {+ f.status = 'running';+ f.queuedSeconds = 0;+ // A worker that answers "running" is up: the cold start is over, and+ // that is a real signal, not a timer expiring.+ f.coldStart = false;+ } else if (data.status === 'done') {+ f.status = 'finalizing';+ } else if (data.status === 'failed') {+ f.status = 'failed';+ }+ paint();+ },++ /** The GLB landed; the client is loading it into the viewer. */+ finalizing() {+ f.status = 'finalizing';+ paint();+ },++ /** The model is on screen. */+ complete() {+ f.status = 'done';+ f.coldStart = false;+ paint();+ },++ /** Terminal failure: freeze the rows where they are, drop the warming card. */+ fail() {+ f.status = 'failed';+ f.coldStart = false;+ paint();+ },++ /** Called once a second by the elapsed timer in forge.js. No state changes. */+ tick(elapsedS) {+ f.elapsedS = elapsedS;+ renderWarming();+ },++ /** The honest ETA the server reported for this job, or null. */+ etaSeconds() {+ return f.etaSeconds;+ },++ /** The art-directed prompt for the current job, or null. */+ directedPrompt() {+ return f.directedPrompt;+ },++ /** Is the current job on a cold (booting) worker? */+ isCold() {+ return f.coldStart;+ },+ };+}diff --git a/src/game/avatar-upload.js b/src/game/avatar-upload.jsindex dce53db3f..125741ec4 100644--- a/src/game/avatar-upload.js+++ b/src/game/avatar-upload.js@@ -19,6 +19,20 @@ import { getMeshoptDecoder } from '../viewer/internal.js';export const MAX_GLB_BYTES = 16 * 1024 * 1024;export const MAX_GLB_MB = MAX_GLB_BYTES / (1024 * 1024);+// World props (P3.3) are downloaded by EVERY player in the world, not just the+// person who chose them, so their budget is tighter than an avatar's. Mirrors+// PROP_ASSET_MAX_BYTES in multiplayer/src/build-limits.js.+export const MAX_PROP_BYTES = 8 * 1024 * 1024;+export const MAX_PROP_MB = MAX_PROP_BYTES / (1024 * 1024);+// A prop that is metres across in every direction is a griefing wall, not a+// decoration; one that is sub-millimetre is an invisible placement. Both are+// rejected up front with a reason the uploader can act on.+const PROP_MAX_EXTENT_M = 40;+const PROP_MIN_EXTENT_M = 0.01;+// Triangle budget: one world can hold MAX_WORLD_OBJECTS props, so a single+// uploaded model has to stay inside a frame budget everyone else pays for too.+const PROP_MAX_TRIANGLES = 300_000;+const GLB_CONTENT_TYPE = 'model/gltf-binary';const _loader = new GLTFLoader();// three.ws GLBs may carry EXT_meshopt_compression — decoder required before load@@ -69,6 +83,80 @@ export async function validateGlb(file) {}}+// ── world props (P3.3) ───────────────────────────────────────────────────────+// A prop is validated harder than an avatar because everyone in the world pays+// for it: tighter size cap, a triangle budget, and a real bounding-box sanity+// check so a mis-exported model can't be dropped in as a kilometre-wide wall.+// Reuses the same parse-before-upload discipline as validateGlb — nothing reaches+// storage until it has been proven to be a renderable model right here.++/**+ * Validate `file` as a placeable world prop.+ * Accepts .glb and .vrm (a VRM file is a glTF binary — see vrm-loader.js).+ * @throws {Error} with a user-facing message on rejection+ * @returns {Promise<{bytes:number, height:number, extent:number, triangles:number, vrm:boolean}>}+ */+export async function validatePropModel(file) {+ if (!file) throw new Error('No file selected.');+ const name = (file.name || '').toLowerCase();+ const isVrm = name.endsWith('.vrm');+ if (!name.endsWith('.glb') && !isVrm) {+ throw new Error('Props must be .glb or .vrm — those bundle meshes and textures into one file. Export your model as GLB and try again.');+ }+ if (file.size < 64) throw new Error('That file is empty.');+ if (file.size > MAX_PROP_BYTES) {+ throw new Error(`That model is ${(file.size / (1024 * 1024)).toFixed(1)} MB — props are capped at ${MAX_PROP_MB} MB so they load fast for everyone in the world. Decimate the mesh or shrink its textures.`);+ }++ await _meshoptReady;+ let gltf;+ try {+ gltf = await _loader.parseAsync(await file.arrayBuffer(), '');+ } catch {+ throw new Error('That file could not be read as a 3D model — it may be corrupt or not actually a GLB/VRM.');+ }++ try {+ let hasMesh = false;+ let triangles = 0;+ gltf.scene.traverse((n) => {+ if (!n.isMesh || !n.geometry) return;+ hasMesh = true;+ const g = n.geometry;+ const count = g.index ? g.index.count : (g.attributes?.position?.count || 0);+ triangles += Math.floor(count / 3);+ });+ if (!hasMesh) throw new Error('That model has no visible geometry.');+ if (triangles > PROP_MAX_TRIANGLES) {+ throw new Error(`That model has ${triangles.toLocaleString()} triangles — props are capped at ${PROP_MAX_TRIANGLES.toLocaleString()} so a world full of them still runs smoothly. Decimate it and try again.`);+ }++ const size = new Vector3();+ new Box3().setFromObject(gltf.scene).getSize(size);+ const extent = Math.max(size.x, size.y, size.z);+ if (!Number.isFinite(extent) || extent <= 0) throw new Error('That model has no measurable size.');+ if (extent < PROP_MIN_EXTENT_M) {+ throw new Error('That model is smaller than a millimetre across — re-export it at a real-world scale (metres).');+ }+ if (extent > PROP_MAX_EXTENT_M) {+ throw new Error(`That model is ${Math.round(extent)} m across — props are capped at ${PROP_MAX_EXTENT_M} m. Re-export it at a real-world scale (metres).`);+ }++ return { bytes: file.size, height: size.y, extent, triangles, vrm: isVrm };+ } finally {+ disposeScene(gltf.scene);+ }+}++/**+ * Upload a validated world prop and return its public URL. Same presigned-PUT+ * path as an avatar (api/avatar/presign-glb) — one storage pipeline, one set of+ * server-side limits — so the resulting url passes the room's asset allow-list.+ */+export async function uploadPropModel(file, onProgress) {+ return uploadGlb(file, onProgress);+}+// PUT the file to a presigned URL, reporting progress (0..1) along the way.function putWithProgress(url, file, onProgress) {return new Promise((resolve, reject) => {diff --git a/src/game/world-persist.js b/src/game/world-persist.jsnew file mode 100644index 000000000..33f0e8bfb--- /dev/null+++ b/src/game/world-persist.js@@ -0,0 +1,240 @@+// world-persist — the browser's half of the per-world build store (P3.1).+//+// `/play` builds into two different authorities depending on the connection:+//+// • ONLINE (a live `walk_world` room). The Colyseus room is authoritative for+// every object and writes the durable doc itself with a service token+// (multiplayer/src/persistence.js → /api/world/save). The browser must NOT+// write in this mode — two writers on one doc is how builds get clobbered —+// so this module is only ever armed while the room is not the authority.+//+// • SOLO / PRE-JOIN (the room is unreachable, or we're still connecting). The+// world's persisted build is still a real, shared place: this module reads it+// straight from the same store (GET /api/world/load) so the player walks into+// the community's creation instead of an empty plaza, and writes back through+// POST /api/world/save with the etag it read, so a build made offline survives+// and shows up for everyone the next time the room boots.+//+// Concurrency is the store's own optimistic-etag model: we send the etag we last+// read as `ifMatch`; a 409 means someone else moved the doc, so we re-read and+// re-run the producer against the FRESH doc (the producer merges — it never+// blindly overwrites) and commit once more. Permission failures (401 anonymous,+// 403 not this world's owner) are terminal for the session and reported through+// `onDenied` so the HUD can stop promising the build is saved.+//+// Storage contract, kept identical to the server's so both writers agree:+// doc = { objects: [ { id, type, kind, ownerId, x, y, z, yaw, scale, url? } ] }++import { log } from '../shared/log.js';++// Matches SAVE_DEBOUNCE_MS in multiplayer/src/persistence.js — a burst of+// placements coalesces into one write, exactly like the server's.+export const WORLD_SAVE_DEBOUNCE_MS = 4000;++/**+ * The store key for a coin world. Mirrors WalkRoom's `worldKey` byte-for-byte+ * (multiplayer/src/rooms/WalkRoom.js) so the browser and the room read and write+ * the SAME document — a different key here would silently fork the build.+ * @param {string} mint coin mint address, '' for the mainland world+ * @param {string} [tier] 'holders' for a coin's gated tier+ */+export function worldIdForCoin(mint, tier = '') {+ const coin = typeof mint === 'string' ? mint.trim() : '';+ if (!coin) return 'mainland';+ return tier === 'holders' ? `${coin}#holders` : coin;+}++/** Objects out of a loaded doc, shape-checked. Never throws on a malformed doc. */+export function docObjects(doc) {+ const list = Array.isArray(doc?.objects) ? doc.objects : [];+ const out = [];+ for (const o of list) {+ if (!o || typeof o.id !== 'string' || !o.id) continue;+ if (![o.x, o.y, o.z].every((n) => Number.isFinite(n))) continue;+ out.push({+ id: o.id,+ type: typeof o.type === 'string' ? o.type : '',+ kind: typeof o.kind === 'string' && o.kind ? o.kind : 'prop',+ ownerId: typeof o.ownerId === 'string' ? o.ownerId : '',+ x: o.x, y: o.y, z: o.z,+ yaw: Number.isFinite(o.yaw) ? o.yaw : 0,+ scale: Number.isFinite(o.scale) && o.scale > 0 ? o.scale : 1,+ url: typeof o.url === 'string' ? o.url : '',+ });+ }+ return out;+}++// Turn a save response into the one word the caller needs to act on.+function outcomeOf(status) {+ if (status >= 200 && status < 300) return 'ok';+ if (status === 409) return 'conflict';+ if (status === 401 || status === 403) return 'denied';+ if (status === 413) return 'too_large';+ return 'error';+}++/**+ * A single world's durable document, as seen from the browser.+ *+ * Lifecycle: `load()` once on entering the world, `queueSave(produce)` on every+ * change while this client is the writer, `flush()` before the tab goes away,+ * `dispose()` on leaving the world.+ */+export class WorldBuildStore {+ /**+ * @param {object} opts+ * @param {string} opts.worldId+ * @param {typeof fetch} [opts.fetchImpl] injectable for tests+ * @param {number} [opts.debounceMs]+ * @param {(info:{reason:string,status:number,message:string})=>void} [opts.onDenied]+ * @param {(info:{reason:string,status:number})=>void} [opts.onError]+ * @param {()=>void} [opts.onSaved]+ */+ constructor({ worldId, fetchImpl, debounceMs = WORLD_SAVE_DEBOUNCE_MS, onDenied, onError, onSaved } = {}) {+ this.worldId = worldId;+ this._fetch = fetchImpl || ((...a) => fetch(...a));+ this._debounceMs = debounceMs;+ this._onDenied = onDenied || null;+ this._onError = onError || null;+ this._onSaved = onSaved || null;+ this.etag = null;+ this.version = 0;+ this.ownerId = null;+ this.doc = null;+ // Terminal for this session once the store refuses our identity: retrying a+ // 403 on every placement would spam the API and lie to the player twice.+ this.denied = false;+ this.lastError = null;+ this._produce = null;+ this._timer = null;+ this._inFlight = null;+ this._disposed = false;+ }++ /** Has a real round-trip proven this client can write? Drives the HUD badge. */+ get writable() { return !this.denied; }++ /**+ * Read the world's current document. Never throws: a network failure resolves+ * with `doc: null` and an `error` so the caller can render the offline state+ * instead of a broken world.+ * @returns {Promise<{doc:object|null, etag:string|null, version:number, error:string|null}>}+ */+ async load() {+ const url = `/api/world/load?worldId=${encodeURIComponent(this.worldId)}`;+ try {+ const res = await this._fetch(url, { headers: { accept: 'application/json' } });+ if (!res.ok) throw new Error(`HTTP ${res.status}`);+ const body = await res.json();+ this.etag = body.etag ?? null;+ this.version = Number(body.version) || 0;+ this.ownerId = body.ownerId ?? null;+ this.doc = body.doc ?? null;+ this.lastError = null;+ return { doc: this.doc, etag: this.etag, version: this.version, error: null };+ } catch (err) {+ const message = err?.message || 'load failed';+ this.lastError = message;+ log.warn('[world-persist] load failed', this.worldId, message);+ return { doc: null, etag: null, version: 0, error: message };+ }+ }++ /**+ * Record the producer for this world and arm a debounced durable write.+ * Synchronous so a placement never awaits the network.+ * @param {(base:object|null)=>object} produce called at flush time with the+ * freshest known doc; must MERGE onto it and return the doc to save.+ */+ queueSave(produce) {+ if (typeof produce !== 'function') {+ throw new TypeError('WorldBuildStore.queueSave(produce): produce must be a function returning the doc');+ }+ if (this._disposed || this.denied) return;+ this._produce = produce;+ if (this._timer) return;+ this._timer = setTimeout(() => { this._timer = null; this.flush().catch(() => {}); }, this._debounceMs);+ }++ /** Is a write pending (debounce armed or in flight)? */+ get pending() { return !!this._timer || !!this._inFlight; }++ /**+ * Write the current doc now. Safe to call at any time; coalesces with an+ * in-flight write so a flush during a save doesn't double-post.+ * @returns {Promise<'ok'|'conflict'|'denied'|'too_large'|'error'|'idle'>}+ */+ async flush() {+ if (this._timer) { clearTimeout(this._timer); this._timer = null; }+ if (this._disposed || this.denied || !this._produce) return 'idle';+ if (this._inFlight) return this._inFlight;+ this._inFlight = this._flushOnce().finally(() => { this._inFlight = null; });+ return this._inFlight;+ }++ async _flushOnce() {+ // Two attempts: the second runs the producer against a freshly-read doc, so+ // a concurrent writer's props are merged in rather than overwritten.+ for (let attempt = 0; attempt < 2; attempt++) {+ const doc = this._produce(this.doc);+ const outcome = await this._post(doc);+ if (outcome === 'ok') { this.doc = doc; this._onSaved?.(); return 'ok'; }+ if (outcome === 'conflict' && attempt === 0) { await this.load(); continue; }+ return outcome;+ }+ return 'conflict';+ }++ async _post(doc) {+ let res;+ try {+ res = await this._fetch('/api/world/save', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ credentials: 'include',+ body: JSON.stringify({ worldId: this.worldId, doc, ifMatch: this.etag ?? null }),+ });+ } catch (err) {+ this.lastError = err?.message || 'network error';+ this._onError?.({ reason: 'network', status: 0 });+ return 'error';+ }+ const outcome = outcomeOf(res.status);+ let body = null;+ try { body = await res.json(); } catch { /* empty or non-JSON body */ }++ if (outcome === 'ok') {+ this.etag = body?.etag ?? this.etag;+ this.version = Number(body?.version) || this.version;+ this.lastError = null;+ return 'ok';+ }+ if (outcome === 'denied') {+ this.denied = true;+ this.lastError = body?.message || 'not permitted to build in this world';+ this._onDenied?.({+ reason: res.status === 401 ? 'signin' : 'owner',+ status: res.status,+ message: this.lastError,+ });+ return 'denied';+ }+ if (outcome === 'too_large') {+ this.lastError = body?.message || 'this world is full';+ this._onError?.({ reason: 'too_large', status: res.status });+ return 'too_large';+ }+ if (outcome === 'conflict') return 'conflict';+ this.lastError = body?.message || `HTTP ${res.status}`;+ this._onError?.({ reason: 'server', status: res.status });+ return 'error';+ }++ /** Stop writing. Any armed debounce is dropped; call flush() first to keep it. */+ dispose() {+ this._disposed = true;+ if (this._timer) { clearTimeout(this._timer); this._timer = null; }+ this._produce = null;+ }+}diff --git a/src/viewer/screenshot.js b/src/viewer/screenshot.jsindex 5ba9c40b2..4667f2b12 100644--- a/src/viewer/screenshot.js+++ b/src/viewer/screenshot.js@@ -2,29 +2,47 @@ import { log } from '../shared/log.js';const WATERMARK_URL = '/three.svg';let watermarkImage = null;-async function getWatermark() {- if (watermarkImage) return watermarkImage;- try {- const res = await fetch(WATERMARK_URL);- if (!res.ok) throw new Error('Failed to load watermark');- const svgText = await res.text();- const blob = new Blob([svgText], { type: 'image/svg+xml' });- const url = URL.createObjectURL(blob);- const img = new Image();- img.src = url;- await new Promise((resolve, reject) => {- img.onload = resolve;- img.onerror = reject;- });- watermarkImage = img;- return watermarkImage;- } catch (e) {- log.error('Failed to load watermark:', e);- return null;- }-}+// Fetched on first screenshot, not on import. Eagerly warming it cost every+// page that merely loads the viewer a request for an asset most visitors never+// use, and turned any transient network blip into a console error on pages+// where nothing had gone wrong. In-flight requests are shared so rapid captures+// issue one fetch, and a failure resolves to null rather than throwing: the+// watermark is decoration, and _capture already falls back to the bare canvas.+let watermarkPending = null;++function getWatermark() {+ if (watermarkImage) return Promise.resolve(watermarkImage);+ if (watermarkPending) return watermarkPending;-getWatermark();+ watermarkPending = (async () => {+ let url;+ try {+ const res = await fetch(WATERMARK_URL);+ if (!res.ok) throw new Error(`HTTP ${res.status}`);+ const svgText = await res.text();+ url = URL.createObjectURL(new Blob([svgText], { type: 'image/svg+xml' }));+ const img = new Image();+ img.src = url;+ await new Promise((resolve, reject) => {+ img.onload = resolve;+ img.onerror = () => reject(new Error('watermark decode failed'));+ });+ watermarkImage = img;+ return watermarkImage;+ } catch (e) {+ // Not an error for the user: the screenshot still saves unwatermarked.+ log.warn('Watermark unavailable; saving screenshot without it:', e.message);+ return null;+ } finally {+ // The decoded image keeps its own copy of the pixels, so the object URL+ // has done its job either way.+ if (url) URL.revokeObjectURL(url);+ watermarkPending = null;+ }+ })();++ return watermarkPending;+}function _capture(viewer) {return new Promise(async (resolve) => {diff --git a/tests/press-kit.test.js b/tests/press-kit.test.jsnew file mode 100644index 000000000..a638477e8--- /dev/null+++ b/tests/press-kit.test.js@@ -0,0 +1,86 @@+/**+ * /press is a page whose entire job is handing files to strangers, so the thing+ * that breaks it is not a rendering bug: it is a download button pointing at a+ * file that moved, or a size printed next to a link that no longer matches the+ * bytes behind it. Those fail silently in a browser and embarrassingly in front+ * of a journalist, so they are asserted here.+ */+import { describe, it, expect } from 'vitest';+import { readFileSync, existsSync, statSync } from 'node:fs';+import { join, dirname } from 'node:path';+import { fileURLToPath } from 'node:url';+import JSZip from 'jszip';++const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');+const PUBLIC = join(ROOT, 'public');+const PAGE = join(ROOT, 'pages/press/index.html');+const html = readFileSync(PAGE, 'utf8');++/** Every same-origin asset reference on the page: src="/…" and href="/…" to a file. */+function assetRefs() {+ const refs = new Set();+ for (const m of html.matchAll(/(?:src|href)="(\/[^"#?]+\.[a-z0-9]+)"/gi)) refs.add(m[1]);+ return [...refs];+}++/** Static files ship from public/; app modules like /i18n.js are bundled out of src/. */+function resolves(ref) {+ const rel = ref.slice(1);+ return existsSync(join(PUBLIC, rel)) || existsSync(join(ROOT, 'src', rel));+}++describe('/press asset references', () => {+ it('resolves every file the page links or embeds', () => {+ const missing = assetRefs().filter((ref) => !resolves(ref));+ expect(missing, `unresolved: ${missing.join(', ')}`).toEqual([]);+ });++ it('offers every rendered brand asset for download', () => {+ const expected = [+ 'three-ws-mark.png',+ 'three-ws-lockup-on-dark.png',+ 'three-ws-lockup-on-light.png',+ 'three-ws-stacked-on-dark.png',+ 'three-ws-stacked-on-light.png',+ ];+ for (const file of expected) {+ expect(existsSync(join(PUBLIC, 'brand', file)), `public/brand/${file} not rendered`).toBe(true);+ expect(html, `${file} is rendered but not offered on /press`).toContain(`/brand/${file}`);+ }+ });++ it('keeps the OpenAI announcement graphics wired', () => {+ for (const file of ['social-card-announcement.png', 'social-card-studio.png']) {+ expect(existsSync(join(PUBLIC, 'partners/openai', file))).toBe(true);+ expect(html).toContain(`/partners/openai/${file}`);+ }+ });+});++describe('press kit archive', () => {+ const zipPath = join(PUBLIC, 'brand/three-ws-press-kit.zip');++ it('exists and carries the marks, the OpenAI graphics, and the usage rules', async () => {+ expect(existsSync(zipPath)).toBe(true);+ const zip = await JSZip.loadAsync(readFileSync(zipPath));+ const names = Object.keys(zip.files);+ expect(names).toContain('README.txt');+ expect(names.some((n) => n.startsWith('marks/'))).toBe(true);+ expect(names.some((n) => n.startsWith('openai/'))).toBe(true);++ const readme = await zip.file('README.txt').async('string');+ // The rules have to travel with the files; a bare folder of PNGs is how a+ // mark ends up recoloured in someone else's deck.+ expect(readme).toMatch(/Using the marks/);+ expect(readme).toMatch(/partnerships@three\.ws/);+ });++ it('quotes its real size on the page', () => {+ const quoted = html.match(/<span data-zip-size>([\d.]+) MB<\/span>/);+ expect(quoted, 'the zip size span is missing from /press').not.toBeNull();+ const actual = statSync(zipPath).size / 1024 / 1024;+ // render-brand-assets.mjs writes this back on every build; a drift bigger+ // than a rounding step means someone edited an asset without re-running it.+ expect(Math.abs(Number(quoted[1]) - actual)).toBeLessThan(0.1);+ });+});diff --git a/vercel.json b/vercel.jsonindex 3372994b7..cc6de3575 100644--- a/vercel.json+++ b/vercel.json@@ -3778,7 +3778,30 @@},{"src": "/agent/new/?",- "dest": "/agent-edit.html"+ "has": [+ {+ "type": "query",+ "key": "avatar_id"+ }+ ],+ "dest": "/create-agent.html"+ },+ {+ "src": "/agent/new/?",+ "has": [+ {+ "type": "query",+ "key": "avatar_glb"+ }+ ],+ "dest": "/create-agent.html"+ },+ {+ "src": "/agent/new/?",+ "status": 301,+ "headers": {+ "Location": "/create-agent"+ }},{"src": "/agent/([^/]+)/share/?",@@ -3805,12 +3828,21 @@"dest": "/avatar-edit.html?id=$1"},{- "src": "/avatar-edit",+ "src": "/avatar-edit/?",+ "has": [+ {+ "type": "query",+ "key": "id"+ }+ ],"dest": "/avatar-edit.html"},{- "src": "/avatar-edit/",- "dest": "/avatar-edit.html"+ "src": "/avatar-edit/?",+ "status": 301,+ "headers": {+ "Location": "/avatars"+ }},{"src": "/agent/([^/]+)/embed",@@ -4722,12 +4754,11 @@"dest": "/genesis.html"},{- "src": "/scan",- "dest": "/scan.html"- },- {- "src": "/scan/",- "dest": "/scan.html"+ "src": "/scan/?",+ "status": 301,+ "headers": {+ "Location": "/create/selfie"+ }},{"src": "/dad",