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
fix(errors): say what a visitor can do about it instead of leaking transport strings
nirholas330289d9602e
diff --git a/pages/galaxy.html b/pages/galaxy.htmlindex d27ae687e..5f9646793 100644--- a/pages/galaxy.html+++ b/pages/galaxy.html@@ -203,7 +203,10 @@<div class="gx-overlay-glyph" aria-hidden="true">✦</div><div class="gx-overlay-title" id="gxEmptyTitle">The galaxy is still forming</div><div class="gx-overlay-sub" id="gxEmptySub">No published agents to map yet. Create and publish an agent to place the first star.</div>- <a class="gx-btn gx-btn-primary" href="/create" data-i18n="galaxy.create_an_agent">Create an agent</a>+ <div class="gx-overlay-actions">+ <a class="gx-btn gx-btn-primary" href="/create" data-i18n="galaxy.create_an_agent">Create an agent</a>+ <a class="gx-btn gx-btn-ghost" href="/agents/" data-i18n="galaxy.browse_every_agent">Browse every agent</a>+ </div></div><!-- Error overlay -->@@ -211,11 +214,15 @@<div class="gx-overlay-glyph" aria-hidden="true">✦</div><div class="gx-overlay-title" id="gxErrorTitle">Couldn't reach the stars</div><div class="gx-overlay-sub" id="gxErrorSub"></div>- <button class="gx-btn gx-btn-primary" id="gxRetry" type="button" data-i18n="galaxy.try_again">Try again</button>+ <div class="gx-overlay-actions">+ <button class="gx-btn gx-btn-primary" id="gxRetry" type="button" data-i18n="galaxy.try_again">Try again</button>+ <a class="gx-btn gx-btn-primary" id="gxErrorBrowse" href="/agents/" hidden data-i18n="galaxy.browse_every_agent">Browse every agent</a>+ <a class="gx-btn gx-btn-ghost" href="/docs/ibm" data-i18n="galaxy.how_the_galaxy_is_built">How the galaxy is built</a>+ </div></div><!-- Footer attribution / controls hint -->- <div class="gx-footnote">+ <div class="gx-footnote" id="gxFootnote"><span class="gx-footnote-hint" id="gxHint" data-i18n="galaxy.drag_to_orbit_scroll_to_zoom_click">Drag to orbit · scroll to zoom · click a star</span><a class="gx-footnote-link" href="/docs/ibm" data-i18n="galaxy.three_ws_ibm_watsonx">three.ws × IBM watsonx →</a></div>diff --git a/src/avatar-embed.js b/src/avatar-embed.jsindex 50aa52700..47fb6ad3e 100644--- a/src/avatar-embed.js+++ b/src/avatar-embed.js@@ -112,9 +112,28 @@ const DEFAULT_HOTKEYS = Object.freeze({});main().catch((err) => {- showError(err?.message || 'Could not load avatar');+ showError(viewerErrorText(err));});+// GLTFLoader rejects with the raw transport string, e.g. `fetch for+// "https://host/x.glb" responded with 502: Bad Gateway`. That names an internal+// URL and tells the viewer nothing they can act on. Map the failures a visitor+// can actually hit onto plain language; anything unrecognised keeps its own+// message, which is already written for a person (resolveAvatar throws+// "avatar <id> not found").+function viewerErrorText(err) {+ const msg = String(err?.message || err || '');+ if (/responded with 4\d\d/.test(msg)) {+ return /40[13]/.test(msg)+ ? 'This avatar is private. Sign in with the account that owns it.'+ : 'This avatar is no longer available.';+ }+ if (/responded with 5\d\d/.test(msg)) return 'The avatar service is unavailable. Refresh to try again.';+ if (/Failed to fetch|NetworkError|Load failed/i.test(msg)) return 'Connection lost. Check your network and refresh.';+ if (/glTF|JSON|Unsupported|Unexpected token/i.test(msg)) return "This avatar's 3D file could not be read.";+ return msg || 'Could not load avatar.';+}+async function main() {const params = new URL(location.href).searchParams;applyBackground(params.get('bg') || 'transparent');diff --git a/src/galaxy.js b/src/galaxy.jsindex 272b117eb..b8c44abd6 100644--- a/src/galaxy.js+++ b/src/galaxy.js@@ -30,7 +30,8 @@ function cacheEls() {'gxTip', 'gxCard', 'gxCardClose', 'gxCardThumb', 'gxCardName', 'gxCardConstellation','gxCardDesc', 'gxCardMeta', 'gxCardView', 'gxCardChat','gxResults', 'gxResultsList', 'gxResultsClose', 'gxResultsLabel',- 'gxLoading', 'gxEmpty', 'gxEmptySub', 'gxError', 'gxErrorSub', 'gxRetry', 'gxHint',+ 'gxLoading', 'gxEmpty', 'gxEmptySub', 'gxError', 'gxErrorSub', 'gxRetry', 'gxErrorBrowse',+ 'gxHint', 'gxFootnote',// Money-Cam'gxMoneyToggle', 'gxMoneyCam', 'gxMcLiveDot', 'gxMcClose','gxMcModeLive', 'gxMcModeReplay', 'gxMcStats', 'gxMcReplay', 'gxMcPlay',@@ -229,7 +230,12 @@ function renderGalaxy(data) {loadNetWorth(data.agents);loadLineageEdges();- // Stats+ // Stats. Both spans declare a data-i18n key whose declared copy is the "0+ // agents" placeholder, and the i18n runtime re-applies the catalog after this+ // render, so they must claim ownership or the real counts get reset to zero.+ // `data-i18n-owned="1"` is that runtime's documented opt-out (src/i18n.js).+ els.gxStatAgents.setAttribute('data-i18n-owned', '1');+ els.gxStatClusters.setAttribute('data-i18n-owned', '1');els.gxStatAgents.innerHTML = `<strong>${n.toLocaleString()}</strong> agents`;els.gxStatClusters.innerHTML = `<strong>${data.clusters.length}</strong> constellations`;els.gxStats.hidden = false;@@ -399,6 +405,12 @@ function toggleClusterFocus(clusterId) {// ── Semantic search (Granite) ───────────────────────────────────────────────let searchSeq = 0;+// The search button's resting label is translated copy, so it is read off the+// button rather than hardcoded. `SEARCH_BUSY` marks the in-flight state and is+// never mistaken for the label, which keeps overlapping searches from restoring+// the spinner glyph as the button's text.+const SEARCH_BUSY = '\u2026';+let searchGoLabel = '';async function runSearch(query) {const q = String(query || '').trim();if (!q) {@@ -406,8 +418,9 @@ async function runSearch(query) {return;}const seq = ++searchSeq;+ if (els.gxSearchGo.textContent !== SEARCH_BUSY) searchGoLabel = els.gxSearchGo.textContent;els.gxSearchGo.disabled = true;- els.gxSearchGo.textContent = '…';+ els.gxSearchGo.textContent = SEARCH_BUSY;try {const res = await fetch('/api/galaxy', {method: 'POST',@@ -441,7 +454,7 @@ async function runSearch(query) {} finally {if (seq === searchSeq) {els.gxSearchGo.disabled = false;- els.gxSearchGo.textContent = 'Search';+ els.gxSearchGo.textContent = searchGoLabel;}}}@@ -540,7 +553,9 @@ function selectAgent(index, fly = false) {wireWalletChips(els.gxCardMeta);els.gxCardView.href = `/agents/${a.id}`;- els.gxCardChat.href = `/agents/${a.id}`;+ // The agent page renders its Chat panel from ?view=chat, so the two actions+ // lead somewhere different instead of both opening the 3D overview.+ els.gxCardChat.href = `/agents/${a.id}?view=chat`;els.gxCard.hidden = false;if (fly) flyToTarget(new THREE.Vector3(...a.coords), 120);@@ -846,15 +861,26 @@ function bindUI() {}// ── Overlays ─────────────────────────────────────────────────────────────────+// An overlay covers the whole stage and eats pointer events, so the HUD, legend and+// footnote under it must leave the tab order too. Without this a keyboard visitor+// can still reach the search box while there is no galaxy to search, submit it, and+// get results rendered underneath an opaque panel.+function setStageInert(inert) {+ for (const el of [els.gxHud, els.gxLegend, els.gxFootnote]) {+ if (el) el.inert = inert;+ }+}function showOverlay(which) {els.gxLoading.hidden = which !== 'loading';els.gxEmpty.hidden = which !== 'empty';els.gxError.hidden = which !== 'error';+ setStageInert(true);}function hideOverlays() {els.gxLoading.hidden = true;els.gxEmpty.hidden = true;els.gxError.hidden = true;+ setStageInert(false);}function showError(title, sub, retryable = true) {dbg.status = 'error';@@ -862,6 +888,9 @@ function showError(title, sub, retryable = true) {$('gxErrorTitle').textContent = title;els.gxErrorSub.textContent = sub;els.gxRetry.hidden = !retryable;+ // Retrying a configuration gap just fails again, so an unretryable failure+ // hands the visitor the same agents as a list instead of a dead end.+ els.gxErrorBrowse.hidden = retryable;showOverlay('error');}diff --git a/src/guardian.js b/src/guardian.jsindex e850d5e5a..a2052f1c7 100644--- a/src/guardian.js+++ b/src/guardian.js@@ -1,19 +1,19 @@/**- * Guardian console — page entry (/guardian).+ * Guardian console, page entry (/guardian).** The cross-agent surface for someone trusted as a guardian or named as a* beneficiary. They are NOT the owner, so they never see the owner-only Recovery- * tab in an agent's wallet hub — this is where they act: approve a recovery,- * decline it, confirm an inheritance, or push a ready process over the line. Being- * a guardian is a real, visible role in the graph; this page surfaces it with the- * weight it deserves.+ * tab in an agent's wallet hub: this is where they act. Approve a recovery,+ * decline it, confirm an inheritance, or push a ready process over the line.+ * Being a guardian is a real, visible role in the graph; this page surfaces it+ * with the weight it deserves.** 100% real: every list item and every action hits the owner/guardian-gated API- * (CSRF-protected). No key is ever exposed — completing a process only changes who- * owns the agent.+ * (CSRF-protected). No key is ever exposed. Completing a process only changes+ * who owns the agent.*/-import { consumeCsrfToken } from './api.js';+import { consumeCsrfToken, noteSession } from './api.js';const root = document.getElementById('guardian-root');@@ -26,24 +26,32 @@ const STYLE = `.gd-badge { display:inline-flex; align-items:center; gap:6px; font-size:var(--text-2xs,.6875rem); font-weight:600; padding:3px 10px; border-radius:999px; margin-top:8px; color:var(--wallet-accent-ink,#c4b5fd); background:color-mix(in srgb,var(--wallet-accent,#8b5cf6) 14%,transparent); border:1px solid color-mix(in srgb,var(--wallet-accent,#8b5cf6) 32%,transparent); }.gd-card { border:1px solid var(--stroke,rgba(255,255,255,.08)); border-radius:14px; background:var(--surface-1,rgba(255,255,255,.03)); padding:16px 18px; }.gd-card.act { border-color:color-mix(in srgb,var(--warn,#fbbf24) 45%,transparent); background:color-mix(in srgb,var(--warn,#fbbf24) 7%,transparent); }-.gd-row { display:flex; gap:12px; align-items:center; }+.gd-row { display:flex; gap:12px; align-items:center; flex-wrap:wrap; }.gd-ava { width:40px; height:40px; border-radius:10px; object-fit:cover; flex:none; background:var(--surface-3,rgba(255,255,255,.08)); display:grid; place-items:center; color:var(--ink-dim,#888); font-size:15px; }-.gd-id { flex:1; min-width:0; }+.gd-id { flex:1; min-width:min(100%,180px); }.gd-name { font-size:var(--text-md,.95rem); color:var(--ink-bright,#fff); font-weight:600; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }-.gd-name a { color:inherit; text-decoration:none; }+.gd-name a { color:inherit; text-decoration:none; border-radius:4px; }.gd-name a:hover { text-decoration:underline; }+.gd-name a:focus-visible { outline:2px solid var(--focus-ring-color,#fff); outline-offset:3px; }.gd-meta { font-size:var(--text-2xs,.6875rem); color:var(--ink-dim,#888); margin-top:2px; }.gd-roles { display:flex; gap:6px; flex-wrap:wrap; }.gd-pill { font-size:var(--text-2xs,.6875rem); font-weight:600; padding:2px 8px; border-radius:999px; border:1px solid transparent; }.gd-pill.guardian { color:var(--wallet-accent-ink,#c4b5fd); background:color-mix(in srgb,var(--wallet-accent,#8b5cf6) 14%,transparent); border-color:color-mix(in srgb,var(--wallet-accent,#8b5cf6) 32%,transparent); }.gd-pill.beneficiary { color:var(--success,#4ade80); background:color-mix(in srgb,var(--success,#4ade80) 12%,transparent); border-color:color-mix(in srgb,var(--success,#4ade80) 30%,transparent); }+.gd-pill.neutral { color:var(--ink-dim,#999); background:var(--surface-2,rgba(255,255,255,.05)); border-color:var(--stroke,rgba(255,255,255,.08)); }.gd-proc { margin-top:12px; padding-top:12px; border-top:1px solid var(--stroke,rgba(255,255,255,.08)); }-.gd-proc-h { font-size:var(--text-sm,.85rem); color:var(--ink-bright,#fff); display:flex; align-items:center; gap:8px; }+.gd-proc-h { font-size:var(--text-sm,.85rem); color:var(--ink-bright,#fff); display:flex; align-items:center; gap:8px; flex-wrap:wrap; }.gd-narrate { font-style:italic; color:var(--ink,#c8c8c8); font-size:var(--text-sm,.8rem); line-height:1.5; padding:10px 12px; margin-top:8px; border-left:2px solid color-mix(in srgb,var(--wallet-accent,#8b5cf6) 50%,transparent); background:color-mix(in srgb,var(--wallet-accent,#8b5cf6) 7%,transparent); border-radius:0 10px 10px 0; }-.gd-count { font-family:var(--font-mono,monospace); font-size:var(--text-2xs,.6875rem); color:var(--ink-dim,#888); margin-top:6px; }+.gd-reason { margin-top:8px; font-size:var(--text-sm,.8rem); color:var(--ink,#d4d4d4); line-height:1.5; padding:10px 12px; border:1px solid var(--stroke,rgba(255,255,255,.08)); border-radius:10px; background:var(--surface-2,rgba(255,255,255,.04)); overflow-wrap:anywhere; }+.gd-reason b { display:block; font-size:var(--text-2xs,.6875rem); font-weight:600; text-transform:uppercase; letter-spacing:.06em; color:var(--ink-dim,#888); margin-bottom:4px; }+.gd-count { font-family:var(--font-mono,monospace); font-size:var(--text-2xs,.6875rem); color:var(--ink-dim,#888); margin-top:8px; }.gd-tl { font-size:var(--text-2xs,.6875rem); color:var(--ink-dim,#888); margin-top:4px; }+.gd-votes { list-style:none; margin:8px 0 0; padding:0; display:flex; flex-direction:column; gap:3px; }+.gd-votes li { font-size:var(--text-2xs,.6875rem); color:var(--ink-dim,#888); }+.gd-votes .yes { color:var(--success,#4ade80); }+.gd-votes .no { color:var(--danger,#f87171); }.gd-actions { display:flex; gap:8px; margin-top:12px; flex-wrap:wrap; }-.gd-btn { appearance:none; font:inherit; font-size:var(--text-sm,.8rem); color:var(--ink,#e8e8e8); background:var(--surface-2,rgba(255,255,255,.05)); border:1px solid var(--stroke,rgba(255,255,255,.08)); border-radius:10px; padding:8px 14px; cursor:pointer; transition:background .14s,border-color .14s,transform .08s; }+.gd-btn { appearance:none; display:inline-flex; align-items:center; justify-content:center; font:inherit; font-size:var(--text-sm,.8rem); text-decoration:none; color:var(--ink,#e8e8e8); background:var(--surface-2,rgba(255,255,255,.05)); border:1px solid var(--stroke,rgba(255,255,255,.08)); border-radius:10px; padding:8px 14px; cursor:pointer; transition:background .14s,border-color .14s,transform .08s; }.gd-btn:hover:not(:disabled){ background:var(--surface-3,rgba(255,255,255,.08)); border-color:var(--stroke-strong,rgba(255,255,255,.14)); }.gd-btn:active:not(:disabled){ transform:translateY(1px); }.gd-btn:disabled{ opacity:.4; cursor:not-allowed; }@@ -51,13 +59,17 @@ const STYLE = `.gd-btn--approve{ background:color-mix(in srgb,var(--success,#4ade80) 16%,transparent); color:var(--success,#4ade80); border-color:color-mix(in srgb,var(--success,#4ade80) 40%,transparent); font-weight:600; }.gd-btn--danger{ background:color-mix(in srgb,var(--danger,#f87171) 14%,transparent); color:var(--danger,#f87171); border-color:color-mix(in srgb,var(--danger,#f87171) 40%,transparent); font-weight:600; }.gd-btn--primary{ background:var(--accent,#fff); color:#0a0a0a; border-color:var(--accent,#fff); font-weight:600; }+.gd-btn--primary:hover:not(:disabled){ background:var(--accent,#fff); filter:brightness(.92); }.gd-empty{ text-align:center; padding:36px 16px; color:var(--ink-dim,#888); }+.gd-empty h1, .gd-empty h2{ margin:0 0 6px; color:var(--ink-bright,#fff); font-family:var(--font-display,system-ui); font-size:var(--text-xl,1.35rem); }+.gd-empty p{ margin:0 auto; max-width:46ch; line-height:1.55; }.gd-empty .ill{ font-size:34px; opacity:.5; display:block; margin-bottom:10px; }.gd-skel{ height:84px; border-radius:14px; background:linear-gradient(90deg,var(--surface-1,rgba(255,255,255,.03)) 25%,var(--surface-2,rgba(255,255,255,.05)) 37%,var(--surface-1,rgba(255,255,255,.03)) 63%); background-size:400% 100%; animation:gd-sh 1.4s ease infinite; }-.gd-toast{ position:fixed; left:50%; bottom:24px; transform:translateX(-50%) translateY(8px); background:var(--bg-1,#1a1a1a); color:var(--ink-bright,#fff); border:1px solid var(--stroke-strong,rgba(255,255,255,.14)); border-radius:10px; padding:10px 16px; font-size:.85rem; box-shadow:0 8px 32px rgba(0,0,0,.5); opacity:0; pointer-events:none; transition:opacity .2s,transform .2s; z-index:9999; }+.gd-toast{ position:fixed; left:50%; bottom:24px; transform:translateX(-50%) translateY(8px); max-width:min(92vw,420px); text-align:center; background:var(--bg-1,#1a1a1a); color:var(--ink-bright,#fff); border:1px solid var(--stroke-strong,rgba(255,255,255,.14)); border-radius:10px; padding:10px 16px; font-size:.85rem; box-shadow:0 8px 32px rgba(0,0,0,.5); opacity:0; pointer-events:none; transition:opacity .2s,transform .2s; z-index:9999; }.gd-toast[data-show="true"]{ opacity:1; transform:translateX(-50%) translateY(0); }@keyframes gd-sh{ 0%{background-position:100% 0} 100%{background-position:-100% 0} }-@media (prefers-reduced-motion: reduce){ .gd-skel{animation:none} }+@media (prefers-reduced-motion: reduce){ .gd-skel{animation:none} .gd-btn,.gd-toast{transition:none} }+@media (max-width:420px){ .gd-actions .gd-btn{ flex:1 1 100%; } }`;function injectStyle() {@@ -92,9 +104,33 @@ function fmtDuration(ms) {return `${s}s`;}+// The API's phase names are storage identifiers. A guardian reads a sentence.+const STATUS_LABEL = {+ pending_approvals: 'awaiting approvals',+ time_locked: 'in the safety window',+ ready: 'ready to complete',+ completed: 'completed',+ cancelled: 'cancelled',+ rejected: 'rejected by the owner',+ expired: 'expired',+};++// Every failure a guardian can actually hit, phrased as something they can do+// about it. Anything unmapped falls through to the server's own sentence, which+// this API writes for humans; a raw exception string never reaches the page.+function humanError(res) {+ if (res.code === 'network_error' || res.status === 0) {+ return 'We could not reach three.ws. Check your connection, then try again.';+ }+ if (res.status === 429) return 'Too many requests in a row. Wait a moment, then try again.';+ if (res.status === 403) return res.message || 'You are not part of this recovery circle any more.';+ if (res.status >= 500) return 'The guardian service is having trouble right now. Nothing was changed. Try again in a moment.';+ return res.message || 'Something went wrong. Nothing was changed.';+}+async function call(url, { method = 'GET', body = null } = {}) {try {- const opts = { method, credentials: 'include', headers: {} };+ const opts = { method, credentials: 'include', headers: { accept: 'application/json' } };if (body != null) { opts.headers['content-type'] = 'application/json'; opts.body = JSON.stringify(body); }if (method !== 'GET') { const tok = await consumeCsrfToken(); if (tok) opts.headers['x-csrf-token'] = tok; }const r = await fetch(url, opts);@@ -107,10 +143,32 @@ async function call(url, { method = 'GET', body = null } = {}) {}let busy = false;+// Set when a process is inside its safety window: reload exactly when the lock+// lifts so "ready to complete" appears without the guardian reloading by hand.+let unlockTimer = null;++function scheduleUnlockRefresh(items) {+ clearTimeout(unlockTimer);+ const waits = items+ .map((it) => it.active_request?.ms_until_unlock)+ .filter((ms) => typeof ms === 'number' && ms > 0);+ if (!waits.length) return;+ // Cap the wait so a multi-day lock does not pin a timer for days; the page+ // re-arms on every render, and a stale tab re-checks when it regains focus.+ const wait = Math.min(Math.min(...waits) + 1000, 10 * 60 * 1000);+ unlockTimer = setTimeout(() => { load(); }, wait);+}function avatarHTML(item) {- if (item.avatar_url) return `<img class="gd-ava" src="${esc(item.avatar_url)}" alt="" loading="lazy" data-fallback="element" data-fallback-tag="span" data-fallback-class="gd-ava" data-fallback-text="${esc((item.agent_name || '?').slice(0, 1).toUpperCase())}" />`;- return `<span class="gd-ava" aria-hidden="true">${esc((item.agent_name || '?').slice(0, 1).toUpperCase())}</span>`;+ const initial = esc((item.agent_name || '?').slice(0, 1).toUpperCase());+ if (item.avatar_url) return `<img class="gd-ava" src="${esc(item.avatar_url)}" alt="" loading="lazy" data-fallback="element" data-fallback-tag="span" data-fallback-class="gd-ava" data-fallback-text="${initial}" />`;+ return `<span class="gd-ava" aria-hidden="true">${initial}</span>`;+}++function votesHTML(p) {+ const votes = (p.votes || []).filter((v) => v.decision === 'approve' || v.decision === 'decline');+ if (!votes.length) return '';+ return `<ul class="gd-votes">${votes.map((v) => `<li class="${v.decision === 'approve' ? 'yes' : 'no'}">${v.decision === 'approve' ? 'Approved' : 'Declined'} by ${esc(v.label || 'a guardian')}</li>`).join('')}</ul>`;}function processHTML(item) {@@ -120,18 +178,21 @@ function processHTML(item) {return `<div class="gd-proc"><p class="gd-tl">No active process. If the owner has gone silent past their threshold, you can arm inheritance.</p><div class="gd-actions"><button class="gd-btn" type="button" data-act="arm" data-agent="${esc(item.agent_id)}">Try to arm inheritance</button></div></div>`;}- return `<div class="gd-proc"><p class="gd-tl">No active recovery or inheritance. You’ll be notified if you’re ever needed.</p></div>`;+ return `<div class="gd-proc"><p class="gd-tl">No active recovery or inheritance. You will be notified if you are ever needed.</p></div>`;}const isInh = p.kind === 'inheritance';const narrate = isInh- ? '“My owner has gone quiet. You’re my beneficiary or guardian — confirm only if you truly believe they’re gone. They can still stop this by showing up.”'- : '“I’m being recovered. If you trust this person is really my owner, approve. If anything feels off, decline.”';+ ? '“My owner has gone quiet. You are my beneficiary or guardian: confirm only if you truly believe they are gone. They can still stop this by showing up.”'+ : '“I am being recovered. If you trust this person is really my owner, approve. If anything feels off, decline.”';const approvalsLine = p.approvals_required > 0? `Approvals: ${p.approvals}/${p.approvals_required}${p.declines ? ` · ${p.declines} declined` : ''}`: (p.needs_beneficiary_confirmation ? 'Awaiting beneficiary confirmation' : 'Beneficiary confirmed');const lockLine = p.ms_until_unlock > 0? `Safety window: ${fmtDuration(p.ms_until_unlock)} remaining`- : (p.status === 'ready' ? 'Safety window elapsed — ready to complete' : 'Safety window starts after approvals');+ : (p.status === 'ready' ? 'Safety window elapsed, ready to complete' : 'Safety window starts after approvals');+ const expiryLine = p.ms_until_expiry > 0 && p.status === 'pending_approvals'+ ? ` · expires in ${fmtDuration(p.ms_until_expiry)} if no one acts`+ : '';const youVoted = (p.votes || []).find((v) => v.user_id === item._viewerId);const actions = [];@@ -152,23 +213,25 @@ function processHTML(item) {return `<div class="gd-proc">- <div class="gd-proc-h">${isInh ? '🕊' : '🔓'} ${isInh ? 'Inheritance' : 'Recovery'} in progress <span class="gd-pill ${isInh ? 'beneficiary' : 'guardian'}">${esc(p.status)}</span></div>+ <div class="gd-proc-h">${isInh ? '🕊' : '🔓'} ${isInh ? 'Inheritance' : 'Recovery'} in progress <span class="gd-pill ${isInh ? 'beneficiary' : 'guardian'}">${esc(STATUS_LABEL[p.status] || p.status)}</span></div><div class="gd-narrate">${esc(narrate)}</div>+ ${p.reason ? `<div class="gd-reason"><b>Why they say they need this</b>${esc(p.reason)}</div>` : ''}<div class="gd-count">${esc(approvalsLine)}</div>- <div class="gd-tl">${esc(lockLine)} · opened ${new Date(p.created_at).toLocaleString()}</div>+ ${votesHTML(p)}+ <div class="gd-tl">${esc(lockLine)}${esc(expiryLine)} · opened ${esc(new Date(p.created_at).toLocaleString())}</div>${actions.length ? `<div class="gd-actions">${actions.join('')}</div>` : ''}</div>`;}function itemHTML(item) {- const roles = (item.roles || []).map((r) => `<span class="gd-pill ${r}">${r}</span>`).join('');+ const roles = (item.roles || []).map((r) => `<span class="gd-pill ${r}">${r === 'guardian' ? 'Guardian' : 'Beneficiary'}</span>`).join('');return `<div class="gd-card ${item.needs_action ? 'act' : ''}"><div class="gd-row">${avatarHTML(item)}<div class="gd-id"><div class="gd-name"><a href="/agents/${esc(item.agent_id)}">${esc(item.agent_name || 'Agent')}</a></div>- <div class="gd-meta">Owned by ${esc(item.owner?.label || 'someone')} · trusted since ${item.since ? new Date(item.since).toLocaleDateString() : '—'}</div>+ <div class="gd-meta">Owned by ${esc(item.owner?.label || 'someone')} · trusted since ${item.since ? esc(new Date(item.since).toLocaleDateString()) : 'unknown'}</div></div><div class="gd-roles">${roles}</div></div>@@ -178,40 +241,70 @@ function itemHTML(item) {function renderLoading() {injectStyle();+ root.setAttribute('aria-busy', 'true');root.innerHTML = `<div class="gd"><div class="gd-skel"></div><div class="gd-skel"></div></div>`;}function renderSignedOut() {+ injectStyle();+ root.removeAttribute('aria-busy');+ const next = encodeURIComponent(location.pathname + location.search);root.innerHTML = `<div class="gd"><div class="gd-empty"><span class="ill" aria-hidden="true">🛡</span>- <h2 style="margin:0 0 6px;color:var(--ink-bright,#fff);">Sign in to your guardian console</h2>- <p>This is where you help the people who trust you back into their agents. Sign in to see who’s named you.</p>- <div class="gd-actions" style="justify-content:center;margin-top:14px;"><a class="gd-btn gd-btn--primary" href="/login">Sign in</a></div>+ <h1>Sign in to your guardian console</h1>+ <p>This is where you help the people who trust you back into their agents. Sign in to see who has named you.</p>+ <div class="gd-actions" style="justify-content:center;margin-top:14px;">+ <a class="gd-btn gd-btn--primary" href="/login?next=${next}">Sign in</a>+ <a class="gd-btn" href="/register?next=${next}">Create an account</a>+ </div></div></div>`;}-function renderError(msg) {- root.innerHTML = `<div class="gd"><div class="gd-empty"><span class="ill">⚠️</span><p>${esc(msg || 'Something went wrong')}</p><div class="gd-actions" style="justify-content:center;"><button class="gd-btn" type="button" id="gd-retry">Try again</button></div></div></div>`;+function renderError(res) {+ injectStyle();+ root.removeAttribute('aria-busy');+ root.innerHTML = `+ <div class="gd">+ <div class="gd-empty" role="alert">+ <span class="ill" aria-hidden="true">⚠️</span>+ <h1>We could not load your guardian console</h1>+ <p>${esc(humanError(res))}</p>+ <div class="gd-actions" style="justify-content:center;margin-top:14px;">+ <button class="gd-btn gd-btn--primary" type="button" id="gd-retry">Try again</button>+ <a class="gd-btn" href="/dashboard">Back to dashboard</a>+ </div>+ </div>+ </div>`;document.getElementById('gd-retry')?.addEventListener('click', load);}+function renderEmpty() {+ root.innerHTML = `+ <div class="gd">+ <div class="gd-hero">+ <span class="gd-hero-ic" aria-hidden="true">🛡</span>+ <div><h1>Guardian console</h1><p>When someone names you a guardian or beneficiary of their agent, it shows up here. You will be able to help them recover access, or, if they are truly gone, pass their agent to its heir.</p></div>+ </div>+ <div class="gd-empty">+ <span class="ill" aria-hidden="true">🫂</span>+ <h2>No one has named you yet</h2>+ <p>Ask a friend who runs a funded agent to add you as a guardian. Being someone's safety net is a real bond on three.ws. You can also name your own guardians from any agent's wallet, so someone can do the same for you.</p>+ <div class="gd-actions" style="justify-content:center;margin-top:14px;">+ <a class="gd-btn gd-btn--primary" href="/dashboard">Set up recovery on your agents</a>+ <a class="gd-btn" href="/docs/guardian">How guardianship works</a>+ </div>+ </div>+ </div>`;+}+function render(data, viewerId) {injectStyle();+ root.removeAttribute('aria-busy');const items = data.items || [];- if (!items.length) {- root.innerHTML = `- <div class="gd">- <div class="gd-hero">- <span class="gd-hero-ic" aria-hidden="true">🛡</span>- <div><h1>Guardian console</h1><p>When someone names you a guardian or beneficiary of their agent, it shows up here. You’ll be able to help them recover access — or, if they’re truly gone, pass their agent to its heir.</p></div>- </div>- <div class="gd-empty"><span class="ill" aria-hidden="true">🫂</span><h2 style="margin:0 0 6px;color:var(--ink-bright,#fff);">No one’s named you yet</h2><p>Ask a friend who runs a funded agent to add you as a guardian — being someone’s safety net is a real bond on three.ws.</p></div>- </div>`;- return;- }+ if (!items.length) { renderEmpty(); return; }items.forEach((it) => { it._viewerId = viewerId; });root.innerHTML = `<div class="gd">@@ -219,13 +312,14 @@ function render(data, viewerId) {<span class="gd-hero-ic" aria-hidden="true">🛡</span><div><h1>Guardian console</h1>- <p>The agents you’re trusted to protect. You never see anyone’s funds or keys — only the power to help them back in.</p>+ <p>The agents you are trusted to protect. You never see anyone's funds or keys, only the power to help them back in.</p>${data.actionable ? `<span class="gd-badge">● ${data.actionable} ${data.actionable === 1 ? 'agent needs' : 'agents need'} your action</span>` : ''}</div></div>${items.map(itemHTML).join('')}</div>`;wire();+ scheduleUnlockRefresh(items);}function wire() {@@ -244,21 +338,23 @@ function wire() {busy = true;btn.disabled = true;- let url, res;+ let res;if (act === 'arm') {res = await call(`/api/agents/${encodeURIComponent(agent)}/recovery/inheritance/arm`, { method: 'POST', body: {} });} else {- url = `/api/agents/${encodeURIComponent(agent)}/recovery/requests/${encodeURIComponent(rid)}/${act}`;- res = await call(url, { method: 'POST', body: {} });+ res = await call(`/api/agents/${encodeURIComponent(agent)}/recovery/requests/${encodeURIComponent(rid)}/${act}`, { method: 'POST', body: {} });}busy = false;- if (!res.ok) { toast(res.message || 'Action failed'); btn.disabled = false; return; }+ // A session that expired while the page sat open must not read as a+ // mystery failure: send them back to the signed-out door.+ if (res.status === 401) { noteSession(false); renderSignedOut(); return; }+ if (!res.ok) { toast(humanError(res)); btn.disabled = false; return; }const msg = {- approve: 'Approved — thank you for vouching',+ approve: 'Approved. Thank you for vouching.',confirm: 'Confirmed',decline: 'Declined',- complete: 'Transfer complete — control has passed',- arm: 'Inheritance armed — the grace window has begun',+ complete: 'Transfer complete. Control has passed.',+ arm: 'Inheritance armed. The grace window has begun.',}[act] || 'Done';toast(msg);await load();@@ -266,19 +362,31 @@ function wire() {});}+/**+ * Resolve the viewer before asking for the inbox. /api/auth/me answers 200 with+ * `{ user: null }` for a signed-out visitor, so the signed-out path costs one+ * clean request instead of a red 401 in every anonymous console, and the authed+ * path gets the viewer id it needs for "you approved" out of the same response+ * rather than a second lookup.+ */async function load() {renderLoading();+ const me = await call('/api/auth/me');+ if (!me.ok) { renderError(me); return; }+ const viewer = me.data?.user || null;+ noteSession(!!viewer);+ if (!viewer) { renderSignedOut(); return; }+const res = await call('/api/agents/recovery-inbox');- if (res.status === 401) { renderSignedOut(); return; }- if (!res.ok) { renderError(res.message); return; }- // Resolve the viewer id from the inbox payload (active_request votes reference- // user_ids); fall back to a /api/me lookup only if needed.- let viewerId = null;- try {- const me = await call('/api/me');- viewerId = me.ok ? (me.data?.id || me.data?.user?.id || null) : null;- } catch { /* non-fatal */ }- render(res.data, viewerId);+ if (res.status === 401) { noteSession(false); renderSignedOut(); return; }+ if (!res.ok) { renderError(res); return; }+ render(res.data, viewer.id || null);}+// A guardian who leaves the tab open across a safety window comes back to live+// state, not a snapshot from whenever they opened it.+document.addEventListener('visibilitychange', () => {+ if (document.visibilityState === 'visible' && !busy && root?.querySelector('.gd-card')) load();+});+if (root) load();diff --git a/src/walk.js b/src/walk.jsindex eda4757b6..1ecb5fdd3 100644--- a/src/walk.js+++ b/src/walk.js@@ -4781,11 +4781,34 @@ if (import.meta.env?.DEV) {if (pickerPanel) pickerPanel.hidden = true;});+ // Distinguish the two ways the list can come up empty. A 401/403 means the+ // visitor has no account yet, so the useful action is signing in; anything+ // else (5xx, offline, a parse failure) is a transient fault, and telling a+ // signed-in walker to "sign in" there is both wrong and unactionable, so+ // that branch offers a retry instead.+ function renderPickerNotice(kind) {+ if (!pickerList) return;+ if (kind === 'unauthenticated') {+ pickerList.innerHTML =+ '<div class="walk-avatar-picker-loading"><a href="/login" style="color:#fff;text-decoration:underline">Sign in</a> to use your avatars</div>';+ return;+ }+ pickerList.innerHTML =+ '<div class="walk-avatar-picker-loading">Could not load your avatars. <button type="button" class="walk-avatar-picker-retry" data-avatar-retry>Try again</button></div>';+ }+async function loadAvatarList() {pickerLoaded = true;+ if (pickerList)+ pickerList.innerHTML =+ '<div class="walk-avatar-picker-loading">Loading your avatars...</div>';try {const res = await fetch('/api/avatars?limit=20', { credentials: 'include' });- if (!res.ok) throw new Error('not signed in');+ if (res.status === 401 || res.status === 403) {+ renderPickerNotice('unauthenticated');+ return;+ }+ if (!res.ok) throw new Error(`avatars request failed: ${res.status}`);const data = await res.json();const avatars = data?.avatars ?? [];if (!avatars.length) {@@ -4810,14 +4833,18 @@ if (import.meta.env?.DEV) {}).join('')}`;- } catch {- pickerList.innerHTML =- '<div class="walk-avatar-picker-loading"><a href="/login" style="color:#fff;text-decoration:underline">Sign in</a> to use your avatars</div>';+ } catch (err) {+ log.error('[walk] avatar list failed:', err);+ renderPickerNotice('error');}}if (pickerList)pickerList.addEventListener('click', async (e) => {+ if (e.target.closest('[data-avatar-retry]')) {+ loadAvatarList();+ return;+ }const btn = e.target.closest('.walk-avatar-opt');if (!btn) return;const url = btn.dataset.avatarUrl;diff --git a/tests/e2e/galaxy.spec.js b/tests/e2e/galaxy.spec.jsindex b8bf19d81..81ecaa461 100644--- a/tests/e2e/galaxy.spec.js+++ b/tests/e2e/galaxy.spec.js@@ -1,59 +1,54 @@/**- * IBM Granite Agent Galaxy — Playwright e2e spec.+ * Agent Galaxy (/galaxy): the Playwright e2e spec.*- * Every test intercepts /api/ibm/galaxy with a fixture built from the REAL- * production pipeline (api/_lib/embedding-math.js), so the coordinates and- * cluster assignments that render are identical to what prod would produce- * for that agent set. No fabricated positions.+ * Every test intercepts /api/galaxy with a payload built by the REAL production+ * assembler (api/_lib/galaxy.js → assembleGalaxy, which runs the same PCA+ * projection and k-means clustering prod runs), so the coordinates, cluster+ * assignments and payload shape that reach the viewer are what prod would emit+ * for that agent set. Nothing about the render path is faked.** State coverage:- * • watsonx unavailable → shows the unavailable overlay- * • no agents → shows the empty overlay- * • populated galaxy → full interaction suite- * • deep link ?agent= → opens the targeted star on first paint- * • deep link ?q= → runs semantic search on first paint+ * - populated galaxy -> stars render, legend + stats fill in+ * - no agents -> empty overlay, with a way to create one+ * - watsonx 503 -> unretryable error overlay, with a way onward+ * - transport failure -> retryable error overlay, retry recovers** Interaction coverage:- * • loading steps animate- * • 3D scene reaches "ready" (WebGL runs under swiftshader)- * • legend lists Granite-named themes- * • cluster labels in 3D space- * • stats panel shows dims/model- * • search box present + chip hints- * • semantic search → ranked results → result click → detail panel- * • detail panel: Granite cosine % on neighbors, constellation links drawn- * • shareable URL updates on select + search- * • guided tour starts/stops, isolates a theme- * • legend row click → fly-to + isolate- * • Escape closes panel; / focuses search; R resets+ * - semantic search -> ranked results -> result click -> agent card+ * - card actions point at the agent page and its chat panel+ * - legend row flies to a constellation and isolates it+ * - Escape closes the card+ * - overlays take the HUD out of the tab order*/-import { createRequire } from 'module';import { test, expect } from '@playwright/test';-import { fileURLToPath } from 'url';+import { fileURLToPath, pathToFileURL } from 'url';import { dirname, resolve } from 'path';const __dirname = dirname(fileURLToPath(import.meta.url));-// Resolve relative to the repo root so the path is absolute regardless of cwd.const repoRoot = resolve(__dirname, '..', '..');-const require = createRequire(import.meta.url);-// Build the fixture lazily so Playwright workers don't pay the import cost for-// specs that don't need it.+// Build the fixture lazily so workers don't pay the import cost for specs that+// don't need it.let _fixture = null;-function buildFixture() {+async function buildFixture() {if (_fixture) return _fixture;- const { makeRng, unit, cosineSimilarity, projectTo3D, kmeans, suggestClusterCount } =- require(resolve(repoRoot, 'api/_lib/embedding-math.js'));+ const mathUrl = pathToFileURL(resolve(repoRoot, 'api/_lib/embedding-math.js')).href;+ const galaxyUrl = pathToFileURL(resolve(repoRoot, 'api/_lib/galaxy.js')).href;+ const { makeRng, unit, cosineSimilarity } = await import(mathUrl);+ const { assembleGalaxy, rankBySimilarity } = await import(galaxyUrl);const DIMS = 32;const AXES = [0, 9, 18, 27];const PER = 11;- const COLORS = ['#4589ff', '#08bdba', '#a56eff', '#ff7eb6', '#fa4d56', '#f1c21b', '#42be65', '#82cfff'];const THEMES = ['Crypto Trading', 'Customer Support', 'Creative Writing', 'Wellness Coaching'];const rng = makeRng(2026);- const agents = [], vectors = [];+ // Four well-separated directions in a 32-dim space stand in for four genuinely+ // different agent themes. The vectors are the only synthetic input; every+ // coordinate and cluster below is computed by the production assembler.+ const agents = [];+ const vectors = [];AXES.forEach((axis, theme) => {for (let i = 0; i < PER; i++) {const v = new Array(DIMS).fill(0).map(() => (rng() - 0.5) * 0.18);@@ -63,127 +58,82 @@ function buildFixture() {id: `aaaaaaaa-aaaa-4aaa-8aaa-${String(theme).padStart(2, '0')}${String(i).padStart(10, '0')}`,name: `${THEMES[theme]} Agent ${i + 1}`,description: `A ${THEMES[theme].toLowerCase()} specialist, agent ${i + 1}.`,+ chat_count: (theme + 1) * (i + 1),});}});- const u = vectors.map(unit);- const coords = projectTo3D(u, { radius: 100 });- const k = suggestClusterCount(agents.length);- const { assignments, k: realK } = kmeans(u, k);- const groups = Array.from({ length: realK }, () => []);- agents.forEach((_, i) => groups[assignments[i]].push(i));- const round = (n) => Math.round(n * 100) / 100;-- const neighborsFor = (i) =>- u.map((v, j) => ({ j, s: cosineSimilarity(u[i], v) }))- .filter((x) => x.j !== i)- .sort((a, b) => b.s - a.s)- .slice(0, 6);-- const outAgents = agents.map((a, i) => ({- ...a,- url: `/agent/${a.id}`,- image: null,- cluster: assignments[i],- x: round(coords[i][0]),- y: round(coords[i][1]),- z: round(coords[i][2]),- neighbors: neighborsFor(i).map((nb) => ({ id: agents[nb.j].id, score: round(nb.s) })),- }));-- const clusters = groups.map((members, ci) => {- const c = [0, 0, 0];- members.forEach((i) => { c[0] += coords[i][0]; c[1] += coords[i][1]; c[2] += coords[i][2]; });- const n = members.length || 1;- return {- id: ci,- label: THEMES[ci] || `Theme ${ci + 1}`,- labelSource: 'granite',- color: COLORS[ci % COLORS.length],- size: members.length,- x: round(c[0] / n),- y: round(c[1] / n),- z: round(c[2] / n),- };+ const model = 'ibm/granite-embedding-278m-multilingual';+ const payload = await assembleGalaxy(agents, vectors, {+ dims: DIMS,+ model,+ // Mirror the prod namer's contract: it returns one {name, theme} per+ // cluster, aligned by index.+ nameClusters: (clusters) =>+ clusters.map((c) => ({ name: THEMES[c.id] || `Theme ${c.id + 1}`, theme: 'test' })),});- const searchResults = (queryTheme = 0) => {- const qAxis = AXES[queryTheme];+ const byId = new Map(agents.map((a, i) => [a.id, unit(vectors[i])]));+ const searchFor = (theme = 0) => {const q = new Array(DIMS).fill(0);- q[qAxis] = 1;- const ranked = outAgents.map((a, i) => ({ id: a.id, score: round(cosineSimilarity(q, u[i])) }))- .sort((b, a) => a.score - b.score).slice(0, 16);- return { query: 'test', model: 'ibm/granite-embedding-278m-multilingual', count: ranked.length, best: ranked[0], results: ranked };+ q[AXES[theme]] = 1;+ const results = rankBySimilarity(q, byId, { topK: 12 });+ return { query: THEMES[theme], model, count: results.length, results };};- _fixture = {- payload: {- available: true,- agents: outAgents,- clusters,- meta: {- count: outAgents.length,- totalPublic: outAgents.length,- truncated: false,- model: 'ibm/granite-embedding-278m-multilingual',- dims: DIMS,- clusterCount: realK,- generatedAt: new Date().toISOString(),- },- },- agents: outAgents,- searchResults,- };+ _fixture = { payload, agents: payload.agents, searchFor, cosineSimilarity };return _fixture;}-// Route helper — intercept galaxy endpoint with the right response per method.-async function mockGalaxy(page, mode = 'success') {- const fx = buildFixture();- await page.route('**/api/ibm/galaxy', async (route) => {- const method = route.request().method();- if (method === 'POST') {- return route.fulfill({ json: fx.searchResults(0) });+// Intercept the galaxy endpoint. `mode` picks which state the page lands in.+async function routeGalaxy(page, mode = 'success') {+ const fx = await buildFixture();+ await page.route('**/api/galaxy', async (route) => {+ if (route.request().method() === 'POST') {+ if (mode === 'unavailable') {+ return route.fulfill({ status: 503, json: watsonx503() });+ }+ return route.fulfill({ json: fx.searchFor(0) });}- if (mode === 'success') return route.fulfill({ json: fx.payload });- if (mode === 'unavailable') return route.fulfill({- json: { available: false, reason: 'watsonx_not_configured', message: 'Set WATSONX_API_KEY.' },- });- if (mode === 'empty') return route.fulfill({- json: { available: true, agents: [], clusters: [], meta: { count: 0, reason: 'no_agents' } },- });+ if (mode === 'success') {+ return route.fulfill({ json: { ...fx.payload, cached: false, generated_at: new Date().toISOString() } });+ }+ if (mode === 'empty') {+ return route.fulfill({+ json: { count: 0, dims: 0, model: null, clusters: [], agents: [], cached: false },+ });+ }+ if (mode === 'unavailable') return route.fulfill({ status: 503, json: watsonx503() });+ if (mode === 'down') return route.abort('failed');return route.fallback();});+ // The galaxy lights its stars from real wallet net worth and draws lineage+ // edges; neither is under test here and both are best-effort in the viewer.+ await page.route('**/api/agents/networth**', (r) => r.fulfill({ json: { data: { items: [] } } }));+ await page.route('**/api/genome/edges**', (r) => r.fulfill({ json: { edges: [] } }));}-// Shared helper: navigate and wait for a given body state.-async function gotoGalaxy(page, { mode = 'success', path = '/ibm/galaxy', expectState } = {}) {- await mockGalaxy(page, mode);- await page.goto(path);- const target = expectState || (mode === 'success' ? 'ready' : mode);- await page.waitForFunction(- (s) => document.body.dataset.galaxyState === s,- target,- { timeout: 20_000 },- );+function watsonx503() {+ return {+ error: 'watsonx_unavailable',+ error_description:+ 'The Agent Galaxy is positioned by IBM Granite embeddings on watsonx.ai. ' ++ 'Set WATSONX_API_KEY and WATSONX_PROJECT_ID (or WATSONX_SPACE_ID) to build it.',+ };}-// ── Tests ─────────────────────────────────────────────────────────────────────+async function gotoGalaxy(page, mode = 'success') {+ await routeGalaxy(page, mode);+ await page.goto('/galaxy');+ const want = { success: 'ready', empty: 'empty' }[mode] || 'error';+ await page.waitForFunction((s) => window.__galaxy?.status === s, want, { timeout: 60_000 });+}-// reason: the IBM-branded galaxy page (pages/ibm/galaxy.html → src/ibm-galaxy.js,-// route /ibm/galaxy, endpoint /api/ibm/galaxy, body.dataset.galaxyState markers)-// was deleted in the concurrent site overhaul (commits 7af4f0b3 "delete IBM pages",-// 2d34e80f "Site overhaul", 9664ef4b "Wire orphaned pages into router"). The galaxy-// product now lives at top-level /galaxy via src/galaxy.js fetching /api/galaxy with-// a different response shape and no galaxyState dataset — none of the locators or-// the fixture below match it. Skipped (not deleted) until the new /galaxy page's-// router wiring stabilizes and this spec is rewritten against src/galaxy.js.-test.describe.skip('IBM Agent Galaxy', () => {- // Throw on any real uncaught page error. Vite's HMR websocket emits a- // "WebSocket closed without opened." error in headless Codespace environments- // (the HMR client targets the :3000 forwarded domain, not the test port) —- // that's dev-server noise and not a product bug, so filter it out.+test.describe('Agent Galaxy', () => {+ // Fail on any real uncaught page error. Vite's HMR websocket emits+ // "WebSocket closed without opened." in headless Codespace runs (the HMR+ // client targets the forwarded :3000 domain, not the test port). That is dev-server+ // noise, not a product bug.test.beforeEach(async ({ page }) => {page.on('pageerror', (err) => {if (/websocket|hmr|wss:|failed to connect/i.test(err.message)) return;@@ -191,245 +141,144 @@ test.describe.skip('IBM Agent Galaxy', () => {});});- // ── State: watsonx unconfigured ──────────────────────────────────────────- test('shows unavailable overlay when watsonx is not configured', async ({ page }) => {- test.setTimeout(60_000);- await gotoGalaxy(page, { mode: 'unavailable', expectState: 'unavailable' });- await expect(page.locator('#unavailableState')).toBeVisible();- await expect(page.locator('#unavailableState h2')).toContainText('not configured');- // The /ibm link is present so users know what to do.- await expect(page.locator('#unavailableState a[href="/ibm"]')).toBeVisible();+ test('renders every agent as a star, with stats and a named legend', async ({ page }) => {+ const fx = await buildFixture();+ await gotoGalaxy(page, 'success');++ const dbg = await page.evaluate(() => ({+ ready: window.__galaxy.ready,+ agents: window.__galaxy.agentCount,+ clusters: window.__galaxy.clusterCount,+ points: window.__galaxy.pointCount,+ }));+ expect(dbg.ready).toBe(true);+ expect(dbg.agents).toBe(fx.agents.length);+ expect(dbg.points).toBe(fx.agents.length);+ expect(dbg.clusters).toBe(fx.payload.clusters.length);++ await expect(page.locator('#gxStats')).toBeVisible();+ await expect(page.locator('#gxStatAgents')).toContainText(String(fx.agents.length));+ await expect(page.locator('#gxLegend')).toBeVisible();+ expect(await page.locator('#gxLegendList .gx-legend-item').count()).toBe(+ fx.payload.clusters.length,+ );++ // No overlay is left covering a rendered galaxy, and the HUD is usable again.+ for (const id of ['gxLoading', 'gxEmpty', 'gxError']) {+ expect(await page.locator(`#${id}`).isVisible()).toBe(false);+ }+ await expect(page.locator('#gxSearchInput')).toBeEnabled();+ await expect(page.locator('#gxMoneyToggle')).toBeEnabled();});- // ── State: no agents ────────────────────────────────────────────────────- test('shows empty state when no public agents exist', async ({ page }) => {- test.setTimeout(60_000);- await gotoGalaxy(page, { mode: 'empty', expectState: 'empty' });- await expect(page.locator('#emptyState')).toBeVisible();- await expect(page.locator('#emptyState a[href="/create"]')).toBeVisible();+ test('semantic search ranks agents, and a result opens its card', async ({ page }) => {+ await gotoGalaxy(page, 'success');++ await page.fill('#gxSearchInput', 'crypto trading');+ await page.click('#gxSearchGo');+ await expect(page.locator('#gxResults')).toBeVisible();+ const results = page.locator('#gxResultsList .gx-result');+ await expect(results.first()).toBeVisible();+ expect(await results.count()).toBeGreaterThan(0);+ // Every match is a real agent in the rendered galaxy, scored as a percentage.+ await expect(results.first()).toContainText('%');++ await results.first().click();+ await expect(page.locator('#gxCard')).toBeVisible();+ await expect(page.locator('#gxCardName')).not.toBeEmpty();++ // The two card actions lead somewhere different: the agent page, and its+ // chat panel.+ const view = await page.getAttribute('#gxCardView', 'href');+ const chat = await page.getAttribute('#gxCardChat', 'href');+ expect(view).toMatch(/^\/agents\/[0-9a-f-]+$/i);+ expect(chat).toBe(`${view}?view=chat`);++ await page.keyboard.press('Escape');+ await expect(page.locator('#gxCard')).toBeHidden();});- // ── Populated galaxy ─────────────────────────────────────────────────────- test.describe('populated galaxy', () => {- test('renders stars, legend, stats, search', async ({ page }) => {- test.setTimeout(90_000);- await gotoGalaxy(page);-- const g = () => page.evaluate(() => window.__ibmGalaxy);-- // WebGL actually rendered something.- const info = await page.evaluate(() => window.__ibmGalaxy.rendererInfo());- expect(info.calls).toBeGreaterThan(0);- expect(info.points).toBeGreaterThan(0);-- // Star count matches payload.- const stars = await page.evaluate(() => window.__ibmGalaxy.starCount());- expect(stars).toBe(buildFixture().payload.agents.length);-- // Legend with correct cluster count.- const fx = buildFixture();- const legendRows = page.locator('#legendRows .row');- await expect(legendRows).toHaveCount(fx.payload.meta.clusterCount);- // Each row has a theme label.- const firstLabel = await legendRows.first().locator('.name').textContent();- expect(firstLabel.length).toBeGreaterThan(0);-- // 3D cluster labels rendered in the overlay.- const clusterLabels = page.locator('#clusterLabels .clabel');- await expect(clusterLabels).toHaveCount(fx.payload.meta.clusterCount);-- // Stats panel visible with model name.- await expect(page.locator('#stats')).toBeVisible();- await expect(page.locator('#stats')).toContainText(String(fx.payload.meta.dims));-- // Search bar and example chips visible.- await expect(page.locator('#searchWrap')).toBeVisible();- await expect(page.locator('#searchHint .chip').first()).toBeVisible();- });-- test('semantic search ranks results and highlights stars', async ({ page }) => {- test.setTimeout(90_000);- await gotoGalaxy(page);-- // Type and submit a search.- await page.fill('#searchInput', 'crypto trading assistant');- await page.keyboard.press('Enter');-- // Results panel appears with ranked items.- await expect(page.locator('#results')).toBeVisible();- const items = page.locator('#results .ritem');- await expect(items).toHaveCount(8); // top 8 shown-- // Each result has a score bar.- await expect(items.first().locator('.r-bar')).toBeVisible();- await expect(items.first().locator('.r-score')).toContainText('%');-- // Ranked by header says Granite.- await expect(page.locator('#results .r-head')).toContainText('Granite');-- // Search active state is set.- const active = await page.evaluate(() => window.__ibmGalaxy.state.searchActive);- expect(active).toBe(true);-- // URL has ?q= param.- expect(page.url()).toContain('q=');-- // Clear button appears.- await expect(page.locator('#searchClear')).toBeVisible();-- // Clearing hides results — the element stays in DOM but loses the "show"- // class (opacity→0, pointer-events→none), so check class not visibility.- await page.click('#searchClear');- await expect(page.locator('#results')).not.toHaveClass(/show/, { timeout: 3_000 });- expect(page.url()).not.toContain('q=');- });-- test('clicking a result opens detail panel with Granite cosine neighbors', async ({ page }) => {- test.setTimeout(90_000);- await gotoGalaxy(page);-- await page.fill('#searchInput', 'crypto trading');- await page.keyboard.press('Enter');- await expect(page.locator('#results .ritem').first()).toBeVisible();-- // Click top result via in-page click (avoids transition timing issues).- await page.evaluate(() => document.querySelector('#results .ritem').click());- await expect(page.locator('#panel')).toHaveClass(/open/);-- // Panel shows agent name.- await expect(page.locator('#panelHead .p-name')).toBeVisible();- const name = await page.locator('#panelHead .p-name').textContent();- expect(name.length).toBeGreaterThan(0);-- // Theme badge with color.- await expect(page.locator('#panelHead .p-theme')).toBeVisible();-- // Neighbors section with Granite cosine label.- await expect(page.locator('#panelBody .neighbors h4')).toContainText('Nearest');- const nbs = page.locator('#panelBody .nb');- await expect(nbs).toHaveCount(5);- // Each neighbor has a cosine % score (new markup uses .nb-pct).- await expect(nbs.first().locator('.nb-pct')).toContainText('%');-- // Constellation links drawn in 3D.- const links = await page.evaluate(() => window.__ibmGalaxy.linkCount());- expect(links).toBeGreaterThan(0);-- // Open-agent CTA link.- await expect(page.locator('#panelBody .p-cta')).toBeVisible();- await expect(page.locator('#panelBody .p-cta')).toContainText('Open');-- // URL has ?agent= param.- expect(page.url()).toContain('agent=');-- // Copy-link button present (new UX feature).- await expect(page.locator('#panelBody .p-copy-link')).toBeVisible();- });-- test('closing panel clears links and URL agent param', async ({ page }) => {- test.setTimeout(90_000);- await gotoGalaxy(page);-- // Open a panel directly.- await page.evaluate(() => document.querySelector('#results .ritem')?.click() || window.__ibmGalaxy.state.agents[0]);- // Select first star via keyboard shortcut (/ then first result click).- await page.fill('#searchInput', 'test');- await page.keyboard.press('Enter');- await expect(page.locator('#results .ritem').first()).toBeVisible();- await page.evaluate(() => document.querySelector('#results .ritem').click());- await expect(page.locator('#panel')).toHaveClass(/open/);-- // Escape closes.- await page.keyboard.press('Escape');- await expect(page.locator('#panel')).not.toHaveClass(/open/);- const links = await page.evaluate(() => window.__ibmGalaxy.linkCount());- expect(links).toBe(0);- expect(page.url()).not.toContain('agent=');- });-- test('guided tour visits each theme and stops on toggle', async ({ page }) => {- test.setTimeout(90_000);- await gotoGalaxy(page);-- await page.click('#tourBtn');- await expect(page.locator('#tourBtn')).toHaveClass(/active/);-- // Tour isolates a cluster.- await page.waitForFunction(() => window.__ibmGalaxy.tourActive() === true, { timeout: 5_000 });- const isolated = await page.evaluate(() => window.__ibmGalaxy.state.isolatedCluster);- expect(isolated).not.toBeNull();-- // Stop.- await page.click('#tourBtn');- await expect(page.locator('#tourBtn')).not.toHaveClass(/active/);- const afterStop = await page.evaluate(() => window.__ibmGalaxy.state.isolatedCluster);- expect(afterStop).toBeNull();- });-- test('legend row click isolates theme and flies camera', async ({ page }) => {- test.setTimeout(90_000);- await gotoGalaxy(page);-- const firstRow = page.locator('#legendRows .row').first();- await firstRow.click();-- // Clicked row stays unmuted; others become muted.- await expect(firstRow).not.toHaveClass(/muted/);- const secondRow = page.locator('#legendRows .row').nth(1);- await expect(secondRow).toHaveClass(/muted/);-- // Isolated cluster is set.- const isolated = await page.evaluate(() => window.__ibmGalaxy.state.isolatedCluster);- expect(isolated).not.toBeNull();-- // Click same row again → deselect.- await firstRow.click();- const afterDeselect = await page.evaluate(() => window.__ibmGalaxy.state.isolatedCluster);- expect(afterDeselect).toBeNull();- });-- test('keyboard shortcuts: / focuses search, R resets, ? toggles help', async ({ page }) => {- test.setTimeout(90_000);- await gotoGalaxy(page);-- // / should focus search input.- await page.keyboard.press('/');- await expect(page.locator('#searchInput')).toBeFocused();-- // Blur first.- await page.keyboard.press('Escape');- await page.locator('#scene').click({ position: { x: 640, y: 400 } });-- // R resets (no error thrown).- await page.keyboard.press('r');+ test('a legend row isolates its constellation', async ({ page }) => {+ await gotoGalaxy(page, 'success');+ const row = page.locator('#gxLegendList .gx-legend-item').first();+ await row.click();+ await expect(row).toHaveClass(/gx-active/);+ expect(await page.evaluate(() => window.__galaxy && document.querySelectorAll('.gx-legend-item.gx-active').length)).toBe(1);+ await row.click();+ await expect(row).not.toHaveClass(/gx-active/);+ });- // ? opens keyboard shortcut overlay.- await page.keyboard.press('?');- await expect(page.locator('#shortcutsOverlay')).toBeVisible();- // Dismiss.- await page.keyboard.press('Escape');- await expect(page.locator('#shortcutsOverlay')).not.toBeVisible();- });+ test('an empty galaxy explains itself and offers a way to fill it', async ({ page }) => {+ await gotoGalaxy(page, 'empty');+ await expect(page.locator('#gxEmpty')).toBeVisible();+ await expect(page.locator('#gxEmpty .gx-overlay-title')).not.toBeEmpty();+ await expect(page.locator('#gxEmpty a[href="/create"]')).toBeVisible();+ await expect(page.locator('#gxEmpty a[href="/agents/"]')).toBeVisible();});- // ── Deep links ───────────────────────────────────────────────────────────- test('?agent= deep link opens targeted agent on first paint', async ({ page }) => {- test.setTimeout(90_000);- const fx = buildFixture();- const target = fx.agents[20];- await gotoGalaxy(page, { path: `/ibm/galaxy?agent=${encodeURIComponent(target.id)}` });+ test('an unconfigured embedder is a dead end for nobody', async ({ page }) => {+ await gotoGalaxy(page, 'unavailable');+ await expect(page.locator('#gxError')).toBeVisible();+ await expect(page.locator('#gxErrorTitle')).toContainText('Granite');+ await expect(page.locator('#gxErrorSub')).toContainText('watsonx');+ // Retrying a configuration gap just fails again, so the retry is hidden and+ // two real onward paths take its place.+ await expect(page.locator('#gxRetry')).toBeHidden();+ await expect(page.locator('#gxErrorBrowse')).toBeVisible();+ await expect(page.locator('#gxError a[href="/docs/ibm"]')).toBeVisible();++ // Nothing behind the overlay stays reachable by keyboard.+ const reachable = await page.evaluate(() =>+ [...document.querySelectorAll('#gxHud button, #gxHud input, #gxFootnote a')].filter(+ (el) => !el.closest('[inert]'),+ ).length,+ );+ expect(reachable).toBe(0);+ });- await expect(page.locator('#panel')).toHaveClass(/open/, { timeout: 10_000 });- await expect(page.locator('#panelHead .p-name')).toContainText(target.name);+ test('a transport failure is retryable, and the retry recovers', async ({ page }) => {+ await gotoGalaxy(page, 'down');+ await expect(page.locator('#gxError')).toBeVisible();+ await expect(page.locator('#gxRetry')).toBeVisible();++ // Swap the endpoint back to a working galaxy, then use the button the page+ // offered. It must recover in place, with no reload.+ await page.unroute('**/api/galaxy');+ await routeGalaxy(page, 'success');+ await page.click('#gxRetry');+ await page.waitForFunction(() => window.__galaxy?.status === 'ready', null, { timeout: 60_000 });+ await expect(page.locator('#gxError')).toBeHidden();+ await expect(page.locator('#gxLegend')).toBeVisible();});- test('?q= deep link runs search on first paint', async ({ page }) => {- test.setTimeout(90_000);- await gotoGalaxy(page, { path: '/ibm/galaxy?q=trading+assistant' });+ test('every control the page offers has a visible keyboard focus ring', async ({ page }) => {+ await gotoGalaxy(page, 'success');+ // Establish keyboard modality so :focus-visible matches.+ await page.keyboard.press('Tab');+ const ids = ['gxSearchInput', 'gxSearchGo', 'gxMoneyToggle'];+ for (const id of ids) {+ const ring = await page.evaluate((i) => {+ const el = document.getElementById(i);+ el.focus();+ const cs = getComputedStyle(el);+ return { fv: el.matches(':focus-visible'), outline: cs.outlineStyle, width: cs.outlineWidth };+ }, id);+ expect(ring.fv, `${id} should match :focus-visible`).toBe(true);+ expect(ring.outline, `${id} needs a focus outline`).not.toBe('none');+ expect(parseFloat(ring.width), `${id} focus outline must be visible`).toBeGreaterThan(0);+ }+ });- await expect(page.locator('#results')).toBeVisible({ timeout: 15_000 });- await expect(page.locator('#results .ritem').first()).toBeVisible();- // Input is pre-filled.- await expect(page.locator('#searchInput')).toHaveValue(/trading/);+ test('lays out without horizontal overflow at 320, 768 and 1440', async ({ page }) => {+ await gotoGalaxy(page, 'success');+ for (const width of [320, 768, 1440]) {+ await page.setViewportSize({ width, height: 800 });+ await page.waitForTimeout(400);+ const m = await page.evaluate(() => ({+ scrollW: document.documentElement.scrollWidth,+ clientW: document.documentElement.clientWidth,+ }));+ expect(m.scrollW, `no horizontal page scroll at ${width}px`).toBeLessThanOrEqual(m.clientW + 1);+ }});});