Files
FreeCADWasmDev/web/teaching/console-runner.js
wangdequan 3a3077c089 teaching: run carrier builds from the toolkit page
Extract the console runner into web/teaching/console-runner.js (classic
script, file:// safe) and mount it on carrier-toolkit.html: per-part 运行本件,
per-group 运行本组, 运行全部 and 运行装配, all fed by lessons.mjs ids at build
time. Fix runButton() emitting a duplicate class attribute that dropped
run-group/run-assembly. Server banner now prints the carrier page URL; new
check:carrier-live gate drives the dry lesson end-to-end.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-25 21:45:08 +08:00

472 lines
19 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 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 { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" }[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 '<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("");
target.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 target = node("evidence");
if (!target) return;
var links = [];
if (job && 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 && job.kind === "probe") {
links.push('<a href="/api/console/artifacts/' + esc(job.jobId) + '/layout.json" target="_blank" rel="noopener">布局报告 JSON</a>');
}
if (job && (job.kind === "reducer-part" || job.kind === "reducer-assembly"
|| job.kind === "carrier-part" || job.kind === "carrier-assembly")) {
links.push('<a href="/api/console/artifacts/' + esc(job.jobId) + '/report.json" target="_blank" rel="noopener">零件/装配报告 JSON</a>');
}
if (job && job.origin) {
links.push('<span class="small muted">本次运行 origin:<code>' + esc(job.origin) + "</code></span>");
}
target.innerHTML = links.length ? links.map(function (link) { return "<div>" + link + "</div>"; }).join("")
: '<p class="muted small">运行结束后可打开完整报告与截图。</p>';
}
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 = '<span class="chip warn">离线:无法读取前置检查</span>';
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 '<span class="chip ' + (check.ok ? "ok" : "bad") + '">' + (check.ok ? "✓ " : "✗ ") + esc(check.id)
+ '<span class="fix">' + esc(check.detail) + (check.ok ? "" : " · 修复:" + esc(check.fix)) + "</span></span>";
}).join("");
}
syncButtons();
}).catch(function () {
var target = node("preflight");
if (target) target.innerHTML = '<span class="chip bad">前置检查失败</span>';
});
}
/* ---------------------------------------------------------------- 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 = '<p class="muted small">运行中…</p>';
var evidence = node("evidence");
if (evidence) evidence.innerHTML = '<p class="muted small">运行结束后生成。</p>';
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 };
})();