teaching: run lessons in-app through an iframe-driven console

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>
This commit is contained in:
2026-11-26 09:18:26 +08:00
parent 3a3077c089
commit fd37b92fd9
22 changed files with 7165 additions and 14 deletions

View File

@@ -10,8 +10,9 @@
// Ordering matters and is not obvious: the first inserted link becomes the
// grounded anchor, so the ground part must be inserted first, before anything
// else. `orderedInserts` enforces that.
import fs from "node:fs";
import path from "node:path";
// No Node imports here on purpose: this module is also loaded inside the
// teaching console's workbench frame, where `document` is the real workspace.
// Filesystem reporting lives in `assembly-report.mjs`.
/** Sort inserts so the ground part comes first, keeping the rest in authored order. */
export function orderedInserts(inserts, groundDocument) {
@@ -102,9 +103,22 @@ export async function insertLink(page, { sourceDocument, sourceObject, position,
// documents (`Body` exists in every reducer part), so the bare object name
// cannot be used as the value -- the task would always resolve to whichever
// document was opened first.
const key = `${sourceDocument}:${sourceObject}`;
let key = `${sourceDocument}:${sourceObject}`;
const values = await objectSelect.evaluate(node => [...node.options].map(option => option.value));
if (!values.includes(key)) throw new Error(`source object ${key} not among ${values.join(", ")}`);
if (!values.includes(key)) {
// Documents built through the workbench UI suffix their object names --
// its `unique()` always yields `Body1`, `Sketch1`, … -- while the course
// data was captured from kernel-built reference files that use the bare
// names (`Body`). Fall back to the lowest suffixed match so one replay
// drives both kinds of source document.
const escaped = key.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const suffixed = values
.map(value => ({ value, index: Number(new RegExp(`^${escaped}(\\d+)$`).exec(value)?.[1] ?? NaN) }))
.filter(entry => Number.isFinite(entry.index))
.sort((a, b) => a.index - b.index);
if (suffixed.length) key = suffixed[0].value;
}
if (!values.includes(key)) throw new Error(`source object ${sourceDocument}:${sourceObject} not among ${values.join(", ")}`);
await objectSelect.selectOption(key);
for (const [index, axis] of ["X", "Y", "Z"].entries()) {
@@ -135,6 +149,9 @@ export async function acceptLinks(page) {
/**
* Insert every link in the planned order, loading each source document once.
* Returns per-insert evidence so the caller can assert rotation was preserved.
* @param {unknown} page
* @param {Array<{sourceDocument: string, sourceObject: string, position: number[], rotation: number[]}>} inserts
* @param {{groundDocument?: string | null, loadOne?: (page: unknown, fileName: string) => Promise<void>}} [options]
*/
export async function insertAll(page, inserts, { groundDocument, loadOne = loadSource } = {}) {
const ordered = orderedInserts(inserts, groundDocument);
@@ -226,7 +243,11 @@ export async function solveAssembly(page, step) {
* manifest `<documentId>.assembly.json` through writeRawStep (`freecad-1-2`),
* so both stores are checked here.
*/
export async function saveAssemblyBundle(page, { document, timeout = 300000 }) {
// The option is `documentId`, not `document`: the callbacks below run through
// `page.waitForFunction`, and in the in-app console they execute in this very
// scope. A parameter named `document` would shadow the page's global `document`
// there and turn `document.querySelector` into a call on a string.
export async function saveAssemblyBundle(page, { document: documentId, timeout = 300000 }) {
const section = page.locator('section[aria-label="Bill of materials task"]');
await section.waitFor({ timeout: 120000 });
const save = section.getByRole("button", { name: "Save FCStd", exact: true }).first();
@@ -266,13 +287,5 @@ export async function saveAssemblyBundle(page, { document, timeout = 300000 }) {
const steps = await list("freecad-1-2");
const manifest = `${documentId}.assembly.json`;
return { files: documents, manifest, manifestStored: steps.includes(manifest) };
}, document);
}
/** Persist the assembly report next to the run evidence. */
export function writeAssemblyReport(runDir, document, report) {
fs.mkdirSync(runDir, { recursive: true });
const file = path.join(runDir, `${document}-assembly.json`);
fs.writeFileSync(file, `${JSON.stringify(report, null, 2)}\n`);
return file;
}, documentId);
}

View File

@@ -0,0 +1,150 @@
#!/usr/bin/env node
// Generate the small data files the in-app teaching console bundles.
//
// The console runs inside the browser, so it cannot read `tools/**/out/**` or
// the 9.4 MB replays at run time. Everything it needs to *name* and *judge* a
// lesson -- which document, how many steps, the reference volume after each
// step, and the assembly placement numbers -- is extracted here into two
// committed JSON files under `src/teaching/generated/`.
//
// The step files are not copied: `src/teaching/steps.ts` globs them straight
// out of the course directories, so they keep exactly one home in the repo.
//
// Usage: node tools/teaching-console/build-inapp-data.mjs [--check]
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { loadCatalog } from "./catalog.mjs";
import { buildLessons } from "./lessons.mjs";
import { loadProject, replayPath } from "../cad-ui-rebuild/manifest.mjs";
const here = path.dirname(fileURLToPath(import.meta.url));
const webRoot = path.resolve(here, "../..");
const generatedDir = path.join(webRoot, "src/teaching/generated");
/** Lesson kinds the browser can run. Everything else needs Node (suites). */
const IN_APP_KINDS = new Set(["preflight", "carrier-part", "carrier-assembly", "reducer-part", "reducer-assembly"]);
const PROJECTS = {
carrier: "tools/carrier-partdesign-course",
reducer: "tools/reducer-parts-course",
};
function readJson(file) {
return JSON.parse(fs.readFileSync(file, "utf8"));
}
/** The volumes the replay recorded after each step: the reference to judge against. */
function stepVolumes(replayFile) {
const replay = readJson(replayFile);
return replay.steps.map(step => (typeof step?.volume === "number" ? step.volume : null));
}
/**
* One lesson, as the console needs it at run time.
*
* `document` and `steps` are what the runner loads and how many rows to expect;
* `volumes` is the per-step reference. A `null` entry means the replay recorded
* no volume for that step, so the runner compares nothing there.
*/
function resolveJob(job, projects) {
if (job.kind === "preflight") return { kind: "preflight" };
const project = projects[job.kind.startsWith("carrier") ? "carrier" : "reducer"];
if (job.kind.endsWith("-part")) {
const part = project.parts.find(item => item.id === job.partId);
if (!part) throw new Error(`${project.name} has no part ${job.partId}`);
const stepsFile = path.join(project.paths.stepsDir, `${part.document}.json`);
if (!fs.existsSync(stepsFile)) throw new Error(`missing ui-steps ${stepsFile}`);
const uiSteps = readJson(stepsFile);
return {
kind: job.kind,
partId: part.id,
document: part.document,
title: part.title,
page: uiSteps.steps[0]?.page ?? "partdesign.html",
steps: uiSteps.steps.length,
volumes: stepVolumes(replayPath(project, part.document)),
};
}
// Assembly: the runner inserts what the replay recorded, in replay order.
const assembly = project.assembly;
if (!assembly) throw new Error(`${project.name} has no assembly block`);
const replay = readJson(replayPath(project, assembly.document, { assembly: true }));
const inserts = replay.steps.filter(step => step.insert).map(step => step.insert);
if (!inserts.length) throw new Error(`${project.name} assembly replay has no insertions`);
return {
kind: job.kind,
document: assembly.document,
title: assembly.label ?? assembly.document,
page: project.pages.assembly,
groundDocument: assembly.groundDocument ?? inserts[0]?.sourceDocument ?? null,
saveBundle: Boolean(assembly.saveBundle),
sourceDocuments: [...new Set(inserts.map(item => item.sourceDocument))],
inserts,
joints: replay.steps
.filter(step => typeof step.action === "string" && step.action.startsWith("Assembly_CreateJoint"))
.map(step => ({ action: step.action, args: step.args ?? null })),
solves: replay.steps
.filter(step => step.action === "Assembly_SolveAssembly")
.map(step => ({ action: step.action, args: step.args ?? null })),
bom: replay.steps
.filter(step => step.action === "Assembly_CreateBom")
.map(step => ({ action: step.action, args: step.args ?? null })),
};
}
function build() {
const projects = Object.fromEntries(Object.entries(PROJECTS)
.map(([name, dir]) => [name, loadProject(path.join(webRoot, dir), { requireParts: true })]));
const curriculum = buildLessons(loadCatalog());
const groups = curriculum.groups.filter(group => ["basics", "carrier", "reducer"].includes(group.id));
const lessons = curriculum.lessons
.filter(lesson => IN_APP_KINDS.has(lesson.job?.kind))
.map(lesson => ({
id: lesson.id,
groupId: lesson.groupId,
title: lesson.title,
level: lesson.level,
durationMin: lesson.durationMin,
summary: lesson.summary,
sees: lesson.sees ?? [],
expect: lesson.expect,
job: resolveJob(lesson.job, projects),
}));
// Both preflight lessons point at the same check; the console keeps one.
const preflight = lessons.find(lesson => lesson.job.kind === "preflight");
const kept = [preflight, ...lessons.filter(lesson => lesson !== preflight)].filter(Boolean);
return {
schema: "freecad-web/teaching-console/in-app/v1",
groups,
lessons: kept,
counts: {
lessons: kept.length,
parts: kept.filter(lesson => lesson.job.kind.endsWith("-part")).length,
assemblies: kept.filter(lesson => lesson.job.kind.endsWith("-assembly")).length,
steps: kept.reduce((sum, lesson) => sum + (lesson.job.steps ?? 0), 0),
},
};
}
function serialize(value) {
return `${JSON.stringify(value, null, 1)}\n`;
}
const data = build();
const file = path.join(generatedDir, "lessons.json");
const text = serialize(data);
if (process.argv.includes("--check")) {
const current = fs.existsSync(file) ? fs.readFileSync(file, "utf8") : "";
if (current !== text) {
console.error(`in-app lesson data is stale: ${path.relative(webRoot, file)}`);
console.error("run: node tools/teaching-console/build-inapp-data.mjs");
process.exit(1);
}
console.log(`in-app lesson data is current (${data.counts.lessons} lessons, ${data.counts.steps} steps)`);
} else {
fs.mkdirSync(generatedDir, { recursive: true });
fs.writeFileSync(file, text);
console.log(JSON.stringify({ file: path.relative(webRoot, file), ...data.counts }));
}

View File

@@ -0,0 +1,209 @@
#!/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教学控制台:全部通过");

View File

@@ -0,0 +1,138 @@
#!/usr/bin/env node
/**
* Run a group of in-app lessons through the console, in lesson order, in one
* browser. Unlike check-inapp-console.mjs this is not a gate: it is the batch
* driver for a whole course (reducer parts + assembly, carrier parts +
* assembly), so the console is exercised the way a teacher would use it.
*
* Every lesson runs in the same browser instance, so the OPFS documents a part
* lesson saves are exactly what the following assembly lesson consumes. A fresh
* launch starts from an empty OPFS; that is expected, not a failure.
*
* Output is one line per lesson; evidence stays in OPFS (`freecad-exports` for
* reports, `freecad-documents` for the parts).
*
* Usage:
* node web/tools/teaching-console/run-inapp-lessons.mjs --group reducer
* node web/tools/teaching-console/run-inapp-lessons.mjs --lessons lesson-reducer-p01,lesson-reducer-assembly
* --base <url> static server (default http://127.0.0.1:5183)
* --timeout <s> per lesson (default 900; assembly gets 2400)
* --profile <dir> keep the browser profile, so OPFS survives between runs
* (a fresh launch otherwise starts with an empty OPFS, and
* an assembly lesson then has no parts to consume)
*/
import path from "node:path";
import { createRequire } from "node:module";
import { fileURLToPath, pathToFileURL } 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 = arg("--base") ?? process.env.TEACHING_BASE ?? "http://127.0.0.1:5183";
const VERDICTS = ["pass", "fail", "blocked", "cancelled"];
function arg(name) {
const index = process.argv.indexOf(name);
return index >= 0 ? process.argv[index + 1] : undefined;
}
const data = JSON.parse(await (await import("node:fs/promises")).readFile(
path.join(REPO, "web/src/teaching/generated/lessons.json"), "utf8"));
const byId = new Map(data.lessons.map(lesson => [lesson.id, lesson]));
const requested = arg("--lessons")?.split(",").map(id => id.trim()).filter(Boolean);
const group = arg("--group");
const ids = requested ?? (group
? data.lessons.filter(lesson => lesson.groupId === group).map(lesson => lesson.id)
: []);
if (!ids.length) {
console.error("用法:--group <groupId> 或 --lessons <id,id,…>");
process.exit(2);
}
const unknown = ids.filter(id => !byId.has(id));
if (unknown.length) {
console.error(`未知课程:${unknown.join("、")}`);
process.exit(2);
}
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);
}
const badge = page => page.locator(".tc-badge").textContent().then(text => (text ?? "").trim());
async function runOne(page, id) {
const lesson = byId.get(id);
const timeout = Number(arg("--timeout") ?? (lesson.job.kind.endsWith("-assembly") ? 2400 : 900)) * 1000;
await page.locator(`.tc-item[data-lesson-id="${id}"]`).click();
// The console remounts the frame per lesson; the run button is the readiness signal.
await page.waitForFunction(() => {
const button = [...document.querySelectorAll("button")].find(item => item.textContent?.includes("运行本课"));
return Boolean(button && !button.disabled);
}, null, { timeout: 300000 });
const started = Date.now();
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 });
const verdict = await badge(page);
const reason = ((await page.locator(".tc-reason").textContent()) ?? "").trim();
const seconds = Math.round((Date.now() - started) / 1000);
console.log(`${verdict === "pass" ? "ok " : "FAIL"} ${id} ${verdict} ${seconds}s ${reason.slice(0, 160)}`);
return { id, verdict, reason, seconds };
}
const profile = arg("--profile");
const browserArgs = ["--no-sandbox", "--disable-dev-shm-usage"];
const launched = profile ? null : await chromium.launch({ headless: true, args: browserArgs });
const context = launched
? await launched.newContext({ viewport: { width: 1440, height: 900 } })
: await chromium.launchPersistentContext(profile, { headless: true, viewport: { width: 1440, height: 900 }, args: browserArgs });
const page = context.pages()[0] ?? await context.newPage();
const pageErrors = [];
page.on("pageerror", error => pageErrors.push(String(error)));
const results = [];
try {
await page.goto(`${BASE}/teaching-console.html`, { waitUntil: "load" });
await page.waitForSelector(".teaching-console", { timeout: 60000 });
for (const id of ids) results.push(await runOne(page, id));
// Final evidence: what the run left in OPFS, read from the console's origin.
const store = await page.evaluate(async () => {
const root = await navigator.storage.getDirectory();
const list = async (name) => {
try {
const dir = await root.getDirectoryHandle(name);
const names = [];
for await (const [entry] of dir.entries()) names.push(entry);
return names.sort();
} catch { return []; }
};
return { documents: await list("freecad-documents"), reports: await list("freecad-exports") };
});
console.log(`\nOPFS freecad-documents:${store.documents.length} 个`);
console.log(`OPFS freecad-exports:${store.reports.length} 份报告`);
} catch (error) {
console.error(`异常:${error instanceof Error ? error.message : String(error)}`);
results.push({ id: "—", verdict: "fail", reason: String(error).slice(0, 200) });
} finally {
await context.close();
await launched?.close();
}
const failed = results.filter(result => result.verdict !== "pass");
if (pageErrors.length) console.error(`页面错误 ${pageErrors.length} 条:${pageErrors[0]}`);
console.log(`\n${results.length - failed.length}/${results.length} 通过`);
process.exit(failed.length ? 1 : 0);