Files
FreeCADWasmDev/web/tools/cad-ui-rebuild/drive.mjs
wangdequan 87b2a6cb8a feat(carrier): 航空母舰 PartDesign 有头创建工具包与初学者教学
- 新数据链 web/teaching/cases/carrier-partdesign:20 件零件(spec.json 唯一来源)、
  内核建造器 parts/*.mjs、traces/FCStd/replay 全量产物;装配 20 插入 + 19 关节。
- 工具包 tools/carrier:catalog / preflight / create-part / create-assembly /
  create-all / list / self-test / README,按零件与装配拆分为独立工具。
- 共享驱动扩展 web/tools/cad-ui-rebuild:Loft/Pipe/Hole/Fillet/Chamfer/Mirrored/
  LinearPattern 交互,Reversed 复选框补齐;装配 saveAssemblyBundle 先 Accept 再保存。
- 教学:lessons.mjs 新增 carrier 组(环境课 + 20 件 + 装配),suite-runner 增加
  carrier-part/carrier-assembly,生成 carrier-toolkit.html 并接入 index 与控制台证据。

验证:20 件 210 步全部有头通过(P05 修复后 39640 m³;P06 回归 8/8);
装配 20/20 插入、19/19 关节、20 组件 0 畸形、0 mismatch;check:carrier、
check:reducer、check-console --live 全绿。

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-25 18:46:27 +08:00

180 lines
8.8 KiB
JavaScript

#!/usr/bin/env node
// Drive the real Web FreeCAD UI to rebuild one part, capturing a screenshot per step.
//
// Usage: node drive.mjs --project <dir> <partId|document> [--headed] [--slow]
// Evidence: <outDir>/ui-run/<document>.json
// <stillsDir>/<partId>/<scene>.png
import fs from "node:fs";
import path from "node:path";
import { createRequire } from "node:module";
import { fileURLToPath } from "node:url";
import { loadProject, projectFromArgv, readJson, replayPath } from "./manifest.mjs";
import { PAGE, waitForWorkspace, newDocumentWithBody, runStep, tipVolume, selectTip } from "./lib/driver.mjs";
import { readReplay } from "./lib/replay.mjs";
import { stillName } from "./lib/stills.mjs";
const here = path.dirname(fileURLToPath(import.meta.url));
const webRoot = path.resolve(here, "../..");
const require = createRequire(path.join(webRoot, "package.json"));
const { chromium } = require("playwright");
const projectDir = projectFromArgv();
const project = loadProject(projectDir, { requireParts: true });
const args = process.argv.slice(2);
// Skip the value that belongs to --project; it may be a directory or a manifest
// file, and either way it is not a part id.
const projectArg = args[args.indexOf("--project") + 1];
const key = args.find(value => !value.startsWith("--") && value !== projectArg
&& args[args.indexOf(value) - 1] !== "--project");
if (!key) throw new Error("usage: drive.mjs --project <dir> <partId> [--headed] [--slow]");
const part = project.parts.find(item => item.id === key || item.document === key);
if (!part) throw new Error(`project ${project.name} has no part "${key}"`);
const headed = args.includes("--headed");
const slow = args.includes("--slow") ? 350 : 0;
const stepsFile = path.join(project.paths.stepsDir, `${part.document}.json`);
if (!fs.existsSync(stepsFile)) {
throw new Error(`no ui-steps for ${part.document}; run build-steps.mjs --project ${projectDir} first`);
}
const uiSteps = JSON.parse(fs.readFileSync(stepsFile, "utf8"));
const replayFile = replayPath(project, part.document);
if (!fs.existsSync(replayFile)) throw new Error(`no replay for ${part.document} in ${project.paths.replayDir}`);
const replay = readReplay(replayFile);
const stillsDir = path.join(project.paths.stillsDir, part.id);
fs.mkdirSync(stillsDir, { recursive: true });
fs.mkdirSync(project.paths.runDir, { recursive: true });
/**
* Internal names of every tree row: the workspace's own object names.
*
* The tree pane sizes its viewport to the full row list (`document-tree.tsx`),
* so every row stays mounted and a single read sees them all.
*/
async function internalNames(page) {
const visible = await page.locator('[role="treeitem"] .fc-tree-col-internal').allTextContents();
return [...new Set(visible.map(name => name.trim()).filter(Boolean))];
}
/**
* Wait for the workspace to finish a native transaction and publish it.
*
* `edit()` in the workspace renders "计算中..." while the kernel request is in
* flight and only swaps `documents[document]` afterwards, so a heavy feature
* (a chamfer over 180 deck edges takes tens of seconds) has no tree row yet
* when the click handler returns. Poll until the row count exceeds `minimum`
* and the busy status has cleared.
*/
async function waitForRows(page, minimum, timeout = 240000) {
const deadline = Date.now() + timeout;
let count = 0;
const busy = () => page.evaluate(() => [...document.querySelectorAll('[role="status"]')]
.some(node => (node.textContent ?? "").includes("计算中")));
while (Date.now() < deadline) {
count = await page.locator('[role="treeitem"]').count();
if (count >= minimum && !(await busy())) return count;
await page.waitForTimeout(250);
}
throw new Error(`model tree stayed at ${count} rows (wanted >= ${minimum}) for ${timeout} ms`);
}
const browser = await chromium.launch({
executablePath: "/usr/bin/google-chrome", headless: !headed,
args: ["--no-sandbox", "--disable-dev-shm-usage", "--enable-unsafe-swiftshader", "--use-gl=angle", "--use-angle=swiftshader"],
});
const page = await browser.newPage({ viewport: { width: 1600, height: 900 } });
const errors = [];
page.on("pageerror", error => errors.push(String(error).slice(0, 300)));
page.on("console", message => { if (message.type() === "error") errors.push(message.text().slice(0, 300)); });
const results = [];
const uiNames = new Map();
const started = Date.now();
try {
await page.goto(`${project.appOrigin}/${PAGE}`, { waitUntil: "domcontentloaded", timeout: 180000 });
await waitForWorkspace(page);
await newDocumentWithBody(page);
for (const [index, step] of uiSteps.steps.entries()) {
const name = stillName(project, part, index, uiSteps.steps);
const t0 = Date.now();
let status = "ok";
try {
// The workspace names objects itself (Sketch1, Pad1 …), so a later step's
// profile/sections/base/originals must be translated to the UI's name.
const resolved = { ...step };
// Every reference must resolve. A name that no earlier step recorded means
// the plan is wrong; failing here beats letting the driver pick a default.
const renamed = name => {
if (uiNames.has(name)) return uiNames.get(name);
throw new Error(`no UI object recorded for ${name}`);
};
if (resolved.profile) resolved.profile = renamed(resolved.profile);
if (resolved.base) resolved.base = renamed(resolved.base);
if (Array.isArray(resolved.sections) && resolved.sections.length) {
resolved.sections = resolved.sections.map(section => (typeof section === "string" ? renamed(section) : section));
}
if (Array.isArray(resolved.originals) && resolved.originals.length) {
resolved.originals = resolved.originals.map(renamed);
}
const before = new Set(await internalNames(page));
const rowsBefore = await page.locator('[role="treeitem"]').count();
await runStep(page, resolved);
await waitForRows(page, rowsBefore + 1);
// The workspace names objects itself (Sketch1, Pad7, Chamfer1 …). The new
// row's internal name is the object name the reference selects expect, and
// later steps address this object by the kernel's name, so record the pair.
const created = (await internalNames(page)).filter(name => !before.has(name));
if (created.length !== 1) throw new Error(`expected one new object, saw [${created.join(", ")}]`);
uiNames.set(step.object, created[0]);
} catch (error) {
status = `fail: ${error instanceof Error ? error.message.slice(0, 240) : String(error)}`;
}
if (slow) await page.waitForTimeout(slow);
await page.screenshot({ path: path.join(stillsDir, `${name}.png`) });
await selectTip(page);
const volume = await tipVolume(page);
const expectedVolume = replay.steps[index]?.volume ?? null;
const match = volume != null && expectedVolume
? Math.abs(volume - expectedVolume) / Math.abs(expectedVolume) < 1e-6 : null;
results.push({ step: step.step, label: step.label, kind: step.kind, command: step.command,
uiName: step.kind === "sketch" ? uiNames.get(step.object) ?? null : null,
volume, expectedVolume, volumeMatches: match, status, ms: Date.now() - t0 });
if (status !== "ok") break;
}
await selectTip(page);
const volume = await tipVolume(page);
const expected = replay.steps.at(-1)?.volume ?? null;
const relative = volume != null && expected ? Math.abs(volume - expected) / Math.abs(expected) : null;
const report = {
schema: "freecad-web-cad-ui-rebuild/ui-run/v1",
generatedAt: new Date().toISOString(),
project: project.name,
episode: part.id, document: part.document,
steps: results.length, stepsTotal: uiSteps.steps.length,
failed: results.filter(item => item.status !== "ok").length,
volume, expected, relativeError: relative,
volumeMatches: relative != null && relative < 1e-6,
seconds: (Date.now() - started) / 1000,
pageErrors: errors.slice(-10), results,
};
fs.writeFileSync(path.join(project.paths.runDir, `${part.document}.json`), `${JSON.stringify(report, null, 2)}\n`);
console.log(JSON.stringify({ episode: part.id, steps: report.steps, failed: report.failed,
volume, expected, relativeError: relative, volumeMatches: report.volumeMatches,
seconds: Math.round(report.seconds), pageErrors: report.pageErrors.length }));
process.exitCode = report.failed === 0 && report.steps === report.stepsTotal ? 0 : 1;
} catch (error) {
fs.writeFileSync(path.join(project.paths.runDir, `${part.document}.json`), `${JSON.stringify({
schema: "freecad-web-cad-ui-rebuild/ui-run/v1", project: project.name,
episode: part.id, document: part.document,
fatal: String(error).slice(0, 800), results, pageErrors: errors.slice(-10),
}, null, 2)}\n`);
console.error(JSON.stringify({ fatal: String(error).slice(0, 400), pageErrors: errors.slice(-5) }));
process.exitCode = 1;
} finally {
await browser.close();
}