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>
This commit is contained in:
2026-11-24 22:09:42 +08:00
parent c3b3160f33
commit facbb196d8
47 changed files with 6813 additions and 247 deletions

View File

@@ -0,0 +1,96 @@
// P1 chapter cases: every manual scenario JSON runs through the same action
// interpreter the screenshot capture tool uses, with per-action step evidence.
import fs from "node:fs";
import path from "node:path";
import { createActionRunner } from "../../../web/tools/manual/lib/actions.mjs";
import { canvasHash, pageState, root } from "../runtime.mjs";
const SCENARIO_DIR = path.join(root, "web", "manual", "scenarios");
// Chapters that import/export large fixtures or drive slow workers need a
// longer ceiling than the 10-minute default.
const TIMEOUT_OVERRIDES = { ch07: 900000, ch09: 900000, ch10: 900000, ch12: 900000 };
function group(actions) {
const groups = [];
let waits = [];
for (const action of actions) {
if (action.type === "wait") { waits.push(action); continue; }
groups.push({ action, waits });
waits = [];
}
if (waits.length) groups.push({ action: null, waits });
return groups;
}
function describe(action) {
if (!action) return "等待渲染";
switch (action.type) {
case "goto": return `打开 ${action.url}`;
case "click": return `点击 ${action.selector ?? `${action.role}:${action.name}`}`;
case "fill": return `填写 ${action.selector}`;
case "select": return `选择 ${action.selector}`;
case "selectIndex": return `选择 ${action.selector}[${action.index}]`;
case "press": return `按键 ${action.key}`;
case "shot": return `截图 ${action.name}`;
case "save": return "保存 FCStd 到 OPFS";
case "seed": return `注入样例 ${action.name ?? path.basename(action.file)}`;
case "eval": return "执行页面脚本";
case "drag": return `拖拽 ${action.selector}`;
case "clickCanvas": return `点击画布 ${action.selector}`;
case "waitFor": return `等待 ${action.selector ?? action.text}`;
case "waitOptions": return `等待选项 ${action.selector}`;
default: return `${action.type} ${action.selector ?? action.contains ?? ""}`.trim();
}
}
function expected(action) {
if (!action) return "页面稳定";
if (action.type === "assertText" || action.type === "assertAnyText") return `文本包含「${action.contains}」`;
if (action.type === "assertValue") return `值为 ${action.value}`;
if (action.type === "assertVisible") return "元素可见";
if (action.type === "shot") return "截图非空(>1KB)";
if (action.type === "save") return "OPFS 出现新的 .FCStd";
return "动作成功执行";
}
function loadScenarios() {
return fs.readdirSync(SCENARIO_DIR).filter(name => name.endsWith(".json")).sort().map(name => {
const scenario = JSON.parse(fs.readFileSync(path.join(SCENARIO_DIR, name), "utf8"));
return { file: name, scenario };
});
}
export const chapterCases = loadScenarios().map(({ file, scenario }) => ({
id: `CH-${scenario.chapter}-${scenario.workflow}`,
title: `${scenario.title ?? scenario.workflow}(${scenario.chapter})`,
priority: "P1",
executor: "scenario",
module: null,
source: `web/manual/scenarios/${file}`,
timeoutMs: TIMEOUT_OVERRIDES[scenario.chapter] ?? 600000,
async run({ page, origin, step, ctx, caseDir }) {
const runner = createActionRunner(page, {
origin,
shotDir: path.join(caseDir, "shots"),
shotPrefix: `${scenario.chapter}/${scenario.workflow}/`,
});
let index = 0;
for (const { action, waits } of group(scenario.actions)) {
index += 1;
const label = action ? `${index}. ${describe(action)}` : `${index}. ${describe(null)}`;
await step(label, expected(action), async () => {
for (const wait of waits) await page.waitForTimeout(wait.ms ?? 500);
if (action) await runner.run(action);
return { type: action?.type ?? "wait", waits: waits.length };
});
}
await step("章末后置断言", "无 pageerror、状态栏无 Error、画布可渲染", async () => {
if (ctx.session.pageErrors.length) throw new Error(`page errors: ${JSON.stringify(ctx.session.pageErrors.slice(0, 3))}`);
const state = await pageState(page);
if (state.status && /^\s*Error:/.test(state.status)) throw new Error(`status bar reports ${state.status}`);
const canvas = await canvasHash(page);
if (canvas && canvas.bytes < 1024) throw new Error(`canvas screenshot too small: ${canvas.bytes}`);
return { status: state.status, canvas: canvas ? { bytes: canvas.bytes, sha256: canvas.sha256 } : null };
});
},
}));

View File

