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.

Enhance UI and functionality across various components

qbdzeeabab12fb64
diff --git a/api/_lib/swarms.js b/api/_lib/swarms.js
index 769a30ff7..5e455d0d7 100644
--- a/api/_lib/swarms.js
+++ b/api/_lib/swarms.js
@@ -849,13 +849,26 @@ export async function getSwarmState(swarmId, { viewerUserId = null } = {}) {
realized_pnl_sol: realizedPnl / LAMPORTS_PER_SOL,
open_positions: positions.filter((p) => ['open', 'opening', 'closing'].includes(p.status)).length,
},
- members: members.map((m) => ({
- id: m.id, agent_id: m.agent_id, name: m.agent_name,
- image: m.profile_image_url || m.avatar_url || null,
- contribution_sol: (Number(m.contribution_lamports) - Number(m.withdrawn_lamports)) / LAMPORTS_PER_SOL,
- share_bps: m.share_bps, reputation: m.reputation == null ? null : Number(m.reputation),
- status: m.status, is_creator: m.is_creator, joined_at: m.joined_at,
- })),
+ members: (() => {
+ // Vote weight is what consensus actually runs on: max(MIN_VOTE_WEIGHT, rep),
+ // summed over ACTIVE members only (exited members carry none). Surfacing each
+ // member's share of that total turns the abstract reputation score into the
+ // literal "how much of this swarm's vote do you control" number — same formula
+ // as computeConsensus, so the board can't drift from the engine.
+ const voteWeight = (m) => (m.status === 'active' ? Math.max(MIN_VOTE_WEIGHT, Number(m.reputation) || 0) : 0);
+ const totalVoteWeight = members.reduce((sum, m) => sum + voteWeight(m), 0);
+ return members.map((m) => {
+ const weight = voteWeight(m);
+ return {
+ id: m.id, agent_id: m.agent_id, name: m.agent_name,
+ image: m.profile_image_url || m.avatar_url || null,
+ contribution_sol: (Number(m.contribution_lamports) - Number(m.withdrawn_lamports)) / LAMPORTS_PER_SOL,
+ share_bps: m.share_bps, reputation: m.reputation == null ? null : Number(m.reputation),
+ vote_weight: weight, vote_power: totalVoteWeight > 0 ? weight / totalVoteWeight : 0,
+ status: m.status, is_creator: m.is_creator, joined_at: m.joined_at,
+ };
+ });
+ })(),
positions: positions.map((p) => ({
id: p.id, mint: p.mint, symbol: p.symbol, name: p.name, status: p.status, exit_reason: p.exit_reason,
entry_sol: sol(p.entry_quote_lamports), current_sol: sol(p.last_value_lamports),
diff --git a/api/agents/agent-trade.js b/api/agents/agent-trade.js
index f4ce13dc6..a2fdbdb1f 100644
--- a/api/agents/agent-trade.js
+++ b/api/agents/agent-trade.js
@@ -768,7 +768,24 @@ async function handleLimits(req, res, id) {
const { auth, meta } = owned;
if (req.method === 'GET') {
- return json(res, 200, { data: { limits: getTradeLimits(meta), defaults: TRADE_LIMIT_DEFAULTS } });
+ // Surface the live daily spend alongside the limits so the owner can see how
+ // much of the daily budget the agent has already burned (mainnet — the
+ // budget guard keys on the same window/network). Best-effort: a spend-query
+ // hiccup must never block reading the limits themselves.
+ const network = normNetwork(new URL(req.url, 'http://x').searchParams.get('network'));
+ let spentLamports = 0n;
+ try { spentLamports = await getDailySpendLamports(id, network); } catch { spentLamports = 0n; }
+ let spentUsd = null;
+ if (spentLamports > 0n) { try { spentUsd = await lamportsToUsd(spentLamports); } catch { spentUsd = null; } }
+ return json(res, 200, {
+ data: {
+ limits: getTradeLimits(meta),
+ defaults: TRADE_LIMIT_DEFAULTS,
+ spent_today_sol: Number(spentLamports) / 1e9,
+ spent_today_usd: spentUsd,
+ network,
+ },
+ });
}
// Relaxing the trade guard rails (per-trade cap, daily budget, kill-switch)
diff --git a/data/changelog.json b/data/changelog.json
index c7a0422ae..96ff46aa8 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -4,7 +4,7 @@
{
"date": "2026-06-30",
"title": "The swarm members panel is now a live standings board",
- "summary": "A swarm is a competition between its members, and the members list now reads like one. Members are ranked by stake — #1, #2, #3 — with the lead member marked by a token accent, and each member's reputation shows as a vote-weight chip that visibly grows with the score, because in a swarm your track record is literally your voting power. The moment the treasury fires a trade, the members who were on the winning side of that consensus pulse green — pulled straight from the real recorded vote breakdown, so you can see exactly who carried it. When someone contributes or exits, the share bars animate and the standings re-sort smoothly instead of snapping. Respects reduced-motion preferences.",
+ "summary": "A swarm is a competition between its members, and the members list now reads like one. Members are ranked by stake — #1, #2, #3 — with the lead member marked by a token accent, and each member's reputation shows as a vote-weight chip: the chip carries the reputation score with the exact share of the swarm's vote that score commands beneath it, so you can see your track record become voting power (computed the same way the consensus engine does). The moment the treasury fires a trade, the members who were on the winning side of that consensus pulse green — pulled straight from the real recorded vote breakdown, so you can see exactly who carried it. When someone contributes or exits, the share bars animate and the standings re-sort smoothly instead of snapping. Respects reduced-motion preferences.",
"tags": [
"improvement"
],
@@ -30,12 +30,12 @@
},
{
"date": "2026-06-30",
- "title": "Fixed the agent wallet page returning a 404",
- "summary": "Opening the agent wallet at /agent-wallet no longer hits a 404. The page was built and shipping, but the clean URL had no route, so it fell through to the not-found page. It now loads correctly and, when opened without a specific agent, shows a clear prompt to pick or create one.",
+ "title": "Fixed several pages returning a 404",
+ "summary": "A handful of pages were built and shipping but had no clean-URL route, so they fell through to the not-found page: the agent wallet (/agent-wallet), the viability report (/viability), and the gallery picker. All now load correctly. The agent wallet, when opened without a specific agent, also shows a clear prompt to pick or create one.",
"tags": [
"fix"
],
- "link": "/agent-wallet"
+ "link": "/viability"
},
{
"date": "2026-06-30",
diff --git a/packages/agent-sniper/bin/agent-sniper.js b/packages/agent-sniper/bin/agent-sniper.js
old mode 100644
new mode 100755
diff --git a/packages/agent-sniper/src/faces/api.js b/packages/agent-sniper/src/faces/api.js
index c029f1191..6f7dd4214 100644
--- a/packages/agent-sniper/src/faces/api.js
+++ b/packages/agent-sniper/src/faces/api.js
@@ -81,17 +81,29 @@ export async function createSniperApiRouter(deps = {}) {
solana: deps.payTo?.solana || process.env.X402_PAY_TO_SOLANA || null,
base: deps.payTo?.base || process.env.X402_PAY_TO_BASE || null,
};
+ // PayAI's Solana facilitator rejects an accept without a sponsor fee-payer, and
+ // paid() throws a 500 at challenge time if asked to advertise a Solana lane it
+ // can't honor. Resolve the fee-payer first so we can actually self-disable the
+ // Solana lane when it's absent — dropping to the Base lane (or the 503 guard)
+ // instead of 500-ing every paid request.
+ const feePayer = deps.feePayer || process.env.X402_FEE_PAYER_SOLANA || undefined;
+
const lanes = {};
- if (payTo.solana) lanes.solana = payTo.solana;
+ if (payTo.solana && feePayer) {
+ lanes.solana = payTo.solana;
+ } else if (payTo.solana && !feePayer) {
+ // eslint-disable-next-line no-console -- one-time boot warning, not per-request noise.
+ console.warn(
+ '[agent-sniper] X402_PAY_TO_SOLANA is set but X402_FEE_PAYER_SOLANA is not — ' +
+ 'the Solana lane needs a facilitator sponsor fee-payer and has been disabled. ' +
+ 'Set X402_FEE_PAYER_SOLANA to enable it; the Base lane (if configured) is unaffected.',
+ );
+ }
if (payTo.base) lanes.base = payTo.base;
const x402Configured = Object.keys(lanes).length > 0;
const prices = { ...DEFAULT_PRICES, ...(deps.prices || {}) };
const facilitator = deps.facilitatorUrl || process.env.X402_FACILITATOR_URL || undefined;
- // PayAI's Solana facilitator rejects an accept without a sponsor fee-payer.
- // Forward it from env when present; without it the Solana lane self-disables
- // to the Base lane (or the 503 guard) rather than erroring at challenge time.
- const feePayer = process.env.X402_FEE_PAYER_SOLANA || undefined;
const router = express.Router();
router.use(express.json({ limit: '64kb' }));
diff --git a/pages/agent-screen.html b/pages/agent-screen.html
index ce56d8fb4..596a8f407 100644
--- a/pages/agent-screen.html
+++ b/pages/agent-screen.html
@@ -890,7 +890,22 @@
.asc-typing i { animation: none; opacity: 0.6; }
}
- /* ── Live Avatar Forge controls ── */
+ /* ── Forge toggle: collapses the secondary avatar-forge bar by default ── */
+ .asc-task-forge-toggle {
+ flex: none; appearance: none; border: none; background: transparent;
+ color: rgba(255,255,255,0.45); border-radius: 8px; width: 30px; height: 30px;
+ display: flex; align-items: center; justify-content: center;
+ font-size: 0.95rem; line-height: 1; cursor: pointer;
+ transition: background 0.15s, color 0.15s, transform 0.1s;
+ }
+ .asc-task-forge-toggle:hover { background: rgba(255,255,255,0.1); color: #fff; }
+ .asc-task-forge-toggle:active { transform: scale(0.9); }
+ .asc-task-forge-toggle:focus-visible { outline: none; box-shadow: 0 0 0 2px rgba(255,255,255,0.4); }
+ .asc-task-forge-toggle[aria-pressed="true"] { color: var(--screen-accent); background: rgba(255,255,255,0.08); }
+
+ /* ── Live Avatar Forge controls (revealed by the ✦ toggle) ── */
+ .asc-task-bar:not(.forge-open) .asc-forge-form,
+ .asc-task-bar:not(.forge-open) .asc-forge-result { display: none; }
.asc-forge-form {
display: flex; align-items: center; gap: 0.5rem; margin-top: 0.3rem;
background: rgba(10,10,12,0.86); backdrop-filter: blur(14px);
@@ -1953,6 +1968,8 @@
/* ── Memory Diary panel (Task 17) ── */
.asc-panel--diary { width: 360px; }
+ /* Reputation packs many sections; scroll the body inside its capped height. */
+ #asc-reputation-body { overflow-y: auto; overscroll-behavior: contain; }
.asc-diary-body { padding: 0; }
.asc-diary {
position: relative;
diff --git a/pages/home.html b/pages/home.html
index 00317ef3f..1899ded09 100644
--- a/pages/home.html
+++ b/pages/home.html
@@ -6433,6 +6433,7 @@
</script>
<script type="module" src="/src/api-playground.js"></script>
<script type="module" src="/src/economy-ticker.js"></script>
+<script type="module" src="/src/home-sniper.js"></script>
<script type="module">
// "Pose it here" pulls Three.js + OrbitControls + the full mannequin rig —
// load it only when the section approaches the viewport. The module
diff --git a/pages/reasoning-ledger.html b/pages/reasoning-ledger.html
index ddf498504..698989438 100644
--- a/pages/reasoning-ledger.html
+++ b/pages/reasoning-ledger.html
@@ -30,6 +30,7 @@
<link rel="manifest" href="/site.webmanifest" />
<link rel="stylesheet" href="/fonts/fonts.css" />
<link rel="stylesheet" href="/nav.css" />
+ <link rel="stylesheet" href="/src/ui-juice.css" />
<link rel="stylesheet" href="/src/reasoning-ledger.css" />
<link rel="stylesheet" href="/footer.css" />
<meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1" />
diff --git a/src/agent-screen.js b/src/agent-screen.js
index da232b592..def9d0658 100644
--- a/src/agent-screen.js
+++ b/src/agent-screen.js
@@ -2316,6 +2316,15 @@ async function boot(id) {
const forgeResult = document.getElementById('asc-forge-result');
const forgeView = document.getElementById('asc-forge-view');
const forgeUse = document.getElementById('asc-forge-use');
+ const forgeToggle = document.getElementById('asc-forge-toggle');
+ const taskBarEl = document.getElementById('asc-task-bar');
+ if (forgeToggle && taskBarEl) {
+ forgeToggle.addEventListener('click', () => {
+ const open = taskBarEl.classList.toggle('forge-open');
+ forgeToggle.setAttribute('aria-pressed', open ? 'true' : 'false');
+ if (open && forgeInput) forgeInput.focus();
+ });
+ }
const forgeQueue = [];
let forgeInFlight = false;
let lastForgedGlb = '';
diff --git a/src/agi.css b/src/agi.css
index c2f2d08ad..3191eed2c 100644
--- a/src/agi.css
+++ b/src/agi.css
@@ -172,10 +172,10 @@
border-radius: var(--radius-md);
padding: var(--space-sm) var(--space-md);
background: var(--surface-1);
- animation: agi-enter 0.5s cubic-bezier(0.16, 1, 0.3, 1) both;
}
+/* Only freshly-streamed decisions enter (via ui-juice enterStagger); already-seen
+ calls are re-rendered each poll and must NOT re-animate. */
.agi-thought.agi-fresh { border-color: var(--stroke-strong); }
-@keyframes agi-enter { from { opacity: 0; transform: translateY(8px); } to { opacity: 1; transform: none; } }
.agi-thought-top { display: flex; align-items: center; justify-content: space-between; gap: var(--space-sm); margin-bottom: var(--space-2xs); }
.agi-thought-kind {
font-family: var(--font-mono); font-size: var(--text-2xs); letter-spacing: 0.08em; text-transform: uppercase;
diff --git a/src/agi.js b/src/agi.js
index ae57662f3..dd68f9720 100644
--- a/src/agi.js
+++ b/src/agi.js
@@ -12,6 +12,7 @@
// designed "awakening" state instead of inventing one.
import { apiFetch } from './api.js';
+import { countUp, enterStagger, liveDot, setLiveDot, reducedMotion } from './ui-juice.js';
const root = document.getElementById('agi-root');
const POLL_MS = 20000;
@@ -22,6 +23,7 @@ const state = {
timer: null,
el3d: null, // the embodied <agent-3d>
embodied: false,
+ lastScore: null, // last reputation value drawn, so the ring only re-sweeps on a real change
};
// ── utilities ─────────────────────────────────────────────────────────────────
@@ -183,7 +185,10 @@ function renderMind(d) {
<section class="agi-card agi-mind">
<div class="agi-section-head">
<h2>The mind, out loud</h2>
- <span class="agi-section-sub">every call, tamper-evident</span>
+ <span class="agi-mind-meta">
+ <span class="agi-section-sub">every call, tamper-evident</span>
+ ${liveDot('live', { label: 'live' })}
+ </span>
</div>
${body}
</section>`;
@@ -194,17 +199,43 @@ function ring(score) {
const r = 40, c = 2 * Math.PI * r;
const pct = Math.max(0, Math.min(100, Number(score) || 0));
const off = c * (1 - pct / 100);
+ const prev = state.lastScore;
+ const fromOff = prev == null ? c : c * (1 - Math.max(0, Math.min(100, prev)) / 100);
+ // Markup carries the FINAL state (correct without JS / under reduced motion);
+ // playRecord sweeps from `data-from-off` to it and counts the number up.
return `
<div class="agi-ring">
<svg viewBox="0 0 92 92" aria-hidden="true">
<circle class="agi-ring-track" cx="46" cy="46" r="${r}" fill="none" stroke-width="6" />
<circle class="agi-ring-val" cx="46" cy="46" r="${r}" fill="none" stroke-width="6"
- stroke-dasharray="${c.toFixed(1)}" stroke-dashoffset="${off.toFixed(1)}" />
+ stroke-dasharray="${c.toFixed(1)}" stroke-dashoffset="${off.toFixed(1)}"
+ data-from-off="${fromOff.toFixed(1)}" />
</svg>
- <div class="agi-ring-num"><b>${Math.round(pct)}</b><small>reputation</small></div>
+ <div class="agi-ring-num"><b data-score="${Math.round(pct)}" data-from="${prev == null ? 0 : Math.round(prev)}">${Math.round(pct)}</b><small>reputation</small></div>
</div>`;
}
+// Sweep the reputation ring from its previous fill to the new one and count the
+// number up in step. Only animates on a real change; reduced motion lands final.
+function playRecord() {
+ const num = root.querySelector('.agi-ring-num b');
+ const arc = root.querySelector('.agi-ring-val');
+ if (num) {
+ const to = Number(num.dataset.score) || 0;
+ const from = Number(num.dataset.from) || 0;
+ countUp(num, from, to, { format: (n) => String(Math.round(n)) });
+ }
+ if (arc && !reducedMotion()) {
+ const fromOff = arc.getAttribute('data-from-off');
+ const finalOff = arc.getAttribute('stroke-dashoffset');
+ if (fromOff != null && fromOff !== finalOff) {
+ arc.style.strokeDashoffset = fromOff;
+ void arc.getBoundingClientRect(); // commit the start frame
+ requestAnimationFrame(() => { arc.style.strokeDashoffset = ''; });
+ }
+ }
+}
+
function stat(k, v, cls = '') {
return `<div class="agi-stat"><div class="k">${esc(k)}</div><div class="v ${cls}">${v}</div></div>`;
}
@@ -284,6 +315,11 @@ function render(d) {
applyAura(d.cognition);
mountBody(d.agent);
if (state.embodied) applyMood(d.cognition);
+ // Only the decisions newly seen this tick slide in — the rest are already settled.
+ enterStagger(root.querySelectorAll('.agi-thought.agi-fresh'), { step: 60 });
+ playRecord();
+ const drawn = root.querySelector('.agi-ring-num b');
+ if (drawn) state.lastScore = Number(drawn.dataset.score);
}
function renderLoading() {
@@ -321,7 +357,9 @@ async function refresh() {
document.title = d.agent?.name ? `${d.agent.name} · The AGI · three.ws` : 'The AGI · three.ws';
} catch (e) {
if (!state.data) renderError();
- // If we already have a render up, keep it and try again next tick.
+ // Keep the last good render up, but mark the live feed as reconnecting so the
+ // "live" dot tells the truth until the next tick recovers.
+ else setLiveDot(root.querySelector('.agi-mind'), 'error', 'reconnecting');
}
}
diff --git a/src/dashboard-next/pages/sniper.js b/src/dashboard-next/pages/sniper.js
index 0a837f5b4..a56a7621b 100644
--- a/src/dashboard-next/pages/sniper.js
+++ b/src/dashboard-next/pages/sniper.js
@@ -77,6 +77,17 @@ const STYLE = `<style>
.sn-card-body { display: none; border-top: 1px solid var(--nxt-line); padding: 16px; }
.sn-card.open .sn-card-body { display: block; }
+/* sub-tab switcher (Strategy ↔ Money Studio) */
+.sn-subtabs { display: inline-flex; gap: 4px; padding: 3px; margin-bottom: 16px; background: var(--nxt-bg-2); border: 1px solid var(--nxt-stroke); border-radius: var(--nxt-radius); }
+.sn-subtab { font-size: 12.5px; font-weight: 600; font-family: inherit; padding: 6px 14px; border-radius: var(--nxt-radius-sm); border: 1px solid transparent; background: transparent; color: var(--nxt-ink-dim); cursor: pointer; transition: color .12s, background .12s; }
+.sn-subtab:hover { color: var(--nxt-ink); }
+.sn-subtab.active { background: var(--nxt-panel); color: var(--nxt-ink); border-color: var(--nxt-stroke); }
+.sn-subtab:focus-visible { outline: 2px solid var(--nxt-accent); outline-offset: 2px; }
+/* host for the embedded Money Studio; re-scope the panel tokens it expects so the
+ wallet accents resolve even though the dashboard theme uses --nxt-* tokens. */
+.sn-money-host { --wallet-accent: var(--nxt-accent, #34d399); --wallet-accent-soft: color-mix(in srgb, var(--nxt-accent, #34d399) 14%, transparent); }
+.sn-money-loading { padding: 28px 16px; text-align: center; color: var(--nxt-ink-faint); font-size: 13px; }
+
/* toggles row */
.sn-toggles { display: flex; gap: 10px; flex-wrap: wrap; margin-bottom: 16px; }
.sn-toggle-btn { font-size: 12px; padding: 6px 14px; border-radius: var(--nxt-radius-sm); border: 1px solid var(--nxt-stroke); background: var(--nxt-bg-2); color: var(--nxt-ink); cursor: pointer; transition: border-color .12s, background .12s, transform .12s; }
@@ -229,6 +240,9 @@ let _sseRetry = 0;
let _positionsMap = new Map();
async function refresh(root) {
+ // Re-render replaces every card's DOM — tear down any mounted Money Studio first
+ // so its 30s balance poll doesn't outlive the node it was rendered into.
+ teardownMoney();
const [stratData, agentData] = await Promise.all([
get('/api/sniper/strategy').catch(() => ({ strategies: [] })),
get('/api/agents').catch(() => ({ agents: [] })),
@@ -328,40 +342,49 @@ function stratCard(s) {
<span class="sn-chevron">▼</span>
</div>
<div class="sn-card-body">
- <div class="sn-toggles">
- <button class="sn-toggle-btn ${armed ? 'active' : ''}" data-action="toggle-enabled" data-agent="${esc(s.agent_id)}">
- ${s.enabled ? 'Disarm' : 'Arm strategy'}
- </button>
- <button class="sn-toggle-btn ${s.kill_switch ? 'active danger' : 'danger'}" data-action="toggle-kill" data-agent="${esc(s.agent_id)}">
- ${s.kill_switch ? 'Clear kill switch' : 'Kill switch'}
- </button>
- <a class="sn-toggle-btn" href="/trader/${esc(s.agent_id)}" target="_blank" rel="noopener">Track record ↗</a>
- ${s.wallet_address ? `<a class="sn-toggle-btn" href="https://solscan.io/account/${esc(s.wallet_address)}" target="_blank" rel="noopener">Wallet ↗</a>` : ''}
+ <div class="sn-subtabs" role="tablist" aria-label="Strategy views">
+ <button class="sn-subtab active" role="tab" aria-selected="true" data-subtab="strategy" data-agent="${esc(s.agent_id)}">Strategy</button>
+ <button class="sn-subtab" role="tab" aria-selected="false" data-subtab="money" data-agent="${esc(s.agent_id)}">Money Studio</button>
</div>
- ${walletWarn ? `<div style="font-size:12px;color:var(--nxt-warn,#f59e0b);padding:4px 0 12px;border-bottom:1px solid var(--nxt-line);margin-bottom:12px;">⚠ Wallet balance (${fmtSol(walletBal)}) may be too low for a trade. Fund ${s.wallet_address ? `<a href="https://solscan.io/account/${esc(s.wallet_address)}" target="_blank" rel="noopener" style="color:inherit;text-decoration:underline">${s.wallet_address.slice(0,8)}…</a>` : 'the agent wallet'} with more SOL before arming.</div>` : ''}
- <div class="sn-sum">
- <div class="sn-sum-item">
- <span class="sn-sum-label">Open</span>
- <span class="sn-sum-val">${s.summary?.open_positions || 0}</span>
- </div>
- <div class="sn-sum-item">
- <span class="sn-sum-label">Closed</span>
- <span class="sn-sum-val">${closed}</span>
- </div>
- <div class="sn-sum-item">
- <span class="sn-sum-label">Wins</span>
- <span class="sn-sum-val sn-pos">${wins}</span>
+ <div class="sn-pane" data-pane="strategy" data-agent="${esc(s.agent_id)}">
+ <div class="sn-toggles">
+ <button class="sn-toggle-btn ${armed ? 'active' : ''}" data-action="toggle-enabled" data-agent="${esc(s.agent_id)}">
+ ${s.enabled ? 'Disarm' : 'Arm strategy'}
+ </button>
+ <button class="sn-toggle-btn ${s.kill_switch ? 'active danger' : 'danger'}" data-action="toggle-kill" data-agent="${esc(s.agent_id)}">
+ ${s.kill_switch ? 'Clear kill switch' : 'Kill switch'}
+ </button>
+ <a class="sn-toggle-btn" href="/trader/${esc(s.agent_id)}" target="_blank" rel="noopener">Track record ↗</a>
+ ${s.wallet_address ? `<a class="sn-toggle-btn" href="https://solscan.io/account/${esc(s.wallet_address)}" target="_blank" rel="noopener">Wallet ↗</a>` : ''}
</div>
- <div class="sn-sum-item">
- <span class="sn-sum-label">Win rate</span>
- <span class="sn-sum-val ${wr != null && wr >= 50 ? 'sn-pos' : ''}">${wr != null ? `${wr}%` : '—'}</span>
- </div>
- <div class="sn-sum-item">
- <span class="sn-sum-label">Realized PnL</span>
- <span class="sn-sum-val ${clr(pnlSol)}">${fmtSol(pnlSol)}</span>
+ ${walletWarn ? `<div style="font-size:12px;color:var(--nxt-warn,#f59e0b);padding:4px 0 12px;border-bottom:1px solid var(--nxt-line);margin-bottom:12px;">⚠ Wallet balance (${fmtSol(walletBal)}) may be too low for a trade. Fund ${s.wallet_address ? `<a href="https://solscan.io/account/${esc(s.wallet_address)}" target="_blank" rel="noopener" style="color:inherit;text-decoration:underline">${s.wallet_address.slice(0,8)}…</a>` : 'the agent wallet'} with more SOL before arming. Open <b>Money Studio</b> above to fund it without leaving the dashboard.</div>` : ''}
+ <div class="sn-sum">
+ <div class="sn-sum-item">
+ <span class="sn-sum-label">Open</span>
+ <span class="sn-sum-val">${s.summary?.open_positions || 0}</span>
+ </div>
+ <div class="sn-sum-item">
+ <span class="sn-sum-label">Closed</span>
+ <span class="sn-sum-val">${closed}</span>
+ </div>
+ <div class="sn-sum-item">
+ <span class="sn-sum-label">Wins</span>
+ <span class="sn-sum-val sn-pos">${wins}</span>
+ </div>
+ <div class="sn-sum-item">
+ <span class="sn-sum-label">Win rate</span>
+ <span class="sn-sum-val ${wr != null && wr >= 50 ? 'sn-pos' : ''}">${wr != null ? `${wr}%` : '—'}</span>
+ </div>
+ <div class="sn-sum-item">
+ <span class="sn-sum-label">Realized PnL</span>
+ <span class="sn-sum-val ${clr(pnlSol)}">${fmtSol(pnlSol)}</span>
+ </div>
</div>
+ ${stratForm(s)}
+ </div>
+ <div class="sn-pane" data-pane="money" data-agent="${esc(s.agent_id)}" hidden>
+ <div class="sn-money-host" data-money-host="${esc(s.agent_id)}"></div>
</div>
- ${stratForm(s)}
</div>
</div>`;
}
@@ -927,6 +950,19 @@ function newStrategyCta() {
function wireEvents(root) {
// Card expand/collapse
root.addEventListener('click', (e) => {
+ // Sub-tab switch (Strategy ↔ Money Studio). Checked before the card-head
+ // toggle so it never collapses the card, and before the action handlers so
+ // money-panel clicks (handled by the mounted Money Studio itself) fall through.
+ const subtab = e.target.closest('[data-subtab]');
+ if (subtab) { switchSubtab(subtab); return; }
+
+ const retryMoney = e.target.closest('[data-action="retry-money"]');
+ if (retryMoney) {
+ const host = retryMoney.closest('.sn-pane')?.querySelector('[data-money-host]');
+ if (host) { host.dataset.mounted = ''; mountAgentMoney(retryMoney.dataset.agent, host); }
+ return;
+ }
+
const head = e.target.closest('[data-toggle="card"]');
if (head) {
head.closest('.sn-card')?.classList.toggle('open');
@@ -958,6 +994,61 @@ function wireEvents(root) {
});
}
+// ── Embedded Money Studio (Wallet · Trading Brain · Pricing · Earnings) ─────────
+//
+// The per-agent Money Studio from /agent-studio#money is reused verbatim here:
+// each strategy card's "Money Studio" sub-tab lazily mounts the real module against
+// a per-agent StudioAdapter. Mounted instances are tracked so we can tear down their
+// live balance polls before every re-render (a stale poll would keep hitting the
+// wallet API for a card that no longer exists).
+
+const _moneyMounts = new Map(); // agent_id → { adapter, instance, host }
+
+function teardownMoney() {
+ for (const { adapter, instance } of _moneyMounts.values()) {
+ try { instance?.destroy?.(); } catch { /* noop */ }
+ try { adapter?.destroy?.(); } catch { /* noop */ }
+ }
+ _moneyMounts.clear();
+}
+
+function switchSubtab(btn) {
+ const agentId = btn.dataset.agent;
+ const want = btn.dataset.subtab;
+ const body = btn.closest('.sn-card-body');
+ if (!body) return;
+ body.querySelectorAll('.sn-subtab').forEach((b) => {
+ const on = b.dataset.subtab === want;
+ b.classList.toggle('active', on);
+ b.setAttribute('aria-selected', on ? 'true' : 'false');
+ });
+ body.querySelectorAll('.sn-pane').forEach((p) => { p.hidden = p.dataset.pane !== want; });
+ if (want === 'money') {
+ const host = body.querySelector('[data-money-host]');
+ if (host && !host.dataset.mounted) mountAgentMoney(agentId, host);
+ }
+}
+
+async function mountAgentMoney(agentId, host) {
+ if (!agentId || !host || host.dataset.mounted) return;
+ host.dataset.mounted = '1';
+ host.innerHTML = '<div class="sn-money-loading">Loading Money Studio…</div>';
+ try {
+ // Full record (skills + meta.studio) — the strategy/agents list payloads are
+ // trimmed; the Money Studio + Trading Brain read agent.skills and
+ // agent.meta.studio.trading, so fetch the decorated record.
+ const { agent } = await get(`/api/agents/${encodeURIComponent(agentId)}`);
+ if (!agent) throw new Error('Agent not found');
+ host.innerHTML = '';
+ const adapter = new StudioAdapter(agent);
+ const instance = mountMoneyStudio(host, { studio: adapter });
+ _moneyMounts.set(agentId, { adapter, instance, host });
+ } catch (err) {
+ host.dataset.mounted = '';
+ host.innerHTML = `<div class="sn-empty" style="padding:24px 16px">Couldn't load Money Studio${err?.message ? ` — ${esc(err.message)}` : ''}. <button class="sn-btn ghost" data-action="retry-money" data-agent="${esc(agentId)}" style="margin-left:8px">Retry</button></div>`;
+ }
+}
+
async function toggleEnabled(btn, root) {
const agentId = btn.dataset.agent;
const strat = _strategies.find((s) => s.agent_id === agentId);
diff --git a/src/home-sniper.js b/src/home-sniper.js
new file mode 100644
index 000000000..69371ea1c
--- /dev/null
+++ b/src/home-sniper.js
@@ -0,0 +1,351 @@
+/**
+ * Homepage "Autonomous trading" section — live agent-sniper console.
+ *
+ * Renders the real on-chain sniper engine on the home page: a worker-liveness
+ * pill, an interactive five-stage decision-loop diagram, a live trade tape, and
+ * the platform's real trading KPIs. Every value is real:
+ *
+ * · /api/sniper/status → worker liveness (alive / feed-live / degraded),
+ * strategies armed, open positions.
+ * · /api/sniper/leaderboard → win rate, best ROI, initial tape backlog
+ * (recent closed trades + currently-open positions).
+ * · /api/sniper/stream → SSE of fresh buy / sell / re-quote events; each
+ * drives a packet through the pipeline and a row
+ * into the tape.
+ *
+ * No simulation: the pipeline's ambient idle pulse illustrates the loop's shape
+ * (it carries no ticker and writes nothing to the tape); only real SSE events
+ * carry a $SYMBOL packet and append a tape row. Loading, empty, and error states
+ * are all designed — when the feed is quiet the tape says so and points the user
+ * at the arena rather than showing a void.
+ *
+ * In dev, /api/* is proxied to production (see vite.config.js), so the feed is
+ * real even on localhost.
+ */
+
+import { reducedMotion } from './ui-juice.js';
+
+const NETWORK = 'mainnet';
+const STATUS_URL = '/api/sniper/status';
+const BOARD_URL = `/api/sniper/leaderboard?network=${NETWORK}&window=30d`;
+const STREAM_URL = `/api/sniper/stream?network=${NETWORK}`;
+const MAX_ROWS = 7;
+const STATUS_POLL_MS = 30_000;
+const IDLE_PULSE_MS = 6500;
+
+const STAGES = ['watch', 'score', 'guard', 'buy', 'exit'];
+
+const EXPLAIN = {
+ watch: '<strong>Watch.</strong> A PumpPortal feed streams every new pump.fun mint the instant it’s created — the agent sees launches the moment they exist.',
+ score: '<strong>Score.</strong> Each candidate is graded against the agent’s strategy — market cap, creator track record, liquidity, momentum — into a single conviction score. Below threshold, it’s skipped.',
+ guard: '<strong>Guard.</strong> Pre-trade checks gate the buy: open-position concurrency, daily budget, SOL headroom, and price-impact ceilings. Any failure aborts before a lamport moves.',
+ buy: '<strong>Buy.</strong> The engine quotes the pump.fun curve, builds the buy, signs with the agent’s wallet, and broadcasts — returning real landing telemetry and a Solscan signature.',
+ exit: '<strong>Exit.</strong> Open positions are swept every tick and closed autonomously on take-profit, stop-loss, trailing-stop, timeout, or a sentiment flip. The loop never sleeps.',
+};
+
+function esc(s) {
+ return String(s ?? '').replace(/[<>&"]/g, (c) => ({ '<': '&lt;', '>': '&gt;', '&': '&amp;', '"': '&quot;' }[c]));
+}
+
+function fmtCompact(n) {
+ if (n == null || !Number.isFinite(Number(n))) return '—';
+ const v = Number(n);
+ if (Math.abs(v) >= 1e6) return (v / 1e6).toFixed(1) + 'M';
+ if (Math.abs(v) >= 1e3) return (v / 1e3).toFixed(1) + 'K';
+ return String(Math.round(v));
+}
+
+function fmtPct(pct) {
+ if (pct == null || !Number.isFinite(Number(pct))) return null;
+ const v = Number(pct);
+ const sign = v > 0 ? '+' : '';
+ return `${sign}${v.toFixed(v >= 100 || v <= -100 ? 0 : 1)}%`;
+}
+
+function pnlClass(pct) {
+ if (pct == null || !Number.isFinite(Number(pct))) return 'flat';
+ if (Number(pct) > 0.05) return 'up';
+ if (Number(pct) < -0.05) return 'down';
+ return 'flat';
+}
+
+// ── pipeline animation ────────────────────────────────────────────────────────
+
+function makePipeline(root) {
+ const stagesEl = root.querySelector('#snipe-stages');
+ const packet = root.querySelector('#snipe-packet');
+ const explain = root.querySelector('#snipe-explain');
+ const buttons = Array.from(root.querySelectorAll('.snipe-stage'));
+ const rail = root.querySelector('.snipe-rail');
+ if (!stagesEl || !buttons.length) return { run() {}, idle() {} };
+
+ let selected = 'watch';
+ function select(stage) {
+ selected = stage;
+ buttons.forEach((b) => {
+ const on = b.dataset.stage === stage;
+ b.classList.toggle('active', on);
+ b.setAttribute('aria-pressed', on ? 'true' : 'false');
+ });
+ if (explain && EXPLAIN[stage]) explain.innerHTML = EXPLAIN[stage];
+ }
+
+ buttons.forEach((b) => {
+ b.addEventListener('click', () => select(b.dataset.stage));
+ // Hover previews the stage without committing the selection on pointer devices.
+ b.addEventListener('mouseenter', () => {
+ if (explain && EXPLAIN[b.dataset.stage]) explain.innerHTML = EXPLAIN[b.dataset.stage];
+ });
+ b.addEventListener('mouseleave', () => {
+ if (explain && EXPLAIN[selected]) explain.innerHTML = EXPLAIN[selected];
+ });
+ });
+
+ let running = false;
+ function lightSequence(bright) {
+ // Sweep each node on as the packet passes its column, off shortly after.
+ buttons.forEach((b, i) => {
+ const at = (i / (buttons.length - 1)) * 1100;
+ setTimeout(() => {
+ b.classList.add('flow');
+ setTimeout(() => b.classList.remove('flow'), 380);
+ }, at);
+ });
+ if (packet) {
+ packet.style.opacity = bright ? '1' : '0.32';
+ packet.style.transition = 'none';
+ packet.style.transform = 'translateX(0)';
+ // next frame: animate across the rail
+ requestAnimationFrame(() => requestAnimationFrame(() => {
+ const w = rail ? rail.getBoundingClientRect().width : 0;
+ packet.style.transition = 'transform 1.2s cubic-bezier(.4,.1,.3,1)';
+ packet.style.transform = `translateX(${w}px)`;
+ }));
+ }
+ }
+
+ function run(bright = true) {
+ if (running || reducedMotion()) return;
+ running = true;
+ lightSequence(bright);
+ setTimeout(() => {
+ running = false;
+ if (packet) { packet.style.transition = 'opacity .3s'; packet.style.opacity = '0'; }
+ }, 1300);
+ }
+
+ return { run, idle: () => run(false) };
+}
+
+// ── trade tape ──────────────────────────────────────────────────────────────
+
+function makeTape(root) {
+ const list = root.querySelector('#snipe-tape');
+ const seen = new Set();
+
+ function rowEl(item, animate) {
+ const kind = item.kind; // 'buy' | 'sell' | 'open'
+ const tag = kind === 'sell' ? 'sell' : kind === 'open' ? 'open' : 'buy';
+ const tagLabel = kind === 'sell' ? 'Sold' : kind === 'open' ? 'Holding' : 'Sniped';
+ const sym = (item.symbol || item.name || '???').toString().slice(0, 12);
+ const agent = item.agent_name || 'agent';
+ const pctLabel = fmtPct(item.pnl_pct);
+ const url = item.url;
+ const tagEl = kind === 'sell' && item.exit_reason ? ` · ${esc(String(item.exit_reason).replace(/_/g, ' '))}` : '';
+ const inner =
+ `<span class="snipe-tag ${tag}">${tagLabel}</span>` +
+ `<span class="snipe-rmeta"><span class="snipe-rsym">$${esc(sym.toUpperCase())}</span> ` +
+ `<span class="snipe-ragent">${esc(agent)}${tagEl}</span></span>` +
+ (pctLabel ? `<span class="snipe-rpnl ${pnlClass(item.pnl_pct)}">${esc(pctLabel)}</span>` : `<span class="snipe-rpnl flat">·</span>`);
+ const el = document.createElement(url ? 'a' : 'div');
+ el.className = 'snipe-row' + (animate && !reducedMotion() ? ' enter' : '');
+ if (url) { el.href = url; el.target = '_blank'; el.rel = 'noopener'; }
+ el.innerHTML = inner;
+ return el;
+ }
+
+ function reset() { if (list) list.innerHTML = ''; }
+
+ function empty(msg) {
+ if (!list) return;
+ list.innerHTML = `<div class="snipe-tape-msg">${esc(msg)}</div>`;
+ }
+
+ function add(item, animate) {
+ if (!list) return false;
+ const key = item.id != null ? `${item.kind}:${item.id}` : `${item.kind}:${item.symbol}:${item.at || ''}`;
+ if (seen.has(key)) return false;
+ seen.add(key);
+ // Clear any placeholder/skeleton/message on first real row.
+ const msg = list.querySelector('.snipe-tape-msg');
+ const skel = list.querySelector('.snipe-skel');
+ if (msg || skel) list.innerHTML = '';
+ list.insertBefore(rowEl(item, animate), list.firstChild);
+ while (list.children.length > MAX_ROWS) list.removeChild(list.lastChild);
+ return true;
+ }
+
+ return { add, reset, empty };
+}
+
+// ── status pill ──────────────────────────────────────────────────────────────
+
+function applyStatus(root, s) {
+ const dot = root.querySelector('#snipe-state-dot');
+ const text = root.querySelector('#snipe-state-text');
+ const sub = root.querySelector('#snipe-substate');
+ const armed = root.querySelector('#snipe-kpi-armed');
+ if (!s) return;
+
+ let cls = 'live', label = 'Engine live';
+ if (s.state === 'down') { cls = 'down'; label = 'Engine offline'; }
+ else if (s.state === 'degraded') { cls = 'degraded'; label = 'Feed degraded'; }
+ else if (s.state === 'unknown') { cls = 'degraded'; label = 'Engine idle'; }
+ else if (s.alive === false) { cls = 'down'; label = 'Engine offline'; }
+ else if (s.feedLive === false) { cls = 'degraded'; label = 'Feed reconnecting'; }
+
+ if (dot) dot.className = 'snipe-dot ' + cls;
+ if (text) text.textContent = label;
+ if (sub) {
+ const parts = [];
+ if (Number.isFinite(s.strategies)) parts.push(`${s.strategies} ${s.strategies === 1 ? 'strategy' : 'strategies'} armed`);
+ if (Number.isFinite(s.openPositions)) parts.push(`${s.openPositions} open`);
+ sub.textContent = parts.join(' · ');
+ }
+ if (armed && Number.isFinite(s.strategies)) {
+ armed.textContent = fmtCompact(s.strategies);
+ armed.classList.remove('loading');
+ }
+}
+
+function setKpi(root, id, val, accent) {
+ const el = root.querySelector(id);
+ if (!el) return;
+ el.textContent = val;
+ el.classList.remove('loading');
+ if (accent) el.classList.add('accent');
+}
+
+// ── boot ──────────────────────────────────────────────────────────────────────
+
+export function initHomeSniper() {
+ const root = document.getElementById('home-sniper');
+ if (!root) return;
+
+ const pipeline = makePipeline(root);
+ const tape = makeTape(root);
+
+ // Ambient idle pulse — illustrates the loop while the feed is quiet. Carries
+ // no ticker and never writes to the tape, so it can't be mistaken for a trade.
+ let lastEventAt = 0;
+ let idleTimer = null;
+ function scheduleIdle() {
+ if (reducedMotion()) return;
+ clearTimeout(idleTimer);
+ idleTimer = setTimeout(function tick() {
+ if (Date.now() - lastEventAt >= IDLE_PULSE_MS) pipeline.idle();
+ idleTimer = setTimeout(tick, IDLE_PULSE_MS);
+ }, IDLE_PULSE_MS);
+ }
+
+ // 1) Worker liveness — poll on an interval (cheap, public, no secrets).
+ async function pollStatus() {
+ try {
+ const r = await fetch(STATUS_URL, { headers: { accept: 'application/json' } });
+ if (r.ok) applyStatus(root, await r.json());
+ } catch { /* non-fatal — keep last good state */ }
+ }
+
+ // 2) Leaderboard — KPIs + initial tape backlog.
+ async function loadBoard() {
+ try {
+ const r = await fetch(BOARD_URL, { headers: { accept: 'application/json' } });
+ if (!r.ok) throw new Error(String(r.status));
+ const d = await r.json();
+ const board = Array.isArray(d.leaderboard) ? d.leaderboard : [];
+
+ const bestWin = board.reduce((m, a) => Math.max(m, Number(a.win_rate) || 0), 0);
+ const bestRoi = board.reduce((m, a) => (Number(a.roi_pct) > (m ?? -Infinity) ? Number(a.roi_pct) : m), null);
+ const totalOpen = board.reduce((s, a) => s + (Number(a.open_positions) || 0), 0)
+ || (Array.isArray(d.positions) ? d.positions.length : 0);
+
+ setKpi(root, '#snipe-kpi-winrate', board.length ? `${Math.round(bestWin * 100)}%` : '—', true);
+ setKpi(root, '#snipe-kpi-roi', bestRoi != null ? (fmtPct(bestRoi) || '—') : '—');
+ setKpi(root, '#snipe-kpi-open', fmtCompact(totalOpen));
+
+ // Seed the tape from real history: most recent closed trades, then open holds.
+ const seedTrades = (d.trades || []).slice(0, MAX_ROWS).map((t) => ({
+ kind: 'sell', id: t.id, symbol: t.symbol, name: t.name, agent_name: t.agent_name,
+ pnl_pct: t.pnl_pct, exit_reason: t.exit_reason, url: t.sell_url || t.buy_url, at: t.at,
+ }));
+ const seedOpen = (d.positions || []).slice(0, MAX_ROWS).map((p) => ({
+ kind: 'open', id: p.id, symbol: p.symbol, name: p.name, agent_name: p.agent_name,
+ pnl_pct: p.unrealized_pct, url: p.buy_url, at: p.at,
+ }));
+ const seed = [...seedTrades, ...seedOpen].slice(0, MAX_ROWS);
+ if (seed.length) {
+ tape.reset();
+ // Oldest first so newest ends up on top after the prepend loop.
+ seed.reverse().forEach((it) => tape.add(it, false));
+ } else {
+ tape.empty('No live trades right now — the engine is watching for the next launch. Open the arena to follow it live.');
+ }
+ } catch {
+ tape.empty('Live feed is catching its breath. Open the arena to watch agents trade in real time →');
+ }
+ }
+
+ // 3) Live SSE stream — fresh buy / sell / re-quote events.
+ let es = null;
+ function connectStream() {
+ if (typeof EventSource !== 'function') return;
+ try { es = new EventSource(STREAM_URL); } catch { return; }
+
+ const onTrade = (kind) => (ev) => {
+ let data;
+ try { data = JSON.parse(ev.data); } catch { return; }
+ lastEventAt = Date.now();
+ const added = tape.add({
+ kind,
+ id: kind === 'update' ? `u${data.id}` : data.id,
+ symbol: data.symbol, name: data.name, agent_name: data.agent_name,
+ pnl_pct: data.pnl_pct,
+ exit_reason: data.exit_reason,
+ url: kind === 'sell' ? (data.sell_url || data.buy_url) : data.buy_url,
+ at: data.at,
+ }, true);
+ if (added || kind !== 'update') pipeline.run(true);
+ };
+
+ es.addEventListener('buy', onTrade('buy'));
+ es.addEventListener('sell', onTrade('sell'));
+ es.addEventListener('update', onTrade('update'));
+ // The server caps each SSE at ~90s, then sends `close` and ends — reconnect.
+ es.addEventListener('close', () => { try { es.close(); } catch {} ; setTimeout(connectStream, 1200); });
+ es.onerror = () => {
+ // EventSource auto-reconnects on transient errors; only hard-reset on a
+ // fully closed stream so we don't thrash the endpoint.
+ if (es && es.readyState === EventSource.CLOSED) { try { es.close(); } catch {} ; setTimeout(connectStream, 3000); }
+ };
+ }
+
+ // Tear down the stream when the tab is hidden; reconnect when it returns.
+ document.addEventListener('visibilitychange', () => {
+ if (document.hidden) { if (es) { try { es.close(); } catch {} es = null; } }
+ else if (!es) connectStream();
+ });
+
+ pollStatus();
+ loadBoard();
+ connectStream();
+ scheduleIdle();
+ setInterval(pollStatus, STATUS_POLL_MS);
+}
+
+if (typeof window !== 'undefined') {
+ if (document.readyState === 'loading') {
+ document.addEventListener('DOMContentLoaded', initHomeSniper, { once: true });
+ } else {
+ initHomeSniper();
+ }
+}
diff --git a/src/leaderboard.css b/src/leaderboard.css
index b7f34a553..828109833 100644
--- a/src/leaderboard.css
+++ b/src/leaderboard.css
@@ -292,6 +292,9 @@
animation: lb-row-in var(--duration-base) var(--ease-out) both;
}
.lb-row:last-child { border-bottom: 0; }
+/* On refresh/sort we FLIP rows to their new rank (src/ui-juice.js) — suppress the
+ per-row entrance animation so standings settle in place instead of re-flashing. */
+.lb-rows--reflow .lb-row { animation: none; }
.lb-row:hover { background: var(--surface-2); }
.lb-row:focus-visible {
outline: var(--focus-ring-width) solid var(--focus-ring-color);
diff --git a/src/reasoning-ledger.css b/src/reasoning-ledger.css
index eca4f76fe..a7e04394a 100644
--- a/src/reasoning-ledger.css
+++ b/src/reasoning-ledger.css
@@ -92,8 +92,24 @@
.rl-score-ring .rl-score-num {
position: absolute; inset: 0; display: grid; place-content: center; text-align: center;
}
-.rl-score-ring .rl-score-val { font-size: 38px; font-weight: 800; line-height: 1; }
+.rl-score-ring .rl-score-val { font-size: 38px; font-weight: 800; line-height: 1; font-variant-numeric: tabular-nums; }
.rl-score-ring .rl-score-cap { font: 600 10px/1 var(--rl-mono); color: var(--rl-dim); letter-spacing: 0.1em; text-transform: uppercase; margin-top: 5px; }
+/* playScoreRing sweeps stroke-dashoffset from full (empty) to its real value. */
+.rl-score-arc { transition: stroke-dashoffset var(--duration-slow) var(--ease-emphasized); }
+
+/* ── Quality trend (real cumulative P&L over settled calls) ─────────────── */
+.rl-trend {
+ display: flex; align-items: center; gap: 14px;
+ margin: 16px 0 0; padding-top: 14px;
+ border-top: 1px solid var(--rl-line-2);
+}
+.rl-trend-k { font: 600 11px/1.3 var(--rl-mono); color: var(--rl-dim); text-transform: uppercase; letter-spacing: 0.06em; flex: 1; min-width: 0; }
+.rl-trend-spark { flex: none; line-height: 0; }
+.rl-trend-v { flex: none; font: 700 15px/1 var(--rl-mono); font-variant-numeric: tabular-nums; }
+@media (max-width: 480px) {
+ .rl-trend { flex-wrap: wrap; gap: 8px; }
+ .rl-trend-k { flex-basis: 100%; }
+}
.rl-rep-stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(120px, 1fr)); gap: 14px 18px; }
.rl-stat dt { font: 600 11px/1 var(--rl-mono); color: var(--rl-dim); text-transform: uppercase; letter-spacing: 0.06em; margin: 0 0 5px; }
@@ -198,4 +214,5 @@
@media (prefers-reduced-motion: reduce) {
.rl-skel, .rl-kicker .rl-dot, .rl-verify.is-checking .rl-vdot { animation: none; }
.rl-entry { transition: none; }
+ .rl-score-arc { transition: none; }
}
diff --git a/src/studio/money/trading-brain.js b/src/studio/money/trading-brain.js
index e16a41aee..db99dd653 100644
--- a/src/studio/money/trading-brain.js
+++ b/src/studio/money/trading-brain.js
@@ -78,6 +78,7 @@ class TradingBrain {
positions: [],
tradeLimits: null,
spentTodaySol: null,
+ spentTodayUsd: null,
candidates: null, // null = not scanned; [] = scanned, none
scanNote: null,
scanning: false,
@@ -115,6 +116,7 @@ class TradingBrain {
this.state.positions = strat.positions;
this.state.tradeLimits = limits.trade_limits;
this.state.spentTodaySol = limits.spent_today_sol;
+ this.state.spentTodayUsd = limits.spent_today_usd;
this.state.audit = audit;
this.state.error = null;
} catch (err) {
@@ -122,6 +124,7 @@ class TradingBrain {
} finally {
this.state.loading = false;
this._renderBody();
+ this._startLivePolling();
}
}
@@ -134,11 +137,12 @@ class TradingBrain {
async _fetchLimits() {
// Canonical, wallet-independent trade-limits endpoint: returns data.limits as
- // the agent's trade guardrails (works even before a signing wallet exists).
- const res = await apiFetch(`/api/agents/${this.agentId}/trade/limits`);
- if (!res.ok) return { trade_limits: null, spent_today_sol: null };
+ // the agent's trade guardrails (works even before a signing wallet exists),
+ // plus the live daily spend so the owner sees budget burn against the cap.
+ const res = await apiFetch(`/api/agents/${this.agentId}/trade/limits?network=${encodeURIComponent(this.rule.network || 'mainnet')}`);
+ if (!res.ok) return { trade_limits: null, spent_today_sol: null, spent_today_usd: null };
const { data } = await res.json();
- return { trade_limits: data.limits, spent_today_sol: null };
+ return { trade_limits: data.limits, spent_today_sol: data.spent_today_sol ?? null, spent_today_usd: data.spent_today_usd ?? null };
}
async _fetchAudit() {
@@ -274,6 +278,67 @@ class TradingBrain {
}
}
+ // ── Live polling ─────────────────────────────────────────────────────────────
+ // Open positions are marked to market server-side by the sniper worker; armed
+ // strategies open and close them on their own. Poll while there's something live
+ // to watch so unrealized P&L, new fills, exits, and today's spend stay current
+ // without a manual reload. Paused while the tab is hidden — no point burning RPC
+ // and rate limit on an unseen panel.
+
+ _hasLiveWork() {
+ return this._armed || (this.state.positions || []).some((p) => p.status === 'open' || p.status === 'closing');
+ }
+
+ _startLivePolling() {
+ if (this._poll || this._destroyed) return;
+ this._onVis = () => { if (!document.hidden) this._pollTick(true); };
+ document.addEventListener('visibilitychange', this._onVis);
+ this._poll = setInterval(() => this._pollTick(), 15000);
+ }
+
+ async _pollTick(force = false) {
+ if (this._destroyed || this._polling) return;
+ if (document.hidden && !force) return;
+ if (!force && !this._hasLiveWork()) return;
+ this._polling = true;
+ try {
+ const [strat, limits] = await Promise.all([
+ this._fetchStrategies().catch(() => null),
+ this._fetchLimits().catch(() => null),
+ ]);
+ if (this._destroyed) return;
+ let touchedPositions = false;
+ let touchedSpent = false;
+ if (strat) {
+ this.state.killed = strat.killed;
+ this.state.equips = strat.equips;
+ this.state.positions = strat.positions;
+ touchedPositions = true;
+ }
+ if (limits) {
+ this.state.tradeLimits = limits.trade_limits ?? this.state.tradeLimits;
+ if (limits.spent_today_sol !== this.state.spentTodaySol || limits.spent_today_usd !== this.state.spentTodayUsd) {
+ this.state.spentTodaySol = limits.spent_today_sol;
+ this.state.spentTodayUsd = limits.spent_today_usd;
+ touchedSpent = true;
+ }
+ }
+ // Re-render only the live regions, and only when not loading (avoid
+ // clobbering a mid-flight scan/backtest in another part of the panel).
+ if (!this.state.loading) {
+ if (touchedPositions) { this._renderPositions(); this._renderHeader(); }
+ if (touchedSpent) { const foot = this._q('.tb-glimits-foot .tb-spent'); if (foot) this._renderGuardrails(); }
+ }
+ } finally {
+ this._polling = false;
+ }
+ }
+
+ _stopLivePolling() {
+ if (this._poll) { clearInterval(this._poll); this._poll = null; }
+ if (this._onVis) { document.removeEventListener('visibilitychange', this._onVis); this._onVis = null; }
+ }
+
// ── Kill switch ─────────────────────────────────────────────────────────────
async _toggleKill() {
@@ -331,6 +396,7 @@ class TradingBrain {
if (!res.ok) throw new Error('Could not save guardrails.');
const { data } = await res.json();
this.state.tradeLimits = data.limits;
+ this._renderGuardrails();
this._toast('Guardrails saved — enforced server-side on every trade');
} catch (err) {
this._toast(err.message || 'Save failed', true);
@@ -646,12 +712,34 @@ class TradingBrain {
<label class="tb-field"><span class="tb-field-l">Max open positions</span><span class="tb-input-wrap"><input type="number" min="0" step="1" data-glimit="max_concurrent" value="${v(t.max_concurrent)}" placeholder="∞"/></span></label>
</div>
<div class="tb-glimits-foot">
- <span class="tb-spent">${this.state.spentTodaySol != null ? `Spent today: ${fmtSol(this.state.spentTodaySol)} SOL` : ''}</span>
+ ${this._spentHtml(t)}
<button class="studio-btn studio-btn-ghost" data-action="save-guardrails">Save guardrails</button>
</div>
</div>`;
}
+ // Daily budget burn — real spend (mainnet trade custody, 24h window) shown
+ // against the daily cap so the owner sees how much leash is left today.
+ _spentHtml(limits) {
+ const spent = this.state.spentTodaySol;
+ if (spent == null) return `<span class="tb-spent"></span>`;
+ const budget = limits?.daily_budget_sol;
+ const usd = this.state.spentTodayUsd;
+ const usdStr = usd != null ? ` · ${fmtUsd(usd)}` : '';
+ if (budget == null || !(budget > 0)) {
+ return `<span class="tb-spent">Spent today: <b>${fmtSol(spent)} SOL</b>${usdStr}</span>`;
+ }
+ const pct = Math.max(0, Math.min(100, (spent / budget) * 100));
+ const warn = pct >= 90 ? ' is-hot' : pct >= 60 ? ' is-warm' : '';
+ return `
+ <span class="tb-spent${warn}">
+ Spent today: <b>${fmtSol(spent)}</b> / ${fmtSol(budget)} SOL${usdStr}
+ <span class="tb-budget-bar" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="${pct.toFixed(0)}" aria-label="Daily budget used">
+ <span class="tb-budget-fill" style="width:${pct.toFixed(1)}%"></span>
+ </span>
+ </span>`;
+ }
+
_renderActions() {
const host = this._q('[data-actions]');
if (!host) return;
@@ -761,9 +849,21 @@ class TradingBrain {
_posRow(p) {
const live = p.status === 'open' || p.status === 'closing';
- const pnl = live ? null : p.pnl_sol;
- const pnlPct = live ? null : p.pnl_pct;
+ // Live positions: mark to market — unrealized P&L is current value vs the SOL
+ // staked in. Closed positions: the realized P&L the worker booked at exit.
+ let pnl;
+ let pnlPct;
+ if (live) {
+ pnl = (p.value_sol != null && p.entry_sol != null) ? p.value_sol - p.entry_sol : null;
+ pnlPct = (pnl != null && p.entry_sol > 0) ? (pnl / p.entry_sol) * 100 : null;
+ } else {
+ pnl = p.pnl_sol;
+ pnlPct = p.pnl_pct;
+ }
const cls = pnlPct == null ? '' : pnlPct >= 0 ? 'pos' : 'neg';
+ const pnlText = pnl == null
+ ? (live ? 'pricing…' : '—')
+ : `${pnl >= 0 ? '+' : ''}${fmtSol(pnl)} SOL${pnlPct != null ? ` (${fmtPct(pnlPct)})` : ''}`;
return `
<li class="tb-pos-row" data-status="${esc(p.status)}">
<span class="tb-pos-id"><b>${esc(p.symbol || p.name || short(p.mint))}</b>
@@ -772,7 +872,7 @@ class TradingBrain {
</span>
<span class="tb-pos-state">${live ? `<span class="tb-pos-live">● ${esc(p.status)}</span>` : esc(p.exit_reason || 'closed')}</span>
<span class="tb-pos-entry">${fmtSol(p.entry_sol)} SOL in</span>
- <span class="tb-pos-pnl ${cls}">${live ? (p.value_sol != null ? `${fmtSol(p.value_sol)} SOL value` : 'live') : `${pnl >= 0 ? '+' : ''}${fmtSol(pnl)} SOL ${pnlPct != null ? `(${fmtPct(pnlPct)})` : ''}`}</span>
+ <span class="tb-pos-pnl ${cls}" title="${live ? 'Unrealized — marked to live price' : 'Realized at exit'}">${pnlText}</span>
</li>`;
}
@@ -868,6 +968,8 @@ class TradingBrain {
}
destroy() {
+ this._destroyed = true;
+ this._stopLivePolling();
clearTimeout(this._metaTimer);
clearTimeout(this._toastTimer);
}
diff --git a/src/swarms.js b/src/swarms.js
index 3b4803dc2..c75d57d2e 100644
--- a/src/swarms.js
+++ b/src/swarms.js
@@ -265,8 +265,12 @@ function repTier(rep) {
function memberRowHTML(m, i) {
const rep = m.reputation == null ? null : Math.round(m.reputation);
const sharePct = Math.min(100, (m.share_bps || 0) / 100);
+ const power = m.vote_power == null ? null : Math.round(m.vote_power * 100);
const lead = i === 0;
- const repTitle = rep == null ? 'Vote weight — unrated track record' : `Vote weight ${rep}/100 — verified track record`;
+ const repLabel = rep == null ? 'unrated track record' : `reputation ${rep}/100`;
+ const repTitle = power == null
+ ? `Vote weight — ${repLabel}`
+ : `Carries ${power}% of the swarm's vote · ${repLabel} (weight ${m.vote_weight})`;
return `
<div class="sw-row sw-member${lead ? ' is-lead' : ''}" data-agent="${esc(m.agent_id)}">
<div class="sw-rank">#${i + 1}</div>
@@ -275,12 +279,12 @@ function memberRowHTML(m, i) {
<div class="sw-bar"><span style="width:${sharePct}%"></span></div>
</div>
<div class="sw-member-meta">
- <div class="mono name">${(m.share_bps / 100).toFixed(1)}%</div>
+ <div class="mono name">${((m.share_bps || 0) / 100).toFixed(1)}%</div>
<div class="muted mono" style="font-size:var(--text-2xs)">${SOL(m.contribution_sol)}</div>
</div>
<div class="sw-rep" data-tier="${repTier(rep)}" style="--rep:${rep == null ? 0 : rep}" title="${esc(repTitle)}" aria-label="${esc(repTitle)}">
<span class="sw-rep-v mono">${rep == null ? '—' : rep}</span>
- <span class="sw-rep-l">wt</span>
+ <span class="sw-rep-l mono">${power == null ? 'wt' : power + '%'}</span>
</div>
</div>`;
}
@@ -680,19 +684,63 @@ function updateTile(el, to, format, onValue) {
const prefersReducedMotion = () => typeof window.matchMedia === 'function' && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
+// Keep the live vote log bounded — an active swarm streams indefinitely, so without
+// a cap the DOM (and its animation listeners) would grow without limit over a session.
+const MAX_VOTE_ROWS = 60;
+function trimVoteLog(box) {
+ if (!box) return;
+ while (box.children.length > MAX_VOTE_ROWS) box.lastElementChild.remove();
+}
+
+// Single live region so the firing moment — the most important event on the page —
+// reaches screen readers, not just sighted users.
+function announce(msg) {
+ let region = document.getElementById('sw-aria-live');
+ if (!region) {
+ region = document.createElement('div');
+ region.id = 'sw-aria-live';
+ region.className = 'sr-only';
+ region.setAttribute('role', 'status');
+ region.setAttribute('aria-live', 'assertive');
+ document.body.appendChild(region);
+ }
+ region.textContent = '';
+ requestAnimationFrame(() => { region.textContent = msg; }); // reset so identical messages re-announce
+}
+
+// Count a percentage readout from 0 → target in lockstep with the meter fill, so the
+// number reads as "consensus building" rather than snapping to its final value.
+function countPercent(el, to) {
+ if (!el) return;
+ const dur = 220, start = performance.now();
+ const step = (now) => {
+ const p = Math.min(1, (now - start) / dur);
+ el.textContent = `${Math.round(to * (1 - Math.pow(1 - p, 3)))}%`;
+ if (p < 1) requestAnimationFrame(step);
+ else el.textContent = `${to}%`;
+ };
+ requestAnimationFrame(step);
+}
+
// Animate a freshly-streamed vote row: slide in, fill the consensus meter from 0
-// toward the real value, and — on a fire — drive the fill across the threshold
-// tick with a hot gradient, a glow at the line, and a single verdict-badge pulse.
+// toward the real value (the % readout counting alongside), and — on a fire — drive the
+// fill across the threshold tick with a hot gradient, a glow at the line, and a verdict
+// pulse. Fires are announced to assistive tech and the log trimmed regardless of motion.
function animateVoteRow(row, v) {
if (!row) return;
- const fill = row.querySelector('.sw-meter-fill');
const fire = v.decision === 'fire';
+ const fill = row.querySelector('.sw-meter-fill');
+ const pctEl = row.querySelector('.meter span.mono');
+ const target = fill ? fill.style.width || '0%' : '0%';
+ const pct = Math.round(parseFloat(target) || 0);
+ if (fire) announce(`Swarm fired at ${pct}% consensus${v.mint ? ` on ${short(v.mint)}` : ''}.`);
+ trimVoteLog(row.parentElement);
if (prefersReducedMotion()) return; // HTML already renders the final state
row.classList.add('sw-enter');
if (!fill) return;
- const target = fill.style.width || '0%';
if (fire) fill.classList.remove('fire'); // start cool, shift hot as it crosses
fill.style.width = '0%';
+ countPercent(pctEl, pct);
void fill.offsetWidth; // commit the 0% start before transitioning
requestAnimationFrame(() => {
fill.style.width = target;
diff --git a/tests/ui-juice.test.js b/tests/ui-juice.test.js
index 626b8535a..aaf4b7503 100644
--- a/tests/ui-juice.test.js
+++ b/tests/ui-juice.test.js
@@ -36,7 +36,7 @@ describe('countUp — instant path (no requestAnimationFrame in node)', () => {
it('records the target on dataset for the next updateValue', () => {
const el = { textContent: '', dataset: {} };
countUp(el, 0, 42, { format: (n) => String(Math.round(n)) });
- expect(el.dataset.ujVal).toBe('42');
+ expect(el.dataset.juiceVal).toBe('42');
expect(el.textContent).toBe('42');
});
@@ -47,10 +47,11 @@ describe('countUp — instant path (no requestAnimationFrame in node)', () => {
describe('updateValue', () => {
it('counts from the element\'s last tracked value to the new one', () => {
- const el = { textContent: '', dataset: { ujVal: '100' } };
- updateValue(el, 250, (n) => String(Math.round(n)));
+ // flash:false isolates the count math from the DOM tint pulse
+ const el = { textContent: '', dataset: { juiceVal: '100' } };
+ updateValue(el, 250, (n) => String(Math.round(n)), { flash: false });
expect(el.textContent).toBe('250');
- expect(el.dataset.ujVal).toBe('250');
+ expect(el.dataset.juiceVal).toBe('250');
});
it('starts cold when no prior value is tracked', () => {
diff --git a/vercel.json b/vercel.json
index 5d24d6988..21c0a50ae 100644
--- a/vercel.json
+++ b/vercel.json
@@ -235,6 +235,30 @@
"src": "/agent-wallet/",
"dest": "/agent-wallet.html"
},
+ {
+ "src": "/viability",
+ "dest": "/viability.html"
+ },
+ {
+ "src": "/viability/",
+ "dest": "/viability.html"
+ },
+ {
+ "src": "/gallery-picker",
+ "dest": "/gallery-picker.html"
+ },
+ {
+ "src": "/gallery-picker/",
+ "dest": "/gallery-picker.html"
+ },
+ {
+ "src": "/admin/launcher",
+ "dest": "/admin/launcher.html"
+ },
+ {
+ "src": "/admin/launcher/",
+ "dest": "/admin/launcher.html"
+ },
{
"src": "/aws-marketplace/welcome",
"dest": "/aws-marketplace/welcome.html"