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
analytics: identify users in PostHog so funnels/cohorts work
nirholase75658dc2855
diff --git a/scripts/_dn-deep-audit.mjs b/scripts/_dn-deep-audit.mjsnew file mode 100644index 000000000..97d5b2a4e--- /dev/null+++ b/scripts/_dn-deep-audit.mjs@@ -0,0 +1,151 @@+// Deep audit: stub *every* /api/* call with realistic data so we surface+// real page-level bugs (not auth failures). Visits every dashboard-next+// page and reports console errors, page errors, failed network requests,+// and HTTP >=400 from the dev origin.+//+// Usage: node scripts/_dn-deep-audit.mjs [baseUrl] [outDir]++import { chromium } from 'playwright';++const BASE = process.argv[2] || 'http://127.0.0.1:3013';+const OUT_DIR = process.argv[3] || '/tmp';++const PAGES = [+ { name: 'home', path: '/dashboard-next' },+ { name: 'avatars', path: '/dashboard-next/avatars' },+ { name: 'library-animations', path: '/dashboard-next/library#tab=animations' },+ { name: 'library-memory', path: '/dashboard-next/library#tab=memory' },+ { name: 'library-strategy', path: '/dashboard-next/library#tab=strategy' },+ { name: 'library-voice', path: '/dashboard-next/library#tab=voice' },+ { name: 'widgets', path: '/dashboard-next/widgets' },+ { name: 'api', path: '/dashboard-next/api' },+ { name: 'monetize', path: '/dashboard-next/monetize' },+ { name: 'account', path: '/dashboard-next/account' },+];++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 AGENT_A = { id: '11111111-1111-1111-1111-111111111111', name: 'Argentina #10', skills: ['greet'], voice_id: 'EXAVITQu4vr4xnSDxMaL', voice_provider: 'elevenlabs', meta: { animations: [+ { name: 'wave', url: '/animations/robotexpressive.glb', source: 'preset', loop: false, addedAt: new Date(Date.now()-86400_000).toISOString() },+ { name: 'celebrate', url: '/animations/robotexpressive.glb', source: 'preset', loop: false },+]}, created_at: new Date().toISOString() };+const AGENT_B = { id: '22222222-2222-2222-2222-222222222222', name: 'Rider VR', skills: ['greet'], voice_id: null, voice_provider: 'browser', meta: { animations: [] }, created_at: new Date().toISOString() };++const AVATAR_1 = { id: 'av1', name: 'Argentina #10', slug: 'arg-10', visibility: 'public', model_url: 'https://three.ws/animations/soldier.glb', thumbnail_url: null, created_at: new Date(Date.now()-86400_000).toISOString() };++const WIDGET_1 = { id: 'w_demo1', name: 'Greeter', kind: 'agent', status: 'active', visibility: 'public', created_at: new Date(Date.now()-86400_000).toISOString(), config: { agent_id: AGENT_A.id }, embed_url: '/widget?id=w_demo1' };++const REVENUE = {+ summary: { gross_total: 12_500_000, fee_total: 500_000, net_total: 12_000_000, payment_count: 18 },+ by_skill: [],+ timeseries: Array.from({ length: 14 }, (_, i) => ({ period: new Date(Date.now()-(13-i)*86400_000).toISOString().slice(0,10), net_total: Math.round(200_000 + Math.random()*1_200_000), count: i+1 })),+};++const STUBS = [+ [/\/api\/auth\/me$/, () => ME],+ [/\/api\/csrf-token$/, () => ({ token: 'audit' })],+ [/\/api\/auth\/wallets/, () => ({ wallets: [] })],+ [/\/api\/avatars(\?|$)/, () => ({ avatars: [AVATAR_1], next_cursor: null, total: 1 })],+ [/\/api\/avatars\/[^/]+$/, () => ({ avatar: AVATAR_1 })],+ [/\/api\/agents(\?|$)/, () => ({ agents: [AGENT_A, AGENT_B] })],+ [/\/api\/agents\/me$/, () => ({ agent: AGENT_A })],+ [/\/api\/agent-memory\?agentId=11.*/, () => ({ entries: [+ { id: 'm1', agent_id: AGENT_A.id, type: 'project', content: 'Argentina #10 voice tuned for chant cadence.', salience: 0.7, createdAt: Date.now()-3600_000 },+ ]})],+ [/\/api\/agent-memory\?agentId=22.*/, () => ({ entries: [] })],+ [/\/api\/agent-memory$/, () => ({ entry: { id: 'mnew', agent_id: AGENT_A.id, type: 'project', content: 'new', salience: 0.6, createdAt: Date.now() }})],+ [/\/api\/agent-strategy.*id=11.*/, () => ({ data: { strategy: { objective: 'engage', max_position_sol: 0.5 } } })],+ [/\/api\/agent-strategy.*id=22.*/, () => ({ data: { strategy: null } })],+ [/\/api\/tts\/eleven\/voices$/, () => ({ enabled: true, voices: [+ { voice_id: 'EXAVITQu4vr4xnSDxMaL', name: 'Bella', category: 'premade', labels: {} },+ { voice_id: '21m00Tcm4TlvDq8ikWAM', name: 'Rachel', category: 'premade', labels: {} },+ ]})],+ [/\/api\/widgets(\?|$)/, () => ({ widgets: [WIDGET_1] })],+ [/\/api\/widgets\/[^/]+\/stats/, () => ({ stats: { views_7d: 412, turns_7d: 87, last_seen: new Date().toISOString() } })],+ [/\/api\/widgets\/[^/]+\/transcripts/, () => ({ transcripts: [] })],+ [/\/api\/widgets\/[^/]+\/og/, () => ({ image_url: null })],+ [/\/api\/widgets\/[^/]+$/, () => ({ widget: WIDGET_1 })],+ [/\/api\/keys$/, () => ({ keys: [{ id: 'k1', name: 'Production', prefix: 'sk_live', scopes: ['avatars:read', 'avatars:write'], created_at: new Date(Date.now()-86400_000).toISOString(), last_used_at: new Date().toISOString() }] })],+ [/\/api\/animations.*/, () => ({ animations: [] })],+ [/\/api\/billing\/revenue/, () => REVENUE],+ [/\/api\/billing\/withdrawals/, () => ({ withdrawals: [] })],+ [/\/api\/billing\/payout-wallets/, () => ({ wallets: [{ id: 'w1', address: '0xabc', chain_id: 8453, label: 'Base ops' }] })],+ [/\/api\/billing\/summary/, () => ({ plan: 'pro', limits: {}, usage: {} })],+ [/\/api\/subscriptions\/mine/, () => ({ subscriptions: [] })],+ [/\/api\/subscriptions\/plans/, () => ({ plans: [] })],+ [/\/api\/subscriptions(\?|$)/, () => ({ subscriptions: [] })],+ [/\/api\/users\/me\/earnings/, () => ({ pending_usd: 12.34, paid_total_usd: 100, currency: 'usd' })],+ [/\/api\/users\/me/, () => ({ user: ME })],+ [/\/api\/audit-log/, () => ({ events: [], next_cursor: null })],+ [/\/api\/notifications/, () => ({ notifications: [] })],+ [/\/api\/events/, () => ({ events: [] })],+ [/\/api\/agents\/[^/]+\/payments/, () => ({ payments: [], next_cursor: null })],+ [/\/api\/agents\/[^/]+\/voice/, () => ({ voice_provider: 'browser', voice_id: null, voice_cloned_at: null })],+ [/\/api\/_mcp\/embed-policy/, () => ({ policy: null })],+];++async function maybeStub(route) {+ const url = route.request().url();+ for (const [re, fn] of STUBS) {+ if (re.test(url)) {+ const body = fn();+ return route.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(body) });+ }+ }+ return route.fulfill({ status: 404, contentType: 'application/json', body: JSON.stringify({ error: 'unstubbed', url: url.replace(BASE, '') }) });+}++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 errs = { page: [], req: [], http: [], unstubbed: [] };+ p.on('pageerror', (e) => errs.page.push('PAGEERROR ' + e.message.slice(0, 260)));+ p.on('console', (m) => { if (m.type() === 'error') errs.page.push('CONSOLE ' + m.text().slice(0, 260)); });+ p.on('requestfailed', (r) => {+ const u = r.url();+ if (u.includes('posthog') || u.includes('analytics')) return;+ errs.req.push(`${u.replace(BASE, '')} ${r.failure()?.errorText || ''}`);+ });+ p.on('response', async (r) => {+ const u = r.url();+ if (!u.includes('/api/')) return;+ if (r.status() >= 400) {+ try {+ const txt = await r.text();+ if (txt.includes('unstubbed')) errs.unstubbed.push(`${r.status()} ${u.replace(BASE, '')}`);+ else errs.http.push(`${r.status()} ${u.replace(BASE, '')}`);+ } catch { errs.http.push(`${r.status()} ${u.replace(BASE, '')}`); }+ }+ });++ await ctx.route('**/api/**', maybeStub);++ 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) {+ errs.page.push('NAV_FAIL ' + e.message.slice(0, 200));+ }+ summary.push({ page: page.name, url: page.path, ...errs });+ await ctx.close();+}++await browser.close();++let totalProblems = 0;+for (const s of summary) {+ console.log(`\n=== ${s.page} (${s.url}) ===`);+ if (s.page.length) { console.log(' page errors:'); for (const e of s.page) console.log(' - ' + e); totalProblems += s.page.length; }+ if (s.req.length) { console.log(' failed requests:'); for (const e of s.req) console.log(' - ' + e); totalProblems += s.req.length; }+ if (s.http.length) { console.log(' http >=400:'); for (const e of s.http) console.log(' - ' + e); totalProblems += s.http.length; }+ if (s.unstubbed.length){ console.log(' unstubbed routes:'); for (const e of s.unstubbed) console.log(' - ' + e); totalProblems += s.unstubbed.length; }+ if (!s.page.length && !s.req.length && !s.http.length && !s.unstubbed.length) console.log(' clean');+}+console.log(`\n${totalProblems} problems across ${summary.length} pages.`);+process.exit(totalProblems ? 1 : 0);diff --git a/scripts/_dn-fullsweep.mjs b/scripts/_dn-fullsweep.mjsindex e1f06216e..db5ae5e29 100644--- a/scripts/_dn-fullsweep.mjs+++ b/scripts/_dn-fullsweep.mjs@@ -1,69 +1,67 @@-// 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.+// Full-sweep verifier — fresh browser per page, mocked auth.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' },+ { slug: '', name: 'overview' },+ { 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 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) {+async function runPage({ slug, name }) {+ const b = await chromium.launch({ args: ['--use-gl=swiftshader','--no-sandbox','--disable-gpu'] });+ const ctx = await b.newContext({ viewport: { width: 1440, height: 900 } });+ await ctx.route('**/api/auth/me', (r) => r.fulfill(json({ user: me })));+ await ctx.route('**/api/csrf-token', (r) => r.fulfill(json({ token: 'test-csrf' })));+ 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: [], summary: {}, withdrawals: [], wallets: [], plans: [] })));+ await ctx.route('**/api/notifications*', (r) => r.fulfill(json({ notifications: [] })));+ await ctx.route('**/api/subscriptions/**', (r) => r.fulfill(json({ subscriptions: [], plans: [] })));+ await ctx.route('**/api/events*', (r) => r.fulfill(json({ events: [] })));+ await ctx.route('**/api/users/**', (r) => r.fulfill(json({ })));+ await ctx.route('**/api/me/**', (r) => r.fulfill(json({ })));+ 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/memory*', (r) => r.fulfill(json({ memories: [] })));+ await ctx.route('**/api/voice*', (r) => r.fulfill(json({ voices: [] })));+ await ctx.route('**/api/sessions*', (r) => r.fulfill(json({ sessions: [] })));+ await ctx.route('**/api/auth/sessions*', (r) => r.fulfill(json({ sessions: [] })));+ await ctx.route('**/api/auth/wallets*', (r) => r.fulfill(json({ wallets: [] })));+ await ctx.route('**/api/embed-policy*', (r) => r.fulfill(json({ policy: { hosts: [] } })));+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 : ''}`;+ p.on('pageerror', (e) => errs.push(`PAGEERROR ${e.message.slice(0, 240)}`));+ p.on('console', (m) => { if (m.type() === 'error') errs.push(`[err] ${m.text().slice(0, 240)}`); });+ const url = `http://127.0.0.1:3010/dashboard-next${slug ? '/' + slug : ''}`;+ let status = 'OK';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 });+ await p.waitForFunction(() => document.querySelector('.dn-shell .dn-rail-item') != null, { timeout: 20000 });+ await p.waitForTimeout(1800);+ await p.screenshot({ path: `/tmp/dn-sweep-${name}.png`, fullPage: false });} catch (e) {- errs.push(`NAV/WAIT failed: ${e.message.slice(0, 220)}`);+ errs.push(`NAV/WAIT ${e.message.slice(0, 240)}`);+ status = 'FAILED';}- // 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();+ const relevant = errs.filter((e) => /PAGEERROR|TypeError|ReferenceError|SyntaxError|Uncaught|NAV\/WAIT/.test(e));+ console.log(`${name}: ${relevant.length === 0 ? status : 'ERRORS'}`);+ for (const e of relevant) console.log(` ${e}`);+ await b.close();+ return relevant.length;}-await b.close();-process.exit(totalErrs > 0 ? 1 : 0);+let total = 0;+for (const page of PAGES) total += await runPage(page);+process.exit(total > 0 ? 1 : 0);diff --git a/scripts/_dn-one.mjs b/scripts/_dn-one.mjsnew file mode 100644index 000000000..f389a0008--- /dev/null+++ b/scripts/_dn-one.mjs@@ -0,0 +1,43 @@+// Single-page screenshot, minimum-memory chromium config.+import { chromium } from 'playwright';+const url = process.argv[2];+const out = process.argv[3];+const b = await chromium.launch({+ args: [+ '--use-gl=swiftshader', '--no-sandbox', '--disable-gpu',+ '--disable-dev-shm-usage', '--single-process',+ '--disable-background-networking', '--disable-extensions',+ '--no-zygote', '--disable-features=IsolateOrigins,site-per-process',+ '--js-flags=--max-old-space-size=128',+ ],+});+const ctx = await b.newContext({ viewport: { width: 1280, height: 820 }, deviceScaleFactor: 1 });+await ctx.route('**/api/auth/me', (r) => r.fulfill({+ status: 200, contentType: 'application/json',+ body: JSON.stringify({ user: {+ id: 'usr_smoke', display_name: 'Smoke Test', handle: 'smoke',+ email: '[email protected]', email_verified: true,+ created_at: new Date(Date.now() - 9e9).toISOString(), plan: 'free',+ } }),+}));+await ctx.route('**/api/csrf-token', (r) => r.fulfill({+ status: 200, contentType: 'application/json',+ body: JSON.stringify({ token: 'csrf_smoke', expiresIn: 3600 }),+}));+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') errs.push('[err] ' + m.text().slice(0, 200)); });+try {+ await p.goto(url, { waitUntil: 'domcontentloaded', timeout: 45000 });+ await p.waitForSelector('.dn-shell .dn-rail-item', { timeout: 25000 });+ await p.waitForTimeout(1200);+ await p.screenshot({ path: out, fullPage: false });+ console.log('saved', out);+ for (const e of errs) console.log(' ' + e);+} catch (err) {+ console.log('FAIL', err?.message?.slice(0, 200) || err);+ for (const e of errs) console.log(' ' + e);+ process.exit(1);+}+await b.close();diff --git a/scripts/_dn-smoke.mjs b/scripts/_dn-smoke.mjsnew file mode 100644index 000000000..9efeb7122--- /dev/null+++ b/scripts/_dn-smoke.mjs@@ -0,0 +1,61 @@+import { chromium } from 'playwright';++const URL_BASE = 'http://127.0.0.1:3010';+const PAGES = [+ { slug: '', name: 'home' },+ { slug: '/avatars', name: 'avatars' },+ { slug: '/library', name: 'library' },+ { slug: '/widgets', name: 'widgets' },+ { slug: '/api', name: 'api' },+ { slug: '/monetize', name: 'monetize' },+ { slug: '/account', name: 'account' },+];++const b = await chromium.launch({ args: ['--use-gl=swiftshader','--no-sandbox','--disable-dev-shm-usage'] });+const ctx = await b.newContext({ viewport: { width: 1440, height: 900 }, deviceScaleFactor: 1 });++const handle = 'dnsmoke' + Date.now().toString(36);+const reg = await ctx.request.post(`${URL_BASE}/api/auth/register`, {+ data: { email: `${handle}@example.test`, password: 'PassP4ss!2026', display_name: 'Smoke Tester' },+ headers: { 'content-type': 'application/json' },+});+if (reg.status() !== 201 && reg.status() !== 200) {+ console.error('register failed', reg.status(), (await reg.text()).slice(0, 200));+ process.exit(1);+}++let failed = false;+for (const page of PAGES) {+ 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') errs.push('[err] ' + m.text().slice(0, 200)); });+ p.on('requestfailed', r => {+ const url = r.url();+ if (url.includes('posthog') || url.includes('us-assets')) return;+ const ftext = r.failure()?.errorText || '';+ if (ftext === 'net::ERR_ABORTED' && url.includes('hot-update')) return;+ errs.push('REQ FAIL ' + url + ' ' + ftext);+ });++ const url = `${URL_BASE}/dashboard-next${page.slug}`;+ const out = `/tmp/dn-${page.name}.png`;+ try {+ await p.goto(url, { waitUntil: 'load', timeout: 60000 });+ await p.waitForTimeout(5500);+ await p.screenshot({ path: out, fullPage: false });+ console.log(`[ok ] ${page.name.padEnd(10)} → ${out}${errs.length ? ' ('+errs.length+' errors)' : ''}`);+ } catch (e) {+ console.log(`[FAIL] ${page.name}: ${e.message.slice(0, 200)}`);+ failed = true;+ }+ if (errs.length) {+ failed = true;+ console.log(' errors:');+ for (const e of errs) console.log(' ' + e);+ }+ await p.close();+}++await b.close();+process.exit(failed ? 1 : 0);diff --git a/scripts/_dn-sweep.mjs b/scripts/_dn-sweep.mjsindex e346a86f7..eff6c0902 100644--- a/scripts/_dn-sweep.mjs+++ b/scripts/_dn-sweep.mjs@@ -1,7 +1,7 @@-// 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.+// Smoke-test every /dashboard-next page. Stubs auth so the shell mounts+// in a headless browser without a real session cookie; downstream /api/*+// calls are allowed to fail naturally — we only care that the page+// renders and the chrome is intact.import { chromium } from 'playwright';const BASE = process.argv[2] || 'http://127.0.0.1:3010';@@ -15,58 +15,98 @@ const PAGES = [{ slug: '/account', name: 'account' },];+const FAKE_USER = {+ id: 'usr_smoke_test',+ display_name: 'Smoke Test',+ handle: 'smoke',+ email: '[email protected]',+ email_verified: true,+ created_at: new Date(Date.now() - 1000 * 60 * 60 * 24 * 90).toISOString(),+ plan: 'free',+};+const browser = await chromium.launch({args: ['--use-gl=swiftshader', '--no-sandbox', '--disable-gpu'],});const ctx = await browser.newContext({ viewport: { width: 1440, height: 900 } });+// Stub the calls that gate the shell. Everything else falls through to the+// dev-server proxy and is allowed to 401/404 — we report those but don't+// fail the smoke test on them.+await ctx.route('**/api/auth/me', (route) => {+ route.fulfill({+ status: 200,+ contentType: 'application/json',+ body: JSON.stringify({ user: FAKE_USER }),+ });+});+await ctx.route('**/api/csrf-token', (route) => {+ route.fulfill({+ status: 200,+ contentType: 'application/json',+ body: JSON.stringify({ token: 'csrf_smoke_test', expiresIn: 3600 }),+ });+});+const results = [];for (const { slug, name } of PAGES) {const page = await ctx.newPage();const errs = [];+ const apiFails = [];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);+ if (u.includes('/api/')) apiFails.push(u.replace(BASE, ''));+ else errs.push('REQ FAIL ' + u + ' ' + r.failure()?.errorText);+ });+ page.on('response', (resp) => {+ const u = resp.url();+ if (!u.includes('/api/')) return;+ if (resp.status() >= 400 && !apiFails.includes(u.replace(BASE, ''))) {+ apiFails.push(`${resp.status()} ${u.replace(BASE, '')}`);+ }});+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.goto(url, { waitUntil: 'domcontentloaded', 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.waitForTimeout(1500);await page.screenshot({ path: out, fullPage: false });} catch (err) {status = 'fail: ' + (err?.message || err).slice(0, 200);}- results.push({ name, url, out, status, errs });+ results.push({ name, url, out, status, errs, apiFails });await page.close();}-// Bonus: open the palette and screenshot it+// 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.goto(`${BASE}/dashboard-next`, { waitUntil: 'domcontentloaded' });await page.waitForSelector('.dn-shell .dn-rail-item', { timeout: 20000 });+ await page.waitForTimeout(500);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);+ const input = await page.$('#dn-palette input, [data-role="palette-input"]');+ if (input) {+ await input.fill('account');+ 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 });+ results.push({ name: 'palette', url: '⌘K', out: '/tmp/dn-palette.png', status: 'ok', errs, apiFails: [] });} catch (err) {- results.push({ name: 'palette', url: 'cmd-k', out: '/tmp/dn-palette.png', status: 'fail: ' + (err?.message || err).slice(0, 200), errs });+ results.push({ name: 'palette', url: '⌘K', out: '/tmp/dn-palette.png', status: 'fail: ' + (err?.message || err).slice(0, 200), errs, apiFails: [] });}await page.close();}@@ -80,34 +120,65 @@ for (const { slug, name } of PAGES) {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.goto(`${BASE}/dashboard-next`, { waitUntil: 'domcontentloaded' });await page.waitForSelector('.dn-shell', { timeout: 20000 });- await page.waitForTimeout(1500);+ await page.waitForTimeout(1800);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 });+ results.push({ name: 'drawer', url: 'drawer-open', out: '/tmp/dn-drawer.png', status: 'ok', errs, apiFails: [] });+ } catch (err) {+ results.push({ name: 'drawer', url: 'drawer-open', out: '/tmp/dn-drawer.png', status: 'fail: ' + (err?.message || err).slice(0, 200), errs, apiFails: [] });+ }+ await page.close();+}++// Mobile breakpoint test+{+ const mobileCtx = await browser.newContext({ viewport: { width: 375, height: 800 } });+ await mobileCtx.route('**/api/auth/me', (r) => r.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ user: FAKE_USER }) }));+ await mobileCtx.route('**/api/csrf-token', (r) => r.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify({ token: 'csrf', expiresIn: 3600 }) }));+ const page = await mobileCtx.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.waitForSelector('.dn-shell', { timeout: 20000 });+ await page.waitForTimeout(1500);+ await page.screenshot({ path: '/tmp/dn-mobile.png', fullPage: true });+ results.push({ name: 'mobile-375', url: 'mobile', out: '/tmp/dn-mobile.png', status: 'ok', errs, apiFails: [] });} catch (err) {- results.push({ name: 'drawer-open', url: 'drawer', out: '/tmp/dn-drawer.png', status: 'fail: ' + (err?.message || err).slice(0, 200), errs });+ results.push({ name: 'mobile-375', url: 'mobile', out: '/tmp/dn-mobile.png', status: 'fail: ' + (err?.message || err).slice(0, 200), errs, apiFails: [] });}await page.close();+ await mobileCtx.close();}await browser.close();-console.log('\n=== SWEEP RESULTS ===');-let bad = 0;+console.log('\n=== SWEEP RESULTS ===\n');+let pageErrCount = 0;+let failCount = 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}`);+ const headline =+ r.status !== 'ok' ? '✗' :+ r.errs.some((e) => e.startsWith('PAGEERROR')) ? '✗' :+ r.errs.length ? '⚠' : '✓';+ console.log(`${headline} ${r.name.padEnd(14)} ${r.out}`);if (r.status !== 'ok') {console.log(` ${r.status}`);- bad++;+ failCount++;}- for (const e of r.errs.slice(0, 6)) {+ const trueErrs = r.errs.filter((e) => e.startsWith('PAGEERROR') || e.startsWith('[err]'));+ for (const e of trueErrs.slice(0, 4)) {console.log(` ${e}`);- if (e.startsWith('PAGEERROR') || e.startsWith('[err]')) bad++;+ pageErrCount++;+ }+ if (trueErrs.length > 4) console.log(` ... +${trueErrs.length - 4} more page errors`);+ if (r.apiFails && r.apiFails.length) {+ const uniqFails = [...new Set(r.apiFails)].slice(0, 4);+ for (const f of uniqFails) console.log(` api: ${f}`);+ if (r.apiFails.length > 4) console.log(` ... +${r.apiFails.length - 4} more api 4xx`);}- if (r.errs.length > 6) console.log(` ... +${r.errs.length - 6} more`);}-process.exit(bad > 0 ? 1 : 0);+console.log(`\nfails: ${failCount}, page-errors: ${pageErrCount}`);+process.exit(failCount > 0 || pageErrCount > 0 ? 1 : 0);diff --git a/src/account.js b/src/account.jsindex 0f8d7b2a4..28be4ac9b 100644--- a/src/account.js+++ b/src/account.js@@ -1,6 +1,8 @@// Lightweight client helpers for talking to the three.ws backend from the viewer.// Keeps the UI code in app.js/avatar-creator.js clean.+import { identifyUser, resetIdentity } from './analytics.js';+const API = ''; // same origin// Single-use CSRF token: fetched lazily, burned by the server on consumption.@@ -133,11 +135,13 @@ export async function getMe() {const res = await apiFetch(`${API}/api/auth/me`, { allowAnonymous: true });if (res.status === 401) {writeAuthHint(false);+ resetIdentity();return null;}if (!res.ok) throw new Error(`auth/me failed: ${res.status}`);const user = (await res.json()).user;writeAuthHint(!!user);+ if (user) identifyUser(user);return user;}diff --git a/src/analytics.js b/src/analytics.jsnew file mode 100644index 000000000..25a3d6e2c--- /dev/null+++ b/src/analytics.js@@ -0,0 +1,70 @@+// Tiny PostHog identity helper.+//+// The snippet injected by vite.config.js auto-captures pageviews, clicks and+// session replays anonymously. Without `posthog.identify()`, every visit is a+// fresh "person" keyed by session ID — funnels, cohorts and retention all+// break. Call identifyUser() once after auth resolves, resetIdentity() on+// sign-out.+//+// All calls are no-ops when window.posthog isn't loaded (embed pages,+// blocked by adblock, ad-blocker test) so callers can fire-and-forget.++function ph() {+ if (typeof window === 'undefined') return null;+ const p = window.posthog;+ if (!p || typeof p.identify !== 'function') return null;+ return p;+}++let _lastDistinctId = null;++/**+ * Tie subsequent events to a stable user.+ * @param {{ id: string, username?: string, email?: string, display_name?: string, created_at?: string }} user+ */+export function identifyUser(user) {+ if (!user?.id) return;+ const p = ph();+ if (!p) return;+ // Avoid re-identifying on every getMe() call (most pages call it on load).+ if (_lastDistinctId === user.id) return;+ _lastDistinctId = user.id;+ try {+ p.identify(String(user.id), {+ username: user.username || undefined,+ email: user.email || undefined,+ name: user.display_name || user.username || undefined,+ created_at: user.created_at || undefined,+ });+ } catch {+ /* swallow — analytics must never break the app */+ }+}++/** Wipe the cookie-stored distinct_id so the next visit isn't tied to the user. */+export function resetIdentity() {+ _lastDistinctId = null;+ const p = ph();+ if (!p) return;+ try {+ p.reset();+ } catch {+ /* swallow */+ }+}++/**+ * Capture a custom event. Use sparingly — most behavior is already auto-captured.+ * Reserve for product-meaningful actions (e.g. "widget_published", "knowledge_uploaded").+ * @param {string} event+ * @param {Record<string, any>} [props]+ */+export function track(event, props = {}) {+ const p = ph();+ if (!p) return;+ try {+ p.capture(event, props);+ } catch {+ /* swallow */+ }+}diff --git a/src/dashboard-next/pages/api.js b/src/dashboard-next/pages/api.jsindex a7c52f9da..da2fd64a2 100644--- a/src/dashboard-next/pages/api.js+++ b/src/dashboard-next/pages/api.js@@ -35,7 +35,7 @@ const EXPIRY_OPTIONS = [{ label: '1 year', days: 365 },];-const KEY_PLACEHOLDER = 'sk_live_yourkeyhere';+const KEY_PLACEHOLDER = 'YOUR_API_KEY';(async function boot() {const main = await mountShell();diff --git a/src/dashboard-next/shell.js b/src/dashboard-next/shell.jsindex c11d6a983..309d9f1a4 100644--- a/src/dashboard-next/shell.js+++ b/src/dashboard-next/shell.js@@ -76,9 +76,9 @@ export async function mountShell() {return shell.querySelector('[data-slot="page"]');}-// Listen for new-event signals (dispatched by the drawer/activity feed-// once prompt #9 wires it up) and briefly pulse the drawer toggle so-// the user knows there's something fresh to look at.+// Listen for new-event signals dispatched by the drawer's live feed and+// briefly pulse the drawer toggle so the user knows there's something+// fresh to look at without having to open the drawer first.function mountDrawerPulse(shellEl) {window.addEventListener('dn:drawer:new-event', () => {const btn = shellEl.querySelector('[data-action="toggle-drawer"]');diff --git a/src/header-user.js b/src/header-user.jsindex b4fc7ab51..3340876d0 100644--- a/src/header-user.js+++ b/src/header-user.js@@ -14,6 +14,8 @@// If a `user` object is already available, pass it in to skip the fetch:// mountHeaderUser({ slot: '#header-user-slot', user });+import { resetIdentity } from './analytics.js';+let stylesInjected = false;function injectStyles() {@@ -147,6 +149,7 @@ async function performSignOut() {await fetch('/api/auth/logout', { method: 'POST', credentials: 'include' });} finally {try { localStorage.removeItem('3dagent:auth-hint'); } catch {}+ resetIdentity();location.href = '/';}}diff --git a/src/wallet-auth.js b/src/wallet-auth.jsindex b4a3765c9..2dbb233f9 100644--- a/src/wallet-auth.js+++ b/src/wallet-auth.js@@ -1,4 +1,5 @@import { ensureWallet } from './erc8004/agent-registry.js';+import { identifyUser, resetIdentity } from './analytics.js';// ─── Public API ─────────────────────────────────────────────────────────────@@ -65,6 +66,7 @@ export async function signOut() {method: 'POST',credentials: 'include',}).catch(() => {});+ resetIdentity();}/** @returns {Promise<object|null>} */@@ -73,6 +75,7 @@ export async function getCurrentUser() {const res = await fetch('/api/auth/me', { credentials: 'include' });if (!res.ok) return null;const { user } = await res.json();+ if (user) identifyUser(user);return user ?? null;} catch {return null;