@@ -0,0 +1,344 @@
// P3 cross-cutting cases: export formats, the OPFS contract, save/reopen and
// error recovery. Each case prepares its own document from the project shell.
import fs from "node:fs";
import path from "node:path";
import { assertNoPageErrors } from "../../ui-parity-preflight.mjs";
import { canvasHash, openRoute, root, VIEWPORT } from "../runtime.mjs";
import { closeStartDialog, closeTaskPanel, openFileMenu, waitCubeEnabled } from "./shell.mjs";
const fail = message => { throw new Error(message); };
// storage.ts keeps the two OPFS contracts separate: geometry exports land in
// freecad-exports, saved FCStd documents in freecad-documents.
const EXPORTS = "freecad-exports";
const DOCUMENTS = "freecad-documents";
async function listExports(page, dirName = EXPORTS) {
return page.evaluate(async dirName => {
const root = await navigator.storage.getDirectory();
let dir;
try { dir = await root.getDirectoryHandle(dirName); } catch { return []; }
const out = [];
for await (const [name, handle] of dir.entries()) {
if (handle.kind !== "file") continue;
const file = await handle.getFile();
out.push({ name, size: file.size });
}
return out;
}, dirName);
}
async function readExport(page, name, dirName = EXPORTS) {
return page.evaluate(async ([dirName, fileName]) => {
const root = await navigator.storage.getDirectory();
const dir = await root.getDirectoryHandle(dirName);
const handle = await dir.getFileHandle(fileName);
const file = await handle.getFile();
const bytes = new Uint8Array(await file.arrayBuffer());
let hash = 0x811c9dc5;
for (const byte of bytes) { hash ^= byte; hash = Math.imul(hash, 0x01000193) >>> 0; }
return { size: bytes.length, hash, head: Array.from(bytes.slice(0, 16)) };
}, [dirName, name]);
}
// Export/save controls live inside a collapsed <details>; the shell's menu item
// just sets .open, so the case does the same before touching them.
async function openFileTools(page) {
await page.evaluate(() => { const panel = document.querySelector("details.file-tools"); if (panel) panel.open = true; });
await page.waitForTimeout(200);
}
async function openProjectWithCube(page, origin) {
await openRoute(page, { origin }, "/project.html", { dismissStart: true });
await closeStartDialog(page);
const menu = await openFileMenu(page);
await menu.locator("button.action", { hasText: "新建 Document" }).first().click();
await waitCubeEnabled(page);
await page.getByRole("toolbar", { name: "Solids" }).getByRole("button", { name: "Cube", exact: true }).click();
await closeTaskPanel(page);
await page.waitForFunction(() => parseFloat(document.querySelector("[data-native-volume]")?.textContent ?? "") > 0, null, { timeout: 120000 });
const volume = await page.evaluate(() => parseFloat(document.querySelector("[data-native-volume]")?.textContent ?? ""));
if (Math.abs(volume - 1000) > 1e-6) fail(`precondition: cube volume ${volume} != 1000`);
await openFileTools(page);
return { volume };
}
async function selectCube(page) {
// The export button only enables for a selected Part:: object.
const disabled = await page.locator('button[aria-label="导出选中对象"]').isDisabled();
if (disabled) await page.locator('[role="treeitem"]').first().click();
await page.waitForTimeout(200);
}
async function exportFormat(page, format) {
const before = new Set((await listExports(page)).map(item => item.name));
await page.locator('select[aria-label="Native export format"]').selectOption(format);
await selectCube(page);
await page.locator('button[aria-label="导出选中对象"]').click();
const deadline = Date.now() + 120000;
while (Date.now() < deadline) {
const fresh = (await listExports(page)).filter(item => !before.has(item.name) && item.size > 0);
if (fresh.length) return fresh[0];
await page.waitForTimeout(400);
}
throw new Error(`export ${format} produced no OPFS file within 120 s`);
}
export const crosscutCases = [
{
id: "X-export-formats",
title: "五种导出格式全部落 OPFS 且字节非空",
priority: "P3",
executor: "functional",
source: "manual ch07 / OPFS 铁律",
timeoutMs: 600000,
async run({ page, origin, step, ctx }) {
await step("准备:新建文档并创建 Cube", "体积 1000 mm³", async () => openProjectWithCube(page, origin));
const formats = [["stl", /\.stl$/i], ["step", /\.(step|stp)$/i], ["iges", /\.(iges|igs)$/i], ["brep", /\.(brep|brp)$/i], ["glb", /\.glb$/i]];
for (const [format, pattern] of formats) {
await step(`导出 ${format.toUpperCase()} 到 OPFS`, `freecad-exports 出现匹配 ${pattern} 的非空文件`, async () => {
const file = await exportFormat(page, format);
if (!pattern.test(file.name)) fail(`${format} export produced ${file.name}`);
return file;
});
}
await step("全程未触发浏览器下载", "downloads 目录为空(下载必须显式)", async () => {
const downloads = path.join(ctx.output, "downloads");
const files = fs.existsSync(downloads) ? fs.readdirSync(downloads) : [];
if (files.length) fail(`unexpected downloads: ${files.join(", ")}`);
return { downloads: 0 };
});
await step("页面无未捕获错误", "pageerror 为空", async () => {
assertNoPageErrors(ctx.session.pageErrors);
return { pageErrors: 0 };
});
},
},
{
id: "X-opfs-roundtrip",
title: "FCStd 保存到 OPFS、列目录、回读哈希一致",
priority: "P3",
executor: "functional",
source: "manual ch15 / storage.ts 契约",
timeoutMs: 300000,
async run({ page, origin, step, ctx }) {
await step("准备:新建文档并创建 Cube", "体积 1000 mm³", async () => openProjectWithCube(page, origin));
await step("保存 FCStd 到 OPFS", "freecad-documents 出现 .FCStd 文件", async () => {
const before = new Set((await listExports(page, DOCUMENTS)).map(item => item.name));
await page.getByRole("button", { name: "保存 FCStd 到 OPFS" }).click();
const deadline = Date.now() + 120000;
while (Date.now() < deadline) {
const fresh = (await listExports(page, DOCUMENTS)).filter(item => !before.has(item.name) && /\.fcstd$/i.test(item.name));
if (fresh.length) return fresh[0];
await page.waitForTimeout(400);
}
const present = (await listExports(page, DOCUMENTS)).map(item => item.name);
throw new Error(`save produced no .FCStd file in OPFS within 120 s; freecad-documents=[${present.join(", ")}]`);
});
await step("OPFS 文档下拉列出该文件", "select[aria-label=\"OPFS document\"] 含保存项", async () => {
const options = await page.locator('select[aria-label="OPFS document"] option').evaluateAll(nodes => nodes.map(node => node.value).filter(Boolean));
const saved = (await listExports(page, DOCUMENTS)).find(item => /\.fcstd$/i.test(item.name));
if (!saved) fail("no .FCStd file to verify");
if (!options.includes(saved.name)) fail(`OPFS document select missing ${saved.name}: ${JSON.stringify(options)}`);
return { saved: saved.name, options };
});
await step("两次回读哈希一致", "FNV 哈希与字节长度稳定", async () => {
const saved = (await listExports(page, DOCUMENTS)).find(item => /\.fcstd$/i.test(item.name));
const first = await readExport(page, saved.name, DOCUMENTS);
const second = await readExport(page, saved.name, DOCUMENTS);
if (second.size !== first.size || second.hash !== first.hash) fail(`unstable readback: ${first.size}/${first.hash} vs ${second.size}/${second.hash}`);
if (!(first.size > 0)) fail("saved FCStd is empty");
return first;
});
},
},
{
id: "X-save-reopen",
title: "保存后刷新页面可从 OPFS 重新打开文档",
priority: "P3",
executor: "functional",
source: "manual ch15 / OPFS 铁律",
timeoutMs: 360000,
async run({ page, origin, step, ctx }) {
await step("准备:新建文档、创建 Cube 并保存", "体积 1000 mm³ 且 OPFS 中存在 .FCStd", async () => {
await openProjectWithCube(page, origin);
const before = new Set((await listExports(page, DOCUMENTS)).map(item => item.name));
await page.getByRole("button", { name: "保存 FCStd 到 OPFS" }).click();
const deadline = Date.now() + 120000;
while (Date.now() < deadline) {
const fresh = (await listExports(page, DOCUMENTS)).filter(item => !before.has(item.name) && /\.fcstd$/i.test(item.name));
if (fresh.length) return fresh[0];
await page.waitForTimeout(400);
}
throw new Error("save produced no .FCStd file within 120 s");
});
await step("刷新后从 OPFS 重新打开", "文档树恢复且体积回到 1000 mm³", async () => {
await openRoute(page, { origin }, "/project.html", { dismissStart: true });
await closeStartDialog(page);
await openFileTools(page);
const saved = (await listExports(page, DOCUMENTS)).find(item => /\.fcstd$/i.test(item.name));
if (!saved) fail("OPFS lost the saved document across reload");
await page.locator('select[aria-label="OPFS document"]').selectOption(saved.name);
await page.getByRole("button", { name: "打开 OPFS 文档" }).click();
await page.waitForFunction(() => parseFloat(document.querySelector("[data-native-volume]")?.textContent ?? "") > 0, null, { timeout: 180000 });
const volume = await page.evaluate(() => parseFloat(document.querySelector("[data-native-volume]")?.textContent ?? ""));
const tree = await page.evaluate(() => [...document.querySelectorAll('[role="treeitem"]')].map(node => node.textContent.trim()));
if (!tree.length) fail("document tree empty after reopen");
if (Math.abs(volume - 1000) > 1e-6) fail(`reopened volume ${volume} != 1000`);
return { volume, tree: tree.slice(0, 5) };
});
await step("页面无未捕获错误", "pageerror 为空", async () => {
assertNoPageErrors(ctx.session.pageErrors);
return { pageErrors: 0 };
});
},
},
{
id: "X-error-recovery",
title: "导入损坏 STEP 报错且文档保持完好",
priority: "P3",
executor: "functional",
source: "manual ch07 / 错误恢复",
timeoutMs: 300000,
async run({ page, origin, step, ctx }) {
await step("准备:新建文档并创建 Cube", "体积 1000 mm³", async () => openProjectWithCube(page, origin));
await step("导入损坏的 STEP 文件", "状态栏报告失败且体积仍为 1000 mm³", async () => {
const input = page.locator('input[aria-label="Import JT, PLMXML, STEPZ, 3MF or shape files"]');
await input.setInputFiles({ name: "broken.step", mimeType: "text/plain", buffer: Buffer.from("ISO-10303-21;\nHEADER;\nENDSEC;\nDATA;\n#1=CARTESIAN_POINT('',(0,0));\nENDSEC;\nEND-ISO-10303-21;\n") });
await page.waitForFunction(() => {
const status = document.querySelector(".desktop-status-bar [role=status]")?.textContent ?? "";
return /fail|error|失败|不支持|无法|invalid/i.test(status);
}, null, { timeout: 120000 });
const status = await page.evaluate(() => document.querySelector(".desktop-status-bar [role=status]")?.textContent ?? "");
const volume = await page.evaluate(() => parseFloat(document.querySelector("[data-native-volume]")?.textContent ?? ""));
if (!(Math.abs(volume - 1000) < 1e-6)) fail(`document changed after failed import: volume ${volume}`);
return { status: status.slice(0, 160), volume };
});
await step("页面无未捕获错误", "pageerror 为空", async () => {
assertNoPageErrors(ctx.session.pageErrors);
return { pageErrors: 0 };
});
},
},
{
id: "X-viewport",
title: "工程页与工作台页均无横向溢出且画布在视口内",
priority: "P3",
executor: "functional",
source: "manual ch01",
timeoutMs: 180000,
async run({ page, origin, step, ctx }) {
await step("工程页无横向溢出", "scrollWidth 不超过 clientWidth", async () => {
await openRoute(page, { origin }, "/project.html", { dismissStart: true });
const metrics = await page.evaluate(() => ({ scrollWidth: document.scrollingElement.scrollWidth, clientWidth: document.scrollingElement.clientWidth, viewport: innerWidth }));
if (metrics.scrollWidth > metrics.clientWidth + 1) fail(`project page overflows: ${metrics.scrollWidth} > ${metrics.clientWidth}`);
if (metrics.viewport !== VIEWPORT.width) fail(`viewport ${metrics.viewport} != ${VIEWPORT.width}`);
return metrics;
});
await step("画布哈希可采样", "canvas 至少 1024 字节", async () => {
const hash = await canvasHash(page);
if (!hash || hash.bytes < 1024) fail(`canvas hash too small: ${JSON.stringify(hash)}`);
return hash;
});
await step("工作台页无横向溢出", "workbench scrollWidth 不超过 clientWidth", async () => {
await openRoute(page, { origin }, "/workbench.html?module=Part");
const metrics = await page.evaluate(() => ({ scrollWidth: document.scrollingElement.scrollWidth, clientWidth: document.scrollingElement.clientWidth }));
if (metrics.scrollWidth > metrics.clientWidth + 1) fail(`workbench overflows: ${metrics.scrollWidth} > ${metrics.clientWidth}`);
return metrics;
});
await step("页面无未捕获错误", "pageerror 为空", async () => {
assertNoPageErrors(ctx.session.pageErrors);
return { pageErrors: 0 };
});
},
},
{
id: "X-panel-scroll",
title: "所有页面三栏布局的左右面板独立滚动且中间舞台不动",
priority: "P3",
executor: "functional",
source: "布局需求:左右面板各自滚动,三维视口保持可见",
timeoutMs: 300000,
async run({ page, origin, step, ctx }) {
// Injects a tall spacer into every side-pane scroller, so overflow is a
// property of the layout rather than of whatever content happens to be
// loaded; then scrolls both panes and checks the centre stage did not move.
const probe = () => page.evaluate(() => {
const layout = document.querySelector(".layout, .design-layout");
const asides = layout ? [...layout.querySelectorAll(":scope > aside")].filter(node => node.getClientRects().length) : [];
const main = layout?.querySelector(":scope > main");
const stageBefore = main?.getBoundingClientRect();
const panes = [];
const scrollers = [];
asides.forEach((aside, index) => {
const pane = aside.querySelector(":scope > .pane-scroll");
const entry = { index, asideOverflow: getComputedStyle(aside).overflow, asideHeight: aside.clientHeight, asideBottom: Math.round(aside.getBoundingClientRect().bottom) };
panes.push(entry);
if (!pane) { entry.error = "missing .pane-scroll"; return; }
const spacer = document.createElement("div");
spacer.style.height = "2000px";
pane.appendChild(spacer);
entry.overflowY = getComputedStyle(pane).overflowY;
entry.clientHeight = pane.clientHeight;
entry.scrollHeight = pane.scrollHeight;
scrollers.push(pane);
});
for (const pane of scrollers) pane.scrollTop = 400;
const stageAfter = main?.getBoundingClientRect();
for (const pane of scrollers) { const spacer = pane.lastElementChild; if (spacer?.style.height === "2000px") spacer.remove(); }
return {
hasLayout: Boolean(layout), asideCount: asides.length, panes,
viewportHeight: innerHeight,
docScrollHeight: document.scrollingElement?.scrollHeight ?? 0,
stageShift: stageBefore && stageAfter
? Math.abs(stageAfter.top - stageBefore.top) + Math.abs(stageAfter.height - stageBefore.height) : null,
};
});
const verify = (label, metrics) => {
if (!metrics.hasLayout) fail(`${label}: three-column layout missing`);
if (metrics.asideCount !== 2) fail(`${label}: expected 2 side panels, found ${metrics.asideCount}`);
for (const pane of metrics.panes) {
if (pane.error) fail(`${label}: side panel ${pane.index} ${pane.error}`);
if (pane.overflowY !== "auto") fail(`${label}: side panel ${pane.index} overflow-y ${pane.overflowY}`);
if (!(pane.scrollHeight > pane.clientHeight + 1)) fail(`${label}: side panel ${pane.index} does not scroll (${pane.scrollHeight} <= ${pane.clientHeight})`);
if (pane.asideOverflow !== "hidden") fail(`${label}: side panel ${pane.index} overflow ${pane.asideOverflow}`);
if (pane.asideBottom > metrics.viewportHeight + 1) fail(`${label}: side panel ${pane.index} bottom ${pane.asideBottom} exceeds viewport ${metrics.viewportHeight}`);
}
if (metrics.docScrollHeight > metrics.viewportHeight + 1) fail(`${label}: page still scrolls (${metrics.docScrollHeight} > ${metrics.viewportHeight})`);
if (metrics.stageShift === null || metrics.stageShift > 1) fail(`${label}: centre stage moved while scrolling panels (${metrics.stageShift})`);
};
await step("工程页左右面板独立滚动", "两个 aside 各自滚动,整页不滚动,舞台不动", async () => {
await openRoute(page, { origin }, "/project.html", { dismissStart: true });
await page.waitForSelector(".layout > aside");
const metrics = await probe();
verify("project.html", metrics);
return metrics;
});
await step("PartDesign 页左右面板独立滚动", "树面板与属性面板各自滚动,视口不动", async () => {
await openRoute(page, { origin }, "/partdesign.html");
await page.waitForSelector(".design-layout > aside");
const metrics = await probe();
verify("partdesign.html", metrics);
return metrics;
});
await step("全部工作台模块三栏独立滚动", "每个 module 页两个面板均可滚动", async () => {
const registry = JSON.parse(fs.readFileSync(path.join(root, "docs", "current", "feature-capability-registry.json"), "utf8"));
const modules = registry.modules.map(meta => meta.module);
const checked = [];
const failures = [];
for (const name of modules) {
await openRoute(page, { origin }, `/workbench.html?module=${encodeURIComponent(name)}`);
await page.waitForSelector(".layout > aside");
const metrics = await probe();
try { verify(`workbench:${name}`, metrics); checked.push(name); }
catch (error) { failures.push(String(error.message ?? error)); }
}
if (failures.length) fail(`${failures.length}/${modules.length} module layouts failed: ${failures.slice(0, 5).join(" | ")}`);
return { modules: checked.length };
});
await step("页面无未捕获错误", "pageerror 为空", async () => {
assertNoPageErrors(ctx.session.pageErrors);
return { pageErrors: 0 };
});
},
},
];

