diff --git a/docs/current/carrier-partdesign-toolkit/continuation.md b/docs/current/carrier-partdesign-toolkit/continuation.md index ec4638f6..e86d3c4b 100644 --- a/docs/current/carrier-partdesign-toolkit/continuation.md +++ b/docs/current/carrier-partdesign-toolkit/continuation.md @@ -87,3 +87,28 @@ `ui-stills/`(22 MB 运行截图,可重建)、`out/opfs` 镜像与 `tmp-*-probe.mjs`。 - 待用户:`git push gitea web-desktop-parity-20261113`(领先远端 11 个提交); 重启教学服务以加载新的 carrier-toolkit.html 与控制台页面。 + +## 2026-11-25 · 教学页内直接运行(单件 / 按组 / 全部 / 装配) + +- 新增 `web/teaching/console-runner.js`(经典脚本,`file://` 安全):`window.TeachingRunner.mount()` + 统一提供令牌读取、`POST /api/console/run`、SSE、终端 / 判定 / 结果 / 证据 / 进度渲染、取消、 + 离线降级;`runSequence()` 逐课串行(`E_BUSY` 409 退避 2 s × 30)、`keepGoing` 失败继续、 + 终判「全部通过 / 已取消(完成 k/n)/ 汇总」。`template.html` 改为引用该脚本 + 控制台专属贴片, + `console.html` 重新生成;`check:console` 与 `self-test` 全绿(120 课 / 71 案例)。 +- `build-carrier-page.mjs`:导出 `carrierLessons()` 构建期生成 `window.__CARRIER__` + (20 件 / 环境 / 装配的课 id,不手抄);每张零件卡一个「运行本件」`button.run-part[data-lesson-id]` + 与 `[data-part-status]` 徽标,每个系统分组一个「运行本组」`button.run-group[data-lesson-ids]`, + 顶部「运行全部 20 件」与「环境自检(dry)」;按钮由 runner 统一门控 + (`online && !busy && preflight.ok`),状态镜像到 `body.dataset.runnerState`。 +- 修复(构建器共享 owner):`runButton()` 曾把 class 写在模板里、调用方又在 attributes 传 + `class="run-group"`,生成重复 `class` 属性 → 浏览器只取第一个,分组/装配类名被静默丢弃, + live 门禁报「分组运行按钮 0 个」。改为合并 class 列表后重新生成(12 组 + 1 装配齐全)。 +- `server.mjs` 启动横幅新增 `carrier: /carrier-toolkit.html?token=…`; + `web/package.json` 新增 `check:carrier-live`,`check:carrier` 保持离线。 +- 门禁:`build-carrier-page/build-console --check` OK;离线 `check-carrier-page` 通过 + (20 卡 / 15 区 / 210 步 / 按钮禁用 / runnerState=offline / 双视口 0 溢出); + `check-carrier-page --live` 通过(临时端口起服务,点环境自检课 → 「前置全部满足」→ + 判定「通过」rows=1 evidence=1,结束后 runnerState=ready、按钮恢复);`check:carrier`、 + `check:console` 全绿。 +- 有头实跑入口:教学服务器横幅打印的 `carrier-toolkit.html?token=…`(默认端口 5190)。 + 5183 是 `vite preview`(服务 `web/dist`),`/teaching/*`、`/api/*` 走 SPA 回退,不能运行。 diff --git a/web/package.json b/web/package.json index 4b5afba1..af3c62fe 100644 --- a/web/package.json +++ b/web/package.json @@ -60,6 +60,7 @@ "carrier:self-test": "node ../tools/carrier/self-test.mjs", "build:carrier-page": "node tools/teaching-console/build-carrier-page.mjs", "check:carrier": "node ../tools/carrier/self-test.mjs && node tools/teaching-console/build-carrier-page.mjs --check && node tools/teaching-console/check-carrier-page.mjs", + "check:carrier-live": "node tools/teaching-console/check-carrier-page.mjs --live", "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", diff --git a/web/teaching/carrier-toolkit.html b/web/teaching/carrier-toolkit.html index 9c4b52d3..229c78dd 100644 --- a/web/teaching/carrier-toolkit.html +++ b/web/teaching/carrier-toolkit.html @@ -35,6 +35,37 @@ table{border-collapse:collapse;width:100%;font-size:13.5px} th,td{border-bottom:1px solid var(--line);padding:6px 8px;text-align:left;vertical-align:top} th{color:var(--muted);font-weight:500} .note{border-left:3px solid var(--warn);padding:8px 12px;background:#1d1a12;border-radius:0 8px 8px 0;margin:10px 0} +.row{display:flex;gap:10px;align-items:center;flex-wrap:wrap} +.grouphead{display:flex;gap:10px;align-items:center} +.chips{display:flex;flex-wrap:wrap;gap:6px;margin:8px 0} +.chip{display:inline-block;border:1px solid var(--line);border-radius:999px;padding:1px 9px;font-size:12px;background:var(--panel2)} +.chip.ok{border-color:#3d6b48;color:var(--ok)} +.chip.bad{border-color:#6b3d3d;color:var(--bad)} +.chip.warn{border-color:#6b5a3d;color:var(--warn)} +.chip .fix{display:none;margin-left:6px;color:var(--muted)} +.chip.bad:hover .fix{display:inline} +button.act,button.ghost{font:inherit;font-size:13px;padding:5px 12px;border-radius:8px;border:1px solid var(--line);cursor:pointer} +button.act{background:#1f3b44;color:var(--text);border-color:#2f6b7a} +button.ghost{background:var(--panel2);color:var(--text)} +button:disabled{opacity:.45;cursor:not-allowed} +.runrow{display:flex;gap:10px;align-items:center;margin:0 0 8px} +.part-status{font-size:12.5px} +.part-status.ok{color:var(--ok)} +.part-status.bad{color:var(--bad)} +.verdict{font-size:13px;padding:2px 10px;border-radius:999px;border:1px solid var(--line);background:var(--panel2)} +.verdict.pass{color:var(--ok);border-color:#3d6b48} +.verdict.bad{color:var(--bad);border-color:#6b3d3d} +.verdict.muted{color:var(--muted)} +.progress{height:8px;background:#0b1117;border:1px solid var(--line);border-radius:999px;overflow:hidden;margin:8px 0} +.progress i{display:block;height:100%;width:0;background:var(--accent);transition:width .3s} +pre.term{background:#0b1117;border:1px solid var(--line);border-radius:8px;padding:10px;max-height:320px;overflow:auto;font-size:12px;white-space:pre-wrap;word-break:break-all} +pre.term .ok{color:var(--ok)} +pre.term .err{color:var(--bad)} +pre.term .sys{color:var(--warn)} +.st-passed{color:var(--ok)} +.st-failed{color:var(--bad)} +.st-blocked{color:var(--warn)} +.banner.offline{border-left:3px solid var(--bad);background:#24161a;padding:10px 12px;border-radius:0 8px 8px 0;margin:8px 0} @media (max-width:700px){.parts{grid-template-columns:1fr}main{padding:12px}} @media print{header.top,.links,pre.cmd{display:none!important}} @@ -60,12 +91,32 @@ th{color:var(--muted);font-weight:500}
零件在船上是什么样:每件都按舰体坐标建模(X 向舰首为 +,z=24 m 为飞行甲板面),所以单独打开是零件、装配后自动就位,插装位姿是单位矩阵。改一个零件的尺寸,装配结果跟着变——这正是教学里要讲的“零件与装配同源”。
+
+

在页面上直接运行

检测服务…等待运行
+ +

