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 };