View File

@@ -0,0 +1,96 @@
// Hand-written chapter cases for the chapters that ship no scenario JSON.
import fs from "node:fs";
import path from "node:path";
import { dismissStartWorkspace, openRoute, root } from "../runtime.mjs";
import { runCommand, selectModule } from "./modules.mjs";
const COURSE = path.join(root, "web", "tools", "line-course");
const MEDIA = path.join(root, "web", "teaching", "media", "line-course");
export const handwrittenCases = [
{
id: "CH-ch14-production-line",
title: "生产线课程:规格表、收口证据与媒体资产",
priority: "P1",
executor: "assets",
source: "web/manual/content/ch14-production-line.md",
timeoutMs: 60000,
async run({ step }) {
await step("line-spec 规格表可解析", "27 个模型 / 88 个部件 / 三角面 > 0 / 6 分量包围盒", async () => {
const spec = JSON.parse(fs.readFileSync(path.join(COURSE, "line-spec.json"), "utf8"));
const bbox = spec.sceneBBox;
if (spec.modelCount !== 27) throw new Error(`modelCount ${spec.modelCount} != 27`);
if (spec.partCount !== 88) throw new Error(`partCount ${spec.partCount} != 88`);
if (!(spec.triangleCount > 0)) throw new Error(`triangleCount ${spec.triangleCount} is not positive`);
if (!Array.isArray(bbox) || bbox.length !== 6 || !bbox.every(value => typeof value === "number" && Number.isFinite(value))) throw new Error(`sceneBBox is not 6 finite numbers: ${JSON.stringify(bbox)}`);
return { modelCount: spec.modelCount, partCount: spec.partCount, triangleCount: spec.triangleCount, bbox };
});
await step("收口证据可解析", "final-status.json 含 state 与 knownBoundaries", async () => {
const status = JSON.parse(fs.readFileSync(path.join(COURSE, "evidence", "final-status.json"), "utf8"));
if (!status.state) throw new Error("final-status.json has no state");
if (!("knownBoundaries" in status)) throw new Error("final-status.json has no knownBoundaries");
return { state: status.state, keys: Object.keys(status).length };
});
await step("媒体目录非空", "至少一集视频或截图", async () => {
const count = fs.readdirSync(MEDIA).length;
if (count < 1) throw new Error("media directory is empty");
return { files: count };
});
},
},
{
id: "CH-ch15-help-start",
title: "帮助、命令面板、偏好与快捷键(第 15 章)",
priority: "P1",
executor: "functional",
source: "web/manual/content/ch15-help-start.md",
timeoutMs: 240000,
async run({ page, origin, step }) {
await step("Help 工作台源码清点可执行", "help.inspectSourceInventory 返回 kind=result", async () => {
await openRoute(page, { origin }, "/workbench.html?module=Help");
await dismissStartWorkspace(page);
await selectModule(page, "Help");
const response = await runCommand(page, "help.inspectSourceInventory");
if (response?.kind !== "result") throw new Error(`help.inspectSourceInventory: ${JSON.stringify(response?.error ?? response).slice(0, 240)}`);
return { kind: response.kind };
});
await step("Ctrl+K 打开命令面板并检索到命令", "面板可见且 Part_Box 出现在结果中", async () => {
await openRoute(page, { origin }, "/project.html", { dismissStart: true });
await page.keyboard.press("Control+k");
const palette = page.locator('[role="dialog"][aria-label="Command palette"]');
await palette.waitFor({ state: "visible", timeout: 15000 });
await palette.getByLabel("Search commands").fill("Part_Box");
const hit = palette.locator("button", { has: page.locator("code", { hasText: "Part_Box" }) }).first();
await hit.waitFor({ state: "visible", timeout: 15000 });
await palette.getByLabel("Close command palette").click();
await palette.waitFor({ state: "detached", timeout: 10000 });
return { palette: "opened", match: (await hit.count()) > 0 };
});
await step("偏好对话框可从 Tools 菜单打开", "Preferences 对话框含单位/主题控件", async () => {
await page.locator(".utility-menus > button", { hasText: "Tools" }).first().click();
await page.locator('[role="menu"][aria-label="Tools"] button', { hasText: "Preferences…" }).click();
const dialog = page.locator('[role="dialog"][aria-label="Preferences"]');
await dialog.waitFor({ state: "visible", timeout: 15000 });
const units = await dialog.getByLabel("Unit system").count();
const theme = await dialog.getByLabel("Theme").count();
if (!units || !theme) throw new Error(`preferences controls missing: units=${units} theme=${theme}`);
await dialog.getByLabel("Close preferences").click();
await dialog.waitFor({ state: "detached", timeout: 10000 });
return { units, theme };
});
await step("快捷键管理器可从 Tools 菜单打开", "Customize shortcuts 对话框可搜索命令", async () => {
await page.locator(".utility-menus > button", { hasText: "Tools" }).first().click();
await page.locator('[role="menu"][aria-label="Tools"] button', { hasText: "Customize shortcuts…" }).click();
const dialog = page.locator('[role="dialog"][aria-label="Customize shortcuts"]');
await dialog.waitFor({ state: "visible", timeout: 15000 });
await dialog.getByLabel("Search shortcuts").fill("Part_Box");
await page.waitForTimeout(300);
const rows = await dialog.locator("tbody tr").count();
if (!rows) throw new Error("shortcut search returned no rows for Part_Box");
await dialog.getByLabel("Close shortcut editor").click();
await dialog.waitFor({ state: "detached", timeout: 10000 });
return { rows };
});
},
},
];

View File

@@ -0,0 +1,12 @@
// Case registry. Cross-cutting cases register here as they land.
import { chapterCases } from "./chapters.mjs";
import { crosscutCases } from "./crosscut.mjs";
import { handwrittenCases } from "./handwritten.mjs";
import { moduleCases } from "./modules.mjs";
import { shellCases } from "./shell.mjs";
export const CASE_LAYERS = { shell: shellCases, chapters: [...chapterCases, ...handwrittenCases], modules: moduleCases, crosscut: crosscutCases };
export function allCases() {
return [...CASE_LAYERS.shell, ...CASE_LAYERS.chapters, ...CASE_LAYERS.modules, ...CASE_LAYERS.crosscut];
}

View File

