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: IBM pages verify + UI contract tests, vision test; agent-edit + IBM page polish
nirholasab9bed7e6846
diff --git a/api/ibm/vision.js b/api/ibm/vision.jsindex add085fa8..ea7e1c8db 100644--- a/api/ibm/vision.js+++ b/api/ibm/vision.js@@ -130,6 +130,9 @@ async function handleSubjects(req, res) {thumbnail: publicUrl(r.thumbnail_key),model_url: publicUrl(r.storage_key),}));+ // Subjects list changes at most once an hour; cache aggressively so the demo+ // loads instantly for repeat visitors while keeping CDN cost negligible.+ res.setHeader('cache-control', 's-maxage=3600, stale-while-revalidate=86400');return json(res, 200, { subjects, visionModel: VISION_MODEL });}@@ -173,10 +176,12 @@ async function handleVision(req, res) {messages: buildVisionMessages(subject, hint, dataUrl),});} catch (e) {- // Surface the real upstream cause (auth, unsupported model in region, quota).+ // Surface the real upstream cause (auth, quota, model not deployed in region).+ // model_unavailable gives the operator a clear signal to check WATSONX_VISION_MODEL_ID+ // or the regional model catalogue; vision_failed covers everything else.const msg = String(e?.message || 'watsonx vision request failed');- const status = /404|not.*found|unsupported|not.*deployed/i.test(msg) ? 502 : 502;- return error(res, status, 'vision_failed', msg);+ const code = /not.*found|not.*deployed|unsupported.*model/i.test(msg) ? 'model_unavailable' : 'vision_failed';+ return error(res, 502, code, msg);}const vision = parseVision(reply.text);diff --git a/package.json b/package.jsonindex 8030a2c1d..00797d38a 100644--- a/package.json+++ b/package.json@@ -93,6 +93,7 @@"test": "vitest run && playwright test","test:e2e": "playwright test","test:pages": "node scripts/test-pages.mjs",+ "verify:ibm": "node scripts/verify-ibm-pages.mjs","test:all": "npm run test && npm run test:pages","verify": "prettier --check . && vite build","format": "prettier --write .",diff --git a/pages/agent-edit.html b/pages/agent-edit.htmlindex a60a02dfe..ef66f80f0 100644--- a/pages/agent-edit.html+++ b/pages/agent-edit.html@@ -863,6 +863,15 @@.voice-range-val { font-variant-numeric: tabular-nums; color: rgba(255, 255, 255, 0.55); font-weight: 400; }.voice-check { grid-column: 1 / -1; display: flex; align-items: center; gap: 0.5rem; font-size: 0.82rem; color: rgba(255, 255, 255, 0.75); cursor: pointer; }.voice-check input { accent-color: #3b82f6; }+ .voice-tile-play.playing { color: #f87171; }+ .voice-unconfigured {+ display: flex; flex-direction: column; align-items: center; gap: 0.75rem;+ padding: 2rem 1.5rem; text-align: center;+ }+ .voice-unconfigured-icon { font-size: 2rem; line-height: 1; }+ .voice-unconfigured-title { font-size: 0.875rem; font-weight: 600; color: var(--t-ink); }+ .voice-unconfigured-body { font-size: 0.764rem; color: var(--t-ink-dim); margin: 0; max-width: 340px; line-height: 1.5; }+ .voice-unconfigured-body code { font-family: 'SF Mono', 'Fira Code', monospace; font-size: 0.73rem; background: var(--t-bg-3); padding: 1px 5px; border-radius: 4px; }/* Memories */.mem-list { display: flex; flex-direction: column; gap: 0.5rem; }diff --git a/pages/ibm/galaxy.html b/pages/ibm/galaxy.htmlindex cc911dfb2..2a7763bc1 100644--- a/pages/ibm/galaxy.html+++ b/pages/ibm/galaxy.html@@ -247,6 +247,19 @@</style></head><body>+ <noscript>+ <div style="position:fixed;inset:0;z-index:99999;display:flex;align-items:center;justify-content:center;padding:24px;background:#06080f;color:#e7ecf5;font-family:system-ui,-apple-system,'Segoe UI',Roboto,sans-serif;text-align:center">+ <div style="max-width:480px">+ <div style="width:12px;height:12px;border-radius:50%;background:#0f62fe;margin:0 auto 20px;box-shadow:0 0 24px #0f62fe" aria-hidden="true"></div>+ <h1 style="font-size:26px;font-weight:600;letter-spacing:-0.02em;margin:0 0 10px;color:#fff">Agent Galaxy</h1>+ <p style="font-size:15px;line-height:1.6;color:#9fb0c8;margin:0 0 22px">A 3D semantic map of every three.ws agent, mapped by IBM Granite embeddings. This interactive 3D experience needs JavaScript enabled.</p>+ <div style="display:flex;gap:10px;justify-content:center;flex-wrap:wrap">+ <a href="/docs/ibm" style="display:inline-block;padding:10px 18px;border-radius:10px;background:#0f62fe;color:#fff;text-decoration:none;font-size:14px;font-weight:500">Read the docs</a>+ <a href="/ibm" style="display:inline-block;padding:10px 18px;border-radius:10px;background:rgba(255,255,255,0.06);border:1px solid rgba(255,255,255,0.14);color:#e7ecf5;text-decoration:none;font-size:14px">Back to the showcase</a>+ </div>+ </div>+ </div>+ </noscript><canvas id="scene"></canvas><div class="cluster-labels" id="clusterLabels"></div>diff --git a/pages/ibm/index.html b/pages/ibm/index.htmlindex dcc754889..15d96cafd 100644--- a/pages/ibm/index.html+++ b/pages/ibm/index.html@@ -97,6 +97,19 @@</style></head><body>+ <noscript>+ <div style="position:fixed;inset:0;z-index:99999;display:flex;align-items:center;justify-content:center;padding:24px;background:#06080f;color:#e7ecf5;font-family:system-ui,-apple-system,'Segoe UI',Roboto,sans-serif;text-align:center">+ <div style="max-width:480px">+ <div style="width:12px;height:12px;border-radius:50%;background:#0f62fe;margin:0 auto 20px;box-shadow:0 0 24px #0f62fe" aria-hidden="true"></div>+ <h1 style="font-size:26px;font-weight:600;letter-spacing:-0.02em;margin:0 0 10px;color:#fff">three.ws × IBM watsonx</h1>+ <p style="font-size:15px;line-height:1.6;color:#9fb0c8;margin:0 0 22px">The IBM Granite showcase — embodied AI agents thinking on watsonx.ai. This interactive 3D experience needs JavaScript enabled.</p>+ <div style="display:flex;gap:10px;justify-content:center;flex-wrap:wrap">+ <a href="/docs/ibm" style="display:inline-block;padding:10px 18px;border-radius:10px;background:#0f62fe;color:#fff;text-decoration:none;font-size:14px;font-weight:500">Read the docs</a>+ <a href="/" style="display:inline-block;padding:10px 18px;border-radius:10px;background:rgba(255,255,255,0.06);border:1px solid rgba(255,255,255,0.14);color:#e7ecf5;text-decoration:none;font-size:14px">three.ws home</a>+ </div>+ </div>+ </div>+ </noscript><header><a href="/" class="home">three.ws</a><nav>diff --git a/pages/ibm/oracle.html b/pages/ibm/oracle.htmlindex e7907dfd0..4284ab8b0 100644--- a/pages/ibm/oracle.html+++ b/pages/ibm/oracle.html@@ -441,6 +441,19 @@</style></head><body>+ <noscript>+ <div style="position:fixed;inset:0;z-index:99999;display:flex;align-items:center;justify-content:center;padding:24px;background:#06080f;color:#e7ecf5;font-family:system-ui,-apple-system,'Segoe UI',Roboto,sans-serif;text-align:center">+ <div style="max-width:480px">+ <div style="width:12px;height:12px;border-radius:50%;background:#0f62fe;margin:0 auto 20px;box-shadow:0 0 24px #0f62fe" aria-hidden="true"></div>+ <h1 style="font-size:26px;font-weight:600;letter-spacing:-0.02em;margin:0 0 10px;color:#fff">Granite Oracle</h1>+ <p style="font-size:15px;line-height:1.6;color:#9fb0c8;margin:0 0 22px">Live token forecasting with IBM Granite TimeSeries, narrated by a 3D agent. This interactive 3D experience needs JavaScript enabled.</p>+ <div style="display:flex;gap:10px;justify-content:center;flex-wrap:wrap">+ <a href="/docs/ibm" style="display:inline-block;padding:10px 18px;border-radius:10px;background:#0f62fe;color:#fff;text-decoration:none;font-size:14px;font-weight:500">Read the docs</a>+ <a href="/ibm" style="display:inline-block;padding:10px 18px;border-radius:10px;background:rgba(255,255,255,0.06);border:1px solid rgba(255,255,255,0.14);color:#e7ecf5;text-decoration:none;font-size:14px">Back to the showcase</a>+ </div>+ </div>+ </div>+ </noscript><div id="oracle-stage"></div><!-- Embodied narrator: speaks the Granite analysis, emotes on the forecast -->diff --git a/pages/ibm/proof.html b/pages/ibm/proof.htmlindex 4a0df828e..8616de08a 100644--- a/pages/ibm/proof.html+++ b/pages/ibm/proof.html@@ -154,6 +154,19 @@</style></head><body>+ <noscript>+ <div style="position:fixed;inset:0;z-index:99999;display:flex;align-items:center;justify-content:center;padding:24px;background:#06080f;color:#e7ecf5;font-family:system-ui,-apple-system,'Segoe UI',Roboto,sans-serif;text-align:center">+ <div style="max-width:480px">+ <div style="width:12px;height:12px;border-radius:50%;background:#0f62fe;margin:0 auto 20px;box-shadow:0 0 24px #0f62fe" aria-hidden="true"></div>+ <h1 style="font-size:26px;font-weight:600;letter-spacing:-0.02em;margin:0 0 10px;color:#fff">Granite Proof</h1>+ <p style="font-size:15px;line-height:1.6;color:#9fb0c8;margin:0 0 22px">AI forecasts notarized on-chain, governed by IBM Granite Guardian. This interactive 3D experience needs JavaScript enabled.</p>+ <div style="display:flex;gap:10px;justify-content:center;flex-wrap:wrap">+ <a href="/docs/ibm" style="display:inline-block;padding:10px 18px;border-radius:10px;background:#0f62fe;color:#fff;text-decoration:none;font-size:14px;font-weight:500">Read the docs</a>+ <a href="/ibm" style="display:inline-block;padding:10px 18px;border-radius:10px;background:rgba(255,255,255,0.06);border:1px solid rgba(255,255,255,0.14);color:#e7ecf5;text-decoration:none;font-size:14px">Back to the showcase</a>+ </div>+ </div>+ </div>+ </noscript><header><a href="/ibm" class="home">three.ws <span class="badge">IBM watsonx</span></a><nav>diff --git a/pages/ibm/trust-layer.html b/pages/ibm/trust-layer.htmlindex 5dad08632..f1ba9730d 100644--- a/pages/ibm/trust-layer.html+++ b/pages/ibm/trust-layer.html@@ -254,6 +254,19 @@</style></head><body>+ <noscript>+ <div style="position:fixed;inset:0;z-index:99999;display:flex;align-items:center;justify-content:center;padding:24px;background:#06080f;color:#e7ecf5;font-family:system-ui,-apple-system,'Segoe UI',Roboto,sans-serif;text-align:center">+ <div style="max-width:480px">+ <div style="width:12px;height:12px;border-radius:50%;background:#0f62fe;margin:0 auto 20px;box-shadow:0 0 24px #0f62fe" aria-hidden="true"></div>+ <h1 style="font-size:26px;font-weight:600;letter-spacing:-0.02em;margin:0 0 10px;color:#fff">Trust Layer</h1>+ <p style="font-size:15px;line-height:1.6;color:#9fb0c8;margin:0 0 22px">IBM Granite Guardian governing autonomous agent actions in real time. This interactive 3D experience needs JavaScript enabled.</p>+ <div style="display:flex;gap:10px;justify-content:center;flex-wrap:wrap">+ <a href="/docs/ibm" style="display:inline-block;padding:10px 18px;border-radius:10px;background:#0f62fe;color:#fff;text-decoration:none;font-size:14px;font-weight:500">Read the docs</a>+ <a href="/ibm" style="display:inline-block;padding:10px 18px;border-radius:10px;background:rgba(255,255,255,0.06);border:1px solid rgba(255,255,255,0.14);color:#e7ecf5;text-decoration:none;font-size:14px">Back to the showcase</a>+ </div>+ </div>+ </div>+ </noscript><canvas id="scene"></canvas><div class="node-labels" id="nodeLabels"></div>diff --git a/pages/ibm/twin.html b/pages/ibm/twin.htmlindex 1ddc75731..48aecce1a 100644--- a/pages/ibm/twin.html+++ b/pages/ibm/twin.html@@ -608,6 +608,19 @@</style></head><body>+ <noscript>+ <div style="position:fixed;inset:0;z-index:99999;display:flex;align-items:center;justify-content:center;padding:24px;background:#06080f;color:#e7ecf5;font-family:system-ui,-apple-system,'Segoe UI',Roboto,sans-serif;text-align:center">+ <div style="max-width:480px">+ <div style="width:12px;height:12px;border-radius:50%;background:#0f62fe;margin:0 auto 20px;box-shadow:0 0 24px #0f62fe" aria-hidden="true"></div>+ <h1 style="font-size:26px;font-weight:600;letter-spacing:-0.02em;margin:0 0 10px;color:#fff">Digital Twin</h1>+ <p style="font-size:15px;line-height:1.6;color:#9fb0c8;margin:0 0 22px">A living market replica projected by IBM Granite TimeSeries. This interactive 3D experience needs JavaScript enabled.</p>+ <div style="display:flex;gap:10px;justify-content:center;flex-wrap:wrap">+ <a href="/docs/ibm" style="display:inline-block;padding:10px 18px;border-radius:10px;background:#0f62fe;color:#fff;text-decoration:none;font-size:14px;font-weight:500">Read the docs</a>+ <a href="/ibm" style="display:inline-block;padding:10px 18px;border-radius:10px;background:rgba(255,255,255,0.06);border:1px solid rgba(255,255,255,0.14);color:#e7ecf5;text-decoration:none;font-size:14px">Back to the showcase</a>+ </div>+ </div>+ </div>+ </noscript><div id="twin-stage"></div><!-- Embodied narrator: the twin speaks of itself, governed by Granite Guardian -->diff --git a/pages/ibm/vision.html b/pages/ibm/vision.htmlindex 9357ca5fe..e9df8e2ab 100644--- a/pages/ibm/vision.html+++ b/pages/ibm/vision.html@@ -28,7 +28,7 @@--ink: #f4f4f4;--muted: #a6b0c3;--faint: #6b7589;- --panel: rgba(13, 17, 28, 0.66);+ --panel: rgba(13, 17, 28, 0.72);--panel-solid: #0d111c;--stroke: rgba(120, 169, 255, 0.22);--line: rgba(255, 255, 255, 0.08);@@ -47,12 +47,14 @@}a { color: var(--ibm-blue-2); text-decoration: none; }+ /* ── 3D stage ──────────────────────────────────────────────── */#vision-stage { position: fixed; inset: 0; z-index: 0; }- #vision-stage canvas { display: block; cursor: grab; }+ #vision-stage canvas { display: block; cursor: grab; outline: none; }#vision-stage canvas:active { cursor: grabbing; }#v-photo {position: fixed; inset: 0; z-index: 0;- display: none; align-items: center; justify-content: center; padding: 8vh 6vw;+ display: none; align-items: center; justify-content: center;+ padding: 8vh 6vw;}#v-photo img {max-width: min(46vw, 520px); max-height: 76vh;@@ -61,7 +63,26 @@object-fit: contain;}- /* Top bar */+ /* ── Drag-and-drop overlay ─────────────────────────────────── */+ .drag-drop-hint {+ position: fixed; inset: 0; z-index: 40;+ display: none; align-items: center; justify-content: center;+ pointer-events: none;+ background: rgba(10, 13, 22, 0.72);+ backdrop-filter: blur(4px);+ }+ .drag-drop-hint-inner {+ display: flex; flex-direction: column; align-items: center; gap: 14px;+ padding: 40px 56px; border-radius: 22px;+ border: 2px dashed rgba(120, 169, 255, 0.6);+ background: rgba(15, 98, 254, 0.08);+ }+ .drag-drop-hint-icon { font-size: 44px; line-height: 1; }+ .drag-drop-hint-text { font-size: 17px; font-weight: 600; color: var(--ink); }+ .drag-drop-hint-sub { font-size: 13px; color: var(--muted); }+ body.drag-active .drag-drop-hint { display: flex; }++ /* ── Top bar ───────────────────────────────────────────────── */.topbar {position: fixed; top: 0; left: 0; right: 0; z-index: 6;display: flex; align-items: center; justify-content: space-between;@@ -69,7 +90,12 @@}.topbar > * { pointer-events: auto; }.brand { display: flex; align-items: center; gap: 10px; font-weight: 600; }- .brand .dot { width: 9px; height: 9px; border-radius: 50%; background: var(--ibm-blue); box-shadow: 0 0 12px var(--ibm-blue); }+ .brand .dot {+ width: 9px; height: 9px; border-radius: 50%;+ background: var(--ibm-blue); box-shadow: 0 0 12px var(--ibm-blue);+ animation: glow-pulse 2.6s ease-in-out infinite;+ }+ @keyframes glow-pulse { 0%,100%{opacity:1} 50%{opacity:.4} }.brand small { color: var(--muted); font-weight: 400; }.topbar .back {font-size: 13px; color: var(--muted); border: 1px solid var(--stroke);@@ -77,19 +103,21 @@backdrop-filter: blur(8px); transition: border-color 0.15s, color 0.15s;}.topbar .back:hover { color: var(--ink); border-color: var(--ibm-blue-2); }+ .topbar .back:focus-visible { outline: 2px solid var(--ibm-blue-2); outline-offset: 2px; }- /* Read-out panel (right) */+ /* ── Read-out panel (right) ─────────────────────────────────── */.read {position: fixed; top: 70px; right: 22px; bottom: 104px; z-index: 5;width: min(380px, calc(100vw - 44px));display: flex; flex-direction: column;background: var(--panel); border: 1px solid var(--stroke); border-radius: 16px;- backdrop-filter: blur(14px); box-shadow: 0 24px 70px rgba(0, 0, 0, 0.4);+ backdrop-filter: blur(16px); box-shadow: 0 24px 70px rgba(0, 0, 0, 0.45);overflow: hidden;}.read-head {display: flex; align-items: center; justify-content: space-between;padding: 15px 18px; border-bottom: 1px solid var(--line);+ flex-shrink: 0;}.read-head .rh-title { display: flex; align-items: center; gap: 9px; font-size: 14px; font-weight: 600; }.read-head .mark {@@ -98,95 +126,195 @@display: grid; place-items: center; font-size: 11px; font-weight: 700; color: #fff;}.read-head .rh-model { font-size: 11px; color: var(--faint); }- .read-body { padding: 18px; overflow-y: auto; scrollbar-width: thin; flex: 1; }+ .read-body {+ padding: 18px; overflow-y: auto; scrollbar-width: thin; flex: 1;+ /* Prevent rubber-band scroll from bleeding into the stage. */+ overscroll-behavior: contain;+ }+ /* ── State visibility + enter animation ─────────────────────── */.v-state { display: none; }- .v-state.on { display: block; }+ .v-state.on {+ display: block;+ animation: v-fadein 0.2s ease both;+ }+ @keyframes v-fadein {+ from { opacity: 0; transform: translateY(5px); }+ to { opacity: 1; transform: translateY(0); }+ }+ @media (prefers-reduced-motion: reduce) {+ .v-state.on { animation: none; }+ }- .idle-glyph { font-size: 30px; margin-bottom: 12px; color: var(--ibm-light); text-shadow: 0 0 22px rgba(120,169,255,0.5); }+ /* ── Idle state ──────────────────────────────────────────────── */+ .idle-glyph {+ font-size: 30px; margin-bottom: 12px; color: var(--ibm-light);+ text-shadow: 0 0 22px rgba(120,169,255,0.5);+ }.idle-title { font-size: 16px; font-weight: 600; margin-bottom: 6px; }.idle-sub { font-size: 13.5px; color: var(--muted); line-height: 1.55; }+ .idle-sub kbd {+ display: inline-flex; align-items: center; gap: 3px; font-size: 11px;+ background: rgba(255,255,255,0.08); border: 1px solid var(--line);+ border-radius: 5px; padding: 1px 6px; font-family: var(--font);+ color: var(--muted); vertical-align: middle;+ }- .skel { background: linear-gradient(100deg, rgba(255,255,255,0.04) 30%, rgba(120,169,255,0.10) 50%, rgba(255,255,255,0.04) 70%); background-size: 200% 100%; animation: shimmer 1.3s infinite; border-radius: 7px; }+ /* ── Loading state ───────────────────────────────────────────── */+ .skel {+ background: linear-gradient(100deg, rgba(255,255,255,0.04) 30%, rgba(120,169,255,0.10) 50%, rgba(255,255,255,0.04) 70%);+ background-size: 200% 100%; animation: shimmer 1.3s infinite; border-radius: 7px;+ }.skel.l { height: 13px; margin-bottom: 9px; }.skel.l.s { width: 55%; }.skel.l.m { width: 80%; }.skel.big { height: 26px; width: 60%; margin-bottom: 14px; }@keyframes shimmer { to { background-position: -200% 0; } }- .looking { font-size: 13px; color: var(--ibm-light); margin-top: 14px; display: flex; align-items: center; gap: 8px; }- .looking .ring { width: 13px; height: 13px; border-radius: 50%; border: 2px solid rgba(120,169,255,0.3); border-top-color: var(--ibm-light); animation: spin 0.9s linear infinite; }+ .looking {+ font-size: 13px; color: var(--ibm-light); margin-top: 14px;+ display: flex; align-items: center; gap: 8px;+ }+ .looking .ring {+ width: 13px; height: 13px; border-radius: 50%; flex: none;+ border: 2px solid rgba(120,169,255,0.3); border-top-color: var(--ibm-light);+ animation: spin 0.9s linear infinite;+ }@keyframes spin { to { transform: rotate(360deg); } }+ /* ── Result state ────────────────────────────────────────────── */.v-name { font-size: 23px; font-weight: 700; letter-spacing: -0.02em; line-height: 1.1; }- .v-bio { font-size: 14px; color: var(--ibm-light); font-style: italic; margin-top: 6px; line-height: 1.45; }+ .v-bio {+ font-size: 14px; color: var(--ibm-light); font-style: italic;+ margin-top: 6px; line-height: 1.45;+ }+ .v-usage-badge {+ display: inline-block; margin-top: 8px; font-size: 10.5px;+ color: var(--faint); background: rgba(255,255,255,0.04);+ border: 1px solid var(--line); border-radius: 6px; padding: 3px 8px;+ font-variant-numeric: tabular-nums;+ }.v-field { margin-top: 18px; }- .v-field-label { font-size: 10.5px; letter-spacing: 0.1em; text-transform: uppercase; color: var(--faint); margin-bottom: 7px; }+ .v-field-label {+ font-size: 10.5px; letter-spacing: 0.1em; text-transform: uppercase;+ color: var(--faint); margin-bottom: 7px;+ }.v-field p { margin: 0; font-size: 13.5px; line-height: 1.6; color: #d7dceb; }.v-chips { display: flex; flex-wrap: wrap; gap: 6px; }- .v-chip { font-size: 12px; color: var(--ink); background: rgba(120,169,255,0.12); border: 1px solid var(--stroke); border-radius: 7px; padding: 4px 10px; }+ .v-chip {+ font-size: 12px; color: var(--ink);+ background: rgba(120,169,255,0.12); border: 1px solid var(--stroke);+ border-radius: 7px; padding: 4px 10px;+ transition: background 0.15s;+ }.v-voice { display: flex; align-items: center; gap: 8px; font-size: 13.5px; color: #d7dceb; }.v-voice svg { width: 15px; height: 15px; color: var(--ibm-light); flex: none; }.v-raw { font-size: 13.5px; line-height: 1.6; color: #d7dceb; white-space: pre-wrap; }.v-actions { display: flex; gap: 8px; margin-top: 20px; flex-wrap: wrap; }+ /* ── Error state ─────────────────────────────────────────────── */.err-glyph { font-size: 28px; color: var(--ibm-light); margin-bottom: 10px; }.err-title { font-size: 16px; font-weight: 600; margin-bottom: 6px; }.err-sub { font-size: 13.5px; color: var(--muted); line-height: 1.55; }- /* Dock (bottom) */+ /* ── Dock (bottom) ───────────────────────────────────────────── */.dock {position: fixed; left: 50%; bottom: 20px; transform: translateX(-50%); z-index: 6;display: flex; align-items: center; gap: 10px; flex-wrap: wrap; justify-content: center;width: min(880px, calc(100vw - 36px));background: var(--panel); border: 1px solid var(--stroke); border-radius: 16px;- padding: 11px 13px; backdrop-filter: blur(14px); box-shadow: 0 24px 70px rgba(0,0,0,0.4);+ padding: 11px 13px; backdrop-filter: blur(16px); box-shadow: 0 24px 70px rgba(0,0,0,0.45);}.subjects { display: flex; gap: 8px; overflow-x: auto; scrollbar-width: thin; flex: 1; min-width: 0; padding: 2px; }.subject {flex: none; width: 50px; height: 50px; border-radius: 11px; cursor: pointer;border: 2px solid transparent; background: #11151f center/cover no-repeat;display: grid; place-items: center; color: var(--faint); font-size: 18px; font-weight: 700;- transition: border-color 0.15s, transform 0.12s; position: relative; overflow: hidden;+ transition: border-color 0.15s, transform 0.12s, box-shadow 0.15s;+ position: relative; overflow: hidden;}.subject:hover { transform: translateY(-2px); }- .subject.sel { border-color: var(--ibm-blue-2); box-shadow: 0 0 0 3px rgba(15,98,254,0.2); }- .subject .cap { position: absolute; bottom: 0; left: 0; right: 0; font-size: 8.5px; background: rgba(0,0,0,0.55); color: #cdd5e6; padding: 1px 3px; text-align: center; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }+ .subject:focus-visible { outline: 2px solid var(--ibm-blue-2); outline-offset: 2px; }+ .subject.sel {+ border-color: var(--ibm-blue-2);+ box-shadow: 0 0 0 3px rgba(15,98,254,0.2), 0 0 18px rgba(120,169,255,0.3);+ }+ .subject .cap {+ position: absolute; bottom: 0; left: 0; right: 0;+ font-size: 8.5px; background: rgba(0,0,0,0.6); color: #cdd5e6;+ padding: 1px 3px; text-align: center; white-space: nowrap;+ overflow: hidden; text-overflow: ellipsis;+ }.dock-sep { width: 1px; height: 34px; background: var(--line); flex: none; }++ /* ── Buttons ─────────────────────────────────────────────────── */.btn {- font: inherit; font-size: 13px; font-weight: 600; border-radius: 10px; padding: 10px 16px;- cursor: pointer; border: 0; display: inline-flex; align-items: center; gap: 7px;+ font: inherit; font-size: 13px; font-weight: 600; border-radius: 10px;+ padding: 10px 16px; cursor: pointer; border: 0;+ display: inline-flex; align-items: center; gap: 7px;transition: filter 0.15s, background 0.15s, transform 0.1s; white-space: nowrap;}+ .btn:focus-visible { outline: 2px solid var(--ibm-blue-2); outline-offset: 2px; }.btn-primary { background: var(--ibm-blue); color: #fff; }.btn-primary:hover { filter: brightness(1.12); }.btn-primary:active { transform: translateY(1px); }.btn-primary:disabled { opacity: 0.55; cursor: progress; }- .btn-ghost { background: rgba(255,255,255,0.06); color: var(--ink); border: 1px solid var(--line); }+ .btn-ghost {+ background: rgba(255,255,255,0.06); color: var(--ink);+ border: 1px solid var(--line);+ }.btn-ghost:hover { background: rgba(255,255,255,0.11); }.btn-sm { font-size: 12px; padding: 8px 13px; }.btn svg { width: 15px; height: 15px; }+ /* ── Misc ────────────────────────────────────────────────────── */.attribution {position: fixed; left: 22px; bottom: 22px; z-index: 5;- font-size: 11.5px; color: var(--faint); display: flex; align-items: center; gap: 7px;- pointer-events: none;+ font-size: 11.5px; color: var(--faint);+ display: flex; align-items: center; gap: 7px; pointer-events: none;+ }+ .attribution .adot {+ width: 6px; height: 6px; border-radius: 50%;+ background: var(--ibm-blue); box-shadow: 0 0 8px var(--ibm-blue);}- .attribution .adot { width: 6px; height: 6px; border-radius: 50%; background: var(--ibm-blue); box-shadow: 0 0 8px var(--ibm-blue); }-.stage-hint {position: fixed; left: 50%; top: 64px; transform: translateX(-50%); z-index: 4;font-size: 12px; color: var(--faint); pointer-events: none; transition: opacity 0.4s;+ white-space: nowrap;}+ /* ── Responsive ──────────────────────────────────────────────── */@media (max-width: 820px) {.read { top: auto; bottom: 86px; right: 12px; left: 12px; width: auto; max-height: 46vh; }#v-photo img { max-width: 80vw; max-height: 40vh; }.attribution { display: none; }.dock { bottom: 12px; }+ .stage-hint { top: 56px; font-size: 11px; }}</style></head><body>+ <noscript>+ <div style="position:fixed;inset:0;z-index:99999;display:flex;align-items:center;justify-content:center;padding:24px;background:#06080f;color:#e7ecf5;font-family:system-ui,-apple-system,'Segoe UI',Roboto,sans-serif;text-align:center">+ <div style="max-width:480px">+ <div style="width:12px;height:12px;border-radius:50%;background:#0f62fe;margin:0 auto 20px;box-shadow:0 0 24px #0f62fe" aria-hidden="true"></div>+ <h1 style="font-size:26px;font-weight:600;letter-spacing:-0.02em;margin:0 0 10px;color:#fff">Granite Vision</h1>+ <p style="font-size:15px;line-height:1.6;color:#9fb0c8;margin:0 0 22px">IBM Granite Vision reads a 3D avatar into a full agent identity. This interactive 3D experience needs JavaScript enabled.</p>+ <div style="display:flex;gap:10px;justify-content:center;flex-wrap:wrap">+ <a href="/docs/ibm" style="display:inline-block;padding:10px 18px;border-radius:10px;background:#0f62fe;color:#fff;text-decoration:none;font-size:14px;font-weight:500">Read the docs</a>+ <a href="/ibm" style="display:inline-block;padding:10px 18px;border-radius:10px;background:rgba(255,255,255,0.06);border:1px solid rgba(255,255,255,0.14);color:#e7ecf5;text-decoration:none;font-size:14px">Back to the showcase</a>+ </div>+ </div>+ </div>+ </noscript>+ <!-- Drag-and-drop overlay (shown by body.drag-active) -->+ <div class="drag-drop-hint" aria-hidden="true">+ <div class="drag-drop-hint-inner">+ <div class="drag-drop-hint-icon">◉</div>+ <div class="drag-drop-hint-text">Drop image to read</div>+ <div class="drag-drop-hint-sub">Granite Vision will read it instantly</div>+ </div>+ </div>+<div id="vision-stage" aria-hidden="true"></div><div id="v-photo"><img id="v-photo-img" alt="Image being read by Granite Vision" /></div>@@ -201,36 +329,42 @@<div class="stage-hint" id="v-stage-hint">Drag to orbit · the avatar Granite is about to read</div>- <aside class="read" aria-live="polite">+ <aside class="read" aria-live="polite" aria-label="Granite's identity read"><div class="read-head"><div class="rh-title"><span class="mark">◉</span> Granite sees</div><div class="rh-model" id="v-model">granite-vision-3-2</div></div><div class="read-body">- <!-- Idle -->++ <!-- Idle: explain the feature + hint at keyboard/drag shortcuts --><div class="v-state on" id="v-idle"><div class="idle-glyph">◉</div><div class="idle-title">Show Granite an avatar</div><div class="idle-sub">- IBM Granite Vision on watsonx.ai will look at the 3D avatar and invent its whole identity —- how it looks, its vibe, a personality, a name, a bio, even a fitting voice. Pick a face below- (or upload any image), then press <strong>Show Granite</strong>.+ IBM Granite Vision on watsonx.ai will look at the 3D avatar and invent its whole+ identity — how it looks, its vibe, a personality, a name, a bio, even a fitting+ voice. Pick a face below (or upload / drag an image), then press+ <strong>Show Granite</strong> or hit <kbd>Enter</kbd>.</div></div>- <!-- Loading -->- <div class="v-state" id="v-loading">+ <!-- Loading: skeleton + live step progress -->+ <div class="v-state" id="v-loading" aria-label="Granite is reading the image"><div class="skel big"></div><div class="skel l m"></div><div class="skel l"></div><div class="skel l s"></div>- <div class="looking"><span class="ring"></span> Granite Vision is looking…</div>+ <div class="looking">+ <span class="ring"></span>+ <span id="v-loading-step">Capturing frame…</span>+ </div></div><!-- Result (structured) --><div class="v-state" id="v-result"><div class="v-name" id="v-name"></div><div class="v-bio" id="v-bio"></div>+ <span class="v-usage-badge" id="v-usage-badge" hidden></span><div class="v-field" id="v-appearance-wrap"><div class="v-field-label">Appearance</div><p id="v-appearance"></p>@@ -250,13 +384,17 @@<div class="v-field" id="v-voice-wrap"><div class="v-field-label">Voice</div><div class="v-voice">- <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M12 2a3 3 0 0 1 3 3v6a3 3 0 0 1-6 0V5a3 3 0 0 1 3-3z"/><path d="M19 10v1a7 7 0 0 1-14 0v-1M12 19v3"/></svg>+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round">+ <path d="M12 2a3 3 0 0 1 3 3v6a3 3 0 0 1-6 0V5a3 3 0 0 1 3-3z"/>+ <path d="M19 10v1a7 7 0 0 1-14 0v-1M12 19v3"/>+ </svg><span id="v-voice"></span></div></div><div class="v-actions">+ <button class="btn btn-ghost btn-sm" id="v-read-again" type="button">Read again</button><button class="btn btn-ghost btn-sm" id="v-copy" type="button">Copy identity</button>- <a class="btn btn-primary btn-sm" id="v-create" href="/create">Create an agent →</a>+ <a class="btn btn-primary btn-sm" id="v-create" href="/create">Create agent →</a></div></div>@@ -264,6 +402,9 @@<div class="v-state" id="v-rawstate"><div class="v-field-label">Granite's read</div><div class="v-raw" id="v-raw"></div>+ <div class="v-actions">+ <button class="btn btn-ghost btn-sm" id="v-read-again-raw" type="button">Read again</button>+ </div></div><!-- Error -->@@ -271,20 +412,28 @@<div class="err-glyph">◉</div><div class="err-title" id="v-error-title">Granite couldn't look</div><div class="err-sub" id="v-error-sub"></div>- <div class="v-actions"><button class="btn btn-ghost btn-sm" id="v-error-retry" type="button">Try again</button></div>+ <div class="v-actions">+ <button class="btn btn-ghost btn-sm" id="v-error-retry" type="button">Try again</button>+ </div></div>+</div></aside><div class="dock">- <div class="subjects" id="v-subjects" aria-label="Pick an avatar to show Granite"></div>- <div class="dock-sep"></div>- <button class="btn btn-ghost btn-sm" id="v-upload" type="button">Upload</button>- <input type="file" id="v-file" accept="image/*" hidden />- <button class="btn btn-primary" id="v-show" type="button">Show Granite</button>+ <div class="subjects" id="v-subjects" aria-label="Pick an avatar to show Granite" role="group"></div>+ <div class="dock-sep" aria-hidden="true"></div>+ <button class="btn btn-ghost btn-sm" id="v-upload" type="button" title="Upload an image file">Upload</button>+ <input type="file" id="v-file" accept="image/*" hidden aria-hidden="true" />+ <button class="btn btn-primary" id="v-show" type="button" aria-label="Show the current avatar to IBM Granite Vision">+ Show Granite+ </button></div>- <div class="attribution"><span class="adot"></span> IBM Granite Vision 3.2 · watsonx.ai · real multimodal inference</div>+ <div class="attribution">+ <span class="adot"></span>+ IBM Granite Vision 3.2 · watsonx.ai · real multimodal inference+ </div><script type="module" src="/src/ibm-vision.js"></script></body>diff --git a/scripts/test-pages.mjs b/scripts/test-pages.mjsindex 4afd6fadc..b7b7efe39 100644--- a/scripts/test-pages.mjs+++ b/scripts/test-pages.mjs@@ -1,218 +1,485 @@#!/usr/bin/env node+/**+ * Page-health regression gate for three.ws.+ *+ * WHY THIS EXISTS+ * ---------------+ * The site is ~90 pages built by ~20 agents in parallel. Lighthouse only runs+ * AFTER a Vercel deploy, so nothing catches a blank page, a thrown boot error,+ * a 500-ing fetch, or a broken hero image BEFORE it ships. This is that gate:+ * one Chromium pass over every public route, run on every PR.+ *+ * WHY YOU CAN TRUST A GREEN RUN+ * -----------------------------+ * A health gate is only useful if green means green. Two classes of false+ * positive used to make this script cry wolf on every run; both are killed:+ *+ * 1. vite-dev HMR noise. `vite dev` injects a client that opens an HMR+ * WebSocket. Behind the Codespaces / github.dev proxy that socket 404s,+ * emitting a `pageerror` + two `console.error`s on EVERY page. There is no+ * vite client in production, so these are pure dev artifacts — filtered.+ *+ * 2. vercel.json rewrites. Pretty URLs (`/pumpfun`, `/legal/privacy`) resolve+ * through vercel.json's ~590-route table to real files in public/.+ * `vite dev` does NOT apply that table, so it 404s on routes that are+ * perfectly healthy in prod. We replicate Vercel's route resolution+ * (rewrites + redirects + `continue` passthroughs) so we navigate to the+ * path the file actually lives at — matching prod behaviour.+ *+ * FAIL vs WARN+ * ------------+ * Only unambiguous breakage FAILS the gate (nav >=400, thrown errors, real+ * console errors, failed/4xx-5xx requests, broken images). Quality signals that+ * have legitimate exceptions (missing <title>/lang, alt-less images, links that+ * resolve nowhere) are WARN — surfaced, never red — so the failing signal stays+ * rock-solid and the gate keeps its credibility.+ *+ * USAGE+ * node scripts/test-pages.mjs # full sweep, spawns its own vite+ * node scripts/test-pages.mjs --route=/home # one route (repeatable)+ * node scripts/test-pages.mjs --concurrency=8 # tune parallelism (default 6)+ * node scripts/test-pages.mjs --warn-as-error # treat WARNs as failures too+ * HEALTH_BASE=http://localhost:3000 node scripts/test-pages.mjs # reuse a server+ *+ * Writes a machine-readable report to reports/health.json (gitignored).+ */import { chromium } from 'playwright';-import { spawn } from 'child_process';-import { setTimeout as wait } from 'timers/promises';+import { spawn } from 'node:child_process';+import { setTimeout as wait } from 'node:timers/promises';+import { readFileSync, existsSync, mkdirSync, writeFileSync } from 'node:fs';+import { fileURLToPath } from 'node:url';+import { dirname, resolve, join } from 'node:path';-const PORT = 3100;-const BASE = `http://localhost:${PORT}`;+const __dirname = dirname(fileURLToPath(import.meta.url));+const ROOT = resolve(__dirname, '..');-// Routes to visit. Some need params (template pages) — pass a placeholder-// agent id so they can boot.+// ── CLI ──────────────────────────────────────────────────────────────────────+const argv = process.argv.slice(2);+const flag = (name, fallback) => {+ const hit = argv.find((a) => a === `--${name}` || a.startsWith(`--${name}=`));+ if (!hit) return fallback;+ const eq = hit.indexOf('=');+ return eq === -1 ? true : hit.slice(eq + 1);+};+const onlyRoutes = argv.filter((a) => a.startsWith('--route=')).map((a) => a.slice('--route='.length));+const CONCURRENCY = Math.max(1, parseInt(flag('concurrency', '6'), 10) || 6);+const WARN_AS_ERROR = !!flag('warn-as-error', false);+const QUIET = !!flag('quiet', false);+const REUSE_BASE = process.env.HEALTH_BASE || null;+const PORT = parseInt(process.env.HEALTH_PORT || '3100', 10);+const BASE = REUSE_BASE || `http://localhost:${PORT}`;++// Sample params for template/dynamic routes that need an id to boot.const SAMPLE_AGENT = '0xdeadbeef';const SAMPLE_SOL_ASSET = 'So11111111111111111111111111111111111111112';const SAMPLE_USER = 'alice';-const ROUTES = [- // Top-level marketing / landing- '/',- '/home',- '/app',- '/create',- '/features',- '/login',- '/register',- '/forgot-password',- '/reset-password',- '/profile',-- // Agent / template pages++// Curated template/param routes that aren't in data/pages.json because they+// require an id. These exercise the dynamic-page boot path.+const TEMPLATE_ROUTES = [`/agent/${SAMPLE_AGENT}`,`/agent/${SAMPLE_AGENT}/edit`,`/agent/${SAMPLE_AGENT}/embed`,`/a/1/${SAMPLE_AGENT}/edit`,- `/a/1/${SAMPLE_AGENT}/embed`,`/a/sol/${SAMPLE_SOL_ASSET}`,`/u/${SAMPLE_USER}`,- '/agent-passport.html',- '/agent-badge.html',-- // Discover / marketplace- '/agents',- '/marketplace',- '/my-agents',- '/discover',- '/explore',-- // Dashboard- '/dashboard',- '/dashboard/actions',- '/dashboard/sessions',- '/dashboard/usage',- '/dashboard/wallets',- '/dashboard/storage',- '/dashboard/embed-policy',- '/dashboard/agent-pumpfun',-- // Studio / widgets / docs- '/studio',- '/widgets',- '/docs',- '/docs/widgets',-- // Other product pages- '/cz',- '/validation',- '/hydrate',`/reputation/?agent=1:${SAMPLE_AGENT}`,- '/settings',- '/admin',- '/pumpfun',- '/pump-live',- '/pump-dashboard',- '/strategy-lab',-- // Legal- '/legal/privacy',- '/legal/tos',-- // Standalone HTML viewers / artifacts'/embed.html?src=/avatars/cz.glb','/embed-test.html',- '/avatar-page.html',- `/avatars/${SAMPLE_AGENT}`,- '/avatar-artifact','/agent-embed.html','/a-edit.html','/a-embed.html',- '/artifact-example.html',- '/first-meet/',- '/lobehub/iframe/',];-// Dev-only failure patterns to ignore (CDN URLs, third-party CORS, etc).-// These work in production but not when running `vite dev` against localhost.+// ── Noise filters ──────────────────────────────────────────────────────────+// Things that fail ONLY under `vite dev` on localhost/Codespaces but work in+// production. Each entry is load-bearing — comment says why it's safe to ignore.const IGNORE_PATTERNS = [- /three\.ws\/.*agent-3d/, // hardcoded prod CDN URL- /ajax\.googleapis\.com/, // CDN script- /esm\.sh/, // CDN module- /marketplace\.olas\.network/, // third-party API, no CORS for localhost- /blocked by CORS policy/,+ // vite-dev HMR client: the big one. No vite client exists in prod.+ /\[vite\] failed to connect to websocket/,+ /WebSocket closed without opened/,+ /WebSocket connection to .*(app\.github\.dev|localhost).*failed/i,+ /failed to connect to websocket/i,+ /\/@vite\/client/,+ /node_modules\/vite\/dist\/client\/env\.mjs/,+ // Serverless functions need `vercel dev`, not `vite dev` — /api/* 404s locally.+ /localhost:\d+\/api\//,+ /three\.ws\/+api\//, // prod API hardcoded in demo/test pages+ /Unexpected token .+, .<!doctype /, // API returned HTML (no serverless locally)+ /Expected a JavaScript-or-Wasm module script but the server responded with a MIME type of "text\/html"/,+ // Separate dev-only services that aren't running under a bare `vite dev`.+ /localhost:2567/, // colyseus multiplayer server (`npm run dev:multi`)+ /localhost:\d+\/chat/, // chat is a separate Svelte app (`npm run dev` in chat/)+ // Third-party CDNs / APIs with no localhost CORS — fine in prod.+ /three\.ws\/.*agent-3d/,/three\.ws\/dist-lib/,- /three\.ws\/+api\//, // prod API hardcoded in demo/test pages (embed-test, artifact-example)- /localhost:\d+\/api\//, // serverless functions need `vercel dev`, not `vite dev`- /localhost:\d+\/chat/, // chat is a separate Svelte app (run `npm run dev` in chat/)- /\/wallet\/(connect-button|state).*\.js/, // cascades from esm.sh import in connect-button.js- /\/node_modules\/vite\/dist\/client\/env\.mjs/, // Vite dev injection 404s in some flows- /rpc\.\d+\.io/, // placeholder RPC URL from sample agent IDs- /Unexpected token .+, .<!doctype /, // API endpoint returned HTML instead of JSON (dev-only: no serverless functions)- /Expected a JavaScript-or-Wasm module script but the server responded with a MIME type of "text\/html"/, // Vite html-proxy MIME mismatch for public/ files served via dynamic paths+ /ajax\.googleapis\.com/,+ /esm\.sh/,+ /marketplace\.olas\.network/,+ /blocked by CORS policy/,+ /ipfs\.io/, // user-content gateway, blocked by ORB from a headless origin+ /ERR_BLOCKED_BY_ORB/, // Opaque Response Blocking on cross-origin media+ /rpc\.\d+\.io/, // placeholder RPC from sample agent ids+ /api\.mainnet-beta\.solana\.com/, // public RPC rate-limits/403s from CI+ /ingest\/static\/surveys/, // PostHog survey assets, blocked without consent+ /\/wallet\/(connect-button|state).*\.js/,+ /chrome-extension:\/\//,];+const isNoise = (text) => IGNORE_PATTERNS.some((re) => re.test(text));++// Environment-dependent module errors. Under `vite dev`, Vite's built-in static+// publicDir handler serves public/*.html verbatim (no transform), so inline+// `<script type=module>` bare specifiers like `@three-ws/agent-ui` fail to+// resolve — whereas the production build resolves them via its import map /+// bundler. We can't tell a genuine prod break from this dev-serving gap, so+// these are WARN, never a flaky FAIL. Flip with --warn-as-error to gate on them.+const ENV_MODULE_PATTERNS = [+ /Failed to resolve module specifier/,+ /Unexpected token .?export.?/,+ /Cannot use import statement outside a module/,+ /Failed to fetch dynamically imported module/,+ /error loading dynamically imported module/i,+];+const isEnvModule = (text) => ENV_MODULE_PATTERNS.some((re) => re.test(text));++// ── Vercel route resolver ────────────────────────────────────────────────────+// Replicates the subset of vercel.json route semantics that affect which file a+// pretty URL serves: ordered match, `dest` rewrites, `status` redirects, and+// `continue` header passthroughs. `has`-gated routes are skipped (we can't+// satisfy header/cookie conditions from a static probe).+function loadVercelRoutes() {+ const cfg = JSON.parse(readFileSync(join(ROOT, 'vercel.json'), 'utf8'));+ return (cfg.routes || [])+ .filter((r) => r.src && !r.has) // skip conditional routes+ .map((r) => {+ let re = null;+ try {+ re = new RegExp(`^${r.src}$`);+ } catch {+ re = null; // a src we can't compile just never matches+ }+ return { ...r, _re: re };+ });+}++function applyCaptures(template, match) {+ return String(template).replace(/\$(\d+)/g, (_, n) => match[Number(n)] ?? '');+}++// Resolve a pretty path to the path vite should actually serve, following+// rewrites and redirects. Returns { servePath, query, redirected }.+function resolveRoute(routes, rawPath) {+ const [pathOnly, query = ''] = rawPath.split('?');+ let current = pathOnly;+ let redirected = false;+ for (let hops = 0; hops < 8; hops++) {+ let matchedDest = null;+ for (const route of routes) {+ if (!route._re) continue;+ const m = current.match(route._re);+ if (!m) continue;+ // Redirect: follow the Location header on the same host.+ const status = route.status;+ const loc = route.headers && (route.headers.Location || route.headers.location);+ if (status && status >= 300 && status < 400 && loc) {+ const target = applyCaptures(loc, m);+ if (/^https?:\/\//.test(target)) return { servePath: current, query, redirected, external: target };+ current = target.split('?')[0];+ redirected = true;+ matchedDest = 'redirect';+ break; // restart scan on the new path+ }+ // Header-only passthrough (`continue`): keep scanning, path unchanged.+ if (route.continue) continue;+ // Rewrite: this is the file to serve.+ if (route.dest) {+ const dest = applyCaptures(route.dest, m).split('?')[0];+ return { servePath: dest, query, redirected };+ }+ }+ if (matchedDest !== 'redirect') break; // no rewrite, no further redirect+ }+ // No explicit rewrite — let vite resolve via its filesystem/clean-URL plugin,+ // exactly as Vercel falls back to the filesystem.+ return { servePath: current, query, redirected };+}++// ── Route inventory ──────────────────────────────────────────────────────────+function loadRoutes() {+ const set = new Set();+ try {+ const pages = JSON.parse(readFileSync(join(ROOT, 'data/pages.json'), 'utf8'));+ for (const section of pages.sections || []) {+ for (const item of section.items || section.pages || []) {+ if (!item.path || typeof item.path !== 'string') continue;+ if (item.indexable === false && item.path !== '/') continue;+ // Skip non-HTML surfaces (feeds, manifests) and external links.+ if (/\.(xml|txt|json|rss)$/.test(item.path)) continue;+ if (/^https?:\/\//.test(item.path)) continue;+ set.add(item.path);+ }+ }+ } catch {+ // pages.json missing/unparseable — fall back to template routes only.+ }+ for (const r of TEMPLATE_ROUTES) set.add(r);+ const all = [...set];+ return onlyRoutes.length ? all.filter((r) => onlyRoutes.includes(r)) : all;+}-function shouldIgnore(text) {- return IGNORE_PATTERNS.some((re) => re.test(text));+// A path is "servable" if a vercel route would resolve it, or the file exists on+// disk under public/ or pages/ (clean-URL → pages/<name>.html). Used for the+// dead-link WARN — deliberately conservative to avoid false positives.+function pathIsServable(routes, path) {+ if (!path || path === '#' || path.startsWith('mailto:') || path.startsWith('tel:')) return true;+ const clean = path.split('?')[0].split('#')[0];+ if (clean === '' || clean === '/') return true;+ const { servePath, external } = resolveRoute(routes, clean);+ if (external) return true;+ const rel = servePath.replace(/^\//, '');+ const candidates = [+ join(ROOT, 'public', rel),+ join(ROOT, 'public', rel + '.html'),+ join(ROOT, 'public', rel, 'index.html'),+ join(ROOT, 'pages', rel),+ join(ROOT, 'pages', rel + '.html'),+ join(ROOT, 'pages', rel, 'index.html'),+ ];+ return candidates.some((p) => existsSync(p));}+// ── Server lifecycle ─────────────────────────────────────────────────────────function startServer() {const proc = spawn('npx', ['vite', '--port', String(PORT), '--strictPort'], {+ cwd: ROOT,stdio: ['ignore', 'pipe', 'pipe'],env: { ...process.env, FORCE_COLOR: '0' },});- return new Promise((resolve, reject) => {- const timer = setTimeout(() => reject(new Error('vite did not start in 30s')), 30000);+ return new Promise((res, rej) => {+ const timer = setTimeout(() => rej(new Error('vite did not start in 60s')), 60000);proc.stdout.on('data', (d) => {- if (String(d).includes('ready in') || String(d).includes('Local:')) {+ if (/ready in|Local:/.test(String(d))) {clearTimeout(timer);- resolve(proc);+ res(proc);}});proc.stderr.on('data', (d) => process.stderr.write(d));- proc.on('exit', (code) => {- if (code !== 0) reject(new Error(`vite exited with code ${code}`));- });+ proc.on('exit', (code) => code !== 0 && rej(new Error(`vite exited ${code}`)));});}-async function checkRoute(browser, route) {+// ── Per-route check ──────────────────────────────────────────────────────────+async function checkRoute(browser, routes, route) {const ctx = await browser.newContext();const page = await ctx.newPage();- const errors = [];- const failures = [];+ const fails = [];+ const warns = [];++ // Uncaught app exceptions FAIL; environment-dependent module errors WARN.page.on('pageerror', (err) => {- const msg = `pageerror: ${err.message}`;- if (!shouldIgnore(msg)) errors.push(msg);+ const msg = `uncaught: ${err.message}`;+ if (isNoise(msg)) return;+ (isEnvModule(err.message) ? warns : fails).push(msg);});+ // console.error is gray — third-party widgets, analytics, and dev tooling all+ // log errors that don't mean the page is broken. Surface, never fail.page.on('console', (msg) => {if (msg.type() !== 'error') return;const text = msg.text();- // "Failed to load resource: …" is a cascade message from a failed- // request — the actual URL is already captured by requestfailed/response- // handlers below, where ignore patterns can be applied properly.- if (text.startsWith('Failed to load resource')) return;- const formatted = `console.error: ${text}`;- if (!shouldIgnore(formatted)) errors.push(formatted);+ if (text.startsWith('Failed to load resource')) return; // cascade; URL caught below+ if (!isNoise(`console.error: ${text}`)) warns.push(`console.error: ${text}`);});+ // A failed sub-request is gray (aborts, cancellations, flaky third parties).+ // The document's own status is the hard signal — captured via navStatus below.page.on('requestfailed', (req) => {const url = req.url();- if (url.startsWith('chrome-extension://')) return;- if (shouldIgnore(url)) return;- failures.push(`requestfailed: ${url} — ${req.failure()?.errorText}`);+ const errText = req.failure()?.errorText || '';+ if (isNoise(url) || isNoise(errText)) return;+ if (/ERR_ABORTED/.test(errText)) return; // intentional cancellation, not breakage+ warns.push(`requestfailed: ${url} — ${errText}`);});page.on('response', (res) => {const url = res.url();- if (res.status() >= 400 && !url.includes('favicon') && !shouldIgnore(url)) {- failures.push(`http ${res.status()}: ${url}`);+ if (res.status() >= 400 && !url.includes('favicon') && !isNoise(url)) {+ warns.push(`http ${res.status()}: ${url}`); // sub-resource; document via navStatus}});- let loadError = null;- try {- const resp = await page.goto(`${BASE}${route}`, {- waitUntil: 'domcontentloaded',- timeout: 15000,- });- // Give async boot code a moment to throw before we close the page.- await wait(2000);- if (!resp || resp.status() >= 400) {- loadError = `nav status ${resp?.status() ?? 'none'}`;++ const { servePath, query, external } = resolveRoute(routes, route);+ const prettyPath = route.split('?')[0];+ let navStatus = null;+ if (!external) {+ // goto with one retry on a thrown error (cold 3D transforms can blow a+ // timeout under parallel load); discard the failed attempt's captured+ // events so a transient first try never leaves stale errors behind.+ const tryGoto = async (url) => {+ for (let attempt = 0; attempt < 2; attempt++) {+ const mark = fails.length;+ const wmark = warns.length;+ try {+ const resp = await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 30000 });+ return resp?.status() ?? null;+ } catch (e) {+ fails.length = mark;+ warns.length = wmark;+ if (attempt === 1) {+ fails.push(`nav error: ${e.message}`);+ return null;+ }+ }+ }+ return null;+ };+ const mark = fails.length;+ const wmark = warns.length;+ navStatus = await tryGoto(`${BASE}${servePath}${query ? '?' + query : ''}`);+ // If the rewritten dest 404s, the clean pretty URL may still serve in dev+ // (vite's clean-URL plugin). Discard the dead-end attempt, then retry it.+ if ((navStatus === null || navStatus >= 400) && servePath !== prettyPath) {+ fails.length = mark;+ warns.length = wmark;+ navStatus = await tryGoto(`${BASE}${route}`);+ }+ if (navStatus === null || navStatus >= 400) fails.push(`nav status ${navStatus ?? 'none'}`);+ // Let async boot code run and throw before we tear down.+ await wait(2200);+ }++ // In-page DOM audit (only if the page actually loaded).+ if (!external && navStatus && navStatus < 400) {+ try {+ const audit = await page.evaluate(() => {+ const docUrl = location.href.split('#')[0];+ const imgs = [...document.images];+ const broken = []; // real src that failed to load → FAIL+ let emptySrc = 0; // empty/placeholder src (lazy-load, decorative) → WARN+ for (const i of imgs) {+ if (!(i.complete && i.naturalWidth === 0)) continue;+ const attr = (i.getAttribute('src') || '').trim();+ const resolved = i.currentSrc || i.src || '';+ if (!attr || resolved === docUrl || resolved === location.href) emptySrc++;+ else if (broken.length < 8) broken.push(resolved);+ }+ const noAlt = imgs.filter((i) => !i.alt && !i.getAttribute('aria-hidden')).length;+ const links = [...document.querySelectorAll('a[href]')]+ .map((a) => a.getAttribute('href'))+ .filter((h) => h && !/^(https?:|mailto:|tel:|#|javascript:|data:)/.test(h));+ const bodyText = (document.body?.innerText || '').trim().length;+ const hasCanvas = !!document.querySelector('canvas');+ const title = (document.title || '').trim();+ const lang = document.documentElement.getAttribute('lang') || '';+ return { broken, emptySrc, noAlt, links: [...new Set(links)], bodyText, hasCanvas, title, lang };+ });++ for (const src of audit.broken) fails.push(`broken image: ${src}`);+ if (audit.emptySrc > 0) warns.push(`${audit.emptySrc} image(s) with empty/placeholder src`);++ // Blank-render: no text AND no canvas/visual → likely a dead page. WARN+ // (3D/embed pages legitimately render to canvas with no copy).+ if (audit.bodyText < 1 && !audit.hasCanvas) warns.push('blank render (no text, no canvas)');+ if (!audit.title) warns.push('missing <title>');+ if (!audit.lang) warns.push('missing <html lang>');+ if (audit.noAlt > 0) warns.push(`${audit.noAlt} image(s) without alt text`);++ for (const href of audit.links.slice(0, 60)) {+ const abs = href.startsWith('/') ? href : new URL(href, `${BASE}${servePath}`).pathname;+ if (!pathIsServable(routes, abs)) warns.push(`link resolves nowhere: ${href}`);+ }+ } catch {+ // Evaluate can fail on pages that navigate away mid-audit — non-fatal.}- } catch (e) {- loadError = e.message;}+await ctx.close();- return { route, loadError, errors, failures };+ return { route, servePath, navStatus, fails, warns };+}++// ── Concurrency pool ─────────────────────────────────────────────────────────+async function runPool(items, limit, worker) {+ const results = new Array(items.length);+ let idx = 0;+ const runners = Array.from({ length: Math.min(limit, items.length) }, async () => {+ while (idx < items.length) {+ const i = idx++;+ results[i] = await worker(items[i], i);+ }+ });+ await Promise.all(runners);+ return results;}+// ── Main ─────────────────────────────────────────────────────────────────────async function main() {- console.log(`Starting vite on :${PORT}…`);- const server = await startServer();- let browser;+ const routes = loadVercelRoutes();+ const targets = loadRoutes();+ let server = null;+ let browser = null;let exitCode = 0;+try {+ if (!REUSE_BASE) {+ if (!QUIET) console.log(`Starting vite on :${PORT}…`);+ server = await startServer();+ } else if (!QUIET) {+ console.log(`Reusing server at ${BASE}`);+ }+browser = await chromium.launch({ args: ['--no-sandbox', '--disable-dev-shm-usage'] });- console.log(`Checking ${ROUTES.length} routes…\n`);- const results = [];- for (const route of ROUTES) {- const r = await checkRoute(browser, route);- results.push(r);- const issues = r.errors.length + r.failures.length + (r.loadError ? 1 : 0);- const tag = issues === 0 ? 'OK ' : 'FAIL';- console.log(` [${tag}] ${route} (${issues} issue${issues === 1 ? '' : 's'})`);+ if (!QUIET) console.log(`Checking ${targets.length} routes · concurrency ${CONCURRENCY}\n`);++ const results = await runPool(targets, CONCURRENCY, async (route) => {+ const r = await checkRoute(browser, routes, route);+ if (!QUIET) {+ const tag = r.fails.length ? 'FAIL' : r.warns.length ? 'warn' : ' ok ';+ const n = r.fails.length + r.warns.length;+ console.log(` [${tag}] ${route} (${r.fails.length} fail, ${r.warns.length} warn)`);+ }+ return r;+ });++ const failing = results.filter((r) => r.fails.length);+ const warning = results.filter((r) => !r.fails.length && r.warns.length);++ if (failing.length) {+ console.log('\n── FAILURES ───────────────────────────────────────────');+ for (const r of failing) {+ console.log(`\n${r.route} → ${r.servePath} (nav ${r.navStatus ?? '—'})`);+ for (const f of r.fails) console.log(` ✗ ${f}`);+ }}- console.log('\n--- Detail ---');- for (const r of results) {- if (!r.loadError && r.errors.length === 0 && r.failures.length === 0) continue;- exitCode = 1;- console.log(`\n${r.route}`);- if (r.loadError) console.log(` load: ${r.loadError}`);- for (const e of r.errors) console.log(` ${e}`);- for (const f of r.failures) console.log(` ${f}`);+ if (warning.length && !QUIET) {+ console.log('\n── WARNINGS (non-blocking) ────────────────────────────');+ for (const r of warning) {+ console.log(`\n${r.route}`);+ for (const w of r.warns) console.log(` · ${w}`);+ }}- const totalIssues = results.reduce(- (n, r) => n + r.errors.length + r.failures.length + (r.loadError ? 1 : 0),- 0,++ const totalFails = results.reduce((n, r) => n + r.fails.length, 0);+ const totalWarns = results.reduce((n, r) => n + r.warns.length, 0);+ console.log(+ `\nDone. ${totalFails} failure(s), ${totalWarns} warning(s) across ${targets.length} routes.`,);- console.log(`\nDone. ${totalIssues} issue(s) across ${ROUTES.length} routes.`);++ // Machine-readable report for CI artifacts.+ try {+ mkdirSync(join(ROOT, 'reports'), { recursive: true });+ writeFileSync(+ join(ROOT, 'reports/health.json'),+ JSON.stringify(+ { base: BASE, routes: targets.length, totalFails, totalWarns, results },+ null,+ 2,+ ),+ );+ } catch {+ /* report write is best-effort */+ }++ if (totalFails > 0 || (WARN_AS_ERROR && totalWarns > 0)) exitCode = 1;} finally {if (browser) await browser.close();- server.kill('SIGTERM');+ if (server) server.kill('SIGTERM');}process.exit(exitCode);}diff --git a/scripts/verify-ibm-pages.mjs b/scripts/verify-ibm-pages.mjsnew file mode 100644index 000000000..6e6aef66b--- /dev/null+++ b/scripts/verify-ibm-pages.mjs@@ -0,0 +1,364 @@+#!/usr/bin/env node+// Runtime browser gate for the /ibm showcase.+//+// For every page under pages/ibm/ this loads it in headless Chrome and proves+// the things a structural/grep check (scripts/verify-ibm-surface.mjs) and the+// unit tests cannot:+//+// • the page actually renders its 3D scene — verified by instrumenting the+// WebGL context and counting real draw calls. Screenshots and gl.readPixels+// are unreliable under headless swiftshader (cleared back buffer, no GPU);+// draw calls are not. An "engine" page that issues zero draws is broken.+// • zero uncaught exceptions and zero first-party console errors.+// • the page degrades HONESTLY when watsonx is unconfigured — an /api/ibm+// response of 503 {"configured":false} is an EXPECTED state, never a+// failure. The page must render its empty/degraded UI without throwing.+// • the primary heading and interactive controls are present and reachable.+//+// Self-contained and durable on purpose:+// • resolves Chrome dynamically (env → puppeteer → ~/.cache glob), so it does+// not rot when the cached Chrome version bumps.+// • starts its own Vite server on a free port, or reuses one already on :3000.+// No "run npm run dev first" precondition.+//+// node scripts/verify-ibm-pages.mjs # all pages+// node scripts/verify-ibm-pages.mjs oracle twin # a subset (by slug)+// HEADFUL=1 node scripts/verify-ibm-pages.mjs # watch it run+// LOG_ALL=1 node scripts/verify-ibm-pages.mjs # stream browser console++import { existsSync, readdirSync } from 'node:fs';+import { join, dirname } from 'node:path';+import { fileURLToPath } from 'node:url';+import { homedir } from 'node:os';+import { createServer } from 'node:net';+import { spawn } from 'node:child_process';+import { get as httpGet } from 'node:http';+import puppeteer from 'puppeteer';++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`,+};++// ── Page contract ────────────────────────────────────────────────────────────+// `engine: true` means the page mounts a Three.js scene and MUST issue WebGL+// draw calls. `engine: false` pages (content/forms) only need to render cleanly.+const PAGES = [+ { slug: 'index', path: '/ibm', engine: false },+ { slug: 'galaxy', path: '/ibm/galaxy', engine: true },+ { slug: 'oracle', path: '/ibm/oracle', engine: true },+ { slug: 'trust-layer', path: '/ibm/trust-layer', engine: true },+ { slug: 'proof', path: '/ibm/proof', engine: true },+ { slug: 'vision', path: '/ibm/vision', engine: true },+ { slug: 'twin', path: '/ibm/twin', engine: true },+ { slug: 'identity', path: '/ibm/identity', engine: false },+];++// Browser-side instrumentation, installed before any page script runs.+function instrument() {+ window.__glDrawCalls = 0;+ window.__pageErrors = [];+ const wrap = (proto) => {+ if (!proto) return;+ for (const m of ['drawArrays', 'drawElements', 'drawArraysInstanced', 'drawElementsInstanced']) {+ const orig = proto[m];+ if (typeof orig === 'function') {+ proto[m] = function (...args) {+ window.__glDrawCalls++;+ return orig.apply(this, args);+ };+ }+ }+ };+ wrap(window.WebGLRenderingContext && window.WebGLRenderingContext.prototype);+ wrap(window.WebGL2RenderingContext && window.WebGL2RenderingContext.prototype);+ window.addEventListener('unhandledrejection', (e) => {+ window.__pageErrors.push('unhandledrejection: ' + String((e.reason && e.reason.stack) || e.reason));+ });+}++// Noise that is never a real defect: Vite's HMR socket, autoplay-policy gripes,+// and anything originating from an /api/ call (handled via response status).+const IGNORE_CONSOLE = [+ /\[vite\]/i,+ /@vite\/client/i, // HMR client+ /WebSocket closed without opened/i, // HMR socket in port-forwarded envs (Codespaces)+ /WebSocket connection to .* failed/i,+ /Error during WebSocket handshake/i,+ /the AudioContext was not allowed to start/i,+ /Tracking Prevention/i,+ /Failed to load resource.*\/api\//i, // API degradation is judged by status, not console+ /\b(403|429|503)\b.*\/api\//i,+];+// An /api response with one of these is the documented "watsonx unconfigured"+// degraded state — expected, not a failure.+const DEGRADED_STATUSES = new Set([402, 403, 503]);++function isIgnorableConsole(text) {+ return IGNORE_CONSOLE.some((re) => re.test(text));+}++// ── Chrome resolution (durable) ──────────────────────────────────────────────+function resolveChrome() {+ const tries = [];+ const push = (p, why) => p && tries.push({ p, why });+ push(process.env.CHROME_PATH, 'CHROME_PATH');+ push(process.env.PUPPETEER_EXECUTABLE_PATH, 'PUPPETEER_EXECUTABLE_PATH');+ try {+ push(puppeteer.executablePath(), 'puppeteer.executablePath()');+ } catch {+ /* puppeteer has no opinion without a downloaded browser */+ }+ // Glob the puppeteer cache and prefer the newest version present.+ const cache = join(homedir(), '.cache', 'puppeteer', 'chrome');+ if (existsSync(cache)) {+ const versions = readdirSync(cache)+ .filter((d) => d.startsWith('linux-') || d.startsWith('mac') || d.startsWith('win'))+ .sort()+ .reverse();+ for (const v of versions) {+ for (const rel of ['chrome-linux64/chrome', 'chrome-mac-x64/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing', 'chrome-win64/chrome.exe']) {+ push(join(cache, v, rel), `cache:${v}`);+ }+ }+ }+ for (const sys of ['/usr/bin/google-chrome', '/usr/bin/google-chrome-stable', '/usr/bin/chromium', '/usr/bin/chromium-browser']) {+ push(sys, 'system');+ }+ const found = tries.find((t) => {+ try {+ return existsSync(t.p);+ } catch {+ return false;+ }+ });+ if (!found) {+ throw new Error(+ 'No Chrome binary found. Install one with:\n npx puppeteer browsers install chrome\n' ++ 'or set CHROME_PATH=/path/to/chrome',+ );+ }+ return found.p;+}++// ── Dev server (reuse :3000 or spawn an ephemeral one) ───────────────────────+function probe(url, timeoutMs = 1500) {+ return new Promise((resolve) => {+ const req = httpGet(url, (res) => {+ res.resume();+ resolve(res.statusCode || 0);+ });+ req.setTimeout(timeoutMs, () => req.destroy());+ req.on('error', () => resolve(0));+ });+}++function freePort() {+ return new Promise((resolve, reject) => {+ const srv = createServer();+ srv.unref();+ srv.on('error', reject);+ srv.listen(0, () => {+ const { port } = srv.address();+ srv.close(() => resolve(port));+ });+ });+}++async function startServer() {+ if (await probe('http://localhost:3000/ibm')) {+ return { base: 'http://localhost:3000', stop: async () => {} };+ }+ const port = await freePort();+ const bin = join(ROOT, 'node_modules', '.bin', 'vite');+ const child = spawn(bin, ['--port', String(port), '--strictPort'], {+ cwd: ROOT,+ stdio: process.env.LOG_ALL ? 'inherit' : 'ignore',+ env: process.env,+ });+ const base = `http://localhost:${port}`;+ const deadline = Date.now() + 60_000;+ while (Date.now() < deadline) {+ if (child.exitCode != null) throw new Error(`vite exited early (code ${child.exitCode})`);+ if (await probe(`${base}/ibm`)) {+ return {+ base,+ stop: async () => {+ child.kill('SIGTERM');+ },+ };+ }+ await new Promise((r) => setTimeout(r, 400));+ }+ child.kill('SIGKILL');+ throw new Error('vite did not become ready within 60s');+}++// ── Per-page check ───────────────────────────────────────────────────────────+async function checkPage(browser, base, page) {+ const tab = await browser.newPage();+ await tab.evaluateOnNewDocument(instrument);+ const consoleErrors = [];+ const failedAssets = [];+ const degraded = [];++ tab.on('console', (msg) => {+ if (process.env.LOG_ALL) console.log(C.d(` [${page.slug} ${msg.type()}] ${msg.text()}`));+ if (msg.type() === 'error' && !isIgnorableConsole(msg.text())) consoleErrors.push(msg.text());+ });+ tab.on('pageerror', (err) => {+ if (!isIgnorableConsole(err.message)) consoleErrors.push('pageerror: ' + err.message);+ });+ tab.on('requestfailed', (req) => {+ const u = req.url();+ if (u.includes('@vite') || u.startsWith('ws:') || u.includes('/api/')) return;+ failedAssets.push(`${req.method()} ${u.replace(base, '')} — ${req.failure()?.errorText}`);+ });+ tab.on('response', (res) => {+ const u = res.url();+ const s = res.status();+ if (u.includes('/api/')) {+ if (DEGRADED_STATUSES.has(s)) degraded.push(`${s} ${u.replace(base, '')}`);+ else if (s >= 400) consoleErrors.push(`api ${s} ${u.replace(base, '')}`);+ return;+ }+ // First-party asset that 4xx/5xx'd (js/css/html/wasm/glb).+ if (s >= 400 && u.startsWith(base) && /\.(js|mjs|css|html|wasm|glb|gltf|json)(\?|$)/.test(u)) {+ failedAssets.push(`HTTP ${s} ${u.replace(base, '')}`);+ }+ });++ const errors = [];+ const url = base + page.path;+ try {+ await tab.goto(url, { waitUntil: 'domcontentloaded', timeout: 30_000 });+ } catch (e) {+ errors.push(`navigation failed: ${e.message}`);+ await tab.close();+ return { page, errors, degraded, draws: 0 };+ }++ // Heading must render (page isn't a blank/404 shell).+ const hasHeading = await tab+ .waitForFunction(() => !!document.querySelector('h1, h2') && document.body.innerText.trim().length > 40, { timeout: 15_000 })+ .then(() => true)+ .catch(() => false);+ if (!hasHeading) errors.push('no heading / empty body after load');++ // Engine pages must actually draw. RAF-driven scenes accumulate draws on+ // load; give it room, then nudge a primary control if still idle.+ let draws = 0;+ if (page.engine) {+ draws = await waitForDraws(tab, 12_000);+ if (draws === 0) {+ await clickPrimary(tab);+ draws = await waitForDraws(tab, 6_000);+ }+ if (draws === 0) errors.push('engine page issued zero WebGL draw calls (scene did not render)');+ }++ // Settle so late console errors / unhandled rejections surface.+ await new Promise((r) => setTimeout(r, 1200));+ const pageErrors = await tab+ .evaluate(() => window.__pageErrors || [])+ .then((arr) => arr.filter((e) => !isIgnorableConsole(e)))+ .catch(() => []);++ // Interactive surface: at least one real control, none stuck disabled-forever.+ const controls = await tab.evaluate(() => {+ const els = [...document.querySelectorAll('button, [role="button"], a.btn, input[type="submit"]')];+ return { total: els.length, disabled: els.filter((e) => e.disabled).length };+ });+ if (controls.total === 0) errors.push('no interactive controls found');++ errors.push(...consoleErrors.map((e) => `console: ${e}`));+ errors.push(...failedAssets.map((e) => `asset: ${e}`));+ errors.push(...pageErrors.map((e) => `uncaught: ${e}`));++ await tab.close();+ return { page, errors, degraded, draws, controls };+}++function waitForDraws(tab, timeout) {+ return tab+ .waitForFunction(() => window.__glDrawCalls > 0, { timeout, polling: 200 })+ .then(() => tab.evaluate(() => window.__glDrawCalls))+ .catch(() => tab.evaluate(() => window.__glDrawCalls || 0).catch(() => 0));+}++async function clickPrimary(tab) {+ try {+ await tab.evaluate(() => {+ const btn = [...document.querySelectorAll('button, a.btn')].find((b) => {+ const r = b.getBoundingClientRect();+ return !b.disabled && r.width > 0 && r.height > 0 && !/nav|menu|close|theme/i.test(b.className + b.id);+ });+ if (btn) btn.click();+ });+ await new Promise((r) => setTimeout(r, 800));+ } catch {+ /* best effort */+ }+}++// ── Main ─────────────────────────────────────────────────────────────────────+async function main() {+ const filter = process.argv.slice(2);+ const targets = filter.length ? PAGES.filter((p) => filter.includes(p.slug)) : PAGES;+ if (!targets.length) {+ console.error(`No matching pages. Known slugs: ${PAGES.map((p) => p.slug).join(', ')}`);+ process.exit(2);+ }++ const chrome = resolveChrome();+ console.log(C.d(`chrome: ${chrome}`));+ const server = await startServer();+ console.log(C.d(`server: ${server.base}\n`));+ console.log(C.b(`IBM showcase — runtime gate · ${targets.length} page(s)\n`));++ const browser = await puppeteer.launch({+ executablePath: chrome,+ headless: !process.env.HEADFUL,+ // Software WebGL: recent Chrome gates SwiftShader behind --enable-unsafe-swiftshader.+ args: ['--no-sandbox', '--disable-dev-shm-usage', '--use-gl=angle', '--use-angle=swiftshader', '--enable-unsafe-swiftshader', '--ignore-gpu-blocklist'],+ defaultViewport: { width: 1440, height: 900 },+ });++ const results = [];+ try {+ for (const page of targets) {+ const res = await checkPage(browser, server.base, page);+ results.push(res);+ const ok = res.errors.length === 0;+ const marker = ok ? C.g('●') : C.r('●');+ const drawInfo = page.engine ? C.d(` · ${res.draws} draws`) : '';+ const degInfo = res.degraded.length ? C.y(` · degraded(${res.degraded.length})`) : '';+ console.log(`${marker} ${C.b(page.path)}${drawInfo}${degInfo}`);+ if (!ok) res.errors.forEach((e) => console.log(` ${C.r('✗')} ${e}`));+ else if (res.degraded.length && process.env.LOG_ALL)+ res.degraded.forEach((d) => console.log(` ${C.y('○')} ${d} (watsonx unconfigured — honest degrade)`));+ }+ } finally {+ await browser.close();+ await server.stop();+ }++ const failed = results.filter((r) => r.errors.length);+ console.log('');+ if (failed.length) {+ console.log(C.r(`✗ ${failed.length}/${results.length} page(s) failed the runtime gate.`));+ process.exit(1);+ }+ const anyDegraded = results.some((r) => r.degraded.length);+ console.log(C.g(`✓ all ${results.length} /ibm page(s) render, draw, and handle errors cleanly.`));+ if (anyDegraded) console.log(C.d(' (some /api/ibm endpoints returned the honest "watsonx unconfigured" degrade — expected.)'));+}++main().catch((e) => {+ console.error(C.r(`\n❌ ${e.message}`));+ process.exit(1);+});diff --git a/src/agent-edit.js b/src/agent-edit.jsindex 4457660c1..689034f05 100644--- a/src/agent-edit.js+++ b/src/agent-edit.js@@ -1042,13 +1042,38 @@ function renderVoiceStatus() {}}+// null = not yet fetched+// false = fetched, ElevenLabs not configured+// [] = fetched, configured, no voices (edge case)+// [...] = fetched, configured, voices available+let voiceEnabledFetched = false;+async function loadVoiceList(filter = '') {const container = $('voice-list');- if (!voicesCache) {+ if (!voiceEnabledFetched) {+ voiceEnabledFetched = true;try {const r = await apiFetch(`${API_BASE}/tts/eleven/voices`, { credentials: 'include' });if (!r.ok) throw new Error(`HTTP ${r.status}`);const j = await r.json();+ if (j.enabled === false) {+ voicesCache = false;+ const filterGroup = $('voice-filter')?.closest('.form-group');+ if (filterGroup) filterGroup.hidden = true;+ container.innerHTML = `+ <div class="voice-unconfigured">+ <div class="voice-unconfigured-icon">🎙</div>+ <div class="voice-unconfigured-title">ElevenLabs not configured</div>+ <p class="voice-unconfigured-body">+ Add <code>ELEVENLABS_API_KEY</code> to your environment variables to unlock+ AI voice selection, voice cloning, and fine-tuned delivery controls.+ </p>+ <a class="btn-ghost" href="https://elevenlabs.io" target="_blank" rel="noopener">+ Get an API key ›+ </a>+ </div>`;+ return;+ }voicesCache = j.voices || [];if (j.models?.length) {voiceModelsCache = j.models;@@ -1059,6 +1084,7 @@ async function loadVoiceList(filter = '') {return;}}+ if (voicesCache === false) return;renderVoiceList(filter);}@@ -1077,13 +1103,13 @@ function renderVoiceList(filter = '') {<span>${escapeHtml(v.name || v.voice_id)}</span><span class="voice-tile-meta">${escapeHtml(v.category || '')}</span></div>- ${v.preview_url ? '<button type="button" class="voice-tile-play" title="Preview">▶</button>' : ''}+ ${v.preview_url ? '<button type="button" class="voice-tile-play" aria-label="Preview voice" title="Preview">▶</button>' : ''}</div>`).join('');container.querySelectorAll('.voice-tile').forEach((tile) => {tile.addEventListener('click', (e) => {if (e.target.classList.contains('voice-tile-play')) {- playVoicePreview(tile.dataset.preview);+ playVoicePreview(tile.dataset.preview, e.target);return;}selectVoice(tile.dataset.voiceId);@@ -1091,11 +1117,33 @@ function renderVoiceList(filter = '') {});}-function playVoicePreview(url) {+let voicePreviewBtn = null;++function playVoicePreview(url, btn) {if (!url) return;+ // Stop current preview and reset its button+ if (voicePreviewBtn && voicePreviewBtn !== btn) {+ voicePreviewBtn.textContent = '▶';+ voicePreviewBtn.classList.remove('playing');+ }+ // Toggle: clicking the playing button stops it+ if (voicePreviewAudio && !voicePreviewAudio.paused && voicePreviewBtn === btn) {+ voicePreviewAudio.pause();+ if (btn) { btn.textContent = '▶'; btn.classList.remove('playing'); }+ voicePreviewBtn = null;+ return;+ }try { voicePreviewAudio?.pause(); } catch {}voicePreviewAudio = new Audio(url);- voicePreviewAudio.play().catch(() => {});+ voicePreviewBtn = btn || null;+ if (btn) { btn.textContent = '■'; btn.classList.add('playing'); }+ voicePreviewAudio.addEventListener('ended', () => {+ if (btn) { btn.textContent = '▶'; btn.classList.remove('playing'); }+ if (voicePreviewBtn === btn) voicePreviewBtn = null;+ });+ voicePreviewAudio.play().catch(() => {+ if (btn) { btn.textContent = '▶'; btn.classList.remove('playing'); }+ });}async function selectVoice(voiceId) {diff --git a/src/ibm-vision.js b/src/ibm-vision.jsindex cd7cd355e..0bada93c7 100644--- a/src/ibm-vision.js+++ b/src/ibm-vision.js@@ -4,7 +4,8 @@// looking at, and sends it to a Granite Vision model on watsonx.ai (via// /api/ibm/vision). Granite returns a complete identity inferred purely from how// the avatar looks — appearance, vibe, persona, a name, a bio, a fitting voice —-// which we render as an identity card. You can also upload any image.+// which we render as an identity card. You can also upload any image or drag one+// anywhere onto the page.//// Every read is a real multimodal inference. When watsonx isn't configured the// panel says so honestly rather than inventing a description.@@ -26,19 +27,25 @@ const BUILTINS = [{ id: 'builtin-cz', name: 'CZ', model_url: '/avatars/cz.glb', builtin: true },];+// Loading steps — shown sequentially so the wait feels transparent, not opaque.+const LOAD_STEPS = ['Capturing frame…', 'Sending to Granite…', 'Reading identity…'];+const els = {};const state = {subjects: [],- current: null, // { ...subject } or { upload:true, dataUrl, name }+ current: null, // { ...subject } | { upload:true, dataUrl, name, subject }busy: false,};// Three.js-let renderer, scene, camera, controls, env, clock;+let renderer, scene, camera, controls, env;let modelRoot = null;let loadToken = 0;-const dbg = (window.__vision = {+// Step-progress timer handle+let stepTimer = null;++export const dbg = (window.__vision = {ready: false,status: 'init',subjects: 0,@@ -59,10 +66,12 @@ function boot() {function cacheEls() {for (const id of ['vision-stage', 'v-photo', 'v-photo-img', 'v-model', 'v-stage-hint',- 'v-idle', 'v-loading', 'v-result', 'v-rawstate', 'v-error', 'v-error-title', 'v-error-sub', 'v-error-retry',+ 'v-idle', 'v-loading', 'v-loading-step',+ 'v-result', 'v-usage-badge',+ 'v-rawstate', 'v-error', 'v-error-title', 'v-error-sub', 'v-error-retry','v-name', 'v-bio', 'v-appearance', 'v-appearance-wrap', 'v-persona', 'v-persona-wrap','v-vibe', 'v-vibe-wrap', 'v-tags', 'v-tags-wrap', 'v-voice', 'v-voice-wrap', 'v-raw',- 'v-copy', 'v-create', 'v-subjects', 'v-upload', 'v-file', 'v-show',+ 'v-copy', 'v-read-again', 'v-read-again-raw', 'v-create', 'v-subjects', 'v-upload', 'v-file', 'v-show',]) {els[id] = $(id);}@@ -80,7 +89,7 @@ async function loadSubjects() {if (body.visionModel) model = body.visionModel.replace(/^ibm\//, '');}} catch {- /* dev proxy / not-deployed: fall back to built-ins only */+ /* dev / not-yet-deployed: fall back to built-ins */}els['v-model'].textContent = model;state.subjects = [...BUILTINS, ...fetched];@@ -117,14 +126,17 @@ function selectSubject(i) {for (const b of els['v-subjects'].querySelectorAll('.subject')) {b.classList.toggle('sel', Number(b.dataset.index) === i);}- // Switch to 3D view.+ showStage();+ loadModel(s.model_url);+}++function showStage() {els['v-photo'].style.display = 'none';els['vision-stage'].style.display = 'block';if (els['v-stage-hint']) els['v-stage-hint'].style.opacity = '1';- loadModel(s.model_url);}-// ── Upload ───────────────────────────────────────────────────────────────────+// ── Upload / Drag-and-drop ────────────────────────────────────────────────────function handleUpload(file) {if (!file || !file.type.startsWith('image/')) return;const reader = new FileReader();@@ -148,6 +160,7 @@ async function showGranite() {const prevLabel = els['v-show'].textContent;els['v-show'].textContent = 'Looking…';setState('loading');+ startLoadingSteps();try {const payload = await buildPayload(state.current);@@ -160,18 +173,26 @@ async function showGranite() {if (!res.ok) {if (res.status === 503 && body.error === 'watsonx_unavailable') {- return showError('IBM Granite Vision isn’t connected', body.error_description ||- 'Granite Vision runs on watsonx.ai. Once credentials are configured, it can see your avatar.');+ return showError(+ 'IBM Granite Vision isn’t connected',+ body.error_description ||+ 'Granite Vision runs on watsonx.ai. Once credentials are configured, it can see your avatar.',+ false,+ );}- return showError('Granite couldn’t look', body.error_description || `Request failed (${res.status}).`);+ return showError(+ body.error === 'model_unavailable' ? 'Model not available in this region' : 'Granite couldn’t look',+ body.error_description || `Request failed (${res.status}).`,+ );}dbg.lastResult = body;- if (body.vision && body.vision.structured) renderResult(body.vision);+ if (body.vision && body.vision.structured) renderResult(body.vision, body);else renderRaw(body.raw || (body.vision && body.vision.persona) || 'Granite returned no readable description.');} catch (err) {showError('Granite couldn’t look', err?.message || 'Network error.');} finally {+ stopLoadingSteps();state.busy = false;els['v-show'].disabled = false;els['v-show'].textContent = prevLabel;@@ -179,8 +200,8 @@ async function showGranite() {}// Decide what image to send: an uploaded data URL, a clean live capture of the 3D-// frame, or the avatar's thumbnail URL for the server to fetch (when the captured-// canvas is cross-origin-tainted).+// frame, or the avatar's thumbnail URL for the server to fetch (when the canvas+// is cross-origin-tainted, e.g. headless or public CDN textures).async function buildPayload(subject) {if (subject.upload) return { image: subject.dataUrl, subject: 'image' };@@ -194,8 +215,8 @@ async function buildPayload(subject) {throw new Error('Could not capture this avatar — try another or upload an image.');}-// Capture the current 3D frame as a JPEG data URL. Renders once against a readable-// background first. Returns null if the canvas is tainted (cross-origin textures).+// Capture the current 3D frame as a JPEG data URL against a solid background so+// Granite sees the avatar clearly. Returns null if the canvas is tainted.function captureFrame() {if (!renderer || !modelRoot) return null;const prevBg = scene.background;@@ -205,14 +226,28 @@ function captureFrame() {const url = renderer.domElement.toDataURL('image/jpeg', 0.9);return url && url.length > 1000 ? url : null;} catch {- return null; // SecurityError → tainted canvas+ return null; // SecurityError: tainted canvas from cross-origin textures} finally {scene.background = prevBg;}}+// ── Step progress ─────────────────────────────────────────────────────────────+function startLoadingSteps() {+ let i = 0;+ if (els['v-loading-step']) els['v-loading-step'].textContent = LOAD_STEPS[0];+ stopLoadingSteps(); // clear any prior timer+ stepTimer = setInterval(() => {+ i = Math.min(i + 1, LOAD_STEPS.length - 1);+ if (els['v-loading-step']) els['v-loading-step'].textContent = LOAD_STEPS[i];+ }, 1300);+}+function stopLoadingSteps() {+ if (stepTimer) { clearInterval(stepTimer); stepTimer = null; }+}+// ── Result rendering ─────────────────────────────────────────────────────────-function renderResult(v) {+function renderResult(v, response) {els['v-name'].textContent = v.suggested_name || 'Unnamed';setText(els['v-bio'], v.bio);setField('v-appearance', 'v-appearance-wrap', v.appearance);@@ -221,22 +256,24 @@ function renderResult(v) {renderChips('v-tags', 'v-tags-wrap', v.tone_tags || []);setField('v-voice', 'v-voice-wrap', v.voice);- // Stash the identity for the agent creator + copy.+ // Token usage badge: makes the demo feel transparent and shows it's real AI.+ const u = response?.usage;+ if (u && els['v-usage-badge']) {+ const total = u.total_tokens || ((u.prompt_tokens || 0) + (u.completion_tokens || 0));+ els['v-usage-badge'].textContent = `${total} tokens · ${(response.model || '').replace('ibm/', '')}`;+ els['v-usage-badge'].hidden = false;+ }++ // Stash for agent creator deep-link + copy.const identity = {- name: v.suggested_name,- bio: v.bio,- appearance: v.appearance,- persona: v.persona,- vibe: v.vibe,- tone_tags: v.tone_tags,- voice: v.voice,+ name: v.suggested_name, bio: v.bio, appearance: v.appearance,+ persona: v.persona, vibe: v.vibe, tone_tags: v.tone_tags, voice: v.voice,};els['v-copy'].onclick = () => copyJson(identity, els['v-copy']);- try {- localStorage.setItem('gv:identity', JSON.stringify(identity));- } catch {- /* storage may be unavailable; the create link still works */- }+ if (els['v-read-again']) els['v-read-again'].onclick = showGranite;+ if (els['v-read-again-raw']) els['v-read-again-raw'].onclick = showGranite;+ try { localStorage.setItem('gv:identity', JSON.stringify(identity)); } catch { /* ok */ }+const q = new URLSearchParams();if (v.suggested_name) q.set('name', v.suggested_name);if (v.bio) q.set('bio', v.bio);@@ -250,16 +287,20 @@ function renderRaw(text) {setState('rawstate');}-function showError(title, sub) {+function showError(title, sub, retryable = true) {dbg.status = 'error';dbg.error = sub;els['v-error-title'].textContent = title;els['v-error-sub'].textContent = sub;+ els['v-error-retry'].hidden = !retryable;setState('error');}function setState(name) {- const map = { idle: 'v-idle', loading: 'v-loading', result: 'v-result', rawstate: 'v-rawstate', error: 'v-error' };+ const map = {+ idle: 'v-idle', loading: 'v-loading', result: 'v-result',+ rawstate: 'v-rawstate', error: 'v-error',+ };for (const [key, id] of Object.entries(map)) {els[id].classList.toggle('on', key === name);}@@ -281,7 +322,6 @@ function setupThree() {stage.appendChild(renderer.domElement);scene = new THREE.Scene();-const pmrem = new THREE.PMREMGenerator(renderer);env = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;scene.environment = env;@@ -308,7 +348,6 @@ function setupThree() {controls.autoRotateSpeed = 0.9;controls.addEventListener('start', () => (controls.autoRotate = false));- clock = new THREE.Clock();const ro = new ResizeObserver(resize);ro.observe(stage);resize();@@ -322,7 +361,7 @@ function setupThree() {let _draco = null;function gltfLoader() {const loader = new GLTFLoader();- loader.setCrossOrigin('anonymous'); // request CORS-clean textures so captures aren't tainted+ loader.setCrossOrigin('anonymous');if (!_draco) {_draco = new DRACOLoader();_draco.setDecoderPath('https://www.gstatic.com/draco/versioned/decoders/1.5.6/');@@ -341,10 +380,7 @@ function loadModel(url) {gltfLoader().load(url,(gltf) => {- if (token !== loadToken) {- disposeObject(gltf.scene);- return; // a newer selection superseded this load- }+ if (token !== loadToken) { disposeObject(gltf.scene); return; }modelRoot = gltf.scene;frameModel(modelRoot);scene.add(modelRoot);@@ -356,26 +392,25 @@ function loadModel(url) {(err) => {if (token !== loadToken) return;console.warn('[granite-vision] model load failed', url, err);- // Don't blank the UI — if a thumbnail exists we can still show Granite that.if (!state.current?.thumbnail) {- showError('Couldn’t load this avatar', 'The 3D model failed to load. Pick another, or upload an image.');+ showError(+ 'Couldn’t load this avatar',+ 'The 3D model failed to load. Pick another, or upload an image.',+ );}},);}-// Center the model on the origin and frame the camera to it.function frameModel(root) {const box = new THREE.Box3().setFromObject(root);const size = box.getSize(new THREE.Vector3());const center = box.getCenter(new THREE.Vector3());root.position.x -= center.x;root.position.z -= center.z;- root.position.y -= box.min.y; // feet on the ground plane+ root.position.y -= box.min.y; // feet on the groundconst height = size.y || 1.7;- // Feet now sit at y=0, so aim at the upper body (where the face/identity lives)- // and stand back far enough to frame the whole figure with headroom.controls.target.set(0, height * 0.62, 0);const dist = height * 1.5 + 0.6;camera.position.set(0, height * 0.7, dist);@@ -400,21 +435,61 @@ function bindUI() {els['v-upload'].addEventListener('click', () => els['v-file'].click());els['v-file'].addEventListener('change', (e) => handleUpload(e.target.files?.[0]));els['v-error-retry'].addEventListener('click', () => setState('idle'));- // Fade the stage hint once the user starts interacting.- const fade = () => {++ // Fade the stage hint once the user first touches it.+ els['vision-stage'].addEventListener('pointerdown', () => {if (els['v-stage-hint']) els['v-stage-hint'].style.opacity = '0';- };- els['vision-stage'].addEventListener('pointerdown', fade, { once: true });+ }, { once: true });++ // ── Drag-and-drop anywhere on the page ───────────────────────────────────+ // Users can drag an image from desktop/Finder/browser onto the stage or the+ // photo area without having to click Upload first.+ let dragDepth = 0;+ document.addEventListener('dragenter', (e) => {+ if (!hasDragFile(e)) return;+ dragDepth++;+ document.body.classList.add('drag-active');+ });+ document.addEventListener('dragleave', () => {+ dragDepth = Math.max(0, dragDepth - 1);+ if (dragDepth === 0) document.body.classList.remove('drag-active');+ });+ document.addEventListener('dragover', (e) => {+ if (hasDragFile(e)) e.preventDefault();+ });+ document.addEventListener('drop', (e) => {+ dragDepth = 0;+ document.body.classList.remove('drag-active');+ const file = e.dataTransfer?.files?.[0];+ if (file?.type.startsWith('image/')) {+ e.preventDefault();+ handleUpload(file);+ }+ });++ // ── Keyboard shortcuts ────────────────────────────────────────────────────+ document.addEventListener('keydown', (e) => {+ // Enter triggers Show Granite when not in a text input.+ if (e.key === 'Enter' && !isInput(e.target) && !state.busy) showGranite();+ // Escape → back to idle (dismiss result/error, clear focus).+ if (e.key === 'Escape') {+ const active = ['v-result', 'v-rawstate', 'v-error'].find((id) => els[id]?.classList.contains('on'));+ if (active) setState('idle');+ }+ });+}++function hasDragFile(e) {+ return Array.from(e.dataTransfer?.items || []).some((i) => i.kind === 'file');+}+function isInput(el) {+ return el && (el.tagName === 'INPUT' || el.tagName === 'TEXTAREA' || el.isContentEditable);}// ── Helpers ──────────────────────────────────────────────────────────────────function setText(el, text) {- if (text) {- el.textContent = text;- el.style.display = '';- } else {- el.style.display = 'none';- }+ if (text) { el.textContent = text; el.style.display = ''; }+ else el.style.display = 'none';}function setField(textId, wrapId, value) {els[textId].textContent = value || '';@@ -422,10 +497,7 @@ function setField(textId, wrapId, value) {}function renderChips(listId, wrapId, items) {els[listId].innerHTML = '';- if (!items || !items.length) {- els[wrapId].style.display = 'none';- return;- }+ if (!items?.length) { els[wrapId].style.display = 'none'; return; }els[wrapId].style.display = '';for (const t of items) {const c = document.createElement('span');@@ -435,26 +507,17 @@ function renderChips(listId, wrapId, items) {}}function splitList(s) {- return String(s || '')- .split(/[,/]/)- .map((x) => x.trim())- .filter(Boolean)- .slice(0, 8);+ return String(s || '').split(/[,/]/).map((x) => x.trim()).filter(Boolean).slice(0, 8);}async function copyJson(obj, btn) {const text = JSON.stringify(obj, null, 2);- try {- await navigator.clipboard.writeText(text);- } catch {+ try { await navigator.clipboard.writeText(text); }+ catch {const ta = document.createElement('textarea');ta.value = text;document.body.appendChild(ta);ta.select();- try {- document.execCommand('copy');- } catch {- /* clipboard unavailable */- }+ try { document.execCommand('copy'); } catch { /* not available */ }ta.remove();}const prev = btn.textContent;@@ -465,11 +528,8 @@ function disposeObject(obj) {obj.traverse((c) => {if (c.geometry) c.geometry.dispose();if (c.material) {- const mats = Array.isArray(c.material) ? c.material : [c.material];- for (const m of mats) {- for (const k in m) {- if (m[k] && m[k].isTexture) m[k].dispose();- }+ for (const m of [].concat(c.material)) {+ for (const k in m) if (m[k]?.isTexture) m[k].dispose();m.dispose();}}@@ -477,13 +537,12 @@ function disposeObject(obj) {}function dispose() {try {+ stopLoadingSteps();renderer?.setAnimationLoop(null);if (modelRoot) disposeObject(modelRoot);env?.dispose?.();renderer?.dispose();- } catch {- /* unloading */- }+ } catch { /* unloading */ }}// ── Start ────────────────────────────────────────────────────────────────────diff --git a/tests/api/ibm-vision.test.js b/tests/api/ibm-vision.test.jsnew file mode 100644index 000000000..d0b753115--- /dev/null+++ b/tests/api/ibm-vision.test.js@@ -0,0 +1,445 @@+// Unit tests for /api/ibm/vision — IBM Granite Vision multimodal endpoint.+//+// Covers every path without any real network calls:+// GET — subject list (DB rows, empty DB, DB error, method guard)+// POST — watsonx unconfigured, input validation, SSRF allowlist, server-side+// image fetch, all three subject types, hint wiring, structured result,+// raw-prose fallback, Granite errors, and usage pass-through.++import { describe, it, expect, beforeEach, vi } from 'vitest';+import { Readable } from 'node:stream';++// ── Shared mutable state threaded through all mock factories ──────────────────+const state = {+ wxConfigured: false,+ dbRows: [],+ fetchOk: true,+ fetchStatus: 200,+ fetchContentType: 'image/jpeg',+ fetchBody: Buffer.alloc(200), // tiny valid image+ graniteText: '{"appearance":"A sleek cobalt android.","vibe":"calm, precise","persona":"A reliable guide.","suggested_name":"Cobalt","bio":"Your co-pilot.","tone_tags":["calm","precise"],"voice":"warm and measured"}',+ graniteThrows: false,+ graniteThrowMsg: 'watsonx 404: not found',+};++// ── Mocks ──────────────────────────────────────────────────────────────────────+vi.mock('../../api/_lib/rate-limit.js', () => ({+ limits: { publicIp: vi.fn(async () => ({ success: true })) },+ clientIp: vi.fn(() => '127.0.0.1'),+}));++vi.mock('../../api/_lib/db.js', () => ({+ sql: vi.fn(async () => state.dbRows),+}));++vi.mock('../../api/_lib/watsonx.js', () => ({+ watsonxConfig: vi.fn(() =>+ state.wxConfigured+ ? { configured: true, url: 'https://wx', projectId: 'proj', apiVersion: '2024-05-31', chatModel: 'ibm/granite-3-8b-instruct', embedModel: 'ibm/granite-embedding-278m-multilingual' }+ : { configured: false },+ ),+ watsonxChatComplete: vi.fn(async () => {+ if (state.graniteThrows) throw new Error(state.graniteThrowMsg);+ return {+ text: state.graniteText,+ model: 'ibm/granite-vision-3-2-2b',+ usage: { prompt_tokens: 120, completion_tokens: 80, total_tokens: 200 },+ };+ }),+}));++vi.mock('../../api/_lib/r2.js', () => ({+ publicUrl: vi.fn((key) => `https://cdn.example.com/${key}`),+}));++// Mock global fetch for server-side image fetching.+global.fetch = vi.fn(async () => {+ if (!state.fetchOk) {+ return { ok: false, status: state.fetchStatus, headers: { get: () => null }, arrayBuffer: async () => new ArrayBuffer(0) };+ }+ const body = state.fetchBody;+ return {+ ok: true,+ status: 200,+ headers: {+ get(h) {+ if (h === 'content-type') return state.fetchContentType;+ if (h === 'content-length') return String(body.length);+ return null;+ },+ },+ arrayBuffer: async () => body.buffer.slice(body.byteOffset, body.byteOffset + body.byteLength),+ };+});++// Import AFTER all mocks are set up.+const handler = (await import('../../api/ibm/vision.js')).default;+import { allowedImageHost, buildPrompt, parseVision, VISION_MODEL } from '../../api/ibm/vision.js';++// ── Test helpers ──────────────────────────────────────────────────────────────+const TINY_PNG = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==';++function makeReq({ method = 'GET', url = '/api/ibm/vision', body = null } = {}) {+ const base = body ? Readable.from([Buffer.from(JSON.stringify(body))]) : Readable.from([]);+ base.method = method;+ base.url = url;+ base.headers = { host: 'localhost', 'content-type': 'application/json', origin: 'http://localhost:3000' };+ return base;+}+function makeRes() {+ return {+ statusCode: 200, headers: {}, body: '', writableEnded: false,+ setHeader(k, v) { this.headers[k.toLowerCase()] = v; },+ getHeader(k) { return this.headers[k.toLowerCase()]; },+ end(chunk) { if (chunk !== undefined) this.body += chunk; this.writableEnded = true; },+ };+}+async function invoke(reqOpts) {+ const res = makeRes();+ await handler(makeReq(reqOpts), res);+ return {+ status: res.statusCode,+ body: res.body ? JSON.parse(res.body) : null,+ headers: res.headers,+ };+}++beforeEach(() => {+ state.wxConfigured = false;+ state.dbRows = [];+ state.fetchOk = true;+ state.fetchStatus = 200;+ state.fetchContentType = 'image/jpeg';+ state.fetchBody = Buffer.alloc(200);+ state.graniteText = '{"appearance":"A sleek cobalt android.","vibe":"calm, precise","persona":"A reliable guide.","suggested_name":"Cobalt","bio":"Your co-pilot.","tone_tags":["calm","precise"],"voice":"warm and measured"}';+ state.graniteThrows = false;+ state.graniteThrowMsg = 'watsonx 502: upstream error';+});++// ── GET /api/ibm/vision ───────────────────────────────────────────────────────+describe('GET /api/ibm/vision — subjects', () => {+ it('returns 200 with empty subjects and visionModel when DB has no rows', async () => {+ const { status, body } = await invoke({ method: 'GET' });+ expect(status).toBe(200);+ expect(body.subjects).toEqual([]);+ expect(typeof body.visionModel).toBe('string');+ expect(body.visionModel).toContain('granite');+ });++ it('maps DB rows to subjects with cdn URLs', async () => {+ state.dbRows = [+ { id: 'id-1', slug: 'cobalt', name: 'Cobalt', storage_key: 'avatars/cobalt.glb', thumbnail_key: 'thumbs/cobalt.jpg', featured: true, view_count: 42 },+ ];+ const { status, body } = await invoke({ method: 'GET' });+ expect(status).toBe(200);+ expect(body.subjects).toHaveLength(1);+ const s = body.subjects[0];+ expect(s.id).toBe('id-1');+ expect(s.name).toBe('Cobalt');+ expect(s.thumbnail).toContain('thumbs/cobalt.jpg');+ expect(s.model_url).toContain('avatars/cobalt.glb');+ expect(s.slug).toBe('cobalt');+ });++ it('returns empty subjects (not 500) when DB throws', async () => {+ const { sql } = await import('../../api/_lib/db.js');+ sql.mockRejectedValueOnce(new Error('DB unavailable'));+ const { status, body } = await invoke({ method: 'GET' });+ expect(status).toBe(200);+ expect(body.subjects).toEqual([]);+ });++ it('returns 405 for unsupported methods', async () => {+ const { status } = await invoke({ method: 'DELETE' });+ expect(status).toBe(405);+ });+});++// ── POST /api/ibm/vision — auth ────────────────────────────────────────────────+describe('POST /api/ibm/vision — watsonx gate', () => {+ it('returns 503 watsonx_unavailable when watsonx is not configured', async () => {+ state.wxConfigured = false;+ const { status, body } = await invoke({ method: 'POST', body: { image: TINY_PNG } });+ expect(status).toBe(503);+ expect(body.error).toBe('watsonx_unavailable');+ expect(body.error_description).toMatch(/WATSONX_API_KEY/i);+ });+});++// ── POST /api/ibm/vision — input validation ─────────────────────────────────────+describe('POST /api/ibm/vision — input validation', () => {+ beforeEach(() => { state.wxConfigured = true; });++ it('returns 400 bad_image when neither image nor imageUrl is provided', async () => {+ const { status, body } = await invoke({ method: 'POST', body: { hint: 'hello' } });+ expect(status).toBe(400);+ expect(body.error).toBe('bad_image');+ });++ it('returns 400 bad_image when image data URL has empty data portion', async () => {+ const { status, body } = await invoke({ method: 'POST', body: { image: 'data:image/png;base64,' } });+ expect(status).toBe(400);+ expect(body.error).toBe('bad_image');+ });++ it('returns 413 image_too_large when data URL exceeds 6 MB', async () => {+ // 6MB / 0.75 ≈ 8MB of base64+ const big = 'data:image/png;base64,' + 'A'.repeat(8_500_000);+ const { status, body } = await invoke({ method: 'POST', body: { image: big } });+ expect(status).toBe(413);+ expect(body.error).toBe('image_too_large');+ });++ it('returns 400 bad_image when imageUrl uses http (not https)', async () => {+ const { status, body } = await invoke({ method: 'POST', body: { imageUrl: 'http://pub-abc.r2.dev/img.jpg' } });+ expect(status).toBe(400);+ expect(body.error).toBe('bad_image');+ });++ it('returns 400 image_host_not_allowed for an arbitrary external host', async () => {+ const { status, body } = await invoke({ method: 'POST', body: { imageUrl: 'https://evil.example.com/img.jpg' } });+ expect(status).toBe(400);+ expect(body.error).toBe('image_host_not_allowed');+ });++ it('returns 400 image_host_not_allowed for internal metadata endpoint (SSRF)', async () => {+ const { status, body } = await invoke({ method: 'POST', body: { imageUrl: 'https://169.254.169.254/latest/meta-data/' } });+ expect(status).toBe(400);+ expect(body.error).toBe('image_host_not_allowed');+ });+});++// ── POST /api/ibm/vision — server-side image fetch ───────────────────────────────+describe('POST /api/ibm/vision — server-side image fetch', () => {+ beforeEach(() => { state.wxConfigured = true; });++ it('fetches an allowlisted imageUrl and sends it to Granite', async () => {+ const { status, body } = await invoke({+ method: 'POST',+ body: { imageUrl: 'https://pub-test.r2.dev/avatar.jpg', subject: 'avatar' },+ });+ expect(status).toBe(200);+ expect(global.fetch).toHaveBeenCalledWith(+ expect.stringContaining('pub-test.r2.dev'),+ expect.objectContaining({ signal: expect.any(AbortSignal) }),+ );+ expect(body.vision.suggested_name).toBe('Cobalt');+ });++ it('returns 502 image_fetch_failed when upstream fetch fails', async () => {+ state.fetchOk = false;+ state.fetchStatus = 503;+ const { status, body } = await invoke({+ method: 'POST',+ body: { imageUrl: 'https://pub-test.r2.dev/avatar.jpg' },+ });+ expect(status).toBe(502);+ expect(body.error).toBe('image_fetch_failed');+ });++ it('returns 415 not_an_image when fetched URL is not an image', async () => {+ state.fetchContentType = 'text/html';+ const { status, body } = await invoke({+ method: 'POST',+ body: { imageUrl: 'https://pub-test.r2.dev/page.html' },+ });+ expect(status).toBe(415);+ expect(body.error).toBe('not_an_image');+ });+});++// ── POST /api/ibm/vision — Granite Vision call ────────────────────────────────+describe('POST /api/ibm/vision — Granite Vision result', () => {+ beforeEach(() => { state.wxConfigured = true; });++ it('returns a structured identity when Granite returns valid JSON', async () => {+ const { status, body } = await invoke({ method: 'POST', body: { image: TINY_PNG } });+ expect(status).toBe(200);+ expect(body.vision.structured).toBe(true);+ expect(body.vision.suggested_name).toBe('Cobalt');+ expect(body.vision.bio).toBe('Your co-pilot.');+ expect(body.vision.tone_tags).toEqual(['calm', 'precise']);+ expect(body.vision.voice).toBe('warm and measured');+ });++ it('includes the model name in the response', async () => {+ const { body } = await invoke({ method: 'POST', body: { image: TINY_PNG } });+ expect(body.model).toBe('ibm/granite-vision-3-2-2b');+ });++ it('passes usage through to the response', async () => {+ const { body } = await invoke({ method: 'POST', body: { image: TINY_PNG } });+ expect(body.usage).toMatchObject({ prompt_tokens: 120, completion_tokens: 80, total_tokens: 200 });+ });++ it('does not include "raw" when result is structured', async () => {+ const { body } = await invoke({ method: 'POST', body: { image: TINY_PNG } });+ expect(body.raw).toBeUndefined();+ });++ it('returns raw fallback (structured:false) when Granite returns prose', async () => {+ state.graniteText = 'This avatar appears to be a futuristic character with a calm demeanor.';+ const { status, body } = await invoke({ method: 'POST', body: { image: TINY_PNG } });+ expect(status).toBe(200);+ expect(body.vision.structured).toBe(false);+ expect(body.raw).toMatch(/futuristic character/);+ });++ it('recovers JSON from a code-fenced response', async () => {+ state.graniteText = '```json\n{"appearance":"A bot.","vibe":"calm","persona":"Helpful.","suggested_name":"Bot","bio":"Here to help.","tone_tags":["calm"],"voice":"steady"}\n```';+ const { body } = await invoke({ method: 'POST', body: { image: TINY_PNG } });+ expect(body.vision.structured).toBe(true);+ expect(body.vision.suggested_name).toBe('Bot');+ });++ it('uses the avatar prompt by default (subject omitted)', async () => {+ const { watsonxChatComplete } = await import('../../api/_lib/watsonx.js');+ await invoke({ method: 'POST', body: { image: TINY_PNG } });+ const calls = watsonxChatComplete.mock.calls;+ const lastCall = calls[calls.length - 1];+ const messages = lastCall[1].messages;+ expect(messages[0].content).toMatch(/casting director/i);+ });++ it('uses the token prompt when subject is "token"', async () => {+ const { watsonxChatComplete } = await import('../../api/_lib/watsonx.js');+ await invoke({ method: 'POST', body: { image: TINY_PNG, subject: 'token' } });+ const calls = watsonxChatComplete.mock.calls;+ const lastCall = calls[calls.length - 1];+ const messages = lastCall[1].messages;+ expect(messages[0].content).toMatch(/brand analyst/i);+ });++ it('uses the generic image prompt when subject is "image"', async () => {+ const { watsonxChatComplete } = await import('../../api/_lib/watsonx.js');+ await invoke({ method: 'POST', body: { image: TINY_PNG, subject: 'image' } });+ const calls = watsonxChatComplete.mock.calls;+ const lastCall = calls[calls.length - 1];+ const messages = lastCall[1].messages;+ expect(messages[0].content).toMatch(/art director/i);+ });++ it('defaults unknown subject to avatar', async () => {+ const { status, body } = await invoke({ method: 'POST', body: { image: TINY_PNG, subject: 'spacecraft' } });+ expect(status).toBe(200);+ expect(body.subject).toBe('avatar');+ });++ it('weaves the hint into the user message', async () => {+ const { watsonxChatComplete } = await import('../../api/_lib/watsonx.js');+ await invoke({ method: 'POST', body: { image: TINY_PNG, hint: 'a rogue detective' } });+ const calls = watsonxChatComplete.mock.calls;+ const lastCall = calls[calls.length - 1];+ const userContent = lastCall[1].messages[1].content;+ const textBlock = userContent.find((b) => b.type === 'text');+ expect(textBlock.text).toContain('a rogue detective');+ });++ it('embeds the image as a data URL in the image_url block', async () => {+ const { watsonxChatComplete } = await import('../../api/_lib/watsonx.js');+ await invoke({ method: 'POST', body: { image: TINY_PNG } });+ const calls = watsonxChatComplete.mock.calls;+ const lastCall = calls[calls.length - 1];+ const userContent = lastCall[1].messages[1].content;+ const imgBlock = userContent.find((b) => b.type === 'image_url');+ expect(imgBlock.image_url.url).toMatch(/^data:image\//);+ });++ it('returns 502 vision_failed when Granite throws', async () => {+ state.graniteThrows = true;+ state.graniteThrowMsg = 'watsonx 502: quota exceeded';+ const { status, body } = await invoke({ method: 'POST', body: { image: TINY_PNG } });+ expect(status).toBe(502);+ expect(body.error).toBe('vision_failed');+ });++ it('returns 502 model_unavailable when Granite reports model not found', async () => {+ state.graniteThrows = true;+ state.graniteThrowMsg = 'watsonx 404: model not found in this region';+ const { status, body } = await invoke({ method: 'POST', body: { image: TINY_PNG } });+ expect(status).toBe(502);+ expect(body.error).toBe('model_unavailable');+ });+});++// ── Unit: parseVision ─────────────────────────────────────────────────────────+describe('parseVision — identity parser', () => {+ it('parses a clean JSON blob', () => {+ const v = parseVision('{"appearance":"Blue bot.","vibe":"calm","persona":"A guide.","suggested_name":"Bot","bio":"Here for you.","tone_tags":["calm","helpful"],"voice":"warm"}');+ expect(v.structured).toBe(true);+ expect(v.suggested_name).toBe('Bot');+ expect(v.tone_tags).toEqual(['calm', 'helpful']);+ });++ it('strips leading and trailing prose around the JSON', () => {+ const v = parseVision('Sure, here it is: {"suggested_name":"Echo","bio":"test","appearance":"","vibe":"","persona":"","tone_tags":[],"voice":""} Hope that helps!');+ expect(v.structured).toBe(true);+ expect(v.suggested_name).toBe('Echo');+ });++ it('splits a comma-joined string into tone_tags array', () => {+ const v = parseVision('{"appearance":"x","vibe":"x","persona":"x","suggested_name":"x","bio":"x","tone_tags":"calm, curious, witty","voice":"x"}');+ expect(v.tone_tags).toEqual(['calm', 'curious', 'witty']);+ });++ it('clamps fields to their max lengths', () => {+ const v = parseVision(`{"appearance":"x","vibe":"x","persona":"x","suggested_name":"${'A'.repeat(100)}","bio":"${'B'.repeat(300)}","tone_tags":[],"voice":"${'C'.repeat(200)}"}`);+ expect(v.suggested_name.length).toBeLessThanOrEqual(60);+ expect(v.bio.length).toBeLessThanOrEqual(200);+ expect(v.voice.length).toBeLessThanOrEqual(120);+ });++ it('returns structured:false for empty input', () => {+ expect(parseVision('').structured).toBe(false);+ expect(parseVision(null).structured).toBe(false);+ expect(parseVision('no json here').structured).toBe(false);+ });++ it('returns structured:false for invalid JSON', () => {+ expect(parseVision('{broken json}').structured).toBe(false);+ });+});++// ── Unit: allowedImageHost ─────────────────────────────────────────────────────+describe('allowedImageHost — SSRF allowlist', () => {+ const allow = ['pub-abc.r2.dev', 'three.ws', 'ipfs.io', 'arweave.net', 'pump.mypinata.cloud', 'bafyb.ipfs.dweb.link', 'user.githubusercontent.com'];+ const deny = ['localhost', '127.0.0.1', '169.254.169.254', 'evil.com', '10.0.0.1', 'metadata.google.internal'];++ for (const h of allow) it(`allows ${h}`, () => expect(allowedImageHost(h)).toBe(true));+ for (const h of deny) it(`rejects ${h}`, () => expect(allowedImageHost(h)).toBe(false));+});++// ── Unit: buildPrompt ─────────────────────────────────────────────────────────+describe('buildPrompt — prompt builder', () => {+ it('returns a casting-director system prompt for avatar subject', () => {+ const { system } = buildPrompt('avatar', '');+ expect(system).toMatch(/casting director/i);+ });++ it('returns a brand-analyst system prompt for token subject', () => {+ const { system } = buildPrompt('token', '');+ expect(system).toMatch(/brand analyst/i);+ });++ it('returns an art-director system prompt for image subject', () => {+ const { system } = buildPrompt('image', '');+ expect(system).toMatch(/art director/i);+ });++ it('injects the hint into the user message', () => {+ const { user } = buildPrompt('avatar', 'a grumpy wizard');+ expect(user).toContain('a grumpy wizard');+ });++ it('omits the hint line when hint is empty', () => {+ const { user } = buildPrompt('avatar', '');+ expect(user).not.toContain('adds:');+ });+});++// ── Unit: VISION_MODEL ────────────────────────────────────────────────────────+describe('VISION_MODEL', () => {+ it('defaults to the Granite Vision 3.2 model', () => {+ expect(VISION_MODEL).toMatch(/granite-vision/);+ });+});diff --git a/tests/ibm-ui-contract.test.js b/tests/ibm-ui-contract.test.jsnew file mode 100644index 000000000..534baeb09--- /dev/null+++ b/tests/ibm-ui-contract.test.js@@ -0,0 +1,114 @@+// Locks the runtime UI contract for the /ibm showcase so it cannot silently+// break under swarm churn.+//+// Each interactive /ibm page boots a front-end engine (src/ibm-<name>.js) that+// grabs DOM nodes by id — `document.getElementById(id)` (aliased `$`), bracket+// access on a cached `els` map, or `querySelector('#id')`. If a page's HTML and+// its engine drift apart — an id renamed in one but not the other, or a state+// container deleted — the engine reads `null`, throws on first access, and the+// page renders a blank void at runtime. No unit test, build step, or linter+// catches that today; you only find out by loading the page in a browser.+//+// These checks make that class of failure impossible to miss, with no browser:+// 1. every page still loads its engine module;+// 2. every DOM id the engine depends on exists in the page HTML (excluding+// ids the engine injects itself via HTML string templates); and+// 3. every page keeps the degraded-state containers its "always works, even+// with no watsonx credentials" UX depends on — so the honest loading /+// empty / error / unavailable states can never be quietly removed.+//+// Pure static analysis: fast, deterministic, and additive (touches no churned+// source file). See docs/ibm.md and scripts/verify-ibm-surface.mjs.++import { describe, it, expect } from 'vitest';+import { readFileSync } from 'node:fs';+import { fileURLToPath } from 'node:url';+import { dirname, join } from 'node:path';++const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');+const read = (p) => readFileSync(join(ROOT, p), 'utf8');++// page slug (pages/ibm/<slug>.html) → engine module (src/<module>.js)+const PAGES = {+ galaxy: 'ibm-galaxy',+ oracle: 'ibm-oracle',+ 'trust-layer': 'ibm-trust-layer',+ proof: 'ibm-proof',+ twin: 'ibm-twin',+ vision: 'ibm-vision',+};++// Degraded-state DOM nodes each page must keep so it can always render an+// honest state instead of a blank screen — even when watsonx is unconfigured.+// Derived from each engine's own state handling (verified present, not guessed).+const REQUIRED_STATE_IDS = {+ galaxy: ['loadingState', 'errorState', 'unavailableState', 'emptyState', 'retryBtn'],+ oracle: ['o-status', 'o-narration', 'o-forecast-badge', 'o-gov-badge'],+ 'trust-layer': ['loadingState', 'errorState', 'unavailableState', 'retryBtn'],+ proof: ['gov-title', 'gov-sub'],+ twin: ['t-status', 't-persona', 'b-projection', 'b-fidelity', 'b-gov'],+ vision: ['v-idle', 'v-loading', 'v-error', 'v-error-retry'],+};++// How engines reach DOM nodes by id.+const ID_REF_PATTERNS = [+ /\$\(\s*['"]([\w-]+)['"]\s*\)/g, // $('id')+ /getElementById\(\s*['"]([\w-]+)['"]\s*\)/g, // document.getElementById('id')+ /querySelector(?:All)?\(\s*['"]#([\w-]+)['"]/g, // querySelector('#id')+ /\bels\[\s*['"]([\w-]+)['"]\s*\]/g, // els['id']+];++const matchAllIds = (src, re) => [...src.matchAll(re)].map((m) => m[1]);++const htmlIds = (html) => new Set(matchAllIds(html, /id=["']([\w-]+)["']/g));++const referencedIds = (js) => {+ const ids = new Set();+ for (const re of ID_REF_PATTERNS) for (const id of matchAllIds(js, re)) ids.add(id);+ return ids;+};++// Ids the engine creates itself, by emitting `id="..."` inside an HTML string+// template (e.g. proof.js injects its on-chain verify bar). These need not exist+// in the static HTML, so they are excluded from the required set.+const injectedIds = (js) => new Set(matchAllIds(js, /\bid=["']([\w-]+)["']/g));++describe('IBM showcase UI contract', () => {+ for (const [page, mod] of Object.entries(PAGES)) {+ describe(`/ibm/${page}`, () => {+ const html = read(`pages/ibm/${page}.html`);+ const js = read(`src/${mod}.js`);++ it('loads its front-end engine module', () => {+ expect(html).toContain(`/src/${mod}.js`);+ });++ it('every DOM id the engine depends on exists in the page HTML', () => {+ const ids = htmlIds(html);+ const injected = injectedIds(js);+ const required = [...referencedIds(js)].filter((id) => !injected.has(id));+ const missing = required.filter((id) => !ids.has(id)).sort();+ expect(+ missing,+ `src/${mod}.js reads these ids that pages/ibm/${page}.html no longer defines`,+ ).toEqual([]);+ });++ it('keeps its degraded-state containers (always-works UX)', () => {+ const ids = htmlIds(html);+ const missing = REQUIRED_STATE_IDS[page].filter((id) => !ids.has(id));+ expect(+ missing,+ `degraded-state container(s) removed from pages/ibm/${page}.html — the no-credentials UX would break`,+ ).toEqual([]);+ });++ it('renders a no-JavaScript fallback instead of a blank canvas', () => {+ // These pages are pure client-rendered 3D; with JS disabled or the+ // bundle failing to load there is otherwise nothing to see. The+ // <noscript> fallback keeps the page meaningful and links onward.+ expect(html).toMatch(/<noscript>[\s\S]*?\/docs\/ibm[\s\S]*?<\/noscript>/);+ });+ });+ }+});