pcbjam/tests/kicad/utils/screenshot-compare.ts
Viktor Vaczi 63ed1f3c1f e2e/CI: dual-engine suites, per-engine screenshots, SwiftShader retired, prod web suite, CI-coverage gate
Squash of experiment/ff-big-modules vs main.

Big-module routing removed: native-EH shrank kicad_editor below
SpiderMonkey's x86-64 code budget (runs 29355049705/29356152413 green on
stock Firefox), so BIG_MODULE_SPECS routing and the baseline-only-JIT
crutch are gone — kicad-firefox and kicad-chromium both run the full
suite, with the module compiled the way real users' browsers compile it.

Per-engine screenshots end to end: stableShot/shotPath write
test-results/<engine>/<name>.png; baselines move to
baseline-screenshots/{chromium,firefox}/ and the whole tools/screenshots
pipeline (compare/promote/manifest/spec-map/changelog/Discord) keys on
<engine>/<name>. Previously Firefox and Chromium renders of one spec
overwrote each other and Firefox renders were never actually gated.
Seeded from CI run 29421380806 (92 new firefox baselines, +24 chromium
web-suite shots); manifest generated from the baseline tree.

One merged playwright.config.ts (kicad/asyncify/coroutine/perf as
projects); ~25 dead npm scripts dropped. The web suite is gated in CI for
the first time ever (4 rotted specs fixed, 5 broken lib-bridge specs
triaged as fixme in docs/features/web-e2e-rot/); cheap lint step after
npm ci; last 26 blind-sleep violations fixed.

SwiftShader retired: CI Chromium renders WebGL on ANGLE → Mesa llvmpipe
(--use-gl=angle --use-angle=gl --ignore-gpu-blocklist; the blocklist flag
is mandatory — llvmpipe is blocklisted and WebGL is silently unavailable
without it) in BOTH configs. Under WORKERS=4 congestion SwiftShader
transiently failed the first post-board-load draw and the recovery
cascade ended in a silent permanent Cairo fallback — that engine flip was
the "~1.2% changedRatio both directions" occ-export baseline flake.
Validated 160/160 across two 80-repeat rigs; full analysis in
docs/features/wx-parity-bugs/occ-export-context-eviction.md. Chromium
baselines shift slightly on llvmpipe — promote once from the first green
run. Deflakes the new coverage exposed: presence baselines settle before
capture; presence fixtures declare current file formats; perf gets its
own outputDir so CI evidence survives; occ-export settles the board paint
before the export dialog; menu-item waits (waitForRenderedByLabel before
clickMenuItem) in 4 specs + the TESTING.md rule.

Web suite runs the PROD build, in parallel: webServer becomes backend
`start` + the standalone's e2e:preview (build-preview.mjs: link-wasm →
stash the public/wasm symlink aside during vite build, build-demo.mjs's
move — then vite preview as the persistent server). The wasm middleware
serves /wasm/* in preview and emits COOP/COEP/CORP itself (a pthread
worker script's own response must carry COEP or Chrome kills it with
ERR_BLOCKED_BY_RESPONSE). VITE_* flags bake at build time;
VITE_ALLOW_USER_OVERRIDE joins turbo globalEnv. fullyParallel + default
workers: 5.2m → 1.4m. Determinism fixes the parallel run exposed:
shared-page specs become serial groups; locks.spec grabs alice's exact
item via the new kicadCollabTestSelectByUuid hook (cross-tab "first
footprint" order is not a ysync invariant); quit specs poll page.url()
(quit supersedes its own navigation — NS_BINDING_ABORTED on Firefox).
Suite: 51 passed / 12 skipped / 0 failed in 1.6m.

CI-coverage gate (lint:ci-coverage): every tests/**/*.spec.ts must be
reachable from the npm scripts the workflows invoke — scraped from
.github/workflows/, resolved through package.json, coverage asked from
playwright --list itself. Rules: uncovered-spec + orphan-project (with a
documented LOCAL_ONLY_PROJECTS allowlist). Gating next to
lint:determinism; 138 spec files / 13 projects accounted for.

Product fixes kept from the investigations (reachable on real GPUs too):
wx 7799fd1be5 — paint flags clear before dispatch + Invalidate always
propagates; kicad 3dcfea5e45 — SwiftShader pass-boundary flush +
per-instance font texture + first-frame GL-error drain (GAL recovery
recovers instead of falling back to Cairo) + the user-facing eeschema
switch navigates again under __EMSCRIPTEN__ (project-sync's
FaceRegistered gate had rerouted it into the hidden sync player; caught
by the newly-gated web suite).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018eUxiPApHgGiu9NFyQfhAq
2026-07-17 12:21:54 +02:00

193 lines
7.2 KiB
TypeScript

