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

@@ -46,6 +46,7 @@
"check:tools-manual": "node ../tools/build-tools-manual.mjs --verify && node ../tools/check-tools-manual.mjs",
"build:console": "node tools/teaching-console/build-console.mjs",
"check:console": "node tools/teaching-console/build-console.mjs --check && node tools/teaching-console/self-test.mjs",
"check:console-inapp": "node tools/teaching-console/check-inapp-console.mjs",
"teach:console": "node teaching/server.mjs",
"reducer:list": "node ../tools/reducer/list.mjs",
"reducer:part": "node ../tools/reducer/create-part.mjs",

82
web/src/navigation.ts Normal file
View File

@@ -0,0 +1,82 @@
export interface NavigationRoute { id: string; label: string; href: string; scope: "core" | "workflow" | "runtime"; }
export interface NavigationContext { documentId?: string; module?: string; command?: string; }
import { WEB_MODULE_REGISTRY } from "./module-registry.generated.js";
export const WEB_NAVIGATION_ROUTES: readonly NavigationRoute[] = [
{ id: "home", label: "3D 视图", href: "/index.html", scope: "core" },
{ id: "document", label: "Document", href: "/document.html", scope: "core" },
{ id: "main-chain", label: "主链", href: "/main-chain.html", scope: "workflow" },
{ id: "project", label: "工程", href: "/project.html", scope: "workflow" },
{ id: "full", label: "全线", href: "/full.html", scope: "workflow" },
{ id: "workbench", label: "工作台", href: "/workbench.html", scope: "workflow" },
{ id: "teaching-console", label: "教学", href: "/teaching-console.html", scope: "workflow" },
{ id: "python", label: "Python", href: "/python.html", scope: "runtime" },
...WEB_MODULE_REGISTRY.map((route) => ({ id: `module-${route.module}`, label: route.module, href: moduleHref(route.module), scope: "workflow" as const })),
];
const CONTEXT_KEYS: readonly [keyof NavigationContext, string][] = [
["documentId", "document"],
["module", "module"],
["command", "command"],
];
function contextValue(value: string | null | undefined): string | undefined {
if (!value) return undefined;
const normalized = value.trim();
return normalized.length > 0 && normalized.length <= 160 ? normalized : undefined;
}
export function readNavigationContext(source: Pick<Location, "search"> = window.location): NavigationContext {
const params = new URLSearchParams(source.search);
return Object.fromEntries(CONTEXT_KEYS.flatMap(([key, queryKey]) => {
const value = contextValue(params.get(queryKey));
return value ? [[key, value]] : [];
})) as NavigationContext;
}
export function navigationHref(route: NavigationRoute, context: NavigationContext = readNavigationContext()): string {
if (route.id.startsWith("module-")) context = { documentId: context.documentId, module: route.id.slice(7) };
const url = new URL(route.href, window.location.origin);
for (const [key, queryKey] of CONTEXT_KEYS) {
const value = contextValue(context[key]);
if (value) url.searchParams.set(queryKey, value);
else url.searchParams.delete(queryKey);
}
return `${url.pathname}${url.search}${url.hash}`;
}
export function updateNavigationContext(context: NavigationContext, mode: "push" | "replace" = "replace"): void {
const url = new URL(window.location.href);
for (const [key, queryKey] of CONTEXT_KEYS) {
const value = contextValue(context[key]);
if (value) url.searchParams.set(queryKey, value);
else url.searchParams.delete(queryKey);
}
const next = `${url.pathname}${url.search}${url.hash}`;
if (mode === "push") window.history.pushState({ navigationContext: context }, "", next);
else window.history.replaceState({ navigationContext: context }, "", next);
document.querySelectorAll<HTMLAnchorElement>(".global-nav a[data-route]").forEach(link => {
const route = WEB_NAVIGATION_ROUTES.find(route => route.id === link.dataset.route);
if (route) link.href = navigationHref(route, context);
});
}
function moduleHref(module: string): string {
return `/workbench.html?module=${encodeURIComponent(module)}`;
}
export function installNavigation(currentId: string, context: NavigationContext = readNavigationContext()): void {
if (document.querySelector(".global-nav")) return;
const nav = document.createElement("nav");
nav.className = "global-nav";
nav.setAttribute("aria-label", "FreeCAD Web navigation");
nav.innerHTML = WEB_NAVIGATION_ROUTES.map((route) => `<a href="${navigationHref(route, context)}" data-route="${route.id}"${route.id === currentId ? " aria-current=page" : ""}>${route.label}</a>`).join("");
if (context.documentId) nav.dataset.documentId = context.documentId;
if (context.module) nav.dataset.module = context.module;
if (context.command) nav.dataset.command = context.command;
const style = document.createElement("style");
style.textContent = ".global-nav{align-items:center;background:#10161dcc;border-bottom:1px solid #2c3b48;box-sizing:border-box;contain:layout paint;display:flex;gap:4px;width:100%;min-width:0;max-width:100%;overflow-x:auto;padding:5px 12px;position:relative;z-index:10}.global-nav a{border:1px solid transparent;border-radius:4px;color:#9cb6c2;flex-shrink:0;font-size:12px;padding:5px 9px;text-decoration:none;white-space:nowrap}.global-nav a:hover,.global-nav a[aria-current=page]{background:#243b47;border-color:#435464;color:#e7edf3}";
document.head.append(style);
document.body.prepend(nav);
}

View File

@@ -1,9 +1,12 @@
import React from "react";
import { createRoot } from "react-dom/client";
import { PartDesignWorkspace } from "./partdesign-workspace-component.js";
import { installTeachingBridge } from "./teaching/bridge.js";
import "./panel-scroll.css";
// Lock the page to the viewport so the tree and property panes scroll on their
// own and the 3D viewport keeps its size (see panel-scroll.css).
document.documentElement.classList.add("stage-lock-pd");
// Lets the in-app teaching console drive this page across the iframe boundary.
installTeachingBridge();
createRoot(document.querySelector<HTMLDivElement>("#app")!).render(<PartDesignWorkspace />);

View File

@@ -0,0 +1,10 @@
// Standalone entry for /teaching-console.html.
import { createRoot } from "react-dom/client";
import { installNavigation, readNavigationContext } from "./navigation.js";
import { TeachingConsole } from "./teaching/console-page.js";
installNavigation("teaching-console", readNavigationContext());
const container = document.querySelector<HTMLDivElement>("#app");
if (!container) throw new Error("teaching console entry: #app container is missing");
createRoot(container).render(<TeachingConsole />);