@@ -0,0 +1,112 @@
// P2 module smoke: every registered module must load its shell, expose its
// command surface and answer one canonical worker command.
import fs from "node:fs";
import path from "node:path";
import { root } from "../runtime.mjs";
import { blockedPrecondition } from "../gap-ledger.mjs";
import { dismissStartWorkspace, openRoute } from "../runtime.mjs";
const REGISTRY = path.join(root, "docs", "current", "feature-capability-registry.json");
// Web FreeCAD ships without OpenSCAD (project iron rule) and AddonManager has no
// interactive command, so neither is a functional module under test here.
const SKIP = new Set(["OpenSCAD", "AddonManager"]);
// Read-only commands come first: they exercise worker + registry without
// depending on selection state or parameters, so a failure means the module
// really is broken rather than under-specified by the smoke.
const PREFERRED_SUFFIXES = ["inspectSourceInventory", "inspectPythonApi", "inspectRegistry", "pythonApi", "measurementApi", "navigationBoundary", "serverContract", "createRecompute"];
// The Web module has no worker route for serverContract (browser-native module);
// its persistence boundary command is the one that actually dispatches.
const CANONICAL_OVERRIDES = { Web: "web.saveReopenBoundary" };
function loadModules() {
const registry = JSON.parse(fs.readFileSync(REGISTRY, "utf8"));
const byModule = new Map();
for (const record of registry.records) {
if (!byModule.has(record.module)) byModule.set(record.module, []);
byModule.get(record.module).push(record);
}
const modules = [];
for (const meta of registry.modules) {
if (SKIP.has(meta.module)) continue;
const records = byModule.get(meta.module) ?? [];
const interactive = records.filter(record => record.uiStatus === "interactive" && record.implementationStatus === "routed");
const override = CANONICAL_OVERRIDES[meta.module];
const canonical = (override ? interactive.find(record => record.command === override) : null)
?? PREFERRED_SUFFIXES.map(suffix => interactive.find(record => record.command.endsWith(suffix))).find(Boolean)
?? interactive[0] ?? null;
modules.push({ name: meta.module, interactive: interactive.length, canonical: canonical?.command ?? null });
}
return modules;
}
export const MODULES = loadModules();
const escapeRe = text => text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
export async function selectModule(page, name) {
// Anchor the match: "Part" is a substring of "MeshPart" and "PartDesign".
const exact = new RegExp(`^\\s*${escapeRe(name)}\\s*$`);
const button = page.locator("button.module").filter({ has: page.locator("strong", { hasText: exact }) }).first();
if (!(await button.count())) throw blockedPrecondition("entry", `module ${name} is not exposed in the module dock`);
await button.click();
// Module labels are capitalised ("Assembly") while command ids are lowercase
// ("assembly.createRecompute"), so compare case-insensitively.
await page.waitForFunction(expected => [...document.querySelectorAll("button.command span")].some(span => String(span.textContent).toLowerCase().startsWith(`${expected}.`)), name.toLowerCase(), { timeout: 60000 });
}
export async function runCommand(page, name) {
const exact = new RegExp(`^\\s*${escapeRe(name)}\\s*$`);
const command = page.locator("button.command").filter({ has: page.locator("span", { hasText: exact }) }).first();
await command.waitFor({ state: "visible", timeout: 60000 });
await command.click();
// The panel prefills the payload the worker expects; overwriting it with "{}"
// is what makes an otherwise valid command fail with invalid_request.
const args = page.getByLabel("命令 JSON 参数");
let payload = "";
if (await args.count()) {
payload = (await args.inputValue()).trim();
if (!payload) { payload = "{}"; await args.fill(payload); }
}
const run = page.getByRole("button", { name: "执行选中命令", exact: true });
await run.waitFor({ state: "visible", timeout: 30000 });
await run.click();
await page.waitForFunction(() => window.__freecadWorkbenchState?.response?.kind === "result" || window.__freecadWorkbenchState?.response?.kind === "error", null, { timeout: 180000 });
return page.evaluate(() => window.__freecadWorkbenchState.response);
}
export const moduleCases = MODULES.map(meta => ({
id: `MOD-${meta.name}-01`,
title: `${meta.name} 模块冒烟:壳层、命令面与规范动作`,
priority: "P2",
executor: "functional",
module: meta.name,
source: "feature-capability-registry.json",
timeoutMs: 240000,
async run({ page, origin, step }) {
await step("打开模块工作台", "模块壳层挂载且隔离头生效", async () => {
const isolation = await openRoute(page, { origin }, `/workbench.html?module=${encodeURIComponent(meta.name)}`);
await dismissStartWorkspace(page);
return isolation;
});
await step(`${meta.name} 模块在模块坞中可选中`, "button.module 存在且被选中", async () => {
await selectModule(page, meta.name);
const selected = await page.evaluate(() => document.querySelector("button.module[aria-current], button.module.selected")?.textContent?.trim().slice(0, 40) ?? null);
return { module: meta.name, selected };
});
await step("命令面已注册", "该模块至少注册一条命令", async () => {
await page.waitForFunction(() => document.querySelectorAll("button.command").length > 0, null, { timeout: 60000 });
const count = await page.locator("button.command").count();
if (count < 1) throw new Error(`${meta.name} exposes no commands`);
return { commands: count, registered: meta.interactive };
});
if (!meta.canonical) throw blockedPrecondition("command-state", `${meta.name} has no interactive routed command`);
await step(`规范动作 ${meta.canonical}`, "原生返回 kind=result 且无 sceneError", async () => {
const response = await runCommand(page, meta.canonical);
if (response?.kind === "error") throw new Error(`command error: ${JSON.stringify(response.error).slice(0, 300)}`);
const row = response?.result?.records?.[0];
const result = row?.result ?? response?.result;
if (result?.sceneError) throw new Error(`scene refresh failed: ${result.sceneError}`);
return { kind: response?.kind, command: meta.canonical, hasRow: Boolean(row) };
});
},
}));

View File

@@ -0,0 +1,202 @@
// P0 shell cases: entry/isolation, project shell, first document, OPFS contract,
// viewport and canvas. These are the preconditions every later case builds on.
import { assertNoPageErrors, prepareProjectShell, prepareWorkbenchShell } from "../../ui-parity-preflight.mjs";
import { VIEWPORT, canvasHash, dismissStartWorkspace, openRoute, pageState } from "../runtime.mjs";
const fail = message => { throw new Error(message); };
export async function waitCubeEnabled(page, timeout = 120000) {
await page.waitForFunction(() => {
const toolbar = document.querySelector('[role="toolbar"][aria-label="Solids"]');
const button = toolbar ? [...toolbar.querySelectorAll("button")].find(node => node.getAttribute("aria-label") === "Cube") : undefined;
return Boolean(button && !button.disabled);
}, null, { timeout });
}
// The application menu is a <details>/<summary> list, so the item buttons are
// not visible until their own menu is opened — role locators never match them.
export async function openFileMenu(page) {
const menu = page.locator("nav.application-menus details").filter({ has: page.locator("button.action", { hasText: "新建 Document" }) }).first();
if (!(await menu.count())) fail("File menu not found");
await menu.locator("summary").first().click();
await page.waitForTimeout(200);
return menu;
}
export async function closeTaskPanel(page) {
if (await page.locator('fieldset[aria-label="Task: Box dimensions"]').count()) await page.keyboard.press("Escape");
await page.waitForTimeout(300);
}
export async function closeStartDialog(page) {
for (let attempt = 0; attempt < 20; attempt += 1) {
if (await page.locator("dialog[open]").count()) { await page.keyboard.press("Escape"); await page.waitForTimeout(250); continue; }
await page.waitForTimeout(300);
if ((await page.locator("dialog[open]").count()) === 0) return;
}
}
export const shellCases = [
{
id: "SHELL-01",
title: "入口、COOP/COEP 隔离与工作台壳层",
priority: "P0",
executor: "functional",
source: "manual ch00/ch01",
timeoutMs: 120000,
async run({ page, origin, step, ctx }) {
await step("打开 Part 工作台并确认隔离头生效", "crossOriginIsolated 且 SharedArrayBuffer 可用", async () => {
const isolation = await openRoute(page, { origin }, "/workbench.html?module=Part");
return isolation;
});
await step("工作台壳层可见且无横向溢出", ".dock-workbench 可测量、在视口内", async () => {
const { state } = await prepareWorkbenchShell(page, { origin, path: "/workbench.html?module=Part", viewport: VIEWPORT });
return state;
});
await step("页面无未捕获错误", "pageerror 为空", async () => {
assertNoPageErrors(ctx.session.pageErrors);
return { pageErrors: 0 };
});
},
},
{
id: "SHELL-02",
title: "工程壳层与 Start 对话框",
priority: "P0",
executor: "functional",
source: "manual ch01",
timeoutMs: 120000,
async run({ page, origin, step, ctx }) {
await step("打开工程页并确认工具栏就绪", ".desktop-workspace 与 Solids 工具栏可见", async () => {
const { state } = await prepareProjectShell(page, { origin, path: "/project.html", viewport: VIEWPORT, toolbarName: "Solids", minDropdowns: 0 });
return state;
});
await step("Start 对话框可关闭且不拦截操作", "dialog[open] 数量为 0", async () => {
await closeStartDialog(page);
await dismissStartWorkspace(page);
const open = await page.locator("dialog[open]").count();
if (open) fail(`Start dialog still open: ${open}`);
return { openDialogs: 0 };
});
await step("工具栏图标全部渲染", "img 均 complete 且 naturalWidth > 0", async () => {
// SVG icons 404/sniff-blocked by a wrong static-host MIME show up here
// as naturalWidth === 0 while still returning HTTP 200.
const icons = await page.evaluate(() => ({ total: document.images.length, broken: [...document.images].filter(image => !image.complete || image.naturalWidth === 0).map(image => image.getAttribute("src")).slice(0, 10) }));
if (!icons.total) fail("no icon images rendered");
if (icons.broken.length) fail(`broken icons: ${icons.broken.join(", ")}`);
return icons;
});
await step("页面无未捕获错误", "pageerror 为空", async () => {
assertNoPageErrors(ctx.session.pageErrors);
return { pageErrors: 0 };
});
},
},
{
id: "SHELL-03",
title: "新建文档、创建 Cube 并显示体积",
priority: "P0",
executor: "functional",
source: "manual ch01/ch02",
timeoutMs: 240000,
async run({ page, origin, step, ctx }) {
await step("关闭 Start 并新建 Document", "Solids/Cube 命令可用", async () => {
await openRoute(page, { origin }, "/project.html", { dismissStart: true });
await closeStartDialog(page);
const menu = await openFileMenu(page);
await menu.locator("button.action", { hasText: "新建 Document" }).first().click();
await waitCubeEnabled(page);
await closeStartDialog(page);
return { cubeEnabled: true };
});
await step("执行 Cube 命令", "文档树出现对象且体积为 1000 mm³(默认 10mm 立方体)", async () => {
await waitCubeEnabled(page);
await page.getByRole("toolbar", { name: "Solids" }).getByRole("button", { name: "Cube", exact: true }).click();
await closeTaskPanel(page);
await page.waitForFunction(() => parseFloat(document.querySelector("[data-native-volume]")?.textContent ?? "") > 0, null, { timeout: 120000 });
const volume = await page.evaluate(() => parseFloat(document.querySelector("[data-native-volume]")?.textContent ?? ""));
const tree = await page.evaluate(() => [...document.querySelectorAll('[role="treeitem"]')].map(node => node.textContent.trim()));
if (tree.length < 1) fail("document tree is empty after Cube");
if (Math.abs(volume - 1000) > 1e-6) fail(`volume ${volume} != 1000`);
return { volume, tree: tree.slice(0, 5) };
});
await step("页面无未捕获错误", "pageerror 为空", async () => {
assertNoPageErrors(ctx.session.pageErrors);
return { pageErrors: 0 };
});
},
},
{
id: "SHELL-04",
title: "OPFS 导出目录可写可读",
priority: "P0",
executor: "functional",
source: "OPFS contract (web/src/storage.ts:67)",
timeoutMs: 60000,
async run({ page, origin, step }) {
await step("进入同源页面", "应用挂载", async () => {
await openRoute(page, { origin }, "/workbench.html?module=Part");
return true;
});
await step("freecad-exports 目录写入、列出、回读、删除", "四步全部成功", async () => {
const result = await page.evaluate(async () => {
const name = `functional-suite-probe-${Date.now()}.txt`;
const payload = new TextEncoder().encode("freecad-web-suite");
const rootDir = await navigator.storage.getDirectory();
const exportsDir = await rootDir.getDirectoryHandle("freecad-exports", { create: true });
const handle = await exportsDir.getFileHandle(name, { create: true });
const writer = await handle.createWritable();
await writer.write(payload);
await writer.close();
const names = [];
for await (const [entry] of exportsDir.entries()) names.push(entry);
const text = await (await (await exportsDir.getFileHandle(name)).getFile()).text();
await exportsDir.removeEntry(name);
const after = [];
for await (const [entry] of exportsDir.entries()) after.push(entry);
return { bytes: payload.byteLength, listed: names.includes(name), text, removed: !after.includes(name) };
});
if (!result.listed) fail("probe file missing from listing");
if (result.text !== "freecad-web-suite") fail(`read-back mismatch: ${result.text}`);
if (!result.removed) fail("probe file was not removed");
return result;
});
},
},
{
id: "SHELL-05",
title: "视口尺寸、画布与场景渲染",
priority: "P0",
executor: "functional",
source: "manual ch01 viewport",
timeoutMs: 120000,
async run({ page, origin, step, ctx }) {
// The 3D canvas lives in the project shell; the module shell only renders
// the command browser (no canvas by design, verified in the DOM probe).
await step("打开工程页并确认视口", "1440x1000 且无横向溢出", async () => {
await openRoute(page, { origin }, "/project.html", { dismissStart: true });
const state = await page.evaluate(() => ({
width: innerWidth, height: innerHeight,
overflow: document.documentElement.scrollWidth > document.documentElement.clientWidth,
}));
if (state.width !== VIEWPORT.width || state.height !== VIEWPORT.height) fail(`viewport ${state.width}x${state.height}`);
if (state.overflow) fail("horizontal overflow");
return state;
});
await step("画布存在且有内容", "canvas 尺寸非零、截图 hash 非空", async () => {
const canvases = await page.evaluate(() => [...document.querySelectorAll("canvas")].map(canvas => ({ width: canvas.width, height: canvas.height })));
if (!canvases.length) fail("no canvas");
if (!canvases.some(item => item.width > 0 && item.height > 0)) fail("canvas has zero size");
const hash = await canvasHash(page);
if (!hash || hash.bytes < 1024) fail(`canvas screenshot too small: ${hash?.bytes ?? 0}`);
return { canvases, hash };
});
await step("页面无未捕获错误", "pageerror 为空", async () => {
assertNoPageErrors(ctx.session.pageErrors);
return { pageErrors: 0 };
});
},
},
];
export { pageState };

