~ knotless Search/
↑↓ move↵ open⇧↵ all results

zat.dev/zds

atproto pds · mirror of https://tangled.org/zat.dev/zds

0
0
481 lines · 27.7 KB Raw History
#!/usr/bin/env node
// Release UI gate: scrolls every web page under both skins at phone and
// desktop size against a local zds and fails on a frame-time, scroll-tracking,
// legibility or toolbar-overlap regression. `just ui-gate` runs it and
// `just release` refuses to tag without it.
//
//   node tools/ui-gate.mjs [--bin path/to/zds] [--skins paper,garden] [--pages home,stats]
//
// Output: ui-gate-out/<version>/{summary.json,*.webm,*.png}; exit 1 on any failure.
import { createRequire } from 'node:module';
import { execFileSync, spawn } from 'node:child_process';
import { mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
import { createServer } from 'node:http';
import { tmpdir } from 'node:os';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';

const require = createRequire(new URL('./ui-gate/package.json', import.meta.url));
const { chromium, devices } = require('playwright');

// Thresholds. Calibrated on v0.17.2 (cf48902), Apple M5 Pro, headless
// Chromium 131 with Metal ANGLE: see CALIBRATION below for the worst values
// that run produced. They are limits, not targets; do not raise them to pass.
const P95_MS = { phone: 34, desktop: 20 };
const LONG_TASK_MS = 100;
const TRACK_PX = 0.5;
const CONTRAST = { body: 4.5, large: 3 };
// CALIBRATION (v0.17.2, 2026-11-24): rAF p95 was 16.7-16.8 ms on every page at
// phone size under both skins, and on desktop under paper. Garden on desktop
// (1440x900 at DPR 2) took a median-of-three p95 of 16.7 ms on most pages but
// 33.3 ms on sign-in and account, which this gate fails on purpose. The worst
// long frame seen while scrolling was 82 ms (garden account, phone), with one
// 112 ms outlier that the median discards.

const root = join(dirname(fileURLToPath(import.meta.url)), '..');
const args = Object.fromEntries(process.argv.slice(2).reduce((acc, a, i, all) => (a.startsWith('--') ? [...acc, [a.slice(2), all[i + 1]]] : acc), []));
const version = readFileSync(join(root, 'build.zig.zon'), 'utf8').match(/\.version = "([^"]+)"/)[1];
const out = join(root, 'ui-gate-out', version);
rmSync(out, { recursive: true, force: true });
mkdirSync(out, { recursive: true });

let bin = args.bin;
if (!bin) {
  const prefix = join(out, 'build');
  console.log(`building zds ${version} with the garden skin`);
  execFileSync(process.env.ZIG || 'zig', ['build', '-Doptimize=ReleaseSafe', '-Dweb-garden=true', '-p', prefix], { cwd: root, stdio: 'inherit' });
  bin = join(prefix, 'bin', 'zds');
}
const skins = (args.skins || 'paper,garden').split(',');
const onlyPages = args.pages ? args.pages.split(',') : null;

const LONG_SCOPE = 'atproto repo:app.bsky.feed.post repo:app.bsky.feed.like repo:app.bsky.feed.repost repo:app.bsky.graph.follow repo:app.bsky.actor.profile repo:fm.plyr.track repo:fm.plyr.list blob:*/* account:email';
const PASSWORD = 'ui-gate-password';

