From 3ef461a0f66b80cd4bd47e50b2fd9f94a2b1ec5a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gerg=C5=91=20T=C3=B6rcsv=C3=A1ri?= Date: Wed, 3 Jun 2026 08:52:34 +0200 Subject: [PATCH] test(e2e): web-app tool open-path suite + pl_editor open/wizard-skip Add an e2e suite that drives the real React web app (not the standalone harness): tests/playwright-web.config.ts + tests/web/tools-open.spec.ts navigate /p/demo// for all five tools and assert each boots, opens its demo file (title drops "untitled"), shows no first-run wizard, and emits no WASM abort or URL-regex modal. global-setup-web.ts re-seeds the demo project through the API if missing, so the suite is self-sufficient against a running dev stack. Wired as `npm run test:web`. Also at the harness level: - pl_editor-load.spec.ts: prove the pl_editor kicadOpenFile embind hook opens a .kicad_wks (mirrors eeschema-load.spec.ts). - seed KiCad config in pl_editor.html / symbol_editor.html (matching eeschema.html and the web app's boot.ts) so the harness boots wizard-free; repurpose pl_editor.spec.ts's stale "wizard completes" test into a wizard-skip regression. Co-Authored-By: Claude Opus 4.8 (1M context) --- tests/apps/kicad/pl_editor.html | 26 ++++++- tests/apps/kicad/symbol_editor.html | 26 ++++++- tests/kicad/pl_editor-load.spec.ts | 105 ++++++++++++++++++++++++++++ tests/kicad/pl_editor.spec.ts | 14 ++-- tests/package.json | 2 + tests/playwright-web.config.ts | 64 +++++++++++++++++ tests/web/global-setup-web.ts | 74 ++++++++++++++++++++ tests/web/tools-open.spec.ts | 81 +++++++++++++++++++++ 8 files changed, 385 insertions(+), 7 deletions(-) create mode 100644 tests/kicad/pl_editor-load.spec.ts create mode 100644 tests/playwright-web.config.ts create mode 100644 tests/web/global-setup-web.ts create mode 100644 tests/web/tools-open.spec.ts diff --git a/tests/apps/kicad/pl_editor.html b/tests/apps/kicad/pl_editor.html index 516ecca..8bfc718 100644 --- a/tests/apps/kicad/pl_editor.html +++ b/tests/apps/kicad/pl_editor.html @@ -140,10 +140,34 @@ console.log('[KICAD] cwd set to ' + home); }; + // single_top.cpp runs STARTWIZARD on launch: a modal first-run "Setup" + // wizard shown whenever the settings dir lacks a kicad_common.json or valid + // global library tables. In this ephemeral MEMFS that is EVERY load, and the + // wizard's modal event loop crashes Asyncify. Seed a minimal default config + // before main() so every provider reports NeedsUserInput()==false and the + // wizard never opens — same as eeschema.html and the web app's boot.ts. + var seedKicadConfig = function() { + var cfgDir = '/home/kicad/.config/kicad/kicad/9.99'; + FS.mkdirTree(cfgDir); + + var writeIfAbsent = function(path, contents) { + try { FS.stat(path); return; } catch (e) { /* absent — seed it */ } + FS.writeFile(path, contents); + console.log('[KICAD] Seeded ' + path); + }; + + writeIfAbsent(cfgDir + '/kicad_common.json', JSON.stringify({ + do_not_show_again: { update_check_prompt: true, data_collection_prompt: true } + }, null, 2)); + writeIfAbsent(cfgDir + '/sym-lib-table', '(sym_lib_table\n (version 7)\n)\n'); + writeIfAbsent(cfgDir + '/fp-lib-table', '(fp_lib_table\n (version 7)\n)\n'); + writeIfAbsent(cfgDir + '/design-block-lib-table', '(design_block_lib_table\n (version 7)\n)\n'); + }; + var Module = { thisProgram: '/usr/bin/pl_editor', // Fake absolute path for argv[0] - preRun: [createCanvas, writeResources, setupHomeDir], + preRun: [createCanvas, writeResources, setupHomeDir, seedKicadConfig], postRun: [], print: function(text) { diff --git a/tests/apps/kicad/symbol_editor.html b/tests/apps/kicad/symbol_editor.html index f18516c..37a1aa9 100644 --- a/tests/apps/kicad/symbol_editor.html +++ b/tests/apps/kicad/symbol_editor.html @@ -137,10 +137,34 @@ } }; + // single_top.cpp runs STARTWIZARD on launch: a modal first-run "Setup" + // wizard shown whenever the settings dir lacks a kicad_common.json or valid + // global library tables. In this ephemeral MEMFS that is EVERY load, and the + // wizard's modal event loop crashes Asyncify. Seed a minimal default config + // before main() so every provider reports NeedsUserInput()==false and the + // wizard never opens — same as eeschema.html and the web app's boot.ts. + var seedKicadConfig = function() { + var cfgDir = '/home/kicad/.config/kicad/kicad/9.99'; + FS.mkdirTree(cfgDir); + + var writeIfAbsent = function(path, contents) { + try { FS.stat(path); return; } catch (e) { /* absent — seed it */ } + FS.writeFile(path, contents); + console.log('[KICAD] Seeded ' + path); + }; + + writeIfAbsent(cfgDir + '/kicad_common.json', JSON.stringify({ + do_not_show_again: { update_check_prompt: true, data_collection_prompt: true } + }, null, 2)); + writeIfAbsent(cfgDir + '/sym-lib-table', '(sym_lib_table\n (version 7)\n)\n'); + writeIfAbsent(cfgDir + '/fp-lib-table', '(fp_lib_table\n (version 7)\n)\n'); + writeIfAbsent(cfgDir + '/design-block-lib-table', '(design_block_lib_table\n (version 7)\n)\n'); + }; + var Module = { thisProgram: '/usr/bin/symbol_editor', // Fake absolute path for argv[0] (KiCad DEBUG check) - preRun: [createCanvas, writeResources], + preRun: [createCanvas, writeResources, seedKicadConfig], postRun: [], print: function(text) { diff --git a/tests/kicad/pl_editor-load.spec.ts b/tests/kicad/pl_editor-load.spec.ts new file mode 100644 index 0000000..dfcfb7a --- /dev/null +++ b/tests/kicad/pl_editor-load.spec.ts @@ -0,0 +1,105 @@ +import { test, expect } from './fixtures'; + +/** + * pl_editor (drawing-sheet editor) programmatic-open regression. + * + * Guards the web-app wiring added for pl_editor: + * 1. the generic kicadOpenFile() embind hook (wasm/bindings/pl_editor_embind.cpp) + * — PL_EDITOR_FRAME overrides OpenProjectFiles, so a .kicad_wks can be opened + * deterministically without UI automation, and + * 2. the seeded KiCad config that skips the first-run STARTWIZARD (the harness + * now seeds it in preRun, matching the web app's boot.ts) — without it the + * wizard's modal loop crashes Asyncify and no file can load. + * + * Strategy mirrors eeschema-load.spec.ts: write a minimal .kicad_wks into MEMFS, + * call Module.kicadOpenFile(), and poll the editor title. GREEN once it shows the + * file name; also asserts no setup wizard is visible and no WASM abort fired. + */ + +const SAMPLE_WKS = `(page_layout + (setup (textsize 1.5 1.5)(linewidth 0.15)(textlinewidth 0.15) + (left_margin 10)(right_margin 10)(top_margin 10)(bottom_margin 10)) + (rect (name border:Rect) (start 0 0 ltcorner) (end 0 0 rbcorner) (comment "page border")) + (rect (name titleblock:Rect) (start 110 34) (end 2 2) (comment "title block frame")) + (tbtext "KiCad WASM — Drawing Sheet Load Test" (name title) (pos 100 20) (font (size 2.5 2.5) (bold))) +) +`; + +type EmscriptenFS = { + mkdirTree(path: string): void; + writeFile(path: string, data: string): void; +}; +type KicadModule = { kicadOpenFile(path: string): unknown }; + +function hasAbort(testLogger: { consoleLogs: string[]; errors: string[] }): boolean { + return [...testLogger.consoleLogs, ...testLogger.errors].some((l) => l.includes('Aborted(')); +} + +test.describe('pl_editor drawing-sheet load', () => { + test('opens a .kicad_wks via kicadOpenFile, wizard-free', async ({ page, testLogger }) => { + await page.goto('/kicad/pl_editor.html'); + + // Editor must be fully up: canvas, registry, the embind open hook, and a + // top-level Frame (so kicadOpenFile's GetTopWindow() resolves to the editor). + await expect(page.locator('#canvas')).toBeVisible({ timeout: 90000 }); + await page.waitForFunction(() => !!window.wxElementRegistry, null, { timeout: 90000 }); + await page.waitForFunction( + () => + typeof (window as unknown as { Module?: KicadModule }).Module?.kicadOpenFile === + 'function', + null, + { timeout: 90000 } + ); + await page.waitForFunction( + () => + !!window.wxElementRegistry && + window.wxElementRegistry + .findAll({ visible: true }) + .some((e) => /Frame$/.test(e.typeName) || (e.name || '').endsWith('Frame')), + null, + { timeout: 90000 } + ); + + // The seed must have suppressed the first-run wizard: no wizard/dialog up. + const wizardVisible = await page.evaluate(() => { + const reg = window.wxElementRegistry; + if (!reg) return -1; + return reg + .findAll({ visible: true }) + .filter((e: { typeName: string }) => /^wxDialog|Wizard/.test(e.typeName)).length; + }); + expect(wizardVisible, 'no setup wizard/dialog should be visible (seed skipped it)').toBe(0); + + // Write a minimal drawing sheet into MEMFS and open it via the hook. + const openedPath = await page.evaluate((content) => { + const w = window as unknown as { FS: EmscriptenFS; Module: KicadModule }; + const dir = '/home/kicad/documents'; + try { + w.FS.mkdirTree(dir); + } catch { + /* already exists */ + } + const path = `${dir}/load-test.kicad_wks`; + w.FS.writeFile(path, content); + w.Module.kicadOpenFile(path); + return path; + }, SAMPLE_WKS); + expect(openedPath).toContain('load-test.kicad_wks'); + + // The title switches to the opened file once the load completes. + await expect + .poll(async () => page.title(), { + message: + 'Drawing sheet load did not complete (title never showed the file). ' + + 'kicadOpenFile / the pl_editor embind hook is likely missing or broken.', + timeout: 30000, + intervals: [500], + }) + .toMatch(/load-test/i); + + await page.waitForTimeout(1000); + await page.screenshot({ path: 'test-results/pl_editor-load-rendered.png', scale: 'device' }); + + expect(hasAbort(testLogger), 'no WASM abort during open').toBe(false); + }); +}); diff --git a/tests/kicad/pl_editor.spec.ts b/tests/kicad/pl_editor.spec.ts index 2d4f3c0..adc1092 100644 --- a/tests/kicad/pl_editor.spec.ts +++ b/tests/kicad/pl_editor.spec.ts @@ -70,10 +70,14 @@ test.describe('pl_editor WASM', () => { expect(canvasCount).toBeGreaterThan(0); }); - test('wizard completes and leaves the editor in a clean state', async ({ page, testLogger }) => { + test('first-run wizard is skipped by the seeded config (none appears)', async ({ page, testLogger }) => { + // The harness seeds a default KiCad config in preRun (like the web app's + // boot.ts), so STARTWIZARD::CheckAndRun() finds NeedsUserInput()==false and + // never opens the modal wizard. completeWizard() therefore finds nothing to + // click and the editor comes straight up. Assert no wizard/dialog is ever + // visible — the inverse of the old "click through the wizard" flow. await completeWizard(page); - // After the wizard, no wxDialog/wxWizard should still be visible. const blockingDialogs = await page.evaluate(() => { const registry = window.wxElementRegistry; if (!registry) return -1; @@ -82,10 +86,10 @@ test.describe('pl_editor WASM', () => { /^wxDialog|Wizard/.test(el.typeName)) .length; }); - expect(blockingDialogs, 'no blocking dialog/wizard visible after completeWizard()').toBe(0); - expect(hasAbort(testLogger), 'no WASM abort during wizard').toBe(false); + expect(blockingDialogs, 'no setup wizard/dialog should be visible (seed skipped it)').toBe(0); + expect(hasAbort(testLogger), 'no WASM abort during launch').toBe(false); - await page.screenshot({ path: 'test-results/pl_editor-02-post-wizard.png', scale: 'device' }); + await page.screenshot({ path: 'test-results/pl_editor-02-no-wizard.png', scale: 'device' }); }); test('File menu exposes Open... and Save As...', async ({ page, testLogger }) => { diff --git a/tests/package.json b/tests/package.json index 66780fb..4e253f7 100644 --- a/tests/package.json +++ b/tests/package.json @@ -9,6 +9,8 @@ "build-wasm": "cd apps && make -f Makefile.wasm", "serve": "npx serve apps -p 8080 -c ../serve.json", "setup:kicad": "./scripts/setup-kicad-wasm.sh", + "test:web": "npm run setup:kicad && playwright test --config=playwright-web.config.ts --project=firefox", + "test:web:headed": "npm run setup:kicad && playwright test --config=playwright-web.config.ts --project=chromium --headed", "test:kicad:firefox": "npm run setup:kicad && playwright test --config=playwright-kicad.config.ts --project=firefox", "test:kicad:chrome": "npm run setup:kicad && playwright test --config=playwright-kicad.config.ts --project=chromium --headed", "test:kicad": "npm run test:kicad:firefox", diff --git a/tests/playwright-web.config.ts b/tests/playwright-web.config.ts new file mode 100644 index 0000000..0e72895 --- /dev/null +++ b/tests/playwright-web.config.ts @@ -0,0 +1,64 @@ +import { defineConfig, devices } from '@playwright/test'; + +/** + * E2E config for the React WEB APP (apps/frontend at :3048 + apps/server :3050), + * as opposed to playwright-kicad.config.ts which drives the standalone tool + * harness HTMLs under tests/apps/kicad. + * + * These tests exercise the real web open paths: navigate to /p///, + * let WasmTool boot the tool in-document (boot.ts), drive the project into MEMFS + * and auto-open the file (open-flow.ts via Module.kicadOpenFile), and assert the + * editor loaded wizard-free. + * + * PREREQUISITE: the web stack must be running. From web/: + * pnpm db:up && pnpm db:migrate && pnpm dev + * (db:migrate seeds the "demo" project; global-setup-web.ts re-seeds it through + * the API if missing.) The webServer block below reuses an already-running stack + * and, if absent, best-effort starts `turbo dev` — but that still needs Postgres + * up (pnpm db:up) and migrated first. + * + * Firefox is the reliable headless target on ARM Mac (Chromium SwiftShader WebGL + * bug); use --project=chromium (system Chrome) for headed debugging. + */ + +const FRONTEND_URL = process.env.WEB_APP_URL ?? 'http://localhost:3048'; + +export default defineConfig({ + globalSetup: './web/global-setup-web.ts', + testDir: './web', + fullyParallel: false, + forbidOnly: !!process.env.CI, + retries: process.env.CI ? 1 : 0, + // KiCad WASM is process-global (one runtime per page) and each tool wasm is + // 40–200 MB; run serially to avoid loading several giant runtimes at once. + workers: 1, + reporter: 'html', + timeout: 180000, // tool wasm download + boot + open can take minutes + + use: { + baseURL: FRONTEND_URL, + trace: 'retain-on-failure', + screenshot: 'only-on-failure', + }, + + projects: [ + { + name: 'firefox', + use: { ...devices['Desktop Firefox'], viewport: { width: 1280, height: 720 } }, + }, + { + name: 'chromium', + use: { channel: 'chrome', viewport: { width: 1280, height: 720 } }, + }, + ], + + webServer: { + // Best-effort: reuse the dev stack if it's already up (the common case); + // otherwise start turbo dev. Postgres (pnpm db:up) + db:migrate must already + // have run — turbo dev does not provision the database. + command: 'pnpm --dir ../web dev', + url: FRONTEND_URL, + reuseExistingServer: true, + timeout: 120000, + }, +}); diff --git a/tests/web/global-setup-web.ts b/tests/web/global-setup-web.ts new file mode 100644 index 0000000..c973761 --- /dev/null +++ b/tests/web/global-setup-web.ts @@ -0,0 +1,74 @@ +import * as fs from 'fs'; +import * as path from 'path'; +import type { FullConfig } from '@playwright/test'; + +/** + * Global setup for the web-app e2e suite. + * + * The tests drive the real React app at :3048 and open files from the committed + * "demo" project. That project is normally created by `pnpm db:migrate` + * (seedDemoProject). This setup makes the suite self-sufficient: it waits for + * the API to be reachable and, if the demo project is missing, recreates it by + * uploading the committed seed-data files through the public API — the same + * bytes db:seed uses. Idempotent. + */ + +const API_BASE = process.env.VITE_API_BASE_URL ?? 'http://localhost:3050'; +const SEED_DIR = path.resolve(__dirname, '../../web/apps/server/seed-data'); +const DEMO_SLUG = 'demo'; +const DEMO_FILES = ['demo.kicad_sch', 'demo.kicad_pcb', 'demo.kicad_wks']; + +async function waitForApi(timeoutMs = 60000): Promise { + const deadline = Date.now() + timeoutMs; + let lastErr = ''; + while (Date.now() < deadline) { + try { + const r = await fetch(`${API_BASE}/health`); + if (r.ok) return; + lastErr = `HTTP ${r.status}`; + } catch (e) { + lastErr = (e as Error).message; + } + await new Promise((res) => setTimeout(res, 1000)); + } + throw new Error( + `API not reachable at ${API_BASE} (${lastErr}). Start the web stack first: ` + + `from web/ run \`pnpm db:up && pnpm db:migrate && pnpm dev\`.` + ); +} + +async function ensureDemoProject(): Promise { + const existing = await fetch(`${API_BASE}/api/projects/${DEMO_SLUG}`); + if (existing.ok) { + const body = (await existing.json()) as { files: { path: string }[] }; + const have = new Set(body.files.map((f) => f.path)); + if (DEMO_FILES.every((f) => have.has(f))) return; + } else { + // Create the project (ignore 409 if a race created it). + const created = await fetch(`${API_BASE}/api/projects`, { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ name: 'Demo Project', slug: DEMO_SLUG }), + }); + if (!created.ok && created.status !== 409) { + throw new Error(`failed to create demo project: HTTP ${created.status}`); + } + } + + // Upload the committed seed bytes (multipart field-name = project-relative path). + const form = new FormData(); + for (const name of DEMO_FILES) { + const buf = fs.readFileSync(path.join(SEED_DIR, name)); + form.append(name, new Blob([buf]), name); + } + const up = await fetch(`${API_BASE}/api/projects/${DEMO_SLUG}/files`, { + method: 'POST', + body: form, + }); + if (!up.ok) throw new Error(`failed to seed demo files: HTTP ${up.status}`); +} + +export default async function globalSetup(_config: FullConfig): Promise { + await waitForApi(); + await ensureDemoProject(); +} diff --git a/tests/web/tools-open.spec.ts b/tests/web/tools-open.spec.ts new file mode 100644 index 0000000..ac01c84 --- /dev/null +++ b/tests/web/tools-open.spec.ts @@ -0,0 +1,81 @@ +import { test, expect, type Page } from '@playwright/test'; + +/** + * Web-app tool open-path e2e. + * + * Drives the real React app (not the standalone harness): for each tool, navigate + * to its route, let WasmTool boot the tool in-document and (for file tools) + * auto-open the demo file via Module.kicadOpenFile, then assert the editor came up + * with the expected title, a painted canvas, no first-run wizard, and no WASM abort + * or URL-regex modal. Fixtures live in the committed "demo" project (seed-data/), + * ensured by global-setup-web.ts. + */ + +interface ToolCase { + /** URL path after /p/demo/ */ + route: string; + /** title the document settles on once the tool is up / file is open */ + titleRe: RegExp; + /** file tools must drop "untitled"; file-less tools just need to boot */ + fileless: boolean; +} + +const CASES: Record = { + eeschema: { route: 'eeschema/demo.kicad_sch', titleRe: /demo — Schematic Editor/i, fileless: false }, + pcbnew: { route: 'pcbnew/demo.kicad_pcb', titleRe: /demo — PCB Editor/i, fileless: false }, + pl_editor: { route: 'pl_editor/demo.kicad_wks', titleRe: /demo — Drawing Sheet Editor/i, fileless: false }, + calculator: { route: 'calculator/', titleRe: /Calculator Tools/i, fileless: true }, + symbol_editor: { route: 'symbol_editor/', titleRe: /Symbol Editor/i, fileless: true }, +}; + +/** Console text that must never appear (wizard-crash + URL-regex modal markers). */ +const FORBIDDEN = /Aborted\(|Invalid regular expression|code points 0xd800|func is not a function/i; + +async function bootAndAssert(page: Page, tc: ToolCase): Promise { + const consoleLines: string[] = []; + page.on('console', (m) => consoleLines.push(m.text())); + page.on('pageerror', (e) => consoleLines.push(`pageerror: ${e.message}`)); + + await page.goto(`/p/demo/${tc.route}`); + + // boot.ts mounts the Emscripten once the runtime starts. + await expect(page.locator('#canvas')).toBeVisible({ timeout: 120000 }); + + // The wasm sets the document title once the frame is up (and, for file tools, + // once OpenProjectFiles finishes). Poll until it matches. + await expect + .poll(() => page.title(), { + message: `${tc.route}: editor never reached expected title`, + timeout: 120000, + intervals: [1000], + }) + .toMatch(tc.titleRe); + + // File tools must have actually loaded the file (title no longer "untitled"). + if (!tc.fileless) { + expect(await page.title(), 'file should be open (title not untitled)').not.toMatch(/untitled/i); + } + + // No first-run setup wizard should be visible (config seed must have skipped it). + const wizardVisible = await page.evaluate(() => { + const reg = (window as unknown as { wxElementRegistry?: { findAll(f: object): { typeName: string }[] } }) + .wxElementRegistry; + if (!reg) return 0; + return reg.findAll({ visible: true }).filter((e) => /^wxDialog|Wizard/.test(e.typeName)).length; + }); + expect(wizardVisible, 'no setup wizard/dialog should be visible').toBe(0); + + const offending = consoleLines.filter((l) => FORBIDDEN.test(l)); + expect(offending, `forbidden console output:\n${offending.join('\n')}`).toHaveLength(0); +} + +test.describe('web app — tool open paths', () => { + for (const [tool, tc] of Object.entries(CASES)) { + test(`${tool}: ${tc.fileless ? 'boots file-less' : 'opens its demo file'} wizard-free`, async ({ + page, + }) => { + await bootAndAssert(page, tc); + await page.screenshot({ path: `test-results/web-${tool}.png`, scale: 'device' }); + }); + } +});