View File

@@ -0,0 +1,83 @@
// CLI contract for the headed Web FreeCAD functional suite.
// Every option has an env equivalent so CI wrappers can stay script-free.
export const USAGE = `Web FreeCAD functional suite (headed by default)
node tools/web-freecad-functional-suite.mjs [options]
--only <ids> comma separated case ids (e.g. SHELL-01,CH02-part)
--priority <list> comma separated priorities: P0,P1,P2,P3 (default all)
--module <list> comma separated module names for MOD-* cases
--resume <dir> continue a previous run directory (skip completed ids)
--force with --resume, re-run completed cases
--headless hide the browser window (default is headed)
--gpu drop swiftshader flags (manual perf observation only)
--slow <ms> Playwright slowMo pacing for live observation
--highlight outline the acted element before each action
--screenshots <s> "fails" (default) or "all"
--jobs <n> browser workers (1 = single headed window, default 1)
--out <dir> evidence root (default docs/current/web-functional-suite)
--prune <n> keep only the newest n run directories
--legacy-ids <ids> also run tools/run_user_manual_tests.mjs ids (all = 53 cases)
--timeout-scale <x> multiply per-case timeouts (default 1)
With no selection flags every non-legacy case runs.`;
const list = value => String(value ?? "").split(",").map(item => item.trim()).filter(Boolean);
export function parseArgs(argv = process.argv.slice(2)) {
const options = {
only: list(process.env.FREECAD_SUITE_ONLY),
priority: list(process.env.FREECAD_SUITE_PRIORITY),
module: list(process.env.FREECAD_SUITE_MODULE),
resume: null, force: false,
headless: process.env.HEADLESS === "1",
gpu: false, slow: Number(process.env.FREECAD_SLOWMO ?? 0) || 0, highlight: false,
screenshots: process.env.FREECAD_SUITE_SCREENSHOTS === "all" ? "all" : "fails",
jobs: 1, out: null, prune: null, legacyIds: [], timeoutScale: 1,
};
for (let index = 0; index < argv.length; index += 1) {
const flag = argv[index];
const value = () => argv[index + 1] ?? "";
switch (flag) {
case "--only": options.only = list(value()); index += 1; break;
case "--priority": options.priority = list(value()).map(item => item.toUpperCase()); index += 1; break;
case "--module": options.module = list(value()); index += 1; break;
case "--resume": options.resume = value(); index += 1; break;
case "--force": options.force = true; break;
case "--headless": options.headless = true; break;
case "--headed": options.headless = false; break;
case "--gpu": options.gpu = true; break;
case "--slow": options.slow = Number(value()) || 0; index += 1; break;
case "--highlight": options.highlight = true; break;
case "--screenshots": options.screenshots = value() === "all" ? "all" : "fails"; index += 1; break;
case "--jobs": options.jobs = Math.max(1, Number(value()) || 1); index += 1; break;
case "--out": options.out = value(); index += 1; break;
case "--prune": options.prune = Math.max(1, Number(value()) || 1); index += 1; break;
case "--legacy-ids": options.legacyIds = list(value()); index += 1; break;
case "--timeout-scale": options.timeoutScale = Math.max(0.1, Number(value()) || 1); index += 1; break;
case "--help": case "-h": options.help = true; break;
default: throw new Error(`unknown option ${flag}\n\n${USAGE}`);
}
}
return options;
}
export function selectCases(cases, options) {
let selected = cases;
if (options.only.length) {
const ids = new Set(options.only);
selected = selected.filter(item => ids.has(item.id));
const missing = [...ids].filter(id => !cases.some(item => item.id === id));
if (missing.length) throw new Error(`unknown case ids: ${missing.join(", ")}`);
}
if (options.priority.length) {
const priorities = new Set(options.priority);
selected = selected.filter(item => priorities.has(item.priority));
}
if (options.module.length) {
const modules = new Set(options.module.map(item => item.toLowerCase()));
selected = selected.filter(item => !item.module || modules.has(item.module.toLowerCase()));
}
return selected;
}

View File

@@ -0,0 +1,56 @@
// Runs the untouched manual runner (tools/run_user_manual_tests.mjs) as a child
// process and folds its results into the functional-suite report as LEGACY-*.
import { spawn } from "node:child_process";
import fs from "node:fs";
import path from "node:path";
import { root } from "../runtime.mjs";
import { persist } from "../report.mjs";
const MAP = {
passed: { status: "passed", classification: "none", failureClass: null },
blocked: { status: "blocked", classification: "precondition", failureClass: "fixture" },
failed: { status: "failed", classification: "product-regression", failureClass: "product-regression" },
};
export async function runLegacyCases(options, ctx) {
const ids = options.legacyIds.includes("all") ? "" : options.legacyIds.join(",");
const env = { ...process.env };
if (ids) env.FREECAD_MANUAL_IDS = ids;
const child = spawn(process.execPath, [path.join(root, "tools", "run_user_manual_tests.mjs")], {
cwd: root, env, stdio: ["ignore", "pipe", "pipe"],
});
let stdout = "";
let stderr = "";
child.stdout.on("data", chunk => { stdout += chunk; process.stdout.write(chunk); });
child.stderr.on("data", chunk => { stderr += chunk; });
const code = await new Promise(resolve => child.on("close", resolve));
const lastJson = [...stdout.trim().split("\n")].reverse().find(line => line.startsWith("{") && line.includes('"output"'));
if (!lastJson) {
const message = `legacy runner exited ${code} without a result line: ${(stderr || stdout).slice(-400)}`;
console.error(message);
ctx.results.push({ id: "LEGACY-RUNNER", title: "Legacy manual runner", priority: "P4", executor: "legacy", status: "blocked", classification: "precondition", failureClass: "fixture", steps: [], seconds: 0, error: message, startedAt: new Date().toISOString(), artifacts: {} });
persist(ctx);
return [];
}
const { output: legacyDir } = JSON.parse(lastJson);
const legacy = JSON.parse(fs.readFileSync(path.join(legacyDir, "results.json"), "utf8"));
const imported = [];
for (const item of legacy.results ?? []) {
const mapped = MAP[item.status] ?? MAP.failed;
const result = {
id: `LEGACY-${item.id}`, title: item.title ?? item.id, priority: "P4", executor: "legacy",
module: null, source: path.relative(root, legacyDir) + "/results.json",
status: mapped.status, classification: mapped.classification, failureClass: mapped.failureClass,
steps: item.steps ?? [], seconds: item.seconds ?? 0, error: item.error ?? null,
startedAt: item.startedAt ?? null, artifacts: { legacy: path.relative(root, legacyDir) },
};
ctx.results.push(result);
imported.push(result);
if (mapped.status !== "passed") {
ctx.gaps.push({ caseId: result.id, status: mapped.status, classification: mapped.classification, failureClass: mapped.failureClass, message: result.error ?? mapped.status, evidence: result.artifacts.legacy });
}
}
persist(ctx);
return imported;
}

View File

@@ -0,0 +1,61 @@
// Failure classification for the functional suite.
// Precondition failures become `blocked`; product failures become `failed`.
// The ledger keeps them separate so a blocked preflight never masks a regression.
import fs from "node:fs";
import path from "node:path";
import { UiParityPreflightError } from "../ui-parity-preflight.mjs";
const PRECONDITION_CLASSES = new Set([
"preview/port", "entry", "fixture", "viewport", "host/iframe", "command-state", "tool-observation",
]);
export function classifyFailure(error) {
if (error?.blocked === true) {
return { status: "blocked", classification: "precondition", failureClass: error.failureClass ?? "fixture", message: String(error.message ?? error) };
}
if (error instanceof UiParityPreflightError) {
const failureClass = error.failureClass;
if (PRECONDITION_CLASSES.has(failureClass)) {
return { status: "blocked", classification: "precondition", failureClass, message: error.message };
}
return { status: "failed", classification: "product-regression", failureClass, message: error.message };
}
// Plain assertion errors come from product steps; cases may mark a known
// unimplemented capability as a product gap instead of a regression.
if (error?.productGap === true) {
return { status: "failed", classification: "product-gap", failureClass: "product-gap", message: String(error.message ?? error) };
}
return { status: "failed", classification: "product-regression", failureClass: "product-regression", message: String(error?.message ?? error) };
}
export function blockedPrecondition(failureClass, message) {
const error = new Error(message);
error.blocked = true;
error.failureClass = failureClass;
return error;
}
export function createGapLedger(file) {
const entries = [];
return {
record(entry) {
const row = { at: new Date().toISOString(), status: "open", ...entry };
entries.push(row);
fs.mkdirSync(path.dirname(file), { recursive: true });
fs.appendFileSync(file, `${JSON.stringify(row)}\n`);
return row;
},
entries,
};
}
export function renderGapSections(entries) {
const blocked = entries.filter(item => item.classification === "precondition");
const product = entries.filter(item => item.classification !== "precondition");
const line = item => `- \`${item.caseId}\` ${item.failureClass}: ${item.message.slice(0, 240)}${item.evidence ? ` — ${item.evidence}` : ""}`;
return {
blocked: blocked.length ? blocked.map(line).join("\n") : "- none",
product: product.length ? product.map(line).join("\n") : "- none",
counts: { blocked: blocked.length, product: product.length },
};
}

