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.

feat(trade-rooms): spectate a trader trading live in a 3D room with their avatar, receipts and one-tap fork

nirholasf38a788df9c9
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1ea6c7c74..903dc5c60 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,7 +6,10 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
## 2026-09-29
+- **Docs · Live trade rooms** (`/docs/trade-rooms`): How live trade rooms work: the trader's 3D avatar reacting to each real fill, the board and ticker tape, spectator presence, the receipt, Fork, ghost-copy and copy on every trade, the list view and frame budget, and the rooms, room and SSE stream APIs.
+- **Live Trade Rooms: watch pump.fun traders trade live in 3D** (`/trade-rooms`): Step into a trader's 3D room and watch their real pump.fun buys and sells land as they fill: the avatar reacts, every trade carries its receipt, P&L and Solscan tx, and one tap forks the trade or ghost-copies the trader. Quiet rooms show the latest real trades and which rooms are live now.
- **The platform's own payments stop crowding out the data it pays for**: Every two minutes a background job sends a batch of tiny tips to keep the payment feed moving, and three.ws pays the network fee on each one. It sent 60 at a time whether or not the day's fee budget could cover them, so about 95% were turned away after the work of preparing them, and the few that got through used up the budget the health, price and volume checks needed. The job now sends only what the budget can pay for and leaves room for those checks first. The status page also flags this pattern if it ever comes back, instead of reporting payments as healthy. (`/status`) `[fix, infra]`
+- **Watch traders trade live in their own 3D trade rooms**: Every public trader now has a live trade room. Their avatar stands on the floor and reacts as each real buy and sell fills, the board and ticker tape fill with their trades, and everyone watching shows up in the room. Tap any trade for the receipt of why it was made, fork it into your own wallet, or ghost-copy the trader. A quiet room still shows the latest real trades and which rooms are live right now, and the whole room also works as an accessible live list. (`/trade-rooms`) `[feature]`
## 2026-09-28
diff --git a/STRUCTURE.md b/STRUCTURE.md
index 0fc1151e9..8a74dd88d 100644
--- a/STRUCTURE.md
+++ b/STRUCTURE.md
@@ -248,6 +248,7 @@ bottom.
| Exit Lab (counterfactual exit replay) | kernel [api/_lib/exit-replay.js](api/_lib/exit-replay.js), corpus [api/sniper/exit-lab.js](api/sniper/exit-lab.js) `→ /api/sniper/exit-lab`, page [pages/exit-lab.html](pages/exit-lab.html) + [src/exit-lab.js](src/exit-lab.js) `→ /exit-lab` | Live | Replays every REAL closed sniper position through the live `decideLadderedExit` with the exit rules changed, so the fleet can ask "were our exits right?" about SOL it already spent. The kernel is pure and is imported by BOTH the handler and the browser, so a slider move is instant and server and client can never disagree. Two-phase walk over the recorded path (entry to peak to final quote) mirroring the live partial-sell bookkeeping leg for leg. States its own limits on the page: earlier exits are exact, longer holds are a lower bound, laddered positions are excluded with a stated reason. Grid search is an exact enumeration, flagged as in-sample. Tests: [tests/exit-replay.test.js](tests/exit-replay.test.js), [tests/exit-lab-page.test.js](tests/exit-lab-page.test.js). Docs: [docs/exit-lab.md](docs/exit-lab.md), tutorial [docs/tutorials/find-a-better-exit-policy.md](docs/tutorials/find-a-better-exit-policy.md) |
| Shareable trade card (per closed trade) | model [api/_lib/trade-card.js](api/_lib/trade-card.js), loader [api/_lib/trade-card-store.js](api/_lib/trade-card-store.js), image [api/trade-og.js](api/trade-og.js) `→ /api/trade-og?id=`, page [api/trade-share.js](api/trade-share.js) `→ /trade/<position id>`, share link on every closed row in [src/trader.js](src/trader.js) | Live | The trader-level card answers "is this trader any good?"; this one answers "what just happened?" and is the artifact worth posting the minute a position closes. One closed `agent_sniper_positions` row becomes an SVG 1200x630 card (coin, result with its return multiple, SOL in/out, hold time, exit reason) plus an SSR page carrying per-trade Open Graph / Twitter / Farcaster meta, both legs linked to Solscan, and a one-tap post. Image and page render from ONE pure model, so the picture that unfurls and the page it lands on can never disagree about a number. Honest by construction: a loss renders exactly like a win, a simulate-mode fill is stamped PAPER and never counted as live, and a moon-bag exit says the position was not fully sold. Unknown, still-open or deleted trades fall back rather than break an unfurl. Tests: [tests/trade-card.test.js](tests/trade-card.test.js) |
| Trade receipts ("why it traded") | model + loader [api/_lib/trade-receipt.js](api/_lib/trade-receipt.js), endpoint [api/sniper/receipt.js](api/sniper/receipt.js) `→ /api/sniper/receipt?id=`, shared renderer [src/shared/trade-receipt-view.js](src/shared/trade-receipt-view.js), drawer on [src/trader.js](src/trader.js) `→ /trader/:id?trade=<id>`, section on [api/trade-share.js](api/trade-share.js) `→ /trade/:id`, MCP tool `trade_receipt` in [api/_mcp/tools/trader.js](api/_mcp/tools/trader.js), tests [tests/trade-receipt.test.js](tests/trade-receipt.test.js) | Live (read-only) | Why an agent took one trade, from the rows its gates actually wrote: entry trigger, Oracle score and pillars at entry with the base-rate reasons behind it, the trade firewall verdict and checks (the simulated buy/sell round-trip included), the LLM judge thesis, the Risk Officer review, paid x402 sentiment and rug-pull reads with their payment tx, launch intel, and every journal leg with its signature. Each block is timed against the entry; evidence logged after the exit is dropped and evidence seen while holding is labeled as such, so a receipt never passes hindsight off as a reason. Same visibility gate as `/api/sniper/trader`. Doc: [docs/trade-receipts.md](docs/trade-receipts.md). |
+| Live trade rooms (spectate a trader trading live in 3D) | Page [pages/trade-room.html](pages/trade-room.html) `→ /trade-rooms` (lobby) and `→ /trade-rooms/:agentId` (a room), controller [src/trade-room/main.js](src/trade-room/main.js), 3D scene [src/trade-room/scene.js](src/trade-room/scene.js), pure model shared with the API [src/trade-room/model.js](src/trade-room/model.js), styles [src/trade-room/trade-room.css](src/trade-room/trade-room.css); read model [api/_lib/trade-room.js](api/_lib/trade-room.js), spectator presence [api/_lib/trade-room-presence.js](api/_lib/trade-room-presence.js), endpoints [api/sniper/rooms.js](api/sniper/rooms.js), [api/sniper/room.js](api/sniper/room.js), SSE [api/sniper/room-stream.js](api/sniper/room-stream.js) | Live | Roadmap 12.13. Every public trader gets a room: their own 3D body (public or unlisted avatar, else the default rig) on a pedestal, a trade board and LED ticker tape, and one crowd figure per open viewer. The stream polls `agent_sniper_positions` for that trader and derives buys, sells and quote moves from timestamps, so fills land within about 2s and the avatar reacts (point on a buy, celebrate or slump on a sell). Each trade carries its receipt (`/api/sniper/receipt`), Solscan tx, `/trade/:id` card and a Fork; the room links to ghost-copy and copy. Quiet rooms show the latest real trades, when the trader last traded, and which rooms are live. Presence is a Redis sorted set per room with an in-process fallback. The canvas is mirrored by an accessible trade list with an aria-live announcer; devices that cannot hold the frame budget or lack WebGL get the list view and are told why. Linked from `/trader/:id`, the leaderboard hero and the nav. Docs: [docs/trade-rooms.md](docs/trade-rooms.md). Tests: [tests/trade-room.test.js](tests/trade-room.test.js) |
| Trading growth programs (big-win X poster, first-rug softener, early-leader bonus) | engine [api/_lib/growth-programs/](api/_lib/growth-programs) (flags + caps [config.js](api/_lib/growth-programs/config.js), [big-win-x.js](api/_lib/growth-programs/big-win-x.js), [rug-softener.js](api/_lib/growth-programs/rug-softener.js), [early-leaders.js](api/_lib/growth-programs/early-leaders.js), capped payout leg [payouts.js](api/_lib/growth-programs/payouts.js)), crons [api/cron/big-win-x.js](api/cron/big-win-x.js) + [api/cron/growth-payouts.js](api/cron/growth-payouts.js), ops board [api/ops/growth-programs.js](api/ops/growth-programs.js) `→ /api/ops/growth-programs`, claim API [api/sniper/rug-softener.js](api/sniper/rug-softener.js) `→ /api/sniper/rug-softener`, claim banner [src/dashboard-next/rug-softener-banner.js](src/dashboard-next/rug-softener-banner.js) on `/dashboard/sniper`, ledger migration [api/_lib/migrations/20260929120000_growth_program_payouts.sql](api/_lib/migrations/20260929120000_growth_program_payouts.sql), report [scripts/growth-programs-report.mjs](scripts/growth-programs-report.mjs) | Built, disarmed | Roadmap 917 items 3.8, 12.15 and 13.4. Posts notable live wins to @trythreews (never naming the traded coin, linking the `/trade/:id` card, filtered like the changelog X lane), pays $THREE toward a first-timer's first verified rug, and pays a bounded $THREE bonus to the first leaders with a verified, followed record. The selection logic runs on live data and is inspectable at any time; posting and paying only run when `BIG_WIN_X_ENABLED`, `RUG_SOFTENER_ENABLED` or `EARLY_LEADER_ENABLED` is set, under rolling caps with code ceilings, from the Arena prize wallet (`THREE_PRIZE_PAYOUT_KEY`) via a Token-2022-aware transfer. Docs + owner arm steps: [docs/growth-programs.md](docs/growth-programs.md). Tests: [tests/growth-programs.test.js](tests/growth-programs.test.js) |
| Never sell 100% of a winner (moon-bag policy) | rule [workers/agent-sniper/exit-logic.js](workers/agent-sniper/exit-logic.js) (`moonbagExitFraction`, `moonbagAlways`), retained-bag booking [workers/agent-sniper/executor.js](workers/agent-sniper/executor.js), position fields [api/_lib/migrations/20260725100000_sniper_moonbag_always.sql](api/_lib/migrations/20260725100000_sniper_moonbag_always.sql), board [api/sniper/experiments.js](api/sniper/experiments.js) + [src/sniper-experiments.js](src/sniper-experiments.js) `→ /sniper/experiments` | Live | Fleet-wide owner rule: a terminal exit that is IN PROFIT sells down to the moon-bag floor (default 15%) instead of to zero, and the retained tokens ride indefinitely. Once the cost basis is back the remainder is free, so a bag that goes to zero costs nothing and a bag that runs is the whole upside; selling the last slice for a rounding error gives that up. Applies with or without the proactive 2x ladder. A loss exit with the stake still at risk is still a FULL exit and the hard stop-loss is never overridden. The position still books `closed`, so realized P&L and the `max_concurrent_positions` slot are unaffected and a held bag can never stop an arm trading; only the tokens stay behind (`moonbag_base_amount`). Per-strategy opt-out `moonbag_always = false`. Tests: [tests/sniper-laddered-exit.test.js](tests/sniper-laddered-exit.test.js), [tests/trading-experiment-e2e.test.js](tests/trading-experiment-e2e.test.js). See [docs/trading-experiment.md](docs/trading-experiment.md) |
| Autonomous Trading hub (front door) | [pages/trading.html](pages/trading.html) `→ /trading` + [src/trading-hub.js](src/trading-hub.js), pure formatters [src/trading-hub-format.js](src/trading-hub-format.js), surface + doc directory [src/trading-hub-data.js](src/trading-hub-data.js), styles [src/trading-hub.css](src/trading-hub.css) | Live | One entry point for a trading system that had grown to ~20 pages with no front door. Live fleet vitals from `GET /api/sniper/status` (mode, armed strategies, open positions, feed health, funding, uptime), the agent scoreboard from `GET /api/sniper/leaderboard` (realized P&L only, closed trades only, with cumulative sparkline), the five-gate entry-to-exit explainer, and directories of every trading surface and doc. Feed health is reported separately from process health because a beating worker with a silent feed reads as green while seeing nothing. Directory is data, so [tests/trading-hub.test.js](tests/trading-hub.test.js) asserts every link resolves against `data/pages.json` and the docs tree. Docs: [docs/trading-hub.md](docs/trading-hub.md), tutorial [docs/tutorials/read-the-trading-fleet.md](docs/tutorials/read-the-trading-fleet.md) |
diff --git a/api/_lib/trade-room-presence.js b/api/_lib/trade-room-presence.js
new file mode 100644
index 000000000..4f028ad44
--- /dev/null
+++ b/api/_lib/trade-room-presence.js
@@ -0,0 +1,139 @@
+/**
+ * Spectator presence for live trade rooms.
+ *
+ * A spectator is an open room stream: /api/sniper/room-stream touches the
+ * viewer's session while the connection is up and removes it on close, so the
+ * number a room shows is "people with this room open right now", not a guess.
+ *
+ * Storage: one Redis sorted set per room (`traderoom:spec:<agentId>`), member =
+ * session id, score = the instant that session expires. A viewer whose tab dies
+ * without a clean close simply ages out after SPECTATOR_TTL_MS. Redis makes the
+ * count true across every Cloud Run instance (scope "shared").
+ *
+ * Failsafe: when Upstash is not configured or a command fails, presence falls
+ * back to an in-process map (scope "instance"). The room keeps a real, if
+ * partial, count instead of going dark; the scope rides along so the client can
+ * say which one it is showing.
+ */
+
+import { getRedis } from './redis.js';
+
+export const SPECTATOR_TTL_MS = 30_000;
+const KEY_PREFIX = 'traderoom:spec:';
+const KEY_EXPIRE_SEC = 120;
+/** Hard ceiling on in-process sessions so untrusted ids cannot grow the heap. */
+const LOCAL_MAX_SESSIONS = 5_000;
+
+/** @type {Map<string, Map<string, number>>} agentId -> (session -> expiresAt) */
+const local = new Map();
+
+function key(agentId) {
+ return KEY_PREFIX + agentId;
+}
+
+function localPrune(now) {
+ for (const [agentId, sessions] of local) {
+ for (const [session, exp] of sessions) if (exp <= now) sessions.delete(session);
+ if (!sessions.size) local.delete(agentId);
+ }
+}
+
+function localSize() {
+ let n = 0;
+ for (const s of local.values()) n += s.size;
+ return n;
+}
+
+function localTouch(agentId, session, now) {
+ localPrune(now);
+ let sessions = local.get(agentId);
+ if (!sessions?.has(session) && localSize() >= LOCAL_MAX_SESSIONS) return;
+ if (!sessions) {
+ sessions = new Map();
+ local.set(agentId, sessions);
+ }
+ sessions.set(session, now + SPECTATOR_TTL_MS);
+}
+
+function localCount(agentId, now) {
+ localPrune(now);
+ return local.get(agentId)?.size || 0;
+}
+
+/**
+ * Mark a session as watching a room (call on connect and every ~10s).
+ * @returns {Promise<'shared'|'instance'>} where the mark landed
+ */
+export async function touchSpectator(agentId, session, now = Date.now()) {
+ const r = getRedis();
+ if (r) {
+ try {
+ await Promise.all([
+ r.zadd(key(agentId), { score: now + SPECTATOR_TTL_MS, member: session }),
+ r.expire(key(agentId), KEY_EXPIRE_SEC),
+ ]);
+ return 'shared';
+ } catch {
+ /* fall through to the in-process count */
+ }
+ }
+ localTouch(agentId, session, now);
+ return 'instance';
+}
+
+/** Remove a session from a room (call when its stream closes). Never throws. */
+export async function leaveSpectator(agentId, session) {
+ local.get(agentId)?.delete(session);
+ const r = getRedis();
+ if (!r) return;
+ try {
+ await r.zrem(key(agentId), session);
+ } catch {
+ /* the member ages out on its own after SPECTATOR_TTL_MS */
+ }
+}
+
+/**
+ * Live spectators in one room.
+ * @returns {Promise<{count: number, scope: 'shared'|'instance'}>}
+ */
+export async function countSpectators(agentId, now = Date.now()) {
+ const r = getRedis();
+ if (r) {
+ try {
+ const n = await r.zcount(key(agentId), now, '+inf');
+ return { count: Number(n) || 0, scope: 'shared' };
+ } catch {
+ /* fall through */
+ }
+ }
+ return { count: localCount(agentId, now), scope: 'instance' };
+}
+
+/**
+ * Live spectators for many rooms at once (the lobby).
+ * @param {string[]} agentIds
+ * @returns {Promise<Map<string, number>>}
+ */
+export async function countSpectatorsMany(agentIds, now = Date.now()) {
+ const ids = [...new Set((agentIds || []).filter(Boolean))];
+ const out = new Map();
+ if (!ids.length) return out;
+ const r = getRedis();
+ if (r) {
+ try {
+ const counts = await Promise.all(ids.map((id) => r.zcount(key(id), now, '+inf')));
+ ids.forEach((id, i) => out.set(id, Number(counts[i]) || 0));
+ return out;
+ } catch {
+ out.clear();
+ }
+ }
+ for (const id of ids) out.set(id, localCount(id, now));
+ return out;
+}
+
+/** Test hook: forget every in-process session. */
+export function _resetLocalPresence() {
+ local.clear();
+}
diff --git a/api/_lib/trade-room.js b/api/_lib/trade-room.js
new file mode 100644
index 000000000..58793fa01
--- /dev/null
+++ b/api/_lib/trade-room.js
@@ -0,0 +1,422 @@
+/**
+ * Live trade rooms: the read model behind /trade-rooms and /trade-rooms/:id.
+ *
+ * A trade room is one leader's corner of the world: their 3D body, their real
+ * trades landing as they happen, the people watching, and the one-tap paths
+ * out (ghost-copy, copy, fork). Every number here comes from the canonical
+ * sniper ledger (`agent_sniper_positions`), the same rows /trader/:id and the
+ * leaderboard read, so a room can never tell a different story than the
+ * profile it links to.
+ *
+ * Two layers, like trader-stats.js:
+ * - PURE: positionEvents, eventsSince, rankRooms, sanitizeSession,
+ * streamStartCursor, plus roomState, which lives in src/trade-room/model.js
+ * so the page and the API compute liveliness identically. No DB, no
+ * network; the tests pin them.
+ * - LOADERS: loadRoom, listRooms, loadRoomAgent, fetchChangedPositions. They
+ * fetch rows and defer every derivation to the pure layer.
+ *
+ * Honesty rules:
+ * - A position becomes up to two events: the buy at opened_at and, once it
+ * closes, the sell at closed_at. A failed position (the buy never landed)
+ * is never shown as a trade.
+ * - Paper fills (buy_sig = SIMULATED) are labeled paper, never passed off as
+ * on-chain trades, and carry no Solscan link.
+ * - Private or deleted agents have no room, the same visibility gate
+ * /api/sniper/trader and /api/sniper/receipt apply.
+ */
+
+import { sql } from './db.js';
+import { thumbnailUrl } from './r2.js';
+import { resolveAvatarUrl } from './avatars.js';
+import { computeTraderMetrics, fetchTraderPositions, cachedSolUsd, shapeOpen } from './trader-stats.js';
+import { exitReasonLabel, solscanTx, SIMULATED_SIG } from './trade-card.js';
+import { roomState, LIVE_WINDOW_MS, WARM_WINDOW_MS } from '../../src/trade-room/model.js';
+
+export { roomState, LIVE_WINDOW_MS, WARM_WINDOW_MS };
+
+const LAMPORTS_PER_SOL = 1e9;
+
+/** How far back the lobby looks for leaders worth a room. */
+export const LOBBY_LOOKBACK_DAYS = 90;
+/** Events a room snapshot carries. */
+export const ROOM_EVENT_LIMIT = 30;
+/** Window the room's headline stats cover. */
+export const ROOM_STATS_WINDOW = '30d';
+
+const LIVE_STATUSES = ['open', 'opening', 'closing'];
+const TRADED_STATUSES = ['open', 'closing', 'closed'];
+
+const SESSION_RE = /^[A-Za-z0-9_-]{8,40}$/;
+/** Furthest back a stream may start, so a stale tab cannot replay the ledger. */
+export const STREAM_SINCE_MAX_AGE_MS = 10 * 60_000;
+
+function lamToSol(v) {
+ if (v == null) return null;
+ try {
+ return Number(BigInt(v)) / LAMPORTS_PER_SOL;
+ } catch {
+ const n = Number(v);
+ return Number.isFinite(n) ? n / LAMPORTS_PER_SOL : null;
+ }
+}
+
+function num(v) {
+ if (v == null) return null;
+ const n = Number(v);
+ return Number.isFinite(n) ? n : null;
+}
+
+function ms(v) {
+ if (v == null) return null;
+ const t = new Date(v).getTime();
+ return Number.isFinite(t) ? t : null;
+}
+
+function iso(v) {
+ const t = ms(v);
+ return t == null ? null : new Date(t).toISOString();
+}
+
+/**
+ * Validate a client-chosen spectator session id. It is untrusted input that
+ * becomes a Redis member, so only a short, plain token is accepted.
+ * @param {unknown} raw
+ * @returns {string|null}
+ */
+export function sanitizeSession(raw) {
+ return typeof raw === 'string' && SESSION_RE.test(raw) ? raw : null;
+}
+
+/**
+ * The stream's starting cursor (ms) from the client's `since`. PURE.
+ * Missing or unparseable: now. Future: now. Older than the cap: the cap.
+ * @param {unknown} raw ISO timestamp of the newest event the page painted
+ * @param {number} [now]
+ */
+export function streamStartCursor(raw, now = Date.now()) {
+ const t = typeof raw === 'string' && raw ? new Date(raw).getTime() : NaN;
+ if (!Number.isFinite(t)) return now;
+ return Math.min(now, Math.max(now - STREAM_SINCE_MAX_AGE_MS, t));
+}
+
+/**
+ * Turn position rows into the room's trade events, newest first. PURE.
+ *
+ * Each traded position yields a buy (at opened_at) and, once closed, a sell
+ * (at closed_at). Sizes are the SOL that actually moved: the entry quote for a
+ * buy, the exit quote for a sell. Rows that never filled are skipped.
+ *
+ * @param {object[]} rows agent_sniper_positions rows
+ * @param {{network?: string, limit?: number}} [opts]
+ * @returns {object[]}
+ */
+export function positionEvents(rows, { network = 'mainnet', limit = ROOM_EVENT_LIMIT } = {}) {
+ const out = [];
+ for (const r of rows || []) {
+ if (!r || !TRADED_STATUSES.includes(r.status)) continue;
+ const openedAt = iso(r.opened_at);
+ if (!openedAt) continue;
+ const paper = !r.buy_sig || r.buy_sig === SIMULATED_SIG;
+ const base = {
+ position_id: r.id,
+ mint: r.mint,
+ symbol: r.symbol || null,
+ name: r.name || null,
+ paper,
+ status: r.status,
+ entry_sol: lamToSol(r.entry_quote_lamports),
+ };
+ out.push({
+ ...base,
+ id: `${r.id}:buy`,
+ kind: 'buy',
+ at: openedAt,
+ size_sol: base.entry_sol,
+ tx_url: solscanTx(r.buy_sig, network),
+ });
+ const closedAt = r.status === 'closed' ? iso(r.closed_at) : null;
+ if (closedAt) {
+ out.push({
+ ...base,
+ id: `${r.id}:sell`,
+ kind: 'sell',
+ at: closedAt,
+ size_sol: lamToSol(r.exit_quote_lamports),
+ pnl_sol: lamToSol(r.realized_pnl_lamports),
+ pnl_pct: num(r.realized_pnl_pct),
+ exit_reason: r.exit_reason || null,
+ exit_label: exitReasonLabel(r.exit_reason),
+ hold_seconds: Math.max(0, Math.round((ms(closedAt) - ms(openedAt)) / 1000)),
+ tx_url: solscanTx(r.sell_sig, network),
+ share_url: `/trade/${r.id}`,
+ });
+ }
+ }
+ out.sort((a, b) => ms(b.at) - ms(a.at) || (a.kind === 'sell' ? -1 : 1));
+ return limit > 0 ? out.slice(0, limit) : out;
+}
+
+/**
+ * Everything that happened to a set of changed rows after a cursor, oldest
+ * first, for the live stream. PURE.
+ *
+ * Deriving from timestamps (not from "what changed last") means a position
+ * that opens and closes inside one poll interval still emits its buy before
+ * its sell, and an open position whose quote moved emits a `quote` update.
+ *
+ * @param {object[]} rows changed agent_sniper_positions rows
+ * @param {number} cursorMs events at or before this instant were already sent
+ * @param {{network?: string}} [opts]
+ * @returns {{trades: object[], quotes: object[]}}
+ */
+export function eventsSince(rows, cursorMs, { network = 'mainnet' } = {}) {
+ const trades = positionEvents(rows, { network, limit: 0 })
+ .filter((e) => ms(e.at) > cursorMs)
+ .reverse();
+ const quotes = [];
+ for (const r of rows || []) {
+ if (!LIVE_STATUSES.includes(r.status) || !r.buy_sig) continue;
+ const quotedAt = ms(r.last_quoted_at);
+ if (quotedAt == null || quotedAt <= cursorMs) continue;
+ const shaped = shapeOpen(r, network);
+ quotes.push({
+ position_id: r.id,
+ symbol: shaped.symbol || null,
+ current_sol: shaped.current_sol,
+ unrealized_pct: shaped.unrealized_pct,
+ at: new Date(quotedAt).toISOString(),
+ });
+ }
+ return { trades, quotes };
+}
+
+const STATE_RANK = { live: 0, warm: 1, quiet: 2 };
+
+/**
+ * Order lobby rooms: live first, then by who is watching, then by recency.
+ * PURE; returns a new array.
+ * @param {object[]} rooms each with state, spectators, last_trade_at
+ */
+export function rankRooms(rooms) {
+ return [...(rooms || [])].sort(
+ (a, b) =>
+ (STATE_RANK[a.state] ?? 3) - (STATE_RANK[b.state] ?? 3) ||
+ (Number(b.spectators) || 0) - (Number(a.spectators) || 0) ||
+ (ms(b.last_trade_at) ?? 0) - (ms(a.last_trade_at) ?? 0),
+ );
+}
+
+/**
+ * The leader's 3D body, only when its avatar is public or unlisted. A private
+ * model resolves to null and the room stands the platform default in its place.
+ */
+async function modelFor(row) {
+ if (!row?.avatar_row_id || !row.storage_key) return null;
+ if (row.avatar_visibility !== 'public' && row.avatar_visibility !== 'unlisted') return null;
+ const { url } = await resolveAvatarUrl({
+ id: row.avatar_row_id,
+ storage_key: row.storage_key,
+ baked_storage_key: row.baked_storage_key,
+ appearance_hash: row.appearance_hash,
+ appearance: row.appearance,
+ visibility: row.avatar_visibility,
+ });
+ return url || null;
+}
+
+function thumbFor(row) {
+ if (row.profile_image_url || row.avatar_url) return row.profile_image_url || row.avatar_url;
+ const readable = row.avatar_visibility === 'public' || row.avatar_visibility === 'unlisted';
+ return readable && row.thumbnail_key ? thumbnailUrl(row.thumbnail_key) : null;
+}
+
+/**
+ * The public agent behind a room, or null when it is unknown, deleted or
+ * private. Shared by the snapshot and the stream so both apply one gate.
+ * @param {string} agentId
+ */
+export async function loadRoomAgent(agentId) {
+ const [row] = await sql`
+ select i.id, i.name, i.description, i.avatar_url, i.profile_image_url,
+ a.id as avatar_row_id, a.storage_key, a.baked_storage_key, a.appearance_hash,
+ a.appearance, a.visibility as avatar_visibility, a.thumbnail_key
+ from agent_identities i
+ left join avatars a on a.id = i.avatar_id and a.deleted_at is null
+ where i.id = ${agentId} and i.deleted_at is null and i.is_public is not false
+ limit 1
+ `;
+ return row || null;
+}
+
+/** Recent traded positions for one leader, newest activity first. */
+async function recentPositions(agentId, network, limit) {
+ return sql`
+ select p.id, p.agent_id, p.wallet, p.mint, p.symbol, p.name, p.status, p.exit_reason,
+ p.entry_quote_lamports, p.exit_quote_lamports, p.last_value_lamports,
+ p.realized_pnl_lamports, p.realized_pnl_pct, p.buy_sig, p.sell_sig,
+ p.opened_at, p.closed_at, p.last_quoted_at
+ from agent_sniper_positions p
+ where p.agent_id = ${agentId} and p.network = ${network}
+ and p.status in ('open', 'closing', 'closed')
+ order by greatest(p.opened_at, coalesce(p.closed_at, p.opened_at)) desc
+ limit ${limit}
+ `;
+}
+
+/** Active copiers for one leader. Best-effort: an unmigrated table reads as 0. */
+async function copierCount(agentId, network) {
+ try {
+ const [row] = await sql`
+ select count(*)::int as copiers from copy_subscriptions
+ where leader_agent_id = ${agentId} and network = ${network} and status = 'active'
+ `;
+ return Number(row?.copiers) || 0;
+ } catch {
+ return 0;
+ }
+}
+
+/**
+ * Full room snapshot for one leader. Returns null when there is no public
+ * agent behind the id. A public agent that has never traded still gets a room
+ * (an empty floor that says so), never a 404.
+ *
+ * @param {{agentId: string, network?: string, spectators?: {count: number|null, scope: string}|null, now?: number}} input
+ */
+export async function loadRoom({ agentId, network = 'mainnet', spectators = null, now = Date.now() }) {
+ const agent = await loadRoomAgent(agentId);
+ if (!agent) return null;
+
+ const [recent, windowPositions, solUsd, copiers, modelUrl] = await Promise.all([
+ recentPositions(agentId, network, ROOM_EVENT_LIMIT),
+ fetchTraderPositions({ agentId, network, window: ROOM_STATS_WINDOW, now }),
+ cachedSolUsd(),
+ copierCount(agentId, network),
+ modelFor(agent).catch(() => null),
+ ]);
+
+ const metrics = computeTraderMetrics(windowPositions, { solUsd });
+ const trades = positionEvents(recent, { network });
+ const open = windowPositions
+ .filter((p) => LIVE_STATUSES.includes(p.status) && p.buy_sig)
+ .map((p) => shapeOpen(p, network));
+ const lastTradeAt = trades[0]?.at || null;
+
+ return {
+ network,
+ leader: {
+ id: agent.id,
+ name: agent.name || 'Unnamed trader',
+ description: agent.description || null,
+ image: thumbFor(agent),
+ model_url: modelUrl,
+ wallet: windowPositions[0]?.wallet || recent[0]?.wallet || null,
+ copiers,
+ },
+ room: {
+ state: roomState({ lastTradeAt, openCount: open.length, now }),
+ last_trade_at: lastTradeAt,
+ spectators: spectators ? spectators.count : null,
+ presence_scope: spectators ? spectators.scope : null,
+ },
+ stats: {
+ window: ROOM_STATS_WINDOW,
+ score: metrics.score,
+ verified: metrics.verified,
+ closed_count: metrics.closed_count,
+ win_rate: metrics.win_rate,
+ realized_pnl_sol: metrics.realized_pnl_sol,
+ realized_pnl_usd: metrics.realized_pnl_usd,
+ best_pnl_pct: metrics.best_pnl_pct,
+ },
+ open,
+ trades,
+ sol_usd: solUsd,
+ t: now,
+ };
+}
+
+/**
+ * Lobby: every public leader with a trade inside LOBBY_LOOKBACK_DAYS or an
+ * open position, with liveliness, spectators, and a 24h activity count.
+ *
+ * @param {{network?: string, limit?: number, spectatorCounts?: (ids: string[]) => Promise<Map<string, number>>, now?: number}} input
+ */
+export async function listRooms({ network = 'mainnet', limit = 24, spectatorCounts = null, now = Date.now() } = {}) {
+ const since = new Date(now - LOBBY_LOOKBACK_DAYS * 86_400_000).toISOString();
+ const dayAgo = new Date(now - 86_400_000).toISOString();
+ const weekAgo = new Date(now - 7 * 86_400_000).toISOString();
+ const rows = await sql`
+ select p.agent_id,
+ i.name, i.avatar_url, i.profile_image_url,
+ a.thumbnail_key, a.visibility as avatar_visibility,
+ count(*) filter (where p.status in ('open', 'opening', 'closing') and p.buy_sig is not null)::int as open_count,
+ (count(*) filter (where p.opened_at > ${dayAgo})
+ + count(*) filter (where p.closed_at > ${dayAgo}))::int as fills_24h,
+ coalesce(sum(p.realized_pnl_lamports) filter (where p.status = 'closed' and p.closed_at > ${weekAgo}), 0) as pnl_7d_lamports,
+ count(*) filter (where p.status = 'closed' and p.closed_at > ${weekAgo})::int as closed_7d,
+ count(*) filter (where p.status = 'closed' and p.closed_at > ${weekAgo} and p.realized_pnl_lamports > 0)::int as wins_7d,
+ max(greatest(p.opened_at, coalesce(p.closed_at, p.opened_at))) as last_trade_at
+ from agent_sniper_positions p
+ join agent_identities i on i.id = p.agent_id and i.deleted_at is null and i.is_public is not false
+ left join avatars a on a.id = i.avatar_id and a.deleted_at is null
+ where p.network = ${network}
+ and p.status in ('open', 'closing', 'closed')
+ and (p.status <> 'closed' or greatest(p.opened_at, coalesce(p.closed_at, p.opened_at)) > ${since})
+ group by p.agent_id, i.name, i.avatar_url, i.profile_image_url, a.thumbnail_key, a.visibility
+ order by last_trade_at desc
+ limit 60
+ `;
+ const ids = rows.map((r) => r.agent_id);
+ let counts = new Map();
+ if (spectatorCounts && ids.length) {
+ try {
+ counts = await spectatorCounts(ids);
+ } catch {
+ counts = new Map();
+ }
+ }
+ const rooms = rows.map((r) => {
+ const lastTradeAt = iso(r.last_trade_at);
+ return {
+ agent_id: r.agent_id,
+ name: r.name || 'Unnamed trader',
+ image: thumbFor(r),
+ state: roomState({ lastTradeAt, openCount: Number(r.open_count) || 0, now }),
+ last_trade_at: lastTradeAt,
+ open_count: Number(r.open_count) || 0,
+ fills_24h: Number(r.fills_24h) || 0,
+ pnl_7d_sol: lamToSol(r.pnl_7d_lamports) ?? 0,
+ closed_7d: Number(r.closed_7d) || 0,
+ win_rate_7d: Number(r.closed_7d) > 0 ? Number(r.wins_7d) / Number(r.closed_7d) : null,
+ spectators: counts.get(r.agent_id) ?? 0,
+ url: `/trade-rooms/${r.agent_id}`,
+ };
+ });
+ return rankRooms(rooms).slice(0, Math.max(1, Math.min(60, limit)));
+}
+
+/**
+ * Rows for one leader whose open, close, or quote time moved past a cursor.
+ * The stream's only DB read; the derivation lives in eventsSince().
+ * @param {{agentId: string, network: string, cursorIso: string}} input
+ */
+export async function fetchChangedPositions({ agentId, network, cursorIso }) {
+ return sql`
+ select p.id, p.agent_id, p.mint, p.symbol, p.name, p.status, p.exit_reason,
+ p.entry_quote_lamports, p.exit_quote_lamports, p.last_value_lamports,
+ p.realized_pnl_lamports, p.realized_pnl_pct, p.buy_sig, p.sell_sig,
+ p.opened_at, p.closed_at, p.last_quoted_at,
+ greatest(p.opened_at, coalesce(p.closed_at, p.opened_at),
+ coalesce(p.last_quoted_at, p.opened_at)) as changed_at
+ from agent_sniper_positions p
+ where p.agent_id = ${agentId} and p.network = ${network}
+ and p.status in ('open', 'opening', 'closing', 'closed')
+ and greatest(p.opened_at, coalesce(p.closed_at, p.opened_at),
+ coalesce(p.last_quoted_at, p.opened_at)) > ${cursorIso}
+ order by changed_at asc
+ limit 100
+ `;
+}
+
diff --git a/api/sniper/room-stream.js b/api/sniper/room-stream.js
new file mode 100644
index 000000000..f0156f088
--- /dev/null
+++ b/api/sniper/room-stream.js
@@ -0,0 +1,154 @@
+/**
+ * Live trade room: one leader's SSE stream.
+ *
+ * GET /api/sniper/room-stream?agent_id=<uuid>&network=mainnet&since=<iso>&session=<id>
+ *
+ * The sniper worker is a separate process, so like /api/sniper/stream this
+ * DB-polls agent_sniper_positions (every POLL_INTERVAL_MS) for this leader's
+ * rows that moved past a cursor, and derives what happened from timestamps
+ * (api/_lib/trade-room.js eventsSince), so a position that opens and closes
+ * inside one poll still emits its buy before its sell.
+ *
+ * `since` is the newest event the page already painted from /api/sniper/room,
+ * so nothing falls in the gap between snapshot and stream. It is clamped to ten
+ * minutes back so a stale tab cannot ask for a replay of the whole ledger.
+ *
+ * `session` is the viewer's random tab id. While the connection is open the
+ * session counts as a spectator of this room (api/_lib/trade-room-presence.js)
+ * and is removed on close, so the room's "watching" number is live.
+ *
+ * Events:
+ * open { agent_id, network, spectators, presence_scope }
+ * trade one positionEvents() row (kind buy | sell)
+ * quote { position_id, symbol, current_sol, unrealized_pct, at }
+ * presence { spectators, presence_scope }
+ * ping { t }
+ * error { message }
+ * close { reason } the client reconnects with its newest `since`
+ */
+
+import { cors, method, rateLimited, error } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { isUuid } from '../_lib/validate.js';
+import {
+ loadRoomAgent, fetchChangedPositions, eventsSince, sanitizeSession, streamStartCursor,
+} from '../_lib/trade-room.js';
+import { touchSpectator, leaveSpectator, countSpectators } from '../_lib/trade-room-presence.js';
+
+const MAX_DURATION_MS = 90_000;
+const PING_INTERVAL_MS = 15_000;
+const POLL_INTERVAL_MS = 2_000;
+const PRESENCE_TOUCH_MS = 10_000;
+const PRESENCE_READ_MS = 5_000;
+const NETWORKS = new Set(['mainnet', 'devnet']);
+
+export default async function handleRoomStream(req, res) {
+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const rl = await limits.mcpIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const url = new URL(req.url, `http://${req.headers.host || 'x'}`);
+ const agentId = (url.searchParams.get('agent_id') || '').trim();
+ const network = NETWORKS.has(url.searchParams.get('network')) ? url.searchParams.get('network') : 'mainnet';
+ const session = sanitizeSession(url.searchParams.get('session'));
+ if (!isUuid(agentId)) return error(res, 400, 'invalid_agent', 'agent_id must be a valid agent UUID');
+
+ let agent;
+ try {
+ agent = await loadRoomAgent(agentId);
+ } catch {
+ return error(res, 503, 'unavailable', 'The trade ledger is unreachable right now. Retry in a moment.');
+ }
+ if (!agent) return error(res, 404, 'not_found', 'No such trader, or it is not public.');
+
+ res.writeHead(200, {
+ 'Content-Type': 'text/event-stream; charset=utf-8',
+ 'Cache-Control': 'no-cache, no-transform',
+ Connection: 'keep-alive',
+ 'X-Accel-Buffering': 'no',
+ });
+ res.flushHeaders?.();
+
+ let active = true;
+ const send = (event, data) => {
+ if (!active) return;
+ res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);
+ };
+
+ let cursorMs = streamStartCursor(url.searchParams.get('since'));
+ let polling = false;
+ let lastPresence = null;
+
+ const poll = async () => {
+ if (!active || polling) return;
+ polling = true;
+ try {
+ const rows = await fetchChangedPositions({ agentId, network, cursorIso: new Date(cursorMs).toISOString() });
+ if (rows.length) {
+ const { trades, quotes } = eventsSince(rows, cursorMs, { network });
+ for (const t of trades) send('trade', t);
+ for (const q of quotes) send('quote', q);
+ for (const r of rows) {
+ const changed = new Date(r.changed_at).getTime();
+ if (changed > cursorMs) cursorMs = changed;
+ }
+ }
+ } catch {
+ send('error', { message: 'poll_failed' });
+ } finally {
+ polling = false;
+ }
+ };
+
+ const readPresence = async () => {
+ if (!active) return;
+ try {
+ const p = await countSpectators(agentId);
+ if (!lastPresence || p.count !== lastPresence.count || p.scope !== lastPresence.scope) {
+ lastPresence = p;
+ send('presence', { spectators: p.count, presence_scope: p.scope });
+ }
+ } catch {
+ /* presence is decoration on top of the trades; never fail the stream for it */
+ }
+ };
+
+ if (session) await touchSpectator(agentId, session).catch(() => null);
+ const opening = await countSpectators(agentId).catch(() => null);
+ lastPresence = opening;
+ send('open', {
+ agent_id: agentId,
+ network,
+ spectators: opening ? opening.count : null,
+ presence_scope: opening ? opening.scope : null,
+ });
+
+ const pollTimer = setInterval(poll, POLL_INTERVAL_MS);
+ const presenceTimer = setInterval(readPresence, PRESENCE_READ_MS);
+ const touchTimer = session
+ ? setInterval(() => touchSpectator(agentId, session).catch(() => null), PRESENCE_TOUCH_MS)
+ : null;
+ const ping = setInterval(() => send('ping', { t: Date.now() }), PING_INTERVAL_MS);
+
+ // A duration-limit close keeps the session's presence: the client reconnects
+ // within a second, and a viewer who does not simply ages out of the TTL.
+ const teardown = ({ leave = true } = {}) => {
+ if (!active) return;
+ active = false;
+ clearInterval(pollTimer);
+ clearInterval(presenceTimer);
+ if (touchTimer) clearInterval(touchTimer);
+ clearInterval(ping);
+ clearTimeout(durationTimer);
+ if (session && leave) leaveSpectator(agentId, session).catch(() => null);
+ try { res.end(); } catch { /* socket already gone */ }
+ };
+ const durationTimer = setTimeout(() => {
+ send('close', { reason: 'duration_limit' });
+ teardown({ leave: false });
+ }, MAX_DURATION_MS);
+
+ req.on('close', () => teardown());
+}
diff --git a/api/sniper/room.js b/api/sniper/room.js
new file mode 100644
index 000000000..09cf0357c
--- /dev/null
+++ b/api/sniper/room.js
@@ -0,0 +1,42 @@
+/**
+ * Live trade room: one leader's snapshot.
+ *
+ * GET /api/sniper/room?agent_id=<uuid>&network=mainnet
+ *
+ * Everything the /trade-rooms/:id page paints before its live stream attaches:
+ * the leader (name, image, and their public 3D body when it has one), the
+ * room's liveliness and spectator count, 30-day headline stats from the shared
+ * trader-stats truth layer, open positions with live unrealized P&L, and the
+ * latest buys and sells (each linked to its Solscan tx and, once closed, its
+ * /trade/:id card). The live stream is /api/sniper/room-stream.
+ *
+ * Public + IP rate-limited, with the same visibility gate as
+ * /api/sniper/trader: a private or deleted agent has no room (404).
+ */
+
+import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { isUuid } from '../_lib/validate.js';
+import { loadRoom } from '../_lib/trade-room.js';
+import { countSpectators } from '../_lib/trade-room-presence.js';
+
+const NETWORKS = new Set(['mainnet', 'devnet']);
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const rl = await limits.publicIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const params = new URL(req.url, `http://${req.headers.host || 'x'}`).searchParams;
+ const agentId = (params.get('agent_id') || params.get('agent') || '').trim();
+ const network = NETWORKS.has(params.get('network')) ? params.get('network') : 'mainnet';
+ if (!isUuid(agentId)) return error(res, 400, 'invalid_agent', 'agent_id must be a valid agent UUID');
+
+ const spectators = await countSpectators(agentId);
+ const room = await loadRoom({ agentId, network, spectators });
+ if (!room) return error(res, 404, 'not_found', 'No such trader, or it is not public.');
+
+ return json(res, 200, room, { 'cache-control': 'public, max-age=5, s-maxage=10' });
+});
diff --git a/api/sniper/rooms.js b/api/sniper/rooms.js
new file mode 100644
index 000000000..3ca02eb94
--- /dev/null
+++ b/api/sniper/rooms.js
@@ -0,0 +1,35 @@
+/**
+ * Live trade rooms: the lobby.
+ *
+ * GET /api/sniper/rooms?network=mainnet&limit=24
+ *
+ * Every public leader with a real fill in the last 90 days (or a position open
+ * right now), ranked live first, then by spectators, then by recency. Each row
+ * carries the room's liveliness, when the leader last traded, their 24h fill
+ * count and 7-day realized P&L from the sniper ledger, and how many people are
+ * watching. Powers /trade-rooms and the "other rooms" rail inside a room.
+ *
+ * Public + IP rate-limited. Shape and ranking live in api/_lib/trade-room.js.
+ */
+
+import { cors, json, method, wrap, rateLimited } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { listRooms } from '../_lib/trade-room.js';
+import { countSpectatorsMany } from '../_lib/trade-room-presence.js';
+
+const NETWORKS = new Set(['mainnet', 'devnet']);
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const rl = await limits.publicIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const params = new URL(req.url, `http://${req.headers.host || 'x'}`).searchParams;
+ const network = NETWORKS.has(params.get('network')) ? params.get('network') : 'mainnet';
+ const limit = Math.max(1, Math.min(60, Number(params.get('limit')) || 24));
+
+ const rooms = await listRooms({ network, limit, spectatorCounts: countSpectatorsMany });
+ return json(res, 200, { network, rooms, t: Date.now() }, { 'cache-control': 'public, max-age=10, s-maxage=15' });
+});
diff --git a/data/changelog.json b/data/changelog.json
index 026e726f7..0e59dd6f4 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,15 @@
{
"$comment": "Curated changelog entries for three.ws, the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security, desktop (desktop entries become the desktop app's release notes). `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-09-29",
+ "title": "Watch traders trade live in their own 3D trade rooms",
+ "summary": "Every public trader now has a live trade room. Their avatar stands on the floor and reacts as each real buy and sell fills, the board and ticker tape fill with their trades, and everyone watching shows up in the room. Tap any trade for the receipt of why it was made, fork it into your own wallet, or ghost-copy the trader. A quiet room still shows the latest real trades and which rooms are live right now, and the whole room also works as an accessible live list.",
+ "tags": [
+ "feature"
+ ],
+ "link": "/trade-rooms"
+ },
{
"date": "2026-09-25",
"title": "The model catalog AI clients read now shows the real price of every model",
diff --git a/data/pages.json b/data/pages.json
index bda551981..3a5d8ad40 100644
--- a/data/pages.json
+++ b/data/pages.json
@@ -1768,6 +1768,14 @@
"changefreq": "weekly",
"added": "2026-06-16"
},
+ {
+ "path": "/trade-rooms",
+ "title": "Live Trade Rooms: watch pump.fun traders trade live in 3D",
+ "description": "Step into a trader's 3D room and watch their real pump.fun buys and sells land as they fill: the avatar reacts, every trade carries its receipt, P&L and Solscan tx, and one tap forks the trade or ghost-copies the trader. Quiet rooms show the latest real trades and which rooms are live now.",
+ "priority": 0.7,
+ "changefreq": "always",
+ "added": "2026-09-29"
+ },
{
"path": "/ghost-copy",
"title": "Ghost-copy: what if you'd copied them?",
@@ -5977,6 +5985,14 @@
"changefreq": "monthly",
"added": "2026-09-03"
},
+ {
+ "path": "/docs/trade-rooms",
+ "title": "Docs · Live trade rooms",
+ "description": "How live trade rooms work: the trader's 3D avatar reacting to each real fill, the board and ticker tape, spectator presence, the receipt, Fork, ghost-copy and copy on every trade, the list view and frame budget, and the rooms, room and SSE stream APIs.",
+ "priority": 0.6,
+ "changefreq": "monthly",
+ "added": "2026-09-29"
+ },
{
"path": "/docs/trade-receipts",
"title": "Docs · Trade receipts",
diff --git a/docs/api-reference.md b/docs/api-reference.md
index d518c7639..6f8ff12ed 100644
--- a/docs/api-reference.md
+++ b/docs/api-reference.md
@@ -3978,6 +3978,79 @@ subject, slot, block_time, payload, reasons[] }`; every failed check is named in
---
+## Trade rooms API
+
+The data behind the live trade rooms (`/trade-rooms`). Every number comes from
+the sniper ledger (`agent_sniper_positions`), the same rows the leaderboard and
+`/trader/:id` read. Public, IP rate-limited, and gated like
+`/api/sniper/trader`: a private or deleted agent has no room. Full guide:
+[docs/trade-rooms.md](trade-rooms.md).
+
+### List rooms
+
+```
+GET /api/sniper/rooms?network=mainnet&limit=24
+```
+
+Every public trader with a fill in the last 90 days or a position open now,
+ranked live first, then by spectators, then by recency. `limit` is 1 to 60
+(default 24). Cached 10s.
+
+Each row: `agent_id`, `name`, `image`, `state` (`live` / `warm` / `quiet`),
+`last_trade_at`, `open_count`, `fills_24h` (buys plus sells), `pnl_7d_sol`,
+`closed_7d`, `win_rate_7d` (null with no closes), `spectators`, `url`.
+
+### Read one room
+
+```
+GET /api/sniper/room?agent_id=<uuid>&network=mainnet
+```
+
+Returns `leader` (`id`, `name`, `description`, `image`, `model_url` for a
+public or unlisted 3D body else null, `wallet`, `copiers`), `room` (`state`,
+`last_trade_at`, `spectators`, `presence_scope` of `shared` or `instance`),
+`stats` over 30 days (`score`, `verified`, `closed_count`, `win_rate`,
+`realized_pnl_sol`, `realized_pnl_usd`, `best_pnl_pct`), `open` positions with
+live `unrealized_pct`, and `trades`: the 30 newest events. Each position is a
+`buy` event at its open and, once closed, a `sell` event at its close:
+`id`, `kind`, `position_id`, `mint`, `symbol`, `name`, `at`, `size_sol` (the SOL
+that moved), `entry_sol`, `paper`, `tx_url` (null for paper), and on sells
+`pnl_sol`, `pnl_pct`, `exit_reason`, `exit_label`, `hold_seconds`, `share_url`.
+Cached 5s.
+
+| Status | Code | Meaning |
+| ------ | ---- | ------- |
+| `400` | `invalid_agent` | `agent_id` is not a UUID |
+| `404` | `not_found` | No such agent, or it is not public |
+| `429` | `rate_limited` | Over the public per-IP limit |
+
+### Stream a room (SSE)
+
+```
+GET /api/sniper/room-stream?agent_id=<uuid>&network=mainnet&since=<iso>&session=<id>
+```
+
+`since` is the newest event you already have (clamped to ten minutes back;
+omitted means now). `session` is an optional 8 to 40 character `[A-Za-z0-9_-]`
+id; while the connection is open it counts as a spectator of the room. The
+connection closes after 90s with a `close` event; reconnect with your newest
+`since`.
+
+| Event | Data |
+| ----- | ---- |
+| `open` | `{ agent_id, network, spectators, presence_scope }` |
+| `trade` | one trade event, same shape as `trades[]` above, oldest first |
+| `quote` | `{ position_id, symbol, current_sol, unrealized_pct, at }` for an open position |
+| `presence` | `{ spectators, presence_scope }` when the count changes |
+| `ping` | `{ t }` every 15s |
+| `error` | `{ message: "poll_failed" }` when one ledger poll fails; the stream keeps going |
+| `close` | `{ reason: "duration_limit" }` |
+
+Errors before the stream opens: `400 invalid_agent`, `404 not_found`,
+`503 unavailable` (ledger unreachable), `429`.
+
+---
+
## Authentication API
Authentication is covered in detail in the [Authentication documentation](authentication.md). Quick reference:
diff --git a/docs/start-here.md b/docs/start-here.md
index d79ea0801..db564942a 100644
--- a/docs/start-here.md
+++ b/docs/start-here.md
@@ -146,6 +146,7 @@ Want the model in your hands rather than on a screen? [Materialize](./materializ
- **Following a trader instead of picking?** → [Copy trading](./copy-trading.md): follow a leader two ways, either your agent mirroring real Solana trades inside its own spend policy, or sized intents you sign yourself. Nothing is simulated, so the doc covers the leaderboard weighting, the Smart Money directory, and how performance fees accrue
- **Found a coin and want to act on it now?** → [Fork a trade](./fork-trade.md): one tap on any coin across the Radar, the Live Trade Feed, the Smart Money Radar, or a ghost-copy replay opens the real pump.fun trade panel for it, pre-filled with the size being forked and signed by your own wallet. No custody, no delegated key, the same safety firewall as every other trade surface, and a `?fork=` link so a coin can travel to X or Telegram and open the panel on arrival
- **Want to know why a trader bought before you copy it?** → [Trade receipts](./trade-receipts.md): press **why** on any closed trade on a track record to see the evidence the agent had at decision time (the entry trigger, the Oracle score and its base-rate reasons, the on-chain firewall simulation, the LLM judge, the Risk Officer, paid x402 reads with their payment tx) and every leg on Solscan. Evidence logged after the exit is left out
+- **Want to watch a trader work before you copy them?** → [Live trade rooms](./trade-rooms.md): step into any public trader's 3D room and see their real buys and sells land as they fill, with the avatar reacting, the receipt for why on every trade, one-tap Fork, and ghost-copy or copy from the same page. A quiet room still shows their latest real trades and which rooms are live right now
- **Not ready to risk money on a trader yet?** → [Ghost-copy](./ghost-copy.md): paper-copy any verified agent over their real closed on-chain trades and see the equity curve your budget would have had, sized by the same engine that runs live copy trades. No wallet, no signature, no account, and every trade your budget could not reach is listed with the reason
- **Have an audience of your own?** → [The trader card](./trader-card-embed.md): one script tag puts a trader's live on-chain record on your site, blog, link in bio or stream overlay, with a Fork button on every coin and a ghost-copy call to action, all signed by the reader's own wallet. It carries your referral code, holds no funds and asks for no key
- **Running the platform?** → [Trading growth programs](./growth-programs.md): the big-win X poster, the first-rug softener and the early-leader $THREE bonus. All three ship disarmed; the page shows how to read what each would do today, every flag and cap, and the exact steps to arm one
diff --git a/docs/trade-rooms.md b/docs/trade-rooms.md
new file mode 100644
index 000000000..173844b58
--- /dev/null
+++ b/docs/trade-rooms.md
@@ -0,0 +1,137 @@
+# Live trade rooms: watch a trader trade, live
+
+A leaderboard tells you who is good. A trade room lets you watch them work.
+Every public trader on three.ws has a room: their 3D avatar stands on a lit
+pedestal, a trade board and an LED ticker tape behind them fill with their
+real pump.fun buys and sells, and the people watching stand around the floor.
+When a trade fills on-chain it lands in the room within a couple of seconds.
+The avatar reacts, and the trade shows up with its receipt ("why"), its
+transaction, and a one-tap Fork.
+
+Pages: [/trade-rooms](https://three.ws/trade-rooms) (the lobby) and
+`/trade-rooms/<agent id>` (one trader's room). Reached from the "Watch live
+room" button on every trader profile (`/trader/:id`), the
+[leaderboard](https://three.ws/leaderboard) hero, and the site nav under Live
+Trade Rooms.
+
+Code: page [pages/trade-room.html](../pages/trade-room.html), controller
+[src/trade-room/main.js](../src/trade-room/main.js), 3D scene
+[src/trade-room/scene.js](../src/trade-room/scene.js), shared pure model
+[src/trade-room/model.js](../src/trade-room/model.js), read model
+[api/_lib/trade-room.js](../api/_lib/trade-room.js), presence
+[api/_lib/trade-room-presence.js](../api/_lib/trade-room-presence.js).
+
+## What you see in a room
+
+- **The trader.** Their own 3D body when their avatar is public or unlisted.
+ A private body, or a trader with no body yet, is stood in by the platform's
+ default avatar, and the room says so. Animation runs through the same rig
+ path as `/play` (`src/game/avatar-rig.js`), so any humanoid rig works.
+- **Reactions.** A buy makes the trader point; a sell reacts to how it went: a
+ nod for a flat exit, a celebration for a win (a cheer past +50%), a shrug for
+ a small loss and a slump for a big one. The pedestal ring flashes the trade's
+ color (blue buy, green win, red loss) and coins burst from it.
+- **The board and the tape.** The six newest fills on a board behind the
+ trader, and a scrolling LED tape above it with the newest eight as sentences.
+- **The crowd.** One figure per person with the room open right now, standing
+ in the round at the sides and back of the pedestal (capped by device tier;
+ the "watching" count above the stage is always the real number).
+- **The side column.** The trader's 30-day win rate, realized P&L, closed
+ trades and best trade (from the same truth layer as the leaderboard), when
+ they last traded, their open positions with live unrealized P&L, the receipt
+ summary for their latest trade, and the full trade list.
+
+## Acting from a room
+
+| Action | Where | What it does |
+|---|---|---|
+| Fork | Every trade | Opens the real pump.fun trade panel for that coin, pre-filled with the trader's entry size, signed by your wallet. See [Fork a trade](./fork-trade.md). |
+| Why | Every trade | Expands the full [trade receipt](./trade-receipts.md): trigger, Oracle score, firewall simulation, LLM judge, Risk Officer, paid reads, every leg. |
+| Card | Every closed trade | The trade's shareable `/trade/:id` page. |
+| tx | Every on-chain fill | The Solscan transaction. Paper fills have none and are labeled paper. |
+| Ghost-copy | Side column | [Ghost-copy](./ghost-copy.md) this trader with a paper budget. |
+| Copy trades | Side column | The copy panel on the trader's profile. See [Copy trading](./copy-trading.md). |
+| Share room | Side column | Share the room link to X, Farcaster, or the clipboard. |
+
+Nothing in a room holds funds, asks for a key, or signs on your behalf.
+
+## When nothing is happening
+
+A room's state comes from the ledger, and the page and the API compute it with
+the same function (`roomState` in `src/trade-room/model.js`):
+
+| State | Meaning |
+|---|---|
+| Live now | A position is open, or the last fill landed in the last 15 minutes |
+| Traded today | The last fill landed in the last 24 hours |
+| Quiet | Nothing in the last 24 hours, or never |
+
+A quiet room is still a full room: the board, the tape, the list and the
+receipt show the trader's most recent real trades, the side column says when
+they last traded, and "Other rooms" lists which rooms are live right now. A
+live room cools on screen as its last fill ages, without a reload.
+
+## Accessibility and devices
+
+The canvas is decorative for assistive technology. Everything it shows is also
+in the page: the trade list is ordered newest first with a plain sentence per
+trade, and each new fill is announced through a polite live region ("Crosshair
+sold $TICKER for 0.0014 ◎, −31.0% on trailing stop."). Every control is a real
+button or link with a visible focus ring.
+
+The 3D view picks a budget from the device (pixel ratio, shadows, crowd size,
+particles), caps the frame rate with the shared frame governor (30fps in power
+saver or an unfocused window), and steps the budget down on sustained slow
+frames. A device that still cannot hold about 20fps at the lowest budget
+switches to the list view and says why, with a button to try 3D again. A
+browser without WebGL gets the list view with the same explanation, and anyone
+can choose **List only** (remembered on that device). On phones, a trader body
+over the mobile size cap is swapped for the default avatar rather than risk
+the tab.
+
+## APIs
+
+All three are public and IP rate-limited, and apply the same visibility gate as
+`/api/sniper/trader`: a private or deleted agent has no room.
+
+```
+GET /api/sniper/rooms?network=mainnet&limit=24
+GET /api/sniper/room?agent_id=<uuid>&network=mainnet
+GET /api/sniper/room-stream?agent_id=<uuid>&network=mainnet&since=<iso>&session=<id> (SSE)
+```
+
+Try the lobby:
+
+```bash
+curl -s 'https://three.ws/api/sniper/rooms?limit=5' | jq '.rooms[] | {name, state, last_trade_at, spectators}'
+```
+
+Full shapes are in the [API reference](./api-reference.md#trade-rooms-api).
+
+### How live works
+
+The sniper worker is a separate process, so the stream polls
+`agent_sniper_positions` for this trader's rows whose open, close, or quote
+time moved past a cursor (every 2s), and derives what happened from the
+timestamps. A position that opens and closes inside one poll still emits its
+buy before its sell. The page passes the newest fill it already painted as
+`since`, so nothing falls in the gap between the snapshot and the stream;
+`since` is clamped to ten minutes back. Each connection lasts 90 seconds, then
+the page reconnects from its newest fill.
+
+### Who is watching
+
+A spectator is an open room stream. The stream registers the tab's random
+session id in a Redis sorted set per room (`traderoom:spec:<agent id>`, scored
+by expiry) on connect and every 10 seconds, and removes it on disconnect; a
+tab that dies without a clean close ages out after 30 seconds. A hidden tab
+disconnects after 30 seconds, so it stops counting. If Redis is unavailable
+the count falls back to the serving instance's own viewers and the stream
+reports `presence_scope: "instance"`, which the page surfaces in the watching
+pill's tooltip.
+
+## Related
+
+- [Trade receipts](./trade-receipts.md), [Fork a trade](./fork-trade.md),
+ [Ghost-copy](./ghost-copy.md), [Copy trading](./copy-trading.md)
+- [STRUCTURE.md](../STRUCTURE.md) row "Live trade rooms"
diff --git a/pages/leaderboard.html b/pages/leaderboard.html
index 19995a7bc..8f4f45922 100644
--- a/pages/leaderboard.html
+++ b/pages/leaderboard.html
@@ -101,6 +101,7 @@
win rate and drawdown, each number traceable to the transaction that made it. Find the best.
Copy the best.
</p>
+ <p class="lb-hero-cta"><a class="lb-btn" href="/trade-rooms">Watch traders trade live in their rooms →</a></p>
<dl class="lb-summary" aria-label="Leaderboard summary">
<div class="lb-summary-cell">
<dt data-i18n="leaderboard.ranked_traders">Ranked traders</dt>
diff --git a/pages/trade-room.html b/pages/trade-room.html
new file mode 100644
index 000000000..ebaff20de
--- /dev/null
+++ b/pages/trade-room.html
@@ -0,0 +1,40 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <script>/* three.ws theme boot, no-flash; runtime in /theme-switcher.js */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <title>Live trade rooms · three.ws</title>
+ <meta name="description" content="Step into a pump.fun trader's room and watch them trade live: their 3D avatar reacts as every real buy and sell lands, with the receipt for why, P&amp;L, and one tap to fork the trade or copy the trader." />
+ <meta property="og:type" content="website" />
+ <meta property="og:site_name" content="three.ws" />
+ <meta property="og:title" content="Live trade rooms · three.ws" />
+ <meta property="og:description" content="Watch a trader's real buys and sells land live inside a 3D room, then fork the trade or copy the trader in one tap." />
+ <meta property="og:image" content="https://three.ws/og-image.png" />
+ <meta name="twitter:card" content="summary_large_image" />
+ <meta name="theme-color" content="#07080d" />
+ <link rel="icon" href="/favicon.ico" sizes="any" />
+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />
+ <link rel="manifest" href="/manifest.webmanifest" />
+ <link rel="stylesheet" href="/fonts/fonts.css" />
+ <link rel="stylesheet" href="/nav.css" />
+ <link rel="stylesheet" href="/src/leaderboard.css" />
+ <link rel="stylesheet" href="/src/trade-room/trade-room.css" />
+ <link rel="stylesheet" href="/footer.css" />
+ <script defer src="/footer-newsletter.js"></script>
+ </head>
+ <body>
+ <header><div id="nav-container"></div></header>
+ <script src="/nav.js"></script>
+
+ <main class="tr-shell" id="tr-root" aria-busy="true">
+ <div id="tr-content"></div>
+ </main>
+
+ <script type="module" src="/src/trade-room/main.js"></script>
+ <script src="/brand.js" defer></script>
+ <div id="footer-container"></div>
+ <script src="/footer.js"></script>
+ </body>
+</html>
diff --git a/public/changelog-recent.json b/public/changelog-recent.json
index b825b88a3..e5edc8a69 100644
--- a/public/changelog-recent.json
+++ b/public/changelog-recent.json
@@ -1,14 +1,34 @@
{
- "generated_at": "2026-09-29T06:45:44.845Z",
+ "generated_at": "2026-09-29T07:36:06.065Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
"url": "https://three.ws"
},
- "total": 3759,
+ "total": 3762,
"complete": false,
"full_feed": "/changelog.json",
"entries": [
+ {
+ "date": "2026-09-29",
+ "type": "launch",
+ "title": "Docs · Live trade rooms",
+ "summary": "How live trade rooms work: the trader's 3D avatar reacting to each real fill, the board and ticker tape, spectator presence, the receipt, Fork, ghost-copy and copy on every trade, the list view and frame budget, and the rooms, room and SSE stream APIs.",
+ "link": "/docs/trade-rooms",
+ "tags": [
+ "launch"
+ ]
+ },
+ {
+ "date": "2026-09-29",
+ "type": "launch",
+ "title": "Live Trade Rooms: watch pump.fun traders trade live in 3D",
+ "summary": "Step into a trader's 3D room and watch their real pump.fun buys and sells land as they fill: the avatar reacts, every trade carries its receipt, P&L and Solscan tx, and one tap forks the trade or ghost-copies the trader. Quiet rooms show the latest real trades and which rooms are live now.",
+ "link": "/trade-rooms",
+ "tags": [
+ "launch"
+ ]
+ },
{
"date": "2026-09-29",
"type": "update",
@@ -20,6 +40,16 @@
"infra"
]
},
+ {
+ "date": "2026-09-29",
+ "type": "update",
+ "title": "Watch traders trade live in their own 3D trade rooms",
+ "summary": "Every public trader now has a live trade room. Their avatar stands on the floor and reacts as each real buy and sell fills, the board and ticker tape fill with their trades, and everyone watching shows up in the room. Tap any trade for the receipt of why it was made, fork it into your own wallet, or ghost-copy the trader. A quiet room still shows the latest real trades and which rooms are live right now, and the whole room also works as an accessible live list.",
+ "link": "/trade-rooms",
+ "tags": [
+ "feature"
+ ]
+ },
{
"date": "2026-09-28",
"type": "update",
@@ -1575,39 +1605,6 @@
"fix",
"improvement"
]
- },
- {
- "date": "2026-09-09",
- "type": "update",
- "title": "The economy solver says which level its numbers belong to, and shares a link that lands on them",
- "summary": "The solver at /play/solver reprices the whole /play world when you move the skill level, and it fetches the new level as you move. If that fetch failed, the page dimmed its tables slightly and said nothing else: the chart marker sat at level 60 while every table below it still held level 1 figures, with no visible explanation, no way to tell which level you were reading, and no retry. The explanation existed but was written only into a region screen readers can reach, so anyone looking at the page saw a silent mismatch. A failed level now raises a banner in the open that names the level that failed, says plainly that the figures below are still the old level, and offers both a retry and a way back. A level still loading shows the same banner as a busy state with the level it is solving, so a slow connection reads as slow rather than as broken. The page also writes the level into its own address bar now: it has always read a level from a shared link, but never wrote one, so sending someone the URL after dragging to level 60 sent them level 1. And a link asking for a level past the cap settles on the cap instead of leaving the page waiting on a level that will never arrive. Alongside it, a conclusion in the model that shouted one word in capitals now reads as a normal sentence.",
- "link": "/play/solver",
- "tags": [
- "fix",
- "improvement"
- ]
- },
- {
- "date": "2026-09-09",
- "type": "update",
- "title": "The floorplan editor can make rooms, so a home with no areas is no longer a dead end",
- "summary": "Most Home Assistant setups we see have devices everywhere and not a single area, which left the 3D home and the floorplan with nothing to draw and the only advice we could give was to go and create areas in Home Assistant's own settings first. That is a chore people leave to do and do not come back from. The floorplan editor now makes the room itself: name it, and the area is created in your own Home Assistant, placed on the plan, and the device that prompted it is filed into it in the same step. It reaches your dashboards, your voice assistant and your automations too, because it is a real area in your registry and not a picture of one here. The tray tells a home with no rooms where to start, and a device you file no longer leaves a stale entry behind in the list.",
- "link": "/smart-home",
- "tags": [
- "feature",
- "improvement"
- ]
- },
- {
- "date": "2026-09-09",
- "type": "update",
- "title": "The generated motion clips were playing upside down, and we can now tell",
- "summary": "Every one of the 133 motion clips three.ws generates from a text prompt was being written down in the wrong reference frame. The bone names all matched the rest of the library, so nothing looked wrong in the data, but a clip's rotations are measured against a rig's resting pose and the generator was measuring against a different one. The result was a half turn missing from the legs: play one of these clips on an avatar and the feet fold up over the body. Forward kinematics put the feet at 1.71 m and the head at 1.45 m, where a hand-authored clip puts them at 0.15 m and 1.68 m. Clips can now be converted into the library's own frame, which puts all 133 back on their feet, and the quality check has learned to spot the fault: it was invisible before because every other rule measures a clip against itself, and a clip in the wrong frame is perfectly consistent with itself. A second fault went with it. Every generated clip was drifting forward at about a quarter of a metre a second whatever it was asked for, so a clip of someone applauding walked a metre across the room while it clapped, and standing-still idles drifted faster than the walks did. That turned out to be an artifact of how the motion model's output is scaled back into real units, and it is now measured and removed while the real motion, a pirouette's sway or a walk's per-step surge, is kept. Removing it also repaired the foot-sliding check, which had been dividing by a stride that was never real, so the library's quality bar finally means something: 39 of the 133 clips meet it, and the rest are being held back rather than served.",
- "link": "/animations",
- "tags": [
- "fix",
- "improvement"
- ]
}
]
}
diff --git a/public/changelog.json b/public/changelog.json
index e810c3e21..1735122e9 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,11 +1,31 @@
{
- "generated_at": "2026-09-29T06:45:44.824Z",
+ "generated_at": "2026-09-29T07:36:06.048Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
"url": "https://three.ws"
},
"entries": [
+ {
+ "date": "2026-09-29",
+ "type": "launch",
+ "title": "Docs · Live trade rooms",
+ "summary": "How live trade rooms work: the trader's 3D avatar reacting to each real fill, the board and ticker tape, spectator presence, the receipt, Fork, ghost-copy and copy on every trade, the list view and frame budget, and the rooms, room and SSE stream APIs.",
+ "link": "/docs/trade-rooms",
+ "tags": [
+ "launch"
+ ]
+ },
+ {
+ "date": "2026-09-29",
+ "type": "launch",
+ "title": "Live Trade Rooms: watch pump.fun traders trade live in 3D",
+ "summary": "Step into a trader's 3D room and watch their real pump.fun buys and sells land as they fill: the avatar reacts, every trade carries its receipt, P&L and Solscan tx, and one tap forks the trade or ghost-copies the trader. Quiet rooms show the latest real trades and which rooms are live now.",
+ "link": "/trade-rooms",
+ "tags": [
+ "launch"
+ ]
+ },
{
"date": "2026-09-29",
"type": "update",
@@ -17,6 +37,16 @@
"infra"
]
},
+ {
+ "date": "2026-09-29",
+ "type": "update",
+ "title": "Watch traders trade live in their own 3D trade rooms",
+ "summary": "Every public trader now has a live trade room. Their avatar stands on the floor and reacts as each real buy and sell fills, the board and ticker tape fill with their trades, and everyone watching shows up in the room. Tap any trade for the receipt of why it was made, fork it into your own wallet, or ghost-copy the trader. A quiet room still shows the latest real trades and which rooms are live right now, and the whole room also works as an accessible live list.",
+ "link": "/trade-rooms",
+ "tags": [
+ "feature"
+ ]
+ },
{
"date": "2026-09-28",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index f48fe26e8..ae0efa3b3 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -6,6 +6,22 @@
<atom:link href="https://three.ws/changelog.xml" rel="self" type="application/rss+xml"/>
<description>What's new on three.ws: features, improvements, and releases, newest first.</description>
<language>en</language>
+ <item>
+ <title>Docs · Live trade rooms</title>
+ <link>https://three.ws/docs/trade-rooms</link>
+ <guid isPermaLink="false">2026-09-29:Docs · Live trade rooms</guid>
+ <pubDate>Tue, 29 Sep 2026 12:00:00 GMT</pubDate>
+ <category>launch</category>
+ <description>How live trade rooms work: the trader's 3D avatar reacting to each real fill, the board and ticker tape, spectator presence, the receipt, Fork, ghost-copy and copy on every trade, the list view and frame budget, and the rooms, room and SSE stream APIs.</description>
+ </item>
+ <item>
+ <title>Live Trade Rooms: watch pump.fun traders trade live in 3D</title>
+ <link>https://three.ws/trade-rooms</link>
+ <guid isPermaLink="false">2026-09-29:Live Trade Rooms: watch pump.fun traders trade live in 3D</guid>
+ <pubDate>Tue, 29 Sep 2026 12:00:00 GMT</pubDate>
+ <category>launch</category>
+ <description>Step into a trader's 3D room and watch their real pump.fun buys and sells land as they fill: the avatar reacts, every trade carries its receipt, P&amp;L and Solscan tx, and one tap forks the trade or ghost-copies the trader. Quiet rooms show the latest real trades and which rooms are live now.</description>
+ </item>
<item>
<title>The platform's own payments stop crowding out the data it pays for</title>
<link>https://three.ws/status</link>
@@ -14,6 +30,14 @@
<category>fix</category>
<description>Every two minutes a background job sends a batch of tiny tips to keep the payment feed moving, and three.ws pays the network fee on each one. It sent 60 at a time whether or not the day's fee budget could cover them, so about 95% were turned away after the work of preparing them, and the few that got through used up the budget the health, price and volume checks needed. The job now sends only what the budget can pay for and leaves room for those checks first. The status page also flags this pattern if it ever comes back, instead of reporting payments as healthy.</description>
</item>
+ <item>
+ <title>Watch traders trade live in their own 3D trade rooms</title>
+ <link>https://three.ws/trade-rooms</link>
+ <guid isPermaLink="false">2026-09-29:Watch traders trade live in their own 3D trade rooms</guid>
+ <pubDate>Tue, 29 Sep 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>Every public trader now has a live trade room. Their avatar stands on the floor and reacts as each real buy and sell fills, the board and ticker tape fill with their trades, and everyone watching shows up in the room. Tap any trade for the receipt of why it was made, fork it into your own wallet, or ghost-copy the trader. A quiet room still shows the latest real trades and which rooms are live right now, and the whole room also works as an accessible live list.</description>
+ </item>
<item>
<title>The Pole Club floor comes alive: a crowd, money on the stages, and tipping from inside the room</title>
<link>https://three.ws/club</link>
diff --git a/public/features.json b/public/features.json
index 017c0f4ce..0946fa909 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-09-28T03:03:42.998Z",
+ "generated_at": "2026-09-29T07:36:06.036Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
@@ -2137,6 +2137,16 @@
"tags": [],
"showcase": false
},
+ {
+ "path": "/trade-rooms",
+ "title": "Live Trade Rooms: watch pump.fun traders trade live in 3D",
+ "description": "Step into a trader's 3D room and watch their real pump.fun buys and sells land as they fill: the avatar reacts, every trade carries its receipt, P&L and Solscan tx, and one tap forks the trade or ghost-copies the trader. Quiet rooms show the latest real trades and which rooms are live now.",
+ "added": "2026-09-29",
+ "auth": null,
+ "indexable": true,
+ "tags": [],
+ "showcase": false
+ },
{
"path": "/ghost-copy",
"title": "Ghost-copy: what if you'd copied them?",
@@ -7698,6 +7708,16 @@
"tags": [],
"showcase": false
},
+ {
+ "path": "/docs/trade-rooms",
+ "title": "Docs · Live trade rooms",
+ "description": "How live trade rooms work: the trader's 3D avatar reacting to each real fill, the board and ticker tape, spectator presence, the receipt, Fork, ghost-copy and copy on every trade, the list view and frame budget, and the rooms, room and SSE stream APIs.",
+ "added": "2026-09-29",
+ "auth": null,
+ "indexable": true,
+ "tags": [],
+ "showcase": false
+ },
{
"path": "/docs/trade-receipts",
"title": "Docs · Trade receipts",
diff --git a/public/llms-full.txt b/public/llms-full.txt
index be5a6a4b9..f5ab93966 100644
--- a/public/llms-full.txt
+++ b/public/llms-full.txt
@@ -1309,6 +1309,12 @@ URL: https://three.ws/claim-wallet
Paste your Solana wallet to see your provable pump.fun track record: win rate, smart-money score, reputation label, and coin history. Sign in to claim it as your official three.ws Trader Card.
+### Live Trade Rooms: watch pump.fun traders trade live in 3D
+
+URL: https://three.ws/trade-rooms
+
+Step into a trader's 3D room and watch their real pump.fun buys and sells land as they fill: the avatar reacts, every trade carries its receipt, P&L and Solscan tx, and one tap forks the trade or ghost-copies the trader. Quiet rooms show the latest real trades and which rooms are live now.
+
### Ghost-copy: what if you'd copied them?
URL: https://three.ws/ghost-copy
@@ -4667,6 +4673,12 @@ URL: https://three.ws/docs/fork-trade
One tap on any coin across the Radar, the Live Trade Feed, the Smart Money Radar, or a ghost-copy replay opens the real pump.fun trade panel for it, pre-filled and signed by your own wallet. No custody, no delegated key, and a ?fork= link so a coin travels.
+### Docs · Live trade rooms
+
+URL: https://three.ws/docs/trade-rooms
+
+How live trade rooms work: the trader's 3D avatar reacting to each real fill, the board and ticker tape, spectator presence, the receipt, Fork, ghost-copy and copy on every trade, the list view and frame budget, and the rooms, room and SSE stream APIs.
+
### Docs · Trade receipts
URL: https://three.ws/docs/trade-receipts
diff --git a/public/llms.txt b/public/llms.txt
index ff95ed34a..4bfdd88d0 100644
--- a/public/llms.txt
+++ b/public/llms.txt
@@ -238,6 +238,7 @@ On-chain features: pay-per-call, token launches, vanity wallets.
- [Trending: Top Agents & Coins on three.ws](https://three.ws/trending): What’s hot on three.ws right now. Top 3D AI agents ranked by real chat activity and top Oracle conviction coins by score, with 24h/7d/all-time windows.
- [Live Trade Feed: Notable pump.fun Exits](https://three.ws/trades): Real-time feed of every notable pump.fun exit from three.ws AI agents: realized PnL, hold time, exit multiple, conviction tier, and a one-click path to copy the trader.
- [Claim Your Wallet: Verified pump.fun Track Record](https://three.ws/claim-wallet): Paste your Solana wallet to see your provable pump.fun track record: win rate, smart-money score, reputation label, and coin history. Sign in to claim it as your official three.ws Trader Card.
+- [Live Trade Rooms: watch pump.fun traders trade live in 3D](https://three.ws/trade-rooms): Step into a trader's 3D room and watch their real pump.fun buys and sells land as they fill: the avatar reacts, every trade carries its receipt, P&L and Solscan tx, and one tap forks the trade or ghost-copies the trader. Quiet rooms show the latest real trades and which rooms are live now.
- [Ghost-copy: what if you'd copied them?](https://three.ws/ghost-copy): Paper-copy any verified pump.fun trader agent with fake money over their real closed on-chain trades. Pick a leader, a budget and a window, and see the equity curve you would have had, plus every trade your budget could not reach and why. No wallet, no signature, no custody, no account.
- [Trader Wrapped: your season on pump.fun](https://three.ws/wrapped): The season recap for any verified pump.fun trading agent on three.ws: realized profit and loss, the trade that carried the season, the trade that hurt, the rhythm behind both, and where they finished against the field. Cut from closed on-chain round-trips with buy and sell signatures attached, so a losing season reads as a losing season. Swipeable, shareable, no account and no wallet.
- [Meta-Allocator: the ETF of degens](https://three.ws/meta-allocator): Do not pick a coin, pick a basket of proven traders. The Meta-Allocator spreads a budget across the top verified pump.fun trader agents, ranked by risk-adjusted on-chain track record and diversified across trading styles, then tells you how to rebalance. Non-custodial: it returns a plan you act on one leader at a time, never a transaction.
@@ -794,6 +795,7 @@ Docs, tutorials, and reference.
- [Tutorial · Give your agent body language](https://three.ws/tutorials/animate-your-agent): Clips, slots and hints: the three-name chain that makes an agent nod, look down while it reads, celebrate a settled payment, and dance on request. Re-point any gesture without touching skill code.
- [Docs · Ghost-copy](https://three.ws/docs/ghost-copy): Replay a verified trader agent's real closed on-chain trades against a wallet that never existed: pick a leader, a budget, and a window, and see where copying them at your size would have left you. Nothing signed, nothing spent.
- [Docs · Fork a trade](https://three.ws/docs/fork-trade): One tap on any coin across the Radar, the Live Trade Feed, the Smart Money Radar, or a ghost-copy replay opens the real pump.fun trade panel for it, pre-filled and signed by your own wallet. No custody, no delegated key, and a ?fork= link so a coin travels.
+- [Docs · Live trade rooms](https://three.ws/docs/trade-rooms): How live trade rooms work: the trader's 3D avatar reacting to each real fill, the board and ticker tape, spectator presence, the receipt, Fork, ghost-copy and copy on every trade, the list view and frame budget, and the rooms, room and SSE stream APIs.
- [Docs · Trade receipts](https://three.ws/docs/trade-receipts): Why an AI trader took a trade, with the evidence it had: the trigger, the Oracle score and its reasons, the on-chain firewall simulation, the LLM judge, the Risk Officer and paid x402 reads, each timed against the entry, plus every leg on Solscan.
- [Docs · Trader Passport](https://three.ws/docs/trader-passport): A trader track record other apps can verify: once a day each ranked trader's rolled-up score is committed to Solana as a signed SPL-Memo attestation, and this API serves that credential for anyone to re-check against the chain.
- [Docs · Wallet Portfolio](https://three.ws/docs/portfolio): How the live wallet portfolio works: the keyless Solana-first data sources behind /api/crypto/portfolio, the stable/major/token classification, the honest 24h coverage contract, and the full response shape for agents and scripts.
diff --git a/public/nav-data.js b/public/nav-data.js
index cb1e20ebb..4445aaae8 100644
--- a/public/nav-data.js
+++ b/public/nav-data.js
@@ -673,6 +673,13 @@ export const NAV_GROUPS = [
badgeTone: 'live',
desc: 'Every notable pump.fun exit — PnL, hold time, and one-click copy',
},
+ {
+ title: 'Live Trade Rooms',
+ href: '/trade-rooms',
+ badge: 'Live',
+ badgeTone: 'live',
+ desc: 'Watch a trader\'s real buys and sells land in a 3D room, then fork or copy in one tap',
+ },
{
title: 'Agent Activity',
href: '/activity',
diff --git a/public/sitemap/index.html b/public/sitemap/index.html
index ff4cc5c39..4e3590aa6 100644
--- a/public/sitemap/index.html
+++ b/public/sitemap/index.html
@@ -96,7 +96,7 @@
<main class="sm-wrap">
<div class="sm-hero">
<h1>Sitemap</h1>
- <p>All 953 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p>
+ <p>All 955 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p>
<div class="sm-formats">
<a href="/sitemap.xml"><code>sitemap.xml</code> · for search engines</a>
<a href="/llms.txt"><code>llms.txt</code> · for AI agents</a>
@@ -108,7 +108,7 @@
</div>
<div class="sm-filter">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></svg>
- <input id="sm-filter-input" type="search" placeholder="Filter 953 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />
+ <input id="sm-filter-input" type="search" placeholder="Filter 955 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />
<kbd id="sm-filter-kbd" aria-hidden="true">/</kbd>
</div>
<p class="sm-filter-count" role="status" aria-live="polite"><span id="sm-filter-count"></span><span id="sm-filter-hint" aria-hidden="true"></span></p>
@@ -116,6 +116,22 @@
<h2 id="sm-new-title">Newest<a class="sm-new-more" href="/changelog">full changelog &rarr;</a></h2>
<p class="sm-section-desc">The 9 most recently launched pages, straight to the live surface.</p>
<ul class="sm-list">
+ <li>
+ <a href="/trade-rooms">
+ <span class="sm-new-date">Sep 29, 2026</span>
+ <span class="sm-title">Live Trade Rooms: watch pump.fun traders trade live in 3D</span>
+ <span class="sm-path">/trade-rooms</span>
+ <span class="sm-desc">Step into a trader's 3D room and watch their real pump.fun buys and sells land as they fill: the avatar reacts, every trade carries its receipt, P&amp;L and Solscan tx, and one tap forks the trade or ghost-copies the trader. Quiet rooms show the latest real trades and which rooms are live now.</span>
+ </a>
+ </li>
+ <li>
+ <a href="/docs/trade-rooms">
+ <span class="sm-new-date">Sep 29, 2026</span>
+ <span class="sm-title">Docs · Live trade rooms</span>
+ <span class="sm-path">/docs/trade-rooms</span>
+ <span class="sm-desc">How live trade rooms work: the trader's 3D avatar reacting to each real fill, the board and ticker tape, spectator presence, the receipt, Fork, ghost-copy and copy on every trade, the list view and frame budget, and the rooms, room and SSE stream APIs.</span>
+ </a>
+ </li>
<li>
<a href="/docs/trade-receipts">
<span class="sm-new-date">Sep 24, 2026</span>
@@ -172,22 +188,6 @@
<span class="sm-desc">Put a live 3D view of any Solana market on your own page with one iframe, keyed by the mint or by the pair address your chart already uses. Covers the pair-to-token bridge, the parameters, sizing, the designed failure states, and driving the scene from the host page.</span>
</a>
</li>
- <li>
- <a href="/docs/prompts">
- <span class="sm-new-date">Sep 20, 2026</span>
- <span class="sm-title">Docs · The prompt library</span>
- <span class="sm-path">/docs/prompts</span>
- <span class="sm-desc">How the three.ws prompt library works: the setup tiers behind each prompt, the lines worth keeping when you edit one, the JSON and plain-text feeds an agent can fetch, and how to add a prompt of your own.</span>
- </a>
- </li>
- <li>
- <a href="/docs/doc-freshness">
- <span class="sm-new-date">Sep 17, 2026</span>
- <span class="sm-title">Docs · Doc freshness, keeping docs true to the code</span>
- <span class="sm-path">/docs/doc-freshness</span>
- <span class="sm-desc">Every doc is bound to the code it names, and git decides whether that code moved after the page was last written or last reviewed. How the measurement works, what each status means, how to record that you checked a page, and where the check runs.</span>
- </a>
- </li>
</ul>
</section>
<nav class="sm-toc" aria-label="Sections">
@@ -1401,7 +1401,7 @@
<section class="sm-section" id="crypto">
<header>
- <h2>Crypto<span class="sm-count" data-count>147</span></h2>
+ <h2>Crypto<span class="sm-count" data-count>148</span></h2>
<p class="sm-section-desc">On-chain features: pay-per-call, token launches, vanity wallets.</p>
</header>
<ul class="sm-list">
@@ -1706,6 +1706,13 @@
<span class="sm-desc">Paste your Solana wallet to see your provable pump.fun track record: win rate, smart-money score, reputation label, and coin history. Sign in to claim it as your official three.ws Trader Card.</span>
</a>
</li>
+ <li>
+ <a href="/trade-rooms">
+ <span class="sm-title">Live Trade Rooms: watch pump.fun traders trade live in 3D</span>
+ <span class="sm-path">/trade-rooms</span>
+ <span class="sm-desc">Step into a trader's 3D room and watch their real pump.fun buys and sells land as they fill: the avatar reacts, every trade carries its receipt, P&amp;L and Solscan tx, and one tap forks the trade or ghost-copies the trader. Quiet rooms show the latest real trades and which rooms are live now.</span>
+ </a>
+ </li>
<li>
<a href="/ghost-copy">
<span class="sm-title">Ghost-copy: what if you'd copied them?</span>
@@ -2618,7 +2625,7 @@
<section class="sm-section" id="learn">
<header>
- <h2>Learn<span class="sm-count" data-count>440</span></h2>
+ <h2>Learn<span class="sm-count" data-count>441</span></h2>
<p class="sm-section-desc">Docs, tutorials, and reference.</p>
</header>
<ul class="sm-list">
@@ -5611,6 +5618,13 @@
<span class="sm-desc">One tap on any coin across the Radar, the Live Trade Feed, the Smart Money Radar, or a ghost-copy replay opens the real pump.fun trade panel for it, pre-filled and signed by your own wallet. No custody, no delegated key, and a ?fork= link so a coin travels.</span>
</a>
</li>
+ <li>
+ <a href="/docs/trade-rooms">
+ <span class="sm-title">Docs · Live trade rooms</span>
+ <span class="sm-path">/docs/trade-rooms</span>
+ <span class="sm-desc">How live trade rooms work: the trader's 3D avatar reacting to each real fill, the board and ticker tape, spectator presence, the receipt, Fork, ghost-copy and copy on every trade, the list view and frame budget, and the rooms, room and SSE stream APIs.</span>
+ </a>
+ </li>
<li>
<a href="/docs/trade-receipts">
<span class="sm-title">Docs · Trade receipts</span>
diff --git a/src/leaderboard.css b/src/leaderboard.css
index 122472d1e..2a9f68971 100644
--- a/src/leaderboard.css
+++ b/src/leaderboard.css
@@ -54,6 +54,7 @@
70% { box-shadow: 0 0 0 8px rgba(74, 222, 128, 0); }
100% { box-shadow: 0 0 0 0 rgba(74, 222, 128, 0); }
}
+.lb-hero-cta { margin: var(--space-sm) 0 0; display: flex; justify-content: center; }
.lb-title {
font-family: var(--font-display);
font-weight: var(--weight-bold);
diff --git a/src/trade-room/main.js b/src/trade-room/main.js
new file mode 100644
index 000000000..f84858bf6
--- /dev/null
+++ b/src/trade-room/main.js
@@ -0,0 +1,838 @@
+/**
+ * /trade-rooms and /trade-rooms/:agentId: live trade rooms.
+ *
+ * The lobby lists every public leader with a room, live ones first (real
+ * fills from the sniper ledger, real spectator counts). A room stands the
+ * leader's 3D avatar on a pedestal and streams their trades as they land from
+ * /api/sniper/room-stream: the avatar reacts, the board and the ticker tape
+ * update, and the accessible trade list below announces each fill through an
+ * aria-live region, because a canvas is opaque to a screen reader.
+ *
+ * Every trade carries its receipt ("why"), its Solscan tx, its share card once
+ * closed, and a one-tap Fork (src/fork-trade.js). The leader carries Ghost-copy
+ * and Copy. A quiet room still shows the leader's recent real trades, when they
+ * last traded, and which other rooms are live right now.
+ *
+ * The 3D scene (./scene.js, which pulls in three.js) is a lazy chunk. A device
+ * without WebGL, a viewer who chose list only, or a device that cannot hold
+ * the frame budget gets the same room without the canvas, and is told why.
+ */
+
+import {
+ escapeHtml as esc, fmtSol, fmtUsd, fmtPct, pnlClass, identicon, verifiedBadge,
+} from '../trader-format.js';
+import { forkButton, mountForkLinks } from '../fork-trade.js';
+import { receiptHTML, receiptSkeletonHTML, RECEIPT_CSS } from '../shared/trade-receipt-view.js';
+import { emptyStateHTML, errorStateHTML, skeletonHTML } from '../shared/state-kit.js';
+import { isWebGLAvailable } from '../webgl-support.js';
+import {
+ STATE_LABEL, ago, backoffMs, coinLabel, lastTradedText, mergeTrade, newSessionId,
+ roomIdFromLocation, roomState, signedPct, solAmount, toneOf, tradeLine,
+} from './model.js';
+
+const NETWORKS = new Set(['mainnet', 'devnet']);
+const VIEW_PREF_KEY = 'tws-trade-room-view';
+const MAX_TRADES = 40;
+const LOBBY_REFRESH_MS = 30_000;
+const OTHERS_REFRESH_MS = 60_000;
+const CLOCK_MS = 30_000;
+const HIDDEN_DISCONNECT_MS = 30_000;
+const SNAPSHOT_DEBOUNCE_MS = 3_000;
+
+const root = document.getElementById('tr-root');
+const content = document.getElementById('tr-content');
+const reducedMotion = typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;
+
+const state = {
+ id: '',
+ network: 'mainnet',
+ room: null,
+ trades: [],
+ open: [],
+ spectators: null,
+ scope: null,
+ session: newSessionId(),
+ es: null,
+ attempt: 0,
+ reconnectTimer: 0,
+ hiddenTimer: 0,
+ snapshotTimer: 0,
+ scene: null,
+ sceneMode: 'off',
+ receipts: new Map(),
+ latestWhyId: '',
+};
+
+// ── small utilities ──────────────────────────────────────────────────────
+
+function readPref() {
+ try { return localStorage.getItem(VIEW_PREF_KEY) === 'list' ? 'list' : '3d'; } catch { return '3d'; }
+}
+
+function writePref(v) {
+ try { localStorage.setItem(VIEW_PREF_KEY, v); } catch { /* private mode: the choice lasts this visit */ }
+}
+
+async function getJson(url) {
+ const res = await fetch(url, { headers: { accept: 'application/json' } });
+ if (!res.ok) {
+ const err = new Error(`http_${res.status}`);
+ err.status = res.status;
+ throw err;
+ }
+ return res.json();
+}
+
+function qs(sel) { return content.querySelector(sel); }
+
+function avatarImg(src, seed, cls, alt = '') {
+ const fallback = identicon(seed || '?');
+ return `<img class="${cls}" src="${esc(src || fallback)}" alt="${esc(alt)}" loading="lazy" decoding="async" data-fallback-src="${fallback}" />`;
+}
+
+function netQuery() {
+ return state.network === 'mainnet' ? '' : `?network=${state.network}`;
+}
+
+function injectReceiptCss() {
+ if (document.getElementById('tr-receipt-css')) return;
+ const style = document.createElement('style');
+ style.id = 'tr-receipt-css';
+ style.textContent = RECEIPT_CSS;
+ document.head.appendChild(style);
+}
+
+// Broken leader images fall back to their identicon instead of a broken glyph.
+document.addEventListener('error', (e) => {
+ const img = e.target;
+ if (!(img instanceof HTMLImageElement) || !img.dataset.fallbackSrc) return;
+ if (img.src === img.dataset.fallbackSrc) return;
+ img.src = img.dataset.fallbackSrc;
+}, true);
+
+// ── lobby ────────────────────────────────────────────────────────────────
+
+function roomCard(r, { compact = false } = {}) {
+ const watching = r.spectators > 0 ? `<span class="tr-watch" title="People with this room open right now">${r.spectators} watching</span>` : '';
+ const pnlLine = r.closed_7d > 0
+ ? `<span class="${pnlClass(r.pnl_7d_sol)}">${fmtSol(r.pnl_7d_sol)}</span> <span class="tr-dim">7d</span>`
+ : '<span class="tr-dim">No closes in 7d</span>';
+ const wr = r.win_rate_7d != null ? `${fmtPct(r.win_rate_7d * 100, { dp: 0 })} win` : '';
+ const label = `Enter ${r.name}'s room: ${STATE_LABEL[r.state]}, ${lastTradedText(r.last_trade_at).toLowerCase()}${r.spectators ? `, ${r.spectators} watching` : ''}`;
+ return `
+ <a class="tr-card tr-card--${esc(r.state)}${compact ? ' tr-card--compact' : ''}" href="${esc(r.url)}${netQuery()}" aria-label="${esc(label)}">
+ <div class="tr-card-top">
+ ${avatarImg(r.image, r.agent_id, 'tr-card-av')}
+ <div class="tr-card-id">
+ <span class="tr-card-name">${esc(r.name)}</span>
+ <span class="tr-state tr-state--${esc(r.state)}"><span class="tr-state-dot" aria-hidden="true"></span>${esc(STATE_LABEL[r.state])}</span>
+ </div>
+ </div>
+ <div class="tr-card-stats">
+ <span>${esc(lastTradedText(r.last_trade_at))}</span>
+ ${compact ? '' : `<span>${r.fills_24h} fills in 24h</span>`}
+ <span>${pnlLine}</span>
+ ${wr && !compact ? `<span>${esc(wr)}</span>` : ''}
+ </div>
+ <div class="tr-card-foot">${watching}<span class="tr-card-cta">Enter room →</span></div>
+ </a>`;
+}
+
+function renderLobbyShell() {
+ document.title = 'Live trade rooms · three.ws';
+ content.innerHTML = `
+ <section class="tr-hero">
+ <p class="tr-kicker"><span class="tr-live-dot" aria-hidden="true"></span>Live trade rooms</p>
+ <h1 class="tr-title">Watch traders trade live</h1>
+ <p class="tr-sub">Step into a trader's room: their avatar is on the floor, their real pump.fun buys and sells
+ land on the board the moment they fill, each with the receipt for why. Fork a trade or copy the trader in one tap.
+ Every number traces to an on-chain transaction.</p>
+ </section>
+ <section class="tr-lobby" aria-labelledby="tr-lobby-h">
+ <div class="tr-lobby-head">
+ <h2 id="tr-lobby-h">Rooms</h2>
+ <a class="lb-btn" href="/leaderboard">Trader leaderboard</a>
+ </div>
+ <div id="tr-lobby-grid" class="tr-grid" aria-live="polite" aria-busy="true">${skeletonHTML(6, 'card')}</div>
+ </section>`;
+}
+
+async function loadLobby() {
+ const grid = qs('#tr-lobby-grid');
+ if (!grid) return;
+ try {
+ const data = await getJson(`/api/sniper/rooms?limit=24${state.network === 'mainnet' ? '' : `&network=${state.network}`}`);
+ const rooms = data.rooms || [];
+ grid.setAttribute('aria-busy', 'false');
+ if (!rooms.length) {
+ grid.innerHTML = emptyStateHTML({
+ title: 'No trade rooms open yet',
+ body: 'A room opens for every public trader the moment they make a real trade. Launch an agent that trades, or browse the traders already ranked.',
+ actions: [
+ { label: 'Launch a trader', href: '/create-agent', primary: true },
+ { label: 'Trader leaderboard', href: '/leaderboard' },
+ ],
+ });
+ return;
+ }
+ const live = rooms.filter((r) => r.state === 'live').length;
+ grid.innerHTML = `${live ? '' : `<p class="tr-lobby-note">No trader has a position open or has filled in the last 15 minutes. Every room below still shows its trader's real recent trades, and lights up the moment they trade.</p>`}${rooms.map((r) => roomCard(r)).join('')}`;
+ } catch {
+ grid.setAttribute('aria-busy', 'false');
+ grid.innerHTML = errorStateHTML({
+ title: 'Could not load the trade rooms',
+ body: 'The trade ledger did not answer. Check your connection and retry; nothing is lost.',
+ });
+ grid.querySelector('[data-sk-retry]')?.addEventListener('click', () => {
+ grid.innerHTML = skeletonHTML(6, 'card');
+ grid.setAttribute('aria-busy', 'true');
+ loadLobby();
+ });
+ }
+}
+
+function startLobby() {
+ renderLobbyShell();
+ root.setAttribute('aria-busy', 'false');
+ loadLobby();
+ setInterval(() => { if (!document.hidden) loadLobby(); }, LOBBY_REFRESH_MS);
+}
+
+// ── room: rendering ──────────────────────────────────────────────────────
+
+function renderNotFound(message) {
+ document.title = 'Trade room not found · three.ws';
+ root.setAttribute('aria-busy', 'false');
+ content.innerHTML = `
+ <nav class="tr-crumbs" aria-label="Breadcrumb"><a href="/trade-rooms">← All trade rooms</a></nav>
+ ${emptyStateHTML({
+ title: 'This trade room does not exist',
+ body: esc(message),
+ actions: [
+ { label: 'Browse live rooms', href: '/trade-rooms', primary: true },
+ { label: 'Trader leaderboard', href: '/leaderboard' },
+ ],
+ })}`;
+}
+
+function renderRoomSkeleton() {
+ content.innerHTML = `
+ <nav class="tr-crumbs" aria-label="Breadcrumb"><a href="/trade-rooms">← All trade rooms</a></nav>
+ <div class="tr-room">
+ <div class="tr-stage tr-stage--loading" aria-hidden="true"><div class="tr-stage-shimmer"></div></div>
+ <div class="tr-side">${skeletonHTML(4, 'row')}</div>
+ </div>`;
+}
+
+function renderRoomError() {
+ root.setAttribute('aria-busy', 'false');
+ content.innerHTML = `
+ <nav class="tr-crumbs" aria-label="Breadcrumb"><a href="/trade-rooms">← All trade rooms</a></nav>
+ ${errorStateHTML({
+ title: 'Could not open this trade room',
+ body: 'The trade ledger did not answer. Check your connection and retry.',
+ })}`;
+ content.querySelector('[data-sk-retry]')?.addEventListener('click', () => openRoom());
+}
+
+function statCell(label, value, cls = '') {
+ return `<div class="tr-stat"><dt>${esc(label)}</dt><dd class="${cls}">${value}</dd></div>`;
+}
+
+function renderRoom(data) {
+ const L = data.leader;
+ const s = data.stats;
+ document.title = `${L.name} · live trade room · three.ws`;
+ const traderHref = `/trader/${encodeURIComponent(L.id)}${netQuery()}`;
+ const usd = s.realized_pnl_usd != null ? ` <span class="tr-dim">${esc(fmtUsd(s.realized_pnl_usd))}</span>` : '';
+ content.innerHTML = `
+ <nav class="tr-crumbs" aria-label="Breadcrumb"><a href="/trade-rooms">← All trade rooms</a></nav>
+ <div class="tr-room">
+ <section class="tr-stage" id="tr-stage" aria-labelledby="tr-leader-name" aria-describedby="tr-stage-desc">
+ <p id="tr-stage-desc" class="tr-sr-only">A 3D room where ${esc(L.name)}'s avatar reacts to each trade. Every trade shown in the room is also in the trade list on this page.</p>
+ <div class="tr-canvas-host" id="tr-canvas-host"></div>
+ <div class="tr-hud">
+ <a class="tr-leader-chip" href="${traderHref}">
+ ${avatarImg(L.image, L.id, 'tr-leader-av')}
+ <span class="tr-leader-meta">
+ <span class="tr-leader-name" id="tr-leader-name">${esc(L.name)}${verifiedBadge(s.verified)}</span>
+ <span class="tr-leader-sub">Score ${s.score} · track record →</span>
+ </span>
+ </a>
+ <div class="tr-pills">
+ <span class="tr-state" id="tr-state"></span>
+ <span class="tr-watch" id="tr-watch" hidden></span>
+ <span class="tr-conn" id="tr-conn" data-state="connecting">Connecting</span>
+ </div>
+ </div>
+ <div class="tr-flash" id="tr-flash" aria-hidden="true"></div>
+ <div class="tr-stage-foot">
+ <p class="tr-stage-note" id="tr-stage-note" role="status"></p>
+ <button type="button" class="tr-tool" id="tr-view-toggle"></button>
+ </div>
+ <div class="tr-stage-panel" id="tr-stage-panel" hidden></div>
+ </section>
+
+ <aside class="tr-side" aria-label="${esc(L.name)}'s trading">
+ <section class="tr-leader-card">
+ <p class="tr-last" id="tr-last"></p>
+ <dl class="tr-stats">
+ ${statCell('Win rate · 30d', s.closed_count ? fmtPct(s.win_rate * 100) : 'None yet')}
+ ${statCell('Realized · 30d', `${fmtSol(s.realized_pnl_sol)}${usd}`, pnlClass(s.realized_pnl_sol))}
+ ${statCell('Closed trades · 30d', String(s.closed_count))}
+ ${statCell('Best trade · 30d', s.best_pnl_pct != null ? signedPct(s.best_pnl_pct) : 'None yet', pnlClass(s.best_pnl_pct))}
+ </dl>
+ <div class="tr-actions">
+ <a class="lb-btn lb-btn-primary" href="/ghost-copy?leader=${encodeURIComponent(L.id)}&window=30d">Ghost-copy</a>
+ <a class="lb-btn" href="${traderHref}#tp-copy-panel">Copy trades</a>
+ <button type="button" class="lb-btn" id="tr-share">Share room</button>
+ </div>
+ ${L.copiers ? `<p class="tr-dim tr-copiers">${L.copiers} ${L.copiers === 1 ? 'person copies' : 'people copy'} this trader</p>` : ''}
+ </section>
+
+ <section class="tr-why" id="tr-why" aria-labelledby="tr-why-h" hidden>
+ <h2 id="tr-why-h" class="tr-h">Why the latest trade</h2>
+ <div id="tr-why-body"></div>
+ </section>
+
+ <section class="tr-open" id="tr-open" aria-labelledby="tr-open-h" hidden>
+ <h2 id="tr-open-h" class="tr-h">Open now</h2>
+ <ul class="tr-open-list" id="tr-open-list"></ul>
+ </section>
+
+ <section class="tr-feed" aria-labelledby="tr-feed-h">
+ <h2 id="tr-feed-h" class="tr-h">Trades, newest first</h2>
+ <ol class="tr-list" id="tr-list" aria-labelledby="tr-feed-h"></ol>
+ </section>
+ </aside>
+ </div>
+
+ <section class="tr-others" aria-labelledby="tr-others-h">
+ <div class="tr-lobby-head">
+ <h2 id="tr-others-h">Other rooms</h2>
+ <a class="lb-btn" href="/trade-rooms">All rooms</a>
+ </div>
+ <div class="tr-grid tr-grid--compact" id="tr-others">${skeletonHTML(3, 'card')}</div>
+ </section>
+ <div class="tr-sr-only" id="tr-announce" role="status" aria-live="polite" aria-atomic="true"></div>`;
+
+ mountForkLinks(content);
+ content.querySelector('#tr-share').addEventListener('click', (e) => shareRoom(e.currentTarget));
+ content.querySelector('#tr-view-toggle').addEventListener('click', toggleView);
+ content.querySelector('#tr-list').addEventListener('click', onListClick);
+ content.querySelector('#tr-why-body').addEventListener('click', onListClick);
+}
+
+function tradeRow(t) {
+ const tone = toneOf(t);
+ const sideLabel = t.kind === 'buy' ? 'Buy' : 'Sell';
+ const pct = t.kind === 'sell' ? `<span class="tr-pnl ${pnlClass(t.pnl_pct)}">${esc(signedPct(t.pnl_pct))}</span>` : '';
+ const meta = [
+ `<time datetime="${esc(t.at)}" data-ago>${esc(ago(t.at))}</time>`,
+ t.kind === 'sell' && t.exit_label ? esc(t.exit_label) : '',
+ t.kind === 'sell' && t.hold_seconds != null ? `held ${esc(holdLabel(t.hold_seconds))}` : '',
+ t.paper ? '<span class="tr-paper" title="Simulated fill, no on-chain transaction">paper</span>' : '',
+ ].filter(Boolean).join(' · ');
+ const whyId = `tr-why-${t.id.replace(/[^a-z0-9]/gi, '')}`;
+ return `
+ <li class="tr-row tr-row--${tone}" data-id="${esc(t.id)}">
+ <span class="tr-badge tr-badge--${tone}">${sideLabel}</span>
+ <div class="tr-row-main">
+ <p class="tr-row-line"><span class="tr-sr-only">${esc(tradeLine(t))}. </span><span aria-hidden="true"><strong>${esc(coinLabel(t))}</strong> <span class="tr-mono">${esc(solAmount(t.size_sol))}</span> ${pct}</span></p>
+ <p class="tr-row-meta">${meta}</p>
+ </div>
+ <div class="tr-row-acts">
+ <button type="button" class="tr-mini" data-why="${esc(t.position_id)}" data-why-target="${whyId}" aria-expanded="false" aria-controls="${whyId}">Why</button>
+ ${forkButton({ mint: t.mint, symbol: t.symbol, name: t.name, size: t.entry_sol }, { className: 'tr-mini tr-mini--fork', label: 'Fork' })}
+ ${t.share_url ? `<a class="tr-mini" href="${esc(t.share_url)}" aria-label="Trade card for ${esc(coinLabel(t))}">Card</a>` : ''}
+ ${t.tx_url ? `<a class="tr-mini" href="${esc(t.tx_url)}" target="_blank" rel="noopener" aria-label="${sideLabel} transaction on Solscan (opens in a new tab)">tx ↗</a>` : ''}
+ </div>
+ <div class="tr-receipt" id="${whyId}" hidden></div>
+ </li>`;
+}
+
+function holdLabel(sec) {
+ if (sec < 60) return `${sec}s`;
+ if (sec < 3600) return `${Math.round(sec / 60)}m`;
+ if (sec < 86400) return `${(sec / 3600).toFixed(1)}h`;
+ return `${(sec / 86400).toFixed(1)}d`;
+}
+
+function renderTrades({ freshId = '' } = {}) {
+ const list = qs('#tr-list');
+ if (!list) return;
+ if (!state.trades.length) {
+ list.innerHTML = `<li class="tr-list-empty">${emptyStateHTML({
+ compact: true,
+ title: 'No trades yet',
+ body: `${esc(state.room.leader.name)} has not made a real trade on this network yet. This list fills the moment they do, and you will hear about it here.`,
+ actions: [{ label: 'Browse live rooms', href: '/trade-rooms' }],
+ })}</li>`;
+ return;
+ }
+ // Keep any receipt a viewer has open across re-renders.
+ const openWhy = [...list.querySelectorAll('.tr-receipt:not([hidden])')].map((el) => el.id);
+ list.innerHTML = state.trades.map(tradeRow).join('');
+ for (const id of openWhy) {
+ const btn = list.querySelector(`[data-why-target="${id}"]`);
+ if (btn) toggleReceipt(btn, true);
+ }
+ if (freshId && !reducedMotion) list.querySelector(`[data-id="${CSS.escape(freshId)}"]`)?.classList.add('is-fresh');
+}
+
+function renderOpen() {
+ const wrap = qs('#tr-open');
+ const list = qs('#tr-open-list');
+ if (!wrap || !list) return;
+ wrap.hidden = !state.open.length;
+ list.innerHTML = state.open.map((o) => `
+ <li class="tr-open-row" data-pos="${esc(o.id)}">
+ <strong>${esc(coinLabel(o))}</strong>
+ <span class="tr-mono">${esc(solAmount(o.entry_sol))} in</span>
+ <span class="tr-pnl ${pnlClass(o.unrealized_pct)}" data-unrealized>${esc(signedPct(o.unrealized_pct))}</span>
+ <span class="tr-dim">opened <time datetime="${esc(o.opened_at)}" data-ago>${esc(ago(o.opened_at))}</time></span>
+ </li>`).join('');
+}
+
+function renderRoomState() {
+ const room = state.room?.room;
+ if (!room) return;
+ const pill = qs('#tr-state');
+ if (pill) {
+ pill.className = `tr-state tr-state--${room.state}`;
+ pill.innerHTML = `<span class="tr-state-dot" aria-hidden="true"></span>${esc(STATE_LABEL[room.state])}`;
+ }
+ const last = qs('#tr-last');
+ if (last) {
+ last.textContent = state.trades.length
+ ? `${lastTradedText(room.last_trade_at)}. ${room.state === 'live' ? 'Trades land here live.' : 'This room lights up the moment they trade again.'}`
+ : 'No trades yet. This room lights up the moment they make one.';
+ }
+ renderStageNote();
+}
+
+function renderSpectators() {
+ const el = qs('#tr-watch');
+ if (!el) return;
+ if (state.spectators == null) { el.hidden = true; return; }
+ el.hidden = false;
+ const n = state.spectators;
+ el.textContent = n <= 1 ? 'Just you here' : `${n} watching`;
+ el.title = state.scope === 'instance'
+ ? 'People with this room open on this server. The full count can be higher.'
+ : 'People with this room open right now.';
+ state.scene?.setSpectators(n);
+}
+
+function setConn(s) {
+ const el = qs('#tr-conn');
+ if (!el) return;
+ el.dataset.state = s;
+ el.textContent = s === 'live' ? 'Streaming' : s === 'reconnecting' ? 'Reconnecting' : s === 'paused' ? 'Paused' : 'Connecting';
+}
+
+function tickClocks() {
+ for (const el of content.querySelectorAll('time[data-ago]')) el.textContent = ago(el.getAttribute('datetime'));
+ if (state.room) {
+ // A room that was live cools to warm when its last fill ages past the window.
+ const room = state.room.room;
+ room.state = roomState({ lastTradeAt: room.last_trade_at, openCount: state.open.length });
+ renderRoomState();
+ }
+}
+
+function flash(t) {
+ const el = qs('#tr-flash');
+ if (!el || reducedMotion) return;
+ el.className = `tr-flash tr-flash--${toneOf(t)}`;
+ el.textContent = tradeLine(t);
+ void el.offsetWidth;
+ el.classList.add('is-on');
+}
+
+// ── receipts ("why") ─────────────────────────────────────────────────────
+
+async function loadReceipt(positionId) {
+ if (state.receipts.has(positionId)) return state.receipts.get(positionId);
+ const p = getJson(`/api/sniper/receipt?id=${encodeURIComponent(positionId)}`);
+ state.receipts.set(positionId, p);
+ p.catch(() => state.receipts.delete(positionId));
+ return p;
+}
+
+async function toggleReceipt(btn, forceOpen = false) {
+ const panel = document.getElementById(btn.dataset.whyTarget);
+ if (!panel) return;
+ const open = forceOpen || panel.hidden;
+ panel.hidden = !open;
+ btn.setAttribute('aria-expanded', String(open));
+ if (!open) return;
+ injectReceiptCss();
+ panel.innerHTML = receiptSkeletonHTML();
+ try {
+ panel.innerHTML = receiptHTML(await loadReceipt(btn.dataset.why));
+ } catch (err) {
+ panel.innerHTML = `<p class="tr-receipt-err">${err?.status === 404
+ ? 'This trade has no receipt: the position never filled, or its agent is private.'
+ : 'The receipt could not load.'} <button type="button" class="tr-mini" data-why-retry>Retry</button></p>`;
+ panel.querySelector('[data-why-retry]')?.addEventListener('click', () => toggleReceipt(btn, true));
+ }
+}
+
+function onListClick(e) {
+ const btn = e.target instanceof Element ? e.target.closest('[data-why]') : null;
+ if (btn) toggleReceipt(btn);
+}
+
+async function renderLatestWhy() {
+ const wrap = qs('#tr-why');
+ const body = qs('#tr-why-body');
+ const latest = state.trades[0];
+ if (!wrap || !body || !latest) return;
+ if (state.latestWhyId === latest.position_id) return;
+ state.latestWhyId = latest.position_id;
+ wrap.hidden = false;
+ body.innerHTML = '<p class="tr-why-line tr-skel-line" aria-busy="true">Reading the receipt</p>';
+ try {
+ const r = await loadReceipt(latest.position_id);
+ if (state.latestWhyId !== latest.position_id) return;
+ const whyTarget = 'tr-why-latest-full';
+ body.innerHTML = `
+ <p class="tr-why-line">${esc(r.summary)}</p>
+ <button type="button" class="tr-mini" data-why="${esc(latest.position_id)}" data-why-target="${whyTarget}" aria-expanded="false" aria-controls="${whyTarget}">Full receipt</button>
+ <div class="tr-receipt" id="${whyTarget}" hidden></div>`;
+ } catch {
+ if (state.latestWhyId !== latest.position_id) return;
+ body.innerHTML = `<p class="tr-why-line tr-dim">No receipt is on record for ${esc(coinLabel(latest))} yet. It appears once the trade's evidence is written.</p>`;
+ }
+}
+
+// ── 3D stage ─────────────────────────────────────────────────────────────
+
+function renderStageNote(extra = '') {
+ const note = qs('#tr-stage-note');
+ const toggle = qs('#tr-view-toggle');
+ if (!note || !toggle) return;
+ const L = state.room?.leader;
+ let msg = extra || state.stageMsg || '';
+ if (!msg && state.room && state.room.room.state !== 'live' && state.sceneMode === 'on') {
+ msg = state.trades.length
+ ? `${L.name} is between trades. ${lastTradedText(state.room.room.last_trade_at)}; the board shows their latest fills.`
+ : `${L.name} has not traded yet. The board fills the moment they do.`;
+ }
+ note.textContent = msg;
+ note.hidden = !msg;
+ toggle.hidden = state.sceneMode === 'unsupported';
+ toggle.textContent = state.sceneMode === 'on' || state.sceneMode === 'loading' ? 'List only' : 'Show 3D room';
+ toggle.setAttribute('aria-pressed', String(state.sceneMode !== 'on' && state.sceneMode !== 'loading'));
+}
+
+function showStagePanel(title, body, { retry = false } = {}) {
+ const panel = qs('#tr-stage-panel');
+ const stage = qs('#tr-stage');
+ if (!panel || !stage) return;
+ stage.classList.add('tr-stage--flat');
+ panel.hidden = false;
+ panel.innerHTML = `
+ <div class="tr-panel-inner">
+ <p class="tr-panel-title">${esc(title)}</p>
+ <p class="tr-panel-body">${esc(body)}</p>
+ ${retry ? '<button type="button" class="lb-btn" data-stage-retry>Try the 3D room again</button>' : ''}
+ </div>`;
+ panel.querySelector('[data-stage-retry]')?.addEventListener('click', () => { writePref('3d'); startScene(); });
+}
+
+function hideStagePanel() {
+ const panel = qs('#tr-stage-panel');
+ qs('#tr-stage')?.classList.remove('tr-stage--flat');
+ if (panel) { panel.hidden = true; panel.innerHTML = ''; }
+}
+
+function stopScene() {
+ state.scene?.dispose();
+ state.scene = null;
+}
+
+async function startScene() {
+ stopScene();
+ state.stageMsg = '';
+ const host = qs('#tr-canvas-host');
+ if (!host || !state.room) return;
+ if (!isWebGLAvailable()) {
+ state.sceneMode = 'unsupported';
+ showStagePanel('3D is not available on this device', 'This browser could not start WebGL, so the room runs as the live list below. Every trade still lands there in real time.');
+ renderStageNote();
+ return;
+ }
+ if (readPref() === 'list') {
+ state.sceneMode = 'list';
+ showStagePanel('3D room is off', 'You chose the list view. Trades keep landing live in the list below.', { retry: true });
+ renderStageNote();
+ return;
+ }
+ hideStagePanel();
+ state.sceneMode = 'loading';
+ qs('#tr-stage')?.classList.add('tr-stage--loading');
+ renderStageNote('Setting up the room');
+ let scene;
+ try {
+ const { TradeRoomScene } = await import('./scene.js');
+ scene = new TradeRoomScene(host, { reducedMotion, onFallback: () => fallbackToList() });
+ scene.init();
+ } catch {
+ state.sceneMode = 'unsupported';
+ qs('#tr-stage')?.classList.remove('tr-stage--loading');
+ showStagePanel('3D could not start here', 'The room could not open a 3D view on this device, so it runs as the live list below. Trades still land there in real time.');
+ renderStageNote();
+ return;
+ }
+ state.scene = scene;
+ scene.setTrades(state.trades);
+ if (state.spectators != null) scene.setSpectators(state.spectators);
+ const L = state.room.leader;
+ const shown = await scene.setLeader({ modelUrl: L.model_url, name: L.name });
+ if (state.scene !== scene) return;
+ qs('#tr-stage')?.classList.remove('tr-stage--loading');
+ state.sceneMode = 'on';
+ if (shown.failed) state.stageMsg = `${L.name}'s 3D body could not load on this device, so the default avatar is standing in.`;
+ else if (!L.model_url) state.stageMsg = `${L.name} has no public 3D body yet, so the default avatar is standing in.`;
+ renderStageNote();
+ if (state.stageMsg) setTimeout(() => { state.stageMsg = ''; renderStageNote(); }, 9000);
+}
+
+function fallbackToList() {
+ stopScene();
+ state.sceneMode = 'fallback';
+ showStagePanel(
+ '3D paused to keep this page smooth',
+ 'This device could not hold the room\'s frame rate, so the live trade list below carries on without the 3D view.',
+ { retry: true },
+ );
+ renderStageNote();
+}
+
+function toggleView() {
+ if (state.sceneMode === 'on' || state.sceneMode === 'loading') {
+ writePref('list');
+ stopScene();
+ state.sceneMode = 'list';
+ showStagePanel('3D room is off', 'You chose the list view. Trades keep landing live in the list below.', { retry: true });
+ renderStageNote();
+ return;
+ }
+ writePref('3d');
+ startScene();
+}
+
+// ── live stream ──────────────────────────────────────────────────────────
+
+function onTrade(t) {
+ const known = state.trades.some((x) => x.id === t.id);
+ state.trades = mergeTrade(state.trades, t, MAX_TRADES);
+ if (known) return;
+ applyFillToOpen(t);
+ // A sell completes its position's receipt (exit leg, P&L); drop the cached open one.
+ if (t.kind === 'sell') {
+ state.receipts.delete(t.position_id);
+ if (state.latestWhyId === t.position_id) state.latestWhyId = '';
+ }
+ const room = state.room.room;
+ if (!room.last_trade_at || new Date(t.at) > new Date(room.last_trade_at)) room.last_trade_at = t.at;
+ room.state = roomState({ lastTradeAt: room.last_trade_at, openCount: state.open.length });
+ renderTrades({ freshId: t.id });
+ renderRoomState();
+ const announce = qs('#tr-announce');
+ if (announce) announce.textContent = `${tradeLine(t, state.room.leader.name)}.`;
+ flash(t);
+ state.scene?.setTrades(state.trades);
+ state.scene?.react(t);
+ renderLatestWhy();
+ // Stats and open positions move with every fill; re-read them from the ledger.
+ clearTimeout(state.snapshotTimer);
+ state.snapshotTimer = setTimeout(refreshSnapshot, SNAPSHOT_DEBOUNCE_MS);
+}
+
+/** Keep "Open now" honest between snapshots: a buy opens a row, a sell closes it. */
+function applyFillToOpen(t) {
+ if (t.kind === 'sell') {
+ state.open = state.open.filter((o) => o.id !== t.position_id);
+ } else if (t.status !== 'closed' && !state.open.some((o) => o.id === t.position_id)) {
+ state.open = [{
+ id: t.position_id, mint: t.mint, symbol: t.symbol, name: t.name,
+ entry_sol: t.entry_sol, current_sol: t.entry_sol, unrealized_pct: 0, opened_at: t.at,
+ }, ...state.open];
+ }
+ renderOpen();
+}
+
+function onQuote(q) {
+ const o = state.open.find((x) => x.id === q.position_id);
+ if (!o) return;
+ o.current_sol = q.current_sol;
+ o.unrealized_pct = q.unrealized_pct;
+ const cell = content.querySelector(`[data-pos="${CSS.escape(q.position_id)}"] [data-unrealized]`);
+ if (cell) {
+ cell.textContent = signedPct(q.unrealized_pct);
+ cell.className = `tr-pnl ${pnlClass(q.unrealized_pct)}`;
+ }
+}
+
+function disconnect() {
+ clearTimeout(state.reconnectTimer);
+ state.es?.close();
+ state.es = null;
+}
+
+function connect() {
+ disconnect();
+ if (!state.room) return;
+ const since = state.trades[0]?.at || new Date(state.room.t).toISOString();
+ const q = new URLSearchParams({ agent_id: state.id, network: state.network, since, session: state.session });
+ const es = new EventSource(`/api/sniper/room-stream?${q}`);
+ state.es = es;
+ const alive = () => { state.attempt = 0; setConn('live'); };
+ const parse = (e) => { try { return JSON.parse(e.data); } catch { return null; } };
+ es.addEventListener('open', (e) => {
+ if (!e.data) return;
+ const d = parse(e);
+ alive();
+ if (d && d.spectators != null) { state.spectators = d.spectators; state.scope = d.presence_scope; renderSpectators(); }
+ });
+ es.addEventListener('trade', (e) => { alive(); const t = parse(e); if (t) onTrade(t); });
+ es.addEventListener('quote', (e) => { alive(); const d = parse(e); if (d) onQuote(d); });
+ es.addEventListener('presence', (e) => {
+ alive();
+ const d = parse(e);
+ if (d) { state.spectators = d.spectators; state.scope = d.presence_scope; renderSpectators(); }
+ });
+ es.addEventListener('ping', alive);
+ es.addEventListener('close', () => { es.close(); if (state.es === es) connect(); });
+ es.onerror = () => {
+ if (state.es !== es) return;
+ es.close();
+ state.es = null;
+ setConn('reconnecting');
+ state.reconnectTimer = setTimeout(connect, backoffMs(state.attempt++));
+ };
+}
+
+async function refreshSnapshot() {
+ try {
+ const data = await getJson(`/api/sniper/room?agent_id=${encodeURIComponent(state.id)}&network=${state.network}`);
+ applySnapshot(data, { rerender: false });
+ } catch {
+ /* the stream keeps the list live; the stats catch up on the next fill */
+ }
+}
+
+function applySnapshot(data, { rerender }) {
+ state.room = data;
+ for (const t of data.trades || []) state.trades = mergeTrade(state.trades, t, MAX_TRADES);
+ state.open = data.open || [];
+ if (data.room.spectators != null) { state.spectators = data.room.spectators; state.scope = data.room.presence_scope; }
+ if (rerender) renderRoom(data);
+ else updateStats(data);
+ renderTrades();
+ renderOpen();
+ renderRoomState();
+ renderSpectators();
+ renderLatestWhy();
+ state.scene?.setTrades(state.trades);
+}
+
+function updateStats(data) {
+ const s = data.stats;
+ const cells = content.querySelectorAll('.tr-stats dd');
+ if (cells.length !== 4) return;
+ cells[0].textContent = s.closed_count ? fmtPct(s.win_rate * 100) : 'None yet';
+ cells[1].className = pnlClass(s.realized_pnl_sol);
+ cells[1].innerHTML = `${fmtSol(s.realized_pnl_sol)}${s.realized_pnl_usd != null ? ` <span class="tr-dim">${esc(fmtUsd(s.realized_pnl_usd))}</span>` : ''}`;
+ cells[2].textContent = String(s.closed_count);
+ cells[3].className = pnlClass(s.best_pnl_pct);
+ cells[3].textContent = s.best_pnl_pct != null ? signedPct(s.best_pnl_pct) : 'None yet';
+}
+
+// ── other rooms ──────────────────────────────────────────────────────────
+
+async function loadOthers() {
+ const grid = qs('#tr-others');
+ if (!grid) return;
+ try {
+ const data = await getJson(`/api/sniper/rooms?limit=12${state.network === 'mainnet' ? '' : `&network=${state.network}`}`);
+ const others = (data.rooms || []).filter((r) => r.agent_id !== state.id).slice(0, 6);
+ grid.innerHTML = others.length
+ ? others.map((r) => roomCard(r, { compact: true })).join('')
+ : emptyStateHTML({
+ compact: true,
+ title: 'This is the only room open',
+ body: 'No other trader has a room yet. Find the next one on the leaderboard.',
+ actions: [{ label: 'Trader leaderboard', href: '/leaderboard' }],
+ });
+ } catch {
+ grid.innerHTML = errorStateHTML({ title: 'Could not load other rooms', body: 'Retry in a moment.' });
+ grid.querySelector('[data-sk-retry]')?.addEventListener('click', loadOthers);
+ }
+}
+
+async function shareRoom(btn) {
+ const L = state.room.leader;
+ const url = `${location.origin}/trade-rooms/${encodeURIComponent(L.id)}${netQuery()}`;
+ const { showSharePanel } = await import('../shared/share.js');
+ showSharePanel({
+ kind: 'trade-room',
+ id: L.id,
+ title: `${L.name}'s live trade room`,
+ description: 'Watch every real buy and sell land live, with the receipt for why. Fork any trade in one tap.',
+ shareText: `Watching ${L.name} trade live on three.ws`,
+ shareUrl: url,
+ }, btn);
+}
+
+// ── lifecycle ────────────────────────────────────────────────────────────
+
+async function openRoom() {
+ renderRoomSkeleton();
+ root.setAttribute('aria-busy', 'true');
+ let data;
+ try {
+ data = await getJson(`/api/sniper/room?agent_id=${encodeURIComponent(state.id)}&network=${state.network}`);
+ } catch (err) {
+ if (err.status === 404) return renderNotFound('No public trader has this id. The trader may be private, or the link may be mistyped.');
+ return renderRoomError();
+ }
+ root.setAttribute('aria-busy', 'false');
+ state.trades = [];
+ applySnapshot(data, { rerender: true });
+ connect();
+ startScene();
+ loadOthers();
+ setInterval(tickClocks, CLOCK_MS);
+ setInterval(() => { if (!document.hidden) loadOthers(); }, OTHERS_REFRESH_MS);
+ document.addEventListener('visibilitychange', onVisibility);
+ window.addEventListener('pagehide', () => { disconnect(); stopScene(); });
+}
+
+// A hidden tab stops counting as a spectator and stops polling; coming back
+// re-reads the snapshot so nothing that landed meanwhile is missed.
+function onVisibility() {
+ if (document.hidden) {
+ state.hiddenTimer = setTimeout(() => { disconnect(); setConn('paused'); }, HIDDEN_DISCONNECT_MS);
+ return;
+ }
+ clearTimeout(state.hiddenTimer);
+ if (!state.es) {
+ refreshSnapshot().finally(connect);
+ }
+}
+
+function boot() {
+ const q = new URLSearchParams(location.search);
+ if (NETWORKS.has(q.get('network'))) state.network = q.get('network');
+ const { id, invalid } = roomIdFromLocation(location.pathname, location.search);
+ if (invalid) return renderNotFound('Room links look like /trade-rooms/ followed by a trader id. This one is not a valid trader id.');
+ if (!id) return startLobby();
+ state.id = id;
+ openRoom();
+}
+
+boot();
diff --git a/src/trade-room/model.js b/src/trade-room/model.js
new file mode 100644
index 000000000..8cb2ca5cf
--- /dev/null
+++ b/src/trade-room/model.js
@@ -0,0 +1,181 @@
+/**
+ * Trade room client model: pure helpers shared by the page controller, the 3D
+ * scene, and the tests. No DOM, no fetch, no three.js.
+ */
+
+const SOL = '◎';
+
+/** Newest-first merge of one event into a list, de-duplicated by id and capped. */
+export function mergeTrade(list, event, max = 40) {
+ if (!event?.id) return list.slice(0, max);
+ const out = list.filter((t) => t.id !== event.id);
+ out.push(event);
+ out.sort((a, b) => new Date(b.at).getTime() - new Date(a.at).getTime() || (a.kind === 'sell' ? -1 : 1));
+ return out.slice(0, max);
+}
+
+/** "$PLUR", or the coin name, or "a coin" when the ledger has neither. */
+export function coinLabel(t) {
+ if (t?.symbol) return `$${String(t.symbol).toUpperCase()}`;
+ if (t?.name) return String(t.name);
+ return 'a coin';
+}
+
+/** SOL amount with enough precision for pump.fun-sized fills: 0.00138 → "0.00138 ◎". */
+export function solAmount(v) {
+ const n = Number(v);
+ if (!Number.isFinite(n)) return `? ${SOL}`;
+ const abs = Math.abs(n);
+ const dp = abs >= 1 ? 2 : abs >= 0.1 ? 3 : abs >= 0.01 ? 4 : 5;
+ return `${Number(n.toFixed(dp))} ${SOL}`;
+}
+
+/** Signed percent with a real minus sign: -31.01 → "−31.0%". */
+export function signedPct(v) {
+ if (v == null || !Number.isFinite(Number(v))) return '';
+ const n = Number(v);
+ const s = n > 0 ? '+' : n < 0 ? '−' : '';
+ return `${s}${Math.abs(n).toFixed(Math.abs(n) >= 100 ? 0 : 1)}%`;
+}
+
+/** How a sell landed: win, loss, or flat (inside half a percent). */
+export function toneOf(t) {
+ if (t?.kind !== 'sell') return 'buy';
+ const p = Number(t.pnl_pct);
+ if (!Number.isFinite(p) || Math.abs(p) < 0.5) return 'flat';
+ return p > 0 ? 'win' : 'loss';
+}
+
+/**
+ * One plain sentence for a trade: the screen-reader announcement, the ticker
+ * tape, and the headline on the room's board all read the same words.
+ */
+export function tradeLine(t, leaderName = '') {
+ const who = leaderName ? `${leaderName} ` : '';
+ const coin = coinLabel(t);
+ if (t?.kind === 'buy') {
+ return `${who}${t.paper ? 'paper-bought' : 'bought'} ${coin} for ${solAmount(t.size_sol)}`.replace(/^./, (c) => c.toUpperCase());
+ }
+ const pct = signedPct(t?.pnl_pct);
+ const why = t?.exit_label ? ` on ${String(t.exit_label).toLowerCase()}` : '';
+ const verb = t?.paper ? 'paper-sold' : 'sold';
+ return `${who}${verb} ${coin} for ${solAmount(t?.size_sol)}${pct ? `, ${pct}` : ''}${why}`.replace(/^./, (c) => c.toUpperCase());
+}
+
+/**
+ * The emote the leader's avatar plays when a trade lands. Every name exists in
+ * /animations/manifest.json; the scene falls back to idle if one cannot load.
+ */
+export function reactionFor(t) {
+ const tone = toneOf(t);
+ if (tone === 'buy') return 'point';
+ if (tone === 'flat') return 'nod';
+ const p = Number(t.pnl_pct);
+ if (tone === 'win') return p >= 50 ? 'av-cheering' : 'celebrate';
+ return p <= -20 ? 'defeated' : 'shrug';
+}
+
+/** A room is "live" while a position is open or the last fill is this fresh. */
+export const LIVE_WINDOW_MS = 15 * 60_000;
+/** A room is "warm" when the leader traded inside this window. */
+export const WARM_WINDOW_MS = 24 * 3_600_000;
+
+/**
+ * The room's liveliness, computed identically by the API (api/_lib/trade-room.js)
+ * and the page (so a live room cools to warm on screen without a refetch).
+ * live : a position is open, or the last fill landed inside LIVE_WINDOW_MS
+ * warm : the leader traded inside WARM_WINDOW_MS
+ * quiet : anything older, or never
+ * @param {{lastTradeAt?: string|null, openCount?: number, now?: number}} input
+ * @returns {'live'|'warm'|'quiet'}
+ */
+export function roomState({ lastTradeAt = null, openCount = 0, now = Date.now() } = {}) {
+ if (openCount > 0) return 'live';
+ const last = lastTradeAt ? new Date(lastTradeAt).getTime() : NaN;
+ if (!Number.isFinite(last)) return 'quiet';
+ const age = now - last;
+ if (age <= LIVE_WINDOW_MS) return 'live';
+ if (age <= WARM_WINDOW_MS) return 'warm';
+ return 'quiet';
+}
+
+/** Room state copy, shared by the lobby card and the room HUD. */
+export const STATE_LABEL = { live: 'Live now', warm: 'Traded today', quiet: 'Quiet' };
+
+/** Relative time from an ISO instant: "just now", "4m ago", "3h ago", "12d ago". */
+export function ago(iso, now = Date.now()) {
+ const t = new Date(iso).getTime();
+ if (!Number.isFinite(t)) return '';
+ const s = Math.max(0, (now - t) / 1000);
+ if (s < 45) return 'just now';
+ if (s < 3600) return `${Math.round(s / 60)}m ago`;
+ if (s < 86400) return `${Math.round(s / 3600)}h ago`;
+ return `${Math.round(s / 86400)}d ago`;
+}
+
+/** "Last traded 3h ago", or the honest "No trades yet" for a fresh leader. */
+export function lastTradedText(iso, now = Date.now()) {
+ return iso ? `Last traded ${ago(iso, now)}` : 'No trades yet';
+}
+
+/** The looping tape text: the newest trades, separated by a bullet. */
+export function tickerText(trades, limit = 12) {
+ const items = (trades || []).slice(0, limit).map((t) => tradeLine(t));
+ return items.length ? items.join(' • ') : 'Waiting for the first trade';
+}
+
+/**
+ * Seat positions for n spectators: two arcs flanking the pedestal, filled
+ * alternately left and right so a small crowd still frames the leader.
+ * @returns {{x:number, z:number, ry:number}[]}
+ */
+export function spectatorSeats(n, radius = 2.35) {
+ const seats = [];
+ for (let i = 0; i < n; i++) {
+ const side = i % 2 === 0 ? 1 : -1;
+ const row = Math.floor(i / 2);
+ const ring = radius + Math.floor(row / 6) * 0.75;
+ const step = row % 6;
+ // Angle from the +z axis (camera side): 84° to 149°, so the crowd stands
+ // in the round at the sides and back of the pedestal, never between the
+ // camera and the leader.
+ const deg = 84 + step * 13 + (Math.floor(row / 6) % 2) * 8;
+ const a = (deg * Math.PI) / 180 * side;
+ const x = Math.sin(a) * ring;
+ const z = Math.cos(a) * ring;
+ seats.push({ x, z, ry: Math.atan2(-x, -z) });
+ }
+ return seats;
+}
+
+/** A random, URL-safe tab id the stream uses to count this viewer. */
+export function newSessionId(rand = globalThis.crypto) {
+ if (rand?.randomUUID) return rand.randomUUID().replace(/-/g, '').slice(0, 24);
+ let s = '';
+ for (let i = 0; i < 24; i++) s += Math.floor(Math.random() * 36).toString(36);
+ return s;
+}
+
+/**
+ * Which room the URL asks for. /trade-rooms is the lobby ({id:'', invalid:false});
+ * /trade-rooms/<uuid> (or ?agent=<uuid>) is a room; anything else is a room id
+ * that cannot exist ({invalid:true}), which the page answers with a designed
+ * not-found state rather than silently showing the lobby.
+ */
+export function roomIdFromLocation(pathname, search = '') {
+ const m = String(pathname || '').replace(/\/+$/, '').match(/^\/trade-rooms\/([^/]+)$/);
+ let raw = '';
+ try {
+ raw = m ? decodeURIComponent(m[1]) : new URLSearchParams(search).get('agent') || '';
+ } catch {
+ return { id: '', invalid: true };
+ }
+ if (!raw) return { id: '', invalid: false };
+ const ok = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(raw);
+ return ok ? { id: raw.toLowerCase(), invalid: false } : { id: '', invalid: true };
+}
+
+/** Reconnect delay for the stream: 1s, 2s, 4s ... capped at 30s. */
+export function backoffMs(attempt) {
+ return Math.min(30_000, 1000 * 2 ** Math.max(0, attempt));
+}
diff --git a/src/trade-room/scene.js b/src/trade-room/scene.js
new file mode 100644
index 000000000..7ae246203
--- /dev/null
+++ b/src/trade-room/scene.js
@@ -0,0 +1,627 @@
+/**
+ * The trade room in 3D: the leader's avatar on a lit pedestal, a trade board
+ * behind them, a ticker tape ring overhead, and the people watching standing
+ * around the floor. Every pixel is driven by the page controller with real
+ * data (trades, spectator count); this module owns rendering only.
+ *
+ * Budget: the device profile (src/club-perf.js detectProfile) picks pixel
+ * ratio, shadows, spectator figures and burst particles. A frame watchdog
+ * steps the tier down on sustained slow frames; if even the low tier cannot
+ * hold the budget, `onFallback('slow')` hands the page back to its list view
+ * and the page says why. The shared frame governor caps the loop at 60fps
+ * (30 in power saver or when the window is unfocused).
+ */
+
+import {
+ AdditiveBlending,
+ AmbientLight,
+ BufferAttribute,
+ BufferGeometry,
+ CanvasTexture,
+ CapsuleGeometry,
+ CircleGeometry,
+ Color,
+ CylinderGeometry,
+ DirectionalLight,
+ Fog,
+ Group,
+ HemisphereLight,
+ InstancedMesh,
+ Matrix4,
+ Mesh,
+ MeshBasicMaterial,
+ MeshStandardMaterial,
+ Object3D,
+ PerspectiveCamera,
+ PlaneGeometry,
+ Points,
+ PointsMaterial,
+ RepeatWrapping,
+ RingGeometry,
+ Scene,
+ SphereGeometry,
+ SRGBColorSpace,
+ Timer,
+} from 'three';
+import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
+import { mergeGeometries } from 'three/addons/utils/BufferGeometryUtils.js';
+
+import { AVATAR_DEFAULT, buildAvatar, getAllEmoteDefs, newAnim, releaseAvatar } from '../game/avatar-rig.js';
+import { detectProfile, createFrameWatchdog } from '../club-perf.js';
+import {
+ createFrameGovernor, trackWindowFocus, getPowerSaver, FPS_ACTIVE, FPS_IDLE, FPS_SAVER,
+} from '../shared/frame-governor.js';
+import { createRenderer } from '../webgl-support.js';
+import { coinLabel, reactionFor, signedPct, solAmount, spectatorSeats, tickerText, toneOf } from './model.js';
+
+/** Spectator figures and burst particles per device tier. */
+export const TIER_BUDGET = {
+ high: { pixelRatio: 2, shadows: true, spectators: 24, particles: 90 },
+ medium: { pixelRatio: 1.5, shadows: false, spectators: 16, particles: 60 },
+ low: { pixelRatio: 1, shadows: false, spectators: 8, particles: 30 },
+};
+
+const TONE_COLOR = { buy: 0x60a5fa, win: 0x34d399, loss: 0xf87171, flat: 0x94a3b8 };
+const TONE_CSS = { buy: '#60a5fa', win: '#34d399', loss: '#f87171', flat: '#94a3b8' };
+const REACTION_CLIPS = new Set(['point', 'nod', 'celebrate', 'av-cheering', 'shrug', 'defeated']);
+
+// Seconds of sustained slow frames on the low tier before the room gives up on 3D.
+const GIVE_UP_AFTER_SEC = 5;
+const GIVE_UP_FRAME_SEC = 1 / 20;
+
+// Spectators read as an audience: a little smaller than the leader on the pedestal.
+const SPECTATOR_SCALE = 0.82;
+const SPECTATOR_RING_R = 2.35;
+const BOARD_W = 5.6;
+const TAPE_W = BOARD_W + 0.16;
+const TAPE_H = 0.3;
+const TAPE_PX_H = 64;
+const BOARD_H = 2.8;
+const BOARD_Y = 2.0;
+
+function roundRect(ctx, x, y, w, h, r) {
+ ctx.beginPath();
+ ctx.moveTo(x + r, y);
+ ctx.arcTo(x + w, y, x + w, y + h, r);
+ ctx.arcTo(x + w, y + h, x, y + h, r);
+ ctx.arcTo(x, y + h, x, y, r);
+ ctx.arcTo(x, y, x + w, y, r);
+ ctx.closePath();
+}
+
+function fitText(ctx, text, maxWidth) {
+ let s = String(text);
+ if (ctx.measureText(s).width <= maxWidth) return s;
+ while (s.length > 1 && ctx.measureText(`${s}…`).width > maxWidth) s = s.slice(0, -1);
+ return `${s}…`;
+}
+
+/** A simple standing figure (body + head) for the spectator crowd. */
+function spectatorGeometry() {
+ const body = new CapsuleGeometry(0.2, 0.62, 4, 10);
+ body.translate(0, 0.52, 0);
+ const head = new SphereGeometry(0.16, 12, 10);
+ head.translate(0, 1.18, 0);
+ const merged = mergeGeometries([body.toNonIndexed(), head.toNonIndexed()]);
+ body.dispose();
+ head.dispose();
+ return merged;
+}
+
+export class TradeRoomScene {
+ /**
+ * @param {HTMLElement} host element the canvas mounts into
+ * @param {{ reducedMotion?: boolean, onFallback?: (reason: string) => void, onAvatar?: (info: object) => void }} [opts]
+ */
+ constructor(host, opts = {}) {
+ this.host = host;
+ this.opts = opts;
+ this.reducedMotion = !!opts.reducedMotion;
+ this.tier = detectProfile();
+ this.maxTier = this.tier;
+ this.budget = TIER_BUDGET[this.tier];
+ this.disposed = false;
+ this.leaderName = '';
+ this.trades = [];
+ this.spectatorCount = 0;
+ this.bursts = [];
+ this._slowOnLow = 0;
+ this.leaderReady = false;
+ this._raf = 0;
+ this._visible = true;
+ }
+
+ /** Build the renderer and the room. Throws WebGLUnavailableError when 3D cannot start. */
+ init() {
+ const renderer = createRenderer({ antialias: this.tier !== 'low', alpha: false, powerPreference: 'high-performance' }, { fallback: this.host });
+ this.renderer = renderer;
+ renderer.outputColorSpace = SRGBColorSpace;
+ renderer.setClearColor(0x07080d, 1);
+ this._applyTier();
+ renderer.domElement.className = 'tr-canvas';
+ renderer.domElement.setAttribute('aria-hidden', 'true');
+ this.host.appendChild(renderer.domElement);
+
+ const scene = new Scene();
+ scene.fog = new Fog(0x07080d, 9, 22);
+ this.scene = scene;
+
+ const camera = new PerspectiveCamera(42, 1, 0.1, 60);
+ camera.position.set(0, 1.95, 5.3);
+ this.camera = camera;
+
+ const controls = new OrbitControls(camera, renderer.domElement);
+ controls.target.set(0, 1.3, 0);
+ controls.enableDamping = true;
+ controls.dampingFactor = 0.08;
+ controls.enablePan = false;
+ controls.minDistance = 3.2;
+ controls.maxDistance = 8.5;
+ controls.minPolarAngle = Math.PI * 0.28;
+ controls.maxPolarAngle = Math.PI * 0.49;
+ controls.minAzimuthAngle = -Math.PI * 0.42;
+ controls.maxAzimuthAngle = Math.PI * 0.42;
+ controls.autoRotate = !this.reducedMotion;
+ controls.autoRotateSpeed = 0.35;
+ controls.addEventListener('start', () => { controls.autoRotate = false; });
+ this.controls = controls;
+
+ this._buildLights();
+ this._buildFloor();
+ this._buildBoard();
+ this._buildTape();
+ this._buildCrowd();
+ this._buildBursts();
+
+ this.rig = new Group();
+ scene.add(this.rig);
+ this.anim = newAnim();
+
+ this.timer = new Timer();
+ this.governor = createFrameGovernor();
+ this.focus = trackWindowFocus();
+ this.watchdog = createFrameWatchdog({
+ initialTier: this.tier,
+ maxTier: this.maxTier,
+ onDowngrade: (t) => this._setTier(t),
+ onUpgrade: (t) => this._setTier(t),
+ });
+
+ this._onResize = () => this._resize();
+ this._ro = typeof ResizeObserver === 'function' ? new ResizeObserver(this._onResize) : null;
+ this._ro?.observe(this.host);
+ window.addEventListener('resize', this._onResize);
+ this._onVisibility = () => {
+ this._visible = !document.hidden;
+ if (this._visible) this.governor.reset();
+ };
+ document.addEventListener('visibilitychange', this._onVisibility);
+ this._resize();
+ this._loop = this._loop.bind(this);
+ this._raf = requestAnimationFrame(this._loop);
+ }
+
+ /**
+ * Stand the leader in the room. Resolves with what was actually shown so the
+ * page can be honest about a stand-in body.
+ * @param {{ modelUrl?: string|null, name?: string }} leader
+ * @returns {Promise<{ usedDefault: boolean, failed: boolean }>}
+ */
+ async setLeader({ modelUrl = null, name = '' } = {}) {
+ this.leaderName = name;
+ this._drawBoard();
+ const res = await buildAvatar(this.rig, modelUrl || AVATAR_DEFAULT, this.anim, { clips: 'locomotion' });
+ if (this.disposed) return { usedDefault: !modelUrl, failed: false };
+ this.anim.appendAnimationDefs(getAllEmoteDefs().filter((d) => REACTION_CLIPS.has(d.name)));
+ // Warm the reaction clips so the first trade lands without a fetch stall.
+ for (const n of REACTION_CLIPS) this.anim.ensureLoaded(n).catch(() => false);
+ this.rig.position.set(0, 0.16, 0);
+ // Only judge the frame budget once the body is standing: the GLB parse is a
+ // one-off hitch, not a sign the device cannot run the room.
+ this.leaderReady = true;
+ return { usedDefault: !modelUrl || !!res.fallback, failed: !!(modelUrl && res.fallback) };
+ }
+
+ /** Replace the trade list the board and the tape render from (newest first). */
+ setTrades(trades) {
+ this.trades = trades || [];
+ this._drawBoard();
+ this._drawTape();
+ }
+
+ /** Show `n` spectators (the figure count is capped by the device tier). */
+ setSpectators(n) {
+ this.spectatorCount = Math.max(0, Number(n) || 0);
+ this._layoutCrowd();
+ }
+
+ /** A trade just landed: the avatar reacts, the floor ring flashes, coins fly. */
+ react(trade) {
+ const tone = toneOf(trade);
+ const color = new Color(TONE_COLOR[tone]);
+ this.ringMat.color.copy(color);
+ this.ringFlash = 1;
+ if (!this.reducedMotion) this._burst(tone);
+ const clip = reactionFor(trade);
+ this.anim.playOnce(clip, { settleTo: 'idle' }).catch(() => this.anim.crossfadeTo('idle').catch(() => {}));
+ }
+
+ dispose() {
+ this.disposed = true;
+ cancelAnimationFrame(this._raf);
+ this._ro?.disconnect();
+ window.removeEventListener('resize', this._onResize);
+ document.removeEventListener('visibilitychange', this._onVisibility);
+ try { this.anim?.dispose(); } catch { /* already torn down */ }
+ releaseAvatar(this.rig);
+ this.controls?.dispose();
+ this.scene?.traverse((o) => {
+ o.geometry?.dispose?.();
+ const mats = Array.isArray(o.material) ? o.material : o.material ? [o.material] : [];
+ for (const m of mats) { m.map?.dispose?.(); m.dispose?.(); }
+ });
+ this.renderer?.dispose();
+ this.renderer?.domElement?.remove();
+ }
+
+ // ── build ──────────────────────────────────────────────────────────────
+
+ _buildLights() {
+ const { scene } = this;
+ scene.add(new AmbientLight(0x9fb3ff, 0.35));
+ scene.add(new HemisphereLight(0xbcd0ff, 0x120c1a, 0.7));
+ const key = new DirectionalLight(0xffffff, 1.6);
+ key.position.set(2.5, 5.5, 4);
+ key.castShadow = this.budget.shadows;
+ key.shadow.mapSize.set(1024, 1024);
+ key.shadow.camera.left = -3; key.shadow.camera.right = 3;
+ key.shadow.camera.top = 3; key.shadow.camera.bottom = -3;
+ scene.add(key);
+ this.keyLight = key;
+ const rim = new DirectionalLight(0x8b5cf6, 0.9);
+ rim.position.set(-3, 3, -4);
+ scene.add(rim);
+ }
+
+ _buildFloor() {
+ const floor = new Mesh(
+ new CircleGeometry(12, 64),
+ new MeshStandardMaterial({ color: 0x0d0f17, roughness: 0.85, metalness: 0.1 }),
+ );
+ floor.rotation.x = -Math.PI / 2;
+ floor.receiveShadow = true;
+ this.scene.add(floor);
+
+ // Faint grid rings give the floor depth without a texture download.
+ for (let i = 1; i <= 4; i++) {
+ const r = i * 2.2;
+ const ring = new Mesh(
+ new RingGeometry(r, r + 0.012, 96),
+ new MeshBasicMaterial({ color: 0x2a3150, transparent: true, opacity: 0.55 - i * 0.1 }),
+ );
+ ring.rotation.x = -Math.PI / 2;
+ ring.position.y = 0.002;
+ this.scene.add(ring);
+ }
+
+ const pedestal = new Mesh(
+ new CylinderGeometry(1.05, 1.15, 0.16, 48),
+ new MeshStandardMaterial({ color: 0x151827, roughness: 0.4, metalness: 0.6 }),
+ );
+ pedestal.position.y = 0.08;
+ pedestal.receiveShadow = true;
+ this.scene.add(pedestal);
+
+ this.ringMat = new MeshBasicMaterial({ color: TONE_COLOR.buy, transparent: true, opacity: 0.55, blending: AdditiveBlending, depthWrite: false });
+ const glow = new Mesh(new RingGeometry(1.08, 1.3, 64), this.ringMat);
+ glow.rotation.x = -Math.PI / 2;
+ glow.position.y = 0.17;
+ this.scene.add(glow);
+ this.ringFlash = 0;
+ }
+
+ _buildBoard() {
+ const canvas = document.createElement('canvas');
+ canvas.width = 1280;
+ canvas.height = 640;
+ this.boardCanvas = canvas;
+ this.boardTex = new CanvasTexture(canvas);
+ this.boardTex.colorSpace = SRGBColorSpace;
+ const board = new Mesh(
+ new PlaneGeometry(BOARD_W, BOARD_H),
+ new MeshBasicMaterial({ map: this.boardTex, toneMapped: false }),
+ );
+ board.position.set(0, BOARD_Y, -3.4);
+ this.scene.add(board);
+ const frame = new Mesh(
+ new PlaneGeometry(BOARD_W + 0.16, BOARD_H + 0.16),
+ new MeshStandardMaterial({ color: 0x1c2135, roughness: 0.5, metalness: 0.7 }),
+ );
+ frame.position.set(0, BOARD_Y, -3.42);
+ this.scene.add(frame);
+ this._drawBoard();
+ }
+
+ _buildTape() {
+ this.tapeCanvas = document.createElement('canvas');
+ this.tapeCanvas.height = TAPE_PX_H;
+ this.tapeMat = new MeshBasicMaterial({ toneMapped: false });
+ // The shared ticker tape: an LED strip running across the top of the board.
+ const tape = new Mesh(new PlaneGeometry(TAPE_W, TAPE_H), this.tapeMat);
+ tape.position.set(0, BOARD_Y + BOARD_H / 2 + 0.08 + TAPE_H / 2, -3.41);
+ this.scene.add(tape);
+ this._drawTape();
+ }
+
+ _buildCrowd() {
+ const geo = spectatorGeometry();
+ const mat = new MeshStandardMaterial({ color: 0xffffff, roughness: 0.7, metalness: 0.05 });
+ const max = TIER_BUDGET.high.spectators;
+ const crowd = new InstancedMesh(geo, mat, max);
+ crowd.count = 0;
+ crowd.castShadow = false;
+ // Instances appear after the first render; a bounding sphere computed while
+ // the crowd was empty would cull every figure that joins later.
+ crowd.frustumCulled = false;
+ this.crowd = crowd;
+ this.crowdSeats = spectatorSeats(max, SPECTATOR_RING_R);
+ this.crowdScale = new Float32Array(max);
+ const palette = [0x5b6fb3, 0x7a64b8, 0x3f8f86, 0xa8843a, 0xa85586, 0x5f86b0];
+ const c = new Color();
+ for (let i = 0; i < max; i++) crowd.setColorAt(i, c.setHex(palette[i % palette.length]));
+ this.scene.add(crowd);
+ }
+
+ _buildBursts() {
+ this.burstPool = [];
+ for (let b = 0; b < 3; b++) {
+ const n = TIER_BUDGET.high.particles;
+ const geo = new BufferGeometry();
+ geo.setAttribute('position', new BufferAttribute(new Float32Array(n * 3), 3));
+ const mat = new PointsMaterial({ size: 0.07, transparent: true, opacity: 0, blending: AdditiveBlending, depthWrite: false });
+ const pts = new Points(geo, mat);
+ pts.frustumCulled = false;
+ pts.visible = false;
+ this.scene.add(pts);
+ this.burstPool.push({ pts, vel: new Float32Array(n * 3), life: 0, n: 0 });
+ }
+ }
+
+ // ── dynamic content ────────────────────────────────────────────────────
+
+ _drawBoard() {
+ const ctx = this.boardCanvas?.getContext('2d');
+ if (!ctx) return;
+ const W = this.boardCanvas.width;
+ const H = this.boardCanvas.height;
+ const grad = ctx.createLinearGradient(0, 0, 0, H);
+ grad.addColorStop(0, '#0f1424');
+ grad.addColorStop(1, '#090b14');
+ ctx.fillStyle = grad;
+ ctx.fillRect(0, 0, W, H);
+
+ ctx.fillStyle = '#8b93b0';
+ ctx.font = '600 30px Inter, system-ui, sans-serif';
+ ctx.textBaseline = 'middle';
+ ctx.fillText('LIVE TRADE ROOM', 48, 50);
+ ctx.fillStyle = '#eef1f7';
+ ctx.font = '700 52px Inter, system-ui, sans-serif';
+ ctx.fillText(fitText(ctx, this.leaderName || 'Trader', W - 96), 48, 108);
+
+ const rows = this.trades.slice(0, 6);
+ if (!rows.length) {
+ ctx.fillStyle = '#9aa3b4';
+ ctx.font = '500 34px Inter, system-ui, sans-serif';
+ ctx.fillText('No trades yet. The board fills the moment they trade.', 48, 330);
+ }
+ rows.forEach((t, i) => {
+ const y = 180 + i * 72;
+ const tone = toneOf(t);
+ ctx.fillStyle = i === 0 ? 'rgba(124,156,255,0.12)' : 'rgba(255,255,255,0.03)';
+ roundRect(ctx, 36, y, W - 72, 62, 12);
+ ctx.fill();
+ ctx.fillStyle = TONE_CSS[tone];
+ roundRect(ctx, 52, y + 13, 92, 36, 8);
+ ctx.fill();
+ ctx.fillStyle = '#07080d';
+ ctx.font = '800 22px Inter, system-ui, sans-serif';
+ ctx.textAlign = 'center';
+ ctx.fillText(t.kind === 'buy' ? 'BUY' : 'SELL', 98, y + 32);
+ ctx.textAlign = 'left';
+ ctx.fillStyle = '#eef1f7';
+ ctx.font = '700 32px Inter, system-ui, sans-serif';
+ ctx.fillText(fitText(ctx, coinLabel(t), 360), 168, y + 32);
+ ctx.fillStyle = '#b6bdd0';
+ ctx.font = '500 28px "JetBrains Mono", ui-monospace, monospace';
+ ctx.fillText(solAmount(t.size_sol), 560, y + 32);
+ if (t.kind === 'sell') {
+ ctx.fillStyle = TONE_CSS[tone];
+ ctx.font = '700 30px "JetBrains Mono", ui-monospace, monospace';
+ ctx.textAlign = 'right';
+ ctx.fillText(signedPct(t.pnl_pct), W - 60, y + 32);
+ ctx.textAlign = 'left';
+ } else if (t.paper) {
+ ctx.fillStyle = '#fbbf24';
+ ctx.font = '600 24px Inter, system-ui, sans-serif';
+ ctx.textAlign = 'right';
+ ctx.fillText('PAPER', W - 60, y + 32);
+ ctx.textAlign = 'left';
+ }
+ });
+ if (this.boardTex) this.boardTex.needsUpdate = true;
+ }
+
+ _drawTape() {
+ const canvas = this.tapeCanvas;
+ if (!canvas) return;
+ let ctx = canvas.getContext('2d');
+ const font = '600 40px "JetBrains Mono", ui-monospace, monospace';
+ const text = `${tickerText(this.trades, 8)} • `;
+ ctx.font = font;
+ // One exact copy of the text per tile, so the wrap has no seam.
+ const w = Math.min(8192, Math.max(256, Math.ceil(ctx.measureText(text).width)));
+ canvas.width = w;
+ ctx = canvas.getContext('2d');
+ ctx.fillStyle = 'rgba(10,12,22,0.86)';
+ ctx.fillRect(0, 0, w, TAPE_PX_H);
+ ctx.fillStyle = '#c7d2fe';
+ ctx.font = font;
+ ctx.textBaseline = 'middle';
+ ctx.fillText(text, 0, TAPE_PX_H / 2);
+ const offset = this.tapeTex?.offset.x || 0;
+ this.tapeTex?.dispose();
+ const tex = new CanvasTexture(canvas);
+ tex.colorSpace = SRGBColorSpace;
+ tex.wrapS = RepeatWrapping;
+ // Show the strip's width worth of tile so glyphs keep their true aspect.
+ const tileMetres = (w / TAPE_PX_H) * TAPE_H;
+ tex.repeat.set(TAPE_W / tileMetres, 1);
+ tex.offset.x = offset;
+ this.tapeTex = tex;
+ this.tapeMat.map = tex;
+ this.tapeMat.needsUpdate = true;
+ }
+
+ _layoutCrowd() {
+ if (!this.crowd) return;
+ const shown = Math.min(this.spectatorCount, this.budget.spectators);
+ this._crowdTarget = shown;
+ this.crowd.count = Math.max(this.crowd.count, shown);
+ }
+
+ _tickCrowd(dt) {
+ const crowd = this.crowd;
+ if (!crowd) return;
+ const target = this._crowdTarget ?? 0;
+ const m = new Matrix4();
+ const o = new Object3D();
+ let changed = false;
+ let live = 0;
+ for (let i = 0; i < crowd.count; i++) {
+ const goal = i < target ? 1 : 0;
+ const s = this.crowdScale[i];
+ const next = this.reducedMotion ? goal : s + (goal - s) * Math.min(1, dt * 5);
+ if (Math.abs(next - s) > 1e-3 || (goal === 1 && s !== 1 && this.reducedMotion)) changed = true;
+ this.crowdScale[i] = Math.abs(next - goal) < 1e-3 ? goal : next;
+ const seat = this.crowdSeats[i];
+ o.position.set(seat.x, 0, seat.z);
+ o.rotation.set(0, seat.ry, 0);
+ const sc = Math.max(0.0001, this.crowdScale[i] * SPECTATOR_SCALE);
+ o.scale.set(sc, sc, sc);
+ o.updateMatrix();
+ m.copy(o.matrix);
+ crowd.setMatrixAt(i, m);
+ if (this.crowdScale[i] > 0.001) live = i + 1;
+ }
+ if (changed || crowd.count !== Math.max(live, target)) {
+ crowd.count = Math.max(live, target);
+ crowd.instanceMatrix.needsUpdate = true;
+ }
+ }
+
+ _burst(tone) {
+ const slot = this.burstPool.find((b) => b.life <= 0) || this.burstPool[0];
+ const n = this.budget.particles;
+ const pos = slot.pts.geometry.getAttribute('position');
+ for (let i = 0; i < n; i++) {
+ const a = Math.random() * Math.PI * 2;
+ const r = 0.2 + Math.random() * 0.5;
+ pos.array[i * 3] = Math.cos(a) * r;
+ pos.array[i * 3 + 1] = tone === 'loss' ? 2.6 : 0.4;
+ pos.array[i * 3 + 2] = Math.sin(a) * r;
+ const up = tone === 'loss' ? -0.4 - Math.random() * 0.6 : 2.2 + Math.random() * 1.8;
+ slot.vel[i * 3] = Math.cos(a) * (0.4 + Math.random());
+ slot.vel[i * 3 + 1] = up;
+ slot.vel[i * 3 + 2] = Math.sin(a) * (0.4 + Math.random());
+ }
+ pos.needsUpdate = true;
+ slot.pts.geometry.setDrawRange(0, n);
+ slot.pts.material.color.setHex(TONE_COLOR[tone]);
+ slot.pts.material.opacity = 1;
+ slot.pts.visible = true;
+ slot.life = 1.8;
+ slot.n = n;
+ }
+
+ _tickBursts(dt) {
+ for (const b of this.burstPool) {
+ if (b.life <= 0) continue;
+ b.life -= dt;
+ const pos = b.pts.geometry.getAttribute('position');
+ for (let i = 0; i < b.n; i++) {
+ b.vel[i * 3 + 1] -= 3.2 * dt;
+ pos.array[i * 3] += b.vel[i * 3] * dt;
+ pos.array[i * 3 + 1] = Math.max(0.02, pos.array[i * 3 + 1] + b.vel[i * 3 + 1] * dt);
+ pos.array[i * 3 + 2] += b.vel[i * 3 + 2] * dt;
+ }
+ pos.needsUpdate = true;
+ b.pts.material.opacity = Math.max(0, Math.min(1, b.life / 0.8));
+ if (b.life <= 0) b.pts.visible = false;
+ }
+ }
+
+ // ── loop / budget ──────────────────────────────────────────────────────
+
+ _applyTier() {
+ this.budget = TIER_BUDGET[this.tier];
+ const dpr = Math.min(window.devicePixelRatio || 1, this.budget.pixelRatio);
+ this.renderer.setPixelRatio(dpr);
+ this.renderer.shadowMap.enabled = this.budget.shadows;
+ if (this.keyLight) this.keyLight.castShadow = this.budget.shadows;
+ }
+
+ _setTier(tier) {
+ this.tier = tier;
+ this._applyTier();
+ this._layoutCrowd();
+ this._resize();
+ }
+
+ _resize() {
+ if (!this.renderer || !this.host) return;
+ const w = Math.max(1, this.host.clientWidth);
+ const h = Math.max(1, this.host.clientHeight);
+ this.renderer.setSize(w, h, false);
+ this.camera.aspect = w / h;
+ // Pull back on narrow screens so the board and the crowd stay in frame.
+ this.camera.fov = w / h < 0.9 ? 58 : 42;
+ this.camera.updateProjectionMatrix();
+ }
+
+ _loop(now) {
+ if (this.disposed) return;
+ this._raf = requestAnimationFrame(this._loop);
+ if (!this._visible) return;
+ const cap = getPowerSaver() ? FPS_SAVER : this.focus.focused ? FPS_ACTIVE : FPS_IDLE;
+ if (!this.governor.shouldRun(now, cap)) return;
+ this.timer.update(now);
+ const dt = Math.min(0.1, this.timer.getDelta());
+
+ this.watchdog.tick(dt);
+ if (this.tier === 'low' && this.leaderReady) {
+ this._slowOnLow = this.watchdog.getFrameAvg() > GIVE_UP_FRAME_SEC ? this._slowOnLow + dt : 0;
+ if (this._slowOnLow > GIVE_UP_AFTER_SEC) {
+ this.opts.onFallback?.('slow');
+ return;
+ }
+ }
+
+ this.anim.update(dt);
+ // Sway between the azimuth limits instead of parking against one of them.
+ if (this.controls.autoRotate) {
+ const az = this.controls.getAzimuthalAngle();
+ if (Math.abs(az) > this.controls.maxAzimuthAngle * 0.55 && Math.sign(az) === -Math.sign(this.controls.autoRotateSpeed)) {
+ this.controls.autoRotateSpeed *= -1;
+ }
+ }
+ this.controls.update();
+ if (!this.reducedMotion) this.tapeTex.offset.x = (this.tapeTex.offset.x + dt * 0.018) % 1;
+ if (this.ringFlash > 0) {
+ this.ringFlash = Math.max(0, this.ringFlash - dt * 0.6);
+ this.ringMat.opacity = 0.45 + this.ringFlash * 0.5;
+ }
+ this._tickCrowd(dt);
+ this._tickBursts(dt);
+ this.renderer.render(this.scene, this.camera);
+ }
+}
diff --git a/src/trade-room/trade-room.css b/src/trade-room/trade-room.css
new file mode 100644
index 000000000..ea89383e2
--- /dev/null
+++ b/src/trade-room/trade-room.css
@@ -0,0 +1,416 @@
+/* Live trade rooms (/trade-rooms, /trade-rooms/:id).
+ Built on the canonical tokens (public/tokens.css via nav.css) plus the
+ leaderboard's shared button and P&L classes (src/leaderboard.css). */
+
+.tr-shell {
+ font-family: var(--font-body);
+ color: var(--ink);
+ max-width: 1280px;
+ margin: 0 auto;
+ padding: var(--space-lg) var(--space-md) var(--space-2xl);
+}
+
+.tr-sr-only {
+ position: absolute !important;
+ width: 1px;
+ height: 1px;
+ padding: 0;
+ margin: -1px;
+ overflow: hidden;
+ clip: rect(0 0 0 0);
+ white-space: nowrap;
+ border: 0;
+}
+
+.tr-dim { color: var(--ink-dim); }
+.tr-mono { font-family: var(--font-mono); font-variant-numeric: tabular-nums; }
+
+/* ── Lobby hero ─────────────────────────────────────────────────────────── */
+.tr-hero { text-align: center; margin: var(--space-lg) auto var(--space-xl); max-width: 760px; }
+.tr-kicker {
+ display: inline-flex;
+ align-items: center;
+ gap: var(--space-2xs);
+ font-family: var(--font-mono);
+ font-size: var(--text-2xs);
+ letter-spacing: 0.08em;
+ text-transform: uppercase;
+ color: var(--ink-dim);
+ padding: var(--space-3xs) var(--space-sm);
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-pill);
+ background: var(--surface-glass);
+}
+.tr-live-dot {
+ width: 7px;
+ height: 7px;
+ border-radius: 50%;
+ background: var(--success);
+ animation: tr-pulse 2.2s var(--ease-out) infinite;
+}
+@keyframes tr-pulse {
+ 0% { box-shadow: 0 0 0 0 rgba(52, 211, 153, 0.5); }
+ 70% { box-shadow: 0 0 0 8px rgba(52, 211, 153, 0); }
+ 100% { box-shadow: 0 0 0 0 rgba(52, 211, 153, 0); }
+}
+.tr-title {
+ font-family: var(--font-display);
+ font-weight: var(--weight-bold);
+ font-size: var(--text-3xl);
+ line-height: var(--leading-tight);
+ margin: var(--space-sm) 0 var(--space-xs);
+ color: var(--ink-bright);
+}
+.tr-sub { color: var(--ink-dim); line-height: var(--leading-normal); margin: 0; }
+
+.tr-lobby-head {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: var(--space-sm);
+ margin-bottom: var(--space-sm);
+}
+.tr-lobby-head h2 { margin: 0; font-size: var(--text-lg); color: var(--ink-bright); }
+.tr-lobby-note {
+ grid-column: 1 / -1;
+ margin: 0 0 var(--space-2xs);
+ padding: var(--space-xs) var(--space-sm);
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-md);
+ background: var(--surface-glass);
+ color: var(--ink-dim);
+ font-size: var(--text-sm);
+}
+
+.tr-grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
+ gap: var(--space-sm);
+}
+.tr-grid--compact { grid-template-columns: repeat(auto-fill, minmax(220px, 1fr)); }
+
+/* ── Room cards ─────────────────────────────────────────────────────────── */
+.tr-card {
+ display: flex;
+ flex-direction: column;
+ gap: var(--space-xs);
+ padding: var(--space-sm);
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-card);
+ background: var(--surface-1);
+ color: var(--ink);
+ text-decoration: none;
+ transition: transform var(--duration-fast) var(--ease-out), border-color var(--duration-fast) var(--ease-out), box-shadow var(--duration-fast) var(--ease-out);
+}
+.tr-card:hover { transform: translateY(-2px); border-color: var(--stroke-strong); box-shadow: var(--shadow-2); }
+.tr-card:active { transform: translateY(0); }
+.tr-card:focus-visible { outline: var(--focus-ring-width) solid var(--focus-ring-color); outline-offset: var(--focus-ring-offset); }
+.tr-card--live { border-color: color-mix(in srgb, var(--success) 40%, var(--stroke)); }
+.tr-card-top { display: flex; align-items: center; gap: var(--space-xs); min-width: 0; }
+.tr-card-av { width: 44px; height: 44px; border-radius: 50%; object-fit: cover; flex: none; background: var(--surface-2); }
+.tr-card-id { display: flex; flex-direction: column; gap: 4px; min-width: 0; }
+.tr-card-name { font-weight: var(--weight-semibold); color: var(--ink-bright); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.tr-card-stats { display: flex; flex-wrap: wrap; gap: 4px var(--space-xs); font-size: var(--text-xs); color: var(--ink-dim); }
+.tr-card-foot { display: flex; align-items: center; justify-content: space-between; gap: var(--space-xs); margin-top: auto; }
+.tr-card-cta { margin-left: auto; font-size: var(--text-sm); font-weight: var(--weight-semibold); color: var(--accent); }
+.tr-card--compact .tr-card-av { width: 36px; height: 36px; }
+
+/* ── State + presence pills ─────────────────────────────────────────────── */
+.tr-state, .tr-watch, .tr-conn {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ font: var(--weight-semibold) var(--text-2xs) / 1 var(--font-mono);
+ letter-spacing: 0.04em;
+ text-transform: uppercase;
+ padding: 5px 9px;
+ border-radius: var(--radius-pill);
+ border: 1px solid var(--stroke);
+ background: var(--surface-glass);
+ color: var(--ink-dim);
+ white-space: nowrap;
+ width: fit-content;
+}
+.tr-state-dot { width: 7px; height: 7px; border-radius: 50%; background: currentColor; }
+.tr-state--live { color: var(--success); border-color: color-mix(in srgb, var(--success) 40%, transparent); }
+.tr-state--live .tr-state-dot { animation: tr-pulse 2.2s var(--ease-out) infinite; }
+.tr-state--warm { color: var(--warn); border-color: color-mix(in srgb, var(--warn) 35%, transparent); }
+.tr-state--quiet { color: var(--ink-faint); }
+.tr-watch { color: var(--ink); }
+.tr-conn[data-state='live'] { color: var(--success); }
+.tr-conn[data-state='reconnecting'] { color: var(--warn); }
+.tr-conn[data-state='paused'] { color: var(--ink-faint); }
+
+/* ── Room layout ────────────────────────────────────────────────────────── */
+.tr-crumbs { margin-bottom: var(--space-sm); }
+.tr-crumbs a { color: var(--ink-dim); text-decoration: none; font-size: var(--text-sm); }
+.tr-crumbs a:hover { color: var(--ink-bright); }
+.tr-crumbs a:focus-visible { outline: var(--focus-ring-width) solid var(--focus-ring-color); outline-offset: 2px; border-radius: 4px; }
+
+.tr-room {
+ display: grid;
+ grid-template-columns: minmax(0, 1fr) 380px;
+ gap: var(--space-md);
+ align-items: start;
+}
+
+.tr-stage {
+ height: min(72vh, 660px);
+ min-height: 360px;
+ border-radius: var(--radius-card);
+ overflow: hidden;
+ border: 1px solid var(--stroke);
+ background: radial-gradient(120% 90% at 50% 20%, #161a2b 0%, #07080d 70%);
+ /* Sticky on wide screens so the room stays in view while the trade list scrolls. */
+ position: sticky;
+ top: calc(var(--nav-h, 64px) + var(--space-sm));
+}
+.tr-canvas-host { position: absolute; inset: 0; }
+.tr-canvas { display: block; width: 100%; height: 100%; touch-action: none; }
+.tr-stage--flat { height: auto; min-height: 0; position: relative; top: auto; }
+.tr-stage--flat .tr-canvas-host { display: none; }
+.tr-stage--flat .tr-hud, .tr-stage--flat .tr-stage-foot { position: relative; }
+.tr-stage--loading .tr-stage-shimmer,
+.tr-stage--loading .tr-canvas-host::after {
+ content: '';
+ position: absolute;
+ inset: 0;
+ background: linear-gradient(100deg, transparent 20%, rgba(255, 255, 255, 0.05) 45%, transparent 70%);
+ background-size: 200% 100%;
+ animation: tr-shimmer 1.4s linear infinite;
+}
+@keyframes tr-shimmer { from { background-position: 200% 0; } to { background-position: -200% 0; } }
+
+.tr-hud {
+ position: absolute;
+ top: 0;
+ left: 0;
+ right: 0;
+ display: flex;
+ justify-content: space-between;
+ align-items: flex-start;
+ gap: var(--space-xs);
+ padding: var(--space-sm);
+ pointer-events: none;
+ z-index: 2;
+}
+.tr-hud > * { pointer-events: auto; }
+.tr-leader-chip {
+ display: flex;
+ align-items: center;
+ gap: var(--space-xs);
+ padding: 6px 12px 6px 6px;
+ border-radius: var(--radius-pill);
+ background: rgba(8, 10, 18, 0.72);
+ border: 1px solid rgba(255, 255, 255, 0.1);
+ backdrop-filter: blur(var(--blur-sm));
+ color: #eef1f7;
+ text-decoration: none;
+ min-width: 0;
+ max-width: 70%;
+ transition: border-color var(--duration-fast) var(--ease-out), transform var(--duration-fast) var(--ease-out);
+}
+.tr-leader-chip:hover { border-color: rgba(255, 255, 255, 0.28); transform: translateY(-1px); }
+.tr-leader-chip:focus-visible { outline: var(--focus-ring-width) solid var(--focus-ring-color); outline-offset: 2px; }
+.tr-leader-av { width: 38px; height: 38px; border-radius: 50%; object-fit: cover; flex: none; background: #1c2135; }
+.tr-leader-meta { display: flex; flex-direction: column; min-width: 0; }
+.tr-leader-name { font-weight: var(--weight-semibold); display: inline-flex; align-items: center; gap: 4px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.tr-leader-sub { font-size: var(--text-2xs); color: #9aa3b4; }
+.tr-pills { display: flex; flex-wrap: wrap; justify-content: flex-end; gap: 6px; }
+.tr-stage .tr-state, .tr-stage .tr-watch, .tr-stage .tr-conn { background: rgba(8, 10, 18, 0.72); border-color: rgba(255, 255, 255, 0.12); }
+.tr-stage .tr-watch { color: #eef1f7; }
+
+.tr-stage-foot {
+ position: absolute;
+ left: 0;
+ right: 0;
+ bottom: 0;
+ display: flex;
+ align-items: flex-end;
+ justify-content: space-between;
+ gap: var(--space-xs);
+ padding: var(--space-sm);
+ z-index: 2;
+ pointer-events: none;
+}
+.tr-stage-foot > * { pointer-events: auto; }
+.tr-stage-note {
+ margin: 0;
+ max-width: 70%;
+ padding: 8px 12px;
+ border-radius: var(--radius-md);
+ background: rgba(8, 10, 18, 0.78);
+ border: 1px solid rgba(255, 255, 255, 0.1);
+ color: #cdd3e0;
+ font-size: var(--text-sm);
+ line-height: 1.4;
+}
+.tr-stage-note[hidden] { display: none; }
+.tr-tool {
+ margin-left: auto;
+ padding: 8px 12px;
+ border-radius: var(--radius-pill);
+ border: 1px solid rgba(255, 255, 255, 0.16);
+ background: rgba(8, 10, 18, 0.72);
+ color: #eef1f7;
+ font: var(--weight-semibold) var(--text-xs) / 1 var(--font-body);
+ cursor: pointer;
+ transition: border-color var(--duration-fast) var(--ease-out), background var(--duration-fast) var(--ease-out);
+}
+.tr-tool:hover { border-color: rgba(255, 255, 255, 0.34); background: rgba(20, 24, 38, 0.9); }
+.tr-tool:active { transform: translateY(1px); }
+.tr-tool:focus-visible { outline: var(--focus-ring-width) solid var(--focus-ring-color); outline-offset: 2px; }
+.tr-tool[hidden] { display: none; }
+
+.tr-stage-panel { padding: 88px var(--space-md) 72px; text-align: center; }
+.tr-panel-inner { max-width: 460px; margin: 0 auto; display: flex; flex-direction: column; align-items: center; gap: var(--space-xs); }
+.tr-panel-title { margin: 0; font-weight: var(--weight-semibold); color: #eef1f7; font-size: var(--text-md); }
+.tr-panel-body { margin: 0; color: #9aa3b4; font-size: var(--text-sm); line-height: 1.5; }
+.tr-stage--flat .tr-stage-foot { display: none; }
+.tr-stage--flat .tr-stage-panel { padding-top: var(--space-md); padding-bottom: var(--space-md); }
+.tr-stage--flat .tr-hud { padding-bottom: 0; }
+
+/* The trade that just landed, big and brief, over the canvas. */
+.tr-flash {
+ position: absolute;
+ left: 50%;
+ top: 22%;
+ transform: translate(-50%, 8px);
+ max-width: 88%;
+ padding: 10px 16px;
+ border-radius: var(--radius-lg);
+ font: var(--weight-bold) var(--text-md) / 1.25 var(--font-body);
+ color: #07080d;
+ text-align: center;
+ opacity: 0;
+ pointer-events: none;
+ z-index: 3;
+}
+.tr-flash--buy { background: #60a5fa; }
+.tr-flash--win { background: #34d399; }
+.tr-flash--loss { background: #f87171; }
+.tr-flash--flat { background: #cbd5e1; }
+.tr-flash.is-on { animation: tr-flash 3.2s var(--ease-out) both; }
+@keyframes tr-flash {
+ 0% { opacity: 0; transform: translate(-50%, 8px) scale(0.96); }
+ 10% { opacity: 1; transform: translate(-50%, 0) scale(1); }
+ 80% { opacity: 1; transform: translate(-50%, 0) scale(1); }
+ 100% { opacity: 0; transform: translate(-50%, -6px) scale(0.98); }
+}
+
+/* ── Side column ────────────────────────────────────────────────────────── */
+.tr-side { display: flex; flex-direction: column; gap: var(--space-sm); min-width: 0; }
+.tr-side > section {
+ padding: var(--space-sm);
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-card);
+ background: var(--surface-1);
+}
+.tr-side > section[hidden] { display: none; }
+.tr-h { margin: 0 0 var(--space-xs); font-size: var(--text-sm); font-weight: var(--weight-semibold); color: var(--ink-bright); }
+.tr-last { margin: 0 0 var(--space-xs); color: var(--ink); font-size: var(--text-sm); line-height: 1.45; }
+.tr-stats { display: grid; grid-template-columns: 1fr 1fr; gap: var(--space-xs); margin: 0 0 var(--space-sm); }
+.tr-stat { padding: 8px 10px; border-radius: var(--radius-md); background: var(--surface-2); min-width: 0; }
+.tr-stat dt { font-size: var(--text-2xs); color: var(--ink-dim); margin-bottom: 2px; }
+.tr-stat dd { margin: 0; font: var(--weight-semibold) var(--text-sm) / 1.3 var(--font-mono); font-variant-numeric: tabular-nums; overflow-wrap: anywhere; }
+.tr-actions { display: flex; flex-wrap: wrap; gap: var(--space-2xs); }
+.tr-actions .lb-btn { flex: 1 1 auto; justify-content: center; }
+.tr-copiers { margin: var(--space-xs) 0 0; font-size: var(--text-xs); }
+
+.tr-why-line { margin: 0 0 var(--space-xs); font-size: var(--text-sm); line-height: 1.5; color: var(--ink); }
+.tr-skel-line { color: var(--ink-faint); }
+
+.tr-open-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 6px; }
+.tr-open-row { display: flex; flex-wrap: wrap; align-items: baseline; gap: 4px var(--space-xs); font-size: var(--text-sm); }
+
+.tr-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 6px; }
+.tr-list-empty { list-style: none; }
+.tr-row {
+ display: grid;
+ grid-template-columns: auto minmax(0, 1fr);
+ gap: 6px var(--space-xs);
+ padding: 8px 10px;
+ border-radius: var(--radius-md);
+ background: var(--surface-2);
+ border: 1px solid transparent;
+}
+.tr-row.is-fresh { animation: tr-row-in 1.6s var(--ease-out); }
+@keyframes tr-row-in {
+ 0% { opacity: 0; transform: translateY(-6px); border-color: var(--accent); }
+ 15% { opacity: 1; transform: translateY(0); }
+ 100% { border-color: transparent; }
+}
+.tr-badge {
+ align-self: start;
+ font: 800 10px / 1 var(--font-mono);
+ letter-spacing: 0.06em;
+ text-transform: uppercase;
+ padding: 5px 7px;
+ border-radius: 6px;
+ color: #07080d;
+}
+.tr-badge--buy { background: #60a5fa; }
+.tr-badge--win { background: #34d399; }
+.tr-badge--loss { background: #f87171; }
+.tr-badge--flat { background: #cbd5e1; }
+.tr-row-main { min-width: 0; }
+.tr-row-line { margin: 0; font-size: var(--text-sm); overflow-wrap: anywhere; }
+.tr-row-line strong { color: var(--ink-bright); }
+.tr-row-meta { margin: 2px 0 0; font-size: var(--text-xs); color: var(--ink-dim); }
+.tr-pnl { font-family: var(--font-mono); font-weight: var(--weight-semibold); }
+.tr-paper { color: var(--warn); font-weight: var(--weight-semibold); }
+.tr-row-acts { grid-column: 1 / -1; display: flex; flex-wrap: wrap; align-items: center; gap: 6px; }
+.tr-mini {
+ display: inline-flex;
+ align-items: center;
+ box-sizing: border-box;
+ padding: 0 12px;
+ height: 32px;
+ min-height: 0;
+ min-width: 0;
+ width: auto;
+ border-radius: var(--radius-pill);
+ border: 1px solid var(--stroke);
+ background: var(--surface-1);
+ color: var(--ink);
+ font: var(--weight-semibold) var(--text-xs) / 1 var(--font-body);
+ text-decoration: none;
+ cursor: pointer;
+ transition: border-color var(--duration-fast) var(--ease-out), background var(--duration-fast) var(--ease-out), transform var(--duration-fast) var(--ease-out);
+}
+.tr-mini:hover { border-color: var(--stroke-strong); background: var(--surface-3); }
+.tr-mini:active { transform: translateY(1px); }
+.tr-mini:focus-visible { outline: var(--focus-ring-width) solid var(--focus-ring-color); outline-offset: 2px; }
+.tr-mini[aria-expanded='true'] { border-color: var(--accent); color: var(--ink-bright); }
+.tr-mini--fork { border-color: color-mix(in srgb, var(--accent) 45%, var(--stroke)); }
+.tr-mini[disabled] { opacity: var(--disabled-opacity, 0.5); cursor: progress; }
+.tr-receipt { grid-column: 1 / -1; }
+.tr-receipt[hidden] { display: none; }
+.tr-receipt-err { margin: 0; font-size: var(--text-sm); color: var(--ink-dim); display: flex; align-items: center; gap: var(--space-xs); flex-wrap: wrap; }
+
+.tr-others { margin-top: var(--space-xl); }
+
+/* ── Responsive ─────────────────────────────────────────────────────────── */
+@media (max-width: 1023px) {
+ .tr-room { grid-template-columns: minmax(0, 1fr); }
+ .tr-stage { position: relative; top: auto; height: min(58vh, 520px); min-height: 300px; }
+}
+@media (max-width: 560px) {
+ .tr-shell { padding: var(--space-sm) var(--space-sm) var(--space-xl); }
+ .tr-title { font-size: var(--text-2xl); }
+ .tr-stage { height: 54vh; min-height: 280px; border-radius: var(--radius-lg); }
+ .tr-leader-chip { max-width: 100%; }
+ .tr-hud { flex-direction: column; }
+ .tr-pills { justify-content: flex-start; }
+ .tr-stage-note { max-width: 100%; font-size: var(--text-xs); }
+ .tr-stage-foot { flex-direction: column; align-items: stretch; }
+ .tr-tool { margin-left: 0; align-self: flex-end; }
+ .tr-flash { font-size: var(--text-sm); top: 36%; }
+ .tr-stats { grid-template-columns: 1fr 1fr; }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .tr-live-dot, .tr-state--live .tr-state-dot, .tr-row.is-fresh, .tr-stage--loading .tr-stage-shimmer,
+ .tr-stage--loading .tr-canvas-host::after { animation: none; }
+ .tr-card, .tr-card:hover { transform: none; }
+}
diff --git a/src/trader.js b/src/trader.js
index 3a7bdde09..fe9a7a1a7 100644
--- a/src/trader.js
+++ b/src/trader.js
@@ -361,7 +361,8 @@ function render(data) {
<div class="tp-actions">
<div class="lb-seg" role="tablist" aria-label="Time window" id="tp-window">${winSeg}</div>
- <div style="display:flex;gap:var(--space-2xs)">
+ <div style="display:flex;flex-wrap:wrap;gap:var(--space-2xs)">
+ <a class="lb-btn" href="/trade-rooms/${encodeURIComponent(a.id)}${ctx.network === 'mainnet' ? '' : `?network=${ctx.network}`}">Watch live room</a>
<button class="lb-btn" id="tp-embed" aria-expanded="false" aria-controls="tp-embed-panel">Embed this trader</button>
<button class="lb-btn" id="tp-share">Share track record</button>
<button class="lb-btn lb-btn-primary" id="tp-card">Download PnL card</button>
diff --git a/tests/trade-room.test.js b/tests/trade-room.test.js
new file mode 100644
index 000000000..fbd6fec44
--- /dev/null
+++ b/tests/trade-room.test.js
@@ -0,0 +1,284 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+import { readFileSync } from 'node:fs';
+
+// The loaders import the database client; everything under test is pure.
+vi.mock('../api/_lib/db.js', () => ({ sql: () => Promise.resolve([]) }));
+
+// Presence reads Redis through this singleton; each test picks the client.
+let redisClient = null;
+vi.mock('../api/_lib/redis.js', () => ({ getRedis: () => redisClient }));
+
+const {
+ positionEvents, eventsSince, roomState, rankRooms, sanitizeSession, streamStartCursor,
+ STREAM_SINCE_MAX_AGE_MS, LIVE_WINDOW_MS, WARM_WINDOW_MS,
+} = await import('../api/_lib/trade-room.js');
+const presence = await import('../api/_lib/trade-room-presence.js');
+const model = await import('../src/trade-room/model.js');
+
+const SIG_BUY = '4M7puu2FyPbLqtW9fML9QaNuupCpGDhw3xh26EHA7PJcUdwY1TkfdxDnregfuUcqp8fPxLrBMtcvnxnhHNXxswhW';
+const SIG_SELL = '2zMLQ2E8spH2toFyAyhvkroyw8akATyrgdYkzvW6fzWLRB4Xyfwv76FrgotiQvNKXoSjE9LonAVNUkFvVuReprC4';
+const THREE = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+
+/** A closed live round-trip on $THREE. Tests override one field at a time. */
+function row(over = {}) {
+ return {
+ id: '11111111-2222-3333-4444-555555555555',
+ agent_id: 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee',
+ mint: THREE,
+ symbol: 'THREE',
+ name: 'three.ws',
+ status: 'closed',
+ exit_reason: 'trailing_stop',
+ entry_quote_lamports: '2000000',
+ exit_quote_lamports: '1379766',
+ last_value_lamports: '1379766',
+ realized_pnl_lamports: '-620234',
+ realized_pnl_pct: '-31.0117',
+ buy_sig: SIG_BUY,
+ sell_sig: SIG_SELL,
+ opened_at: '2026-09-29T06:08:17.327Z',
+ closed_at: '2026-09-29T06:09:12.197Z',
+ last_quoted_at: '2026-09-29T06:09:10.000Z',
+ ...over,
+ };
+}
+
+describe('positionEvents', () => {
+ it('turns a closed round-trip into a sell then its buy, newest first', () => {
+ const [sell, buy] = positionEvents([row()]);
+ expect(sell).toMatchObject({
+ id: '11111111-2222-3333-4444-555555555555:sell',
+ kind: 'sell',
+ at: '2026-09-29T06:09:12.197Z',
+ size_sol: 0.001379766,
+ pnl_sol: -0.000620234,
+ exit_label: 'Trailing stop',
+ hold_seconds: 55,
+ share_url: '/trade/11111111-2222-3333-4444-555555555555',
+ paper: false,
+ });
+ expect(sell.tx_url).toBe(`https://solscan.io/tx/${SIG_SELL}`);
+ expect(buy).toMatchObject({ kind: 'buy', size_sol: 0.002, entry_sol: 0.002, at: '2026-09-29T06:08:17.327Z' });
+ expect(buy.tx_url).toBe(`https://solscan.io/tx/${SIG_BUY}`);
+ expect(buy.share_url).toBeUndefined();
+ });
+
+ it('shows an open position as a buy only', () => {
+ const events = positionEvents([row({ status: 'open', closed_at: null, sell_sig: null })]);
+ expect(events.map((e) => e.kind)).toEqual(['buy']);
+ });
+
+ it('never shows a failed position as a trade', () => {
+ expect(positionEvents([row({ status: 'failed', buy_sig: null })])).toEqual([]);
+ expect(positionEvents([row({ status: 'opening', buy_sig: null })])).toEqual([]);
+ });
+
+ it('labels paper fills and gives them no Solscan link', () => {
+ const [sell, buy] = positionEvents([row({ buy_sig: 'SIMULATED', sell_sig: 'SIMULATED' })]);
+ expect(buy.paper).toBe(true);
+ expect(sell.paper).toBe(true);
+ expect(buy.tx_url).toBeNull();
+ expect(sell.tx_url).toBeNull();
+ });
+
+ it('links devnet trades to the devnet explorer', () => {
+ const [sell] = positionEvents([row()], { network: 'devnet' });
+ expect(sell.tx_url).toBe(`https://solscan.io/tx/${SIG_SELL}?cluster=devnet`);
+ });
+
+ it('merges several positions by time and honours the limit', () => {
+ const older = row({ id: 'p-old', opened_at: '2026-09-29T05:00:00.000Z', closed_at: '2026-09-29T05:10:00.000Z' });
+ const events = positionEvents([older, row()], { limit: 3 });
+ expect(events.map((e) => e.id)).toEqual([
+ '11111111-2222-3333-4444-555555555555:sell',
+ '11111111-2222-3333-4444-555555555555:buy',
+ 'p-old:sell',
+ ]);
+ });
+});
+
+describe('eventsSince', () => {
+ const opened = Date.parse('2026-09-29T06:08:17.327Z');
+
+ it('emits the buy before the sell when both land inside one poll', () => {
+ const { trades } = eventsSince([row()], opened - 1000);
+ expect(trades.map((t) => t.kind)).toEqual(['buy', 'sell']);
+ });
+
+ it('skips what the page already painted', () => {
+ const { trades } = eventsSince([row()], opened);
+ expect(trades.map((t) => t.kind)).toEqual(['sell']);
+ });
+
+ it('emits a quote for an open position whose value moved', () => {
+ const open = row({ status: 'open', closed_at: null, sell_sig: null, last_value_lamports: '2500000' });
+ const { trades, quotes } = eventsSince([open], opened + 1000);
+ expect(trades).toEqual([]);
+ expect(quotes).toHaveLength(1);
+ expect(quotes[0]).toMatchObject({ position_id: open.id, current_sol: 0.0025 });
+ expect(quotes[0].unrealized_pct).toBeCloseTo(25, 6);
+ });
+
+ it('does not quote a closed position', () => {
+ expect(eventsSince([row()], Date.parse('2026-09-29T06:09:13.000Z')).quotes).toEqual([]);
+ });
+});
+
+describe('roomState', () => {
+ const now = Date.parse('2026-09-29T12:00:00.000Z');
+ const ago = (ms) => new Date(now - ms).toISOString();
+
+ it('is live while a position is open, however old the last fill', () => {
+ expect(roomState({ lastTradeAt: ago(3 * WARM_WINDOW_MS), openCount: 1, now })).toBe('live');
+ });
+ it('is live inside the live window', () => {
+ expect(roomState({ lastTradeAt: ago(LIVE_WINDOW_MS - 1), now })).toBe('live');
+ });
+ it('cools to warm, then quiet', () => {
+ expect(roomState({ lastTradeAt: ago(LIVE_WINDOW_MS + 1), now })).toBe('warm');
+ expect(roomState({ lastTradeAt: ago(WARM_WINDOW_MS + 1), now })).toBe('quiet');
+ });
+ it('is quiet for a leader who never traded', () => {
+ expect(roomState({ lastTradeAt: null, now })).toBe('quiet');
+ expect(roomState({ lastTradeAt: 'not a date', now })).toBe('quiet');
+ });
+});
+
+describe('rankRooms', () => {
+ it('puts live rooms first, then by spectators, then by recency', () => {
+ const ranked = rankRooms([
+ { agent_id: 'quiet', state: 'quiet', spectators: 9, last_trade_at: '2026-09-01T00:00:00Z' },
+ { agent_id: 'warm-old', state: 'warm', spectators: 0, last_trade_at: '2026-09-29T01:00:00Z' },
+ { agent_id: 'warm-new', state: 'warm', spectators: 0, last_trade_at: '2026-09-29T02:00:00Z' },
+ { agent_id: 'live', state: 'live', spectators: 0, last_trade_at: '2026-09-29T03:00:00Z' },
+ { agent_id: 'warm-watched', state: 'warm', spectators: 3, last_trade_at: '2026-09-28T23:00:00Z' },
+ ]);
+ expect(ranked.map((r) => r.agent_id)).toEqual(['live', 'warm-watched', 'warm-new', 'warm-old', 'quiet']);
+ });
+});
+
+describe('stream inputs', () => {
+ it('accepts only short plain session ids', () => {
+ expect(sanitizeSession('a1b2c3d4e5f6')).toBe('a1b2c3d4e5f6');
+ expect(sanitizeSession('short')).toBeNull();
+ expect(sanitizeSession('x'.repeat(41))).toBeNull();
+ expect(sanitizeSession('has space 12345')).toBeNull();
+ expect(sanitizeSession(null)).toBeNull();
+ });
+
+ it('clamps the stream start to a recent, non-future instant', () => {
+ const now = Date.parse('2026-09-29T12:00:00.000Z');
+ expect(streamStartCursor(undefined, now)).toBe(now);
+ expect(streamStartCursor('garbage', now)).toBe(now);
+ expect(streamStartCursor('2026-09-29T13:00:00.000Z', now)).toBe(now);
+ expect(streamStartCursor('2026-09-29T11:58:00.000Z', now)).toBe(now - 120_000);
+ expect(streamStartCursor('2026-09-01T00:00:00.000Z', now)).toBe(now - STREAM_SINCE_MAX_AGE_MS);
+ });
+});
+
+describe('spectator presence', () => {
+ const AGENT = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee';
+ beforeEach(() => {
+ presence._resetLocalPresence();
+ redisClient = null;
+ });
+
+ it('counts in-process when Redis is not configured, and ages sessions out', async () => {
+ const t0 = 1_000_000;
+ expect(await presence.touchSpectator(AGENT, 'session-aaaa', t0)).toBe('instance');
+ await presence.touchSpectator(AGENT, 'session-bbbb', t0);
+ expect(await presence.countSpectators(AGENT, t0 + 1)).toEqual({ count: 2, scope: 'instance' });
+ await presence.leaveSpectator(AGENT, 'session-aaaa');
+ expect((await presence.countSpectators(AGENT, t0 + 1)).count).toBe(1);
+ expect((await presence.countSpectators(AGENT, t0 + presence.SPECTATOR_TTL_MS + 1)).count).toBe(0);
+ });
+
+ it('uses the shared sorted set when Redis answers', async () => {
+ const sets = new Map();
+ redisClient = {
+ zadd: async (k, { score, member }) => { if (!sets.has(k)) sets.set(k, new Map()); sets.get(k).set(member, score); return 1; },
+ expire: async () => 1,
+ zrem: async (k, m) => { sets.get(k)?.delete(m); return 1; },
+ zcount: async (k, min) => [...(sets.get(k)?.values() || [])].filter((s) => s >= min).length,
+ };
+ expect(await presence.touchSpectator(AGENT, 'session-aaaa', 5_000)).toBe('shared');
+ expect(await presence.countSpectators(AGENT, 5_001)).toEqual({ count: 1, scope: 'shared' });
+ const many = await presence.countSpectatorsMany([AGENT, 'other-agent'], 5_001);
+ expect(many.get(AGENT)).toBe(1);
+ expect(many.get('other-agent')).toBe(0);
+ await presence.leaveSpectator(AGENT, 'session-aaaa');
+ expect((await presence.countSpectators(AGENT, 5_001)).count).toBe(0);
+ });
+
+ it('falls back to the in-process count when Redis errors', async () => {
+ const boom = async () => { throw new Error('down'); };
+ redisClient = { zadd: boom, expire: boom, zrem: boom, zcount: boom };
+ expect(await presence.touchSpectator(AGENT, 'session-aaaa', 10)).toBe('instance');
+ expect(await presence.countSpectators(AGENT, 11)).toEqual({ count: 1, scope: 'instance' });
+ expect((await presence.countSpectatorsMany([AGENT], 11)).get(AGENT)).toBe(1);
+ });
+});
+
+describe('trade room client model', () => {
+ const sell = positionEvents([row()])[0];
+ const buy = positionEvents([row()])[1];
+
+ it('reads a trade as one plain sentence', () => {
+ expect(model.tradeLine(buy)).toBe('Bought $THREE for 0.002 ◎');
+ expect(model.tradeLine(sell, 'Crosshair')).toBe('Crosshair sold $THREE for 0.00138 ◎, −31.0% on trailing stop');
+ expect(model.tradeLine({ ...buy, paper: true })).toBe('Paper-bought $THREE for 0.002 ◎');
+ });
+
+ it('picks a reaction clip that exists in the animation manifest', () => {
+ const manifest = JSON.parse(readFileSync(new URL('../public/animations/manifest.json', import.meta.url), 'utf8'));
+ const names = new Set(manifest.map((d) => d.name));
+ const cases = [buy, sell, { ...sell, pnl_pct: 0.2 }, { ...sell, pnl_pct: 12 }, { ...sell, pnl_pct: 80 }, { ...sell, pnl_pct: -5 }];
+ for (const t of cases) expect(names.has(model.reactionFor(t))).toBe(true);
+ expect(model.reactionFor(buy)).toBe('point');
+ expect(model.reactionFor(sell)).toBe('defeated');
+ expect(model.reactionFor({ ...sell, pnl_pct: 80 })).toBe('av-cheering');
+ });
+
+ it('merges live trades newest first without duplicates', () => {
+ let list = model.mergeTrade([], buy);
+ list = model.mergeTrade(list, sell);
+ list = model.mergeTrade(list, sell);
+ expect(list.map((t) => t.kind)).toEqual(['sell', 'buy']);
+ expect(model.mergeTrade(list, { ...buy, id: 'x', at: '2026-09-29T07:00:00Z' }, 2)).toHaveLength(2);
+ });
+
+ it('parses the room id from the URL', () => {
+ const id = '6287faf3-d41b-43cb-97bb-d305c1ac6e45';
+ expect(model.roomIdFromLocation('/trade-rooms')).toEqual({ id: '', invalid: false });
+ expect(model.roomIdFromLocation(`/trade-rooms/${id}/`)).toEqual({ id, invalid: false });
+ expect(model.roomIdFromLocation(`/trade-rooms/${id.toUpperCase()}`)).toEqual({ id, invalid: false });
+ expect(model.roomIdFromLocation('/trade-rooms', `?agent=${id}`)).toEqual({ id, invalid: false });
+ expect(model.roomIdFromLocation('/trade-rooms/not-a-room')).toEqual({ id: '', invalid: true });
+ });
+
+ it('backs off the stream reconnect up to 30s', () => {
+ expect([0, 1, 2, 3, 10].map(model.backoffMs)).toEqual([1000, 2000, 4000, 8000, 30000]);
+ });
+
+ it('writes an honest ticker for an empty room', () => {
+ expect(model.tickerText([])).toBe('Waiting for the first trade');
+ expect(model.lastTradedText(null)).toBe('No trades yet');
+ });
+
+ it('seats every spectator beside or behind the pedestal, facing it', () => {
+ const seats = model.spectatorSeats(24);
+ expect(seats).toHaveLength(24);
+ for (const s of seats) {
+ // Nobody stands between the camera (+z) and the leader.
+ expect(Math.atan2(Math.abs(s.x), s.z)).toBeGreaterThan((80 * Math.PI) / 180);
+ // Facing the pedestal: the seat's forward (+z rotated by ry) points at the origin.
+ const fx = Math.sin(s.ry);
+ const fz = Math.cos(s.ry);
+ expect(fx * -s.x + fz * -s.z).toBeGreaterThan(0);
+ }
+ });
+
+ it('mints URL-safe session ids the API accepts', () => {
+ for (let i = 0; i < 5; i++) expect(sanitizeSession(model.newSessionId())).not.toBeNull();
+ });
+});
diff --git a/vercel.json b/vercel.json
index 2761b2747..1e23617c9 100644
--- a/vercel.json
+++ b/vercel.json
@@ -40,7 +40,7 @@
"{api/agents/networth,api/avatars/from-forge,api/pay/execute,api/pay/simulate,api/cron/launcher-claimer,api/cron/fee-bridge,api/seed/synthesize,api/cron/x402-ring-tick}.js": {
"maxDuration": 60
},
- "{api/club/tips-stream,api/feed-stream,api/pump/trades-stream,api/oracle/stream,api/oracle/action-stream,api/sniper/stream,api/sniper/radar-stream,api/agent-screen-stream}.js": {
+ "{api/club/tips-stream,api/feed-stream,api/pump/trades-stream,api/oracle/stream,api/oracle/action-stream,api/sniper/stream,api/sniper/room-stream,api/sniper/radar-stream,api/agent-screen-stream}.js": {
"includeFiles": "{examples/skills/**,data/pages.json,data/archives/**,data/rss/**,data/_generated/**,sdk/src/sas-config.json}",
"maxDuration": 300
},
@@ -1485,6 +1485,14 @@
"src": "/trader/?",
"dest": "/trader.html"
},
+ {
+ "src": "/trade-rooms/([^/.]+)/?",
+ "dest": "/trade-room.html"
+ },
+ {
+ "src": "/trade-rooms/?",
+ "dest": "/trade-room.html"
+ },
{
"src": "/signals/?",
"dest": "/signals.html"
@@ -3809,6 +3817,18 @@
"src": "/api/sniper/receipt",
"dest": "/api/sniper/receipt.js"
},
+ {
+ "src": "/api/sniper/rooms",
+ "dest": "/api/sniper/rooms.js"
+ },
+ {
+ "src": "/api/sniper/room",
+ "dest": "/api/sniper/room.js"
+ },
+ {
+ "src": "/api/sniper/room-stream",
+ "dest": "/api/sniper/room-stream.js"
+ },
{
"src": "/api/traders/preview",
"dest": "/api/traders/preview.js"
diff --git a/vite.config.js b/vite.config.js
index cb59e6c18..a2ec8f32e 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -841,6 +841,7 @@ const appConfig = {
'ui-juice': resolve(__dirname, 'pages/ui-juice.html'),
terminal: resolve(__dirname, 'pages/terminal.html'),
trader: resolve(__dirname, 'pages/trader.html'),
+ 'trade-room': resolve(__dirname, 'pages/trade-room.html'),
signals: resolve(__dirname, 'pages/signals.html'),
'signal-detail': resolve(__dirname, 'pages/signal-detail.html'),
trades: resolve(__dirname, 'pages/trades.html'),
@@ -1694,6 +1695,8 @@ const appConfig = {
'/diorama/': resolve(root, 'pages/diorama.html'),
'/trader': resolve(root, 'pages/trader.html'),
'/trader/': resolve(root, 'pages/trader.html'),
+ '/trade-rooms': resolve(root, 'pages/trade-room.html'),
+ '/trade-rooms/': resolve(root, 'pages/trade-room.html'),
'/signals': resolve(root, 'pages/signals.html'),
'/signals/': resolve(root, 'pages/signals.html'),
'/trades': resolve(root, 'pages/trades.html'),
@@ -2284,6 +2287,10 @@ const appConfig = {
// route in prod, so keep it out of the HTML shell here too.
else if (!filePath && /^\/trader\/[^/.]+\/?$/.test(path))
filePath = resolve(root, 'pages/trader.html');
+ // /trade-rooms/:agentId → one leader's live trade room. Mirrors
+ // vercel.json's `/trade-rooms/([^/.]+)/?`.
+ else if (!filePath && /^\/trade-rooms\/[^/.]+\/?$/.test(path))
+ filePath = resolve(root, 'pages/trade-room.html');
// `[^/.]+` (no dot) mirrors vercel.json's `/agents/([^/.]+)` so
// static assets like /agents/boot.js fall through to public/
// instead of being served the agent-detail HTML shell.