View File

@@ -0,0 +1,46 @@
// Publishes `window.__teaching` in a workbench page, so the console page can
// drive it across the iframe boundary.
//
// Both sides are same-origin documents, so the console simply reaches into
// `frame.contentWindow.__teaching` and calls `run()`. The request and the report
// are plain data and the progress callback is a plain function, so nothing here
// has to serialise.
//
// The runner is a dynamic import: a workbench page pays nothing for the teaching
// stack until a lesson actually starts, and the per-lesson step chunks stay
// unloaded until then too.
import type { LessonReport, LessonRunRequest, RunEvent, TeachingBridge } from "./types.js";
interface BridgeHost {
__teaching?: TeachingBridge;
}
let running = false;
/** Call once per workbench document, before the app renders. */
export function installTeachingBridge(): void {
const host = window as unknown as BridgeHost;
if (host.__teaching) return;
const bridge: TeachingBridge = {
ready: true,
page: `${location.pathname.replace(/^\/+/, "")}${location.search}`,
running: () => running,
cancel: () => {
// The runner module is already loaded while a lesson runs, so this import
// resolves from cache and the abort lands between steps.
void import("./runner.js").then(runner => runner.cancelLesson());
},
run: async (request: LessonRunRequest, onEvent?: (event: RunEvent) => void): Promise<LessonReport> => {
if (running) throw new Error("已有课程在运行");
running = true;
try {
const runner = await import("./runner.js");
return await runner.executeLesson(request, onEvent);
} finally {
running = false;
}
},
};
host.__teaching = bridge;
}

View File