View File

@@ -0,0 +1,126 @@
// Run artefacts: manifest, results, checkpoint, markdown/JUnit/HTML reports.
import fs from "node:fs";
import path from "node:path";
import { renderGapSections } from "./gap-ledger.mjs";
const ISO_STAMP = () => new Date().toISOString().replace(/[:.]/g, "-");
const esc = value => String(value ?? "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
export function createRunContext({ options, root, output, origin }) {
return {
schema: "freecad-web/functional-suite/v1",
root, output, origin,
startedAt: new Date().toISOString(),
updatedAt: null,
options,
results: [],
gaps: [],
counts: { passed: 0, failed: 0, blocked: 0, reference_only: 0, running: 0 },
manifest: {},
};
}
export function newRunDir(base, resume) {
if (resume) return path.resolve(resume);
const dir = path.join(base, `run-${ISO_STAMP()}`);
fs.mkdirSync(dir, { recursive: true });
return dir;
}
export function writeManifest(ctx, extra = {}) {
ctx.manifest = {
schema: "freecad-web/functional-suite-manifest/v1",
generatedAt: new Date().toISOString(),
origin: ctx.origin,
platform: process.platform,
node: process.version,
display: process.env.DISPLAY ?? null,
headless: ctx.options.headless,
command: process.argv.join(" "),
...extra,
};
fs.writeFileSync(path.join(ctx.output, "manifest.json"), `${JSON.stringify(ctx.manifest, null, 2)}\n`);
}
export function recount(ctx) {
const counts = { passed: 0, failed: 0, blocked: 0, reference_only: 0, running: 0 };
for (const result of ctx.results) counts[result.status] = (counts[result.status] ?? 0) + 1;
ctx.counts = counts;
return counts;
}
export function persist(ctx) {
ctx.updatedAt = new Date().toISOString();
recount(ctx);
fs.writeFileSync(path.join(ctx.output, "results.json"), `${JSON.stringify({
schema: ctx.schema, startedAt: ctx.startedAt, updatedAt: ctx.updatedAt, origin: ctx.origin,
headless: ctx.options.headless, counts: ctx.counts, results: ctx.results,
}, null, 2)}\n`);
const completed = ctx.results.filter(item => item.status !== "running").map(item => ({ id: item.id, status: item.status, seconds: item.seconds }));
fs.writeFileSync(path.join(ctx.output, "checkpoint.json"), `${JSON.stringify({
schema: "freecad-web/functional-suite-checkpoint/v1", updatedAt: ctx.updatedAt,
current: ctx.results.find(item => item.status === "running")?.id ?? null, completed,
}, null, 2)}\n`);
}
const statusCell = item => {
if (item.status === "passed") return "passed";
if (item.status === "blocked") return `blocked (${item.failureClass})`;
return `${item.status} (${item.classification})`;
};
export function writeMarkdown(ctx) {
const gaps = renderGapSections(ctx.gaps);
const rows = ctx.results.map(item =>
`| ${item.id} | ${item.priority} | ${statusCell(item)} | ${Number(item.seconds ?? 0).toFixed(1)}s | ${item.steps.length} | ${item.error ? item.error.slice(0, 120).replace(/\|/g, "\\|") : ""} |`);
return `# Web FreeCAD 功能测试(有头)\n\n` +
`- 运行:${ctx.startedAt}\n- Origin:${ctx.origin}\n- 模式:${ctx.options.headless ? "headless" : "headed"}\n` +
`- 计数:passed ${ctx.counts.passed} / failed ${ctx.counts.failed} / blocked ${ctx.counts.blocked} / reference_only ${ctx.counts.reference_only}\n\n` +
`## 用例\n\n| id | 优先级 | 状态 | 耗时 | 步骤 | 错误 |\n|---|---|---|---|---|---|\n${rows.join("\n")}\n\n` +
`## Blocked(前置未满足)\n\n${gaps.blocked}\n\n## Product(产品/UI 缺口)\n\n${gaps.product}\n`;
}
export function writeJUnit(ctx) {
const body = ctx.results.map(item => {
const time = Number(item.seconds ?? 0).toFixed(3);
const failure = item.status === "passed" ? "" :
item.status === "blocked"
? `\n <skipped message="${esc(item.failureClass)}: ${esc(item.error)}"/>`
: `\n <failure message="${esc(item.classification)}">${esc(item.error)}</failure>`;
return ` <testcase classname="${esc(item.priority)}" name="${esc(item.id)}" time="${time}">${failure}\n </testcase>`;
});
return `<?xml version="1.0" encoding="UTF-8"?>\n<testsuite name="web-freecad-functional-suite" tests="${ctx.results.length}" failures="${ctx.counts.failed}" skipped="${ctx.counts.blocked}" time="${(ctx.results.reduce((sum, item) => sum + Number(item.seconds ?? 0), 0)).toFixed(3)}">\n${body.join("\n")}\n</testsuite>\n`;
}
export function writeIndex(ctx) {
const rows = ctx.results.map(item => {
const color = item.status === "passed" ? "#137333" : item.status === "blocked" ? "#8a6d00" : "#a50e0e";
return `<tr><td><a href="cases/${esc(item.id)}/">${esc(item.id)}</a></td><td>${esc(item.priority)}</td><td style="color:${color}">${esc(statusCell(item))}</td><td>${Number(item.seconds ?? 0).toFixed(1)}s</td><td>${esc(item.error ? item.error.slice(0, 160) : "")}</td></tr>`;
});
return `<!doctype html><meta charset="utf-8"><title>Web FreeCAD functional suite</title>
<style>body{font:14px/1.5 system-ui,sans-serif;margin:24px}table{border-collapse:collapse}td,th{border:1px solid #ddd;padding:4px 8px;text-align:left}</style>
<h1>Web FreeCAD 功能测试(有头)</h1>
<p>${esc(ctx.startedAt)} · origin ${esc(ctx.origin)} · passed ${ctx.counts.passed} / failed ${ctx.counts.failed} / blocked ${ctx.counts.blocked}</p>
<table><thead><tr><th>id</th><th>优先级</th><th>状态</th><th>耗时</th><th>错误</th></tr></thead><tbody>${rows.join("")}</tbody></table>
<p><a href="report.md">report.md</a> · <a href="results.json">results.json</a> · <a href="junit.xml">junit.xml</a></p>`;
}
export function finalize(ctx) {
persist(ctx);
fs.writeFileSync(path.join(ctx.output, "report.md"), writeMarkdown(ctx));
fs.writeFileSync(path.join(ctx.output, "junit.xml"), writeJUnit(ctx));
fs.writeFileSync(path.join(ctx.output, "index.html"), writeIndex(ctx));
const gaps = renderGapSections(ctx.gaps);
fs.writeFileSync(path.join(ctx.output, "GAPS.md"),
`# Gap ledger\n\n## Blocked (preconditions): ${gaps.counts.blocked}\n\n${gaps.blocked}\n\n## Product regressions/gaps: ${gaps.counts.product}\n\n${gaps.product}\n`);
}
export function pruneRuns(base, keep) {
if (!fs.existsSync(base)) return [];
const dirs = fs.readdirSync(base, { withFileTypes: true })
.filter(entry => entry.isDirectory() && entry.name.startsWith("run-"))
.map(entry => entry.name).sort();
const removed = dirs.slice(0, Math.max(0, dirs.length - keep));
for (const name of removed) fs.rmSync(path.join(base, name), { recursive: true, force: true });
return removed;
}

View File

@@ -0,0 +1,176 @@
// 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;
}

314
tools/layout-probe.mjs Normal file
View File