import * as fs from 'fs';
import * as path from 'path';
import { expect, type Page } from '@playwright/test';
import { clickByLabel, shotPath } from '../../e2e/utils/element-tracker';
/**
* Shared screenshot-comparison and app-startup helpers for the KiCad specs
* (extracted from pcbnew.spec.ts so dark-mode.spec.ts and future specs don't
* carry their own copies of the pixel-diff logic and thresholds).
*/
export type ReferenceRegion = {
name: string;
x: number;
y: number;
width: number;
height: number;
maxDiffRatio: number;
maxMeanChannelDiff: number;
};
export type ReferenceComparison = {
name: string;
actualWidth: number;
actualHeight: number;
referenceWidth: number;
referenceHeight: number;
diffPixels: number;
diffRatio: number;
meanChannelDiff: number;
};
/** Post-wizard pcbnew baseline screenshot (committed) and its toolbar region. */
export const PCBNEW_REFERENCE = path.resolve(__dirname, '../../wizard-04-finish-headless.png');
export const PCBNEW_HEADER_REGION: ReferenceRegion = {
// maxDiffRatio counts every pixel differing by >16 in any channel, so it is dominated
// by sub-pixel/anti-aliasing differences along text and icon edges. Those vary with the
// render environment (e.g. local Firefox/macOS vs the headless baseline), giving ~0.15
// even when the UI is pixel-correct in content. The real dark-theme guard is
// maxMeanChannelDiff (a colour-magnitude check): a dark-variant icon/widget leak shifts
// colours and pushes it well past 12, whereas pure AA noise stays low (~8.5 observed).
// So keep maxMeanChannelDiff tight and give maxDiffRatio cross-environment headroom.
name: 'header', x: 0, y: 0, width: 1280, height: 90, maxDiffRatio: 0.2, maxMeanChannelDiff: 12,
};
/**
* Crop `region` out of both images and pixel-diff them inside the page (the
* Node side has no canvas). Returns Infinity diffs on size mismatch.
*/
export async function compareToReference(
page: Page,
actualPng: Buffer,
referencePath: string,
region: ReferenceRegion
): Promise<ReferenceComparison> {
const referencePng = fs.readFileSync(referencePath);
return page.evaluate(async ({ actualBase64, referenceBase64, crop }) => {
const loadImage = async (base64: string): Promise<HTMLImageElement> => {
const image = new Image();
image.src = `data:image/png;base64,${base64}`;
await image.decode();
return image;
};
const [actual, reference] = await Promise.all([
loadImage(actualBase64),
loadImage(referenceBase64),
]);
if (actual.width !== reference.width || actual.height !== reference.height) {
return {
name: crop.name,
actualWidth: actual.width,
actualHeight: actual.height,
referenceWidth: reference.width,
referenceHeight: reference.height,
diffPixels: Number.POSITIVE_INFINITY,
diffRatio: Number.POSITIVE_INFINITY,
meanChannelDiff: Number.POSITIVE_INFINITY,
};
}
const canvas = document.createElement('canvas');
canvas.width = crop.width;
canvas.height = crop.height;
const context = canvas.getContext('2d', { willReadFrequently: true });
if (!context) {
throw new Error('2D canvas context unavailable for screenshot comparison');
}
context.drawImage(actual, crop.x, crop.y, crop.width, crop.height, 0, 0, crop.width, crop.height);
const actualData = context.getImageData(0, 0, canvas.width, canvas.height).data;
context.clearRect(0, 0, canvas.width, canvas.height);
context.drawImage(reference, crop.x, crop.y, crop.width, crop.height, 0, 0, crop.width, crop.height);
const referenceData = context.getImageData(0, 0, canvas.width, canvas.height).data;
let diffPixels = 0;
let totalChannelDiff = 0;
for (let i = 0; i < actualData.length; i += 4) {
const dr = Math.abs(actualData[i] - referenceData[i]);
const dg = Math.abs(actualData[i + 1] - referenceData[i + 1]);
const db = Math.abs(actualData[i + 2] - referenceData[i + 2]);
const da = Math.abs(actualData[i + 3] - referenceData[i + 3]);
const maxDiff = Math.max(dr, dg, db, da);
totalChannelDiff += dr + dg + db + da;
if (maxDiff > 16) {
diffPixels += 1;
}
}
return {
name: crop.name,
actualWidth: actual.width,
actualHeight: actual.height,
referenceWidth: reference.width,
referenceHeight: reference.height,
diffPixels,
diffRatio: diffPixels / (canvas.width * canvas.height),
meanChannelDiff: totalChannelDiff / actualData.length,
};
}, {
actualBase64: actualPng.toString('base64'),
referenceBase64: referencePng.toString('base64'),
crop: region,
});
}
/**
* Click through the first-run setup wizard until Finish (or until no wizard
* page is showing). With `screenshots: true`, saves the per-step
* test-results/wizard-NN[-finish].png series pcbnew.spec.ts captures.
*/
export async function completeWizard(page: Page, opts: { screenshots?: boolean } = {}): Promise<void> {
await expect(page.locator('#canvas')).toBeVisible({ timeout: 90000 });
await page.waitForFunction(() => !!window.wxElementRegistry, null, { timeout: 90000 });
// The registry OBJECT exists as soon as wx.js initializes — long before the
// app wasm boots (slow on CI: ~190M module on baseline-JIT + software GL).
// Wait for actual UI entries (the wizard is the first window) before the
// bounded click loop below, which otherwise starts too early and gives up.
await page.waitForFunction(() => {
const registry = window.wxElementRegistry;
return !!registry && registry.findAll({}).length > 0;
}, null, { timeout: 150000 });
await page.waitForTimeout(2000);
if (opts.screenshots) {
await page.screenshot({ path: shotPath(page, 'wizard-00-initial.png'), scale: 'css' });
}
for (let i = 1; i <= 10; i++) {
const clicked = await clickByLabel(page, 'Next >');
if (!clicked) {
const finished = await clickByLabel(page, 'Finish');
if (finished && opts.screenshots) {
await page.waitForTimeout(500);
await page.screenshot({
path: shotPath(page, `wizard-${String(i).padStart(2, '0')}-finish.png`),
scale: 'css'
});
}
break;
}
await page.waitForTimeout(500);
if (opts.screenshots) {
await page.screenshot({
path: shotPath(page, `wizard-${String(i).padStart(2, '0')}.png`),
scale: 'css'
});
}
}
await page.waitForTimeout(2000);
}
/** Hide the mouse cursor so screenshots are stable. */
export async function hideCursor(page: Page): Promise<void> {
await page.evaluate(() => {
document.documentElement.style.cursor = 'none';
document.body.style.cursor = 'none';
});
}