按钮调用的是已有的工具 tools/carrier/create-part.mjs 与 create-assembly.mjs:界面点击由共享引擎执行,本机会开一个有头的 Chrome 窗口,日志与判定实时显示在下面。单件约 5–10 分钟;「运行本组 / 运行全部」按队列串行(同一时间只跑一件),失败的零件会标记在卡片上,队列继续(等同于 create-all --keep-going)。

+
检查中…
+
+ + + + + +
+
0 / 0
+
+
等待运行…
+

运行结束后按零件列出。

+

运行结束后给出报告 JSON。

+
+
-

舰体结构 1 件

+

舰体结构 1 件

P01 · 舰体

10 步
CarrierHull · 记录体积 260,847 mm³ · 特征 Loft
  1. 草图CarrierHull · 横剖面 x=-166.5
  2. 草图CarrierHull · 横剖面 x=-150
  3. 草图CarrierHull · 横剖面 x=-120
  4. 草图CarrierHull · 横剖面 x=-60
  5. 草图CarrierHull · 横剖面 x=0
  6. 草图CarrierHull · 横剖面 x=60
  7. 草图CarrierHull · 横剖面 x=110
  8. 草图CarrierHull · 横剖面 x=145
  9. 草图CarrierHull · 横剖面 x=166.5
  10. 特征CarrierHull · 舰体放样
+
cd "/media/mes123456/Elements SE/WebFreeCAD/FreeCADWasmDev/working/FreeCAD" && DISPLAY=:1 node tools/carrier/create-part.mjs P01
-

斜角甲板 1 件

+

斜角甲板 1 件

P03 · 斜角甲板

2 步
CarrierAngledDeck · 记录体积 6,912 mm³ · 特征 Pad
  1. 草图CarrierAngledDeck · 斜角甲板平面
  2. 特征CarrierAngledDeck · 斜角甲板
+
cd "/media/mes123456/Elements SE/WebFreeCAD/FreeCADWasmDev/working/FreeCAD" && DISPLAY=:1 node tools/carrier/create-part.mjs P03
-

飞行甲板 1 件

+

飞行甲板 1 件

P02 · 飞行甲板

14 步
CarrierDeck · 记录体积 35,733 mm³ · 特征 Pad、Pocket、Chamfer
  1. 草图CarrierDeck · 甲板平面
  2. 特征CarrierDeck · 甲板板
  3. 草图CarrierDeck · 升降机井口 (-20, 26)
  4. 特征CarrierDeck · 切除井口 WellPocket1
  5. 草图CarrierDeck · 升降机井口 (-20, -26)
  6. 特征CarrierDeck · 切除井口 WellPocket2
  7. 草图CarrierDeck · 升降机井口 (-62, 26)
  8. 特征CarrierDeck · 切除井口 WellPocket3
  9. 草图CarrierDeck · 升降机井口 (-62, -26)
  10. 特征CarrierDeck · 切除井口 WellPocket4
  11. 修整CarrierDeck · 井口边缘倒角
  12. 草图CarrierDeck · 系留桩平面
  13. 特征CarrierDeck · 系留桩
  14. 阵列/镜像CarrierDeck · 系留桩阵列
+
cd "/media/mes123456/Elements SE/WebFreeCAD/FreeCADWasmDev/working/FreeCAD" && DISPLAY=:1 node tools/carrier/create-part.mjs P02
-

舰岛上层建筑 1 件

+

舰岛上层建筑 1 件

P04 · 舰岛

11 步
CarrierIsland · 记录体积 10,658 mm³ · 特征 Pad、Chamfer
  1. 草图CarrierIsland · IslandBase 平面 z=24
  2. 特征CarrierIsland · 塔体 IslandBase
  3. 草图CarrierIsland · IslandTower 平面 z=36
  4. 特征CarrierIsland · 塔体 IslandTower
  5. 草图CarrierIsland · IslandBridge 平面 z=46
  6. 特征CarrierIsland · 塔体 IslandBridge
  7. 草图CarrierIsland · 烟囱平面
  8. 特征CarrierIsland · 烟囱
  9. 草图CarrierIsland · 桅杆截面
  10. 特征CarrierIsland · 桅杆
  11. 修整CarrierIsland · 舰桥顶倒角
+
cd "/media/mes123456/Elements SE/WebFreeCAD/FreeCADWasmDev/working/FreeCAD" && DISPLAY=:1 node tools/carrier/create-part.mjs P04
-

机库 1 件

+

机库 1 件

P05 · 机库

4 步
CarrierHangar · 记录体积 39,640 mm³ · 特征 Pad、Pocket
  1. 草图CarrierHangar · 机库外壳平面
  2. 特征CarrierHangar · 机库外壳
  3. 草图CarrierHangar · 机库内腔平面
  4. 特征CarrierHangar · 掏空内腔
+
cd "/media/mes123456/Elements SE/WebFreeCAD/FreeCADWasmDev/working/FreeCAD" && DISPLAY=:1 node tools/carrier/create-part.mjs P05
-

航空保障(升降机/弹射器/拦阻索) 3 件

+

航空保障(升降机/弹射器/拦阻索) 3 件

P06 · 升降机

8 步
CarrierElevators · 记录体积 1,008 mm³ · 特征 Pad
  1. 草图CarrierElevators · 升降机平台 (-20, 26)
  2. 特征CarrierElevators · 升降机平台
  3. 草图CarrierElevators · 升降机平台 (-20, -26)
  4. 特征CarrierElevators · 升降机平台
  5. 草图CarrierElevators · 升降机平台 (-62, 26)
  6. 特征CarrierElevators · 升降机平台
  7. 草图CarrierElevators · 升降机平台 (-62, -26)
  8. 特征CarrierElevators · 升降机平台
+
cd "/media/mes123456/Elements SE/WebFreeCAD/FreeCADWasmDev/working/FreeCAD" && DISPLAY=:1 node tools/carrier/create-part.mjs P06
-

雷达与传感 1 件

+

雷达与传感 1 件

P09 · 相控阵雷达

6 步
CarrierRadar · 记录体积 69 mm³ · 特征 Pad
  1. 草图CarrierRadar · 雷达基座截面
  2. 特征CarrierRadar · 雷达基座
  3. 草图CarrierRadar · 阵面草图
  4. 特征CarrierRadar · 相控阵面
  5. 草图CarrierRadar · 阵面支架截面
  6. 特征CarrierRadar · 阵面支架
+
cd "/media/mes123456/Elements SE/WebFreeCAD/FreeCADWasmDev/working/FreeCAD" && DISPLAY=:1 node tools/carrier/create-part.mjs P09
-

近防武器 1 件

+

近防武器 1 件

P10 · 近防炮

8 步
CarrierCiws · 记录体积 56 mm³ · 特征 Pad
  1. 草图CarrierCiws · 炮座截面
  2. 特征CarrierCiws · 炮座
  3. 草图CarrierCiws · 炮塔壳体
  4. 特征CarrierCiws · 炮塔壳体
  5. 草图CarrierCiws · 炮管截面 y=-0.7
  6. 特征CarrierCiws · 炮管
  7. 草图CarrierCiws · 炮管截面 y=0.7
  8. 特征CarrierCiws · 炮管
+
cd "/media/mes123456/Elements SE/WebFreeCAD/FreeCADWasmDev/working/FreeCAD" && DISPLAY=:1 node tools/carrier/create-part.mjs P10
-

舰载战斗机 6 件

+

舰载战斗机 6 件

P11 · 舰载战斗机 A

