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
dashboard-next: account make-primary wallet + CSV export UX; monetize requireUser cleanup; rename audit scripts
nirholasaca061d0199d
diff --git a/api/billing/withdrawals/index.js b/api/billing/withdrawals/index.jsindex b2f2d6e9d..dd8871cba 100644--- a/api/billing/withdrawals/index.js+++ b/api/billing/withdrawals/index.js@@ -33,22 +33,38 @@ export default wrap(async (req, res) => {const limit = Math.min(100, Math.max(1, parseInt(params.get('limit') || '20', 10)));const offset = Math.max(0, parseInt(params.get('offset') || '0', 10));- const withdrawals = await sql`- select id, agent_id, amount, currency_mint, chain, to_address,- status, tx_signature, created_at, updated_at- from agent_withdrawals- where user_id = ${user.id}- and (${status} is null or status = ${status})- order by created_at desc- limit ${limit} offset ${offset}- `;-- const [{ total }] = await sql`- select count(*)::int as total- from agent_withdrawals- where user_id = ${user.id}- and (${status} is null or status = ${status})- `;+ // Branching on `status` avoids Postgres's `42P18: could not determine+ // data type of parameter` when the entire predicate compares two NULLs+ // (the `(${status} is null or status = ${status})` shape).+ const withdrawals = status+ ? await sql`+ select id, agent_id, amount, currency_mint, chain, to_address,+ status, tx_signature, created_at, updated_at+ from agent_withdrawals+ where user_id = ${user.id} and status = ${status}+ order by created_at desc+ limit ${limit} offset ${offset}+ `+ : await sql`+ select id, agent_id, amount, currency_mint, chain, to_address,+ status, tx_signature, created_at, updated_at+ from agent_withdrawals+ where user_id = ${user.id}+ order by created_at desc+ limit ${limit} offset ${offset}+ `;++ const [{ total }] = status+ ? await sql`+ select count(*)::int as total+ from agent_withdrawals+ where user_id = ${user.id} and status = ${status}+ `+ : await sql`+ select count(*)::int as total+ from agent_withdrawals+ where user_id = ${user.id}+ `;return json(res, 200, { withdrawals, total, limit, offset });}diff --git a/scripts/_dn-audit-all.mjs b/scripts/_dn-audit-all.mjsnew file mode 100644index 000000000..91dd115e7--- /dev/null+++ b/scripts/_dn-audit-all.mjs@@ -0,0 +1,101 @@+// Smoke-test every dashboard-next page against the local dev server.+// Stubs only /api/auth/me (so the page renders past requireUser) and lets+// every other /api/* request flow to the real dev proxy. Reports console+// errors + failed network requests per page.++import { chromium } from 'playwright';++const BASE = process.argv[2] || 'http://127.0.0.1:3011';+const OUT_DIR = process.argv[3] || '/tmp';++const PAGES = [+ { name: 'home', path: '/pages/dashboard-next/index.html' },+ { name: 'avatars', path: '/pages/dashboard-next/avatars.html' },+ { name: 'library-animations', path: '/pages/dashboard-next/library.html#tab=animations' },+ { name: 'library-memory', path: '/pages/dashboard-next/library.html#tab=memory' },+ { name: 'library-strategy', path: '/pages/dashboard-next/library.html#tab=strategy' },+ { name: 'library-voice', path: '/pages/dashboard-next/library.html#tab=voice' },+ { name: 'widgets', path: '/pages/dashboard-next/widgets.html' },+ { name: 'api', path: '/pages/dashboard-next/api.html' },+ { name: 'monetize', path: '/pages/dashboard-next/monetize.html' },+ { name: 'account', path: '/pages/dashboard-next/account.html' },+];++const ME = {+ id: 'u_demo',+ display_name: 'Nicholas',+ handle: 'nicholas',+ username: 'nicholas',+ email: '[email protected]',+ plan: 'pro',+ created_at: new Date(Date.now() - 90 * 86400_000).toISOString(),+};++const browser = await chromium.launch({ args: ['--use-gl=swiftshader', '--no-sandbox'] });++const summary = [];++for (const page of PAGES) {+ const ctx = await browser.newContext({ viewport: { width: 1440, height: 900 } });+ const p = await ctx.newPage();+ const pageErrors = [];+ const failedReqs = [];+ const httpErrors = [];++ p.on('pageerror', (e) => pageErrors.push('PAGEERROR ' + e.message.slice(0, 240)));+ p.on('console', (m) => { if (m.type() === 'error') pageErrors.push('CONSOLE ' + m.text().slice(0, 240)); });+ p.on('requestfailed', (r) => {+ const u = r.url();+ if (u.includes('analytics') || u.includes('posthog') || u.includes('favicon')) return;+ failedReqs.push(`${u.replace(BASE, '')} ${r.failure()?.errorText || ''}`);+ });+ p.on('response', (r) => {+ const u = r.url();+ if (!u.startsWith(BASE) && !u.startsWith('http://127.0.0.1')) return;+ if (u.includes('analytics') || u.includes('posthog')) return;+ const s = r.status();+ if (s >= 400) httpErrors.push(`${s} ${u.replace(BASE, '')}`);+ });++ // Stub just auth/me — everything else goes through.+ await ctx.route('**/api/auth/me', (r) => r.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(ME) }));+ await ctx.route('**/api/csrf-token', (r) => r.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ token: 'audit' }) }));++ const url = BASE + page.path;+ try {+ await p.goto(url, { waitUntil: 'domcontentloaded', timeout: 60_000 });+ await p.waitForSelector('.dn-shell .dn-rail-item', { timeout: 20_000 });+ await p.waitForTimeout(3500);+ await p.screenshot({ path: `${OUT_DIR}/dn-audit-${page.name}.png`, fullPage: false });+ } catch (e) {+ pageErrors.push('NAV_FAIL ' + e.message.slice(0, 200));+ }++ summary.push({ page: page.name, url: page.path, pageErrors, failedReqs, httpErrors });+ await ctx.close();+}++await browser.close();++for (const s of summary) {+ console.log(`\n=== ${s.page} (${s.url}) ===`);+ if (s.pageErrors.length) {+ console.log(' page errors:');+ for (const e of s.pageErrors) console.log(' - ' + e);+ }+ if (s.failedReqs.length) {+ console.log(' failed requests:');+ for (const e of s.failedReqs.slice(0, 20)) console.log(' - ' + e);+ }+ if (s.httpErrors.length) {+ console.log(' http >=400:');+ for (const e of s.httpErrors.slice(0, 20)) console.log(' - ' + e);+ }+ if (!s.pageErrors.length && !s.failedReqs.length && !s.httpErrors.length) {+ console.log(' clean');+ }+}++const broken = summary.filter((s) => s.pageErrors.length || s.failedReqs.length || s.httpErrors.length);+console.log(`\n${broken.length} of ${summary.length} pages have issues.`);+process.exit(broken.length ? 1 : 0);diff --git a/scripts/_dn-audit.mjs b/scripts/_dn-audit.mjsdeleted file mode 100644index 7de81e2b3..000000000--- a/scripts/_dn-audit.mjs+++ /dev/null@@ -1,143 +0,0 @@-// Headless audit of /dashboard-next/* pages with mocked API.-// Run from repo root: node scripts/_dn-audit.mjs-import { chromium } from 'playwright';--const BASE = 'http://127.0.0.1:3010';-const PAGES = [- { slug: 'overview', path: '/dashboard-next' },- { slug: 'avatars', path: '/dashboard-next/avatars' },- { slug: 'library', path: '/dashboard-next/library' },- { slug: 'widgets', path: '/dashboard-next/widgets' },- { slug: 'api', path: '/dashboard-next/api' },- { slug: 'monetize', path: '/dashboard-next/monetize' },- { slug: 'account', path: '/dashboard-next/account' },-];--const FAKE_USER = {- id: '00000000-0000-0000-0000-000000000001',- display_name: 'Test',- email: 't@t',- handle: 'test',-};--const MOCKS = [- [/\/api\/auth\/me(\?|$)/, { user: FAKE_USER }],- [/\/api\/csrf-token(\?|$)/, { token: 'x' }],- [/\/api\/auth\/profile/, { user: FAKE_USER }],- [/\/api\/auth\/logout/, { ok: true }],- [/\/api\/auth\/wallets/, { wallets: [] }],- [/\/api\/avatars\?/, { avatars: [], items: [], cursor: null }],- [/\/api\/avatars\/[^/]+$/, { id: 'a1', name: 'Test', visibility: 'private' }],- [/\/api\/widgets\/[^/]+\/stats/, { calls: 0, revenue_atomics: '0', series: [] }],- [/\/api\/widgets\/[^/]+\/transcripts/, { transcripts: [] }],- [/\/api\/widgets\/[^/]+\/duplicate/, { id: 'w2' }],- [/\/api\/widgets\/[^/]+$/, { ok: true }],- [/\/api\/widgets(\?|$)/, { widgets: [], items: [] }],- [/\/api\/keys(\?|$)/, { keys: [] }],- [/\/api\/agents\/[^/]+\/payments/, { payments: [] }],- [/\/api\/agents\/[^/]+\/embed-policy/, { policy: { allowed_origins: [] } }],- [/\/api\/agents\/[^/]+\/animations/, { ok: true }],- [/\/api\/agents(\?|$)/, { agents: [] }],- [/\/api\/agent-memory/, { memories: [], items: [] }],- [/\/api\/agent-strategy/, { strategy: {} }],- [/\/api\/animations\/presign/, { url: 'https://example/upload', key: 'x' }],- [/\/api\/tts\/eleven\/voices/, { voices: [] }],- [/\/api\/tts\/eleven$/, { ok: true }],- [/\/api\/billing\/revenue/, { series: [], total_atomics: '0' }],- [/\/api\/billing\/withdrawals/, { withdrawals: [], items: [] }],- [/\/api\/billing\/payout-wallets/, { wallets: [] }],- [/\/api\/billing\/summary/, { available_atomics: '0', pending_atomics: '0', lifetime_atomics: '0' }],- [/\/api\/subscriptions\/plans/, { plans: [] }],- [/\/api\/subscriptions\/mine/, { subscriptions: [] }],- [/\/api\/users\/me\/earnings/, { total_atomics: '0', breakdown: [] }],- [/\/api\/audit-log/, { events: [], items: [] }],- [/\/api\/sns\?/, { domain: null }],- [/\/api\/mcp/, { ok: true }],-];--function jsonResponse(route, body) {- return route.fulfill({- status: 200,- contentType: 'application/json',- body: JSON.stringify(body),- });-}--async function auditPage(browser, { slug, path }) {- const ctx = await browser.newContext({ viewport: { width: 1280, height: 900 } });- const errors = { pageerror: [], console: [], http: [], unmocked: [] };-- await ctx.route('**/api/**', (route) => {- const url = route.request().url();- for (const [re, body] of MOCKS) {- if (re.test(url)) return jsonResponse(route, body);- }- errors.unmocked.push(`${route.request().method()} ${url.replace(BASE, '')}`);- return route.fulfill({ status: 404, contentType: 'application/json', body: '{"error":"not_found"}' });- });-- const page = await ctx.newPage();- page.on('pageerror', (err) => {- errors.pageerror.push(`${err.name}: ${err.message}`);- });- page.on('console', (msg) => {- if (msg.type() === 'error') {- const text = msg.text();- if (/Failed to load resource/i.test(text)) return;- errors.console.push(text);- }- });- page.on('response', (resp) => {- const url = resp.url();- const status = resp.status();- if (status >= 400 && /\/api\//.test(url)) {- errors.http.push(`${status} ${resp.request().method()} ${url.replace(BASE, '')}`);- }- });-- try {- await page.goto(BASE + path, { waitUntil: 'domcontentloaded', timeout: 20000 });- await page.waitForTimeout(3000);- await page.screenshot({ path: `/tmp/dn-audit-${slug}.png`, fullPage: false });- } catch (err) {- errors.pageerror.push(`navigation: ${err.message}`);- }-- await ctx.close();- return { slug, path, errors };-}--const browser = await chromium.launch({ headless: true, args: ['--no-sandbox'] });-const results = [];-for (const p of PAGES) {- try {- const r = await auditPage(browser, p);- results.push(r);- } catch (e) {- results.push({ slug: p.slug, path: p.path, errors: { pageerror: ['outer: ' + e.message], console: [], http: [], unmocked: [] } });- }-}-await browser.close();--console.log('\n===== DASHBOARD-NEXT AUDIT =====\n');-for (const { slug, path, errors } of results) {- const total = errors.pageerror.length + errors.console.length + errors.http.length + errors.unmocked.length;- console.log(`── ${slug.padEnd(9)} ${path} [${total} issues]`);- if (errors.pageerror.length) {- console.log(' pageerror:');- for (const e of errors.pageerror) console.log(' • ' + e);- }- if (errors.console.length) {- console.log(' console.error:');- for (const e of errors.console) console.log(' • ' + e);- }- if (errors.http.length) {- console.log(' http >=400:');- for (const e of errors.http) console.log(' • ' + e);- }- if (errors.unmocked.length) {- console.log(' unmocked endpoints (returned 404):');- for (const e of errors.unmocked) console.log(' • ' + e);- }- console.log('');-}diff --git a/scripts/_dn-fullsweep.mjs b/scripts/_dn-fullsweep.mjsnew file mode 100644index 000000000..e1f06216e--- /dev/null+++ b/scripts/_dn-fullsweep.mjs@@ -0,0 +1,69 @@+// Full-sweep verifier: opens every dashboard-next page in a real browser+// with a mocked /api/auth/me, captures any console errors / failed fetches+// (filtered to dashboard-next surface only), and screenshots each page.+//+// Usage: node scripts/_dn-fullsweep.mjs+// Output: /tmp/dn-sweep-<page>.png for every page; non-zero exit on errors.++import { chromium } from 'playwright';++const PAGES = [+ { slug: '', name: 'overview', sel: '.dn-shell .dn-rail-item' },+ { slug: 'avatars', name: 'avatars', sel: '.dn-shell .dn-rail-item' },+ { slug: 'widgets', name: 'widgets', sel: '.dn-shell .dn-rail-item' },+ { slug: 'library', name: 'library', sel: '.dn-shell .dn-rail-item' },+ { slug: 'api', name: 'api', sel: '.dn-shell .dn-rail-item' },+ { slug: 'monetize', name: 'monetize', sel: '.dn-shell .dn-rail-item' },+ { slug: 'account', name: 'account', sel: '.dn-shell .dn-rail-item' },+];++const b = await chromium.launch({ args: ['--use-gl=swiftshader','--no-sandbox'] });+const ctx = await b.newContext({ viewport: { width: 1440, height: 900 } });++// Mocks: keep responses minimal so home doesn't mount live <threews-avatar>+// (Three.js + SwiftShader headless = GPU crashes — see memory).+const json = (obj) => ({ status: 200, contentType: 'application/json', body: JSON.stringify(obj) });+const me = { id: 'test-user', display_name: 'Test User', handle: 'tester', email: '[email protected]', plan: 'pro' };+await ctx.route('**/api/auth/me', (r) => r.fulfill(json({ user: me })));+await ctx.route('**/api/avatars*', (r) => r.fulfill(json({ avatars: [], next_cursor: null })));+await ctx.route('**/api/widgets*', (r) => r.fulfill(json({ widgets: [] })));+await ctx.route('**/api/agents*', (r) => r.fulfill(json({ agents: [] })));+await ctx.route('**/api/keys*', (r) => r.fulfill(json({ keys: [] })));+await ctx.route('**/api/animations*', (r) => r.fulfill(json({ animations: [] })));+await ctx.route('**/api/billing/**', (r) => r.fulfill(json({ revenue: 0, rows: [], series: [] })));+await ctx.route('**/api/notifications*', (r) => r.fulfill(json({ notifications: [] })));+await ctx.route('**/api/subscriptions/**', (r) => r.fulfill(json({ subscriptions: [] })));+await ctx.route('**/api/events*', (r) => r.fulfill(json({ events: [] })));+await ctx.route('**/api/me/**', (r) => r.fulfill(json({ }))); // earnings, totals, etc.+await ctx.route('**/api/strategy*', (r) => r.fulfill(json({ strategy: null })));+await ctx.route('**/api/memories*', (r) => r.fulfill(json({ memories: [] })));+await ctx.route('**/api/voice*', (r) => r.fulfill(json({ voices: [] })));+await ctx.route('**/api/csrf-token', (r) => r.fulfill(json({ token: 'test-csrf' })));++let totalErrs = 0;+for (const page of PAGES) {+ const p = await ctx.newPage();+ const errs = [];+ p.on('pageerror', (e) => errs.push(`PAGEERROR ${e.message.slice(0, 220)}`));+ p.on('console', (m) => { if (m.type() === 'error') errs.push(`[err] ${m.text().slice(0, 220)}`); });+ const url = `http://127.0.0.1:3010/dashboard-next${page.slug ? '/' + page.slug : ''}`;+ try {+ await p.goto(url, { waitUntil: 'domcontentloaded', timeout: 60000 });+ await p.waitForSelector(page.sel, { timeout: 20000 });+ await p.waitForTimeout(1500); // let async fetches settle+ await p.screenshot({ path: `/tmp/dn-sweep-${page.name}.png`, fullPage: false });+ } catch (e) {+ errs.push(`NAV/WAIT failed: ${e.message.slice(0, 220)}`);+ }+ // Filter known unrelated browser-noise errors that aren't bugs in our code.+ const relevant = errs.filter((e) =>+ !/Failed to load resource: the server responded with a status of 4\d\d/.test(e) || // 4xx logged by browser auto-handler+ /PAGEERROR|TypeError|ReferenceError|SyntaxError|Uncaught/.test(e),+ );+ console.log(`${page.name}: ${relevant.length === 0 ? 'OK' : 'ERRORS'}`);+ for (const e of relevant) { console.log(` ${e}`); totalErrs++; }+ await p.close();+}++await b.close();+process.exit(totalErrs > 0 ? 1 : 0);diff --git a/scripts/_dn-sweep.mjs b/scripts/_dn-sweep.mjsnew file mode 100644index 000000000..e346a86f7--- /dev/null+++ b/scripts/_dn-sweep.mjs@@ -0,0 +1,113 @@+// Smoke-test every /dashboard-next page. Captures one screenshot per page+// and reports any page-error / console-error / failed-request. Exit code is+// the number of pages with issues. Deletes itself when caller is done — this+// file is intentionally not checked in long-term.+import { chromium } from 'playwright';++const BASE = process.argv[2] || 'http://127.0.0.1:3010';+const PAGES = [+ { slug: '', name: 'home' },+ { slug: '/avatars', name: 'avatars' },+ { slug: '/widgets', name: 'widgets' },+ { slug: '/library', name: 'library' },+ { slug: '/api', name: 'api' },+ { slug: '/monetize', name: 'monetize' },+ { slug: '/account', name: 'account' },+];++const browser = await chromium.launch({+ args: ['--use-gl=swiftshader', '--no-sandbox', '--disable-gpu'],+});+const ctx = await browser.newContext({ viewport: { width: 1440, height: 900 } });++const results = [];+for (const { slug, name } of PAGES) {+ const page = await ctx.newPage();+ const errs = [];+ page.on('pageerror', (e) => errs.push('PAGEERROR ' + e.message.slice(0, 220)));+ page.on('console', (m) => {+ if (m.type() === 'error') errs.push('[err] ' + m.text().slice(0, 220));+ });+ page.on('requestfailed', (r) => {+ const u = r.url();+ // Ignore irrelevant 404s on optional analytics/sw assets.+ if (/posthog|sw\.js|workbox|favicon\.svg/.test(u)) return;+ errs.push('REQ FAIL ' + u + ' ' + r.failure()?.errorText);+ });+ const url = `${BASE}/dashboard-next${slug}`;+ const out = `/tmp/dn-${name}.png`;+ let status = 'ok';+ try {+ await page.goto(url, { waitUntil: 'networkidle', timeout: 60000 });+ await page.waitForSelector('.dn-shell .dn-rail-item', { timeout: 25000 });+ // Settle for any in-flight 3D/component mounts.+ await page.waitForTimeout(1200);+ await page.screenshot({ path: out, fullPage: false });+ } catch (err) {+ status = 'fail: ' + (err?.message || err).slice(0, 200);+ }+ results.push({ name, url, out, status, errs });+ await page.close();+}++// Bonus: open the palette and screenshot it+{+ const page = await ctx.newPage();+ const errs = [];+ page.on('pageerror', (e) => errs.push('PAGEERROR ' + e.message.slice(0, 220)));+ page.on('console', (m) => { if (m.type() === 'error') errs.push('[err] ' + m.text().slice(0, 220)); });+ try {+ await page.goto(`${BASE}/dashboard-next`, { waitUntil: 'networkidle', timeout: 45000 });+ await page.waitForSelector('.dn-shell .dn-rail-item', { timeout: 20000 });+ await page.keyboard.press('Meta+K');+ await page.waitForTimeout(400);+ await page.fill('#dn-palette input, [data-role="palette-input"]', 'avatars').catch(() => {});+ await page.waitForTimeout(200);+ await page.screenshot({ path: '/tmp/dn-palette.png', fullPage: false });+ results.push({ name: 'palette', url: 'cmd-k', out: '/tmp/dn-palette.png', status: 'ok', errs });+ } catch (err) {+ results.push({ name: 'palette', url: 'cmd-k', out: '/tmp/dn-palette.png', status: 'fail: ' + (err?.message || err).slice(0, 200), errs });+ }+ await page.close();+}++// Open the drawer too+{+ const page = await ctx.newPage();+ const errs = [];+ page.on('pageerror', (e) => errs.push('PAGEERROR ' + e.message.slice(0, 220)));+ page.on('console', (m) => { if (m.type() === 'error') errs.push('[err] ' + m.text().slice(0, 220)); });+ try {+ await page.goto(`${BASE}/dashboard-next`, { waitUntil: 'domcontentloaded' });+ await page.evaluate(() => localStorage.setItem('dn:drawer:open', '1'));+ await page.goto(`${BASE}/dashboard-next`, { waitUntil: 'networkidle', timeout: 45000 });+ await page.waitForSelector('.dn-shell', { timeout: 20000 });+ await page.waitForTimeout(1500);+ await page.screenshot({ path: '/tmp/dn-drawer.png', fullPage: false });+ results.push({ name: 'drawer-open', url: 'drawer', out: '/tmp/dn-drawer.png', status: 'ok', errs });+ } catch (err) {+ results.push({ name: 'drawer-open', url: 'drawer', out: '/tmp/dn-drawer.png', status: 'fail: ' + (err?.message || err).slice(0, 200), errs });+ }+ await page.close();+}++await browser.close();++console.log('\n=== SWEEP RESULTS ===');+let bad = 0;+for (const r of results) {+ const headline = r.status === 'ok' && r.errs.length === 0+ ? '✓'+ : (r.status === 'ok' ? '⚠' : '✗');+ console.log(`${headline} ${r.name.padEnd(14)} ${r.out}`);+ if (r.status !== 'ok') {+ console.log(` ${r.status}`);+ bad++;+ }+ for (const e of r.errs.slice(0, 6)) {+ console.log(` ${e}`);+ if (e.startsWith('PAGEERROR') || e.startsWith('[err]')) bad++;+ }+ if (r.errs.length > 6) console.log(` ... +${r.errs.length - 6} more`);+}+process.exit(bad > 0 ? 1 : 0);diff --git a/src/dashboard-next/pages/account.js b/src/dashboard-next/pages/account.jsindex 179333bb7..6ab7ebdd6 100644--- a/src/dashboard-next/pages/account.js+++ b/src/dashboard-next/pages/account.js@@ -18,11 +18,11 @@ const CHAIN_STYLES = {const MONO = `'JetBrains Mono', ui-monospace, SFMono-Regular, Menlo, monospace`;const CATEGORY_BY_ACTION = [- [/^(link_wallet|unlink_wallet|password_|email_|login|logout|session)/, 'Auth'],+ [/^(link_wallet|unlink_wallet|set_primary_wallet|password_|email_|login|logout|session|revoke_oauth_token)/, 'Auth'],[/^(avatar_|create_avatar|delete_avatar|upload_avatar)/, 'Avatar'],[/^(widget_|embed_)/, 'Widget'],[/^(payment_|invoice_|payout_|withdraw_|stripe_|x402_)/, 'Payment'],- [/^(api_key|key_|delegate_|delegation_)/, 'Auth'],+ [/^(api_key|key_|revoke_api_key|delegate_|delegation_)/, 'Auth'],];function categoryOf(action) {@@ -166,8 +166,35 @@ async function copyToClipboard(text) {loadDelegations(delegationHost);loadActions(actionsHost);- main.querySelector('[data-action="export-csv"]').addEventListener('click', () => {- window.location.href = '/api/audit-log?format=csv';+ main.querySelector('[data-action="export-csv"]').addEventListener('click', async (e) => {+ const btn = e.currentTarget;+ const originalText = btn.textContent;+ btn.disabled = true;+ btn.textContent = 'Exporting…';+ try {+ const res = await fetch('/api/audit-log?format=csv', { credentials: 'include' });+ if (!res.ok) {+ if (res.status === 404) toast('Audit log endpoint not deployed yet');+ else if (res.status === 401) toast('Sign in required');+ else toast(`Export failed: HTTP ${res.status}`);+ return;+ }+ const blob = await res.blob();+ const url = URL.createObjectURL(blob);+ const a = document.createElement('a');+ a.href = url;+ a.download = `audit-log-${new Date().toISOString().slice(0, 10)}.csv`;+ document.body.appendChild(a);+ a.click();+ a.remove();+ URL.revokeObjectURL(url);+ toast('CSV downloaded');+ } catch (err) {+ toast(err?.message ? `Export failed: ${err.message}` : 'Export failed');+ } finally {+ btn.disabled = false;+ btn.textContent = originalText;+ }});})();@@ -318,7 +345,10 @@ function renderWallets(host, wallets) {${isPrimary ? '<span class="dn-tag" style="background:rgba(255,212,121,0.12);border-color:rgba(255,212,121,0.28);color:#ffd479">primary</span>' : ''}</td><td style="padding:11px 12px;text-align:right;white-space:nowrap">- <button class="dn-btn danger" data-action="unlink" data-address="${esc(w.address)}" style="padding:5px 10px;font-size:12px">Disconnect</button>+ <div style="display:inline-flex;gap:6px">+ ${isPrimary ? '' : `<button class="dn-btn" data-action="make-primary" data-address="${esc(w.address)}" style="padding:5px 10px;font-size:12px">Make primary</button>`}+ <button class="dn-btn danger" data-action="unlink" data-address="${esc(w.address)}" style="padding:5px 10px;font-size:12px">Disconnect</button>+ </div></td></tr>`;@@ -364,6 +394,23 @@ function renderWallets(host, wallets) {}});});+ host.querySelectorAll('[data-action="make-primary"]').forEach((btn) => {+ btn.addEventListener('click', async () => {+ const addr = btn.dataset.address;+ btn.disabled = true;+ btn.textContent = 'Setting…';+ try {+ await post('/api/auth/wallets/primary', { address: addr });+ toast('Primary wallet updated');+ const r = await get('/api/auth/wallets');+ renderWallets(host, Array.isArray(r?.wallets) ? r.wallets : []);+ } catch (err) {+ toast(err?.message ? `Failed: ${err.message}` : 'Couldn’t set primary');+ btn.disabled = false;+ btn.textContent = 'Make primary';+ }+ });+ });}// ── SNS ───────────────────────────────────────────────────────────────────diff --git a/src/dashboard-next/pages/monetize.js b/src/dashboard-next/pages/monetize.jsindex 55dc394df..31f9efbed 100644--- a/src/dashboard-next/pages/monetize.js+++ b/src/dashboard-next/pages/monetize.js@@ -33,13 +33,7 @@ const PAYMENT_FILTERS = [(async function boot() {const main = await mountShell();- const meResp = await requireUser();- // /api/auth/me returns { user: {...} } — peel the envelope.- const me = meResp?.user || meResp;- if (!me?.id) {- location.href = `/login?return=${encodeURIComponent(location.pathname)}`;- return;- }+ const me = await requireUser();main.innerHTML = `<h1 class="dn-h1">Money</h1>@@ -105,7 +99,6 @@ async function safe(fn) {return await fn();} catch (err) {if (err instanceof ApiError && err.status === 401) throw err;- console.warn('[monetize] request failed:', err?.message || err);return null;}}