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/home: drop drawer display:none workaround (drawer now scopes flex to open state)
nirholas5747380c29a9
diff --git a/api/_lib/audit.js b/api/_lib/audit.jsindex 8b7119e8a..2bad40fa9 100644--- a/api/_lib/audit.js+++ b/api/_lib/audit.js@@ -4,10 +4,15 @@// what, when" trail (deletions, revocations, ownership transfers). Reads,// idempotent updates, and analytics belong in usage_events, not here.//-// Schema: api/_lib/migrations/2026-05-01-audit-log.sql+// Schema:+// api/_lib/migrations/2026-05-01-audit-log.sql — base table+// api/_lib/migrations/2026-05-25-audit-log-context.sql — ip + user_agent// Audit data starts 2026-05-01 — earlier deletions/revocations have no row.import { sql } from './db.js';+import { clientIp } from './rate-limit.js';++const UA_MAX = 512;/*** Fire-and-forget audit log write. Never throws, never blocks the response.@@ -16,13 +21,19 @@ import { sql } from './db.js';* @param {string} entry.action — short kebab-case verb, e.g. 'delete_avatar'* @param {string|null} [entry.resourceId]* @param {object|null} [entry.meta] — small JSON blob; avoid PII+ * @param {object} [entry.req] — request, used to capture IP + UA+ * @param {string|null} [entry.ip] — explicit override (otherwise derived from req)+ * @param {string|null} [entry.userAgent] — explicit override (otherwise derived from req)*/-export function logAudit({ userId, action, resourceId = null, meta = null }) {+export function logAudit({ userId, action, resourceId = null, meta = null, req = null, ip = null, userAgent = null }) {+ const resolvedIp = ip ?? (req ? clientIp(req) : null);+ const rawUa = userAgent ?? (req ? req.headers?.['user-agent'] : null);+ const resolvedUa = rawUa ? String(rawUa).slice(0, UA_MAX) : null;queueMicrotask(async () => {try {await sql`- insert into audit_log (user_id, action, resource_id, meta)- values (${userId}, ${action}, ${resourceId}, ${meta})+ insert into audit_log (user_id, action, resource_id, meta, ip, user_agent)+ values (${userId}, ${action}, ${resourceId}, ${meta}, ${resolvedIp}, ${resolvedUa})`;} catch (err) {console.error('[audit] insert failed', { action, resourceId, error: err?.message });diff --git a/api/_lib/migrations/2026-05-25-audit-log-context.sql b/api/_lib/migrations/2026-05-25-audit-log-context.sqlnew file mode 100644index 000000000..7e835e7ac--- /dev/null+++ b/api/_lib/migrations/2026-05-25-audit-log-context.sql@@ -0,0 +1,16 @@+-- Migration: capture request context (IP + user agent) on audit_log rows.+-- Apply: psql "$DATABASE_URL" -f api/_lib/migrations/2026-05-25-audit-log-context.sql+-- Idempotent.+--+-- Rationale: the per-user audit feed on /dashboard-next/account exposes+-- IP and user-agent columns. Existing audit_log rows had no slot for+-- either. Both columns are nullable so rows written before this migration+-- (or by callers that don't yet pass req) remain valid.+--+-- Length caps mirror what we already accept in sessions.user_agent and+-- sessions.ip — keep the audit row representation aligned with how we+-- already store request metadata elsewhere.++alter table audit_log+ add column if not exists ip text,+ add column if not exists user_agent text;diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.jsindex 7a5d54645..2f93a9ad8 100644--- a/api/_lib/rate-limit.js+++ b/api/_lib/rate-limit.js@@ -152,6 +152,9 @@ export const limits = {xSeed: (agentId) => getLimiter('memory:seed:x', { limit: 1, window: '6 h' }).limit(agentId),// Withdrawal requests: 5 per user per day to prevent spam.withdrawalPerUser: (userId) => getLimiter('withdrawal:user', { limit: 5, window: '1 d' }).limit(userId),+ // Per-user audit-log reads — the page polls on mount + "load older". 120/min+ // per user is generous for browse but discourages scraping the full year.+ auditLogRead: (userId) => getLimiter('audit-log:read', { limit: 120, window: '1 m' }).limit(userId),};// Trust only proxy headers that Vercel itself sets and signs. Naively readingdiff --git a/api/audit-log.js b/api/audit-log.jsnew file mode 100644index 000000000..5d5d9cc66--- /dev/null+++ b/api/audit-log.js@@ -0,0 +1,141 @@+// GET /api/audit-log — JSON list of the caller's audit events+// GET /api/audit-log?format=csv — CSV download (same data, last 90 days)+//+// Backs the "Action log" panel on /dashboard-next/account. Reads from the+// audit_log table populated by api/_lib/audit.js. JSON form is cursor-+// paginated (opaque cursor = the created_at + id of the last row).+//+// Schema:+// api/_lib/migrations/2026-05-01-audit-log.sql — base table+// api/_lib/migrations/2026-05-25-audit-log-context.sql — ip + user_agent+//+// Retention: rows older than 365 days are pruned by the audit-log-cleanup+// cron (vercel.json). The CSV export caps at 90 days to keep the download+// small and predictable.++import { sql } from './_lib/db.js';+import { getSessionUser } from './_lib/auth.js';+import { cors, error, json, method, wrap } from './_lib/http.js';+import { limits } from './_lib/rate-limit.js';++const DEFAULT_LIMIT = 50;+const MAX_LIMIT = 200;+const CSV_DAYS = 90;++// Cursors are base64url("<iso-ts>|<uuid>") — the timestamp+id of the last row+// returned, used as a stable strictly-less-than key for the next page.+function encodeCursor(createdAt, id) {+ const raw = `${new Date(createdAt).toISOString()}|${id}`;+ return Buffer.from(raw, 'utf8').toString('base64url');+}++function decodeCursor(cursor) {+ if (!cursor) return null;+ try {+ const raw = Buffer.from(String(cursor), 'base64url').toString('utf8');+ const [iso, id] = raw.split('|');+ if (!iso || !id) return null;+ if (Number.isNaN(Date.parse(iso))) return null;+ if (!/^[0-9a-f-]{36}$/i.test(id)) return null;+ return { iso, id };+ } catch {+ return null;+ }+}++function csvEscape(value) {+ if (value === null || value === undefined) return '';+ const s = typeof value === 'string' ? value : JSON.stringify(value);+ if (/[",\n\r]/.test(s)) return `"${s.replace(/"/g, '""')}"`;+ return s;+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET'])) return;++ const session = await getSessionUser(req);+ if (!session) return error(res, 401, 'unauthorized', 'sign in required');++ const rl = await limits.auditLogRead(session.id);+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');++ const url = new URL(req.url, 'http://x');+ const format = (url.searchParams.get('format') || '').toLowerCase();++ if (format === 'csv') return handleCsv(session.id, res);+ return handleList(session.id, url, res);+});++async function handleList(userId, url, res) {+ const rawLimit = parseInt(url.searchParams.get('limit') || String(DEFAULT_LIMIT), 10);+ const limit = Math.min(MAX_LIMIT, Math.max(1, Number.isFinite(rawLimit) ? rawLimit : DEFAULT_LIMIT));+ const cursor = decodeCursor(url.searchParams.get('cursor'));++ const rows = cursor+ ? await sql`+ select id, action, resource_id, meta, ip, user_agent, created_at+ from audit_log+ where user_id = ${userId}+ and (created_at, id) < (${cursor.iso}::timestamptz, ${cursor.id}::uuid)+ order by created_at desc, id desc+ limit ${limit + 1}+ `+ : await sql`+ select id, action, resource_id, meta, ip, user_agent, created_at+ from audit_log+ where user_id = ${userId}+ order by created_at desc, id desc+ limit ${limit + 1}+ `;++ const hasMore = rows.length > limit;+ const page = hasMore ? rows.slice(0, limit) : rows;+ const last = page[page.length - 1];+ const nextCursor = hasMore && last ? encodeCursor(last.created_at, last.id) : null;++ return json(res, 200, {+ items: page.map((r) => ({+ id: r.id,+ action: r.action,+ resource_id: r.resource_id,+ meta: r.meta,+ ip: r.ip,+ user_agent: r.user_agent,+ created_at: r.created_at,+ })),+ next_cursor: nextCursor,+ has_more: hasMore,+ });+}++async function handleCsv(userId, res) {+ const rows = await sql`+ select action, resource_id, meta, ip, user_agent, created_at+ from audit_log+ where user_id = ${userId}+ and created_at > now() - (${CSV_DAYS} || ' days')::interval+ order by created_at desc+ limit 5000+ `;++ const header = ['when', 'action', 'resource_id', 'ip', 'user_agent', 'meta'];+ const lines = [header.join(',')];+ for (const r of rows) {+ lines.push([+ csvEscape(new Date(r.created_at).toISOString()),+ csvEscape(r.action),+ csvEscape(r.resource_id),+ csvEscape(r.ip),+ csvEscape(r.user_agent),+ csvEscape(r.meta),+ ].join(','));+ }++ const filename = `audit-log-${new Date().toISOString().slice(0, 10)}.csv`;+ res.statusCode = 200;+ res.setHeader('content-type', 'text/csv; charset=utf-8');+ res.setHeader('content-disposition', `attachment; filename="${filename}"`);+ res.setHeader('cache-control', 'no-store');+ res.end(lines.join('\n') + '\n');+}diff --git a/api/auth/[action].js b/api/auth/[action].jsindex 592195e67..7d7ea12b8 100644--- a/api/auth/[action].js+++ b/api/auth/[action].js@@ -16,6 +16,7 @@ import { parse, loginBody, registerBody, usernameRegisterBody, username as usernimport { sendPasswordResetEmail, sendVerificationEmail } from '../_lib/email.js';import { generateReferralCode } from '../_lib/referrals.js';import { seedDefaultAgent } from '../_lib/seed-default-agent.js';+import { logAudit } from '../_lib/audit.js';import { z } from 'zod';const APP_ORIGIN = process.env.APP_ORIGIN || 'https://three.ws';@@ -39,6 +40,7 @@ async function handleLogin(req, res) {await destroySession(req);const token = await createSession({ userId: user.id, userAgent: req.headers['user-agent'], ip });res.setHeader('set-cookie', sessionCookie(token));+ logAudit({ userId: user.id, action: 'login', req });const { password_hash: _p, ...safe } = user;return json(res, 200, { user: safe });}@@ -48,8 +50,10 @@ async function handleLogin(req, res) {async function handleLogout(req, res) {if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;if (!method(req, res, ['POST'])) return;+ const sessionUser = await getSessionUser(req).catch(() => null);await destroySession(req);res.setHeader('set-cookie', sessionCookie('', { clear: true }));+ if (sessionUser) logAudit({ userId: sessionUser.id, action: 'logout', req });return json(res, 200, { ok: true });}@@ -185,6 +189,17 @@ async function handleProfile(req, res) {if (taken[0]) return error(res, 409, 'conflict', 'username already taken');}const [updated] = await sql`update users set username = coalesce(${body.username ?? null}, username), display_name = coalesce(${body.display_name ?? null}, display_name), updated_at = now() where id = ${user.id} and deleted_at is null returning id, display_name, username`;+ logAudit({+ userId: user.id,+ action: 'update_profile',+ meta: {+ fields: [+ body.username !== undefined ? 'username' : null,+ body.display_name !== undefined ? 'display_name' : null,+ ].filter(Boolean),+ },+ req,+ });return json(res, 200, { user: updated });}diff --git a/api/auth/wallets/[action].js b/api/auth/wallets/[action].jsindex 80525657f..579785f07 100644--- a/api/auth/wallets/[action].js+++ b/api/auth/wallets/[action].js@@ -65,6 +65,11 @@ export default wrap(async (req, res) => {return handleLinkSolana(req, res);}+ // /api/auth/wallets/primary — mark one of the caller's wallets as primary+ if (action === 'primary') {+ return handleSetPrimary(req, res);+ }+// /api/auth/wallets/<address> — unlink wallet (action carries the address)return handleUnlinkWallet(req, res, action);});@@ -197,6 +202,13 @@ async function handleLinkWallet(userId, req, res) {insert into user_wallets (user_id, address, chain_id, is_primary)values (${userId}, ${addrLower}, ${chainId}, false)`;+ logAudit({+ userId,+ action: 'link_wallet',+ resourceId: addrLower,+ meta: { chain_id: chainId },+ req,+ });return json(res, 201, { wallet: { address: claimed, chain_id: chainId } });}@@ -437,12 +449,14 @@ async function handleLinkSolana(req, res) {action: 'unlink_wallet_transferred',resourceId: addr,meta: { to_user_id: session.id },+ req,});logAudit({userId: session.id,action: 'link_wallet_solana_takeover',resourceId: addr,meta: { from_user_id: conflict.user_id },+ req,});return json(res, 200, {wallet: { address: addr, chain_type: 'solana', chain_id: chain },@@ -454,11 +468,61 @@ async function handleLinkSolana(req, res) {insert into user_wallets (user_id, address, chain_type, is_primary)values (${session.id}, ${addr}, 'solana', false)`;- logAudit({ userId: session.id, action: 'link_wallet_solana', resourceId: addr });+ logAudit({ userId: session.id, action: 'link_wallet_solana', resourceId: addr, req });return json(res, 201, { wallet: { address: addr, chain_type: 'solana', chain_id: chain } });}+// ── Set primary ────────────────────────────────────────────────────────────+// Mark one of the caller's wallets as primary; demote every other row in+// the same transaction so exactly one wallet is primary at a time.+//+// Body: { address }. EVM addresses are stored lowercased; Solana base58 is+// case-sensitive — we try the literal address first, then the lowercased+// form as a fallback for EVM callers who send a mixed-case checksum.++async function handleSetPrimary(req, res) {+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['POST'])) return;++ const session = await getSessionUser(req);+ if (!session) return error(res, 401, 'unauthorized', 'sign in required');++ const body = await readJson(req).catch(() => null);+ const rawAddress = body?.address;+ if (!rawAddress || typeof rawAddress !== 'string') {+ return error(res, 400, 'validation_error', 'address required');+ }++ const candidates = [rawAddress, rawAddress.toLowerCase()].filter(+ (v, i, a) => a.indexOf(v) === i,+ );++ const [wallet] = await sql`+ select id, address, is_primary+ from user_wallets+ where user_id = ${session.id}+ and address = any(${candidates}::text[])+ limit 1+ `;+ if (!wallet) return error(res, 404, 'not_found', 'wallet not found');++ if (!wallet.is_primary) {+ await sql.transaction([+ sql`update user_wallets set is_primary = false where user_id = ${session.id} and is_primary = true`,+ sql`update user_wallets set is_primary = true where id = ${wallet.id}`,+ ]);+ logAudit({+ userId: session.id,+ action: 'set_primary_wallet',+ resourceId: wallet.address,+ req,+ });+ }++ return json(res, 200, { primary: { address: wallet.address } });+}+// ── Unlink ─────────────────────────────────────────────────────────────────// Unlink a wallet from authenticated user.// Refuse if it's the only wallet AND user has no email+password.@@ -506,7 +570,7 @@ async function handleUnlinkWallet(req, res, address) {// 4. Delete the wallet.await sql`delete from user_wallets where user_id = ${session.id} and address = ${addrLower}`;- logAudit({ userId: session.id, action: 'unlink_wallet', resourceId: addrLower });+ logAudit({ userId: session.id, action: 'unlink_wallet', resourceId: addrLower, req });return json(res, 200, { removed: true });}diff --git a/api/widgets/[id]/[action].js b/api/widgets/[id]/[action].jsindex 35ef12734..fd4ced3aa 100644--- a/api/widgets/[id]/[action].js+++ b/api/widgets/[id]/[action].js@@ -818,6 +818,7 @@ async function handleStats(req, res) {recentChats,topQuestions,knowledgeSummary,+ sessionStats,] = await Promise.all([recentViewsByDay(id),topAggregates(id, 'referer_host'),@@ -827,6 +828,7 @@ async function handleStats(req, res) {isTalkingAgent ? recentChatsByDay(id) : Promise.resolve(null),isTalkingAgent ? topQuestionsFor(id) : Promise.resolve(null),isTalkingAgent ? knowledgeSummaryFor(id) : Promise.resolve(null),+ isTalkingAgent ? sessionStatsFor(id) : Promise.resolve(null),]);res.setHeader('cache-control', 'private, max-age=30');@@ -841,6 +843,9 @@ async function handleStats(req, res) {recent_chats_7d: recentChats,top_questions: topQuestions,knowledge: knowledgeSummary,+ // Rolling-7-day chat session metrics derived from widget_chat_threads.+ // Null for non-talking-agent widgets (no chat threads exist).+ sessions_7d: sessionStats,},});}@@ -972,6 +977,40 @@ async function topQuestionsFor(id) {}}+// Rolling 7-day chat-session metrics. Sessions are widget_chat_threads rows+// where the visitor sent at least one message in the window. Avg duration is+// (last_message_at − started_at) clamped at zero so single-message threads+// register as a 0s session rather than a negative outlier.+async function sessionStatsFor(id) {+ try {+ const [row] = await sql`+ select+ count(*)::int as thread_count,+ coalesce(+ avg(+ greatest(extract(epoch from (last_message_at - started_at)), 0)+ )::float,+ 0+ ) as avg_seconds,+ coalesce(+ sum(message_count)::int,+ 0+ ) as total_messages+ from widget_chat_threads+ where widget_id = ${id}+ and started_at >= now() - interval '7 days'+ `;+ return {+ thread_count: Number(row?.thread_count || 0),+ avg_seconds: Math.round(Number(row?.avg_seconds || 0)),+ total_messages: Number(row?.total_messages || 0),+ };+ } catch (err) {+ if (/relation .* does not exist/i.test(err?.message || '')) return null;+ throw err;+ }+}+// Lightweight knowledge summary — pulled into stats so the dashboard's main// card can show "5 docs · 42 chunks" without a second round trip.async function knowledgeSummaryFor(id) {diff --git a/scripts/_dn-audit.mjs b/scripts/_dn-audit.mjsnew file mode 100644index 000000000..7de81e2b3--- /dev/null+++ b/scripts/_dn-audit.mjs@@ -0,0 +1,143 @@+// 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-drawer-verify.mjs b/scripts/_dn-drawer-verify.mjsnew file mode 100644index 000000000..c570c1ab1--- /dev/null+++ b/scripts/_dn-drawer-verify.mjs@@ -0,0 +1,94 @@+import { chromium } from 'playwright';+const PORT = process.argv[2] || '3012';+const b = await chromium.launch({ args: ['--use-gl=swiftshader','--no-sandbox'] });+const ctx = await b.newContext({ viewport: { width: 1440, height: 900 } });+const p = await ctx.newPage();+const errs = [];+p.on('pageerror', e => errs.push('PAGEERROR ' + e.message.slice(0, 200)));+p.on('console', m => { if (m.type() === 'error') { const t = m.text(); if (!/Failed to load resource/.test(t)) errs.push('[err] ' + t.slice(0, 200)); }});++const FAKE_ME = { id: 'u_test', email: '[email protected]', display_name: 'Demo', handle: 'demo' };++async function setupAuthed() {+ await p.unroute('**/api/notifications**').catch(() => {});+ await p.route('**/api/auth/me', (route) => route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(FAKE_ME) }));+ await p.route('**/api/csrf-token', (route) => route.fulfill({ status: 200, contentType: 'application/json', body: '{"token":"t"}' }));+ await p.route('**/api/notifications**', (route) => route.fulfill({+ status: 200, contentType: 'application/json',+ body: JSON.stringify({ unread_count: 2, notifications: [+ { id: 'n1', type: 'payment_received', payload: { amount_usdc: 500000, from: '0xabc123def456' }, created_at: new Date(Date.now() - 2 * 60 * 1000).toISOString(), read_at: null },+ { id: 'n2', type: 'skill_purchased', payload: { amount_usdc: 100000, buyer: 'alice.eth' }, created_at: new Date(Date.now() - 17 * 60 * 1000).toISOString(), read_at: null },+ { id: 'n3', type: 'withdrawal_completed', payload: { amount_usdc: 2500000, tx: 'sig123' }, created_at: new Date(Date.now() - 26 * 60 * 60 * 1000).toISOString(), read_at: '2026-05-24T00:00:00Z' },+ { id: 'n4', type: 'auth_signin', payload: { ip: '198.51.100.10' }, created_at: new Date(Date.now() - 2 * 86400000).toISOString(), read_at: null },+ ] }),+ }));+}++const URL = `http://127.0.0.1:${PORT}/dashboard-next`;++console.log('--- A. drawer CLOSED state ---');+await setupAuthed();+await p.goto(URL, { waitUntil: 'domcontentloaded' });+await p.evaluate(() => { localStorage.removeItem('dn:drawer:open'); localStorage.removeItem('dn:drawer:filters'); });+await p.reload({ waitUntil: 'domcontentloaded' });+await p.waitForSelector('.dn-shell', { timeout: 10000 });+await p.waitForTimeout(1500);+const closed = await p.evaluate(() => {+ const d = document.querySelector('.dn-drawer');+ return { display: d ? getComputedStyle(d).display : null, width: d ? d.getBoundingClientRect().width : null, shellOpen: document.querySelector('.dn-shell').getAttribute('data-drawer-open') };+});+console.log('closed=', JSON.stringify(closed));+await p.screenshot({ path: '/tmp/dn-drawer-closed.png' });++console.log('--- B. drawer OPEN with events ---');+await p.evaluate(() => { localStorage.setItem('dn:drawer:open', '1'); });+await p.reload({ waitUntil: 'domcontentloaded' });+await p.waitForSelector('.dn-drawer[aria-label="Activity"]', { state: 'visible', timeout: 10000 });+await p.waitForTimeout(8000);+const opened = await p.evaluate(() => {+ const d = document.querySelector('.dn-drawer');+ const rows = document.querySelectorAll('.dnd-row');+ const days = [...document.querySelectorAll('.dnd-day')].map(e => e.innerText);+ const reads = [...rows].map(r => r.getAttribute('data-read'));+ return { width: d.getBoundingClientRect().width, rowCount: rows.length, days, reads };+});+console.log('opened=', JSON.stringify(opened));+const dEl = await p.$('.dn-drawer');+await dEl.screenshot({ path: '/tmp/dn-drawer-open.png' });++console.log('--- C. expand row ---');+await p.click('.dnd-row');+await p.waitForTimeout(400);+await dEl.screenshot({ path: '/tmp/dn-drawer-expanded.png' });++console.log('--- D. filter chip ---');+// Collapse first+await p.click('.dnd-row');+await p.waitForTimeout(150);+await p.click('.dnd-chip[data-filter="payment.received"]');+await p.waitForTimeout(400);+const filtered = await p.evaluate(() => ({+ visibleRows: document.querySelectorAll('.dnd-row').length,+ pressed: [...document.querySelectorAll('.dnd-chip[aria-pressed="true"]')].map(c => c.getAttribute('data-filter')),+ ls: localStorage.getItem('dn:drawer:filters'),+}));+console.log('filtered=', JSON.stringify(filtered));+await dEl.screenshot({ path: '/tmp/dn-drawer-filtered.png' });++console.log('--- E. signed-out state ---');+await p.unroute('**/api/notifications**');+await p.route('**/api/notifications**', (route) => route.fulfill({ status: 401, contentType: 'application/json', body: '{"error":"unauthorized"}' }));+await p.evaluate(() => { localStorage.removeItem('dn:drawer:filters'); });+await p.reload({ waitUntil: 'domcontentloaded' });+await p.waitForSelector('.dn-drawer', { state: 'visible' });+await p.waitForTimeout(7000);+const so = await p.evaluate(() => document.querySelector('.dn-drawer .dn-empty h3')?.innerText);+console.log('signedOut h3=', so);+const drEl = await p.$('.dn-drawer');+await drEl.screenshot({ path: '/tmp/dn-drawer-signedout.png' });++console.log('--- console errors ---');+for (const e of errs) console.log(' ', e);+if (errs.length) { console.log('FAIL: errors above'); process.exitCode = 1; }++await b.close();diff --git a/scripts/_dn-full-audit.mjs b/scripts/_dn-full-audit.mjsnew file mode 100644index 000000000..18a29a650--- /dev/null+++ b/scripts/_dn-full-audit.mjs@@ -0,0 +1,85 @@+// Authenticated, full-stack audit of every /dashboard-next page.+// - Logs in via the real session API (fixture user, falls back to register).+// - Visits each page, waits for shell + 1.5s settle, snaps fullPage screenshot.+// - Reports pageerror / console.error / requestfailed / 4xx-5xx /api/ responses.+//+// Usage: node scripts/_dn-full-audit.mjs [base-url]+import { chromium } from 'playwright';++const base = (process.argv[2] || 'http://127.0.0.1:3010').replace(/\/$/, '');++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 fixtureEmail = process.env.DN_FIXTURE_EMAIL || '[email protected]';+const fixturePass = process.env.DN_FIXTURE_PASS || 'PassP4ss!2026';++const browser = await chromium.launch({ args: ['--use-gl=swiftshader', '--no-sandbox'] });+const ctx = await browser.newContext({ viewport: { width: 1440, height: 900 } });++async function ensureSession() {+ let login = await ctx.request.post(`${base}/api/auth/login`, {+ data: { email: fixtureEmail, password: fixturePass },+ headers: { 'content-type': 'application/json' },+ });+ if (login.status() === 200) return 'login';+ const reg = await ctx.request.post(`${base}/api/auth/register`, {+ data: { email: fixtureEmail, password: fixturePass, display_name: 'DN Audit' },+ headers: { 'content-type': 'application/json' },+ });+ if (reg.status() !== 201) return `register:${reg.status()}`;+ login = await ctx.request.post(`${base}/api/auth/login`, {+ data: { email: fixtureEmail, password: fixturePass },+ headers: { 'content-type': 'application/json' },+ });+ return login.status() === 200 ? 'registered+login' : `login:${login.status()}`;+}+console.log('session', await ensureSession());++const summary = [];+for (const { slug, path } of PAGES) {+ const page = await ctx.newPage();+ const errs = [];+ const bad = [];+ page.on('pageerror', (e) => errs.push(`pageerror: ${e.message.slice(0, 220)}`));+ page.on('console', (m) => {+ if (m.type() === 'error') errs.push(`console.error: ${m.text().slice(0, 220)}`);+ });+ page.on('requestfailed', (r) => errs.push(`requestfailed: ${r.url()} ${r.failure()?.errorText || ''}`));+ page.on('response', (r) => {+ if (r.status() >= 400 && /\/api\//.test(r.url())) {+ bad.push(`${r.status()} ${r.request().method()} ${r.url().replace(base, '')}`);+ }+ });++ try {+ await page.goto(`${base}${path}`, { waitUntil: 'networkidle', timeout: 30000 });+ await page.waitForSelector('.dn-shell .dn-rail-item', { timeout: 15000 });+ await page.waitForTimeout(2000);+ } catch (e) {+ errs.push(`nav: ${e.message.slice(0, 220)}`);+ }+ const shot = `/tmp/dn-full-${slug}.png`;+ try { await page.screenshot({ path: shot, fullPage: true }); } catch {}+ summary.push({ slug, path, errors: errs, badRequests: bad, shot });+ await page.close();+}++await browser.close();+console.log('\n=== DASHBOARD-NEXT FULL AUDIT ===\n');+let total = 0;+for (const r of summary) {+ const count = r.errors.length + r.badRequests.length;+ total += count;+ console.log(`── ${r.slug.padEnd(9)} ${r.path} issues=${count} shot=${r.shot}`);+ for (const e of r.errors) console.log(` ! ${e}`);+ for (const b of r.badRequests) console.log(` @ ${b}`);+}+console.log(`\nTOTAL ISSUES: ${total}\n`);diff --git a/scripts/_dn-widgets-shot.mjs b/scripts/_dn-widgets-shot.mjsnew file mode 100644index 000000000..d2560c24d--- /dev/null+++ b/scripts/_dn-widgets-shot.mjs@@ -0,0 +1,84 @@+// Smoke-test the /dashboard-next/widgets page authenticated.+// Registers a throwaway account so /api/widgets returns the empty-state, then+// captures a screenshot and pageerror/console messages. Exit non-zero on any.+import { chromium } from 'playwright';++const url = process.argv[2] || 'http://127.0.0.1:3010/dashboard-next/widgets';+const out = process.argv[3] || '/tmp/dn-widgets.png';++const browser = await chromium.launch({ args: ['--use-gl=swiftshader', '--no-sandbox'] });+const ctx = await browser.newContext({ viewport: { width: 1440, height: 900 } });+const page = await ctx.newPage();++const errs = [];+page.on('pageerror', (e) => errs.push('PAGEERROR ' + e.message.slice(0, 200)));+page.on('console', (m) => {+ if (m.type() === 'error') errs.push('[console.error] ' + m.text().slice(0, 200));+});+page.on('requestfailed', (r) => {+ const u = r.url();+ if (u.startsWith('chrome-extension://')) return;+ errs.push('REQ FAIL ' + u + ' ' + (r.failure()?.errorText || ''));+});++const origin = new URL(url).origin;+const handle = 'dnwx' + Date.now().toString(36);+const regRes = await ctx.request.post(`${origin}/api/auth/register`, {+ data: {+ email: `${handle}@example.test`,+ password: 'PassP4ss!2026',+ display_name: 'Widget Smoke',+ },+ headers: { 'content-type': 'application/json' },+});+if (!regRes.ok()) {+ console.warn('[register]', regRes.status(), (await regRes.text()).slice(0, 200));+}++// Need a CSRF token to POST through the api helper used by /api/widgets.+const csrfRes = await ctx.request.get(`${origin}/api/csrf-token`);+const csrfTok = csrfRes.ok() ? (await csrfRes.json())?.token : null;++// Seed two widgets so the populated-grid path actually renders, including+// the lazy-iframe + per-card stats lookups. Type 'turntable' so we don't+// need an avatar wired up just to make a row exist.+for (let i = 1; i <= 2; i++) {+ const created = await ctx.request.post(`${origin}/api/widgets`, {+ data: {+ type: 'turntable',+ name: `Smoke widget ${i}`,+ config: {},+ is_public: true,+ },+ headers: {+ 'content-type': 'application/json',+ ...(csrfTok ? { 'x-csrf-token': csrfTok } : {}),+ },+ });+ if (!created.ok()) {+ console.warn('[create widget]', created.status(), (await created.text()).slice(0, 200));+ }+}++await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 60000 });+await page.waitForSelector('.dn-shell .dn-rail-item', { timeout: 20000 });+// Empty state OR cards both qualify as "rendered" — wait for either.+await page.waitForFunction(+ () =>+ document.querySelector('[data-slot="grid"] [data-card]') ||+ document.querySelector('[data-slot="grid"] .dn-empty') ||+ document.querySelector('[data-slot="grid"] [data-retry]'),+ null,+ { timeout: 20000 },+);+// Give iframes a beat to start mounting + stats to come back.+await page.waitForTimeout(2500);+await page.screenshot({ path: out, fullPage: false });+console.log('saved', out);++if (errs.length) {+ console.log('errors:');+ for (const e of errs) console.log(' ', e);+ process.exit(1);+}+await browser.close();diff --git a/src/dashboard-next/components/drawer.js b/src/dashboard-next/components/drawer.jsindex e8f0a7c49..5cf9244e2 100644--- a/src/dashboard-next/components/drawer.js+++ b/src/dashboard-next/components/drawer.js@@ -17,6 +17,7 @@ const RELTIME_TICK_MS = 30_000;const SSE_CONNECT_TIMEOUT_MS = 5_000;const NOTIFICATIONS_PATH = '/api/notifications?limit=50';const SSE_PATH = '/api/events/stream';+const SEEN_IDS_CAP = 1000;const CATEGORIES = [{ key: 'widget.view', label: 'Widget views' },@@ -151,6 +152,8 @@ export function renderDrawer() {transition: background 120ms;}.dnd-row:hover { background: rgba(255, 255, 255, 0.03); }+ .dnd-row[data-read="1"] .dnd-row-title { color: var(--nxt-ink-dim); font-weight: 400; }+ .dnd-row[data-read="1"] .dnd-row-icon { opacity: 0.6; }.dnd-row[data-fresh="1"] { animation: dnd-slide-in 200ms ease-out, dnd-highlight 1800ms ease-out; }@keyframes dnd-slide-in {from { transform: translateY(-6px); opacity: 0; }@@ -434,6 +437,7 @@ function startPolling() {async function pollOnce() {if (!state.open) return;+ let scheduleNext = true;try {const data = await get(NOTIFICATIONS_PATH);const list = Array.isArray(data?.notifications) ? data.notifications : [];@@ -444,6 +448,7 @@ async function pollOnce() {state.loadedOnce = true;state.pollFails = 0;state.pollDelay = POLL_INTERVAL_MS;+ pruneSeenIds();setStatus(state.events.length ? 'ok' : '');if (!state.events.length) renderEmpty();} catch (err) {@@ -452,23 +457,36 @@ async function pollOnce() {state.pollDelay = Math.min(state.pollDelay * 2, POLL_MAX_INTERVAL_MS);setStatus('reconnecting');}- if (!state.loadedOnce && state.pollFails === 1) {- // First load failed — keep skeletons visible so the UI doesn't- // flash empty between attempts.+ // 401 = signed out. Don't keep nagging the server — give the user a+ // quiet "sign in" empty state instead. Polling resumes on next open.+ if (err && err.status === 401) {+ scheduleNext = false;+ state.loadedOnce = true;+ renderSignedOut();+ setStatus('');+ return;}- // 404 from a missing notifications endpoint should still show empty- // state rather than spinning forever.+ // 404 from a missing notifications endpoint: surface the empty state+ // rather than spinning forever, but keep retrying in case the+ // endpoint comes back (handy during local backend restarts).if (err && err.status === 404 && !state.loadedOnce) {state.loadedOnce = true;renderEmpty();}} finally {- if (state.open) {+ if (scheduleNext && state.open) {state.pollTimer = setTimeout(pollOnce, state.pollDelay);}}}+function pruneSeenIds() {+ if (state.seenIds.size <= SEEN_IDS_CAP) return;+ // Keep only IDs that correspond to events we're still rendering.+ const live = new Set(state.events.map((e) => e.id));+ state.seenIds = live;+}+// ── Event normalization ──────────────────────────────────────────────────function normalizeNotification(n) {@@ -481,6 +499,7 @@ function normalizeNotification(n) {category,payload: n.payload && typeof n.payload === 'object' ? n.payload : {},created_at: n.created_at || n.timestamp || new Date().toISOString(),+ read: Boolean(n.read_at),};}@@ -526,6 +545,17 @@ function renderEmpty() {</div>`;}+function renderSignedOut() {+ state.listEl.setAttribute('aria-busy', 'false');+ const ret = encodeURIComponent(location.pathname + location.search);+ state.listEl.innerHTML = `+ <div class="dn-empty" style="margin:18px 16px">+ <h3>Sign in to see your activity</h3>+ <p>Your session expired or you're not signed in.</p>+ <a class="dn-btn primary" href="/login?return=${ret}" style="margin-top:10px">Sign in</a>+ </div>`;+}+function renderList() {state.listEl.setAttribute('aria-busy', 'false');@@ -558,8 +588,9 @@ function renderRow(ev) {const colour = COLOR_FOR_CATEGORY[ev.category] || COLOR_FOR_CATEGORY.unknown;const icon = ICONS[ev.category] || ICONS.unknown;const fresh = ev.__fresh ? '1' : '0';+ const read = ev.read ? '1' : '0';return `- <div class="dnd-row" role="article" aria-expanded="false" data-id="${esc(ev.id)}" data-fresh="${fresh}">+ <div class="dnd-row" role="article" aria-expanded="false" data-id="${esc(ev.id)}" data-fresh="${fresh}" data-read="${read}"><span class="dnd-row-icon" style="color:${colour};background:rgba(255,255,255,0.03)">${icon}</span><div class="dnd-row-body"><div class="dnd-row-title">${esc(detail.title)}</div>@@ -583,7 +614,7 @@ function describeEvent(ev) {return {title: 'Widget viewed',subtitle: w ? String(w) : '',- link: w ? { label: 'Open in viewer', href: `/dashboard/widgets/${encodeURIComponent(w)}` } : null,+ link: w ? { label: 'Open in studio', href: `/widget-studio?id=${encodeURIComponent(w)}` } : null,};}case 'widget.chat_turn': {@@ -592,13 +623,12 @@ function describeEvent(ev) {return {title: 'Chat turn',subtitle: msg ? `"${String(msg).slice(0, 90)}"` : '',- link: w ? { label: 'Open transcript', href: `/dashboard/widgets/${encodeURIComponent(w)}` } : null,+ link: w ? { label: 'Open transcript', href: `/widget-studio?id=${encodeURIComponent(w)}` } : null,};}case 'payment.received': {const amount = formatAmount(p);const from = p.from || p.buyer || p.payer || p.referrer || '';- const tx = p.tx || p.transaction || p.signature || '';const title = ev.type === 'referral_earned' ? 'Referral earned': ev.type === 'skill_purchased' ? 'Skill purchased': ev.type === 'skill_purchase_confirmed' ? 'Purchase confirmed'@@ -606,7 +636,7 @@ function describeEvent(ev) {return {title,subtitle: [amount, from && `from ${shorten(from)}`].filter(Boolean).join(' · '),- link: tx ? { label: 'Open payment', href: `/dashboard/x402.html` } : null,+ link: { label: 'Open monetize', href: '/dashboard-next/monetize' },};}case 'avatar.updated': {@@ -615,7 +645,8 @@ function describeEvent(ev) {return {title: 'Avatar updated',subtitle: name || (id ? shorten(id) : ''),- link: id ? { label: 'Open avatar', href: `/dashboard-next/avatars` } : null,+ link: id ? { label: 'Open avatar', href: `/avatars/${encodeURIComponent(id)}` }+ : { label: 'Open avatars', href: '/dashboard-next/avatars' },};}case 'withdrawal.completed': {diff --git a/src/dashboard-next/pages/home.js b/src/dashboard-next/pages/home.jsindex 6bcd053fd..2dfd5d176 100644--- a/src/dashboard-next/pages/home.js+++ b/src/dashboard-next/pages/home.js@@ -19,13 +19,7 @@ const STATE = {(async function boot() {const main = await mountShell();- const env = await requireUser().catch(() => null);- const me = env?.user ?? env;- if (!me || !me.id) {- const ret = encodeURIComponent(location.pathname + location.search);- location.href = `/login?return=${ret}`;- return;- }+ const me = await requireUser();const greeting = me.display_name || me.username || (me.email ? me.email.split('@')[0] : 'creator');main.innerHTML = `@@ -81,7 +75,16 @@ const STATE = {if (STATE.relTimeHandle) clearInterval(STATE.relTimeHandle);});})().catch((err) => {- console.error('[dashboard-next/home] boot failed', err);+ if (err?.message === 'redirecting') return;+ const main = document.querySelector('.dn-main-inner') || document.body;+ main.innerHTML = `+ <h1 class="dn-h1">Overview</h1>+ <div class="dn-panel" style="border-color:rgba(255,107,138,0.3)">+ <div class="dn-panel-title" style="color:var(--nxt-danger)">Couldn't load this page</div>+ <div class="dn-panel-sub">${(err && err.message ? err.message : 'unknown error').replace(/[<>&]/g, (c) => ({ '<':'<','>':'>','&':'&' }[c]))}</div>+ <button class="dn-btn" onclick="location.reload()">Reload</button>+ </div>+ `;});// ── Skeletons ─────────────────────────────────────────────────────────────@@ -453,11 +456,6 @@ function tweenNumber(node, from, to, finalLabel) {function injectStyles() {if (document.getElementById('dnx-home-styles')) return;const css = `- /* Foundation workaround: the drawer component injects an inline style- forcing display:flex on .dn-drawer, which defeats the shell's- closed-state hide rule and steals a phantom grid column. */- .dn-shell[data-drawer-open='false'] .dn-drawer { display: none !important; }-.dnx-grid {display: grid;grid-template-columns: minmax(0, 1fr) 340px;diff --git a/src/dashboard-next/pages/widgets.js b/src/dashboard-next/pages/widgets.jsindex 36c52d04a..ac211852b 100644--- a/src/dashboard-next/pages/widgets.js+++ b/src/dashboard-next/pages/widgets.js@@ -10,6 +10,10 @@ import { requireUser, get, post, del, esc } from '../api.js';const STATS_DAYS = 7;const SKELETON_COUNT = 6;+// Module-scoped cache so card-level handlers and duplicate flows can look up+// a widget by id without re-querying the list.+const WIDGETS = new Map();+(async function boot() {const main = await mountShell();await requireUser();@@ -55,10 +59,13 @@ async function render(main) {return;}- // Render cards immediately (posters first, stats pending).+ // Refresh the lookup cache; render cards immediately (poster-first, stats+ // pending in parallel below).+ WIDGETS.clear();+ for (const w of widgets) WIDGETS.set(w.id, w);grid.innerHTML = widgets.map(cardHtml).join('');- wireCardBehavior(grid, widgets);+ wireCardBehavior(grid);observeIframes(grid);// Fetch stats per widget in parallel; update each card + the aggregate strip.@@ -116,7 +123,8 @@ function cardHtml(w) {</div></div></div>- <button class="dn-wx-menu-btn" data-menu type="button" aria-label="Widget menu">+ <button class="dn-wx-menu-btn" data-menu type="button"+ aria-label="Widget menu" aria-haspopup="menu" aria-expanded="false"><svg viewBox="0 0 16 16" width="16" height="16" fill="currentColor" aria-hidden="true"><circle cx="8" cy="3" r="1.4"/><circle cx="8" cy="8" r="1.4"/><circle cx="8" cy="13" r="1.4"/></svg>@@ -150,6 +158,8 @@ function markStatsFailed(card) {function renderStatStrip(strip, widgetCount, statsResults) {let views = 0;let turns = 0;+ let weightedDurationSec = 0;+ let totalThreads = 0;let anyStat = false;for (const r of statsResults) {if (r.status !== 'fulfilled') continue;@@ -157,12 +167,16 @@ function renderStatStrip(strip, widgetCount, statsResults) {const s = r.value?.stats || {};views += sumDaily(s.recent_views_7d);turns += sumDaily(s.recent_chats_7d);+ const ss = s.sessions_7d;+ if (ss && Number(ss.thread_count) > 0) {+ weightedDurationSec += Number(ss.avg_seconds || 0) * Number(ss.thread_count);+ totalThreads += Number(ss.thread_count);+ }}- // "Avg session (s)" — there's no thread-duration field on /stats and we're- // instructed not to invent a new endpoint, so the slot stays a dash until- // stats gains a duration field.- const avgSession = '—';+ const avgSession = totalThreads > 0+ ? formatDuration(weightedDurationSec / totalThreads)+ : '—';const allZero = widgetCount === 0 && views === 0 && turns === 0;if (allZero) {@@ -174,7 +188,7 @@ function renderStatStrip(strip, widgetCount, statsResults) {`<span><strong>${formatCount(widgetCount)}</strong> ${widgetCount === 1 ? 'widget' : 'widgets'}</span>`,`<span><strong>${anyStat ? formatCount(views) : '—'}</strong> views (7d)</span>`,`<span><strong>${anyStat ? formatCount(turns) : '—'}</strong> chat turns (7d)</span>`,- `<span><strong>${avgSession}</strong> avg session (s)</span>`,+ `<span><strong>${avgSession}</strong> avg session</span>`,];strip.innerHTML = parts.join('<span class="dn-wx-sep">·</span>');strip.hidden = false;@@ -182,11 +196,7 @@ function renderStatStrip(strip, widgetCount, statsResults) {// ── Card interactions (menu, popover, duplicate, delete) ─────────────────-const WIDGETS = new Map();--function wireCardBehavior(grid, widgets) {- for (const w of widgets) WIDGETS.set(w.id, w);-+function wireCardBehavior(grid) {grid.addEventListener('click', (ev) => {const menuBtn = ev.target.closest('[data-menu]');if (menuBtn) {@@ -208,10 +218,12 @@ function wireCardBehavior(grid, widgets) {function openMenu(anchor, card, widget) {closeAllMenus();+ anchor.setAttribute('aria-expanded', 'true');const menu = document.createElement('div');menu.className = 'dn-wx-menu';menu.setAttribute('role', 'menu');+ menu.dataset.anchor = anchor.dataset.cardAnchor || '';menu.innerHTML = `<button role="menuitem" data-act="studio">Open studio</button><button role="menuitem" data-act="embed">Copy embed snippet</button>@@ -226,14 +238,31 @@ function openMenu(anchor, card, widget) {menu.style.top = `${Math.round(r.bottom + window.scrollY + 4)}px`;menu.style.left = `${Math.round(r.right + window.scrollX - menu.offsetWidth)}px`;+ const firstItem = menu.querySelector('button[role="menuitem"]');+ firstItem?.focus({ preventScroll: true });+const dismiss = (ev) => {if (ev && menu.contains(ev.target)) return;menu.remove();+ anchor.setAttribute('aria-expanded', 'false');document.removeEventListener('mousedown', dismiss, true);document.removeEventListener('keydown', onKey, true);};const onKey = (ev) => {- if (ev.key === 'Escape') dismiss();+ if (ev.key === 'Escape') {+ dismiss();+ anchor.focus({ preventScroll: true });+ return;+ }+ if (ev.key === 'ArrowDown' || ev.key === 'ArrowUp') {+ ev.preventDefault();+ const items = [...menu.querySelectorAll('button[role="menuitem"]')];+ const i = items.indexOf(document.activeElement);+ const next = ev.key === 'ArrowDown'+ ? items[(i + 1 + items.length) % items.length]+ : items[(i - 1 + items.length) % items.length];+ next?.focus({ preventScroll: true });+ }};setTimeout(() => {document.addEventListener('mousedown', dismiss, true);@@ -261,6 +290,9 @@ function openMenu(anchor, card, widget) {}function closeAllMenus() {+ document.querySelectorAll('.dn-wx-menu-btn[aria-expanded="true"]').forEach((b) => {+ b.setAttribute('aria-expanded', 'false');+ });document.querySelectorAll('.dn-wx-menu').forEach((m) => m.remove());document.querySelectorAll('.dn-wx-popover.open').forEach((p) => p.classList.remove('open'));}@@ -349,6 +381,8 @@ function openEmbedPopover(anchor, widget) {};const pop = document.querySelector('[data-slot="popover"]');+ pop.setAttribute('role', 'dialog');+ pop.setAttribute('aria-label', 'Embed snippet');pop.innerHTML = `<div class="dn-wx-pop-head"><div class="dn-wx-pop-title">Embed snippet</div>@@ -475,14 +509,24 @@ function activateIframe(frame, force) {frame.appendChild(iframe);const play = frame.querySelector('[data-poster-play]');+ const poster = frame.querySelector('[data-poster-img]');if (force && play) play.style.display = 'none';- iframe.addEventListener('load', () => {+ // Reveal on real load, but cap the wait — three.js + GLB downloads inside+ // the widget can stall behind a slow network and we'd rather show a+ // half-loaded iframe than a poster forever. Also handles error events so+ // embeds that 404 still surface the failure to the user.+ let revealed = false;+ const reveal = () => {+ if (revealed) return;+ revealed = true;iframe.style.opacity = '1';- const poster = frame.querySelector('[data-poster-img]');if (poster) poster.style.opacity = '0';if (play) play.style.display = 'none';- });+ };+ iframe.addEventListener('load', reveal);+ iframe.addEventListener('error', reveal);+ setTimeout(reveal, 4000);}// ── Confirm modal ────────────────────────────────────────────────────────@@ -595,6 +639,20 @@ function formatCount(n) {return String(Math.round(v));}+// Render an integer number of seconds as a compact "Xs / Ym Xs / Hh Mm" string.+// Used by the aggregate strip — keep the value short so the strip stays a single+// line on a typical viewport even with four stats.+function formatDuration(sec) {+ const s = Math.max(0, Math.round(Number(sec) || 0));+ if (s < 60) return `${s}s`;+ const m = Math.floor(s / 60);+ const rs = s % 60;+ if (m < 60) return rs ? `${m}m ${rs}s` : `${m}m`;+ const h = Math.floor(m / 60);+ const rm = m % 60;+ return rm ? `${h}h ${rm}m` : `${h}h`;+}+function setText(el, text) {if (!el) return;el.textContent = text;