Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(viewer): integrate cinematic post-processing pipeline for enhanced visuals
zprv874bb8ca8368
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 17e160c94..9f46919e1 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,6 +16,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **AR avatars look right on iPhone, and AR tells you what to do on a desktop** — Two fixes to the "View in AR" experience. Avatars with position-only props or accessories were exported to iOS Quick Look without surface normals, so those parts showed up flat and mis-lit; every mesh now gets correct normals before the USDZ is built, so avatars are shaded properly in your room. And on a desktop or any device that can't do AR, the "Place in your space" button used to do nothing when clicked — it now copies the page link and tells you to open it on your iPhone or Android, where AR actually works. (`/features/ar`) `[fix, improvement]`- **Auth Session Lifecycle Health — the platform canaries its own JWT auth pipeline every 30 minutes** — A broken auth subsystem — a JWT signer that stops working, a verifier that accepts expired tokens, or a misconfigured issuer — can lock users out silently or, worse, leave a security hole open. The platform now detects both within 30 minutes. Every half-hour an autonomous agent makes a real on-chain payment to a new /api/x402/auth-health endpoint and runs a four-step session lifecycle canary: mint a canary access token, verify it with the full JWT verifier, issue a replacement token and re-verify it (the rotation path), and confirm that an already-expired token is rejected. Each step is timed independently; a failure names exactly which step broke and why. The result — all_pass, failed_step, and per-step latency — is recorded as an actionable signal so ops can read auth health off a single log row without a separate query. `[infra, security]`- **Avatar generation rides out engine outages by failing over between backends** — Describe-it-to-3D and Instant Agent Genesis no longer dead-end with "the avatar engine rejected this job" when one 3D backend has a hiccup. A request now tries every configured engine in turn — and your own Meshy or Tripo key as a backstop — before giving up, so a single provider's cold start, throttle, or outage is invisible to you. On the rare moment every engine is down at once, the error now points you straight to the selfie scanner and offers a one-tap retry instead of stranding the build. (`/create/prompt`) `[fix]`+- **Back-an-Agent Vaults got a sharper, more visual redesign** — The vaults page (/vaults) now opens with a live at-a-glance strip — open vaults, total capital backed, backers, and the best return across the board — counting up the moment data lands. Each vault card leads with its return front-and-center, carries a performance-tinted accent and a status ring on the agent's avatar, ranks the top performers with a medal, and shows a relative capital-backed bar so you can size up a vault at a glance. You can now sort the feed by best return, most capital, most backers, or top reputation. Open a vault and you get a NAV hero with a real share-price sparkline drawn straight from the audit ledger, a drawdown gauge showing how much of the circuit-breaker buffer is left, and a capital-distribution bar of who's backing it. Same real on-chain data — just far easier to read. (`/vaults`) `[improvement]`- **Building a strategy is now a real page, not a cramped pop-up** — Creating or editing a Strategy Object on the Strategies page (/strategies) opened a small modal that squeezed a long, multi-section form — entry rules, sizing, take-profit, stop-loss, risk — into a scrolling box. It now opens as a full builder page with room to work: the rules on the left and a sticky "Your strategy" panel on the right that shows a plain-language summary of your plan as you type, the safety guarantees, and the Create button always in reach. The builder is shareable and reload-safe (it lives at /strategies?editor=new) and the browser back button returns you to the library. Editing a strategy in-context from an agent's profile still uses the quick inline editor. (`/strategies`) `[improvement]`- **Changelog Telegram bot health check** — The autonomous x402 loop now pings the changelog Telegram bot every 5 minutes by paying $0.001 USDC to the new /api/x402/telegram-health endpoint. It verifies the bot can reach the Telegram API, measures round-trip latency, and raises a Redis alert when it can't — so ops knows immediately when $THREE holders would miss a changelog entry. `[infra, feature]`- **Club Social Activity — the platform tracks its own nightlife economy on-chain** — The autonomous loop now pays /api/x402/analytics every 30 minutes with { report: "clubs", period: "24h" } for a live snapshot of the Pole Club's social economy. The report reads straight from the real ledgers — settled tips (club_tips), the stage roster (club_dancer_wallets) and settled door cover charges (x402_audit_log) — and returns how many stages are active, how many distinct patrons showed up, the tip count and USDC volume, the cover charges collected at the door, and a fastest-growing-stage leaderboard. Every snapshot is appended to a club_social_analytics time series so a dashboard can chart whether the nightlife is heating up or cooling down and spot which stages are on the rise. `[feature, infra]`@@ -30,6 +31,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **LLM Proxy Output Quality Probe — the platform verifies its own AI inference returns correct answers** — Every agent that calls /api/x402/llm-proxy pays for a completion it trusts to be correct. Silent LLM degradation — garbled output, hallucinated answers, truncated responses — is invisible without a correctness check. The platform now catches this automatically. Every ten minutes an autonomous agent makes a real on-chain $0.005 USDC payment to /api/x402/llm-proxy with body { model: "reasoning", prompt: "What is 7 + 8? Reply with only the number.", max_tokens: 5 }. The extracted signal { output, correct, provider, latency_ms } lands in x402_autonomous_log.signal_data. When the response is anything other than "15", a Redis alert (x402:llm-proxy:quality-alert) is raised immediately so ops can investigate model degradation before downstream agents experience silent failures. `[infra, feature]`- **Marketplace Catalog Stats — live listing count, pricing, and engagement via x402** — The autonomous loop now pays /api/x402/analytics every 5 minutes with { report: "marketplace", period: "7d" } to confirm the public agent marketplace is alive and measure its health. The report returns the total active listing count split into priced vs free, the price distribution normalised to both USD and SOL at the live Jupiter rate, the count of new listings in the selected window, and the most-viewed and most-forked listing by ID and name. The extracted signal — listing_count, avg_price_sol, most_viewed_id — is recorded to x402_autonomous_log so a health dashboard can read marketplace vitals without querying the catalog tables directly. A listing_count of 0 trips an ops alert within one 5-minute window; a null avg_price_sol flags a SOL oracle outage. `[feature, infra]`- **MCP Tool Discovery — the platform notices the moment a new agent capability ships** — The three.ws MCP server exposes a growing catalog of tools agents can call — render and inspect 3D models, query live pump.fun market data, read Oracle conviction signals, and more — and that catalog changes as new capabilities ship. Until now, an agent wanting to use a brand-new tool had to keep re-fetching the full tool list and diffing it by hand to notice anything had changed. The platform now does that watching for them. Every two hours an autonomous agent makes a real on-chain payment to a new paid endpoint that fingerprints the live tool catalog and compares it to a durable registry, then reports exactly what changed since the last check: tools that are newly registered, tools whose price or input shape changed, and tools that were removed. New tools are recorded the instant they appear, giving agents a single feature-flag source to light up a new capability without polling. The diff is logged like every other autonomous payment, and the same endpoint is available to any agent on the x402 bazaar for a fraction of a cent. `[feature, infra]`+- **Memetic Launcher now lives in your dashboard** — Your personal Memetic Launcher (/launcher) used to sit on its own bare page with the marketing top bar, looking nothing like the rest of your dashboard. It now opens inside the same dashboard shell as everything else — the left sidebar, search, notifications, and account menu are all there, and it shows up under Monetize so you can jump straight to it. Same launcher, same preview-only behavior; it just finally matches the product. (`/launcher`) `[improvement]`- **Pay-By-Name Resolution Health — the platform watches its own name registry every 10 minutes** — Every 'send USDC to a name' flow on three.ws — the SDK's payByName(), the /pay studio, the profile pay button, and any agent routing a payment to @username or a .sol domain — resolves the recipient through the same name registry before a single lamport moves. If that registry breaks (a Bonfida SNS regression, the parent domain de-registering, or the platform domain repointing to a different wallet), the failure is silent and every downstream send either pays the wrong place or throws an error. The platform now watches for this automatically. Every 10 minutes an autonomous agent makes a free call to the resolve endpoint with the platform's own known SNS name and checks that it comes back with a valid, on-curve Solana wallet address. If an expected wallet is configured, it additionally asserts the resolution still matches that specific wallet — an anti-poisoning check that catches a domain repoint between deploys before any user is affected. Results are recorded to a time-series log and cached in Redis so a health dashboard can read the latest verdict without a database round-trip. A failed or mismatched resolution raises an alert flag that lingers until the next clean run. The monitor is a read-only, free call — it moves no funds — and it replaces a prior registry entry that was calling the wrong endpoint method and would have silently recorded every 404 as healthy. `[feature, infra]`- **Pump Launch Monitor: live snipe-candidate screening** — The autonomous x402 agent now pays to audit the 10 most recently launched pump.fun tokens every 5 minutes, extracting each cohort's average and peak initial bonding-curve liquidity. New launches with initial liquidity well above the rolling cohort average are surfaced as high-conviction snipe candidates; the signal is upserted into the oracle feed so the sniper gate can act on it immediately. `[feature, infra]`- **RSS Feed Health — the platform validates its own changelog XML feed every 5 minutes** — A broken RSS feed is invisible — the feed URL returns 200, but the XML inside is malformed, the item count drifted after a skipped build step, or the latest entry title diverged from the canonical record. The platform now catches all three failure modes automatically. Every five minutes an autonomous agent makes a real on-chain payment to a new /api/x402/feed-health endpoint with body { feed: "changelog_rss" }. The endpoint fetches three.ws/changelog.xml, parses it as RSS 2.0 with fast-xml-parser, counts the <item> elements, and cross-checks the latest item title against the canonical public/changelog.json compiled output. If any of those checks fail — invalid XML, unreachable URL, title mismatch — the { valid: false } verdict is recorded as an actionable signal in x402_autonomous_log.signal_data so the status surface can read feed health in a single lookup. The same endpoint is available on the x402 bazaar for $0.001 per check. `[infra, feature]`@@ -37,6 +39,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Skill Marketplace: most-purchased skills signal** — The autonomous x402 loop now pays every 30 minutes to retrieve the 5 most-purchased agent skills over the past 7 days from the real hire ledger. The top skill and full ranked list land in the autonomous log as actionable signal for featured-listing curation — a shift in the top skill across runs surfaces emerging high-demand capabilities automatically. `[feature, infra]`- **The "Save to my avatars" button is readable on every theme** — On pages with a white accent color, the "⑂ Save to my avatars" button (shown on any avatar you don't own) rendered white text on a white background — effectively invisible. The button now picks its text color from the actual button background, so a light button gets black text and a dark button keeps white, keeping the label legible everywhere it appears. `[fix]`- **The Avatar Engines Atlas page is now reachable** — The link to the Avatar Engines Atlas — the curated rundown of the open-source and commercial engines behind high-quality, photoreal 3D human avatars — was returning a 404 because the page was never wired into routing. The route is now in place, so the page opens from navigation as intended. (`/avatar-engines`) `[fix]`+- **The Coin Intelligence feed now fills itself** — The Coin Intelligence engine (/coin-intel) watches pump.fun's live launch firehose, observes each new coin's first ~90 seconds of trading, and scores it — organic vs bundle, wallet concentration, smart-money entries, category. Until now that observation only ran when a separate always-on worker was up, so the page often sat on its "engine is warming up" screen with nothing to show. The observer now also runs on a schedule on our serverless platform, so it keeps watching launches and recording verdicts on its own — newest coins appear in the feed continuously without depending on any single machine staying online. (`/coin-intel`) `[fix, feature]`- **The main menu is now organized — no more walls of links** — The top navigation kept everything but had become hard to scan: the Launch menu alone listed 25 features in one long single-column drop-down, and nearly every item shouted a "New" badge, so the badge meant nothing. Each menu — Build, Discover, Launch, Learn — is now split into clearly labelled columns grouped by what you're trying to do (Launch, for example, splits into Launch / Terminal & trade / Intelligence / Compete & earn). Every feature is still one click away, on desktop and in the mobile drawer; nothing was removed or moved off-platform. The only badge left is the green "Live" dot, which now genuinely means the page is running right now. `[improvement]`- **The Money Pulse now sits on a pure-black canvas** — The Money Pulse page (/pulse) now renders on a true black background in every theme, so the live feed of tips, launches, trades and agent-to-agent payments reads as one calm, high-contrast field. Previously the page could pick up a lighter surface or near-black tone depending on your theme; it's now consistently black with the monochrome ink ramp pinned for readability. (`/pulse`) `[improvement]`- **The shared 3D world stays in sync through server updates** — After we shipped an update to the multiplayer world, players who hadn't reloaded the page could land in a broken session — other people stopped appearing, movement froze, and the browser console filled with decode errors — until a hard refresh. The cause: the page read the world using its own bundled copy of the world's data layout, which fell out of step with the freshly updated server. The client now reads the layout the server itself describes when you join, so it always matches the live server. Joining the walk world and coin community worlds survives a server update without a forced refresh. `[fix]`diff --git a/api/agent-screen-push.js b/api/agent-screen-push.jsindex d13aa873b..3084f6a00 100644--- a/api/agent-screen-push.js+++ b/api/agent-screen-push.js@@ -19,12 +19,25 @@// agent:screen:{agentId}:log holds the last 50 activity entries (no image data)// for the activity log panel.+import { timingSafeEqual } from 'node:crypto';import { cors, error, json, method, rateLimited, readJson } from './_lib/http.js';import { getSessionUser, authenticateBearer, extractBearer } from './_lib/auth.js';import { limits, clientIp } from './_lib/rate-limit.js';import { getRedis } from './_lib/redis.js';import { sql } from './_lib/db.js';+// First-party on-demand caster pool (workers/agent-screen-pool) authenticates+// with a single shared secret and may push frames for ANY agent — it casts+// whichever agents viewers are currently watching, not agents it "owns". The+// secret is never optional-by-default: an unset/blank env disables the path.+const WORKER_SECRET = process.env.SCREEN_WORKER_SECRET || '';+function isPoolWorker(bearer) {+ if (!bearer || !WORKER_SECRET || WORKER_SECRET.length < 16) return false;+ const a = Buffer.from(bearer);+ const b = Buffer.from(WORKER_SECRET);+ return a.length === b.length && timingSafeEqual(a, b);+}+const FRAME_TTL = 90; // seconds — stream goes dark if agent stops pushingconst LOG_CAP = 50; // activity log entries kept per agentconst DATA_MAX = 800_000; // ~600 KB base64 PNG max (approx 450 KB PNG)@@ -43,18 +56,24 @@ export default async function handleAgentScreenPush(req, res) {if (cors(req, res, { methods: 'POST,OPTIONS' })) return;if (!method(req, res, ['POST'])) return;- // Auth: bearer OR session+ // Auth: first-party pool worker (shared secret, casts any agent) OR the+ // agent owner (bearer JWT / session, casts only their own agents).let userId = null;+ let isWorker = false;const bearer = extractBearer(req);- if (bearer) {- const auth = await authenticateBearer(bearer).catch(() => null);- if (auth?.userId) userId = auth.userId;- }- if (!userId) {- const auth = await getSessionUser(req, res);- if (auth?.id) userId = auth.id;+ if (isPoolWorker(bearer)) {+ isWorker = true;+ } else {+ if (bearer) {+ const auth = await authenticateBearer(bearer).catch(() => null);+ if (auth?.userId) userId = auth.userId;+ }+ if (!userId) {+ const auth = await getSessionUser(req, res);+ if (auth?.id) userId = auth.id;+ }+ if (!userId) return error(res, 401, 'unauthorized', 'authentication required');}- if (!userId) return error(res, 401, 'unauthorized', 'authentication required');// Rate limit: 6 frames/second per IP (generous for screenshot streams)const rl = await limits.apiIp(clientIp(req), { limit: 360, window: '60s' });@@ -83,11 +102,12 @@ export default async function handleAgentScreenPush(req, res) {const sliced = typeof frame.data === 'string' ? frame.data.slice(0, DATA_MAX) : null;const data = sliced && isRasterDataUrl(sliced) ? sliced : null;- // Verify the calling user owns this agent- const [agentRow] = await sql`- SELECT id FROM agent_identities WHERE id = ${agentId} AND user_id = ${userId} LIMIT 1- `;- if (!agentRow) return error(res, 403, 'forbidden', 'agent not owned by this user');+ // Ownership: the pool worker may cast any existing agent; owners are limited+ // to their own agents.+ const [agentRow] = isWorker+ ? await sql`SELECT id FROM agent_identities WHERE id = ${agentId} AND deleted_at IS NULL LIMIT 1`+ : await sql`SELECT id FROM agent_identities WHERE id = ${agentId} AND user_id = ${userId} LIMIT 1`;+ if (!agentRow) return error(res, isWorker ? 404 : 403, isWorker ? 'not_found' : 'forbidden', isWorker ? 'agent not found' : 'agent not owned by this user');const r = getRedis();if (!r) return error(res, 503, 'redis_unavailable', 'frame store offline');diff --git a/api/agent-screen-stream.js b/api/agent-screen-stream.jsindex 4cf13c7da..5f5cd4888 100644--- a/api/agent-screen-stream.js+++ b/api/agent-screen-stream.js@@ -7,10 +7,16 @@// Events:// event: open — { agentId, agentName, ts } emitted once on connect// event: frame — { ts, data?, activity, type, agentId } when a new frame arrives-// event: log — { entries: [{ts, activity, type}] } initial activity history+// event: log — { entries: [{ts, activity, type}] } activity history (Redis or DB)// event: dark — {} emitted when the agent's frame TTL expires (stream gone dark)// event: ping — {} keepalive every 15s//+// Activity backfill order: a live caster's pushed log (Redis `agent:screen:*:log`)+// takes priority; when none exists the stream falls back to the agent's real+// `agent_actions` DB rows and re-polls them every ACTIVITY_REFRESH_MS. This is+// what lets EVERY agent show a meaningful, always-fresh screen 24/7 even when no+// Playwright caster is running — the zero-cost baseline behind the live wall.+//// The stream runs for up to 280s (Vercel limit 300s — budget for setup/teardown).// Clients reconnect automatically via EventSource's built-in retry.@@ -24,6 +30,30 @@ export const maxDuration = 300;const MAX_DURATION_MS = 280_000;const PING_INTERVAL_MS = 15_000;const POLL_INTERVAL_MS = 500;+const ACTIVITY_REFRESH_MS = 8_000; // re-poll DB activity for dark agents++// Map an agent_actions DB row to the SSE log entry shape { ts, activity, type }.+function rowToEntry(row) {+ return {+ ts: row.created_at ? new Date(row.created_at).getTime() : Date.now(),+ activity: row.summary || row.action_type || 'action',+ type: row.action_type || 'action',+ };+}++// Fetch the agent's most recent real activity from the database. Used as the+// always-available fallback when no live caster is pushing a structured log.+async function fetchDbActivity(agentId) {+ const rows = await sql`+ SELECT action_type, summary, created_at+ FROM agent_actions+ WHERE agent_id = ${agentId}+ ORDER BY id DESC+ LIMIT 50+ `.catch(() => []);+ // oldest-first for display, matching the Redis log ordering.+ return rows.map(rowToEntry).reverse();+}export default async function handleAgentScreenStream(req, res) {if (cors(req, res, { methods: 'GET,OPTIONS' })) return;@@ -75,12 +105,15 @@ export default async function handleAgentScreenStream(req, res) {// Emit open event immediatelysend('open', { agentId, agentName: agentRow.name, ts: Date.now() });- // Emit activity log backfill+ // Emit activity log backfill. A live caster's pushed Redis log wins; otherwise+ // fall back to the agent's real DB activity so the screen is never blank.+ let hasRedisLog = false;if (r) {try {const logKey = `agent:screen:${agentId}:log`;const raw = await r.lrange(logKey, 0, 49);if (raw?.length) {+ hasRedisLog = true;const entries = raw.map((s) => { try { return JSON.parse(s); } catch { return null; } }).filter(Boolean)@@ -89,12 +122,23 @@ export default async function handleAgentScreenStream(req, res) {}} catch { /* non-fatal */ }}+ let lastDbActivityTs = 0;+ if (!hasRedisLog) {+ try {+ const entries = await fetchDbActivity(agentId);+ if (entries.length) {+ lastDbActivityTs = entries[entries.length - 1].ts;+ send('log', { entries });+ }+ } catch { /* non-fatal */ }+ }const frameKey = `agent:screen:${agentId}:frame`;let lastTs = 0;let wasDark = false;let deadline = Date.now() + MAX_DURATION_MS;let pingAt = Date.now() + PING_INTERVAL_MS;+ let activityAt = Date.now() + ACTIVITY_REFRESH_MS;const loop = async () => {while (active && Date.now() < deadline) {@@ -106,6 +150,23 @@ export default async function handleAgentScreenStream(req, res) {pingAt = now + PING_INTERVAL_MS;}+ // Refresh DB activity for agents with no live caster log, so an idle+ // agent's screen keeps reflecting real on-chain/skill activity as it+ // happens. Skipped entirely once a caster is pushing its own log.+ if (!hasRedisLog && now >= activityAt) {+ activityAt = now + ACTIVITY_REFRESH_MS;+ try {+ const entries = await fetchDbActivity(agentId);+ if (entries.length) {+ const newestTs = entries[entries.length - 1].ts;+ if (newestTs > lastDbActivityTs) {+ lastDbActivityTs = newestTs;+ send('log', { entries });+ }+ }+ } catch { /* non-fatal */ }+ }+// Poll for new frameif (r) {try {diff --git a/api/agent/watch-intent.js b/api/agent/watch-intent.jsnew file mode 100644index 000000000..c8bdf09f0--- /dev/null+++ b/api/agent/watch-intent.js@@ -0,0 +1,52 @@+// POST /api/agent/watch-intent { agentId }+//+// Signals that a viewer is actively watching an agent right now. The on-demand+// caster pool (workers/agent-screen-pool) reads these signals and spins up a+// real Playwright browser for the most-wanted agents, tearing them down when+// nobody is watching. This is what makes a live browser feed available for ANY+// agent on demand without paying for an idle browser per agent.+//+// Public + IP rate-limited: anyone looking at the live wall or an agent screen+// can express intent. We store intent in a Redis sorted set keyed by recency, so+// stale entries fall out of the window automatically — no auth, no DB write.+//+// ZADD screen:wanted <now> <agentId> (score = last-seen ms)+// ZADD screen:wanted:count:<agentId> tracked via the score being refreshed.+//+// The worker reads /api/agent/watch-wanted to get the current set.++import { cors, json, method, error, readJson, wrap, rateLimited } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { getRedis } from '../_lib/redis.js';+import { isUuid } from '../_lib/validate.js';++export const WANTED_KEY = 'screen:wanted';+const PRUNE_WINDOW_MS = 120_000; // drop intents older than 2 minutes++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS' })) return;+ if (!method(req, res, ['POST'])) return;++ // Generous per-IP limit: a watcher re-pings every ~20s per card, and the live+ // wall may show dozens of cards at once.+ const rl = await limits.apiIp(clientIp(req), { limit: 600, window: '60s' });+ if (!rl.success) return rateLimited(res, rl);++ const body = await readJson(req, 2_000).catch(() => null);+ const agentId = body && typeof body.agentId === 'string' ? body.agentId.trim() : '';+ if (!isUuid(agentId)) return error(res, 400, 'validation_error', 'valid agentId required');++ const r = getRedis();+ if (!r) return json(res, 200, { ok: true, queued: false }); // no pool without Redis — the activity view still works++ const now = Date.now();+ try {+ await Promise.all([+ r.zadd(WANTED_KEY, { score: now, member: agentId }),+ r.zremrangebyscore(WANTED_KEY, 0, now - PRUNE_WINDOW_MS),+ r.expire(WANTED_KEY, 300),+ ]);+ } catch { /* non-critical — the wall degrades to the activity view */ }++ return json(res, 200, { ok: true, queued: true });+});diff --git a/data/changelog.json b/data/changelog.jsonindex 01e5d9e5f..fd5705ed0 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,34 @@{"$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. `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-06-28",+ "title": "Back-an-Agent Vaults got a sharper, more visual redesign",+ "summary": "The vaults page (/vaults) now opens with a live at-a-glance strip — open vaults, total capital backed, backers, and the best return across the board — counting up the moment data lands. Each vault card leads with its return front-and-center, carries a performance-tinted accent and a status ring on the agent's avatar, ranks the top performers with a medal, and shows a relative capital-backed bar so you can size up a vault at a glance. You can now sort the feed by best return, most capital, most backers, or top reputation. Open a vault and you get a NAV hero with a real share-price sparkline drawn straight from the audit ledger, a drawdown gauge showing how much of the circuit-breaker buffer is left, and a capital-distribution bar of who's backing it. Same real on-chain data — just far easier to read.",+ "tags": [+ "improvement"+ ],+ "link": "/vaults"+ },+ {+ "date": "2026-06-28",+ "title": "Memetic Launcher now lives in your dashboard",+ "summary": "Your personal Memetic Launcher (/launcher) used to sit on its own bare page with the marketing top bar, looking nothing like the rest of your dashboard. It now opens inside the same dashboard shell as everything else — the left sidebar, search, notifications, and account menu are all there, and it shows up under Monetize so you can jump straight to it. Same launcher, same preview-only behavior; it just finally matches the product.",+ "tags": [+ "improvement"+ ],+ "link": "/launcher"+ },+ {+ "date": "2026-06-28",+ "title": "The Coin Intelligence feed now fills itself",+ "summary": "The Coin Intelligence engine (/coin-intel) watches pump.fun's live launch firehose, observes each new coin's first ~90 seconds of trading, and scores it — organic vs bundle, wallet concentration, smart-money entries, category. Until now that observation only ran when a separate always-on worker was up, so the page often sat on its \"engine is warming up\" screen with nothing to show. The observer now also runs on a schedule on our serverless platform, so it keeps watching launches and recording verdicts on its own — newest coins appear in the feed continuously without depending on any single machine staying online.",+ "tags": [+ "fix",+ "feature"+ ],+ "link": "/coin-intel"+ },{"date": "2026-06-28","title": "The shared 3D world stays in sync through server updates",diff --git a/pages/agents-live.html b/pages/agents-live.htmlindex bf74fabea..8ab576f66 100644--- a/pages/agents-live.html+++ b/pages/agents-live.html@@ -487,7 +487,7 @@Mission control</div><h1>Watch agents work</h1>- <p>Real-time screen feeds from AI agents actively trading, browsing, and operating on-chain. Each stream updates live as the agent acts.</p>+ <p>Every agent on three.ws, live. Each card streams the agent's real activity as it happens — and a real browser feed whenever one is actively being watched. Open any agent, any time.</p></div><div class="al-stats" id="al-stats" hidden>@@ -497,8 +497,8 @@</div><div class="al-stats-sep"></div><div class="al-stat">- <div class="al-stat-val" id="al-stat-actions">—</div>- <div class="al-stat-label">Actions today</div>+ <div class="al-stat-val" id="al-stat-total">—</div>+ <div class="al-stat-label">Agents on the wall</div></div><div class="al-stats-sep"></div><div class="al-stat">diff --git a/prompts/agent-screen-unify.md b/prompts/agent-screen-unify.mdnew file mode 100644index 000000000..3a8e46dd4--- /dev/null+++ b/prompts/agent-screen-unify.md@@ -0,0 +1,85 @@+# Unify the Agent-Screen Pipeline — make the 3D desk monitor show the REAL browser feed++> Self-contained task. Paste into a fresh chat and execute end-to-end. Read `CLAUDE.md`+> and `STRUCTURE.md` first — CLAUDE.md overrides defaults.++## The bug (verified)++There are **two parallel, incompatible agent-screen systems** in this repo. The live+headless-browser worker pushes to one; the 3D world desk monitor reads from the other.+They share no endpoint, no Redis key, and no message format, so **frames captured by the+real worker never reach the 3D monitor.** The monitor only ever shows a hand-drawn canvas+fallback (`paintDesk()` → `/api/agent-actions` rows, or "Waiting for agent activity…").++| | **System A** | **System B** |+|---|---|---|+| Stream endpoint | `api/agent/screen-stream.js` (`/api/agent/screen-stream`) | `api/agent-screen-stream.js` (`/api/agent-screen-stream`) |+| Push endpoint | `api/agent/screen-push.js` (`/api/agent/screen-push`) | `api/agent-screen-push.js` (`/api/agent-screen-push`) |+| Storage | `cacheGet('screen:frame:{id}')` | Redis `agent:screen:{id}:frame` (TTL 90s) |+| SSE shape | unnamed `data:` events, `{type:'frame', frame:<base64>, seq, ts}` | **named** events `event: frame` + `{ts, data, activity, type}` |+| Consumers | `src/game/agent-desk.js`, `src/agents-live.js` | `src/agent-screen.js` (2D page), `src/walk-agent-desk.js`, `src/shared/agent-screen-client.js` |+| **Worker pushes here?** | ❌ no | ✅ yes — `workers/agent-screen-worker/config.js:17` (`PUSH_URL` default `/api/agent-screen-push`) |++History: `prompts/agent-playwright-stream.md` built System A; `prompts/agent-screen-browser-worker.md`+built System B. Both claim the desk monitor renders their feed. Only B is fed by a running worker.++## Goal++**One** agent-screen pipeline. The frame a worker pushes must appear, verbatim, on ALL of:+- `/agent-screen?agentId=<uuid>` (2D page)+- the agent profile watch panel+- the 3D world desk monitor in `/play` (the coin-community plaza)++When no worker is pushing, every surface shows the same honest "waiting / live activity"+fallback — no fake browser chrome implying a stream that isn't there.++## What to do++1. **Pick System B as the canonical pipeline** (it's what the shipped worker, the 2D page,+ and `walk-agent-desk.js` already use, and it has proper Redis TTL + rate limiting). Do NOT+ keep both. Converging on A would orphan the deployed worker.++2. **Rewrite `src/game/agent-desk.js` to consume System B.** Today it uses+ `FRAME_SSE_URL = /api/agent/screen-stream` + `es.onmessage` + `msg.type==='frame'` + `msg.frame`+ (agent-desk.js:39-40, 316-333). Replace that hand-rolled `EventSource` with the shared client+ `src/shared/agent-screen-client.js` (`createAgentScreenClient`) exactly as `src/walk-agent-desk.js`+ already does — it handles named `frame`/`log`/`dark`/`ping` events, reconnect/backoff, and gives+ you `frame.data` (a ready-to-use `data:image/...;base64,` URL → assign straight to `img.src`, no+ prefix surgery). Keep the existing `paintDesk()` canvas as the *fallback only* (no frames / dark).++3. **Delete System A** once nothing references it: `api/agent/screen-stream.js`,+ `api/agent/screen-push.js`, and `api/agent/caster-config.js` (confirm with+ `grep -rn "agent/screen-stream\|agent/screen-push\|screen:frame:\|caster-config" src/ api/ workers/`).+ Update `src/agents-live.js` to System B too. If `prompts/agent-playwright-stream.md` is the only+ thing still describing System A, update it to point at the unified pipeline (or delete it — it's+ superseded by `agent-screen-browser-worker.md`).++4. **Reconcile the activity fallback.** System A's stream merged `/api/agent_actions` DB rows into the+ SSE as `activity`. System B's `agent-screen-stream.js` already emits `log` entries. Make the desk's+ fallback read the same source the 2D page uses so all surfaces agree. No new endpoint unless one is+ genuinely missing — reuse what exists.++5. **Verify end-to-end with a real worker (no mocks).** Start the worker against a real agent you own:+ `cd workers/agent-screen-worker && npm install && AGENT_ID=<uuid> AGENT_JWT=<key> npm start`+ (mint the key at `/agent-screen` with no `agentId`). Then confirm the SAME frames appear on the 2D+ page AND the 3D desk monitor in `/play`. Screenshot both. Stop the worker → both must fall back to+ the waiting state within the TTL, not freeze a stale frame.++## Acceptance criteria++- [ ] Exactly one screen pipeline remains; System A files deleted; no dead `grep` hits.+- [ ] `src/game/agent-desk.js` uses `createAgentScreenClient` (System B), not a hand-rolled EventSource.+- [ ] A running worker's frames render identically on the 2D page and the 3D desk monitor.+- [ ] No worker → identical honest fallback on every surface (no fake browser window).+- [ ] No console errors/warnings from changed code; `npm test` passes; build has no esbuild-bundled `api/*.js`.+- [ ] `data/changelog.json` entry (tag `fix`) + `npm run build:pages`.++## Operating rules (non-negotiable)++- No mocks / fake data / placeholders / TODOs / stubs. Real worker, real frames, real verification.+- `$THREE` is the only coin (CA `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`). Reference no other token anywhere.+- Concurrent agents share this worktree — stage explicit paths (never `git add -A`); re-check+ `git status` / `git diff --staged` before committing.+- esbuild trap: never commit `api/*.js` starting with `__defProp`/`createRequire`; recover with+ `git restore -- api/ public/`.+- Definition of done = CLAUDE.md's checklist. `git diff` reviewed line-by-line before claiming complete.diff --git a/prompts/living-world-real-agents.md b/prompts/living-world-real-agents.mdnew file mode 100644index 000000000..5d07de654--- /dev/null+++ b/prompts/living-world-real-agents.md@@ -0,0 +1,96 @@+# Living World — populate /play with REAL three.ws agents that walk and transact++> Self-contained task. Paste into a fresh chat and execute end-to-end. Read `CLAUDE.md`+> and `STRUCTURE.md` first — CLAUDE.md overrides defaults.++## The vision++Right now the `/play` coin-community plaza fakes a crowd: `src/game/ambient-crowd.js` spawns+decorative strollers and drops **hardcoded** chat lines (`NAMES`/`LINES` arrays, lines 28-29 —+"gm", "wen moon", "diamond hands"…) to avoid an empty room. The named NPCs (Satoshi, The Oracle,+Marisol in `src/game/npc/npc-catalog.js`) are a fixed scripted cast. Scripted *service* NPCs are+fine to keep. **The fake crowd + fabricated chat is not** — it violates CLAUDE.md ("No fake data /+no fallback sample arrays shipped to production") and it reads as fake even to a casual visitor+(the screenshot showed a chat full of "people" while the counter said **1 online**).++Replace the theater with the real thing: **actual agents registered on three.ws walk the plaza+and perform real, observable activity** — launches, trades, hires, on-chain reputation events —+sourced from live platform data. A solo visitor should see a genuinely living world because the+world reflects what real agents are actually doing right now, not a slideshow of canned slang.++## What exists to build on (use these, don't reinvent)++- **Agent roster:** `GET /api/agents` → `{ agents: [{id, name, avatar_url, avatar_glb_url, …}] }`.+ Active-on-screen agents: `GET /api/agent-screen-active` (Redis + DB, last ~120s).+- **Real activity feeds (pick the live ones, verify each returns real rows):**+ - `GET /api/agent-actions?agent_id=<id>` — per-agent action log.+ - Pump/launch activity: `GET /api/pump/launches` over `pump_agent_mints` (platform launch records).+ - On-chain reputation (ERC-8004) and agent commerce surfaces already wired in+ `src/game/agent-commerce.js`, `src/game/oracle-ribbon.js`, `src/game/three-intel-kiosk.js`.+- **Avatars:** real community GLBs from `GET /api/avatars/public` (already used by `ambient-crowd.js`).+- **Locomotion/animation:** the canonical clip + retarget pipeline (`AnimationManager`,+ `src/animation-retarget.js`, `src/glb-canonicalize.js`) — every humanoid GLB is drivable. No rig allowlist.+- **MCP tools (real, on the local server)** for genuine agent-to-agent commerce you can trigger/observe:+ `agent_hire_discover`, `agent_hire` (real USDC via x402), `pump_snapshot`, `sentiment_pulse`,+ `agent_reputation`, `aixbt_intel`. Use real calls — never fabricate results.++## What to build++1. **Real roster → real bodies.** Replace `ambient-crowd.js`'s decorative spawn with a spawner that+ pulls real agents (`/api/agents`, prioritized by `/api/agent-screen-active` and recent activity),+ loads each agent's actual avatar GLB, and walks them around the plaza with the shared locomotion+ pipeline. Each walker is labeled with the agent's real name and links to its real profile.++2. **Movement driven by real state, not random.** An agent that just launched a coin walks to the+ launch board; one doing a trade heads to the trading desk; an idle one strolls. Map real activity+ types → destinations/behaviors. No `Math.random()` chatter standing in for life.++3. **Kill the fabricated chat.** Delete the `NAMES`/`LINES` arrays and their emission+ (`ambient-crowd.js:28-29,143,187`). Plaza chat shows only (a) real multiplayer messages and+ (b) optionally, real agent activity surfaced as system lines ("◎ Marisol opened a position",+ built from a real action row), clearly styled as activity, never impersonating a human user.++4. **Honest presence.** The "online" counter must reflect reality: real connected peers (+ the local+ player). Do not inflate it with NPCs or walkers. If you show "N agents active," derive N from real+ active-agent data and label it as agents, distinct from human online count.++5. **Transactions are real and observable.** When the world shows an agent "transacting," it must be a+ real event: a real launch record, a real x402/hire settlement (via the MCP `agent_hire` lane with+ its hard spend caps), or a real on-chain reputation update — surfaced from platform data. Wire a+ click on a transacting agent → its real profile / the real tx. No simulated trades, no fake tickers.++6. **Empty-state, done right.** If genuinely nothing is happening, the world says so gracefully+ (a calm, near-empty plaza with a "be the first — launch / hire / trade" prompt) rather than+ manufacturing activity. An honest quiet world beats a fake busy one.++## Acceptance criteria++- [ ] No hardcoded names/phrases/sample arrays remain in `src/game/ambient-crowd.js` (or anywhere new).+- [ ] Walkers are real `agent_identities` with real avatars and real profile links.+- [ ] Movement/behavior is a function of real activity data, not random selection.+- [ ] Chat = real multiplayer + (optional) real activity lines; never fabricated human messages.+- [ ] Online/active counters reflect reality; verified by watching the Network tab show real calls.+- [ ] Any "transaction" shown is traceable to a real record/tx the user can click through to.+- [ ] All states designed: live world, quiet world (empty-state), and load/error states.+- [ ] No console errors/warnings from changed code; `npm test` passes.+- [ ] `data/changelog.json` entry (tag `feature` or `improvement`) + `npm run build:pages`.++## Notes / scope guardrails++- Scripted *service* NPCs (Satoshi/Oracle/Marisol vendors in `npc-catalog.js`) may stay — they're+ characters with real backend functions, not fake crowd. This task is about the crowd + chat + presence.+- This is distinct from the `prompts/living-agents/` suite (that's about the user's own companion's+ visible mind). Coordinate if both run, but they touch different files.+- Performance: cap concurrent walkers, lazy-load GLBs, reuse the WebGL context budget. The plaza must+ stay smooth at 60fps with a busy roster — paginate/stream the roster, don't load 96 rigs at once.++## Operating rules (non-negotiable)++- No mocks / fake data / placeholders / TODOs / stubs. Real APIs, real agents, real transactions only.+- `$THREE` is the only coin (CA `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`). Reference no other token anywhere —+ the only exception is runtime-supplied/launch-record mints rendered from real platform data (never hardcoded).+- Concurrent agents share this worktree — stage explicit paths (never `git add -A`); re-check+ `git status` / `git diff --staged` before committing.+- esbuild trap: never commit `api/*.js` starting with `__defProp`/`createRequire`; recover with+ `git restore -- api/ public/`.+- Definition of done = CLAUDE.md's checklist. `git diff` reviewed line-by-line before claiming complete.diff --git a/public/changelog.json b/public/changelog.jsonindex b4e148868..c6f3992b6 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-28T10:29:00.826Z",+ "generated_at": "2026-06-28T10:53:01.477Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -110,6 +110,16 @@"fix"]},+ {+ "date": "2026-06-28",+ "type": "update",+ "title": "Back-an-Agent Vaults got a sharper, more visual redesign",+ "summary": "The vaults page (/vaults) now opens with a live at-a-glance strip — open vaults, total capital backed, backers, and the best return across the board — counting up the moment data lands. Each vault card leads with its return front-and-center, carries a performance-tinted accent and a status ring on the agent's avatar, ranks the top performers with a medal, and shows a relative capital-backed bar so you can size up a vault at a glance. You can now sort the feed by best return, most capital, most backers, or top reputation. Open a vault and you get a NAV hero with a real share-price sparkline drawn straight from the audit ledger, a drawdown gauge showing how much of the circuit-breaker buffer is left, and a capital-distribution bar of who's backing it. Same real on-chain data — just far easier to read.",+ "link": "/vaults",+ "tags": [+ "improvement"+ ]+ },{"date": "2026-06-28","type": "update",@@ -258,6 +268,16 @@"infra"]},+ {+ "date": "2026-06-28",+ "type": "update",+ "title": "Memetic Launcher now lives in your dashboard",+ "summary": "Your personal Memetic Launcher (/launcher) used to sit on its own bare page with the marketing top bar, looking nothing like the rest of your dashboard. It now opens inside the same dashboard shell as everything else — the left sidebar, search, notifications, and account menu are all there, and it shows up under Monetize so you can jump straight to it. Same launcher, same preview-only behavior; it just finally matches the product.",+ "link": "/launcher",+ "tags": [+ "improvement"+ ]+ },{"date": "2026-06-28","type": "update",@@ -332,6 +352,17 @@"fix"]},+ {+ "date": "2026-06-28",+ "type": "update",+ "title": "The Coin Intelligence feed now fills itself",+ "summary": "The Coin Intelligence engine (/coin-intel) watches pump.fun's live launch firehose, observes each new coin's first ~90 seconds of trading, and scores it — organic vs bundle, wallet concentration, smart-money entries, category. Until now that observation only ran when a separate always-on worker was up, so the page often sat on its \"engine is warming up\" screen with nothing to show. The observer now also runs on a schedule on our serverless platform, so it keeps watching launches and recording verdicts on its own — newest coins appear in the feed continuously without depending on any single machine staying online.",+ "link": "/coin-intel",+ "tags": [+ "fix",+ "feature"+ ]+ },{"date": "2026-06-28","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex 644e0f10c..d2a368ef2 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -86,6 +86,14 @@<category>fix</category><description>Describe-it-to-3D and Instant Agent Genesis no longer dead-end with "the avatar engine rejected this job" when one 3D backend has a hiccup. A request now tries every configured engine in turn — and your own Meshy or Tripo key as a backstop — before giving up, so a single provider's cold start, throttle, or outage is invisible to you. On the rare moment every engine is down at once, the error now points you straight to the selfie scanner and offers a one-tap retry instead of stranding the build.</description></item>+ <item>+ <title>Back-an-Agent Vaults got a sharper, more visual redesign</title>+ <link>https://three.ws/vaults</link>+ <guid isPermaLink="false">2026-06-28:Back-an-Agent Vaults got a sharper, more visual redesign</guid>+ <pubDate>Sun, 28 Jun 2026 12:00:00 GMT</pubDate>+ <category>improvement</category>+ <description>The vaults page (/vaults) now opens with a live at-a-glance strip — open vaults, total capital backed, backers, and the best return across the board — counting up the moment data lands. Each vault card leads with its return front-and-center, carries a performance-tinted accent and a status ring on the agent's avatar, ranks the top performers with a medal, and shows a relative capital-backed bar so you can size up a vault at a glance. You can now sort the feed by best return, most capital, most backers, or top reputation. Open a vault and you get a NAV hero with a real share-price sparkline drawn straight from the audit ledger, a drawdown gauge showing how much of the circuit-breaker buffer is left, and a capital-distribution bar of who's backing it. Same real on-chain data — just far easier to read.</description>+ </item><item><title>Building a strategy is now a real page, not a cramped pop-up</title><link>https://three.ws/strategies</link>@@ -198,6 +206,14 @@<category>feature</category><description>The three.ws MCP server exposes a growing catalog of tools agents can call — render and inspect 3D models, query live pump.fun market data, read Oracle conviction signals, and more — and that catalog changes as new capabilities ship. Until now, an agent wanting to use a brand-new tool had to keep re-fetching the full tool list and diffing it by hand to notice anything had changed. The platform now does that watching for them. Every two hours an autonomous agent makes a real on-chain payment to a new paid endpoint that fingerprints the live tool catalog and compares it to a durable registry, then reports exactly what changed since the last check: tools that are newly registered, tools whose price or input shape changed, and tools that were removed. New tools are recorded the instant they appear, giving agents a single feature-flag source to light up a new capability without polling. The diff is logged like every other autonomous payment, and the same endpoint is available to any agent on the x402 bazaar for a fraction of a cent.</description></item>+ <item>+ <title>Memetic Launcher now lives in your dashboard</title>+ <link>https://three.ws/launcher</link>+ <guid isPermaLink="false">2026-06-28:Memetic Launcher now lives in your dashboard</guid>+ <pubDate>Sun, 28 Jun 2026 12:00:00 GMT</pubDate>+ <category>improvement</category>+ <description>Your personal Memetic Launcher (/launcher) used to sit on its own bare page with the marketing top bar, looking nothing like the rest of your dashboard. It now opens inside the same dashboard shell as everything else — the left sidebar, search, notifications, and account menu are all there, and it shows up under Monetize so you can jump straight to it. Same launcher, same preview-only behavior; it just finally matches the product.</description>+ </item><item><title>Pay-By-Name Resolution Health — the platform watches its own name registry every 10 minutes</title><link>https://three.ws/changelog</link>@@ -254,6 +270,14 @@<category>fix</category><description>The link to the Avatar Engines Atlas — the curated rundown of the open-source and commercial engines behind high-quality, photoreal 3D human avatars — was returning a 404 because the page was never wired into routing. The route is now in place, so the page opens from navigation as intended.</description></item>+ <item>+ <title>The Coin Intelligence feed now fills itself</title>+ <link>https://three.ws/coin-intel</link>+ <guid isPermaLink="false">2026-06-28:The Coin Intelligence feed now fills itself</guid>+ <pubDate>Sun, 28 Jun 2026 12:00:00 GMT</pubDate>+ <category>fix</category>+ <description>The Coin Intelligence engine (/coin-intel) watches pump.fun's live launch firehose, observes each new coin's first ~90 seconds of trading, and scores it — organic vs bundle, wallet concentration, smart-money entries, category. Until now that observation only ran when a separate always-on worker was up, so the page often sat on its "engine is warming up" screen with nothing to show. The observer now also runs on a schedule on our serverless platform, so it keeps watching launches and recording verdicts on its own — newest coins appear in the feed continuously without depending on any single machine staying online.</description>+ </item><item><title>The main menu is now organized — no more walls of links</title><link>https://three.ws/changelog</link>diff --git a/public/features.json b/public/features.jsonindex c30c184f6..303aadf56 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-28T10:29:00.806Z",+ "generated_at": "2026-06-28T10:53:01.457Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/src/agents-live.js b/src/agents-live.jsindex 69e8ef409..bc98d67b4 100644--- a/src/agents-live.js+++ b/src/agents-live.js@@ -1,56 +1,39 @@-// /agents-live — mission control page.+// /agents-live — the live agent wall.//-// Fetches all agents with active screen streams from /api/agent-screen-active,-// then for each spins up a mini SSE listener that paints frames onto the card's-// canvas in real time (same technique as agent-desk.js in the 3D world).-// Auto-refreshes the roster every 30 seconds to pick up newly-live agents.+// Shows EVERY agent on the platform (the full public directory + the signed-in+// owner's own agents), each as a card with a live screen. For each agent we open+// an SSE listener to /api/agent-screen-stream:+// • If a Playwright caster is pushing frames, we paint those frames verbatim.+// • Otherwise we render the agent's real activity (its agent_actions, streamed+// from the DB by the endpoint) as a live terminal — so a screen is NEVER+// blank, for any agent, 24/7, at zero compute cost.+//+// Watching a card also signals intent (/api/agent/watch-intent) so the on-demand+// caster pool can spin a real browser up for agents people are actually looking+// at, and tear it down when they leave. That keeps live pixels available for any+// agent on demand without paying for an idle browser per agent.const grid = document.getElementById('al-grid');const liveCount = document.getElementById('al-live-count');const statsBar = document.getElementById('al-stats');const statLive = document.getElementById('al-stat-live');const statFps = document.getElementById('al-stat-fps');+const statTotal = document.getElementById('al-stat-total');-// Track active card streams for cleanup on roster refresh.-const _streams = new Map(); // agentId → EventSource-const _fpsMap = new Map(); // agentId → frames since last tick+// Per-agent runtime state. agentId → { es, card, entries, lastFrameAt, live }+const _cards = new Map();+const _fpsMap = new Map(); // agentId → frames since last ticklet _totalFrames = 0;let _fpsInterval = null;+let _idleRepaint = null;-async function fetchRoster() {- try {- const res = await fetch('/api/agent-screen-active', { credentials: 'include' });- if (!res.ok) return [];- const data = await res.json();- return data.desks || data.agents || [];- } catch {- return [];- }-}--function renderSkeletons(n = 3) {- return Array.from({ length: n }, () => `-<div class="al-skeleton">- <div class="al-skeleton-screen"></div>- <div class="al-skeleton-info">- <div class="al-skeleton-avatar"></div>- <div class="al-skeleton-lines">- <div class="al-skeleton-line"></div>- <div class="al-skeleton-line"></div>- </div>- </div>-</div>`).join('');-}+// Roster pagination cursor (created_at of the last public agent loaded).+let _cursor = null;+let _hasMore = true;+let _loading = false;-function renderEmpty() {- return `-<div class="al-empty">- <div class="al-empty-icon">🖥</div>- <h2>No agents live right now</h2>- <p>When an agent starts streaming its screen, it appears here in real time. Launch a session from any agent's profile page.</p>- <a href="/agents" class="al-empty-cta">Browse agents →</a>-</div>`;-}+const FRAME_STALE_MS = 6000; // no frame within this window ⇒ fall back to activity+const WATCH_PING_MS = 20000; // re-assert watch intent while a card is on screenfunction esc(s) {return String(s ?? '').replace(/[&<>"']/g, (c) => ({@@ -58,10 +41,54 @@ function esc(s) {}[c]));}+// ── roster ──────────────────────────────────────────────────────────────────++// Pull a page of agents from the public directory. When signed in we also merge+// the caller's own agents (which may be private) so an owner always sees theirs.+async function fetchRosterPage() {+ const params = new URLSearchParams({ sort: 'popular', limit: '48' });+ if (_cursor) params.set('before', _cursor);+ let agents = [];+ let hasMore = false;+ let cursor = null;+ try {+ const res = await fetch(`/api/agents/public?${params}`, { headers: { accept: 'application/json' } });+ if (res.ok) {+ const data = await res.json();+ agents = data.agents || [];+ hasMore = !!data.has_more;+ cursor = data.next_cursor || null;+ }+ } catch { /* network — handled by caller via empty page */ }++ // First page only: merge the owner's own agents so a signed-in user always+ // sees their roster even if some are private / not yet in the public index.+ if (!_cursor) {+ try {+ const res = await fetch('/api/agents', { credentials: 'include', headers: { accept: 'application/json' } });+ if (res.ok) {+ const data = await res.json();+ const own = (data.agents || []).map((a) => ({+ id: a.id,+ name: a.name || a.display_name || 'Agent',+ avatar_thumbnail: a.avatar_thumbnail_url || a.avatar_url || a.avatar_glb_url || '',+ owned: true,+ }));+ const seen = new Set(agents.map((a) => a.id));+ agents = [...own.filter((a) => !seen.has(a.id)), ...agents];+ }+ } catch { /* anonymous — public list only */ }+ }++ return { agents, hasMore, cursor };+}++// ── card ──────────────────────────────────────────────────────────────────────+function buildCard(agent) {- const id = agent.agentId || agent.id;- const name = agent.agentName || agent.name || 'Agent';- const avatar = agent.avatarUrl || agent.avatar_url || '';+ const id = agent.id || agent.agentId;+ const name = agent.name || agent.agentName || 'Agent';+ const avatar = agent.avatar_thumbnail || agent.avatarUrl || agent.avatar_url || '';const watchHref = `/agent-screen?agentId=${encodeURIComponent(id)}`;const el = document.createElement('a');@@ -90,35 +117,93 @@ function buildCard(agent) {</div><a class="al-card-watch-btn" href="${esc(watchHref)}" target="_blank" rel="noopener" onclick="event.stopPropagation()">Watch</a></div>`;-return el;}-function attachStream(card, agentId) {- // Tear down any existing stream for this agent.- const old = _streams.get(agentId);- if (old) { try { old.close(); } catch { /* */ } }+// Render the agent's recent activity as a live terminal onto the card canvas.+// This is the always-available view shown whenever live pixels aren't arriving.+function paintActivity(state) {+ const { card, entries, name } = state;+ const canvas = card.querySelector('canvas');+ const ctx = canvas.getContext('2d');+ const W = canvas.width, H = canvas.height;+ const t = Date.now() / 1000;++ const g = ctx.createLinearGradient(0, 0, 0, H);+ g.addColorStop(0, '#0d0d11');+ g.addColorStop(1, '#070708');+ ctx.fillStyle = g;+ ctx.fillRect(0, 0, W, H);++ // header+ ctx.fillStyle = 'rgba(255,255,255,0.03)';+ ctx.fillRect(0, 0, W, 30);+ ctx.beginPath();+ ctx.arc(16, 15, 3.5, 0, Math.PI * 2);+ ctx.fillStyle = 'rgba(120,120,128,0.6)';+ ctx.fill();+ ctx.font = '600 11px Inter, system-ui, sans-serif';+ ctx.fillStyle = 'rgba(255,255,255,0.55)';+ ctx.textAlign = 'left';+ ctx.textBaseline = 'middle';+ ctx.fillText(`${(name || 'Agent').slice(0, 28)} · activity`, 28, 15);++ const lines = (entries || []).slice().reverse(); // newest-first+ if (!lines.length) {+ ctx.font = '500 12px "Courier New", monospace';+ ctx.fillStyle = 'rgba(255,255,255,0.18)';+ const msg = '> standing by — no recorded actions yet';+ ctx.fillText(msg, 16, 56);+ if (Math.sin(t * 4) > 0) {+ ctx.fillStyle = 'rgba(255,255,255,0.18)';+ ctx.fillRect(16 + ctx.measureText(msg).width + 4, 48, 7, 14);+ }+ if (state.action) state.action.textContent = 'Standing by';+ return;+ }++ const lH = 26;+ const y = 52;+ const max = Math.floor((H - 52) / lH);+ lines.slice(0, max).forEach((a, i) => {+ const latest = i === 0;+ const age = Math.max(0, Math.round((Date.now() - (a.ts || Date.now())) / 1000));+ const ts = age < 5 ? 'now' : age < 60 ? `${age}s` : age < 3600 ? `${Math.round(age / 60)}m` : `${Math.round(age / 3600)}h`;+ ctx.font = '600 11px "Courier New", monospace';+ ctx.fillStyle = latest ? '#5fd08a' : 'rgba(255,255,255,0.2)';+ const pfx = `[${ts}] `;+ ctx.fillText(pfx, 16, y + i * lH);+ const pw = ctx.measureText(pfx).width;+ ctx.font = `${latest ? '600' : '400'} 12px "Courier New", monospace`;+ ctx.fillStyle = latest ? '#f0f0f4' : 'rgba(255,255,255,0.4)';+ ctx.fillText((a.activity || a.type || 'action').slice(0, 64), 16 + pw, y + i * lH);+ });++ if (state.action) state.action.textContent = lines[0].activity || lines[0].type || 'active';+}++function isLiveNow(state) {+ return state.lastFrameAt && (Date.now() - state.lastFrameAt) < FRAME_STALE_MS;+}++function attachStream(state) {+ const { card, agentId } = state;+ if (state.es) { try { state.es.close(); } catch { /* */ } }- const canvas = card.querySelector('canvas');- const ctx = canvas.getContext('2d');const dot = card.querySelector('[data-dot]');const statusEl = card.querySelector('[data-status]');- const actionEl = card.querySelector('[data-action]');-- let frameTimeoutId = null;+ const canvas = card.querySelector('canvas');+ const ctx = canvas.getContext('2d');function setLive(live) {+ state.live = live;dot.classList.toggle('idle', !live);- statusEl.textContent = live ? 'Live' : 'Idle';- }-- function bumpTimeout() {- clearTimeout(frameTimeoutId);- frameTimeoutId = setTimeout(() => setLive(false), 5000);+ statusEl.textContent = live ? 'Live' : (state.entries?.length ? 'Active' : 'Idle');}+ state.setLive = setLive;const es = new EventSource(`/api/agent-screen-stream?agentId=${encodeURIComponent(agentId)}`);- _streams.set(agentId, es);+ state.es = es;es.addEventListener('frame', (e) => {try {@@ -128,133 +213,170 @@ function attachStream(card, agentId) {const img = new Image();img.onload = () => ctx.drawImage(img, 0, 0, canvas.width, canvas.height);img.src = src.startsWith('data:') ? src : 'data:image/png;base64,' + src;+ state.lastFrameAt = Date.now();setLive(true);- bumpTimeout();_totalFrames++;_fpsMap.set(agentId, (_fpsMap.get(agentId) || 0) + 1);- if (msg.activity) actionEl.textContent = msg.activity;+ if (msg.activity && state.action) state.action.textContent = msg.activity;} catch { /* malformed */ }});es.addEventListener('log', (e) => {try {const { entries } = JSON.parse(e.data);- if (entries?.length) actionEl.textContent = entries[0]?.activity || '';+ if (Array.isArray(entries)) state.entries = entries;+ if (!isLiveNow(state)) { paintActivity(state); setLive(false); }} catch { /* */ }});- es.addEventListener('dark', () => setLive(false));- es.addEventListener('ping', () => {- if (statusEl.textContent === 'Connecting') { statusEl.textContent = 'Idle'; }- });+ es.addEventListener('open', () => { if (statusEl.textContent === 'Connecting') setLive(false); });+ es.addEventListener('dark', () => { setLive(false); paintActivity(state); });+ es.addEventListener('ping', () => { if (statusEl.textContent === 'Connecting') setLive(false); });es.onerror = () => setLive(false);}-function paintActivityFallback(canvas, agentName, status) {- const ctx = canvas.getContext('2d');- const W = canvas.width, H = canvas.height;- ctx.fillStyle = '#08090e';- ctx.fillRect(0, 0, W, H);-- // Dot- ctx.beginPath();- ctx.arc(20, H / 2, 4, 0, Math.PI * 2);- ctx.fillStyle = status === 'live' ? '#5fd08a' : 'rgba(255,255,255,0.15)';- ctx.fill();-- ctx.font = '600 13px Inter, system-ui, sans-serif';- ctx.fillStyle = 'rgba(255,255,255,0.5)';- ctx.textAlign = 'left';- ctx.textBaseline = 'middle';- ctx.fillText((agentName || 'Agent') + ' — awaiting stream', 32, H / 2);+// ── watch intent ────────────────────────────────────────────────────────────+// Tell the backend which agents are being actively watched so the caster pool+// can prioritise real browser streams for them. Fire-and-forget; the wall works+// fully (activity view) whether or not a caster ever picks the agent up.+function signalWatch(agentId) {+ try {+ fetch('/api/agent/watch-intent', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ agentId }),+ keepalive: true,+ }).catch(() => {});+ } catch { /* */ }}-async function refresh() {- const agents = await fetchRoster();-- liveCount.textContent = agents.length;- statLive.textContent = agents.length;- if (statsBar) statsBar.hidden = agents.length === 0;+// ── lifecycle ──────────────────────────────────────────────────────────────────++function mountAgent(agent) {+ const id = agent.id || agent.agentId;+ if (!id || _cards.has(id)) return;+ const card = buildCard(agent);+ grid.querySelectorAll('.al-skeleton').forEach((s) => s.remove());+ grid.querySelector('.al-empty')?.remove();+ grid.appendChild(card);+ const state = {+ agentId: id,+ card,+ name: agent.name || agent.agentName || 'Agent',+ action: card.querySelector('[data-action]'),+ entries: [],+ lastFrameAt: 0,+ live: false,+ es: null,+ };+ _cards.set(id, state);+ attachStream(state);+ signalWatch(id);+}- // Build a set of current agent IDs to prune stale streams.- const currentIds = new Set(agents.map((a) => a.agentId || a.id));+function renderEmpty() {+ grid.innerHTML = `+<div class="al-empty">+ <div class="al-empty-icon">🖥</div>+ <h2>No agents yet</h2>+ <p>Agents appear here the moment they're created. Spin one up and watch it work in real time.</p>+ <a href="/dashboard-next/create" class="al-empty-cta">Create an agent →</a>+</div>`;+}- // Remove cards for agents no longer streaming.- for (const [id, es] of _streams) {- if (!currentIds.has(id)) {- try { es.close(); } catch { /* */ }- _streams.delete(id);- const old = grid.querySelector(`[data-agent-id="${CSS.escape(id)}"]`);- if (old) old.remove();- }- }+async function loadMore() {+ if (_loading || !_hasMore) return;+ _loading = true;+ const { agents, hasMore, cursor } = await fetchRosterPage();+ _hasMore = hasMore;+ _cursor = cursor;- if (!agents.length) {- // Preserve existing cards (might still have streams), only show empty if none at all.- if (!_streams.size) {- grid.innerHTML = renderEmpty();- }+ if (!_cards.size && !agents.length) {+ renderEmpty();+ _loading = false;return;}+ agents.forEach(mountAgent);+ updateStats();+ _loading = false;+}- // Add new cards — and re-attach streams to existing cards whose stream was- // torn down (e.g. after the tab was backgrounded via suspendStreams()).- for (const agent of agents) {- const id = agent.agentId || agent.id;- let card = grid.querySelector(`[data-agent-id="${CSS.escape(id)}"]`);- if (!card) {- card = buildCard(agent);- // Remove skeleton loaders once we have real cards.- grid.querySelectorAll('.al-skeleton').forEach((s) => s.remove());- grid.querySelector('.al-empty')?.remove();- grid.appendChild(card);- attachStream(card, id);- } else if (!_streams.has(id)) {- attachStream(card, id);- }- }+function updateStats() {+ const total = _cards.size;+ let live = 0;+ for (const s of _cards.values()) if (isLiveNow(s)) live++;+ if (liveCount) liveCount.textContent = live;+ if (statLive) statLive.textContent = live;+ if (statTotal) statTotal.textContent = total;+ if (statsBar) statsBar.hidden = total === 0;}-// FPS ticker — measures aggregate frames/s across all cards.+// FPS + live-count ticker.function startFpsTicker() {_fpsInterval = setInterval(() => {let total = 0;for (const c of _fpsMap.values()) total += c;_fpsMap.clear();- statFps.textContent = total > 0 ? `${total}/s` : '—';+ if (statFps) statFps.textContent = total > 0 ? `${total}/s` : '—';+ updateStats();}, 1000);}-// Tear down every live stream (used when the tab goes to the background — no-// point decoding frames nobody is watching). Cards stay in the DOM showing-// their last frame; refresh() re-attaches streams when the tab returns.+// Repaint idle cards so relative timestamps + the cursor stay alive, and a card+// that just lost its live feed falls back to the activity terminal.+function startIdleRepaint() {+ _idleRepaint = setInterval(() => {+ if (document.hidden) return;+ for (const s of _cards.values()) {+ if (!isLiveNow(s)) {+ paintActivity(s);+ if (s.live) s.setLive?.(false);+ }+ }+ }, 2500);+}++// Re-assert watch intent for every mounted card on a slow cadence.+function startWatchPings() {+ setInterval(() => {+ if (document.hidden) return;+ for (const id of _cards.keys()) signalWatch(id);+ }, WATCH_PING_MS);+}++// Infinite scroll: load the next page as the user nears the bottom.+function startInfiniteScroll() {+ window.addEventListener('scroll', () => {+ if (_loading || !_hasMore) return;+ if (window.innerHeight + window.scrollY >= document.body.offsetHeight - 600) loadMore();+ }, { passive: true });+}+function suspendStreams() {- for (const [id, es] of _streams) {- try { es.close(); } catch { /* */ }- _streams.delete(id);- const card = grid.querySelector(`[data-agent-id="${CSS.escape(id)}"]`);- card?.querySelector('[data-status]')?.replaceChildren(document.createTextNode('Paused'));- card?.querySelector('[data-dot]')?.classList.add('idle');+ for (const s of _cards.values()) {+ try { s.es?.close(); } catch { /* */ }+ s.es = null;+ const statusEl = s.card.querySelector('[data-status]');+ if (statusEl) statusEl.textContent = 'Paused';+ s.card.querySelector('[data-dot]')?.classList.add('idle');}}-// ── boot ──────────────────────────────────────────────────────────────────────--let _refreshTimer = null;-function startRefreshLoop() {- clearInterval(_refreshTimer);- _refreshTimer = setInterval(() => { if (!document.hidden) refresh(); }, 30_000);+function resumeStreams() {+ for (const s of _cards.values()) {+ if (!s.es) { attachStream(s); signalWatch(s.agentId); }+ }}-await refresh();+// ── boot ──────────────────────────────────────────────────────────────────────++await loadMore();startFpsTicker();-startRefreshLoop();+startIdleRepaint();+startWatchPings();+startInfiniteScroll();-// Pause all decoding while the tab is hidden; reconnect the moment it's visible.document.addEventListener('visibilitychange', () => {- if (document.hidden) {- suspendStreams();- } else {- refresh(); // re-discovers the roster and re-attaches streams to existing cards- }+ if (document.hidden) suspendStreams();+ else resumeStreams();});diff --git a/src/vaults.css b/src/vaults.cssindex 998c7d85b..be01dabb2 100644--- a/src/vaults.css+++ b/src/vaults.css@@ -11,17 +11,37 @@@keyframes vx-fade { from { opacity: 0; transform: translateY(6px); } to { opacity: 1; transform: none; } }/* ── hero ─────────────────────────────────────────────────────────────────── */-.vx-hero { max-width: 760px; margin-bottom: var(--space-xl); }+.vx-hero {+ position: relative;+ max-width: 820px;+ margin-bottom: var(--space-xl);+ padding: var(--space-xl) var(--space-lg);+ border: 1px solid var(--stroke);+ border-radius: var(--radius-card);+ background:+ radial-gradient(120% 140% at 0% 0%, var(--wallet-accent-soft), transparent 55%),+ radial-gradient(120% 160% at 100% 0%, color-mix(in srgb, var(--success) 12%, transparent), transparent 50%),+ var(--surface-1);+ overflow: hidden;+}+.vx-hero::after {+ content: ""; position: absolute; inset: 0; pointer-events: none;+ background: radial-gradient(60% 60% at 85% 110%, var(--wallet-glow, rgba(139,92,246,0.16)), transparent 70%);+}+.vx-hero > * { position: relative; }.vx-kicker {display: inline-flex; align-items: center; gap: var(--space-xs);font: var(--weight-medium) var(--text-sm) / 1 var(--font-mono);color: var(--wallet-accent); text-transform: uppercase; letter-spacing: 0.08em;margin: 0 0 var(--space-sm);+ padding: 5px 10px; border-radius: var(--radius-pill);+ background: color-mix(in srgb, var(--wallet-accent) 12%, transparent);+ border: 1px solid color-mix(in srgb, var(--wallet-accent) 22%, transparent);}.vx-live-dot { width: 7px; height: 7px; border-radius: var(--radius-pill); background: var(--success); box-shadow: 0 0 0 0 rgba(74, 222, 128, 0.5); animation: vx-pulse 2s infinite; }@keyframes vx-pulse { 0% { box-shadow: 0 0 0 0 rgba(74, 222, 128, 0.5); } 70% { box-shadow: 0 0 0 7px rgba(74, 222, 128, 0); } 100% { box-shadow: 0 0 0 0 rgba(74, 222, 128, 0); } }-.vx-title { font: var(--weight-bold) var(--text-2xl) / 1.05 var(--font-display); color: var(--ink-bright); margin: 0 0 var(--space-sm); letter-spacing: -0.02em; }-.vx-sub { font-size: var(--text-base); line-height: var(--leading-normal); color: var(--ink-dim); margin: 0 0 var(--space-lg); }+.vx-title { font: var(--weight-bold) var(--text-3xl) / 1.03 var(--font-display); color: var(--ink-bright); margin: 0 0 var(--space-sm); letter-spacing: -0.025em; }+.vx-sub { font-size: var(--text-base); line-height: var(--leading-normal); color: var(--ink-dim); margin: 0 0 var(--space-lg); max-width: 60ch; }.vx-sub strong { color: var(--ink); font-weight: var(--weight-semibold); }.vx-hero-actions { display: flex; flex-wrap: wrap; gap: var(--space-sm); }@@ -37,48 +57,112 @@.vx-btn:hover { background: var(--surface-3); border-color: var(--wallet-accent-strong); }.vx-btn:active { transform: translateY(1px); }.vx-btn:focus-visible { outline: var(--focus-ring-width) solid var(--focus-ring-color); outline-offset: var(--focus-ring-offset); }-.vx-btn--primary { background: var(--wallet-accent-strong); border-color: var(--wallet-accent-strong); color: #15032e; font-weight: var(--weight-semibold); }+.vx-btn--primary { background: var(--wallet-accent-strong); border-color: var(--wallet-accent-strong); color: #15032e; font-weight: var(--weight-semibold); box-shadow: 0 6px 20px -8px var(--wallet-glow, rgba(139,92,246,0.6)); }.vx-btn--primary:hover { background: var(--wallet-accent); border-color: var(--wallet-accent); }.vx-btn--ghost { background: transparent; }.vx-btn--block { width: 100%; }.vx-btn:disabled { opacity: 0.5; cursor: not-allowed; }-/* ── feed ─────────────────────────────────────────────────────────────────── */+/* ── aggregate stats strip ─────────────────────────────────────────────────── */+.vx-stats { display: grid; grid-template-columns: repeat(4, 1fr); gap: var(--space-sm); margin-bottom: var(--space-lg); }+.vx-stats[hidden] { display: none; }+.vx-stat-tile {+ position: relative; overflow: hidden;+ display: flex; flex-direction: column; gap: var(--space-2xs);+ padding: var(--space-md);+ background: var(--surface-1); border: 1px solid var(--stroke); border-radius: var(--radius-lg);+}+.vx-stat-tile::before { content: ""; position: absolute; left: 0; top: 0; bottom: 0; width: 3px; background: var(--wallet-accent-strong); opacity: 0.7; }+.vx-stat-tile.is-pos::before { background: var(--success); }+.vx-stat-tile-l { font: var(--weight-medium) var(--text-2xs) var(--font-body); color: var(--ink-faint); text-transform: uppercase; letter-spacing: 0.05em; }+.vx-stat-tile-v { font: var(--weight-bold) var(--text-xl) var(--font-mono); color: var(--ink-bright); letter-spacing: -0.01em; }+.vx-stat-tile-s { font: var(--text-2xs) var(--font-mono); color: var(--ink-dim); }++/* ── feed head ────────────────────────────────────────────────────────────── */.vx-feed-head { display: flex; align-items: center; justify-content: space-between; gap: var(--space-md); margin-bottom: var(--space-md); flex-wrap: wrap; }+.vx-feed-head-l { display: flex; align-items: baseline; gap: var(--space-sm); }+.vx-feed-head-r { display: flex; align-items: center; gap: var(--space-sm); flex-wrap: wrap; }.vx-h2 { font: var(--weight-semibold) var(--text-lg) / 1 var(--font-display); color: var(--ink-bright); margin: 0; }+.vx-feed-count { font: var(--weight-medium) var(--text-sm) var(--font-mono); color: var(--ink-faint); }+.vx-sort { display: inline-flex; align-items: center; gap: var(--space-xs); }+.vx-sort-l { font: var(--weight-medium) var(--text-2xs) var(--font-body); color: var(--ink-faint); text-transform: uppercase; letter-spacing: 0.05em; }+.vx-sort-sel {+ appearance: none; -webkit-appearance: none;+ padding: var(--space-xs) calc(var(--space-md) + 10px) var(--space-xs) var(--space-sm);+ background: var(--surface-1) url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='10' height='6' viewBox='0 0 10 6'%3E%3Cpath d='M1 1l4 4 4-4' stroke='%23999' fill='none' stroke-width='1.5' stroke-linecap='round'/%3E%3C/svg%3E") no-repeat right var(--space-sm) center;+ border: 1px solid var(--stroke); border-radius: var(--radius-pill);+ color: var(--ink); font: var(--weight-medium) var(--text-sm) var(--font-body); cursor: pointer;+ transition: border-color var(--duration-fast);+}+.vx-sort-sel:hover { border-color: var(--wallet-accent-strong); }+.vx-sort-sel:focus-visible { outline: var(--focus-ring-width) solid var(--focus-ring-color); outline-offset: var(--focus-ring-offset); }.vx-tabs { display: inline-flex; gap: var(--space-3xs); padding: var(--space-3xs); background: var(--surface-1); border: 1px solid var(--stroke); border-radius: var(--radius-pill); }.vx-tab { border: none; background: transparent; color: var(--ink-dim); padding: var(--space-xs) var(--space-md); border-radius: var(--radius-pill); cursor: pointer; font: var(--weight-medium) var(--text-sm) var(--font-body); transition: background var(--duration-fast), color var(--duration-fast); }.vx-tab.is-active { background: var(--surface-3); color: var(--ink-bright); }.vx-tab:hover { color: var(--ink); }-.vx-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: var(--space-md); }+/* ── feed grid + cards ────────────────────────────────────────────────────── */+.vx-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(320px, 1fr)); gap: var(--space-md); }.vx-card {+ position: relative; isolation: isolate;display: flex; flex-direction: column; gap: var(--space-sm);- padding: var(--space-md); text-align: left; cursor: pointer;+ padding: var(--space-md); padding-left: calc(var(--space-md) + 3px);+ text-align: left; cursor: pointer;background: var(--surface-1); border: 1px solid var(--stroke); border-radius: var(--radius-lg);- color: inherit; font: inherit;- transition: border-color var(--duration-fast) var(--ease-standard), transform var(--duration-fast), background var(--duration-fast);+ color: inherit; font: inherit; overflow: hidden;+ transition: border-color var(--duration-fast) var(--ease-standard), transform var(--duration-fast), box-shadow var(--duration-fast), background var(--duration-fast);}-.vx-card:hover { border-color: var(--wallet-accent-strong); transform: translateY(-2px); background: var(--surface-2); }+.vx-card:hover { border-color: var(--wallet-accent-strong); transform: translateY(-3px); background: var(--surface-2); box-shadow: 0 14px 30px -18px var(--wallet-glow, rgba(139,92,246,0.5)); }.vx-card:focus-visible { outline: var(--focus-ring-width) solid var(--focus-ring-color); outline-offset: var(--focus-ring-offset); }+.vx-card-accent { position: absolute; left: 0; top: 0; bottom: 0; width: 3px; background: var(--ink-faint); opacity: 0.6; }+.vx-card-accent.is-pos { background: var(--success); opacity: 0.9; }+.vx-card-accent.is-neg { background: var(--danger); opacity: 0.85; }+.vx-card-head { display: flex; align-items: center; gap: var(--space-sm); }-.vx-card-av { width: 44px; height: 44px; border-radius: var(--radius-md); object-fit: cover; flex: 0 0 auto; background: var(--surface-3); }+.vx-card-avwrap { position: relative; flex: 0 0 auto; width: 48px; height: 48px; border-radius: var(--radius-md); padding: 2px; background: var(--stroke); }+.vx-card-avwrap.is-open { background: linear-gradient(135deg, var(--success), color-mix(in srgb, var(--success) 30%, transparent)); }+.vx-card-avwrap.is-paused { background: linear-gradient(135deg, var(--warn), color-mix(in srgb, var(--warn) 30%, transparent)); }+.vx-card-av { width: 100%; height: 100%; border-radius: calc(var(--radius-md) - 2px); object-fit: cover; display: block; background: var(--surface-3); }.vx-card-av--ph { background: linear-gradient(135deg, var(--surface-3), var(--wallet-accent-soft)); }-.vx-card-id { display: flex; flex-direction: column; gap: 2px; min-width: 0; flex: 1; }+.vx-card-rank {+ position: absolute; top: -7px; left: -7px; z-index: 2;+ width: 22px; height: 22px; border-radius: var(--radius-pill);+ display: flex; align-items: center; justify-content: center;+ font: var(--weight-bold) var(--text-2xs) var(--font-mono); color: #1a1300;+ background: linear-gradient(135deg, #ffe28a, #f5b13a); box-shadow: 0 2px 6px rgba(0,0,0,0.35); border: 1.5px solid var(--bg-1);+}+.vx-card-rank.rank-1 { background: linear-gradient(135deg, #d6dce6, #9aa6b8); }+.vx-card-rank.rank-2 { background: linear-gradient(135deg, #e6b489, #c47f44); }+.vx-card-id { display: flex; flex-direction: column; gap: 3px; min-width: 0; flex: 1; }.vx-card-name { font: var(--weight-semibold) var(--text-md) var(--font-display); color: var(--ink-bright); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }-.vx-rep { font: var(--weight-medium) var(--text-2xs) / 1.3 var(--font-mono); padding: 2px 6px; border-radius: var(--radius-sm); align-self: flex-start; }+.vx-rep { display: inline-flex; align-items: center; gap: 4px; font: var(--weight-medium) var(--text-2xs) / 1.3 var(--font-mono); padding: 2px 7px; border-radius: var(--radius-sm); align-self: flex-start; }.vx-rep--ok { color: var(--success); background: rgba(74, 222, 128, 0.12); }.vx-rep--warn { color: var(--warn); background: rgba(251, 191, 36, 0.12); }.vx-rep--none, .vx-rep--muted { color: var(--ink-faint); background: var(--surface-2); }-.vx-chip { font: var(--weight-medium) var(--text-2xs) var(--font-mono); padding: 2px 7px; border-radius: var(--radius-pill); align-self: flex-start; }+.vx-chip { font: var(--weight-medium) var(--text-2xs) var(--font-mono); padding: 2px 8px; border-radius: var(--radius-pill); align-self: flex-start; white-space: nowrap; }.vx-chip--warn { color: var(--warn); background: rgba(251, 191, 36, 0.14); }-.vx-card-stats { display: grid; grid-template-columns: repeat(3, 1fr); gap: var(--space-xs); padding: var(--space-sm) 0; border-top: 1px solid var(--stroke); border-bottom: 1px solid var(--stroke); }+/* prominent return block */+.vx-card-return { display: flex; align-items: baseline; gap: var(--space-xs); padding: var(--space-xs) 0; }+.vx-card-return-arrow { font-size: var(--text-md); line-height: 1; }+.vx-card-return-v { font: var(--weight-bold) var(--text-2xl) / 1 var(--font-mono); letter-spacing: -0.02em; }+.vx-card-return-l { font: var(--weight-medium) var(--text-2xs) var(--font-body); color: var(--ink-faint); text-transform: uppercase; letter-spacing: 0.05em; margin-left: auto; align-self: center; }++.vx-card-stats { display: grid; grid-template-columns: 1fr 1fr; gap: var(--space-xs); padding: var(--space-sm) 0; border-top: 1px solid var(--stroke); }.vx-stat { display: flex; flex-direction: column; gap: 3px; }.vx-stat-l { font: var(--text-2xs) var(--font-body); color: var(--ink-faint); text-transform: uppercase; letter-spacing: 0.04em; }.vx-stat-v { font: var(--weight-semibold) var(--text-md) var(--font-mono); color: var(--ink-bright); }-.vx-card-foot { display: flex; justify-content: space-between; gap: var(--space-xs); font: var(--text-xs) var(--font-mono); color: var(--ink-dim); flex-wrap: wrap; }++/* capital-backed comparison bar */+.vx-card-cap { display: flex; flex-direction: column; gap: 5px; }+.vx-card-cap-bar { height: 5px; border-radius: var(--radius-pill); background: var(--surface-3); overflow: hidden; }+.vx-card-cap-bar > i { display: block; height: 100%; border-radius: var(--radius-pill); background: linear-gradient(90deg, var(--wallet-accent), var(--wallet-accent-strong)); transition: width var(--duration-slow) var(--ease-out); }+.vx-card-cap-meta { display: flex; justify-content: space-between; gap: var(--space-xs); font: var(--text-2xs) var(--font-mono); color: var(--ink-dim); }++.vx-card-foot { display: flex; align-items: center; justify-content: space-between; gap: var(--space-xs); font: var(--text-xs) var(--font-mono); color: var(--ink-dim); flex-wrap: wrap; }+.vx-card-cta { color: var(--wallet-accent); font-family: var(--font-body); font-weight: var(--weight-medium); opacity: 0; transform: translateX(-4px); transition: opacity var(--duration-fast), transform var(--duration-fast); margin-left: auto; }+.vx-card:hover .vx-card-cta { opacity: 1; transform: none; }.is-pos { color: var(--success) !important; }.is-neg { color: var(--danger) !important; }@@ -114,7 +198,35 @@.vx-link:hover { color: var(--ink-bright); text-decoration: underline; }.vx-d-cta { margin-left: auto; }-.vx-d-metrics { display: grid; grid-template-columns: repeat(5, 1fr); gap: var(--space-sm); margin-bottom: var(--space-lg); }+/* hero NAV + sparkline panel */+.vx-navhero {+ display: grid; grid-template-columns: 1fr 1.3fr; gap: var(--space-md); align-items: stretch;+ margin-bottom: var(--space-md);+}+.vx-navhero-main {+ display: flex; flex-direction: column; justify-content: center; gap: var(--space-2xs);+ padding: var(--space-lg);+ background: radial-gradient(120% 140% at 0% 0%, var(--wallet-accent-soft), transparent 60%), var(--surface-1);+ border: 1px solid var(--stroke); border-radius: var(--radius-lg);+}+.vx-navhero-l { font: var(--weight-medium) var(--text-2xs) var(--font-body); color: var(--ink-faint); text-transform: uppercase; letter-spacing: 0.06em; }+.vx-navhero-v { font: var(--weight-bold) var(--text-3xl) / 1 var(--font-mono); color: var(--ink-bright); letter-spacing: -0.025em; }+.vx-navhero-roi { display: inline-flex; align-items: center; gap: 5px; align-self: flex-start; margin-top: var(--space-2xs); padding: 3px 10px; border-radius: var(--radius-pill); font: var(--weight-semibold) var(--text-sm) var(--font-mono); }+.vx-navhero-roi.is-pos { color: var(--success); background: rgba(74, 222, 128, 0.12); }+.vx-navhero-roi.is-neg { color: var(--danger); background: rgba(248, 113, 113, 0.12); }+.vx-navhero-roi.is-flat { color: var(--ink-dim); background: var(--surface-2); }+.vx-navhero-chart {+ display: flex; flex-direction: column;+ padding: var(--space-md);+ background: var(--surface-1); border: 1px solid var(--stroke); border-radius: var(--radius-lg);+}+.vx-chart-head { display: flex; align-items: baseline; justify-content: space-between; gap: var(--space-sm); margin-bottom: var(--space-xs); }+.vx-chart-t { font: var(--weight-medium) var(--text-2xs) var(--font-body); color: var(--ink-faint); text-transform: uppercase; letter-spacing: 0.05em; }+.vx-chart-now { font: var(--weight-semibold) var(--text-sm) var(--font-mono); color: var(--ink-bright); }+.vx-spark { width: 100%; flex: 1; min-height: 64px; display: block; }+.vx-spark-empty { display: flex; align-items: center; justify-content: center; flex: 1; min-height: 64px; color: var(--ink-faint); font: var(--text-xs) var(--font-mono); text-align: center; }++.vx-d-metrics { display: grid; grid-template-columns: repeat(4, 1fr); gap: var(--space-sm); margin-bottom: var(--space-lg); }.vx-metric { background: var(--surface-1); border: 1px solid var(--stroke); border-radius: var(--radius-md); padding: var(--space-sm) var(--space-md); display: flex; flex-direction: column; gap: var(--space-2xs); }.vx-metric-l { font: var(--text-2xs) var(--font-body); color: var(--ink-faint); text-transform: uppercase; letter-spacing: 0.04em; }.vx-metric-v { font: var(--weight-semibold) var(--text-lg) var(--font-mono); color: var(--ink-bright); }@@ -127,6 +239,18 @@.vx-panel-h { font: var(--weight-semibold) var(--text-md) var(--font-display); color: var(--ink-bright); margin: 0 0 var(--space-sm); display: flex; align-items: baseline; gap: var(--space-xs); }.vx-panel-sub { font: var(--text-2xs) var(--font-mono); color: var(--ink-faint); font-weight: var(--weight-regular); }+/* drawdown gauge */+.vx-gauge { margin-top: var(--space-sm); }+.vx-gauge-head { display: flex; align-items: baseline; justify-content: space-between; gap: var(--space-sm); margin-bottom: 6px; }+.vx-gauge-l { font: var(--weight-medium) var(--text-2xs) var(--font-body); color: var(--ink-faint); text-transform: uppercase; letter-spacing: 0.05em; }+.vx-gauge-v { font: var(--weight-semibold) var(--text-sm) var(--font-mono); }+.vx-gauge-track { position: relative; height: 8px; border-radius: var(--radius-pill); background: var(--surface-3); overflow: hidden; }+.vx-gauge-fill { height: 100%; border-radius: var(--radius-pill); transition: width var(--duration-slow) var(--ease-out); }+.vx-gauge-fill.is-ok { background: linear-gradient(90deg, var(--success), color-mix(in srgb, var(--success) 60%, var(--warn))); }+.vx-gauge-fill.is-warn { background: linear-gradient(90deg, var(--warn), color-mix(in srgb, var(--warn) 50%, var(--danger))); }+.vx-gauge-fill.is-crit { background: linear-gradient(90deg, var(--danger), color-mix(in srgb, var(--danger) 70%, #fff)); }+.vx-gauge-cap { font: var(--text-2xs) var(--font-mono); color: var(--ink-faint); margin-top: 6px; }+.vx-kv-grid { display: grid; grid-template-columns: 1fr 1fr; gap: var(--space-sm); }.vx-kv-grid > div { display: flex; flex-direction: column; gap: 2px; }.vx-kv-grid span { font: var(--text-2xs) var(--font-body); color: var(--ink-faint); text-transform: uppercase; letter-spacing: 0.04em; }@@ -139,6 +263,14 @@.vx-mono { font-family: var(--font-mono); }.vx-muted { color: var(--ink-faint); }+/* backer distribution */+.vx-distbar { display: flex; height: 10px; border-radius: var(--radius-pill); overflow: hidden; background: var(--surface-3); margin-bottom: var(--space-sm); }+.vx-distbar > i { height: 100%; min-width: 2px; transition: width var(--duration-slow) var(--ease-out); }+.vx-distbar > i.is-me { background: var(--wallet-accent-strong); }+.vx-dist-legend { display: flex; flex-wrap: wrap; gap: var(--space-xs) var(--space-md); font: var(--text-2xs) var(--font-mono); color: var(--ink-dim); }+.vx-dist-legend span { display: inline-flex; align-items: center; gap: 5px; }+.vx-dist-dot { width: 8px; height: 8px; border-radius: var(--radius-pill); flex: 0 0 auto; }+.vx-terms { display: flex; flex-direction: column; gap: var(--space-xs); }.vx-terms > div { display: flex; justify-content: space-between; align-items: baseline; gap: var(--space-sm); font-size: var(--text-sm); }.vx-terms span { color: var(--ink-dim); }@@ -147,9 +279,10 @@.vx-ledger { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; max-height: 420px; overflow-y: auto; }.vx-ledger-row { display: flex; align-items: center; gap: var(--space-sm); padding: var(--space-xs) 0; border-top: 1px solid var(--stroke); }.vx-ledger-row:first-child { border-top: none; }-.vx-ledger-i { width: 22px; text-align: center; color: var(--ink-dim); flex: 0 0 auto; }-.vx-ledger--drawdown_halt .vx-ledger-i { color: var(--danger); }-.vx-ledger--deposit .vx-ledger-i { color: var(--success); }+.vx-ledger-i { width: 26px; height: 26px; flex: 0 0 auto; display: flex; align-items: center; justify-content: center; border-radius: var(--radius-pill); background: var(--surface-2); color: var(--ink-dim); font-size: var(--text-xs); }+.vx-ledger--drawdown_halt .vx-ledger-i { color: var(--danger); background: rgba(248, 113, 113, 0.12); }+.vx-ledger--deposit .vx-ledger-i { color: var(--success); background: rgba(74, 222, 128, 0.12); }+.vx-ledger--trade .vx-ledger-i { color: var(--wallet-accent); background: var(--wallet-accent-soft); }.vx-ledger-b { flex: 1; min-width: 0; display: flex; flex-direction: column; }.vx-ledger-b b { font: var(--weight-medium) var(--text-sm) var(--font-body); color: var(--ink); }.vx-ledger-d { font: var(--text-xs) var(--font-mono); color: var(--ink-dim); }@@ -200,13 +333,18 @@ body.vx-modal-open { overflow: hidden; }/* ── responsive ───────────────────────────────────────────────────────────── */@media (max-width: 900px) {+ .vx-stats { grid-template-columns: repeat(2, 1fr); }+ .vx-navhero { grid-template-columns: 1fr; }.vx-d-cols { grid-template-columns: 1fr; }.vx-d-metrics { grid-template-columns: repeat(2, 1fr); }.vx-trade-grid { grid-template-columns: 1fr 1fr; }}@media (max-width: 560px) {.vx-shell { padding: var(--space-lg) var(--space-sm) var(--space-2xl); }- .vx-title { font-size: var(--text-xl); }+ .vx-hero { padding: var(--space-lg) var(--space-md); }+ .vx-title { font-size: var(--text-2xl); }+ .vx-stats { grid-template-columns: repeat(2, 1fr); }+ .vx-feed-head-r { width: 100%; justify-content: space-between; }.vx-grid { grid-template-columns: 1fr; }.vx-field-row { grid-template-columns: 1fr; }.vx-d-metrics { grid-template-columns: 1fr 1fr; }@@ -216,5 +354,5 @@ body.vx-modal-open { overflow: hidden; }#vx-toast { left: var(--space-sm); right: var(--space-sm); max-width: none; }}@media (prefers-reduced-motion: reduce) {- .vx-view, .vx-modal-card, .vx-modal-backdrop, .vx-toast-item, .vx-live-dot, .vx-skel-line { animation: none !important; transition: none !important; }+ .vx-view, .vx-modal-card, .vx-modal-backdrop, .vx-toast-item, .vx-live-dot, .vx-skel-line, .vx-card-cap-bar > i, .vx-gauge-fill, .vx-distbar > i { animation: none !important; transition: none !important; }}diff --git a/src/vaults.js b/src/vaults.jsindex 307669685..76bf41abc 100644--- a/src/vaults.js+++ b/src/vaults.js@@ -12,6 +12,7 @@ const state = {me: false,agents: [], // the signed-in user's agentstab: 'all',+ sort: 'perf',feed: [],vault: null, // current detail vaultpollTimer: null,@@ -55,6 +56,96 @@ async function readErr(res, fallback) {try { const j = await res.json(); return j.error_description || j.message || fallback; } catch { return fallback; }}+// ── visual helpers ───────────────────────────────────────────────────────────+const reduceMotion = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;++// Animated count-up for headline stats. fmt maps a raw number to display text.+function countUp(el, to, fmt, dur = 700) {+ if (!el) return;+ if (reduceMotion || !(to > 0)) { el.textContent = fmt(to); return; }+ const start = performance.now();+ const step = (now) => {+ const t = Math.min(1, (now - start) / dur);+ const eased = 1 - Math.pow(1 - t, 3);+ el.textContent = fmt(to * eased);+ if (t < 1) requestAnimationFrame(step);+ };+ requestAnimationFrame(step);+}++function sumBig(items, key) {+ return items.reduce((acc, it) => acc + (it[key] != null ? BigInt(it[key]) : 0n), 0n);+}++// Inline SVG sparkline from a real series of {p} price points (chronological).+function sparkline(points, { w = 320, h = 64, pad = 4, tone = 'pos' } = {}) {+ if (!points || points.length < 2) return '';+ const ys = points.map((p) => p.p);+ const min = Math.min(...ys), max = Math.max(...ys);+ const span = max - min || 1;+ const stepX = (w - pad * 2) / (points.length - 1);+ const coords = points.map((p, i) => {+ const x = pad + i * stepX;+ const y = pad + (h - pad * 2) * (1 - (p.p - min) / span);+ return [x, y];+ });+ const line = coords.map(([x, y], i) => `${i ? 'L' : 'M'}${x.toFixed(1)} ${y.toFixed(1)}`).join(' ');+ const area = `${line} L${coords[coords.length - 1][0].toFixed(1)} ${h - pad} L${coords[0][0].toFixed(1)} ${h - pad} Z`;+ const stroke = tone === 'neg' ? 'var(--danger)' : tone === 'flat' ? 'var(--ink-dim)' : 'var(--success)';+ const gid = `vxg-${tone}`;+ const [lx, ly] = coords[coords.length - 1];+ return `<svg class="vx-spark" viewBox="0 0 ${w} ${h}" preserveAspectRatio="none" role="img" aria-label="Share price history">+ <defs><linearGradient id="${gid}" x1="0" y1="0" x2="0" y2="1">+ <stop offset="0%" stop-color="${stroke}" stop-opacity="0.28"/>+ <stop offset="100%" stop-color="${stroke}" stop-opacity="0"/>+ </linearGradient></defs>+ <path d="${area}" fill="url(#${gid})"/>+ <path d="${line}" fill="none" stroke="${stroke}" stroke-width="2" stroke-linejoin="round" stroke-linecap="round" vector-effect="non-scaling-stroke"/>+ <circle cx="${lx.toFixed(1)}" cy="${ly.toFixed(1)}" r="3" fill="${stroke}"/>+ </svg>`;+}++// Real drawdown gauge: how much of the drawdown budget is currently used.+function drawdownGauge(peakE6, curE6, stopBps) {+ const peak = Number(BigInt(peakE6 || 1_000_000));+ const cur = Number(BigInt(curE6 || 1_000_000));+ const ddBps = peak > cur ? Math.round(((peak - cur) / peak) * 10000) : 0;+ const stop = Math.max(1, Number(stopBps || 2500));+ const ratio = Math.max(0, Math.min(1, ddBps / stop));+ const tone = ratio < 0.5 ? 'ok' : ratio < 0.85 ? 'warn' : 'crit';+ const used = (ddBps / 100).toFixed(1);+ const cap = (stop / 100).toFixed(0);+ return `<div class="vx-gauge">+ <div class="vx-gauge-head">+ <span class="vx-gauge-l">Drawdown from peak</span>+ <span class="vx-gauge-v ${ddBps > 0 ? (tone === 'crit' ? 'is-neg' : '') : 'is-pos'}">${ddBps > 0 ? `−${used}%` : 'At peak'}</span>+ </div>+ <div class="vx-gauge-track"><div class="vx-gauge-fill is-${tone}" style="width:${(ratio * 100).toFixed(1)}%"></div></div>+ <div class="vx-gauge-cap">Circuit breaker halts trading at −${cap}% · ${(100 - ratio * 100).toFixed(0)}% of buffer left</div>+ </div>`;+}++// Real backer capital distribution from the public roster (stake size only).+function backerDist(backers) {+ const rows = (backers || []).filter((b) => BigInt(b.deposited_atomics || 0) > 0n);+ if (!rows.length) return '';+ const total = rows.reduce((a, b) => a + Number(BigInt(b.deposited_atomics)), 0) || 1;+ const sorted = [...rows].sort((a, b) => Number(BigInt(b.deposited_atomics)) - Number(BigInt(a.deposited_atomics)));+ const palette = ['#8b5cf6', '#a78bfa', '#7c6fe8', '#6d6bd6', '#5b6cc4', '#4a6bb2'];+ let ci = 0;+ const seg = sorted.slice(0, 6).map((b) => {+ const pct = (Number(BigInt(b.deposited_atomics)) / total) * 100;+ const color = b.is_me ? '' : palette[ci++ % palette.length];+ return { pct, me: b.is_me, color };+ });+ const restPct = 100 - seg.reduce((a, s) => a + s.pct, 0);+ const bars = seg.map((s) => `<i class="${s.me ? 'is-me' : ''}" style="width:${s.pct.toFixed(1)}%${s.me ? '' : `;background:${s.color}`}" title="${s.pct.toFixed(1)}%"></i>`).join('') ++ (restPct > 0.5 ? `<i style="width:${restPct.toFixed(1)}%;background:var(--surface-3)"></i>` : '');+ const mine = seg.find((s) => s.me);+ const legend = `${mine ? `<span><span class="vx-dist-dot" style="background:var(--wallet-accent-strong)"></span>You · ${mine.pct.toFixed(1)}%</span>` : ''}<span><span class="vx-dist-dot" style="background:${palette[0]}"></span>${rows.length} backer${rows.length === 1 ? '' : 's'}</span>`;+ return `<div class="vx-distbar">${bars}</div><div class="vx-dist-legend">${legend}</div>`;+}+// ── auth + agents ──────────────────────────────────────────────────────────────async function loadMe() {try {@@ -95,10 +186,67 @@ function skeletonCards(n) {return Array.from({ length: n }, () => '<div class="vx-card vx-card--skel"><div class="vx-skel-line"></div><div class="vx-skel-line short"></div><div class="vx-skel-stats"></div></div>').join('');}+const navNum = (v) => (v.last_nav_atomics != null ? Number(BigInt(v.last_nav_atomics)) : 0);++function sortFeed(items) {+ const by = {+ perf: (a, b) => (b.roi_bps || 0) - (a.roi_bps || 0),+ capital: (a, b) => navNum(b) - navNum(a),+ backers: (a, b) => (b.backer_count || 0) - (a.backer_count || 0),+ rep: (a, b) => {+ const av = a.reputation?.verified ? 1 : 0, bv = b.reputation?.verified ? 1 : 0;+ if (av !== bv) return bv - av;+ return (b.reputation?.score ?? 0) - (a.reputation?.score ?? 0);+ },+ };+ return [...items].sort(by[state.sort] || by.perf);+}++function renderStats() {+ const host = $('#vx-stats');+ if (!host) return;+ if (!state.feed.length) { host.hidden = true; return; }+ host.hidden = false;+ if (state.tab === 'mine') {+ const deposited = sumBig(state.feed, 'deposited_atomics');+ const realized = state.feed.reduce((a, v) => a + (v.realized_gain_atomics != null ? BigInt(v.realized_gain_atomics) : 0n), 0n);+ const tiles = [+ { l: 'Positions', to: state.feed.length, fmt: (n) => Math.round(n).toLocaleString() },+ { l: 'Total deposited', to: Number(deposited) / ATOMICS, fmt: (n) => '$' + n.toLocaleString('en-US', { maximumFractionDigits: 0 }) },+ { l: 'Realized P&L', to: Number(realized) / ATOMICS, fmt: (n) => (realized >= 0n ? '+' : '−') + '$' + Math.abs(n).toLocaleString('en-US', { maximumFractionDigits: 0 }), pos: realized >= 0n },+ { l: 'Active vaults', to: state.feed.filter((v) => v.status === 'open').length, fmt: (n) => Math.round(n).toLocaleString() },+ ];+ paintStats(host, tiles);+ return;+ }+ const capital = sumBig(state.feed, 'last_nav_atomics');+ const backers = state.feed.reduce((a, v) => a + (v.backer_count || 0), 0);+ const best = state.feed.reduce((m, v) => Math.max(m, v.roi_bps || 0), 0);+ const verified = state.feed.filter((v) => v.reputation?.verified).length;+ const tiles = [+ { l: 'Open vaults', to: state.feed.length, fmt: (n) => Math.round(n).toLocaleString(), sub: `${verified} reputation-verified` },+ { l: 'Capital backed', to: Number(capital) / ATOMICS, fmt: (n) => '$' + n.toLocaleString('en-US', { maximumFractionDigits: 0 }) },+ { l: 'Backers', to: backers, fmt: (n) => Math.round(n).toLocaleString() },+ { l: 'Best return', to: best / 100, fmt: (n) => (best > 0 ? '+' : '') + n.toFixed(1) + '%', pos: best > 0 },+ ];+ paintStats(host, tiles);+}++function paintStats(host, tiles) {+ host.innerHTML = tiles.map((t) => `<div class="vx-stat-tile${t.pos ? ' is-pos' : ''}">+ <span class="vx-stat-tile-l">${t.l}</span>+ <span class="vx-stat-tile-v">${esc(t.fmt(0))}</span>+ ${t.sub ? `<span class="vx-stat-tile-s">${esc(t.sub)}</span>` : ''}+ </div>`).join('');+ $$('.vx-stat-tile-v', host).forEach((el, i) => countUp(el, tiles[i].to, tiles[i].fmt));+}+function renderFeed() {const grid = $('#vx-grid');+ renderStats();if (state.tab === 'mine') return renderMine();if (!state.feed.length) {+ $('#vx-feed-count').textContent = '';grid.innerHTML = `<div class="vx-empty"><p class="vx-empty-t">No open vaults yet</p><p class="vx-empty-d">Be the first. If your agent has a verified trading track record, open a vault and let backers stake behind it.</p>@@ -107,17 +255,23 @@ function renderFeed() {$('#vx-empty-open')?.addEventListener('click', openVaultModal);return;}- grid.innerHTML = state.feed.map(cardHtml).join('');+ $('#vx-feed-count').textContent = `${state.feed.length} ${state.feed.length === 1 ? 'vault' : 'vaults'}`;+ const items = sortFeed(state.feed);+ const maxNav = items.reduce((m, v) => Math.max(m, navNum(v)), 0);+ const topIds = [...state.feed].filter((v) => (v.roi_bps || 0) > 0).sort((a, b) => (b.roi_bps || 0) - (a.roi_bps || 0)).slice(0, 3).map((v) => v.id);+ grid.innerHTML = items.map((v) => cardHtml(v, maxNav, topIds.indexOf(v.id))).join('');$$('.vx-card[data-id]', grid).forEach((c) => c.addEventListener('click', () => openDetail(c.dataset.id)));}function renderMine() {const grid = $('#vx-grid');if (!state.feed.length) {+ $('#vx-feed-count').textContent = '';grid.innerHTML = `<div class="vx-empty"><p class="vx-empty-t">You haven't backed any agent</p><p class="vx-empty-d">Browse open vaults and stake behind a verified trader.</p><button class="vx-btn vx-btn--primary" id="vx-go-all" type="button">Browse vaults</button></div>`;$('#vx-go-all')?.addEventListener('click', () => setTab('all'));return;}+ $('#vx-feed-count').textContent = `${state.feed.length} ${state.feed.length === 1 ? 'position' : 'positions'}`;grid.innerHTML = state.feed.map(mineCardHtml).join('');$$('.vx-card[data-id]', grid).forEach((c) => c.addEventListener('click', () => openDetail(c.dataset.id)));}@@ -128,29 +282,46 @@ function repBadge(rep) {return `<span class="vx-rep vx-rep--warn">Unverified · ${rep.closed_count} trades</span>`;}-function cardHtml(v) {+function avatar(src, cls) {+ return src ? `<img class="vx-card-av ${cls || ''}" src="${esc(src)}" alt="" loading="lazy" />` : `<div class="vx-card-av vx-card-av--ph ${cls || ''}" aria-hidden="true"></div>`;+}++function cardHtml(v, maxNav, rank) {const roi = v.roi_bps || 0;- const img = v.agent_image ? `<img class="vx-card-av" src="${esc(v.agent_image)}" alt="" loading="lazy" />` : '<div class="vx-card-av vx-card-av--ph" aria-hidden="true"></div>';+ const sc = signClass(roi);const navLine = v.last_nav_atomics ? usdCompact(v.last_nav_atomics) : '—';+ const ringTone = v.status === 'paused' ? 'is-paused' : v.status === 'open' ? 'is-open' : '';const statusChip = v.status === 'paused' ? '<span class="vx-chip vx-chip--warn">Paused</span>' : '';+ const rankBadge = rank >= 0 ? `<span class="vx-card-rank rank-${rank}">${rank + 1}</span>` : '';+ const capPct = maxNav > 0 ? Math.max(3, (navNum(v) / maxNav) * 100) : 0;+ const arrow = roi > 0 ? '▲' : roi < 0 ? '▼' : '•';return `<button class="vx-card" data-id="${esc(v.id)}" type="button">+ <span class="vx-card-accent ${sc}" aria-hidden="true"></span><div class="vx-card-head">- ${img}+ <div class="vx-card-avwrap ${ringTone}">${rankBadge}${avatar(v.agent_image)}</div><div class="vx-card-id"><span class="vx-card-name">${esc(v.agent_name || 'Agent')}</span>${repBadge(v.reputation)}</div>${statusChip}</div>+ <div class="vx-card-return ${sc}">+ <span class="vx-card-return-arrow" aria-hidden="true">${arrow}</span>+ <span class="vx-card-return-v">${roiText(roi)}</span>+ <span class="vx-card-return-l">return</span>+ </div><div class="vx-card-stats"><div class="vx-stat"><span class="vx-stat-l">Vault NAV</span><span class="vx-stat-v">${navLine}</span></div><div class="vx-stat"><span class="vx-stat-l">Share price</span><span class="vx-stat-v">${priceE6(v.share_price_e6)}</span></div>- <div class="vx-stat"><span class="vx-stat-l">Return</span><span class="vx-stat-v ${signClass(roi)}">${roiText(roi)}</span></div>+ </div>+ <div class="vx-card-cap">+ <div class="vx-card-cap-bar"><i style="width:${capPct.toFixed(1)}%"></i></div>+ <div class="vx-card-cap-meta"><span>${navLine} backed</span><span>${v.backer_count} ${v.backer_count === 1 ? 'backer' : 'backers'}</span></div></div><div class="vx-card-foot"><span title="Performance fee">${pctBps(v.performance_fee_bps)} fee</span><span title="Drawdown circuit breaker">${pctBps(v.max_drawdown_bps)} stop</span>- <span title="Backers">${v.backer_count} ${v.backer_count === 1 ? 'backer' : 'backers'}</span>+ <span class="vx-card-cta">View vault →</span></div></button>`;}@@ -158,15 +329,23 @@ function cardHtml(v) {function mineCardHtml(v) {const deposited = BigInt(v.deposited_atomics || 0);const realized = BigInt(v.realized_gain_atomics || 0);- const img = v.agent_image ? `<img class="vx-card-av" src="${esc(v.agent_image)}" alt="" loading="lazy" />` : '<div class="vx-card-av vx-card-av--ph" aria-hidden="true"></div>';+ const realizedPos = realized >= 0n;+ const ringTone = v.status === 'paused' ? 'is-paused' : v.status === 'open' ? 'is-open' : '';return `<button class="vx-card" data-id="${esc(v.id)}" type="button">- <div class="vx-card-head">${img}<div class="vx-card-id"><span class="vx-card-name">${esc(v.agent_name || 'Agent')}</span><span class="vx-rep vx-rep--muted">${v.status}</span></div></div>+ <span class="vx-card-accent ${signClass(Number(realized))}" aria-hidden="true"></span>+ <div class="vx-card-head">+ <div class="vx-card-avwrap ${ringTone}">${avatar(v.agent_image)}</div>+ <div class="vx-card-id"><span class="vx-card-name">${esc(v.agent_name || 'Agent')}</span><span class="vx-rep vx-rep--muted">${esc(v.status)}</span></div>+ </div>+ <div class="vx-card-return ${signClass(Number(realized))}">+ <span class="vx-card-return-v" style="font-size:var(--text-xl)">${realizedPos ? '+' : '−'}${usdCompact(realizedPos ? realized : -realized)}</span>+ <span class="vx-card-return-l">realized P&L</span>+ </div><div class="vx-card-stats"><div class="vx-stat"><span class="vx-stat-l">Your shares</span><span class="vx-stat-v">${shares(v.shares)}</span></div><div class="vx-stat"><span class="vx-stat-l">Deposited</span><span class="vx-stat-v">${usdCompact(deposited)}</span></div>- <div class="vx-stat"><span class="vx-stat-l">Realized P&L</span><span class="vx-stat-v ${signClass(Number(realized))}">${Number(realized) >= 0 ? '+' : ''}${usdCompact(realized < 0n ? -realized : realized).replace('$', '$')}</span></div></div>- <div class="vx-card-foot"><span>${pctBps(v.performance_fee_bps)} fee</span><span>Tap to manage →</span></div>+ <div class="vx-card-foot"><span>${pctBps(v.performance_fee_bps)} fee</span><span class="vx-card-cta">Manage →</span></div></button>`;}@@ -207,6 +386,27 @@ function renderDetail(v, ledger) {const halted = v.status === 'paused';const closed = v.status === 'closing' || v.status === 'closed';+ // Real share-price history straight from the audit ledger (newest-first → chronological).+ const sparkPoints = (ledger || []).filter((e) => e.share_price_e6 != null).map((e) => ({ p: Number(BigInt(e.share_price_e6)) / ATOMICS })).reverse();+ const sparkTone = sparkPoints.length >= 2 ? (sparkPoints[sparkPoints.length - 1].p > sparkPoints[0].p ? 'pos' : sparkPoints[sparkPoints.length - 1].p < sparkPoints[0].p ? 'neg' : 'flat') : 'flat';+ const chartHtml = sparkPoints.length >= 2+ ? sparkline(sparkPoints, { tone: sparkTone })+ : '<div class="vx-spark-empty">Share-price history appears once the vault records its first trades.</div>';+ const inPositions = BigInt(nav.nav_atomics) - BigInt(nav.usdc_atomics);+ const gaugeHtml = drawdownGauge(nav.peak_share_price_e6, nav.share_price_e6, t.max_drawdown_bps);+ const distHtml = backerDist(v.backers);+ const navHero = `<div class="vx-navhero">+ <div class="vx-navhero-main">+ <span class="vx-navhero-l">Vault NAV · live</span>+ <span class="vx-navhero-v">${usd(nav.nav_atomics)}</span>+ <span class="vx-navhero-roi ${signClass(roi)}">${roi > 0 ? '▲' : roi < 0 ? '▼' : '•'} ${roiText(roi)} all-time</span>+ </div>+ <div class="vx-navhero-chart">+ <div class="vx-chart-head"><span class="vx-chart-t">Share price</span><span class="vx-chart-now">${priceE6(nav.share_price_e6)}</span></div>+ ${chartHtml}+ </div>+ </div>`;+const statusBanner = halted? `<div class="vx-banner vx-banner--warn">⚠ Trading halted${v.halt_reason === 'drawdown' ? ' by the drawdown circuit breaker' : v.halt_reason === 'owner_pause' ? ' by the owner' : ''}. Backers can still redeem.</div>`: closed ? '<div class="vx-banner">Vault is winding down, redemptions only.</div>' : '';@@ -252,11 +452,12 @@ function renderDetail(v, ledger) {</div></div>+ ${navHero}+<div class="vx-d-metrics">- <div class="vx-metric"><span class="vx-metric-l">Vault NAV</span><span class="vx-metric-v">${usd(nav.nav_atomics)}</span></div>- <div class="vx-metric"><span class="vx-metric-l">Share price</span><span class="vx-metric-v">${priceE6(nav.share_price_e6)}</span></div>- <div class="vx-metric"><span class="vx-metric-l">Return</span><span class="vx-metric-v ${signClass(roi)}">${roiText(roi)}</span></div><div class="vx-metric"><span class="vx-metric-l">Liquid USDC</span><span class="vx-metric-v">${usd(nav.usdc_atomics)}</span></div>+ <div class="vx-metric"><span class="vx-metric-l">In positions</span><span class="vx-metric-v">${usd(inPositions < 0n ? 0n : inPositions)}</span></div>+ <div class="vx-metric"><span class="vx-metric-l">Share price</span><span class="vx-metric-v">${priceE6(nav.share_price_e6)}</span></div><div class="vx-metric"><span class="vx-metric-l">Backers</span><span class="vx-metric-v">${v.backer_count}</span></div></div>@@ -280,8 +481,10 @@ function renderDetail(v, ledger) {<div><span>Per-backer cap</span><b>${t.per_backer_cap_atomics ? usd(t.per_backer_cap_atomics) : 'None'}</b></div><div><span>Network</span><b>${esc(v.network)}</b></div></div>+ ${gaugeHtml}<p class="vx-fineprint">Funds live in a dedicated, segregated wallet. Trading is hard-capped and halts automatically on a ${pctBps(t.max_drawdown_bps)} drawdown. Not investment advice; you can lose principal.</p></div>+ ${distHtml ? `<div class="vx-panel"><h3 class="vx-panel-h">Capital distribution <span class="vx-panel-sub">${v.backer_count} backer${v.backer_count === 1 ? '' : 's'}</span></h3>${distHtml}</div>` : ''}<div class="vx-panel"><h3 class="vx-panel-h">Audit trail</h3><ul class="vx-ledger" id="vx-ledger">${ledger.map(ledgerRow).join('') || '<li class="vx-muted">No activity yet.</li>'}</ul>@@ -521,6 +724,8 @@ function setTab(tab) {state.tab = tab;state.feed = [];$$('.vx-tab').forEach((b) => { const on = b.dataset.tab === tab; b.classList.toggle('is-active', on); b.setAttribute('aria-selected', on ? 'true' : 'false'); });+ const sortEl = $('.vx-sort');+ if (sortEl) sortEl.style.display = tab === 'mine' ? 'none' : '';loadFeed();}@@ -536,6 +741,7 @@ function stopPoll() { if (state.pollTimer) { clearInterval(state.pollTimer); stafunction wireGlobal() {$('#vx-open-cta')?.addEventListener('click', openVaultModal);+ $('#vx-sort')?.addEventListener('change', (e) => { state.sort = e.target.value; if (state.feed.length) renderFeed(); });$('#vx-back')?.addEventListener('click', backToFeed);$('#vx-open-form')?.addEventListener('submit', submitOpen);$$('.vx-tab').forEach((b) => b.addEventListener('click', () => setTab(b.dataset.tab)));diff --git a/src/viewer.js b/src/viewer.jsindex d7ddf4b9c..64d321744 100644--- a/src/viewer.js+++ b/src/viewer.js@@ -53,7 +53,12 @@ import { computeFramingExtent, computeFramingWidth } from './viewer/framing.js';import { LightProbeGrid } from './light-probe-grid.js';import { AnimationManager } from './animation-manager.js';import { computeBoundsTree, disposeBoundsTree, acceleratedRaycast } from 'three-mesh-bvh';-import { EffectComposer, RenderPass, BloomEffect, VignetteEffect, EffectPass } from 'postprocessing';+import {+ CinematicPipeline,+ CINEMATIC_PRESET_NAMES,+ CINEMATIC_DEFAULTS,+ DEFAULT_CINEMATIC_PRESET,+} from './viewer/cinematic.js';import { log } from './shared/log.js';// Install BVH-accelerated raycasting on Three.js prototypes. This must happen@@ -234,26 +239,19 @@ export class Viewer {this.el.appendChild(this.renderer.domElement);- // Post-processing: a single merged fullscreen pass (postprocessing lib)- // gives a subtle vignette that focuses attention on the avatar, plus mild- // bloom on bright specular highlights. The luminance threshold keeps normal- // surfaces from blooming. Screenshot capture bypasses this — see screenshot.js.- this._composer = new EffectComposer(this.renderer);- this._renderPass = new RenderPass(this.scene, this.activeCamera);- this._composer.addPass(this._renderPass);- // Gentle vignette — pulls focus to the avatar without darkening the small- // gallery thumbnails. Lower darkness + wider offset keeps the body lit.- const vignetteEffect = new VignetteEffect({ offset: 0.5, darkness: 0.22 });- const bloomEffect = new BloomEffect({- intensity: 0.6,- luminanceThreshold: 0.8,- luminanceSmoothing: 0.05,- mipmapBlur: true,+ // Post-processing: the CinematicPipeline owns the full post chain (SSAO,+ // depth-of-field, bloom, colour grade, chromatic aberration, film grain,+ // vignette) behind selectable presets. The default 'Studio' preset+ // reproduces the historical look exactly — subtle bloom + vignette, nothing+ // else — so gallery thumbnails and embeds are unchanged unless a user opts+ // into a richer look. Screenshot capture bypasses this — see screenshot.js.+ this.state.cinematicPreset = options.cinematicPreset ?? DEFAULT_CINEMATIC_PRESET;+ this._cinematic = new CinematicPipeline(this.renderer, this.scene, this.activeCamera, {+ width: el.clientWidth,+ height: el.clientHeight,+ preset: this.state.cinematicPreset,});- this._effectPass = new EffectPass(this.activeCamera, bloomEffect, vignetteEffect);- this._effectPass.renderToScreen = true;- this._composer.addPass(this._effectPass);- this._composer.setSize(el.clientWidth, el.clientHeight);+ this._composer = this._cinematic.composer;this.cameraCtrl = null;this.cameraFolder = null;@@ -439,6 +437,7 @@ export class Viewer {'autoRotate','exposure','environment',+ 'cinematicPreset',];let touched = false;for (const key of KEYS) {@@ -453,6 +452,7 @@ export class Viewer {this.updateEnvironment();this.updateDisplay();this.updateBackground();+ this._cinematic?.applyPreset(this.state.cinematicPreset);this.updateGUI?.();}}@@ -470,6 +470,7 @@ export class Viewer {autoRotate: this.state.autoRotate,exposure: this.state.exposure,environment: this.state.environment,+ cinematicPreset: this.state.cinematicPreset,};localStorage.setItem(this._prefsKey, JSON.stringify(snapshot));} catch {@@ -660,7 +661,7 @@ export class Viewer {}}- this.render();+ this.render(dt);this._needsRender = false;if (this._animating && this._visible && this._tabVisible && !this._disposed) {@@ -696,7 +697,7 @@ export class Viewer {};}- render() {+ render(deltaTime = 0) {// Additive bloom bleeds bright highlights into neighbouring pixels —// including the alpha-0 background. Over a transparent canvas that halo// composites onto the host page as a washed-out "box" around the avatar@@ -706,7 +707,7 @@ export class Viewer {if (this.state.transparentBg) {this.renderer.render(this.scene, this.activeCamera);} else {- this._composer.render();+ this._cinematic.render(deltaTime);}if (this.state.grid) {this._ensureAxesRenderer();@@ -1229,8 +1230,7 @@ export class Viewer {});}// Keep the post-processing passes pointed at the live camera.- if (this._renderPass) this._renderPass.mainCamera = this.activeCamera;- if (this._effectPass) this._effectPass.mainCamera = this.activeCamera;+ if (this._cinematic) this._cinematic.setCamera(this.activeCamera);this.invalidate();}@@ -1605,6 +1605,54 @@ export class Viewer {lightFolder.addColor(this.state, 'rimColor'),].forEach((ctrl) => ctrl.onChange(() => this.updateLights()));+ // Cinematic FX — selectable post-processing looks plus live per-effect+ // tuning. Preset picker rewrites every slider; sliders write straight into+ // the live pipeline so the canvas updates as you drag.+ const fxFolder = gui.addFolder('Cinematic FX');+ const fx = this._cinematic;+ const presetHolder = { preset: this.state.cinematicPreset };+ const fxCtrls = [];+ const syncFxCtrls = () => fxCtrls.forEach((c) => c.updateDisplay());++ fxFolder+ .add(presetHolder, 'preset', CINEMATIC_PRESET_NAMES)+ .name('preset')+ .onChange((name) => {+ fx.applyPreset(name);+ this.state.cinematicPreset = name;+ syncFxCtrls();+ this.invalidate();+ this.notifyScenePrefChange();+ });++ // Each slider mutates fx.params[key] in place, then re-pushes the whole+ // param set so the canvas updates live as you drag.+ const onFxChange = () => {+ fx.apply();+ this.invalidate();+ };+ const addFx = (key, min, max, step, label) => {+ const c = fxFolder.add(fx.params, key, min, max, step).name(label).onChange(onFxChange);+ fxCtrls.push(c);+ return c;+ };++ addFx('bloom', 0, 3, 0.01, 'bloom');+ addFx('bloomThreshold', 0, 1, 0.01, 'bloom threshold');+ addFx('vignette', 0, 1, 0.01, 'vignette');+ addFx('ssao', 0, 1, 1, 'ambient occlusion');+ addFx('ssaoIntensity', 0, 4, 0.05, 'AO strength');+ addFx('dof', 0, 1, 1, 'depth of field');+ addFx('dofFocusDistance', 0.2, 12, 0.1, 'focus distance');+ addFx('dofBokeh', 0, 6, 0.1, 'bokeh');+ addFx('saturation', -1, 1, 0.01, 'saturation');+ addFx('contrast', -1, 1, 0.01, 'contrast');+ addFx('brightness', -1, 1, 0.01, 'brightness');+ addFx('hue', 0, Math.PI * 2, 0.01, 'hue shift');+ addFx('chromaticAberration', 0, 0.01, 0.0001, 'chromatic ab.');+ addFx('grain', 0, 0.5, 0.01, 'film grain');+ fxFolder.close();+// Light Probe Grid controls.const probeFolder = gui.addFolder('Light Probes');probeFolder.add(this.state, 'probeNx', 1, 8, 1).name('grid X');@@ -2248,11 +2296,10 @@ export class Viewer {this.axesScene = null;this.axesCamera = null;- if (this._composer) {- this._composer.dispose();+ if (this._cinematic) {+ this._cinematic.dispose();+ this._cinematic = null;this._composer = null;- this._renderPass = null;- this._effectPass = null;}if (this.renderer) {diff --git a/src/viewer/cinematic.js b/src/viewer/cinematic.jsnew file mode 100644index 000000000..8ce0e828b--- /dev/null+++ b/src/viewer/cinematic.js@@ -0,0 +1,307 @@+/**+ * Cinematic post-processing pipeline for the avatar viewer.+ *+ * Wraps a single EffectComposer and owns the full post chain so the core+ * Viewer stays readable. The chain, in render order:+ *+ * RenderPass → NormalPass → DepthDownsamplingPass → SSAO → DoF → Bloom → Grade+ *+ * SSAO needs scene normals + depth (NormalPass / DepthDownsamplingPass), so it+ * lives in its own pass. Bloom and depth-of-field are *convolution* effects and+ * the postprocessing lib forbids merging two of them into one EffectPass — each+ * gets a dedicated pass. Everything cheap and per-pixel (colour grade, vignette,+ * chromatic aberration, film grain) is merged into one always-on final pass.+ *+ * Tone mapping stays on the WebGLRenderer (Viewer.updateLights sets+ * renderer.toneMapping) — we deliberately do NOT add a ToneMappingEffect here to+ * avoid double-tone-mapping the carefully-tuned Neutral default.+ *+ * Passes that aren't needed for the active preset are toggled off via `.enabled`+ * (zero GPU cost) rather than rebuilt, so switching presets is allocation-free.+ */++import { Vector2 } from 'three';+import {+ EffectComposer,+ RenderPass,+ EffectPass,+ NormalPass,+ DepthDownsamplingPass,+ BloomEffect,+ VignetteEffect,+ SSAOEffect,+ DepthOfFieldEffect,+ HueSaturationEffect,+ BrightnessContrastEffect,+ ChromaticAberrationEffect,+ NoiseEffect,+ BlendFunction,+} from 'postprocessing';++/**+ * Full parameter set. Presets are partial overrides of these defaults; any key a+ * preset omits resets to the value here, so presets are declarative and total.+ * @typedef {Object} CinematicParams+ */+export const CINEMATIC_DEFAULTS = Object.freeze({+ // Bloom — bleeds bright specular highlights. Threshold keeps matte surfaces flat.+ bloom: 0.6,+ bloomThreshold: 0.8,+ bloomSmoothing: 0.05,+ // Vignette — darkens the frame edges to pull focus onto the avatar.+ vignette: 0.22,+ vignetteOffset: 0.5,+ // Ambient occlusion — soft contact shadows in creases and where limbs meet.+ ssao: false,+ ssaoIntensity: 1.4,+ ssaoRadius: 0.18,+ // Depth of field — cinematic focus falloff. World-space focus distance in metres.+ dof: false,+ dofFocusDistance: 2.4,+ dofFocalLength: 0.08,+ dofBokeh: 2.2,+ // Colour grade — screen-space, applied after tone mapping.+ saturation: 0,+ brightness: 0,+ contrast: 0,+ hue: 0,+ // Chromatic aberration — RGB split at the lens edges. Subtle = lens realism.+ chromaticAberration: 0,+ // Film grain — animated luminance noise. Adds texture / hides banding.+ grain: 0,+});++/**+ * Named looks. Order here is the order shown in the picker. 'Studio' reproduces+ * the historical default (subtle bloom + vignette, no AO/DoF/grade) byte-for-byte+ * so existing gallery thumbnails and embeds are unchanged unless a user opts in.+ */+export const CINEMATIC_PRESETS = Object.freeze({+ Off: { bloom: 0, vignette: 0 },+ Studio: {},+ Cinematic: {+ bloom: 0.7,+ vignette: 0.34,+ ssao: true,+ ssaoIntensity: 1.3,+ dof: true,+ dofBokeh: 1.8,+ dofFocusDistance: 2.2,+ contrast: 0.09,+ saturation: 0.06,+ grain: 0.06,+ chromaticAberration: 0.0008,+ },+ Portrait: {+ bloom: 0.5,+ vignette: 0.3,+ ssao: true,+ ssaoIntensity: 1.0,+ dof: true,+ dofBokeh: 3.4,+ dofFocusDistance: 1.9,+ dofFocalLength: 0.05,+ saturation: 0.04,+ brightness: 0.03,+ },+ Vivid: {+ bloom: 0.8,+ vignette: 0.18,+ saturation: 0.26,+ contrast: 0.12,+ },+ Neon: {+ bloom: 1.4,+ bloomThreshold: 0.55,+ vignette: 0.32,+ saturation: 0.3,+ contrast: 0.06,+ chromaticAberration: 0.0016,+ },+ Noir: {+ bloom: 0.4,+ vignette: 0.5,+ saturation: -1,+ contrast: 0.26,+ grain: 0.13,+ },+});++export const CINEMATIC_PRESET_NAMES = Object.keys(CINEMATIC_PRESETS);+export const DEFAULT_CINEMATIC_PRESET = 'Studio';++export class CinematicPipeline {+ /**+ * @param {import('three').WebGLRenderer} renderer+ * @param {import('three').Scene} scene+ * @param {import('three').Camera} camera+ * @param {{ width: number, height: number, preset?: string }} opts+ */+ constructor(renderer, scene, camera, { width, height, preset = DEFAULT_CINEMATIC_PRESET } = {}) {+ this.renderer = renderer;+ this.scene = scene;+ this.camera = camera;+ this.params = { ...CINEMATIC_DEFAULTS };+ this.preset = CINEMATIC_PRESETS[preset] ? preset : DEFAULT_CINEMATIC_PRESET;++ this.composer = new EffectComposer(renderer);++ this._renderPass = new RenderPass(scene, camera);+ this.composer.addPass(this._renderPass);++ // Scene-space normals + downsampled normal/depth feed SSAO. Disabled with+ // SSAO so they cost nothing when ambient occlusion is off (the default).+ this._normalPass = new NormalPass(scene, camera);+ this._depthDownsamplingPass = new DepthDownsamplingPass({+ normalBuffer: this._normalPass.texture,+ resolutionScale: 0.5,+ });+ this.composer.addPass(this._normalPass);+ this.composer.addPass(this._depthDownsamplingPass);++ this._ssaoEffect = new SSAOEffect(camera, this._normalPass.texture, {+ blendFunction: BlendFunction.MULTIPLY,+ normalDepthBuffer: this._depthDownsamplingPass.texture,+ samples: 9,+ rings: 7,+ distanceThreshold: 0.97,+ distanceFalloff: 0.03,+ rangeThreshold: 0.0005,+ rangeFalloff: 0.001,+ luminanceInfluence: 0.7,+ radius: this.params.ssaoRadius,+ intensity: this.params.ssaoIntensity,+ bias: 0.025,+ fade: 0.01,+ });+ this._ssaoPass = new EffectPass(camera, this._ssaoEffect);+ this.composer.addPass(this._ssaoPass);++ this._dofEffect = new DepthOfFieldEffect(camera, {+ focusDistance: 0,+ focalLength: this.params.dofFocalLength,+ bokehScale: this.params.dofBokeh,+ });+ this._dofPass = new EffectPass(camera, this._dofEffect);+ this.composer.addPass(this._dofPass);++ this._bloomEffect = new BloomEffect({+ intensity: this.params.bloom,+ luminanceThreshold: this.params.bloomThreshold,+ luminanceSmoothing: this.params.bloomSmoothing,+ mipmapBlur: true,+ });+ this._bloomPass = new EffectPass(camera, this._bloomEffect);+ this.composer.addPass(this._bloomPass);++ // Always-on final pass: cheap per-pixel grade + lens character, composited+ // straight to screen.+ this._hueSat = new HueSaturationEffect({ hue: 0, saturation: 0 });+ this._brightContrast = new BrightnessContrastEffect({ brightness: 0, contrast: 0 });+ this._chromaticAberration = new ChromaticAberrationEffect({+ offset: new Vector2(0, 0),+ radialModulation: true,+ modulationOffset: 0.15,+ });+ this._noiseEffect = new NoiseEffect({ blendFunction: BlendFunction.OVERLAY, premultiply: true });+ this._noiseEffect.blendMode.opacity.value = 0;+ this._vignetteEffect = new VignetteEffect({+ offset: this.params.vignetteOffset,+ darkness: this.params.vignette,+ });+ this._finalPass = new EffectPass(+ camera,+ this._hueSat,+ this._brightContrast,+ this._chromaticAberration,+ this._noiseEffect,+ this._vignetteEffect,+ );+ this._finalPass.renderToScreen = true;+ this.composer.addPass(this._finalPass);++ this.composer.setSize(width, height);+ this.applyPreset(this.preset);+ }++ /** Apply a named preset: reset to defaults, layer the preset's overrides, push. */+ applyPreset(name) {+ const overrides = CINEMATIC_PRESETS[name];+ if (!overrides) return;+ this.preset = name;+ this.params = { ...CINEMATIC_DEFAULTS, ...overrides };+ this.apply();+ }++ /** Push the current `params` into every effect + pass-enable flag. */+ apply() {+ const p = this.params;++ this._bloomEffect.intensity = p.bloom;+ this._bloomEffect.luminanceMaterial.threshold = p.bloomThreshold;+ this._bloomEffect.luminanceMaterial.smoothing = p.bloomSmoothing;+ this._bloomPass.enabled = p.bloom > 0;++ this._vignetteEffect.darkness = p.vignette;+ this._vignetteEffect.offset = p.vignetteOffset;++ this._ssaoEffect.intensity = p.ssaoIntensity;+ this._ssaoEffect.radius = p.ssaoRadius;+ const ssaoOn = !!p.ssao;+ this._ssaoPass.enabled = ssaoOn;+ this._normalPass.enabled = ssaoOn;+ this._depthDownsamplingPass.enabled = ssaoOn;++ this._dofEffect.cocMaterial.focalLength = p.dofFocalLength;+ this._dofEffect.bokehScale = p.dofBokeh;+ this._setDofFocusDistance(p.dofFocusDistance);+ this._dofPass.enabled = !!p.dof;++ this._hueSat.saturation = p.saturation;+ this._hueSat.hue = p.hue;+ this._brightContrast.brightness = p.brightness;+ this._brightContrast.contrast = p.contrast;++ this._chromaticAberration.offset.set(p.chromaticAberration, p.chromaticAberration);+ this._noiseEffect.blendMode.opacity.value = p.grain;+ }++ /** Set one parameter and re-push. Keeps GUI bindings one-line. */+ set(key, value) {+ if (!(key in this.params)) return;+ this.params[key] = value;+ this.apply();+ }++ _setDofFocusDistance(metres) {+ // DoF focusDistance is normalised [0,1] over the camera near→far range.+ const cam = this.camera;+ const near = cam?.near ?? 0.01;+ const far = cam?.far ?? 1000;+ const norm = Math.min(1, Math.max(0, (metres - near) / (far - near)));+ if (this._dofEffect.cocMaterial) this._dofEffect.cocMaterial.focusDistance = norm;+ }++ setCamera(camera) {+ this.camera = camera;+ this._renderPass.mainCamera = camera;+ this._normalPass.mainCamera = camera;+ this._ssaoPass.mainCamera = camera;+ this._dofPass.mainCamera = camera;+ this._bloomPass.mainCamera = camera;+ this._finalPass.mainCamera = camera;+ this._setDofFocusDistance(this.params.dofFocusDistance);+ }++ setSize(width, height) {+ if (width > 0 && height > 0) this.composer.setSize(width, height);+ }++ render(deltaTime) {+ this.composer.render(deltaTime);+ }++ dispose() {+ this.composer.dispose();+ }+}