#!/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"); // Reducer lesson: runs tools/reducer/create-part.mjs P06 headed and maps // the part report into the same verdict / results / evidence UI. await page.fill("#search", "P06"); await page.click('#course-list button[data-id="lesson-reducer-p06"]'); await page.click("#run"); await page.waitForFunction(() => document.getElementById("terminal").textContent.includes("零件 P06"), null, { timeout: 120000 }); await page.waitForFunction(() => /通过|失败|运行失败|超时/.test(document.getElementById("verdict").textContent), null, { timeout: 360000 }); const reducer = await page.evaluate(() => ({ verdict: document.getElementById("verdict").textContent, rows: document.querySelectorAll("#results tbody tr").length, evidence: document.querySelectorAll("#evidence a").length, })); if (!/通过/.test(reducer.verdict)) note(`live reducer: 判定为「${reducer.verdict}」`); if (reducer.rows < 1) note("live reducer: 结果表没有零件行"); if (reducer.evidence < 1) note("live reducer: 没有证据链接"); console.log(`live reducer: verdict=${reducer.verdict} rows=${reducer.rows} evidence=${reducer.evidence}`); // Carrier lesson: the environment lesson runs create-part --dry, which // exercises the whole carrier-part job kind (whitelist, argv, report // folding) in seconds instead of rebuilding a 13-step aircraft. await page.fill("#search", "航母"); await page.click('#course-list button[data-id="lesson-carrier-environment"]'); await page.click("#run"); await page.waitForFunction(() => document.getElementById("terminal").textContent.includes("前置全部满足"), null, { timeout: 120000 }); await page.waitForFunction(() => /通过|失败|运行失败|超时/.test(document.getElementById("verdict").textContent), null, { timeout: 180000 }); const carrier = await page.evaluate(() => ({ verdict: document.getElementById("verdict").textContent, rows: document.querySelectorAll("#results tbody tr").length, evidence: document.querySelectorAll("#evidence a").length, })); if (!/通过/.test(carrier.verdict)) note(`live carrier: 判定为「${carrier.verdict}」`); if (carrier.rows < 1) note("live carrier: 结果表没有零件行"); if (carrier.evidence < 1) note("live carrier: 没有证据链接"); console.log(`live carrier: verdict=${carrier.verdict} rows=${carrier.rows} evidence=${carrier.evidence}`); // 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); });