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: portfolio page overhaul, light-probe grid, home dashboard charts, sitemap/features expansion
nirholas36eb41ede659
diff --git a/CLAUDE.md b/CLAUDE.mdindex 00666cf14..f03501376 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -2,11 +2,29 @@These rules OVERRIDE defaults. Every agent in this workspace must follow them.+---++## Identity++You are building **three.ws** — a platform that competes with the best in the world. Every line of code, every UI element, every interaction should reflect that ambition. You are not a task-completing machine. You are a senior engineer and product thinker who happens to write code. Act like it.+## Prime directive-**Execute. Do not interview the user.** Pick the most reasonable interpretation and ship a complete feature. Questions waste the user's time.++**Execute. Do not interview the user.** Pick the most reasonable interpretation and ship a complete, polished feature. Questions waste the user's time.**Do what's proper and professional, always. Never take shortcuts. Always wire completely. Never use mocks or fake data. Always build real implementations and integrations and use real APIs.**+---++## Mindset: think like a founder, build like a craftsman++Before writing a single line of code, answer these questions internally:++1. **What is the user's user trying to accomplish?** Every feature exists for the end user. If you can't articulate who benefits and how, stop and think harder.+2. **What would the best version of this look like?** Not the fastest to implement — the best to use. Study how top platforms (Vercel, Linear, Stripe, Figma) solve similar problems. Match that bar.+3. **What's the second-order effect?** Does this feature interact with existing features? Does it create new possibilities? Wire those connections. A marketplace that doesn't link to agent profiles is half-built. A dashboard that doesn't surface actionable data is decoration.+4. **What would make someone screenshot this and share it?** That's the quality bar. If the answer is "nothing," raise the bar.+## Hard rules (non-negotiable)1. **No mocks. No fake data. No placeholders.** Use real APIs, real endpoints, real data. If credentials are missing, locate them in `.env`, `vercel env`, or ask once — then proceed.@@ -16,18 +34,71 @@ These rules OVERRIDE defaults. Every agent in this workspace must follow them.5. **No `setTimeout` fake-loading or fake progress bars.** Real async or nothing.6. **No fallback sample arrays** (e.g. `const sampleAgents = [...]`) shipped to production. Real fetch only.7. **Errors handled at boundaries** (network, user input). Internal code trusts itself.+8. **No "good enough."** If you notice something is mediocre while building, fix it now. Don't leave it for later. Later never comes.++## Engineering excellence++### Architecture+- **Read before you write.** Before adding code, understand the existing patterns. Use the same naming conventions, file organization, and abstractions already established. Consistency compounds.+- **Think in systems, not files.** A feature touches routing, data fetching, state management, UI rendering, and error handling. Trace the full path before you start. Wire every connection.+- **Eliminate dead paths.** If a button exists, it must work. If a link exists, it must go somewhere. If a state exists, there must be a way to reach it. Audit your own work for unreachable or broken paths.+- **Design data flow first.** Where does the data come from? How does it transform? Where does it render? Solve this before writing UI code.++### Code quality+- **Name things precisely.** `fetchAgentMetrics` not `getData`. `isWalletConnected` not `flag`. Names are documentation.+- **Small functions, clear boundaries.** Each function does one thing. If you need a comment to explain what a block does, extract it into a named function.+- **Delete aggressively.** Dead code, unused imports, vestigial features — remove them. Less code is better code.+- **Performance by default.** Lazy-load heavy modules. Debounce user input handlers. Paginate large lists. Use `will-change` and `transform` for animations. Don't ship jank.++### UI/UX standards+- **Every state is designed.** Loading, empty, error, populated, overflow — all of them. A page with no data should tell the user what to do next, not show a blank void.+- **Transitions matter.** Elements should enter and exit with intention. No jarring pops. CSS transitions on opacity and transform at minimum.+- **Responsive by default.** Test at 320px, 768px, and 1440px mentally. Use relative units. Flex/grid over fixed widths.+- **Accessibility is not optional.** Semantic HTML. ARIA labels on interactive elements. Keyboard navigation. Sufficient color contrast. Focus indicators.+- **Microinteractions signal quality.** Hover states, active states, focus rings, subtle animations on state change. These are not polish — they are the product.+- **Consistent spacing and typography.** Use the existing design tokens / CSS variables. If none exist, establish them and use them everywhere.++### Innovation standard+- **Don't just implement the feature. Improve the platform.** If you're adding a list view and notice the existing list views lack sorting — add sorting to yours and note the gap. Think about what features *should* exist adjacent to what you're building.+- **Cross-pollinate.** When building feature A, consider: does this data/capability unlock something in feature B? Wire the connection. The best platforms feel like everything is linked.+- **Surprise with quality.** Add the keyboard shortcut. Add the tooltip. Add the empty state illustration. Add the subtle gradient. The accumulation of small quality decisions is what separates great products from adequate ones.++---## Definition of doneA feature is NOT done until ALL of these are true:-- Code is written, wired into the UI, and reachable by the user.-- For UI work: dev server started (`npm run dev`), feature exercised in a real browser, no console errors, network tab shows real API calls succeeding.-- Edge cases handled (empty state, error state, loading state — all real, not faked).-- Existing tests still pass (`npm test`).-- `git diff` reviewed by you before claiming completion.++- [ ] Code is written, wired into the UI, and reachable by the user via navigation.+- [ ] For UI work: dev server started (`npm run dev`), feature exercised in a real browser.+- [ ] No console errors. No console warnings from your code.+- [ ] Network tab shows real API calls succeeding with real data.+- [ ] Every interactive element has hover, active, and focus states.+- [ ] Empty state is designed and helpful (tells user what to do, not just "no data").+- [ ] Error state is designed and actionable (tells user what went wrong and how to recover).+- [ ] Loading state uses real async indicators (skeleton screens preferred over spinners).+- [ ] Existing tests still pass (`npm test`).+- [ ] `git diff` reviewed by you before claiming completion — every changed line justified.+- [ ] You would be proud to demo this feature to a room of senior engineers.If you cannot verify a step, say so explicitly. Do not claim done.+---++## Self-review protocol++Before reporting any feature complete, run this internal audit:++1. **The lazy check:** Did I take any shortcuts? Did I leave anything half-wired? Did I use a hardcoded value where a dynamic one belongs?+2. **The user check:** If I were using this platform for the first time, would this feature make sense? Would I know how to find it? Would it feel polished?+3. **The integration check:** Does this feature connect to the rest of the platform? Can the user navigate to it and away from it naturally? Does it share data/state with related features?+4. **The edge case check:** What happens with 0 items? 1 item? 1000 items? A really long name? A network failure mid-operation? An expired session?+5. **The pride check:** Would I put this in my portfolio? If not, what's stopping me? Fix that.++Fix every issue found. Then report complete.++---+## Workflow- Use TodoWrite for any task with 3+ steps. Mark items complete in real time.diff --git a/package-lock.json b/package-lock.jsonindex 46ef17d45..2a2970b2c 100644--- a/package-lock.json+++ b/package-lock.json@@ -99,6 +99,7 @@"graphql": "^16.14.0","helius-sdk": "^2.2.2","jose": "^5.9.6",+ "lightweight-charts": "^5.2.0","livekit-client": "^2.19.0","livepeer": "^3.2.4","meshoptimizer": "^1.1.1",@@ -29482,6 +29483,12 @@"node": "> 0.1.90"}},+ "node_modules/fancy-canvas": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/fancy-canvas/-/fancy-canvas-2.1.0.tgz",+ "integrity": "sha512-nifxXJ95JNLFR2NgRV4/MxVP45G9909wJTEKz5fg/TZS20JJZA6hfgRVh/bC9bwl2zBtBNcYPjiBE4njQHVBwQ==",+ "license": "MIT"+ },"node_modules/fast-check": {"version": "4.8.0","resolved": "https://registry.npmjs.org/fast-check/-/fast-check-4.8.0.tgz",@@ -37004,6 +37011,15 @@"immediate": "~3.0.5"}},+ "node_modules/lightweight-charts": {+ "version": "5.2.0",+ "resolved": "https://registry.npmjs.org/lightweight-charts/-/lightweight-charts-5.2.0.tgz",+ "integrity": "sha512-ey3Vas8UhV06ni+LT9TA1nEe4y8So4Mi6CL/oarNHFMyTktz/xy8e8+oh04Q//eO3t6etvFXgayz2fClyFQb5w==",+ "license": "Apache-2.0",+ "dependencies": {+ "fancy-canvas": "2.1.0"+ }+ },"node_modules/lilconfig": {"version": "3.1.3","resolved": "https://registry.npmjs.org/lilconfig/-/lilconfig-3.1.3.tgz",diff --git a/package.json b/package.jsonindex 8a8c24074..deb66d17b 100644--- a/package.json+++ b/package.json@@ -183,6 +183,7 @@"graphql": "^16.14.0","helius-sdk": "^2.2.2","jose": "^5.9.6",+ "lightweight-charts": "^5.2.0","livekit-client": "^2.19.0","livepeer": "^3.2.4","meshoptimizer": "^1.1.1",diff --git a/public/features.json b/public/features.jsonindex b00ec123f..44daf53b1 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-05-27T06:38:13.963Z",+ "generated_at": "2026-05-27T10:06:15.054Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",@@ -220,9 +220,9 @@},{"path": "/brain",- "title": "Brain",- "description": "Multi-turn chat with Claude, GPT, DeepSeek, Qwen, and Llama. Conversation history, model switching, side-by-side comparison, real streaming with token metrics.",- "added": "2026-05-27",+ "title": "Multi-LLM Brain",+ "description": "Send one prompt to Claude, GPT, Qwen, ModelScope, and Groq simultaneously. Side-by-side streaming with latency and token stats.",+ "added": null,"auth": null,"indexable": true,"tags": []diff --git a/public/sitemap.xml b/public/sitemap.xmlindex 47141a9ff..9c6def654 100644--- a/public/sitemap.xml+++ b/public/sitemap.xml@@ -96,12 +96,7 @@<changefreq>weekly</changefreq><priority>0.7</priority></url>- <url>- <loc>https://three.ws/walkaround</loc>- <lastmod>2026-05-25</lastmod>- <changefreq>weekly</changefreq>- <priority>0.7</priority>- </url>+<url><loc>https://three.ws/brain</loc><lastmod>2026-05-25</lastmod>@@ -544,4 +539,124 @@<changefreq>yearly</changefreq><priority>0.6</priority></url>+ <url>+ <loc>https://three.ws/pricing</loc>+ <lastmod>2026-05-27</lastmod>+ <changefreq>weekly</changefreq>+ <priority>0.9</priority>+ </url>+ <url>+ <loc>https://three.ws/changelog</loc>+ <lastmod>2026-05-27</lastmod>+ <changefreq>weekly</changefreq>+ <priority>0.7</priority>+ </url>+ <url>+ <loc>https://three.ws/bazaar</loc>+ <lastmod>2026-05-27</lastmod>+ <changefreq>daily</changefreq>+ <priority>0.8</priority>+ </url>+ <url>+ <loc>https://three.ws/voice</loc>+ <lastmod>2026-05-27</lastmod>+ <changefreq>weekly</changefreq>+ <priority>0.7</priority>+ </url>+ <url>+ <loc>https://three.ws/club</loc>+ <lastmod>2026-05-27</lastmod>+ <changefreq>weekly</changefreq>+ <priority>0.6</priority>+ </url>+ <url>+ <loc>https://three.ws/launch-week</loc>+ <lastmod>2026-05-27</lastmod>+ <changefreq>monthly</changefreq>+ <priority>0.7</priority>+ </url>+ <url>+ <loc>https://three.ws/demos</loc>+ <lastmod>2026-05-27</lastmod>+ <changefreq>weekly</changefreq>+ <priority>0.8</priority>+ </url>+ <url>+ <loc>https://three.ws/demos/agents</loc>+ <lastmod>2026-05-27</lastmod>+ <changefreq>weekly</changefreq>+ <priority>0.7</priority>+ </url>+ <url>+ <loc>https://three.ws/demo/avatar-os</loc>+ <lastmod>2026-05-27</lastmod>+ <changefreq>monthly</changefreq>+ <priority>0.6</priority>+ </url>+ <url>+ <loc>https://three.ws/demo/coin</loc>+ <lastmod>2026-05-27</lastmod>+ <changefreq>monthly</changefreq>+ <priority>0.6</priority>+ </url>+ <url>+ <loc>https://three.ws/x402</loc>+ <lastmod>2026-05-27</lastmod>+ <changefreq>weekly</changefreq>+ <priority>0.7</priority>+ </url>+ <url>+ <loc>https://three.ws/characters</loc>+ <lastmod>2026-05-27</lastmod>+ <changefreq>daily</changefreq>+ <priority>0.7</priority>+ </url>+ <url>+ <loc>https://three.ws/mocap-studio</loc>+ <lastmod>2026-05-27</lastmod>+ <changefreq>weekly</changefreq>+ <priority>0.6</priority>+ </url>+ <url>+ <loc>https://three.ws/ar</loc>+ <lastmod>2026-05-27</lastmod>+ <changefreq>weekly</changefreq>+ <priority>0.6</priority>+ </url>+ <url>+ <loc>https://three.ws/xr</loc>+ <lastmod>2026-05-27</lastmod>+ <changefreq>weekly</changefreq>+ <priority>0.6</priority>+ </url>+ <url>+ <loc>https://three.ws/pose</loc>+ <lastmod>2026-05-27</lastmod>+ <changefreq>weekly</changefreq>+ <priority>0.5</priority>+ </url>+ <url>+ <loc>https://three.ws/agenc/embodied</loc>+ <lastmod>2026-05-27</lastmod>+ <changefreq>weekly</changefreq>+ <priority>0.6</priority>+ </url>+ <url>+ <loc>https://three.ws/agenc/room</loc>+ <lastmod>2026-05-27</lastmod>+ <changefreq>weekly</changefreq>+ <priority>0.6</priority>+ </url>+ <url>+ <loc>https://three.ws/aws</loc>+ <lastmod>2026-05-27</lastmod>+ <changefreq>monthly</changefreq>+ <priority>0.5</priority>+ </url>+ <url>+ <loc>https://three.ws/aws-marketplace/welcome</loc>+ <lastmod>2026-05-27</lastmod>+ <changefreq>monthly</changefreq>+ <priority>0.5</priority>+ </url></urlset>diff --git a/src/dashboard-next/pages/home.js b/src/dashboard-next/pages/home.jsindex 00ddfe634..dc05f5ef7 100644--- a/src/dashboard-next/pages/home.js+++ b/src/dashboard-next/pages/home.js@@ -522,11 +522,68 @@ function renderQuickActions(host, { avatars = [], agents = [] } = {}) {// ── Feature directory ─────────────────────────────────────────────────────+const DIR_ICONS = {+ '/create': '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="10" cy="7" r="3.5"/><path d="M16 18c0-3.3-2.7-6-6-6s-6 2.7-6 6"/><path d="M15 3v4M13 5h4"/></svg>',+ '/avatar-studio': '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="2" width="16" height="16" rx="2"/><circle cx="10" cy="8.5" r="2.5"/><path d="M6 15c0-2.2 1.8-4 4-4s4 1.8 4 4"/></svg>',+ '/brain': '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M10 3C7.5 3 5 5 5 8c0 1.5.5 2.5 1.2 3.3.5.5.8 1.2.8 2V15h6v-1.7c0-.8.3-1.5.8-2C14.5 10.5 15 9.5 15 8c0-3-2.5-5-5-5z"/><path d="M8 15v1a2 2 0 004 0v-1"/><path d="M8.5 8h3M8.5 10.5h3"/></svg>',+ '/voice': '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect x="7" y="2" width="6" height="10" rx="3"/><path d="M4 10a6 6 0 0012 0"/><path d="M10 16v2"/></svg>',+ '/mocap-studio': '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="10" cy="4" r="2"/><path d="M10 6v5M10 11l-3 5M10 11l3 5M7 9h6"/></svg>',+ '/gallery-picker': '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="3" width="16" height="14" rx="2"/><circle cx="7" cy="8" r="1.5"/><path d="M2 14l4-4 3 3 4-5 5 6"/></svg>',+ '/import-rpm': '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M10 2v12M6 10l4 4 4-4"/><path d="M3 14v3h14v-3"/></svg>',+ '/create/selfie': '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="3" width="16" height="14" rx="2"/><circle cx="10" cy="10" r="3"/><path d="M6 3V2M14 3V2"/></svg>',+ '/walk': '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="10" cy="4" r="2"/><path d="M10 6v4l-2 4M10 10l2 4M7 8l3 2 3-2"/></svg>',+ '/pose': '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="10" cy="4" r="2"/><path d="M10 6v5M6 8l4 2 4-2M8 11l-2 5M12 11l2 5"/></svg>',+ '/dashboard/agents': '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect x="5" y="2" width="10" height="10" rx="2"/><circle cx="8" cy="6.5" r="1"/><circle cx="12" cy="6.5" r="1"/><path d="M8 9h4M3 14l2-2h10l2 2v3a1 1 0 01-1 1H4a1 1 0 01-1-1v-3z"/></svg>',+ '/onchain': '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M8 12a4 4 0 005.7 0l2-2a4 4 0 00-5.7-5.7l-1 1"/><path d="M12 8a4 4 0 00-5.7 0l-2 2a4 4 0 005.7 5.7l1-1"/></svg>',+ '/reputation': '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M10 2l2.5 5 5.5.8-4 3.9.9 5.5L10 14.7l-4.9 2.5.9-5.5L2 7.8l5.5-.8L10 2z"/></svg>',+ '/strategy-lab': '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M7 2v5l-4 8h14l-4-8V2"/><path d="M5 18h10"/><path d="M7 2h6"/></svg>',+ '/profile': '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="10" cy="7" r="3.5"/><path d="M4 18c0-3.3 2.7-6 6-6s6 2.7 6 6"/></svg>',+ '/dashboard/widgets': '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="6" height="6" rx="1"/><rect x="11" y="3" width="6" height="6" rx="1"/><rect x="3" y="11" width="6" height="6" rx="1"/><rect x="11" y="11" width="6" height="6" rx="1"/></svg>',+ '/dashboard/api': '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M7 5l-4 5 4 5M13 5l4 5-4 5"/></svg>',+ '/marketplace': '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M3 7l1.5-4h11L17 7"/><path d="M3 7h14v10H3V7z"/><path d="M8 12h4v5H8v-5z"/></svg>',+ '/discover': '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="10" cy="10" r="7.5"/><path d="M10 2.5c-2 2.5-2 12.5 0 15M10 2.5c2 2.5 2 12.5 0 15M2.5 10h15"/></svg>',+ '/embed': '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M5 4h10a2 2 0 012 2v8a2 2 0 01-2 2H5a2 2 0 01-2-2V6a2 2 0 012-2z"/><path d="M8 9l-2 1.5L8 12M12 9l2 1.5L12 12"/></svg>',+ '/dashboard/monetize': '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="10" cy="10" r="7"/><path d="M10 6v8M7.5 8h4a1.5 1.5 0 010 3H8.5a1.5 1.5 0 000 3h4"/></svg>',+ '/dashboard/tokens': '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M10 2l2.5 5 5.5.8-4 3.9.9 5.5L10 14.7l-4.9 2.5.9-5.5L2 7.8l5.5-.8L10 2z"/></svg>',+ '/dashboard/portfolio': '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="7" width="16" height="11" rx="1.5"/><path d="M6 7V5a4 4 0 018 0v2"/><path d="M2 11h16"/></svg>',+ '/pump-live': '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="10" cy="10" r="2"/><path d="M6 6a5.5 5.5 0 000 8M14 6a5.5 5.5 0 010 8"/><path d="M3.5 3.5a9 9 0 000 13M16.5 3.5a9 9 0 010 13"/></svg>',+ '/launchpad': '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M10 2l-3 10h6L10 2z"/><path d="M7 12l-2 6M13 12l2 6M8 18h4"/></svg>',+ '/pay': '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="4" width="16" height="12" rx="2"/><path d="M2 8h16"/><path d="M6 13h3"/></svg>',+ '/pricing': '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M5 2h3v16H5zM12 6h3v12h-3z"/></svg>',+ '/pumpfun-trending': '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M3 17l4-6 3 3 7-11"/><path d="M14 3h3v3"/></svg>',+ '/pumpfun-search': '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="8.5" cy="8.5" r="5"/><path d="M15 15l2.5 2.5"/></svg>',+ '/demos': '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect x="2" y="3" width="16" height="14" rx="2"/><path d="M8 7.5v5l4.5-2.5z"/></svg>',+ '/tutorials': '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M2 4h5a3 3 0 013 3v11a2 2 0 00-2-2H2V4z"/><path d="M18 4h-5a3 3 0 00-3 3v11a2 2 0 012-2h6V4z"/></svg>',+ '/community': '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="7" cy="7" r="2.5"/><circle cx="14" cy="7" r="2"/><path d="M2 16c.8-2.8 2.8-4.2 5-4.2s4.2 1.4 5 4.2"/><path d="M13.5 11.8c1.5 0 3 1.2 3.5 3.2"/></svg>',+ '/features': '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M4 4h12v12H4z"/><path d="M4 10h12M10 4v12"/></svg>',+ '/playground': '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M4 6l4 4-4 4"/><path d="M10 14h6"/></svg>',+ '/avatar-sdk': '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="14" height="14" rx="2"/><path d="M7 8h6M7 11h4"/></svg>',+ '/xr': '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect x="1" y="5" width="18" height="10" rx="3"/><circle cx="7" cy="10" r="2.5"/><circle cx="13" cy="10" r="2.5"/></svg>',+ '/club': '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M10 2l1.5 3.5H16l-3 3 1.5 4L10 10l-4.5 2.5 1.5-4-3-3h4.5z"/><path d="M5 16h10"/><path d="M7 18h6"/></svg>',+ '/app': '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M2 4h16v12H2V4z"/><path d="M2 8h16"/><circle cx="4.5" cy="6" r=".6" fill="currentColor"/><circle cx="7" cy="6" r=".6" fill="currentColor"/></svg>',+ '/dashboard/account': '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="10" cy="7" r="3.5"/><path d="M4 18c0-3.3 2.7-6 6-6s6 2.7 6 6"/></svg>',+ '/dashboard/settings': '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="10" cy="10" r="2.5"/><path d="M10 2v2M10 16v2M2 10h2M16 10h2M4.2 4.2l1.4 1.4M14.4 14.4l1.4 1.4M4.2 15.8l1.4-1.4M14.4 5.6l1.4-1.4"/></svg>',+ '/dashboard/library': '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M4 4h4v12H4zM12 4h4v12h-4z"/><path d="M6 7h0M14 7h0"/></svg>',+ '/dashboard/avatars': '<svg viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="10" cy="7" r="3.2"/><path d="M3.5 17c1.1-3.4 3.8-5 6.5-5s5.4 1.6 6.5 5"/></svg>',+};++const CATEGORY_COLORS = {+ 'Create & Build': { accent: '139,92,246', label: '#a78bfa' },+ 'Agents & Identity': { accent: '59,130,246', label: '#60a5fa' },+ 'Distribute & Embed': { accent: '16,185,129', label: '#34d399' },+ 'Monetize & Trade': { accent: '245,158,11', label: '#fbbf24' },+ 'Learn & Explore': { accent: '236,72,153', label: '#f472b6' },+ 'Account & Settings': { accent: '148,163,184', label: '#94a3b8' },+ '3D & Immersive': { accent: '6,182,212', label: '#22d3ee' },+ 'Trading & Pump.fun': { accent: '249,115,22', label: '#fb923c' },+};+const DIRECTORY = [{group: 'Create & Build',items: [{ href: '/create', title: 'Create Avatar', sub: 'Snap a selfie — 3D agent in 60 seconds' },+ { href: '/create/selfie', title: 'Selfie Capture', sub: 'Camera-based avatar creation flow' },{ href: '/avatar-studio', title: 'Avatar Studio', sub: 'Full 3D editor with lighting and poses' },{ href: '/brain', title: 'Brain', sub: 'Persona builder, model playground, agent voice' },{ href: '/voice', title: 'Voice Lab', sub: 'Clone your voice for TTS and lip-sync' },@@ -561,12 +618,28 @@ const DIRECTORY = [{ href: '/dashboard/monetize', title: 'Monetize', sub: 'Revenue, subscriptions, and withdrawals' },{ href: '/dashboard/tokens', title: 'Tokens', sub: 'Launch tokens on Pump.fun with bonding curves' },{ href: '/dashboard/portfolio', title: 'Portfolio & NFTs', sub: 'Holdings, balances, and NFT collections' },- { href: '/pump-live', title: 'Pump.fun Live', sub: 'Real-time token feed and trending' },{ href: '/launchpad', title: 'Launchpad', sub: 'Token and project launchpad creator' },{ href: '/pay', title: 'Payments (x402)', sub: 'Payment hub and hosted checkout' },{ href: '/pricing', title: 'Pricing', sub: 'Platform plans and feature comparison' },],},+ {+ group: 'Trading & Pump.fun',+ items: [+ { href: '/pump-live', title: 'Pump.fun Live', sub: 'Real-time token feed and activity' },+ { href: '/pumpfun-trending', title: 'Trending Tokens', sub: 'Top trending tokens right now' },+ { href: '/pumpfun-search', title: 'Token Search', sub: 'Search for any Pump.fun token' },+ ],+ },+ {+ group: '3D & Immersive',+ items: [+ { href: '/app', title: '3D Viewer', sub: 'Interactive 3D agent editor and viewer' },+ { href: '/walk', title: 'Walk Viewer', sub: 'Walk and animation preview' },+ { href: '/pose', title: 'Pose Editor', sub: 'Pose and position your avatar' },+ { href: '/xr', title: 'XR / AR', sub: 'Augmented and extended reality views' },+ ],+ },{group: 'Learn & Explore',items: [@@ -576,6 +649,7 @@ const DIRECTORY = [{ href: '/features', title: 'Features', sub: 'Platform capabilities overview' },{ href: '/playground', title: 'Playground', sub: 'Experiment with agents interactively' },{ href: '/avatar-sdk', title: 'Avatar SDK', sub: 'Developer docs for avatar integration' },+ { href: '/club', title: 'Club / VIP', sub: 'Exclusive membership and perks' },],},{@@ -589,35 +663,129 @@ const DIRECTORY = [},];+const RECENTS_KEY = 'twx_recent_pages';+const PINS_KEY = 'twx_pinned_pages';+const MAX_RECENTS = 6;++function getRecents() {+ try { return JSON.parse(localStorage.getItem(RECENTS_KEY)) || []; } catch { return []; }+}++function getPins() {+ try { return JSON.parse(localStorage.getItem(PINS_KEY)) || []; } catch { return []; }+}++function togglePin(href) {+ const pins = getPins();+ const idx = pins.indexOf(href);+ if (idx >= 0) pins.splice(idx, 1);+ else pins.unshift(href);+ localStorage.setItem(PINS_KEY, JSON.stringify(pins.slice(0, 12)));+ return pins;+}++function allItems() {+ return DIRECTORY.flatMap((s) => s.items);+}++function lookupItem(href) {+ return allItems().find((i) => i.href === href);+}++function trackVisit(href) {+ const recents = getRecents().filter((r) => r !== href);+ recents.unshift(href);+ localStorage.setItem(RECENTS_KEY, JSON.stringify(recents.slice(0, 20)));+}+function renderDirectory(host) {const DIR_COLLAPSED_KEY = 'twx_dir_collapsed';const collapsed = localStorage.getItem(DIR_COLLAPSED_KEY) === '1';+ const pins = getPins();+ const recents = getRecents().filter((r) => !pins.includes(r)).slice(0, MAX_RECENTS);+ const hasPersonalized = pins.length > 0 || recents.length > 0;++ const dirItemHtml = (item, section) => {+ const icon = DIR_ICONS[item.href] || '';+ const cc = CATEGORY_COLORS[section.group] || CATEGORY_COLORS['Account & Settings'];+ const isPinned = getPins().includes(item.href);+ return `+ <a href="${item.href}" class="dnx-dir-item" data-href="${esc(item.href)}" data-title="${esc(item.title)}" data-sub="${esc(item.sub)}">+ <div class="dnx-dir-item-row">+ <span class="dnx-dir-item-icon" style="background:rgba(${cc.accent},0.1);color:${cc.label}">${icon}</span>+ <div class="dnx-dir-item-text">+ <div class="dnx-dir-item-title">${esc(item.title)}</div>+ <div class="dnx-dir-item-sub">${esc(item.sub)}</div>+ </div>+ <button class="dnx-dir-pin${isPinned ? ' is-pinned' : ''}" data-pin="${esc(item.href)}" title="${isPinned ? 'Unpin' : 'Pin to shortcuts'}" aria-label="${isPinned ? 'Unpin' : 'Pin'}">+ <svg viewBox="0 0 14 14" width="12" height="12" fill="${isPinned ? 'currentColor' : 'none'}" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round"><path d="M5 1l1 4-3 2v1h4.5L8 13l.5-5H13v-1l-3-2 1-4z"/></svg>+ </button>+ </div>+ </a>+ `;+ };++ const personalizedHtml = hasPersonalized ? `+ ${pins.length ? `+ <div class="dnx-dir-section">+ <div class="dnx-dir-group-label" style="color:#fbbf24">Pinned</div>+ <div class="dnx-dir-items">+ ${pins.map((href) => {+ const item = lookupItem(href);+ if (!item) return '';+ const section = DIRECTORY.find((s) => s.items.includes(item)) || DIRECTORY[0];+ return dirItemHtml(item, section);+ }).join('')}+ </div>+ </div>+ ` : ''}+ ${recents.length ? `+ <div class="dnx-dir-section">+ <div class="dnx-dir-group-label" style="color:#94a3b8">Recently Visited</div>+ <div class="dnx-dir-items">+ ${recents.map((href) => {+ const item = lookupItem(href);+ if (!item) return '';+ const section = DIRECTORY.find((s) => s.items.includes(item)) || DIRECTORY[0];+ return dirItemHtml(item, section);+ }).join('')}+ </div>+ </div>+ ` : ''}+ <div class="dnx-dir-divider"></div>+ ` : '';host.innerHTML = `<div class="dn-panel dnx-dir">- <button class="dnx-dir-head" aria-expanded="${!collapsed}" data-action="dir-toggle">- <div>- <div class="dn-panel-title" style="margin:0 0 2px">All Features & Pages</div>- <div class="dn-panel-sub" style="margin:0">Every tool, page, and feature on three.ws — all in one place.</div>+ <div class="dnx-dir-head-bar">+ <button class="dnx-dir-head-toggle" aria-expanded="${!collapsed}" data-action="dir-toggle">+ <div>+ <div class="dn-panel-title" style="margin:0 0 2px">All Features & Pages</div>+ <div class="dn-panel-sub" style="margin:0">Every tool, page, and feature on three.ws — all in one place.</div>+ </div>+ <span class="dnx-dir-chevron" aria-hidden="true">+ <svg viewBox="0 0 12 12" width="12" height="12" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M3 4.5l3 3 3-3"/></svg>+ </span>+ </button>+ <div class="dnx-dir-search-wrap">+ <svg class="dnx-dir-search-icon" viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"><circle cx="7" cy="7" r="4.5"/><path d="M13 13l-3-3"/></svg>+ <input type="text" class="dnx-dir-search" placeholder="Filter pages..." data-action="dir-search" autocomplete="off" spellcheck="false" /></div>- <span class="dnx-dir-chevron" aria-hidden="true">- <svg viewBox="0 0 12 12" width="12" height="12" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"><path d="M3 4.5l3 3 3-3"/></svg>- </span>- </button>- <div class="dnx-dir-body${collapsed ? ' is-collapsed' : ''}">- ${DIRECTORY.map((section) => `- <div class="dnx-dir-section">- <div class="dnx-dir-group-label">${esc(section.group)}</div>- <div class="dnx-dir-items">- ${section.items.map((item) => `- <a href="${item.href}" class="dnx-dir-item">- <div class="dnx-dir-item-title">${esc(item.title)}</div>- <div class="dnx-dir-item-sub">${esc(item.sub)}</div>- </a>- `).join('')}+ </div>+ <div class="dnx-dir-body${collapsed ? ' is-collapsed' : ''}" data-slot="dir-body">+ ${personalizedHtml}+ ${DIRECTORY.map((section) => {+ const cc = CATEGORY_COLORS[section.group] || CATEGORY_COLORS['Account & Settings'];+ return `+ <div class="dnx-dir-section" data-group="${esc(section.group)}">+ <div class="dnx-dir-group-label" style="color:${cc.label}">${esc(section.group)}</div>+ <div class="dnx-dir-items">+ ${section.items.map((item) => dirItemHtml(item, section)).join('')}+ </div></div>- </div>- `).join('')}+ `;+ }).join('')}+ <div class="dnx-dir-no-results" style="display:none">No pages match your search.</div></div></div>`;@@ -629,6 +797,64 @@ function renderDirectory(host) {btn.setAttribute('aria-expanded', !isCollapsed);localStorage.setItem(DIR_COLLAPSED_KEY, isCollapsed ? '1' : '0');});++ const searchInput = host.querySelector('[data-action="dir-search"]');+ searchInput.addEventListener('input', () => {+ const q = searchInput.value.trim().toLowerCase();+ const body = host.querySelector('[data-slot="dir-body"]');+ const items = body.querySelectorAll('.dnx-dir-item');+ const sections = body.querySelectorAll('.dnx-dir-section');+ const noResults = body.querySelector('.dnx-dir-no-results');+ let visibleCount = 0;++ if (!q) {+ items.forEach((el) => el.style.display = '');+ sections.forEach((el) => el.style.display = '');+ noResults.style.display = 'none';+ if (body.classList.contains('is-collapsed')) {+ body.classList.remove('is-collapsed');+ host.querySelector('[data-action="dir-toggle"]').setAttribute('aria-expanded', 'true');+ }+ return;+ }++ if (body.classList.contains('is-collapsed')) {+ body.classList.remove('is-collapsed');+ host.querySelector('[data-action="dir-toggle"]').setAttribute('aria-expanded', 'true');+ }++ items.forEach((el) => {+ const title = (el.dataset.title || '').toLowerCase();+ const sub = (el.dataset.sub || '').toLowerCase();+ const href = (el.dataset.href || '').toLowerCase();+ const match = title.includes(q) || sub.includes(q) || href.includes(q);+ el.style.display = match ? '' : 'none';+ if (match) visibleCount++;+ });++ sections.forEach((el) => {+ const hasVisible = [...el.querySelectorAll('.dnx-dir-item')].some((i) => i.style.display !== 'none');+ el.style.display = hasVisible ? '' : 'none';+ });++ noResults.style.display = visibleCount === 0 ? '' : 'none';+ });++ host.addEventListener('click', (e) => {+ const pinBtn = e.target.closest('.dnx-dir-pin');+ if (pinBtn) {+ e.preventDefault();+ e.stopPropagation();+ const href = pinBtn.dataset.pin;+ togglePin(href);+ renderDirectory(host);+ return;+ }+ const link = e.target.closest('.dnx-dir-item');+ if (link && link.dataset.href) {+ trackVisit(link.dataset.href);+ }+ });}// ── Sparkline ─────────────────────────────────────────────────────────────@@ -932,36 +1158,59 @@ function injectStyles() {/* ── Feature directory ── */.dnx-dir { padding: 0; overflow: hidden; }- .dnx-dir-head {+ .dnx-dir-head-bar {+ display: flex; flex-direction: column; gap: 0;+ }+ .dnx-dir-head-toggle {display: flex; justify-content: space-between; align-items: center;- width: 100%; padding: 18px 20px;+ width: 100%; padding: 18px 20px 10px;background: none; border: none; cursor: pointer;text-align: left; color: inherit;transition: background 0.12s ease;}- .dnx-dir-head:hover { background: rgba(255,255,255,0.03); }+ .dnx-dir-head-toggle:hover { background: rgba(255,255,255,0.03); }.dnx-dir-chevron {color: var(--nxt-ink-fade);transition: transform 0.2s ease;display: grid; place-items: center;flex-shrink: 0;}- .dnx-dir-head[aria-expanded="false"] .dnx-dir-chevron { transform: rotate(-90deg); }+ .dnx-dir-head-toggle[aria-expanded="false"] .dnx-dir-chevron { transform: rotate(-90deg); }+ .dnx-dir-search-wrap {+ position: relative; padding: 0 20px 12px;+ }+ .dnx-dir-search-icon {+ position: absolute; left: 32px; top: 50%; transform: translateY(calc(-50% - 6px));+ color: var(--nxt-ink-fade); pointer-events: none;+ }+ .dnx-dir-search {+ width: 100%; padding: 9px 12px 9px 34px;+ background: rgba(255,255,255,0.04); border: 1px solid var(--nxt-stroke);+ border-radius: 8px; color: var(--nxt-ink); font-size: 13px;+ outline: none; transition: border-color 0.14s ease, background 0.14s ease;+ }+ .dnx-dir-search::placeholder { color: var(--nxt-ink-fade); }+ .dnx-dir-search:focus {+ border-color: var(--nxt-stroke-strong);+ background: rgba(255,255,255,0.06);+ }.dnx-dir-body {padding: 0 20px 20px;display: flex; flex-direction: column; gap: 20px;- transition: max-height 0.3s ease, opacity 0.2s ease, padding 0.3s ease;- max-height: 3000px; opacity: 1; overflow: hidden;+ transition: max-height 0.35s ease, opacity 0.2s ease, padding 0.3s ease;+ max-height: 5000px; opacity: 1; overflow: hidden;}.dnx-dir-body.is-collapsed {max-height: 0; opacity: 0;padding-top: 0; padding-bottom: 0;}+ .dnx-dir-divider {+ height: 1px; background: var(--nxt-stroke); margin: 4px 0;+ }.dnx-dir-section {}.dnx-dir-group-label {font-size: 11px; font-weight: 700;letter-spacing: 0.08em; text-transform: uppercase;- color: var(--nxt-ink-fade);margin-bottom: 8px; padding-left: 2px;}.dnx-dir-items {@@ -972,26 +1221,62 @@ function injectStyles() {@media (max-width: 920px) { .dnx-dir-items { grid-template-columns: repeat(2, minmax(0, 1fr)); } }@media (max-width: 560px) { .dnx-dir-items { grid-template-columns: 1fr; } }.dnx-dir-item {- display: block; padding: 12px 14px;+ display: block; padding: 10px 12px;border-radius: 10px; border: 1px solid var(--nxt-stroke);background: rgba(255,255,255,0.015);transition: border-color 0.14s ease, background 0.14s ease, transform 0.14s ease;- cursor: pointer;+ cursor: pointer; position: relative;}.dnx-dir-item:hover {border-color: var(--nxt-stroke-strong);background: rgba(255,255,255,0.04);transform: translateY(-1px);}+ .dnx-dir-item-row {+ display: flex; align-items: flex-start; gap: 10px;+ }+ .dnx-dir-item-icon {+ width: 32px; height: 32px; border-radius: 8px;+ display: grid; place-items: center; flex-shrink: 0;+ transition: transform 0.14s ease;+ }+ .dnx-dir-item-icon svg { width: 16px; height: 16px; }+ .dnx-dir-item:hover .dnx-dir-item-icon { transform: scale(1.08); }+ .dnx-dir-item-text { flex: 1; min-width: 0; }.dnx-dir-item-title {- font-size: 13.5px; font-weight: 550;- color: var(--nxt-ink); margin-bottom: 2px;+ font-size: 13px; font-weight: 550;+ color: var(--nxt-ink); margin-bottom: 1px;+ line-height: 1.3;}.dnx-dir-item-sub {- font-size: 12px; color: var(--nxt-ink-fade);+ font-size: 11.5px; color: var(--nxt-ink-fade);line-height: 1.35;overflow: hidden; text-overflow: ellipsis; white-space: nowrap;}+ .dnx-dir-pin {+ background: none; border: none; cursor: pointer;+ color: var(--nxt-ink-fade); padding: 4px;+ border-radius: 6px; flex-shrink: 0;+ opacity: 0; transition: opacity 0.12s ease, color 0.12s ease, background 0.12s ease;+ display: grid; place-items: center;+ margin-top: 2px;+ }+ .dnx-dir-item:hover .dnx-dir-pin,+ .dnx-dir-pin.is-pinned { opacity: 1; }+ .dnx-dir-pin.is-pinned { color: #fbbf24; }+ .dnx-dir-pin:hover { background: rgba(255,255,255,0.08); color: var(--nxt-ink); }+ .dnx-dir-pin.is-pinned:hover { color: #fbbf24; }+ .dnx-dir-no-results {+ text-align: center; padding: 32px 16px;+ color: var(--nxt-ink-fade); font-size: 13px;+ }+ @media (max-width: 560px) {+ .dnx-dir-item-icon { width: 28px; height: 28px; border-radius: 7px; }+ .dnx-dir-item-icon svg { width: 14px; height: 14px; }+ .dnx-dir-search-wrap { padding: 0 14px 10px; }+ .dnx-dir-head-toggle { padding: 14px 14px 8px; }+ .dnx-dir-body { padding: 0 14px 14px; }+ }`;const tag = document.createElement('style');tag.id = 'dnx-home-styles';diff --git a/src/dashboard-next/pages/portfolio.js b/src/dashboard-next/pages/portfolio.jsindex 524447065..df04b6510 100644--- a/src/dashboard-next/pages/portfolio.js+++ b/src/dashboard-next/pages/portfolio.js@@ -1,63 +1,74 @@-// dashboard-next — Portfolio & NFTs page.-//-// Shows the user's on-chain holdings across linked wallets:-// • Token balances (SOL, USDC, custom tokens via /api/wallet/balances)-// • Avatar NFTs the user has minted-// • Agent badges / credentials-// • Pump.fun tokens launched by the user's agents-//-// Real endpoints:-// GET /api/wallet/balances { balances: [{ symbol, amount, usd_value, chain, mint }] }-// GET /api/auth/wallets { wallets: [...] }-// GET /api/avatars { avatars: [...] } (filter nft_mint set)-// GET /api/agents { agents: [...] }-import { mountShell } from '../shell.js';-import { requireUser, get, esc, relTime, formatUsdc, ApiError } from '../api.js';+import { requireUser, get, post, esc, relTime, formatUsdc, ApiError } from '../api.js';+import { createChart, AreaSeries, LineSeries } from 'lightweight-charts';const MONO = `'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, monospace`;-const CHAIN_LABELS = {- solana: 'Solana',- base: 'Base',- ethereum: 'Ethereum',- polygon: 'Polygon',- optimism: 'Optimism',+const CHAIN_LABELS = { solana: 'Solana', evm: 'Ethereum', base: 'Base', polygon: 'Polygon' };+const CHAIN_EXPLORER = {+ solana: (addr) => `https://solscan.io/account/${addr}`,+ evm: (addr) => `https://etherscan.io/address/${addr}`,+};+const TX_EXPLORER = {+ solana: (hash) => `https://solscan.io/tx/${hash}`,+ evm: (hash) => `https://etherscan.io/tx/${hash}`,};+let _chartInstance = null;+let _assetChartInstance = null;+(async function boot() {try {const main = await mountShell();- await requireUser();+ const me = await requireUser();main.innerHTML = `- <h1 class="dn-h1">Portfolio & NFTs</h1>- <p class="dn-h1-sub">Your on-chain holdings — tokens, avatars minted as NFTs, and agent credentials.</p>+ <h1 class="dn-h1">Portfolio</h1>+ <p class="dn-h1-sub">Live balances, holdings, and market data across your agent wallets.</p><div data-slot="content" style="display:flex;flex-direction:column;gap:16px">- ${Array.from({ length: 3 }).map(() => `<div class="dn-skeleton" style="height:120px;border-radius:12px"></div>`).join('')}+ ${skel(3)}</div>`;-const host = main.querySelector('[data-slot="content"]');- const [balancesResp, walletsResp, avatarsResp, agentsResp] = await Promise.all([- safeGet('/api/wallet/balances'),- safeGet('/api/auth/wallets'),- safeGet('/api/avatars?limit=100'),- safeGet('/api/agents'),+ injectStyles();++ const [summaryRes, historyRes] = await Promise.allSettled([+ get('/api/portfolio/summary?snapshot=1'),+ get('/api/portfolio/history?days=90'),]);- const balances = balancesResp?.balances || balancesResp?.tokens || [];- const wallets = walletsResp?.wallets || [];- const avatars = (avatarsResp?.avatars || []).filter((av) => av.nft_mint || av.nft_address || av.token_id);- const agents = agentsResp?.agents || [];- const pumpAgents = agents.filter((a) => a.meta?.pumpfun?.mint || a.meta?.token?.mint || a.meta?.token?.ca);+ const summary = summaryRes.status === 'fulfilled' ? summaryRes.value : null;+ const history = historyRes.status === 'fulfilled' ? historyRes.value : null;host.innerHTML = '';- host.appendChild(renderBalances(balances, wallets));- host.appendChild(renderNftAvatars(avatars));- host.appendChild(renderPumpTokens(pumpAgents));- host.appendChild(renderAgentBadges(agents));++ if (!summary || !summary.wallets?.length) {+ host.innerHTML = `+ <div class="dn-panel pf-empty-hero">+ <div class="pf-empty-icon">+ <svg viewBox="0 0 40 40" width="40" height="40" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">+ <rect x="4" y="14" width="32" height="22" rx="3"/>+ <path d="M12 14V10a8 8 0 0116 0v4"/>+ <path d="M4 22h32"/>+ <circle cx="28" cy="25" r="2.5"/>+ </svg>+ </div>+ <h3>No agent wallets</h3>+ <p>Create an agent with a wallet to start tracking your portfolio.</p>+ <a class="dn-btn primary" href="/dashboard/agents">Create agent →</a>+ </div>`;+ return;+ }++ host.appendChild(renderHero(summary, history));+ host.appendChild(renderWallets(summary));+ host.appendChild(renderHoldings(summary));++ const detailPanel = document.createElement('div');+ detailPanel.setAttribute('data-slot', 'asset-detail');+ host.appendChild(detailPanel);+} catch (err) {if (err instanceof ApiError && err.status === 401) {location.href = `/login?return=${encodeURIComponent(location.pathname)}`;@@ -67,251 +78,785 @@ const CHAIN_LABELS = {}})();-async function safeGet(url) {- try { return await get(url); }- catch { return null; }+function skel(n) {+ return Array.from({ length: n }, () =>+ `<div class="dn-skeleton" style="height:120px;border-radius:12px"></div>`,+ ).join('');}-// ── Token balances ─────────────────────────────────────────────────────────+// ── Hero: total value + portfolio history chart ────────────────────────────-function renderBalances(balances, wallets) {+function renderHero(summary, history) {const panel = document.createElement('div');- panel.className = 'dn-panel';+ panel.className = 'dn-panel pf-hero';++ const totalUsd = summary.total_usd || 0;+ const points = history?.points || [];++ const prevUsd = points.length >= 2 ? points[0].usd : totalUsd;+ const changeUsd = totalUsd - prevUsd;+ const changePct = prevUsd > 0 ? (changeUsd / prevUsd) * 100 : 0;+ const changeClass = changeUsd >= 0 ? 'pf-gain' : 'pf-loss';+ const changeSign = changeUsd >= 0 ? '+' : '';+panel.innerHTML = `- <div style="display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap;margin-bottom:14px">- <div>- <div class="dn-panel-title">Token balances</div>- <div class="dn-panel-sub" style="margin:2px 0 0">Across ${wallets.length} linked wallet${wallets.length === 1 ? '' : 's'}.</div>+ <div class="pf-hero-top">+ <div class="pf-hero-value-wrap">+ <div class="pf-hero-label">Total portfolio value</div>+ <div class="pf-hero-value">$${fmtUsd(totalUsd)}</div>+ <div class="pf-hero-change ${changeClass}">+ ${changeSign}$${fmtUsd(Math.abs(changeUsd))}+ <span>(${changeSign}${changePct.toFixed(2)}%)</span>+ <span class="pf-hero-period">90d</span>+ </div>+ </div>+ <div class="pf-hero-meta">+ <div class="pf-hero-meta-item">+ <span class="pf-hero-meta-label">Wallets</span>+ <span class="pf-hero-meta-val">${summary.wallets.length}</span>+ </div>+ <div class="pf-hero-meta-item">+ <span class="pf-hero-meta-label">Tokens</span>+ <span class="pf-hero-meta-val">${countTokens(summary)}</span>+ </div>+ <div class="pf-hero-meta-item">+ <span class="pf-hero-meta-label">Updated</span>+ <span class="pf-hero-meta-val">${relTime(summary.captured_at)}</span>+ </div></div>- <a class="dn-btn" href="/dashboard/account">Manage wallets →</a></div>- <div data-slot="balances"></div>+ <div class="pf-chart-wrap" data-slot="chart"></div>`;- const host = panel.querySelector('[data-slot="balances"]');-- if (!wallets.length) {- host.innerHTML = `- <div class="dn-empty">- <h3>No wallets linked</h3>- <p>Link a wallet to see your token balances.</p>- <a class="dn-btn primary" href="/dashboard/account">Link wallet →</a>- </div>`;- return panel;- }-- if (!balances.length) {- host.innerHTML = `- <div class="dn-empty">- <h3>No balances found</h3>- <p>Your linked wallets appear to be empty, or balance data is temporarily unavailable.</p>- </div>`;- return panel;- }-- const totalUsd = balances.reduce((s, b) => s + (Number(b.usd_value) || 0), 0);+ requestAnimationFrame(() => {+ const chartEl = panel.querySelector('[data-slot="chart"]');+ if (!chartEl || points.length < 2) {+ if (chartEl) chartEl.innerHTML = '<div class="pf-chart-empty">Not enough history for a chart yet. Check back after a day or two.</div>';+ return;+ }+ renderPortfolioChart(chartEl, points);+ });- host.innerHTML = `- <div style="font-size:28px;font-weight:700;letter-spacing:-0.02em;margin-bottom:16px">- $${totalUsd.toFixed(2)}- <span style="font-size:13px;font-weight:400;color:var(--nxt-ink-dim)">estimated total</span>- </div>- <div style="overflow-x:auto">- <table style="width:100%;border-collapse:collapse;font-size:13px">- <thead>- <tr style="text-align:left;color:var(--nxt-ink-fade);border-bottom:1px solid var(--nxt-stroke)">- <th style="padding:8px 10px;font-weight:500">Token</th>- <th style="padding:8px 10px;font-weight:500">Chain</th>- <th style="padding:8px 10px;font-weight:500;text-align:right">Balance</th>- <th style="padding:8px 10px;font-weight:500;text-align:right">USD Value</th>- </tr>- </thead>- <tbody>- ${balances.map((b) => `- <tr style="border-bottom:1px solid var(--nxt-stroke)">- <td style="padding:10px">- <div style="font-weight:600">${esc(b.symbol || b.name || 'Unknown')}</div>- ${b.mint ? `<div style="font-family:${MONO};font-size:11px;color:var(--nxt-ink-fade)">${esc(b.mint.slice(0, 12))}…</div>` : ''}- </td>- <td style="padding:10px;color:var(--nxt-ink-dim)">${esc(CHAIN_LABELS[b.chain] || b.chain || '—')}</td>- <td style="padding:10px;text-align:right;font-variant-numeric:tabular-nums">- ${esc(formatAmount(b))}- </td>- <td style="padding:10px;text-align:right;font-variant-numeric:tabular-nums;color:var(--nxt-ink-dim)">- ${b.usd_value != null ? `$${Number(b.usd_value).toFixed(2)}` : '—'}- </td>- </tr>- `).join('')}- </tbody>- </table>- </div>- `;return panel;}-function formatAmount(b) {- const n = Number(b.amount) || 0;- if (n === 0) return '0';- if (n >= 1_000_000) return (n / 1_000_000).toFixed(2) + 'M';- if (n >= 1_000) return (n / 1_000).toFixed(2) + 'K';- if (n < 0.0001) return n.toExponential(2);- return n.toFixed(n < 0.01 ? 6 : 4);+function renderPortfolioChart(container, points) {+ if (_chartInstance) { _chartInstance.remove(); _chartInstance = null; }++ const chart = createChart(container, {+ width: container.clientWidth,+ height: 220,+ layout: {+ background: { color: 'transparent' },+ textColor: '#888888',+ fontFamily: `'JetBrains Mono', monospace`,+ fontSize: 11,+ },+ grid: {+ vertLines: { color: 'rgba(255,255,255,0.04)' },+ horzLines: { color: 'rgba(255,255,255,0.04)' },+ },+ rightPriceScale: {+ borderColor: 'rgba(255,255,255,0.08)',+ },+ timeScale: {+ borderColor: 'rgba(255,255,255,0.08)',+ timeVisible: false,+ },+ crosshair: {+ horzLine: { color: 'rgba(255,255,255,0.15)', style: 2 },+ vertLine: { color: 'rgba(255,255,255,0.15)', style: 2 },+ },+ });+ _chartInstance = chart;++ const isPositive = points.length >= 2 && points[points.length - 1].usd >= points[0].usd;+ const lineColor = isPositive ? '#4ade80' : '#f87171';+ const topColor = isPositive ? 'rgba(74, 222, 128, 0.25)' : 'rgba(248, 113, 113, 0.25)';++ const series = chart.addSeries(AreaSeries, {+ lineColor,+ topColor,+ bottomColor: 'transparent',+ lineWidth: 2,+ priceFormat: { type: 'custom', formatter: (v) => '$' + fmtUsd(v) },+ });++ const data = points.map((p) => ({+ time: p.t.slice(0, 10),+ value: p.usd,+ }));++ const deduped = [];+ const seen = new Set();+ for (const d of data) {+ if (!seen.has(d.time)) { seen.add(d.time); deduped.push(d); }+ }+ series.setData(deduped);+ chart.timeScale().fitContent();++ const ro = new ResizeObserver(() => {+ chart.applyOptions({ width: container.clientWidth });+ });+ ro.observe(container);}-// ── NFT Avatars ────────────────────────────────────────────────────────────+// ── Wallet cards ──────────────────────────────────────────────────────────-function renderNftAvatars(nftAvatars) {+function renderWallets(summary) {const panel = document.createElement('div');panel.className = 'dn-panel';panel.innerHTML = `- <div style="display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap;margin-bottom:14px">+ <div class="pf-section-head"><div>- <div class="dn-panel-title">Avatar NFTs</div>- <div class="dn-panel-sub" style="margin:2px 0 0">Avatars you've minted on-chain as NFTs.</div>+ <div class="dn-panel-title">Agent wallets</div>+ <div class="dn-panel-sub" style="margin:2px 0 0">${summary.wallets.length} wallet${summary.wallets.length === 1 ? '' : 's'} across ${new Set(summary.wallets.map(w => w.chain)).size} chain${new Set(summary.wallets.map(w => w.chain)).size === 1 ? '' : 's'}.</div></div>- <a class="dn-btn" href="/dashboard/avatars">All avatars →</a></div>- <div data-slot="nfts"></div>+ <div class="pf-wallets" data-slot="wallets"></div>`;- const host = panel.querySelector('[data-slot="nfts"]');- if (!nftAvatars.length) {- host.innerHTML = `- <div class="dn-empty">- <h3>No avatar NFTs</h3>- <p>Mint an avatar as an NFT to anchor your 3D identity on-chain.</p>- <a class="dn-btn primary" href="/dashboard/avatars">View avatars →</a>- </div>`;- return panel;+ const grid = panel.querySelector('[data-slot="wallets"]');+ for (const w of summary.wallets) {+ const card = document.createElement('div');+ card.className = 'pf-wallet-card';+ const addr = w.address || '';+ const short = addr.slice(0, 6) + '…' + addr.slice(-4);+ const chainLabel = CHAIN_LABELS[w.chain] || w.chain;+ const explorerUrl = (CHAIN_EXPLORER[w.chain] || (() => '#'))(addr);+ const tokenCount = (w.tokens || []).length;+ const snsLabel = w.sns ? `<span class="pf-wallet-sns">${esc(w.sns)}</span>` : '';++ card.innerHTML = `+ <div class="pf-wallet-top">+ <div class="pf-wallet-chain-badge">${chainLabel}</div>+ <a href="${explorerUrl}" target="_blank" rel="noopener" class="pf-wallet-explorer" title="View on explorer">↗</a>+ </div>+ <div class="pf-wallet-name">${esc(w.agent_name)}${snsLabel}</div>+ <div class="pf-wallet-addr" style="font-family:${MONO}">${short}</div>+ <div class="pf-wallet-bal">+ <div class="pf-wallet-bal-main">$${fmtUsd(w.usd)}</div>+ <div class="pf-wallet-bal-sub">${esc(fmtAmount(w.native?.amount))} ${esc(w.native?.symbol || '')} + ${tokenCount} token${tokenCount === 1 ? '' : 's'}</div>+ </div>+ ${!w.ok && w.error ? `<div class="pf-wallet-err">${esc(w.error)}</div>` : ''}+ `;+ grid.appendChild(card);}-- host.innerHTML = `- <div style="display:grid;grid-template-columns:repeat(auto-fill,minmax(180px,1fr));gap:12px">- ${nftAvatars.map((av) => `- <div style="border:1px solid var(--nxt-stroke);border-radius:10px;overflow:hidden;background:rgba(255,255,255,0.02)">- ${av.thumbnail_url- ? `<img src="${esc(av.thumbnail_url)}" alt="${esc(av.name || '')}" style="width:100%;aspect-ratio:1;object-fit:cover" loading="lazy" />`- : `<div style="width:100%;aspect-ratio:1;background:rgba(200,202,208,0.10);display:grid;place-items:center;color:var(--nxt-ink-fade);font-size:32px">🎭</div>`- }- <div style="padding:10px">- <div style="font-weight:600;font-size:13px;margin-bottom:4px">${esc(av.name || 'Untitled')}</div>- <div style="font-family:${MONO};font-size:11px;color:var(--nxt-ink-fade)">${esc((av.nft_mint || av.nft_address || av.token_id || '').slice(0, 14))}…</div>- <a href="/avatar-artifact?id=${encodeURIComponent(av.id)}" target="_blank" rel="noopener"- style="display:inline-block;margin-top:8px;font-size:11.5px;color:var(--nxt-accent)">View NFT ↗</a>- </div>- </div>- `).join('')}- </div>- `;return panel;}-// ── Pump.fun tokens ────────────────────────────────────────────────────────+// ── Holdings table ────────────────────────────────────────────────────────-function renderPumpTokens(pumpAgents) {+function renderHoldings(summary) {const panel = document.createElement('div');panel.className = 'dn-panel';++ const allTokens = [];+ for (const w of summary.wallets) {+ if (w.native && w.native.amount > 0) {+ allTokens.push({+ chain: w.chain,+ id: 'native',+ symbol: w.native.symbol,+ name: w.native.name || w.native.symbol,+ amount: w.native.amount,+ price: w.native.price || 0,+ change24h: w.native.change24h,+ usd: w.native.usd || 0,+ logo: null,+ agent: w.agent_name,+ address: w.address,+ });+ }+ for (const t of (w.tokens || [])) {+ allTokens.push({+ chain: w.chain,+ id: t.mint || t.contract || '',+ symbol: t.symbol,+ name: t.name || t.symbol,+ amount: t.amount,+ price: t.price || 0,+ change24h: t.change24h,+ usd: t.usd || 0,+ logo: t.logo,+ agent: w.agent_name,+ address: w.address,+ });+ }+ }++ const merged = mergeHoldings(allTokens);+ merged.sort((a, b) => (b.usd || 0) - (a.usd || 0));+panel.innerHTML = `- <div style="display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap;margin-bottom:14px">+ <div class="pf-section-head"><div>- <div class="dn-panel-title">Pump.fun tokens</div>- <div class="dn-panel-sub" style="margin:2px 0 0">Tokens your agents launched on Pump.fun.</div>+ <div class="dn-panel-title">Holdings</div>+ <div class="dn-panel-sub" style="margin:2px 0 0">${merged.length} asset${merged.length === 1 ? '' : 's'} across all wallets.</div></div>- <a class="dn-btn" href="/dashboard/tokens">Token dashboard →</a></div>- <div data-slot="tokens"></div>+ <div data-slot="holdings"></div>`;- const host = panel.querySelector('[data-slot="tokens"]');- if (!pumpAgents.length) {+ const host = panel.querySelector('[data-slot="holdings"]');++ if (!merged.length) {host.innerHTML = `<div class="dn-empty">- <h3>No tokens launched</h3>- <p>Launch a Pump.fun token from any of your agents to see it here.</p>- <a class="dn-btn primary" href="/dashboard/tokens">Token dashboard →</a>+ <h3>No holdings</h3>+ <p>Your agent wallets are empty. Fund a wallet or launch a token to see holdings here.</p></div>`;return panel;}host.innerHTML = `<div style="overflow-x:auto">- <table style="width:100%;border-collapse:collapse;font-size:13px">+ <table class="pf-table"><thead>- <tr style="text-align:left;color:var(--nxt-ink-fade);border-bottom:1px solid var(--nxt-stroke)">- <th style="padding:8px 10px;font-weight:500">Agent / Token</th>- <th style="padding:8px 10px;font-weight:500;text-align:right">Holders</th>- <th style="padding:8px 10px;font-weight:500"></th>+ <tr>+ <th class="pf-th" style="min-width:180px">Asset</th>+ <th class="pf-th right">Price</th>+ <th class="pf-th right">24h</th>+ <th class="pf-th right">Balance</th>+ <th class="pf-th right">Value</th>+ <th class="pf-th right">Allocation</th></tr></thead>- <tbody>- ${pumpAgents.map((a) => {- const meta = a.meta?.pumpfun || a.meta?.token || {};- const mint = meta.mint || meta.address || meta.ca || '';- const ticker = meta.symbol || meta.ticker || a.name || 'TOKEN';- const holders = meta.holders ?? '—';- return `- <tr style="border-bottom:1px solid var(--nxt-stroke)">- <td style="padding:10px">- <div style="font-weight:600">$${esc(String(ticker).toUpperCase())}</div>- <div style="color:var(--nxt-ink-dim);font-size:12px">${esc(a.name || a.display_name || '')}</div>- </td>- <td style="padding:10px;text-align:right;color:var(--nxt-ink-dim)">${esc(String(holders))}</td>- <td style="padding:10px;text-align:right">- ${mint ? `<a href="https://pump.fun/coin/${encodeURIComponent(mint)}" target="_blank" rel="noopener" style="color:var(--nxt-accent);font-size:12px">View ↗</a>` : ''}- </td>- </tr>- `;- }).join('')}- </tbody>+ <tbody data-slot="rows"></tbody></table></div>`;++ const totalUsd = merged.reduce((s, t) => s + (t.usd || 0), 0);+ const tbody = host.querySelector('[data-slot="rows"]');++ for (const t of merged) {+ const tr = document.createElement('tr');+ tr.className = 'pf-row';+ tr.style.cursor = 'pointer';+ tr.setAttribute('data-chain', t.chain);+ tr.setAttribute('data-id', t.id);++ const pct = totalUsd > 0 ? ((t.usd / totalUsd) * 100) : 0;+ const changeHtml = renderChange(t.change24h);+ const logoHtml = t.logo+ ? `<img src="${esc(t.logo)}" alt="" class="pf-token-logo" loading="lazy" />`+ : `<div class="pf-token-logo pf-token-logo-placeholder">${esc((t.symbol || '?')[0])}</div>`;++ tr.innerHTML = `+ <td class="pf-td">+ <div class="pf-token-cell">+ ${logoHtml}+ <div>+ <div class="pf-token-symbol">${esc(t.symbol)}</div>+ <div class="pf-token-name">${esc(t.name)}</div>+ </div>+ </div>+ </td>+ <td class="pf-td right" style="font-variant-numeric:tabular-nums">$${fmtPrice(t.price)}</td>+ <td class="pf-td right">${changeHtml}</td>+ <td class="pf-td right" style="font-variant-numeric:tabular-nums">${esc(fmtAmount(t.amount))}</td>+ <td class="pf-td right" style="font-variant-numeric:tabular-nums;font-weight:600">$${fmtUsd(t.usd)}</td>+ <td class="pf-td right">+ <div class="pf-alloc-bar-wrap">+ <div class="pf-alloc-bar" style="width:${Math.min(100, pct).toFixed(1)}%"></div>+ <span class="pf-alloc-label">${pct.toFixed(1)}%</span>+ </div>+ </td>+ `;++ tr.addEventListener('click', () => openAssetDetail(t));+ tbody.appendChild(tr);+ }+return panel;}-// ── Agent badges ───────────────────────────────────────────────────────────+function mergeHoldings(tokens) {+ const map = new Map();+ for (const t of tokens) {+ const key = `${t.chain}:${t.id}`;+ if (map.has(key)) {+ const existing = map.get(key);+ existing.amount += t.amount;+ existing.usd += t.usd;+ if (!existing.price && t.price) existing.price = t.price;+ if (existing.change24h == null && t.change24h != null) existing.change24h = t.change24h;+ if (!existing.logo && t.logo) existing.logo = t.logo;+ } else {+ map.set(key, { ...t });+ }+ }+ return [...map.values()];+}++// ── Asset detail panel ────────────────────────────────────────────────────++async function openAssetDetail(token) {+ const host = document.querySelector('[data-slot="asset-detail"]');+ if (!host) return;-function renderAgentBadges(agents) {+ host.innerHTML = `+ <div class="dn-panel pf-detail" id="pf-detail">+ <div class="pf-detail-loading">+ <div class="pf-detail-header">+ <button class="pf-detail-close" aria-label="Close" data-action="close-detail">×</button>+ </div>+ ${skel(1)}+ </div>+ </div>+ `;+ host.querySelector('[data-action="close-detail"]').addEventListener('click', () => { host.innerHTML = ''; });+ host.scrollIntoView({ behavior: 'smooth', block: 'nearest' });++ try {+ const data = await get(`/api/portfolio/asset?chain=${encodeURIComponent(token.chain)}&id=${encodeURIComponent(token.id)}&days=30`);+ renderAssetDetail(host, data);+ } catch (err) {+ host.querySelector('.pf-detail-loading').innerHTML = `+ <div class="pf-detail-header">+ <button class="pf-detail-close" data-action="close-detail">×</button>+ </div>+ <div style="color:var(--nxt-danger);padding:16px">Failed to load asset data: ${esc(err.message)}</div>+ `;+ host.querySelector('[data-action="close-detail"]').addEventListener('click', () => { host.innerHTML = ''; });+ }+}++function renderAssetDetail(host, data) {const panel = document.createElement('div');- panel.className = 'dn-panel';+ panel.className = 'dn-panel pf-detail';+ panel.id = 'pf-detail';- const registered = agents.filter((a) => a.onchain_id || a.erc8004_id || a.chain_id);+ const market = data.market || {};+ const symbol = data.symbol || '?';+ const logoHtml = data.logo+ ? `<img src="${esc(data.logo)}" alt="" class="pf-detail-logo" />`+ : `<div class="pf-detail-logo pf-token-logo-placeholder" style="width:40px;height:40px;font-size:18px">${esc(symbol[0])}</div>`;++ const changeHtml = renderChange(market.change_24h_pct);+ const hasChart = data.chart?.points?.length >= 2;panel.innerHTML = `- <div style="display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap;margin-bottom:14px">- <div>- <div class="dn-panel-title">On-chain agent registry</div>- <div class="dn-panel-sub" style="margin:2px 0 0">Agents registered under ERC-8004.</div>+ <div class="pf-detail-header">+ <div class="pf-detail-title-row">+ ${logoHtml}+ <div>+ <div class="pf-detail-symbol">${esc(symbol)}</div>+ <div class="pf-detail-name">${esc(market.name || data.name || symbol)}</div>+ </div></div>- <a class="dn-btn" href="/onchain" target="_blank" rel="noopener">Browse registry ↗</a>+ <button class="pf-detail-close" data-action="close-detail">×</button></div>- <div data-slot="badges"></div>++ <div class="pf-detail-price-row">+ <div class="pf-detail-price">$${fmtPrice(data.unit_price_usd)}</div>+ ${changeHtml}+ </div>++ ${hasChart ? '<div class="pf-asset-chart-wrap" data-slot="asset-chart"></div>' : ''}++ <div class="pf-detail-stats">+ ${statItem('Your balance', `${fmtAmount(data.total_amount)} ${esc(symbol)}`)}+ ${statItem('Your value', `$${fmtUsd(data.total_usd)}`)}+ ${market.market_cap_usd ? statItem('Market cap', `$${fmtCompact(market.market_cap_usd)}`) : ''}+ ${market.total_volume_usd ? statItem('24h volume', `$${fmtCompact(market.total_volume_usd)}`) : ''}+ ${market.high_24h_usd ? statItem('24h high', `$${fmtPrice(market.high_24h_usd)}`) : ''}+ ${market.low_24h_usd ? statItem('24h low', `$${fmtPrice(market.low_24h_usd)}`) : ''}+ ${market.change_7d_pct != null ? statItem('7d change', renderChangeText(market.change_7d_pct)) : ''}+ ${market.change_30d_pct != null ? statItem('30d change', renderChangeText(market.change_30d_pct)) : ''}+ ${market.ath_usd ? statItem('All-time high', `$${fmtPrice(market.ath_usd)}`) : ''}+ </div>++ ${data.holdings?.length ? renderHoldingsBreakdown(data) : ''}++ ${renderSendForm(data)}++ ${market.description ? `<div class="pf-detail-desc">${esc(market.description)}</div>` : ''}`;- const host = panel.querySelector('[data-slot="badges"]');- if (!registered.length) {- host.innerHTML = `- <div class="dn-empty">- <h3>No on-chain registrations</h3>- <p>Register an agent on-chain to give it an immutable ERC-8004 identity.</p>- <a class="dn-btn primary" href="/onchain" target="_blank" rel="noopener">ERC-8004 registry ↗</a>- </div>`;- return panel;+ host.innerHTML = '';+ host.appendChild(panel);++ host.querySelector('[data-action="close-detail"]').addEventListener('click', () => { host.innerHTML = ''; });++ if (hasChart) {+ requestAnimationFrame(() => {+ const chartEl = panel.querySelector('[data-slot="asset-chart"]');+ if (chartEl) renderAssetChart(chartEl, data.chart.points);+ });}- host.innerHTML = `- <div style="display:flex;flex-direction:column;gap:8px">- ${registered.map((a) => `- <div style="display:flex;align-items:center;gap:12px;padding:10px;border:1px solid var(--nxt-stroke);border-radius:8px">- <div style="flex:1">- <div style="font-weight:600;font-size:13.5px">${esc(a.name || a.display_name || 'Agent')}</div>- <div style="font-family:${MONO};font-size:11.5px;color:var(--nxt-ink-fade)">${esc(a.onchain_id || a.erc8004_id || '')}</div>+ const form = panel.querySelector('[data-slot="send-form"]');+ if (form) mountSendForm(form, data);+}++function renderAssetChart(container, points) {+ if (_assetChartInstance) { _assetChartInstance.remove(); _assetChartInstance = null; }++ const chart = createChart(container, {+ width: container.clientWidth,+ height: 180,+ layout: {+ background: { color: 'transparent' },+ textColor: '#888888',+ fontFamily: `'JetBrains Mono', monospace`,+ fontSize: 10,+ },+ grid: {+ vertLines: { color: 'rgba(255,255,255,0.03)' },+ horzLines: { color: 'rgba(255,255,255,0.03)' },+ },+ rightPriceScale: { borderColor: 'rgba(255,255,255,0.06)' },+ timeScale: { borderColor: 'rgba(255,255,255,0.06)', timeVisible: true },+ crosshair: {+ horzLine: { color: 'rgba(255,255,255,0.12)', style: 2 },+ vertLine: { color: 'rgba(255,255,255,0.12)', style: 2 },+ },+ });+ _assetChartInstance = chart;++ const isPositive = points.length >= 2 && points[points.length - 1].price >= points[0].price;+ const lineColor = isPositive ? '#4ade80' : '#f87171';++ const series = chart.addSeries(LineSeries, {+ color: lineColor,+ lineWidth: 2,+ priceFormat: { type: 'custom', formatter: (v) => '$' + fmtPrice(v) },+ });++ const data = points.map((p) => {+ const d = new Date(p.t);+ return { time: Math.floor(d.getTime() / 1000), value: p.price };+ });+ series.setData(data);+ chart.timeScale().fitContent();++ const ro = new ResizeObserver(() => chart.applyOptions({ width: container.clientWidth }));+ ro.observe(container);+}++function renderHoldingsBreakdown(data) {+ if (!data.holdings?.length) return '';+ return `+ <div class="pf-detail-section-label">Held in</div>+ <div class="pf-detail-holdings">+ ${data.holdings.map((h) => `+ <div class="pf-detail-holding-row">+ <div>+ <span class="pf-detail-holding-agent">${esc(h.agent_name)}</span>+ <span class="pf-detail-holding-addr" style="font-family:${MONO}">${h.address.slice(0, 6)}…${h.address.slice(-4)}</span>+ </div>+ <div class="pf-detail-holding-val">+ <span>${fmtAmount(h.amount)}</span>+ <span style="color:var(--nxt-ink-dim)">$${fmtUsd(h.usd)}</span></div>- <span class="dn-tag success">registered</span>- <a href="/onchain?agent=${encodeURIComponent(a.id)}" target="_blank" rel="noopener" style="font-size:12px;color:var(--nxt-accent)">View ↗</a></div>`).join('')}</div>`;- return panel;+}++function renderSendForm(data) {+ if (!data.holdings?.length) return '';+ return `+ <div class="pf-detail-section-label">Send ${esc(data.symbol)}</div>+ <form class="pf-send-form" data-slot="send-form">+ <select name="agent_id" class="pf-input">+ ${data.holdings.map((h) => `+ <option value="${esc(h.agent_id)}" data-chain="${esc(data.chain)}" data-max="${h.amount}">+ ${esc(h.agent_name)} (${fmtAmount(h.amount)} ${esc(data.symbol)})+ </option>+ `).join('')}+ </select>+ <input type="text" name="recipient" class="pf-input" placeholder="Recipient address or .sol name" required autocomplete="off" />+ <div class="pf-send-amount-row">+ <input type="text" name="amount" class="pf-input" placeholder="Amount" required pattern="^(\\d+(\\.\\d*)?|\\.\\d+)$" inputmode="decimal" />+ <button type="button" class="dn-btn pf-max-btn" data-action="max">MAX</button>+ </div>+ <div class="pf-send-actions">+ <button type="submit" class="dn-btn primary">Send</button>+ <div class="pf-send-status" data-slot="send-status"></div>+ </div>+ </form>+ `;+}++function mountSendForm(form, data) {+ const maxBtn = form.querySelector('[data-action="max"]');+ const amountInput = form.querySelector('[name="amount"]');+ const agentSelect = form.querySelector('[name="agent_id"]');+ const statusEl = form.querySelector('[data-slot="send-status"]');++ maxBtn.addEventListener('click', () => {+ const opt = agentSelect.selectedOptions[0];+ amountInput.value = opt?.dataset.max || '0';+ });++ form.addEventListener('submit', async (e) => {+ e.preventDefault();+ const submitBtn = form.querySelector('[type="submit"]');+ submitBtn.disabled = true;+ submitBtn.textContent = 'Sending…';+ statusEl.innerHTML = '';++ const agentId = agentSelect.value;+ const recipient = form.querySelector('[name="recipient"]').value.trim();+ const amount = amountInput.value.trim();+ const chain = agentSelect.selectedOptions[0]?.dataset.chain || data.chain;+ const asset = data.is_native ? 'native' : data.id;++ try {+ const result = await post('/api/portfolio/send', {+ agent_id: agentId,+ chain,+ asset,+ recipient,+ amount,+ });+ const explorerUrl = (TX_EXPLORER[chain] || (() => '#'))(result.tx_hash);+ statusEl.innerHTML = `<span class="pf-send-ok">Sent. <a href="${explorerUrl}" target="_blank" rel="noopener">View tx ↗</a></span>`;+ } catch (err) {+ statusEl.innerHTML = `<span class="pf-send-err">${esc(err.message)}</span>`;+ } finally {+ submitBtn.disabled = false;+ submitBtn.textContent = 'Send';+ }+ });+}++// ── Formatting helpers ────────────────────────────────────────────────────++function fmtUsd(n) {+ n = Number(n) || 0;+ if (n >= 1_000_000) return (n / 1_000_000).toFixed(2) + 'M';+ if (n >= 1_000) return n.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });+ return n.toFixed(2);+}++function fmtPrice(n) {+ n = Number(n) || 0;+ if (n === 0) return '0.00';+ if (n >= 1) return n.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });+ if (n >= 0.01) return n.toFixed(4);+ if (n >= 0.0001) return n.toFixed(6);+ return n.toExponential(2);+}++function fmtAmount(n) {+ n = Number(n) || 0;+ if (n === 0) return '0';+ if (n >= 1_000_000) return (n / 1_000_000).toFixed(2) + 'M';+ if (n >= 1_000) return n.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 4 });+ if (n < 0.0001) return n.toExponential(2);+ return n.toFixed(n < 0.01 ? 6 : 4);+}++function fmtCompact(n) {+ n = Number(n) || 0;+ if (n >= 1e12) return (n / 1e12).toFixed(2) + 'T';+ if (n >= 1e9) return (n / 1e9).toFixed(2) + 'B';+ if (n >= 1e6) return (n / 1e6).toFixed(2) + 'M';+ if (n >= 1e3) return (n / 1e3).toFixed(1) + 'K';+ return n.toFixed(2);+}++function renderChange(pct) {+ if (pct == null) return '<span class="pf-change pf-neutral">—</span>';+ const n = Number(pct);+ const cls = n > 0 ? 'pf-gain' : n < 0 ? 'pf-loss' : 'pf-neutral';+ const sign = n > 0 ? '+' : '';+ return `<span class="pf-change ${cls}">${sign}${n.toFixed(2)}%</span>`;+}++function renderChangeText(pct) {+ if (pct == null) return '—';+ const n = Number(pct);+ const sign = n > 0 ? '+' : '';+ return `${sign}${n.toFixed(2)}%`;+}++function statItem(label, value) {+ return `+ <div class="pf-stat">+ <span class="pf-stat-label">${label}</span>+ <span class="pf-stat-value">${value}</span>+ </div>+ `;+}++function countTokens(summary) {+ let n = 0;+ for (const w of summary.wallets) {+ if (w.native?.amount > 0) n++;+ n += (w.tokens || []).length;+ }+ return n;+}++// ── Styles ────────────────────────────────────────────────────────────────++function injectStyles() {+ if (document.getElementById('pf-styles')) return;+ const css = `+ .pf-hero { padding: 0; overflow: hidden; }+ .pf-hero-top { padding: 24px 24px 0; display: flex; justify-content: space-between; align-items: flex-start; gap: 16px; flex-wrap: wrap; }+ .pf-hero-label { font-size: 12px; font-weight: 600; letter-spacing: 0.06em; text-transform: uppercase; color: var(--nxt-ink-fade); margin-bottom: 6px; }+ .pf-hero-value { font-size: 36px; font-weight: 700; letter-spacing: -0.03em; color: var(--nxt-ink); line-height: 1.1; }+ .pf-hero-change { font-size: 14px; font-weight: 500; margin-top: 6px; display: flex; align-items: center; gap: 6px; }+ .pf-hero-change span { font-size: 12px; color: var(--nxt-ink-dim); }+ .pf-hero-period { font-size: 11px; color: var(--nxt-ink-fade); }+ .pf-gain { color: var(--nxt-success); }+ .pf-loss { color: var(--nxt-danger); }+ .pf-neutral { color: var(--nxt-ink-dim); }+ .pf-hero-meta { display: flex; gap: 20px; }+ .pf-hero-meta-item { display: flex; flex-direction: column; align-items: flex-end; gap: 2px; }+ .pf-hero-meta-label { font-size: 11px; color: var(--nxt-ink-fade); text-transform: uppercase; letter-spacing: 0.05em; }+ .pf-hero-meta-val { font-size: 14px; font-weight: 600; color: var(--nxt-ink-dim); font-variant-numeric: tabular-nums; }+ .pf-chart-wrap { padding: 16px 8px 8px; }+ .pf-chart-empty { padding: 24px; text-align: center; color: var(--nxt-ink-fade); font-size: 13px; }++ .pf-empty-hero { display: flex; flex-direction: column; align-items: center; text-align: center; padding: 48px 24px; gap: 12px; }+ .pf-empty-icon { color: var(--nxt-ink-fade); margin-bottom: 8px; }+ .pf-empty-hero h3 { font-size: 18px; font-weight: 600; margin: 0; }+ .pf-empty-hero p { font-size: 14px; color: var(--nxt-ink-dim); margin: 0; max-width: 360px; }++ .pf-section-head { display: flex; align-items: center; justify-content: space-between; gap: 12px; flex-wrap: wrap; margin-bottom: 14px; }++ .pf-wallets { display: grid; grid-template-columns: repeat(auto-fill, minmax(260px, 1fr)); gap: 12px; }+ .pf-wallet-card {+ border: 1px solid var(--nxt-stroke);+ border-radius: var(--nxt-radius-sm);+ padding: 16px;+ background: rgba(255,255,255,0.015);+ transition: border-color 0.14s ease, transform 0.14s ease;+ }+ .pf-wallet-card:hover { border-color: var(--nxt-stroke-strong); transform: translateY(-2px); }+ .pf-wallet-top { display: flex; justify-content: space-between; align-items: center; margin-bottom: 8px; }+ .pf-wallet-chain-badge {+ font-size: 11px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.06em;+ padding: 3px 8px; border-radius: 6px;+ background: rgba(255,255,255,0.06); color: var(--nxt-ink-dim);+ }+ .pf-wallet-explorer { font-size: 13px; color: var(--nxt-ink-fade); text-decoration: none; }+ .pf-wallet-explorer:hover { color: var(--nxt-ink); }+ .pf-wallet-name { font-size: 14px; font-weight: 600; color: var(--nxt-ink); margin-bottom: 2px; }+ .pf-wallet-sns { font-size: 12px; font-weight: 400; color: var(--nxt-ink-dim); margin-left: 6px; }+ .pf-wallet-addr { font-size: 12px; color: var(--nxt-ink-fade); margin-bottom: 10px; }+ .pf-wallet-bal-main { font-size: 20px; font-weight: 700; letter-spacing: -0.02em; font-variant-numeric: tabular-nums; }+ .pf-wallet-bal-sub { font-size: 12px; color: var(--nxt-ink-dim); margin-top: 2px; }+ .pf-wallet-err { font-size: 12px; color: var(--nxt-danger); margin-top: 8px; padding: 6px 8px; border-radius: 6px; background: rgba(248,113,113,0.08); }++ .pf-table { width: 100%; border-collapse: collapse; font-size: 13px; }+ .pf-th {+ padding: 10px 12px;+ font-weight: 600;+ font-size: 11.5px;+ text-transform: uppercase;+ letter-spacing: 0.05em;+ color: var(--nxt-ink-fade);+ border-bottom: 1px solid var(--nxt-stroke);+ text-align: left;+ }+ .pf-th.right { text-align: right; }+ .pf-td { padding: 12px; border-bottom: 1px solid var(--nxt-stroke); vertical-align: middle; }+ .pf-td.right { text-align: right; }+ .pf-row { transition: background 0.1s ease; }+ .pf-row:hover { background: rgba(255,255,255,0.03); }+ .pf-token-cell { display: flex; align-items: center; gap: 10px; }+ .pf-token-logo {+ width: 32px; height: 32px; border-radius: 50%;+ object-fit: cover; flex-shrink: 0;+ background: rgba(255,255,255,0.05);+ border: 1px solid var(--nxt-stroke);+ }+ .pf-token-logo-placeholder {+ display: grid; place-items: center;+ font-size: 14px; font-weight: 700;+ color: var(--nxt-ink-dim);+ }+ .pf-token-symbol { font-weight: 600; font-size: 14px; color: var(--nxt-ink); }+ .pf-token-name { font-size: 12px; color: var(--nxt-ink-fade); max-width: 160px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }+ .pf-change { font-size: 13px; font-weight: 500; font-variant-numeric: tabular-nums; }+ .pf-alloc-bar-wrap { display: flex; align-items: center; gap: 8px; min-width: 100px; }+ .pf-alloc-bar {+ height: 6px; border-radius: 3px;+ background: var(--nxt-ink-dim);+ flex: 1; max-width: 60px;+ }+ .pf-alloc-label { font-size: 12px; color: var(--nxt-ink-dim); font-variant-numeric: tabular-nums; min-width: 42px; text-align: right; }++ /* ── Asset detail panel ── */+ .pf-detail { margin-top: 8px; padding: 20px 24px; position: relative; }+ .pf-detail-header { display: flex; justify-content: space-between; align-items: flex-start; margin-bottom: 16px; }+ .pf-detail-title-row { display: flex; align-items: center; gap: 12px; }+ .pf-detail-logo { width: 40px; height: 40px; border-radius: 50%; object-fit: cover; flex-shrink: 0; }+ .pf-detail-symbol { font-size: 18px; font-weight: 700; color: var(--nxt-ink); }+ .pf-detail-name { font-size: 13px; color: var(--nxt-ink-dim); }+ .pf-detail-close {+ background: none; border: none; cursor: pointer;+ font-size: 24px; color: var(--nxt-ink-fade); padding: 4px 8px;+ line-height: 1; border-radius: 6px;+ transition: color 0.12s ease, background 0.12s ease;+ }+ .pf-detail-close:hover { color: var(--nxt-ink); background: rgba(255,255,255,0.06); }+ .pf-detail-price-row { display: flex; align-items: baseline; gap: 10px; margin-bottom: 16px; }+ .pf-detail-price { font-size: 28px; font-weight: 700; letter-spacing: -0.02em; font-variant-numeric: tabular-nums; }+ .pf-asset-chart-wrap { margin: 0 -8px 16px; }+ .pf-detail-stats {+ display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));+ gap: 2px; margin-bottom: 20px;+ }+ .pf-stat {+ display: flex; flex-direction: column; gap: 2px;+ padding: 10px 12px; border-radius: 8px;+ background: rgba(255,255,255,0.02);+ }+ .pf-stat-label { font-size: 11px; color: var(--nxt-ink-fade); text-transform: uppercase; letter-spacing: 0.05em; }+ .pf-stat-value { font-size: 14px; font-weight: 600; color: var(--nxt-ink); font-variant-numeric: tabular-nums; }+ .pf-detail-section-label { font-size: 12px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.06em; color: var(--nxt-ink-fade); margin: 16px 0 8px; }+ .pf-detail-holdings { display: flex; flex-direction: column; gap: 6px; margin-bottom: 16px; }+ .pf-detail-holding-row {+ display: flex; justify-content: space-between; align-items: center;+ padding: 8px 12px; border-radius: 8px;+ background: rgba(255,255,255,0.02); border: 1px solid var(--nxt-stroke);+ }+ .pf-detail-holding-agent { font-weight: 600; font-size: 13px; }+ .pf-detail-holding-addr { font-size: 12px; color: var(--nxt-ink-fade); margin-left: 8px; }+ .pf-detail-holding-val { display: flex; gap: 12px; font-size: 13px; font-variant-numeric: tabular-nums; }+ .pf-detail-desc { font-size: 13px; color: var(--nxt-ink-dim); line-height: 1.5; margin-top: 16px; padding-top: 16px; border-top: 1px solid var(--nxt-stroke); }++ /* ── Send form ── */+ .pf-send-form { display: flex; flex-direction: column; gap: 10px; margin-bottom: 16px; }+ .pf-input {+ width: 100%; padding: 10px 12px;+ font-size: 13px; font-family: inherit;+ background: rgba(255,255,255,0.04);+ border: 1px solid var(--nxt-stroke);+ border-radius: 8px; color: var(--nxt-ink);+ outline: none;+ transition: border-color 0.14s ease;+ }+ .pf-input:focus { border-color: var(--nxt-stroke-strong); }+ .pf-input option { background: #111; color: var(--nxt-ink); }+ .pf-send-amount-row { display: flex; gap: 8px; align-items: stretch; }+ .pf-send-amount-row .pf-input { flex: 1; }+ .pf-max-btn { padding: 8px 14px; font-size: 11px; letter-spacing: 0.05em; }+ .pf-send-actions { display: flex; align-items: center; gap: 12px; }+ .pf-send-ok { font-size: 13px; color: var(--nxt-success); }+ .pf-send-ok a { color: var(--nxt-success); }+ .pf-send-err { font-size: 13px; color: var(--nxt-danger); }+ .pf-send-status { flex: 1; }++ @media (max-width: 640px) {+ .pf-hero-top { flex-direction: column; }+ .pf-hero-meta { flex-wrap: wrap; }+ .pf-hero-value { font-size: 28px; }+ .pf-detail-stats { grid-template-columns: 1fr 1fr; }+ }+ `;+ const tag = document.createElement('style');+ tag.id = 'pf-styles';+ tag.textContent = css;+ document.head.appendChild(tag);}diff --git a/src/light-probe-grid.js b/src/light-probe-grid.jsnew file mode 100644index 000000000..7f684814c--- /dev/null+++ b/src/light-probe-grid.js@@ -0,0 +1,227 @@+import {+ Box3,+ CubeCamera,+ LightProbe,+ RGBAFormat,+ SphericalHarmonics3,+ Vector3,+ WebGLCubeRenderTarget,+} from 'three';+import { LightProbeGenerator } from 'three/addons/lights/LightProbeGenerator.js';++// Trilinear blend of eight scalar corner values.+function trilinear(v000, v100, v010, v110, v001, v101, v011, v111, tx, ty, tz) {+ const v00 = v000 + (v100 - v000) * tx;+ const v10 = v010 + (v110 - v010) * tx;+ const v01 = v001 + (v101 - v001) * tx;+ const v11 = v011 + (v111 - v011) * tx;+ const v0 = v00 + (v10 - v00) * ty;+ const v1 = v01 + (v11 - v01) * ty;+ return v0 + (v1 - v0) * tz;+}++export class LightProbeGrid {+ constructor(nx, ny, nz, bounds) {+ this.nx = nx;+ this.ny = ny;+ this.nz = nz;+ this.bounds = bounds instanceof Box3 ? bounds.clone() : new Box3();+ this._sh = new Array(nx * ny * nz).fill(null);+ this._activeProbe = new LightProbe(new SphericalHarmonics3(), 1);+ this._inScene = false;+ // Cached scratch vectors — avoids per-frame allocation in update().+ this._tmpSize = new Vector3();+ this._tmpPos = new Vector3();+ }++ _idx(ix, iy, iz) {+ return iz * this.ny * this.nx + iy * this.nx + ix;+ }++ _cellCenter(ix, iy, iz, out, size) {+ out.set(+ this.bounds.min.x + (ix + 0.5) * (size.x / this.nx),+ this.bounds.min.y + (iy + 0.5) * (size.y / this.ny),+ this.bounds.min.z + (iz + 0.5) * (size.z / this.nz),+ );+ }++ // Trilinearly blend the 8 surrounding cells into _activeProbe.sh.+ _applyTrilinear(worldPos) {+ const s = this.bounds.getSize(this._tmpSize);++ // Fractional grid coordinates; 0.5 offset maps cell centres.+ const gx = ((worldPos.x - this.bounds.min.x) / s.x) * this.nx - 0.5;+ const gy = ((worldPos.y - this.bounds.min.y) / s.y) * this.ny - 0.5;+ const gz = ((worldPos.z - this.bounds.min.z) / s.z) * this.nz - 0.5;++ const ix0 = Math.max(0, Math.min(this.nx - 1, Math.floor(gx)));+ const iy0 = Math.max(0, Math.min(this.ny - 1, Math.floor(gy)));+ const iz0 = Math.max(0, Math.min(this.nz - 1, Math.floor(gz)));+ const ix1 = Math.min(this.nx - 1, ix0 + 1);+ const iy1 = Math.min(this.ny - 1, iy0 + 1);+ const iz1 = Math.min(this.nz - 1, iz0 + 1);++ const tx = Math.max(0, Math.min(1, gx - ix0));+ const ty = Math.max(0, Math.min(1, gy - iy0));+ const tz = Math.max(0, Math.min(1, gz - iz0));++ const s000 = this._sh[this._idx(ix0, iy0, iz0)];+ const s100 = this._sh[this._idx(ix1, iy0, iz0)];+ const s010 = this._sh[this._idx(ix0, iy1, iz0)];+ const s110 = this._sh[this._idx(ix1, iy1, iz0)];+ const s001 = this._sh[this._idx(ix0, iy0, iz1)];+ const s101 = this._sh[this._idx(ix1, iy0, iz1)];+ const s011 = this._sh[this._idx(ix0, iy1, iz1)];+ const s111 = this._sh[this._idx(ix1, iy1, iz1)];++ const out = this._activeProbe.sh.coefficients;++ for (let j = 0; j < 9; j++) {+ const c000 = s000?.coefficients[j];+ const c100 = s100?.coefficients[j];+ const c010 = s010?.coefficients[j];+ const c110 = s110?.coefficients[j];+ const c001 = s001?.coefficients[j];+ const c101 = s101?.coefficients[j];+ const c011 = s011?.coefficients[j];+ const c111 = s111?.coefficients[j];++ out[j].x = trilinear(+ c000?.x ?? 0, c100?.x ?? 0, c010?.x ?? 0, c110?.x ?? 0,+ c001?.x ?? 0, c101?.x ?? 0, c011?.x ?? 0, c111?.x ?? 0,+ tx, ty, tz,+ );+ out[j].y = trilinear(+ c000?.y ?? 0, c100?.y ?? 0, c010?.y ?? 0, c110?.y ?? 0,+ c001?.y ?? 0, c101?.y ?? 0, c011?.y ?? 0, c111?.y ?? 0,+ tx, ty, tz,+ );+ out[j].z = trilinear(+ c000?.z ?? 0, c100?.z ?? 0, c010?.z ?? 0, c110?.z ?? 0,+ c001?.z ?? 0, c101?.z ?? 0, c011?.z ?? 0, c111?.z ?? 0,+ tx, ty, tz,+ );+ }+ }++ // Bake SH at each cell; probe is removed during capture so it doesn't+ // corrupt the captured radiance with its own contribution.+ async bake(renderer, scene, cubeFaceSize = 64, onProgress) {+ if (this._inScene) scene.remove(this._activeProbe);++ const cubeRT = new WebGLCubeRenderTarget(cubeFaceSize);+ cubeRT.texture.format = RGBAFormat;+ const cubeCamera = new CubeCamera(0.01, 10000, cubeRT);+ scene.add(cubeCamera);++ const total = this.nx * this.ny * this.nz;+ let done = 0;+ const pos = new Vector3();+ const size = this.bounds.getSize(new Vector3());++ try {+ for (let iz = 0; iz < this.nz; iz++) {+ for (let iy = 0; iy < this.ny; iy++) {+ for (let ix = 0; ix < this.nx; ix++) {+ this._cellCenter(ix, iy, iz, pos, size);+ cubeCamera.position.copy(pos);+ cubeCamera.update(renderer, scene);++ const probe = await LightProbeGenerator.fromCubeRenderTarget(renderer, cubeRT);+ this._sh[this._idx(ix, iy, iz)] = probe.sh.clone();++ onProgress?.(++done / total);+ }+ }+ }+ } finally {+ scene.remove(cubeCamera);+ cubeRT.dispose();+ if (this._inScene) scene.add(this._activeProbe);+ }++ // Prime the active probe at the volume centre.+ this._applyTrilinear(this.bounds.getCenter(this._tmpPos));+ }++ addToScene(scene) {+ if (!this._inScene) {+ scene.add(this._activeProbe);+ this._inScene = true;+ }+ }++ removeFromScene(scene) {+ if (this._inScene) {+ scene.remove(this._activeProbe);+ this._inScene = false;+ }+ }++ // Clamps worldPos to the grid volume so the probe is always valid even+ // when the camera orbits outside the baked bounds.+ update(worldPos) {+ this._tmpPos.copy(worldPos).clamp(this.bounds.min, this.bounds.max);+ this._applyTrilinear(this._tmpPos);+ }++ toJSON() {+ const coefficients = this._sh.map((sh) => {+ if (!sh) return null;+ const packed = [];+ for (let j = 0; j < 9; j++) {+ const c = sh.coefficients[j];+ packed.push(+ Math.round(c.x * 4096),+ Math.round(c.y * 4096),+ Math.round(c.z * 4096),+ );+ }+ return packed;+ });++ return {+ type: 'LightProbeGrid',+ nx: this.nx,+ ny: this.ny,+ nz: this.nz,+ bounds: {+ min: this.bounds.min.toArray(),+ max: this.bounds.max.toArray(),+ },+ coefficients,+ };+ }++ static fromJSON(json) {+ if (json.type !== 'LightProbeGrid') throw new Error('Invalid LightProbeGrid JSON');++ const bounds = new Box3();+ bounds.min.fromArray(json.bounds.min);+ bounds.max.fromArray(json.bounds.max);++ const grid = new LightProbeGrid(json.nx, json.ny, json.nz, bounds);++ grid._sh = json.coefficients.map((packed) => {+ if (!packed) return null;+ const sh = new SphericalHarmonics3();+ for (let j = 0; j < 9; j++) {+ sh.coefficients[j].set(+ packed[j * 3] / 4096,+ packed[j * 3 + 1] / 4096,+ packed[j * 3 + 2] / 4096,+ );+ }+ return sh;+ });++ grid._applyTrilinear(bounds.getCenter(grid._tmpPos));++ return grid;+ }++ dispose() {+ this._sh = [];+ }+}diff --git a/src/viewer.js b/src/viewer.jsindex b41090ef6..4c4f2a770 100644--- a/src/viewer.js+++ b/src/viewer.js@@ -43,6 +43,7 @@ import { addLights, removeLights } from './viewer/lights.js';import { getCubeMapTexture } from './viewer/environment.js';import { takeScreenshot, captureScreenshot } from './viewer/screenshot.js';import { setClips, playAllClips } from './viewer/animation.js';+import { LightProbeGrid } from './light-probe-grid.js';import { AnimationManager } from './animation-manager.js';Cache.enabled = true;@@ -64,6 +65,7 @@ export class Viewer {this.mixer = null;this.clips = [];this.gui = null;+ this._lightProbeGrid = null;// External animation system (Mixamo-style)this.animationManager = new AnimationManager();@@ -107,6 +109,12 @@ export class Viewer {// Avatar follow modefollowMode: 'mouse',++ // Light probe grid+ probeNx: 4,+ probeNy: 2,+ probeNz: 4,+ probeCubeFace: 64,};this.prevTime = 0;@@ -500,6 +508,7 @@ export class Viewer {this.stats.update();if (this.mixer) this.mixer.update(dt);this.animationManager.update(dt);+ if (this._lightProbeGrid) this._lightProbeGrid.update(this.activeCamera.position);// Extension point for the AgentAvatar empathy tick and any other per-frame hooksif (this._afterAnimateHooks) {@@ -613,6 +622,95 @@ export class Viewer {return captureScreenshot(this);}+ async bakeLightProbes() {+ if (!this.content) {+ console.warn('LightProbeGrid: load a model first');+ return;+ }++ if (this._lightProbeGrid) {+ this._lightProbeGrid.removeFromScene(this.scene);+ this._lightProbeGrid.dispose();+ }++ const bounds = new Box3().setFromObject(this.content);+ // Expand slightly so probes sit inside the volume, not on surface.+ bounds.expandByScalar(0.5);++ const { probeNx, probeNy, probeNz, probeCubeFace } = this.state;+ const grid = new LightProbeGrid(probeNx, probeNy, probeNz, bounds);++ let progressEl = this.el.querySelector('.lpg-progress');+ if (!progressEl) {+ progressEl = document.createElement('div');+ progressEl.className = 'lpg-progress';+ progressEl.style.cssText =+ 'position:absolute;bottom:12px;left:50%;transform:translateX(-50%);' ++ 'background:rgba(0,0,0,.7);color:#fff;font:12px/1.5 monospace;' ++ 'padding:6px 12px;border-radius:4px;pointer-events:none;z-index:100';+ this.el.appendChild(progressEl);+ }+ progressEl.textContent = 'Baking probes… 0%';+ progressEl.style.display = 'block';++ try {+ await grid.bake(this.renderer, this.scene, probeCubeFace, (t) => {+ progressEl.textContent = `Baking probes… ${Math.round(t * 100)}%`;+ });+ } catch (err) {+ console.error('LightProbeGrid bake failed:', err);+ return;+ } finally {+ progressEl.style.display = 'none';+ }++ this._lightProbeGrid = grid;+ grid.addToScene(this.scene);++ console.log(`LightProbeGrid baked: ${probeNx}×${probeNy}×${probeNz} cells`);+ }++ saveLightProbes() {+ if (!this._lightProbeGrid) {+ console.warn('LightProbeGrid: bake or load a grid first');+ return;+ }+ const json = JSON.stringify(this._lightProbeGrid.toJSON());+ const blob = new Blob([json], { type: 'application/json' });+ const url = URL.createObjectURL(blob);+ const a = document.createElement('a');+ a.href = url;+ a.download = 'light-probe-grid.json';+ a.click();+ URL.revokeObjectURL(url);+ }++ loadLightProbes() {+ const input = document.createElement('input');+ input.type = 'file';+ input.accept = '.json,application/json';+ input.onchange = async (e) => {+ const file = e.target.files[0];+ if (!file) return;+ const text = await file.text();+ let json;+ try {+ json = JSON.parse(text);+ } catch {+ console.error('LightProbeGrid: invalid JSON file');+ return;+ }+ if (this._lightProbeGrid) {+ this._lightProbeGrid.removeFromScene(this.scene);+ this._lightProbeGrid.dispose();+ }+ this._lightProbeGrid = LightProbeGrid.fromJSON(json);+ this._lightProbeGrid.addToScene(this.scene);+ console.log(`LightProbeGrid loaded: ${json.nx}×${json.ny}×${json.nz} cells`);+ };+ input.click();+ }+/*** Update the AR button visibility and target URLs after a model loads.* @param {string|null} glbUrl — absolute or relative URL to the GLB (for Android/WebXR)@@ -1223,6 +1321,16 @@ export class Viewer {lightFolder.addColor(this.state, 'directColor'),].forEach((ctrl) => ctrl.onChange(() => this.updateLights()));+ // Light Probe Grid controls.+ const probeFolder = gui.addFolder('Light Probes');+ probeFolder.add(this.state, 'probeNx', 1, 8, 1).name('grid X');+ probeFolder.add(this.state, 'probeNy', 1, 4, 1).name('grid Y');+ probeFolder.add(this.state, 'probeNz', 1, 8, 1).name('grid Z');+ probeFolder.add(this.state, 'probeCubeFace', { '32px': 32, '64px': 64, '128px': 128 }).name('cube face');+ probeFolder.add({ bake: () => this.bakeLightProbes() }, 'bake').name('Bake Probes');+ probeFolder.add({ save: () => this.saveLightProbes() }, 'save').name('Save JSON');+ probeFolder.add({ load: () => this.loadLightProbes() }, 'load').name('Load JSON');+// Animation controls.this.animFolder = gui.addFolder('Animation');this.animFolder.domElement.style.display = 'none';@@ -1752,6 +1860,12 @@ export class Viewer {this.scene.background = null;}+ if (this._lightProbeGrid) {+ this._lightProbeGrid.removeFromScene(this.scene);+ this._lightProbeGrid.dispose();+ this._lightProbeGrid = null;+ }+if (this.pmremGenerator) {this.pmremGenerator.dispose();this.pmremGenerator = null;