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(agents-live): poll the activity endpoint so every card loads instead of stalling on Connecting
nirholas6b81ea3ffd8f
diff --git a/pages/agent-studio.html b/pages/agent-studio.htmlindex 77997a87b..245a81482 100644--- a/pages/agent-studio.html+++ b/pages/agent-studio.html@@ -419,6 +419,31 @@.sk-stage { min-height: 240px; }}@media (max-width: 560px) {+ /* At 320px the five tabs measured 534px against a 298px strip, so+ Money and Skills sat off-screen behind a deliberately hidden+ scrollbar with nothing to hint they existed. Below 560px drop the+ keyboard-shortcut number chips (the 1-5 shortcuts still work, they+ are just a desktop affordance) and share the width evenly, so the+ row reads as a segmented control with every tab visible.+ overflow-x stays as the safety net for longer translated labels. */+ .studio-tabs {+ gap: 0;+ padding-left: var(--space-sm, 0.618rem);+ padding-right: var(--space-sm, 0.618rem);+ scroll-snap-type: x proximity;+ }+ .studio-tab {+ flex: 1 1 auto;+ justify-content: center;+ gap: 0;+ padding: 9px 6px;+ font-size: var(--text-md, 0.8125rem);+ scroll-snap-align: center;+ }+ .studio-tab-num {+ display: none;+ }+/* Side-by-side identity + actions needs ~430px; below that the actionrow overflowed the panel and its `overflow: hidden` clipped "Savedraft" and "View agent" off-screen. Stack the actions under thediff --git a/pages/agent-trade.html b/pages/agent-trade.htmlindex 450a62fcb..8f24be21e 100644--- a/pages/agent-trade.html+++ b/pages/agent-trade.html@@ -96,6 +96,19 @@.bubble.hidden { opacity: 0; transform: translateY(8px); }#buyerBubble { background: rgba(69,137,255,0.15); border: 1px solid rgba(69,137,255,0.35); }#sellerBubble { background: rgba(241,194,27,0.1); border: 1px solid rgba(241,194,27,0.35); }+ /* The two long waits (broadcasting the transfer, generating the analysis)+ happen while the centre of the screen stays clear for the 3D beam, so the+ bubble itself carries the liveness cue: a real indeterminate bar, not a+ line of static text that looks identical to a stalled page. */+ .bubble.pending::after {+ content: ''; display: block; height: 2px; margin-top: 9px; border-radius: 2px;+ background: linear-gradient(90deg, transparent 0%, currentColor 45%, currentColor 55%, transparent 100%);+ background-size: 220% 100%; opacity: 0.75;+ animation: bubbleProgress 1.25s linear infinite;+ }+ #buyerBubble.pending::after { color: var(--blue); }+ #sellerBubble.pending::after { color: var(--gold); }+ @keyframes bubbleProgress { from { background-position: 120% 0; } to { background-position: -120% 0; } }/* ── Central floating card ─────────────────────────────────────────── */#centralCard {@@ -127,6 +140,25 @@.c-content { font-size: 0.86rem; line-height: 1.65; color: var(--text); margin-top: 8px; }.c-powered { margin-top: 12px; font-size: 0.67rem; color: var(--muted); font-family: var(--mono); display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }+ /* Pre-flight skeleton: the wallets, price and network are being read from+ Solana, so the card shows the shape of the answer instead of an empty+ stage that reads as a broken page. */+ .c-skel {+ height: 11px; border-radius: 4px; margin: 7px 0;+ background: linear-gradient(90deg, rgba(255,255,255,0.05) 0%, rgba(255,255,255,0.13) 50%, rgba(255,255,255,0.05) 100%);+ background-size: 220% 100%;+ animation: skelSweep 1.4s linear infinite;+ }+ .c-skel-price { height: 26px; width: 58%; margin: 12px 0 10px; }+ .c-skel-row { width: 82%; }+ .c-skel-row.short { width: 62%; }+ @keyframes skelSweep { from { background-position: 120% 0; } to { background-position: -120% 0; } }++ @media (prefers-reduced-motion: reduce) {+ .c-skel, .bubble.pending::after { animation: none; }+ #liveDot { animation: none; }+ }+/* ── Step log ──────────────────────────────────────────────────────── */#stepLog {position: fixed; bottom: 76px; left: 50%; transform: translateX(-50%);@@ -267,7 +299,16 @@#topicSelect, #startBtn { width: 100%; max-width: none; }#stepLog { bottom: 128px; }.step-chip { padding: 3px 8px; font-size: 0.62rem; }- #centralCard { max-height: calc(100vh - 280px); padding: 16px; }+ /* The bottom of a small screen carries the stacked CTA and the wrapped+ step log (about 177px of it), so a card centred on the viewport lands+ on top of the chips. Centre it on the band that is actually free+ instead: below the header, above the step log. */+ #centralCard {+ top: calc(50% - 52px); margin-top: 0;+ transform: translate(-50%, -50%);+ max-height: calc(100vh - 270px); padding: 16px;+ }+ #centralCard.hidden { transform: translate(-50%, -50%) translateY(14px); }.bubble { max-width: 160px; font-size: 0.76rem; }}@media (max-width: 460px) {diff --git a/pages/alpha-copilot.html b/pages/alpha-copilot.htmlindex 35fb3dd4d..e8bd605d6 100644--- a/pages/alpha-copilot.html+++ b/pages/alpha-copilot.html@@ -127,7 +127,13 @@<!-- Live launches --><section class="ac-launches" aria-label="Live launches"><header class="ac-launches-head">- <h2 data-i18n-html="alpha_copilot.live_launches"><span class="ac-live-dot" aria-hidden="true"></span> Live launches <span class="ac-launches-count" id="ac-launches-count" hidden></span></h2>+ <!-- The counter is live data, so it sits OUTSIDE the translated heading:+ a data-i18n-html node has its innerHTML rewritten on every i18n pass,+ which would replace the counter element the script holds a ref to. -->+ <div class="ac-launches-title">+ <h2 data-i18n-html="alpha_copilot.live_launches"><span class="ac-live-dot" aria-hidden="true"></span> Live launches</h2>+ <span class="ac-launches-count" id="ac-launches-count" hidden></span>+ </div><button type="button" class="ac-btn ac-btn-ghost ac-refresh" id="ac-refresh" title="Refresh feed" aria-label="Refresh feed" data-i18n-attr="aria-label:alpha_copilot.refresh_feed_arialabel;title:alpha_copilot.refresh_feed_title"><svg viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 12a9 9 0 1 1-3-6.7L21 8"/><path d="M21 3v5h-5"/></svg><span>Refresh</span>diff --git a/pages/animations.html b/pages/animations.htmlindex 6fb46e221..483de7480 100644--- a/pages/animations.html+++ b/pages/animations.html@@ -481,6 +481,20 @@}/* ── Empty / error states ─────────────────────────────────────── */+ /* Names the results region for assistive tech without a visible heading,+ so the outline runs h1 → h2 → card h3 instead of h1 → h3. */+ .ag-sr-only {+ position: absolute;+ width: 1px;+ height: 1px;+ margin: -1px;+ padding: 0;+ overflow: hidden;+ clip-path: inset(50%);+ white-space: nowrap;+ border: 0;+ }+.ag-state { text-align: center; padding: 80px 24px; }.ag-state-icon { font-size: 48px; margin-bottom: 16px; }.ag-state h2 { font-size: 20px; font-weight: 600; margin: 0 0 8px; }@@ -641,7 +655,8 @@border-radius: 4px;font-size: 10.5px;background: var(--ag-surface-2);- color: var(--text-3, #71717a);+ /* Raised for the 4.5:1 axe AA floor, same as the other muted ink here. */+ color: var(--text-3, #84848e);}.ag-modal-actions {display: flex;@@ -658,7 +673,8 @@.ag-modal-nav .ag-btn:disabled { opacity: 0.35; cursor: default; }.ag-modal-hint {font-size: 11px;- color: var(--text-3, #71717a);+ /* Raised for the 4.5:1 axe AA floor; #71717a measured 3.9:1 here. */+ color: var(--text-3, #84848e);text-align: center;}.ag-modal-hint kbd {@@ -715,7 +731,7 @@<meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1"><meta property="og:locale" content="en_US">- <meta property="og:image:alt" content="Animation Gallery — three.ws">+ <meta property="og:image:alt" content="Animation Gallery on three.ws"></head><body class="ag-page"><header>@@ -732,7 +748,7 @@</div></div><h1 data-i18n="animations.animation_gallery">Animation Gallery</h1>- <p data-i18n="animations.every_clip_in_the_three_ws_motion">Every clip in the three.ws motion library — mocap performances, studio presets, and community-authored animations. Hover any card for a live preview, open the details for playback controls, or send it straight to the Studio.</p>+ <p data-i18n="animations.every_clip_in_the_three_ws_motion">Every clip in the three.ws motion library: mocap performances, studio presets, and community-authored animations. Hover any card for a live preview, open the details for playback controls, or send it straight to the Studio.</p><div class="ag-hero-actions"><a href="/pose" class="ag-btn ag-btn--primary" data-i18n="animations.open_animation_studio">Open Animation Studio</a><a href="/gallery" class="ag-btn ag-btn--secondary" data-i18n="animations.avatar_gallery">Avatar Gallery</a>@@ -786,6 +802,7 @@<div class="ag-skeleton"></div><div class="ag-skeleton"></div></div>+ <h2 class="ag-sr-only" data-i18n="animations.results_heading">Animation results</h2><div data-role="grid" class="ag-grid" hidden></div><div data-role="empty" class="ag-state" hidden><div class="ag-state-icon">🎬</div>@@ -813,7 +830,7 @@</main><!-- Clip detail modal -->- <div class="ag-modal" data-role="modal" hidden role="dialog" aria-modal="true" aria-labelledby="ag-modal-title">+ <div class="ag-modal" data-role="modal" hidden tabindex="-1" role="dialog" aria-modal="true" aria-labelledby="ag-modal-title"><div class="ag-modal-card"><div class="ag-modal-stage-wrap"><div class="ag-modal-stage" data-role="modal-stage"></div>diff --git a/public/agents/index.html b/public/agents/index.htmlindex 2a1a51ca7..9d07c9947 100644--- a/public/agents/index.html+++ b/public/agents/index.html@@ -83,6 +83,11 @@select.ctrl { background: var(--panel); border: 1px solid var(--line); border-radius: 8px;padding: 9px 12px; font: 14px/1 inherit; color: var(--ink); outline: none; cursor: pointer; }select.ctrl:focus { border-color: color-mix(in srgb, var(--cyan) 50%, var(--line)); }+ /* Both controls set outline:none for the mouse-focus look, which left a+ keyboard user with a 1px border tint as the only cue. Give them the same+ ring the chips and buttons on this page already use. */+ .search-wrap input:focus-visible,+ select.ctrl:focus-visible { outline: 2px solid var(--cyan); outline-offset: 2px; }.count-label { font-size: 13px; color: var(--muted); white-space: nowrap; }/* grid */@@ -201,7 +206,7 @@<svg viewBox="0 0 24 24" fill="none" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>- <input id="ag-search" type="search" placeholder="Search agents…" autocomplete="off" />+ <input id="ag-search" type="search" placeholder="Search agents…" autocomplete="off" data-i18n-attr="placeholder:agents_index.search_placeholder" /></div><label class="sr-only" for="ag-sort" data-i18n="agents_index.sort_label">Sort agents</label><select id="ag-sort" class="ctrl">@@ -212,7 +217,10 @@</div><div id="ag-grid" class="agents-grid" aria-label="Agents" aria-busy="true"></div>- <div id="ag-state" class="state" hidden></div>+ <!-- The empty and error panels are the only feedback a failed or fruitless+ load gives, so announce them: without a live region a screen-reader+ user hears the busy state end and nothing after it. -->+ <div id="ag-state" class="state" role="status" aria-live="polite" hidden></div><div class="load-more-wrap" id="ag-more-wrap" hidden><button type="button" id="ag-more" class="btn btn-ghost" data-i18n="agents_index.load_more">Load more</button></div>@@ -329,12 +337,20 @@</div>`;}- function renderList() {- let items = state.items;- if (state.sort === 'name') {- items = [...items].sort((a, b) => (a.name || '').localeCompare(b.name || ''));+ // `appendFrom` is the index the newest page starts at. In the server's own+ // order that page only has to be appended: rebuilding the whole grid on+ // every "load more" re-decodes every thumbnail already on screen and makes+ // the list flash once a few pages are in. Name sort interleaves the new+ // page into the existing one, so it still rebuilds.+ function renderList(appendFrom = null) {+ if (appendFrom !== null && state.sort === 'newest') {+ grid.insertAdjacentHTML('beforeend', state.items.slice(appendFrom).map(cardHtml).join(''));+ } else {+ const items = state.sort === 'name'+ ? [...state.items].sort((a, b) => (a.name || '').localeCompare(b.name || ''))+ : state.items;+ grid.innerHTML = items.map(cardHtml).join('');}- grid.innerHTML = items.map(cardHtml).join('');grid.setAttribute('aria-busy', 'false');}@@ -378,6 +394,19 @@</div>`;}+ // A page that fails mid-list is a different failure from a page that fails+ // on arrival: the agents already loaded are still good and the cursor still+ // points at the next page, so this offers a resume rather than the reset+ // "Try again" does. Retrying from page one after loading four pages threw+ // away everything the visitor had scrolled through.+ function moreErrorStateHtml(detail) {+ return `<b>Couldn't load more agents</b>The next page didn't arrive (${esc(detail)}). The ${state.items.length} already listed are still here.+ <div class="state-actions">+ <button type="button" class="btn btn-primary" data-act="retry-more">Resume loading</button>+ <button type="button" class="btn btn-ghost" data-act="retry">Start over</button>+ </div>`;+ }+function setBusy(on) {moreBtn.disabled = on;moreBtn.setAttribute('aria-busy', on ? 'true' : 'false');@@ -416,9 +445,10 @@// a future server change can't leak non-agent rows into this view.const items = (data.items || []).filter((it) => it.kind === 'onchain' || it.kind === 'solana');+ const appendFrom = state.items.length;state.items.push(...items);state.cursor = data.nextCursor || null;- renderList();+ renderList(reset ? null : appendFrom);const more = !!data.nextCursor;countEl.textContent = state.items.length > 0@@ -426,17 +456,23 @@: '';moreWrap.hidden = !more;+ // Clearing the panel is part of the success path: a resumed "load+ // more" used to leave the error it recovered from sitting under the+ // freshly loaded results.if (!state.items.length) showState(emptyStateHtml());+ else stateEl.hidden = true;} catch (err) {if (req !== state.req) return;+ const detail = err?.message || 'network error';if (reset) {grid.innerHTML = '';grid.setAttribute('aria-busy', 'false');- showState(errorStateHtml(err?.message || 'network error'));+ showState(errorStateHtml(detail));} else {- // A failed "load more" keeps the results already on screen and- // offers the retry inline instead of wiping the page.- showState(errorStateHtml(err?.message || 'network error'));+ // A failed "load more" keeps every page already on screen and keeps+ // state.cursor, so the panel's resume picks up the interrupted page+ // instead of restarting the list.+ showState(moreErrorStateHtml(detail));}moreWrap.hidden = true;} finally {@@ -457,14 +493,21 @@state.q = '';syncUrl();}- load(true);+ // "retry-more" resumes the interrupted page off the surviving cursor;+ // every other action starts the list over.+ load(act !== 'retry-more');});let _t;searchEl.addEventListener('input', (e) => {clearTimeout(_t);_t = setTimeout(() => {- state.q = e.target.value.trim();+ const next = e.target.value.trim();+ // Trailing whitespace and an edit that lands back on the same term+ // both settle here; refetching the identical query would rebuild the+ // grid and throw away every page past the first for nothing.+ if (next === state.q) return;+ state.q = next;syncUrl();load(true);}, 320);diff --git a/public/settings/index.html b/public/settings/index.htmlindex 5ce5039dc..5f4bde6bf 100644--- a/public/settings/index.html+++ b/public/settings/index.html@@ -295,6 +295,24 @@outline: 2px solid #6aa9ff; outline-offset: 2px;}.btn[disabled] { opacity: 0.55; cursor: not-allowed; filter: none; }+ .token-form {+ margin-top: 10px; padding: 14px 16px;+ background: var(--panel); border: 1px solid var(--border); border-radius: 10px;+ animation: tokenFormIn 160ms ease-out;+ }+ @keyframes tokenFormIn { from { opacity: 0; transform: translateY(-4px); } to { opacity: 1; transform: none; } }+ @media (prefers-reduced-motion: reduce) { .token-form { animation: none; } }+ .token-form label {+ display: block; font-size: 12px; font-weight: 600; color: #aaa;+ text-transform: uppercase; letter-spacing: 0.06em; margin-bottom: 6px;+ }+ .token-form input { width: 100%; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; }+ .token-form .token-actions { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 10px; }+ .token-form .token-note { font-size: 12px; color: #888; margin: 10px 0 0; line-height: 1.55; }+ .token-form code {+ background: #1c1c1c; border: 1px solid var(--border); border-radius: 4px;+ padding: 1px 5px; font-size: 11px; color: #ccc;+ }.agent-seed-area {margin-top: 16px; padding: 14px 16px;background: var(--panel); border: 1px solid var(--border); border-radius: 10px;@@ -558,6 +576,7 @@<span class="muted" style="font-size:13px" data-i18n="settings_index.loading">Loading…</span></div></div>+ <div id="github-token-form" style="display:none"></div><span class="inline-msg" id="github-msg" style="display:none;margin-top:10px"></span><div class="social-card" id="x-card" style="margin-top:14px">@@ -865,7 +884,7 @@async function disconnectGitHub() {const btn = document.getElementById('github-disconnect-btn');const msg = document.getElementById('github-msg');- if (!confirm('Disconnect GitHub? Every memory your agents learned from GitHub is deleted, and the access is revoked on GitHub.')) return;+ if (!confirm('Disconnect GitHub? Every memory your agents learned from GitHub is deleted, and the stored access is destroyed.')) return;if (btn) {btn.disabled = true;btn.textContent = 'Disconnecting…';@@ -873,9 +892,15 @@try {const data = await apiJson('/api/auth/github/disconnect', { method: 'POST' });const n = data?.memories_deleted ?? 0;- showMsg(msg, 'ok', n+ const deleted = n? `GitHub disconnected. ${n} seeded ${n === 1 ? 'memory' : 'memories'} deleted.`- : 'GitHub disconnected.');+ : 'GitHub disconnected.';+ // A pasted token is gone from our side but still exists on GitHub+ // until its owner deletes it, so say that instead of implying we+ // revoked something we cannot.+ showMsg(msg, 'ok', data?.connect_method === 'token'+ ? `${deleted} Delete the token on GitHub to finish revoking it.`+ : deleted);} catch (e) {showMsg(msg, 'err', e.data?.error_description || 'Could not disconnect GitHub.');if (btn) {@@ -887,6 +912,76 @@loadGitHubStatus();}+ function hideTokenForm() {+ const host = document.getElementById('github-token-form');+ if (host) {+ host.style.display = 'none';+ host.innerHTML = '';+ }+ }++ // The token path. The user mints the token on GitHub with the scopes we+ // ask for, so consent happens on GitHub's own screen exactly as it does+ // for OAuth; this form only carries it across.+ function renderTokenForm(tokenConnect, { open } = {}) {+ const host = document.getElementById('github-token-form');+ const toggle = document.getElementById('github-token-toggle');+ if (!host || !tokenConnect?.available) return;++ const createUrl = tokenConnect.create_url || 'https://github.com/settings/tokens/new';+ const scopes = (tokenConnect.recommended_scopes || ['read:user']).map((s) => `<code>${escHtml(s)}</code>`).join(' ');++ host.innerHTML = `+ <div class="token-form">+ <label for="inp-github-token">GitHub personal access token</label>+ <input type="password" id="inp-github-token" autocomplete="off" autocapitalize="off" spellcheck="false"+ placeholder="ghp_…" aria-describedby="github-token-note" />+ <div class="token-actions">+ <button class="btn" id="github-token-submit" style="font-size:12px;padding:6px 16px">Connect</button>+ <a class="btn sec" href="${escHtml(createUrl)}" target="_blank" rel="noopener noreferrer" style="font-size:12px;padding:6px 16px;text-decoration:none">Create one on GitHub</a>+ <a class="btn sec" href="/docs/github-memory-seeding" style="font-size:12px;padding:6px 16px;text-decoration:none">How this works</a>+ </div>+ <p class="token-note" id="github-token-note">Tick only ${scopes} when you create it. The token is encrypted before it is stored, is used only to read the public profile, repositories and READMEs you tick, and is deleted the moment you disconnect. A token carrying more access than that is refused.</p>+ </div>`;+ host.style.display = open ? 'block' : 'none';+ if (toggle) toggle.setAttribute('aria-expanded', open ? 'true' : 'false');++ document.getElementById('github-token-submit')?.addEventListener('click', submitGitHubToken);+ document.getElementById('inp-github-token')?.addEventListener('keydown', (e) => {+ if (e.key === 'Enter') { e.preventDefault(); submitGitHubToken(); }+ });+ if (open) document.getElementById('inp-github-token')?.focus();+ }++ async function submitGitHubToken() {+ const input = document.getElementById('inp-github-token');+ const btn = document.getElementById('github-token-submit');+ const msg = document.getElementById('github-msg');+ const token = (input?.value || '').trim();+ if (!token) {+ showMsg(msg, 'err', 'Paste your GitHub token first.');+ input?.focus();+ return;+ }+ btn.disabled = true;+ btn.textContent = 'Connecting…';+ try {+ const data = await apiJson('/api/auth/github/token', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ token }),+ });+ // The token never needs to sit in the DOM after a successful post.+ if (input) input.value = '';+ showMsg(msg, 'ok', `GitHub connected as @${data.username}.`);+ loadGitHubStatus();+ } catch (e) {+ showMsg(msg, 'err', e.data?.error_description || 'Could not connect that token.');+ btn.disabled = false;+ btn.textContent = 'Connect';+ }+ }+async function loadGitHubStatus() {const statusEl = document.getElementById('github-status-text');const actionsEl = document.getElementById('github-actions');@@ -899,24 +994,38 @@const seeded = data.seeded_fact_count? ` · ${data.seeded_fact_count} seeded ${data.seeded_fact_count === 1 ? 'memory' : 'memories'}`: '';- statusEl.textContent = `@${data.username} · connected ${when}${seeded}`;+ const via = data.connect_method === 'token' ? ' · via personal access token' : '';+ statusEl.textContent = `@${data.username} · connected ${when}${via}${seeded}`;actionsEl.innerHTML = '<span class="tag green">Connected</span><button class="btn sec" id="github-disconnect-btn" style="font-size:12px;padding:5px 14px">Disconnect</button>';document.getElementById('github-disconnect-btn')?.addEventListener('click', disconnectGitHub);+ hideTokenForm();if (seedArea) {seedArea.style.display = 'block';mountSeedPanel();}- } else if (data.configured === false) {- // No OAuth app on this deployment. Say so plainly rather than- // offering a button whose only outcome is a 501 error page.- statusEl.textContent = 'GitHub connect is unavailable on this deployment';- actionsEl.innerHTML = '<span class="tag">Unavailable</span><a href="/docs/github-memory-seeding" class="btn sec" style="font-size:12px;padding:5px 14px;text-decoration:none">How this works</a>';- if (seedArea) seedArea.style.display = 'none';} else {- statusEl.textContent = 'Not connected';+ // Two ways in. OAuth is the one-click path, but it only exists+ // where an operator registered a GitHub OAuth app; the token path+ // needs nothing provisioned, so an unconfigured deployment offers+ // it up front instead of a dead "Unavailable" tag.+ const oauth = data.configured !== false;+ statusEl.textContent = oauth+ ? 'Not connected'+ : 'Not connected. Connect with a personal access token.';const agentId = _urlP.get('agent_id') || '';const connectUrl = `/api/auth/github/connect${agentId ? `?agent_id=${encodeURIComponent(agentId)}` : ''}`;- actionsEl.innerHTML = `<a href="${connectUrl}" class="btn" style="font-size:12px;padding:5px 14px;text-decoration:none">Connect GitHub</a>`;+ actionsEl.innerHTML =+ (oauth ? `<a href="${connectUrl}" class="btn" style="font-size:12px;padding:5px 14px;text-decoration:none">Connect GitHub</a>` : '')+ + `<button class="btn${oauth ? ' sec' : ''}" id="github-token-toggle" style="font-size:12px;padding:5px 14px" aria-expanded="${oauth ? 'false' : 'true'}" aria-controls="github-token-form">${oauth ? 'Use a token' : 'Connect with a token'}</button>`;+ renderTokenForm(data.token_connect, { open: !oauth });+ document.getElementById('github-token-toggle')?.addEventListener('click', (e) => {+ e.preventDefault();+ const host = document.getElementById('github-token-form');+ const nowOpen = host.style.display === 'none';+ host.style.display = nowOpen ? 'block' : 'none';+ e.currentTarget.setAttribute('aria-expanded', nowOpen ? 'true' : 'false');+ if (nowOpen) document.getElementById('inp-github-token')?.focus();+ });if (seedArea) seedArea.style.display = 'none';}} catch {diff --git a/src/agent-identity.js b/src/agent-identity.jsindex 292e1b042..aa88c4797 100644--- a/src/agent-identity.js+++ b/src/agent-identity.js@@ -49,6 +49,12 @@ export class AgentIdentity {this._loadPromise = null; // re-entrancy guardthis.memory = null;+ // An id the CALLER named explicitly (e.g. /agent-studio?id=…, an agent+ // profile route). It must survive the localStorage seeding below: loading a+ // different agent than the one asked for is never right, and in an owner+ // console it silently points the editor at the wrong record.+ this._requestedId = agentId || null;+// Pre-seed agentId from arg or storage so callers can use it synchronouslythis._agentId = agentId || this._readStoredId();@@ -261,8 +267,15 @@ export class AgentIdentity {this._backendConfirmed = false;this._owned = false;- // 1. Try localStorage first (instant) — backendSync disabled until confirmed- const local = this._readLocal();+ // 1. Try localStorage first (instant), backendSync disabled until confirmed.+ // The stored slot holds ONE agent (whichever was loaded last), so when the+ // caller named a specific id we may only use it if it is that same agent.+ // Adopting it regardless overwrote `_agentId` with the stored id, so the+ // backend probe below fetched the stored agent and the requested one was+ // never loaded: /agent-studio?id=<someone else's agent> silently rendered+ // the caller's OWN agent in a full editor under the other agent's URL.+ const stored = this._readLocal();+ const local = stored && (!this._requestedId || stored.id === this._requestedId) ? stored : null;if (local) {this._record = local;this._agentId = local.id;@@ -276,7 +289,12 @@ export class AgentIdentity {try {const agentId = this._agentId;const storedConfirmed = this._record?.backendConfirmed;- const url = (agentId && storedConfirmed) ? `/api/agents/${agentId}` : '/api/agents/me';+ // A caller-named id is always probed directly: `/api/agents/:id` is a+ // public read that also reports `is_owner`, which is what lets an owner+ // console tell "your agent" from "someone else's".+ const url = this._requestedId+ ? `/api/agents/${this._requestedId}`+ : (agentId && storedConfirmed) ? `/api/agents/${agentId}` : '/api/agents/me';const resp = await apiFetch(url, ANON);if (resp.ok) {@@ -292,7 +310,7 @@ export class AgentIdentity {// EXISTS, not that we own it. Owner-only fields (is_owner) tell// us whether the signed-in session may write to its action log.this._owned = agent.is_owner === true;- this._persist();+ this._persistOwnSlot();if (!this.memory) {this.memory = new AgentMemory(this._record.id, { backendSync: true, embedFn: _makeEmbedFn(this._record.id) });} else {@@ -311,7 +329,7 @@ export class AgentIdentity {this._record = _makeDefault(this._agentId);this._agentId = this._record.id;this._loaded = true;- this._persist();+ this._persistOwnSlot();this.memory = new AgentMemory(this._agentId, { backendSync: false, embedFn: _makeEmbedFn(this._agentId) });}} catch {@@ -320,7 +338,7 @@ export class AgentIdentity {this._record = _makeDefault(this._agentId);this._agentId = this._record.id;this._loaded = true;- this._persist();+ this._persistOwnSlot();this.memory = new AgentMemory(this._agentId, { backendSync: false, embedFn: _makeEmbedFn(this._agentId) });}}@@ -348,6 +366,18 @@ export class AgentIdentity {localStorage.setItem(STORAGE_KEY, JSON.stringify(this._record));} catch {}}++ /**+ * Persist only into this browser's single "current agent" slot, and only when+ * the record belongs there. Reading someone else's agent by explicit id (an+ * agent profile, a shared /agent-studio?id=… link) must not evict the visitor's+ * own identity from that slot: every surface that loads without an id reads it+ * back, so a single foreign read would follow them across the whole platform.+ */+ _persistOwnSlot() {+ if (this._requestedId && !this._owned) return;+ this._persist();+ }}// ── Helpers ──────────────────────────────────────────────────────────────────diff --git a/src/agent-trade.js b/src/agent-trade.jsindex d13ffd572..7e72c1187 100644--- a/src/agent-trade.js+++ b/src/agent-trade.js@@ -438,6 +438,12 @@ function openConfigOverlay() {requestAnimationFrame(() => els.cfgClose?.focus());}+// The overlay opens by itself on an unconfigured deployment, so the element that+// "had focus" at that moment is <body>. Restoring to it drops focus out of the+// document entirely and Tab restarts from the top, so a candidate only counts+// when it is genuinely focusable.+const FOCUSABLE = 'a[href], button:not([disabled]), select:not([disabled]), input:not([disabled]), [tabindex]:not([tabindex="-1"])';+function closeConfigOverlay() {if (els.notConfigured.classList.contains('hidden')) return;els.notConfigured.classList.add('hidden');@@ -450,7 +456,7 @@ function closeConfigOverlay() {els.centralCard.querySelector('[data-action="show-walkthrough"]'),els.startBtn,els.topicSelect,- ].filter((el) => el && document.contains(el) && !el.disabled);+ ].filter((el) => el && document.contains(el) && !el.disabled && el.matches?.(FOCUSABLE));candidates[0]?.focus?.();}@@ -477,20 +483,25 @@ els.notConfigured.addEventListener('keydown', (e) => {els.cfgClose.addEventListener('click', closeConfigOverlay);// Dismissing the overlay used to strand the walkthrough with no way back. The-// idle card carries a control that re-opens it.+// idle card carries a control that re-opens it, and every failure card carries+// the one control that can clear it.els.centralCard.addEventListener('click', (e) => {- if (e.target.closest('[data-action="show-walkthrough"]')) openConfigOverlay();+ if (e.target.closest('[data-action="show-walkthrough"]')) { openConfigOverlay(); return; }+ if (e.target.closest('[data-action="retry-preflight"]')) { checkConfig(); return; }+ if (e.target.closest('[data-action="run-again"]')) startDemo();});// ── Bubble helpers ──────────────────────────────────────────────────────────-function showBubble(side, text) {+function showBubble(side, text, { pending = false } = {}) {const el = side === 'buyer' ? els.buyerBubble : els.sellerBubble;el.textContent = text;+ el.classList.toggle('pending', pending);el.classList.remove('hidden');}function hideBubble(side) {const el = side === 'buyer' ? els.buyerBubble : els.sellerBubble;el.classList.add('hidden');+ el.classList.remove('pending');}// ── Central card ────────────────────────────────────────────────────────────@@ -514,6 +525,32 @@ function showReadyCard(cfg) {`);}+// Pre-flight in flight. The wallets, price and network come off Solana, which+// takes as long as the RPC takes, so the card shows the shape of the answer+// rather than leaving the stage empty and the run button in an unknown state.+function showCheckingCard() {+ showCard(`+ <div class="c-badge c-badge-idle">x402 · oracle-market-analysis</div>+ <div class="c-label">Checking the demo wallets</div>+ <div class="c-skel c-skel-price"></div>+ <div class="c-skel c-skel-row"></div>+ <div class="c-skel c-skel-row short"></div>+ <div class="c-content">Reading the buyer and seller balances from Solana before the trade can start.</div>+ `);+}++// Any failure that leaves the user with nothing to look at. The action is the+// point: a red toast fades after eight seconds and then the page reads as a+// half-finished trade with no explanation.+function showErrorCard({ badge, label, message, action }) {+ showCard(`+ <div class="c-badge c-badge-402">${escHtml(badge)}</div>+ <div class="c-label">${escHtml(label)}</div>+ <div class="c-content">${escHtml(message)}</div>+ <button class="cfg-close" type="button" data-action="${escHtml(action.id)}">${escHtml(action.label)}</button>+ `);+}+// Pre-run state when no wallets are configured: says why the button is off and// keeps the walkthrough one click away.function showUnconfiguredCard() {@@ -527,6 +564,15 @@ function showUnconfiguredCard() {// ── Step log ─────────────────────────────────────────────────────────────────const STEP_NAMES = ['init', 'request', 'challenged', 'paying', 'confirmed', 'delivering', 'delivered'];+// The server codes that deserve their own headline on the failure card; anything+// else falls back to the generic one.+const ERROR_BADGES = {+ insufficient_funds: 'Buyer wallet is short',+ daily_budget_exhausted: 'Daily spend limit reached',+ analysis_unavailable: 'No analysis model available',+ analysis_failed: 'Analysis failed after payment',+ send_failed: 'Payment failed',+};const chips = {};function buildStepLog() {@@ -580,6 +626,22 @@ function setRunning(on) {if (!on) stage?.setAutoRotate(true);}+// Every way a run can end badly funnels through here, so a stream that simply+// drops leaves the same honest wreckage as a server-sent `error`: the step that+// was in flight is marked failed instead of pulsing forever, the stale bubble+// goes, and the centre of the screen says what happened and how to retry.+function failRun(message, { badge = 'Trade stopped', label = 'x402 · oracle-market-analysis' } = {}) {+ clearPendingTimers();+ STEP_NAMES.forEach((s) => { if (chips[s]?.classList.contains('active')) setChip(s, 'error'); });+ hideBubble('buyer');+ hideBubble('seller');+ stage?.stopBeam();+ showToast(message);+ announce(`Demo stopped: ${message}`);+ setRunning(false);+ showErrorCard({ badge, label, message, action: { id: 'run-again', label: 'Run it again' } });+}+// Deferred touches (a chip settling to `done`, a bubble appearing a beat later)// belong to the step that scheduled them. When the next event lands the step is// over, so its pending timers are dropped: a slow proxy that delivers two events@@ -652,8 +714,11 @@ function handleEvent(ev) {setChip('challenged', 'done');setChip('paying', 'active');hideBubble('seller');+ // The centre stays clear so the payment beam is the thing you watch; the+ // bubble carries the pending bar, because a real transfer can take tens of+ // seconds and static text is indistinguishable from a stalled page.hideCard();- showBubble('buyer', `Sending ${ev.sol} SOL on-chain…`);+ showBubble('buyer', `Sending ${ev.sol} SOL on-chain…`, { pending: true });stage?.startBeam();// Fly camera to watch the beam from a low anglestage?.flyCamera(vec3(0, 1.6, 7.2), vec3(0, 0.9, 0), 950);@@ -692,7 +757,7 @@ function handleEvent(ev) {// `delivered` card first and then this timeout wiped it off the screen.hideBubble('seller');hideCard();- after(200, () => showBubble('seller', `Analyzing with ${ev.model}…`));+ after(200, () => showBubble('seller', `Analyzing with ${ev.model}…`, { pending: true }));// Fly back to a wide viewstage?.flyCamera(vec3(0, 3.0, 9.5), vec3(0, 1.2, 0), 1100);break;@@ -719,19 +784,24 @@ function handleEvent(ev) {}case 'error': {- STEP_NAMES.forEach((s) => { if (chips[s]?.classList.contains('active')) setChip(s, 'error'); });const msg = ev.message || 'Something went wrong';- showToast(msg);- announce(`Demo stopped: ${msg}`);- setRunning(false);- stage?.stopBeam();// A deployment with no wallets can never run: say so where the answer is,- // rather than leaving a toast the user has to interpret.+ // rather than leaving a toast the user has to interpret. A "run it again"+ // button would be a lie here, so this branch keeps the walkthrough card.if (ev.code === 'not_configured') {+ STEP_NAMES.forEach((s) => { if (chips[s]?.classList.contains('active')) setChip(s, 'error'); });+ hideBubble('buyer');+ hideBubble('seller');+ stage?.stopBeam();+ showToast(msg);+ announce(`Demo stopped: ${msg}`);+ setRunning(false);els.startBtn.disabled = true;showUnconfiguredCard();openConfigOverlay();+ break;}+ failRun(msg, { badge: ERROR_BADGES[ev.code] || 'Trade stopped' });break;}}@@ -770,12 +840,11 @@ function startDemo() {// Only a genuinely broken stream reaches here: a completed run closes the// EventSource in onmessage above.if (currentEs !== es) return;- showToast('The live stream dropped before the trade finished. Check your connection, then run it again.');- announce('The live stream dropped before the trade finished.');- setRunning(false);- stage?.stopBeam();es.close();currentEs = null;+ failRun('The live stream dropped before the trade finished. Check your connection, then run it again.', {+ badge: 'Stream dropped',+ });};}@@ -783,6 +852,10 @@ els.startBtn.addEventListener('click', startDemo);// ── Config pre-flight ─────────────────────────────────────────────────────────async function checkConfig() {+ // Nothing is known yet, so nothing is offered yet: the button stays out of+ // reach until the answer lands, and the skeleton says the answer is coming.+ els.startBtn.disabled = true;+ showCheckingCard();try {const r = await fetch('/api/agent-trade/demo?check=1');if (!r.ok) throw new Error(`pre-flight ${r.status}`);@@ -796,11 +869,20 @@ async function checkConfig() {if (d.buyer?.address) els.buyerAddr.textContent = fmt(d.buyer.address);if (d.seller?.address) els.sellerAddr.textContent = fmt(d.seller.address);if (d.network) els.networkName.textContent = d.network;+ els.startBtn.disabled = false;showReadyCard(d);} catch {// The pre-flight is unreachable. Leave the button live (the run itself- // reports the real failure) but say why the wallets are blank.+ // reports the real failure) and put the retry where the user is looking,+ // because the toast is gone eight seconds later.+ els.startBtn.disabled = false;showToast('Could not reach the demo API for a status check. Running the demo will report what failed.');+ showErrorCard({+ badge: 'Status check failed',+ label: 'x402 · oracle-market-analysis',+ message: 'The demo API did not answer the wallet status check, so the balances above are unknown. Retry the check, or run the demo anyway and it will report what failed.',+ action: { id: 'retry-preflight', label: 'Retry the status check' },+ });}}diff --git a/src/agent-wallet-hub/tabs/balance.js b/src/agent-wallet-hub/tabs/balance.jsindex 6619c8554..fedfa3706 100644--- a/src/agent-wallet-hub/tabs/balance.js+++ b/src/agent-wallet-hub/tabs/balance.js@@ -86,6 +86,12 @@ registerWalletTab({refreshing: false,};+ // GET /api/agents/:id/solana/activity is owner-only (401 anonymous, 403 for+ // another owner). A visitor requesting it gets no data, one console error+ // per load, and a Retry button that can never succeed, so the visitor view+ // says the feed is private instead of pretending the request failed.+ const canReadActivity = ctx.isOwner;+function render() {if (destroyed) return;if (!state.loaded) {@@ -165,6 +171,12 @@ registerWalletTab({}function renderActivity(net) {+ if (!canReadActivity) {+ const explorer = state.address+ ? ` Every transaction is still public on the <a class="awh-act-sig" href="${escapeHtml(explorerAddressUrl(state.address, net))}" target="_blank" rel="noopener">block explorer</a>.`+ : '';+ return `<div class="awh-empty">This wallet's activity feed is private to its owner.${explorer}</div>`;+ }if (state.activityError) {return `<div class="awh-empty">Could not load activity. <button class="awh-btn awh-bal-mini" type="button" data-act="retry-activity">Retry</button></div>`;}@@ -237,7 +249,7 @@ registerWalletTab({async function loadActivity() {const net = ctx.getNetwork();- if (!state.address) {+ if (!canReadActivity || !state.address) {state.activity = [];state.activityLoaded = true;state.activityError = null;diff --git a/src/agent-wallet-hub/tabs/deposit.js b/src/agent-wallet-hub/tabs/deposit.jsindex 0fe5263df..481ec09d2 100644--- a/src/agent-wallet-hub/tabs/deposit.js+++ b/src/agent-wallet-hub/tabs/deposit.js@@ -456,7 +456,10 @@ registerWalletTab({async function loadActivity() {const net = ctx.getNetwork();- if (!state.address) return;+ // The activity feed is owner-only server-side; a visitor funding someone+ // else's agent would only earn a 401 in the console. The deposit QR,+ // address, and live "received" confirmation all work without it.+ if (!ctx.isOwner || !state.address) return;try {const data = await fetchAgentSolanaActivity(ctx.agentId, net, 8);state.activity = data?.signatures || [];diff --git a/src/agent-wallet.js b/src/agent-wallet.jsindex 2780ccc08..b3f001e3b 100644--- a/src/agent-wallet.js+++ b/src/agent-wallet.js@@ -28,6 +28,24 @@ function resolveAgentId() {const root = document.getElementById('awh-root');+/**+ * Write a dynamic page title (an agent's name, the picker heading) and hold it.+ *+ * The document's <title> carries a data-i18n key, so the i18n runtime's catalog+ * pass reverts it to the declared "Agent Wallet · three.ws" whenever /api/locale+ * resolves after this page has already rendered, a race the title lost roughly+ * one load in three. `data-i18n-owned="1"` is that runtime's documented opt-out+ * for an element whose content is live data rather than translatable copy.+ *+ * States that show the page's declared default never call this: leaving the+ * title unclaimed is what lets a non-English visitor keep a localized one.+ */+const titleEl = document.querySelector('title');+function setPageTitle(text) {+ document.title = text;+ titleEl?.setAttribute('data-i18n-owned', '1');+}+function escapeHtml(s) {return String(s ?? '').replace(/[&<>"']/g,@@ -103,7 +121,7 @@ function renderPicker(agents) {<a class="awh-page-btn" href="/create-agent">Create an agent</a></div></section>`;- document.title = 'Your agent wallets · three.ws';+ setPageTitle('Your agent wallets · three.ws');}/** Fetch one agent by id. Returns { agent } or { state } for a designed stop. */@@ -147,7 +165,7 @@ async function fetchOwnAgents() {}function mountHub(agent) {- document.title = `${agent.name || 'Agent'} wallet · three.ws`;+ setPageTitle(`${agent.name || 'Agent'} wallet · three.ws`);mountAgentWalletHub({ mount: root, agent });}@@ -164,7 +182,6 @@ async function loadOwnWallets() {body: 'We could not reach the agent service. This is usually temporary, so check your connection and try again.',retry: true,});- document.title = 'Agent Wallet · three.ws';return;}@@ -177,7 +194,6 @@ async function loadOwnWallets() {{ href: '/register', label: 'Create account' },],});- document.title = 'Agent Wallet · three.ws';return;}@@ -188,7 +204,6 @@ async function loadOwnWallets() {body: 'Every agent you create gets a self-custodied Solana wallet it can fund, trade, and pay from. Create your first agent to open its wallet.',actions: [{ href: '/create-agent', label: 'Create an agent', primary: true }],});- document.title = 'Agent Wallet · three.ws';return;}@@ -211,7 +226,6 @@ async function loadNamedWallet(agentId) {{ href: '/agents', label: 'Browse agents' },],});- document.title = 'Agent Wallet · three.ws';return;}@@ -226,7 +240,6 @@ async function loadNamedWallet(agentId) {body: 'We could not reach the agent service. This is usually temporary, so check your connection and try again.',retry: true,});- document.title = 'Agent Wallet · three.ws';return;}@@ -236,7 +249,7 @@ async function loadNamedWallet(agentId) {body: 'This agent does not exist or has been removed. It may have been deleted by its owner.',actions: [{ href: '/agents', label: 'Browse agents', primary: true }],});- document.title = 'Agent not found · three.ws';+ setPageTitle('Agent not found · three.ws');return;}diff --git a/src/agents-live.js b/src/agents-live.jsindex 742385da0..8c572737d 100644--- a/src/agents-live.js+++ b/src/agents-live.js@@ -12,6 +12,13 @@// caster pool can spin a real browser up for agents people are actually looking// at, and tear it down when they leave. That keeps live pixels available for any// agent on demand without paying for an idle browser per agent.+//+// The SSE listeners are POOLED, not one-per-card. A browser caps concurrent+// connections per origin (6 on HTTP/1.1; the server's stream limit on HTTP/2),+// and an SSE stream is long-lived, so opening one per card meant the roster's+// first handful connected and every card after them sat on "Connecting" forever.+// Streams are now attached as a card nears the viewport and released once it is+// well past it, bounded by a pool sized from the origin's real transport.import { parsePnlDelta, formatSol, formatUsd } from './shared/trade-pnl.js';import { mountAgentReactions } from './agent-reactions.js';@@ -24,7 +31,7 @@ import { sanitizeMmEvent, fmtPriceSol } from './shared/mm-render.js';import { parseForgeFrame } from './shared/forge-frames.js';import { createArena } from './agents-live-arena.js';import { createShowrunner } from './showrunner.js';-import { noteSession } from './api.js';+import { apiFetch, noteSession } from './api.js';// Subtle accent for a card showing a live Coin World Tour walkthrough.(() => {@@ -90,6 +97,37 @@ const STATUS_GRACE_POLLS = 3; // keep polling this many ticks to cover theconst _inView = new Set();let _observer = null;+// ── SSE stream pool ──────────────────────────────────────────────────────────+// A second, wider observer band: cards within STREAM_MARGIN of the viewport are+// "near view" and eligible for a stream, so a card is already tailing by the time+// it scrolls into sight. `_streamed` is insertion-ordered and used as an LRU:+// re-touching an id moves it to the end, and eviction takes from the front.+const STREAM_MARGIN = '400px 0px';+const _nearView = new Set();+const _streamed = new Set();+let _streamObserver = null;++// How many SSE listeners the origin can actually carry at once. Over HTTP/1.1 a+// browser allows 6 sockets per origin and an SSE stream never releases its one,+// so a pool anywhere near that ceiling starves the page's own fetches (roster,+// balances, watch intent). Multiplexed transports have no such per-request cost.+// Read from the real navigation entry rather than guessed: prod is served over+// h2 behind the load balancer, the vite dev server is http/1.1.+export function streamPoolSize(nextHopProtocol) {+ const p = String(nextHopProtocol || '').toLowerCase();+ if (p === 'h2' || p === 'h3' || p.startsWith('h3-') || p === 'http/2' || p === 'http/3') return 12;+ return 4;+}++function detectPoolSize() {+ try {+ const nav = performance.getEntriesByType('navigation')[0];+ return streamPoolSize(nav?.nextHopProtocol);+ } catch { return 4; }+}++const MAX_STREAMS = detectPoolSize();+// Showrunner Director — programs the wall like a live TV channel: a rotating// spotlight stage above the grid + a float-the-active-agents-up grid order.// Declared here (not in the boot section) so the stream callbacks wired up@@ -236,7 +274,7 @@ function buildCard(agent) {</div><div class="al-card-live-badge"><div class="al-card-live-dot idle" data-dot></div>- <span data-status>Connecting</span>+ <span data-status>Idle</span></div><div class="al-card-floor" data-mm hidden title="Market-maker floor under defense"><span class="al-floor-anchor">⚓</span>@@ -253,7 +291,7 @@ function buildCard(agent) {: `<div class="al-card-avatar" style="background:rgba(255,255,255,0.06)"></div>`}<div class="al-card-meta"><div class="al-card-name">${esc(name)}</div>- <div class="al-card-action" data-action>Connecting…</div>+ <div class="al-card-action" data-action>Standing by</div><div class="al-card-submeta"><span class="al-card-age" data-age hidden></span><span class="al-card-pnl" data-pnl hidden></span>@@ -380,20 +418,39 @@ function paintActivity(state) {ctx.textBaseline = 'middle';ctx.fillText(`${(name || 'Agent').slice(0, 28)} · activity`, 28, 15);- // Empty → a designed standby card, not a blank void.+ // Empty → a designed standby card, not a blank void. Three honest variants:+ // the stream is being opened, the agent has a real history we have not pulled+ // yet (pooled out, or the log is still in flight), or it genuinely never acted.if (!entries || !entries.length) {+ const acted = state.actionCount > 0;+ const ago = fmtAgo(state.lastActionAt);+ let head, l1, l2;+ if (state.attaching) {+ head = 'Opening the tail';+ l1 = acted ? `${state.actionCount.toLocaleString('en-US')} actions recorded` : 'Reading this agent\'s activity';+ l2 = ago ? `last active ${ago}` : '';+ } else if (acted) {+ head = 'Standing by';+ l1 = `${state.actionCount.toLocaleString('en-US')} actions recorded`;+ l2 = ago ? `last active ${ago} · scroll here to tail it live` : 'scroll here to tail it live';+ } else {+ head = 'Standing by';+ l1 = 'No actions yet. This agent will narrate';+ l2 = 'here the moment it acts.';+ }ctx.font = '500 12px "Courier New", monospace';ctx.fillStyle = 'rgba(255,255,255,0.32)';- ctx.fillText('Standing by', 16, 60);+ ctx.fillText(head, 16, 60);+ const headW = ctx.measureText(head).width;ctx.font = '400 11px "Courier New", monospace';ctx.fillStyle = 'rgba(255,255,255,0.18)';- ctx.fillText('No actions yet — this agent will narrate', 16, 84);- ctx.fillText('here the moment it acts.', 16, 102);+ if (l1) ctx.fillText(l1, 16, 84);+ if (l2) ctx.fillText(l2, 16, 102);if (!REDUCED_MOTION && Math.sin(t * 4) > 0) {ctx.fillStyle = 'rgba(255,255,255,0.22)';- ctx.fillRect(16 + ctx.measureText('Standing by').width + 4, 53, 7, 13);+ ctx.fillRect(16 + headW + 4, 53, 7, 13);}- if (state.action) state.action.textContent = 'Standing by';+ if (state.action) state.action.textContent = state.attaching ? 'Opening the tail…' : 'Standing by';return;}@@ -559,8 +616,12 @@ function attachStream(state) {const canvas = card.querySelector('canvas');const ctx = canvas.getContext('2d');+ statusEl.textContent = 'Connecting';+ state.attaching = true;+function setLive(live) {state.live = live;+ state.attaching = false;dot.classList.toggle('idle', !live);if (live) {statusEl.textContent = 'Live';@@ -808,6 +869,81 @@ function getObserver() {return _observer;}+// ── pooled stream lifecycle ──────────────────────────────────────────────────+// A card gets its SSE listener when it nears the viewport and gives it back once+// it is well past, so the pool always covers what a viewer can see, and a wall+// of 2,000 agents costs the same handful of connections as a wall of 12.++// Move an id to the LRU tail (a Set re-insert after delete reorders it).+function touchStream(id) {+ if (_streamed.delete(id)) _streamed.add(id);+}++// Give a stream back. Keeps the card's loaded entries so scrolling back shows its+// history instantly, and parks the badge on the honest resting label.+function releaseStream(state) {+ if (!_streamed.delete(state.agentId)) return;+ try { state.es?.close(); } catch { /* already gone */ }+ state.es = null;+ state.attaching = false;+ state.reconnecting = false;+ clearTimeout(state.reconnectLabelTimer);+ stopStatusPolling(state);+ hideWarming(state);+ state.lastFrameAt = 0;+ state.live = false;+ state.reactions?.setConnected(false);+ const statusEl = state.card.querySelector('[data-status]');+ if (statusEl) { statusEl.textContent = state.entries?.length ? 'Active' : 'Idle'; statusEl.title = ''; }+ const dot = state.card.querySelector('[data-dot]');+ dot?.classList.add('idle');+ dot?.classList.remove('thin');+ renderAge(state);+}++// Free slots by dropping the least-recently-needed streams. Never evicts the+// spotlit card or anything actually on screen, those are what the viewer is+// looking at; the ones merely inside the pre-warm band go first.+function evictStreams() {+ if (_streamed.size <= MAX_STREAMS) return;+ for (const pass of [0, 1]) {+ for (const id of [..._streamed]) {+ if (_streamed.size <= MAX_STREAMS) return;+ if (id === _spotAgentId) continue;+ if (pass === 0 && _inView.has(id)) continue;+ const s = _cards.get(id);+ if (s) releaseStream(s); else _streamed.delete(id);+ }+ }+}++function ensureStream(state) {+ if (state.es) { touchStream(state.agentId); return; }+ _streamed.add(state.agentId);+ attachStream(state);+ paintActivity(state);+ evictStreams();+}++function getStreamObserver() {+ if (_streamObserver) return _streamObserver;+ _streamObserver = new IntersectionObserver((entries) => {+ for (const entry of entries) {+ const id = entry.target.dataset.agentId;+ const state = _cards.get(id);+ if (!state) continue;+ if (entry.isIntersecting) {+ _nearView.add(id);+ if (!document.hidden) ensureStream(state);+ } else {+ _nearView.delete(id);+ if (id !== _spotAgentId) releaseStream(state);+ }+ }+ }, { rootMargin: STREAM_MARGIN, threshold: 0 });+ return _streamObserver;+}+// ── lifecycle ──────────────────────────────────────────────────────────────────function mountAgent(agent) {@@ -825,6 +961,11 @@ function mountAgent(agent) {action: card.querySelector('[data-action]'),age: card.querySelector('[data-age]'),lastActionAt,+ // The roster already knows how much this agent has actually done. Holding it+ // on the card lets the pre-stream canvas say something true ("28 actions+ // recorded") instead of the flat "no actions yet" that used to greet every+ // card the pool had not reached.+ actionCount: Number(agent.action_count) || 0,entries: [],lastFrameAt: 0,live: false,@@ -855,10 +996,12 @@ function mountAgent(agent) {});}renderAge(state);- attachStream(state);- // Intent + status polling are intersection-driven (getObserver), so the pool- // only spins up for cards actually on screen and frees the slot on scroll-away.+ paintActivity(state);+ // Intent + status polling are intersection-driven (getObserver), so the caster+ // pool only spins up for cards actually on screen and frees the slot on+ // scroll-away. The wider band (getStreamObserver) owns the SSE listener itself.getObserver().observe(card);+ getStreamObserver().observe(card);}function renderEmpty() {@@ -998,7 +1141,11 @@ function updateStats() {function startFpsTicker() {_fpsInterval = setInterval(() => {let total = 0;- for (const [id, s] of _cards) {+ // Only a streamed card can have frames to count; the rest carry no badge+ // state worth touching every second.+ for (const id of _streamed) {+ const s = _cards.get(id);+ if (!s) continue;const c = _fpsMap.get(id) || 0;total += c;s.fps = c;@@ -1024,7 +1171,12 @@ function startFpsTicker() {function startIdleRepaint() {_idleRepaint = setInterval(() => {if (document.hidden) return;+ // Only repaint what a viewer can actually see (plus the spotlit hero). A+ // canvas redraw per mounted card was burning frames on a wall the visitor+ // had long scrolled past; an off-screen card keeps its last painted state+ // and repaints the moment it re-enters the band.for (const s of _cards.values()) {+ if (!_nearView.has(s.agentId) && s.agentId !== _spotAgentId) continue;if (!isLiveNow(s)) {paintActivity(s);renderAge(s);@@ -1055,24 +1207,27 @@ function startInfiniteScroll() {}function suspendStreams() {+ for (const id of [..._streamed]) {+ const s = _cards.get(id);+ if (s) releaseStream(s); else _streamed.delete(id);+ }for (const s of _cards.values()) {- try { s.es?.close(); } catch { /* */ }- s.es = null;- stopStatusPolling(s);- clearTimeout(s.reconnectLabelTimer);- s.reconnecting = false;- hideWarming(s);const statusEl = s.card.querySelector('[data-status]');if (statusEl) { statusEl.textContent = 'Paused'; statusEl.title = ''; }- const dot = s.card.querySelector('[data-dot]');- dot?.classList.add('idle');- dot?.classList.remove('thin');}}function resumeStreams() {+ // Only the pre-warm band comes back, not every mounted card: a backgrounded tab+ // must not return by reopening one connection per agent on the wall.+ for (const id of _nearView) {+ const s = _cards.get(id);+ if (s) ensureStream(s);+ }for (const s of _cards.values()) {- if (!s.es) attachStream(s);+ if (s.es) continue;+ const statusEl = s.card.querySelector('[data-status]');+ if (statusEl?.textContent === 'Paused') statusEl.textContent = s.entries?.length ? 'Active' : 'Idle';}// IntersectionObserver doesn't re-fire on tab focus, so re-assert intent and// restart the handoff poll for cards that are still on screen.@@ -1325,8 +1480,15 @@ function restoreSpotNode() {if (!_spotNode) return;_spotNode.classList.remove('al-card--spotlit');grid.appendChild(_spotNode);+ const leaving = _spotAgentId;_spotNode = null;_spotAgentId = null;+ // The outgoing hero loses its pinned slot. If its grid position is off the+ // pool's band it hands the connection straight back to the next candidate.+ if (leaving && !_nearView.has(leaving)) {+ const s = _cards.get(leaving);+ if (s) releaseStream(s);+ }}function updateCaption(candidate) {@@ -1352,8 +1514,11 @@ function promote(state, candidate) {_spotNode = state.card;_spotAgentId = candidate.agentId;// Prioritise a real caster for the spotlit agent (same intent path the grid- // cards use), and never leave a frozen frame on the hero.+ // cards use), and never leave a frozen frame on the hero. The hero holds a+ // stream slot for as long as it holds the stage, even once its grid position+ // has scrolled out of the pool's band._inView.add(candidate.agentId);+ ensureStream(state);signalWatch(candidate.agentId);if (!isLiveNow(state)) { startStatusPolling(state); paintActivity(state); }updateCaption(candidate);diff --git a/src/agi.css b/src/agi.cssindex b685bc2f6..5e9a0b381 100644--- a/src/agi.css+++ b/src/agi.css@@ -162,6 +162,27 @@ body {font-family: var(--font-mono); font-size: var(--text-sm); color: var(--ink-dim);letter-spacing: 0.1em;}+/* Shown only when the agent's model AND the default body both fail to load, so+ the stage explains itself instead of sitting empty. */+.agi-stage-fallback {+ position: relative; z-index: 3;+ flex: 1;+ display: flex; flex-direction: column; align-items: center; justify-content: center;+ gap: var(--space-sm);+ padding: var(--space-lg) var(--space-md) var(--space-2xl);+ text-align: center;+}+.agi-stage-fallback-title {+ margin: 0;+ font-family: var(--font-mono); font-size: var(--text-2xs);+ letter-spacing: 0.12em; text-transform: uppercase;+ color: var(--ink);+}+.agi-stage-fallback-body {+ margin: 0; max-width: 38ch;+ font-size: var(--text-sm); line-height: 1.55; color: var(--ink-dim);+}+.agi-stage-fallback .agi-btn { margin-top: var(--space-2xs); }/* ── section grid ─────────────────────────────────────────────────────────── */.agi-grid {diff --git a/src/agi.js b/src/agi.jsindex 7bfa21818..5751993e2 100644--- a/src/agi.js+++ b/src/agi.js@@ -29,6 +29,7 @@ const state = {timer: null,el3d: null, // the embodied <agent-3d>embodied: false,+ bodyFailover: false, // the agent's own model died; the default body is standing inlastScore: null, // last reputation value drawn, so the ring only re-sweeps on a real changeshell: false, // the stable layout has been builtfilter: 'trade', // decision stream lens: 'trade' | 'all'@@ -103,9 +104,45 @@ function applyMood(cog) {} catch (_) { /* embodiment is enhancement, never a hard dependency */ }}-function mountBody(agent) {- const stage = document.getElementById('agi-stage');- if (!stage || state.el3d) return;+// The platform's own body, used when an agent has none and as the failover when+// an agent's own model can't be fetched.+const DEFAULT_BODY = '/avatars/default.glb';++function bodyLabel(agent) {+ return agent?.name ? `Live 3D body of ${agent.name}, the trading agent` : 'Live 3D body of the trading agent';+}++// Replace the stage's contents with an honest account of why the body is absent.+// Reached only when BOTH the agent's model and the default body fail, so it says+// what is actually still true: the mind and the record below are unaffected.+function renderStageFallback(stage, agent) {+ state.el3d = null;+ state.embodied = false;+ stage.querySelector('agent-3d')?.remove();+ stage.querySelector('.agi-stage-boot')?.remove();+ stage.querySelector('.agi-stage-fallback')?.remove();+ const box = document.createElement('div');+ box.className = 'agi-stage-fallback';+ box.setAttribute('role', 'status');+ box.innerHTML = `+ <p class="agi-stage-fallback-title">Its body didn't load</p>+ <p class="agi-stage-fallback-body">The 3D avatar couldn't be fetched from here. Everything else on this page is live and unaffected: the agent is still trading, and its decisions and track record below are current.</p>+ <button type="button" class="agi-btn" data-embody-retry>Try embodying again</button>`;+ box.querySelector('[data-embody-retry]').addEventListener('click', () => {+ box.remove();+ const boot = document.createElement('div');+ boot.className = 'agi-stage-boot';+ boot.textContent = 'embodying…';+ stage.insertBefore(boot, stage.querySelector('.agi-stage-floor'));+ state.bodyFailover = false;+ mountBody(agent);+ });+ stage.insertBefore(box, stage.querySelector('.agi-stage-floor'));+}++// Build and attach one <agent-3d>. `source` is either the agent's own id or an+// explicit model URL, which is what makes the failover possible.+function attachBody(stage, agent, source) {const el = document.createElement('agent-3d');el.setAttribute('mode', 'inline');el.setAttribute('background', 'transparent');@@ -119,27 +156,58 @@ function mountBody(agent) {el.setAttribute('responsive', '');el.setAttribute('eager', '');// The body is a graphic: name it for screen readers, since the canvas inside- // carries no text of its own.+ // carries no text of its own. role="img" also makes it a leaf, so it must not+ // sit in the tab order: it has nothing to activate and no focus indicator.el.setAttribute('role', 'img');- el.setAttribute('aria-label', agent?.name ? `Live 3D body of ${agent.name}, the trading agent` : 'Live 3D body of the trading agent');- if (agent?.id) el.setAttribute('agent-id', agent.id);- else el.setAttribute('body', '/avatars/default.glb');+ el.setAttribute('tabindex', '-1');+ el.setAttribute('aria-label', bodyLabel(agent));+ if (source.agentId) el.setAttribute('agent-id', source.agentId);+ else el.setAttribute('body', source.body);++ let settled = false;// Reveal only once the model is in; until then the boot line shows.const reveal = () => {+ if (settled) return;+ settled = true;+ clearTimeout(failsafe);el.classList.add('agi-loaded');- const boot = stage.querySelector('.agi-stage-boot');- if (boot) boot.remove();+ stage.querySelector('.agi-stage-boot')?.remove();state.embodied = true;if (state.data?.cognition) { applyMood(state.data.cognition); }};+ // The component suppresses its own error card for non-chat embeds, so a dead+ // model is otherwise completely silent. Fail over to the default body once,+ // then explain rather than leaving an empty stage.+ const fail = () => {+ if (settled) return;+ settled = true;+ clearTimeout(failsafe);+ el.remove();+ state.el3d = null;+ if (!state.bodyFailover && source.agentId) {+ state.bodyFailover = true;+ attachBody(stage, agent, { body: DEFAULT_BODY });+ return;+ }+ renderStageFallback(stage, agent);+ };el.addEventListener('agent:ready', reveal, { once: true });el.addEventListener('load', reveal, { once: true });- // Failsafe: if neither event fires (older bundle), reveal after a beat.- setTimeout(reveal, 4000);+ el.addEventListener('agent:error', fail);+ // Failsafe: if no event at all fires (older bundle), reveal rather than strand+ // the reader on the boot line. A bundle that does emit agent:error settles the+ // element first, so this can no longer paper over a genuine failure.+ const failsafe = setTimeout(reveal, 8000);stage.insertBefore(el, stage.querySelector('.agi-stage-floor'));state.el3d = el;}+function mountBody(agent) {+ const stage = document.getElementById('agi-stage');+ if (!stage || state.el3d) return;+ attachBody(stage, agent, agent?.id ? { agentId: agent.id } : { body: DEFAULT_BODY });+}+// ── hero ──────────────────────────────────────────────────────────────────────function heroActions(agent) {const ledgerHref = agent?.id ? `/ledger/${agent.id}` : '/ledger';@@ -458,6 +526,7 @@ function renderError() {state.shell = false;state.el3d = null;state.embodied = false;+ state.bodyFailover = false;document.getElementById('agi-retry')?.addEventListener('click', () => { renderLoading(); boot(); });}diff --git a/src/agora/agora-world.js b/src/agora/agora-world.jsindex 49387a7d9..50366a389 100644--- a/src/agora/agora-world.js+++ b/src/agora/agora-world.js@@ -13,7 +13,7 @@ import * as THREE from 'three';import { fetchOSMData, buildCity, CITY_HALF } from '../city/city-map.js';import { createCityScene, bindResize } from '../city/city-scene.js';import { CityCamera } from '../city/city-camera.js';-import { CitizenPopulation } from './citizen-avatar.js';+import { CitizenPopulation, citizenProfessionLabel } from './citizen-avatar.js';import { PassportPanel } from './passport-panel.js';import { mountEconomyLayer } from './economy-layer.js';import { log } from '../shared/log.js';@@ -292,8 +292,10 @@ async function main() {btn.type = 'button';btn.className = 'agora-roster-btn';btn.dataset.id = c.id;- const prof = c.professions?.[0]?.label || c.profession || 'Citizen';- btn.textContent = `Inspect ${c.displayName || 'citizen'} — ${prof}`;+ // The craft this citizen is known for, resolved exactly the way the 3D+ // nameplate and the accent colour resolve it, so the screen-reader roster+ // and the square never describe the same citizen differently.+ btn.textContent = `Inspect ${c.displayName || 'citizen'}, ${citizenProfessionLabel(c)}`;btn.addEventListener('focus', () => {population.highlight(c.id);const p = population.worldPosition(c.id);diff --git a/src/agora/citizen-avatar.js b/src/agora/citizen-avatar.jsindex af5c94143..e4de3338c 100644--- a/src/agora/citizen-avatar.js+++ b/src/agora/citizen-avatar.js@@ -60,6 +60,45 @@ export function professionColor(profession) {return PROFESSION_COLORS[String(profession || '').toLowerCase()] || NEUTRAL_ACCENT;}+// Display labels for the profession keys the API emits (lowercase). Falls back to+// a capitalised key so an unmapped/new profession still reads cleanly: open by+// design, never a hardcoded gate. Lives beside the colour map so a profession's+// name and its accent can never disagree.+export const PROFESSION_LABELS = {+ fetcher: 'Fetcher', sculptor: 'Sculptor', scribe: 'Scribe',+ cartographer: 'Cartographer', crier: 'Crier', appraiser: 'Appraiser',+ verifier: 'Verifier', namekeeper: 'Namekeeper',+};+export function professionLabelFor(profession) {+ const key = String(profession || '').toLowerCase();+ if (PROFESSION_LABELS[key]) return PROFESSION_LABELS[key];+ if (!key) return 'Citizen';+ return key.charAt(0).toUpperCase() + key.slice(1);+}++// The craft a citizen is *known for*, as a profession key.+//+// A citizen carries two profession fields and they mean different things:+// `profession` is the primary craft the world seeds and the job board hires on,+// while `professions` is the decoded AgenC capability bitmap (everything it is+// allowed to claim). Every citizen is granted the fetcher bit because an x402+// service call is the one craft anyone can do (workers/agora-citizens/roster.js),+// so `professions[0]` is *always* Fetcher and says nothing about who this is.+// Reading it as the citizen's craft labelled all 200 citizens "FETCHER" while+// their accent colour showed the real primary. Primary first, bitmap only as the+// fallback, so name, chip and colour always agree.+export function primaryProfessionKey(citizen) {+ return citizen?.profession || citizen?.professions?.[0]?.key || null;+}++/** The citizen's craft as display text ("Appraiser"), never an empty chip. */+export function citizenProfessionLabel(citizen) {+ const key = primaryProfessionKey(citizen);+ if (key) return professionLabelFor(key);+ // No primary key: honour a label the API already formatted before giving up.+ return citizen?.professions?.[0]?.label || 'Citizen';+}+const _box = new Box3();const _v = new Vector3();@@ -317,8 +356,8 @@ export class CitizenPopulation {group.userData.citizenId = citizen.id;this.root.add(group);- const accent = professionColor(citizen.profession || citizen.professions?.[0]?.key);- const label = buildLabelSprite(citizen.displayName || 'Citizen', citizen.professions?.[0]?.label || citizen.profession, accent);+ const accent = professionColor(primaryProfessionKey(citizen));+ const label = buildLabelSprite(citizen.displayName || 'Citizen', citizenProfessionLabel(citizen), accent);_box.setFromObject(model, true);const height = Number.isFinite(_box.max.y) ? _box.max.y : AVATAR_HEIGHT;label.position.set(0, height + 0.3, 0);@@ -481,7 +520,7 @@ export class CitizenPopulation {if (!inst) return;inst.busy = status === 'Busy';if (inst.busy && !inst.busyRing) {- const accent = professionColor(inst.citizen.profession || inst.citizen.professions?.[0]?.key);+ const accent = professionColor(primaryProfessionKey(inst.citizen));inst.busyRing = this._buildBusyRing(accent);}}@@ -524,7 +563,7 @@ export class CitizenPopulation {if (!inst) { this._ring.visible = false; return; }inst.group.getWorldPosition(_v);this._ring.position.set(_v.x, 0.02, _v.z);- const accent = professionColor(inst.citizen.profession || inst.citizen.professions?.[0]?.key);+ const accent = professionColor(primaryProfessionKey(inst.citizen));this._ring.material.color.set(accent);this._ring.visible = true;}diff --git a/src/agora/passport-panel.js b/src/agora/passport-panel.jsindex 3b1eea665..45e28aca1 100644--- a/src/agora/passport-panel.js+++ b/src/agora/passport-panel.js@@ -188,13 +188,13 @@ export class PassportPanel {// ── Renderers ──────────────────────────────────────────────────────────────_renderLoading(hint) {- const accent = hint ? professionColor(hint.profession || hint.professions?.[0]?.key) : '#9fb4cc';+ const accent = hint ? professionColor(primaryProfessionKey(hint)) : '#9fb4cc';this._bodyEl.innerHTML = `<div class="agora-pp-hero"><span class="agora-pp-dot" style="background:${accent}"></span><div><div class="agora-pp-name">${esc(hint?.displayName || 'Loading…')}</div>- <div class="agora-pp-prof">${esc(hint?.professions?.[0]?.label || hint?.profession || 'Citizen')}</div>+ <div class="agora-pp-prof">${esc(citizenProfessionLabel(hint))}</div></div></div><div class="agora-pp-skel" aria-hidden="true">@@ -220,7 +220,7 @@ export class PassportPanel {_render(data) {const c = data.citizen || {};const onchain = data.onchain || null;- const accent = professionColor(c.profession || c.professions?.[0]?.key);+ const accent = professionColor(primaryProfessionKey(c));this._cluster = c.agenc?.cluster === 'mainnet' ? 'mainnet' : 'devnet';this._titleEl.textContent = c.displayName || 'Passport';diff --git a/src/agora/professions.js b/src/agora/professions.jsindex 3dc6470bb..1f13e6d33 100644--- a/src/agora/professions.js+++ b/src/agora/professions.js@@ -8,24 +8,18 @@// sizing/formatting. No second colour map, ever.import * as THREE from 'three';-import { professionColor, PROFESSION_COLORS } from './citizen-avatar.js';+import {+ professionColor, PROFESSION_COLORS, PROFESSION_LABELS,+ professionLabelFor, primaryProfessionKey, citizenProfessionLabel,+} from './citizen-avatar.js';-export { professionColor, PROFESSION_COLORS };--// Display labels for the profession keys the API emits (lowercase). Falls back-// to a capitalised key so an unmapped/new profession still reads cleanly —-// open by design, never a hardcoded gate.-const PROFESSION_LABELS = {- fetcher: 'Fetcher', sculptor: 'Sculptor', scribe: 'Scribe',- cartographer: 'Cartographer', crier: 'Crier', appraiser: 'Appraiser',- verifier: 'Verifier', namekeeper: 'Namekeeper',+// The profession vocabulary (colour, label, and which craft a citizen is known+// for) has exactly one home, next to the crowd that renders it. Re-exported here+// so the economy visuals keep importing from one module. No second map, ever.+export {+ professionColor, PROFESSION_COLORS, PROFESSION_LABELS,+ professionLabelFor, primaryProfessionKey, citizenProfessionLabel,};-export function professionLabelFor(profession) {- const key = String(profession || '').toLowerCase();- if (PROFESSION_LABELS[key]) return PROFESSION_LABELS[key];- if (!key) return 'Citizen';- return key.charAt(0).toUpperCase() + key.slice(1);-}// The CSS accent for a profession as a Three.js Color (markers, coin arcs, the// board glow all live in the 3D scene). Memoised so we don't allocate a Colordiff --git a/src/alpha-copilot.css b/src/alpha-copilot.cssindex d2117c4a4..486d34cff 100644--- a/src/alpha-copilot.css+++ b/src/alpha-copilot.css@@ -266,6 +266,7 @@ body {/* ── launches ─────────────────────────────────────────────────────────────── */.ac-launches { padding: var(--space-sm); display: flex; flex-direction: column; }.ac-launches-head { display: flex; align-items: center; justify-content: space-between; padding: var(--space-xs) var(--space-sm) var(--space-sm); }+.ac-launches-title { display: flex; align-items: center; gap: var(--space-xs); min-width: 0; }.ac-launches-head h2 { display: flex; align-items: center; gap: var(--space-xs); font-size: var(--text-md); font-family: var(--font-display); margin: 0; color: var(--ink-bright); }.ac-launches-count { font-family: var(--font-mono); font-size: var(--text-2xs); color: var(--ink-faint); background: var(--surface-2); border-radius: var(--radius-pill); padding: 1px var(--space-xs); }.ac-launches-list { display: flex; flex-direction: column; gap: var(--space-sm); max-height: 660px; overflow-y: auto; padding: var(--space-sm) var(--space-2xs) var(--space-2xs); }diff --git a/src/alpha-copilot.js b/src/alpha-copilot.jsindex 034896163..90b4675b2 100644--- a/src/alpha-copilot.js+++ b/src/alpha-copilot.js@@ -13,6 +13,7 @@*/import { agentAvatarGlb } from './shared/agent-3d.js';+import { resolveDevR2Url } from './shared/dev-r2-proxy.js';import { previewAgentTrade, executeAgentTrade, TradeError } from './agent-solana-wallet.js';import { countUp, enterStagger, rippleOnce, reducedMotion } from './ui-juice.js';@@ -94,7 +95,6 @@ function cacheDom() {dom.readEmpty = $('#ac-read-empty');dom.readBody = $('#ac-read-body');dom.launchesList = $('#ac-launches-list');- dom.launchesCount = $('#ac-launches-count');dom.refresh = $('#ac-refresh');dom.actDrawer = $('#ac-act-drawer');dom.actBody = $('#ac-act-body');@@ -211,6 +211,7 @@ async function loadAgent(id) {dom.agentName.textContent = 'Not found';dom.agentRole.textContent = e.message || 'Could not load that agent';state.agent = null;+ clearStage();return;}state.agent = agent;@@ -226,8 +227,26 @@ async function loadAgent(id) {loadCandidates();}+// A failed load must not leave the PREVIOUS agent standing on stage with its+// launch cards still rendered: `requestRead` needs `state.agent`, so every one of+// those "Ask for a read" buttons becomes a silent no-op click. Strip the stage+// back to its first-paint state so the only thing on screen is the real one.+function clearStage() {+ if (state.avatarEl) { try { state.avatarEl.remove(); } catch { /* already detached */ } state.avatarEl = null; }+ if (dom.avatarPlaceholder) dom.avatarPlaceholder.hidden = false;+ dom.agentLink.hidden = true;+ state.candidates = [];+ markActiveCard(null);+ resetRead();+ showLaunchesIdle(IDLE_PICK);+}+async function mountAvatar(agent) {- const glb = agentAvatarGlb(agent);+ // r2.dev only sends CORS headers for the production origins, so on localhost /+ // Codespaces the raw GLB fetch is blocked and the stage shows a network error+ // where the body should be. Every other GLB-mounting surface routes through+ // this helper; it is a no-op in production.+ const glb = resolveDevR2Url(agentAvatarGlb(agent));try { await import('./element.js'); } catch { /* element may already be registered */ }// Rebuild the avatar element each load so a new agent shows its own body.if (state.avatarEl) { try { state.avatarEl.remove(); } catch { /* ignore */ } state.avatarEl = null; }@@ -246,12 +265,18 @@ async function mountAvatar(agent) {}// ── candidate launches ──────────────────────────────────────────────────────+// Resolved on every write rather than cached: this badge sits next to a+// `data-i18n-html` heading, and any element the i18n pass rewrites is a NEW node+// afterwards. A cached ref there goes stale the moment a locale lands, and the+// counter silently stops updating with no error anywhere.function setCount(n) {+ const el = document.getElementById('ac-launches-count');+ if (!el) return;if (n > 0) {- const from = parseInt(dom.launchesCount.textContent, 10) || 0;- dom.launchesCount.hidden = false;- countUp(dom.launchesCount, from, n, { format: (v) => String(Math.round(v)) });- } else dom.launchesCount.hidden = true;+ const from = parseInt(el.textContent, 10) || 0;+ el.hidden = false;+ countUp(el, from, n, { format: (v) => String(Math.round(v)) });+ } else el.hidden = true;}// The launches column is the page's call to action, so it must never render as@@ -368,6 +393,7 @@ function markActiveLaunch(mint) {function resetRead() {state.read = null;state.activeMint = null;+ state.lastSpoken = '';markActiveLaunch(null);dom.readEmpty.hidden = false;dom.readBody.hidden = true;@@ -499,7 +525,9 @@ function renderAction(data) {if (!host) return;const gate = data.gate || {};if (gate.can_act) {- host.innerHTML = `<button type="button" class="ac-btn ac-btn-act" id="ac-act-go">Act — buy ${fmtSol(gate.size_sol)} SOL</button>+ // fmtSol already prefixes the SOL glyph, so no unit suffix here: appending+ // one renders the amount with a doubled unit ("◎0.01 SOL").+ host.innerHTML = `<button type="button" class="ac-btn ac-btn-act" id="ac-act-go">Act: buy ${fmtSol(gate.size_sol)}</button><p class="ac-action-note">${esc(gate.message || '')}</p>`;$('#ac-act-go')?.addEventListener('click', () => openActDrawer(data));} else {@@ -586,7 +614,7 @@ function openActDrawer(data) {const sig = data.signals || {};const sym = sig.symbol ? `$${esc(sig.symbol)}` : short(data.mint, 4, 4);dom.actBody.innerHTML = `- <p class="ac-act-lead">${esc(state.agent?.name || 'Your agent')} wants to buy <strong>${fmtSol(gate.size_sol)} SOL</strong> of ${sym}.</p>+ <p class="ac-act-lead">${esc(state.agent?.name || 'Your agent')} wants to buy <strong>${fmtSol(gate.size_sol)}</strong> of ${sym}.</p><div class="ac-act-quote" id="ac-act-quote">Fetching a fresh live quote…</div><div class="ac-act-controls"><button type="button" class="ac-btn ac-btn-act" id="ac-act-confirm" disabled>Confirm buy</button>@@ -605,7 +633,7 @@ function openActDrawer(data) {const expected = q?.expected_out ?? q?.out?.amount ?? q?.outUi;const warn = q?.warning || q?.blocked_reason;quoteHost.innerHTML = `- <div class="ac-act-qrow"><span>You pay</span><strong>${fmtSol(gate.size_sol)} SOL</strong></div>+ <div class="ac-act-qrow"><span>You pay</span><strong>${fmtSol(gate.size_sol)}</strong></div>${expected != null ? `<div class="ac-act-qrow"><span>Expected</span><strong>${Number(expected).toLocaleString(undefined, { maximumFractionDigits: 2 })} ${esc(sig.symbol || 'tokens')}</strong></div>` : ''}<div class="ac-act-qrow"><span>Price impact</span><strong>${fmtPct(impact)}</strong></div>${warn ? `<p class="ac-act-warn">${esc(warn)}</p>` : ''}`;@@ -629,7 +657,7 @@ function openActDrawer(data) {dom.actBody.innerHTML = `<div class="ac-act-done"><div class="ac-act-done-mark">✓</div>- <p>Bought into ${sym} for ${fmtSol(spent)} SOL.</p>+ <p>Bought into ${sym} for ${fmtSol(spent)}.</p>${sig2 ? `<a class="ac-btn ac-btn-ghost" href="${esc(res.explorer || explorerTxUrl(sig2))}" target="_blank" rel="noopener">View transaction</a>` : ''}${res?.new_balance_sol != null ? `<p class="ac-act-fine">Wallet now ${fmtSol(res.new_balance_sol)}.</p>` : ''}<a class="ac-act-audit" href="/agent/${esc(state.agent.id)}" target="_blank" rel="noopener">See it in the custody trail →</a>diff --git a/src/animations-gallery.js b/src/animations-gallery.jsindex 6d0a39cea..13bfdf274 100644--- a/src/animations-gallery.js+++ b/src/animations-gallery.js@@ -83,12 +83,20 @@ const els = {modalError: $('modal-error'),};+// URL params are user-editable, so every one is validated against the values the+// UI can actually represent. An unknown ?sort= used to blank the sort <select>,+// and an unknown ?cat= filtered the whole grid away with no chip to clear it.+const TYPE_FILTERS = new Set(['', 'loop', 'once']);+const SORTS = new Set(['featured', 'az', 'za', 'shortest', 'longest', 'shuffle']);+const CATEGORY_KEYS = new Set(GALLERY_CATEGORIES.map((c) => c.key));+const oneOf = (allowed, value, fallback) => (allowed.has(value) ? value : fallback);+const params = new URLSearchParams(location.search);const state = {query: params.get('q') || '',- filter: params.get('filter') || '', // '' | loop | once- category: params.get('cat') || '', // '' | GALLERY_CATEGORIES key- sort: params.get('sort') || 'featured',+ filter: oneOf(TYPE_FILTERS, params.get('filter') || '', ''), // '' | loop | once+ category: oneOf(CATEGORY_KEYS, params.get('cat') || '', ''), // '' | GALLERY_CATEGORIES key+ sort: oneOf(SORTS, params.get('sort') || 'featured', 'featured'),all: [],filtered: [],shown: 0,@@ -100,6 +108,7 @@ const live = getLivePreview();if (state.query) els.search.value = state.query;if (els.sort) els.sort.value = state.sort;+syncTypeFilter();// ── URL state ──────────────────────────────────────────────────────────────@@ -189,12 +198,12 @@ function normalizeFullLibraryClip(clip) {category: galleryCategoryOf(clip.name, clip.label),duration_ms: clip.duration ? Math.round(clip.duration * 1000) : null,url: clip.url, // absolute CDN url- // The library manifest publishes a `thumb` url per clip; older manifests- // predate thumbnails, so fall back to the CDN convention (thumbs live- // beside clips) and let the card's onerror show the icon placeholder.- thumbnail_url:- clip.thumb ||- (clip.url ? clip.url.replace('/clips/', '/thumbs/').replace(/\.json$/, '.webp') : null),+ // The library manifest publishes a `thumb` url only for clips that have+ // one baked. Guessing the CDN convention for the rest (853 of 2,874 today)+ // requested an object that is never there: every one 404s, and the browser+ // logs a blocked cross-origin read before the card falls back to its icon.+ // No thumb in the manifest means no request.+ thumbnail_url: clip.thumb || null,price: null,};}@@ -223,11 +232,7 @@ async function loadAll() {fetchFullLibrary(),]);- if (libRes.status === 'rejected' && comRes.status === 'rejected' && fullRes.status === 'rejected') {- showState('error');- return;- }-+ const results = [libRes, comRes, fullRes];const library = libRes.status === 'fulfilled' ? libRes.value : [];const community = comRes.status === 'fulfilled' ? comRes.value : [];const full = fullRes.status === 'fulfilled' ? fullRes.value : [];@@ -237,6 +242,15 @@ async function loadAll() {state.all = [...community, ...library, ...full.filter((c) => !curatedNames.has(c.id))];state.loaded = true;+ // Nothing to show AND at least one source errored is a failure, not an empty+ // library: "be the first to publish" would be a lie, and Retry is the action+ // the user needs. A genuinely empty catalog (every source answered, none had+ // clips) still falls through to the empty state below.+ if (state.all.length === 0 && results.some((r) => r.status === 'rejected')) {+ showState('error');+ return;+ }+renderHeroStats();renderChips();applyFilters();@@ -249,11 +263,12 @@ async function loadAll() {else {const item = state.all.find((c) => c.id === wanted);if (item) {- // Visible under different filters — clear them so the link works.+ // Visible under different filters, so clear them for the link.state.query = '';state.category = '';state.filter = '';els.search.value = '';+ syncTypeFilter();renderChips();applyFilters();openModal(state.filtered.findIndex((c) => c.id === wanted));@@ -303,6 +318,15 @@ function syncChips() {});}+// Keep the loop/once segmented control showing what is actually filtering. The+// chips render from state on every pass; these three buttons are static markup,+// so a ?filter= deep link (or the clear-filters button) has to press them.+function syncTypeFilter() {+ els.typeFilter?.querySelectorAll('[data-filter]').forEach((btn) => {+ btn.setAttribute('aria-pressed', String((btn.dataset.filter || '') === state.filter));+ });+}+// ── Filter + sort + render ───────────────────────────────────────────────────function applyFilters() {@@ -339,7 +363,8 @@ function sortFiltered() {arr.sort((a, b) => (b.duration_ms ?? -1) - (a.duration_ms ?? -1));break;case 'shuffle': {- // Deterministic per page load, reshuffled when re-selected.+ // Reshuffled on every filter pass, so changing a chip or the search+ // while shuffled deals a fresh hand rather than the same order.for (let i = arr.length - 1; i > 0; i--) {const j = Math.floor(Math.random() * (i + 1));[arr[i], arr[j]] = [arr[j], arr[i]];@@ -428,7 +453,7 @@ function buildCard(clip, index) {card.innerHTML = `<div class="ag-card-preview" role="button" tabindex="0"- aria-label="${escHtml(clip.name)} — open details">+ aria-label="${escHtml(clip.name)}: open details">${clip.thumbnail_url? `<img class="ag-card-thumb" src="${escHtml(clip.thumbnail_url)}" alt="" loading="lazy" decoding="async" />`: ''}@@ -518,9 +543,20 @@ function escHtml(s) {// ── Detail modal ─────────────────────────────────────────────────────────────+// The element that opened the modal, so closing returns focus where the user+// left it instead of dropping it on <body> and restarting the tab order.+let modalOpener = null;+function openModal(index) {const clip = state.filtered[index];if (!clip || !els.modal) return;+ // Stepping prev/next re-opens the modal; only a cold open owns the opener,+ // and only a cold open moves focus (stepping with the keyboard has to leave+ // focus on Next so the next press steps again).+ const coldOpen = els.modal.hidden;+ if (coldOpen && document.activeElement instanceof HTMLElement) {+ modalOpener = document.activeElement;+ }state.modalIndex = index;els.modalTitle.textContent = clip.name;@@ -551,7 +587,10 @@ function openModal(index) {els.modal.hidden = false;document.body.style.overflow = 'hidden';- els.modalClose.focus();+ // Focus the dialog itself, not its close button: a screen reader then reads+ // the clip title first, and Space stays free for the play/pause shortcut the+ // on-screen hint advertises.+ if (coldOpen) els.modal.focus();syncUrl(clip.id);let scrubbing = false;@@ -589,6 +628,34 @@ function closeModal() {live.stop();state.modalIndex = -1;syncUrl();+ // The opener can be gone (a filter change rebuilt the grid under the modal);+ // fall back to the search field so focus never lands on <body>.+ const back = modalOpener?.isConnected ? modalOpener : els.search;+ modalOpener = null;+ back?.focus();+}++const FOCUSABLE =+ 'a[href], button:not([disabled]), input:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])';++// aria-modal="true" promises the rest of the page is inert, so Tab has to wrap+// inside the dialog instead of walking off into the grid behind it.+function trapModalFocus(e) {+ const nodes = [...els.modal.querySelectorAll(FOCUSABLE)].filter(+ (n) => n.offsetWidth > 0 || n.offsetHeight > 0,+ );+ if (!nodes.length) return;+ const first = nodes[0];+ const last = nodes[nodes.length - 1];+ const active = document.activeElement;+ const outside = !els.modal.contains(active);+ if (e.shiftKey && (outside || active === first)) {+ e.preventDefault();+ last.focus();+ } else if (!e.shiftKey && (outside || active === last)) {+ e.preventDefault();+ first.focus();+ }}function stepModal(delta) {@@ -634,7 +701,7 @@ els.modalCopyEmbed?.addEventListener('click', async () => {const clip = state.filtered[state.modalIndex];if (!clip) return;const src = `${location.origin}/embed/avatar?anim=${encodeURIComponent(clip.id)}`;- const snippet = `<iframe src="${src}" width="360" height="480" style="border:0;border-radius:12px" allow="autoplay" title="${clip.name} — three.ws"></iframe>`;+ const snippet = `<iframe src="${src}" width="360" height="480" style="border:0;border-radius:12px" allow="autoplay" title="${clip.name} on three.ws"></iframe>`;await navigator.clipboard.writeText(snippet).catch(() => {});flashButton(els.modalCopyEmbed, 'Copied!');});@@ -684,10 +751,8 @@ els.chips?.addEventListener('click', (e) => {els.typeFilter?.addEventListener('click', (e) => {const btn = e.target.closest('[data-filter]');if (!btn) return;- state.filter = btn.dataset.filter;- els.typeFilter.querySelectorAll('[data-filter]').forEach((b) => {- b.setAttribute('aria-pressed', String(b === btn));- });+ state.filter = btn.dataset.filter || '';+ syncTypeFilter();syncUrl();if (state.loaded) applyFilters();});@@ -703,9 +768,7 @@ els.clearSearch?.addEventListener('click', () => {state.filter = '';state.category = '';els.search.value = '';- els.typeFilter?.querySelectorAll('[data-filter]').forEach((b) => {- b.setAttribute('aria-pressed', String(b.dataset.filter === ''));- });+ syncTypeFilter();syncChips();syncUrl();if (state.loaded) applyFilters();@@ -729,10 +792,16 @@ if ('IntersectionObserver' in window && els.sentinel) {document.addEventListener('keydown', (e) => {if (!els.modal.hidden) {+ // The scrub and speed sliders own their own arrow and space keys; stealing+ // them would scrub and step the clip list at the same time.+ const tag = document.activeElement?.tagName || '';+ const onSlider = /^(INPUT|SELECT|TEXTAREA)$/.test(tag);if (e.key === 'Escape') closeModal();+ else if (e.key === 'Tab') trapModalFocus(e);+ else if (onSlider) return;else if (e.key === 'ArrowLeft') stepModal(-1);else if (e.key === 'ArrowRight') stepModal(1);- else if (e.key === ' ' && e.target === document.body) {+ else if (e.key === ' ' && tag !== 'BUTTON' && tag !== 'A') {e.preventDefault();els.modalPlay.click();}diff --git a/src/app.js b/src/app.jsindex 3d22cdc3c..0ea3017d5 100644--- a/src/app.js+++ b/src/app.js@@ -1858,6 +1858,11 @@ class App {this._currentModelUrl = typeof rootFile === 'string' ? rootFile : null;this._hasLocalGlb = typeof rootFile !== 'string';this._currentLocalFile = typeof rootFile !== 'string' ? rootFile : null;+ // Replay handle for the error overlay. Anonymous visitors on /app have no+ // agent to re-fetch, so without this a failed load left a dead-end card with+ // no way back. Replaying the same arguments is safe for a dropped File too:+ // view() mints a fresh object URL, so cleanup()'s revoke doesn't strand it.+ this._retryLastView = () => this.view(rootFile, rootPath, fileMap);this._refreshMakeWidgetButton();this._refreshSaveToAccountButton();this._refreshOpenInComposerButton();@@ -2140,7 +2145,9 @@ class App {const msg = this._classifyLoadError(err, action?.payload?.error);this._showViewerError(msg,- this._editingAgentId ? () => this._retryAgentLoad() : null,+ this._editingAgentId+ ? () => this._retryAgentLoad()+ : this._retryLastView || null,);// Notify the host page that the GLB failed — paired with the// `widget:ready` event so script-tag embeds can show their owndiff --git a/src/components/footer.jsx b/src/components/footer.jsxindex 72096c3de..2107ed541 100644--- a/src/components/footer.jsx+++ b/src/components/footer.jsx@@ -5,7 +5,13 @@ import vhtml from 'vhtml';export function Footer() {return (<footer>- <a class="item" target="_blank" href="https://x.com/trythreews" aria-label="Follow on X">+ <a+ class="item"+ target="_blank"+ rel="noopener noreferrer"+ href="https://x.com/trythreews"+ aria-label="Follow on X"+ ><svgxmlns="http://www.w3.org/2000/svg"width="16"@@ -29,7 +35,7 @@ export function Footer() {|</span>- <a class="item" href="/validation/">+ <a class="item" href="/validation">validation</a>@@ -37,7 +43,7 @@ export function Footer() {|</span>- <a class="item" href="/reputation/">+ <a class="item" href="/reputation">reputation</a>@@ -45,7 +51,12 @@ export function Footer() {|</span>- <a class="item" target="_blank" href="https://github.com/nirholas/3d-agent/issues/new">+ <a+ class="item"+ target="_blank"+ rel="noopener noreferrer"+ href="https://github.com/nirholas/three.ws/issues/new"+ >help & feedback</a>@@ -56,7 +67,8 @@ export function Footer() {<aclass="item"target="_blank"- href="https://github.com/nirholas/3d-agent"+ rel="noopener noreferrer"+ href="https://github.com/nirholas/three.ws"aria-label="GitHub"><svgdiff --git a/src/editor/scene-explorer.js b/src/editor/scene-explorer.jsindex 73936c6d4..aeada46d5 100644--- a/src/editor/scene-explorer.js+++ b/src/editor/scene-explorer.js@@ -110,9 +110,9 @@ export class SceneExplorer {panel.innerHTML = `<div class="scene-explorer__header"><span class="scene-explorer__title">Scene</span>- <button class="scene-explorer__close" title="Close [T]">×</button>+ <button class="scene-explorer__close" type="button" title="Close [T]" aria-label="Close scene explorer">×</button></div>- <input type="text" class="scene-explorer__search" placeholder="Search nodes…">+ <input type="text" class="scene-explorer__search" placeholder="Search nodes…" aria-label="Search scene nodes"><div class="scene-explorer__hint">W translate · E rotate · R scale · Esc deselect</div><div class="scene-explorer__tree"></div><div class="scene-explorer__inspector"></div>diff --git a/src/nich-agent.js b/src/nich-agent.jsindex d68679533..c0d6ed27d 100644--- a/src/nich-agent.js+++ b/src/nich-agent.js@@ -161,7 +161,7 @@ export class NichAgent {<div class="nich-message agent">${_escapeHTML(greeting)}</div></div><div class="nich-controls">- <input type="text" class="nich-input" placeholder="Ask the agent…" autocomplete="off" maxlength="4000" />+ <input type="text" class="nich-input" placeholder="Ask the agent…" autocomplete="off" maxlength="4000" aria-label="Message the agent" /><button class="nich-send" aria-label="Send"><svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="currentColor"><path d="M2.01 21L23 12 2.01 3 2 10l15 2-15 2z"/></svg></button>diff --git a/src/studio/agent-presence.js b/src/studio/agent-presence.jsindex 8f3c0acf1..4ecdebcd2 100644--- a/src/studio/agent-presence.js+++ b/src/studio/agent-presence.js@@ -453,6 +453,20 @@ class AgentPresenceElement extends HTMLElement {:host([hidden]) { display: none; }#stage { position: relative; width: 100%; height: 100%; min-height: inherit; }#stage canvas { display: block; width: 100% !important; height: 100% !important; }+ /* Viewer.addGUI()/addAxesHelper() append the dat.GUI debug panel, its+ toggle, the axes gizmo, and the model-info readout straight into the+ stage element. Everything that positions or hides them lives in+ public/style.css (or in <agent-3d>'s own shadow CSS), and neither+ crosses into THIS shadow root, so the markup landed unstyled and in+ normal flow, and dat.GUI's inline-positioned colour picker painted a+ rainbow hue strip over the avatar on every presence surface. Presence+ is a display surface in every mode (it builds the Viewer with+ kiosk:true), so the debug chrome is suppressed here rather than+ depending on a host stylesheet that may not be loaded. */+ #stage .gui-wrap,+ #stage .gui-toggle,+ #stage .axes,+ #stage .model-info { display: none !important; }.status {position: absolute; inset: 0; display: none; place-items: center;text-align: center; padding: 16px; pointer-events: none;