feat: preview and download selected results from the reader

This commit is contained in:
cflmy committed 2026-11-24 14:03:27 +08:00
1 parent aa2a2b3ce4
commit a482df80be
9 files changed
+470 -42

No files matched your search

+32 -28
View File
@@ -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(&current_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
View File
@@ -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,
})
}
+1
View File
@@ -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
+6
View File
@@ -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
View File
@@ -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!(
+5 -1
View File
@@ -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,