Files
FreeCADWasmDev/tools/functional-suite/runtime.mjs
wangdequan facbb196d8 feat(web): panel scroll contract, layout probe and functional suite
- lock the three-column height chain on workbench/PartDesign pages so each
  side panel scrolls independently and the centre stage keeps its size
- dock module task panels above the layout with their own scrollbar instead
  of letting them push the stage out of the viewport
- add tools/layout-probe.mjs (page scroll, aside bounds, pane scrolling,
  stage stability) and CLI mode for tools/static-host.mjs with relative
  --root support
- add the P0-P4 browser functional suite, manual scenarios and capture
  tooling; document it under docs/current/web-functional-suite

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-24 22:09:42 +08:00

177 lines
8.6 KiB
JavaScript

// Headed browser runtime: static host, page lifecycle, per-case isolation,
// step recording and failure evidence.
import fs from "node:fs";
import path from "node:path";
import { createHash } from "node:crypto";
import { createRequire } from "node:module";
import { fileURLToPath } from "node:url";
import { startStaticHost, findChrome } from "../static-host.mjs";
import { UiParityPreflightError, capturePageErrors } from "../ui-parity-preflight.mjs";
import { classifyFailure } from "./gap-ledger.mjs";
import { persist } from "./report.mjs";
const here = path.dirname(fileURLToPath(import.meta.url));
export const root = path.resolve(here, "../..");
export const webRoot = path.join(root, "web");
export const distRoot = path.join(webRoot, "dist");
const requireWeb = createRequire(path.join(webRoot, "package.json"));
export const { chromium } = requireWeb("playwright");
export const VIEWPORT = { width: 1440, height: 1000 };
export function launchOptions(options) {
const executablePath = findChrome();
if (!executablePath) throw new Error(`Chrome not found; set FREECAD_CHROME (tried /usr/bin/google-chrome)`);
const args = ["--no-sandbox", "--disable-dev-shm-usage", "--window-size=1600,1000"];
// swiftshader keeps canvas hashes and meshes deterministic across headed runs;
// --gpu is a manual-observation escape hatch only.
if (!options.gpu) args.push("--use-gl=angle", "--use-angle=swiftshader", "--enable-unsafe-swiftshader");
return { executablePath, headless: options.headless, slowMo: options.slow || undefined, args };
}
export async function startHost() {
if (!fs.existsSync(path.join(distRoot, "index.html"))) {
throw new Error(`web/dist/index.html is missing; run "npx vite build" in web/ first`);
}
return startStaticHost(distRoot);
}
export async function openBrowser(options) {
return chromium.launch(launchOptions(options));
}
export async function openPage(browser, ctx) {
const context = await browser.newContext({ viewport: VIEWPORT, acceptDownloads: true });
const page = await context.newPage();
page.setDefaultTimeout(30000);
const pageErrors = capturePageErrors(page);
const consoleErrors = [];
page.on("console", message => { if (message.type() === "error") consoleErrors.push(message.text().slice(0, 300)); });
const downloadsDir = path.join(ctx.output, "downloads");
fs.mkdirSync(downloadsDir, { recursive: true });
page.on("download", async download => {
try { await download.saveAs(path.join(downloadsDir, download.suggestedFilename())); } catch { /* download cancelled */ }
});
return { context, page, pageErrors, consoleErrors };
}
// Same-origin OPFS wipe between cases; keeps HTTP/WASM caches warm.
export async function resetState(page, origin) {
await page.goto(`${origin}/index.html`, { waitUntil: "domcontentloaded", timeout: 60000 });
await page.evaluate(async () => {
const rootDir = await navigator.storage.getDirectory();
const names = [];
for await (const [name] of rootDir.entries()) names.push(name);
for (const name of names) await rootDir.removeEntry(name, { recursive: true }).catch(() => {});
});
await page.goto("about:blank");
}
export async function openRoute(page, ctx, route, { timeout = 60000, dismissStart = false } = {}) {
await page.goto(`${ctx.origin}${route}`, { waitUntil: "domcontentloaded", timeout });
await page.waitForFunction(() => document.querySelectorAll("#app button").length > 0, null, { timeout });
const isolation = await page.evaluate(() => ({ isolated: self.crossOriginIsolated, sab: typeof SharedArrayBuffer === "function" }));
if (!isolation.isolated || !isolation.sab) throw new UiParityPreflightError("host/iframe", "COOP/COEP isolation missing");
if (dismissStart) await dismissStartWorkspace(page);
return isolation;
}
export async function dismissStartWorkspace(page) {
const button = page.getByRole("button", { name: "Dismiss Start", exact: true });
if (await button.count()) { try { await button.first().click({ timeout: 3000 }); } catch { /* already gone */ } }
await page.waitForTimeout(300);
}
export async function pageState(page) {
return page.evaluate(() => ({
url: location.href,
title: document.title,
status: document.querySelector(".desktop-status-bar [role=status]")?.textContent ?? null,
tree: [...document.querySelectorAll('[role="treeitem"]')].map(node => node.textContent.trim().slice(0, 60)).slice(0, 20),
tabs: [...document.querySelectorAll('.document-tabs [role="tab"]')].map(node => ({ text: node.textContent.trim(), active: node.getAttribute("aria-selected") === "true" })),
canvases: [...document.querySelectorAll("canvas")].map(canvas => ({ width: canvas.width, height: canvas.height })),
appButtons: document.querySelectorAll("#app button").length,
})).catch(error => ({ error: String(error) }));
}
export async function canvasHash(page, selector = "canvas") {
const locator = page.locator(selector).first();
if ((await locator.count()) === 0) return null;
let buffer = null;
try {
buffer = await locator.screenshot({ timeout: 20000 });
} catch {
// An element screenshot scrolls the canvas into view; a modal Start dialog
// or a tall panel can keep that from ever settling. Clip a viewport shot to
// the canvas box instead — the pixels are the same evidence.
try {
const box = await locator.boundingBox({ timeout: 5000 });
if (box && box.width > 0 && box.height > 0) buffer = await page.screenshot({ clip: box, timeout: 20000 });
} catch { /* canvas gone or unreachable */ }
}
if (!buffer) return null;
return { selector, bytes: buffer.length, sha256: createHash("sha256").update(buffer).digest("hex") };
}
async function captureFailure(page, caseDir, result, ctx) {
const evidence = { at: new Date().toISOString(), ...(await pageState(page)), steps: result.steps };
fs.writeFileSync(path.join(caseDir, "failure.json"), `${JSON.stringify(evidence, null, 2)}\n`);
try { await page.screenshot({ path: path.join(caseDir, "failure.png"), fullPage: true }); } catch { /* page gone */ }
const canvas = await canvasHash(page).catch(() => null);
if (canvas && (await page.locator("canvas").count())) {
try { await page.locator("canvas").first().screenshot({ path: path.join(caseDir, "failure-canvas.png") }); } catch { /* detached */ }
}
result.artifacts = { ...result.artifacts, failure: path.relative(ctx.output, path.join(caseDir, "failure.png")), canvas };
}
export async function runCase(page, definition, ctx) {
const caseDir = path.join(ctx.output, "cases", definition.id);
fs.mkdirSync(caseDir, { recursive: true });
const started = Date.now();
const result = {
id: definition.id, title: definition.title, priority: definition.priority,
executor: definition.executor, module: definition.module ?? null, source: definition.source ?? null,
status: "running", classification: "none", failureClass: null, steps: [], seconds: 0,
error: null, startedAt: new Date().toISOString(), artifacts: {},
};
ctx.results.push(result);
const step = async (name, expected, fn) => {
const item = { number: result.steps.length + 1, name, expected, status: "running", startedAt: new Date().toISOString() };
result.steps.push(item);
persist(ctx);
const begin = Date.now();
try {
item.actual = await fn();
item.status = "passed";
} catch (error) {
item.status = "failed";
item.error = String(error?.message ?? error);
throw error;
} finally {
item.seconds = Number(((Date.now() - begin) / 1000).toFixed(3));
persist(ctx);
}
};
try {
await definition.run({ page, origin: ctx.origin, step, ctx, caseDir, timeoutMs: Math.round((definition.timeoutMs ?? 120000) * ctx.options.timeoutScale) });
result.status = "passed";
} catch (error) {
const verdict = classifyFailure(error);
result.status = verdict.status;
result.classification = verdict.classification;
result.failureClass = verdict.failureClass;
result.error = verdict.message;
await captureFailure(page, caseDir, result, ctx);
ctx.gaps.push({ caseId: result.id, ...verdict, evidence: path.relative(ctx.output, caseDir) });
} finally {
result.seconds = Number(((Date.now() - started) / 1000).toFixed(3));
if (result.status === "passed" && ctx.options.screenshots === "all") {
try { await page.screenshot({ path: path.join(caseDir, "pass.png"), fullPage: true }); } catch { /* page gone */ }
}
fs.writeFileSync(path.join(caseDir, "result.json"), `${JSON.stringify(result, null, 2)}\n`);
persist(ctx);
}
console.log(`${result.id}: ${result.status} (${result.seconds}s)${result.failureClass ? ` [${result.failureClass}]` : ""}`);
return result;
}