// ---------- a PLC directory and OAuth client, enough for zds to create accounts and show sign-in ----------
const plcOps = new Map();
const stub = createServer((req, res) => {
  let body = '';
  req.on('data', c => { body += c; });
  req.on('end', () => {
    const port = stub.address().port;
    const did = decodeURIComponent(req.url.slice(1));
    if (req.method === 'POST' && did.startsWith('did:plc:')) { plcOps.set(did, [...(plcOps.get(did) || []), JSON.parse(body)]); res.end(); return; }
    if (req.url === '/oauth-client-metadata.json') {
      res.setHeader('content-type', 'application/json');
      res.end(JSON.stringify({ client_id: `http://127.0.0.1:${port}/oauth-client-metadata.json`, client_name: 'ui gate', redirect_uris: ['http://127.0.0.1/callback'], scope: LONG_SCOPE, grant_types: ['authorization_code', 'refresh_token'], response_types: ['code'], token_endpoint_auth_method: 'none', application_type: 'native', dpop_bound_access_tokens: true }));
      return;
    }
    const last = did.match(/^(did:plc:[^/]+)\/log\/last$/);
    if (last && plcOps.has(last[1])) { res.setHeader('content-type', 'application/json'); res.end(JSON.stringify(plcOps.get(last[1]).at(-1))); return; }
    res.statusCode = 404; res.end();
  });
});
await new Promise(r => stub.listen(0, '127.0.0.1', r));
const plcPort = stub.address().port;
const clientId = `http://127.0.0.1:${plcPort}/oauth-client-metadata.json`;

const freePort = () => new Promise(r => { const s = createServer(); s.listen(0, '127.0.0.1', () => { const p = s.address().port; s.close(() => r(p)); }); });
const post = async (url, body, token) => {
  const r = await fetch(url, { method: 'POST', headers: { 'content-type': 'application/json', ...(token ? { authorization: `Bearer ${token}` } : {}) }, body: JSON.stringify(body) });
  if (!r.ok) throw new Error(`${url}: ${r.status} ${await r.text()}`);
  return r.json();
};

async function bootZds(skin) {
  const dir = mkdtempSync(join(tmpdir(), `zds-ui-gate-${skin}-`));
  mkdirSync(join(dir, 'blobs'));
  const port = await freePort(), base = `http://localhost:${port}`, db = join(dir, 'zds.sqlite3');
  const proc = spawn(bin, ['--host', '127.0.0.1', '--port', String(port), '--db', db, '--blobstore-path', join(dir, 'blobs'), '--public-url', base, '--server-did', 'did:web:localhost', '--handle-domains', '.pds.garden', '--admin-token', 'ui-gate-admin', '--plc-directory', `http://127.0.0.1:${plcPort}`], {
    env: { ...process.env, ZDS_PLC_ROTATION_KEY: '1'.repeat(64), ZDS_MAIL_PROVIDER: 'outbox', ZDS_ALLOW_PRIVATE_FETCH: 'true', ZDS_WEB_SKIN: skin },
    stdio: ['ignore', 'ignore', 'pipe'],
  });
  let log = ''; proc.stderr.on('data', d => { log += d; });
  for (let i = 0; ; i++) {
    try { if ((await fetch(base + '/xrpc/_health')).ok) break; } catch {}
    if (i > 100 || proc.exitCode !== null) throw new Error(`zds (${skin}) did not start:\n${log.slice(-2000)}`);
    await new Promise(r => setTimeout(r, 100));
  }
  for (const h of ['nate', 'alice', 'juniper']) {
    const a = await post(base + '/xrpc/com.atproto.server.createAccount', { handle: `${h}.pds.garden`, email: `${h}@example.com`, password: PASSWORD });
    for (let n = 1; n <= 3; n++) await post(base + '/xrpc/com.atproto.repo.createRecord', { repo: a.did, collection: 'app.bsky.feed.post', record: { $type: 'app.bsky.feed.post', text: `hello ${n}`, createdAt: `2026-11-23T00:00:0${n}Z` } }, a.accessJwt);
  }
  const expires = Math.floor(Date.now() / 1000) + 3600;
  const rows = [['gate-signin', 'atproto', null], ['gate-consent', LONG_SCOPE, 'nate.pds.garden']]
    .map(([id, scope, hint]) => `('${id}','${clientId}','http://127.0.0.1/callback','${scope}','state','challenge','S256',${hint ? `'${hint}'` : 'NULL'},${expires})`).join(',');
  execFileSync('sqlite3', [db, `insert into oauth_requests (request_id, client_id, redirect_uri, scope, state, code_challenge, code_challenge_method, login_hint, expires_at) values ${rows};`]);
  return { base, stop: () => { proc.kill(); rmSync(dir, { recursive: true, force: true }); } };
}

