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>
139 lines
6.3 KiB
JavaScript
139 lines
6.3 KiB
JavaScript
#!/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);
|