feat: preview and download selected results from the reader
This commit is contained in:
1 parent
aa2a2b3ce4
commit
a482df80be
9 files changed
+470
-42
No files matched your search
@@ -1441,3 +1441,58 @@
|
||||
|
||||
.mq-snapshot-counts dd { margin: 0; }
|
||||
}
|
||||
|
||||
@layer overlays {
|
||||
.mq-export-dialog {
|
||||
max-inline-size: min(36rem, calc(100vw - 2rem));
|
||||
max-block-size: calc(100dvh - 2rem);
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
.mq-export-target {
|
||||
background: var(--mq-surface-2);
|
||||
border: 1px solid var(--mq-line);
|
||||
border-radius: .45rem;
|
||||
padding: .65rem .85rem;
|
||||
}
|
||||
|
||||
.mq-export-fields {
|
||||
padding: 0;
|
||||
border: 0;
|
||||
margin: 0 0 1rem;
|
||||
min-inline-size: 0;
|
||||
}
|
||||
|
||||
.mq-export-fields legend { font-weight: 650; }
|
||||
|
||||
.mq-export-fields label {
|
||||
display: grid;
|
||||
grid-template-columns: 1.25rem minmax(0, 1fr) auto;
|
||||
align-items: center;
|
||||
gap: .55rem;
|
||||
border-block-start: 1px solid var(--mq-line);
|
||||
padding: .65rem 0 .4rem;
|
||||
}
|
||||
|
||||
.mq-export-fields small { color: var(--mq-muted); }
|
||||
|
||||
.mq-export-fields details {
|
||||
margin-inline-start: 1.8rem;
|
||||
margin-block-end: .6rem;
|
||||
font-size: .86rem;
|
||||
}
|
||||
|
||||
.mq-export-fields pre {
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
overflow: auto;
|
||||
max-block-size: 12rem;
|
||||
background: var(--mq-surface-2);
|
||||
padding: .65rem;
|
||||
}
|
||||
|
||||
.mq-export-confirm { display: block; margin-block: .75rem; }
|
||||
.mq-export-confirm[hidden], .mq-export-result[hidden] { display: none; }
|
||||
.mq-export-result { margin-block-start: .75rem; }
|
||||
#mq-export-error { color: var(--mq-error); }
|
||||
}
|
||||
+160
-8
@@ -310,6 +310,12 @@
|
||||
case "cancel-run":
|
||||
cancelRun();
|
||||
break;
|
||||
case "export-result":
|
||||
openExportPreview();
|
||||
break;
|
||||
case "download-result":
|
||||
downloadSnapshot();
|
||||
break;
|
||||
case "call-function":
|
||||
if (trigger) {
|
||||
var params = [];
|
||||
@@ -409,6 +415,7 @@
|
||||
button.disabled = false;
|
||||
}
|
||||
}
|
||||
$$(".mq-fn-call[data-action=call-function]").forEach(function (call) { call.disabled = busy; });
|
||||
var cancel = $("#mq-run-actions");
|
||||
if (cancel) cancel.hidden = !busy;
|
||||
}
|
||||
@@ -430,6 +437,10 @@
|
||||
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-trace-title");
|
||||
if (traceTitle) traceTitle.textContent = "实时结构事件";
|
||||
var traceWrap = $("#mq-run-trace-wrap");
|
||||
if (traceWrap) traceWrap.hidden = true;
|
||||
$$(".mq-run-chip[data-view-chip]").forEach(function (chip) {
|
||||
@@ -474,12 +485,15 @@
|
||||
var preview = $("#mq-run-command");
|
||||
if (!preview || !pendingRun) return;
|
||||
var mode = selectedMode();
|
||||
var protocol = reader.dataset.executionEvents === "true" ? ["--event-stream", "jsonl"] : ["--json"];
|
||||
var args = ["--mode", mode].concat(protocol, ["--trace-file", "<临时文件>"]);
|
||||
var parts = [];
|
||||
if (pendingRun.kind === "entry") {
|
||||
parts = ["marqdo", "run", reader.dataset.document, "--mode", mode, "--json", "--trace-file", "<临时文件>"];
|
||||
parts = ["marqdo", "run", reader.dataset.document].concat(args);
|
||||
} else {
|
||||
parts = ["marqdo", "call", reader.dataset.document, "<函数 " + pendingRun.label + ">", "--mode", mode, "--json", "--trace-file", "<临时文件>"];
|
||||
parts = ["marqdo", "call", reader.dataset.document, "<函数 " + pendingRun.label + ">"].concat(args);
|
||||
rawParams().forEach(function (param) {
|
||||
if (!param.required && param.expression.trim() === "") return;
|
||||
parts.push("--arg");
|
||||
parts.push(param.name + "=" + (param.expression || "<常量表达式>"));
|
||||
});
|
||||
@@ -588,7 +602,9 @@
|
||||
target: pendingRun.kind === "entry"
|
||||
? { kind: "entry" }
|
||||
: { kind: "function", function_id: pendingRun.functionId },
|
||||
parameters: params.map(function (param) {
|
||||
parameters: params.filter(function (param) {
|
||||
return param.required || param.expression.trim() !== "";
|
||||
}).map(function (param) {
|
||||
return { name: param.name, expression: param.expression };
|
||||
}),
|
||||
analysis_digest: reader.dataset.analysisDigest,
|
||||
@@ -631,7 +647,7 @@
|
||||
toast("运行未启动:" + reason);
|
||||
return;
|
||||
}
|
||||
subscribeRun(result.data, pendingRun ? pendingRun.label : "运行");
|
||||
subscribeRun(result.data, pendingRun ? pendingRun.label : "运行", payload.parameters);
|
||||
})
|
||||
.catch(function (error) {
|
||||
setRunBusy(false);
|
||||
@@ -640,7 +656,7 @@
|
||||
});
|
||||
}
|
||||
|
||||
function subscribeRun(job, targetLabel) {
|
||||
function subscribeRun(job, targetLabel, parameters) {
|
||||
closeActiveObserver();
|
||||
activeRun = {
|
||||
runId: job.run_id,
|
||||
@@ -649,6 +665,7 @@
|
||||
source: null,
|
||||
lastSeq: -1,
|
||||
targetLabel: targetLabel || "运行",
|
||||
parameters: parameters,
|
||||
terminal: false
|
||||
};
|
||||
clearRunOutput();
|
||||
@@ -669,7 +686,7 @@
|
||||
} catch (error) {
|
||||
return;
|
||||
}
|
||||
if (!data ||
|
||||
if (!data || !activeRun || activeRun.runId !== job.run_id ||
|
||||
data.schema !== "marqdo.view-run-events" ||
|
||||
data.schema_version !== 1 ||
|
||||
data.run_id !== job.run_id ||
|
||||
@@ -728,17 +745,148 @@
|
||||
setRunBusy(true);
|
||||
return;
|
||||
}
|
||||
if (activeRun) activeRun.terminal = true;
|
||||
if (activeRun) {
|
||||
activeRun.terminal = true;
|
||||
activeRun.exportData = data.result && data.result.export_preview ? data : null;
|
||||
var exportButton = $("#mq-export-result");
|
||||
if (exportButton) exportButton.hidden = !activeRun.exportData;
|
||||
}
|
||||
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.trace) renderTrace(data.trace);
|
||||
if (data.trace) {
|
||||
var traceTitle = $("#mq-run-trace-title");
|
||||
if (traceTitle && data.trace.status === "verified") traceTitle.textContent = "已验证的 Trace v2 事件";
|
||||
renderTrace(data.trace);
|
||||
}
|
||||
else if (data.result && data.result.trace_status) renderTraceStatus(data.result.trace_status);
|
||||
if (data.state === "succeeded") toast("运行完成");
|
||||
else toast("运行" + stateLabel(data.state));
|
||||
}
|
||||
|
||||
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.trace_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.trace_summary && data.trace && data.trace.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, previewBytes(result.value_text, preview.value_bytes)],
|
||||
["stdout", "stdout", preview.stdout_bytes, false, previewBytes(result.stdout, preview.stdout_bytes)],
|
||||
["stderr", "stderr", preview.stderr_bytes, false, previewBytes(result.stderr, preview.stderr_bytes)],
|
||||
["trace_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();
|
||||
}
|
||||
}
|
||||
|
||||
function renderRunResult(result, state, error) {
|
||||
var summary = $("#mq-run-summary");
|
||||
if (!summary) return;
|
||||
@@ -892,6 +1040,7 @@
|
||||
function clearRun() {
|
||||
closeAllDialogs();
|
||||
closeActiveObserver();
|
||||
activeRun = null;
|
||||
var panel = runPanel();
|
||||
if (panel) {
|
||||
panel.hidden = true;
|
||||
@@ -934,6 +1083,9 @@
|
||||
}
|
||||
});
|
||||
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";
|
||||
|
||||
+32
-28
@@ -174,12 +174,12 @@ struct ControllerState {
|
||||
jobs: HashMap<String, Arc<Job>>,
|
||||
order: VecDeque<String>,
|
||||
active: Option<String>,
|
||||
dedupe: HashMap<String, DedupeEntry>,
|
||||
dedupe: HashMap<(String, String), DedupeEntry>,
|
||||
}
|
||||
|
||||
struct CoreRun {
|
||||
process: ProcessOutcome,
|
||||
trace: Option<Vec<u8>>,
|
||||
trace: ViewResult<Option<Vec<u8>>>,
|
||||
stream: Option<core_events::Stream>,
|
||||
}
|
||||
|
||||
@@ -208,13 +208,13 @@ impl ExecutionController {
|
||||
pub fn submit(self: &Arc<Self>, session_id: &str, body: &[u8]) -> ViewResult<AcceptedRun> {
|
||||
let validated = request::validate_request(body)?;
|
||||
let digest = payload_digest(body);
|
||||
let client_request_id = validated.client_request_id.clone();
|
||||
let request_identity = (session_id.to_string(), validated.client_request_id.clone());
|
||||
let mut state = self.state.lock().map_err(|_| ViewError::Io {
|
||||
detail: "execution controller lock poisoned".to_string(),
|
||||
})?;
|
||||
self.purge_locked(&mut state);
|
||||
|
||||
if let Some(entry) = state.dedupe.get(&client_request_id) {
|
||||
if let Some(entry) = state.dedupe.get(&request_identity) {
|
||||
if entry.digest != digest {
|
||||
return Err(ViewError::RunConflict {
|
||||
detail: "同一 client_request_id 携带了不同请求内容;拒绝执行以避免偷换任务"
|
||||
@@ -262,7 +262,7 @@ impl ExecutionController {
|
||||
state.jobs.insert(run_id.clone(), Arc::clone(&job));
|
||||
state.active = Some(run_id.clone());
|
||||
state.dedupe.insert(
|
||||
client_request_id,
|
||||
request_identity,
|
||||
DedupeEntry {
|
||||
digest,
|
||||
run_id: run_id.clone(),
|
||||
@@ -372,10 +372,7 @@ impl ExecutionController {
|
||||
let mut options = self.run_options(plan);
|
||||
let projection = &static_doc.verified.projection;
|
||||
options.event_stream =
|
||||
semver::Version::parse(&projection.producer_version).is_ok_and(|version| {
|
||||
version >= semver::Version::new(3, 0, 0)
|
||||
|| version >= semver::Version::parse("3.0.0-rc.2").expect("valid Core version")
|
||||
});
|
||||
crate::protocol::tool_v1::supports_execution_events(&projection.producer_version);
|
||||
let args = match &plan.target {
|
||||
ExecutionTarget::Entry => build_run_args(&entry, &trace_path, &options),
|
||||
ExecutionTarget::Function { cli_name, .. } => {
|
||||
@@ -437,7 +434,7 @@ impl ExecutionController {
|
||||
Some(Arc::clone(&job.cancel)),
|
||||
hooks,
|
||||
)?;
|
||||
let trace = read_trace_limited(&trace_path)?;
|
||||
let trace = read_trace_limited(&trace_path);
|
||||
Ok(CoreRun {
|
||||
process: outcome,
|
||||
trace,
|
||||
@@ -630,13 +627,16 @@ impl ExecutionController {
|
||||
.unwrap_or_default();
|
||||
let stale = sha256_hex(¤t_source) != static_doc.source_sha256;
|
||||
|
||||
let (mut trace, mut trace_status) = build_trace_summary(
|
||||
trace_bytes.as_deref(),
|
||||
static_doc,
|
||||
&json,
|
||||
outcome.exit_code.unwrap_or(-1),
|
||||
stale,
|
||||
);
|
||||
let (mut trace, mut trace_status) = match trace_bytes {
|
||||
Ok(trace_bytes) => build_trace_summary(
|
||||
trace_bytes.as_deref(),
|
||||
static_doc,
|
||||
&json,
|
||||
outcome.exit_code.unwrap_or(-1),
|
||||
stale,
|
||||
),
|
||||
Err(_) => (None, "invalid".into()),
|
||||
};
|
||||
let mut result = build_cli_result(plan, static_doc, duration_ms, &json, &outcome);
|
||||
result["stale"] = serde_json::json!(stale);
|
||||
if let Some(stream) = stream {
|
||||
@@ -820,18 +820,22 @@ impl ExecutionController {
|
||||
}
|
||||
|
||||
fn read_trace_limited(path: &std::path::Path) -> ViewResult<Option<Vec<u8>>> {
|
||||
match std::fs::read(path) {
|
||||
Ok(bytes) if bytes.is_empty() => Ok(None),
|
||||
Ok(bytes) if bytes.len() > MAX_TRACE_FILE_BYTES => Err(ViewError::OutputLimit {
|
||||
detail: format!("Trace 文件超过 {} 字节上限", MAX_TRACE_FILE_BYTES),
|
||||
}),
|
||||
Ok(bytes) => Ok(Some(bytes)),
|
||||
Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(None),
|
||||
Err(err) => Err(ViewError::io(
|
||||
&format!("read trace {}", path.display()),
|
||||
err,
|
||||
)),
|
||||
use std::io::Read;
|
||||
let file = match std::fs::File::open(path) {
|
||||
Ok(file) => file,
|
||||
Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(None),
|
||||
Err(err) => return Err(ViewError::io("open Core Trace", err)),
|
||||
};
|
||||
let mut bytes = Vec::new();
|
||||
file.take(MAX_TRACE_FILE_BYTES as u64 + 1)
|
||||
.read_to_end(&mut bytes)
|
||||
.map_err(|err| ViewError::io("read Core Trace", err))?;
|
||||
if bytes.len() > MAX_TRACE_FILE_BYTES {
|
||||
return Err(ViewError::OutputLimit {
|
||||
detail: "Trace v2 byte limit exceeded".into(),
|
||||
});
|
||||
}
|
||||
Ok((!bytes.is_empty()).then_some(bytes))
|
||||
}
|
||||
|
||||
fn base_result(
|
||||
|
||||
+5
-3
@@ -158,10 +158,10 @@ fn build_site(
|
||||
};
|
||||
for media in model.media.values() {
|
||||
let path = format!("media/{}", media.filename());
|
||||
if !media_files.contains_key(&path) {
|
||||
let mut record = writer.write(&path, &media.bytes)?;
|
||||
if let std::collections::btree_map::Entry::Vacant(entry) = media_files.entry(path) {
|
||||
let mut record = writer.write(entry.key(), &media.bytes)?;
|
||||
record["mime"] = serde_json::json!(media.mime);
|
||||
media_files.insert(path, record);
|
||||
entry.insert(record);
|
||||
}
|
||||
}
|
||||
let depth = relative.as_str().split('/').count();
|
||||
@@ -243,6 +243,7 @@ fn build_site(
|
||||
pub struct SnapshotArchive {
|
||||
pub file: std::fs::File,
|
||||
pub len: usize,
|
||||
pub manifest_sha256: String,
|
||||
_scratch: ScratchDir,
|
||||
}
|
||||
|
||||
@@ -290,6 +291,7 @@ pub fn snapshot(
|
||||
Ok(SnapshotArchive {
|
||||
file,
|
||||
len,
|
||||
manifest_sha256: site.manifest_sha256,
|
||||
_scratch: scratch,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -111,6 +111,7 @@ impl ExportSelection {
|
||||
}
|
||||
if (candidate.state != RunState::Succeeded
|
||||
|| !candidate.output_complete
|
||||
|| !candidate.result_complete
|
||||
|| candidate.observation_truncated
|
||||
|| candidate.trace_status == "truncated")
|
||||
&& !self.confirm_partial
|
||||
|
||||
@@ -63,6 +63,12 @@ pub fn product_is_compatible(version: &Version) -> bool {
|
||||
version.major == 3 && version >= &min
|
||||
}
|
||||
|
||||
/// RC.2 is the first public Core release with Execution Events v1.
|
||||
pub fn supports_execution_events(version: &str) -> bool {
|
||||
let first = Version::parse("3.0.0-rc.2").expect("valid Core version");
|
||||
Version::parse(version).is_ok_and(|version| version >= first)
|
||||
}
|
||||
|
||||
/// Validate the negotiated environment for Tool Protocol v1.
|
||||
///
|
||||
/// Absence of `MARQDO_PROTOCOL_*` is allowed for a directly-run development
|
||||
|
||||
+30
-2
@@ -195,7 +195,7 @@ impl ReaderRenderer {
|
||||
<link rel="stylesheet" href="{css}"/>
|
||||
{script}
|
||||
</head>
|
||||
<body class="mq-reader" data-mode="document" data-theme="light" data-annotations="{annotations}" data-size="normal" data-source-status="{status}" data-run-state="{run_state}" data-run-available="{run_available}" data-has-main="{has_main}" data-core-available="{core_available}" data-document="{document}" data-analysis-digest="{analysis_digest}" data-run-timeout="{run_timeout}" data-live="{live}">
|
||||
<body class="mq-reader" data-mode="document" data-theme="light" data-annotations="{annotations}" data-size="normal" data-source-status="{status}" data-run-state="{run_state}" data-run-available="{run_available}" data-has-main="{has_main}" data-core-available="{core_available}" data-execution-events="{execution_events}" data-document="{document}" data-analysis-digest="{analysis_digest}" data-run-timeout="{run_timeout}" data-live="{live}">
|
||||
<a class="mq-skip" href="#mq-main">跳到正文</a>
|
||||
"##,
|
||||
presentation_version = model.version,
|
||||
@@ -210,6 +210,10 @@ impl ReaderRenderer {
|
||||
run_available = if ctx.run_available { "true" } else { "false" },
|
||||
has_main = if has_main { "true" } else { "false" },
|
||||
core_available = if ctx.core_available { "true" } else { "false" },
|
||||
execution_events = model
|
||||
.core_version
|
||||
.as_deref()
|
||||
.is_some_and(crate::protocol::tool_v1::supports_execution_events),
|
||||
document = escape_attr(&relative_path),
|
||||
analysis_digest = escape_attr(&analysis_digest),
|
||||
run_timeout = ctx.run_timeout_secs,
|
||||
@@ -573,9 +577,10 @@ impl ReaderRenderer {
|
||||
<pre id="mq-run-stdout" class="mq-stdout" aria-label="程序标准输出" hidden></pre>
|
||||
<pre id="mq-run-stderr" class="mq-stdout mq-stderr" aria-label="程序标准错误" hidden></pre>
|
||||
<details id="mq-run-trace-wrap" class="mq-run-events-wrap" hidden>
|
||||
<summary>真实 Trace v2 事件</summary>
|
||||
<summary id="mq-run-trace-title">实时结构事件</summary>
|
||||
<ol id="mq-run-events" class="mq-run-events"></ol>
|
||||
</details>
|
||||
<button type="button" class="mq-fn-call mq-export-result" data-action="export-result" id="mq-export-result" hidden>导出文档(含本次结果)</button>
|
||||
</details>
|
||||
"##,
|
||||
);
|
||||
@@ -675,6 +680,7 @@ impl ReaderRenderer {
|
||||
<div id="mq-unsupported-body"></div>
|
||||
</dialog>
|
||||
{run_dialog}
|
||||
{export_dialog}
|
||||
<dialog class="mq-dialog" id="mq-dialog-about" aria-labelledby="mq-about-title">
|
||||
<div class="mq-dialog-head"><h2 id="mq-about-title">关于 Marqdo View</h2><button type="button" class="mq-icon-btn mq-close" data-action="close-dialog" aria-label="关闭关于">×</button></div>
|
||||
<p>版本 {view_version} · Tool Protocol v1 · Analysis v2/v3 · Trace v2。</p>
|
||||
@@ -683,6 +689,11 @@ impl ReaderRenderer {
|
||||
</dialog>
|
||||
"##,
|
||||
csrf = csrf,
|
||||
export_dialog = if ctx.live && ctx.core_available {
|
||||
EXPORT_DIALOG
|
||||
} else {
|
||||
""
|
||||
},
|
||||
files = self.render_file_list(model, ctx),
|
||||
run_dialog = if ctx.core_available {
|
||||
render_run_form_dialog(model, ctx)
|
||||
@@ -1611,6 +1622,23 @@ fn function_params_json(function: &crate::protocol::analysis_v2::SemanticFunctio
|
||||
.to_string()
|
||||
}
|
||||
|
||||
const EXPORT_DIALOG: &str = r##"<dialog class="mq-dialog mq-export-dialog" id="mq-dialog-export" aria-labelledby="mq-export-title">
|
||||
<div class="mq-dialog-head"><h2 id="mq-export-title">导出文档(含本次结果)</h2><button type="button" class="mq-icon-btn mq-close" data-action="close-dialog" aria-label="关闭导出">×</button></div>
|
||||
<p id="mq-export-target" class="mq-export-target"></p>
|
||||
<fieldset class="mq-export-fields">
|
||||
<legend>导出内容</legend>
|
||||
<div id="mq-export-fields"></div>
|
||||
</fieldset>
|
||||
<p class="mq-colophon">输出和参数可能包含令牌、路径或个人信息。请检查所选内容。</p>
|
||||
<label class="mq-export-confirm"><input type="checkbox" id="mq-export-confirm"> 我已检查选中的内容,可以将其写入 ZIP。</label>
|
||||
<label class="mq-export-confirm" id="mq-export-partial-row" hidden><input type="checkbox" id="mq-export-partial"> 我确认导出带有失败或截断标记的部分观察。</label>
|
||||
<p id="mq-export-error" role="alert" hidden></p>
|
||||
<div class="mq-dialog-actions">
|
||||
<button type="button" class="mq-secondary" data-action="close-dialog">取消</button>
|
||||
<button type="button" class="mq-primary" id="mq-export-download" data-action="download-result" disabled>下载 ZIP</button>
|
||||
</div>
|
||||
</dialog>"##;
|
||||
|
||||
fn render_run_form_dialog(model: &PresentationModel, ctx: &RenderContext) -> String {
|
||||
let path = &model.document.identity.relative_path;
|
||||
format!(
|
||||
|
||||
@@ -366,12 +366,16 @@ fn submit_export(state: &ServerState, mut request: Request) -> ViewResult<()> {
|
||||
),
|
||||
("Content-Security-Policy", "default-src 'none'; sandbox"),
|
||||
]);
|
||||
let headers = headers
|
||||
let mut headers: Vec<Header> = headers
|
||||
.into_iter()
|
||||
.map(|(name, value)| {
|
||||
Header::from_bytes(name, value).expect("valid snapshot download header")
|
||||
})
|
||||
.collect();
|
||||
headers.push(
|
||||
Header::from_bytes("X-Marqdo-Manifest-SHA256", archive.manifest_sha256.as_str())
|
||||
.expect("valid manifest digest header"),
|
||||
);
|
||||
let response = Response::new(
|
||||
StatusCode(200),
|
||||
headers,
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
"use strict";
|
||||
|
||||
const assert = require("node:assert/strict");
|
||||
const { execFileSync, spawn } = require("node:child_process");
|
||||
const fs = require("node:fs");
|
||||
const os = require("node:os");
|
||||
const path = require("node:path");
|
||||
const { createInterface } = require("node:readline");
|
||||
const { pathToFileURL } = require("node:url");
|
||||
const { chromium } = require("playwright");
|
||||
|
||||
const root = path.resolve(__dirname, "../..");
|
||||
const core = fs.realpathSync(process.env.MARQDO_BIN);
|
||||
const view = process.env.VIEW_BIN || path.join(root, "target/debug/marqdo-view");
|
||||
const artifactDir = process.env.MQ_SCREENSHOT_DIR;
|
||||
const temp = fs.mkdtempSync(path.join(os.tmpdir(), "mq-complete-browser-"));
|
||||
const project = path.join(temp, "project");
|
||||
const runCount = path.join(temp, "calls");
|
||||
const wrapper = path.join(temp, "counted-core");
|
||||
|
||||
fs.cpSync(path.join(root, "examples/complete-reader"), project, { recursive: true });
|
||||
fs.writeFileSync(wrapper, `#!/usr/bin/env python3
|
||||
import json, os, subprocess, sys, time
|
||||
core, calls = ${JSON.stringify(core)}, ${JSON.stringify(runCount)}
|
||||
args = sys.argv[1:]
|
||||
if args[0] not in ('run','call'):
|
||||
os.execv(core, [core, *args])
|
||||
assert '--event-stream' in args and '--json' not in args
|
||||
with open(calls, 'a') as f: f.write(args[0]+'\\n')
|
||||
if 'write_output' not in args:
|
||||
os.execv(core, [core, *args])
|
||||
with subprocess.Popen([core, *args], stdout=subprocess.PIPE) as child:
|
||||
for line in child.stdout:
|
||||
sys.stdout.buffer.write(line)
|
||||
sys.stdout.buffer.flush()
|
||||
if json.loads(line)['kind'] == 'stdout.chunk': time.sleep(1.2)
|
||||
sys.exit(child.wait())
|
||||
`, { mode: 0o700 });
|
||||
|
||||
async function awaitUrl(server) {
|
||||
const logger = createInterface({ input: server.stderr });
|
||||
return new Promise((resolve, reject) => {
|
||||
const timer = setTimeout(() => reject(new Error("View startup timeout")), 8000);
|
||||
logger.on("line", line => {
|
||||
const url = line.match(/http:\/\/127\.0\.0\.1:\d+\//);
|
||||
if (url) {
|
||||
clearTimeout(timer);
|
||||
resolve(url[0]);
|
||||
}
|
||||
});
|
||||
server.once("exit", (code) => {
|
||||
clearTimeout(timer);
|
||||
reject(new Error("View exited " + code));
|
||||
});
|
||||
server.once("error", reject);
|
||||
});
|
||||
}
|
||||
|
||||
async function screenshot(page, file) {
|
||||
if (!artifactDir) return;
|
||||
fs.mkdirSync(artifactDir, { recursive: true });
|
||||
await page.screenshot({ path: path.join(artifactDir, file), animations: "disabled" });
|
||||
}
|
||||
|
||||
async function imagesLoaded(page, count) {
|
||||
const loaded = await page.evaluate(async () => {
|
||||
const images = Array.from(document.querySelectorAll("img.mq-document-image"));
|
||||
await Promise.all(images.map(image => image.decode()));
|
||||
return images.filter(image => image.complete && image.naturalWidth > 0).length;
|
||||
});
|
||||
assert.equal(loaded, count);
|
||||
}
|
||||
|
||||
async function verifyOffline(browser, url) {
|
||||
const offline = await browser.newContext({ javaScriptEnabled: false, offline: true });
|
||||
const page = await offline.newPage();
|
||||
const requests = [];
|
||||
page.on("request", request => requests.push(request.url()));
|
||||
await page.goto(url);
|
||||
await imagesLoaded(page, 1);
|
||||
assert.equal(await page.locator("math mfrac").count(), 1);
|
||||
assert.equal(await page.locator("script, [data-action=run], [data-action=call-function]").count(), 0);
|
||||
assert.match(await page.locator(".mq-snapshot pre[aria-label=返回值]").innerText(), /4\.0|Float\(4\)/);
|
||||
assert.equal(await page.locator(".mq-snapshot [aria-label=stdout]").count(), 0);
|
||||
await screenshot(page, "offline-snapshot.png");
|
||||
await page.getByRole("link", { name: "误差说明", exact: true }).click();
|
||||
await imagesLoaded(page, 2);
|
||||
assert.equal(decodeURIComponent(new URL(page.url()).hash), "#误差-1");
|
||||
assert.equal(await page.locator(":target").textContent(), "误差");
|
||||
assert.equal(await page.locator(".mq-snapshot").count(), 0);
|
||||
assert.ok(requests.every(request => request.startsWith("file:") || request.startsWith("data:")), requests);
|
||||
await offline.close();
|
||||
}
|
||||
|
||||
(async () => {
|
||||
const server = spawn(view, ["--marqdo-bin", wrapper, project, "--port", "0", "--no-open"], {
|
||||
stdio: ["ignore", "ignore", "pipe"],
|
||||
});
|
||||
let browser;
|
||||
try {
|
||||
const url = await awaitUrl(server);
|
||||
browser = await chromium.launch({ executablePath: process.env.CHROMIUM_BIN || undefined });
|
||||
console.log("Chromium " + browser.version());
|
||||
const context = await browser.newContext({ viewport: { width: 1480, height: 960 }, acceptDownloads: true });
|
||||
const page = await context.newPage();
|
||||
const external = [];
|
||||
const errors = [];
|
||||
page.on("request", request => {
|
||||
if (!request.url().startsWith(url) && !request.url().startsWith("data:") &&
|
||||
!request.url().startsWith("blob:")) external.push(request.url());
|
||||
});
|
||||
page.on("pageerror", error => errors.push(String(error)));
|
||||
await page.goto(url);
|
||||
await imagesLoaded(page, 1);
|
||||
assert.equal(await page.locator("math mfrac").count(), 1);
|
||||
await page.getByRole("link", { name: "误差说明", exact: true }).click();
|
||||
await imagesLoaded(page, 2);
|
||||
assert.equal(await page.locator(":target").textContent(), "误差");
|
||||
assert.equal(decodeURIComponent(new URL(page.url()).hash), "#误差-1");
|
||||
await page.getByRole("link", { name: "返回计算均值", exact: true }).click();
|
||||
assert.match(await page.locator(":target").innerText(), /计算均值/);
|
||||
assert.equal(fs.existsSync(runCount), false);
|
||||
|
||||
await page.locator("h2[id=计算均值] [data-action=call-function]").click();
|
||||
await page.locator("[data-param-name=a]").fill("3");
|
||||
assert.equal(fs.existsSync(runCount), false);
|
||||
await page.locator("[data-action=run-confirm]").click();
|
||||
const result = page.locator(".mq-result-slot #mq-run-panel");
|
||||
await result.locator("[data-action=export-result]").waitFor();
|
||||
assert.equal(await result.getAttribute("data-run-state"), "succeeded");
|
||||
assert.match(await result.locator("#mq-run-summary").innerText(), /Float\(4\.0\)/);
|
||||
assert.equal(fs.readFileSync(runCount, "utf8"), "call\n");
|
||||
await result.scrollIntoViewIfNeeded();
|
||||
await screenshot(page, "live-result.png");
|
||||
|
||||
await result.locator("[data-action=export-result]").click();
|
||||
assert.equal(await page.locator("#mq-export-download").isDisabled(), true);
|
||||
assert.equal(await page.locator("#mq-export-fields [name=arguments]").isChecked(), false);
|
||||
assert.equal(await page.locator("#mq-export-fields [name=stdout]").isChecked(), false);
|
||||
await screenshot(page, "export-preview.png");
|
||||
await page.locator("#mq-export-confirm").check();
|
||||
const downloading = page.waitForEvent("download");
|
||||
await page.locator("#mq-export-download").click();
|
||||
const download = await downloading;
|
||||
assert.equal(fs.readFileSync(runCount, "utf8"), "call\n");
|
||||
const zip = path.join(temp, "snapshot.zip");
|
||||
await download.saveAs(zip);
|
||||
const extracted = path.join(temp, "offline");
|
||||
execFileSync("python3", ["-m", "zipfile", "-e", zip, extracted]);
|
||||
|
||||
await page.locator("h2[id=write_output] [data-action=call-function]").click();
|
||||
await page.locator("[data-action=run-confirm]").click();
|
||||
await page.locator("#mq-run-stdout").waitFor();
|
||||
assert.equal(await result.getAttribute("data-run-state"), "running");
|
||||
assert.equal((await page.locator("#mq-run-stdout").innerText()).trim(), "4");
|
||||
await page.locator("[data-action=export-result]").waitFor();
|
||||
assert.equal(fs.readFileSync(runCount, "utf8"), "call\ncall\n");
|
||||
assert.deepEqual(external, []);
|
||||
assert.deepEqual(errors, []);
|
||||
|
||||
const mobile = await context.newPage();
|
||||
await mobile.setViewportSize({ width: 390, height: 844 });
|
||||
await mobile.goto(url);
|
||||
await imagesLoaded(mobile, 1);
|
||||
assert.equal(await mobile.evaluate(() => document.documentElement.scrollWidth <= innerWidth), true);
|
||||
await screenshot(mobile, "mobile-reader.png");
|
||||
await context.close();
|
||||
server.kill();
|
||||
await verifyOffline(browser, pathToFileURL(path.join(extracted, "index.html")).href);
|
||||
console.log("Live media, cross-document anchors, confirmed call, pre-terminal stdout, private download and offline ZIP: PASS");
|
||||
} finally {
|
||||
if (browser) await browser.close();
|
||||
server.kill();
|
||||
fs.rmSync(temp, { recursive: true, force: true });
|
||||
}
|
||||
})().catch(error => { console.error(error); process.exitCode = 1; });
|
||||
Reference in new issue
Block a user