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(swarms,flow-map): land the swarm dashboard and money-flow work from this worktree
nirholasc306e9ccc0e5
diff --git a/docs/money-flow-map.md b/docs/money-flow-map.mdindex cf230ffca..9687b43f2 100644--- a/docs/money-flow-map.md+++ b/docs/money-flow-map.md@@ -169,6 +169,14 @@ Two fields worth reading before you trust a number:Cached for 60s server-side; the page refreshes every 60s and stops pollingentirely in a hidden tab.+That background refresh never covers the drawn map. The timestamp beside the+controls reports the re-read while it is out, and if it fails, the last good+graph stays on screen with the failure named there rather than being replaced by+an error panel. Switching window is the opposite case, because it throws the+drawn topology away: that one takes the loading state, and it cancels any read+still in flight, so a slow earlier window can never land on top of a newer one+and draw a graph the buttons disagree with.+---## Reading the pagediff --git a/src/flow-map.css b/src/flow-map.cssindex a6572bbc2..766e08a1e 100644--- a/src/flow-map.css+++ b/src/flow-map.css@@ -249,6 +249,17 @@ body {font-variant-numeric: tabular-nums;}+/* A background re-read never covers the map, so the stamp is where it is+ reported: brighter while the request is out, and coloured when the last one+ failed and the graph on screen is therefore older than it looks. */+.fm-stamp[data-state='busy'] {+ color: var(--fm-dim);+}++.fm-stamp[data-state='stale'] {+ color: var(--fm-sink);+}+/* Label text that only assistive tech needs. Defined here because the sharedstylesheets do not ship a screen-reader utility class. */.fm-wrap .sr-only {@@ -788,6 +799,12 @@ body {.fm-below {margin-top: 22px;display: grid;+ /* Explicit minmax(0, 1fr) rather than the implicit single column: a grid item+ defaults to min-width:auto, so the table's own min-width pushed both+ sections past the viewport on a phone. The page clips horizontal overflow,+ so the services grid and the whole wallet table were cut off with no way to+ scroll to them. Constrained here, .fm-table-shell scrolls its own table. */+ grid-template-columns: minmax(0, 1fr);gap: 18px;}diff --git a/src/flow-map.js b/src/flow-map.jsindex 96c17c1ba..96bbead7d 100644--- a/src/flow-map.js+++ b/src/flow-map.js@@ -26,6 +26,10 @@ import {const $ = (sel) => document.querySelector(sel);const REFRESH_MS = 60_000;const ROLE_IDS = ['source', 'hub', 'relay', 'sink', 'quiet'];+// Narrowest first, so "the next window that could hold more" is just the next+// entry. The order has to match the buttons in the markup.+const WINDOWS = ['24h', '7d', '30d', '90d'];+const WINDOW_LABELS = { '24h': '24 hours', '7d': '7 days', '30d': '30 days', '90d': '90 days' };const state = {raw: null,@@ -45,26 +49,63 @@ const state = {timer: 0,paused: false,reduceMotion: false,+ refreshing: false,+ staleError: '',+ loadId: 0,+ inflight: null,};// ── data ─────────────────────────────────────────────────────────────────────-async function load() {- setOverlay('loading');+/**+ * Fetch the graph for the current window.+ *+ * `replace` distinguishes the two reasons this runs, because they want opposite+ * treatment on screen. Switching window (or the very first load, or a retry) is+ * about to throw the drawn topology away, so it takes the overlay. The 60s poll+ * is not: covering a live map with a spinner every minute would make the page+ * look like it is failing when it is working. That one only marks the stamp.+ *+ * Every call takes a ticket. A slower earlier response landing after a newer one+ * would otherwise draw a window the visitor is no longer looking at, under a+ * button that says something else, which is the one lie a live map cannot tell.+ */+async function load({ replace = true } = {}) {+ const id = (state.loadId += 1);+ state.inflight?.abort();+ const controller = new AbortController();+ state.inflight = controller;++ if (replace || !state.raw) setOverlay('loading');+ else { state.refreshing = true; stamp(); }+try {const r = await fetch(`/api/pulse?view=graph&window=${encodeURIComponent(state.window)}`, {headers: { accept: 'application/json' },+ signal: controller.signal,});if (!r.ok) throw new Error(`HTTP ${r.status}`);const body = await r.json();+ if (id !== state.loadId) return;if (!body?.data) throw new Error('malformed response');state.raw = annotate(body.data);- state.error = null;+ state.refreshing = false;+ state.staleError = '';applyFilters({ relayout: true });stamp();} catch (err) {- state.error = err;- setOverlay('error', err);+ if (err?.name === 'AbortError' || id !== state.loadId) return;+ state.refreshing = false;+ // A background refresh that fails must not blank a map that is still+ // perfectly readable: keep the last good graph and say so on the stamp.+ if (!replace && state.raw) {+ state.staleError = err?.message || 'request failed';+ stamp();+ } else {+ setOverlay('error', err);+ }+ } finally {+ if (id === state.loadId) state.inflight = null;}}@@ -95,6 +136,17 @@ function applyFilters({ relayout = false } = {}) {draw();}+/** True when the visitor narrowed the view themselves, so an empty result is+ * something they can undo rather than something the economy did. */+function hasFilters() {+ return Boolean(state.query) || state.kind !== 'all' || state.roles.size !== ROLE_IDS.length;+}++/** The next window that can only contain more than the current one, if any. */+function widerWindow() {+ return WINDOWS[WINDOWS.indexOf(state.window) + 1] || null;+}+/** Hide whole roles, then drop any edge that lost an end. */function dropRoles(graph, roles) {const kept = new Set(graph.nodes.filter((n) => roles.has(n.role)).map((n) => n.id));@@ -157,11 +209,21 @@ function sizeCanvas() {ctx.setTransform(dpr, 0, 0, dpr, 0, 0);}-const cssVar = (name) => getComputedStyle(document.documentElement).getPointerVar- ? ''- : getComputedStyle(document.documentElement).getPropertyValue(name).trim();--const roleColor = (role) => cssVar(`--fm-${role}`) || '#888';+// Every colour the canvas paints, resolved ONCE per frame. Reading a custom+// property is a style lookup, and the draw loop asks for one per edge and two+// per node: on a 400-route graph that was tens of thousands of forced style+// resolutions a second, for six values that cannot change mid-frame. Resolving+// per frame also means a theme switch is picked up on the very next paint with+// no cache to invalidate.+const PALETTE_ROLES = ['source', 'hub', 'relay', 'sink', 'quiet'];++function readPalette() {+ const cs = getComputedStyle(document.documentElement);+ const read = (name) => cs.getPropertyValue(name).trim();+ const out = { accent: read('--fm-accent') || '#888', ink: read('--fm-canvas-ink') || '255, 255, 255' };+ for (const role of PALETTE_ROLES) out[role] = read(`--fm-${role}`) || '#888';+ return out;+}function toScreen(p) {const { x, y, scale } = state.transform;@@ -177,9 +239,9 @@ function draw(now = performance.now()) {ctx.clearRect(0, 0, w, h);const { scale } = state.transform;- const nodesById = new Map(state.view.nodes.map((n) => [n.id, n]));const focus = state.hovered || state.selected;const neighbours = focus ? neighboursOf(focus) : null;+ const palette = readPalette();const maxEdgeUsd = Math.max(0, ...state.view.edges.map((e) => e.usd || 0));@@ -194,9 +256,7 @@ function draw(now = performance.now()) {ctx.save();ctx.globalAlpha = dim ? 0.06 : 0.34 + weight * 0.4;- ctx.strokeStyle = e.kinds?.includes('tip')- ? roleColor('sink')- : roleColor('hub');+ ctx.strokeStyle = e.kinds?.includes('tip') ? palette.sink : palette.hub;ctx.lineWidth = Math.max(0.7, (0.8 + weight * 2.6) * Math.min(1.4, scale));ctx.beginPath();ctx.moveTo(pa.x, pa.y);@@ -205,7 +265,7 @@ function draw(now = performance.now()) {ctx.restore();if (dim) continue;- drawParticles(ctx, pa, pb, e, weight, now);+ drawParticles(ctx, pa, pb, e, weight, now, palette);}const ordered = [...state.view.nodes].sort(@@ -217,7 +277,7 @@ function draw(now = performance.now()) {const s = toScreen(p);const r = (state.radii.get(n.id) || 10) * Math.min(1.5, Math.max(0.55, scale));const dim = focus && n.id !== focus && !neighbours?.has(n.id);- drawNode(ctx, n, s, r, dim, n.id === state.selected, n.id === state.hovered);+ drawNode(ctx, n, s, r, dim, n.id === state.selected, n.id === state.hovered, palette);}// Label only what can be read: at low zoom labels turn into noise.@@ -234,15 +294,15 @@ function draw(now = performance.now()) {const s = toScreen(p);const dim = focus && n.id !== focus && !neighbours?.has(n.id);ctx.globalAlpha = dim ? 0.12 : 0.82;- ctx.fillStyle = `rgb(${cssVar('--fm-canvas-ink') || '255,255,255'})`;+ ctx.fillStyle = `rgb(${palette.ink})`;ctx.fillText(truncate(n.name, 18), s.x, s.y + r + 5);}ctx.restore();}}-function drawNode(ctx, n, s, r, dim, selected, hovered) {- const color = roleColor(n.role || 'quiet');+function drawNode(ctx, n, s, r, dim, selected, hovered, palette) {+ const color = palette[n.role] || palette.quiet;ctx.save();ctx.globalAlpha = dim ? 0.16 : 1;@@ -291,7 +351,7 @@ function drawNode(ctx, n, s, r, dim, selected, hovered) {ctx.restore();}-function drawParticles(ctx, a, b, e, weight, now) {+function drawParticles(ctx, a, b, e, weight, now, palette) {if (state.reduceMotion || state.paused) return;const dx = b.x - a.x;const dy = b.y - a.y;@@ -302,7 +362,7 @@ function drawParticles(ctx, a, b, e, weight, now) {const count = Math.min(4, 1 + Math.floor(Math.log2(1 + (e.count || 1))));const speed = 0.00013 + weight * 0.00009;ctx.save();- ctx.fillStyle = e.kinds?.includes('tip') ? roleColor('sink') : roleColor('accent');+ ctx.fillStyle = e.kinds?.includes('tip') ? palette.sink : palette.accent;for (let i = 0; i < count; i += 1) {const t = ((now * speed) + i / count + hash01(e.from + e.to + i)) % 1;const x = a.x + dx * t;@@ -718,9 +778,14 @@ function renderTable() {const caption = $('#fm-table-caption');if (!body || !state.view) return;const nodes = [...state.view.nodes].sort((a, b) => b.throughput_usd - a.throughput_usd);+ // The caption is the table's own empty state, and it has to tell the same+ // story the overlay does: "no match" and "nothing happened" are different+ // answers, and only one of them is the visitor's to fix.caption.textContent = nodes.length? `Every wallet on the map, ranked by value handled. Selecting a row highlights it above. ${nodes.length} shown.`- : 'No wallets match the current filters.';+ : hasFilters()+ ? 'No wallets match the current filters.'+ : 'No settled transfers in this window, so there is nothing to list.';body.innerHTML = '';for (const n of nodes) {@@ -812,25 +877,34 @@ function setOverlay(kind, err) {btn.type = 'button';btn.className = 'fm-btn';btn.textContent = 'Try again';- btn.addEventListener('click', load);+ btn.addEventListener('click', () => load({ replace: true }));overlay.append(h2, p, btn);return;}- const filtered = state.query || state.kind !== 'all' || state.roles.size !== ROLE_IDS.length;+ const filtered = hasFilters();+ const wider = widerWindow();h2.textContent = filtered ? 'Nothing matches those filters' : 'No settled flow in this window';p.textContent = filtered? 'Widen the window, clear the search, or turn a role back on.'- : 'Every edge here is a real on-chain transfer between agent wallets, so a quiet platform draws an empty map rather than a fabricated one. Try a longer window.';+ : wider+ ? 'Every edge here is a real on-chain transfer between agent wallets, so a quiet platform draws an empty map rather than a fabricated one. Try a longer window.'+ : 'Every edge here is a real on-chain transfer between agent wallets, so a quiet platform draws an empty map rather than a fabricated one. Nothing has settled in the longest window we keep, so the next transfer will appear here on its own.';+ overlay.append(h2, p);++ // An action is only offered when it can change the outcome: a "Show 90 days"+ // button on the 90-day window is a control that does nothing, which is worse+ // than no control at all.+ if (!filtered && !wider) return;const btn = document.createElement('button');btn.type = 'button';btn.className = 'fm-btn';- btn.textContent = filtered ? 'Clear filters' : 'Show 90 days';+ btn.textContent = filtered ? 'Clear filters' : `Show ${WINDOW_LABELS[wider]}`;btn.addEventListener('click', () => {if (filtered) resetFilters();- else setWindow('90d');+ else setWindow(wider);});- overlay.append(h2, p, btn);+ overlay.append(btn);}function stamp() {@@ -838,7 +912,10 @@ function stamp() {if (!el || !state.raw) return;const bits = [`updated ${relTime(state.raw.generated_at)}`];if (state.raw.truncated) bits.push(`top ${state.raw.max_edges} routes`);+ if (state.refreshing) bits.push('refreshing…');+ else if (state.staleError) bits.push(`refresh failed (${state.staleError}), showing the last good read`);el.textContent = bits.join(' · ');+ el.dataset.state = state.refreshing ? 'busy' : state.staleError ? 'stale' : '';const note = $('#fm-truncated');if (note) {note.hidden = !state.raw.truncated;@@ -855,7 +932,9 @@ function setWindow(w) {for (const b of document.querySelectorAll('[data-window]')) {b.setAttribute('aria-pressed', String(b.dataset.window === w));}- load();+ // A window switch replaces the topology outright, so the overlay is honest+ // here in a way it would not be for a background refresh.+ load({ replace: true });}function resetFilters() {@@ -863,6 +942,7 @@ function resetFilters() {state.kind = 'all';state.roles = new Set(ROLE_IDS);$('#fm-q').value = '';+ $('#fm-q-clear').hidden = true;for (const b of document.querySelectorAll('[data-kind]')) {b.setAttribute('aria-pressed', String(b.dataset.kind === 'all'));}@@ -914,7 +994,9 @@ function bindControls() {applyFilters({ relayout: true });});- $('#fm-refresh').addEventListener('click', load);+ // Refresh re-reads the window the visitor is already looking at, so the map+ // stays on screen and the stamp reports the round trip.+ $('#fm-refresh').addEventListener('click', () => load({ replace: false }));const pause = $('#fm-pause');pause.addEventListener('click', () => {state.paused = !state.paused;@@ -924,10 +1006,11 @@ function bindControls() {});document.addEventListener('keydown', (ev) => {- if (ev.target.matches('input, textarea')) return;+ const el = ev.target;+ if (el instanceof Element && el.closest('input, textarea, select, [contenteditable="true"]')) return;if (ev.key === '/') { ev.preventDefault(); q.focus(); }if (ev.key === 'Escape') select(null);- if (ev.key === 'r' && !ev.metaKey && !ev.ctrlKey) load();+ if (ev.key === 'r' && !ev.metaKey && !ev.ctrlKey && !ev.altKey) load({ replace: false });});}@@ -952,20 +1035,21 @@ function boot() {// Polling stops entirely in a hidden tab: this is an RPC-backed read and an// ops page left open all day should not keep paying for nobody.+ const poll = () => { if (!state.paused) load({ replace: false }); };document.addEventListener('visibilitychange', () => {if (document.hidden) {clearInterval(state.timer);state.timer = 0;} else if (!state.timer) {- state.timer = setInterval(() => { if (!state.paused) load(); }, REFRESH_MS);- load();+ state.timer = setInterval(poll, REFRESH_MS);+ poll();}});- state.timer = setInterval(() => { if (!state.paused) load(); }, REFRESH_MS);+ state.timer = setInterval(poll, REFRESH_MS);setInterval(stamp, 15_000);if (!state.reduceMotion) state.raf = requestAnimationFrame(tick);- load();+ load({ replace: true });}if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', boot);diff --git a/src/swarms.css b/src/swarms.cssindex 1e16d8acc..9ec68e157 100644--- a/src/swarms.css+++ b/src/swarms.css@@ -12,6 +12,11 @@ body {padding: var(--space-xl) var(--space-lg) var(--space-2xl);min-height: 70vh;}+/* Below ~360px the lg inline padding costs more than a fifth of the viewport, which+ is what pushed the card grid past the right edge on a 320px phone. */+@media (max-width: 420px) {+ .sw-shell { padding-inline: var(--space-md); }+}/* ── hero ─────────────────────────────────────────────────────────────────── */.sw-hero {@@ -58,7 +63,9 @@ body {background var(--duration-fast) var(--ease-standard), border-color var(--duration-fast);display: inline-flex;align-items: center;+ justify-content: center;gap: var(--space-2xs);+ text-decoration: none; /* the class is also worn by anchors (sign-in, create agent) */}.sw-btn:hover { background: var(--surface-3); transform: translateY(-1px); }.sw-btn:active { transform: translateY(0); }@@ -96,11 +103,15 @@ body {cursor: pointer;transition: color var(--duration-fast), background var(--duration-fast);}+.sw-seg button:hover { color: var(--ink); background: var(--surface-2); }+.sw-seg button:focus-visible { outline: 2px solid var(--wallet-accent); outline-offset: -2px; }.sw-seg button[aria-pressed='true'] { background: var(--surface-3); color: var(--ink-bright); }.sw-grid {display: grid;- grid-template-columns: repeat(auto-fill, minmax(310px, 1fr));+ /* min() so the track collapses with the viewport instead of forcing a fixed 310px+ column (and a clipped card) inside a narrower container. */+ grid-template-columns: repeat(auto-fill, minmax(min(310px, 100%), 1fr));gap: var(--space-md);}.sw-card {@@ -151,13 +162,16 @@ body {.sw-back:hover { color: var(--ink); }.sw-dash-head { display: flex; flex-wrap: wrap; gap: var(--space-md); align-items: flex-start; justify-content: space-between; margin-bottom: var(--space-lg); }-.sw-dash-head h1 { margin: 0 0 var(--space-3xs); font-size: var(--text-xl); color: var(--ink-bright); }+/* The status pill sits beside the heading, not inside it: a screen reader announcing+ the h1 should read the swarm's name, not "Test Funding". */+.sw-dash-title { display: flex; align-items: center; flex-wrap: wrap; gap: var(--space-xs); margin-bottom: var(--space-3xs); }+.sw-dash-head h1 { margin: 0; font-size: var(--text-xl); color: var(--ink-bright); overflow-wrap: anywhere; }.sw-live { display: inline-flex; align-items: center; gap: var(--space-2xs); font-size: var(--text-2xs); color: var(--ink-faint); text-transform: uppercase; letter-spacing: 0.05em; }.sw-live .dot { width: 7px; height: 7px; border-radius: 50%; background: var(--ink-faint); }.sw-live[data-state='live'] .dot { background: var(--success); box-shadow: 0 0 0 3px rgba(74, 222, 128, 0.18); }.sw-live[data-state='live'] { color: var(--success); }-.sw-tiles { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: var(--space-sm); margin-bottom: var(--space-lg); }+.sw-tiles { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(150px, 100%), 1fr)); gap: var(--space-sm); margin-bottom: var(--space-lg); }.sw-tile { padding: var(--space-md); border: 1px solid var(--stroke); border-radius: var(--radius-lg); background: var(--surface-1); }/* Directional flash when a live value moves: green up, red down, then settle. */.sw-tile--up { animation: sw-tile-up 0.9s ease-out; }@@ -175,8 +189,11 @@ body {.sw-tile a { color: var(--wallet-accent); text-decoration: none; font-size: var(--text-sm); }.sw-tile a:hover { text-decoration: underline; }-.sw-cols { display: grid; grid-template-columns: 1.1fr 1fr; gap: var(--space-lg); align-items: start; }-@media (max-width: 880px) { .sw-cols { grid-template-columns: 1fr; } }+/* minmax(0, …) rather than a bare fr: an fr track floors at its content's min-content+ width, and the panel rows' min-content held the column open ~70px past a 320px+ viewport, clipping every panel's right edge. */+.sw-cols { display: grid; grid-template-columns: minmax(0, 1.1fr) minmax(0, 1fr); gap: var(--space-lg); align-items: start; }+@media (max-width: 880px) { .sw-cols { grid-template-columns: minmax(0, 1fr); } }.sw-panel { border: 1px solid var(--stroke); border-radius: var(--radius-lg); background: var(--surface-1); overflow: hidden; margin-bottom: var(--space-lg); }.sw-panel-h { display: flex; justify-content: space-between; align-items: center; padding: var(--space-sm) var(--space-md); border-bottom: 1px solid var(--stroke); }@@ -184,7 +201,7 @@ body {.sw-panel-h .count { font-size: var(--text-2xs); color: var(--ink-faint); }.sw-panel-body { max-height: 420px; overflow-y: auto; }-.sw-row { display: flex; align-items: center; gap: var(--space-sm); padding: var(--space-xs) var(--space-md); border-bottom: 1px solid var(--surface-1); font-size: var(--text-sm); }+.sw-row { display: flex; align-items: center; gap: var(--space-sm); padding: var(--space-xs) var(--space-md); border-bottom: 1px solid var(--surface-1); font-size: var(--text-sm); min-width: 0; overflow-wrap: anywhere; }.sw-row:last-child { border-bottom: 0; }.sw-row .grow { flex: 1; min-width: 0; }.sw-row .mono { font-variant-numeric: tabular-nums; }@@ -252,7 +269,8 @@ body {.sw-member.sw-win { animation: none; }}-.sw-vote { padding: var(--space-sm) var(--space-md); border-bottom: 1px solid var(--surface-1); font-size: var(--text-sm); }+.sw-vote { padding: var(--space-sm) var(--space-md); border-bottom: 1px solid var(--surface-1); font-size: var(--text-sm); min-width: 0; overflow-wrap: anywhere; }+.sw-vote-top .name { min-width: 0; }.sw-vote:last-child { border-bottom: 0; }.sw-vote-top { display: flex; align-items: center; gap: var(--space-xs); }.sw-vote .verdict { font-size: var(--text-2xs); font-weight: 700; text-transform: uppercase; padding: 1px 6px; border-radius: var(--radius-pill); }@@ -328,7 +346,8 @@ body {background: var(--surface-1); border: 1px solid var(--stroke); border-radius: var(--radius-md); color: var(--ink);}.sw-field input:focus, .sw-field select:focus, .sw-field textarea:focus { outline: none; border-color: var(--wallet-accent); }-.sw-grid2 { display: grid; grid-template-columns: 1fr 1fr; gap: var(--space-sm); }+.sw-grid2 { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: var(--space-sm); }+@media (max-width: 460px) { .sw-grid2 { grid-template-columns: minmax(0, 1fr); } }.sw-modal-actions { display: flex; justify-content: flex-end; gap: var(--space-sm); margin-top: var(--space-md); }.sw-modal-err { color: var(--danger); font-size: var(--text-sm); margin-top: var(--space-xs); min-height: 1.2em; }@@ -337,6 +356,12 @@ body {.sw-msg h3 { color: var(--ink); font-size: var(--text-lg); margin: 0 0 var(--space-xs); }.sw-msg p { margin: 0 auto var(--space-md); max-width: 44ch; line-height: 1.5; }.sw-skel { border: 1px solid var(--stroke); border-radius: var(--radius-lg); height: 168px; background: linear-gradient(100deg, var(--surface-1) 30%, var(--surface-3) 50%, var(--surface-1) 70%); background-size: 200% 100%; animation: swShimmer 1.4s ease infinite; }+/* The dashboard is not a card grid, so its placeholder mirrors the real layout+ (header strip, tile row, two panels) instead of stacking card-shaped blocks. */+.sw-dash-skel { display: grid; gap: var(--space-md); }+.sw-dash-skel .sw-skel { height: 64px; }+.sw-dash-skel .sw-skel--tiles { height: 92px; }+.sw-dash-skel .sw-skel--panel { height: 220px; }@keyframes swShimmer { from { background-position: 200% 0; } to { background-position: -200% 0; } }@media (prefers-reduced-motion: reduce) { .sw-skel { animation: none; } .sw-card:hover { transform: none; } }diff --git a/src/swarms.js b/src/swarms.jsindex 86fcb3cdf..106c01a2b 100644--- a/src/swarms.js+++ b/src/swarms.js@@ -14,7 +14,7 @@ const PCT = (n) => (n == null ? '—' : `${(Number(n) * 100).toFixed(0)}%`);const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));const short = (a) => (a ? `${a.slice(0, 4)}…${a.slice(-4)}` : '');-const state = { network: 'mainnet', agents: null, authed: false };+const state = { agents: null, authed: false };// Single-use CSRF token for a state-changing call. Never cached: the server// consumes the token in the same statement that validates it, so a reused one is@@ -30,6 +30,17 @@ async function csrfToken() {}}+// The platform error envelope is { error: <machine code>, error_description: <sentence> }.+// Reading `error` first surfaced raw codes to the user: a missing swarm read+// "not_found" and a rejected contribution read "bad_agent", so the human sentence the+// API already sends never reached the screen. Prefer the sentence, in the order the+// handlers actually populate it, and only fall back to the code when there is none.+function errorText(data, status) {+ const pick = [data?.error_description, data?.message, data?.error?.message, typeof data?.error === 'string' ? data.error : null]+ .find((v) => typeof v === 'string' && v.trim());+ return pick ? pick.trim() : `Request failed (HTTP ${status}).`;+}+async function api(path, opts = {}) {const ctrl = new AbortController();const to = setTimeout(() => ctrl.abort(), opts.timeout || 20000);@@ -43,7 +54,7 @@ async function api(path, opts = {}) {}const res = await fetch(path, { credentials: 'include', signal: ctrl.signal, ...opts, headers });const data = await res.json().catch(() => null);- return { ok: res.ok, status: res.status, data: data?.data ?? data, error: res.ok ? null : data?.message || data?.error || `HTTP ${res.status}` };+ return { ok: res.ok, status: res.status, data: data?.data ?? data, error: res.ok ? null : errorText(data, res.status) };} catch (e) {return { ok: false, status: 0, data: null, error: e?.name === 'AbortError' ? 'request timed out' : 'network error' };} finally {@@ -54,31 +65,71 @@ async function api(path, opts = {}) {function toast(msg, isErr = false) {const t = document.createElement('div');t.className = 'sw-toast' + (isErr ? ' err' : '');+ // Errors interrupt, confirmations wait their turn; either way the toast is the only+ // feedback some actions give, so it has to reach a screen reader.+ t.setAttribute('role', isErr ? 'alert' : 'status');t.textContent = msg;document.body.appendChild(t);setTimeout(() => { t.style.opacity = '0'; t.style.transition = 'opacity .3s'; setTimeout(() => t.remove(), 300); }, isErr ? 5200 : 3400);}-async function loadAgents() {- if (state.agents) return state.agents;- const r = await api('/api/agents');- const list = Array.isArray(r.data) ? r.data : Array.isArray(r.data?.agents) ? r.data.agents : [];- state.agents = list.map((a) => ({ id: a.id, name: a.name || 'Agent' }));- state.authed = r.ok;- return state.agents;+// The in-flight promise is cached, not just the result: boot and the dashboard's+// action bar both need the agent list, and without this they raced into two+// identical reads on every dashboard open.+let agentsPromise = null;+function loadAgents() {+ if (state.agents) return Promise.resolve(state.agents);+ if (agentsPromise) return agentsPromise;+ // /api/auth/me answers 200 with a null user for a signed-out visitor, while+ // /api/agents answers 401. Asking the former first keeps a page that reads+ // perfectly well anonymously from logging a console error on every visit, and+ // skips a request whose answer is already known.+ agentsPromise = api('/api/auth/me').then(async (me) => {+ state.authed = Boolean(me.ok && (me.data?.user || me.data?.id));+ if (!state.authed) return (state.agents = []);+ const r = await api('/api/agents');+ const list = Array.isArray(r.data) ? r.data : Array.isArray(r.data?.agents) ? r.data.agents : [];+ state.authed = r.ok;+ return (state.agents = list.map((a) => ({ id: a.id, name: a.name || 'Agent' })));+ }).finally(() => { agentsPromise = null; });+ return agentsPromise;}// ── router ────────────────────────────────────────────────────────────────────--function currentId() {- return new URL(location.href).searchParams.get('id');-}-function goto(id) {+//+// Everything that decides what the page shows (which swarm, which network, whose+// swarms) lives in the query string, so every view is linkable, survives a reload,+// and answers the back button. Scope used to be click-only state with no way back to+// the public list once you opened "My swarms".++const params = () => new URL(location.href).searchParams;+const currentId = () => params().get('id');+const currentNetwork = () => (params().get('network') === 'devnet' ? 'devnet' : 'mainnet');+const currentScope = () => (params().get('scope') === 'mine' ? 'mine' : 'all');++// Build the URL this page would have with `patch` applied; null clears a key.+function hrefWith(patch) {const u = new URL(location.href);- if (id) u.searchParams.set('id', id); else u.searchParams.delete('id');- history.pushState({}, '', u);+ for (const [k, v] of Object.entries(patch)) {+ if (v == null || v === '') u.searchParams.delete(k);+ else u.searchParams.set(k, String(v));+ }+ const q = u.searchParams.toString();+ return u.pathname + (q ? `?${q}` : '');+}++// Navigating between swarms pushes history; flipping a filter replaces it, so the+// back button steps between views rather than through every toggle.+function navigate(patch, { replace = false } = {}) {+ const href = hrefWith(patch);+ if (href === location.pathname + location.search) return;+ history[replace ? 'replaceState' : 'pushState']({}, '', href);render();}++const goto = (id) => navigate({ id });+const isPlainClick = (e) => e.button === 0 && !e.metaKey && !e.ctrlKey && !e.shiftKey && !e.altKey;+window.addEventListener('popstate', render);function render() {@@ -90,65 +141,98 @@ function render() {// ── directory ──────────────────────────────────────────────────────────────────async function renderDirectory() {+ const net = currentNetwork();+ const scope = currentScope();root.innerHTML = `<section class="sw-hero"><div><h1>Trading Swarms</h1>- <p>Pool capital with other agents into one auditable on-chain treasury. The swarm only fires when enough of its members' verified track record agrees — and pays realized profit back to every member pro-rata.</p>+ <p>Pool capital with other agents into one auditable on-chain treasury. The swarm only fires when enough of its members' verified track record agrees, and pays realized profit back to every member pro-rata.</p></div><div class="sw-hero-actions"><button class="sw-btn sw-btn--primary" id="sw-create">+ Create a swarm</button></div></section><div class="sw-toolbar">- <div class="sw-seg" role="tablist" aria-label="Network">- <button data-net="mainnet" aria-pressed="${state.network === 'mainnet'}">Mainnet</button>- <button data-net="devnet" aria-pressed="${state.network === 'devnet'}">Devnet</button>+ <div class="sw-seg" role="group" aria-label="Which swarms to show">+ <button data-scope="all" aria-pressed="${scope === 'all'}">All swarms</button>+ <button data-scope="mine" aria-pressed="${scope === 'mine'}">My swarms</button>+ </div>+ <div class="sw-seg" role="group" aria-label="Network">+ <button data-net="mainnet" aria-pressed="${net === 'mainnet'}">Mainnet</button>+ <button data-net="devnet" aria-pressed="${net === 'devnet'}">Devnet</button></div>- <button class="sw-btn sw-btn--ghost sw-btn--sm" id="sw-mine">My swarms</button></div><div id="sw-list" class="sw-grid" aria-busy="true">${skeletons(6)}</div>`;document.getElementById('sw-create').onclick = openCreateModal;root.querySelectorAll('[data-net]').forEach((b) => {- b.onclick = () => { state.network = b.dataset.net; renderDirectory(); };+ b.onclick = () => navigate({ network: b.dataset.net === 'devnet' ? 'devnet' : null }, { replace: true });+ });+ root.querySelectorAll('[data-scope]').forEach((b) => {+ b.onclick = () => navigate({ scope: b.dataset.scope === 'mine' ? 'mine' : null }, { replace: true });});- document.getElementById('sw-mine').onclick = () => loadList(true);- loadList(false);+ loadList();}function skeletons(n) {return Array.from({ length: n }, () => '<div class="sw-skel"></div>').join('');}-async function loadList(mine) {+// Every list read carries a generation. A slower earlier request (the public list+// still in flight when the visitor switches to "My swarms") used to land last and+// overwrite the newer result, so the toolbar and the grid disagreed.+let listGen = 0;++async function loadList() {+ const gen = ++listGen;const listEl = document.getElementById('sw-list');if (!listEl) return;+ const mine = currentScope() === 'mine';+ const network = currentNetwork();listEl.setAttribute('aria-busy', 'true');listEl.innerHTML = skeletons(6);- const path = mine ? `/api/swarms?mine=1&network=${state.network}` : `/api/swarms?network=${state.network}`;- const r = await api(path);+ // A signed-out visitor's "my swarms" read can only ever 401, so resolve the session+ // first and answer from what we already know instead of spending a round trip on a+ // guaranteed rejection. The 401 branch below still covers a session that expired+ // between this check and the read.+ if (mine) await loadAgents();+ const r = state.authed || !mine+ ? await api(`/api/swarms?${mine ? 'mine=1&' : ''}network=${network}`)+ : { ok: false, status: 401, data: null, error: 'sign in required' };+ if (gen !== listGen || !listEl.isConnected) return; // superseded by a newer readlistEl.setAttribute('aria-busy', 'false');if (!r.ok && r.status === 401 && mine) {- listEl.innerHTML = msg('Sign in to see your swarms', 'Your swarms — ones you created or funded — appear here once you sign in.');+ listEl.innerHTML = msg('Sign in to see your swarms', 'Swarms you created or funded appear here once you sign in.', 'Sign in', () => { location.href = loginHref(); });return;}if (!r.ok) {- listEl.innerHTML = msg('Couldn’t load swarms', esc(r.error || 'Something went wrong.'), 'Retry', () => loadList(mine));+ listEl.innerHTML = msg('Couldn’t load swarms', esc(r.error || 'Something went wrong.'), 'Retry', () => loadList());return;}const swarms = Array.isArray(r.data) ? r.data : [];if (!swarms.length) {listEl.innerHTML = mine? msg('No swarms yet', 'You haven’t created or joined a swarm. Start one and invite agents to pool capital.', 'Create a swarm', openCreateModal)- : msg('No open swarms yet', 'Be the first — create a swarm, set its consensus policy, and invite other agents to fund the treasury.', 'Create a swarm', openCreateModal);+ : msg(`No open swarms on ${network} yet`, 'Be the first: create a swarm, set its consensus policy, and invite other agents to fund the treasury.', 'Create a swarm', openCreateModal);return;}listEl.innerHTML = swarms.map(cardHTML).join('');listEl.querySelectorAll('[data-swarm]').forEach((c) => {- c.onclick = () => goto(c.dataset.swarm);- c.onkeydown = (e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); goto(c.dataset.swarm); } };+ // The card is a real link, so cmd/middle-click opens the swarm in a new tab and+ // the browser shows its target on hover. Only a plain click is intercepted, and+ // the re-render is deferred out of the dispatch: rewriting root.innerHTML from+ // inside the handler detaches the anchor that is still being dispatched on.+ // data-no-transition on the markup is what lets this handler run at all: the+ // site-wide view-transition listener in src/view-transitions.js captures internal+ // link clicks at the document level, ahead of any per-page handler, and would+ // otherwise turn each directory click into a full page load.+ c.onclick = (e) => {+ if (!isPlainClick(e)) return;+ e.preventDefault();+ queueMicrotask(() => goto(c.dataset.swarm));+ };});}@@ -162,7 +246,7 @@ function cardHTML(s) {const pnlCls = s.realized_pnl_sol > 0 ? 'pos' : s.realized_pnl_sol < 0 ? 'neg' : '';const wr = s.win_rate == null ? '—' : `${Math.round(s.win_rate * 100)}%`;return `- <a class="sw-card" tabindex="0" role="button" data-swarm="${esc(s.id)}" aria-label="Open ${esc(s.name)}">+ <a class="sw-card" href="${esc(hrefWith({ id: s.id }))}" data-no-transition="1" data-swarm="${esc(s.id)}" aria-label="Open ${esc(s.name)}"><div class="sw-card-top"><h3 class="sw-card-name">${esc(s.name)}</h3>${statusPill(s.status)}@@ -195,35 +279,56 @@ function closeStream() {if (activeStream) { try { activeStream.close(); } catch {} activeStream = null; }}+let dashGen = 0;+async function renderDashboard(id) {closeStream();- root.innerHTML = `<a class="sw-back" id="sw-back" href="/swarms">← All swarms</a><div id="sw-dash" aria-busy="true">${skeletons(3)}</div>`;- document.getElementById('sw-back').onclick = (e) => { e.preventDefault(); goto(null); };+ const gen = ++dashGen;+ root.innerHTML = `<a class="sw-back" id="sw-back" href="${esc(hrefWith({ id: null }))}" data-no-transition="1">← All swarms</a>+ <div id="sw-dash" aria-busy="true">${dashSkeleton()}</div>`;+ document.getElementById('sw-back').onclick = (e) => {+ if (!isPlainClick(e)) return;+ e.preventDefault();+ queueMicrotask(() => goto(null));+ };const r = await api(`/api/swarms/${id}`);const dash = document.getElementById('sw-dash');- if (!dash) return;+ if (gen !== dashGen || !dash) return; // the visitor moved on before this landeddash.setAttribute('aria-busy', 'false');if (!r.ok) {- dash.innerHTML = msg('Swarm not found', esc(r.error || 'This swarm doesn’t exist or was removed.'), 'Back to directory', () => goto(null));+ const [title, body] = r.status === 404+ ? ['Swarm not found', 'This swarm doesn’t exist, or it was removed.']+ : ['Couldn’t load this swarm', r.error || 'Something went wrong.'];+ dash.innerHTML = msg(title, esc(body), r.status === 404 ? 'Back to directory' : 'Retry',+ r.status === 404 ? () => goto(null) : () => renderDashboard(id));return;}paintDashboard(dash, r.data);subscribeStream(id);}+// Mirrors the real dashboard's shape (title strip, tile row, two panels) so the load+// does not reflow from a stack of card-sized blocks into a different layout.+function dashSkeleton() {+ return `<div class="sw-dash-skel">+ <div class="sw-skel"></div>+ <div class="sw-skel sw-skel--tiles"></div>+ <div class="sw-skel sw-skel--panel"></div>+ </div>`;+}+function paintDashboard(dash, s) {const sw = s.swarm;const pol = s.policy;const tr = s.treasury;const rec = s.track_record;- const member = s.viewer_member;const pnlCls = rec.realized_pnl_sol > 0 ? 'pos' : rec.realized_pnl_sol < 0 ? 'neg' : '';dash.innerHTML = `<div class="sw-dash-head"><div>- <h1>${esc(sw.name)} ${statusPill(sw.status)}</h1>+ <div class="sw-dash-title"><h1>${esc(sw.name)}</h1>${statusPill(sw.status)}</div>${sw.description ? `<p class="muted" style="color:var(--ink-dim);max-width:60ch;margin:.2rem 0 0">${esc(sw.description)}</p>` : ''}${sw.status === 'killed' && sw.kill_reason ? `<p style="color:var(--danger);font-size:var(--text-sm);margin:.4rem 0 0">Killed: ${esc(sw.kill_reason)}</p>` : ''}</div>@@ -325,7 +430,7 @@ function positionsHTML(positions) {const cls = pnl > 0 ? 'pos' : pnl < 0 ? 'neg' : '';const link = (closed ? p.sell_url : p.buy_url);return `<div class="sw-row">- <div class="grow"><span class="name">${esc(p.symbol || short(p.mint))}</span> <span class="muted" style="font-size:var(--text-2xs)">${closed ? esc(p.exit_reason || 'closed') : p.status}</span></div>+ <div class="grow"><span class="name">${esc(p.symbol || short(p.mint))}</span> <span class="muted" style="font-size:var(--text-2xs)">${esc(closed ? p.exit_reason || 'closed' : p.status)}</span></div><div class="mono" style="text-align:right">${closed ? `<span class="${cls}">${pnl >= 0 ? '+' : ''}${SOL(pnl)}</span>` : `<span class="muted">${SOL(p.current_sol)}</span>`}${link ? ` <a href="${esc(link)}" target="_blank" rel="noopener" class="muted">↗</a>` : ''}</div></div>`;}).join('');@@ -334,11 +439,12 @@ function positionsHTML(positions) {function voteRowHTML(v) {const pct = Math.min(100, (v.consensus || 0) * 100);const thr = Math.min(100, (v.min_consensus || 0) * 100);+ const fire = v.decision === 'fire';return `<div class="sw-vote"><div class="sw-vote-top">- <span class="verdict ${v.decision}">${v.decision === 'fire' ? '✓ fire' : 'skip'}</span>+ <span class="verdict ${fire ? 'fire' : 'skip'}">${fire ? '✓ fire' : 'skip'}</span><span class="name grow">${esc(v.mint ? short(v.mint) : '')}</span>- <span class="muted mono" style="font-size:var(--text-2xs)">${v.members_long}/${v.members_total} long</span>+ <span class="muted mono" style="font-size:var(--text-2xs)">${Number(v.members_long) || 0}/${Number(v.members_total) || 0} long</span></div><div class="meter"><div class="sw-meter-track"><div class="sw-meter-fill${v.decision === 'fire' ? ' fire' : ''}" style="width:${pct}%"></div><div class="sw-meter-thresh" style="left:${thr}%"></div></div>@@ -358,7 +464,7 @@ function payoutRowHTML(p) {const stCls = p.status === 'confirmed' ? 'pos' : p.status === 'failed' ? 'neg' : 'muted';return `<div class="sw-row"><div class="grow"><span class="name">${esc(kindLabel)}</span> <span class="muted" style="font-size:var(--text-2xs)">${p.share_bps != null ? (p.share_bps / 100).toFixed(1) + '%' : ''}</span></div>- <div class="mono" style="text-align:right"><span class="${p.kind === 'fee' ? 'muted' : 'pos'}">${SOL(p.amount_sol)}</span> <span class="${stCls}" style="font-size:var(--text-2xs)">${p.status}</span>${p.tx_url ? ` <a href="${esc(p.tx_url)}" target="_blank" rel="noopener" class="muted">↗</a>` : ''}</div>+ <div class="mono" style="text-align:right"><span class="${p.kind === 'fee' ? 'muted' : 'pos'}">${SOL(p.amount_sol)}</span> <span class="${stCls}" style="font-size:var(--text-2xs)">${esc(p.status)}</span>${p.tx_url ? ` <a href="${esc(p.tx_url)}" target="_blank" rel="noopener" class="muted">↗</a>` : ''}</div></div>`;}@@ -399,11 +505,35 @@ async function renderActions(s) {});}-function handleAction(act, s) {- if (!state.authed || !state.agents?.length) {- toast('Sign in and create an agent first', true);- return;+// A swarm action needs a session AND an agent to act through. Both used to dead-end+// in a toast that named the requirement but never offered the way to satisfy it.+const loginHref = () => `/login?next=${encodeURIComponent(location.pathname + location.search)}`;++function requireAccount(title, body, action, href) {+ const { close } = modal(`+ <h2>${esc(title)}</h2>+ <p class="sub">${esc(body)}</p>+ <div class="sw-modal-actions">+ <button class="sw-btn sw-btn--ghost" id="r-cancel">Not now</button>+ <a class="sw-btn sw-btn--primary" href="${esc(href)}">${esc(action)}</a>+ </div>`);+ document.getElementById('r-cancel').onclick = close;+}++function needsAccount() {+ if (!state.authed) {+ requireAccount('Sign in to act on a swarm', 'Joining, funding, and governing a swarm all move real SOL from an agent wallet, so they need a signed-in account.', 'Sign in', loginHref());+ return true;+ }+ if (!state.agents?.length) {+ requireAccount('Create an agent first', 'A swarm acts through one of your agents: its wallet funds the treasury and its track record carries your vote weight.', 'Create an agent', '/create');+ return true;}+ return false;+}++function handleAction(act, s) {+ if (needsAccount()) return;if (act === 'join' || act === 'contribute') return openContributeModal(s, act);if (act === 'exit') return openExitModal(s);if (act === 'kill') return openKillModal(s);@@ -420,15 +550,46 @@ async function doSimpleAction(action, swarmId, extra = {}) {// ── modals ─────────────────────────────────────────────────────────────────────+const FOCUSABLE = 'a[href], button:not(:disabled), input:not(:disabled), select:not(:disabled), textarea:not(:disabled), [tabindex]:not([tabindex="-1"])';+let dialogSeq = 0;++// aria-modal only tells assistive tech the rest of the page is inert; it does not move+// or hold the keyboard. Without the focus move, trap, and restore below, Tab walked+// straight out of an open dialog into the page behind it.function modal(html) {+ const opener = document.activeElement;const scrim = document.createElement('div');scrim.className = 'sw-scrim';- scrim.innerHTML = `<div class="sw-modal" role="dialog" aria-modal="true">${html}</div>`;+ scrim.innerHTML = `<div class="sw-modal" role="dialog" aria-modal="true" tabindex="-1">${html}</div>`;document.body.appendChild(scrim);+ const box = scrim.firstElementChild;++ const close = () => {+ scrim.remove();+ document.removeEventListener('keydown', onKey, true);+ if (opener && opener.isConnected && typeof opener.focus === 'function') opener.focus();+ };+ const onKey = (e) => {+ if (e.key === 'Escape') { e.preventDefault(); close(); return; }+ if (e.key !== 'Tab') return;+ const items = [...box.querySelectorAll(FOCUSABLE)].filter((el) => el.offsetParent !== null);+ if (!items.length) return;+ const first = items[0], last = items[items.length - 1];+ if (!box.contains(document.activeElement)) { e.preventDefault(); first.focus(); return; }+ if (e.shiftKey && document.activeElement === first) { e.preventDefault(); last.focus(); }+ else if (!e.shiftKey && document.activeElement === last) { e.preventDefault(); first.focus(); }+ };++ // Name the dialog from its own heading so it is announced as more than "dialog".+ const heading = box.querySelector('h2');+ if (heading) {+ heading.id = heading.id || `sw-dlg-${++dialogSeq}`;+ box.setAttribute('aria-labelledby', heading.id);+ }+scrim.addEventListener('click', (e) => { if (e.target === scrim) close(); });- const close = () => { scrim.remove(); document.removeEventListener('keydown', onKey); };- const onKey = (e) => { if (e.key === 'Escape') close(); };- document.addEventListener('keydown', onKey);+ document.addEventListener('keydown', onKey, true);+ (box.querySelector(FOCUSABLE) || box).focus();return { scrim, close };}@@ -438,8 +599,7 @@ function agentOptions() {async function openCreateModal() {await loadAgents();- if (!state.authed) { toast('Sign in to create a swarm', true); return; }- if (!state.agents.length) { toast('Create an agent first', true); return; }+ if (needsAccount()) return;const { close } = modal(`<h2>Create a trading swarm</h2><p class="sub">A dedicated custodial treasury wallet is provisioned on-chain. You set the consensus threshold and risk policy; members fund it with real SOL.</p>@@ -851,4 +1011,9 @@ window.addEventListener('beforeunload', closeStream);// ── boot ────────────────────────────────────────────────────────────────────────-loadAgents().finally(render);+// Paint first, resolve the session alongside. Gating the first render on the auth+// probe left the visitor staring at skeletons for a whole extra round trip, and+// nothing in the directory needs the agent list: the surfaces that do+// (renderActions, the modals) await loadAgents themselves.+loadAgents();+render();