feat(teaching): browser console that runs the functional suite by workbench
A lesson-oriented page plus a loopback job service: click a lesson and the page really runs tools/web-freecad-functional-suite.mjs, tools/layout-probe.mjs or tools/static-host.mjs, streaming logs and rendering verdicts from the suite's own manifest/checkpoint/results files. - web/tools/teaching-console: catalog derived from scenarios + registry, 73 workbench lessons, template, builder (--check), Playwright gate, no-browser self-test for every spawn validation path - web/teaching/suite-runner.mjs: argv whitelist, env whitelist, single concurrent job, process-group cancel, ring-buffered logs, preflight - web/teaching/server.mjs: /api/console/* routes with startup token, Origin check, SSE events, artifact serving; existing routes untouched - preflight blocks runs (E_PREFLIGHT) instead of starting without dist, Chrome, DISPLAY, kernel or Playwright - gates: self-test OK, build --check idempotent, offline + live Playwright (MOD-Part-01 pass, cancel path) OK Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
@@ -44,6 +44,9 @@
|
||||
"check:manual": "node tools/manual/check-page.mjs",
|
||||
"manual:tools": "node ../tools/build-tools-manual.mjs",
|
||||
"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",
|
||||
"teach:console": "node teaching/server.mjs",
|
||||
"prebuild": "npm run sync-show-python-family-fixture && npm run check:geometry-boundary",
|
||||
"dev": "npm run sync-api-index && npm run sync-object-index && npm run sync-format-index && npm run sync-module-registry && npm run sync-part-tier2-adapter && npm run sync-partdesign-tier2-adapter && npm run sync-sketcher-tier2-adapter && npm run sync-techdraw-tier2-adapter && npm run sync-import-tier2-adapter && npm run sync-mesh-tier2-adapter && npm run sync-material-tier1-adapter && npm run sync-tier2-remainder && npm run sync-tier3-stateful && npm run sync-viewprovider-index && npm run sync-property-index && npm run sync-geometry-index && npm run sync-document-graph-index && npm run sync-capability-index && npm run sync-tier1-readonly && npm run sync-tier4-restricted && npm run sync-api-adapter-fill && npm run sync-format-extensions && npm run sync-kernel && npm run sync-release-manifest && vite --host 0.0.0.0",
|
||||
"build": "npm run sync-api-index && npm run sync-object-index && npm run sync-format-index && npm run sync-module-registry && npm run sync-part-tier2-adapter && npm run sync-partdesign-tier2-adapter && npm run sync-sketcher-tier2-adapter && npm run sync-techdraw-tier2-adapter && npm run sync-import-tier2-adapter && npm run sync-mesh-tier2-adapter && npm run sync-material-tier1-adapter && npm run sync-tier2-remainder && npm run sync-tier3-stateful && npm run sync-viewprovider-index && npm run sync-property-index && npm run sync-geometry-index && npm run sync-document-graph-index && npm run sync-capability-index && npm run sync-tier1-readonly && npm run sync-tier4-restricted && npm run sync-api-adapter-fill && npm run sync-format-extensions && npm run sync-kernel && npm run sync-release-manifest && tsc --noEmit && vite build",
|
||||
|
||||
152
web/teaching/README.md
Normal file
152
web/teaching/README.md
Normal file
@@ -0,0 +1,152 @@
|
||||
# FreeCAD Web 官方案例 · 初学者教学目录
|
||||
|
||||
本目录把 278 条已通过验收的官方案例,转成可阅读、可亲手执行的教学材料。
|
||||
它不改动 Web 应用本身,只读取账本、证据与工作台,因此可以安全地独立运行。
|
||||
|
||||
## 目录结构
|
||||
|
||||
| 文件 | 作用 |
|
||||
| --- | --- |
|
||||
| `index.html` | 图文手册:项目在做什么、验收十步、七道关、动手演示、术语表、截图墙 |
|
||||
| `runner.html` | 278 案例可视化执行页:搜索、按模块过滤、单个案例有头执行并截图 |
|
||||
| `server.mjs` | 教学服务:静态页 + `/data` + `/evidence` + `POST /api/run` |
|
||||
| `run-case.mjs` | 单案例有头执行器:打开工作台、选中命令、点击执行、截图、输出 JSON |
|
||||
| `generate-cases.mjs` | 从账本与目录生成 `data/cases.json` |
|
||||
| `generate-features.mjs` | 从模块注册表、manifest、dist 内核与账本生成 `data/features.json`(32 模块功能清单) |
|
||||
| `features.html` | 功能列表页:模块命令数、Python API 数、对象类型、探针体积、已验证案例、页面入口 |
|
||||
| `data/cases.json` | 教学数据(自动生成,勿手改) |
|
||||
| `cases/engine-block.html` | 案例教学:在 Web 中建 4 缸发动机缸体(含设计参数、逐步建模、验证与复现) |
|
||||
| `cases/t1-replica.html` | 案例教学:导入 t1.stp、切片测量、用图元与布尔复刻并做体积对账 |
|
||||
| `cases/secondary-reducer.html` | 案例教学:在 Web 中建二级齿轮减速器(PartDesign 渐开线齿轮 + GB/T 1095 键槽 + 有头界面截图 + STEP/FCStd,见 `cases/secondary-reducer/`) |
|
||||
| `cases/assembly-tolerance.html` | 案例教学:装配公差分析(四块板真实装配 + 网格提取 + 极值/RSS/蒙特卡洛/分配/Cpk + OPFS 报告,见 `cases/assembly-tolerance/`) |
|
||||
| `cases/cam-teaching.html` | 案例教学:三轴 CAM(真实 Job/毛坯/6 mm 刀具 + Profile/Pocket/RampEntry + 3D 仿真 + GRBL/LinuxCNC + G-code 查看 + OPFS,见 `cases/cam-teaching/`) |
|
||||
| `cases/carrier.html` | 案例教学:航空母舰(20 对象 Part 模型 + React 查看器 + BOM/排水量/GM/甲板容量 + GA SVG + 等效甲板梁 FEM + 中文配音培训视频,见 `cases/carrier/`) |
|
||||
| `cases/t1-replica/out/` | 程序化重建报告(体积偏差 69.86%,用于说明图元复刻的边界) |
|
||||
| `../../test/t1-web-freecad.stp` | A 路径交付件:Web FreeCAD 导入-导出往返,几何与原 t1.stp 一致 |
|
||||
| `cases/engine-block/` | 缸体构建脚本 `build-engine-block.mjs`、three.js 渲染页 `render.html`、有头截图 `capture-render.mjs`、复现性对比 `compare-builds.mjs` 与 `out/` 产物 |
|
||||
| `assets/three.module.min.js`、`assets/three.core.min.js` | 渲染页使用的 three.js 本地副本(渲染页从 `../../assets/` 引入) |
|
||||
| `../../docs/current/teaching-runs/` | 可视化执行产生的截图与结果 |
|
||||
|
||||
## 启动
|
||||
|
||||
前置条件是 Web 应用已运行(默认 `http://127.0.0.1:5180`)。
|
||||
|
||||
```bash
|
||||
# 1) 重新生成教学数据(账本变化后执行)
|
||||
node /media/mes123456/Elements SE/WebFreeCAD/FreeCADWasmDev/working/FreeCAD/web/teaching/generate-cases.mjs
|
||||
|
||||
# 2) 启动教学服务(默认 http://127.0.0.1:5190)
|
||||
TEACHING_PORT=5190 FREECAD_APP_ORIGIN=http://127.0.0.1:5180 \
|
||||
node /media/mes123456/Elements SE/WebFreeCAD/FreeCADWasmDev/working/FreeCAD/web/teaching/server.mjs
|
||||
|
||||
# 3) 浏览器打开
|
||||
# 手册:http://127.0.0.1:5190/index.html
|
||||
# 执行页:http://127.0.0.1:5190/runner.html
|
||||
```
|
||||
|
||||
## 功能列表
|
||||
|
||||
```bash
|
||||
node /media/mes123456/Elements SE/WebFreeCAD/FreeCADWasmDev/working/FreeCAD/web/teaching/generate-features.mjs
|
||||
```
|
||||
|
||||
产物是 `data/features.json`,页面是 `http://127.0.0.1:5190/features.html`。
|
||||
数据全部来自代码:模块注册表、manifest、`dist/kernel` 真实文件大小与官方案例账本,
|
||||
因此不会与实现漂移。口径提醒:命令数与 Python API 数单位不同,不能相加。
|
||||
|
||||
## t1 复刻案例
|
||||
|
||||
```bash
|
||||
# 程序化重建(教学对照,含真实偏差)
|
||||
node /media/mes123456/Elements SE/WebFreeCAD/FreeCADWasmDev/working/FreeCAD/web/teaching/cases/t1-replica/build-t1-replica.mjs
|
||||
```
|
||||
|
||||
A 路径(几何完全一致)在 `FreeCADWebDocumentProbe` 内完成导入与导出,
|
||||
交付文件 `working/test/t1-web-freecad.stp`;原 `t1.stp` 不被覆盖。
|
||||
|
||||
## 缸体案例(engine-block)
|
||||
|
||||
```bash
|
||||
# 建模 + 导出 STEP/FCStd + 生成渲染网格
|
||||
node /media/mes123456/Elements SE/WebFreeCAD/FreeCADWasmDev/working/FreeCAD/web/teaching/cases/engine-block/build-engine-block.mjs
|
||||
# 有头渲染四视图截图(依赖 out/engine-block-mesh.json)
|
||||
node /media/mes123456/Elements SE/WebFreeCAD/FreeCADWasmDev/working/FreeCAD/web/teaching/cases/engine-block/capture-render.mjs
|
||||
|
||||
二级减速器案例复现(精确版:参数化渐开线齿轮 + GB/T 1095 键槽):
|
||||
|
||||
```bash
|
||||
HEADLESS=0 node /media/mes123456/Elements SE/WebFreeCAD/FreeCADWasmDev/working/FreeCAD/web/teaching/cases/secondary-reducer/ui-gears.mjs
|
||||
node /media/mes123456/Elements SE/WebFreeCAD/FreeCADWasmDev/working/FreeCAD/web/teaching/cases/secondary-reducer/build-shafts-keys.mjs
|
||||
node /media/mes123456/Elements SE/WebFreeCAD/FreeCADWasmDev/working/FreeCAD/web/teaching/cases/secondary-reducer/build-gear-fit.mjs
|
||||
node /media/mes123456/Elements SE/WebFreeCAD/FreeCADWasmDev/working/FreeCAD/web/teaching/cases/secondary-reducer/build-assembly.mjs
|
||||
node /media/mes123456/Elements SE/WebFreeCAD/FreeCADWasmDev/working/FreeCAD/web/teaching/cases/secondary-reducer/render-assembly-parts.mjs
|
||||
```
|
||||
# 连续两次构建比对体积与 STEP
|
||||
node /media/mes123456/Elements SE/WebFreeCAD/FreeCADWasmDev/working/FreeCAD/web/teaching/cases/engine-block/compare-builds.mjs
|
||||
```
|
||||
|
||||
3D 预览页:`http://127.0.0.1:5190/cases/engine-block/render.html`;
|
||||
教学页:`http://127.0.0.1:5190/cases/engine-block.html`。
|
||||
|
||||
## 有头执行
|
||||
|
||||
执行页的按钮会调用 `POST /api/run`,服务端再启动 `run-case.mjs`,
|
||||
以 `headless:false` 打开真实 Chrome 窗口。你会看到页面自动选中模块与命令、
|
||||
点击「执行选中命令」,随后返回结果并自动截图。
|
||||
|
||||
```bash
|
||||
# 命令行方式(等价于页面按钮)
|
||||
node /media/mes123456/Elements SE/WebFreeCAD/FreeCADWasmDev/working/FreeCAD/web/teaching/run-case.mjs \
|
||||
--module Inspection --command inspection.createRecompute \
|
||||
--case real.Inspection:inspection.createRecompute \
|
||||
--origin http://127.0.0.1:5180
|
||||
```
|
||||
|
||||
- 默认有头(`HEADLESS=1` 可切无头,仅用于排查)。
|
||||
- 需要图形环境(本机 `DISPLAY=:1`)与 `/usr/bin/google-chrome`。
|
||||
- 截图写入 `docs/current/teaching-runs/`,不覆盖既有验收证据。
|
||||
|
||||
## 数据口径
|
||||
|
||||
`generate-cases.mjs` 只收录账本中 `status === "passed"` 的行,
|
||||
并合并目录里的 `module`、`command`、`sourcePath`:
|
||||
|
||||
- `executable`:目录中同时有 `module` 与 `command`,可在工作台深链执行。
|
||||
- `payloadFixture`:该命令在 `workbench-shell.tsx` 的 `PAYLOADS` 中有官方默认参数。
|
||||
- `hasImage` / `jsonCount`:证据文件在磁盘上真实存在的数量。
|
||||
|
||||
因此页面上的「可执行」是真实可达的入口,而不是推测。
|
||||
没有独立命令入口的案例仍可阅读其验收证据、结果 JSON 与截图。
|
||||
|
||||
## 注意
|
||||
|
||||
- 这是教学目录,不是验收脚本;它不会写账本,也不会修改案例状态。
|
||||
- 若账本或工作台命令注册表更新,重新运行 `generate-cases.mjs` 即可同步。
|
||||
- 教学服务只监听 `127.0.0.1`,不对外暴露。
|
||||
|
||||
## 教学控制台(console.html)
|
||||
|
||||
按工作台组织的课程页:点击课程即可调用真实工具(功能测试套件、布局探针、静态服务),
|
||||
页面实时显示日志、进度、判定与证据。生成与校验:
|
||||
|
||||
```bash
|
||||
cd web
|
||||
npm run build:console # 由课程数据生成 teaching/console.html
|
||||
npm run check:console # 字节幂等 + 白名单/参数校验自测
|
||||
DISPLAY=:1 node tools/teaching-console/check-console.mjs --offline # 离线只读门禁
|
||||
DISPLAY=:1 node tools/teaching-console/check-console.mjs --live # 在线运行一条模块冒烟 + 取消路径
|
||||
```
|
||||
|
||||
启动服务(默认 `127.0.0.1:5190`,打印带 token 的 console 地址):
|
||||
|
||||
```bash
|
||||
cd web && DISPLAY=:1 npm run teach:console
|
||||
```
|
||||
|
||||
- 课程数据:`web/tools/teaching-console/lessons.mjs`(按工作台分组;用例 id 由 `catalog.mjs`
|
||||
从场景、注册表与套件源码推导,引用了不存在的 id 会构建失败)。
|
||||
- 服务端:`web/teaching/server.mjs` 的 `/api/console/*`(token 保护 POST、Origin 校验、单任务并发),
|
||||
任务执行在 `web/teaching/suite-runner.mjs`(argv 白名单、进程组取消、日志环形缓冲)。
|
||||
- 运行证据写入 `docs/current/teaching-console/runs/<jobId>/`;进度读取套件自己的
|
||||
`manifest.json` / `checkpoint.json` / `results.json`,不解析 stdout。
|
||||
- 前置未满足时服务返回 `E_PREFLIGHT` 并禁用运行按钮(铁律:先准备前置,再做产品断言)。
|
||||
437
web/teaching/console.html
Normal file
437
web/teaching/console.html
Normal file
File diff suppressed because one or more lines are too long
@@ -80,6 +80,7 @@
|
||||
<a href="#glossary">术语</a>
|
||||
<a href="features.html">功能列表</a>
|
||||
<a href="runner.html">可视化执行 →</a>
|
||||
<a href="console.html">教学控制台 →</a>
|
||||
</nav>
|
||||
</div>
|
||||
</header>
|
||||
@@ -214,7 +215,7 @@
|
||||
</li>
|
||||
</ol>
|
||||
|
||||
<p><a class="cta" href="runner.html">打开可视化执行页</a><a class="cta secondary" href="features.html">查看 32 个模块的功能列表</a><a class="cta" href="cases/engine-block.html">案例教学:4 缸发动机缸体</a><a class="cta secondary" href="cases/t1-replica.html">案例教学:照 t1.stp 复刻零件</a><a class="cta secondary" href="cases/secondary-reducer.html">案例教学:二级齿轮减速器(界面操作)</a><a class="cta" href="cases/assembly-tolerance.html">案例教学:装配公差分析(初学者)</a><a class="cta" href="cases/cam-teaching.html">案例教学:三轴 CAM(初学者)</a><a class="cta" href="cases/carrier.html">案例教学:航空母舰(含培训视频)</a><a class="cta" href="cases/fem-cantilever.html">案例教学:FEM 悬臂梁(应力云图)</a><a class="cta" href="cases/production-line.html">案例教学:三维产线(有头界面 + MCP)</a><a class="cta" href="cases/abb120-line.html">案例教学:ABB IRB 120 产线(MCP)</a><a class="cta" href="cases/production-line-course.html">视频课程:27 件 GLB 产线建模(18 集)</a><a class="cta secondary" href="z-up-verification.html">Three.js Z-up 验证报告</a><a class="cta" href="http://127.0.0.1:5180/bim-workshop.html">BIM 厂房车间(30×18m)</a><a class="cta secondary" href="bim-workshop-tutorial.html">BIM 厂房教程</a><a class="cta secondary" href="bim-workshop-manual.html">BIM 厂房初学者手册(视频)</a><a class="cta secondary" href="http://127.0.0.1:5180/workbench.html?module=Inspection&command=inspection.createRecompute" target="_blank" rel="noopener">直接打开这条案例</a></p>
|
||||
<p><a class="cta" href="runner.html">打开可视化执行页</a><a class="cta" href="console.html">打开教学控制台(按工作台课程在线运行真实用例)</a><a class="cta secondary" href="features.html">查看 32 个模块的功能列表</a><a class="cta" href="cases/engine-block.html">案例教学:4 缸发动机缸体</a><a class="cta secondary" href="cases/t1-replica.html">案例教学:照 t1.stp 复刻零件</a><a class="cta secondary" href="cases/secondary-reducer.html">案例教学:二级齿轮减速器(界面操作)</a><a class="cta" href="cases/reducer-course.html">视频课程:二级减速器生产级建模(12 集)</a><a class="cta secondary" href="reducer-manual.html">初学者手册:二级减速器</a><a class="cta" href="cases/reducer-replay.html">过程可视化:二级减速器建模回放(24 件 + 装配)</a><a class="cta" href="cases/reducer-parts-course.html">逐零件建模过程视频(23 集 + 中文配音)</a><a class="cta secondary" href="reducer-parts-manual.html">零件设计入门:图文教案(14 章)</a><a class="cta" href="fcweb-toolkit.html">工具库:建零件与装配的通用工具(API 指南)</a><a class="cta" href="cases/assembly-tolerance.html">案例教学:装配公差分析(初学者)</a><a class="cta" href="cases/cam-teaching.html">案例教学:三轴 CAM(初学者)</a><a class="cta" href="cases/carrier.html">案例教学:航空母舰(含培训视频)</a><a class="cta" href="cases/fem-cantilever.html">案例教学:FEM 悬臂梁(应力云图)</a><a class="cta" href="cases/production-line.html">案例教学:三维产线(有头界面 + MCP)</a><a class="cta" href="cases/abb120-line.html">案例教学:ABB IRB 120 产线(MCP)</a><a class="cta" href="cases/production-line-course.html">视频课程:27 件 GLB 产线建模(18 集)</a><a class="cta secondary" href="z-up-verification.html">Three.js Z-up 验证报告</a><a class="cta" href="http://127.0.0.1:5180/bim-workshop.html">BIM 厂房车间(30×18m)</a><a class="cta secondary" href="bim-workshop-tutorial.html">BIM 厂房教程</a><a class="cta secondary" href="bim-workshop-manual.html">BIM 厂房初学者手册(视频)</a><a class="cta secondary" href="http://127.0.0.1:5180/workbench.html?module=Inspection&command=inspection.createRecompute" target="_blank" rel="noopener">直接打开这条案例</a></p>
|
||||
</section>
|
||||
|
||||
<section id="gallery">
|
||||
|
||||
312
web/teaching/server.mjs
Normal file
312
web/teaching/server.mjs
Normal file
@@ -0,0 +1,312 @@
|
||||
#!/usr/bin/env node
|
||||
// Teaching console server: serves the manual pages, the generated case data,
|
||||
// the real evidence files and a POST /api/run endpoint that executes one case
|
||||
// in a HEADED Chrome window (run-case.mjs) so a beginner can watch it happen.
|
||||
import fs from "node:fs";
|
||||
import http from "node:http";
|
||||
import path from "node:path";
|
||||
import crypto from "node:crypto";
|
||||
import { spawn } from "node:child_process";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { JobError, createRunner } from "./suite-runner.mjs";
|
||||
|
||||
const here = path.dirname(fileURLToPath(import.meta.url));
|
||||
const repoRoot = path.resolve(here, "../..");
|
||||
const port = Number(process.env.TEACHING_PORT || "5190");
|
||||
// TEACHING_PORT=0 binds an ephemeral port; the Origin check must use the real one.
|
||||
let boundPort = port;
|
||||
const appOrigin = process.env.FREECAD_APP_ORIGIN || "http://127.0.0.1:5180";
|
||||
// Random per-process token guards the endpoints that spawn processes. The page
|
||||
// receives it in the console URL; EventSource passes it back as ?token=.
|
||||
const token = process.env.TEACHING_TOKEN || crypto.randomBytes(16).toString("hex");
|
||||
const runner = createRunner();
|
||||
|
||||
const types = {
|
||||
".html": "text/html; charset=utf-8",
|
||||
".js": "text/javascript; charset=utf-8",
|
||||
".mjs": "text/javascript; charset=utf-8",
|
||||
".css": "text/css; charset=utf-8",
|
||||
".json": "application/json; charset=utf-8",
|
||||
".png": "image/png",
|
||||
".jpg": "image/jpeg",
|
||||
".jpeg": "image/jpeg",
|
||||
".svg": "image/svg+xml",
|
||||
".txt": "text/plain; charset=utf-8",
|
||||
".md": "text/plain; charset=utf-8",
|
||||
".mp4": "video/mp4",
|
||||
".webm": "video/webm",
|
||||
".vtt": "text/vtt; charset=utf-8",
|
||||
".srt": "application/x-subrip; charset=utf-8",
|
||||
".m4a": "audio/mp4",
|
||||
};
|
||||
|
||||
function sendFile(request, response, filePath) {
|
||||
if (!fs.existsSync(filePath) || !fs.statSync(filePath).isFile()) {
|
||||
response.writeHead(404, { "content-type": "text/plain; charset=utf-8" });
|
||||
response.end("not found");
|
||||
return;
|
||||
}
|
||||
const stat = fs.statSync(filePath);
|
||||
const extension = path.extname(filePath).toLowerCase();
|
||||
const media = [".mp4", ".webm", ".m4a", ".vtt", ".srt"].includes(extension);
|
||||
const headers = {
|
||||
"content-type": types[extension] ?? "application/octet-stream",
|
||||
// Video must be cacheable and range-readable for seeking; HTML/data stay fresh.
|
||||
"cache-control": media ? "public, max-age=3600" : "no-store",
|
||||
"access-control-allow-origin": "*",
|
||||
"access-control-expose-headers": "content-length, content-range, accept-ranges",
|
||||
"accept-ranges": "bytes",
|
||||
};
|
||||
const range = request.headers.range;
|
||||
if (range) {
|
||||
const match = /^bytes=(\d*)-(\d*)$/.exec(String(range).trim());
|
||||
if (!match || (match[1] === "" && match[2] === "")) {
|
||||
response.writeHead(416, { ...headers, "content-range": `bytes */${stat.size}` });
|
||||
response.end();
|
||||
return;
|
||||
}
|
||||
let start;
|
||||
let end;
|
||||
if (match[1] === "") {
|
||||
const suffix = Number(match[2]);
|
||||
if (!Number.isFinite(suffix) || suffix <= 0) {
|
||||
response.writeHead(416, { ...headers, "content-range": `bytes */${stat.size}` });
|
||||
response.end();
|
||||
return;
|
||||
}
|
||||
start = Math.max(stat.size - suffix, 0);
|
||||
end = stat.size - 1;
|
||||
} else {
|
||||
start = Number(match[1]);
|
||||
end = match[2] === "" ? stat.size - 1 : Number(match[2]);
|
||||
if (!Number.isFinite(start) || !Number.isFinite(end) || start > end || start >= stat.size) {
|
||||
response.writeHead(416, { ...headers, "content-range": `bytes */${stat.size}` });
|
||||
response.end();
|
||||
return;
|
||||
}
|
||||
end = Math.min(end, stat.size - 1);
|
||||
}
|
||||
response.writeHead(206, {
|
||||
...headers,
|
||||
"content-range": `bytes ${start}-${end}/${stat.size}`,
|
||||
"content-length": String(end - start + 1),
|
||||
});
|
||||
if (request.method === "HEAD") { response.end(); return; }
|
||||
fs.createReadStream(filePath, { start, end }).pipe(response);
|
||||
return;
|
||||
}
|
||||
response.writeHead(200, { ...headers, "content-length": String(stat.size) });
|
||||
if (request.method === "HEAD") { response.end(); return; }
|
||||
fs.createReadStream(filePath).pipe(response);
|
||||
}
|
||||
|
||||
function within(root, target) {
|
||||
const resolved = path.resolve(target);
|
||||
return resolved === root || resolved.startsWith(`${root}${path.sep}`);
|
||||
}
|
||||
|
||||
const running = new Map();
|
||||
|
||||
/* ------------------------------------------------------ console API helpers */
|
||||
|
||||
function sendJson(response, status, payload) {
|
||||
response.writeHead(status, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" });
|
||||
response.end(JSON.stringify(payload));
|
||||
}
|
||||
|
||||
async function readBody(request, limit = 8192) {
|
||||
let size = 0;
|
||||
const chunks = [];
|
||||
for await (const chunk of request) {
|
||||
size += chunk.length;
|
||||
if (size > limit) throw new JobError("E_BODY", "请求体过大");
|
||||
chunks.push(chunk);
|
||||
}
|
||||
try {
|
||||
return JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}");
|
||||
} catch {
|
||||
throw new JobError("E_BODY", "请求体不是 JSON");
|
||||
}
|
||||
}
|
||||
|
||||
function tokenOk(request, url) {
|
||||
const header = request.headers["x-teaching-token"];
|
||||
const provided = typeof header === "string" ? header : (url.searchParams.get("token") ?? "");
|
||||
if (provided.length !== token.length) return false;
|
||||
return crypto.timingSafeEqual(Buffer.from(provided), Buffer.from(token));
|
||||
}
|
||||
|
||||
function originOk(request) {
|
||||
const origin = request.headers.origin;
|
||||
if (!origin) return true;
|
||||
return origin === `http://127.0.0.1:${boundPort}` || origin === `http://localhost:${boundPort}`;
|
||||
}
|
||||
|
||||
const JOB_STATUS = { E_LESSON: 404, E_PARAM: 400, E_BUSY: 409, E_PREFLIGHT: 409, E_NO_JOB: 404, E_NOT_RUNNING: 409, E_BODY: 400 };
|
||||
|
||||
function handleConsoleApi(request, response, url, pathname) {
|
||||
const sub = pathname.slice("/api/console/".length);
|
||||
const method = request.method ?? "GET";
|
||||
const route = async () => {
|
||||
if (sub === "health" && method === "GET") {
|
||||
sendJson(response, 200, { schema: "freecad-web-teaching-console/v1", origin: `http://127.0.0.1:${port}`, preflight: runner.preflight().ok });
|
||||
return;
|
||||
}
|
||||
if (sub === "lessons" && method === "GET") { sendJson(response, 200, runner.catalog().lessons); return; }
|
||||
if (sub === "preflight" && method === "GET") { sendJson(response, 200, runner.preflight()); return; }
|
||||
if ((sub === "run" || sub === "cancel") && method === "POST") {
|
||||
if (!originOk(request)) { sendJson(response, 403, { code: "E_ORIGIN", error: "来源不在白名单" }); return; }
|
||||
if (!tokenOk(request, url)) { sendJson(response, 401, { code: "E_TOKEN", error: "缺少或错误的 token" }); return; }
|
||||
const body = await readBody(request);
|
||||
if (sub === "run") {
|
||||
sendJson(response, 202, runner.start({ lessonId: String(body.lessonId ?? ""), params: body.params ?? {} }));
|
||||
} else {
|
||||
sendJson(response, 200, runner.cancel(String(body.jobId ?? "")));
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (sub === "events" && method === "GET") {
|
||||
const jobId = url.searchParams.get("jobId") ?? "";
|
||||
try {
|
||||
runner.get(jobId);
|
||||
} catch (error) {
|
||||
sendJson(response, 404, { code: "E_NO_JOB", error: "找不到该任务" });
|
||||
return;
|
||||
}
|
||||
response.writeHead(200, {
|
||||
"content-type": "text/event-stream; charset=utf-8",
|
||||
"cache-control": "no-store",
|
||||
connection: "keep-alive",
|
||||
"x-accel-buffering": "no",
|
||||
});
|
||||
const send = (event, data) => response.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);
|
||||
const unsubscribe = runner.subscribe(jobId, send);
|
||||
const ping = setInterval(() => response.write(": ping\n\n"), 15000);
|
||||
request.on("close", () => { clearInterval(ping); unsubscribe(); });
|
||||
return;
|
||||
}
|
||||
const jobMatch = /^job\/([^/]+)$/.exec(sub);
|
||||
if (jobMatch && method === "GET") { sendJson(response, 200, runner.get(jobMatch[1])); return; }
|
||||
const artifactMatch = /^artifacts\/([^/]+)\/(.+)$/.exec(sub);
|
||||
if (artifactMatch && method === "GET") {
|
||||
sendFile(request, response, runner.artifact(artifactMatch[1], decodeURIComponent(artifactMatch[2])));
|
||||
return;
|
||||
}
|
||||
sendJson(response, 404, { code: "E_ROUTE", error: "未知接口" });
|
||||
};
|
||||
route().catch((error) => {
|
||||
if (error instanceof JobError) {
|
||||
sendJson(response, JOB_STATUS[error.code] ?? 500, { code: error.code, error: error.message, detail: error.detail ?? null });
|
||||
} else {
|
||||
sendJson(response, 500, { code: "E_INTERNAL", error: error instanceof Error ? error.message : String(error) });
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function runCase(body) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const { moduleName, command, caseId, payload } = body;
|
||||
if (!moduleName || !command) { reject(new Error("moduleName and command are required")); return; }
|
||||
const args = [
|
||||
path.join(here, "run-case.mjs"),
|
||||
"--module", String(moduleName),
|
||||
"--command", String(command),
|
||||
"--case", String(caseId || `${moduleName}-${command}`),
|
||||
"--origin", appOrigin,
|
||||
"--artifacts", path.join(repoRoot, "docs", "current", "teaching-runs"),
|
||||
];
|
||||
if (payload) args.push("--payload", String(payload));
|
||||
const child = spawn(process.execPath, args, { cwd: repoRoot, env: { ...process.env, HEADLESS: process.env.HEADLESS ?? "0" } });
|
||||
let stdout = "";
|
||||
let stderr = "";
|
||||
child.stdout.on("data", chunk => { stdout += chunk; });
|
||||
child.stderr.on("data", chunk => { stderr += chunk; });
|
||||
child.on("error", reject);
|
||||
child.on("close", code => {
|
||||
const line = stdout.trim().split("\n").filter(Boolean).at(-1) ?? "{}";
|
||||
let parsed;
|
||||
try { parsed = JSON.parse(line); } catch { parsed = { ok: false, error: line.slice(0, 400) }; }
|
||||
parsed.exitCode = code;
|
||||
parsed.stderrTail = stderr.slice(-1200);
|
||||
resolve(parsed);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
const server = http.createServer(async (request, response) => {
|
||||
const url = new URL(request.url ?? "/", `http://127.0.0.1:${port}`);
|
||||
const pathname = decodeURIComponent(url.pathname);
|
||||
|
||||
if (request.method === "OPTIONS") {
|
||||
response.writeHead(204, { "access-control-allow-origin": "*", "access-control-allow-headers": "content-type", "access-control-allow-methods": "GET,POST" });
|
||||
response.end();
|
||||
return;
|
||||
}
|
||||
|
||||
if (pathname.startsWith("/api/console/")) {
|
||||
handleConsoleApi(request, response, url, pathname);
|
||||
return;
|
||||
}
|
||||
|
||||
if (pathname === "/api/health") {
|
||||
response.writeHead(200, { "content-type": "application/json; charset=utf-8" });
|
||||
response.end(JSON.stringify({ ok: true, appOrigin, cases: path.join(here, "data/cases.json") }));
|
||||
return;
|
||||
}
|
||||
|
||||
if (pathname === "/api/run" && request.method === "POST") {
|
||||
let raw = "";
|
||||
for await (const chunk of request) raw += chunk;
|
||||
try {
|
||||
const body = JSON.parse(raw || "{}");
|
||||
const key = `${body.caseId}`;
|
||||
if (running.has(key)) {
|
||||
response.writeHead(409, { "content-type": "application/json; charset=utf-8" });
|
||||
response.end(JSON.stringify({ ok: false, error: "该案例正在执行中" }));
|
||||
return;
|
||||
}
|
||||
running.set(key, true);
|
||||
const result = await runCase(body);
|
||||
running.delete(key);
|
||||
response.writeHead(200, { "content-type": "application/json; charset=utf-8", "access-control-allow-origin": "*" });
|
||||
response.end(JSON.stringify(result));
|
||||
} catch (error) {
|
||||
response.writeHead(500, { "content-type": "application/json; charset=utf-8" });
|
||||
response.end(JSON.stringify({ ok: false, error: error instanceof Error ? error.message : String(error) }));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (pathname.startsWith("/evidence/")) {
|
||||
const target = path.join(repoRoot, "docs", pathname.slice("/evidence/".length));
|
||||
if (!within(path.join(repoRoot, "docs"), target)) { response.writeHead(403); response.end("forbidden"); return; }
|
||||
sendFile(request, response, target);
|
||||
return;
|
||||
}
|
||||
|
||||
const relative = pathname === "/" ? "index.html" : pathname.replace(/^\/+/, "");
|
||||
const target = within(here, path.join(here, relative)) ? path.join(here, relative) : null;
|
||||
if (!target) { response.writeHead(403); response.end("forbidden"); return; }
|
||||
sendFile(request, response, target);
|
||||
});
|
||||
|
||||
server.listen(port, "127.0.0.1", () => {
|
||||
const actualPort = server.address()?.port ?? port;
|
||||
boundPort = actualPort;
|
||||
const origin = `http://127.0.0.1:${actualPort}`;
|
||||
console.log(JSON.stringify({
|
||||
schema: "freecad-web-teaching-server/v1",
|
||||
origin,
|
||||
appOrigin,
|
||||
token,
|
||||
console: `${origin}/console.html?token=${token}`,
|
||||
}));
|
||||
});
|
||||
|
||||
for (const signal of ["SIGINT", "SIGTERM"]) {
|
||||
process.on(signal, () => {
|
||||
runner.close();
|
||||
server.close(() => process.exit(0));
|
||||
setTimeout(() => process.exit(0), 2000).unref();
|
||||
});
|
||||
}
|
||||
516
web/teaching/suite-runner.mjs
Normal file
516
web/teaching/suite-runner.mjs
Normal file
@@ -0,0 +1,516 @@
|
||||
/**
|
||||
* Whitelisted job runner behind the teaching console.
|
||||
*
|
||||
* The browser may only ask for a *lesson id* (plus bounded parameters for the
|
||||
* free-practice lesson). This module turns that into fixed argv arrays for:
|
||||
* - tools/web-freecad-functional-suite.mjs (kind "suite")
|
||||
* - tools/layout-probe.mjs (kind "probe")
|
||||
* - tools/static-host.mjs (kind "host")
|
||||
* - the preflight report itself (kind "preflight")
|
||||
*
|
||||
* Nothing here accepts a shell string: spawn() always receives an argv array,
|
||||
* cwd is the repo root, the environment is a whitelist, and only one job may
|
||||
* run at a time (headed Chrome + a 4 GB dist tolerate no more).
|
||||
*
|
||||
* Progress is read from the suite's own files — manifest.json (planned cases),
|
||||
* checkpoint.json (current/completed, rewritten during the run) and
|
||||
* results.json (counts + per-case records) — never parsed from stdout. stdout
|
||||
* is forwarded only as log lines.
|
||||
*/
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import crypto from "node:crypto";
|
||||
import { spawn } from "node:child_process";
|
||||
import { createRequire } from "node:module";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { loadCatalog } from "../tools/teaching-console/catalog.mjs";
|
||||
import { buildLessons } from "../tools/teaching-console/lessons.mjs";
|
||||
import { findChrome } from "../../tools/static-host.mjs";
|
||||
|
||||
const HERE = path.dirname(fileURLToPath(import.meta.url));
|
||||
export const REPO_ROOT = path.resolve(HERE, "../..");
|
||||
export const CONSOLE_ROOT = path.join(REPO_ROOT, "docs/current/teaching-console");
|
||||
const SUITE_ENTRY = path.join(REPO_ROOT, "tools/web-freecad-functional-suite.mjs");
|
||||
const PROBE_ENTRY = path.join(REPO_ROOT, "tools/layout-probe.mjs");
|
||||
const HOST_ENTRY = path.join(REPO_ROOT, "tools/static-host.mjs");
|
||||
|
||||
const LINE_LIMIT = 2000;
|
||||
const BYTE_LIMIT = 512 * 1024;
|
||||
const POLL_MS = 750;
|
||||
const PROBE_PAGES = new Set(["/", "/project.html", "/partdesign.html"]);
|
||||
const TIMEOUTS = { suite: 45 * 60_000, probe: 10 * 60_000, host: 2 * 60_000 };
|
||||
|
||||
export class JobError extends Error {
|
||||
constructor(code, message, detail) {
|
||||
super(message);
|
||||
this.code = code;
|
||||
this.detail = detail;
|
||||
}
|
||||
}
|
||||
|
||||
const require = createRequire(path.join(REPO_ROOT, "web/package.json"));
|
||||
|
||||
/* ---------------------------------------------------------------- catalog */
|
||||
|
||||
let cached = null;
|
||||
export function catalog() {
|
||||
if (!cached) {
|
||||
const cases = loadCatalog();
|
||||
cached = { cases, lessons: buildLessons(cases), byId: new Map() };
|
||||
for (const lesson of cached.lessons.lessons) cached.byId.set(lesson.id, lesson);
|
||||
}
|
||||
return cached;
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------- preflight */
|
||||
|
||||
export function preflight() {
|
||||
const checks = [];
|
||||
const add = (id, ok, detail, fix, hard = true) => checks.push({ id, ok, detail, fix, hard });
|
||||
|
||||
const distIndex = path.join(REPO_ROOT, "web/dist/index.html");
|
||||
add("dist", fs.existsSync(distIndex), fs.existsSync(distIndex) ? "web/dist/index.html 已就绪" : "web/dist/index.html 不存在",
|
||||
"cd web && npx vite build");
|
||||
|
||||
const kernelDirs = ["web/dist/kernel", "web/public/kernel"].map((rel) => path.join(REPO_ROOT, rel));
|
||||
const wasm = kernelDirs.flatMap((dir) => {
|
||||
try {
|
||||
return fs.readdirSync(dir).filter((name) => name.endsWith(".wasm")).map((name) => path.join(dir, name));
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
});
|
||||
add("kernel", wasm.length > 0, wasm.length ? `内核产物 ${wasm.length} 个 .wasm` : "未找到内核 .wasm 产物",
|
||||
"cd web && node ../tools/sync-assets.mjs");
|
||||
|
||||
let chrome = null;
|
||||
try {
|
||||
chrome = findChrome();
|
||||
} catch {
|
||||
chrome = null;
|
||||
}
|
||||
add("chrome", Boolean(chrome), chrome || "未找到 Chrome/Chromium", "export FREECAD_CHROME=/usr/bin/google-chrome");
|
||||
|
||||
const display = process.env.DISPLAY || "";
|
||||
const displayOk = Boolean(display) && (display.startsWith(":") ? fs.existsSync(`/tmp/.X11-unix/X${display.replace(/^:/, "").split(".")[0]}`) : true);
|
||||
add("display", displayOk, display ? `DISPLAY=${display}${displayOk ? "" : "(找不到 X socket)"}` : "DISPLAY 未设置",
|
||||
"DISPLAY=:1 node web/teaching/server.mjs");
|
||||
|
||||
let playwright = null;
|
||||
try {
|
||||
playwright = require.resolve("playwright");
|
||||
} catch {
|
||||
playwright = null;
|
||||
}
|
||||
add("playwright", Boolean(playwright), playwright ? "web/node_modules 可解析 playwright" : "web/node_modules 中找不到 playwright",
|
||||
"cd web && npm install");
|
||||
|
||||
const entriesOk = [SUITE_ENTRY, PROBE_ENTRY, HOST_ENTRY].every((file) => fs.existsSync(file));
|
||||
add("tools", entriesOk, entriesOk ? "套件、探针与静态服务入口存在" : "工具入口缺失", "git status tools/");
|
||||
|
||||
const hard = checks.filter((check) => check.hard);
|
||||
return { ok: hard.every((check) => check.ok), checks, checkedAt: new Date().toISOString() };
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------- validation */
|
||||
|
||||
const ID_PATTERN = /^[A-Za-z][A-Za-z0-9._-]{0,79}$/;
|
||||
|
||||
export function validateCaseIds(ids, catalogData, maxCases = 8) {
|
||||
if (!Array.isArray(ids) || ids.length === 0) throw new JobError("E_PARAM", "至少选择一个用例");
|
||||
if (ids.length > maxCases) throw new JobError("E_PARAM", `最多选择 ${maxCases} 个用例`);
|
||||
const known = new Set(catalogData.ids);
|
||||
const seen = new Set();
|
||||
for (const id of ids) {
|
||||
if (typeof id !== "string" || !ID_PATTERN.test(id)) throw new JobError("E_PARAM", `非法用例 id:${String(id).slice(0, 40)}`);
|
||||
if (!known.has(id)) throw new JobError("E_PARAM", `用例不在目录内:${id}`);
|
||||
if (seen.has(id)) throw new JobError("E_PARAM", `用例重复:${id}`);
|
||||
seen.add(id);
|
||||
}
|
||||
return [...ids];
|
||||
}
|
||||
|
||||
export function validateProbeUrl(url) {
|
||||
if (typeof url !== "string" || !url.startsWith("/")) throw new JobError("E_PARAM", "页面地址必须以 / 开头");
|
||||
if (PROBE_PAGES.has(url)) return url;
|
||||
const match = /^\/workbench\.html\?module=([A-Za-z0-9]+)$/.exec(url);
|
||||
if (match && catalog().cases.modules.includes(match[1])) return url;
|
||||
throw new JobError("E_PARAM", `页面不在白名单内:${url.slice(0, 60)}`);
|
||||
}
|
||||
|
||||
function boundedInt(value, min, max, fallback) {
|
||||
if (value === undefined || value === null || value === "") return fallback;
|
||||
const parsed = Number(value);
|
||||
if (!Number.isInteger(parsed) || parsed < min || parsed > max) throw new JobError("E_PARAM", `数值超出范围(${min}..${max})`);
|
||||
return parsed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Turn a lesson + bounded parameters into the exact argv to spawn.
|
||||
* Exported so self-test can assert the whitelist without starting a process.
|
||||
*/
|
||||
export function buildJobArgv(lesson, params = {}, { jobDir } = {}) {
|
||||
const job = lesson.job;
|
||||
if (job.kind === "preflight") return { argv: null, dir: jobDir };
|
||||
if (job.kind === "suite") {
|
||||
const catalogData = catalog().cases;
|
||||
const only = job.selectable
|
||||
? validateCaseIds(params.only, catalogData, job.maxCases ?? 8)
|
||||
: validateCaseIds(job.only, catalogData, 40);
|
||||
const slow = job.selectable ? boundedInt(params.slow, 0, 1500, 0) : boundedInt(job.slow, 0, 1500, 0);
|
||||
const highlight = job.selectable ? params.highlight === true : job.highlight === true;
|
||||
const screenshots = job.selectable
|
||||
? (params.screenshots === "all" ? "all" : "fails")
|
||||
: (job.screenshots === "all" ? "all" : "fails");
|
||||
const argv = [process.execPath, SUITE_ENTRY, "--only", only.join(","), "--headed"];
|
||||
if (slow > 0) argv.push("--slow", String(slow));
|
||||
if (highlight) argv.push("--highlight");
|
||||
argv.push("--screenshots", screenshots, "--out", path.join(jobDir, "suite"));
|
||||
return { argv, dir: jobDir };
|
||||
}
|
||||
if (job.kind === "probe") {
|
||||
const url = validateProbeUrl(job.selectable ? params.url : job.url);
|
||||
return {
|
||||
argv: [
|
||||
process.execPath, PROBE_ENTRY,
|
||||
"--root", path.join(REPO_ROOT, "web/dist"),
|
||||
"--url", url,
|
||||
"--viewport", "1440x1000",
|
||||
"--headed",
|
||||
"--json", path.join(jobDir, "layout.json"),
|
||||
"--screenshot", path.join(jobDir, "layout-{page}.png"),
|
||||
],
|
||||
dir: jobDir,
|
||||
};
|
||||
}
|
||||
if (job.kind === "host") {
|
||||
return {
|
||||
argv: [process.execPath, HOST_ENTRY, "--root", path.join(REPO_ROOT, "web/dist"), "--port", "0"],
|
||||
dir: jobDir,
|
||||
};
|
||||
}
|
||||
throw new JobError("E_PARAM", `未知课程类型:${job.kind}`);
|
||||
}
|
||||
|
||||
/** Copyable command text for the page (quoted because the repo path has a space). */
|
||||
export function argvToCommand(argv) {
|
||||
if (!argv) return "";
|
||||
return argv.map((part) => (/[\s"'$`]/.test(part) && part !== process.execPath ? JSON.stringify(part) : part)).join(" ");
|
||||
}
|
||||
|
||||
/* --------------------------------------------------------------- progress */
|
||||
|
||||
export function parseProgressLine(line) {
|
||||
const match = /^([A-Za-z][\w-]*): (passed|failed|blocked|skipped)\b/.exec(line.trim());
|
||||
return match ? { id: match[1], status: match[2] } : null;
|
||||
}
|
||||
|
||||
function readJson(file) {
|
||||
try {
|
||||
return { value: JSON.parse(fs.readFileSync(file, "utf8")), stamp: fs.statSync(file).mtimeMs };
|
||||
} catch {
|
||||
return { value: null, stamp: 0 };
|
||||
}
|
||||
}
|
||||
|
||||
function findSuiteRunDir(suiteRoot) {
|
||||
try {
|
||||
const entries = fs.readdirSync(suiteRoot)
|
||||
.filter((name) => name.startsWith("run-"))
|
||||
.map((name) => path.join(suiteRoot, name));
|
||||
if (!entries.length) return null;
|
||||
return entries.sort().at(-1);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function summarizeSuite(runDir) {
|
||||
const manifest = readJson(path.join(runDir, "manifest.json")).value;
|
||||
const checkpoint = readJson(path.join(runDir, "checkpoint.json")).value;
|
||||
const results = readJson(path.join(runDir, "results.json")).value;
|
||||
const planned = manifest?.cases?.length ?? 0;
|
||||
const completed = checkpoint?.completed?.length ?? results?.results?.filter((item) => item.status !== "running").length ?? 0;
|
||||
return {
|
||||
planned,
|
||||
completed,
|
||||
current: checkpoint?.current ?? results?.results?.find((item) => item.status === "running")?.id ?? null,
|
||||
counts: results?.counts ?? null,
|
||||
results: (results?.results ?? []).map((item) => ({
|
||||
id: item.id, title: item.title, status: item.status, seconds: item.seconds, error: item.error ?? null,
|
||||
})),
|
||||
origin: results?.origin ?? manifest?.origin ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
/* ----------------------------------------------------------------- runner */
|
||||
|
||||
export function createRunner({ root = CONSOLE_ROOT } = {}) {
|
||||
const jobs = new Map();
|
||||
const listeners = new Map();
|
||||
let active = null;
|
||||
|
||||
function emit(job, event, data) {
|
||||
const set = listeners.get(job.id);
|
||||
if (!set) return;
|
||||
for (const send of set) {
|
||||
try {
|
||||
send(event, data);
|
||||
} catch {
|
||||
/* listener gone; cleaned up by its close handler */
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function snapshot(job) {
|
||||
const base = {
|
||||
jobId: job.id, lessonId: job.lessonId, kind: job.kind, state: job.state,
|
||||
startedAt: job.startedAt, endedAt: job.endedAt, seconds: job.seconds,
|
||||
exitCode: job.exitCode, runDir: job.runDir, verdict: job.verdict, error: job.error,
|
||||
argv: job.command, logs: job.lines.length,
|
||||
};
|
||||
if (job.kind === "suite" && job.runDir) return { ...base, ...job.progress };
|
||||
return { ...base, ...job.progress };
|
||||
}
|
||||
|
||||
function setState(job, state, extra = {}) {
|
||||
job.state = state;
|
||||
Object.assign(job, extra);
|
||||
emit(job, "snapshot", snapshot(job));
|
||||
}
|
||||
|
||||
function appendLine(job, stream, line) {
|
||||
job.lines.push({ stream, text: line, at: Date.now() });
|
||||
job.bytes += Buffer.byteLength(line) + 1;
|
||||
while (job.lines.length > LINE_LIMIT || (job.bytes > BYTE_LIMIT && job.lines.length > 200)) {
|
||||
const removed = job.lines.shift();
|
||||
job.bytes -= Buffer.byteLength(removed.text) + 1;
|
||||
}
|
||||
emit(job, "log", { stream, text: line });
|
||||
}
|
||||
|
||||
function wireOutput(job, stream, chunk) {
|
||||
job.partial[stream] += chunk.toString("utf8");
|
||||
const pieces = job.partial[stream].split("\n");
|
||||
job.partial[stream] = pieces.pop() ?? "";
|
||||
for (const piece of pieces) onLine(job, stream, piece);
|
||||
}
|
||||
|
||||
function onLine(job, stream, line) {
|
||||
if (!line.trim()) return;
|
||||
appendLine(job, stream, line);
|
||||
if (/^ORIGIN=/.test(line)) job.progress.origin = line.slice("ORIGIN=".length).trim();
|
||||
if (/^fatal:/.test(line)) job.fatal = line;
|
||||
const parsed = parseProgressLine(line);
|
||||
if (parsed && job.progress.results) {
|
||||
const existing = job.progress.results.find((item) => item.id === parsed.id);
|
||||
if (existing) existing.status = parsed.status;
|
||||
if (parsed.status !== "skipped") job.progress.completed = Math.min((job.progress.completed ?? 0) + (existing ? 0 : 1), job.progress.planned || Number.MAX_SAFE_INTEGER);
|
||||
if (parsed.status !== "skipped") emit(job, "snapshot", snapshot(job));
|
||||
}
|
||||
}
|
||||
|
||||
function pollSuite(job) {
|
||||
const suiteRoot = path.join(job.dir, "suite");
|
||||
const runDir = findSuiteRunDir(suiteRoot);
|
||||
if (runDir) {
|
||||
job.runDir = path.relative(REPO_ROOT, runDir).split(path.sep).join("/");
|
||||
const summary = summarizeSuite(runDir);
|
||||
const changed = JSON.stringify(summary) !== JSON.stringify(job.progress);
|
||||
job.progress = summary;
|
||||
if (changed) emit(job, "snapshot", snapshot(job));
|
||||
}
|
||||
}
|
||||
|
||||
function finish(job, code, signal) {
|
||||
if (job.finished) return;
|
||||
job.finished = true;
|
||||
clearInterval(job.poll);
|
||||
clearTimeout(job.timeout);
|
||||
if (active === job) active = null;
|
||||
job.endedAt = new Date().toISOString();
|
||||
job.seconds = Math.round((Date.now() - Date.parse(job.startedAt)) / 1000);
|
||||
job.exitCode = code;
|
||||
|
||||
if (job.kind === "suite") {
|
||||
pollSuite(job);
|
||||
const counts = job.progress.counts ?? { passed: 0, failed: 0, blocked: 0 };
|
||||
if (job.cancelled) job.verdict = "cancelled";
|
||||
else if (job.timedOut) job.verdict = "timeout";
|
||||
else if (job.fatal) job.verdict = "run_fail";
|
||||
else if ((counts.failed ?? 0) > 0) job.verdict = "product_fail";
|
||||
else if ((counts.blocked ?? 0) > 0) job.verdict = "precondition_fail";
|
||||
else if (code === 0) job.verdict = "pass";
|
||||
else job.verdict = "run_fail";
|
||||
} else if (job.kind === "probe") {
|
||||
job.progress = { ...job.progress, report: readJson(path.join(job.dir, "layout.json")).value };
|
||||
if (job.cancelled) job.verdict = "cancelled";
|
||||
else if (job.timedOut) job.verdict = "timeout";
|
||||
else if (code === 0) job.verdict = "pass";
|
||||
else if (code === 2) job.verdict = "precondition_fail";
|
||||
else job.verdict = "product_fail";
|
||||
} else if (job.kind === "host") {
|
||||
// The host lesson succeeds once ORIGIN is printed; an explicit user
|
||||
// cancel still reads as cancelled even if that already happened.
|
||||
if (job.cancelled) job.verdict = "cancelled";
|
||||
else if (job.progress.origin) job.verdict = "pass";
|
||||
else job.verdict = job.timedOut ? "timeout" : "run_fail";
|
||||
} else {
|
||||
job.verdict = code === 0 ? "pass" : "run_fail";
|
||||
}
|
||||
|
||||
// Flush any trailing partial line before the terminal snapshot.
|
||||
for (const stream of ["stdout", "stderr"]) {
|
||||
if (job.partial[stream]) {
|
||||
appendLine(job, stream, job.partial[stream]);
|
||||
job.partial[stream] = "";
|
||||
}
|
||||
}
|
||||
job.progress = { ...job.progress, signal: signal ?? null };
|
||||
emit(job, "snapshot", snapshot(job));
|
||||
emit(job, "done", snapshot(job));
|
||||
}
|
||||
|
||||
function killTree(job, signal = "SIGTERM") {
|
||||
if (!job.child?.pid) return;
|
||||
try {
|
||||
process.kill(-job.child.pid, signal);
|
||||
} catch {
|
||||
try {
|
||||
job.child.kill(signal);
|
||||
} catch {
|
||||
/* already gone */
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function start({ lessonId, params = {} }) {
|
||||
const entry = catalog().byId.get(lessonId);
|
||||
if (!entry) throw new JobError("E_LESSON", `未知课程:${String(lessonId).slice(0, 40)}`);
|
||||
if (active) throw new JobError("E_BUSY", "已有一节课在运行", { activeJobId: active.id });
|
||||
|
||||
const report = preflight();
|
||||
if (!report.ok && entry.job.kind !== "preflight") {
|
||||
throw new JobError("E_PREFLIGHT", "前置条件未满足,未启动运行", { blockers: report.checks.filter((check) => check.hard && !check.ok) });
|
||||
}
|
||||
|
||||
const id = `job-${new Date().toISOString().replace(/[:.]/g, "-")}-${crypto.randomBytes(3).toString("hex")}`;
|
||||
const dir = path.join(root, "runs", id);
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
const { argv } = buildJobArgv(entry, params, { jobDir: dir });
|
||||
const job = {
|
||||
id, lessonId, kind: entry.job.kind, dir, state: "starting",
|
||||
startedAt: new Date().toISOString(), endedAt: null, seconds: null,
|
||||
exitCode: null, runDir: null, verdict: null, error: null, fatal: null,
|
||||
cancelRequested: false, cancelled: false, timedOut: false,
|
||||
lines: [], bytes: 0, partial: { stdout: "", stderr: "" },
|
||||
progress: { planned: entry.job.selectable ? (params.only?.length ?? 0) : (entry.job.only?.length ?? 0), completed: 0, current: null, counts: null, results: [] },
|
||||
command: argv ? argvToCommand(argv) : "(无命令:仅检查前置条件)",
|
||||
};
|
||||
fs.writeFileSync(path.join(dir, "job.json"), JSON.stringify({
|
||||
id, lessonId, kind: job.kind, command: job.command,
|
||||
argv: argv ? argv.map((part) => path.relative(REPO_ROOT, part) || part) : null,
|
||||
startedAt: job.startedAt,
|
||||
}, null, 2));
|
||||
|
||||
jobs.set(id, job);
|
||||
if (entry.job.kind === "preflight") {
|
||||
job.progress = { ...job.progress, preflight: report };
|
||||
setState(job, "running");
|
||||
setImmediate(() => finish(job, 0, null));
|
||||
return snapshot(job);
|
||||
}
|
||||
|
||||
active = job;
|
||||
setState(job, "running");
|
||||
|
||||
const env = {
|
||||
PATH: process.env.PATH ?? "",
|
||||
HOME: process.env.HOME ?? "",
|
||||
LANG: process.env.LANG ?? "C.UTF-8",
|
||||
LC_ALL: process.env.LC_ALL ?? "",
|
||||
TMPDIR: process.env.TMPDIR ?? "",
|
||||
DISPLAY: process.env.DISPLAY ?? "",
|
||||
FREECAD_CHROME: process.env.FREECAD_CHROME ?? "",
|
||||
};
|
||||
|
||||
let child;
|
||||
try {
|
||||
child = spawn(argv[0], argv.slice(1), { cwd: REPO_ROOT, env, detached: true, stdio: ["ignore", "pipe", "pipe"] });
|
||||
} catch (error) {
|
||||
job.error = error instanceof Error ? error.message : String(error);
|
||||
finish(job, -1, null);
|
||||
return snapshot(job);
|
||||
}
|
||||
job.child = child;
|
||||
child.stdout.on("data", (chunk) => wireOutput(job, "stdout", chunk));
|
||||
child.stderr.on("data", (chunk) => wireOutput(job, "stderr", chunk));
|
||||
child.on("error", (error) => {
|
||||
job.error = error instanceof Error ? error.message : String(error);
|
||||
});
|
||||
child.on("close", (code, signal) => finish(job, code, signal));
|
||||
|
||||
job.poll = setInterval(() => {
|
||||
if (job.kind === "suite") pollSuite(job);
|
||||
}, POLL_MS);
|
||||
job.timeout = setTimeout(() => {
|
||||
job.timedOut = true;
|
||||
job.stoppedByTimeout = job.kind === "host";
|
||||
killTree(job);
|
||||
}, TIMEOUTS[job.kind] ?? TIMEOUTS.suite);
|
||||
if (job.timeout.unref) job.timeout.unref();
|
||||
|
||||
return snapshot(job);
|
||||
}
|
||||
|
||||
function cancel(jobId) {
|
||||
const job = jobs.get(jobId);
|
||||
if (!job) throw new JobError("E_NO_JOB", "找不到该任务");
|
||||
if (job.finished) throw new JobError("E_NOT_RUNNING", "任务已结束");
|
||||
job.cancelRequested = true;
|
||||
job.cancelled = true;
|
||||
killTree(job);
|
||||
setTimeout(() => killTree(job, "SIGKILL"), 5000).unref?.();
|
||||
setState(job, "cancelling");
|
||||
return snapshot(job);
|
||||
}
|
||||
|
||||
function get(jobId) {
|
||||
const job = jobs.get(jobId);
|
||||
if (!job) throw new JobError("E_NO_JOB", "找不到该任务");
|
||||
return { snapshot: snapshot(job), lines: job.lines.slice(-300) };
|
||||
}
|
||||
|
||||
function subscribe(jobId, send) {
|
||||
if (!listeners.has(jobId)) listeners.set(jobId, new Set());
|
||||
listeners.get(jobId).add(send);
|
||||
const job = jobs.get(jobId);
|
||||
if (job) {
|
||||
send("snapshot", snapshot(job));
|
||||
for (const line of job.lines.slice(-200)) send("log", { stream: line.stream, text: line.text });
|
||||
}
|
||||
return () => {
|
||||
const set = listeners.get(jobId);
|
||||
if (!set) return;
|
||||
set.delete(send);
|
||||
if (!set.size) listeners.delete(jobId);
|
||||
};
|
||||
}
|
||||
|
||||
function artifact(jobId, rel) {
|
||||
const job = jobs.get(jobId);
|
||||
if (!job) throw new JobError("E_NO_JOB", "找不到该任务");
|
||||
const base = job.dir;
|
||||
const target = path.resolve(base, rel);
|
||||
if (target !== base && !target.startsWith(`${base}${path.sep}`)) throw new JobError("E_PARAM", "非法路径");
|
||||
return target;
|
||||
}
|
||||
|
||||
function close() {
|
||||
for (const job of jobs.values()) {
|
||||
if (!job.finished && job.child) killTree(job, "SIGKILL");
|
||||
}
|
||||
}
|
||||
|
||||
return { start, cancel, get, subscribe, artifact, preflight, catalog, close };
|
||||
}
|
||||
97
web/tools/teaching-console/build-console.mjs
Normal file
97
web/tools/teaching-console/build-console.mjs
Normal file
@@ -0,0 +1,97 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Generate web/teaching/console.html from template.html + the curriculum.
|
||||
*
|
||||
* Deterministic: no timestamps, sorted inputs, so `--check` can byte-compare.
|
||||
* The generated page embeds the lesson catalog and a copyable command per
|
||||
* lesson; at runtime it talks to web/teaching/server.mjs for real runs.
|
||||
*
|
||||
* Usage:
|
||||
* node web/tools/teaching-console/build-console.mjs # write
|
||||
* node web/tools/teaching-console/build-console.mjs --check # exit 1 if stale
|
||||
* node web/tools/teaching-console/build-console.mjs --out <file>
|
||||
* Exit: 0 written/identical, 1 stale (--check), 2 bad arguments.
|
||||
*/
|
||||
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 { argvToCommand, buildJobArgv } from "../../teaching/suite-runner.mjs";
|
||||
|
||||
const HERE = path.dirname(fileURLToPath(import.meta.url));
|
||||
const DEFAULT_OUT = path.resolve(HERE, "../../teaching/console.html");
|
||||
|
||||
function parseArgs(argv) {
|
||||
const options = { check: false, out: DEFAULT_OUT };
|
||||
for (let index = 0; index < argv.length; index += 1) {
|
||||
const arg = argv[index];
|
||||
if (arg === "--check") options.check = true;
|
||||
else if (arg === "--out") options.out = path.resolve(argv[++index] ?? DEFAULT_OUT);
|
||||
else if (arg === "--help" || arg === "-h") {
|
||||
console.log("node web/tools/teaching-console/build-console.mjs [--check] [--out <file>]");
|
||||
process.exit(0);
|
||||
} else {
|
||||
console.error(`未知参数:${arg}`);
|
||||
process.exit(2);
|
||||
}
|
||||
}
|
||||
return options;
|
||||
}
|
||||
|
||||
function json(value) {
|
||||
return JSON.stringify(value).replace(/</g, "\\u003c");
|
||||
}
|
||||
|
||||
export function buildHtml() {
|
||||
const cases = loadCatalog();
|
||||
const curriculum = buildLessons(cases);
|
||||
const commands = {};
|
||||
for (const lesson of curriculum.lessons) {
|
||||
if (lesson.job.kind === "preflight") continue;
|
||||
if (lesson.job.selectable) {
|
||||
commands[lesson.id] = "(自由练习:勾选用例后由服务端生成受约束命令)";
|
||||
continue;
|
||||
}
|
||||
const { argv } = buildJobArgv(lesson, {}, { jobDir: "<jobDir>" });
|
||||
commands[lesson.id] = argvToCommand(argv);
|
||||
}
|
||||
const template = fs.readFileSync(path.join(HERE, "template.html"), "utf8");
|
||||
const html = template
|
||||
.replace("{{LESSONS_JSON}}", json(curriculum))
|
||||
.replace("{{CATALOG_JSON}}", json({ shell: cases.shell, crosscut: cases.crosscut, chapters: cases.chapters, modules: cases.modules }))
|
||||
.replace("{{COMMANDS_JSON}}", json(commands));
|
||||
for (const marker of ["{{LESSONS_JSON}}", "{{CATALOG_JSON}}", "{{COMMANDS_JSON}}"]) {
|
||||
if (html.includes(marker)) throw new Error(`占位符未替换:${marker}`);
|
||||
}
|
||||
return { html, curriculum, cases };
|
||||
}
|
||||
|
||||
function main() {
|
||||
const options = parseArgs(process.argv.slice(2));
|
||||
const { html, curriculum, cases } = buildHtml();
|
||||
|
||||
if (options.check) {
|
||||
let existing = "";
|
||||
try {
|
||||
existing = fs.readFileSync(options.out, "utf8");
|
||||
} catch {
|
||||
console.error(`FAIL --check:目标文件不存在 ${options.out}`);
|
||||
process.exit(1);
|
||||
}
|
||||
if (existing === html) {
|
||||
console.log(`check: OK(${options.out} 已是最新)`);
|
||||
return;
|
||||
}
|
||||
let offset = 0;
|
||||
while (offset < existing.length && offset < html.length && existing[offset] === html[offset]) offset += 1;
|
||||
console.error(`FAIL --check:磁盘文件与生成结果不一致(首个差异偏移 ${offset})`);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
fs.mkdirSync(path.dirname(options.out), { recursive: true });
|
||||
fs.writeFileSync(options.out, html);
|
||||
console.log(`written ${path.relative(path.resolve(HERE, "../../.."), options.out)} (${(Buffer.byteLength(html) / 1024).toFixed(0)} KB, ${curriculum.lessons.length} lessons, ${cases.ids.length} cases)`);
|
||||
}
|
||||
|
||||
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) main();
|
||||
84
web/tools/teaching-console/catalog.mjs
Normal file
84
web/tools/teaching-console/catalog.mjs
Normal file
@@ -0,0 +1,84 @@
|
||||
/**
|
||||
* Build-time case catalog for the teaching console.
|
||||
*
|
||||
* Derives the real case ids from their sources instead of copying them:
|
||||
* - P0 shell ids and P3 crosscut ids are regex-extracted from the suites;
|
||||
* - P1 chapter ids are `CH-<chapter>-<workflow>` from web/manual/scenarios;
|
||||
* - P2 module ids are `MOD-<Module>-01` from the capability registry, minus
|
||||
* the two modules the suite itself skips (OpenSCAD is not implemented on
|
||||
* the Web, AddonManager has no interactive command).
|
||||
*
|
||||
* Importing the suite modules directly would pull in Playwright; the builder
|
||||
* must stay runnable without a browser.
|
||||
*/
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const HERE = path.dirname(fileURLToPath(import.meta.url));
|
||||
export const REPO_ROOT = path.resolve(HERE, "../../..");
|
||||
|
||||
const SCENARIO_DIR = path.join(HERE, "../../manual/scenarios");
|
||||
const AND_UP = fs.existsSync(SCENARIO_DIR) ? null : "web/manual/scenarios 不存在";
|
||||
const REGISTRY = path.join(REPO_ROOT, "docs/current/feature-capability-registry.json");
|
||||
const SKIP_MODULES = new Set(["OpenSCAD", "AddonManager"]);
|
||||
|
||||
function readIds(file) {
|
||||
const source = fs.readFileSync(file, "utf8");
|
||||
return [...source.matchAll(/id:\s*"([A-Z][A-Za-z0-9-]*)"/g)].map((match) => match[1]);
|
||||
}
|
||||
|
||||
function loadChapters() {
|
||||
const fromScenarios = fs.readdirSync(SCENARIO_DIR)
|
||||
.filter((name) => name.endsWith(".json"))
|
||||
.sort()
|
||||
.map((name) => {
|
||||
const scenario = JSON.parse(fs.readFileSync(path.join(SCENARIO_DIR, name), "utf8"));
|
||||
return {
|
||||
id: `CH-${scenario.chapter}-${scenario.workflow}`,
|
||||
chapter: scenario.chapter,
|
||||
workflow: scenario.workflow,
|
||||
title: scenario.title ?? scenario.workflow,
|
||||
};
|
||||
});
|
||||
// Two P1 cases are handwritten (production line + help centre), not scenarios.
|
||||
const source = fs.readFileSync(path.join(REPO_ROOT, "tools/functional-suite/cases/handwritten.mjs"), "utf8");
|
||||
const handwritten = [...source.matchAll(/id:\s*"(CH-[^"]+)"[\s\S]{0,200}?title:\s*"([^"]+)"/g)].map((match) => {
|
||||
const [, id, title] = match;
|
||||
const rest = id.slice("CH-".length);
|
||||
const separator = rest.indexOf("-");
|
||||
return { id, chapter: rest.slice(0, separator), workflow: rest.slice(separator + 1), title };
|
||||
});
|
||||
return [...fromScenarios, ...handwritten];
|
||||
}
|
||||
|
||||
function loadModules() {
|
||||
const registry = JSON.parse(fs.readFileSync(REGISTRY, "utf8"));
|
||||
return registry.modules
|
||||
.map((meta) => meta.module)
|
||||
.filter((name) => !SKIP_MODULES.has(name))
|
||||
.sort();
|
||||
}
|
||||
|
||||
export function loadCatalog() {
|
||||
if (AND_UP) throw new Error(`catalog: ${AND_UP}`);
|
||||
const shell = readIds(path.join(REPO_ROOT, "tools/functional-suite/cases/shell.mjs"));
|
||||
const crosscut = readIds(path.join(REPO_ROOT, "tools/functional-suite/cases/crosscut.mjs"));
|
||||
const chapters = loadChapters();
|
||||
const modules = loadModules();
|
||||
const ids = new Set([
|
||||
...shell,
|
||||
...crosscut,
|
||||
...chapters.map((item) => item.id),
|
||||
...modules.map((name) => `MOD-${name}-01`),
|
||||
]);
|
||||
return {
|
||||
schema: "freecad-web/teaching-console-catalog/v1",
|
||||
shell,
|
||||
crosscut,
|
||||
chapters,
|
||||
modules,
|
||||
ids: [...ids].sort(),
|
||||
counts: { shell: shell.length, chapters: chapters.length, modules: modules.length, crosscut: crosscut.length },
|
||||
};
|
||||
}
|
||||
248
web/tools/teaching-console/check-console.mjs
Normal file
248
web/tools/teaching-console/check-console.mjs
Normal file
@@ -0,0 +1,248 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Browser gate for the teaching console page.
|
||||
*
|
||||
* Two modes:
|
||||
* --offline open the generated page over file:// — it must stay readable
|
||||
* with no server: lessons listed, run buttons disabled, no
|
||||
* horizontal overflow at 1440×900 and 390×844.
|
||||
* --live start web/teaching/server.mjs on an ephemeral port with a fixed
|
||||
* token, then run one fast module case end to end: preflight chips,
|
||||
* lesson click, log stream, verdict, results table, evidence links.
|
||||
* Also asserts the token/existence guards (401 / 404).
|
||||
*
|
||||
* Prerequisites: DISPLAY=:1, Chrome, web/dist built (the live run executes
|
||||
* MOD-Part-01 headed). Missing prerequisites fail as precondition (exit 2).
|
||||
*
|
||||
* Usage:
|
||||
* node web/tools/teaching-console/check-console.mjs --offline
|
||||
* DISPLAY=:1 node web/tools/teaching-console/check-console.mjs --live
|
||||
*/
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { spawn } from "node:child_process";
|
||||
import { createRequire } from "node:module";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { findChrome } from "../../../tools/static-host.mjs";
|
||||
|
||||
const HERE = path.dirname(fileURLToPath(import.meta.url));
|
||||
const REPO = path.resolve(HERE, "../../..");
|
||||
const require = createRequire(path.join(REPO, "web/package.json"));
|
||||
const PAGE = path.join(REPO, "web/teaching/console.html");
|
||||
const SERVER = path.join(REPO, "web/teaching/server.mjs");
|
||||
|
||||
const failures = [];
|
||||
const note = (message) => { failures.push(message); console.error(`FAIL ${message}`); };
|
||||
|
||||
function parseArgs(argv) {
|
||||
const options = { offline: false, live: false };
|
||||
for (const arg of argv) {
|
||||
if (arg === "--offline") options.offline = true;
|
||||
else if (arg === "--live") options.live = true;
|
||||
else if (arg === "--help" || arg === "-h") {
|
||||
console.log("node web/tools/teaching-console/check-console.mjs [--offline] [--live]");
|
||||
process.exit(0);
|
||||
} else {
|
||||
console.error(`未知参数:${arg}`);
|
||||
process.exit(2);
|
||||
}
|
||||
}
|
||||
if (!options.offline && !options.live) options.offline = true;
|
||||
return options;
|
||||
}
|
||||
|
||||
async function openPage(browser, url) {
|
||||
const page = await browser.newPage({ viewport: { width: 1440, height: 900 } });
|
||||
const pageErrors = [];
|
||||
const consoleErrors = [];
|
||||
const failedRequests = [];
|
||||
page.on("pageerror", (error) => pageErrors.push(String(error)));
|
||||
page.on("console", (message) => { if (message.type() === "error") consoleErrors.push(message.text()); });
|
||||
page.on("requestfailed", (request) => failedRequests.push(`${request.url()} ${request.failure()?.errorText ?? ""}`));
|
||||
const response = await page.goto(url, { waitUntil: "load" });
|
||||
return { page, response, pageErrors, consoleErrors, failedRequests };
|
||||
}
|
||||
|
||||
function ignoreExpected(list, { offline }) {
|
||||
// Designed failure paths: offline health probe (file://) and, live, the two
|
||||
// guard requests (401/404) plus the EventSource abort after `done`.
|
||||
return list.filter((entry) => {
|
||||
if (offline) return !(/\/api\/console\/|ERR_FILE_NOT_FOUND|ERR_CONNECTION_REFUSED|Failed to load resource/.test(entry));
|
||||
return !(/status of 401|status of 404|\/api\/console\/events\?.*ERR_ABORTED/.test(entry));
|
||||
});
|
||||
}
|
||||
|
||||
async function checkOffline(browser) {
|
||||
const url = `file://${PAGE}`;
|
||||
for (const viewport of [{ width: 1440, height: 900 }, { width: 390, height: 844 }]) {
|
||||
const { page, pageErrors, consoleErrors, failedRequests } = await openPage(browser, url);
|
||||
await page.setViewportSize(viewport);
|
||||
await page.waitForTimeout(600);
|
||||
const dom = await page.evaluate(() => ({
|
||||
lessons: document.querySelectorAll("#course-list button[data-id]").length,
|
||||
runDisabled: document.getElementById("run").disabled,
|
||||
overflow: Math.max(0, document.documentElement.scrollWidth - document.documentElement.clientWidth),
|
||||
banner: !document.getElementById("offline-banner").hidden,
|
||||
command: document.getElementById("lesson-command").textContent.trim().length,
|
||||
title: document.getElementById("lesson-title").textContent,
|
||||
}));
|
||||
if (dom.lessons < 40) note(`offline ${viewport.width}px: 课程仅 ${dom.lessons} 个`);
|
||||
if (!dom.runDisabled) note(`offline ${viewport.width}px: 运行按钮未禁用`);
|
||||
if (dom.overflow > 0) note(`offline ${viewport.width}px: 横向溢出 ${dom.overflow}px`);
|
||||
if (!dom.banner) note(`offline ${viewport.width}px: 未显示离线提示`);
|
||||
if (dom.command < 10) note(`offline ${viewport.width}px: 等价命令为空`);
|
||||
for (const error of pageErrors) note(`offline ${viewport.width}px pageerror: ${error}`);
|
||||
for (const error of ignoreExpected(consoleErrors, { offline: true })) note(`offline ${viewport.width}px console: ${error}`);
|
||||
for (const error of ignoreExpected(failedRequests, { offline: true })) note(`offline ${viewport.width}px request: ${error}`);
|
||||
console.log(`offline ${viewport.width}x${viewport.height}: lessons=${dom.lessons} overflow=${dom.overflow} runDisabled=${dom.runDisabled}`);
|
||||
await page.close();
|
||||
}
|
||||
}
|
||||
|
||||
function startServer() {
|
||||
const token = "gate-" + Date.now().toString(36);
|
||||
const child = spawn(process.execPath, [SERVER], {
|
||||
cwd: REPO,
|
||||
env: { ...process.env, TEACHING_PORT: "0", TEACHING_TOKEN: token },
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
});
|
||||
const ready = new Promise((resolve, reject) => {
|
||||
let buffer = "";
|
||||
const timer = setTimeout(() => reject(new Error("server did not report an origin within 15s")), 15000);
|
||||
child.stdout.on("data", (chunk) => {
|
||||
buffer += chunk.toString("utf8");
|
||||
for (const line of buffer.split("\n")) {
|
||||
try {
|
||||
const parsed = JSON.parse(line);
|
||||
if (parsed.origin) {
|
||||
clearTimeout(timer);
|
||||
resolve({ origin: parsed.origin, token });
|
||||
return;
|
||||
}
|
||||
} catch {
|
||||
/* partial line */
|
||||
}
|
||||
}
|
||||
});
|
||||
child.on("exit", (code) => reject(new Error(`server exited early (${code})`)));
|
||||
});
|
||||
return { child, ready, token };
|
||||
}
|
||||
|
||||
async function checkLive(browser) {
|
||||
const server = startServer();
|
||||
try {
|
||||
const { origin, token } = await server.ready;
|
||||
const url = `${origin}/console.html?token=${token}`;
|
||||
const { page, response, pageErrors, consoleErrors, failedRequests } = await openPage(browser, url);
|
||||
await page.waitForTimeout(1200);
|
||||
|
||||
if ((response?.status() ?? 0) !== 200) note(`live: HTTP ${response?.status()}`);
|
||||
|
||||
const chips = await page.evaluate(() => [...document.querySelectorAll("#preflight-chips .chip")].map((chip) => ({ cls: chip.className, text: chip.textContent })));
|
||||
if (chips.length < 6) note(`live: 前置检查仅 ${chips.length} 项`);
|
||||
const blocked = chips.filter((chip) => /chip bad/.test(chip.cls));
|
||||
for (const chip of blocked) note(`live: 前置未通过 - ${chip.text.slice(0, 80)}`);
|
||||
console.log(`live: preflight chips=${chips.length} blocked=${blocked.length}`);
|
||||
|
||||
// Guards: wrong token → 401, unknown lesson → 404.
|
||||
const guards = await page.evaluate(async ({ origin, token }) => {
|
||||
const bad = await fetch(`${origin}/api/console/run`, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json", "x-teaching-token": "wrong" },
|
||||
body: JSON.stringify({ lessonId: "lesson-shell" }),
|
||||
});
|
||||
const unknown = await fetch(`${origin}/api/console/run`, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json", "x-teaching-token": token },
|
||||
body: JSON.stringify({ lessonId: "lesson-does-not-exist" }),
|
||||
});
|
||||
return { bad: bad.status, unknown: unknown.status };
|
||||
}, { origin, token });
|
||||
if (guards.bad !== 401) note(`live: 错误 token 返回 ${guards.bad}(期望 401)`);
|
||||
if (guards.unknown !== 404) note(`live: 未知课程返回 ${guards.unknown}(期望 404)`);
|
||||
|
||||
// Run one fast module case end to end.
|
||||
await page.fill("#search", "Part · 模块冒烟");
|
||||
await page.click('#course-list button[data-id="lesson-module-part"]');
|
||||
await page.click("#run");
|
||||
await page.waitForFunction(() => {
|
||||
const verdict = document.getElementById("verdict");
|
||||
return verdict && /通过|失败|运行失败|超时|已取消/.test(verdict.textContent);
|
||||
}, null, { timeout: 240000 });
|
||||
const outcome = await page.evaluate(() => ({
|
||||
verdict: document.getElementById("verdict").textContent,
|
||||
verdictClass: document.getElementById("verdict").className,
|
||||
logLines: document.getElementById("terminal").querySelectorAll("span").length,
|
||||
rows: document.querySelectorAll("#results tbody tr").length,
|
||||
evidence: document.querySelectorAll("#evidence a").length,
|
||||
progress: document.getElementById("progress-text").textContent,
|
||||
}));
|
||||
if (!/通过/.test(outcome.verdict)) note(`live: 判定为「${outcome.verdict}」`);
|
||||
if (outcome.logLines < 1) note(`live: 日志为空`);
|
||||
if (outcome.rows < 1) note("live: 结果表没有用例行");
|
||||
if (outcome.evidence < 1) note("live: 没有证据链接");
|
||||
console.log(`live: verdict=${outcome.verdict} logs=${outcome.logLines} rows=${outcome.rows} evidence=${outcome.evidence} progress=${outcome.progress}`);
|
||||
|
||||
// Cancellation: the host lesson prints ORIGIN= quickly and then waits;
|
||||
// cancelling must end the job as "cancelled" rather than leaving it hung.
|
||||
await page.fill("#search", "静态服务");
|
||||
await page.click('#course-list button[data-id="lesson-01-static-host"]');
|
||||
await page.click("#run");
|
||||
await page.waitForFunction(() => document.getElementById("terminal").textContent.includes("ORIGIN="), null, { timeout: 60000 });
|
||||
await page.click("#cancel");
|
||||
await page.waitForFunction(() => /已取消/.test(document.getElementById("verdict").textContent), null, { timeout: 60000 });
|
||||
console.log("live: cancel ok");
|
||||
|
||||
// Mobile layout on the same live server.
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
await page.waitForTimeout(300);
|
||||
const overflow = await page.evaluate(() => Math.max(0, document.documentElement.scrollWidth - document.documentElement.clientWidth));
|
||||
if (overflow > 0) note(`live mobile: 横向溢出 ${overflow}px`);
|
||||
|
||||
for (const error of pageErrors) note(`live pageerror: ${error}`);
|
||||
for (const error of ignoreExpected(consoleErrors, { offline: false })) note(`live console: ${error}`);
|
||||
for (const error of ignoreExpected(failedRequests, { offline: false })) note(`live request: ${error}`);
|
||||
await page.close();
|
||||
} finally {
|
||||
server.child.kill("SIGTERM");
|
||||
await new Promise((resolve) => server.child.once("exit", resolve));
|
||||
}
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const options = parseArgs(process.argv.slice(2));
|
||||
if (!fs.existsSync(PAGE)) {
|
||||
console.error(`前置缺失:${PAGE} 不存在,先运行 build-console.mjs`);
|
||||
process.exit(2);
|
||||
}
|
||||
let chromium;
|
||||
try {
|
||||
({ chromium } = require("playwright"));
|
||||
} catch {
|
||||
console.error("前置缺失:web/node_modules 下找不到 playwright");
|
||||
process.exit(2);
|
||||
}
|
||||
const chrome = findChrome();
|
||||
if (!chrome) {
|
||||
console.error("前置缺失:找不到 Chrome(可用 FREECAD_CHROME 指定)");
|
||||
process.exit(2);
|
||||
}
|
||||
const browser = await chromium.launch({ executablePath: chrome, headless: true, args: ["--no-sandbox", "--disable-dev-shm-usage"] });
|
||||
try {
|
||||
if (options.offline) await checkOffline(browser);
|
||||
if (options.live) await checkLive(browser);
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
if (failures.length) {
|
||||
console.error(`\ncheck-console: ${failures.length} failure(s)`);
|
||||
process.exit(1);
|
||||
}
|
||||
console.log("check-console: OK");
|
||||
}
|
||||
|
||||
main().catch((error) => {
|
||||
console.error(`FAIL ${error?.stack ?? error}`);
|
||||
process.exit(1);
|
||||
});
|
||||
269
web/tools/teaching-console/lessons.mjs
Normal file
269
web/tools/teaching-console/lessons.mjs
Normal file
@@ -0,0 +1,269 @@
|
||||
/**
|
||||
* Teaching curriculum for the console.
|
||||
*
|
||||
* Data only — no Node APIs beyond nothing at all, so the builder can inline it
|
||||
* into the page and the server can serve it verbatim.
|
||||
*
|
||||
* Every suite lesson names real case ids; `build-console.mjs` validates them
|
||||
* against catalog.mjs and fails the build if one no longer exists.
|
||||
*/
|
||||
|
||||
export const GROUPS = [
|
||||
{ id: "basics", title: "准备:让环境可用", workbench: "系统", blurb: "先证明 dist、Chrome、显示和静态服务都就绪,再谈功能。" },
|
||||
{ id: "shell", title: "壳层与入口", workbench: "Shell", blurb: "COOP/COEP 隔离、工作台外壳、命令面板与偏好——所有功能的前提。" },
|
||||
{ id: "part", title: "Part:参数化零件", workbench: "Part", blurb: "图元、布尔、任务面板;最直观的建模入口。" },
|
||||
{ id: "partdesign", title: "PartDesign:实体特征", workbench: "PartDesign", blurb: "Body、草图、Pad 与边缘特征、Thickness。" },
|
||||
{ id: "sketcher", title: "Sketcher:草图与约束", workbench: "Sketcher", blurb: "草图编辑、约束面板与自由度读数。" },
|
||||
{ id: "assembly", title: "Assembly:装配", workbench: "Assembly", blurb: "创建装配、插入链接、关节与任务面板。" },
|
||||
{ id: "mesh", title: "Mesh:网格", workbench: "Mesh", blurb: "网格工作台与 MeshPart 转换;也是性能敏感区。" },
|
||||
{ id: "bim", title: "BIM:建筑构件", workbench: "BIM", blurb: "BIM 工作台与任务面板。" },
|
||||
{ id: "cam", title: "CAM:加工路径", workbench: "CAM", blurb: "Job、Profile、Pocket 与工具控制器。" },
|
||||
{ id: "io", title: "导入导出", workbench: "Import", blurb: "Files 工具、OPFS 浏览器与格式导出。" },
|
||||
{ id: "data", title: "表格与测量", workbench: "Spreadsheet", blurb: "电子表格与测量/检查面板。" },
|
||||
{ id: "drawing", title: "制图与仿真", workbench: "TechDraw", blurb: "TechDraw 图纸与 FEM 分析。" },
|
||||
{ id: "specialists", title: "专业模块", workbench: "Specialists", blurb: "Draft、Surface、Inspection、逆向、材料、机器人、Web。" },
|
||||
{ id: "crosscut", title: "交叉能力", workbench: "Crosscut", blurb: "面板滚动、OPFS 往返、保存回开、导出格式、错误恢复、视口。" },
|
||||
{ id: "practice", title: "自由练习", workbench: "自由练习", blurb: "在自己挑选的用例范围内组一次运行;参数仍受白名单约束。" },
|
||||
];
|
||||
|
||||
/** Chapter id → group + one-line teaching blurb. */
|
||||
const CHAPTER_NOTES = {
|
||||
ch00: { group: "basics", blurb: "启动页、OPFS 文档与第一次保存。" },
|
||||
ch01: { group: "shell", blurb: "界面、文档、对象树、属性、视图与保存。" },
|
||||
ch02: { group: "part", blurb: "Part 图元、布尔与检查。" },
|
||||
ch03: { group: "sketcher", blurb: "草图、矩形与约束入口。" },
|
||||
ch04: { group: "partdesign", blurb: "PartDesign Body、草图与 Pad。" },
|
||||
ch05: { group: "assembly", blurb: "创建装配与插入链接。" },
|
||||
ch06: { group: "data", blurb: "电子表格驱动尺寸与测量读数。" },
|
||||
ch07: { group: "io", blurb: "导入导出面板与文件工具。" },
|
||||
ch08: { group: "mesh", blurb: "网格工作台全流程。" },
|
||||
ch09: { group: "bim", blurb: "BIM 工作台构件流程。" },
|
||||
ch10: { group: "cam", blurb: "CAM Job 与加工操作。" },
|
||||
ch11: { group: "drawing", blurb: "TechDraw 页面与标注。" },
|
||||
ch12: { group: "drawing", blurb: "FEM 分析与结果查看。" },
|
||||
ch13: { group: "specialists", blurb: "专业模块工具集。" },
|
||||
ch14: { group: "specialists", blurb: "生产线案例(复合装配)。" },
|
||||
ch15: { group: "shell", blurb: "帮助与启动中心。" },
|
||||
ch16: { group: "shell", blurb: "壳层区域、偏好、快捷键与命令面板。" },
|
||||
};
|
||||
|
||||
/**
|
||||
* Hand-written lessons. `job` kinds:
|
||||
* preflight — no spawn, renders the server preflight report
|
||||
* suite — runs tools/web-freecad-functional-suite.mjs with fixed flags
|
||||
* probe — runs tools/layout-probe.mjs on one whitelisted page
|
||||
* host — runs tools/static-host.mjs for 2 minutes (watch ORIGIN=)
|
||||
*/
|
||||
const CORE_LESSONS = [
|
||||
{
|
||||
id: "lesson-00-preflight",
|
||||
groupId: "basics",
|
||||
title: "第 0 课 · 环境自检",
|
||||
level: "入门",
|
||||
durationMin: 1,
|
||||
summary: "在执行任何产品用例之前,先确认四件事:dist 已构建、内核产物已同步、Chrome 可执行、DISPLAY 可用。缺失项按「前置失败」处理,而不是产品失败。",
|
||||
sees: ["六项前置检查全部变绿", "每项失败都附带可直接复制的修复命令"],
|
||||
expect: "前置面板全绿;若某项失败,页面禁用运行按钮并给出修复命令。",
|
||||
job: { kind: "preflight" },
|
||||
notes: ["铁律:前置条件未满足时不得执行产品断言。"],
|
||||
},
|
||||
{
|
||||
id: "lesson-01-static-host",
|
||||
groupId: "basics",
|
||||
title: "第 1 课 · 静态服务与隔离头",
|
||||
level: "入门",
|
||||
durationMin: 2,
|
||||
summary: "所有浏览器用例都跑在一个带 COOP/COEP 头的临时静态服务上。本课用 120 秒观察服务启动,并读出 ORIGIN——这是后面所有页面的地址。",
|
||||
sees: ["终端出现 ORIGIN=、ROOT=、DOCUMENT=", "服务监听在 127.0.0.1 的临时端口"],
|
||||
expect: "日志出现 `ORIGIN=` 即通过;2 分钟到点自动结束。",
|
||||
job: { kind: "host" },
|
||||
},
|
||||
{
|
||||
id: "lesson-02-layout-probe",
|
||||
groupId: "basics",
|
||||
title: "第 2 课 · 三栏布局探针",
|
||||
level: "入门",
|
||||
durationMin: 1,
|
||||
summary: "用探针确认 PartDesign 页面的三栏布局:页面本身不滚动、左右面板各自可滚动、注入内容后中间舞台不位移。",
|
||||
sees: ["每项检查输出 page-scroll / aside-bounds / aside-scrolls / stage-stable", "失败时给出具体像素"],
|
||||
expect: "全部检查为 ok;任一失败,探针退出码为 1。",
|
||||
job: { kind: "probe", url: "/partdesign.html" },
|
||||
},
|
||||
{
|
||||
id: "lesson-shell",
|
||||
groupId: "shell",
|
||||
title: "壳层冒烟:五个入口用例",
|
||||
level: "入门",
|
||||
durationMin: 2,
|
||||
summary: "SHELL-01..05 验证所有功能的前提:入口可打开、COOP/COEP 隔离生效、SharedArrayBuffer 可用、工作台壳层与命令面板就位。",
|
||||
sees: ["有头浏览器逐个打开 Part / Mesh / 工作台页面", "每个用例一行 `<id>: passed (Xs)`"],
|
||||
expect: "5/5 通过;任何失败都先怀疑环境,再怀疑产品。",
|
||||
job: { kind: "suite", only: ["SHELL-01", "SHELL-02", "SHELL-03", "SHELL-04", "SHELL-05"], slow: 150, highlight: true },
|
||||
},
|
||||
{
|
||||
id: "lesson-part-boolean",
|
||||
groupId: "part",
|
||||
title: "Part · 图元、布尔与检查",
|
||||
level: "入门",
|
||||
durationMin: 2,
|
||||
summary: "在工作台里创建一个立方体与圆柱,做布尔差集,并打开检查工具确认真实几何。",
|
||||
sees: ["对象树出现布尔结果", "属性面板显示体积等真实数值"],
|
||||
expect: "用例 CH-ch02-part-primitives-boolean 通过。",
|
||||
job: { kind: "suite", only: ["CH-ch02-part-primitives-boolean"], slow: 200, highlight: true, screenshots: "all" },
|
||||
},
|
||||
{
|
||||
id: "lesson-part-panels",
|
||||
groupId: "part",
|
||||
title: "Part · 任务面板(Shape Builder、Fillet)",
|
||||
level: "进阶",
|
||||
durationMin: 2,
|
||||
summary: "任务面板是 Web 端最容易回归的区域:它们参与文档流,可能把三维舞台挤出视口。本课逐项操作并确认舞台稳定。",
|
||||
sees: ["任务面板出现在底部停靠区", "舞台高度不变"],
|
||||
expect: "用例 CH-ch02-part-task-panels 通过。",
|
||||
job: { kind: "suite", only: ["CH-ch02-part-task-panels"], slow: 150, highlight: true },
|
||||
},
|
||||
{
|
||||
id: "lesson-part-module",
|
||||
groupId: "part",
|
||||
title: "Part · 模块冒烟",
|
||||
level: "入门",
|
||||
durationMin: 1,
|
||||
summary: "P2 模块冒烟:加载模块壳体、暴露命令面、派发一条规范化 worker 命令。",
|
||||
sees: ["一条 MOD-Part-01 记录", "命令返回结果而不只是挂载页面"],
|
||||
expect: "用例 MOD-Part-01 通过。",
|
||||
job: { kind: "suite", only: ["MOD-Part-01"] },
|
||||
},
|
||||
{
|
||||
id: "lesson-robot-layout",
|
||||
groupId: "specialists",
|
||||
title: "Robot · 布局压力测试",
|
||||
level: "进阶",
|
||||
durationMin: 1,
|
||||
summary: "Robot 工作台的任务面板最高,历史上曾把 `.layout` 压成几百像素。探针会注入内容并验证舞台不位移。",
|
||||
sees: ["aside-bounds 与 stage-stable 检查", "Robot 页面 `layout {y,h}` 实测值"],
|
||||
expect: "全部检查 ok;失败说明又出现了布局回归。",
|
||||
job: { kind: "probe", url: "/workbench.html?module=Robot" },
|
||||
},
|
||||
{
|
||||
id: "lesson-crosscut-scroll",
|
||||
groupId: "crosscut",
|
||||
title: "交叉 · 左右面板独立滚动",
|
||||
level: "进阶",
|
||||
durationMin: 1,
|
||||
summary: "X-panel-scroll 是布局契约的端到端用例:页面锁定、面板自己滚动、内容不互相挤压。",
|
||||
sees: ["注入 2000px 内容后面板仍可滚动", "页面文档本身不滚动"],
|
||||
expect: "用例 X-panel-scroll 通过(约 20–30 秒)。",
|
||||
job: { kind: "suite", only: ["X-panel-scroll"] },
|
||||
},
|
||||
{
|
||||
id: "lesson-crosscut-opfs",
|
||||
groupId: "crosscut",
|
||||
title: "交叉 · OPFS 保存与回开",
|
||||
level: "进阶",
|
||||
durationMin: 2,
|
||||
summary: "文档保存到 OPFS 的 freecad-documents,再次打开后对象与属性一致。OPFS 是本项目唯一的数据落盘位置。",
|
||||
sees: ["列表中新增 .FCStd", "回开后对象树与属性一致"],
|
||||
expect: "X-opfs-roundtrip 与 X-save-reopen 均通过。",
|
||||
job: { kind: "suite", only: ["X-opfs-roundtrip", "X-save-reopen"], screenshots: "all" },
|
||||
},
|
||||
{
|
||||
id: "lesson-crosscut-export",
|
||||
groupId: "crosscut",
|
||||
title: "交叉 · 导出格式",
|
||||
level: "进阶",
|
||||
durationMin: 2,
|
||||
summary: "STEP/BREP/IGES/STL/GLB 导出到 freecad-exports;导出是显式动作,页面不会自动下载。",
|
||||
sees: ["每种格式生成非空文件", "错误恢复路径可用"],
|
||||
expect: "X-export-formats 与 X-error-recovery 通过。",
|
||||
job: { kind: "suite", only: ["X-export-formats", "X-error-recovery"] },
|
||||
},
|
||||
{
|
||||
id: "lesson-practice",
|
||||
groupId: "practice",
|
||||
title: "自由练习 · 组一次自己的运行",
|
||||
level: "入门",
|
||||
durationMin: 5,
|
||||
summary: "在课程目录内勾选用例,生成受约束的命令并运行。页面绝不接受原始字符串:每个 id 都会先对照用例目录校验。",
|
||||
sees: ["所选 id 与白名单一致", "实时日志与判定按用例汇总"],
|
||||
expect: "所选用例全部 passed;blocked 会被单独标为前置失败。",
|
||||
job: { kind: "suite", selectable: true, maxCases: 8 },
|
||||
notes: ["慢速与高亮只用于观察,会显著拉长运行时间。"],
|
||||
},
|
||||
];
|
||||
|
||||
function chapterLessons(catalog) {
|
||||
return catalog.chapters.map((chapter) => {
|
||||
const note = CHAPTER_NOTES[chapter.chapter] ?? { group: "specialists", blurb: chapter.title };
|
||||
return {
|
||||
id: `lesson-${chapter.id.toLowerCase()}`,
|
||||
groupId: note.group,
|
||||
title: `${chapter.id} · ${chapter.title}`,
|
||||
level: "入门",
|
||||
durationMin: 2,
|
||||
summary: `${note.blurb} 本课运行手册场景 ${chapter.chapter}/${chapter.workflow},按真实操作脚本逐步执行并截图。`,
|
||||
sees: ["有头浏览器逐步执行场景动作", "失败时保留每一步的实际值与截图"],
|
||||
expect: `用例 ${chapter.id} 通过。`,
|
||||
job: { kind: "suite", only: [chapter.id], slow: 120, highlight: true },
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function moduleLessons(catalog) {
|
||||
return catalog.modules.map((name) => ({
|
||||
id: `lesson-module-${name.toLowerCase()}`,
|
||||
groupId: groupForModule(name),
|
||||
title: `${name} · 模块冒烟`,
|
||||
level: "入门",
|
||||
durationMin: 1,
|
||||
summary: `P2 模块冒烟:${name} 的壳体加载、命令面暴露与一条规范化 worker 命令。它证明模块能真正执行,而不只是页面挂载。`,
|
||||
sees: ["MOD- 用例记录中出现该模块", "命令返回结构而非错误"],
|
||||
expect: `用例 MOD-${name}-01 通过。`,
|
||||
job: { kind: "suite", only: [`MOD-${name}-01`] },
|
||||
}));
|
||||
}
|
||||
|
||||
function groupForModule(name) {
|
||||
const map = {
|
||||
Part: "part",
|
||||
PartDesign: "partdesign",
|
||||
Sketcher: "sketcher",
|
||||
Assembly: "assembly",
|
||||
Mesh: "mesh",
|
||||
MeshPart: "mesh",
|
||||
BIM: "bim",
|
||||
CAM: "cam",
|
||||
Import: "io",
|
||||
Spreadsheet: "data",
|
||||
Measure: "data",
|
||||
Inspection: "specialists",
|
||||
TechDraw: "drawing",
|
||||
Fem: "drawing",
|
||||
};
|
||||
return map[name] ?? "specialists";
|
||||
}
|
||||
|
||||
function crosscutLessons(catalog) {
|
||||
return catalog.crosscut
|
||||
.filter((id) => !["X-panel-scroll", "X-opfs-roundtrip", "X-save-reopen", "X-export-formats", "X-error-recovery"].includes(id))
|
||||
.map((id) => ({
|
||||
id: `lesson-${id.toLowerCase()}`,
|
||||
groupId: "crosscut",
|
||||
title: `${id} · 视口与布局`,
|
||||
level: "进阶",
|
||||
durationMin: 1,
|
||||
summary: "视口尺寸契约:不同窗口尺寸下三维视口不被面板挤出,Canvas 尺寸与容器一致。",
|
||||
sees: ["视口与容器尺寸一致", "无滚动条挤压"],
|
||||
expect: `用例 ${id} 通过。`,
|
||||
job: { kind: "suite", only: [id] },
|
||||
}));
|
||||
}
|
||||
|
||||
export function buildLessons(catalog) {
|
||||
const lessons = [...CORE_LESSONS, ...chapterLessons(catalog), ...moduleLessons(catalog), ...crosscutLessons(catalog)];
|
||||
const seen = new Set();
|
||||
for (const lesson of lessons) {
|
||||
if (seen.has(lesson.id)) throw new Error(`课程 id 重复:${lesson.id}`);
|
||||
seen.add(lesson.id);
|
||||
}
|
||||
return { schema: "freecad-web/teaching-console-lessons/v1", groups: GROUPS, lessons };
|
||||
}
|
||||
157
web/tools/teaching-console/self-test.mjs
Normal file
157
web/tools/teaching-console/self-test.mjs
Normal file
@@ -0,0 +1,157 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* No-browser self test for the teaching console core.
|
||||
*
|
||||
* Covers the catalog, the curriculum wiring, every validation path that guards
|
||||
* spawn(), and the argv templates. It never starts a browser or a suite run —
|
||||
* the live gate is check-console.mjs.
|
||||
*
|
||||
* Usage: node web/tools/teaching-console/self-test.mjs
|
||||
* Exit: 0 all assertions pass, 1 the first failure.
|
||||
*/
|
||||
import assert from "node:assert/strict";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { loadCatalog } from "./catalog.mjs";
|
||||
import { buildLessons } from "./lessons.mjs";
|
||||
import {
|
||||
REPO_ROOT, buildJobArgv, catalog, parseProgressLine, preflight,
|
||||
validateCaseIds, validateProbeUrl,
|
||||
} from "../../teaching/suite-runner.mjs";
|
||||
|
||||
const HERE = path.dirname(fileURLToPath(import.meta.url));
|
||||
let failures = 0;
|
||||
|
||||
function check(name, fn) {
|
||||
try {
|
||||
fn();
|
||||
console.log(`ok ${name}`);
|
||||
} catch (error) {
|
||||
failures += 1;
|
||||
console.error(`FAIL ${name}`);
|
||||
console.error(` ${error instanceof Error ? error.message.split("\n")[0] : error}`);
|
||||
}
|
||||
}
|
||||
|
||||
function throwsCode(fn, code) {
|
||||
try {
|
||||
fn();
|
||||
} catch (error) {
|
||||
assert.equal(error.code, code, `expected ${code}, got ${error.code ?? error.message}`);
|
||||
return;
|
||||
}
|
||||
throw new Error(`expected ${code}, nothing thrown`);
|
||||
}
|
||||
|
||||
const cases = loadCatalog();
|
||||
const curriculum = buildLessons(cases);
|
||||
const byId = new Map(curriculum.lessons.map((lesson) => [lesson.id, lesson]));
|
||||
|
||||
check("catalog derives all four layers", () => {
|
||||
assert.equal(cases.shell.length, 5);
|
||||
assert.equal(cases.chapters.length, 29);
|
||||
assert.equal(cases.modules.length, 31);
|
||||
assert.equal(cases.crosscut.length, 6);
|
||||
assert.equal(new Set(cases.ids).size, cases.ids.length);
|
||||
});
|
||||
|
||||
check("every lesson references catalog ids only", () => {
|
||||
const known = new Set(cases.ids);
|
||||
for (const lesson of curriculum.lessons) {
|
||||
if (lesson.job.kind !== "suite" || !lesson.job.only) continue;
|
||||
for (const id of lesson.job.only) assert.ok(known.has(id), `${lesson.id} → ${id}`);
|
||||
}
|
||||
});
|
||||
|
||||
check("lesson ids are unique and groups exist", () => {
|
||||
assert.equal(new Set(curriculum.lessons.map((lesson) => lesson.id)).size, curriculum.lessons.length);
|
||||
const groups = new Set(curriculum.groups.map((group) => group.id));
|
||||
for (const lesson of curriculum.lessons) assert.ok(groups.has(lesson.groupId), `${lesson.id} → ${lesson.groupId}`);
|
||||
assert.ok(curriculum.lessons.length >= 40, `only ${curriculum.lessons.length} lessons`);
|
||||
});
|
||||
|
||||
check("validateCaseIds accepts catalog ids", () => {
|
||||
assert.deepEqual(validateCaseIds(["SHELL-01", "MOD-Part-01"], cases, 8), ["SHELL-01", "MOD-Part-01"]);
|
||||
});
|
||||
|
||||
check("validateCaseIds rejects unknown ids", () => {
|
||||
throwsCode(() => validateCaseIds(["SHELL-99"], cases, 8), "E_PARAM");
|
||||
});
|
||||
|
||||
check("validateCaseIds rejects injection and empty input", () => {
|
||||
throwsCode(() => validateCaseIds(["; rm -rf /"], cases, 8), "E_PARAM");
|
||||
throwsCode(() => validateCaseIds([], cases, 8), "E_PARAM");
|
||||
throwsCode(() => validateCaseIds("SHELL-01", cases, 8), "E_PARAM");
|
||||
});
|
||||
|
||||
check("validateCaseIds enforces the cap", () => {
|
||||
throwsCode(() => validateCaseIds(["SHELL-01", "SHELL-02", "SHELL-03"], cases, 2), "E_PARAM");
|
||||
});
|
||||
|
||||
check("validateProbeUrl whitelists pages", () => {
|
||||
assert.equal(validateProbeUrl("/partdesign.html"), "/partdesign.html");
|
||||
assert.equal(validateProbeUrl("/workbench.html?module=Robot"), "/workbench.html?module=Robot");
|
||||
throwsCode(() => validateProbeUrl("/../../etc/passwd"), "E_PARAM");
|
||||
throwsCode(() => validateProbeUrl("http://evil.example/"), "E_PARAM");
|
||||
throwsCode(() => validateProbeUrl("/workbench.html?module=OpenSCAD"), "E_PARAM");
|
||||
});
|
||||
|
||||
check("suite argv carries only whitelisted flags", () => {
|
||||
const lesson = byId.get("lesson-part-boolean");
|
||||
const { argv } = buildJobArgv(lesson, {}, { jobDir: "/tmp/job-x" });
|
||||
assert.equal(argv[0], process.execPath);
|
||||
assert.ok(argv.includes("--only"));
|
||||
assert.equal(argv[argv.indexOf("--only") + 1], "CH-ch02-part-primitives-boolean");
|
||||
assert.ok(argv.includes("--out"));
|
||||
assert.ok(String(argv[argv.indexOf("--out") + 1]).startsWith("/tmp/job-x"));
|
||||
for (const part of argv) assert.ok(!part.includes(";"), `unexpected shell token in ${part}`);
|
||||
});
|
||||
|
||||
check("probe argv pins root, url and viewport", () => {
|
||||
const lesson = byId.get("lesson-02-layout-probe");
|
||||
const { argv } = buildJobArgv(lesson, {}, { jobDir: "/tmp/job-y" });
|
||||
assert.ok(String(argv[argv.indexOf("--root") + 1]).endsWith(path.join("web", "dist")));
|
||||
assert.equal(argv[argv.indexOf("--url") + 1], "/partdesign.html");
|
||||
assert.equal(argv[argv.indexOf("--viewport") + 1], "1440x1000");
|
||||
});
|
||||
|
||||
check("free-practice honours bounded parameters", () => {
|
||||
const lesson = byId.get("lesson-practice");
|
||||
const { argv } = buildJobArgv(lesson, { only: ["SHELL-01"], slow: 300, highlight: true, screenshots: "all" }, { jobDir: "/tmp/job-z" });
|
||||
assert.equal(argv[argv.indexOf("--slow") + 1], "300");
|
||||
assert.ok(argv.includes("--highlight"));
|
||||
assert.equal(argv[argv.indexOf("--screenshots") + 1], "all");
|
||||
throwsCode(() => buildJobArgv(lesson, { only: ["SHELL-01"], slow: 99999 }, { jobDir: "/tmp/job-z" }), "E_PARAM");
|
||||
throwsCode(() => buildJobArgv(lesson, { only: ["NOPE-01"] }, { jobDir: "/tmp/job-z" }), "E_PARAM");
|
||||
});
|
||||
|
||||
check("host argv binds an ephemeral port", () => {
|
||||
const lesson = byId.get("lesson-01-static-host");
|
||||
const { argv } = buildJobArgv(lesson, {}, { jobDir: "/tmp/job-h" });
|
||||
assert.equal(argv[argv.indexOf("--port") + 1], "0");
|
||||
});
|
||||
|
||||
check("preflight report has boolean checks", () => {
|
||||
const report = preflight();
|
||||
assert.equal(typeof report.ok, "boolean");
|
||||
assert.ok(report.checks.length >= 6);
|
||||
for (const item of report.checks) assert.equal(typeof item.ok, "boolean", item.id);
|
||||
});
|
||||
|
||||
check("progress lines parse without trusting text", () => {
|
||||
assert.deepEqual(parseProgressLine("SHELL-01: passed (3.2s)"), { id: "SHELL-01", status: "passed" });
|
||||
assert.deepEqual(parseProgressLine("MOD-Fem-01: blocked (0s) [fixture]"), { id: "MOD-Fem-01", status: "blocked" });
|
||||
assert.equal(parseProgressLine("fatal: boom"), null);
|
||||
assert.equal(parseProgressLine("legacy: 3 case(s) imported"), null);
|
||||
});
|
||||
|
||||
check("catalog() caches and exposes lessons by id", () => {
|
||||
assert.equal(catalog().byId.get("lesson-shell")?.job.kind, "suite");
|
||||
assert.ok(REPO_ROOT.endsWith(path.join("working", "FreeCAD")));
|
||||
});
|
||||
|
||||
if (failures) {
|
||||
console.error(`\nself-test: ${failures} failure(s)`);
|
||||
process.exit(1);
|
||||
}
|
||||
console.log(`self-test: OK (${curriculum.lessons.length} lessons, ${cases.ids.length} cases)`);
|
||||
437
web/tools/teaching-console/template.html
Normal file
437
web/tools/teaching-console/template.html
Normal file
@@ -0,0 +1,437 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Web FreeCAD 教学控制台</title>
|
||||
<style>
|
||||
:root{--bg:#0f1419;--panel:#17212b;--panel2:#1b2733;--line:#2a3a45;--text:#dbe6ee;--muted:#93a6b3;--accent:#73c6d4;--ok:#7fc98b;--warn:#e0b15c;--bad:#e58a8a;color-scheme:dark}
|
||||
*{box-sizing:border-box}
|
||||
body{margin:0;background:var(--bg);color:var(--text);font:15px/1.6 system-ui,-apple-system,"Segoe UI","Noto Sans CJK SC","Microsoft YaHei",sans-serif;overflow-wrap:break-word}
|
||||
a{color:var(--accent);text-decoration:none}
|
||||
a:hover{text-decoration:underline}
|
||||
code,pre{font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}
|
||||
code{background:#0b1117;border:1px solid var(--line);border-radius:4px;padding:.1em .35em;font-size:.9em}
|
||||
header.top{position:sticky;top:0;z-index:20;display:flex;gap:12px;align-items:center;padding:10px 16px;background:rgba(15,20,25,.92);border-bottom:1px solid var(--line);backdrop-filter:blur(6px)}
|
||||
header.top .brand{font-weight:650;font-size:16px}
|
||||
header.top .spacer{flex:1}
|
||||
.chip{display:inline-flex;gap:6px;align-items:center;border:1px solid var(--line);border-radius:999px;padding:2px 10px;font-size:12.5px;color:var(--muted);background:var(--panel)}
|
||||
.chip.ok{color:var(--ok);border-color:#2f5138}
|
||||
.chip.bad{color:var(--bad);border-color:#5a3030}
|
||||
.chip.warn{color:var(--warn);border-color:#5a4a2a}
|
||||
.layout{display:grid;grid-template-columns:300px minmax(0,1fr);gap:18px;padding:16px;max-width:1500px;margin:0 auto}
|
||||
nav.side{position:sticky;top:60px;align-self:start;max-height:calc(100vh - 76px);overflow:auto;background:var(--panel);border:1px solid var(--line);border-radius:10px;padding:10px}
|
||||
nav.side input{width:100%;margin-bottom:8px;background:#0b1117;color:var(--text);border:1px solid var(--line);border-radius:8px;padding:7px 10px;font-size:13.5px}
|
||||
nav.side .group{margin:10px 0 4px;font-size:12px;color:var(--muted);text-transform:none;letter-spacing:.02em}
|
||||
nav.side button{display:block;width:100%;text-align:left;background:none;border:0;color:var(--text);border-radius:6px;padding:5px 8px;font-size:13.5px;line-height:1.35;cursor:pointer}
|
||||
nav.side button:hover{background:var(--panel2)}
|
||||
nav.side button.active{background:#223243;color:#eaf6fb}
|
||||
nav.side button.done::after{content:" ✓";color:var(--ok)}
|
||||
main{min-width:0}
|
||||
section.card{background:var(--panel);border:1px solid var(--line);border-radius:10px;padding:14px 16px;margin-bottom:14px}
|
||||
h1{font-size:21px;margin:0 0 6px}
|
||||
h2{font-size:16px;margin:0 0 8px}
|
||||
h3{font-size:14px;margin:14px 0 6px;color:var(--muted)}
|
||||
p{margin:6px 0}
|
||||
ul{margin:6px 0 6px 20px;padding:0}
|
||||
li{margin:2px 0}
|
||||
.lead{color:#c6d6e2}
|
||||
.muted{color:var(--muted)}
|
||||
.small{font-size:12.5px}
|
||||
.row{display:flex;gap:10px;flex-wrap:wrap;align-items:center}
|
||||
button.act{background:var(--accent);color:#04161a;border:0;border-radius:8px;padding:8px 16px;font-size:14px;font-weight:600;cursor:pointer}
|
||||
button.act:disabled{opacity:.45;cursor:not-allowed}
|
||||
button.ghost{background:transparent;color:var(--text);border:1px solid var(--line);border-radius:8px;padding:8px 14px;cursor:pointer}
|
||||
button.ghost:disabled{opacity:.45;cursor:not-allowed}
|
||||
label.opt{display:inline-flex;gap:6px;align-items:center;color:var(--muted);font-size:13px}
|
||||
pre.term{background:#070b0f;border:1px solid var(--line);border-radius:8px;padding:10px 12px;height:320px;overflow:auto;font-size:12.5px;line-height:1.5;white-space:pre-wrap;word-break:break-word}
|
||||
pre.term .err{color:var(--bad)}
|
||||
pre.term .ok{color:var(--ok)}
|
||||
pre.term .sys{color:var(--muted)}
|
||||
pre.cmd{background:#0b1117;border:1px solid var(--line);border-radius:8px;padding:9px 11px;overflow:auto;font-size:12.5px;white-space:pre-wrap;word-break:break-all}
|
||||
.progress{height:8px;background:#0b1117;border:1px solid var(--line);border-radius:999px;overflow:hidden}
|
||||
.progress > i{display:block;height:100%;width:0;background:var(--accent);transition:width .3s}
|
||||
.verdict{font-size:15px;font-weight:650}
|
||||
.verdict.pass{color:var(--ok)}
|
||||
.verdict.product_fail,.verdict.run_fail,.verdict.timeout,.verdict.preflight_failed{color:var(--bad)}
|
||||
.verdict.precondition_fail{color:var(--warn)}
|
||||
.verdict.cancelled{color:var(--muted)}
|
||||
table{border-collapse:collapse;width:100%;font-size:13px}
|
||||
th,td{border-bottom:1px solid var(--line);padding:5px 8px;text-align:left;vertical-align:top}
|
||||
th{color:var(--muted);font-weight:500}
|
||||
td.st-passed{color:var(--ok)}td.st-failed{color:var(--bad)}td.st-blocked{color:var(--warn)}td.st-running{color:var(--accent)}
|
||||
.chips{display:flex;gap:8px;flex-wrap:wrap;margin:8px 0}
|
||||
.chip .fix{display:block;color:var(--muted);font-size:11.5px}
|
||||
details{border:1px solid var(--line);border-radius:8px;padding:6px 10px;margin:6px 0;background:#0d1319}
|
||||
summary{cursor:pointer;font-size:13.5px}
|
||||
.grid2{display:grid;grid-template-columns:1fr 1fr;gap:10px}
|
||||
.banner{padding:9px 12px;border-radius:8px;margin-bottom:12px;font-size:13.5px}
|
||||
.banner.offline{background:#2a2317;border:1px solid #5a4a2a;color:var(--warn)}
|
||||
.practice-list{max-height:240px;overflow:auto;border:1px solid var(--line);border-radius:8px;padding:8px}
|
||||
.practice-list label{display:block;font-size:13px;color:var(--text);padding:2px 0}
|
||||
.practice-list .g{color:var(--muted);font-size:12px;margin-top:6px}
|
||||
.skip{position:absolute;left:-999px}
|
||||
@media (max-width:900px){.layout{grid-template-columns:1fr;padding:10px}nav.side{position:static;max-height:none}.grid2{grid-template-columns:1fr}header.top{flex-wrap:wrap}}
|
||||
@media print{header.top,nav.side,button{display:none!important}.layout{display:block}}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<a class="skip" href="#main">跳到主内容</a>
|
||||
<header class="top">
|
||||
<span class="brand">Web FreeCAD 教学控制台</span>
|
||||
<span id="status" class="chip">检测服务…</span>
|
||||
<span class="spacer"></span>
|
||||
<a href="index.html">教学中心</a>
|
||||
<a href="runner.html">可视化执行</a>
|
||||
<a href="manual.html">图文教案</a>
|
||||
</header>
|
||||
<div class="layout">
|
||||
<nav class="side" aria-label="课程目录">
|
||||
<input id="search" type="search" placeholder="搜索课程…(按 / 聚焦)" aria-label="搜索课程">
|
||||
<div id="course-list"></div>
|
||||
</nav>
|
||||
<main id="main">
|
||||
<div id="offline-banner" class="banner offline" hidden>
|
||||
未连接教学服务(或服务是旧版本)。页面仍可阅读与复制命令;要在线运行,请在仓库根执行
|
||||
<code>DISPLAY=:1 node web/teaching/server.mjs</code>,再打开它打印的 console 地址。
|
||||
</div>
|
||||
<section class="card" id="preflight-card">
|
||||
<h2>前置条件</h2>
|
||||
<p class="small muted">铁律:前置未满足时不执行产品断言。任一硬性检查失败,运行按钮会被禁用。</p>
|
||||
<div class="chips" id="preflight-chips"><span class="chip">检查中…</span></div>
|
||||
<div class="row"><button class="ghost" id="recheck" type="button">重新检查</button></div>
|
||||
</section>
|
||||
<section class="card" id="lesson-card">
|
||||
<div class="row"><h1 id="lesson-title">选择一门课程</h1><span id="lesson-meta" class="muted small"></span></div>
|
||||
<p class="lead" id="lesson-summary">左侧按工作台分组,从「第 0 课 · 环境自检」开始。</p>
|
||||
<h3>你会看到</h3><ul id="lesson-sees"></ul>
|
||||
<h3>预期判定</h3><p id="lesson-expect" class="small"></p>
|
||||
<div id="lesson-notes"></div>
|
||||
<div id="practice-box" hidden>
|
||||
<h3>选择用例(最多 8 个)</h3>
|
||||
<div class="practice-list" id="practice-list"></div>
|
||||
</div>
|
||||
<h3>运行</h3>
|
||||
<div class="row">
|
||||
<button class="act" id="run" type="button">开始</button>
|
||||
<button class="ghost" id="cancel" type="button" disabled>取消</button>
|
||||
<label class="opt" id="opt-observe"><input id="observe" type="checkbox" checked> 观察模式(慢速 + 高亮)</label>
|
||||
<label class="opt" id="opt-shots"><input id="shots" type="checkbox"> 全部截图</label>
|
||||
</div>
|
||||
<h3>等价命令</h3>
|
||||
<pre class="cmd" id="lesson-command">(选择课程后显示)</pre>
|
||||
</section>
|
||||
<section class="card">
|
||||
<div class="row"><h2 style="margin:0">运行状态</h2><span id="job-id" class="muted small"></span><span class="spacer" style="flex:1"></span><span id="verdict" class="verdict muted">等待运行</span></div>
|
||||
<div class="row small muted" style="margin:8px 0"><span id="progress-text">0 / 0</span><span id="current-case"></span></div>
|
||||
<div class="progress"><i id="progress-bar"></i></div>
|
||||
<h3>实时日志</h3>
|
||||
<pre class="term" id="terminal"><span class="sys">等待运行…</span></pre>
|
||||
<h3>用例结果</h3>
|
||||
<div id="results"><p class="muted small">运行结束后按用例列出。</p></div>
|
||||
<h3>证据</h3>
|
||||
<div id="evidence"><p class="muted small">套件运行结束后可打开完整报告与截图。</p></div>
|
||||
</section>
|
||||
</main>
|
||||
</div>
|
||||
<script>window.__LESSONS__ = {{LESSONS_JSON}};</script>
|
||||
<script>window.__CATALOG__ = {{CATALOG_JSON}};</script>
|
||||
<script>window.__COMMANDS__ = {{COMMANDS_JSON}};</script>
|
||||
<script>
|
||||
(function(){
|
||||
"use strict";
|
||||
var LESSONS = window.__LESSONS__;
|
||||
var CATALOG = window.__CATALOG__;
|
||||
var COMMANDS = window.__COMMANDS__;
|
||||
var byId = {};
|
||||
LESSONS.lessons.forEach(function(l){ byId[l.id] = l; });
|
||||
var groups = LESSONS.groups;
|
||||
|
||||
var token = "";
|
||||
(function(){
|
||||
var url = new URL(location.href);
|
||||
var param = url.searchParams.get("token");
|
||||
if (param) { token = param; try { sessionStorage.setItem("teaching-token", param); } catch(e){} url.searchParams.delete("token"); history.replaceState(null, "", url.toString()); }
|
||||
else { try { token = sessionStorage.getItem("teaching-token") || ""; } catch(e){} }
|
||||
})();
|
||||
|
||||
var state = {
|
||||
online: false, checked: false, preflight: null, lesson: null,
|
||||
job: null, jobId: null, source: null, running: false, logs: 0,
|
||||
practice: {}, autoScroll: true, completed: {}
|
||||
};
|
||||
try { state.completed = JSON.parse(localStorage.getItem("teaching-console-done-v1") || "{}"); } catch(e) { state.completed = {}; }
|
||||
|
||||
function $(id){ return document.getElementById(id); }
|
||||
function esc(text){ return String(text == null ? "" : text).replace(/[&<>"]/g, function(c){ return {"&":"&","<":"<",">":">","\"":"""}[c]; }); }
|
||||
|
||||
/* --------------------------------------------------------------- sidebar */
|
||||
function renderSidebar(){
|
||||
var q = ($("search").value || "").trim().toLowerCase();
|
||||
var html = "";
|
||||
groups.forEach(function(group){
|
||||
var items = LESSONS.lessons.filter(function(l){ return l.groupId === group.id; });
|
||||
if (q) items = items.filter(function(l){ return (l.title + " " + l.summary + " " + group.title).toLowerCase().indexOf(q) >= 0; });
|
||||
if (!items.length) return;
|
||||
html += '<div class="group">' + esc(group.title) + ' · ' + items.length + '</div>';
|
||||
items.forEach(function(l){
|
||||
var cls = "lesson-btn" + (state.lesson && state.lesson.id === l.id ? " active" : "") + (state.completed[l.id] ? " done" : "");
|
||||
html += '<button type="button" class="' + cls + '" data-id="' + esc(l.id) + '">' + esc(l.title) + '</button>';
|
||||
});
|
||||
});
|
||||
$("course-list").innerHTML = html || '<p class="muted small">没有匹配的课程。</p>';
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- lesson */
|
||||
function renderLesson(){
|
||||
var l = state.lesson;
|
||||
if (!l) return;
|
||||
$("lesson-title").textContent = l.title;
|
||||
$("lesson-meta").textContent = (l.level || "") + " · 约 " + (l.durationMin || 1) + " 分钟 · " + l.job.kind;
|
||||
$("lesson-summary").textContent = l.summary || "";
|
||||
$("lesson-sees").innerHTML = (l.sees || []).map(function(x){ return "<li>" + esc(x) + "</li>"; }).join("");
|
||||
$("lesson-expect").textContent = l.expect || "";
|
||||
$("lesson-notes").innerHTML = (l.notes || []).map(function(x){ return '<p class="small muted">注意:' + esc(x) + "</p>"; }).join("");
|
||||
$("practice-box").hidden = !l.job.selectable;
|
||||
if (l.job.selectable) renderPractice();
|
||||
$("opt-observe").hidden = l.job.kind !== "suite" || l.job.selectable;
|
||||
$("opt-shots").hidden = l.job.kind !== "suite" || l.job.selectable;
|
||||
$("lesson-command").textContent = commandFor(l);
|
||||
updateButtons();
|
||||
renderSidebar();
|
||||
}
|
||||
|
||||
function commandFor(l){
|
||||
if (l.job.kind === "preflight") return "(无需命令:只读取前置检查结果)";
|
||||
var cmd = COMMANDS[l.id];
|
||||
return (cmd || "(命令将在运行时由服务端生成)") + "\n# 工作目录:仓库根(WebFreeCAD 工作区),有头浏览器需要 DISPLAY=:1";
|
||||
}
|
||||
|
||||
function renderPractice(){
|
||||
var html = "";
|
||||
var groupsByKind = [
|
||||
["壳层", CATALOG.shell],
|
||||
["交叉", CATALOG.crosscut],
|
||||
["手册章节", CATALOG.chapters.map(function(c){ return c.id; })],
|
||||
["模块", CATALOG.modules.map(function(m){ return "MOD-" + m + "-01"; })]
|
||||
];
|
||||
groupsByKind.forEach(function(pair){
|
||||
html += '<div class="g">' + esc(pair[0]) + '</div>';
|
||||
pair[1].forEach(function(id){
|
||||
var checked = state.practice[id] ? " checked" : "";
|
||||
html += '<label><input type="checkbox" class="practice-case" value="' + esc(id) + '"' + checked + '> ' + esc(id) + '</label>';
|
||||
});
|
||||
});
|
||||
$("practice-list").innerHTML = html;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------- preflight */
|
||||
function renderPreflight(report){
|
||||
state.preflight = report;
|
||||
if (!report) { $("preflight-chips").innerHTML = '<span class="chip bad">无法读取前置检查</span>'; return; }
|
||||
$("preflight-chips").innerHTML = report.checks.map(function(c){
|
||||
return '<span class="chip ' + (c.ok ? "ok" : "bad") + '">' + (c.ok ? "✓ " : "✗ ") + esc(c.id) +
|
||||
'<span class="fix">' + esc(c.detail) + (c.ok ? "" : " · 修复:" + esc(c.fix)) + '</span></span>';
|
||||
}).join("");
|
||||
updateButtons();
|
||||
}
|
||||
|
||||
function updateButtons(){
|
||||
var l = state.lesson;
|
||||
var ready = state.online && !state.running && l && (!state.preflight || state.preflight.ok || l.job.kind === "preflight");
|
||||
$("run").disabled = !ready;
|
||||
$("cancel").disabled = !state.running || !state.online;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------- api */
|
||||
function api(path, options){
|
||||
options = options || {};
|
||||
options.headers = Object.assign({ "x-teaching-token": token }, options.headers || {});
|
||||
return fetch(path, options).then(function(res){
|
||||
return res.json().catch(function(){ return {}; }).then(function(body){
|
||||
if (!res.ok) { var err = new Error(body.error || ("HTTP " + res.status)); err.code = body.code; err.detail = body.detail; throw err; }
|
||||
return body;
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function checkHealth(){
|
||||
fetch("/api/console/health", { cache: "no-store" }).then(function(res){ return res.json(); }).then(function(){
|
||||
state.online = true; state.checked = true; setStatus(); refreshPreflight(); updateButtons();
|
||||
}).catch(function(){
|
||||
state.online = false; state.checked = true; setStatus(); updateButtons();
|
||||
$("preflight-chips").innerHTML = '<span class="chip warn">离线:无法读取前置检查</span>';
|
||||
});
|
||||
}
|
||||
|
||||
function setStatus(){
|
||||
var chip = $("status");
|
||||
chip.className = "chip " + (state.online ? "ok" : "bad");
|
||||
chip.textContent = state.online ? "服务在线" : "服务离线";
|
||||
$("offline-banner").hidden = state.online;
|
||||
}
|
||||
|
||||
function refreshPreflight(){
|
||||
if (!state.online) return;
|
||||
fetch("/api/console/preflight", { cache: "no-store" }).then(function(r){ return r.json(); }).then(renderPreflight).catch(function(){
|
||||
$("preflight-chips").innerHTML = '<span class="chip bad">前置检查失败</span>';
|
||||
});
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- running */
|
||||
function params(){
|
||||
if (!state.lesson || !state.lesson.job.selectable) return {};
|
||||
var ids = Object.keys(state.practice).filter(function(id){ return state.practice[id]; });
|
||||
return { only: ids, slow: $("observe").checked ? 300 : 0, highlight: $("observe").checked, screenshots: $("shots").checked ? "all" : "fails" };
|
||||
}
|
||||
|
||||
function startRun(){
|
||||
var l = state.lesson;
|
||||
if (!l) return;
|
||||
clearTerminal();
|
||||
state.logs = 0; state.running = true; state.job = null; state.jobId = null;
|
||||
$("verdict").className = "verdict muted"; $("verdict").textContent = "启动中…";
|
||||
$("results").innerHTML = '<p class="muted small">运行中…</p>';
|
||||
$("evidence").innerHTML = '<p class="muted small">运行结束后生成。</p>';
|
||||
updateButtons();
|
||||
var payload = { lessonId: l.id, params: params() };
|
||||
api("/api/console/run", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(payload) }).then(function(job){
|
||||
state.jobId = job.jobId;
|
||||
$("job-id").textContent = job.jobId;
|
||||
subscribe(job.jobId);
|
||||
}).catch(function(err){
|
||||
state.running = false; updateButtons();
|
||||
appendLine("stderr", "无法启动:" + (err.message || err));
|
||||
if (err.code === "E_PREFLIGHT" && err.detail && err.detail.blockers) {
|
||||
appendLine("sys", "未满足的前置:" + err.detail.blockers.map(function(b){ return b.id; }).join(", "));
|
||||
}
|
||||
$("verdict").className = "verdict bad"; $("verdict").textContent = "未启动(" + (err.code || "错误") + ")";
|
||||
});
|
||||
}
|
||||
|
||||
function subscribe(jobId){
|
||||
if (state.source) { state.source.close(); state.source = null; }
|
||||
var source = new EventSource("/api/console/events?jobId=" + encodeURIComponent(jobId) + "&token=" + encodeURIComponent(token));
|
||||
state.source = source;
|
||||
source.addEventListener("snapshot", function(event){ onSnapshot(JSON.parse(event.data)); });
|
||||
source.addEventListener("log", function(event){ var data = JSON.parse(event.data); appendLine(data.stream, data.text); });
|
||||
source.addEventListener("done", function(event){ onSnapshot(JSON.parse(event.data)); finishRun(); });
|
||||
source.onerror = function(){ /* server restarts close the stream; the page stays readable */ };
|
||||
}
|
||||
|
||||
function finishRun(){
|
||||
state.running = false;
|
||||
if (state.source) { state.source.close(); state.source = null; }
|
||||
updateButtons();
|
||||
var job = state.job;
|
||||
if (job && job.verdict === "pass") {
|
||||
state.completed[state.lesson.id] = true;
|
||||
try { localStorage.setItem("teaching-console-done-v1", JSON.stringify(state.completed)); } catch(e){}
|
||||
renderSidebar();
|
||||
}
|
||||
}
|
||||
|
||||
function onSnapshot(job){
|
||||
state.job = job;
|
||||
$("job-id").textContent = job.jobId || "";
|
||||
var planned = job.planned || 0, completed = job.completed || 0;
|
||||
$("progress-text").textContent = completed + " / " + planned;
|
||||
$("progress-bar").style.width = planned ? Math.round(100 * completed / planned) + "%" : "0%";
|
||||
$("current-case").textContent = job.current ? ("当前:" + job.current) : "";
|
||||
if (job.verdict) {
|
||||
$("verdict").className = "verdict " + job.verdict;
|
||||
$("verdict").textContent = verdictLabel(job.verdict) + (job.exitCode != null ? "(exit " + job.exitCode + ")" : "");
|
||||
} else if (job.state) {
|
||||
$("verdict").className = "verdict muted";
|
||||
$("verdict").textContent = job.state === "running" ? "运行中…" : job.state;
|
||||
}
|
||||
renderResults(job);
|
||||
renderEvidence(job);
|
||||
}
|
||||
|
||||
function verdictLabel(v){
|
||||
return { pass: "通过", product_fail: "产品失败", precondition_fail: "前置失败", run_fail: "运行失败",
|
||||
timeout: "超时", cancelled: "已取消", preflight_failed: "前置失败" }[v] || v;
|
||||
}
|
||||
|
||||
function renderResults(job){
|
||||
var results = job.results || [];
|
||||
if (!results.length) return;
|
||||
var rows = results.map(function(item){
|
||||
return '<tr><td class="path">' + esc(item.id) + '</td><td>' + esc(item.title || "") + '</td><td class="st-' + esc(item.status) + '">' + esc(item.status) + '</td><td>' + (item.seconds != null ? Number(item.seconds).toFixed(1) + "s" : "") + '</td><td class="small">' + esc(item.error || "") + '</td></tr>';
|
||||
}).join("");
|
||||
$("results").innerHTML = '<div class="table-scroll" style="overflow:auto"><table><thead><tr><th>用例</th><th>标题</th><th>状态</th><th>耗时</th><th>错误</th></tr></thead><tbody>' + rows + "</tbody></table></div>";
|
||||
}
|
||||
|
||||
function renderEvidence(job){
|
||||
var links = [];
|
||||
if (job.runDir) {
|
||||
var base = "/evidence/" + job.runDir.replace(/^docs\//, "");
|
||||
links.push('<a href="' + esc(base) + '/index.html" target="_blank" rel="noopener">完整报告(index.html)</a>');
|
||||
links.push('<a href="' + esc(base) + '/report.md" target="_blank" rel="noopener">report.md</a>');
|
||||
links.push('<a href="' + esc(base) + '/GAPS.md" target="_blank" rel="noopener">GAPS.md</a>');
|
||||
}
|
||||
if (job.kind === "probe") links.push('<a href="/api/console/artifacts/' + esc(job.jobId) + '/layout.json" target="_blank" rel="noopener">布局报告 JSON</a>');
|
||||
if (job.origin) links.push('<span class="small muted">本次运行 origin:<code>' + esc(job.origin) + '</code></span>');
|
||||
$("evidence").innerHTML = links.length ? links.map(function(x){ return '<div>' + x + '</div>'; }).join("") : '<p class="muted small">运行结束后可打开完整报告与截图。</p>';
|
||||
}
|
||||
|
||||
/* --------------------------------------------------------------- terminal */
|
||||
function appendLine(stream, text){
|
||||
var term = $("terminal");
|
||||
if (state.logs === 0) term.textContent = "";
|
||||
state.logs += 1;
|
||||
var span = document.createElement("span");
|
||||
span.className = stream === "stderr" ? "err" : (/passed|ORIGIN=/.test(text) ? "ok" : (stream === "sys" ? "sys" : ""));
|
||||
span.textContent = text + "\n";
|
||||
term.appendChild(span);
|
||||
while (term.childNodes.length > 2000) term.removeChild(term.firstChild);
|
||||
if (state.autoScroll) term.scrollTop = term.scrollHeight;
|
||||
}
|
||||
|
||||
function clearTerminal(){
|
||||
$("terminal").textContent = "";
|
||||
state.logs = 0;
|
||||
}
|
||||
|
||||
/* ----------------------------------------------------------------- wiring */
|
||||
$("search").addEventListener("input", renderSidebar);
|
||||
document.addEventListener("keydown", function(event){
|
||||
if (event.key === "/" && document.activeElement !== $("search")) { event.preventDefault(); $("search").focus(); }
|
||||
});
|
||||
$("course-list").addEventListener("click", function(event){
|
||||
var button = event.target.closest("button[data-id]");
|
||||
if (!button) return;
|
||||
state.lesson = byId[button.getAttribute("data-id")];
|
||||
state.practice = {};
|
||||
renderLesson();
|
||||
});
|
||||
$("practice-list").addEventListener("change", function(event){
|
||||
var input = event.target.closest("input.practice-case");
|
||||
if (!input) return;
|
||||
var id = input.value;
|
||||
if (input.checked) {
|
||||
var selected = Object.keys(state.practice).filter(function(k){ return state.practice[k]; });
|
||||
if (selected.length >= 8) { input.checked = false; appendLine("sys", "自由练习最多选择 8 个用例。"); return; }
|
||||
state.practice[id] = true;
|
||||
} else {
|
||||
delete state.practice[id];
|
||||
}
|
||||
});
|
||||
$("run").addEventListener("click", startRun);
|
||||
$("cancel").addEventListener("click", function(){
|
||||
if (!state.jobId) return;
|
||||
api("/api/console/cancel", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ jobId: state.jobId }) })
|
||||
.catch(function(err){ appendLine("stderr", "取消失败:" + err.message); });
|
||||
});
|
||||
$("recheck").addEventListener("click", function(){ checkHealth(); });
|
||||
$("terminal").addEventListener("scroll", function(){ var t = $("terminal"); state.autoScroll = t.scrollTop + t.clientHeight >= t.scrollHeight - 30; });
|
||||
|
||||
renderSidebar();
|
||||
state.lesson = byId["lesson-00-preflight"] || LESSONS.lessons[0];
|
||||
renderLesson();
|
||||
checkHealth();
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
Reference in New Issue
Block a user