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>
This commit is contained in:
2026-11-25 21:45:08 +08:00
parent a6576b72ac
commit 3a3077c089
10 changed files with 1002 additions and 457 deletions

View File

@@ -137,6 +137,7 @@ summary{cursor:pointer;font-size:13.5px}
<script>window.__LESSONS__ = {{LESSONS_JSON}};</script>
<script>window.__CATALOG__ = {{CATALOG_JSON}};</script>
<script>window.__COMMANDS__ = {{COMMANDS_JSON}};</script>
<script src="console-runner.js"></script>
<script>
(function(){
"use strict";
@@ -147,19 +148,10 @@ summary{cursor:pointer;font-size:13.5px}
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: {}
};
// Console-only glue: the course list, lesson panels and practice picker.
// Running, streaming, verdicts and evidence live in console-runner.js, which
// the carrier toolkit page mounts too.
var state = { lesson: null, practice: {}, completed: {} };
try { state.completed = JSON.parse(localStorage.getItem("teaching-console-done-v1") || "{}"); } catch(e) { state.completed = {}; }
function $(id){ return document.getElementById(id); }
@@ -197,7 +189,7 @@ summary{cursor:pointer;font-size:13.5px}
$("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();
runner.syncButtons();
renderSidebar();
}
@@ -225,177 +217,29 @@ summary{cursor:pointer;font-size:13.5px}
$("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.kind === "reducer-part" || job.kind === "reducer-assembly") links.push('<a href="/api/console/artifacts/' + esc(job.jobId) + '/report.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 */
var runner = TeachingRunner.mount({
buttonSelector: "#run",
extraGate: function(){ return Boolean(state.lesson); },
resolveRun: function(){
if (!state.lesson) return null;
return { lessonId: state.lesson.id, params: params() };
},
onDone: function(lessonId, job){
if (job && job.verdict === "pass") {
state.completed[lessonId] = true;
try { localStorage.setItem("teaching-console-done-v1", JSON.stringify(state.completed)); } catch(e){}
renderSidebar();
}
}
});
$("search").addEventListener("input", renderSidebar);
document.addEventListener("keydown", function(event){
if (event.key === "/" && document.activeElement !== $("search")) { event.preventDefault(); $("search").focus(); }
@@ -413,25 +257,16 @@ summary{cursor:pointer;font-size:13.5px}
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; }
if (selected.length >= 8) { input.checked = false; runner.append("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>