pcbjam/tests/kicad/eeschema-crosshair.spec.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

240 lines
11 KiB
TypeScript

import type { Page } from '@playwright/test';
import { test, expect } from './fixtures';
import { findByTooltip, waitForCanvasStable, waitForEditorReady, shotPath } from '../e2e/utils/element-tracker';
/**
* Eeschema crosshair-mode toolbar button (pcbjam #24)
*
* The left toolbar has a single "Crosshair modes" group button that should switch the
* on-canvas cursor between small / full-window / 45-degree crosshairs. In the WASM/DOM port
* the three modes are bundled into one ACTION_GROUP whose only directly-clickable action is
* the default (small crosshairs) — already the active mode — and the other two live behind a
* long-press palette flyout the DOM toolbar can't show. So clicking the button does nothing.
*
* The fix (kicad/common/tool/action_toolbar.cpp, ACTION_TOOLBAR::onToolEvent, #ifdef
* __EMSCRIPTEN__) makes a click on a grouped button advance to the next action in the group,
* so a click cycles small -> full-window -> 45-degree -> small.
*
* This test fails before the fix (the button's tooltip never advances past "Small
* crosshairs" and the canvas never changes) and passes after it.
*/
const CROSSHAIR_MATCH = 'rosshair'; // substring shared by all three crosshair tooltips
type DiffRegion = { x: number; y: number; width: number; height: number };
type ScreenshotDifference = {
actualWidth: number;
actualHeight: number;
diffPixels: number;
diffRatio: number;
meanChannelDiff: number;
};
// Pixel-diff two PNG screenshots over a crop region, decoding in-page (mirrors eeschema.spec.ts).
async function compareScreenshots(
page: Page,
beforePng: Buffer,
afterPng: Buffer,
region: DiffRegion
): Promise<ScreenshotDifference> {
return page.evaluate(async ({ beforeBase64, afterBase64, 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 [before, after] = await Promise.all([
loadImage(beforeBase64),
loadImage(afterBase64),
]);
if (before.width !== after.width || before.height !== after.height) {
return {
actualWidth: after.width,
actualHeight: after.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(before, crop.x, crop.y, crop.width, crop.height, 0, 0, crop.width, crop.height);
const beforeData = context.getImageData(0, 0, canvas.width, canvas.height).data;
context.clearRect(0, 0, canvas.width, canvas.height);
context.drawImage(after, crop.x, crop.y, crop.width, crop.height, 0, 0, crop.width, crop.height);
const afterData = context.getImageData(0, 0, canvas.width, canvas.height).data;
let diffPixels = 0;
let totalChannelDiff = 0;
for (let i = 0; i < beforeData.length; i += 4) {
const dr = Math.abs(beforeData[i] - afterData[i]);
const dg = Math.abs(beforeData[i + 1] - afterData[i + 1]);
const db = Math.abs(beforeData[i + 2] - afterData[i + 2]);
const da = Math.abs(beforeData[i + 3] - afterData[i + 3]);
const maxDiff = Math.max(dr, dg, db, da);
totalChannelDiff += dr + dg + db + da;
if (maxDiff > 16) {
diffPixels += 1;
}
}
return {
actualWidth: after.width,
actualHeight: after.height,
diffPixels,
diffRatio: diffPixels / (canvas.width * canvas.height),
meanChannelDiff: totalChannelDiff / beforeData.length,
};
}, {
beforeBase64: beforePng.toString('base64'),
afterBase64: afterPng.toString('base64'),
crop: region,
});
}
// Hide the native browser cursor so it can't pollute canvas screenshots.
async function hideCursor(page: Page): Promise<void> {
await page.evaluate(() => {
document.documentElement.style.cursor = 'none';
document.body.style.cursor = 'none';
});
}
// Bounding box of the visible GL (schematic) canvas.
async function glCanvasBox(page: Page): Promise<{ x: number; y: number; width: number; height: number; sel: string }> {
const glCanvasId = await page.evaluate(() => {
const glCanvas =
Array.from(document.querySelectorAll('[id^="glcanvas-"]'))
.map((canvas) => canvas as HTMLCanvasElement)
.find((canvas) => {
const rect = canvas.getBoundingClientRect();
const style = window.getComputedStyle(canvas);
return style.display !== 'none' && rect.width > 0 && rect.height > 0;
}) ??
document.querySelector('[id^="glcanvas-"]') as HTMLCanvasElement | null;
return glCanvas?.id ?? null;
});
expect(glCanvasId, 'a visible GL canvas should exist').not.toBeNull();
const box = await page.locator(`#${glCanvasId}`).boundingBox();
expect(box, 'GL canvas bounding box should be available').not.toBeNull();
if (!box) {
throw new Error('GL canvas bounding box unavailable');
}
return { ...box, sel: `#${glCanvasId}` };
}
test.describe('Eeschema crosshair modes', () => {
test.beforeEach(async ({ page }) => {
await page.goto('/kicad/eeschema.html');
});
// Clicking the crosshair group button cycles the on-canvas cursor small -> full -> 45 ->
// small. This is upstream KiCad's own ACTION_TOOLBAR::onToolEvent group-cycle behavior
// (our fork's copy was behind upstream and missing it; now restored). The long-press
// palette flyout, which renders thanks to the wxPopupTransientWindow DOM fix, is covered
// generically by tests/e2e/popup.spec.ts. Each click advances the group's selected action;
// the tooltip + the rendered crosshair both change.
test('crosshair toolbar button cycles small -> full -> 45 on click', async ({ page, testLogger }) => {
await waitForEditorReady(page);
await hideCursor(page);
await page.waitForFunction((match: string) => {
const registry = window.wxElementRegistry;
return registry?.findAllRendered?.({ elementType: 'tool' })
.some((tool) => tool.tooltip?.includes(match)) ?? false;
}, CROSSHAIR_MATCH, { timeout: 15000 });
const crosshairTool = await findByTooltip(page, CROSSHAIR_MATCH, { elementType: 'tool' });
expect(crosshairTool, 'crosshair-modes toolbar button should exist').not.toBeNull();
expect(crosshairTool?.enabled, 'crosshair button should be enabled').toBe(true);
expect(crosshairTool?.tooltip ?? '', 'starts on Small crosshairs').toContain('Small crosshairs');
// Draw Wires guarantees the GAL crosshair cursor is shown; we only MOVE over the canvas
// (never click it) so no wire is drawn.
const drawWires = await findByTooltip(page, 'Draw Wires', { elementType: 'tool' });
expect(drawWires, 'Draw Wires tool should exist').not.toBeNull();
await page.mouse.click(drawWires!.centerX, drawWires!.centerY);
await expect.poll(async () =>
((await findByTooltip(page, 'Draw Wires', { elementType: 'tool' }))?.label ?? '').includes('[checked]'),
{ timeout: 5000, intervals: [200] },
).toBe(true);
const box = await glCanvasBox(page);
const probe = { x: Math.round(box.x + box.width * 0.5), y: Math.round(box.y + box.height * 0.5) };
const diffRegion: DiffRegion = {
x: Math.round(box.x), y: Math.round(box.y),
width: Math.round(box.width), height: Math.round(box.height),
};
const btn = { x: crosshairTool!.centerX, y: crosshairTool!.centerY };
const tooltipNow = async () =>
(await findByTooltip(page, CROSSHAIR_MATCH, { elementType: 'tool' }))?.tooltip ?? '';
// A quick click (no long hold) cycles; then re-settle the cursor on the canvas so the
// crosshair redraws at the probe point in the new mode.
// Quick click (no long hold) cycles the mode; then re-settle the cursor on the
// canvas so the crosshair redraws at the probe point in the new mode. The caller
// confirms the new mode via the tooltip poll, then waits for the canvas to settle
// (waitForCanvasStable) before capturing — deterministic, no fixed sleeps.
const clickAndSettle = async () => {
await page.mouse.click(btn.x, btn.y);
await page.mouse.move(probe.x + 1, probe.y + 1);
await page.mouse.move(probe.x, probe.y);
};
await page.mouse.move(probe.x, probe.y);
await waitForCanvasStable(page, box.sel);
const shotSmall = await page.screenshot({ path: shotPath(page, 'eeschema-crosshair-00-small.png'), scale: 'css' });
// click 1 -> full-window
await clickAndSettle();
await expect.poll(tooltipNow, {
message: 'one click should advance to Full-Window Crosshairs', timeout: 6000,
}).toContain('Full-Window Crosshairs');
await waitForCanvasStable(page, box.sel);
const shotFull = await page.screenshot({ path: shotPath(page, 'eeschema-crosshair-01-full.png'), scale: 'css' });
expect((await compareScreenshots(page, shotSmall, shotFull, diffRegion)).diffPixels,
'full-window crosshair should visibly differ from the small crosshair').toBeGreaterThan(200);
// click 2 -> 45-degree
await clickAndSettle();
await expect.poll(tooltipNow, {
message: 'second click should advance to 45 Degree Crosshairs', timeout: 6000,
}).toContain('45 Degree Crosshairs');
await waitForCanvasStable(page, box.sel);
const shot45 = await page.screenshot({ path: shotPath(page, 'eeschema-crosshair-02-45.png'), scale: 'css' });
expect((await compareScreenshots(page, shotFull, shot45, diffRegion)).diffPixels,
'45-degree crosshair should visibly differ from the full-window crosshair').toBeGreaterThan(200);
// click 3 -> cycles back to small
await clickAndSettle();
await expect.poll(tooltipNow, {
message: 'third click should cycle back to Small crosshairs', timeout: 6000,
}).toContain('Small crosshairs');
await waitForCanvasStable(page, box.sel);
await page.screenshot({ path: shotPath(page, 'eeschema-crosshair-03-small-again.png'), scale: 'css' });
const realErrors = testLogger.errors.filter((error: string) => !error.includes('favicon'));
expect(realErrors).toEqual([]);
});
});