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): stop printing 401s in every signed-out visitor's console
nirholasc9a17d7bf951
diff --git a/pages/agents-live.html b/pages/agents-live.htmlindex b0ef72c4b..5a9759301 100644--- a/pages/agents-live.html+++ b/pages/agents-live.html@@ -722,11 +722,11 @@.al-empty h2 {font-size: 17px;font-weight: 700;- color: rgba(255,255,255,0.55);+ color: var(--al-muted);}.al-empty p {font-size: 13px;- color: rgba(255,255,255,0.25);+ color: var(--al-faint);max-width: 340px;line-height: 1.55;}@@ -743,6 +743,79 @@transition: opacity 0.12s;}.al-empty-cta:hover { opacity: 0.85; }+ .al-empty-cta:focus-visible,+ .al-error-retry:focus-visible,+ .al-error-alt:focus-visible {+ outline: 2px solid var(--al-accent);+ outline-offset: 3px;+ }++ /* ── error state ──────────────────────────────────────────────── */+ /* Shown when the roster request itself fails. Deliberately distinct from+ the empty state: "no agents yet" would misread an outage as an empty+ platform. Carries a real retry plus a route to the full directory. */+ .al-error {+ grid-column: 1 / -1;+ display: flex;+ flex-direction: column;+ align-items: center;+ justify-content: center;+ gap: 12px;+ padding: 56px 24px;+ text-align: center;+ border: 1px solid var(--al-border-hi);+ border-radius: 12px;+ background: var(--al-surface);+ }+ .al-error-icon { font-size: 30px; opacity: 0.5; line-height: 1; }+ .al-error h2 {+ font-size: 16px;+ font-weight: 700;+ color: var(--al-text);+ }+ .al-error p {+ font-size: 13px;+ color: var(--al-muted);+ max-width: 400px;+ line-height: 1.55;+ }+ .al-error-actions {+ margin-top: 4px;+ display: flex;+ flex-wrap: wrap;+ align-items: center;+ justify-content: center;+ gap: 10px;+ }+ .al-error-retry {+ padding: 9px 20px;+ border-radius: 7px;+ background: var(--al-text);+ border: 1px solid var(--al-text);+ color: var(--al-bg);+ font: 700 13px/1 var(--al-font);+ cursor: pointer;+ transition: opacity 0.12s;+ }+ .al-error-retry:hover:not(:disabled) { opacity: 0.85; }+ .al-error-retry:active:not(:disabled) { transform: translateY(1px); }+ .al-error-retry:disabled { opacity: 0.5; cursor: progress; }+ .al-error-alt {+ padding: 9px 16px;+ border-radius: 7px;+ border: 1px solid var(--al-border-hi);+ color: var(--al-text);+ font-size: 13px;+ font-weight: 600;+ text-decoration: none;+ transition: background 0.12s;+ }+ .al-error-alt:hover { background: var(--al-surface-2); }+ .al-error-next {+ font-size: 12px;+ color: var(--al-faint);+ min-height: 15px;+ }/* ── skeleton loader ──────────────────────────────────────────── */.al-skeleton {diff --git a/src/agents-live.js b/src/agents-live.jsindex a567cc90e..742385da0 100644--- a/src/agents-live.js+++ b/src/agents-live.js@@ -24,6 +24,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';// Subtle accent for a card showing a live Coin World Tour walkthrough.(() => {@@ -145,11 +146,30 @@ function esc(s) {// identity) are suppressed server-side, so the grid reads as alive instead of a// graveyard of empty test agents. When signed in we also merge the caller's own// agents (which may be private) so an owner always sees theirs.+// Resolve the viewer's session exactly once. /api/auth/me answers 200 with+// `{ user: null }` for a signed-out visitor, so this costs one clean request and+// buys two things: we skip the owner-roster read (/api/agents) that could only+// 401 for an anonymous viewer, and we tell the shared client to skip the CSRF+// pre-flight on the public batch-balance POST. Both of those 401s used to land+// as red console errors on every signed-out visit to this very public page.+let _sessionPromise = null;+function hasSession() {+ if (!_sessionPromise) {+ _sessionPromise = fetch('/api/auth/me', { credentials: 'include', headers: { accept: 'application/json' } })+ .then((r) => (r.ok ? r.json() : null))+ .then((d) => !!(d && d.user))+ .catch(() => false)+ .then((ok) => { noteSession(ok); return ok; });+ }+ return _sessionPromise;+}+async function fetchRosterPage() {const firstPage = _offset === 0;const params = new URLSearchParams({ sort: 'live', limit: '48', offset: String(_offset) });let agents = [];let hasMore = false;+ let failed = false;try {const res = await fetch(`/api/agents/public?${params}`, { headers: { accept: 'application/json' } });if (res.ok) {@@ -161,12 +181,15 @@ async function fetchRosterPage() {// First page carries the platform-wide header-stat counts.if (Number.isFinite(data.total)) _rosterTotal = data.total;if (Number.isFinite(data.active_total)) _activeTotal = data.active_total;+ } else {+ failed = true;}- } catch { /* network — handled by caller via empty page */ }+ } catch { failed = true; }// First page only: merge the owner's own agents so a signed-in user always// sees their roster even if some are private / not yet in the public index.- if (firstPage) {+ // Gated on a resolved session: asking anonymously only ever returns 401.+ if (firstPage && await hasSession()) {try {const res = await fetch('/api/agents', { credentials: 'include', headers: { accept: 'application/json' } });if (res.ok) {@@ -183,7 +206,10 @@ async function fetchRosterPage() {} catch { /* anonymous — public list only */ }}- return { agents, hasMore };+ // `failed` only stands if we ended up with nothing to show: when the owner's+ // own agents merged in, the wall still has real cards and the public-list+ // outage degrades to a partial roster rather than an error screen.+ return { agents, hasMore, failed: failed && !agents.length };}// ── card ──────────────────────────────────────────────────────────────────────@@ -845,11 +871,94 @@ function renderEmpty() {</div>`;}+// ── roster error state ───────────────────────────────────────────────────────+// The roster request failing is NOT the same thing as the platform having no+// agents, and rendering "No agents yet" for an outage tells the viewer a lie.+// This panel says what actually happened, retries on its own with backoff, and+// offers both a manual retry and a route to the full directory.++const RETRY_BACKOFF_MS = [8000, 16000, 30000, 60000];+let _retryAttempt = 0;+let _retryTimer = null;+// While the error panel owns the wall, scroll must not re-fire the failing+// request on every wheel tick. The backoff timer and the button are the only+// retry paths.+let _rosterErrored = false;++function clearRosterError() {+ if (_retryTimer) { clearTimeout(_retryTimer); _retryTimer = null; }+ _retryAttempt = 0;+ _rosterErrored = false;+ document.getElementById('al-roster-error')?.remove();+}++async function retryRoster(box) {+ const btn = box.querySelector('.al-error-retry');+ const next = box.querySelector('.al-error-next');+ btn.disabled = true;+ btn.textContent = 'Retrying…';+ if (next) next.textContent = '';+ _hasMore = true; // a failed page must not permanently end pagination+ _rosterErrored = false; // this call IS the retry, so let it through+ await loadMore();+ // Still on screen ⇒ the retry failed too; hand control back and re-arm.+ if (document.getElementById('al-roster-error') === box) {+ btn.disabled = false;+ btn.textContent = 'Try again';+ scheduleRosterRetry(box);+ }+}++function scheduleRosterRetry(box) {+ if (_retryTimer) clearTimeout(_retryTimer);+ const wait = RETRY_BACKOFF_MS[Math.min(_retryAttempt, RETRY_BACKOFF_MS.length - 1)];+ _retryAttempt++;+ const next = box.querySelector('.al-error-next');+ if (next) next.textContent = `Retrying automatically in ${Math.round(wait / 1000)}s`;+ _retryTimer = setTimeout(() => {+ _retryTimer = null;+ if (document.getElementById('al-roster-error') !== box) return;+ if (document.hidden) { scheduleRosterRetry(box); return; }+ retryRoster(box);+ }, wait);+}++function renderRosterError() {+ _rosterErrored = true;+ if (document.getElementById('al-roster-error')) return;+ const firstLoad = _cards.size === 0;+ if (firstLoad) grid.querySelectorAll('.al-skeleton').forEach((s) => s.remove());+ const box = document.createElement('div');+ box.id = 'al-roster-error';+ box.className = 'al-error';+ box.setAttribute('role', 'alert');+ box.innerHTML = `+<div class="al-error-icon" aria-hidden="true">⚠</div>+<h2>${firstLoad ? "Couldn't load the agent wall" : "Couldn't load more agents"}</h2>+<p>The live roster request didn't come back. Your connection or the roster API is briefly unavailable.${firstLoad ? '' : ' The agents already on the wall keep streaming.'}</p>+<div class="al-error-actions">+ <button type="button" class="al-error-retry">Try again</button>+ <a class="al-error-alt" href="/agents">Browse the agent directory</a>+</div>+<div class="al-error-next" aria-live="polite"></div>`;+ grid.appendChild(box);+ box.querySelector('.al-error-retry').addEventListener('click', () => retryRoster(box));+ scheduleRosterRetry(box);+}+async function loadMore() {- if (_loading || !_hasMore) return;+ if (_loading || !_hasMore || _rosterErrored) return;_loading = true;- const { agents, hasMore } = await fetchRosterPage();+ const { agents, hasMore, failed } = await fetchRosterPage();++ if (failed) {+ // Leave `_hasMore` alone so infinite scroll and the retry can try again.+ renderRosterError();+ _loading = false;+ return;+ }_hasMore = hasMore;+ clearRosterError();if (!_cards.size && !agents.length) {renderEmpty();diff --git a/src/api.js b/src/api.jsindex 682088b60..9c04eefea 100644--- a/src/api.js+++ b/src/api.js@@ -28,13 +28,38 @@ function routeOf(path) {.replace(/\/\d{4,}(?=\/|$)/g, '/:id');}+// Known session state for this tab: null = unknown, true/false = resolved.+// A CSRF token is bound to the session cookie (api/_lib/auth.js), so for a+// signed-out visitor the server has nothing to bind it to and answers 401.+// Asking anyway printed a red 401 in the console of every anonymous visitor on+// a public page that POSTs a read (the live agent wall's batch balance+// hydration, for one). Pages that already resolved the answer tell us via+// noteSession(); the token endpoint itself also teaches us.+let _sessionKnown = null;++/**+ * Record whether this visitor has a session, so anonymous public reads can skip+ * a CSRF pre-flight that could only 401. Pass the resolved answer from+ * /api/auth/me, which returns 200 with `{ user: null }` when signed out.+ *+ * Only `allowAnonymous` requests act on a `false` here, so a genuine mutation+ * always still fetches its token and can never be weakened by a stale reading.+ *+ * @param {boolean} hasSession+ */+export function noteSession(hasSession) {+ _sessionKnown = !!hasSession;+}+// Fetch a fresh single-use CSRF token for every mutation. Tokens are burned// on first use (api/_lib/csrf.js), so caching is unsafe when concurrent// mutations share the module — two callers that read the same cached token// race: the first succeeds, the second gets 403 csrf_invalid.async function freshCsrfToken() {const r = await fetch('/api/csrf-token', { credentials: 'include' });+ if (r.status === 401) { _sessionKnown = false; return null; }if (!r.ok) return null;+ _sessionKnown = true;const j = await r.json().catch(() => null);return j?.data?.token || null;}@@ -64,7 +89,11 @@ export async function apiFetch(path, options = {}) {const headers = new Headers(init.headers || {});const hasBearer = (headers.get('authorization') || '').startsWith('Bearer ');- if (!SAFE_METHODS.has(method) && !hasBearer) {+ // A known-anonymous caller on an endpoint that accepts anonymous reads has no+ // session for a token to bind to; skipping the pre-flight keeps a public page+ // console clean. Anything that is not `allowAnonymous` still asks, always.+ const skipCsrf = allowAnonymous && _sessionKnown === false;+ if (!SAFE_METHODS.has(method) && !hasBearer && !skipCsrf) {const token = await freshCsrfToken();if (token) headers.set('x-csrf-token', token);}