13 步
CarrierFighterA · 记录体积 83 mm³ · 特征 Revolution、Pad、Mirrored
  1. 草图CarrierFighterA · 机身半剖
  2. 特征CarrierFighterA · 机身回转
  3. 草图CarrierFighterA · 右机翼平面
  4. 特征CarrierFighterA · 右机翼
  5. 阵列/镜像CarrierFighterA · 左机翼镜像
  6. 草图CarrierFighterA · 平尾平面
  7. 特征CarrierFighterA · 平尾
  8. 阵列/镜像CarrierFighterA · 平尾镜像
  9. 草图CarrierFighterA · 垂尾平面
  10. 特征CarrierFighterA · 垂尾
  11. 图元CarrierFighterA · 座舱盖
  12. 草图CarrierFighterA · 尾喷口截面
  13. 特征CarrierFighterA · 尾喷口
+
cd "/media/mes123456/Elements SE/WebFreeCAD/FreeCADWasmDev/working/FreeCAD" && DISPLAY=:1 node tools/carrier/create-part.mjs P11
-

舰载预警机 1 件

+

舰载预警机 1 件

P17 · 舰载预警机

21 步
CarrierAwacs · 记录体积 255 mm³ · 特征 Revolution、Pad、Mirrored
  1. 草图CarrierAwacs · 机身半剖
  2. 特征CarrierAwacs · 机身回转
  3. 草图CarrierAwacs · 右机翼平面
  4. 特征CarrierAwacs · 右机翼
  5. 阵列/镜像CarrierAwacs · 左机翼镜像
  6. 草图CarrierAwacs · 桨舱截面 y=4.2
  7. 特征CarrierAwacs · 桨舱
  8. 草图CarrierAwacs · 桨舱截面 y=8.6
  9. 特征CarrierAwacs · 桨舱
  10. 阵列/镜像CarrierAwacs · 桨舱镜像
  11. 草图CarrierAwacs · 平尾平面
  12. 特征CarrierAwacs · 平尾
  13. 阵列/镜像CarrierAwacs · 平尾镜像
  14. 草图CarrierAwacs · 垂尾平面
  15. 特征CarrierAwacs · 垂尾
  16. 草图CarrierAwacs · 旋罩支柱截面 x=-2.4
  17. 特征CarrierAwacs · 旋罩支柱
  18. 草图CarrierAwacs · 旋罩支柱截面 x=2.4
  19. 特征CarrierAwacs · 旋罩支柱
  20. 草图CarrierAwacs · 旋罩截面
  21. 特征CarrierAwacs · 雷达旋罩
+
cd "/media/mes123456/Elements SE/WebFreeCAD/FreeCADWasmDev/working/FreeCAD" && DISPLAY=:1 node tools/carrier/create-part.mjs P17
-

舰载直升机 2 件

+

舰载直升机 2 件

P18 · 舰载直升机 A

13 步
CarrierHelicopterA · 记录体积 48 mm³ · 特征 Revolution、Pad、PolarPattern
  1. 草图CarrierHelicopterA · 机身半剖
  2. 特征CarrierHelicopterA · 机身回转
  3. 草图CarrierHelicopterA · 尾梁截面
  4. 特征CarrierHelicopterA · 尾梁
  5. 草图CarrierHelicopterA · 尾鳍平面
  6. 特征CarrierHelicopterA · 尾鳍
  7. 草图CarrierHelicopterA · 尾桨截面
  8. 特征CarrierHelicopterA · 尾桨
  9. 草图CarrierHelicopterA · 旋翼轴截面
  10. 特征CarrierHelicopterA · 旋翼轴
  11. 草图CarrierHelicopterA · 主旋翼叶片
  12. 特征CarrierHelicopterA · 主旋翼叶片
  13. 阵列/镜像CarrierHelicopterA · 四叶旋翼
+
cd "/media/mes123456/Elements SE/WebFreeCAD/FreeCADWasmDev/working/FreeCAD" && DISPLAY=:1 node tools/carrier/create-part.mjs P18
-

甲板标线 1 件

+

甲板标线 1 件

P20 · 甲板标线

6 步
CarrierMarkings · 记录体积 26 mm³ · 特征 Pad
  1. 草图CarrierMarkings · 甲板中心线
  2. 特征CarrierMarkings · 中心线
  3. 草图CarrierMarkings · 降落区边框
  4. 特征CarrierMarkings · 降落区边框
  5. 草图CarrierMarkings · 甲板边缘线
  6. 特征CarrierMarkings · 甲板边缘线
+
cd "/media/mes123456/Elements SE/WebFreeCAD/FreeCADWasmDev/working/FreeCAD" && DISPLAY=:1 node tools/carrier/create-part.mjs P20
-

装配 1 艘

+

装配 1 艘

CarrierAssembly · 20 件合成整舰

20 插入 / 19 关节
新建装配文档「航空母舰」,逐个装载并插入 20 个零件链接,接地舰体,其余 19 件各建一个固定关节,最后求解并列出 BOM。
@@ -324,5 +394,35 @@ th{color:var(--muted);font-weight:500}

本页由 web/tools/teaching-console/build-carrier-page.mjs 生成,请勿手改。