const req = id => '/oauth/authorize?request_uri=' + encodeURIComponent('urn:ietf:params:oauth:request_uri:' + id);
const PAGES = [
  { name: 'home', path: '/' },
  { name: 'stats', path: '/stats' },
  { name: 'signup', path: '/signup' },
  { name: 'signin', path: req('gate-signin') },
  { name: 'consent', path: req('gate-consent'), consent: true },
  { name: 'account', path: '/account' },
].filter(p => !onlyPages || onlyPages.includes(p.name));
const VIEWPORTS = [
  { name: 'phone', ctx: { ...devices['iPhone 13'] } },
  { name: 'desktop', ctx: { viewport: { width: 1440, height: 900 }, deviceScaleFactor: 2 } },
];

// ---------- in-page checks ----------
const CARD_SEL = '.card,.hero,.pulse,.grid>section,.g-sheet,.sheet-card';
function pageChecks({ CARD_SEL, CONTRAST }) {
  const fails = [];
  const rgba = s => { const m = s.match(/rgba?\(([^)]+)\)/); if (!m) return null; const p = m[1].split(/[\s,/]+/).filter(Boolean).map(parseFloat); return [p[0], p[1], p[2], p.length > 3 ? p[3] : 1]; };
  const lum = c => { const f = v => { v /= 255; return v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4; }; return 0.2126 * f(c[0]) + 0.7152 * f(c[1]) + 0.0722 * f(c[2]); };
  const over = (top, under) => [0, 1, 2].map(i => top[i] * top[3] + under[i] * (1 - top[3])).concat(1);
  const visible = el => { for (let e = el; e && e.nodeType === 1; e = e.parentElement) { const cs = getComputedStyle(e); if (cs.display === 'none' || cs.visibility === 'hidden' || parseFloat(cs.opacity) === 0) return false; } const r = el.getBoundingClientRect(); return r.width > 1 && r.height > 1; };
  const label = el => el.tagName.toLowerCase() + (el.id ? '#' + el.id : '') + (el.className && typeof el.className === 'string' ? '.' + el.className.trim().split(/\s+/).join('.') : '');
  const backdrop = el => {
    const layers = [];
    for (let e = el; e; e = e.parentElement) { const c = rgba(getComputedStyle(e).backgroundColor); if (c && c[3] > 0) { layers.push(c); if (c[3] >= 1) break; } }
    if (!layers.length || layers.at(-1)[3] < 1) return null;
    return layers.reduceRight((acc, c) => (acc ? over(c, acc) : c), null);
  };
  const cards = [...document.querySelectorAll(CARD_SEL)];
  const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
  let checked = 0, minRatio = Infinity;
  for (let n; (n = walker.nextNode());) {
    if (!n.textContent.trim()) continue;
    const el = n.parentElement;
    if (!el || el.closest('script,style,noscript,.g-ride,.g-toast,.sheet') || !visible(el)) continue;
    const cs = getComputedStyle(el);
    const fill = rgba(cs.webkitTextFillColor || cs.color), color = rgba(cs.color);
    if ((fill && fill[3] === 0) || (color && color[3] === 0)) fails.push(`transparent text: ${label(el)} "${n.textContent.trim().slice(0, 40)}"`);
    for (let e = el; e; e = e.parentElement) { const s = getComputedStyle(e); if (/blur\(/.test(s.filter) || /blur\(/.test(s.backdropFilter)) { fails.push(`blur on text ancestor ${label(e)}`); break; } }
    if (!cards.some(c => c.contains(el)) || el.closest(':disabled')) continue;
    const bg = backdrop(el);
    if (!bg || !color) continue;
    const fg = color[3] < 1 ? over(color, bg) : color;
    const [a, b] = [lum(fg), lum(bg)];
    const ratio = (Math.max(a, b) + 0.05) / (Math.min(a, b) + 0.05);
    const size = parseFloat(cs.fontSize), weight = parseFloat(cs.fontWeight) || 400;
    const need = size >= 24 || (size >= 18.66 && weight >= 700) ? CONTRAST.large : CONTRAST.body;
    checked++; minRatio = Math.min(minRatio, ratio);
    if (ratio < need) fails.push(`contrast ${ratio.toFixed(2)} < ${need}: ${label(el)} "${n.textContent.trim().slice(0, 40)}"`);
  }
  for (const c of cards) for (const m of c.querySelectorAll('svg,img')) {
    const cs = getComputedStyle(m);
    if (cs.visibility === 'hidden' || parseFloat(cs.opacity) === 0) fails.push(`hidden ${m.tagName.toLowerCase()} in card ${label(c)}`);
  }
  return { fails: [...new Set(fails)], textChecked: checked, minContrast: +minRatio.toFixed(2) };
}

// Card tracking and fixed-over-clickable, measured inside one rAF.
function stepProbe(CARD_SEL) {
  return new Promise(res => requestAnimationFrame(() => {
    const sy = scrollY, st = window.__gate;
    const inFixed = e => { for (let a = e; a; a = a.parentElement) if (getComputedStyle(a).position === "fixed") return true; return false; };
    const cards = [...document.querySelectorAll(CARD_SEL)].filter(c => c.getClientRects().length && !inFixed(c));
    if (!st.tops) st.tops = cards.map(c => c.getBoundingClientRect().top + sy);
    let worst = 0;
    cards.forEach((c, i) => { const d = Math.abs(c.getBoundingClientRect().top - (st.tops[i] - sy)); if (d > worst) worst = d; });
    st.track = Math.max(st.track || 0, worst);
    const fixed = [...document.querySelectorAll('body *')].filter(e => { const cs = getComputedStyle(e); if (cs.position !== 'fixed' || cs.pointerEvents === 'none' || cs.visibility === 'hidden' || e.tagName === 'CANVAS') return false; const r = e.getBoundingClientRect(); return r.width > 0 && r.height > 0; }).map(e => e.getBoundingClientRect());
    const clicks = [...document.querySelectorAll('a[href],button,input:not([type=hidden]),select,textarea')].filter(e => !e.closest('.g-ride,.g-toast') && getComputedStyle(e).visibility !== 'hidden' && e.getClientRects().length);
    st.clear = st.clear || new Map();
    const covered = [];
    clicks.forEach((e, i) => {
      const r = e.getBoundingClientRect();
      if (r.bottom <= 0 || r.top >= innerHeight || r.width < 1) return;
      const hit = fixed.some(f => r.left < f.right && r.right > f.left && r.top < f.bottom && r.bottom > f.top);
      const key = i + ':' + (e.textContent || e.name || e.type || '').trim().slice(0, 30);
      if (!hit) st.clear.set(key, true); else { if (!st.clear.has(key)) st.clear.set(key, false); covered.push(key); }
    });
    st.lastCovered = covered;
    res(scrollY);
  }));
}

async function scrollPass(page, measure) {
  await page.evaluate(() => {
    window.__gate = { frames: [], loaf: [], long: [] };
    const g = window.__gate;
    (function f(t) { g.frames.push(t); g.raf = requestAnimationFrame(f); })(performance.now());
    try { new PerformanceObserver(l => g.loaf.push(...l.getEntries().map(e => e.duration))).observe({ type: 'long-animation-frame' }); } catch {}
    try { new PerformanceObserver(l => g.long.push(...l.getEntries().map(e => e.duration))).observe({ type: 'longtask' }); } catch {}
  });
  const box = page.viewportSize();
  await page.mouse.move(box.width / 2, box.height / 2);
  for (const dir of [1, -1]) {
    for (let i = 0; i < 200; i++) {
      const before = await page.evaluate(() => scrollY);
      await page.mouse.wheel(0, 120 * dir);
      await page.waitForTimeout(16);
      if (measure) await page.evaluate(stepProbe, CARD_SEL);
      const after = await page.evaluate(() => scrollY);
      if (after === before && i > 0) break;
      if (dir > 0 && i === 0 && after === before) break;
    }
    if (measure && dir > 0) await page.evaluate(() => { window.__gate.bottomCovered = window.__gate.lastCovered || []; });
  }
  return page.evaluate(() => {
    const g = window.__gate; cancelAnimationFrame(g.raf);
    const d = []; for (let i = 1; i < g.frames.length; i++) d.push(g.frames[i] - g.frames[i - 1]);
    d.sort((a, b) => a - b);
    const q = p => (d.length ? +d[Math.min(d.length - 1, Math.floor(d.length * p))].toFixed(1) : 0);
    const never = g.clear ? [...g.clear].filter(([, ok]) => !ok).map(([k]) => k) : [];
    return { frames: d.length, p50: q(0.5), p95: q(0.95), maxLoaf: Math.round(Math.max(0, ...g.loaf)), maxLong: Math.round(Math.max(0, ...g.long)), track: +(g.track || 0).toFixed(2), neverClear: never, bottomCovered: g.bottomCovered || [] };
  });
}

async function open(ctx, base, p) {
  const page = await ctx.newPage();
  const errors = [];
  page.on('pageerror', e => errors.push(e.message));
  await page.goto(base + p.path);
  if (p.consent) {
    // zds sets __Host- Secure cookies, which Chromium drops over plain http, so
    // the sign-in response's cookie is sent as a request header instead.
    await page.goto(base + p.path + '&step=password');
    await page.locator('#password').fill(PASSWORD);
    const [resp] = await Promise.all([page.waitForResponse(r => r.request().method() === 'POST'), page.locator('button.primary', { hasText: /sign in/i }).first().click()]);
    const set = (await resp.allHeaders())['set-cookie'] || '';
    const m = set.match(/(__Host-zds-signin)=([^;]+)/);
    if (!m) throw new Error(`sign-in did not set a cookie (status ${resp.status()})`);
    await page.context().setExtraHTTPHeaders({ cookie: `${m[1]}=${m[2]}` });
    await page.goto(base + p.path);
    await page.locator('main.card.consent').waitFor({ timeout: 10000 }).catch(async () => {
      throw new Error(`consent page not reached; at ${page.url()}: ${(await page.locator('main').first().innerText().catch(() => '')).replace(/\s+/g, ' ').slice(0, 300)}`);
    });
  }
  await page.waitForTimeout(3500);
  return { page, errors };
}

async function checkGardenNavigation(page, base) {
  const live = page.locator('html.garden-scene #garden-scene');
  await live.waitFor();
  const before = await live.evaluate(canvas => canvas.height);
  const { width, height } = page.viewportSize();
  await page.setViewportSize({ width: width + 24, height: height + 48 });
  await page.locator(`#garden-scene:not([height="${before}"])`).waitFor();

  await page.context().addInitScript(() => {
    window.__gatePoster = false;
    new MutationObserver(() => {
      if (document.querySelector('#garden-poster:not(.g-gone)')) window.__gatePoster = true;
    }).observe(document, { childList: true, subtree: true });
  });
  async function follow(link, url) {
    await Promise.all([page.waitForURL(url), link.click()]);
    await live.waitFor();
    return page.evaluate(() => ({
      state: JSON.parse(sessionStorage.getItem('zds.garden')),
      size: innerWidth + 'x' + document.querySelector('#garden-scene').offsetHeight,
      poster: window.__gatePoster,
    }));
  }
  const account = await follow(page.locator('a.account-link'), base + '/account');
  const home = await follow(page.getByRole('link', { name: 'server home' }), base + '/');
  const fails = [];
  for (const [route, { state, size, poster }] of [['account', account], ['home', home]]) {
    if (state?.size !== size) fails.push(`garden navigation to ${route} saved the wrong viewport size`);
    if (!poster) fails.push(`garden navigation to ${route} missed the handoff poster`);
  }
  if (!account.state || !home.state || home.state.t <= account.state.t) fails.push('garden clock reset on the home/account round trip');
  const moteTraits = state => state?.motes?.map(({ s, p, v }) => [s, p, v]);
  if (!account.state?.motes?.length || JSON.stringify(moteTraits(account.state)) !== JSON.stringify(moteTraits(home.state))) fails.push('garden motes reset on the home/account round trip');
  return fails;
}

function observeGardenDraws() {
  const gl = WebGL2RenderingContext.prototype;
  const programs = new WeakMap();
  const getUniformLocation = gl.getUniformLocation;
  gl.getUniformLocation = function (program, name) {
    const location = getUniformLocation.call(this, program, name);
    if (location && name === 'u_fox') programs.set(location, program);
    return location;
  };
  const uniform4f = gl.uniform4f;
  gl.uniform4f = function (location, x, y, z, w) {
    const program = programs.get(location);
    if (program) window.__gardenDraw = { gl: this, program };
    return uniform4f.call(this, location, x, y, z, w);
  };
  let sampleFrame;
  window.__sampleGarden = () => new Promise((resolve, reject) => {
    const timeout = setTimeout(() => {
      sampleFrame = undefined;
      reject(new Error('garden did not draw a sample frame'));
    }, 2000);
    sampleFrame = image => { clearTimeout(timeout); resolve(image); };
  });
  const capture = document.createElement('canvas');
  capture.width = 72;
  capture.height = 45;
  const ctx = capture.getContext('2d', { willReadFrequently: true });
  const drawArrays = gl.drawArrays;
  gl.drawArrays = function (...args) {
    drawArrays.apply(this, args);
    if (!sampleFrame || this !== window.__gardenDraw?.gl
        || this.getParameter(this.CURRENT_PROGRAM) !== window.__gardenDraw.program) return;
    ctx.drawImage(this.canvas, 0, 0, capture.width, capture.height);
    const rgba = ctx.getImageData(0, 0, capture.width, capture.height).data;
    const luminance = new Float32Array(rgba.length / 4);
    for (let i = 0; i < luminance.length; i++) {
      luminance[i] = rgba[4*i] * 0.2126 + rgba[4*i+1] * 0.7152 + rgba[4*i+2] * 0.0722;
    }
    const resolve = sampleFrame;
    sampleFrame = undefined;
    resolve(luminance);
  };

}

async function checkGardenLight(page, touch) {
  await page.waitForFunction(() => window.__gardenDraw);
  return page.evaluate(async touch => {
    const move = (x, y) => {
      const point = { pointerType: touch ? 'touch' : 'mouse', clientX: innerWidth * x, clientY: innerHeight * y };
      if (touch) dispatchEvent(new PointerEvent('pointerdown', point));
      dispatchEvent(new PointerEvent(touch ? 'pointerup' : 'pointermove', point));
    };
    const settle = () => new Promise(resolve => setTimeout(resolve, 1000));
    move(0.14, 0.18);
    await settle();
    const before = await window.__sampleGarden();
    move(0.86, 0.63);
    const early = await window.__sampleGarden();
    await settle();
    const after = await window.__sampleGarden();

    // Project the first rendered change onto the eventual change. Moving
    // wildlife contributes little to the scene-wide lighting signal.
    let energy = 0, progress = 0;
    for (let i = 0; i < before.length; i++) {
      const target = after[i] - before[i];
      energy += target * target;
      progress += (early[i] - before[i]) * target;
    }
    if (Math.sqrt(energy / before.length) < 4) return ['garden pointer movement did not change the rendered lighting'];
    if (progress / energy < 0.7) return [`garden lighting completed only ${Math.round(100 * progress / energy)}% of its response on the first frame`];
    return [];
  }, touch);
}

async function checkAccountFocus(page) {
  const fails = [];
  const scale = () => page.evaluate(() => visualViewport.scale);
  const before = await scale();
  for (const id of ['identifier', 'password']) {
    const field = page.locator('#' + id);
    const size = await field.evaluate(el => parseFloat(getComputedStyle(el).fontSize));
    if (size < 16) fails.push(`account #${id} uses ${size}px text on the phone`);
    await field.tap();
    const focused = await field.evaluate(el => el === document.activeElement);
    if (!focused || await scale() !== before) fails.push(`account #${id} changed viewport scale or failed to focus`);
  }
  return fails;
}

async function checkGardenFox(page) {
  return page.evaluate(async () => {
    const { gl, program } = window.__gardenDraw;
    const foxLoc = gl.getUniformLocation(program, 'u_fox');
    const poseLoc = gl.getUniformLocation(program, 'u_fox2');
    const scale = gl.getUniform(program, gl.getUniformLocation(program, 'u_dpr'));
    const [x, y] = gl.getUniform(program, foxLoc);
    dispatchEvent(new PointerEvent('pointermove', { pointerType: 'mouse', clientX: x / scale, clientY: y / scale }));
    const started = await new Promise(requestAnimationFrame);
    let phase, moved = 0, stepped = false;
    for (let now = started; now - started < 1100; now = await new Promise(requestAnimationFrame)) {
      if (now - started < 650) continue;
      const [fx, fy] = gl.getUniform(program, foxLoc);
      const [gait, , , stride] = gl.getUniform(program, poseLoc);
      moved = Math.max(moved, Math.hypot(fx - x, fy - y) / scale);
      phase ??= gait;
      stepped ||= gait !== phase || stride >= 0.02;
    }
    const fails = [];
    if (phase === undefined || moved > 1) fails.push('garden fox did not stop near the pointer');
    else if (stepped) fails.push('garden fox kept stepping after it had stopped near the pointer');
    return fails;
  });
}

const launchArgs = ['--enable-gpu-rasterization', '--ignore-gpu-blocklist', ...(process.platform === 'darwin' ? ['--use-angle=metal'] : [])];
// The installed Chrome is what people run; the bundled Chromium (131 with
// Playwright 1.49) drops frames scrolling a garden page at desktop size where
// Chrome does not, so it is only the fallback. UI_GATE_CHANNEL picks one.
const channel = process.env.UI_GATE_CHANNEL ?? 'chrome';
const browser = await chromium.launch({ args: launchArgs, ...(channel && channel !== 'chromium' ? { channel } : {}) })
  .catch(() => chromium.launch({ args: launchArgs }));
console.log(`browser: ${browser.version()}`);
const results = [];
let failed = false;
try {
  for (const skin of skins) {
    const zds = await bootZds(skin);
    try {
      for (const p of PAGES) for (const vp of VIEWPORTS) {
        const id = `${skin}-${p.name}-${vp.name}`;
        const gardenMotion = skin === 'garden' && p.name === 'home';
        // pass 1: measure, no recording (recording skews frame timing)
        const ctx = await browser.newContext({ ...vp.ctx });
        if (gardenMotion) await ctx.addInitScript(observeGardenDraws);
        const { page, errors } = await open(ctx, zds.base, p);
        const pagePath = new URL(page.url()).pathname;
        const statics = await page.evaluate(pageChecks, { CARD_SEL, CONTRAST });
        const m = await scrollPass(page, true);
        const behavior = [];
        if (skin === 'garden' && p.name === 'home') {
          behavior.push(...await checkGardenLight(page, vp.name === 'phone'));
          if (vp.name === 'desktop') behavior.push(...await checkGardenFox(page));
          behavior.push(...await checkGardenNavigation(page, zds.base));
        }
        if (p.name === 'account' && vp.name === 'phone') behavior.push(...await checkAccountFocus(page));
        await ctx.close();
        // pass 2: video and screenshots
        const vdir = join(out, '.video-' + id);
        const vsize = vp.name === 'phone' ? { width: 390, height: 844 } : { width: 1440, height: 900 };
        const ctx2 = await browser.newContext({ ...vp.ctx, recordVideo: { dir: vdir, size: vsize } });
        const { page: page2 } = await open(ctx2, zds.base, p);
        await scrollPass(page2, false);
        for (const [where, f] of [['top', 0], ['middle', 0.5], ['bottom', 1]]) {
          await page2.evaluate(f => scrollTo(0, (document.documentElement.scrollHeight - innerHeight) * f), f);
          await page2.waitForTimeout(400);
          await page2.screenshot({ path: join(out, `${id}-${where}.png`) });
        }
        const video = page2.video();
        await ctx2.close();
        if (video) { renameSync(await video.path(), join(out, `${id}.webm`)); rmSync(vdir, { recursive: true, force: true }); }

        // Frame timing on a shared desktop is noisy, so a miss is measured twice
        // more and judged on the median of three; a real regression misses all three.
        const long = r => Math.max(r.maxLong, r.maxLoaf);
        const frameMiss = r => r.p95 > P95_MS[vp.name] || long(r) > LONG_TASK_MS;
        if (frameMiss(m)) {
          const runs = [m];
          for (let k = 0; k < 2; k++) { const c = await browser.newContext({ ...vp.ctx }); const { page: pr } = await open(c, zds.base, p); runs.push(await scrollPass(pr, false)); await c.close(); }
          const med = xs => xs.sort((a, b) => a - b)[1];
          m.p95Runs = runs.map(r => r.p95); m.longRuns = runs.map(long);
          m.p95 = med(runs.map(r => r.p95)); m.maxLong = med(runs.map(long)); m.maxLoaf = 0;
        }
        const fails = [...statics.fails, ...behavior];
        if (m.p95 > P95_MS[vp.name]) fails.push(`p95 ${m.p95} ms > ${P95_MS[vp.name]} ms (runs ${m.p95Runs})`);
        if (long(m) > LONG_TASK_MS) fails.push(`long frame/task ${long(m)} ms > ${LONG_TASK_MS} ms (runs ${m.longRuns})`);
        if (m.track > TRACK_PX) fails.push(`cards off scroll by ${m.track}px`);
        for (const k of m.neverClear) fails.push(`never clear of fixed toolbar: ${k}`);
        for (const k of m.bottomCovered) fails.push(`covered at page bottom: ${k}`);
        for (const e of errors) fails.push(`page error: ${e}`);
        const row = { skin, page: p.name, viewport: vp.name, path: pagePath, ...m, textChecked: statics.textChecked, minContrast: statics.minContrast, fails };
        results.push(row);
        if (fails.length) failed = true;
        console.log(`${fails.length ? 'FAIL' : 'ok  '} ${id}  p50 ${m.p50}  p95 ${m.p95}  long ${Math.max(m.maxLong, m.maxLoaf)}  track ${m.track}  contrast ${statics.minContrast}${fails.length ? '\n       ' + fails.join('\n       ') : ''}`);
      }
    } finally { zds.stop(); }
  }
} finally {
  await browser.close();
  stub.close();
}
writeFileSync(join(out, 'summary.json'), JSON.stringify({ version, thresholds: { P95_MS, LONG_TASK_MS, TRACK_PX, CONTRAST }, results }, null, 1));
console.table(results.map(r => ({ skin: r.skin, page: r.page, vp: r.viewport, p50: r.p50, p95: r.p95, long: Math.max(r.maxLong, r.maxLoaf), track: r.track, contrast: r.minContrast, fails: r.fails.length })));
console.log(failed ? `ui gate FAILED (${results.filter(r => r.fails.length).length} of ${results.length}); see ${out}` : `ui gate passed; ${out}`);
process.exit(failed ? 1 : 0);