1367 lines
53 KiB
JavaScript
1367 lines
53 KiB
JavaScript
/* Marqdo View — the single reader interaction script.
|
||
*
|
||
* Boundaries: this file only manipulates DOM state, layout and accessibility.
|
||
* It never parses @exec/@knowledge, never invents Analysis/Trace facts and
|
||
* never executes anything. All content is rendered by the one server-side
|
||
* ReaderRenderer (RFC-VIEW-0001 §7.1, §14.3). */
|
||
(function () {
|
||
"use strict";
|
||
|
||
var reader = document.querySelector(".mq-reader");
|
||
if (!reader) return;
|
||
|
||
function $(selector, root) {
|
||
return (root || document).querySelector(selector);
|
||
}
|
||
function $$(selector, root) {
|
||
return Array.prototype.slice.call((root || document).querySelectorAll(selector));
|
||
}
|
||
|
||
var toastTimer = null;
|
||
function toast(message) {
|
||
var el = $("#mq-toast");
|
||
if (!el) return;
|
||
el.textContent = message;
|
||
el.hidden = false;
|
||
clearTimeout(toastTimer);
|
||
toastTimer = setTimeout(function () {
|
||
el.hidden = true;
|
||
}, 3800);
|
||
}
|
||
|
||
function openDialog(id) {
|
||
var dialog = document.getElementById(id);
|
||
if (!dialog) return null;
|
||
if (typeof dialog.showModal === "function") {
|
||
if (!dialog.open) dialog.showModal();
|
||
} else {
|
||
dialog.setAttribute("open", "");
|
||
}
|
||
var focusTarget = dialog.querySelector("[autofocus], input, button");
|
||
if (focusTarget) focusTarget.focus();
|
||
return dialog;
|
||
}
|
||
|
||
function closeDialog(dialog) {
|
||
if (!dialog) return;
|
||
if (typeof dialog.close === "function" && dialog.open) dialog.close();
|
||
else dialog.removeAttribute("open");
|
||
}
|
||
|
||
function closeAllDialogs() {
|
||
$$("dialog[open]").forEach(closeDialog);
|
||
}
|
||
|
||
function setMode(mode) {
|
||
reader.dataset.mode = mode === "source" ? "source" : "document";
|
||
$$("[data-action='mode-document'], [data-action='mode-source']").forEach(function (button) {
|
||
var active = button.dataset.action === "mode-" + reader.dataset.mode;
|
||
button.setAttribute("aria-current", active ? "page" : "false");
|
||
});
|
||
if (reader.dataset.mode === "source") {
|
||
var source = $(".mq-source");
|
||
if (source) source.focus({ preventScroll: true });
|
||
}
|
||
try {
|
||
var url = new URL(window.location.href);
|
||
if (reader.dataset.mode === "document") url.searchParams.delete("mode");
|
||
else url.searchParams.set("mode", "source");
|
||
window.history.replaceState(null, "", url.toString());
|
||
} catch (error) {
|
||
/* history is optional */
|
||
}
|
||
}
|
||
|
||
function gotoAnchor(target) {
|
||
if (!target) return;
|
||
var heading = document.getElementById(target);
|
||
if (heading) {
|
||
closeAllDialogs();
|
||
heading.scrollIntoView({ block: "start" });
|
||
heading.classList.add("is-focus");
|
||
setTimeout(function () {
|
||
heading.classList.remove("is-focus");
|
||
}, 1600);
|
||
return true;
|
||
}
|
||
return false;
|
||
}
|
||
|
||
function gotoSourceLine(line) {
|
||
var row = document.querySelector(".mq-source-lines li[data-line='" + line + "']");
|
||
if (!row) return false;
|
||
closeAllDialogs();
|
||
setMode("source");
|
||
row.scrollIntoView({ block: "center" });
|
||
row.classList.add("is-focus");
|
||
setTimeout(function () {
|
||
row.classList.remove("is-focus");
|
||
}, 1600);
|
||
return true;
|
||
}
|
||
|
||
function showFunctions() {
|
||
var items = $$(".mq-functions li");
|
||
var body = $("#mq-functions-body");
|
||
if (!body) return;
|
||
body.textContent = "";
|
||
if (!items.length) {
|
||
var empty = document.createElement("p");
|
||
empty.textContent = "本文没有 Analysis 可见的 @exec 函数。";
|
||
body.appendChild(empty);
|
||
} else {
|
||
var list = document.createElement("ul");
|
||
list.className = "mq-annotation-list";
|
||
items.forEach(function (item) {
|
||
var clone = item.cloneNode(true);
|
||
list.appendChild(clone);
|
||
});
|
||
body.appendChild(list);
|
||
}
|
||
openDialog("mq-dialog-functions");
|
||
}
|
||
|
||
function showSearch() {
|
||
openDialog("mq-dialog-search");
|
||
var input = $("#mq-search-input");
|
||
if (input) {
|
||
input.value = "";
|
||
input.focus();
|
||
renderSearch("");
|
||
}
|
||
}
|
||
|
||
function collectSearchNodes() {
|
||
var nodes = [];
|
||
var walker = document.createTreeWalker(
|
||
$(".mq-document") || reader,
|
||
NodeFilter.SHOW_TEXT,
|
||
null
|
||
);
|
||
while (walker.nextNode()) {
|
||
var text = walker.currentNode;
|
||
if (!text.nodeValue || !text.nodeValue.trim()) continue;
|
||
if (text.parentElement && text.parentElement.closest("script, style")) continue;
|
||
nodes.push(text);
|
||
}
|
||
return nodes;
|
||
}
|
||
|
||
var searchNodes = null;
|
||
function renderSearch(query) {
|
||
var results = $("#mq-search-results");
|
||
if (!results) return;
|
||
results.textContent = "";
|
||
var needle = query.trim().toLowerCase();
|
||
if (needle.length < 2) {
|
||
var hint = document.createElement("li");
|
||
hint.textContent = "输入至少两个字符以搜索当前文档正文。";
|
||
hint.className = "mq-search-hint";
|
||
results.appendChild(hint);
|
||
return;
|
||
}
|
||
if (!searchNodes) searchNodes = collectSearchNodes();
|
||
var shown = 0;
|
||
searchNodes.forEach(function (node) {
|
||
if (shown >= 40) return;
|
||
var value = node.nodeValue;
|
||
var index = value.toLowerCase().indexOf(needle);
|
||
if (index < 0) return;
|
||
var start = Math.max(0, index - 28);
|
||
var end = Math.min(value.length, index + needle.length + 34);
|
||
var li = document.createElement("li");
|
||
var button = document.createElement("button");
|
||
button.type = "button";
|
||
var before = document.createTextNode(
|
||
(start > 0 ? "…" : "") + value.slice(start, index)
|
||
);
|
||
var mark = document.createElement("mark");
|
||
mark.textContent = value.slice(index, index + needle.length);
|
||
var after = document.createTextNode(
|
||
value.slice(index + needle.length, end) + (end < value.length ? "…" : "")
|
||
);
|
||
button.appendChild(before);
|
||
button.appendChild(mark);
|
||
button.appendChild(after);
|
||
button.addEventListener("click", function () {
|
||
closeAllDialogs();
|
||
var el = node.parentElement;
|
||
if (el) {
|
||
el.scrollIntoView({ block: "center" });
|
||
el.classList.add("is-focus");
|
||
setTimeout(function () {
|
||
el.classList.remove("is-focus");
|
||
}, 1600);
|
||
}
|
||
});
|
||
li.appendChild(button);
|
||
results.appendChild(li);
|
||
shown += 1;
|
||
});
|
||
if (!shown) {
|
||
var none = document.createElement("li");
|
||
none.textContent = "没有匹配的正文文本。";
|
||
none.className = "mq-search-hint";
|
||
results.appendChild(none);
|
||
}
|
||
}
|
||
|
||
function toggleAnnotationVisibility() {
|
||
var off = reader.dataset.annotations === "off";
|
||
reader.dataset.annotations = off ? "on" : "off";
|
||
toast(off ? "已显示语义标注" : "已隐藏语义标注");
|
||
closeAllDialogs();
|
||
}
|
||
|
||
function applyTheme(theme, announce) {
|
||
var next = theme === "dark" ? "dark" : "light";
|
||
reader.dataset.theme = next;
|
||
try {
|
||
window.localStorage.setItem("marqdo.view.theme", next);
|
||
} catch (error) {
|
||
/* storage is optional */
|
||
}
|
||
if (announce) toast(next === "dark" ? "已切换到深色主题" : "已切换到暖纸主题");
|
||
}
|
||
|
||
function cycleTheme() {
|
||
applyTheme(reader.dataset.theme === "dark" ? "light" : "dark", true);
|
||
closeAllDialogs();
|
||
}
|
||
|
||
function cycleTextSize() {
|
||
var order = ["normal", "large", "small"];
|
||
var current = reader.dataset.size || "normal";
|
||
var next = order[(order.indexOf(current) + 1) % order.length];
|
||
reader.dataset.size = next;
|
||
toast("正文字号:" + (next === "large" ? "大" : next === "small" ? "小" : "标准"));
|
||
}
|
||
|
||
function showUnsupported(what, why) {
|
||
var body = $("#mq-unsupported-body");
|
||
if (body) {
|
||
body.textContent = "";
|
||
var title = document.createElement("p");
|
||
title.textContent = what + ":当前版本不支持。";
|
||
var reason = document.createElement("p");
|
||
reason.className = "mq-colophon";
|
||
reason.textContent = why;
|
||
body.appendChild(title);
|
||
body.appendChild(reason);
|
||
}
|
||
openDialog("mq-dialog-unsupported");
|
||
}
|
||
|
||
function handleAction(action, trigger) {
|
||
switch (action) {
|
||
case "mode-document":
|
||
setMode("document");
|
||
break;
|
||
case "mode-source":
|
||
setMode("source");
|
||
break;
|
||
case "search":
|
||
showSearch();
|
||
break;
|
||
case "functions":
|
||
showFunctions();
|
||
break;
|
||
case "reload":
|
||
window.location.reload();
|
||
break;
|
||
case "settings":
|
||
openDialog("mq-dialog-settings");
|
||
break;
|
||
case "more":
|
||
openDialog("mq-dialog-more");
|
||
break;
|
||
case "close-dialog":
|
||
closeAllDialogs();
|
||
break;
|
||
case "print":
|
||
closeAllDialogs();
|
||
window.print();
|
||
break;
|
||
case "size":
|
||
cycleTextSize();
|
||
break;
|
||
case "annotations":
|
||
toggleAnnotationVisibility();
|
||
break;
|
||
case "unsupported":
|
||
showUnsupported(
|
||
"变量快照 / 内存检查 / 调试器 / 证明状态",
|
||
"Observation v1 支持显式请求 --observe-variable / --observe-parameter,但 View 默认不请求任何变量或参数值;" +
|
||
"它不提供内存快照、断点或单步通道;知识证明属于独立 Prove 工具。View 绝不猜测这些运行事实。"
|
||
);
|
||
break;
|
||
case "theme":
|
||
cycleTheme();
|
||
break;
|
||
case "about":
|
||
openDialog("mq-dialog-about");
|
||
break;
|
||
case "run":
|
||
openRunForMain();
|
||
break;
|
||
case "run-confirm":
|
||
submitRun();
|
||
break;
|
||
case "cancel-run":
|
||
cancelRun();
|
||
break;
|
||
case "export-result":
|
||
openExportPreview();
|
||
break;
|
||
case "download-result":
|
||
downloadSnapshot();
|
||
break;
|
||
case "call-function":
|
||
if (trigger) openFunctionForm(trigger);
|
||
break;
|
||
case "prepare-function":
|
||
prepareFunction(trigger.closest(".mq-function-interaction"));
|
||
break;
|
||
case "show-function-result":
|
||
showFunctionResult(trigger.closest(".mq-function-interaction"));
|
||
break;
|
||
case "clear-run":
|
||
case "clear":
|
||
clearRun();
|
||
break;
|
||
default:
|
||
break;
|
||
}
|
||
}
|
||
|
||
var activeRun = null;
|
||
var pendingRun = null;
|
||
var runBusy = false;
|
||
var functionRuns = new Map();
|
||
|
||
function randomId() {
|
||
var bytes = new Uint8Array(16);
|
||
if (window.crypto && window.crypto.getRandomValues) {
|
||
window.crypto.getRandomValues(bytes);
|
||
} else {
|
||
for (var i = 0; i < bytes.length; i += 1) bytes[i] = Math.floor(Math.random() * 256);
|
||
}
|
||
var out = "";
|
||
for (var j = 0; j < bytes.length; j += 1) {
|
||
out += (bytes[j] < 16 ? "0" : "") + bytes[j].toString(16);
|
||
}
|
||
return "req-" + out;
|
||
}
|
||
|
||
function csrfToken() {
|
||
var meta = document.querySelector('meta[name="mq-csrf-token"]');
|
||
return meta ? meta.getAttribute("content") : "";
|
||
}
|
||
|
||
function stateLabel(state) {
|
||
switch (state) {
|
||
case "accepted": return "已接受";
|
||
case "running": return "运行中";
|
||
case "cancel_requested": return "正在取消";
|
||
case "succeeded": return "成功";
|
||
case "failed": return "失败";
|
||
case "cancelled": return "已取消";
|
||
case "timed_out": return "超时";
|
||
case "unavailable": return "不可用";
|
||
case "incomplete": return "事件流不完整";
|
||
default: return String(state || "未知");
|
||
}
|
||
}
|
||
|
||
function isTerminalState(state) {
|
||
return ["succeeded", "failed", "cancelled", "timed_out", "unavailable", "incomplete"].indexOf(state) >= 0;
|
||
}
|
||
|
||
function runPanel() {
|
||
return $("#mq-run-panel");
|
||
}
|
||
|
||
function setRunStatus(text) {
|
||
var status = $("#mq-run-status");
|
||
if (status) status.textContent = text;
|
||
}
|
||
|
||
function showRunPanel() {
|
||
var panel = runPanel();
|
||
if (panel) panel.hidden = false;
|
||
}
|
||
|
||
function setRunBusy(busy) {
|
||
runBusy = busy;
|
||
var button = document.querySelector('.mq-dock-btn[data-action="run"]');
|
||
if (button) {
|
||
if (busy) {
|
||
button.setAttribute("aria-busy", "true");
|
||
button.dataset.busy = "true";
|
||
button.disabled = true;
|
||
reader.dataset.runState = "running";
|
||
} else {
|
||
button.removeAttribute("aria-busy");
|
||
delete button.dataset.busy;
|
||
button.disabled = false;
|
||
}
|
||
}
|
||
$$("[data-action=call-function], [data-action=prepare-function], [data-action=show-function-result]")
|
||
.forEach(function (call) { call.disabled = busy; });
|
||
var cancel = $("#mq-run-actions");
|
||
if (cancel) cancel.hidden = !busy;
|
||
}
|
||
|
||
function appendLine(container, tag, className, text) {
|
||
var node = document.createElement(tag);
|
||
if (className) node.className = className;
|
||
node.textContent = text;
|
||
container.appendChild(node);
|
||
return node;
|
||
}
|
||
|
||
function clearRunOutput() {
|
||
["#mq-run-summary", "#mq-run-stdout", "#mq-run-stderr", "#mq-run-events", "#mq-run-audit-items"].forEach(function (selector) {
|
||
var node = $(selector);
|
||
if (node) node.textContent = "";
|
||
});
|
||
var audit = $("#mq-run-audit");
|
||
if (audit) { audit.hidden = true; audit.open = false; }
|
||
var stdout = $("#mq-run-stdout");
|
||
if (stdout) stdout.hidden = true;
|
||
var stderr = $("#mq-run-stderr");
|
||
if (stderr) stderr.hidden = true;
|
||
var exportButton = $("#mq-export-result");
|
||
if (exportButton) exportButton.hidden = true;
|
||
var traceTitle = $("#mq-run-observation-title");
|
||
if (traceTitle) traceTitle.textContent = "实时结构观察事件";
|
||
var traceWrap = $("#mq-run-observation-wrap");
|
||
if (traceWrap) traceWrap.hidden = true;
|
||
$$(".mq-run-chip[data-view-chip]").forEach(function (chip) {
|
||
chip.remove();
|
||
});
|
||
}
|
||
|
||
function closeActiveObserver() {
|
||
if (activeRun && activeRun.source) {
|
||
try {
|
||
activeRun.source.close();
|
||
} catch (error) {
|
||
/* optional */
|
||
}
|
||
activeRun.source = null;
|
||
}
|
||
}
|
||
|
||
function selectedMode() {
|
||
var checked = document.querySelector('input[name="mq-mode"]:checked');
|
||
return checked ? checked.value : "pure";
|
||
}
|
||
|
||
function grantList(id) {
|
||
var field = document.getElementById(id);
|
||
if (!field) return [];
|
||
return field.value
|
||
.split("\n")
|
||
.map(function (line) { return line.trim(); })
|
||
.filter(function (line) { return line.length > 0; });
|
||
}
|
||
|
||
function functionPanel(functionId) {
|
||
return $$(".mq-function-interaction").find(function (panel) {
|
||
return panel.dataset.functionFor === functionId;
|
||
});
|
||
}
|
||
|
||
function collectParameters(panel) {
|
||
var parameters = [];
|
||
$$("[data-param-name]", panel).forEach(function (input) {
|
||
var type = input.dataset.paramType;
|
||
var name = input.dataset.paramName;
|
||
var expression = type === "text" ? input.value : input.value.trim();
|
||
var supplied = expression !== "";
|
||
if (type === "text") {
|
||
supplied = supplied || $("[data-text-present]", input.parentElement.parentElement).checked;
|
||
if (supplied) expression = JSON.stringify(expression);
|
||
}
|
||
if (!supplied) {
|
||
if (input.dataset.required === "true") throw new Error("缺少必填参数:" + name);
|
||
return;
|
||
}
|
||
if (type === "int" && !/^-?\d+$/.test(expression)) throw new Error(name + " 需要十进制整数");
|
||
if (type === "float") {
|
||
if (/^-?\d+$/.test(expression)) expression += ".0";
|
||
if (!/^-?\d+\.\d+(?:[eE][+-]?\d+)?$/.test(expression) || !Number.isFinite(Number(expression))) {
|
||
throw new Error(name + " 需要有限浮点数,例如 3.0 或 1.0e3");
|
||
}
|
||
}
|
||
if (Array.from(expression).length > 4096) throw new Error(name + " 超过参数长度上限");
|
||
parameters.push({ name: name, expression: expression });
|
||
});
|
||
return parameters;
|
||
}
|
||
|
||
function updateRunPreview() {
|
||
var preview = $("#mq-run-command");
|
||
if (!preview || !pendingRun) return;
|
||
var mode = selectedMode();
|
||
var parts = pendingRun.kind === "entry"
|
||
? ["marqdo", "run", reader.dataset.document]
|
||
: ["marqdo", "call", reader.dataset.document, pendingRun.cliName];
|
||
parts.push("--mode", mode, "--output", "jsonl");
|
||
pendingRun.parameters.forEach(function (param) { parts.push("--arg", param.name + "=" + param.expression); });
|
||
if (mode === "project") {
|
||
grantList("mq-grant-read").forEach(function (glob) { parts.push("--allow-read", glob); });
|
||
grantList("mq-grant-write").forEach(function (glob) { parts.push("--allow-write", glob); });
|
||
}
|
||
preview.textContent = parts.map(function (part) { return /[\s"\\]/.test(part) ? JSON.stringify(part) : part; }).join(" ");
|
||
$("#mq-run-target-mode").textContent = mode;
|
||
var previous = functionRuns.get(pendingRun.functionId);
|
||
var grants = mode === "project" ? { read: grantList("mq-grant-read"), write: grantList("mq-grant-write") } : { read: [], write: [] };
|
||
if (pendingRun.panel) updateApplicability(pendingRun.panel);
|
||
if (previous && (previous.mode !== mode || JSON.stringify(previous.grants) !== JSON.stringify(grants))) {
|
||
setApplicability(pendingRun.panel, "运行模式或授权已修改,上次结果属于历史。");
|
||
}
|
||
}
|
||
|
||
function renderRunParams(params, panel) {
|
||
var container = $(".mq-run-params", panel);
|
||
if (!params.length) {
|
||
appendLine(container, "p", "mq-colophon", "该函数无需参数。");
|
||
return;
|
||
}
|
||
params.forEach(function (param) {
|
||
var type = (param.type || "").toLowerCase();
|
||
var label = document.createElement("label");
|
||
label.className = "mq-run-param";
|
||
var title = document.createElement("span");
|
||
title.textContent = param.name + ": " + (param.type || "未声明类型") + (param.required ? "(必填)" : "(可选)");
|
||
label.appendChild(title);
|
||
var wrapper = document.createElement("div");
|
||
wrapper.appendChild(label);
|
||
container.appendChild(wrapper);
|
||
if (["resource", "memory", "pluginhandle", "functionref"].includes(type)) {
|
||
appendLine(label, "small", "mq-colophon", "此类型不能从阅读器传入。");
|
||
if (param.required) panel.dataset.unsupported = param.name;
|
||
return;
|
||
}
|
||
var input = document.createElement(type === "bool" ? "select" : type === "text" ? "textarea" : "input");
|
||
if (type === "bool") {
|
||
input.add(new Option(param.required ? "请选择" : "使用声明默认值", ""));
|
||
input.add(new Option("真 (true)", "true"));
|
||
input.add(new Option("假 (false)", "false"));
|
||
} else {
|
||
input.maxLength = 4096;
|
||
input.spellcheck = false;
|
||
input.placeholder = param.default !== null && param.default !== undefined
|
||
? "默认:" + JSON.stringify(param.default).slice(0, 120)
|
||
: ({ int: "十进制整数", float: "例如 3.0", text: "输入原文本", list: "例如 [1, 2]", map: '例如 {"key": 1}' }[type] || "CLI 常量表达式");
|
||
if (type === "int") input.inputMode = "numeric";
|
||
if (type === "float") input.inputMode = "decimal";
|
||
if (type === "text") input.rows = 2;
|
||
}
|
||
input.dataset.paramName = param.name;
|
||
input.dataset.paramType = type;
|
||
input.dataset.required = String(param.required);
|
||
if (param.required) input.setAttribute("aria-required", "true");
|
||
label.appendChild(input);
|
||
if (type === "text") {
|
||
var emptyLabel = document.createElement("label");
|
||
emptyLabel.className = "mq-colophon mq-empty-text";
|
||
var empty = document.createElement("input");
|
||
empty.type = "checkbox";
|
||
empty.dataset.textPresent = "true";
|
||
emptyLabel.append(empty, " 提交空文本");
|
||
wrapper.appendChild(emptyLabel);
|
||
}
|
||
});
|
||
}
|
||
|
||
function openFunctionForm(trigger) {
|
||
var panel = functionPanel(trigger.dataset.functionId);
|
||
if (!panel || runBusy) return;
|
||
closeAllDialogs();
|
||
setMode("document");
|
||
if (panel.hidden) {
|
||
renderRunParams(JSON.parse(panel.dataset.params), panel);
|
||
panel.hidden = false;
|
||
$$("[data-action=call-function]").filter(function (button) {
|
||
return button.dataset.functionId === panel.dataset.functionFor;
|
||
}).forEach(function (button) { button.setAttribute("aria-expanded", "true"); });
|
||
}
|
||
updateApplicability(panel);
|
||
var field = $("[data-param-name]", panel) || $("[data-action=prepare-function]", panel);
|
||
if (field) field.focus();
|
||
}
|
||
|
||
function setApplicability(panel, text) {
|
||
if (!panel) return;
|
||
var notice = $("[data-function-applicability]", panel);
|
||
notice.textContent = text;
|
||
notice.hidden = !text;
|
||
}
|
||
|
||
function updateApplicability(panel) {
|
||
var previous = functionRuns.get(panel.dataset.functionFor);
|
||
$("[data-action=show-function-result]", panel).hidden = !previous;
|
||
if (!previous) { setApplicability(panel, ""); return; }
|
||
var same = false;
|
||
try { same = JSON.stringify(collectParameters(panel)) === JSON.stringify(previous.parameters); }
|
||
catch (error) { /* The draft no longer matches the accepted arguments. */ }
|
||
setApplicability(panel, same ? "" : "参数已修改,待重新调用。上次结果与原参数仍可查看。");
|
||
}
|
||
|
||
function prepareFunction(panel) {
|
||
if (!panel || runBusy) return;
|
||
var feedback = $("[data-function-feedback]", panel);
|
||
try {
|
||
if (panel.dataset.unsupported) throw new Error(panel.dataset.unsupported + " 无法直接传入,请在文稿中组织调用");
|
||
var parameters = collectParameters(panel);
|
||
feedback.hidden = true;
|
||
openRunForm({
|
||
kind: "function",
|
||
functionId: panel.dataset.functionFor,
|
||
label: panel.dataset.functionLabel,
|
||
cliName: panel.dataset.cliName,
|
||
effects: panel.dataset.effects,
|
||
parameters: parameters,
|
||
panel: panel
|
||
});
|
||
} catch (error) {
|
||
feedback.textContent = error.message;
|
||
feedback.hidden = false;
|
||
}
|
||
}
|
||
|
||
function openRunForm(target) {
|
||
var dialog = $("#mq-dialog-run");
|
||
if (!dialog || runBusy) return;
|
||
pendingRun = Object.assign({ parameters: [], clientRequestId: randomId() }, target);
|
||
$("#mq-run-target-label").textContent = target.kind === "entry" ? "入口 main" : "函数 " + target.label;
|
||
$("#mq-run-identity").textContent = reader.dataset.document + " · Analysis " + reader.dataset.analysisDigest +
|
||
(target.effects ? " · 静态效果 " + target.effects : " · 静态效果未标注");
|
||
$('input[name="mq-mode"][value="pure"]').checked = true;
|
||
$("#mq-grant-read").value = "";
|
||
$("#mq-grant-write").value = "";
|
||
$("#mq-run-grants").hidden = true;
|
||
updateRunPreview();
|
||
openDialog("mq-dialog-run");
|
||
}
|
||
|
||
function openRunForMain() {
|
||
if (reader.dataset.coreAvailable !== "true") {
|
||
showUnsupported("运行文档", "当前页面没有可用的冻结核心(MARQDO_BIN)。");
|
||
return;
|
||
}
|
||
if (reader.dataset.hasMain !== "true") {
|
||
toast("本文档没有可执行的 main;请从函数面板选择函数");
|
||
showFunctions();
|
||
return;
|
||
}
|
||
var functionId = reader.dataset.entryFunction;
|
||
if (reader.dataset.entryNeedsParameters === "true") {
|
||
var trigger = $$(".mq-document [data-action=call-function]").find(function (button) {
|
||
return button.dataset.functionId === functionId;
|
||
});
|
||
if (trigger) openFunctionForm(trigger);
|
||
return;
|
||
}
|
||
openRunForm({ kind: "entry", label: "入口 main", functionId: functionId });
|
||
}
|
||
|
||
function placeRunPanel(functionId) {
|
||
var panel = runPanel();
|
||
var slot = $$(".mq-result-slot").find(function (item) { return item.dataset.resultFor === functionId; });
|
||
if (slot && panel) slot.appendChild(panel);
|
||
else if (panel) $("#mq-document").after(panel);
|
||
if (panel) panel.open = true;
|
||
}
|
||
|
||
function submitRun() {
|
||
if (!pendingRun || runBusy) return;
|
||
var selection = pendingRun;
|
||
var mode = selectedMode();
|
||
var grants = mode === "project"
|
||
? { read: grantList("mq-grant-read"), write: grantList("mq-grant-write") }
|
||
: { read: [], write: [] };
|
||
if (mode === "project" && grants.read.length === 0 && grants.write.length === 0) {
|
||
toast("project 模式必须至少声明一个相对项目根的 fs read/write glob");
|
||
return;
|
||
}
|
||
if (mode === "project" &&
|
||
!window.confirm("project 模式将按你填写的 glob 授予文件读写权限。它仍不是操作系统沙箱,是否继续?")) {
|
||
return;
|
||
}
|
||
var payload = {
|
||
document: reader.dataset.document,
|
||
target: selection.kind === "entry"
|
||
? { kind: "entry" }
|
||
: { kind: "function", function_id: selection.functionId },
|
||
parameters: selection.parameters,
|
||
analysis_digest: reader.dataset.analysisDigest,
|
||
mode: mode,
|
||
grants: grants,
|
||
client_request_id: selection.clientRequestId
|
||
};
|
||
pendingRun = null;
|
||
closeAllDialogs();
|
||
clearRunOutput();
|
||
placeRunPanel(selection.functionId);
|
||
showRunPanel();
|
||
setRunBusy(true);
|
||
setRunStatus("正在提交运行请求…");
|
||
fetch("/api/runs", {
|
||
method: "POST",
|
||
credentials: "same-origin",
|
||
cache: "no-store",
|
||
headers: {
|
||
"Content-Type": "application/json",
|
||
"Accept": "application/json",
|
||
"X-View-CSRF": csrfToken()
|
||
},
|
||
body: JSON.stringify(payload)
|
||
})
|
||
.then(function (response) {
|
||
return response.json().then(function (data) { return { ok: response.ok, status: response.status, data: data }; });
|
||
})
|
||
.then(function (result) {
|
||
if (!result.ok || !result.data || !result.data.run_id) {
|
||
setRunBusy(false);
|
||
var reason = result.data && result.data.message ? result.data.message : "运行请求被拒绝";
|
||
setRunStatus("运行未启动(" + result.status + "):" + reason);
|
||
if (result.status === 409 && result.data && result.data.code === "view.observation_stale") {
|
||
placeRunPanel("");
|
||
functionRuns.forEach(function (previous) { previous.sourceStale = true; });
|
||
setApplicability(selection.panel, "文稿或依赖已变化。请刷新后重新确认,旧结果属于历史。");
|
||
}
|
||
toast("运行未启动:" + reason);
|
||
return;
|
||
}
|
||
subscribeRun(result.data, selection, payload);
|
||
})
|
||
.catch(function (error) {
|
||
setRunBusy(false);
|
||
setRunStatus("运行请求失败:" + error.message);
|
||
toast("运行请求失败:" + error.message);
|
||
});
|
||
}
|
||
|
||
function subscribeRun(job, selection, payload) {
|
||
closeActiveObserver();
|
||
activeRun = {
|
||
runId: job.run_id,
|
||
eventsUrl: job.events_url,
|
||
cancelUrl: job.cancel_url,
|
||
source: null,
|
||
lastSeq: -1,
|
||
targetLabel: selection.label,
|
||
functionId: selection.functionId,
|
||
parameters: payload.parameters,
|
||
mode: payload.mode,
|
||
grants: payload.grants,
|
||
terminal: false
|
||
};
|
||
clearRunOutput();
|
||
showRunPanel();
|
||
setRunStatus("状态:已接受 · " + activeRun.targetLabel);
|
||
if (!window.EventSource) {
|
||
setRunBusy(false);
|
||
setRunStatus("浏览器不支持 EventSource,无法接收运行状态;请使用现代浏览器。");
|
||
return;
|
||
}
|
||
var decoders = { stdout: new TextDecoder(), stderr: new TextDecoder() };
|
||
var source = new EventSource(job.events_url, { withCredentials: true });
|
||
activeRun.source = source;
|
||
function apply(event) {
|
||
var data;
|
||
try {
|
||
data = JSON.parse(event.data);
|
||
} catch (error) {
|
||
return;
|
||
}
|
||
if (!data || !activeRun || activeRun.runId !== job.run_id ||
|
||
data.schema !== "marqdo.view-run-events" ||
|
||
data.schema_version !== 1 ||
|
||
data.run_id !== job.run_id ||
|
||
!Number.isSafeInteger(data.seq) ||
|
||
data.seq <= activeRun.lastSeq) {
|
||
return;
|
||
}
|
||
activeRun.lastSeq = data.seq;
|
||
if (data.observation) {
|
||
renderObservation(data.observation, decoders);
|
||
return;
|
||
}
|
||
updateRunView(data);
|
||
}
|
||
["run.state", "run.complete", "run.error", "run.snapshot", "run.observation"].forEach(function (kind) {
|
||
source.addEventListener(kind, apply);
|
||
});
|
||
source.onerror = function () {
|
||
if (activeRun && !activeRun.terminal) {
|
||
setRunStatus("SSE 连接中断,正在自动恢复…(任务仍在服务端运行;不会重新执行)");
|
||
}
|
||
};
|
||
}
|
||
|
||
function renderObservation(observation, decoders) {
|
||
var stream = observation.kind === "stdout.chunk" ? "stdout"
|
||
: observation.kind === "stderr.chunk" ? "stderr" : null;
|
||
if (stream) {
|
||
var output = $("#mq-run-" + stream);
|
||
if (!output) return;
|
||
var bytes = Uint8Array.from(atob(observation.data_base64), function (value) {
|
||
return value.charCodeAt(0);
|
||
});
|
||
output.append(document.createTextNode(decoders[stream].decode(bytes, { stream: true })));
|
||
output.hidden = false;
|
||
} else if (/^(branch|loop|control|call)\./.test(observation.kind)) {
|
||
var wrap = $("#mq-run-observation-wrap");
|
||
if (wrap) wrap.hidden = false;
|
||
var events = $("#mq-run-events");
|
||
if (events && events.childElementCount < 100) {
|
||
appendLine(events, "li", "", observation.kind +
|
||
(observation.decision === undefined ? "" : " · " + observation.decision));
|
||
}
|
||
}
|
||
}
|
||
|
||
function showFunctionResult(panel) {
|
||
var previous = panel && functionRuns.get(panel.dataset.functionFor);
|
||
if (!previous || runBusy) return;
|
||
activeRun = previous;
|
||
clearRunOutput();
|
||
placeRunPanel(previous.sourceStale ? "" : previous.functionId);
|
||
updateRunView(previous.terminalEvent, true);
|
||
}
|
||
|
||
function updateRunView(data, historical) {
|
||
var panel = runPanel();
|
||
if (panel) {
|
||
panel.hidden = false;
|
||
panel.dataset.runState = data.state;
|
||
}
|
||
reader.dataset.runState = data.state;
|
||
var partial = data.state === "succeeded" && data.result && data.result.output_complete === false;
|
||
var rejected = data.result && data.result.core_run_status === "rejected";
|
||
var label = rejected ? "运行前拒绝" : partial ? "已结束,观察或输出不完整" : stateLabel(data.state);
|
||
setRunStatus((historical ? "历史运行:" : "状态:") + label +
|
||
(data.at ? " · " + data.at : ""));
|
||
if (!isTerminalState(data.state)) {
|
||
setRunBusy(true);
|
||
return;
|
||
}
|
||
if (activeRun) {
|
||
activeRun.terminal = true;
|
||
activeRun.terminalEvent = data;
|
||
activeRun.exportData = data.result && data.result.export_preview ? data : null;
|
||
var exportButton = $("#mq-export-result");
|
||
if (exportButton) exportButton.hidden = !activeRun.exportData;
|
||
if (data.result && data.result.stale) {
|
||
placeRunPanel("");
|
||
functionRuns.forEach(function (previous) { previous.sourceStale = true; });
|
||
setApplicability(functionPanel(activeRun.functionId), "文稿或依赖已变化,当前结果无法绑定。请刷新后重新确认。");
|
||
} else if (activeRun.functionId && !historical) {
|
||
functionRuns.delete(activeRun.functionId);
|
||
functionRuns.set(activeRun.functionId, activeRun);
|
||
if (functionRuns.size > 8) {
|
||
var retired = functionRuns.keys().next().value;
|
||
functionRuns.delete(retired);
|
||
var retiredPanel = functionPanel(retired);
|
||
if (retiredPanel) updateApplicability(retiredPanel);
|
||
}
|
||
var targetPanel = functionPanel(activeRun.functionId);
|
||
if (targetPanel) updateApplicability(targetPanel);
|
||
}
|
||
}
|
||
closeActiveObserver();
|
||
setRunBusy(false);
|
||
if (data.result) renderRunResult(data.result, data.state, data.error);
|
||
else if (data.error) renderRunResult(null, data.state, data.error);
|
||
if (data.observation_summary) {
|
||
var traceTitle = $("#mq-run-observation-title");
|
||
if (traceTitle && data.observation_summary.status === "verified") traceTitle.textContent = "已验证的 Observation v1 事件";
|
||
renderTrace(data.observation_summary, historical);
|
||
}
|
||
else if (data.result && data.result.observation_status) renderTraceStatus(data.result.observation_status);
|
||
renderRunAudit(data);
|
||
if (!historical) toast(data.state === "succeeded" && !partial ? "运行完成" : label);
|
||
}
|
||
|
||
function renderRunAudit(data) {
|
||
var audit = $("#mq-run-audit");
|
||
var items = $("#mq-run-audit-items");
|
||
if (!audit || !items || !activeRun) return;
|
||
var result = data.result || {};
|
||
var submitted = activeRun.parameters.map(function (param) { return param.name + " = " + param.expression; });
|
||
var grants = activeRun.grants;
|
||
var rows = [
|
||
["函数身份(Analysis)", result.function_id || activeRun.functionId],
|
||
["提交的参数表达式", submitted.join("\n") || "无;声明默认值由 CLI 处理"],
|
||
["调用计划", activeRun.mode + " · 读 " + (grants.read.join(", ") || "无") + " · 写 " + (grants.write.join(", ") || "无")],
|
||
["文稿身份(Analysis)", result.analysis_digest || reader.dataset.analysisDigest],
|
||
["Stdlib / lock 摘要", (result.stdlib_digest || "未知") + " / " + (result.lock_digest || "未锁定")],
|
||
["CLI 生产者 / Observation run_id", (result.core_version || "未取得") + " / " + (result.core_run_id || "未取得")],
|
||
["CLI 开始时刻(Unix 毫秒)", result.started_unix_ms === null || result.started_unix_ms === undefined ? "未取得" : String(result.started_unix_ms)],
|
||
["View 终态时间", data.at || "未取得"],
|
||
["观测值", "未请求实际参数值和变量值"],
|
||
["适用范围", "可核验静态身份见上。文件内容、时间或外部环境可能变化,仍需独立核验。"]
|
||
];
|
||
items.textContent = "";
|
||
rows.forEach(function (row) {
|
||
appendLine(items, "dt", "", row[0]);
|
||
appendLine(items, "dd", "", row[1]);
|
||
});
|
||
audit.hidden = false;
|
||
}
|
||
|
||
function previewBytes(text, count) {
|
||
if (!text || !count) return "";
|
||
return new TextDecoder().decode(new TextEncoder().encode(text).slice(0, count));
|
||
}
|
||
|
||
function exportNeedsPartial(data) {
|
||
var preview = data.result.export_preview;
|
||
return data.state !== "succeeded" || !preview.output_complete ||
|
||
!preview.result_complete || preview.observation_truncated ||
|
||
preview.observation_status === "truncated";
|
||
}
|
||
|
||
function updateExportConfirm() {
|
||
var button = $("#mq-export-download");
|
||
var data = activeRun && activeRun.exportData;
|
||
if (!button || !data) return;
|
||
button.disabled = button.dataset.busy === "true" || !$("#mq-export-confirm").checked ||
|
||
(exportNeedsPartial(data) && !$("#mq-export-partial").checked);
|
||
}
|
||
|
||
function openExportPreview() {
|
||
var data = activeRun && activeRun.exportData;
|
||
if (!data) return;
|
||
var result = data.result;
|
||
var preview = result.export_preview;
|
||
var fields = $("#mq-export-fields");
|
||
var counts = preview.observation_summary && data.observation_summary && data.observation_summary.counts;
|
||
var argumentsText = (activeRun.parameters || []).map(function (parameter) {
|
||
return parameter.name + " = " + parameter.expression;
|
||
}).join("\n");
|
||
$("#mq-export-target").textContent = preview.label + " · " + stateLabel(data.state) +
|
||
(exportNeedsPartial(data) ? " · 部分观察" : "");
|
||
fields.textContent = "";
|
||
[
|
||
["result_value", "返回值", preview.value_bytes, preview.value_is_public_scalar, preview.value],
|
||
["stdout", "stdout", preview.stdout_bytes, false, previewBytes(result.stdout, preview.stdout_bytes)],
|
||
["stderr", "stderr", preview.stderr_bytes, false, previewBytes(result.stderr, preview.stderr_bytes)],
|
||
["observation_summary", "观察摘要", counts ? new TextEncoder().encode(JSON.stringify(counts)).length : null, true, counts && JSON.stringify(counts, null, 2)],
|
||
["arguments", "已提交的参数", preview.arguments_count ? new TextEncoder().encode(argumentsText).length : null, false, argumentsText]
|
||
].forEach(function (field) {
|
||
var label = document.createElement("label");
|
||
var input = document.createElement("input");
|
||
input.type = "checkbox";
|
||
input.name = field[0];
|
||
input.disabled = !field[2];
|
||
input.checked = field[3] && !input.disabled;
|
||
label.appendChild(input);
|
||
appendLine(label, "span", "", field[1]);
|
||
appendLine(label, "small", "", field[2] ? field[2] + " B" : "无内容");
|
||
fields.appendChild(label);
|
||
if (field[4]) {
|
||
var disclosure = document.createElement("details");
|
||
appendLine(disclosure, "summary", "", "查看" + field[1]);
|
||
appendLine(disclosure, "pre", "", field[4]);
|
||
fields.appendChild(disclosure);
|
||
}
|
||
});
|
||
$("#mq-export-confirm").checked = false;
|
||
$("#mq-export-partial").checked = false;
|
||
$("#mq-export-partial-row").hidden = !exportNeedsPartial(data);
|
||
$("#mq-export-error").hidden = true;
|
||
updateExportConfirm();
|
||
openDialog("mq-dialog-export");
|
||
}
|
||
|
||
async function downloadSnapshot() {
|
||
var button = $("#mq-export-download");
|
||
var data = activeRun && activeRun.exportData;
|
||
if (!data || button.disabled) return;
|
||
var include = {};
|
||
$$("#mq-export-fields input").forEach(function (input) {
|
||
include[input.name] = input.checked;
|
||
});
|
||
var error = $("#mq-export-error");
|
||
error.hidden = true;
|
||
button.dataset.busy = "true";
|
||
updateExportConfirm();
|
||
try {
|
||
var response = await fetch("/api/exports", {
|
||
method: "POST",
|
||
credentials: "same-origin",
|
||
cache: "no-store",
|
||
headers: { "Content-Type": "application/json", "Accept": "application/zip", "X-View-CSRF": csrfToken() },
|
||
body: JSON.stringify({
|
||
schema: "marqdo.view-static-export-request",
|
||
schema_version: 1,
|
||
run_id: data.run_id,
|
||
document: data.result.document,
|
||
analysis_digest: data.result.analysis_digest,
|
||
scope: "document",
|
||
include: include,
|
||
confirm_sensitive_output: $("#mq-export-confirm").checked,
|
||
confirm_partial: $("#mq-export-partial").checked,
|
||
client_export_request_id: randomId()
|
||
})
|
||
});
|
||
if (!response.ok) {
|
||
var failure = await response.json();
|
||
throw new Error(failure.message || "导出请求未完成");
|
||
}
|
||
if (!(response.headers.get("Content-Type") || "").startsWith("application/zip")) {
|
||
throw new Error("服务返回的文件格式无效");
|
||
}
|
||
var url = URL.createObjectURL(await response.blob());
|
||
var link = document.createElement("a");
|
||
link.href = url;
|
||
link.download = "marqdo-execution-snapshot.zip";
|
||
document.body.appendChild(link);
|
||
link.click();
|
||
link.remove();
|
||
window.setTimeout(function () { URL.revokeObjectURL(url); }, 1000);
|
||
closeAllDialogs();
|
||
toast("执行快照已下载");
|
||
} catch (failure) {
|
||
error.textContent = failure.message;
|
||
error.hidden = false;
|
||
} finally {
|
||
delete button.dataset.busy;
|
||
updateExportConfirm();
|
||
}
|
||
}
|
||
|
||
// Rust supplies one inert fragment for both snapshots and Live. Parse as
|
||
// XML, then recreate only presentation nodes and their safe attributes.
|
||
function mountResultValue(container, markup) {
|
||
if (!markup) return false;
|
||
var htmlTags = new Set("div span small p details summary ol li dl dt dd table thead tr th tbody td pre code a".split(" "));
|
||
var mathTags = new Set("math mrow mi mo mn mtext mfrac msqrt mroot msub msup msubsup munder mover munderover mtable mtr mtd mspace mpadded mstyle menclose mphantom mmultiscripts mprescripts none".split(" "));
|
||
var mathAttributes = new Set("display mathvariant mathsize mathcolor displaystyle scriptlevel stretchy symmetric movablelimits form fence separator lspace rspace minsize maxsize accent accentunder linethickness width height depth columnalign rowalign rowspacing columnspacing notation".split(" "));
|
||
var mathNS = "http://www.w3.org/1998/Math/MathML";
|
||
var root = new DOMParser().parseFromString(markup, "application/xml").documentElement;
|
||
if (root.namespaceURI !== null || root.localName !== "div" || root.getAttribute("class") !== "mq-result-value") return false;
|
||
function copy(node) {
|
||
if (node.nodeType === Node.TEXT_NODE) return document.createTextNode(node.data);
|
||
if (node.nodeType !== Node.ELEMENT_NODE) return null;
|
||
var isMath = node.namespaceURI === mathNS;
|
||
var name = node.localName;
|
||
if (!(isMath ? mathTags.has(name) : node.namespaceURI === null && htmlTags.has(name))) return null;
|
||
var result = isMath ? document.createElementNS(mathNS, name) : document.createElement(name);
|
||
Array.from(node.attributes).forEach(function (attr) {
|
||
var safeMathAttribute = isMath && attr.namespaceURI === null && mathAttributes.has(attr.name);
|
||
var safeHtmlAttribute = !isMath && (
|
||
(attr.name === "class" && /^mq-[a-z-]+$/.test(attr.value)) ||
|
||
(attr.name === "open" && name === "details") ||
|
||
(attr.name === "href" && name === "a" && /^#mq-h-[0-9a-f]+-[0-9a-f]+$/.test(attr.value)) ||
|
||
(attr.name === "tabindex" && attr.value === "0")
|
||
);
|
||
if (safeMathAttribute || safeHtmlAttribute) result.setAttribute(attr.name, attr.value);
|
||
});
|
||
node.childNodes.forEach(function (child) {
|
||
var element = copy(child);
|
||
if (element) result.appendChild(element);
|
||
});
|
||
return result;
|
||
}
|
||
container.appendChild(copy(root));
|
||
return true;
|
||
}
|
||
|
||
function renderRunResult(result, state, error) {
|
||
var summary = $("#mq-run-summary");
|
||
if (!summary) return;
|
||
summary.textContent = "";
|
||
if (result) {
|
||
if (result.target) {
|
||
var label = result.target.kind === "entry" ? "入口 main" : "函数 " + (result.target.label || result.target.cli_name || "");
|
||
appendLine(summary, "p", "mq-run-result", label + " · 模式 " + (result.mode || "pure") +
|
||
(typeof result.duration_ms === "number" ? " · " + result.duration_ms + " ms" : "") +
|
||
(result.exit_code === null || typeof result.exit_code === "undefined" ? "" : " · 退出码 " + result.exit_code));
|
||
}
|
||
if (!mountResultValue(summary, result.value_markup) && result.value_text && result.source_verified) {
|
||
appendLine(summary, "p", "mq-run-result", "返回值:" + result.value_text);
|
||
}
|
||
var observationState = result.observation_status;
|
||
if (observationState === "truncated") {
|
||
var badge = document.createElement("span");
|
||
badge.className = "mq-truncated-badge";
|
||
badge.textContent = "TRUNCATED";
|
||
appendLine(summary, "p", "mq-run-warning", "观察事件达到协议预算,已截断;本次结果不再宣称完整。");
|
||
summary.lastChild.appendChild(badge);
|
||
} else if (observationState === "invalid") {
|
||
appendLine(summary, "p", "mq-run-warning", "Observation 无效:不绘制任何执行标注,也不显示为成功。");
|
||
} else if (observationState === "stale") {
|
||
appendLine(summary, "p", "mq-run-warning", "Observation 与当前 Analysis 不匹配:结果标记为过期,不显示为成功。");
|
||
}
|
||
if (result.stale) {
|
||
appendLine(summary, "p", "mq-run-warning", "源码在运行后发生变化:结果可见但标记为过期,不在当前正文上绘制执行标注。");
|
||
}
|
||
if (result.output_complete === false && observationState !== "truncated") {
|
||
appendLine(summary, "p", "mq-run-warning", "本次输出未完整交付(未完成/已被截断);不声明完整结果。");
|
||
}
|
||
if (result.stdout) {
|
||
var stdout = $("#mq-run-stdout");
|
||
if (stdout) {
|
||
stdout.textContent = result.stdout;
|
||
stdout.hidden = false;
|
||
}
|
||
}
|
||
if (result.stderr) {
|
||
var stderr = $("#mq-run-stderr");
|
||
if (stderr) {
|
||
stderr.textContent = result.stderr;
|
||
stderr.hidden = false;
|
||
}
|
||
}
|
||
if (Array.isArray(result.diagnostics) && result.diagnostics.length) {
|
||
appendLine(summary, "p", "mq-run-warning", "诊断:" + result.diagnostics.length + " 条(详见运行详情)");
|
||
var list = document.createElement("ol");
|
||
list.className = "mq-run-events";
|
||
result.diagnostics.slice(0, 20).forEach(function (diagnostic) {
|
||
var code = diagnostic && diagnostic.code ? diagnostic.code : "diagnostic";
|
||
var message = diagnostic && diagnostic.message ? diagnostic.message : "";
|
||
appendLine(list, "li", "", code + ":" + message);
|
||
});
|
||
summary.appendChild(list);
|
||
}
|
||
}
|
||
if (error && (error.code || error.message)) {
|
||
appendLine(summary, "p", "mq-run-error", (error.code || "error") + ":" + (error.message || "运行失败"));
|
||
}
|
||
if (state === "cancelled") appendLine(summary, "p", "mq-run-warning", "View 已结束本次运行;详情见实际终态。");
|
||
}
|
||
|
||
function renderTraceStatus(status) {
|
||
if (!status || status === "verified") return;
|
||
var summary = $("#mq-run-summary");
|
||
if (!summary) return;
|
||
var message = status === "rejected"
|
||
? "CLI 在开始运行前拒绝了本次调用,未建立源码观察绑定。"
|
||
: status === "invalid"
|
||
? "Observation 与本次 Analysis 不匹配或格式无效:不绘制执行标注,也不声称观察到完整过程。"
|
||
: "本次运行没有可用的 Observation v1(unavailable):只展示 CLI 返回值与输出。";
|
||
appendLine(summary, "p", "mq-run-warning", message);
|
||
}
|
||
|
||
function renderTrace(trace, historical) {
|
||
var summary = $("#mq-run-summary");
|
||
var wrap = $("#mq-run-observation-wrap");
|
||
var list = $("#mq-run-events");
|
||
if (!wrap || !list) return;
|
||
list.textContent = "";
|
||
if (!trace || trace.status !== "verified") {
|
||
wrap.hidden = true;
|
||
renderTraceStatus(trace && trace.status ? trace.status : "unavailable");
|
||
return;
|
||
}
|
||
wrap.hidden = false;
|
||
if (summary) {
|
||
if (trace.stale) {
|
||
appendLine(summary, "p", "mq-run-warning", "Observation 属于运行时的源码:当前源码已变化,本次不绘制执行标注。");
|
||
}
|
||
if (trace.truncated) {
|
||
var label = trace.truncated.label || (trace.truncated.reason + "(上限 " + trace.truncated.limit + ")");
|
||
appendLine(summary, "p", "mq-run-warning", "Observation 被截断:" + label + ";这不代表程序终止。");
|
||
}
|
||
}
|
||
var entryEvents = Array.isArray(trace.events) ? trace.events : [];
|
||
entryEvents.slice(0, 200).forEach(function (event) {
|
||
var location = event.span ? "span " + event.span.start + "–" + event.span.end : (event.module_id || "");
|
||
var detail = event.detail ? " · " + event.detail : "";
|
||
var operation = event.operation ? " · " + event.operation : "";
|
||
appendLine(list, "li", "", event.kind + " · " + location + detail + operation);
|
||
});
|
||
if (entryEvents.length > 200) {
|
||
appendLine(list, "li", "mq-colophon", "仅显示前 200 条(共 " + entryEvents.length + " 条)。");
|
||
}
|
||
if (!trace.stale && !historical) {
|
||
var bySource = {};
|
||
$$("[data-source-id]").forEach(function (element) {
|
||
bySource[element.dataset.sourceId] = element;
|
||
});
|
||
var grouped = {};
|
||
entryEvents.forEach(function (event) {
|
||
if (!event.source_id || !bySource[event.source_id]) return;
|
||
if (!grouped[event.source_id]) grouped[event.source_id] = [];
|
||
grouped[event.source_id].push(event);
|
||
});
|
||
Object.keys(grouped).forEach(function (sourceId) {
|
||
var group = grouped[sourceId];
|
||
var last = group[group.length - 1];
|
||
var kinds = [];
|
||
group.forEach(function (event) {
|
||
if (kinds.indexOf(event.kind) < 0) kinds.push(event.kind);
|
||
});
|
||
var chip = document.createElement("span");
|
||
chip.className = "mq-run-chip";
|
||
chip.dataset.viewChip = "1";
|
||
chip.dataset.annotationSource = "observation";
|
||
chip.dataset.runSeq = String(last.seq);
|
||
chip.dataset.runKind = kinds.join(",");
|
||
var text = last.detail || last.kind;
|
||
if (group.length > 3) text += " ×" + group.length;
|
||
chip.textContent = text;
|
||
chip.title = "本次 Observation 事件:" + group.length + " 条(" + kinds.join(",") + ")";
|
||
bySource[sourceId].appendChild(chip);
|
||
});
|
||
}
|
||
}
|
||
|
||
function cancelRun() {
|
||
if (!activeRun || activeRun.terminal) return;
|
||
setRunStatus("正在请求取消…");
|
||
fetch(activeRun.cancelUrl, {
|
||
method: "POST",
|
||
credentials: "same-origin",
|
||
cache: "no-store",
|
||
headers: { "Accept": "application/json", "X-View-CSRF": csrfToken() }
|
||
})
|
||
.then(function (response) {
|
||
return response.json().then(function (data) { return { ok: response.ok, status: response.status, data: data }; });
|
||
})
|
||
.then(function (result) {
|
||
if (!result.ok) {
|
||
var reason = result.data && result.data.message ? result.data.message : "取消失败";
|
||
setRunStatus("取消请求被拒绝(" + result.status + "):" + reason);
|
||
return;
|
||
}
|
||
setRunStatus("已请求取消;等待唯一终态…");
|
||
})
|
||
.catch(function (error) {
|
||
setRunStatus("取消请求失败:" + error.message);
|
||
});
|
||
}
|
||
|
||
function clearRun() {
|
||
if (runBusy) { toast("请先取消运行或等待终态。"); return; }
|
||
closeAllDialogs();
|
||
closeActiveObserver();
|
||
activeRun = null;
|
||
functionRuns.clear();
|
||
$$(".mq-function-interaction").filter(function (panel) { return !panel.hidden; }).forEach(updateApplicability);
|
||
var panel = runPanel();
|
||
if (panel) {
|
||
panel.hidden = true;
|
||
panel.dataset.runState = "idle";
|
||
}
|
||
reader.dataset.runState = "idle";
|
||
clearRunOutput();
|
||
setRunStatus("尚未运行。点击 Dock 的“运行”执行 main,或在函数面板选择函数。");
|
||
toast("已清理本地结果展示(未删除项目文件、lock 或服务端运行记录)");
|
||
}
|
||
|
||
document.addEventListener("click", function (event) {
|
||
var trigger = event.target.closest ? event.target.closest("[data-action]") : null;
|
||
if (!trigger) return;
|
||
event.preventDefault();
|
||
handleAction(trigger.dataset.action, trigger);
|
||
});
|
||
|
||
document.addEventListener("click", function (event) {
|
||
var link = event.target.closest ? event.target.closest("[data-goto-anchor]") : null;
|
||
if (link) {
|
||
event.preventDefault();
|
||
gotoAnchor(link.dataset.gotoAnchor);
|
||
return;
|
||
}
|
||
var lineLink = event.target.closest ? event.target.closest("[data-goto-line]") : null;
|
||
if (lineLink) {
|
||
event.preventDefault();
|
||
var line = parseInt(lineLink.dataset.gotoLine, 10);
|
||
if (!isNaN(line)) gotoSourceLine(line);
|
||
}
|
||
});
|
||
|
||
document.addEventListener("input", function (event) {
|
||
if (event.target && event.target.id === "mq-search-input") {
|
||
renderSearch(event.target.value);
|
||
}
|
||
if (event.target && (event.target.id === "mq-grant-read" || event.target.id === "mq-grant-write")) {
|
||
updateRunPreview();
|
||
}
|
||
var panel = event.target.closest ? event.target.closest(".mq-function-interaction") : null;
|
||
if (panel) updateApplicability(panel);
|
||
});
|
||
document.addEventListener("change", function (event) {
|
||
if (event.target && (event.target.id === "mq-export-confirm" || event.target.id === "mq-export-partial")) {
|
||
updateExportConfirm();
|
||
}
|
||
if (event.target && event.target.name === "mq-mode") {
|
||
var grants = $("#mq-run-grants");
|
||
if (grants) grants.hidden = event.target.value !== "project";
|
||
updateRunPreview();
|
||
}
|
||
});
|
||
|
||
document.addEventListener("keydown", function (event) {
|
||
var isMac = /Mac|iPhone|iPad/.test(navigator.platform || "");
|
||
var modifier = isMac ? event.metaKey : event.ctrlKey;
|
||
if (modifier && (event.key === "k" || event.key === "K")) {
|
||
event.preventDefault();
|
||
showSearch();
|
||
return;
|
||
}
|
||
if (event.key === "Escape") {
|
||
closeAllDialogs();
|
||
}
|
||
});
|
||
|
||
document.addEventListener("toggle", function (event) {
|
||
if (event.target && event.target.classList.contains("mq-diagnostics")) {
|
||
try {
|
||
window.localStorage.setItem("marqdo.view.diagnostics", event.target.open ? "1" : "0");
|
||
} catch (error) {
|
||
/* storage is optional */
|
||
}
|
||
}
|
||
}, true);
|
||
|
||
// Restore reading preferences (theme only; never secrets/permissions).
|
||
try {
|
||
var storedTheme = window.localStorage.getItem("marqdo.view.theme");
|
||
if (storedTheme === "dark" || storedTheme === "light") {
|
||
applyTheme(storedTheme, false);
|
||
} else if (window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches) {
|
||
applyTheme("dark", false);
|
||
}
|
||
} catch (error) {
|
||
/* storage is optional */
|
||
}
|
||
|
||
// Restore a URL-selected mode, then honour the persisted diagnostics state.
|
||
try {
|
||
var params = new URLSearchParams(window.location.search);
|
||
if (params.get("mode") === "source") setMode("source");
|
||
else setMode("document");
|
||
var diagnosticsState = window.localStorage.getItem("marqdo.view.diagnostics");
|
||
if (diagnosticsState === "1") {
|
||
$$(".mq-diagnostics").forEach(function (details) {
|
||
details.open = true;
|
||
});
|
||
}
|
||
} catch (error) {
|
||
setMode("document");
|
||
}
|
||
|
||
// Keep dock buttons visible above the last line on small screens.
|
||
function syncDockInset() {
|
||
var dock = $(".mq-dock");
|
||
if (!dock) return;
|
||
var height = dock.getBoundingClientRect().height + 36;
|
||
reader.style.setProperty("--mq-dock-h", Math.round(height) + "px");
|
||
}
|
||
if (typeof ResizeObserver !== "undefined") {
|
||
var dock = $(".mq-dock");
|
||
if (dock) new ResizeObserver(syncDockInset).observe(dock);
|
||
}
|
||
window.addEventListener("resize", syncDockInset);
|
||
syncDockInset();
|
||
})();
|