okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221rc1 merge tui-update (3165c2e8a)a1cc285fa

main
8.4 KiB205 linesraw
1#!/usr/bin/env node
2/**
3 * Strata motion budget.
4 *
5 *   node scripts/motionbudget.mjs
6 *
7 * The plans ask for one thing about the scroll-driven effects that a static
8 * audit cannot answer: what do they cost while you actually scroll? Six rules
9 * are bound to the transcript's scroll timeline, and "it looks smooth" is not a
10 * measurement.
11 *
12 * So this scrolls a real transcript twice — once as shipped, once with the
13 * scroll-driven animations switched off — and compares p95 frame time. The
14 * budget is 1.2x, taken from plan 15. A ratio rather than an absolute figure
15 * because absolute frame times depend on the machine running the check.
16 *
17 * Requires the dev server.
18 */
19import { chromium } from 'playwright-core';
20import { existsSync } from 'node:fs';
21import { join } from 'node:path';
22import { homedir } from 'node:os';
23import { requireChromium } from './browser.mjs';
24
25const BASE = process.env.STRATA_URL ?? 'http://localhost:5199';
26const BUDGET = 1.2;
27
28const executablePath = requireChromium();
29
30if (!executablePath) {
31  console.error('No cached Chromium found. Run `npm run shot -- x.png <url>` once to confirm the harness.');
32  process.exit(2);
33}
34
35const browser = await chromium.launch({ executablePath, args: ['--no-sandbox'] });
36
37/**
38 * Confirms the harness can see a cost at all, before trusting it to report one.
39 *
40 * This was written after the check passed with a deliberately expensive effect
41 * injected — blur, saturation and scale bound to every message's scroll
42 * timeline — and the ratio did not move. In this environment, programmatic
43 * scrolling does not appear to drive scroll-timeline paint cost, so the
44 * measurement cannot distinguish cheap from expensive here.
45 *
46 * A budget check that cannot detect a six-fold increase in per-frame work is
47 * worse than no check: it reports "within budget" with confidence it has not
48 * earned. So it measures a known-expensive case first and says so when it
49 * cannot see the difference.
50 */
51async function canDiscriminate() {
52  const page = await browser.newPage({ viewport: { width: 1512, height: 700 } });
53  await page.goto(`${BASE}/#/chat`, { waitUntil: 'domcontentloaded' });
54  await page.waitForTimeout(1500);
55  await page.click('button.nav-new');
56  await page.waitForTimeout(400);
57  for (const m of ['write a paragraph about tides', 'and another about the moon']) {
58    await page.fill('textarea', m);
59    await page.keyboard.press('Enter');
60    await page.waitForTimeout(8000);
61    await page.keyboard.press('Enter').catch(() => {});
62    await page.waitForTimeout(3500);
63  }
64  await scrollProfile(page);
65  const before = await scrollProfile(page);
66  await page.addStyleTag({
67    content: `@keyframes probe-expensive { from { filter: blur(0px); } to { filter: blur(8px) saturate(2); } }
68              .st-msg { scroll-timeline: --probe block; animation: probe-expensive linear both; animation-timeline: --probe; }`,
69  });
70  await scrollProfile(page);
71  const after = await scrollProfile(page);
72  await page.close();
73  return { before: stats(before.frames), after: stats(after.frames) };
74}
75
76/**
77 * Scrolls the transcript and returns the frame deltas.
78 *
79 * Deliberately drives the scroll from inside the page on rAF: driving it over
80 * the protocol would measure the round-trip rather than the rendering.
81 */
82async function scrollProfile(page) {
83  return page.evaluate(
84    () =>
85      new Promise((resolve) => {
86        const el = document.querySelector('.main__body.chat');
87        if (!el) return resolve(null);
88        const frames = [];
89        let last = performance.now();
90        const started = last;
91        let dir = 1;
92        const step = () => {
93          const now = performance.now();
94          frames.push(now - last);
95          last = now;
96          // sweep down then up, so both directions are represented
97          el.scrollTop += dir * 24;
98          if (el.scrollTop <= 0) dir = 1;
99          if (el.scrollTop >= el.scrollHeight - el.clientHeight) dir = -1;
100          if (frames.length < 240) requestAnimationFrame(step);
101          else resolve({ frames: frames.slice(5), wall: performance.now() - started });
102        };
103        requestAnimationFrame(step);
104      }),
105  );
106}
107
108/**
109 * What is measured, and why not p95 frame time.
110 *
111 * The first version of this compared p95 frame deltas and reported a ratio of
112 * exactly 1.000 — then still reported 1.006 against a deliberately expensive
113 * scroll-driven effect (blur, saturation and scale on every message). p95 sits
114 * at the 60fps frame cap in both runs, so it is saturated: any cost that fits
115 * inside a frame reads as free. A check that cannot detect a six-fold increase
116 * in per-frame work is not measuring the thing it claims to.
117 *
118 * What does discriminate is **total scripting time for a fixed amount of
119 * scrolling**, which accumulates work that individual frames hide.
120 */
121const stats = (xs) => {
122  const sorted = [...xs].sort((a, b) => a - b);
123  const at = (q) => sorted[Math.min(sorted.length - 1, Math.floor(sorted.length * q))];
124  return { p50: at(0.5), p95: at(0.95), total: xs.reduce((a, b) => a + b, 0), n: xs.length };
125};
126
127async function makeTranscript() {
128  const page = await browser.newPage({ viewport: { width: 1512, height: 700 } });
129  await page.goto(`${BASE}/#/chat`, { waitUntil: 'domcontentloaded' });
130  await page.waitForTimeout(1500);
131  await page.click('button.nav-new');
132  await page.waitForTimeout(400);
133  for (const m of ['write a paragraph about tides', 'and another about the moon', 'and one about the wind']) {
134    await page.fill('textarea', m);
135    await page.keyboard.press('Enter');
136    await page.waitForTimeout(8000);
137    await page.keyboard.press('Enter').catch(() => {});
138    await page.waitForTimeout(3500);
139  }
140  return page;
141}
142
143/* ---- run ---------------------------------------------------------------- */
144
145// First: can this harness see a cost at all? Without this the check would
146// report "within budget" whether or not it was measuring anything.
147const probe = await canDiscriminate();
148const probeRatio = probe.before.total > 0 ? probe.after.total / probe.before.total : 1;
149const blind = probeRatio < 1.05;
150
151console.log('self-check: known-expensive effect');
152console.log(`  total frame time ${probe.before.total.toFixed(0)}ms -> ${probe.after.total.toFixed(0)}ms (${probeRatio.toFixed(3)}x)`);
153
154if (blind) {
155  console.log('  the harness cannot see a deliberately expensive effect, so it cannot');
156  console.log('  measure the real one either. Reporting nothing rather than passing.');
157  console.log('\nmotion budget: NOT MEASURED — see plan 15');
158  await browser.close();
159  process.exit(3);
160}
161console.log('  detected, so the measurement below is meaningful\n');
162
163const page = await makeTranscript();
164const room = await page.evaluate(() => {
165  const el = document.querySelector('.main__body.chat');
166  return el ? el.scrollHeight - el.clientHeight : 0;
167});
168
169if (room < 200) {
170  console.log(`motion budget: not enough transcript to scroll (${room}px) — skipped`);
171  await browser.close();
172  process.exit(0);
173}
174
175// warm up so the first pass is not paying for layout the second one gets free
176await scrollProfile(page);
177const shipped = await scrollProfile(page);
178
179// the same page, with the scroll-driven animations switched off
180await page.addStyleTag({
181  content: `*, *::before, *::after { animation-timeline: none !important; animation-name: none !important; }`,
182});
183await scrollProfile(page);
184const withoutEffects = await scrollProfile(page);
185
186await browser.close();
187
188const a = stats(shipped.frames);
189const b = stats(withoutEffects.frames);
190// Compared on total frame time for the same number of scroll steps.
191const ratio = b.total > 0 ? a.total / b.total : 1;
192// Reported alongside, to show whether the p95 was saturated.
193const p95Ratio = b.p95 > 0 ? a.p95 / b.p95 : 1;
194
195console.log(`scroll room           : ${Math.round(room)}px`);
196console.log(`frames sampled        : ${a.n} (${Math.round(shipped.wall)}ms as shipped, ${Math.round(withoutEffects.wall)}ms without)`);
197console.log(`total frame time      : ${a.total.toFixed(0)}ms shipped vs ${b.total.toFixed(0)}ms without`);
198console.log(`p95 frame             : ${a.p95.toFixed(2)}ms vs ${b.p95.toFixed(2)}ms (ratio ${p95Ratio.toFixed(3)}x — usually saturated at the frame cap)`);
199console.log(`ratio                 : ${ratio.toFixed(3)}x (budget ${BUDGET}x)`);
200
201if (ratio > BUDGET) {
202  console.log(`\nmotion budget: FAIL — scroll-driven effects cost ${ratio.toFixed(2)}x, over the ${BUDGET}x budget`);
203  process.exit(1);
204}
205console.log('\nmotion budget: within budget');