The teaching console now lives inside Web FreeCAD: web/teaching-console.html hosts the workbench in a same-origin iframe and drives its DOM directly, with no Node server and no spawned Chrome. The driver modules run in the framed page's own realm (bridge.ts publishes window.__teaching), so the proven driver/assembly code is reused unchanged and the CSP without 'unsafe-eval' is never crossed. - steps.ts globs both courses' ui-steps records (skipping their index.json manifests) so each lesson downloads only its own chunk - runner.ts checks prerequisites in dependency order, then runs part or assembly lessons; a pass stores the FCStd in OPFS freecad-documents under the course document name, which is what assembly lessons consume - assembly lessons insert, joint, solve and save through lib/assembly.mjs; insertLink falls back to UI-suffixed object names (Body1 for Body) - check-inapp-console.mjs (npm run check:console-inapp) is green: preflight, P01 volume within 6e-13, OPFS evidence, both viewports - run-inapp-lessons.mjs runs a whole course in one browser; reducer 23 parts + assembly and carrier 20 parts + assembly all pass in-browser Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
210 lines
9.4 KiB
JavaScript
210 lines
9.4 KiB
JavaScript
#!/usr/bin/env node
|
||
/**
|
||
* Browser gate for the in-app teaching console (web/teaching-console.html).
|
||
*
|
||
* Proves the console drives the real workbench by itself: no teaching Node
|
||
* server, no spawned Chrome, no /api/console/* traffic. It opens the built page
|
||
* from an ordinary static server, waits for the iframe to publish its bridge,
|
||
* runs 环境自检, then builds P01 (Gear2_80T) inside the iframe and checks the
|
||
* report the run wrote to OPFS.
|
||
*
|
||
* Assertions:
|
||
* - the console lists all 48 in-app lessons with the generated counts;
|
||
* - the run button stays disabled until the iframe bridge answers;
|
||
* - 环境自检 → verdict pass, at least four prerequisite rows green;
|
||
* - P01 → verdict pass, 4/4 steps, volume within the replay tolerance;
|
||
* - the report lands in OPFS freecad-exports and parses as in-app-run/v1;
|
||
* - body[data-runner-state] mirrors the verdict;
|
||
* - no page errors, no horizontal overflow at 1440×900 and 390×844.
|
||
*
|
||
* Prerequisites (checked first, in this order): playwright resolvable from
|
||
* web/node_modules, then a running static server serving this build. Either
|
||
* missing is exit 2 -- a prerequisite failure, never a product failure.
|
||
*
|
||
* Usage: node web/tools/teaching-console/check-inapp-console.mjs [--quick]
|
||
* --quick stop after 环境自检 (skips the P01 build)
|
||
*/
|
||
import path from "node:path";
|
||
import { createRequire } from "node:module";
|
||
import { fileURLToPath } from "node:url";
|
||
|
||
const HERE = path.dirname(fileURLToPath(import.meta.url));
|
||
const REPO = path.resolve(HERE, "../../..");
|
||
const require = createRequire(path.join(REPO, "web/package.json"));
|
||
const BASE = process.env.TEACHING_BASE ?? "http://127.0.0.1:5183";
|
||
const QUICK = process.argv.includes("--quick");
|
||
const VERDICTS = ["pass", "fail", "blocked", "cancelled"];
|
||
|
||
const failures = [];
|
||
const note = (message) => { failures.push(message); console.error(`FAIL ${message}`); };
|
||
const ok = (message) => { console.log(`ok ${message}`); };
|
||
|
||
let chromium;
|
||
try {
|
||
({ chromium } = require("playwright"));
|
||
} catch {
|
||
console.error("前置缺失:web/node_modules 下没有 playwright");
|
||
process.exit(2);
|
||
}
|
||
|
||
const served = await fetch(`${BASE}/teaching-console.html`).then(response => response.ok, () => false);
|
||
if (!served) {
|
||
console.error(`前置缺失:${BASE} 上没有 teaching-console.html`);
|
||
console.error("先在本机构建并预览:npx vite build && npx vite preview --port 5183");
|
||
process.exit(2);
|
||
}
|
||
|
||
/** The report a run wrote, straight out of OPFS, plus the name it used. */
|
||
const READ_OPFS_REPORT = async (prefix) => {
|
||
const root = await navigator.storage.getDirectory();
|
||
let dir;
|
||
try {
|
||
dir = await root.getDirectoryHandle("freecad-exports");
|
||
} catch {
|
||
return null; // nothing has been written yet
|
||
}
|
||
const names = [];
|
||
for await (const [name] of dir.entries()) if (name.startsWith(prefix)) names.push(name);
|
||
names.sort();
|
||
if (!names.length) return null;
|
||
const file = await (await dir.getFileHandle(names.at(-1))).getFile();
|
||
return { name: names.at(-1), text: await file.text() };
|
||
};
|
||
|
||
const badgeText = (page) => page.locator(".tc-badge").textContent().then(text => (text ?? "").trim());
|
||
|
||
async function waitForBridge(page) {
|
||
await page.waitForFunction(() => {
|
||
const button = [...document.querySelectorAll("button")].find(item => item.textContent?.includes("运行本课"));
|
||
return Boolean(button && !button.disabled);
|
||
}, null, { timeout: 240000 });
|
||
}
|
||
|
||
async function runSelected(page, timeout) {
|
||
await waitForBridge(page);
|
||
await page.getByRole("button", { name: "运行本课" }).click();
|
||
await page.waitForFunction(
|
||
() => (document.querySelector(".tc-badge")?.textContent ?? "").includes("运行中"),
|
||
null,
|
||
{ timeout: 60000 },
|
||
);
|
||
await page.waitForFunction(
|
||
verdicts => verdicts.includes((document.querySelector(".tc-badge")?.textContent ?? "").trim()),
|
||
VERDICTS,
|
||
{ timeout },
|
||
);
|
||
return badgeText(page);
|
||
}
|
||
|
||
const browser = await chromium.launch({ headless: true, args: ["--no-sandbox", "--disable-dev-shm-usage"] });
|
||
const page = await browser.newPage({ viewport: { width: 1440, height: 900 } });
|
||
const pageErrors = [];
|
||
page.on("pageerror", error => pageErrors.push(String(error)));
|
||
|
||
try {
|
||
await page.goto(`${BASE}/teaching-console.html`, { waitUntil: "load" });
|
||
await page.waitForSelector(".teaching-console", { timeout: 60000 });
|
||
|
||
const lessons = await page.locator(".tc-item").count();
|
||
if (lessons !== 48) note(`课程列表应有 48 课,实际 ${lessons}`);
|
||
else ok(`课程列表 ${lessons} 课`);
|
||
|
||
const counts = (await page.locator(".tc-count").textContent() ?? "").trim();
|
||
if (counts !== "48 课 · 45 件 · 328 步") note(`页头计数不对:${counts}`);
|
||
else ok(`页头计数 ${counts}`);
|
||
|
||
// 1. 环境自检: prerequisites run in the iframe, nothing is asserted yet.
|
||
await page.locator(".tc-item").first().click();
|
||
const preflightVerdict = await runSelected(page, 300000);
|
||
if (preflightVerdict !== "pass") {
|
||
const reason = (await page.locator(".tc-reason").textContent() ?? "").trim();
|
||
note(`环境自检判定 ${preflightVerdict}:${reason}`);
|
||
} else {
|
||
const green = await page.locator(".tc-checks .tc-ok").count();
|
||
if (green < 4) note(`环境自检通过但只有 ${green} 项前置为绿`);
|
||
else ok(`环境自检通过,${green} 项前置全绿`);
|
||
}
|
||
|
||
await page.waitForFunction(
|
||
() => document.body.innerText.includes("teaching-lesson-00-preflight-"),
|
||
null,
|
||
{ timeout: 60000 },
|
||
).catch(() => note("环境自检的报告名没有出现在证据栏"));
|
||
const preflightReport = await page.evaluate(READ_OPFS_REPORT, "teaching-lesson-00-preflight-");
|
||
if (!preflightReport) note("OPFS freecad-exports 里没有环境自检报告");
|
||
else {
|
||
const parsed = JSON.parse(preflightReport.text);
|
||
if (parsed.schema !== "freecad-web/teaching-console/in-app-run/v1") note(`环境自检报告 schema 不对:${parsed.schema}`);
|
||
if (parsed.verdict !== "pass") note(`环境自检报告 verdict=${parsed.verdict}:${parsed.reason}`);
|
||
else ok(`证据 ${preflightReport.name}(verdict pass)`);
|
||
}
|
||
|
||
const state = await page.locator("body").getAttribute("data-runner-state");
|
||
if (state !== "pass") note(`body[data-runner-state]=${state},应为 pass`);
|
||
else ok("body[data-runner-state] 与判定一致");
|
||
|
||
// 2. P01 in the browser: a real part, built by clicking the real UI.
|
||
if (!QUICK) {
|
||
await page.locator(".tc-item", { hasText: "P01" }).first().click();
|
||
// runSelected() waits for the fresh frame's bridge itself; nothing to add here.
|
||
const partVerdict = await runSelected(page, 900000);
|
||
if (partVerdict !== "pass") {
|
||
const reason = (await page.locator(".tc-reason").textContent() ?? "").trim();
|
||
note(`P01 判定 ${partVerdict}:${reason}`);
|
||
} else {
|
||
// The table only mounts on its tab; the console opens on the log tab.
|
||
await page.getByRole("tab", { name: /结果表/ }).click();
|
||
const rows = await page.locator(".tc-table tbody tr").count();
|
||
if (rows !== 4) note(`P01 结果表应有 4 行,实际 ${rows}`);
|
||
else ok("P01 通过,4/4 步");
|
||
}
|
||
|
||
const partReport = await page.evaluate(READ_OPFS_REPORT, "teaching-lesson-reducer-p01-");
|
||
if (!partReport) note("OPFS 里没有 P01 报告");
|
||
else {
|
||
const parsed = JSON.parse(partReport.text);
|
||
const mismatched = parsed.results.filter(row => row.volumeMatches === false);
|
||
if (parsed.verdict !== "pass") note(`P01 报告 verdict=${parsed.verdict}:${parsed.reason}`);
|
||
else if (parsed.failed !== 0) note(`P01 报告有 ${parsed.failed} 步失败`);
|
||
else if (mismatched.length) note(`P01 有 ${mismatched.length} 步体积不符`);
|
||
else if (!(parsed.relativeError < 1e-6)) note(`P01 相对误差 ${parsed.relativeError} 超出容差`);
|
||
else ok(`证据 ${partReport.name}:体积 ${parsed.volume} / 期望 ${parsed.expected},相对误差 ${parsed.relativeError.toExponential(2)}`);
|
||
}
|
||
|
||
// The assembly lessons take their parts from OPFS freecad-documents, so a
|
||
// passing part lesson must leave its document there under the course name.
|
||
const documents = await page.evaluate(async () => {
|
||
const root = await navigator.storage.getDirectory();
|
||
try {
|
||
const dir = await root.getDirectoryHandle("freecad-documents");
|
||
const names = [];
|
||
for await (const [name] of dir.entries()) names.push(name);
|
||
return names.sort();
|
||
} catch { return []; }
|
||
});
|
||
if (documents.includes("Gear2_80T.FCStd")) ok("P01 文档已存入 OPFS freecad-documents(Gear2_80T.FCStd)");
|
||
else note(`OPFS freecad-documents 里没有 Gear2_80T.FCStd(现有 ${documents.join("、") || "无"})`);
|
||
}
|
||
|
||
for (const viewport of [{ width: 1440, height: 900 }, { width: 390, height: 844 }]) {
|
||
await page.setViewportSize(viewport);
|
||
await page.waitForTimeout(300);
|
||
const overflow = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth);
|
||
if (overflow > 0) note(`${viewport.width}px 下横向溢出 ${overflow}px`);
|
||
else ok(`${viewport.width}×${viewport.height} 无横向溢出`);
|
||
}
|
||
|
||
if (pageErrors.length) note(`页面错误 ${pageErrors.length} 条:${pageErrors[0]}`);
|
||
else ok("无页面错误");
|
||
} catch (error) {
|
||
note(`异常:${error instanceof Error ? error.message : String(error)}`);
|
||
} finally {
|
||
await browser.close();
|
||
}
|
||
|
||
if (failures.length) {
|
||
console.error(`\n${failures.length} 项未通过`);
|
||
process.exit(1);
|
||
}
|
||
console.log("\n教学控制台:全部通过");
|