okami.mom/strata

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

Niko1221rc1 merge tui-update (3165c2e8a)a1cc285fa

main
11.1 KiB292 linesraw
1#!/usr/bin/env node
2/**
3 * Motion capture and interruptibility check.
4 *
5 *   node scripts/motion.mjs
6 *
7 * Two jobs:
8 *
9 *  1. Record the canonical interactions and sample frames from each recording
10 *     into a contact sheet (`.shots/motion-<name>.png`), so choreography can be
11 *     reviewed as pictures rather than argued about.
12 *  2. Assert the thing a screenshot cannot show: that a surface toggled
13 *     mid-flight *reverses* rather than queueing or jumping to the end.
14 *
15 * Requires the dev server and a cached Chromium. The bundled ffmpeg that ships
16 * with Playwright is used to extract frames.
17 */
18import { chromium } from 'playwright-core';
19import { execFile } from 'node:child_process';
20import { promisify } from 'node:util';
21import { existsSync, mkdirSync, rmSync, readdirSync } from 'node:fs';
22import { join, resolve } from 'node:path';
23import { homedir } from 'node:os';
24import { requireChromium } from './browser.mjs';
25
26const run = promisify(execFile);
27const BASE = process.env.STRATA_URL ?? 'http://localhost:5199';
28const ROOT = resolve(process.env.STRATA_SHOTS ?? '.shots');
29const TMP = join(ROOT, 'motion-frames');
30mkdirSync(TMP, { recursive: true });
31
32const executablePath = requireChromium();
33
34const ffmpeg = [
35  join(homedir(), 'Library/Caches/ms-playwright/ffmpeg-1011/ffmpeg-mac'),
36  '/opt/homebrew/bin/ffmpeg',
37].find((p) => existsSync(p));
38
39if (!executablePath) {
40  console.error('No cached Chromium found.');
41  process.exit(2);
42}
43
44const W = 1280;
45const H = 720;
46const failures = [];
47
48/** Record one interaction, then sample frames from the resulting webm. */
49async function clip(browser, name, script) {
50  const dir = join(TMP, name);
51  rmSync(dir, { recursive: true, force: true });
52  mkdirSync(dir, { recursive: true });
53
54  const t0 = Date.now();
55  const context = await browser.newContext({
56    viewport: { width: W, height: H },
57    recordVideo: { dir, size: { width: W, height: H } },
58  });
59  const page = await context.newPage();
60  page.on('pageerror', (e) => failures.push(`${name}: page error — ${e.message}`));
61  await page.goto(`${BASE}/#/chat`, { waitUntil: 'domcontentloaded' });
62  await page.waitForTimeout(1200);
63  // Recording starts at context creation, so the first second is page load.
64  // Each clip reports when its interaction actually happened, and frames are
65  // sampled from that window — otherwise every sheet shows an idle app.
66  const started = Date.now();
67  await script(page);
68  const window = { from: (started - t0) / 1000, to: (Date.now() - t0) / 1000 };
69  const video = page.video();
70  await context.close();
71
72  const videoPath = video ? await video.path() : null;
73  if (!videoPath || !existsSync(videoPath)) {
74    failures.push(`${name}: no recording produced`);
75    return null;
76  }
77
78  if (!ffmpeg) {
79    console.log(`  ${name}: recorded, but no ffmpeg found to sample frames`);
80    return videoPath;
81  }
82
83  // The ffmpeg Playwright bundles is a stripped build (no `fps` or `hstack`
84  // filters), so frames are taken by seeking to a timestamp and grabbing one.
85  const span = Math.max(0.6, window.to - window.from);
86  const stamps = Array.from({ length: 6 }, (_, i) => Number((window.from + (span * i) / 5).toFixed(2)));
87  const frames = [];
88  for (const t of stamps) {
89    const out = join(dir, `t${String(t).replace('.', '_')}.png`);
90    await run(ffmpeg, ['-y', '-ss', String(t), '-i', videoPath, '-frames:v', '1', out]).catch(() => {});
91    if (existsSync(out)) frames.push(out);
92  }
93  if (!frames.length) failures.push(`${name}: ffmpeg produced no frames`);
94  return { videoPath, frames, window };
95}
96
97/**
98 * Stitch sampled frames into one image. Done in Python rather than ffmpeg
99 * because the bundled build has no `hstack` filter.
100 */
101async function contactSheet(name, frames) {
102  if (!frames?.length) return;
103  const out = join(ROOT, `motion-${name}.png`);
104  const script = `
105import sys
106from PIL import Image
107paths, out = sys.argv[1:-1], sys.argv[-1]
108ims = [Image.open(p) for p in paths]
109w = sum(i.width for i in ims)
110h = max(i.height for i in ims)
111sheet = Image.new('RGB', (w, h), '#ffffff')
112x = 0
113for im in ims:
114    sheet.paste(im, (x, 0))
115    x += im.width
116sheet.save(out)
117`;
118  await run('python3', ['-c', script, ...frames, out]).catch(() =>
119    failures.push(`${name}: could not build the contact sheet`),
120  );
121  if (existsSync(out)) console.log(`  ${name}: ${frames.length} frames -> ${out}`);
122}
123
124const browser = await chromium.launch({ executablePath, args: ['--no-sandbox'] });
125console.log('recording interactions\n');
126
127const clips = {
128  'route-change': async (page) => {
129    await page.keyboard.press('Meta+3');
130    await page.waitForTimeout(700);
131    await page.keyboard.press('Meta+5');
132    await page.waitForTimeout(700);
133  },
134  'drawer-toggle': async (page) => {
135    await page.click('button.nav-new');
136    await page.waitForTimeout(400);
137    await page.getByRole('button', {name:'Add a task',exact:true}).click();
138    await page.waitForTimeout(600);
139    await page.getByRole('button', {name:/Close .*task/i}).click();
140    await page.waitForTimeout(600);
141  },
142  'palette-toggle': async (page) => {
143    await page.keyboard.press('Meta+k');
144    await page.waitForTimeout(600);
145    await page.keyboard.press('Escape');
146    await page.waitForTimeout(600);
147  },
148  disclosure: async (page) => {
149    await page.click('button.nav-new');
150    await page.waitForTimeout(300);
151    await page.fill('textarea', 'read the readme');
152    await page.keyboard.press('Enter');
153    await page.waitForTimeout(7000);
154    const details = page.locator('.st-collapse').first();
155    if (await details.count()) {
156      await details.locator('summary').click();
157      await page.waitForTimeout(400);
158      await details.locator('summary').click();
159      await page.waitForTimeout(500);
160    }
161  },
162};
163
164for (const [name, script] of Object.entries(clips)) {
165  const result = await clip(browser, name, script);
166  if (result && typeof result === 'object') {
167    console.log(`  ${name}: sampling ${result.window.from.toFixed(2)}s–${result.window.to.toFixed(2)}s`);
168    await contactSheet(name, result.frames);
169  }
170}
171
172/* ---------------------------------------------------- interruptibility ---- */
173
174/**
175 * Open a surface, reverse it mid-flight, and confirm it comes to rest in the
176 * reversed state. A queued or keyframe-driven animation fails this: it finishes
177 * the entrance first and only then plays the exit.
178 */
179async function reversesMidFlight(label, open, close, readState) {
180  const page = await browser.newPage({ viewport: { width: W, height: H } });
181  await page.goto(`${BASE}/#/chat`, { waitUntil: 'domcontentloaded' });
182  await page.waitForTimeout(1200);
183  await open(page);
184  await page.waitForTimeout(60); // deliberately inside the entrance
185  await close(page);
186  await page.waitForTimeout(500); // longer than any transition on the scale
187  const settled = await readState(page);
188  await page.close();
189  if (!settled) failures.push(`${label}: did not settle in the reversed state`);
190  console.log(`  ${label}: reversed mid-flight — ${settled ? 'settled closed' : 'STUCK OPEN'}`);
191}
192
193/* A step that throws must still leave the other checks reported — a crash
194   before the summary tells the reader nothing about what did pass. */
195try {
196  await reversesMidFlight(
197    'task dialog',
198    (p) => p.click('button.nav-new').then(() => p.waitForTimeout(300)).then(() => p.getByRole('button', {name:'Add a task',exact:true}).click()),
199    (p) => p.getByRole('button', {name:/Close .*task/i}).click(),
200    (p) =>
201      p.evaluate(() => {
202        const el = document.querySelector('.dialog-layer');
203        if (!el) return true;
204        return getComputedStyle(el).visibility === 'hidden';
205      }),
206  );
207
208  await reversesMidFlight(
209    'command palette',
210    (p) => p.keyboard.press('Meta+k'),
211    (p) => p.keyboard.press('Escape'),
212    (p) =>
213      p.evaluate(() => {
214        const el = document.querySelector('.modal');
215        return !!el && !el.matches('[data-open="true"]') && getComputedStyle(el).visibility === 'hidden';
216      }),
217  );
218
219  /**
220   * One loop per region.
221   *
222   * Several indefinite animations running in the same part of the screen read as
223   * a fault rather than as activity — two pulsing things side by side have no
224   * hierarchy, and the eye cannot settle on either. Each screen is checked for
225   * regions containing more than one looping animation.
226   *
227   * "Region" is the nearest ancestor that is a card, a panel or the page body, so
228   * a spinner inside a list row is judged against that row rather than against
229   * everything on the screen.
230   */
231  async function loopBudget(route, theme) {
232    const page = await browser.newPage({ viewport: { width: 1512, height: 1110 } });
233    await page.goto(`${BASE}/#/${route}`, { waitUntil: 'domcontentloaded' });
234    await page.waitForTimeout(1500);
235    if (theme === 'dark') {
236      /* Set the theme the way the app does rather than by clicking a control a
237         modal may be covering — the setup screen renders one over the whole
238         window, and clicking through it timed out. */
239      await page.evaluate(() => {
240        const raw = JSON.parse(localStorage.getItem('strata.prefs.v2') ?? '{}');
241        localStorage.setItem('strata.prefs.v2', JSON.stringify({ ...raw, theme: 'dark' }));
242      });
243      await page.reload({ waitUntil: 'domcontentloaded' });
244      await page.waitForTimeout(1200);
245    }
246    const out = await page.evaluate(() => {
247      const loops = [...document.querySelectorAll('*')].filter((el) => {
248        const cs = getComputedStyle(el);
249        if (!cs.animationIterationCount.split(',').some((v) => v.trim() === 'infinite')) return false;
250        const r = el.getBoundingClientRect();
251        return r.width > 0 && r.height > 0 && cs.visibility !== 'hidden';
252      });
253      const regions = new Map();
254      for (const el of loops) {
255        const region =
256          el.closest('.st-card, .st-drawer, section, aside, table') ?? document.querySelector('.main__body') ?? document.body;
257        const label = region.className?.toString().split(' ').slice(0, 2).join('.') || region.tagName.toLowerCase();
258        regions.set(label, (regions.get(label) ?? 0) + 1);
259      }
260      return [...regions.entries()].map(([label, n]) => ({ label, n }));
261    });
262    await page.close();
263    return out;
264  }
265
266  for (const theme of ['light', 'dark']) {
267    // Every route a reader can reach, not just the ones the reverse checks visit.
268  for (const route of ['chat', 'models', 'tuning', 'monitor', 'serving', 'workspace', 'skills', 'settings', 'setup']) {
269      const regions = await loopBudget(route, theme);
270      const over = regions.filter((r) => r.n > 1);
271      for (const r of over) failures.push(`${theme} · ${route}: ${r.n} loops at once in "${r.label}"`);
272    }
273  }
274} catch (err) {
275  failures.push(`a step threw before finishing: ${err instanceof Error ? err.message.split('\n')[0] : err}`);
276}
277
278await browser.close();
279
280/* The summary has to name what was checked. Saying "every surface reverses
281   mid-flight" when the failure was two spinners in one card would send the
282   reader looking in the wrong place. */
283console.log(
284  failures.length
285    ? `\nmotion: ${failures.length} failure(s)\n  ${failures.join('\n  ')}`
286    : [
287        '',
288        'motion: every surface reverses mid-flight',
289        'motion: one loop per region on every screen, both themes',
290      ].join('\n'),
291);
292process.exit(failures.length ? 1 : 0);