+ + + diff --git a/web/teaching/console-runner.js b/web/teaching/console-runner.js new file mode 100644 index 00000000..b9327f60 --- /dev/null +++ b/web/teaching/console-runner.js @@ -0,0 +1,471 @@ +// Shared runner for the teaching pages (console.html and carrier-toolkit.html). +// +// Classic script on purpose: carrier-toolkit.html is also opened straight from +// disk with file://, where ES modules are blocked. The runner owns everything +// that talks to the teaching server — token handling, /api/console/run, the SSE +// event stream, progress/verdict/results/evidence rendering, the log terminal +// and cancellation. Pages keep only their own glue (course list, card buttons) +// and mount the runner over the shared DOM contract below. +// +// Server contract (web/teaching/server.mjs): same-origin only, `x-teaching-token` +// header, one job globally (E_BUSY), events `snapshot` / `log` / `done`. +(function () { + "use strict"; + + var DEFAULT_IDS = { + status: "status", + banner: "offline-banner", + preflight: "preflight-chips", + recheck: "recheck", + run: "run", + cancel: "cancel", + terminal: "terminal", + verdict: "verdict", + results: "results", + evidence: "evidence", + progressText: "progress-text", + progressBar: "progress-bar", + current: "current-case", + jobId: "job-id", + }; + + var VERDICT_ZH = { + pass: "通过", + product_fail: "产品失败", + precondition_fail: "前置失败", + run_fail: "运行失败", + timeout: "超时", + cancelled: "已取消", + preflight_failed: "前置失败", + }; + + function esc(text) { + return String(text == null ? "" : text).replace(/[&<>"]/g, function (c) { + return { "&": "&", "<": "<", ">": ">", '"': """ }[c]; + }); + } + + function verdictLabel(value) { + return VERDICT_ZH[value] || value || ""; + } + + function wait(ms) { + return new Promise(function (resolve) { setTimeout(resolve, ms); }); + } + + /** `?token=…` → sessionStorage → URL cleaned; empty when the page came from disk. */ + function readToken() { + var token = ""; + try { + var url = new URL(location.href); + var param = url.searchParams.get("token"); + if (param) { + token = param; + sessionStorage.setItem("teaching-token", param); + url.searchParams.delete("token"); + history.replaceState(null, "", url.toString()); + } else { + token = sessionStorage.getItem("teaching-token") || ""; + } + } catch (error) { + token = ""; + } + return token; + } + + function mount(options) { + var config = options || {}; + var ids = Object.assign({}, DEFAULT_IDS, config.ids || {}); + var selector = config.buttonSelector || "#run"; + var extraGate = config.extraGate || function () { return true; }; + var resolveRun = config.resolveRun || function () { return null; }; + var onDone = config.onDone || function () {}; + var labelFor = config.labelFor || function (lessonId) { return lessonId; }; + var token = readToken(); + + var state = { + online: false, preflight: null, running: false, queue: null, + job: null, jobId: null, source: null, logs: 0, autoScroll: true, lessonId: null, + }; + + function node(key) { return document.getElementById(ids[key]); } + + function busy() { return state.running || Boolean(state.queue); } + + /* ------------------------------------------------------------- rendering */ + function setVerdict(text, className) { + var target = node("verdict"); + if (!target) return; + target.className = "verdict " + (className || "muted"); + target.textContent = text; + } + + function appendLine(stream, text) { + var term = node("terminal"); + if (!term) return; + 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() { + var term = node("terminal"); + if (term) term.textContent = ""; + state.logs = 0; + } + + function renderProgress(job) { + var progress = (job && job.progress) || job || {}; + var planned = progress.planned != null ? progress.planned : (job && job.planned) || 0; + var completed = progress.completed != null ? progress.completed : (job && job.completed) || 0; + var current = progress.current || (job && job.current) || ""; + if (state.queue) { + var queue = state.queue; + var finished = queue.results.length; + var passed = queue.results.filter(function (item) { return item.verdict === "pass"; }).length; + var text = node("progressText"); + if (text) { + text.textContent = finished + " / " + queue.total + " 件 · 通过 " + passed + + " / 失败 " + (finished - passed); + } + var bar = node("progressBar"); + if (bar) bar.style.width = queue.total ? Math.round(100 * finished / queue.total) + "%" : "0%"; + var currentCase = node("current"); + if (currentCase) { + currentCase.textContent = queue.currentLabel ? "当前:" + queue.currentLabel + "(" + (finished + 1) + "/" + queue.total + ")" : ""; + } + return; + } + var progressText = node("progressText"); + if (progressText) progressText.textContent = completed + " / " + planned; + var progressBar = node("progressBar"); + if (progressBar) progressBar.style.width = planned ? Math.round(100 * completed / planned) + "%" : "0%"; + var currentCase = node("current"); + if (currentCase) currentCase.textContent = current ? "当前:" + current : ""; + } + + function renderResults(job) { + var target = node("results"); + if (!target) return; + var progress = (job && job.progress) || {}; + var results = progress.results || (job && job.results) || []; + if (!results.length) return; + var rows = results.map(function (item) { + return '' + esc(item.id) + '' + esc(item.title || "") + + '' + esc(item.status) + + "" + (item.seconds != null ? Number(item.seconds).toFixed(1) + "s" : "") + + '' + esc(item.error || "") + ""; + }).join(""); + target.innerHTML = '
' + + rows + "
用例标题状态耗时错误
"; + } + + function renderEvidence(job) { + var target = node("evidence"); + if (!target) return; + var links = []; + if (job && job.runDir) { + var base = "/evidence/" + job.runDir.replace(/^docs\//, ""); + links.push('完整报告(index.html)'); + links.push('report.md'); + links.push('GAPS.md'); + } + if (job && job.kind === "probe") { + links.push('布局报告 JSON'); + } + if (job && (job.kind === "reducer-part" || job.kind === "reducer-assembly" + || job.kind === "carrier-part" || job.kind === "carrier-assembly")) { + links.push('零件/装配报告 JSON'); + } + if (job && job.origin) { + links.push('本次运行 origin:' + esc(job.origin) + ""); + } + target.innerHTML = links.length ? links.map(function (link) { return "
" + link + "
"; }).join("") + : '

运行结束后可打开完整报告与截图。

'; + } + + function onSnapshot(job) { + if (!job) return; + state.job = job; + var jobId = node("jobId"); + if (jobId) jobId.textContent = job.jobId || ""; + renderProgress(job); + if (job.verdict) { + setVerdict(verdictLabel(job.verdict) + (job.exitCode != null ? "(exit " + job.exitCode + ")" : ""), + job.verdict === "pass" ? "pass" : (job.verdict === "cancelled" ? "muted" : "bad")); + } else if (job.state) { + setVerdict(job.state === "running" ? "运行中…" : job.state, "muted"); + } + renderResults(job); + renderEvidence(job); + } + + /* --------------------------------------------------------------- buttons */ + function ready() { + var preflightBlocked = state.preflight && state.preflight.ok === false; + return state.online && !busy() && !preflightBlocked && extraGate(); + } + + function syncButtons() { + var buttons = document.querySelectorAll(selector); + for (var index = 0; index < buttons.length; index += 1) buttons[index].disabled = !ready(); + var cancelButton = node("cancel"); + if (cancelButton) cancelButton.disabled = !busy() || !state.online; + // Gates read this instead of re-deriving the conditions. + document.body.dataset.runnerState = busy() ? "running" : (!state.online ? "offline" : (ready() ? "ready" : "blocked")); + } + + /* ------------------------------------------------------------------- api */ + function api(path, request) { + var requestOptions = request || {}; + requestOptions.headers = Object.assign({ "x-teaching-token": token }, requestOptions.headers || {}); + return fetch(path, requestOptions).then(function (response) { + return response.json().catch(function () { return {}; }).then(function (body) { + if (!response.ok) { + var error = new Error(body.error || ("HTTP " + response.status)); + error.code = body.code; + error.detail = body.detail; + throw error; + } + return body; + }); + }); + } + + function checkHealth() { + fetch("/api/console/health", { cache: "no-store" }).then(function (response) { + if (!response.ok) throw new Error("HTTP " + response.status); + return response.json(); + }).then(function () { + state.online = true; + var status = node("status"); + if (status) { status.className = "chip ok"; status.textContent = "服务在线"; } + var banner = node("banner"); + if (banner) banner.hidden = true; + syncButtons(); + refreshPreflight(); + }).catch(function () { + state.online = false; + var status = node("status"); + if (status) { status.className = "chip bad"; status.textContent = token ? "服务离线" : "未连接教学服务"; } + var banner = node("banner"); + if (banner) banner.hidden = false; + var preflight = node("preflight"); + if (preflight) preflight.innerHTML = '离线:无法读取前置检查'; + syncButtons(); + }); + } + + function refreshPreflight() { + if (!state.online) return; + fetch("/api/console/preflight", { cache: "no-store" }).then(function (response) { + return response.json(); + }).then(function (report) { + state.preflight = report; + var target = node("preflight"); + if (target) { + target.innerHTML = (report.checks || []).map(function (check) { + return '' + (check.ok ? "✓ " : "✗ ") + esc(check.id) + + '' + esc(check.detail) + (check.ok ? "" : " · 修复:" + esc(check.fix)) + ""; + }).join(""); + } + syncButtons(); + }).catch(function () { + var target = node("preflight"); + if (target) target.innerHTML = '前置检查失败'; + }); + } + + /* ---------------------------------------------------------------- running */ + function closeSource() { + if (state.source) { state.source.close(); state.source = null; } + } + + function subscribe(jobId) { + closeSource(); + return new Promise(function (resolve) { + 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) { + var job = JSON.parse(event.data); + onSnapshot(job); + closeSource(); + state.running = false; + syncButtons(); + try { onDone(state.lessonId, job); } catch (error) { /* page glue must not break the runner */ } + resolve(job); + }); + source.onerror = function () { /* a server restart closes the stream; the page stays readable */ }; + }); + } + + /** Start one lesson. Resolves with the final snapshot once the job is done. */ + function run(lessonId, params) { + if (!lessonId) return Promise.reject(new Error("没有选择课程")); + if (!state.queue) clearTerminal(); + state.running = true; + state.job = null; + state.jobId = null; + state.lessonId = lessonId; + setVerdict("启动中…", "muted"); + var results = node("results"); + if (results) results.innerHTML = '