@@ -0,0 +1,314 @@
#!/usr/bin/env node
/**
* Three-column layout / scroll probe for the built FreeCAD Web dist.
*
* Replaces the throwaway probes written while fixing panel scrolling (plus
* module task panels pushing the centre stage out of the viewport). Every
* pitfall hit back then is baked in here:
* - tools/static-host.mjs is a module, not a CLI: start it via startStaticHost
* (a standalone CLI now exists too, but this tool starts its own host);
* - playwright resolves only from web/node_modules: require it through
* web/package.json, never from /tmp or the repo root;
* - the dist root is resolved inside startStaticHost, so relative roots work
* (before, they made every request answer 403);
* - output is never sliced JSON: the full report goes to --json and the
* console gets a bounded summary.
*
* Per page it measures:
* - page scroll: a height-locked page (html/body overflow hidden) must not
* scroll as a document;
* - side panels: every aside inside the layout stays inside the viewport and
* owns a .pane-scroll that actually scrolls (a spacer is injected first by
* default so sparse pages are measurable);
* - stage stability: injecting panel content and scrolling the panels must
* not move the centre stage (<=1px drift in x/y/width/height). This is the
* exact regression class: a tall Robot/Mesh task panel pushed .layout down
* or collapsed it to a few pixels.
*
* Checks fail the run (exit 1) unless --no-assert; a missing Chrome or dist
* exits 2. Pages with no asides (Start, standalone tools) report the panel
* checks as skipped (null) rather than failing.
*
* Usage
* node tools/layout-probe.mjs
* node tools/layout-probe.mjs --url '/workbench.html?module=Robot' --url /partdesign.html
* node tools/layout-probe.mjs --headed --pause # manual scroll inspection
* node tools/layout-probe.mjs --json /tmp/layout.json --screenshot '/tmp/{page}.png'
* node tools/layout-probe.mjs --origin http://127.0.0.1:46059 # reuse a host
*
* Options
* --url <path> repeatable page path (default: /project.html,
* /partdesign.html, /workbench.html?module=Part|Robot|Mesh)
* --root <dir> dist root to serve (default <repo>/web/dist)
* --origin <url> probe an already running host instead of starting one
* --wait-for <sel> ready selector (default: .layout, .design-layout or .pane-scroll)
* --wait-ms <n> settle time after ready (default 1500)
* --viewport <WxH> default 1440x1000
* --headed show the browser (needs DISPLAY); --slow <ms> adds slowMo
* --pause keep each headed page open until Enter (implies --headed)
* --inject <px> spacer height used to test pane scrolling (default 2000, 0 disables)
* --scroll-test <px> how far each pane is scrolled (default 400)
* --screenshot <path> per-page PNG; "{page}" is replaced by a url slug
* --json <path> write the full report here
* --no-assert always exit 0
*/
import fs from "node:fs";
import path from "node:path";
import { createRequire } from "node:module";
import { fileURLToPath } from "node:url";
import { findChrome, startStaticHost } from "./static-host.mjs";
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
const require = createRequire(path.join(root, "web", "package.json"));
const { chromium } = require("playwright");
const argv = process.argv.slice(2);
const option = (name, fallback) => { const i = argv.indexOf(name); return i >= 0 && i + 1 < argv.length ? argv[i + 1] : fallback; };
const flag = (name) => argv.includes(name);
const urls = [];
for (let i = 0; i < argv.length; i += 1) if (argv[i] === "--url" && i + 1 < argv.length) urls.push(argv[i + 1]);
const DEFAULT_URLS = [
"/project.html",
"/partdesign.html",
"/workbench.html?module=Part",
"/workbench.html?module=Robot",
"/workbench.html?module=Mesh",
];
const pages = urls.length ? urls : DEFAULT_URLS;
const distRoot = path.resolve(option("--root", path.join(root, "web", "dist")));
const externalOrigin = option("--origin", null);
const waitFor = option("--wait-for", ".layout, .design-layout, .pane-scroll");
const waitMs = Number(option("--wait-ms", "1500"));
const [viewportW, viewportH] = option("--viewport", "1440x1000").split("x").map(Number);
const headed = flag("--headed") || flag("--pause");
const slowMo = Number(option("--slow", "0"));
const injectPx = Number(option("--inject", "2000"));
const scrollPx = Number(option("--scroll-test", "400"));
const jsonPath = option("--json", null);
const shotPath = option("--screenshot", null);
const assertOn = !flag("--no-assert");
const slug = (url) => url.replace(/^\//, "").replace(/[^a-zA-Z0-9._-]+/g, "-").replace(/^-+|-+$/g, "") || "index";
const near = (a, b, tol = 1) => Math.abs(a - b) <= tol;
const executablePath = findChrome();
if (!executablePath) { console.error("precondition: Google Chrome not found (set FREECAD_CHROME)"); process.exit(2); }
if (!fs.existsSync(path.join(distRoot, "index.html")) && !fs.existsSync(path.join(distRoot, "project.html"))) {
console.error(`precondition: ${distRoot} is missing a built dist; run npx vite build in web/`);
process.exit(2);
}
let host = null;
const origin = externalOrigin ?? (host = await startStaticHost(distRoot)).origin;
const browser = await chromium.launch({
executablePath,
headless: !headed,
slowMo: slowMo > 0 ? slowMo : undefined,
args: ["--no-sandbox", "--disable-dev-shm-usage", "--use-angle=swiftshader", "--enable-unsafe-swiftshader"],
});
const report = { origin, startedAt: new Date().toISOString(), viewport: { width: viewportW, height: viewportH }, injectPx, scrollPx, pages: [] };
async function probe(url) {
const page = await browser.newPage({ viewport: { width: viewportW, height: viewportH } });
const pageErrors = [];
page.on("pageerror", (error) => { if (pageErrors.length < 20) pageErrors.push(String(error).slice(0, 300)); });
let ready = true;
try {
await page.goto(`${origin}${url}`, { waitUntil: "load", timeout: 60000 });
await page.waitForSelector(waitFor, { timeout: 45000 });
} catch {
ready = false;
}
if (ready && waitMs > 0) await page.waitForTimeout(waitMs);
const diag = await page.evaluate(({ inject, scroll }) => {
const round = (value) => Math.round(value * 10) / 10;
const rect = (element) => {
const r = element.getBoundingClientRect();
return { x: round(r.x), y: round(r.y), w: round(r.width), h: round(r.height), right: round(r.right), bottom: round(r.bottom) };
};
const describe = (element) => ({ tag: element.tagName.toLowerCase(), cls: String(element.className || "").slice(0, 120), rect: rect(element) });
const scrolling = document.scrollingElement || document.documentElement;
const htmlStyle = getComputedStyle(document.documentElement);
const bodyStyle = getComputedStyle(document.body);
const locked = htmlStyle.overflowY === "hidden" || bodyStyle.overflowY === "hidden";
const layout = document.querySelector(".layout, .design-layout");
const stage = document.querySelector(".layout > main, .design-layout > main, .stage");
const asideElements = [...new Set(document.querySelectorAll(".layout > aside, .design-layout > aside, [data-dock-side], .tree-pane, .property-pane"))];
const asideRecords = asideElements.map((aside) => {
const paneElements = [...aside.querySelectorAll(".pane-scroll")];
const containers = paneElements.length
? paneElements
: (getComputedStyle(aside).overflowY !== "visible" ? [aside] : []);
return {
desc: describe(aside),
side: aside.dataset.dockSide ?? null,
panel: aside.dataset.dockPanel ?? null,
source: paneElements.length ? "pane-scroll" : "aside",
panes: containers.map((pane) => ({ element: pane, overflowY: getComputedStyle(pane).overflowY, rect: rect(pane) })),
};
});
const stageBeforeInject = stage ? rect(stage) : null;
const spacers = [];
if (inject > 0) {
for (const aside of asideRecords) for (const pane of aside.panes) {
const spacer = document.createElement("div");
spacer.dataset.layoutProbeSpacer = "1";
spacer.style.cssText = `height:${inject}px;flex:0 0 auto;`;
pane.element.appendChild(spacer);
spacers.push(spacer);
}
void document.body.offsetHeight; // reflow before measuring
}
const stageAfterInject = stage ? rect(stage) : null;
const scrollBefore = window.scrollY;
for (const aside of asideRecords) for (const pane of aside.panes) pane.element.scrollTop = scroll;
const stageAfterScroll = stage ? rect(stage) : null;
const scrollAfter = window.scrollY;
const scrollTops = asideRecords.map((aside) => aside.panes.map((pane) => Math.round(pane.element.scrollTop)));
const asides = asideRecords.map((aside) => ({
...aside.desc,
side: aside.side,
panel: aside.panel,
source: aside.source,
panes: aside.panes.map((pane) => ({
overflowY: pane.overflowY,
rect: pane.rect,
clientH: pane.element.clientHeight,
scrollH: pane.element.scrollHeight,
scrollable: pane.element.scrollHeight > pane.element.clientHeight + 1,
})),
}));
for (const spacer of spacers) spacer.remove();
for (const aside of asideRecords) for (const pane of aside.panes) pane.element.scrollTop = 0;
const shift = (from, to) => (from && to ? { dx: round(to.x - from.x), dy: round(to.y - from.y), dw: round(to.w - from.w), dh: round(to.h - from.h) } : null);
return {
htmlClass: document.documentElement.className,
locked,
viewport: { width: window.innerWidth, height: window.innerHeight },
body: rect(document.body),
doc: { clientH: scrolling.clientHeight, scrollH: scrolling.scrollHeight },
scrollY: { before: scrollBefore, after: scrollAfter },
layout: layout ? describe(layout) : null,
stage: stageAfterInject,
injectShift: shift(stageBeforeInject, stageAfterInject),
scrollShift: shift(stageAfterInject, stageAfterScroll),
scrollTops,
asides,
};
}, { inject: injectPx, scroll: scrollPx });
if (shotPath) {
const target = shotPath.includes("{page}") ? shotPath.replaceAll("{page}", slug(url)) : path.join(shotPath, `${slug(url)}.png`);
fs.mkdirSync(path.dirname(target), { recursive: true });
await page.screenshot({ path: target, fullPage: false });
}
const checks = [];
checks.push({ name: "ready", ok: ready, detail: ready ? undefined : `selector ${JSON.stringify(waitFor)} never appeared` });
if (diag.locked) {
const fits = diag.doc.scrollH <= diag.viewport.height + 1;
checks.push({
name: "page-scroll",
ok: fits && diag.scrollY.after === 0,
detail: `doc ${diag.doc.scrollH}px vs viewport ${diag.viewport.height}px; scrollY ${diag.scrollY.before}->${diag.scrollY.after}`,
});
} else {
checks.push({ name: "page-scroll", ok: null, detail: "page is not height-locked (reference only)" });
}
if (diag.asides.length === 0) {
checks.push({ name: "aside-bounds", ok: null, detail: "no side panels on this page" });
checks.push({ name: "aside-scrolls", ok: null, detail: "no side panels on this page" });
} else {
const outside = diag.asides.filter((aside) => aside.rect.y < -1 || aside.rect.bottom > diag.viewport.height + 1);
checks.push({
name: "aside-bounds",
ok: outside.length === 0,
detail: outside.length ? outside.map((aside) => `${aside.side ?? aside.cls}: y=${aside.rect.y} bottom=${aside.rect.bottom}`).join("; ") : undefined,
});
const unscrollable = diag.asides.filter((aside) => !aside.panes.some((pane) => pane.scrollable && /auto|scroll/.test(pane.overflowY)));
checks.push({
name: "aside-scrolls",
ok: unscrollable.length === 0,
detail: unscrollable.length
? unscrollable.map((aside) => {
const pane = aside.panes[0];
return `${aside.side ?? aside.cls}: ${pane ? `overflowY=${pane.overflowY} ${pane.scrollH}/${pane.clientH}` : "no .pane-scroll"}`;
}).join("; ")
: undefined,
});
}
const stable = (m) => !m || (near(m.dx, 0) && near(m.dy, 0) && near(m.dw, 0) && near(m.dh, 0));
checks.push({
name: "stage-stable",
ok: diag.stage ? stable(diag.injectShift) && stable(diag.scrollShift) : null,
detail: diag.stage
? `inject ${JSON.stringify(diag.injectShift)} scroll ${JSON.stringify(diag.scrollShift)}`
: "no centre stage on this page",
});
await page.close();
const ok = ready && checks.every((check) => check.ok !== false);
return {
url,
ok,
checks,
pageErrors,
htmlClass: diag.htmlClass,
locked: diag.locked,
doc: diag.doc,
layout: diag.layout,
stage: diag.stage,
asides: diag.asides.map(({ panes, ...aside }) => ({ ...aside, panes: panes.length, scrollable: panes.some((pane) => pane.scrollable), firstPane: panes[0] ?? null })),
scrollTops: diag.scrollTops,
};
}
let failures = 0;
for (const url of pages) {
let result;
try {
result = await probe(url);
} catch (error) {
result = { url, ok: false, checks: [{ name: "probe", ok: false, detail: String(error).slice(0, 400) }], pageErrors: [] };
}
if (!result.ok) failures += 1;
report.pages.push(result);
const summary = {
url: result.url,
ok: result.ok,
checks: Object.fromEntries(result.checks.map((check) => [check.name, check.ok === null ? "skip" : check.ok])),
layout: result.layout?.rect ?? null,
stage: result.stage ?? null,
asides: result.asides?.map((aside) => ({ side: aside.side, panel: aside.panel, rect: aside.rect, scrollable: aside.scrollable })),
problems: result.checks.filter((check) => check.ok === false).map((check) => `${check.name}: ${check.detail}`),
pageErrors: result.pageErrors,
};
console.log(JSON.stringify(summary));
if (flag("--pause")) {
await new Promise((resolve) => {
process.stdout.write(`[${url}] inspect the page, then press Enter to continue... `);
process.stdin.once("data", resolve);
});
}
}
await browser.close();
if (host) host.close();
if (jsonPath) {
fs.mkdirSync(path.dirname(path.resolve(jsonPath)), { recursive: true });
fs.writeFileSync(path.resolve(jsonPath), `${JSON.stringify(report, null, 2)}\n`);
console.log(`report=${path.resolve(jsonPath)}`);
}
console.log(`pages=${pages.length} failures=${failures}`);
process.exit(assertOn && failures > 0 ? 1 : 0);

View File

@@ -1,7 +1,15 @@
/** Shared static host + Chrome discovery for browser runners and the MCP session. */
/**
* Shared static host + Chrome discovery for browser runners and the MCP session.
*
* CLI (for probes and for web/tools/manual/capture.mjs --origin):
* node tools/static-host.mjs [--root <dist>] [--port <n>] [--document <file>]
* Prints ORIGIN=http://127.0.0.1:<port> and stays up until killed. --root may
* be relative (to the current directory) or absolute; it is resolved here.
*/
import fs from "node:fs";
import http from "node:http";
import path from "node:path";
import { fileURLToPath } from "node:url";
export const CHROME_CANDIDATES = ["/usr/bin/google-chrome", "/usr/bin/google-chrome-stable", "/opt/google/chrome/google-chrome"];
@@ -16,24 +24,53 @@ export const ISOLATION_HEADERS = {
"cross-origin-embedder-policy": "require-corp",
};
const CONTENT_TYPES = { ".html": "text/html; charset=utf-8", ".js": "text/javascript; charset=utf-8", ".css": "text/css", ".json": "application/json", ".wasm": "application/wasm", ".png": "image/png" };
// Chrome refuses to render <img src="*.svg"> when the response is octet-stream,
// so every type the shell actually loads has to be listed explicitly.
const CONTENT_TYPES = {
".html": "text/html; charset=utf-8", ".js": "text/javascript; charset=utf-8", ".mjs": "text/javascript; charset=utf-8",
".css": "text/css; charset=utf-8", ".json": "application/json", ".wasm": "application/wasm",
".svg": "image/svg+xml", ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".gif": "image/gif",
".webp": "image/webp", ".ico": "image/x-icon", ".woff": "font/woff", ".woff2": "font/woff2", ".ttf": "font/ttf",
".txt": "text/plain; charset=utf-8", ".map": "application/json", ".md": "text/markdown; charset=utf-8",
};
/**
* Serve a built dist directory on an ephemeral loopback port with COOP/COEP.
* Returns { server, origin, close }.
*/
export async function startStaticHost(distRoot, defaultDocument = "index.html") {
if (!fs.existsSync(path.join(distRoot, defaultDocument))) throw new Error(`web/dist/${defaultDocument} is missing; run npm run build first`);
export async function startStaticHost(distRoot, defaultDocument = "index.html", port = 0) {
// Resolve once: with a relative root the traversal guard below compared an
// absolute file path against a relative prefix and answered 403 for every
// request.
const resolvedRoot = path.resolve(distRoot);
if (!fs.existsSync(path.join(resolvedRoot, defaultDocument))) throw new Error(`${resolvedRoot}/${defaultDocument} is missing; run npm run build first`);
const server = http.createServer((request, response) => {
const requestPath = decodeURIComponent(new URL(request.url ?? "/", "http://127.0.0.1").pathname);
if (requestPath === "/favicon.ico") { response.writeHead(204, ISOLATION_HEADERS); response.end(); return; }
const relative = requestPath === "/" ? defaultDocument : requestPath.replace(/^\/+/, "");
const filePath = path.resolve(distRoot, relative);
if (filePath !== distRoot && !filePath.startsWith(`${distRoot}${path.sep}`)) { response.writeHead(403); response.end("forbidden"); return; }
const filePath = path.resolve(resolvedRoot, relative);
if (filePath !== resolvedRoot && !filePath.startsWith(`${resolvedRoot}${path.sep}`)) { response.writeHead(403); response.end("forbidden"); return; }
if (!fs.existsSync(filePath) || !fs.statSync(filePath).isFile()) { response.writeHead(404); response.end("not found"); return; }
response.writeHead(200, { "content-type": CONTENT_TYPES[path.extname(filePath)] ?? "application/octet-stream", "cache-control": "no-store", ...ISOLATION_HEADERS });
fs.createReadStream(filePath).pipe(response);
});
await new Promise((resolve, reject) => { server.once("error", reject); server.listen(0, "127.0.0.1", resolve); });
return { server, origin: `http://127.0.0.1:${server.address().port}`, close: () => server.close() };
await new Promise((resolve, reject) => { server.once("error", reject); server.listen(port, "127.0.0.1", resolve); });
return { server, origin: `http://127.0.0.1:${server.address().port}`, root: resolvedRoot, close: () => server.close() };
}
/* --- CLI ---------------------------------------------------------------- */
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
const argv = process.argv.slice(2);
const option = (name, fallback) => { const i = argv.indexOf(name); return i >= 0 && i + 1 < argv.length ? argv[i + 1] : fallback; };
const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
const distRoot = option("--root", path.join(repoRoot, "web", "dist"));
const document = option("--document", "index.html");
const port = Number(option("--port", "0"));
const host = await startStaticHost(distRoot, document, port);
console.log(`ORIGIN=${host.origin}`);
console.log(`ROOT=${host.root}`);
console.log(`DOCUMENT=${document}`);
const stop = () => { host.close(); process.exit(0); };
process.on("SIGINT", stop);
process.on("SIGTERM", stop);
}

View File

@@ -0,0 +1,98 @@
#!/usr/bin/env node
// Headed Web FreeCAD functional suite.
// node tools/web-freecad-functional-suite.mjs --priority P0
// See tools/functional-suite/cli.mjs for the full option contract.
import fs from "node:fs";
import path from "node:path";
import { parseArgs, selectCases, USAGE } from "./functional-suite/cli.mjs";
import { allCases } from "./functional-suite/cases/index.mjs";
import { createRunContext, finalize, newRunDir, persist, pruneRuns, writeManifest } from "./functional-suite/report.mjs";
import { openBrowser, openPage, resetState, root, runCase, startHost } from "./functional-suite/runtime.mjs";
import { runLegacyCases } from "./functional-suite/executors/legacy.mjs";
const options = parseArgs();
if (options.help) { console.log(USAGE); process.exit(0); }
const selected = selectCases(allCases(), options);
if (!selected.length) { console.error("no cases selected"); process.exit(2); }
const base = options.out ? path.resolve(options.out) : path.join(root, "docs", "current", "web-functional-suite");
const output = newRunDir(base, options.resume);
let previous = [];
if (options.resume) {
const resultsFile = path.join(output, "results.json");
if (fs.existsSync(resultsFile)) {
const payload = JSON.parse(fs.readFileSync(resultsFile, "utf8"));
previous = (payload.results ?? []).filter(item => item.status !== "running");
}
}
const completed = new Map(previous.map(item => [item.id, item]));
let host;
let browser;
let session;
const ctx = createRunContext({ options, root, output, origin: "" });
const shutdown = async () => {
try { await session?.context.close(); } catch { /* already closed */ }
try { await browser?.close(); } catch { /* already closed */ }
try { host?.close(); } catch { /* already closed */ }
};
try {
host = await startHost();
ctx.origin = host.origin;
browser = await openBrowser(options);
session = await openPage(browser, ctx);
ctx.session = session;
writeManifest(ctx, {
chrome: browser.version(),
cases: selected.map(item => ({ id: item.id, priority: item.priority, executor: item.executor })),
disk: { dist: path.relative(root, path.join(root, "web", "dist")) },
});
for (const definition of selected) {
const prior = completed.get(definition.id);
if (prior && !options.force) {
ctx.results.push(prior);
persist(ctx);
console.log(`${definition.id}: skipped (resume, ${prior.status})`);
continue;
}
try {
await resetState(session.page, ctx.origin);
// Errors are a per-case assertion, so previous cases must not leak in.
session.pageErrors.length = 0;
session.consoleErrors.length = 0;
} catch (error) {
// A broken page cannot host the next case; surface it on the case record.
const failed = { id: definition.id, title: definition.title, priority: definition.priority, executor: definition.executor, status: "blocked", classification: "precondition", failureClass: "fixture", steps: [], seconds: 0, error: `resetState failed: ${String(error?.message ?? error)}`, startedAt: new Date().toISOString(), artifacts: {} };
ctx.results.push(failed);
ctx.gaps.push({ caseId: definition.id, status: "blocked", classification: "precondition", failureClass: "fixture", message: failed.error, evidence: "" });
persist(ctx);
console.log(`${definition.id}: blocked (resetState failed)`);
continue;
}
await runCase(session.page, definition, ctx);
}
if (options.legacyIds.length) {
const results = await runLegacyCases(options, ctx, { base });
console.log(`legacy: ${results.length} case(s) imported`);
}
finalize(ctx);
if (options.prune) pruneRuns(base, options.prune);
} catch (error) {
fs.mkdirSync(output, { recursive: true });
fs.writeFileSync(path.join(output, "fatal.json"), `${JSON.stringify({ at: new Date().toISOString(), error: String(error?.stack ?? error) }, null, 2)}\n`);
console.error(`fatal: ${String(error?.message ?? error)}`);
process.exitCode = 1;
} finally {
await shutdown();
}
const counts = ctx.counts;
console.log(JSON.stringify({ output, counts, gaps: ctx.gaps.length }));
if (counts.failed > 0 || counts.running > 0) process.exitCode = 1;