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

510
web/src/teaching/runner.ts Normal file
View File

@@ -0,0 +1,510 @@
// The in-page executor: runs one lesson against the workbench it lives in.
//
// This module is imported *into the workbench document* (see `bridge.ts`), so
// `window` here is the document under test and `createInPagePage(window)` yields
// the same Playwright-shaped surface `drive.mjs` hands the driver. That is why
// there is no cross-frame plumbing: the driver modules run in the page's own
// realm and `document` already means the right thing.
//
// Prerequisites are checked first and in dependency order. A failing prerequisite
// makes the lesson `blocked` -- never `fail` -- because nothing was asserted yet.
import { newDocumentWithBody, waitForWorkspace } from "../../tools/cad-ui-rebuild/lib/driver.mjs";
import { runPart } from "../../tools/cad-ui-rebuild/lib/run-part.mjs";
import { deleteExportFile, isOpfsSupported, writeExportFile } from "../storage.js";
import { createInPagePage } from "./in-page-page.js";
import { hasSteps, loadSteps } from "./steps.js";
import type {
AssemblyJob,
LessonReport,
LessonRunRequest,
PartJob,
PreflightCheck,
RunEvent,
StepRow,
Verdict,
} from "./types.js";
/** The replay judgement: same tolerance `drive.mjs` writes into `ui-run/v1`. */
const VOLUME_TOLERANCE = 1e-6;
/** One run at a time; `cancelLesson()` clears it between steps. */
let active: AbortController | null = null;
export function cancelLesson(): void {
active?.abort();
}
export function isRunning(): boolean {
return active !== null;
}
/** `page` as the run request names it -- path plus query, both sides normalised. */
function currentPage(): string {
const { pathname, search } = window.location;
return `${pathname.replace(/^\/+/, "")}${search}`;
}
/** Compare a lesson's page with the frame's, ignoring query order. */
function samePage(a: string, b: string): boolean {
const split = (value: string) => {
const [path, query = ""] = value.split("?");
const params = new URLSearchParams(query);
return `${path.replace(/^\/+/, "")}?${[...params.entries()]
.sort(([x], [y]) => x.localeCompare(y))
.map(([key, val]) => `${key}=${val}`)
.join("&")}`;
};
return split(a) === split(b);
}
/**
* Wait for the workspace each kind of page publishes once it is usable.
*
* Part pages mount a landmark element; the assembly shell instead publishes
* `__freecadWorkbenchState` and has no single stable element, so the two wait
* differently. Returns what it waited on, or `null` if the wait timed out.
*/
async function waitForPage(page: ReturnType<typeof createInPagePage>, kind: LessonRunRequest["job"]["kind"]): Promise<string | null> {
const timeout = 60000;
try {
if (kind.endsWith("-assembly")) {
await page.waitForFunction(
() => Boolean((window as unknown as { __freecadWorkbenchState?: unknown }).__freecadWorkbenchState),
undefined,
{ timeout },
);
return "__freecadWorkbenchState";
}
const landmark = '[aria-label="Native PartDesign view"]';
await page.waitForSelector(landmark, { timeout });
return landmark;
} catch {
return null;
}
}
/**
* Can this browser actually persist? `isOpfsSupported` only proves the API is
* there; a private window can still refuse the directory, so write once.
*/
async function checkOpfs(): Promise<PreflightCheck> {
if (!isOpfsSupported()) {
return { id: "opfs", label: "OPFS 可用", ok: false, detail: "此浏览器没有 navigator.storage.getDirectory" };
}
const name = `teaching-probe-${Date.now()}.json`;
try {
const bytes = new TextEncoder().encode('{"probe":true}');
await writeExportFile(name, bytes.buffer as ArrayBuffer);
await deleteExportFile(name);
return { id: "opfs", label: "OPFS 可写", ok: true, detail: "freecad-exports 写入并删除成功" };
} catch (error) {
return { id: "opfs", label: "OPFS 可写", ok: false, detail: message(error) };
}
}
/** The kernel answers: a newly opened document plus a body, then a throwaway. */
async function checkKernel(page: ReturnType<typeof createInPagePage>, kind: LessonRunRequest["job"]["kind"]): Promise<PreflightCheck> {
try {
if (kind.endsWith("-assembly")) {
// The assembly workbench has no PartDesign viewport. Its create panel is
// the landmark, and the shell stage returning to "ready" is the signal
// that the kernel finished booting. No document is created here: the
// lesson's own first step creates the assembly.
await page.waitForSelector('section[aria-label="Create assembly"]', { timeout: 180000 });
await page.waitForFunction(
() => (window as unknown as { __freecadWorkbenchState?: { stage?: string } })
.__freecadWorkbenchState?.stage === "ready",
undefined,
{ timeout: 180000 },
);
const rows = await page.locator('[role="treeitem"]').count();
return { id: "kernel", label: "内核就绪", ok: true, detail: `装配工作台已就绪(模型树 ${rows} 个对象)` };
}
await waitForWorkspace(page);
await newDocumentWithBody(page);
const rows = await page.locator('[role="treeitem"]').count();
return rows >= 1
? { id: "kernel", label: "内核就绪", ok: true, detail: `工作台已建立 ${rows} 个对象` }
: { id: "kernel", label: "内核就绪", ok: false, detail: "新建文档后模型树仍为空" };
} catch (error) {
return { id: "kernel", label: "内核就绪", ok: false, detail: message(error) };
}
}
function message(error: unknown): string {
return error instanceof Error ? error.message.slice(0, 300) : String(error).slice(0, 300);
}
/** Part milestones: what the console renders in the results table. */
function toRow(row: unknown): StepRow {
return row as StepRow;
}
/**
* What the assembly lesson needs on hand before it can start: every source part
* already in OPFS `freecad-documents`. Node seeds these from disk; the browser
* has no such source, so a missing part is a prerequisite, not a bug.
*/
async function checkAssemblySources(job: AssemblyJob): Promise<PreflightCheck> {
const { listDocumentFiles } = await import("../storage.js");
try {
const present = new Set(await listDocumentFiles());
const missing = job.sourceDocuments.filter(document => !present.has(`${document}.FCStd`) && !present.has(document));
return missing.length === 0
? { id: "sources", label: "装配源件在 OPFS", ok: true, detail: `${job.sourceDocuments.length} 个源件齐备` }
: {
id: "sources",
label: "装配源件在 OPFS",
ok: false,
detail: `缺少 ${missing.length} 个源件(先跑对应零件课):${missing.slice(0, 6).join("、")}`,
};
} catch (error) {
return { id: "sources", label: "装配源件在 OPFS", ok: false, detail: message(error) };
}
}
interface RunContext {
page: ReturnType<typeof createInPagePage>;
emit(event: RunEvent): void;
preflight: PreflightCheck[];
controller: AbortController;
}
/** Every prerequisite, in dependency order: storage, kernel, page, data. */
async function preflight(request: LessonRunRequest, context: RunContext): Promise<boolean> {
const { job } = request;
const checks: PreflightCheck[] = [await checkOpfs()];
context.emit({ type: "preflight", check: checks[0] });
if (checks[0].ok) {
const mounted = await waitForPage(context.page, job.kind);
const required = job.kind === "preflight" ? null : job.page;
const matches = mounted != null && (required == null || samePage(currentPage(), required));
const pageCheck: PreflightCheck = matches
? { id: "workbench", label: "工作台页匹配", ok: true, detail: `当前 ${currentPage()},等到 ${mounted}` }
: {
id: "workbench",
label: "工作台页匹配",
ok: false,
detail: mounted == null
? `当前页 ${currentPage()} 的工作台没有出现`
: `当前 ${currentPage()},课程要求 ${required}`,
};
checks.push(pageCheck);
context.emit({ type: "preflight", check: pageCheck });
}
if (checks.every(check => check.ok)) {
const kernel = await checkKernel(context.page, job.kind);
checks.push(kernel);
context.emit({ type: "preflight", check: kernel });
}
// Only part lessons replay a ui-steps record; an assembly lesson carries its
// own inserts/joints/solves, so asking for a steps file would block it forever.
if (checks.every(check => check.ok) && job.kind !== "preflight" && !job.kind.endsWith("-assembly")) {
const document = "document" in job ? job.document : "";
const ok = hasSteps(document);
const steps: PreflightCheck = {
id: "steps",
label: "界面步骤齐备",
ok,
detail: ok ? `${document} 的步骤记录已打包` : `没有 ${document} 的步骤记录(out/ui-steps)`,
};
checks.push(steps);
context.emit({ type: "preflight", check: steps });
}
if (checks.every(check => check.ok) && job.kind.endsWith("-assembly")) {
const sources = await checkAssemblySources(job as AssemblyJob);
checks.push(sources);
context.emit({ type: "preflight", check: sources });
}
context.preflight.push(...checks);
return checks.every(check => check.ok);
}
/** Nothing asserted yet: say why in the user's terms, not the stack's. */
function blockedReason(checks: PreflightCheck[]): string {
return checks.filter(check => !check.ok).map(check => `${check.label}:${check.detail}`).join(";")
|| "前置检查未全部通过";
}
async function runPartLesson(request: LessonRunRequest, context: RunContext): Promise<Partial<LessonReport>> {
const job = request.job as PartJob;
context.emit({ type: "phase", phase: "build", detail: `${job.title}(${job.document})` });
const uiSteps = await loadSteps(job.document);
const outcome = await runPart({
page: context.page,
uiSteps,
// `runPart` types this `number[]`, but reads each slot through `?? null`, so a
// `null` (a step whose replay recorded no volume) skips the comparison.
expectedVolumes: job.volumes as number[],
shouldStop: () => context.controller.signal.aborted,
onStep: (row, index, total) => {
const typed = toRow(row);
context.emit({ type: "step", index, total, row: typed });
context.emit({
type: "log",
line: `#${typed.step} ${typed.label} — ${typed.status === "ok" ? "ok" : typed.status},`
+ `体积 ${typed.volume ?? "—"}(期望 ${typed.expectedVolume ?? "—"})`,
});
},
});
const expected = outcome.expected ?? null;
const relativeError = outcome.relativeError ?? null;
const volumeOk = relativeError != null && relativeError < VOLUME_TOLERANCE;
const failed = outcome.results.filter(row => row.status !== "ok").length;
let verdict: Verdict = "pass";
let reason = `体积 ${outcome.volume} ≈ 期望 ${expected}(相对误差 ${relativeError?.toExponential(2)})`;
if (outcome.stopped) {
verdict = "cancelled";
reason = `已取消:执行 ${outcome.results.length}/${uiSteps.steps.length} 步`;
} else if (failed > 0) {
verdict = "fail";
const first = outcome.results.find(row => row.status !== "ok");
reason = `第 ${first?.step} 步失败:${first?.status}`;
} else if (!volumeOk) {
verdict = "fail";
reason = `体积不符:${outcome.volume},期望 ${expected}(相对误差 ${relativeError?.toExponential(2) ?? "无法比较"})`;
}
// A passing part is the input of an assembly lesson. Persisting it is not
// part of the judgement -- the model is already measured -- so a save that
// fails is logged and reported, never turned into a product failure.
const savedDocument = verdict === "pass" ? await savePartDocument(context, job.document) : null;
return {
verdict,
reason,
steps: outcome.results.length,
stepsTotal: uiSteps.steps.length,
failed,
volume: outcome.volume,
expected,
relativeError,
results: outcome.results as unknown as StepRow[],
savedDocument,
};
}
/**
* Store the just-built document where the assembly lessons look for it.
*
* The workspace saves under the name it gave the document (Design1, Design2,
* …) -- a lesson never names documents. Assembly lessons, the Insert Link task
* and the course data all address a part as `<document>.FCStd`, and an FCStd
* takes its document name from its file name, so re-storing the bytes under the
* course name is the whole contract. The workspace's own save control is used
* rather than a private kernel call, so the OPFS rules stay in one owner.
*/
async function savePartDocument(context: RunContext, documentId: string): Promise<string | null> {
const { readDocumentFile, writeDocumentFile, deleteDocumentFile } = await import("../storage.js");
const target = `${documentId}.FCStd`;
try {
const active = await context.page.locator('select[aria-label="Active document"]').first()
.evaluate(element => (element as HTMLSelectElement).value);
if (!active) throw new Error("找不到当前文档名");
const savedName = `${active}.FCStd`;
await context.page.getByRole("button", { name: "保存 FCStd 到 OPFS" }).first().click({ timeout: 120000 });
await context.page.waitForFunction(
(name) => (document.querySelector(".document-status")?.textContent ?? "").includes(`已保存 ${name}`),
savedName,
{ timeout: 120000 },
);
if (savedName !== target) {
const bytes = await readDocumentFile(savedName);
await writeDocumentFile(target, bytes);
await deleteDocumentFile(savedName);
}
context.emit({ type: "log", line: `文档已存入 OPFS:${target}` });
return target;
} catch (error) {
context.emit({ type: "log", line: `文档未能存入 OPFS(装配课会因缺源件而阻塞):${message(error)}` });
return null;
}
}
/**
* Insert every part, make the joints, solve, and save the bundle -- through the
* same `lib/assembly.mjs` calls the Node channel makes, in the same order. The
* only difference is seeding: Node copies sample FCStd files into OPFS from
* disk; here the part lessons have already stored them (see preflight).
*/
async function runAssemblyLesson(request: LessonRunRequest, context: RunContext): Promise<Partial<LessonReport>> {
const job = request.job as AssemblyJob;
const assembly = await import("../../tools/cad-ui-rebuild/lib/assembly.mjs");
const stop = () => {
if (context.controller.signal.aborted) throw new Error("已取消");
};
context.emit({ type: "phase", phase: "assembly", detail: `创建装配 ${job.document}` });
await assembly.createAssembly(context.page, {
appOrigin: window.location.origin,
pagePath: job.page,
document: job.document,
label: job.document,
});
stop();
context.emit({ type: "phase", phase: "insert", detail: `${job.inserts.length} 个零件` });
const inserted = await assembly.insertAll(context.page, job.inserts, { groundDocument: job.groundDocument });
const listed = await assembly.insertedLinkCount(context.page);
const mismatches: string[] = [];
if (listed != null && listed !== inserted.length) {
mismatches.push(`任务面板列出 ${listed} 个链接,实际插入 ${inserted.length}`);
}
for (const [index, expected] of job.inserts.entries()) {
const actual = inserted[index] as { sourceDocument?: string; position?: number[]; rotation?: number[] } | undefined;
if (!actual) { mismatches.push(`${expected.sourceDocument}: not inserted`); continue; }
if (actual.sourceDocument !== expected.sourceDocument) {
mismatches.push(`#${index + 1} document ${actual.sourceDocument} != ${expected.sourceDocument}`);
}
const quaternion = actual.rotation ?? [0, 0, 0, 1];
const wanted = expected.rotation ?? [0, 0, 0, 1];
if (quaternion.some((value, at) => Math.abs(value - wanted[at]) > 1e-6)) {
mismatches.push(`${expected.sourceDocument}: rotation ${quaternion.join(",")} != ${wanted.join(",")}`);
}
const position = actual.position ?? [0, 0, 0];
const targetPosition = expected.position ?? [0, 0, 0];
if (position.some((value, at) => Math.abs(value - targetPosition[at]) > 1e-6)) {
mismatches.push(`${expected.sourceDocument}: position ${position.join(",")} != ${targetPosition.join(",")}`);
}
}
stop();
context.emit({ type: "phase", phase: "joints", detail: `${job.joints.length} 个关节` });
const joints = job.joints.length ? await assembly.createJoints(context.page, job.joints) : [];
if (joints.length !== job.joints.length) {
mismatches.push(`${joints.length} joints created, replay records ${job.joints.length}`);
}
stop();
context.emit({ type: "phase", phase: "solve", detail: `${job.solves.length} 次求解` });
const solves = [];
for (const step of job.solves) solves.push(await assembly.solveAssembly(context.page, step));
let saved: unknown = null;
if (job.saveBundle && job.bom.length) {
stop();
context.emit({ type: "phase", phase: "bom", detail: "物料清单与保存" });
for (const step of job.bom) await assembly.executeCommand(context.page, step.action, step.args);
saved = await assembly.saveAssemblyBundle(context.page, { document: job.document });
if (!(saved as { manifestStored?: boolean } | null)?.manifestStored) {
mismatches.push(`OPFS 未存储装配清单 ${job.document}.assembly.json`);
}
}
const components = (solves.at(-1)?.components ?? []) as Array<{ position?: unknown; rotation?: unknown }>;
const malformed = components.filter(component => !Array.isArray(component.position) || component.position.length !== 3
|| !component.position.every(Number.isFinite)
|| !Array.isArray(component.rotation) || component.rotation.length !== 4
|| !component.rotation.every(Number.isFinite)).length;
const failed = (job.inserts.length - inserted.length) + Math.abs(job.joints.length - joints.length);
const verdict: Verdict = mismatches.length || malformed ? "fail" : "pass";
const reason = `插入 ${inserted.length}/${job.inserts.length} · 关节 ${joints.length}/${job.joints.length}`
+ ` · 组件 ${components.length}${malformed ? `(畸形 ${malformed})` : ""}`
+ (mismatches.length ? ` · 失配 ${mismatches.length}:${mismatches[0]}` : "");
return {
verdict,
reason,
steps: inserted.length,
stepsTotal: job.inserts.length,
failed,
results: [],
assembly: {
inserted: inserted.length,
expected: job.inserts.length,
joints: joints.length,
expectedJoints: job.joints.length,
solves: solves.length,
mismatches,
components: components.length,
malformed,
saved,
},
};
}
/**
* Run one lesson to completion and hand back a report.
*
* The caller owns persistence; this function only measures.
*/
export async function executeLesson(
request: LessonRunRequest,
onEvent?: (event: RunEvent) => void,
): Promise<LessonReport> {
if (active) throw new Error("已有课程在运行");
const controller = new AbortController();
active = controller;
const startedAt = new Date();
const started = performance.now();
const pageErrors: string[] = [];
const onError = (event: ErrorEvent) => pageErrors.push(String(event.message ?? event.error).slice(0, 300));
const onRejection = (event: PromiseRejectionEvent) => pageErrors.push(message(event.reason));
window.addEventListener("error", onError);
window.addEventListener("unhandledrejection", onRejection);
const emit = (event: RunEvent) => {
try {
onEvent?.(event);
} catch {
// A console that navigated away must not take the lesson down with it.
}
};
const context: RunContext = { page: createInPagePage(window), emit, preflight: [], controller };
const report: LessonReport = {
schema: "freecad-web/teaching-console/in-app-run/v1",
lessonId: request.lessonId,
title: request.title,
kind: request.job.kind,
document: "document" in request.job ? request.job.document : null,
startedAt: startedAt.toISOString(),
finishedAt: startedAt.toISOString(),
seconds: 0,
verdict: "blocked",
reason: "",
steps: 0,
stepsTotal: request.job.kind === "preflight" ? 0 : ("steps" in request.job ? request.job.steps : 0),
failed: 0,
volume: null,
expected: null,
relativeError: null,
preflight: [],
results: [],
pageErrors,
};
try {
emit({ type: "phase", phase: "preflight" });
const ready = await preflight(request, context);
if (!ready) {
report.reason = blockedReason(context.preflight);
emit({ type: "log", line: `前置未通过:${report.reason}` });
return report;
}
const outcome = request.job.kind === "preflight"
? { verdict: "pass" as Verdict, reason: `前置 ${context.preflight.length} 项全部通过` }
: request.job.kind.endsWith("-assembly")
? await runAssemblyLesson(request, context)
: await runPartLesson(request, context);
Object.assign(report, outcome);
} catch (error) {
report.verdict = controller.signal.aborted ? "cancelled" : "fail";
report.reason = message(error);
emit({ type: "log", line: `异常:${report.reason}` });
} finally {
window.removeEventListener("error", onError);
window.removeEventListener("unhandledrejection", onRejection);
active = null;
const finishedAt = new Date();
report.finishedAt = finishedAt.toISOString();
report.seconds = (performance.now() - started) / 1000;
report.preflight = context.preflight;
emit({ type: "phase", phase: "done", detail: report.verdict });
}
return report;
}