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
test(play): add journey and performance audit harnesses for the world
nirholas27bf3122ddf2
diff --git a/scripts/play-journey-audit.mjs b/scripts/play-journey-audit.mjsnew file mode 100644index 000000000..f069e9f6b--- /dev/null+++ b/scripts/play-journey-audit.mjs@@ -0,0 +1,374 @@+// Full-journey audit for /play. Walks the player path a first-time visitor+// walks (cold load, lobby, search, avatar bar, world entry, HUD panels) in a+// real browser and reports only measured facts: console output, failed+// requests, cumulative layout shift, elements that overflow the viewport,+// touch targets under the 40px bar, and every tab stop with its focus ring.+//+// node scripts/play-journey-audit.mjs # desktop, local+// VIEWPORT=375 node scripts/play-journey-audit.mjs+// VIEWPORT=320 node scripts/play-journey-audit.mjs https://three.ws/play+//+// Nothing here is inferred from source. Every finding is a resolved computed+// style or a measured box, so a clean run is real evidence the journey is clean.+import { chromium, devices } from 'playwright';++const BASE = process.argv[2] || 'http://localhost:3000/play';+const VIEWPORT = String(process.env.VIEWPORT || 'desktop');+const HOME_COIN = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';+const TOUCH_MIN = 40;++const MOBILE = VIEWPORT !== 'desktop';+const width = MOBILE ? Number(VIEWPORT) : 1440;+const height = MOBILE ? 812 : 900;++const browser = await chromium.launch({ args: ['--use-gl=swiftshader', '--enable-unsafe-swiftshader'] });+const ctx = await browser.newContext(+ MOBILE+ ? { ...devices['iPhone 14'], viewport: { width, height }, screen: { width, height } }+ : { viewport: { width, height } },+);++// CLS has to be observed from the first frame, so the observer is installed+// before any page script runs.+await ctx.addInitScript(() => {+ window.__cls = 0;+ window.__shifts = [];+ try {+ new PerformanceObserver((list) => {+ for (const e of list.getEntries()) {+ if (e.hadRecentInput) continue;+ window.__cls += e.value;+ if (e.value > 0.01) {+ window.__shifts.push({+ value: Number(e.value.toFixed(4)),+ sources: (e.sources || []).map((s) => s.node?.className || s.node?.id || s.node?.tagName || '?').slice(0, 3),+ });+ }+ }+ }).observe({ type: 'layout-shift', buffered: true });+ } catch { /* layout-shift unsupported */ }+});++const page = await ctx.newPage();+const t0 = Date.now();+const at = () => `+${((Date.now() - t0) / 1000).toFixed(1)}s`;+const findings = { console: [], network: [], overflow: [], touch: [], focus: [], states: [], cls: null };++// Noise that is not our code: the swiftshader driver's own performance chatter,+// and Vite's dev-only HMR client, whose websocket cannot reach a forwarded+// Codespaces port. Everything else counts as a defect.+const NOISE = /GL Driver Message|GPU stall|\[vite\]|@vite\/client|WebSocket closed without opened|Third-party cookie|preloaded using link preload/i;+const OURS = (text) => !NOISE.test(text);++page.on('console', (m) => {+ const type = m.type();+ if (type !== 'error' && type !== 'warning') return;+ const text = m.text().slice(0, 300);+ if (!OURS(text)) return;+ findings.console.push(`[${type}] ${text}`);+ console.log(at(), `[console.${type}]`, text);+});+page.on('pageerror', (e) => {+ const line = String(e?.stack || e).slice(0, 400);+ if (!OURS(line)) return;+ findings.console.push(`[pageerror] ${line}`);+ console.log(at(), '[pageerror]', line);+});+page.on('requestfailed', (r) => {+ const err = r.failure()?.errorText || '';+ if (/ERR_ABORTED/.test(err)) return;+ findings.network.push(`${err} ${r.url().slice(0, 120)}`);+ console.log(at(), '[reqfail]', err, r.url().slice(0, 120));+});+page.on('response', (r) => {+ if (r.status() < 400) return;+ findings.network.push(`HTTP ${r.status()} ${r.url().slice(0, 120)}`);+ console.log(at(), `[http ${r.status()}]`, r.url().slice(0, 120));+});++/** Every element whose border box crosses the right edge of the viewport. */+async function overflowScan(label) {+ const hits = await page.evaluate((vw) => {+ const out = [];+ const doc = document.scrollingElement;+ if (doc.scrollWidth > doc.clientWidth + 1) out.push({ sel: 'document', right: doc.scrollWidth, w: doc.clientWidth });+ for (const n of document.querySelectorAll('body *')) {+ if (!n.offsetParent && getComputedStyle(n).position !== 'fixed') continue;+ const r = n.getBoundingClientRect();+ if (r.width === 0 || r.height === 0) continue;+ if (r.right > vw + 1 || r.left < -1) {+ const sel = n.id ? `#${n.id}` : `${n.tagName.toLowerCase()}.${String(n.className).split(' ').slice(0, 2).join('.')}`;+ out.push({ sel, left: Math.round(r.left), right: Math.round(r.right) });+ }+ }+ // Collapse to unique selectors: a repeated grid cell is one defect, not thirty.+ const seen = new Map();+ for (const o of out) if (!seen.has(o.sel)) seen.set(o.sel, o);+ return [...seen.values()].slice(0, 25);+ }, width);+ if (hits.length) {+ findings.overflow.push({ label, hits });+ console.log(at(), `[overflow:${label}]`, JSON.stringify(hits));+ }+ return hits;+}++/** Visible interactive elements whose hit box is under the touch bar. */+async function touchScan(label) {+ const hits = await page.evaluate((min) => {+ const out = [];+ const sel = 'button, a[href], input, select, textarea, [role="button"], [tabindex]:not([tabindex="-1"])';+ for (const n of document.querySelectorAll(sel)) {+ const r = n.getBoundingClientRect();+ if (r.width === 0 || r.height === 0) continue;+ const cs = getComputedStyle(n);+ if (cs.visibility === 'hidden' || cs.display === 'none' || Number(cs.opacity) === 0) continue;+ // Inline links inside a paragraph are exempt (WCAG 2.5.8).+ const inlineLink = n.tagName === 'A' && cs.display.startsWith('inline') && n.closest('p, li, small');+ if (inlineLink) continue;+ if (r.width < min || r.height < min) {+ out.push({+ sel: n.id ? `#${n.id}` : `${n.tagName.toLowerCase()}.${String(n.className).split(' ').slice(0, 2).join('.')}`,+ label: (n.getAttribute('aria-label') || n.textContent || '').trim().slice(0, 24),+ w: Math.round(r.width), h: Math.round(r.height),+ });+ }+ }+ const seen = new Map();+ for (const o of out) if (!seen.has(o.sel)) seen.set(o.sel, o);+ return [...seen.values()].slice(0, 30);+ }, TOUCH_MIN);+ if (hits.length) {+ findings.touch.push({ label, hits });+ console.log(at(), `[touch<${TOUCH_MIN}:${label}]`, JSON.stringify(hits));+ }+ return hits;+}++/**+ * Tab through the surface and record whether each stop paints a focus ring.+ * A stop with no outline and no box-shadow change is invisible to a keyboard+ * user, which is the defect this catches.+ */+async function focusSweep(label, steps = 60) {+ const stops = [];+ await page.evaluate(() => document.body.focus());+ for (let i = 0; i < steps; i++) {+ await page.keyboard.press('Tab');+ const stop = await page.evaluate(() => {+ const n = document.activeElement;+ if (!n || n === document.body) return null;+ const cs = getComputedStyle(n);+ const r = n.getBoundingClientRect();+ const ring = (cs.outlineStyle !== 'none' && parseFloat(cs.outlineWidth) > 0) || /rgb|inset/.test(cs.boxShadow || '');+ return {+ sel: n.id ? `#${n.id}` : `${n.tagName.toLowerCase()}.${String(n.className).split(' ').slice(0, 2).join('.')}`,+ label: (n.getAttribute('aria-label') || n.textContent || '').trim().slice(0, 30),+ ring,+ offscreen: r.width === 0 || r.height === 0 || r.bottom < 0 || r.top > innerHeight,+ };+ });+ if (!stop) break;+ if (stops.some((s) => s.sel === stop.sel && s.label === stop.label)) continue;+ stops.push(stop);+ }+ const bad = stops.filter((s) => !s.ring && !s.offscreen);+ console.log(at(), `[focus:${label}] ${stops.length} stops, ${bad.length} without a visible ring`);+ if (bad.length) {+ findings.focus.push({ label, bad });+ for (const b of bad) console.log(' no ring:', b.sel, '|', b.label);+ }+ return stops;+}++async function noteState(label, fn) {+ const v = await page.evaluate(fn).catch((e) => ({ error: String(e) }));+ findings.states.push({ label, v });+ console.log(at(), `[state:${label}]`, JSON.stringify(v));+ return v;+}++// ── 1. cold load into the lobby ────────────────────────────────────────────+console.log(at(), `journey start ${BASE} @ ${width}x${height}${MOBILE ? ' (touch)' : ''}`);+await page.goto(BASE, { waitUntil: 'domcontentloaded', timeout: 60000 });+await page.waitForSelector('#cc-lobby', { timeout: 30000 }).catch(() => console.log(at(), 'LOBBY NEVER RENDERED'));++// The skeleton has to exist before data lands, otherwise the grid pops in.+await noteState('lobby-first-paint', () => ({+ skeletons: document.querySelectorAll('.cc-skeleton').length,+ cards: document.querySelectorAll('.cc-card:not(.cc-skeleton)').length,+ empty: !!document.querySelector('.cc-empty'),+}));++await page.waitForFunction(() => document.querySelectorAll('.cc-card:not(.cc-skeleton)').length > 0+ || document.querySelector('.cc-empty') || document.querySelector('.cc-grid-error'), { timeout: 30000 })+ .catch(() => console.log(at(), 'GRID NEVER RESOLVED (no cards, no empty state, no error state)'));++await noteState('lobby-loaded', () => ({+ cards: document.querySelectorAll('.cc-card:not(.cc-skeleton)').length,+ skeletons: document.querySelectorAll('.cc-skeleton').length,+ empty: !!document.querySelector('.cc-empty'),+ error: !!document.querySelector('.cc-grid-error'),+ presets: document.querySelectorAll('.cc-avatar-chip').length,+}));++await overflowScan('lobby');+if (MOBILE) await touchScan('lobby');+await focusSweep('lobby', MOBILE ? 40 : 70);++// ── 2. search: a query with hits, then one with none ───────────────────────+const search = await page.$('.cc-search input');+if (search) {+ await search.click();+ await search.type('dog', { delay: 30 });+ await page.waitForTimeout(3500);+ await noteState('search-hits', () => ({+ cards: document.querySelectorAll('.cc-card:not(.cc-skeleton)').length,+ more: !!document.querySelector('.cc-search-more'),+ empty: !!document.querySelector('.cc-empty'),+ }));+ await search.fill('zzzqqqxnotacoin9999');+ await page.waitForTimeout(4000);+ await noteState('search-no-hits', () => ({+ cards: document.querySelectorAll('.cc-card:not(.cc-skeleton)').length,+ empty: !!document.querySelector('.cc-empty'),+ emptyText: document.querySelector('.cc-empty')?.textContent?.trim().slice(0, 120) || null,+ }));+ await search.fill('');+ await page.waitForTimeout(1500);+}++// ── 3. avatar bar: gallery + create modal open/close ───────────────────────+for (const [name, sel] of [['create', '.cc-create-btn'], ['gallery', '.cc-gallery-btn']]) {+ const btn = await page.$(sel);+ if (!btn) { console.log(at(), `[missing] ${name} button`); continue; }+ await btn.click().catch(() => {});+ await page.waitForTimeout(2500);+ await noteState(`${name}-open`, () => ({+ overlays: [...document.querySelectorAll('[class*="overlay"], [class*="modal"], dialog')]+ .filter((n) => n.offsetParent).map((n) => String(n.className).slice(0, 40)),+ }));+ await overflowScan(`${name}-modal`);+ await page.keyboard.press('Escape');+ await page.waitForTimeout(800);+ await noteState(`${name}-closed-by-escape`, () => ({+ stillOpen: [...document.querySelectorAll('[class*="overlay"], [class*="modal"], dialog')].filter((n) => n.offsetParent).length,+ }));+ // Belt and braces: click any close control still on screen.+ await page.evaluate(() => {+ const x = [...document.querySelectorAll('button')].find((b) => b.offsetParent && /close|✕|×/i.test(b.getAttribute('aria-label') || b.textContent || ''));+ x?.click();+ });+ await page.waitForTimeout(500);+}++// ── 4. into the $THREE world ───────────────────────────────────────────────+const worldUrl = `${BASE}${BASE.includes('?') ? '&' : '?'}coin=${HOME_COIN}`;+console.log(at(), 'entering world', worldUrl);+await page.goto(worldUrl, { waitUntil: 'domcontentloaded', timeout: 60000 });+await page.waitForFunction(() => {+ const l = document.getElementById('kx-loading');+ return !l || l.classList.contains('kx-hidden') || l.hidden || getComputedStyle(l).display === 'none';+}, { timeout: 60000 }).catch(() => console.log(at(), 'LOADER NEVER CLEARED'));+console.log(at(), 'world interactive');++// Dismiss whatever onboarding is showing so the HUD is reachable.+for (let i = 0; i < 4; i++) {+ await page.waitForTimeout(1500);+ const hit = await page.evaluate(() => {+ const b = [...document.querySelectorAll('button')]+ .find((x) => x.offsetParent && /^(continue|enter the world|got it|start|skip|drop in|let's go)$/i.test((x.textContent || '').trim()));+ if (b) { b.click(); return b.textContent.trim(); }+ return null;+ });+ if (hit) console.log(at(), '[dismissed]', hit);+}++await noteState('world-hud', () => ({+ hud: !!document.querySelector('#cc-hud:not([hidden])'),+ canvas: !!document.querySelector('canvas'),+ status: document.getElementById('cc-status')?.getAttribute('data-state') || null,+ statusText: document.getElementById('cc-status')?.textContent?.trim().slice(0, 60) || null,+ joystick: !!document.getElementById('cc-joystick'),+ chatCollapsed: document.getElementById('cc-chat')?.classList.contains('cc-chat-min') ?? null,+}));++await overflowScan('world');+if (MOBILE) await touchScan('world');++// ── 5. every HUD panel: open, measure, close ───────────────────────────────+const PANELS = [+ ['store', /store|shop|boutique/i],+ ['bank', /bank|wallet|balance/i],+ ['wheel', /wheel|spin/i],+ ['quests', /quest|job|board/i],+ ['friends', /friend|crew/i],+ ['emotes', /emote/i],+];+for (const [name, re] of PANELS) {+ const opened = await page.evaluate((src) => {+ const rx = new RegExp(src.slice(1, src.lastIndexOf('/')), 'i');+ const b = [...document.querySelectorAll('button, [role="button"]')]+ .filter((x) => x.offsetParent)+ .find((x) => rx.test((x.getAttribute('aria-label') || x.title || x.textContent || '')));+ if (!b) return null;+ b.click();+ return (b.getAttribute('aria-label') || b.textContent || '').trim().slice(0, 30);+ }, String(re));+ if (!opened) { console.log(at(), `[panel:${name}] no trigger visible`); continue; }+ await page.waitForTimeout(2200);+ const shape = await page.evaluate(() => {+ const panels = [...document.querySelectorAll('[class*="panel"], [class*="modal"], [class*="overlay"], dialog')]+ .filter((n) => n.offsetParent)+ .map((n) => {+ const r = n.getBoundingClientRect();+ return {+ cls: String(n.className).slice(0, 40),+ box: [Math.round(r.left), Math.round(r.top), Math.round(r.width), Math.round(r.height)],+ overflows: r.right > innerWidth + 1 || r.bottom > innerHeight + 1,+ text: (n.textContent || '').replace(/\s+/g, ' ').trim().slice(0, 100),+ };+ });+ return panels.slice(0, 4);+ });+ findings.states.push({ label: `panel:${name}`, v: { opened, shape } });+ console.log(at(), `[panel:${name}] via "${opened}"`, JSON.stringify(shape));+ if (MOBILE) await touchScan(`panel:${name}`);+ await overflowScan(`panel:${name}`);+ await page.keyboard.press('Escape');+ await page.waitForTimeout(700);+}++// ── 6. leave back to the lobby ─────────────────────────────────────────────+const left = await page.evaluate(() => {+ const b = document.querySelector('.cc-leave');+ if (!b) return false;+ b.click();+ return true;+});+await page.waitForTimeout(2500);+await noteState('after-leave', () => ({ leaveButton: left, lobbyVisible: !!document.querySelector('#cc-lobby:not([hidden])') }))+ .catch(() => {});++findings.cls = await page.evaluate(() => ({ cls: Number((window.__cls || 0).toFixed(4)), shifts: (window.__shifts || []).slice(0, 8) }));+console.log(at(), '[cls]', JSON.stringify(findings.cls));++await page.screenshot({ path: process.env.SHOT || `/tmp/play-journey-${VIEWPORT}.png` }).catch(() => {});++console.log('\n=== summary @' + VIEWPORT + ' ===');+const counts = new Map();+for (const c of findings.console) {+ const k = c.replace(/\d+/g, 'N').slice(0, 160);+ counts.set(k, (counts.get(k) || 0) + 1);+}+console.log('console issues:', findings.console.length);+for (const [k, n] of [...counts].sort((a, b) => b[1] - a[1])) console.log(' ', String(n).padStart(3), 'x', k);+console.log('network issues:', findings.network.length);+for (const n of [...new Set(findings.network)].slice(0, 15)) console.log(' ', n);+console.log('overflow scans with hits:', findings.overflow.length);+console.log('touch-target scans with hits:', findings.touch.length);+console.log('focus stops without a ring:', findings.focus.reduce((a, f) => a + f.bad.length, 0));+console.log('CLS:', findings.cls?.cls);++await browser.close();+process.exit(findings.console.length || findings.network.length ? 1 : 0);diff --git a/scripts/play-perf-audit.mjs b/scripts/play-perf-audit.mjsnew file mode 100644index 000000000..d11596801--- /dev/null+++ b/scripts/play-perf-audit.mjs@@ -0,0 +1,258 @@+// Performance audit for /play: transfer weight to interactive, frame-time+// distribution while walking the busiest area, renderer draw-call/geometry+// budget, and heap growth over a long idle sit.+//+// node scripts/play-perf-audit.mjs "<url>" [walkSeconds] [idleSeconds]+// IDLE=300 node scripts/play-perf-audit.mjs "$PLAY_URL"+//+// Chromium only (heap counters + WebGL under swiftshader). Everything it prints+// is a number you can diff across a change: totals are keyed so two runs line up+// line for line.+import { chromium } from 'playwright';++const TARGET = process.argv[2] || 'https://three.ws/play';+const WALK_MS = Number(process.argv[3] || 30) * 1000;+const IDLE_MS = Number(process.argv[4] || process.env.IDLE || 300) * 1000;+const LABEL = process.env.LABEL || 'run';++const browser = await chromium.launch({+ args: ['--use-gl=swiftshader', '--enable-unsafe-swiftshader', '--js-flags=--expose-gc'],+});+const ctx = await browser.newContext({ viewport: { width: 1440, height: 900 } });++// Frame instrumentation has to be installed before any page script runs, so the+// very first rendered frame is measured too.+await ctx.addInitScript(() => {+ window.__frames = [];+ window.__marks = {};+ let last = 0;+ const tick = (t) => {+ if (last) window.__frames.push(t - last);+ last = t;+ requestAnimationFrame(tick);+ };+ requestAnimationFrame(tick);+ window.__glbLoads = [];+ const note = (url) => window.__glbLoads.push(String(url).replace(/^https?:\/\/[^/]+/, ''));+ const origOpen = XMLHttpRequest.prototype.open;+ XMLHttpRequest.prototype.open = function (method, url, ...rest) {+ if (/\.(glb|gltf|hdr|ktx2)(\?|$)/i.test(String(url))) note(url);+ return origOpen.call(this, method, url, ...rest);+ };+ const origFetch = window.fetch;+ window.fetch = function (input, init) {+ const url = typeof input === 'string' ? input : input?.url || '';+ if (/\.(glb|gltf|hdr|ktx2)(\?|$)/i.test(url) || /\/animations\/(clips|manifest)/.test(url)) note(url);+ return origFetch.call(this, input, init);+ };+});++const page = await ctx.newPage();+const t0 = Date.now();+const at = () => `+${((Date.now() - t0) / 1000).toFixed(1)}s`;+const errors = [];+page.on('pageerror', (e) => errors.push(String(e).slice(0, 200)));+page.on('console', (m) => { if (m.type() === 'error') errors.push(m.text().slice(0, 200)); });++const resourceTotals = () =>+ page.evaluate(() => {+ const rows = performance.getEntriesByType('resource').map((r) => ({+ url: r.name,+ // transferSize is 0 for a memory-cache hit and ~300 for a 304; the+ // decoded body is what the CPU actually paid for either way.+ transfer: r.transferSize || 0,+ encoded: r.encodedBodySize || 0,+ type: r.initiatorType,+ }));+ return { rows, nav: performance.getEntriesByType('navigation')[0]?.duration || 0 };+ });++const heapMB = async () => {+ const client = await page.context().newCDPSession(page);+ await client.send('HeapProfiler.collectGarbage');+ const { metrics } = await client.send('Performance.getMetrics');+ await client.detach();+ return Math.round((metrics.find((m) => m.name === 'JSHeapUsedSize')?.value || 0) / 1048576);+};++const rendererStats = () =>+ page.evaluate(() => {+ const g = window.__CC__;+ const r = g?.renderer;+ if (!r) return null;+ let meshes = 0, instanced = 0, geoms = new Set(), mats = new Set();+ g.scene?.traverse?.((o) => {+ if (o.isInstancedMesh) instanced++;+ else if (o.isMesh) meshes++;+ if (o.geometry) geoms.add(o.geometry.uuid);+ if (o.material) (Array.isArray(o.material) ? o.material : [o.material]).forEach((m) => mats.add(m.uuid));+ });+ return {+ calls: r.info.render.calls,+ triangles: r.info.render.triangles,+ programs: r.info.programs?.length || 0,+ geometriesResident: r.info.memory.geometries,+ texturesResident: r.info.memory.textures,+ meshes, instanced,+ uniqueGeometries: geoms.size,+ uniqueMaterials: mats.size,+ pixelRatio: r.getPixelRatio(),+ };+ });++const frameStats = async (reset = false) => {+ const f = await page.evaluate((r) => {+ const arr = window.__frames.slice();+ if (r) window.__frames.length = 0;+ return arr;+ }, reset);+ if (!f.length) return null;+ const s = f.slice().sort((a, b) => a - b);+ const pct = (p) => s[Math.min(s.length - 1, Math.floor((p / 100) * s.length))];+ return {+ frames: f.length,+ mean: +(f.reduce((a, b) => a + b, 0) / f.length).toFixed(2),+ p50: +pct(50).toFixed(2),+ p95: +pct(95).toFixed(2),+ p99: +pct(99).toFixed(2),+ worst: +s[s.length - 1].toFixed(2),+ over33ms: f.filter((x) => x > 33).length,+ fps: +(1000 / (f.reduce((a, b) => a + b, 0) / f.length)).toFixed(1),+ };+};++console.log(at(), 'goto', TARGET.slice(0, 120));+await page.goto(TARGET, { waitUntil: 'domcontentloaded', timeout: 60000 });++try {+ await page.waitForSelector('.pi-btn-primary', { timeout: 25000 });+ await page.click('.pi-btn-primary');+ console.log(at(), 'clicked drop-in');+} catch { console.log(at(), 'no intro CTA (deep link drops straight in)'); }++// "Interactive" = the world phase is live and the renderer is drawing. The+// third argument is where waitForFunction takes its options; passing them as+// the second silently falls back to the 30 s default and reports a healthy+// world as a failure.+try {+ await page.waitForFunction(+ () => {+ const l = document.getElementById('kx-loading');+ return (!l || l.classList.contains('kx-hidden')) && window.__CC__?.phase === 'world';+ },+ null,+ { timeout: 120000 },+ );+} catch { console.log(at(), 'WORLD NEVER BECAME INTERACTIVE, phase =', await page.evaluate(() => window.__CC__?.phase)); }+const interactiveAt = (Date.now() - t0) / 1000;+console.log(at(), 'interactive');++const atInteractive = await resourceTotals();++// Clear onboarding so input reaches the world.+for (let i = 0; i < 5; i++) {+ await page.waitForTimeout(1200);+ await page.evaluate(() => {+ const btn = [...document.querySelectorAll('button')].find(+ (b) => /^(continue|enter the world|got it|start|close|skip|next)$/i.test(b.textContent.trim()) && b.offsetParent,+ );+ if (btn) btn.click();+ });+}++await page.mouse.click(720, 500);+await page.waitForTimeout(2000);+await frameStats(true);++console.log(at(), `walking ${WALK_MS / 1000}s`);+const walkEnd = Date.now() + WALK_MS;+const keys = ['KeyW', 'KeyA', 'KeyW', 'KeyD', 'KeyS', 'KeyD', 'KeyW', 'KeyA'];+let ki = 0;+while (Date.now() < walkEnd) {+ const k = keys[ki++ % keys.length];+ await page.keyboard.down(k);+ await page.waitForTimeout(1500);+ await page.keyboard.up(k);+ await page.mouse.move(400 + ((ki * 137) % 640), 450);+}+const walk = await frameStats(true);+const render = await rendererStats();++const heapAfterWalk = await heapMB();+console.log(at(), `idling ${IDLE_MS / 1000}s for heap growth`);+const heapSamples = [];+const idleEnd = Date.now() + IDLE_MS;+while (Date.now() < idleEnd) {+ await page.waitForTimeout(Math.min(30000, Math.max(1000, idleEnd - Date.now())));+ const mb = await heapMB();+ heapSamples.push([+((Date.now() - t0) / 1000).toFixed(0), mb]);+ console.log(at(), 'heap', mb, 'MB');+}+const idle = await frameStats(true);+const heapEnd = heapSamples.length ? heapSamples[heapSamples.length - 1][1] : heapAfterWalk;++const final = await resourceTotals();+const glb = await page.evaluate(() => window.__glbLoads || []);+const dupes = new Map();+for (const u of glb) dupes.set(u, (dupes.get(u) || 0) + 1);++const sum = (rows, key) => rows.reduce((a, r) => a + (r[key] || 0), 0);+const mb = (n) => (n / 1048576).toFixed(2);++console.log(`\n================ PERF REPORT (${LABEL}) ================`);+console.log('url ', TARGET.slice(0, 100));+console.log('time to interactive ', interactiveAt.toFixed(1), 's');+console.log('transfer @interactive ', mb(sum(atInteractive.rows, 'transfer')), 'MB over', atInteractive.rows.length, 'requests');+console.log('decoded @interactive ', mb(sum(atInteractive.rows, 'encoded')), 'MB');+console.log('transfer @end ', mb(sum(final.rows, 'transfer')), 'MB over', final.rows.length, 'requests');++const byGroup = new Map();+for (const r of final.rows) {+ const k = r.url.replace(/^https?:\/\/[^/]+/, '').replace(/[?#].*$/, '').replace(/\/[^/]*$/, '/*');+ const cur = byGroup.get(k) || [0, 0];+ byGroup.set(k, [cur[0] + r.transfer, cur[1] + 1]);+}+console.log('\n--- bytes by path group (top 15) ---');+for (const [k, [n, c]] of [...byGroup].sort((a, b) => b[1][0] - a[1][0]).slice(0, 15))+ console.log(' ', mb(n).padStart(8), 'MB', String(c).padStart(4), 'x', k.slice(0, 100));++console.log('\n--- 20 largest single responses ---');+for (const r of final.rows.slice().sort((a, b) => b.transfer - a.transfer).slice(0, 20))+ console.log(' ', mb(r.transfer).padStart(8), 'MB', r.url.replace(/^https?:\/\/[^/]+/, '').slice(0, 110));++const repeats = new Map();+for (const r of final.rows) {+ const k = r.url.replace(/^https?:\/\/[^/]+/, '');+ repeats.set(k, (repeats.get(k) || 0) + 1);+}+console.log('\n--- responses fetched more than once ---');+const rep = [...repeats].filter(([, c]) => c > 1).sort((a, b) => b[1] - a[1]);+if (!rep.length) console.log(' none');+for (const [k, c] of rep.slice(0, 20)) console.log(' ', String(c).padStart(4), 'x', k.slice(0, 120));++console.log('\n--- model/clip loads issued by the page ---');+console.log(' total', glb.length);+for (const [u, c] of [...dupes].filter(([, c]) => c > 1).sort((a, b) => b[1] - a[1]).slice(0, 20))+ console.log(' ', String(c).padStart(4), 'x', u.slice(0, 120));++console.log('\n--- frame time (ms) ---');+console.log(' walking', JSON.stringify(walk));+console.log(' idle ', JSON.stringify(idle));++console.log('\n--- renderer ---');+console.log(' ', JSON.stringify(render));++console.log('\n--- heap ---');+console.log(' after walk', heapAfterWalk, 'MB');+console.log(' after idle', heapEnd, 'MB');+console.log(' growth ', heapEnd - heapAfterWalk, 'MB over', (IDLE_MS / 60000).toFixed(1), 'min');+console.log(' samples ', JSON.stringify(heapSamples));++console.log('\n--- console errors (' + errors.length + ') ---');+for (const e of [...new Set(errors)].slice(0, 12)) console.log(' ', e);++// animations:'disabled' would freeze the world loop mid-measure; a short+// timeout instead, because a busy main thread can stall the capture forever and+// a missing screenshot must never lose the numbers above.+if (process.env.SHOT) await page.screenshot({ path: process.env.SHOT, timeout: 15000 }).catch(() => {});+await browser.close();