运行中…

'; + var evidence = node("evidence"); + if (evidence) evidence.innerHTML = '

运行结束后生成。

'; + syncButtons(); + var payload = { lessonId: lessonId, params: params || {} }; + return api("/api/console/run", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify(payload), + }).then(function (job) { + state.jobId = job.jobId; + var jobId = node("jobId"); + if (jobId) jobId.textContent = job.jobId; + return subscribe(job.jobId); + }).catch(function (error) { + state.running = false; + syncButtons(); + if (error.code !== "E_BUSY") { + appendLine("stderr", "无法启动:" + (error.message || error)); + if (error.code === "E_PREFLIGHT" && error.detail && error.detail.blockers) { + appendLine("sys", "未满足的前置:" + error.detail.blockers.map(function (blocker) { return blocker.id; }).join(", ")); + } + setVerdict("未启动(" + (error.code || "错误") + ")", "bad"); + } + throw error; + }); + } + + /** One at a time with E_BUSY back-off, so a queue never fights the server's single job. */ + function startWithRetry(lessonId, params) { + var attempt = 0; + function go() { + return run(lessonId, params).catch(function (error) { + if (error.code === "E_BUSY" && attempt < 30) { + attempt += 1; + appendLine("sys", "上一个任务仍在运行,排队等待…"); + return wait(2000).then(go); + } + throw error; + }); + } + return go(); + } + + function cancel() { + if (!state.jobId) return Promise.resolve(); + return api("/api/console/cancel", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ jobId: state.jobId }), + }).catch(function (error) { appendLine("stderr", "取消失败:" + error.message); }); + } + + /** Run lessons sequentially; each step waits for the previous `done` event. */ + function runSequence(lessonIds, sequenceOptions) { + var options = sequenceOptions || {}; + var keepGoing = options.keepGoing !== false; + var list = (lessonIds || []).slice(); + var results = []; + var cancelled = false; + clearTerminal(); + state.queue = { total: list.length, results: results, currentLabel: "" }; + var index = 0; + + function finish(how) { + state.running = false; + var passed = results.filter(function (item) { return item.verdict === "pass"; }).length; + var failed = results.length - passed; + if (how === "cancelled") { + setVerdict("已取消(完成 " + results.length + "/" + list.length + ")", "muted"); + } else if (passed === list.length && results.length === list.length) { + setVerdict("全部通过(" + passed + "/" + list.length + ")", "pass"); + } else { + setVerdict("完成 " + results.length + "/" + list.length + " · 通过 " + passed + " · 失败 " + failed, "bad"); + } + state.queue = null; + syncButtons(); + return results; + } + + function next() { + if (cancelled) return Promise.resolve(finish("cancelled")); + if (index >= list.length) return Promise.resolve(finish(null)); + var lessonId = list[index]; + index += 1; + state.queue.currentLabel = labelFor(lessonId); + appendLine("sys", "—— " + labelFor(lessonId) + " ——"); + return startWithRetry(lessonId, {}).then(function (job) { + var verdict = job && job.verdict; + results.push({ lessonId: lessonId, verdict: verdict }); + renderProgress(job); + if (verdict !== "pass" && !keepGoing) return finish("stopped"); + return next(); + }).catch(function (error) { + results.push({ lessonId: lessonId, verdict: "start_fail" }); + appendLine("stderr", "启动失败:" + (error.message || error)); + return finish("stopped"); + }); + } + + state.abortSequence = function () { cancelled = true; return cancel(); }; + return next(); + } + + /* ---------------------------------------------------------------- wiring */ + document.addEventListener("click", function (event) { + var button = event.target && event.target.closest ? event.target.closest(selector) : null; + if (!button || button.disabled) return; + var plan = resolveRun(button); + if (!plan) return; + event.preventDefault(); + if (plan.sequence) runSequence(plan.sequence, plan); + else run(plan.lessonId, plan.params); + }); + var cancelButton = node("cancel"); + if (cancelButton) { + cancelButton.addEventListener("click", function () { + if (state.abortSequence) state.abortSequence(); + else cancel(); + }); + } + var recheck = node("recheck"); + if (recheck) recheck.addEventListener("click", function () { checkHealth(); }); + var term = node("terminal"); + if (term) { + term.addEventListener("scroll", function () { + state.autoScroll = term.scrollTop + term.clientHeight >= term.scrollHeight - 30; + }); + } + + checkHealth(); + + return { + run: run, + runSequence: runSequence, + cancel: cancel, + refreshHealth: checkHealth, + refreshPreflight: refreshPreflight, + syncButtons: syncButtons, + isRunning: busy, + isOnline: function () { return state.online; }, + token: token, + state: state, + append: appendLine, + }; + } + + window.TeachingRunner = { mount: mount }; +})(); diff --git a/web/teaching/console.html b/web/teaching/console.html index 665dcdb7..438b0b41 100644 --- a/web/teaching/console.html +++ b/web/teaching/console.html @@ -134,9 +134,10 @@ summary{cursor:pointer;font-size:13.5px}
- + + diff --git a/web/teaching/server.mjs b/web/teaching/server.mjs index 007b3c66..139e0186 100644 --- a/web/teaching/server.mjs +++ b/web/teaching/server.mjs @@ -300,6 +300,9 @@ server.listen(port, "127.0.0.1", () => { appOrigin, token, console: `${origin}/console.html?token=${token}`, + // The carrier toolkit page mounts the same runner (console-runner.js), so it + // is a first-class entry point, not a link out to the console. + carrier: `${origin}/carrier-toolkit.html?token=${token}`, })); }); diff --git a/web/tools/teaching-console/build-carrier-page.mjs b/web/tools/teaching-console/build-carrier-page.mjs index b7ea99b6..bab69b2e 100644 --- a/web/tools/teaching-console/build-carrier-page.mjs +++ b/web/tools/teaching-console/build-carrier-page.mjs @@ -16,6 +16,7 @@ import fs from "node:fs"; import path from "node:path"; import { fileURLToPath } from "node:url"; import { PROJECT_DIR, REPO_ROOT, groups, parts, stats } from "../../../tools/carrier/catalog.mjs"; +import { carrierLessons } from "./lessons.mjs"; const HERE = path.dirname(fileURLToPath(import.meta.url)); const DEFAULT_OUT = path.resolve(HERE, "../../teaching/carrier-toolkit.html"); @@ -47,7 +48,7 @@ function volumeText(volume) { return volume == null ? "—" : `${Math.round(volume).toLocaleString("en-US")} mm³`; } -function partCard(part) { +function partCard(part, lesson) { const steps = readSteps(part.document); const rows = steps.map((step) => { const kind = KIND_ZH[step.kind] ?? step.kind ?? ""; @@ -56,10 +57,14 @@ function partCard(part) { const features = part.featureTypes?.length ? ` · 特征 ${part.featureTypes.map(esc).join("、")}` : ""; + const runButton = lesson + ? `` + : ""; return `

${esc(part.id)} · ${esc(part.title)}

${part.steps} 步
${esc(part.document)} · 记录体积 ${esc(volumeText(part.volume))}${features}
    ${rows}
+
${runButton}
cd "${esc(REPO_ROOT)}" && DISPLAY=:1 node tools/carrier/create-part.mjs ${esc(part.id)}
`; } +/** + * Map catalog parts to their console lessons, so the page never re-types an id: + * the runner only needs `data-lesson-id` / `data-lesson-ids` on the buttons. + */ +function lessonIndex() { + const lessons = carrierLessons(); + const env = lessons.find((lesson) => lesson.job.dry) + ?? lessons.find((lesson) => lesson.job.kind === "carrier-part"); + const assembly = lessons.find((lesson) => lesson.job.kind === "carrier-assembly"); + const perPart = new Map(); + for (const lesson of lessons) { + if (lesson.job.kind === "carrier-part" && !lesson.job.dry) perPart.set(lesson.job.partId, lesson); + } + const lessonPart = Object.fromEntries([...perPart].map(([partId, lesson]) => [lesson.id, partId])); + const labels = Object.fromEntries(lessons.map((lesson) => [lesson.id, lesson.title])); + return { env, assembly, perPart, lessonPart, labels }; +} + +function runButton(label, attributes = "", kind = "ghost") { + // Callers add modifier classes as `class="run-group"` inside `attributes`. + // Merge them into the base class list: two class attributes on one tag make + // the browser keep only the first, silently dropping the modifier. + const extra = []; + const attrs = attributes + .replace(/\bclass="([^"]*)"/g, (_, names) => { + extra.push(...names.trim().split(/\s+/).filter(Boolean)); + return ""; + }) + .replace(/\s+/g, " ") + .trim(); + const classes = [kind, ...extra].filter(Boolean).join(" "); + return ``; +} + +/** + * The in-page runner panel: the same DOM contract console.html uses, so + * console-runner.js can drive it unchanged. Buttons start real headed builds + * through the teaching server's job queue. + */ +function runnerPanel(summary, index, allLessonIds) { + const runAll = allLessonIds + ? runButton(`运行全部 ${summary.parts} 件`, `id="run" data-lesson-ids="${esc(allLessonIds)}"`, "act") + : ""; + const envButton = index.env + ? runButton("环境自检(dry,不打开浏览器)", `data-lesson-id="${esc(index.env.id)}"`) + : ""; + return `
+

在页面上直接运行

检测服务…等待运行
+ +

按钮调用的是已有的工具 tools/carrier/create-part.mjs 与 create-assembly.mjs:界面点击由共享引擎执行,本机会开一个有头的 Chrome 窗口,日志与判定实时显示在下面。单件约 5–10 分钟;「运行本组 / 运行全部」按队列串行(同一时间只跑一件),失败的零件会标记在卡片上,队列继续(等同于 create-all --keep-going)。

+
检查中…
+
+ ${runAll} + ${envButton} + + + +
+
0 / 0
+
+
等待运行…
+

运行结束后按零件列出。

+

运行结束后给出报告 JSON。

+
`; +} + function render() { const summary = stats(); const all = parts(); + const index = lessonIndex(); + const carrierData = JSON.stringify({ labels: index.labels, lessonPart: index.lessonPart }) + .replace(/ index.perPart.has(part.id)); + const allLessonIds = partsWithLessons.map((part) => index.perPart.get(part.id).id).join(","); const sections = groups().map((group) => { const members = all.filter((part) => part.system === group.id); + const groupLessonIds = members + .map((part) => index.perPart.get(part.id)?.id) + .filter(Boolean); + const groupButton = groupLessonIds.length + ? runButton(`运行本组(${groupLessonIds.length} 件)`, + `class="run-group" data-lesson-ids="${esc(groupLessonIds.join(","))}"`) + : ""; return `
-

${esc(group.label)} ${members.length} 件

-
${members.map(partCard).join("")}
+

${esc(group.label)} ${members.length} 件

${groupButton}
+
${members.map((part) => partCard(part, index.perPart.get(part.id))).join("")}
`; }).join(""); @@ -116,6 +199,37 @@ table{border-collapse:collapse;width:100%;font-size:13.5px} th,td{border-bottom:1px solid var(--line);padding:6px 8px;text-align:left;vertical-align:top} th{color:var(--muted);font-weight:500} .note{border-left:3px solid var(--warn);padding:8px 12px;background:#1d1a12;border-radius:0 8px 8px 0;margin:10px 0} +.row{display:flex;gap:10px;align-items:center;flex-wrap:wrap} +.grouphead{display:flex;gap:10px;align-items:center} +.chips{display:flex;flex-wrap:wrap;gap:6px;margin:8px 0} +.chip{display:inline-block;border:1px solid var(--line);border-radius:999px;padding:1px 9px;font-size:12px;background:var(--panel2)} +.chip.ok{border-color:#3d6b48;color:var(--ok)} +.chip.bad{border-color:#6b3d3d;color:var(--bad)} +.chip.warn{border-color:#6b5a3d;color:var(--warn)} +.chip .fix{display:none;margin-left:6px;color:var(--muted)} +.chip.bad:hover .fix{display:inline} +button.act,button.ghost{font:inherit;font-size:13px;padding:5px 12px;border-radius:8px;border:1px solid var(--line);cursor:pointer} +button.act{background:#1f3b44;color:var(--text);border-color:#2f6b7a} +button.ghost{background:var(--panel2);color:var(--text)} +button:disabled{opacity:.45;cursor:not-allowed} +.runrow{display:flex;gap:10px;align-items:center;margin:0 0 8px} +.part-status{font-size:12.5px} +.part-status.ok{color:var(--ok)} +.part-status.bad{color:var(--bad)} +.verdict{font-size:13px;padding:2px 10px;border-radius:999px;border:1px solid var(--line);background:var(--panel2)} +.verdict.pass{color:var(--ok);border-color:#3d6b48} +.verdict.bad{color:var(--bad);border-color:#6b3d3d} +.verdict.muted{color:var(--muted)} +.progress{height:8px;background:#0b1117;border:1px solid var(--line);border-radius:999px;overflow:hidden;margin:8px 0} +.progress i{display:block;height:100%;width:0;background:var(--accent);transition:width .3s} +pre.term{background:#0b1117;border:1px solid var(--line);border-radius:8px;padding:10px;max-height:320px;overflow:auto;font-size:12px;white-space:pre-wrap;word-break:break-all} +pre.term .ok{color:var(--ok)} +pre.term .err{color:var(--bad)} +pre.term .sys{color:var(--warn)} +.st-passed{color:var(--ok)} +.st-failed{color:var(--bad)} +.st-blocked{color:var(--warn)} +.banner.offline{border-left:3px solid var(--bad);background:#24161a;padding:10px 12px;border-radius:0 8px 8px 0;margin:8px 0} @media (max-width:700px){.parts{grid-template-columns:1fr}main{padding:12px}} @media print{header.top,.links,pre.cmd{display:none!important}} @@ -141,10 +255,14 @@ th{color:var(--muted);font-weight:500}
零件在船上是什么样:每件都按舰体坐标建模(X 向舰首为 +,z=24 m 为飞行甲板面),所以单独打开是零件、装配后自动就位,插装位姿是单位矩阵。改一个零件的尺寸,装配结果跟着变——这正是教学里要讲的“零件与装配同源”。
+${runnerPanel(summary, index, allLessonIds)} + ${sections}
-

装配 1 艘

+

装配 1 艘

${index.assembly + ? runButton("运行装配", `class="run-assembly" data-lesson-id="${esc(index.assembly.id)}"`) + : ""}

CarrierAssembly · ${summary.parts} 件合成整舰

${summary.parts} 插入 / ${summary.parts - 1} 关节
新建装配文档「航空母舰」,逐个装载并插入 ${summary.parts} 个零件链接,接地舰体,其余 ${summary.parts - 1} 件各建一个固定关节,最后求解并列出 BOM。
@@ -189,6 +307,36 @@ ${sections}

本页由 web/tools/teaching-console/build-carrier-page.mjs 生成,请勿手改。

+ + + `; diff --git a/web/tools/teaching-console/check-carrier-page.mjs b/web/tools/teaching-console/check-carrier-page.mjs index c50b4903..68085b90 100644 --- a/web/tools/teaching-console/check-carrier-page.mjs +++ b/web/tools/teaching-console/check-carrier-page.mjs @@ -2,18 +2,23 @@ /** * Browser gate for the beginner page web/teaching/carrier-toolkit.html. * - * Opens the generated page over file:// (it must be self-contained and readable - * with no server) and asserts: 20 part cards, every system section present, - * copyable commands and links to the console / old case / hub, no template - * leakage, no pageerror/console/request failures, and zero horizontal overflow - * at 1440×900 and 390×844. + * Default (offline): opens the generated page over file:// — it must stay + * readable with no server — and asserts: 20 part cards, every system section, + * copyable commands and links, the runner UI degrading to disabled buttons with + * an offline banner, no unexpected pageerror/console/request failures, and zero + * horizontal overflow at 1440×900 and 390×844. + * + * --live: starts the teaching server on an ephemeral port, opens the page with + * its token and runs the environment lesson (dry, seconds) through the in-page + * runner, asserting the same verdict/results/evidence the console gate expects. * * Prerequisite: playwright resolvable from web/node_modules. * Exit: 0 pass / 1 page problem / 2 prerequisite missing. * - * Usage: node web/tools/teaching-console/check-carrier-page.mjs + * Usage: node web/tools/teaching-console/check-carrier-page.mjs [--live] */ import path from "node:path"; +import { spawn } from "node:child_process"; import { pathToFileURL } from "node:url"; import { createRequire } from "node:module"; import { fileURLToPath } from "node:url"; @@ -22,6 +27,8 @@ 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/carrier-toolkit.html"); +const SERVER = path.join(REPO, "web/teaching/server.mjs"); +const LIVE = process.argv.includes("--live"); const failures = []; const note = (message) => { failures.push(message); console.error(`FAIL ${message}`); }; @@ -36,64 +43,185 @@ try { const VIEWPORTS = [{ width: 1440, height: 900 }, { width: 390, height: 844 }]; -const browser = await chromium.launch({ headless: true, args: ["--no-sandbox", "--disable-dev-shm-usage"] }); -const page = await browser.newPage({ viewport: VIEWPORTS[0] }); -const pageErrors = []; -const consoleErrors = []; -const failedRequests = []; -page.on("pageerror", (error) => pageErrors.push(String(error.message ?? 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(pathToFileURL(PAGE).href, { waitUntil: "load" }); -if (!response) note("file:// 打开页面失败(无 response)"); - -const dom = await page.evaluate(() => { - const text = document.body.innerText; - const partIds = [...document.querySelectorAll("article.part[id]")].map((node) => node.id); - const hrefs = [...document.querySelectorAll("a[href]")].map((node) => node.getAttribute("href")); - const commands = [...document.querySelectorAll("code")].map((node) => node.textContent).join("\n"); - return { - partIds, - groups: document.querySelectorAll("section.group").length, - stepRows: document.querySelectorAll("ol.steps li").length, - hrefs, - hasConsole: hrefs.some((href) => /console\.html/.test(href)), - hasCase: hrefs.some((href) => /cases\/carrier\.html/.test(href)), - hasIndex: hrefs.some((href) => /(^|\/)index\.html$/.test(href)), - command: /create-part\.mjs P\d{2}/.test(commands) && /create-assembly\.mjs/.test(commands) - && /create-all\.mjs/.test(commands), - leakage: ["[object Object]", "undefined", "NaN", "${"].filter((token) => text.includes(token)), - }; -}); - -const expectedIds = Array.from({ length: 20 }, (_, index) => `P${String(index + 1).padStart(2, "0")}`); -const missing = expectedIds.filter((id) => !dom.partIds.includes(id)); -if (dom.partIds.length !== 20) note(`零件卡片 ${dom.partIds.length} 张,应为 20 张`); -if (missing.length) note(`缺少零件卡片:${missing.join(", ")}`); -// 12 system sections + assembly/tools/troubleshooting. -if (dom.groups < 15) note(`分组区仅 ${dom.groups} 个,应至少 15 个(12 系统 + 装配/工具/排错)`); -if (dom.stepRows < 200) note(`界面步骤条目仅 ${dom.stepRows} 条,应至少 200 条(记录 210 步)`); -if (!dom.hasConsole) note("没有跳转教学控制台的链接"); -if (!dom.hasCase) note("没有跳转旧版案例(cases/carrier.html)的链接"); -if (!dom.hasIndex) note("没有返回 index.html 的链接"); -if (!dom.command) note("缺少可复制的 create-part / create-all / create-assembly 命令"); -for (const token of dom.leakage) note(`模板泄漏标记:${token}`); -for (const error of pageErrors) note(`pageerror: ${error}`); -for (const error of consoleErrors) note(`console: ${error}`); -for (const error of failedRequests) note(`request: ${error}`); - -for (const viewport of VIEWPORTS) { - await page.setViewportSize(viewport); - await page.waitForTimeout(120); - const overflow = await page.evaluate(() => Math.max(0, document.documentElement.scrollWidth - window.innerWidth)); - if (overflow > 0) note(`${viewport.width}px: 横向溢出 ${overflow}px`); - console.log(`${viewport.width}x${viewport.height}: overflow=${overflow}`); +/** Failure paths we design for: the offline health probe, plus live guard/abort requests. */ +function ignoreExpected(list, { offline }) { + 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)); + }); +} + +const browser = await chromium.launch({ headless: true, args: ["--no-sandbox", "--disable-dev-shm-usage"] }); + +async function openPage(url) { + const page = await browser.newPage({ viewport: VIEWPORTS[0] }); + const pageErrors = []; + const consoleErrors = []; + const failedRequests = []; + page.on("pageerror", (error) => pageErrors.push(String(error.message ?? 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 }; +} + +async function checkOffline() { + const { page, response, pageErrors, consoleErrors, failedRequests } = await openPage(pathToFileURL(PAGE).href); + if (!response) note("file:// 打开页面失败(无 response)"); + + const dom = await page.evaluate(() => { + const text = document.body.innerText; + const partIds = [...document.querySelectorAll("article.part[id]")].map((node) => node.id); + const hrefs = [...document.querySelectorAll("a[href]")].map((node) => node.getAttribute("href")); + const commands = [...document.querySelectorAll("code")].map((node) => node.textContent).join("\n"); + const runParts = [...document.querySelectorAll("button.run-part")]; + return { + partIds, + groups: document.querySelectorAll("section.group").length, + stepRows: document.querySelectorAll("ol.steps li").length, + hrefs, + hasConsole: hrefs.some((href) => /console\.html/.test(href)), + hasCase: hrefs.some((href) => /cases\/carrier\.html/.test(href)), + hasIndex: hrefs.some((href) => /(^|\/)index\.html$/.test(href)), + command: /create-part\.mjs P\d{2}/.test(commands) && /create-assembly\.mjs/.test(commands) + && /create-all\.mjs/.test(commands), + leakage: ["[object Object]", "undefined", "NaN", "${"].filter((token) => text.includes(token)), + runParts: runParts.length, + runPartsDisabled: runParts.every((button) => button.disabled), + runAllDisabled: document.getElementById("run")?.disabled ?? null, + banner: !document.getElementById("offline-banner").hidden, + runnerState: document.body.dataset.runnerState, + }; + }); + + const expectedIds = Array.from({ length: 20 }, (_, index) => `P${String(index + 1).padStart(2, "0")}`); + const missing = expectedIds.filter((id) => !dom.partIds.includes(id)); + if (dom.partIds.length !== 20) note(`零件卡片 ${dom.partIds.length} 张,应为 20 张`); + if (missing.length) note(`缺少零件卡片:${missing.join(", ")}`); + // 12 system sections + assembly/tools/troubleshooting. + if (dom.groups < 15) note(`分组区仅 ${dom.groups} 个,应至少 15 个(12 系统 + 装配/工具/排错)`); + if (dom.stepRows < 200) note(`界面步骤条目仅 ${dom.stepRows} 条,应至少 200 条(记录 210 步)`); + if (!dom.hasConsole) note("没有跳转教学控制台的链接"); + if (!dom.hasCase) note("没有跳转旧版案例(cases/carrier.html)的链接"); + if (!dom.hasIndex) note("没有返回 index.html 的链接"); + if (!dom.command) note("缺少可复制的 create-part / create-all / create-assembly 命令"); + for (const token of dom.leakage) note(`模板泄漏标记:${token}`); + // The runner must degrade, not fail, without a server. + if (dom.runParts !== 20) note(`运行本件按钮 ${dom.runParts} 个,应为 20 个`); + if (!dom.runPartsDisabled) note("file:// 下仍有可点的运行本件按钮"); + if (dom.runAllDisabled !== true) note("file:// 下「运行全部」按钮未禁用"); + if (!dom.banner) note("file:// 下未显示离线提示"); + if (dom.runnerState !== "offline") note(`file:// 下 runnerState=${dom.runnerState},应为 offline`); + for (const error of pageErrors) note(`pageerror: ${error}`); + for (const error of ignoreExpected(consoleErrors, { offline: true })) note(`console: ${error}`); + for (const error of ignoreExpected(failedRequests, { offline: true })) note(`request: ${error}`); + + for (const viewport of VIEWPORTS) { + await page.setViewportSize(viewport); + await page.waitForTimeout(120); + const overflow = await page.evaluate(() => Math.max(0, document.documentElement.scrollWidth - window.innerWidth)); + if (overflow > 0) note(`${viewport.width}px: 横向溢出 ${overflow}px`); + console.log(`${viewport.width}x${viewport.height}: overflow=${overflow}`); + } + await page.close(); + console.log(`offline: 20 卡片 / ${dom.groups} 分区 / ${dom.stepRows} 步 / 运行按钮禁用 / runnerState=${dom.runnerState}`); +} + +function startServer() { + const token = "carrier-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 }; +} + +async function checkLive() { + const server = startServer(); + try { + const { origin, token } = await server.ready; + console.log(`live: ${origin}`); + const { page, pageErrors, consoleErrors, failedRequests } = await openPage(`${origin}/carrier-toolkit.html?token=${token}`); + await page.waitForFunction(() => document.body.dataset.runnerState === "ready", null, { timeout: 120000 }); + await page.waitForFunction(() => document.querySelectorAll("#preflight-chips .chip.bad").length === 0 + && document.querySelectorAll("#preflight-chips .chip").length >= 5, null, { timeout: 120000 }); + const ready = await page.evaluate(() => ({ + runParts: document.querySelectorAll("button.run-part").length, + runPartsEnabled: [...document.querySelectorAll("button.run-part")].every((button) => !button.disabled), + groups: document.querySelectorAll("button.run-group").length, + assembly: Boolean(document.querySelector("button.run-assembly")), + status: document.getElementById("status").textContent, + })); + if (ready.runParts !== 20) note(`live: 运行本件按钮 ${ready.runParts} 个`); + if (!ready.runPartsEnabled) note("live: 前置已满足但运行本件按钮仍禁用"); + if (ready.groups < 12) note(`live: 分组运行按钮 ${ready.groups} 个,应至少 12 个`); + if (!ready.assembly) note("live: 缺少装配运行按钮"); + + // The environment lesson is the dry run: seconds, not minutes. Never click a + // part card here — those rebuild a full model headed. + await page.click('button[data-lesson-id="lesson-carrier-environment"]'); + await page.waitForFunction(() => document.getElementById("terminal").textContent.includes("前置全部满足"), null, { timeout: 180000 }); + await page.waitForFunction(() => /通过|失败|运行失败|超时|已取消/.test(document.getElementById("verdict").textContent), null, { timeout: 240000 }); + const outcome = await page.evaluate(() => ({ + verdict: document.getElementById("verdict").textContent, + rows: document.querySelectorAll("#results tbody tr").length, + evidence: document.querySelectorAll('#evidence a[href*="/api/console/artifacts/"]').length, + runnerState: document.body.dataset.runnerState, + buttonsReenabled: [...document.querySelectorAll("button[data-run]")].every((button) => !button.disabled), + })); + if (!/通过/.test(outcome.verdict)) note(`live: 判定为「${outcome.verdict}」`); + if (outcome.rows < 1) note("live: 结果表没有行"); + if (outcome.evidence < 1) note("live: 没有报告 JSON 证据链接"); + if (outcome.runnerState !== "ready") note(`live: 结束后 runnerState=${outcome.runnerState}`); + if (!outcome.buttonsReenabled) note("live: 结束后运行按钮未恢复"); + console.log(`live: verdict=${outcome.verdict} rows=${outcome.rows} evidence=${outcome.evidence}`); + + for (const viewport of VIEWPORTS) { + await page.setViewportSize(viewport); + await page.waitForTimeout(200); + const overflow = await page.evaluate(() => Math.max(0, document.documentElement.scrollWidth - window.innerWidth)); + if (overflow > 0) note(`live ${viewport.width}px: 横向溢出 ${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)); + } +} + +try { + if (LIVE) await checkLive(); + else await checkOffline(); +} finally { + await browser.close(); } -await browser.close(); if (failures.length) { console.error(`\ncarrier-toolkit.html 门禁失败:${failures.length} 项`); process.exit(1); } -console.log(`\ncarrier-toolkit.html 门禁通过:20 张零件卡片 / ${dom.groups} 个分组区 / ${dom.stepRows} 条步骤 / 双视口 0 溢出`); +console.log(`\ncarrier-toolkit.html 门禁通过${LIVE ? "(live)" : ""}`); diff --git a/web/tools/teaching-console/lessons.mjs b/web/tools/teaching-console/lessons.mjs index 6a1e9c17..e15d38d9 100644 --- a/web/tools/teaching-console/lessons.mjs +++ b/web/tools/teaching-console/lessons.mjs @@ -275,7 +275,7 @@ function volumeText(volume) { * where it sits on the vessel), and the last lesson assembles all 20 into one * document with 19 fixed joints. */ -function carrierLessons() { +export function carrierLessons() { const parts = carrierParts(); const byGroup = new Map(carrierGroups().map((group) => [group.id, group.label])); const intro = { diff --git a/web/tools/teaching-console/template.html b/web/tools/teaching-console/template.html index 66b2ba52..6a842ff6 100644 --- a/web/tools/teaching-console/template.html +++ b/web/tools/teaching-console/template.html @@ -137,6 +137,7 @@ summary{cursor:pointer;font-size:13.5px} +