Skip to content

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.

fix(brain): land the reasoning surface, categories and bundles page work from this worktree

nirholasb50b78d5c92c
diff --git a/pages/bundles.html b/pages/bundles.html
index d0c3b280c..db3f4e9c7 100644
--- a/pages/bundles.html
+++ b/pages/bundles.html
@@ -90,7 +90,8 @@
.bd-skill-name { flex: 1 1 auto; min-width: 0; font-weight: 550; overflow-wrap: anywhere; }
.bd-skill-meta { flex: none; text-align: right; font-variant-numeric: tabular-nums; }
.bd-skill-price { display: block; font-weight: 600; color: var(--ink-bright, var(--ink)); }
- .bd-skill-sold { display: block; font-size: 0.74rem; color: var(--ink-dim); margin-top: 1px; }
+ .bd-skill-unit { display: block; font-size: 0.74rem; color: var(--ink-dim); margin-top: 1px; }
+ .bd-retry { margin-top: 12px; }
/* ── price panel ────────────────────────────────────────────────── */
.bd-pricebox { border: 1px solid var(--stroke); border-radius: 10px; padding: 14px; margin-bottom: 14px; background: color-mix(in srgb, var(--ink) 3%, transparent); }
@@ -317,7 +318,19 @@
// Number.MAX_SAFE_INTEGER on a 9-decimal mint, so scaling goes through
// BigInt and only the already-scaled result becomes a Number.
let decimals = 6;
- let symbol = '$THREE';
+ let symbol = '';
+
+ // A price is labelled with the token it is actually in. Only the mint this
+ // platform promotes has a ticker here; every other mint shows a truncated
+ // address rather than a guessed symbol, because labelling a price with the
+ // wrong coin is worse than showing no coin at all.
+ const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+ function mintSymbol(mint) {
+ if (!mint) return 'tokens';
+ if (mint === THREE_MINT) return '$THREE';
+ const s = String(mint);
+ return s.length > 12 ? s.slice(0, 4) + '…' + s.slice(-4) : s;
+ }
function fromAtomic(atomic) {
const neg = String(atomic).startsWith('-');
@@ -350,19 +363,23 @@
// ── boot ────────────────────────────────────────────────────────
async function boot() {
+ // GET /api/agents lists the caller's agents and answers 401 with no session.
+ // Its sibling /api/agents/me answers 200 with a SINGLE agent (auto-creating
+ // one) even for an anonymous visitor, so reading a list off it told every
+ // signed-out visitor they had no agents and hid the sign-in gate below.
let res;
try {
- res = await apiFetch('/api/agents/me', { allowAnonymous: true });
+ res = await apiFetch('/api/agents', { allowAnonymous: true });
} catch {
- return gate('Could not reach three.ws. Check your connection and <a href="/bundles">try again</a>.');
+ return gate('<b>Could not reach three.ws.</b> Your connection dropped before your agents loaded.', boot);
}
if (res.status === 401) {
return gate('<b>Sign in to build a bundle.</b> Bundles belong to an agent you own, so this page needs your account. <a href="/login?next=%2Fbundles">Sign in</a> or <a href="/register">create an account</a>.');
}
- if (!res.ok) return gate('Could not load your agents (HTTP ' + res.status + '). <a href="/bundles">Retry</a>.');
+ if (!res.ok) return gate('<b>Could not load your agents</b> (HTTP ' + res.status + ').', boot);
const body = await res.json().catch(() => null);
- agents = body?.data?.agents || body?.agents || (Array.isArray(body?.data) ? body.data : []) || [];
+ agents = Array.isArray(body?.agents) ? body.agents : [];
if (!agents.length) {
return gate('<b>You have no agents yet.</b> A bundle groups the skills of one agent, so make an agent and give it priced skills first. <a href="/create">Create an agent</a>.');
}
@@ -377,12 +394,34 @@
await selectAgent(agents[0].id);
}
- function gate(html) {
- $('bd-gate').innerHTML = html;
- show($('bd-gate'), true);
+ // A retry that re-runs the failed call beats a link back to this URL: the
+ // visitor keeps their scroll position and the page never reloads the world
+ // to recover from one dropped request.
+ function gate(html, retry) {
+ const el = $('bd-gate');
+ el.innerHTML = html;
+ el.classList.toggle('bd-note--error', !!retry);
+ if (retry) el.appendChild(retryButton(retry));
+ show(el, true);
show($('bd-builder'), false);
}
+ function retryButton(fn, label = 'Retry') {
+ const btn = document.createElement('button');
+ btn.type = 'button';
+ btn.className = 'bd-btn bd-btn--ghost bd-retry';
+ btn.textContent = label;
+ btn.addEventListener('click', () => {
+ btn.disabled = true;
+ btn.textContent = 'Retrying…';
+ Promise.resolve(fn()).finally(() => {
+ btn.disabled = false;
+ btn.textContent = label;
+ });
+ });
+ return btn;
+ }
+
const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
async function selectAgent(id) {
@@ -399,24 +438,46 @@
box.innerHTML = '<div class="bd-sk bd-sk-row"></div><div class="bd-sk bd-sk-row"></div><div class="bd-sk bd-sk-row"></div>';
show($('bd-skills-empty'), false);
- let rows = [];
+ // A failed request and an agent with no priced skills are different
+ // answers. Collapsing them into one empty state told a seller to go price
+ // skills they had already priced, so a failure keeps its own state and a
+ // retry that re-runs only this call.
+ let rows = null;
+ let failure = null;
try {
const res = await apiFetch('/api/agents/' + encodeURIComponent(agentId) + '/skills-pricing');
if (res.ok) {
const b = await res.json().catch(() => null);
- rows = b?.data?.prices || b?.prices || b?.data || [];
+ rows = b?.prices || b?.data?.prices || [];
+ } else {
+ failure = 'HTTP ' + res.status;
}
- } catch { rows = []; }
+ } catch {
+ failure = 'the request never got a response';
+ }
+
+ if (failure) {
+ box.innerHTML = '';
+ const note = $('bd-skills-empty');
+ note.classList.add('bd-note--error');
+ note.innerHTML = '<b>Could not load this agent’s skills</b> (' + esc(failure) + '). Nothing is missing on your side.';
+ note.appendChild(retryButton(loadSkills));
+ show(note, true);
+ renderPricing();
+ return;
+ }
priced = (Array.isArray(rows) ? rows : []).filter((r) => r && (r.is_active === undefined || r.is_active) && Number(r.amount) > 0);
if (priced.length) decimals = Number(priced[0].mint_decimals ?? 6);
if (priced.length < 2) {
box.innerHTML = '';
- $('bd-skills-empty').innerHTML = priced.length
+ const note = $('bd-skills-empty');
+ note.classList.remove('bd-note--error');
+ note.innerHTML = priced.length
? '<b>This agent has one priced skill.</b> A bundle needs at least two. <a href="/marketplace">Price another skill</a> and come back.'
: '<b>This agent has no priced skills.</b> Set a price on two or more skills first, then bundle them. <a href="/marketplace">Open the marketplace</a>.';
- show($('bd-skills-empty'), true);
+ show(note, true);
renderPricing();
return;
}
@@ -428,6 +489,7 @@
'<span class="bd-skill-name">' + skill + '</span>' +
'<span class="bd-skill-meta">' +
'<span class="bd-skill-price">' + fmt(r.amount) + '</span>' +
+ '<span class="bd-skill-unit">' + esc(mintSymbol(r.currency_mint)) + '</span>' +
'</span>' +
'</label>';
}).join('');
@@ -497,6 +559,9 @@
if (!ready) return;
const h = pricing.history;
+ // Every amount in this panel is denominated in the mint the server priced
+ // against, not in whatever the platform's own coin happens to be.
+ symbol = mintSymbol(pricing.currency_mint);
$('bd-sum').textContent = fmt(pricing.sum_of_parts_atomic) + ' ' + symbol;
$('bd-unit').textContent = symbol;
@@ -631,19 +696,37 @@
list.innerHTML = '<div class="bd-sk" style="height:132px"></div><div class="bd-sk" style="height:132px"></div>';
show($('bd-list-empty'), false);
- let bundles = [];
+ let bundles = null;
+ let failure = null;
try {
const res = await apiFetch('/api/agents/' + encodeURIComponent(agentId) + '/bundles');
if (res.ok) {
const b = await res.json().catch(() => null);
bundles = b?.data?.bundles || [];
+ } else {
+ failure = 'HTTP ' + res.status;
}
- } catch { bundles = []; }
+ } catch {
+ failure = 'the request never got a response';
+ }
+
+ const note = $('bd-list-empty');
+ // "No bundles yet" is a claim about this agent. Only say it when the
+ // server actually answered; a dropped request gets its own retry instead.
+ if (failure) {
+ list.innerHTML = '';
+ note.classList.add('bd-note--error');
+ note.innerHTML = '<b>Could not load your published bundles</b> (' + esc(failure) + '). Anything already live is unaffected.';
+ note.appendChild(retryButton(loadBundles));
+ show(note, true);
+ return;
+ }
if (!bundles.length) {
list.innerHTML = '';
- $('bd-list-empty').innerHTML = '<b>No bundles yet.</b> Pick two skills above, set a price, and publish. Buyers will see it on this agent’s listing.';
- show($('bd-list-empty'), true);
+ note.classList.remove('bd-note--error');
+ note.innerHTML = '<b>No bundles yet.</b> Pick two skills above, set a price, and publish. Buyers will see it on this agent’s listing.';
+ show(note, true);
return;
}
@@ -654,7 +737,7 @@
(b.description ? '<p>' + esc(b.description) + '</p>' : '') +
'<div class="bd-chips">' + skills.map((s) => '<span class="bd-chip">' + esc(s) + '</span>').join('') + '</div>' +
'<div class="bd-bundle-foot">' +
- '<span class="bd-bundle-price">' + fmt(b.price_amount) + ' ' + symbol + '</span>' +
+ '<span class="bd-bundle-price">' + fmt(b.price_amount) + ' ' + esc(mintSymbol(b.currency_mint)) + '</span>' +
'<button type="button" class="bd-btn bd-btn--ghost" data-off="' + esc(b.id) + '">Deactivate</button>' +
'</div>' +
'</article>';
diff --git a/src/avatar-engines-data.js b/src/avatar-engines-data.js
index ad34c7112..dae258a21 100644
--- a/src/avatar-engines-data.js
+++ b/src/avatar-engines-data.js
@@ -506,7 +506,7 @@ export const ENGINES = Object.freeze([
blurb: 'Faces Learned with an Articulated Model and Expressions: the standard parametric head that drives the photoreal-head column.',
links: {
repo: 'https://github.com/Rubikplayer/flame-fitting',
- paper: 'https://ps.is.mpg.de/publications/flame-siggraph-asia-2017',
+ paper: 'https://download.is.tue.mpg.de/flame/flame_paper.pdf',
demo: 'https://flame.is.tue.mpg.de/',
},
},
diff --git a/src/brain.js b/src/brain.js
index 8f14923c7..38acf60ba 100644
--- a/src/brain.js
+++ b/src/brain.js
@@ -3,37 +3,53 @@
import { renderMarkdown } from './shared/markdown.js';
import { apiFetch } from './api.js';
-// ── Provider registry ────────────────────────────────────────────────────────
-const PROVIDERS = [
- { key: 'gpt-oss-120b', label: 'GPT-OSS 120B', short: 'GPT-OSS', network: 'OpenAI · OpenRouter', color: '#a5b4fc', ctx: '128K', tier: 'Default' },
- { key: 'claude-fable-5', label: 'Claude Fable 5', short: 'Fable 5', network: 'Anthropic', color: '#caa24f', ctx: '200K', tier: 'Flagship' },
- { key: 'claude-mythos-5', label: 'Claude Mythos 5', short: 'Mythos 5', network: 'Anthropic', color: '#b8923f', ctx: '200K', tier: 'Flagship' },
- { key: 'claude-opus-4-7', label: 'Claude Opus 4.7', short: 'Opus 4.7', network: 'Anthropic', color: '#c8a96e', ctx: '200K', tier: 'Flagship' },
- { key: 'claude-sonnet-4-6', label: 'Claude Sonnet 4.6', short: 'Sonnet 4.6', network: 'Anthropic', color: '#d4b87a', ctx: '200K', tier: 'Balanced' },
- { key: 'claude-haiku-4-5', label: 'Claude Haiku 4.5', short: 'Haiku 4.5', network: 'Anthropic', color: '#e0c88a', ctx: '200K', tier: 'Fast' },
- { key: 'gpt-5.6-sol', label: 'GPT-5.6 Sol', short: 'Sol', network: 'OpenAI', color: '#74c0fc', ctx: '1M', tier: 'Flagship' },
- { key: 'gpt-5.6-terra', label: 'GPT-5.6 Terra', short: 'Terra', network: 'OpenAI', color: '#82c6fc', ctx: '1M', tier: 'Balanced' },
- { key: 'gpt-5.6-luna', label: 'GPT-5.6 Luna', short: 'Luna', network: 'OpenAI', color: '#90ccfc', ctx: '1M', tier: 'Fast' },
- { key: 'gpt-5.5', label: 'GPT-5.5', short: 'GPT-5.5', network: 'OpenAI', color: '#6bb8f7', ctx: '1M', tier: 'Flagship' },
- { key: 'gpt-5.5-pro', label: 'GPT-5.5 Pro', short: '5.5 Pro', network: 'OpenAI', color: '#5fb0f2', ctx: '1M', tier: 'Pro' },
- { key: 'gpt-5.4', label: 'GPT-5.4', short: 'GPT-5.4', network: 'OpenAI', color: '#9cd2fd', ctx: '1M', tier: 'Balanced' },
- { key: 'gpt-5.4-pro', label: 'GPT-5.4 Pro', short: '5.4 Pro', network: 'OpenAI', color: '#57a8ee', ctx: '1M', tier: 'Pro' },
- { key: 'gpt-5.4-mini', label: 'GPT-5.4 mini', short: '5.4 mini', network: 'OpenAI', color: '#a8d8fe', ctx: '400K', tier: 'Fast' },
- { key: 'gpt-5.4-nano', label: 'GPT-5.4 nano', short: '5.4 nano', network: 'OpenAI', color: '#b4defe', ctx: '400K', tier: 'Fast' },
- { key: 'gpt-5.3-codex', label: 'GPT-5.3 Codex', short: 'Codex', network: 'OpenAI', color: '#4da0ea', ctx: '400K', tier: 'Coding' },
- { key: 'o3', label: 'o3', short: 'o3', network: 'OpenAI', color: '#c0e4ff', ctx: '200K', tier: 'Reasoning' },
- { key: 'o3-pro', label: 'o3-pro', short: 'o3-pro', network: 'OpenAI', color: '#cce9ff', ctx: '200K', tier: 'Reasoning' },
- { key: 'o3-mini', label: 'o3-mini', short: 'o3-mini', network: 'OpenAI', color: '#5cb0f4', ctx: '128K', tier: 'Reasoning' },
- { key: 'grok-4.5', label: 'Grok 4.5', short: 'Grok 4.5', network: 'xAI', color: '#e8e8e8', ctx: '500K', tier: 'Flagship' },
- { key: 'grok-4.3', label: 'Grok 4.3', short: 'Grok 4.3', network: 'xAI', color: '#d0d0d0', ctx: '1M', tier: 'Balanced' },
- { key: 'grok-4.1-fast', label: 'Grok 4.1 Fast', short: 'Grok Fast', network: 'xAI', color: '#bcbcbc', ctx: '2M', tier: 'Fast' },
- { key: 'groq-llama', label: 'Llama 3.3 70B', short: 'Llama 3.3', network: 'Groq', color: '#ff9a3c', ctx: '128K', tier: 'Fast' },
- { key: 'qwen-plus', label: 'Qwen Plus', short: 'Qwen+', network: 'DashScope', color: '#69db7c', ctx: '131K', tier: 'Balanced' },
- { key: 'modelscope-qwen', label: 'Qwen3-Coder 480B', short: 'Qwen3-Code', network: 'ModelScope', color: '#40c057', ctx: '32K', tier: 'Flagship' },
- { key: 'deepseek-r1', label: 'DeepSeek R1', short: 'DeepSeek', network: 'DeepSeek', color: '#888888', ctx: '64K', tier: 'Reasoning' },
- { key: 'ibm-granite', label: 'IBM Granite 3.8B', short: 'Granite', network: 'IBM watsonx.ai', color: '#0f62fe', ctx: '128K', tier: 'Balanced' },
-];
-const PMAP = new Map(PROVIDERS.map(p => [p.key, p]));
+// ── Provider roster ──────────────────────────────────────────────────────────
+// The roster is NOT declared here. GET /api/brain/chat is the only place that
+// knows which models this deployment can actually reach, and a second hardcoded
+// copy on the client drifts against it in both directions: models the server
+// added never appear in the picker, and keys the server dropped render as
+// selectable entries that 400 at send time. Everything below is presentation
+// applied to whatever that endpoint returns, with a fallback for every field so
+// a model added server-side shows up here without a client change.
+const NETWORK_COLORS = {
+ 'OpenAI · OpenRouter': '#a5b4fc',
+ 'Anthropic': '#caa24f',
+ 'OpenAI': '#74c0fc',
+ 'xAI': '#e8e8e8',
+ 'Groq': '#ff9a3c',
+ 'DashScope': '#69db7c',
+ 'ModelScope': '#40c057',
+ 'DeepSeek': '#888888',
+ 'IBM watsonx.ai': '#0f62fe',
+ 'NVIDIA NIM': '#76b900',
+};
+const UNKNOWN_NETWORK_COLOR = '#8a8a8a';
+
+// Preferred opening line-up, filtered against what the server reports as
+// available. Anything unavailable falls through to the first live model, so the
+// page never boots with a column that cannot answer.
+const DEFAULT_MODEL_KEYS = ['gpt-oss-120b', 'claude-sonnet-5', 'gpt-5.6-luna', 'groq-llama'];
+
+const PMAP = new Map();
+
+function decorateProvider(spec) {
+ return {
+ ...spec,
+ color: NETWORK_COLORS[spec.network] || UNKNOWN_NETWORK_COLOR,
+ // The network already reads off the colour and the tooltip, so the pill
+ // drops the redundant vendor prefix and keeps the part that identifies
+ // the model. Any label without that prefix passes through untouched.
+ short: String(spec.label || spec.key).replace(/^Claude\s+/, ''),
+ meta: [spec.network, spec.tier, spec.maxOutput ? `${spec.maxOutput} tok out` : '']
+ .filter(Boolean).join(' / '),
+ };
+}
+
+function providerTitle(p) {
+ const head = [p.label, p.network, p.tier].filter(Boolean).join(' · ');
+ if (!p.available) return `${head} (not configured on this deployment)`;
+ return p.description ? `${head}\n${p.description}` : head;
+}
// ── Archetype quick-picks ────────────────────────────────────────────────────
const ARCHETYPES = [
@@ -152,13 +168,19 @@ const state = {
authed: isAuthedHint(),
playMode: 'compare',
- focusKey: 'gpt-oss-120b',
- active: new Set(['gpt-oss-120b', 'groq-llama', 'claude-sonnet-4-6', 'gpt-5.6-luna']),
+ focusKey: '',
+ active: new Set(),
sessions: [],
currentId: null,
streaming: false,
agents: [],
- availableProviders: null, // set after API fetch; null = not yet loaded
+
+ // Roster lifecycle: 'loading' until GET /api/brain/chat answers, then
+ // 'ready' or 'error'. Every model control and the send button read this, so
+ // there is exactly one place that decides whether the page can be driven.
+ providerState: 'loading',
+ providerError: '',
+ selectionRestored: false,
};
// ── DOM helpers ──────────────────────────────────────────────────────────────
@@ -178,6 +200,7 @@ function persistSessions() { save('brain_sessions_v3', state.sessions); }
function loadSessions() { state.sessions = load('brain_sessions_v3') || []; }
function persistPersona() { save('brain_persona_v1', state.persona); }
function loadPersona() { state.persona = load('brain_persona_v1'); }
+function persistSelection() { save('brain_models_v1', { active: [...state.active], focusKey: state.focusKey }); }
// ── Toast ────────────────────────────────────────────────────────────────────
let toastTimer;
@@ -573,70 +596,115 @@ function renderSidebar() {
}
// ── Render: Playground toolbar ───────────────────────────────────────────────
-function isProviderAvailable(key) {
- if (!state.availableProviders) return true; // optimistic before load
- const found = state.availableProviders.find(p => p.key === key);
- return found ? found.available : false;
-}
-
function renderPlayControls() {
const ctrl = $('brPlayControls');
const label = $('brPlayLabel');
+
+ if (state.providerState === 'loading') {
+ label.textContent = 'Models';
+ ctrl.innerHTML = `<div class="br-play-status" role="status">
+ <span class="br-spin"></span>
+ <span>Loading models…</span>
+ </div>`;
+ return;
+ }
+
+ if (state.providerState === 'error') {
+ label.textContent = 'Models';
+ ctrl.innerHTML = `<div class="br-play-status br-play-status-error" role="alert">
+ <span>Model list unavailable: ${escHtml(state.providerError)}</span>
+ <button type="button" class="br-btn br-btn-secondary br-btn-sm" data-retry-providers>Retry</button>
+ </div>`;
+ return;
+ }
+
if (state.playMode === 'compare') {
label.textContent = 'Models';
ctrl.innerHTML = `<div class="br-provider-pills">${
- PROVIDERS.map(p => {
- const avail = isProviderAvailable(p.key);
+ [...PMAP.values()].map(p => {
const cls = [
'br-pill',
state.active.has(p.key) ? 'on' : '',
- !avail ? 'unavailable' : '',
+ !p.available ? 'unavailable' : '',
].filter(Boolean).join(' ');
- const title = avail ? '' : ` title="${p.label} — not configured on this deployment"`;
- return `<label class="${cls}" style="--pc:${p.color}" data-key="${p.key}"${title}>
+ return `<button type="button" class="${cls}" style="--pc:${p.color}" data-key="${escHtml(p.key)}"
+ aria-pressed="${state.active.has(p.key)}"${p.available ? '' : ' disabled'}
+ title="${escHtml(providerTitle(p))}">
<span class="br-pill-dot"></span>
- <span>${p.short}</span>
- ${!avail ? '<span class="br-pill-na" aria-hidden="true">✕</span>' : ''}
- </label>`;
+ <span>${escHtml(p.short)}</span>
+ ${p.available ? '' : '<span class="br-pill-na" aria-hidden="true">✕</span>'}
+ </button>`;
}).join('')
}</div>`;
} else {
label.textContent = 'Model';
- ctrl.innerHTML = `<select class="br-focus-sel" id="brFocusSel">${
- PROVIDERS.map(p => {
- const avail = isProviderAvailable(p.key);
- return `<option value="${p.key}"${p.key === state.focusKey ? ' selected' : ''}${!avail ? ' disabled' : ''}>${p.label}${avail ? '' : ' (unavailable)'}</option>`;
- }).join('')
+ ctrl.innerHTML = `<select class="br-focus-sel" id="brFocusSel" aria-label="Model">${
+ [...PMAP.values()].map(p =>
+ `<option value="${escHtml(p.key)}"${p.key === state.focusKey ? ' selected' : ''}${p.available ? '' : ' disabled'}>${escHtml(p.label)}${p.available ? '' : ' (unavailable)'}</option>`
+ ).join('')
}</select>`;
}
bindPlayControlEvents();
}
-async function fetchProviderAvailability() {
+// Restore the saved line-up once, then drop anything this deployment cannot
+// serve. Runs on every successful roster load, so a model that goes offline
+// between visits is dropped instead of failing on the next send.
+function reconcileSelection() {
+ const availableKeys = [...PMAP.values()].filter(p => p.available).map(p => p.key);
+ const live = new Set(availableKeys);
+
+ if (!state.selectionRestored) {
+ const saved = load('brain_models_v1');
+ if (Array.isArray(saved?.active)) state.active = new Set(saved.active);
+ if (typeof saved?.focusKey === 'string') state.focusKey = saved.focusKey;
+ state.selectionRestored = true;
+ }
+
+ for (const key of [...state.active]) if (!live.has(key)) state.active.delete(key);
+ if (!state.active.size) {
+ for (const key of DEFAULT_MODEL_KEYS) if (live.has(key)) state.active.add(key);
+ }
+ if (!state.active.size && availableKeys.length) state.active.add(availableKeys[0]);
+ if (!live.has(state.focusKey)) state.focusKey = [...state.active][0] || availableKeys[0] || '';
+ persistSelection();
+}
+
+async function fetchProviderRoster() {
+ state.providerState = 'loading';
+ state.providerError = '';
+ renderPlayControls();
+ renderCanvas();
+ updateSendAvailability();
+
try {
- const r = await fetch('/api/brain/chat', { method: 'GET' });
- if (!r.ok) return;
- const data = await r.json();
- if (Array.isArray(data.providers)) {
- state.availableProviders = data.providers;
- for (const key of [...state.active]) {
- const found = data.providers.find(p => p.key === key);
- if (found && !found.available) state.active.delete(key);
- }
- if (state.active.size === 0) {
- const first = data.providers.find(p => p.available);
- if (first) state.active.add(first.key);
- }
- const focusAvail = data.providers.find(p => p.key === state.focusKey);
- if (!focusAvail || !focusAvail.available) {
- const first = data.providers.find(p => p.available);
- if (first) state.focusKey = first.key;
- }
- renderPlayControls();
- }
- } catch {
- // Non-fatal — providers just show as all-available
+ const res = await fetch('/api/brain/chat', { headers: { accept: 'application/json' } });
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
+ const data = await res.json();
+ const providers = Array.isArray(data.providers) ? data.providers.filter(p => p?.key) : [];
+ if (!providers.length) throw new Error('no models returned');
+
+ PMAP.clear();
+ for (const spec of providers) PMAP.set(spec.key, decorateProvider(spec));
+ state.providerState = 'ready';
+ reconcileSelection();
+ } catch (err) {
+ state.providerState = 'error';
+ state.providerError = err.message || 'network error';
}
+
+ renderPlayControls();
+ renderCanvas();
+ updateSendAvailability();
+}
+
+// One place decides whether a prompt can be sent, so the button never invites a
+// click that can only fail.
+function updateSendAvailability() {
+ const send = $('brSend');
+ const ready = state.providerState === 'ready';
+ send.disabled = !ready || state.streaming;
+ send.title = ready ? '' : 'Waiting for the model list';
}
// ── Render: Compare canvas ───────────────────────────────────────────────────
@@ -652,8 +720,8 @@ function renderCompareCanvas() {
<div class="br-col" data-col="${escHtml(key)}" style="--pc:${p.color}">
<div class="br-col-head">
<div>
- <div class="br-col-name">${escHtml(p.short)}</div>
- <div class="br-col-meta">${escHtml(p.network)} / ${escHtml(p.ctx)} / ${escHtml(p.tier)}</div>
+ <div class="br-col-name" title="${escHtml(providerTitle(p))}">${escHtml(p.short)}</div>
+ <div class="br-col-meta">${escHtml(p.meta)}</div>
</div>
<div style="display:flex;gap:6px;align-items:center">
<div class="br-col-stats" data-stats="${escHtml(key)}"></div>
@@ -725,7 +793,33 @@ function renderChatCanvas() {
</div>`;
}
+// Until the roster resolves there is no honest column to draw, so the canvas
+// owns the loading and failure states rather than rendering an empty grid that
+// looks ready and answers nothing.
+function renderRosterState() {
+ const canvas = $('brCanvas');
+ if (state.providerState === 'loading') {
+ canvas.innerHTML = `
+ <div class="br-canvas-state" role="status">
+ <span class="br-spin"></span>
+ <p>Loading the model roster…</p>
+ </div>`;
+ return true;
+ }
+ if (state.providerState === 'error') {
+ canvas.innerHTML = `
+ <div class="br-canvas-state br-canvas-state-error" role="alert">
+ <h3>Model list unavailable</h3>
+ <p>The playground could not reach the model service (${escHtml(state.providerError)}), so no prompt can be sent yet. Your sessions and persona are safe in this browser.</p>
+ <button type="button" class="br-btn br-btn-primary br-btn-sm" data-retry-providers>Try again</button>
+ </div>`;
+ return true;
+ }
+ return false;
+}
+
function renderCanvas() {
+ if (renderRosterState()) return;
if (state.playMode === 'compare') renderCompareCanvas();
else renderChatCanvas();
}
@@ -815,8 +909,14 @@ async function sendMessage() {
const promptEl = $('brPrompt');
const text = promptEl.value.trim();
if (!text || state.streaming) return;
+ if (state.providerState !== 'ready') {
+ showNotice(state.providerState === 'error'
+ ? 'The model list failed to load. Retry it before sending.'
+ : 'Still loading the model list. One moment.');
+ return;
+ }
- const activeKeys = state.playMode === 'compare' ? [...state.active] : [state.focusKey];
+ const activeKeys = (state.playMode === 'compare' ? [...state.active] : [state.focusKey]).filter(Boolean);
if (!activeKeys.length) { showNotice('Select at least one model.'); return; }
const system = getEffectiveSystemPrompt();
@@ -838,7 +938,7 @@ async function sendMessage() {
renderSidebar();
state.streaming = true;
- $('brSend').disabled = true;
+ updateSendAvailability();
renderCanvas();
if (state.playMode === 'compare') activeKeys.forEach(scrollColToBottom);
@@ -934,7 +1034,7 @@ async function sendMessage() {
}));
state.streaming = false;
- $('brSend').disabled = false;
+ updateSendAvailability();
}
// ── Export ────────────────────────────────────────────────────────────────────
diff --git a/src/categories.js b/src/categories.js
index 4b7b10669..6882f9275 100644
--- a/src/categories.js
+++ b/src/categories.js
@@ -1,7 +1,11 @@
-// /categories — crypto sector leaderboard, styled after the /coins markets
-// index: a couple of summary stat cards up top, then a sortable table of every
-// CoinGecko category ranked by market cap with its top-3 coin icons, 24h move,
-// and 24h volume. Consumes /api/coin/categories.
+// /categories: crypto sector leaderboard, styled after the /coins markets
+// index. A couple of summary stat cards up top, then a searchable, sortable
+// table of every CoinGecko category ranked by market cap with its top-3 coin
+// icons, 24h move, and 24h volume. Consumes /api/coin/categories.
+//
+// The upstream returns ~750 categories. Rendering all of them at once meant
+// ~2,250 lazy <img> nodes on first paint, so the table pages in PAGE_SIZE rows
+// at a time and the search box narrows the set before you ever need to page.
import { formatUsd, formatPercent, escapeHtml as esc } from './shared/coin-format.js';
@@ -25,6 +29,17 @@ const ICONS = {
bars: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 3v18h18"/><path d="M18 17V9"/><path d="M13 17V5"/><path d="M8 17v-3"/></svg>',
};
+const statsGrid = (inner) =>
+ `<div style="display:grid;gap:1rem;grid-template-columns:repeat(auto-fit,minmax(200px,1fr))">${inner}</div>`;
+
+// The cards land in the same beat as the table rows, so they get the same
+// skeleton treatment rather than popping in from an empty strip.
+function statSkeletons() {
+ return statsGrid(
+ Array.from({ length: 3 }, () => '<div class="cv-skel" style="height:6.25rem"></div>').join(''),
+ );
+}
+
function statCard({ label, value, delta, deltaClass, icon }) {
return `
<div class="cv-stat-card">
@@ -41,7 +56,7 @@ function renderStats() {
const el = $('cat-stats');
const cats = state.categories;
if (!cats.length) {
- el.innerHTML = '';
+ el.innerHTML = state.status === 'loading' ? statSkeletons() : '';
return;
}
// Categories overlap (a coin sits in many), so a summed market cap would
@@ -71,7 +86,7 @@ function renderStats() {
icon: 'trend',
}),
];
- el.innerHTML = `<div style="display:grid;gap:1rem;grid-template-columns:repeat(auto-fit,minmax(200px,1fr))">${cards.join('')}</div>`;
+ el.innerHTML = statsGrid(cards.join(''));
}
// ── Category table ────────────────────────────────────────────────────────────
@@ -84,7 +99,16 @@ const COLUMNS = [
{ key: 'volume_24h', label: 'Volume (24h)', hide: 'hide-md', num: true },
];
-const state = { categories: [], sortKey: 'rank', sortDir: 'asc' };
+const PAGE_SIZE = 50;
+
+const state = {
+ categories: [],
+ sortKey: 'rank',
+ sortDir: 'asc',
+ query: '',
+ shown: PAGE_SIZE,
+ status: 'loading', // loading | ready | error
+};
function pctCell(v) {
if (v == null) return '<td class="pct dim">—</td>';
@@ -109,8 +133,13 @@ function sortValue(c, key) {
return c[key] ?? -Infinity;
}
-function sortedCategories() {
- const copy = [...state.categories];
+function matchesQuery(c, q) {
+ return c.name.toLowerCase().includes(q) || c.id.toLowerCase().includes(q);
+}
+
+function visibleCategories() {
+ const q = state.query.trim().toLowerCase();
+ const copy = q ? state.categories.filter((c) => matchesQuery(c, q)) : [...state.categories];
const { sortKey, sortDir } = state;
copy.sort((a, b) => {
const va = sortValue(a, sortKey);
@@ -121,21 +150,61 @@ function sortedCategories() {
return copy;
}
-function renderTable() {
- const el = $('cat-table');
+function skeletonRows() {
+ return (
+ '<div class="cv-table-wrap" style="padding:0.75rem">' +
+ Array.from(
+ { length: 12 },
+ () => '<div class="cv-skel" style="height:2.5rem;margin:0.375rem 0"></div>',
+ ).join('') +
+ '</div>'
+ );
+}
+
+// The three no-rows outcomes are different problems and get different copy:
+// a failed fetch is retryable here, an upstream that returned nothing is not
+// the user's doing, and a search that matched nothing is fixed by clearing it.
+function renderPlaceholder(el) {
+ if (state.status === 'loading') {
+ el.innerHTML = skeletonRows();
+ return true;
+ }
+ if (state.status === 'error') {
+ el.innerHTML =
+ '<div class="cv-empty">Category data could not be loaded. The market data provider did not answer. <button type="button" class="cv-linkbtn" data-act="retry">Try again</button>.</div>';
+ return true;
+ }
if (!state.categories.length) {
el.innerHTML =
- '<div class="cv-empty">Category data is temporarily unavailable. Please try again shortly.</div>';
+ '<div class="cv-empty">No categories are being reported right now. <button type="button" class="cv-linkbtn" data-act="retry">Refresh</button> to check again.</div>';
+ return true;
+ }
+ return false;
+}
+
+function renderTable() {
+ const el = $('cat-table');
+ if (renderPlaceholder(el)) {
+ bindActions(el);
return;
}
+ const matches = visibleCategories();
+ if (!matches.length) {
+ el.innerHTML = `<div class="cv-empty">No category matches “${esc(state.query.trim())}”. <button type="button" class="cv-linkbtn" data-act="clear">Clear the search</button> to see all ${state.categories.length.toLocaleString('en-US')}.</div>`;
+ bindActions(el);
+ return;
+ }
+
+ const page = matches.slice(0, state.shown);
const head = COLUMNS.map((col) => {
const active = col.key === state.sortKey;
const arrow = active ? (state.sortDir === 'asc' ? '↑' : '↓') : '↕';
- return `<th scope="col" tabindex="0" data-key="${col.key}" class="${col.left ? 'left' : ''} ${col.hide || ''}"${active ? ` aria-sort="${state.sortDir === 'asc' ? 'ascending' : 'descending'}"` : ''}>${esc(col.label)}<span class="arrow" aria-hidden="true">${arrow}</span></th>`;
+ const sort = active ? (state.sortDir === 'asc' ? 'ascending' : 'descending') : 'none';
+ return `<th scope="col" tabindex="0" data-key="${col.key}" aria-sort="${sort}" class="${col.left ? 'left' : ''} ${col.hide || ''}">${esc(col.label)}<span class="arrow" aria-hidden="true">${arrow}</span></th>`;
}).join('');
- const rows = sortedCategories()
+ const rows = page
.map((c) => {
const href = `/category/${encodeURIComponent(c.id)}`;
return `
@@ -152,13 +221,20 @@ function renderTable() {
})
.join('');
+ const remaining = matches.length - page.length;
+ const more = remaining
+ ? `<button type="button" class="cv-load-more" data-act="more">Show ${Math.min(PAGE_SIZE, remaining).toLocaleString('en-US')} more (${remaining.toLocaleString('en-US')} left)</button>`
+ : '';
+
el.innerHTML = `
<div class="cv-table-wrap">
<table class="cv-table">
+ <caption class="cv-sr-only">Crypto categories ranked by market cap, showing ${page.length} of ${matches.length}</caption>
<thead><tr>${head}</tr></thead>
<tbody>${rows}</tbody>
</table>
- </div>`;
+ </div>
+ ${more}`;
el.querySelectorAll('th[data-key]').forEach((th) => {
const activate = () => {
@@ -170,6 +246,9 @@ function renderTable() {
state.sortDir = key === 'name' || key === 'rank' ? 'asc' : 'desc';
}
renderTable();
+ // The header this came from is a fresh node after the re-render, so
+ // keyboard users would otherwise be dropped back to the document.
+ $('cat-table')?.querySelector(`th[data-key="${key}"]`)?.focus();
};
th.addEventListener('click', activate);
th.addEventListener('keydown', (e) => {
@@ -186,30 +265,95 @@ function renderTable() {
location.href = tr.dataset.href;
});
});
+
+ bindActions(el);
+ renderCount(matches.length);
+}
+
+function bindActions(el) {
+ el.querySelector('[data-act="retry"]')?.addEventListener('click', () => loadCategories());
+ el.querySelector('[data-act="clear"]')?.addEventListener('click', () => {
+ const input = $('cat-search-input');
+ if (input) input.value = '';
+ setQuery('');
+ input?.focus();
+ });
+ el.querySelector('[data-act="more"]')?.addEventListener('click', () => {
+ state.shown += PAGE_SIZE;
+ renderTable();
+ // Land focus on the first newly revealed row so the keyboard path
+ // continues where the button was instead of at the top of the table.
+ $('cat-table')
+ ?.querySelectorAll('tbody tr')
+ [state.shown - PAGE_SIZE]?.querySelector('a')
+ ?.focus();
+ });
+}
+
+// ── Search ────────────────────────────────────────────────────────────────────
+
+function renderCount(shownTotal) {
+ const el = $('cat-count');
+ if (!el) return;
+ const total = state.categories.length;
+ const visible = Math.min(state.shown, shownTotal);
+ el.textContent = state.query.trim()
+ ? `${shownTotal.toLocaleString('en-US')} of ${total.toLocaleString('en-US')} categories match`
+ : `Showing ${visible.toLocaleString('en-US')} of ${total.toLocaleString('en-US')} categories`;
+}
+
+function setQuery(value) {
+ state.query = value;
+ state.shown = PAGE_SIZE;
+ renderTable();
+ if (!visibleCategories().length) renderCount(0);
+}
+
+function wireSearch() {
+ const input = $('cat-search-input');
+ if (!input) return;
+ let timer = 0;
+ input.addEventListener('input', () => {
+ clearTimeout(timer);
+ timer = setTimeout(() => setQuery(input.value), 120);
+ });
+ input.addEventListener('keydown', (e) => {
+ if (e.key === 'Escape' && input.value) {
+ e.preventDefault();
+ input.value = '';
+ setQuery('');
+ }
+ });
}
// ── Load ──────────────────────────────────────────────────────────────────────
async function loadCategories() {
- const el = $('cat-table');
- el.innerHTML =
- '<div class="cv-table-wrap" style="padding:0.75rem">' +
- Array.from(
- { length: 12 },
- () => '<div class="cv-skel" style="height:2.5rem;margin:0.375rem 0"></div>',
- ).join('') +
- '</div>';
+ state.status = 'loading';
+ state.shown = PAGE_SIZE;
+ $('cat-updated').textContent = '';
+ renderStats();
+ renderTable();
try {
const { categories } = await getJson('/api/coin/categories');
// The endpoint returns market-cap-desc order; that ordinal is the rank.
state.categories = (categories || []).map((c, i) => ({ ...c, rank: i + 1 }));
+ state.status = 'ready';
$('cat-updated').textContent = `Updated ${new Date().toLocaleTimeString('en-US')}`;
} catch {
state.categories = [];
+ state.status = 'error';
$('cat-updated').textContent = '';
}
+ const search = $('cat-search');
+ if (search) search.hidden = state.status !== 'ready' || !state.categories.length;
renderStats();
renderTable();
+ if (state.status !== 'ready' || !state.categories.length) {
+ const count = $('cat-count');
+ if (count) count.textContent = '';
+ }
}
+wireSearch();
loadCategories();