@@ -0,0 +1,404 @@
// The teaching console, running inside Web FreeCAD.
//
// Left: the lesson list. Centre: the real workbench in a same-origin iframe.
// Bottom: the run's terminal, the results table and the verdict.
//
// Nothing here talks to a server. The frame publishes `__teaching` (see
// `bridge.ts`); this page calls it, streams its progress events into the panes,
// and writes the finished report to OPFS. The only way a report leaves the
// browser is the explicit "下载到本地" button.
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { isOpfsSupported } from "../storage.js";
import raw from "./generated/lessons.json";
import { downloadReport, persistReport } from "./report-store.js";
import type {
LessonJob,
LessonReport,
PreflightCheck,
RunEvent,
StepRow,
TeachingBridge,
Verdict,
} from "./types.js";
import "./console.css";
interface LessonEntry {
id: string;
groupId: string;
title: string;
level: string;
durationMin: number;
summary: string;
sees: string[];
expect: string;
job: LessonJob;
}
interface GroupEntry {
id: string;
title: string;
workbench: string;
blurb: string;
}
interface LessonData {
groups: GroupEntry[];
lessons: LessonEntry[];
counts: { lessons: number; parts: number; assemblies: number; steps: number };
}
const DATA = raw as unknown as LessonData;
const LESSONS = DATA.lessons;
const GROUPS = DATA.groups;
/** Which shell page a lesson runs against. The self-check needs no argument. */
function lessonPage(lesson: LessonEntry): string {
return "page" in lesson.job ? lesson.job.page : "partdesign.html";
}
function lessonSteps(lesson: LessonEntry): number {
return "steps" in lesson.job ? lesson.job.steps : 0;
}
function frameBridge(frame: HTMLIFrameElement | null): TeachingBridge | null {
try {
const win = frame?.contentWindow as (Window & { __teaching?: TeachingBridge }) | null;
return win?.__teaching?.ready ? win.__teaching : null;
} catch {
// A frame that is not same-origin cannot be driven, and that includes one
// still at about:blank after a reload.
return null;
}
}
function message(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
export function TeachingConsole(): React.ReactElement {
const [selectedId, setSelectedId] = useState<string>(LESSONS[0]?.id ?? "");
const [frameKey, setFrameKey] = useState(0);
const [frameReady, setFrameReady] = useState(false);
const [running, setRunning] = useState(false);
const [logs, setLogs] = useState<string[]>([]);
const [checks, setChecks] = useState<PreflightCheck[]>([]);
const [rows, setRows] = useState<StepRow[]>([]);
const [progress, setProgress] = useState({ done: 0, total: 0 });
const [report, setReport] = useState<LessonReport | null>(null);
const [saved, setSaved] = useState<string | null>(null);
const [saveError, setSaveError] = useState<string | null>(null);
const [tab, setTab] = useState<"log" | "table">("log");
const [verdicts, setVerdicts] = useState<Record<string, Verdict>>({});
const frame = useRef<HTMLIFrameElement | null>(null);
/** Resolved by the frame's `onLoad` once the bridge answers. */
const ticket = useRef<((ok: boolean) => void) | null>(null);
const selected = useMemo(
() => LESSONS.find(lesson => lesson.id === selectedId) ?? LESSONS[0],
[selectedId],
);
const opfsOk = isOpfsSupported();
const pushLog = useCallback((line: string) => {
setLogs(previous => [...previous.slice(-500), line]);
}, []);
const onEvent = useCallback((event: RunEvent) => {
switch (event.type) {
case "log":
pushLog(event.line);
break;
case "phase":
pushLog(`· ${event.phase}${event.detail ? `:${event.detail}` : ""}`);
break;
case "preflight":
setChecks(previous => [...previous.filter(check => check.id !== event.check.id), event.check]);
break;
case "step":
setRows(previous => [...previous, event.row]);
setProgress({ done: event.index + 1, total: event.total });
break;
}
}, [pushLog]);
/**
* The frame loads its page, then mounts React, then the kernel. The bridge is
* installed before the first render, so waiting for it proves the document is
* ours to drive; the runner's own preflight waits for the workspace itself.
*/
const handleFrameLoad = useCallback(async () => {
setFrameReady(false);
const deadline = Date.now() + 180000;
while (Date.now() < deadline) {
if (frameBridge(frame.current)) {
setFrameReady(true);
ticket.current?.(true);
ticket.current = null;
return;
}
await new Promise(resolve => setTimeout(resolve, 250));
}
ticket.current?.(false);
ticket.current = null;
}, []);
useEffect(() => {
document.body.dataset.runnerState = running ? "running" : report?.verdict ?? "idle";
}, [running, report]);
function selectLesson(id: string) {
if (running || id === selectedId) return;
setSelectedId(id);
setReport(null);
setSaved(null);
setSaveError(null);
setChecks([]);
setRows([]);
setLogs([]);
// Show the page this lesson needs, from a clean document.
setFrameReady(false);
setFrameKey(key => key + 1);
}
async function runLesson() {
if (!selected || running) return;
const armed = new Promise<boolean>(resolve => { ticket.current = resolve; });
setRunning(true);
setReport(null);
setSaved(null);
setSaveError(null);
setChecks([]);
setRows([]);
setLogs([]);
setTab("log");
setProgress({ done: 0, total: lessonSteps(selected) });
pushLog(`开始:${selected.title}`);
// Every lesson starts from a freshly loaded workbench: no state can leak
// from the previous lesson, and the page matches what the lesson names.
setFrameReady(false);
setFrameKey(key => key + 1);
const errorText = (text: string): LessonReport => ({
schema: "freecad-web/teaching-console/in-app-run/v1",
lessonId: selected.id,
title: selected.title,
kind: selected.job.kind,
document: "document" in selected.job ? selected.job.document : null,
startedAt: new Date().toISOString(),
finishedAt: new Date().toISOString(),
seconds: 0,
verdict: "blocked",
reason: text,
steps: 0,
stepsTotal: lessonSteps(selected),
failed: 0,
volume: null,
expected: null,
relativeError: null,
preflight: [],
results: [],
pageErrors: [],
});
const ready = await armed;
const bridge = ready ? frameBridge(frame.current) : null;
if (!bridge) {
const blocked = errorText(`工作台页 ${lessonPage(selected)} 没有在 iframe 内就绪`);
setReport(blocked);
pushLog(`前置未通过:${blocked.reason}`);
setRunning(false);
return;
}
try {
const result = await bridge.run(
{ lessonId: selected.id, title: selected.title, job: selected.job },
onEvent,
);
setReport(result);
setVerdicts(previous => ({ ...previous, [selected.id]: result.verdict }));
pushLog(`判定:${result.verdict} — ${result.reason}`);
try {
setSaved(await persistReport(result));
} catch (error) {
setSaveError(`报告未能写入 OPFS:${message(error)}`);
}
} catch (error) {
const failed = errorText(message(error));
setReport(failed);
pushLog(`异常:${failed.reason}`);
} finally {
setRunning(false);
}
}
function cancelLesson() {
const bridge = frameBridge(frame.current);
bridge?.cancel();
pushLog("已请求取消:当前步骤结束后停止");
}
const shownChecks = report?.preflight?.length ? report.preflight : checks;
const total = progress.total || lessonSteps(selected);
const percent = total ? Math.min(100, Math.round((progress.done / total) * 100)) : 0;
const canRun = Boolean(selected) && frameReady && !running && opfsOk;
return (
<div className="teaching-console">
<header className="tc-head">
<h1>Web FreeCAD 教学控制台</h1>
<span className="tc-sub" title={selected?.expect}>{selected?.expect ?? ""}</span>
<span className="tc-count">
{DATA.counts.lessons} 课 · {DATA.counts.parts} 件 · {DATA.counts.steps} 步
</span>
</header>
<nav className="tc-list" aria-label="课程列表">
{GROUPS.map(group => (
<details key={group.id} className="tc-group" open>
<summary title={group.blurb}>{group.title}</summary>
{LESSONS.filter(lesson => lesson.groupId === group.id).map(lesson => (
<button
key={lesson.id}
type="button"
className="tc-item"
aria-current={lesson.id === selected?.id}
data-lesson-id={lesson.id}
data-verdict={verdicts[lesson.id] ?? undefined}
title={lesson.summary}
onClick={() => selectLesson(lesson.id)}
>
<span className="tc-name">{lesson.title}</span>
<span className="tc-min">{lesson.durationMin}′</span>
</button>
))}
</details>
))}
</nav>
<div className="tc-stage">
<iframe
key={frameKey}
ref={frame}
className="tc-frame"
title="FreeCAD 工作台"
src={`/${selected ? lessonPage(selected) : "partdesign.html"}`}
onLoad={() => { void handleFrameLoad(); }}
/>
{!frameReady && <span className="tc-stage-note">工作台加载中…</span>}
</div>
<footer className="tc-foot">
<div className="tc-foot-left">
<div className="tc-tabs" role="tablist">
<button
type="button"
role="tab"
className="tc-tab"
aria-selected={tab === "log"}
onClick={() => setTab("log")}
>终端</button>
<button
type="button"
role="tab"
className="tc-tab"
aria-selected={tab === "table"}
onClick={() => setTab("table")}
>结果表{rows.length ? `(${rows.length})` : ""}</button>
</div>
{tab === "log"
? <pre className="tc-log" aria-label="运行日志">{logs.join("\n")}</pre>
: (
// A table is `display: table`, so `overflow` on it does nothing:
// the seven columns keep their intrinsic width and push the page
// sideways on a phone. The wrapper is the scroll container.
<div className="tc-table-wrap">
<table className="tc-table" aria-label="步骤结果">
<thead>
<tr><th>步</th><th>动作</th><th>命令</th><th>体积</th><th>期望</th><th>判定</th><th>用时</th></tr>
</thead>
<tbody>
{rows.map(row => (
<tr key={`${row.step}-${row.label}`} data-status={row.status}>
<td className="tc-num">{row.step}</td>
<td>{row.label}</td>
<td>{row.command}</td>
<td className="tc-num">{row.volume ?? "—"}</td>
<td className="tc-num">{row.expectedVolume ?? "—"}</td>
<td>{row.status === "ok" ? "ok" : row.status}</td>
<td className="tc-num">{row.ms} ms</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
<aside className="tc-foot-right">
<div className="tc-verdict">
判定
<span className="tc-badge" data-verdict={report?.verdict ?? (running ? "blocked" : "idle")}>
{report?.verdict ?? (running ? "运行中" : "未运行")}
</span>
</div>
<p className="tc-reason">{report?.reason ?? selected?.summary ?? ""}</p>
<div className="tc-bar"><span style={{ width: `${running ? percent : report ? 100 : 0}%` }} /></div>
<p className="tc-evidence">
{report
? `步数 ${report.steps}/${report.stepsTotal} · 失败 ${report.failed} · 用时 ${report.seconds.toFixed(1)} s`
: `本课 ${lessonSteps(selected)} 步`}
</p>
<table className="tc-checks" aria-label="前置检查">
<tbody>
<tr>
<td className={opfsOk ? "tc-ok" : "tc-no"}>{opfsOk ? "✓" : "✗"}</td>
<td>OPFS {opfsOk ? "可用" : "不可用(此浏览器不支持,无法保存文档)"}</td>
</tr>
{shownChecks.map(check => (
<tr key={check.id}>
<td className={check.ok ? "tc-ok" : "tc-no"}>{check.ok ? "✓" : "✗"}</td>
<td>{check.label}:{check.detail}</td>
</tr>
))}
</tbody>
</table>
{selected?.sees?.length ? (
<p className="tc-evidence">本课应看到:{selected.sees.join(";")}</p>
) : null}
{report?.pageErrors?.length ? (
<p className="tc-evidence tc-no">页面错误 {report.pageErrors.length} 条,详见证据。</p>
) : null}
<div className="tc-actions">
<button
type="button"
className="tc-button"
data-primary="true"
disabled={!canRun}
onClick={() => { void runLesson(); }}
>{running ? "运行中…" : "运行本课"}</button>
<button type="button" className="tc-button" disabled={!running} onClick={cancelLesson}>取消</button>
<button
type="button"
className="tc-button"
disabled={!report}
onClick={() => { if (report) downloadReport(report); }}
>下载到本地</button>
</div>
<p className="tc-evidence">
{saved ? `证据已写入 OPFS freecad-exports/${saved}` : null}
{saveError ? <span className="tc-no">{saveError}</span> : null}
{!saved && !saveError ? "报告在每课结束后写入 OPFS;下载需手动点击。" : null}
</p>
{!frameReady && !running ? <p className="tc-evidence">工作台尚未就绪,运行按钮暂不可用。</p> : null}
</aside>
</footer>
</div>
);
}

View File

@@ -0,0 +1,184 @@
/* The in-app teaching console: lesson list, live workbench, run report. */
body:has(> #app > .teaching-console) {
display: flex;
flex-direction: column;
height: 100dvh;
margin: 0;
overflow: hidden;
}
body:has(> #app > .teaching-console) > #app {
flex: 1;
min-height: 0;
}
.teaching-console {
--line: #2c3b48;
--panel: #0e141a;
--cell: #131b22;
--ink: #e7edf3;
--dim: #9cb6c2;
--pass: #4fd08a;
--fail: #ff7a6b;
--blocked: #f0c04a;
--cancelled: #8a9aa6;
background: #0b1116;
color: var(--ink);
display: grid;
font: 13px/1.5 system-ui, "Noto Sans CJK SC", sans-serif;
grid-template-areas: "head head" "list stage" "foot foot";
grid-template-columns: 268px minmax(0, 1fr);
grid-template-rows: auto minmax(0, 1fr) minmax(170px, 32%);
height: 100%;
min-height: 0;
}
.tc-head {
align-items: center;
background: var(--panel);
border-bottom: 1px solid var(--line);
display: flex;
gap: 14px;
grid-area: head;
padding: 8px 14px;
}
.tc-head h1 { font-size: 14px; margin: 0; }
.tc-head .tc-sub { color: var(--dim); flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.tc-head .tc-count { color: var(--dim); font-variant-numeric: tabular-nums; white-space: nowrap; }
.tc-list {
background: var(--panel);
border-right: 1px solid var(--line);
grid-area: list;
min-height: 0;
overflow: auto;
padding: 6px 0 24px;
}
.tc-group > summary {
color: var(--dim);
cursor: pointer;
font-size: 11px;
letter-spacing: .04em;
list-style: none;
padding: 8px 12px 4px;
text-transform: uppercase;
}
.tc-group > summary::-webkit-details-marker { display: none; }
.tc-item {
align-items: baseline;
background: transparent;
border: 0;
border-left: 2px solid transparent;
color: var(--ink);
cursor: pointer;
display: flex;
gap: 8px;
justify-content: space-between;
padding: 5px 12px;
text-align: left;
width: 100%;
}
.tc-item:hover { background: #16212b; }
.tc-item[aria-current="true"] { background: #1b2b36; border-left-color: var(--dim); }
.tc-item .tc-name { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.tc-item .tc-min { color: var(--dim); font-size: 11px; font-variant-numeric: tabular-nums; }
.tc-item[data-verdict="pass"] .tc-name::after { color: var(--pass); content: " ✓"; }
.tc-item[data-verdict="fail"] .tc-name::after { color: var(--fail); content: " ✗"; }
.tc-item[data-verdict="blocked"] .tc-name::after { color: var(--blocked); content: " !"; }
.tc-item[data-verdict="cancelled"] .tc-name::after { color: var(--cancelled); content: " –"; }
.tc-stage {
background: #05080a;
display: flex;
grid-area: stage;
min-height: 0;
min-width: 0;
position: relative;
}
.tc-frame { border: 0; height: 100%; width: 100%; }
.tc-stage-note {
background: #000a;
border-radius: 4px;
color: var(--dim);
left: 12px;
padding: 4px 8px;
position: absolute;
top: 12px;
}
.tc-foot {
background: var(--panel);
border-top: 1px solid var(--line);
display: grid;
grid-area: foot;
grid-template-columns: minmax(0, 1fr) 300px;
min-height: 0;
}
.tc-foot-left { display: flex; flex-direction: column; min-height: 0; min-width: 0; }
.tc-foot-right { border-left: 1px solid var(--line); min-height: 0; overflow: auto; padding: 8px 12px; }
.tc-tabs { border-bottom: 1px solid var(--line); display: flex; gap: 2px; padding: 4px 8px 0; }
.tc-tab {
background: transparent;
border: 1px solid transparent;
border-bottom: 0;
border-radius: 4px 4px 0 0;
color: var(--dim);
cursor: pointer;
padding: 4px 10px;
}
.tc-tab[aria-selected="true"] { background: var(--cell); border-color: var(--line); color: var(--ink); }
.tc-log {
flex: 1;
font: 12px/1.55 ui-monospace, "Cascadia Mono", monospace;
margin: 0;
min-height: 0;
overflow: auto;
padding: 8px 12px;
white-space: pre-wrap;
}
.tc-log .tc-warn { color: var(--blocked); }
.tc-log .tc-bad { color: var(--fail); }
.tc-table-wrap { display: flex; flex: 1; min-height: 0; min-width: 0; overflow: auto; }
.tc-table { border-collapse: collapse; font-size: 12px; width: 100%; }
.tc-table th, .tc-table td { border-bottom: 1px solid #1d2831; padding: 3px 8px; text-align: left; }
.tc-table th { background: var(--cell); color: var(--dim); font-weight: 600; position: sticky; top: 0; }
.tc-table td.tc-num { font-variant-numeric: tabular-nums; text-align: right; }
.tc-table tr[data-status]:not([data-status="ok"]) td { background: #2a1714; }
.tc-verdict { align-items: center; display: flex; gap: 8px; font-size: 15px; font-weight: 600; margin-bottom: 6px; }
.tc-badge { border: 1px solid currentColor; border-radius: 999px; font-size: 11px; padding: 1px 8px; }
.tc-badge[data-verdict="pass"] { color: var(--pass); }
.tc-badge[data-verdict="fail"] { color: var(--fail); }
.tc-badge[data-verdict="blocked"] { color: var(--blocked); }
.tc-badge[data-verdict="cancelled"] { color: var(--cancelled); }
.tc-reason { color: var(--dim); font-size: 12px; margin: 0 0 10px; }
.tc-checks { border-collapse: collapse; font-size: 12px; width: 100%; }
.tc-checks td { border-bottom: 1px solid #1d2831; padding: 3px 0; vertical-align: top; }
.tc-checks td:first-child { padding-right: 8px; white-space: nowrap; }
.tc-ok { color: var(--pass); }
.tc-no { color: var(--fail); }
.tc-actions { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 10px; }
.tc-button {
background: #1b2b36;
border: 1px solid var(--line);
border-radius: 4px;
color: var(--ink);
cursor: pointer;
padding: 5px 12px;
}
.tc-button:hover:not(:disabled) { border-color: var(--dim); }
.tc-button:disabled { cursor: not-allowed; opacity: .45; }
.tc-button[data-primary="true"] { background: #1f4b3c; border-color: #2f6f57; }
.tc-bar { background: #1b2b36; border-radius: 999px; height: 4px; margin-top: 8px; overflow: hidden; }
.tc-bar > span { background: var(--dim); display: block; height: 100%; transition: width .2s; }
.tc-evidence { color: var(--dim); font-size: 11px; margin-top: 10px; }

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,373 @@
// A Playwright-shaped `page` over the DOM of the window that runs it.
//
// `web/tools/cad-ui-rebuild/lib/{driver,assembly}.mjs` were written against
// Playwright and are proven against the real workspace. The teaching console
// reuses them verbatim by handing them this object instead of a Playwright
// Page: the driver modules are imported *into* the workspace document (see
// `runner.ts`), so a bare `document` already refers to the page under test and
// `evaluate` is a plain function call. That is also the only option here --
// the app's CSP has no `'unsafe-eval'`, so function bodies cannot be
// stringified across a realm boundary.
//
// Only the surface the drivers actually use is implemented. Anything else
// throws by name instead of quietly doing nothing: a driver that silently
// skips a control would report a pass for a model it never built.
const DEFAULT_TIMEOUT = 30000;
type Mutable = any;
interface RoleOptions { name?: string | RegExp; exact?: boolean }
interface FilterOptions { hasText?: string | RegExp }
interface WaitOptions { state?: "visible" | "attached"; timeout?: number }
interface SelectValue { label?: string; value?: string; index?: number }
/**
* Constructors live on the window of their own realm, and a node inside the
* workbench frame is not an instance of this realm's constructors -- so every
* `instanceof` here has to go through the frame's window. `Window` has no typed
* members for them, hence this cast, kept in one place.
*/
interface RealmGlobals {
Event: typeof Event;
KeyboardEvent: typeof KeyboardEvent;
MouseEvent: typeof MouseEvent;
PointerEvent: typeof PointerEvent;
HTMLInputElement: typeof HTMLInputElement;
HTMLSelectElement: typeof HTMLSelectElement;
HTMLTextAreaElement: typeof HTMLTextAreaElement;
}
function realm(win: Window): RealmGlobals { return win as unknown as RealmGlobals; }
export interface InPageLocator {
first(): InPageLocator;
locator(selector: string): InPageLocator;
getByRole(role: string, options?: RoleOptions): InPageLocator;
filter(options: FilterOptions): InPageLocator;
count(): Promise<number>;
click(options?: { timeout?: number }): Promise<void>;
fill(value: string, options?: { timeout?: number }): Promise<void>;
press(key: string): Promise<void>;
selectOption(value: string | SelectValue): Promise<void>;
setChecked(checked: boolean): Promise<void>;
allTextContents(): Promise<string[]>;
isDisabled(): Promise<boolean>;
waitFor(options?: WaitOptions): Promise<void>;
dispatchEvent(type: string, init?: Record<string, unknown>): Promise<void>;
evaluate<R, A = unknown>(fn: (element: Element, arg: A) => R | Promise<R>, arg?: A): Promise<R>;
}
export interface InPagePage {
locator(selector: string): InPageLocator;
getByRole(role: string, options?: RoleOptions): InPageLocator;
evaluate<R, A = unknown>(fn: (arg: A) => R | Promise<R>, arg?: A): Promise<R>;
waitForTimeout(ms: number): Promise<void>;
waitForSelector(selector: string, options?: WaitOptions): Promise<Element>;
waitForFunction<R>(fn: (arg: Mutable) => R, arg?: Mutable, options?: { timeout?: number }): Promise<R>;
goto(url: string, options?: { waitUntil?: string; timeout?: number }): Promise<void>;
}
/** `:text-is("…")` is a Playwright pseudo-class; split it off before querySelector. */
function splitTextIs(selector: string): { css: string; want?: string } {
const match = /^(.*?):text-is\(\s*"((?:[^"\\]|\\.)*)"\s*\)\s*$/.exec(selector);
if (!match) return { css: selector };
return { css: match[1], want: match[2].replace(/\\(.)/g, "$1") };
}
/** Candidate markup for a role, so `getByRole("button")` finds real buttons too. */
function roleSelector(role: string): string {
const native: Record<string, string> = {
button: 'button, input[type="button"], input[type="submit"]',
checkbox: 'input[type="checkbox"]',
combobox: "select",
listbox: "select",
textbox: 'input:not([type]), input[type="text"], textarea',
};
const base = native[role];
return base ? `${base}, [role="${role}"]` : `[role="${role}"]`;
}
/** Accessible name as Playwright computes it, reduced to what the drivers use. */
function accessibleName(win: Window, element: Element): string {
const label = element.getAttribute("aria-label");
if (label) return label;
const by = element.getAttribute("aria-labelledby");
if (by) {
const text = by.split(/\s+/).map((id) => win.document.getElementById(id)?.textContent ?? "").join(" ");
if (text.trim()) return text;
}
if (element instanceof realm(win).HTMLInputElement || element instanceof realm(win).HTMLSelectElement
|| element instanceof realm(win).HTMLTextAreaElement) {
const wrapping = element.closest("label")?.textContent ?? "";
if (wrapping.trim()) return wrapping;
}
return element.textContent ?? "";
}
function norm(text: string): string { return text.replace(/\s+/g, " ").trim(); }
function isVisible(element: Element): boolean {
const html = element as HTMLElement;
if (!html.getClientRects().length) return false;
const style = (element.ownerDocument?.defaultView ?? window).getComputedStyle(html);
return style.visibility !== "hidden" && style.display !== "none";
}
class Locator implements InPageLocator {
constructor(
private readonly win: Window,
private readonly resolve: () => Element[],
private readonly firstOnly = false,
) {}
private all(): Element[] {
const found = this.resolve();
return this.firstOnly ? found.slice(0, 1) : found;
}
private one(): Element {
const found = this.all();
if (!found.length) throw new Error("no element matched the locator");
return found[0];
}
first(): InPageLocator { return new Locator(this.win, this.resolve, true); }
locator(selector: string): InPageLocator {
const parent = this;
return new Locator(this.win, () => {
const { css, want } = splitTextIs(selector);
const out: Element[] = [];
for (const root of parent.all()) {
for (const node of Array.from(root.querySelectorAll(css))) {
// Playwright normalizes whitespace on both sides of `:text-is`.
if (want === undefined || norm(node.textContent ?? "") === norm(want)) out.push(node);
}
}
return out;
}, this.firstOnly);
}
getByRole(role: string, options: RoleOptions = {}): InPageLocator {
const parent = this;
return new Locator(this.win, () => {
const out: Element[] = [];
for (const root of parent.all()) {
for (const node of Array.from(root.querySelectorAll(roleSelector(role)))) {
if (matchesName(accessibleName(this.win, node), options)) out.push(node);
}
}
return out;
}, this.firstOnly);
}
filter(options: FilterOptions): InPageLocator {
const parent = this;
return new Locator(this.win, () => parent.all().filter((node) => {
const text = norm(node.textContent ?? "");
const want = options.hasText;
if (want === undefined) return true;
return want instanceof RegExp ? want.test(node.textContent ?? "") : text.toLowerCase().includes(norm(want).toLowerCase());
}), this.firstOnly);
}
async count(): Promise<number> { return this.all().length; }
async waitFor(options: WaitOptions = {}): Promise<void> {
const deadline = Date.now() + (options.timeout ?? DEFAULT_TIMEOUT);
const state = options.state ?? "visible";
for (;;) {
const found = this.all();
if (state === "attached" ? found.length > 0 : found.some(isVisible)) return;
if (Date.now() > deadline) {
throw new Error(`waitFor(${state}) timed out after ${options.timeout ?? DEFAULT_TIMEOUT} ms`);
}
await this.waitForTimeout(100);
}
}
async click(options: { timeout?: number } = {}): Promise<void> {
const timeout = options.timeout ?? DEFAULT_TIMEOUT;
await this.waitFor({ state: "visible", timeout });
// Playwright's click() waits for the control to be enabled before acting.
// The workspace disables its toolbar until the kernel reports ready, so a
// click that did not wait would either fail outright or, worse, land on a
// page whose document does not exist yet. Re-resolve every poll: React
// replaces the button node on re-render.
const deadline = Date.now() + timeout;
for (;;) {
const candidate = this.all().find(isVisible) as Mutable;
const disabled = !candidate || candidate.disabled === true
|| candidate.getAttribute?.("aria-disabled") === "true";
if (!disabled) break;
if (Date.now() > deadline) {
throw new Error(`cannot click a disabled control (still disabled after ${timeout} ms)`);
}
await this.waitForTimeout(100);
}
const element = this.one() as HTMLElement;
element.scrollIntoView?.({ block: "center" });
// Playwright sends the full pointer sequence; React drag/pointer handlers on
// the workspace need it. `click()` alone only fires a `click` event.
const view = this.win;
const { PointerEvent: Pointer, MouseEvent: Mouse } = realm(view);
const base = { bubbles: true, cancelable: true, composed: true, view, button: 0, detail: 1 };
element.dispatchEvent(new Pointer("pointerover", base));
element.dispatchEvent(new Pointer("pointerenter", { ...base, bubbles: false }));
element.dispatchEvent(new Pointer("pointerdown", base));
element.dispatchEvent(new Mouse("mousedown", base));
element.focus?.();
element.dispatchEvent(new Pointer("pointerup", base));
element.dispatchEvent(new Mouse("mouseup", base));
element.click();
await this.waitForTimeout(0);
}
async fill(value: string, options: { timeout?: number } = {}): Promise<void> {
await this.waitFor({ state: "visible", timeout: options.timeout });
const element = this.one() as Mutable;
element.focus?.();
const proto = element instanceof realm(this.win).HTMLTextAreaElement
? realm(this.win).HTMLTextAreaElement.prototype : realm(this.win).HTMLInputElement.prototype;
const setter = Object.getOwnPropertyDescriptor(proto, "value")?.set;
// React keeps its own value tracker; a plain assignment is swallowed.
if (setter) setter.call(element, value); else element.value = value;
// Playwright's fill dispatches `input` only; the drivers that need a
// committed value dispatch `change` themselves.
const { Event: RealmEvent } = realm(this.win);
element.dispatchEvent(new RealmEvent("input", { bubbles: true }));
}
async press(key: string): Promise<void> {
await this.waitFor({ state: "visible" });
const element = this.one() as HTMLElement;
element.focus?.();
const init = { key, code: key, bubbles: true, cancelable: true, view: this.win };
const { KeyboardEvent: Key } = realm(this.win);
element.dispatchEvent(new Key("keydown", init));
if (key === "Enter" || key.length === 1) {
element.dispatchEvent(new Key("keypress", init));
}
element.dispatchEvent(new Key("keyup", init));
}
async selectOption(value: string | SelectValue): Promise<void> {
await this.waitFor({ state: "visible" });
const select = this.one() as HTMLSelectElement;
const options = Array.from(select.options);
let index = -1;
if (typeof value === "string") {
index = options.findIndex((option) => option.value === value);
// Some workspace selects carry no `value` attribute; the text is the value.
if (index < 0) index = options.findIndex((option) => norm(option.text) === norm(value));
if (index < 0) {
throw new Error(`no option "${value}"; available: ${options.map((o) => `${o.value}|${norm(o.text)}`).join(", ")}`);
}
} else if (value.index !== undefined) {
index = value.index;
} else if (value.value !== undefined) {
index = options.findIndex((option) => option.value === value.value);
} else if (value.label !== undefined) {
index = options.findIndex((option) => norm(option.text) === norm(value.label!));
}
if (index < 0 || index >= options.length) throw new Error(`selectOption(${JSON.stringify(value)}) matched nothing`);
select.selectedIndex = index;
const { Event: RealmEvent } = realm(this.win);
select.dispatchEvent(new RealmEvent("input", { bubbles: true }));
select.dispatchEvent(new RealmEvent("change", { bubbles: true }));
}
async setChecked(checked: boolean): Promise<void> {
await this.waitFor({ state: "visible" });
const element = this.one() as HTMLInputElement;
if (Boolean(element.checked) !== checked) await this.click();
}
async allTextContents(): Promise<string[]> {
return this.all().map((element) => element.textContent ?? "");
}
async isDisabled(): Promise<boolean> {
const element = this.one() as Mutable;
return element.disabled === true || element.getAttribute?.("aria-disabled") === "true";
}
async dispatchEvent(type: string, init: Record<string, unknown> = {}): Promise<void> {
const element = this.one();
const { Event: RealmEvent } = realm(this.win);
element.dispatchEvent(new RealmEvent(type, { bubbles: true, cancelable: true, ...init }));
}
async evaluate<R, A = unknown>(fn: (element: Element, arg: A) => R | Promise<R>, arg?: A): Promise<R> {
await this.waitFor({ state: "attached" });
return fn(this.one(), arg as A);
}
private waitForTimeout(ms: number): Promise<void> {
return new Promise((resolve) => this.win.setTimeout(resolve, ms));
}
}
function matchesName(name: string, options: RoleOptions): boolean {
const want = options.name;
if (want === undefined) return true;
if (want instanceof RegExp) return want.test(name);
return options.exact ? name === want : norm(name).toLowerCase() === norm(want).toLowerCase();
}
/**
* Build the page object over `win`.
*
* `goto` cannot navigate: the frame's document is this very script's realm, so
* loading another URL would tear the runner down mid-lesson. The console
* navigates the frame first (see `console/executor.ts`), and `goto` then either
* confirms it is already there or fails loudly.
*/
export function createInPagePage(win: Window): InPagePage {
const root = () => [win.document.documentElement].filter(Boolean) as Element[];
const page: InPagePage = {
locator(selector: string): InPageLocator {
return new Locator(win, () => {
const { css, want } = splitTextIs(selector);
const found = Array.from(win.document.querySelectorAll(css));
return want === undefined ? found : found.filter((node) => norm(node.textContent ?? "") === want);
});
},
getByRole(role: string, options: RoleOptions = {}): InPageLocator {
return new Locator(win, () => Array.from(win.document.querySelectorAll(roleSelector(role)))
.filter((node) => matchesName(accessibleName(win, node), options)));
},
async evaluate<R, A = unknown>(fn: (arg: A) => R | Promise<R>, arg?: A): Promise<R> {
return fn(arg as A);
},
waitForTimeout(ms: number): Promise<void> {
return new Promise((resolve) => win.setTimeout(resolve, ms));
},
async waitForSelector(selector: string, options: WaitOptions = {}): Promise<Element> {
await page.locator(selector).waitFor({ state: options.state ?? "visible", timeout: options.timeout });
const element = win.document.querySelector(splitTextIs(selector).css) ?? root()[0];
if (!element) throw new Error(`waitForSelector(${selector}) found nothing`);
return element;
},
async waitForFunction<R>(fn: (arg: Mutable) => R, arg?: Mutable, options: { timeout?: number } = {}): Promise<R> {
const deadline = Date.now() + (options.timeout ?? DEFAULT_TIMEOUT);
for (;;) {
const value = await fn(arg);
if (value) return value as R;
if (Date.now() > deadline) throw new Error(`waitForFunction timed out after ${options.timeout ?? DEFAULT_TIMEOUT} ms`);
await page.waitForTimeout(100);
}
},
async goto(url: string): Promise<void> {
const target = new URL(url, win.location.href);
const here = win.location;
const samePath = target.pathname === here.pathname && target.origin === here.origin;
const targetQuery = [...target.searchParams].sort().join("&");
const hereQuery = [...new URLSearchParams(here.search)].sort().join("&");
if (samePath && targetQuery === hereQuery) return;
throw new Error(`in-page runner cannot navigate to ${target.pathname}${target.search}; the console must load that page in the frame first`);
},
};
return page;
}

View File

@@ -0,0 +1,31 @@
// Where a finished lesson's report lands: OPFS `freecad-exports`, one file per run.
//
// Kept apart from `runner.ts` so the console page can persist a report without
// bundling the driver into its own chunk. Nothing here downloads anything --
// turning a stored report into a browser download stays an explicit user action.
import { writeExportFile } from "../storage.js";
import type { LessonReport } from "./types.js";
/** `teaching-<lessonId>-<utcstamp>.json`; `writeExportFile` wants a flat name. */
export function reportFileName(report: LessonReport): string {
const stamp = report.finishedAt.replace(/[-:]/g, "").replace(/\.\d+Z$/, "Z");
return `teaching-${report.lessonId}-${stamp}.json`.replace(/[^A-Za-z0-9._-]/g, "-");
}
/** Write the report to OPFS and return the name it was stored under. */
export async function persistReport(report: LessonReport): Promise<string> {
const bytes = new TextEncoder().encode(`${JSON.stringify(report, null, 1)}\n`);
return writeExportFile(reportFileName(report), bytes.buffer as ArrayBuffer);
}
/** Explicit user action only: the browser saves a copy where the user chooses. */
export function downloadReport(report: LessonReport): void {
const blob = new Blob([`${JSON.stringify(report, null, 1)}\n`], { type: "application/json" });
const url = URL.createObjectURL(blob);
const anchor = document.createElement("a");
anchor.href = url;
anchor.download = reportFileName(report);
anchor.click();
setTimeout(() => URL.revokeObjectURL(url), 10000);
}

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;
}

60
web/src/teaching/steps.ts Normal file
View File

@@ -0,0 +1,60 @@
// The `out/ui-steps/<document>.json` records, straight out of the course
// directories.
//
// They are globbed rather than copied: the course tooling owns them, they are
// already tracked in git, and a copy under `src/` would drift the first time a
// course is rebuilt. Vite emits one chunk per file, so a lesson only downloads
// the step list it is about to run.
export interface UiStep {
step: number;
label: string;
kind: string;
command: string;
page?: string;
object: string;
[key: string]: unknown;
}
export interface UiSteps {
schema: string;
document: string;
steps: UiStep[];
}
const FILES: Record<string, () => Promise<unknown>> = {
...import.meta.glob("../../tools/carrier-partdesign-course/out/ui-steps/*.json"),
...import.meta.glob("../../tools/reducer-parts-course/out/ui-steps/*.json"),
};
/**
* `index.json` in those directories is the course manifest
* (`ui-steps-index/v1`), not a document's step list, so it is not addressable
* by document name. Every other file is `<document>.json`.
*/
const MANIFEST = "index";
/** document name → loader. Two courses must not ship the same document. */
const BY_DOCUMENT = new Map<string, () => Promise<unknown>>();
for (const [key, load] of Object.entries(FILES)) {
const document = key.slice(key.lastIndexOf("/") + 1).replace(/\.json$/, "");
if (document === MANIFEST) continue;
const existing = BY_DOCUMENT.get(document);
if (existing && existing !== load) throw new Error(`两份课程都提供了 ${document} 的界面步骤`);
BY_DOCUMENT.set(document, load);
}
export function hasSteps(document: string): boolean {
return BY_DOCUMENT.has(document);
}
export function stepDocuments(): string[] {
return [...BY_DOCUMENT.keys()].sort();
}
export async function loadSteps(document: string): Promise<UiSteps> {
const load = BY_DOCUMENT.get(document);
if (!load) throw new Error(`没有 ${document} 的界面步骤记录(out/ui-steps)`);
const module = await load() as { default: UiSteps };
return module.default;
}

123
web/src/teaching/types.ts Normal file
View File

@@ -0,0 +1,123 @@
// Shapes shared by the in-app teaching console and the runner it drives.
//
// The console page and the runner live in different realms (parent document vs.
// workbench frame) but exchange ordinary objects, so one set of types covers
// both sides. Everything here is data: no DOM, no imports.
export type LessonKind = "preflight" | "carrier-part" | "reducer-part" | "carrier-assembly" | "reducer-assembly";
export interface PartJob {
kind: "carrier-part" | "reducer-part";
partId: string;
document: string;
title: string;
page: string;
steps: number;
/** Reference volume after each step; `null` where the replay recorded none. */
volumes: (number | null)[];
}
export interface AssemblyJob {
kind: "carrier-assembly" | "reducer-assembly";
document: string;
title: string;
page: string;
groundDocument: string | null;
saveBundle: boolean;
sourceDocuments: string[];
inserts: Array<{
sourceDocument: string;
sourceObject: string;
position: number[];
rotation: number[];
}>;
joints: Array<{ action: string; args: Record<string, unknown> | null }>;
solves: Array<{ action: string; args: Record<string, unknown> | null }>;
bom: Array<{ action: string; args: Record<string, unknown> | null }>;
}
export interface PreflightJob { kind: "preflight" }
export type LessonJob = PartJob | AssemblyJob | PreflightJob;
export interface LessonRunRequest {
lessonId: string;
title: string;
job: LessonJob;
}
/** One row of the results table, mirroring `ui-run/v1` so both channels agree. */
export interface StepRow {
step: number;
label: string;
kind: string;
command: string;
uiName: string | null;
volume: number | null;
expectedVolume: number | null;
volumeMatches: boolean | null;
status: string;
ms: number;
}
/** One prerequisite. A failing prerequisite blocks the lesson; it is not a product failure. */
export interface PreflightCheck {
id: string;
label: string;
ok: boolean;
detail: string;
}
export type RunEvent =
| { type: "phase"; phase: string; detail?: string }
| { type: "preflight"; check: PreflightCheck }
| { type: "step"; index: number; total: number; row: StepRow }
| { type: "log"; line: string };
export type Verdict = "pass" | "fail" | "blocked" | "cancelled";
export interface LessonReport {
schema: "freecad-web/teaching-console/in-app-run/v1";
lessonId: string;
title: string;
kind: LessonKind;
document: string | null;
startedAt: string;
finishedAt: string;
seconds: number;
verdict: Verdict;
reason: string;
steps: number;
stepsTotal: number;
failed: number;
volume: number | null;
expected: number | null;
relativeError: number | null;
preflight: PreflightCheck[];
results: StepRow[];
pageErrors: string[];
/** Part lessons: the FCStd stored under the course document name, if it worked. */
savedDocument?: string | null;
/** Assembly only: what the UI actually did, compared against the replay. */
assembly?: {
inserted: number;
expected: number;
joints: number;
expectedJoints: number;
solves: number;
mismatches: string[];
components: number;
malformed: number;
saved: unknown;
};
}
/** The contract the workbench page publishes for the console to call. */
export interface TeachingBridge {
ready: true;
/** `page` is the shell page this workbench is currently showing. */
page: string;
run(request: LessonRunRequest, onEvent?: (event: RunEvent) => void): Promise<LessonReport>;
cancel(): void;
running(): boolean;
}

View File

@@ -5,11 +5,14 @@
// <WorkbenchShell /> without side effects on its own document.
import { createRoot } from "react-dom/client";
import { installNavigation, readNavigationContext } from "./navigation.js";
import { installTeachingBridge } from "./teaching/bridge.js";
import { installUiAccessibility } from "./ui-accessibility.js";
import { WorkbenchShell } from "./workbench-shell.js";
installNavigation("workbench", readNavigationContext());
installUiAccessibility();
// Lets the in-app teaching console drive this page across the iframe boundary.
installTeachingBridge();
const container = document.querySelector<HTMLDivElement>("#app");
if (!container) throw new Error("workbench entry: #app container is missing");

13
web/teaching-console.html Normal file
View File

@@ -0,0 +1,13 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="icon" href="data:," />
<title>Web FreeCAD 教学控制台</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/teaching-console-entry.tsx"></script>
</body>
</html>

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);

17
web/tsconfig.json Normal file
View File

@@ -0,0 +1,17 @@
{
"compilerOptions": {
"target": "ES2022",
"useDefineForClassFields": true,
"module": "ESNext",
"moduleResolution": "Bundler",
"jsx": "react-jsx",
"strict": true,
"noEmit": true,
"skipLibCheck": true,
"isolatedModules": true,
"allowJs": true,
"resolveJsonModule": true,
"types": ["vite/client"]
},
"include": ["src"]
}

View File

@@ -34,6 +34,7 @@ export default defineConfig({
"shell-preview": "shell-preview.html",
full: "full.html",
workbench: "workbench.html",
"teaching-console": "teaching-console.html",
python: "python.html",
assembly: "assembly.html",
bim: "bim.html",