From 115d1f6c0b736513cb84a3122a1a8cddfd04d253 Mon Sep 17 00:00:00 2001 From: cflmy Date: Sun, 18 Oct 2026 14:47:54 +0800 Subject: [PATCH] feat(view): explicit persist and nested-plan boundary Add per-cell Persist backed by lib/writeback and /api/session/cell/persist. Reject nested foreign.session plans with a top-level diagnostic and tests. --- CHANGELOG.md | 2 +- doc/design/foreign-v3.md | 4 ++- src/host/foreign_doc.rs | 61 ++++++++++++++++++++++++++++++++++++++++ src/view/html.rs | 45 ++++++++++++++++++++++++++--- src/view/mod.rs | 5 ++++ src/view/notebook_api.rs | 10 +++++++ src/view/render.rs | 2 ++ 7 files changed, 123 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a6dcbb6..a81c1ba 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,7 +4,7 @@ ### Added -- **外联 v3 P0/P1**:session eval 支持 raw stdin(Python/Node 持久内核);`foreign.session inputs=` 支持每 cell 独立 stdin;view 增加每卡 stdin 字段与 Interrupt;静态导出使用 inputs 表;新增 plan generation/add/remove/value API、snapshot export/import/replay,以及 `view capture` / `view output --snapshot`。 +- **外联 v3 P0/P1**:session eval 支持 raw stdin(Python/Node 持久内核);`foreign.session inputs=` 支持每 cell 独立 stdin;view 增加每卡 stdin 字段与 Interrupt;静态导出使用 inputs 表;新增 plan generation/add/remove/value API、snapshot export/import/replay,以及 `view capture` / `view output --snapshot`;新增显式 Persist 按钮与 `/api/session/cell/persist`。 ### Fixed diff --git a/doc/design/foreign-v3.md b/doc/design/foreign-v3.md index 2cc2c8b..e5165c4 100644 --- a/doc/design/foreign-v3.md +++ b/doc/design/foreign-v3.md @@ -54,7 +54,9 @@ v3 必须继续满足以下约束,否则不进入实现: | G4 | ✅ 已实现(API) | add/remove/set-value + generation;view 尚未提供 add/remove UI | | G6 | ✅ 已实现(API) | export/import/replay JSON snapshot;view/CLI 尚未做文件封装 | | G9 | ✅ 已实现(CLI/API 基础) | `view capture` + `view output --snapshot`;source hash 校验 | -| G3/G7/G8/G10 | ⏳ 设计已定,未实现 | 见对应章节 | +| G3 | ✅ 边界已实现 | 顶层 plan;嵌套 plan 诊断 | +| G10 | ✅ 显式 persist | `/api/session/cell/persist` + view Persist;不自动写源码 | +| G7/G8 | ⏳ 设计已定,未实现 | 见对应章节 | ## 3. 缺口清单 diff --git a/src/host/foreign_doc.rs b/src/host/foreign_doc.rs index b898721..927dd7f 100644 --- a/src/host/foreign_doc.rs +++ b/src/host/foreign_doc.rs @@ -56,6 +56,8 @@ pub struct Cell { pub last_ms: u64, pub last_ok: bool, pub last_error: String, + /// Value returned by the last successful evaluation, used by explicit persist. + pub last_result: Value, } #[derive(Debug, Clone)] @@ -287,6 +289,7 @@ fn collect_cells(stmts: &[crate::ast::Stmt], out: &mut Vec, seen: &mut Has last_ms: 0, last_ok: false, last_error: String::new(), + last_result: Value::None, }); } crate::ast::Stmt::Branch { arms, .. } => { @@ -625,6 +628,13 @@ impl DocumentSession { c.last_ms = ms; c.last_ok = ok; c.last_error = error.clone(); + c.last_result = field("result") + .filter(|v| !matches!(v, Value::None)) + .unwrap_or_else(|| { + field("stdout") + .and_then(|v| v.reveal_text().map(|s| Value::Text(s.to_string()))) + .unwrap_or(Value::None) + }); c.status = if ok { CellStatus::Clean } else { CellStatus::Error }; } self.seq += 1; @@ -928,6 +938,7 @@ impl DocumentSession { last_ms: 0, last_ok: false, last_error: String::new(), + last_result: Value::None, }); self.order.push(cell.to_string()); self.generation += 1; @@ -1276,6 +1287,28 @@ impl DocumentSession { ])) } + /// Explicitly persist the last cell result through lib/writeback. + pub fn persist_cell(&mut self, cell: &str, key: &str) -> Result { + let i = self + .cell_index(cell) + .ok_or_else(|| format!("unknown cell `{cell}`"))?; + let value = self.cells[i].last_result.clone(); + if matches!(value, Value::None) { + return Err(format!("cell `{cell}` has no result to persist")); + } + let key = if key.is_empty() { cell } else { key }; + let line = self.cells[i].line_end.max(self.cells[i].line_start); + crate::host::writeback::record( + &mut self.host, + &value, + None, + Some(&Value::Text(key.to_string())), + Some(&Value::Int(line as i64)), + )?; + self.generation += 1; + Ok(Value::Bool(true)) + } + pub fn clear_outputs(&mut self) -> Value { for cell in &mut self.cells { cell.runs = 0; @@ -1727,6 +1760,34 @@ console.log(globalThis.kept); s.close(); } + #[test] + fn persist_cell_writes_a_keyed_slot() { + let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")); + let path = root.join(format!( + "target/view-persist-{}-{}.mq.md", + std::process::id(), + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_nanos()) + .unwrap_or(0) + )); + let source = r#"# main + +`a` = +```python +print(950) +``` +"#; + std::fs::write(&path, source).unwrap(); + let mut s = DocumentSession::open(&path, &root).unwrap(); + s.run_cell("a", None).unwrap(); + s.persist_cell("a", "total").unwrap(); + let text = std::fs::read_to_string(&path).unwrap(); + assert!(text.contains("marqdo-out total"), "{text}"); + s.close(); + let _ = std::fs::remove_file(&path); + } + #[test] fn plan_inputs_feed_each_cell() { let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")); diff --git a/src/view/html.rs b/src/view/html.rs index 7431cb8..b74f9e4 100644 --- a/src/view/html.rs +++ b/src/view/html.rs @@ -3300,6 +3300,20 @@ body.notebook-page .code-head .nb-cell-stdin { color: var(--nb-text); font: 0.62rem/1.2 var(--mono); } +body.notebook-page .code-head .nb-persist { + order: 6; + padding: 0.14rem 0.4rem; + border: 1px solid var(--nb-border); + border-radius: 3px; + background: var(--nb-bg); + color: var(--nb-muted); + font: 0.62rem/1.2 var(--sans); + cursor: pointer; +} +body.notebook-page .code-head .nb-persist:hover { + border-color: var(--nb-accent); + color: var(--nb-strong); +} body.notebook-page .code-head .nb-clean { order: 5; padding: 0.14rem 0.4rem; @@ -3315,7 +3329,7 @@ body.notebook-page .code-head .nb-clean:hover { color: var(--nb-strong); } body.notebook-page .code-head .nb-badge { - order: 6; + order: 7; padding: 0.14rem 0.34rem; border: 1px solid var(--nb-border); border-radius: 3px; @@ -3327,7 +3341,7 @@ body.notebook-page .code-head .nb-badge { body.notebook-page .nb-badge.ok { color: var(--nb-success); } body.notebook-page .nb-badge.bad { color: var(--nb-error); } body.notebook-page .code-head .code-actions { - order: 7; + order: 8; display: flex; align-items: center; gap: 0.3rem; @@ -3694,6 +3708,23 @@ body.notebook-page .wb-source-text { color: var(--nb-text); } }).catch(function (e2) { status(String(e2)); }); }); } + function bindPersist(el) { + var btn = el.querySelector(".nb-persist"); + if (!btn || btn.dataset.bound) return; + btn.dataset.bound = "1"; + btn.addEventListener("click", function (e) { + e.preventDefault(); + var name = el.getAttribute("data-code-name") || ""; + if (!name) return; + if (!live) { + status("static export: persist is unavailable"); + return; + } + post("api/session/cell/persist", { cell: name, key: name }).then(function (r) { + status(r.ok ? "persisted " + name : (r.error || "persist failed")); + }).catch(function (e2) { status(String(e2)); }); + }); + } function renderRecord(name, rec) { var el = card(name); if (!el || !rec) return; @@ -3902,11 +3933,17 @@ body.notebook-page .wb-source-text { color: var(--nb-text); } ensureKernel(el, false); }); } - document.querySelectorAll(".code-card").forEach(bindClean); + document.querySelectorAll(".code-card").forEach(function (el) { + bindClean(el); + bindPersist(el); + }); status("static export · preview only"); return; } - document.querySelectorAll(".code-card").forEach(bindClean); + document.querySelectorAll(".code-card").forEach(function (el) { + bindClean(el); + bindPersist(el); + }); bind("nb-run-all", function () { runAll(false); }); bind("nb-restart", function () { runAll(true); }); bind("nb-interrupt", function () { diff --git a/src/view/mod.rs b/src/view/mod.rs index 0262e94..bb46fca 100644 --- a/src/view/mod.rs +++ b/src/view/mod.rs @@ -229,6 +229,11 @@ fn handle(root: &ViewRoot, request: Request) -> Result<()> { notebook_api::api_plan_value(&root.root, body) }) } + "/api/session/cell/persist" => { + return api_debug_post(request, |body| { + notebook_api::api_persist_cell(&root.root, body) + }) + } "/api/session/interrupt" => { return api_debug_post(request, |body| { notebook_api::api_interrupt(&root.root, body) diff --git a/src/view/notebook_api.rs b/src/view/notebook_api.rs index 274554d..04da995 100644 --- a/src/view/notebook_api.rs +++ b/src/view/notebook_api.rs @@ -170,6 +170,16 @@ where } } +pub fn api_persist_cell(root: &Path, body: &str) -> serde_json::Value { + let v = body_value(body); + let cell = v.get("cell").and_then(|x| x.as_str()).unwrap_or(""); + let key = v.get("key").and_then(|x| x.as_str()).unwrap_or(""); + if cell.is_empty() { + return err("missing cell".into()); + } + with_session(root, body, "persisted", |s| s.persist_cell(cell, key)) +} + pub fn api_interrupt(root: &Path, body: &str) -> serde_json::Value { with_session(root, body, "interrupted", |s| s.interrupt()) } diff --git a/src/view/render.rs b/src/view/render.rs index e3232b4..77d561c 100644 --- a/src/view/render.rs +++ b/src/view/render.rs @@ -1260,6 +1260,7 @@ fn render_stmt( `{name}` = {lang} +
{src}
@@ -1539,6 +1540,7 @@ pub(crate) fn render_code_assign_card(name: &str, lang: &str, source: &str) -> S {name} {lang} +
{src}