#!/usr/bin/env node // Per-design frame budget over the full-app fixture (tool/perf/README.md). // // For every registered AppDesign (read from the build through // `window.__perfDesigns()`, tool/perf/design_probe.dart) it runs the same // scenarios, records Flutter's FrameTiming (tool/perf/frame_log.dart) and // compares each design's medians with Default's. It exits 1 when a design // goes over budget: // - mean build or raster time per frame of a scenario above `--ratio` x // Default + `--slack` ms; // - a request leaving the loopback origin (a font fallback fetch) that the // design makes and Default does not (Default's own are listed as baseline); // - live design switches growing the JS heap by more than `--leak` MB. // // node tool/perf/design_bench.mjs --build build/design-profile --out /tmp/design \ // [--repeat 3] [--only scroll,switch] [--designs default,terminal] [--gpu] // // Build the fixture in profile mode (readable names, real timings): // flutter build web --profile --wasm --no-web-resources-cdn --source-maps \ // --target tool/search_selection_probe_entry.dart --output build/design-profile import { mkdir, writeFile } from 'node:fs/promises'; import { join } from 'node:path'; import { parseArgs } from 'node:util'; import { setTimeout as delay } from 'node:timers/promises'; import { openBrowser } from '../capture/browser.mjs'; import { serveBuild } from '../capture/serve.mjs'; const { values: opts } = parseArgs({ options: { build: { type: 'string' }, out: { type: 'string' }, repeat: { type: 'string', default: '3' }, only: { type: 'string' }, designs: { type: 'string' }, gpu: { type: 'boolean' }, ratio: { type: 'string', default: '1.35' }, slack: { type: 'string', default: '1' }, switches: { type: 'string', default: '10' }, leak: { type: 'string', default: '8' }, }, }); if (!opts.build || !opts.out) throw new Error('usage: --build --out '); // Desktop chat fixture: three chats of 200 messages each, with a CLI-agent // exchange (tool calls, glyph rows), the transcript beside its list. const CHAT = { size: '1280x800', route: '/chat/perf-chat-0', q: { chats: '3', msgs: '200', cli: '1', rich: '1' } }; const SCENARIOS = [ { name: 'scroll', label: 'scroll a 200-message transcript', ...CHAT, act: [{ wheel: [860, 400, -240, 40] }, { wheel: [860, 400, 240, 20] }] }, { name: 'switch', label: 'switch chats', ...CHAT, act: [{ click: [300, 260] }, { click: [300, 335] }, { click: [300, 170] }] }, { name: 'runs', label: 'scroll 400 runs', size: '560x900', route: '/runs', q: { runs: '400' }, act: [{ wheel: [280, 450, 240, 40] }] }, { name: 'graph', label: 'open and pan the run graph', size: '560x900', route: '/runs/7', q: { graph: '1' }, act: [{ click: [512, 152] }, { drag: [280, 500, -200, -150] }] }, { name: 'design', label: 'switch designs live (to and back)', ...CHAT, live: true }, ]; const median = (xs) => { const s = [...xs].sort((a, b) => a - b); return s[Math.floor(s.length / 2)] ?? 0; }; const r1 = (x) => Math.round(x * 100) / 100; const server = await serveBuild(opts.build); const browser = await openBrowser({ gpu: Boolean(opts.gpu) }); const { send, on } = browser; const evaluate = async (expression) => (await send('Runtime.evaluate', { expression, returnByValue: true, awaitPromise: true })).result?.value; let frames = []; let firstFrame = null; let offOrigin = new Set(); const fetchesBy = {}; const errors = []; on('Runtime.consoleAPICalled', (p) => { const text = p.args.map((a) => a.value ?? '').join(' '); if (text.startsWith('PERF_FRAME ')) frames.push(text.split(' ').slice(1).map(Number)); else if (text.startsWith('PERF_FIRST_FRAME ')) firstFrame = Number(text.split(' ')[1]); else if (p.type === 'error') errors.push(text.slice(0, 200)); }); on('Network.requestWillBeSent', (p) => { const url = p.request.url; if (/^https?:/.test(url) && !url.startsWith(server.origin)) offOrigin.add(url); }); async function tap([x, y]) { for (const type of ['mouseMoved', 'mousePressed', 'mouseReleased']) { await send('Input.dispatchMouseEvent', { type, x, y, button: 'left', clickCount: 1 }); } } async function drag([x, y, dx, dy]) { await send('Input.dispatchMouseEvent', { type: 'mouseMoved', x, y, button: 'none' }); await send('Input.dispatchMouseEvent', { type: 'mousePressed', x, y, button: 'left', clickCount: 1 }); for (let i = 1; i <= 40; i++) { await send('Input.dispatchMouseEvent', { type: 'mouseMoved', x: x + (dx * i) / 40, y: y + (dy * i) / 40, button: 'left', buttons: 1 }); await delay(16); } await send('Input.dispatchMouseEvent', { type: 'mouseReleased', x: x + dx, y: y + dy, button: 'left', clickCount: 1 }); } async function run(steps) { for (const step of steps ?? []) { if (step.click) { await tap(step.click); await delay(1000); } if (step.drag) { await drag(step.drag); await delay(400); } if (step.wheel) { const [x, y, deltaY, count] = step.wheel; for (let i = 0; i < count; i++) { await send('Input.dispatchMouseEvent', { type: 'mouseWheel', x, y, deltaX: 0, deltaY }); await delay(16); } await delay(400); } } } // The engine hands timings over in batches; two late frames flush them. async function settle(ms = 1500) { await delay(ms); for (let i = 0; i < 2; i++) { await evaluate('window.__perfKick?.()'); await delay(250); } } async function heapMB() { await send('HeapProfiler.collectGarbage'); const { metrics } = await send('Performance.getMetrics'); return (metrics.find((m) => m.name === 'JSHeapUsedSize')?.value ?? 0) / 1048576; } async function load(s, design) { const [w, h] = s.size.split('x').map(Number); await send('Emulation.setDeviceMetricsOverride', { width: w, height: h, deviceScaleFactor: 1, mobile: false }); const url = new URL('/', server.origin); url.searchParams.set('route', s.route); url.searchParams.set('theme', 'dark'); url.searchParams.set('perf', '1'); url.searchParams.set('design', design); for (const [k, v] of Object.entries(s.q ?? {})) url.searchParams.set(k, v); frames = []; firstFrame = null; offOrigin = new Set(); await send('Page.navigate', { url: url.href }); for (let i = 0; i < 300 && firstFrame === null; i++) await delay(50); await settle(2000); } // One measured repetition of [s] under [design]: frame sums and maxima. async function measure(s, design, others) { await load(s, design); const start = frames.length; const out = { firstFrame }; if (s.live) { // Each round switches to every other design and back to this one. const before = await heapMB(); for (let i = 0; i < Number(opts.switches); i++) { for (const other of others) { await evaluate(`window.__perfDesign(${JSON.stringify(other)})`); await delay(350); await evaluate(`window.__perfDesign(${JSON.stringify(design)})`); await delay(350); } } await settle(); out.switches = Number(opts.switches) * others.length * 2; out.heapGrowthMB = (await heapMB()) - before; } else { await run(s.act); await settle(); } fetchesBy[design] ??= new Set(); for (const url of offOrigin) fetchesBy[design].add(url.replace(/\?.*/, '')); const f = frames.slice(start).filter((x) => x[0] + x[1] > 300); const sum = (i) => f.reduce((a, x) => a + x[i], 0) / 1000; const max = (i) => f.reduce((a, x) => Math.max(a, x[i]), 0) / 1000; const mean = (i) => (f.length ? sum(i) / f.length : 0); return { ...out, frames: f.length, buildMean: mean(0), rasterMean: mean(1), buildSum: sum(0), buildMax: max(0), rasterSum: sum(1), rasterMax: max(1), over16: f.filter((x) => x[2] > 16667).length }; } await mkdir(opts.out, { recursive: true }); const results = {}; const failures = []; try { await send('Page.enable'); await send('Runtime.enable'); await send('Network.enable'); await send('Performance.enable'); await send('Page.addScriptToEvaluateOnNewDocument', { source: 'try { localStorage.clear(); sessionStorage.clear(); } catch (_) {}', }); await load(SCENARIOS[0], 'default'); const registered = JSON.parse(await evaluate('window.__perfDesigns?.() ?? "[]"')); if (!registered.length) throw new Error('build has no window.__perfDesigns (rebuild the fixture with ?perf=1 support)'); const designs = opts.designs ? opts.designs.split(',') : registered; if (designs[0] !== 'default') designs.unshift('default'); console.log(`designs: ${designs.join(', ')} renderer: ${await evaluate(`(window._flutter_skwasmInstance ? 'skwasm' : 'canvaskit')`)}`); const only = opts.only?.split(','); for (const s of SCENARIOS.filter((s) => !only || only.includes(s.name))) { for (const design of designs) { const others = registered.filter((d) => d !== design); const reps = []; for (let rep = 0; rep < Number(opts.repeat); rep++) reps.push(await measure(s, design, others)); const keys = Object.keys(reps[0]).filter((k) => typeof reps[0][k] === 'number'); const row = Object.fromEntries(keys.map((k) => [k, r1(median(reps.map((r) => r[k])))])); (results[s.name] ??= {})[design] = row; console.log(`${s.name.padEnd(7)} ${design.padEnd(10)} ${JSON.stringify(row)}`); const base = results[s.name].default; if (design !== 'default' && base) { // Per-frame means, not sums: a cheaper design draws more frames in // the same gesture, so its sum can exceed a slower design's. for (const key of ['buildMean', 'rasterMean']) { const limit = base[key] * Number(opts.ratio) + Number(opts.slack); if (row[key] > limit) failures.push(`${s.name}/${design}: ${key} ${row[key]} ms > ${r1(limit)} ms (Default ${base[key]})`); } } if (s.live && row.heapGrowthMB > Number(opts.leak)) { failures.push(`${s.name}/${design}: heap grew ${row.heapGrowthMB} MB over ${row.switches} switches`); } } } const baseline = fetchesBy.default ?? new Set(); for (const [design, urls] of Object.entries(fetchesBy)) { console.log(`off-origin ${design.padEnd(10)} ${[...urls].join(' ') || 'none'}`); const added = [...urls].filter((url) => !baseline.has(url)); if (design !== 'default' && added.length) failures.push(`${design}: fetches Default does not: ${added.join(', ')}`); } if (errors.length) console.log('page errors (first 5):', [...new Set(errors)].slice(0, 5)); await writeFile(join(opts.out, 'design-bench.json'), JSON.stringify({ build: opts.build, gpu: Boolean(opts.gpu), results, fetches: Object.fromEntries(Object.entries(fetchesBy).map(([k, v]) => [k, [...v]])), failures }, null, 2)); } finally { await browser.close().catch(() => {}); await server.close(); } if (failures.length) { console.log(`FAIL\n ${failures.join('\n ')}`); process.exit(1); } console.log('PASS: every design within budget of Default');