From 3001ed7ba5f1b9a862b45358137c23d46f9e8efd Mon Sep 17 00:00:00 2001 From: cflmy Date: Sun, 18 Oct 2026 01:39:36 +0800 Subject: [PATCH] feat(notebook): document session with shared kernels and view controls MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit D1/D2: 内核表/会话表 parsing, DocumentSession cell index, named/default kernels, shared state + isolation, run_cell/step/run_all/restart/assign, state bridge, journal, POST /api/session/*, and a live-view notebook bar with status badges, per-cell kernel selector, step/run-all and push/pull state form. --- CHANGELOG.md | 1 + doc/design/foreign-kernel.md | 17 +- doc/design/notebook-session.md | 28 +- doc/design/notebook-syntax.md | 2 +- doc/roadmap/foreign-v2.md | 2 +- doc/roadmap/notebook-session.md | 2 +- src/host/foreign_session.rs | 5 +- src/lib.rs | 2 + src/notebook/mod.rs | 919 ++++++++++++++++++++++++++++++++ src/view/html.rs | 242 +++++++++ src/view/mod.rs | 56 ++ src/view/notebook_api.rs | 277 ++++++++++ src/view/render.rs | 2 +- tests/notebook/shared.mq.md | 35 ++ 14 files changed, 1582 insertions(+), 8 deletions(-) create mode 100644 src/notebook/mod.rs create mode 100644 src/view/notebook_api.rs create mode 100644 tests/notebook/shared.mq.md diff --git a/CHANGELOG.md b/CHANGELOG.md index 2ce5ddc..4051750 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,7 @@ - **`lib/foreign` F0/F1**:`invoke` 结构化记录(`ok`/`code`/`stdout`/`stderr`/`ms`/`timed_out`/`truncated`/`result`);`run`/`run_lang` 新增 `env`/`cwd`/`timeout`/`args`/`max_output`;15 个语言预设;`probe`/`register`/`unset`/`load_config`;`.marqdo/foreign.toml`。 - **`lib/foreign` F2**:JSON 进 / JSON 出 `call`;并行 `run_many` / `call_many`(有序、单项隔离、并发上限);`invoke` 的 `input` / `output` / `result` / `result_error`。 - **`lib/foreign` F3/F3.5**:Python / Node 持久会话 `session_open` / `session_eval` / `session_close` / `session_list`;状态桥 `session_set` / `session_get` / `session_names`;会话超时即杀、崩溃隔离、drop 清理。 +- **Notebook D1/D2**:`内核表` / `会话表` 文档原生语法;`DocumentSession`(cell index / 命名内核 / journal / value store);view Notebook 工具栏(Run All / Restart & Run All / Step / State)、状态徽标、内核下拉、Push/Pull 状态表单;`POST /api/session/*`。 - **安全与健壮性**:所有外联入口检查 `exec` 能力;有界 stdout/stderr 读取与截断标记;stdin 写线程;Unix 进程组 / Windows `taskkill /T` 超时清理;shell-like argv 切分。 ### Fixed diff --git a/doc/design/foreign-kernel.md b/doc/design/foreign-kernel.md index 5a40c26..224fcf9 100644 --- a/doc/design/foreign-kernel.md +++ b/doc/design/foreign-kernel.md @@ -2,7 +2,7 @@ | | | |---|---| -| 状态 | **Decided(待实现)** | +| 状态 | **F0–F3.5 已实现** | | 日期 | 2026-10-17 | | 层 | Runtime(`src/foreign/` · `src/host/foreign*` · `lib/foreign.mq.md`) | | 相关 | [foreign-notebook-decisions.md](../research/foreign-notebook-decisions.md) · [notebook-syntax.md](notebook-syntax.md) · [notebook-session.md](notebook-session.md) · [stdlib-foreign.md](stdlib-foreign.md) · [stdlib-subtask.md](stdlib-subtask.md) | @@ -46,6 +46,21 @@ --- +## 1.4 实施状态(2026-10-17) + +| 阶段 | 状态 | 关键文件 | +|---|---|---| +| F0 安全执行 / `invoke` 记录 | ✅ | `src/host/foreign.rs` | +| F1 预设 / probe / register / config | ✅ | `src/foreign/registry.rs` · `src/host/foreign.rs` | +| F2 JSON 桥 / run_many / call_many | ✅ | `src/host/foreign.rs` | +| F3 Python/Node 持久内核 | ✅ | `src/host/foreign_session.rs` | +| F3.5 session_set/get/names | ✅ | 同上 | +| F4 history / view 打磨 / 发布 | 部分 | — | + +测试:`cargo test --lib foreign`(11+)、`cargo test --test gold lib_foreign`(12,python 条件跳过)、`tests/notebook/shared.mq.md` 手工 view 验证。 + +--- + ## 2. 语言与内核模型 ### 2.1 语言预设 diff --git a/doc/design/notebook-session.md b/doc/design/notebook-session.md index 982343f..66c8d41 100644 --- a/doc/design/notebook-session.md +++ b/doc/design/notebook-session.md @@ -2,7 +2,7 @@ | | | |---|---| -| 状态 | **Decided(待实现)** | +| 状态 | **D1–D2 首版已实现;D3/D4 部分** | | 日期 | 2026-10-17 | | 层 | Runtime + Document(view 服务端 / notebook 交互) | | 相关 | [notebook-syntax.md](notebook-syntax.md) · [foreign-kernel.md](foreign-kernel.md) · [foreign-notebook-decisions.md](../research/foreign-notebook-decisions.md) · [view.md](view.md) · [view-debug.md](view-debug.md) · [stdlib-subtask.md](stdlib-subtask.md) | @@ -23,6 +23,32 @@ --- +## 1.1 实施状态(2026-10-17) + +| 能力 | 状态 | 位置 | +|---|---|---| +| `内核表` / `会话表` 解析(中英列名) | ✅ | `src/notebook/mod.rs` | +| cell index(绑定名 / 行号 / source hash) | ✅ | 同上 | +| 命名内核 + 默认内核 + 语言校验 | ✅ | 同上 | +| 同内核共享 / 跨内核隔离 | ✅ | Node 金样例 + 单测 | +| `run_cell` / `step` / `run_all(restart)` | ✅ | `DocumentSession` | +| `restart_kernel` / `assign_kernel` | ✅ | 同上 | +| 状态桥 `push` / `pull` / `state_list` | ✅ | `DocumentSession` + `foreign_session` | +| journal(记录 + API) | ✅(UI 面板待补) | `DocumentSession::journal_json` | +| view 工具栏 / 状态徽标 / 内核下拉 / 状态表单 | ✅ | `src/view/html.rs` | +| `POST /api/session/*` | ✅ | `src/view/notebook_api.rs` | +| cell step | ✅ | 同上 | +| Marqdo statement step | 复用 `marqdo debug`;view 集成待做 | `src/debug` | +| dirty/stale 自动检测 | 部分(assign → dirty;reload 待做) | `src/notebook/mod.rs` | +| writeback 集成 | 待做 | `writeback` | +| replay / 持久化 | 待做 | — | +| Python 会话 | ✅(本机无 python,CI/用户机条件测试) | `src/host/foreign_session.rs` | +| Node 会话 | ✅ | 同上 | + +首版刻意不做:把状态写进 `.mq.md`、自动镜像变量、foreign 行级 debug、跨文档共享内核。 + +--- + ## 2. 两种执行模式 ### 2.1 Program mode(规范) diff --git a/doc/design/notebook-syntax.md b/doc/design/notebook-syntax.md index feb77b5..c79f38a 100644 --- a/doc/design/notebook-syntax.md +++ b/doc/design/notebook-syntax.md @@ -2,7 +2,7 @@ | | | |---|---| -| 状态 | **Decided(v2 目标)** | +| 状态 | **Decided;D1 解析已实现** | | 日期 | 2026-10-17 | | 层 | Document(读取约定) + Runtime(校验) | | 相关 | [foreign-notebook-decisions.md](../research/foreign-notebook-decisions.md) · [notebook-session.md](notebook-session.md) · [foreign-kernel.md](foreign-kernel.md) · [core-surface.md](core-surface.md) · [layers.md](layers.md) | diff --git a/doc/roadmap/foreign-v2.md b/doc/roadmap/foreign-v2.md index ee9b039..05c9dae 100644 --- a/doc/roadmap/foreign-v2.md +++ b/doc/roadmap/foreign-v2.md @@ -2,7 +2,7 @@ | | | |---|---| -| 状态 | **待实施** | +| 状态 | **F0–F3.5 已落地;F4 进行中** | | 日期 | 2026-10-17 | | 层 | Runtime | | 相关 | [foreign-kernel.md](../design/foreign-kernel.md) · [notebook-session.md](../design/notebook-session.md) · [notebook-syntax.md](../design/notebook-syntax.md) · [foreign-notebook-decisions.md](../research/foreign-notebook-decisions.md) · [stdlib-foreign.md](../design/stdlib-foreign.md) · [notebook-session.md](notebook-session.md)(D 层路线) | diff --git a/doc/roadmap/notebook-session.md b/doc/roadmap/notebook-session.md index 38116ae..e5806c2 100644 --- a/doc/roadmap/notebook-session.md +++ b/doc/roadmap/notebook-session.md @@ -2,7 +2,7 @@ | | | |---|---| -| 状态 | **规划中(依赖 F3)** | +| 状态 | **D1–D2 已落地;D3–D5 待做** | | 日期 | 2026-10-17 | | 层 | Runtime + Document(view 服务端 / 前端) | | 相关 | [notebook-session.md](../design/notebook-session.md) · [notebook-syntax.md](../design/notebook-syntax.md) · [foreign-kernel.md](../design/foreign-kernel.md) · [foreign-v2.md](foreign-v2.md) · [foreign-notebook-decisions.md](../research/foreign-notebook-decisions.md) | diff --git a/src/host/foreign_session.rs b/src/host/foreign_session.rs index 18fdeeb..98a35fb 100644 --- a/src/host/foreign_session.rs +++ b/src/host/foreign_session.rs @@ -107,7 +107,8 @@ rl.on("line", async (line) => { return; } if (op === "names") { - const names = Object.keys(globalThis).filter(k => !k.startsWith("__") && typeof globalThis[k] !== "function"); + const skip = new Set(["global","globalThis","process","Buffer","console","require","module","exports","__dirname","__filename","performance","crypto","navigator","fetch","URL","URLSearchParams","TextEncoder","TextDecoder","setTimeout","clearTimeout","setInterval","clearInterval","queueMicrotask","structuredClone","atob","btoa","marqdo_input"]); + const names = Object.keys(globalThis).filter(k => !k.startsWith("__") && !skip.has(k) && typeof globalThis[k] !== "function"); send({ id: rid, ok: true, stdout: "", stderr: "", result: names, error: "" }); return; } @@ -295,6 +296,7 @@ pub fn open( cwd_path.display() )); } + let session_timeout = parse_timeout(timeout, SESSION_TIMEOUT_SECS)?; let mut command = Command::new(&argv[0]); for a in &argv[1..] { command.arg(a); @@ -384,7 +386,6 @@ pub fn open( ctx.foreign_session_seq = seq; let id = format!("s{seq}"); let started_ms = now_ms(); - let session_timeout = parse_timeout(timeout, SESSION_TIMEOUT_SECS)?; let cmd_display = argv[0].clone(); let session = Session { id: id.clone(), diff --git a/src/lib.rs b/src/lib.rs index 04a929f..b0b3fc9 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -34,6 +34,8 @@ pub mod lex; pub mod linalg_ops; pub mod load; pub mod mlsp; +#[cfg(feature = "exec-host")] +pub mod notebook; pub mod parse; pub mod repair; pub mod value; diff --git a/src/notebook/mod.rs b/src/notebook/mod.rs new file mode 100644 index 0000000..81bb118 --- /dev/null +++ b/src/notebook/mod.rs @@ -0,0 +1,919 @@ +//! Document session: cells, kernels, execution journal, state store. +//! +//! The notebook layer reads the conventional `内核表`/`会话表` bindings and the +//! bound code fences. It does not change the Markdown parser. + +use std::collections::{HashMap, HashSet}; +use std::path::{Path, PathBuf}; + +use sha2::{Digest, Sha256}; + +use crate::foreign::registry; +use crate::host::foreign_session; +use crate::host::HostContext; +use crate::parse::parse_source; +use crate::value::Value; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum CellStatus { + Never, + Running, + Clean, + Dirty, + Stale, + Error, + Unlisted, +} + +impl CellStatus { + fn as_str(self) -> &'static str { + match self { + Self::Never => "never", + Self::Running => "running", + Self::Clean => "clean", + Self::Dirty => "dirty", + Self::Stale => "stale", + Self::Error => "error", + Self::Unlisted => "unlisted", + } + } +} + +#[derive(Debug, Clone)] +pub struct Cell { + pub name: String, + pub lang: String, + pub source: String, + pub line_start: u32, + pub line_end: u32, + pub source_hash: String, + pub kernel: String, + pub listed: bool, + pub status: CellStatus, + pub runs: u64, + pub last_ms: u64, + pub last_ok: bool, + pub last_error: String, +} + +#[derive(Debug, Clone)] +pub struct KernelDecl { + pub name: String, + pub lang: String, + pub cmd: Option, + pub implicit: bool, +} + +#[derive(Debug, Clone)] +pub struct JournalRecord { + pub seq: u64, + pub cell: String, + pub kernel: String, + pub lang: String, + pub ok: bool, + pub code: i64, + pub ms: u64, + pub timestamp_ms: i64, + pub error: String, +} + +pub struct DocumentSession { + pub path: PathBuf, + pub cells: Vec, + pub kernels: Vec, + pub order: Vec, + pub journal: Vec, + pub value_store: HashMap, + pub cursor: usize, + pub opened_ms: i64, + host: HostContext, + kernel_sessions: HashMap, + seq: u64, +} + +fn hash_source(source: &str) -> String { + let mut h = Sha256::new(); + h.update(source.as_bytes()); + format!("{:x}", h.finalize()) +} + +fn now_ms() -> i64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_millis() as i64) + .unwrap_or(0) +} + +/// Split a GFM row into trimmed cells. +fn split_row(line: &str) -> Vec { + let t = line.trim(); + let t = t.strip_prefix('|').unwrap_or(t); + let t = t.strip_suffix('|').unwrap_or(t); + t.split('|') + .map(|c| c.trim().trim_matches('`').trim().to_string()) + .collect() +} + +/// Find `` `name` = `` and the first contiguous table after it. +fn table_after(source: &str, name: &str) -> Result>>, String> { + let lines: Vec<&str> = source.lines().collect(); + let needle_a = format!("`{name}`"); + let needle_b = format!("{name} ="); + let mut start = None; + for (i, line) in lines.iter().enumerate() { + let t = line.trim(); + if t.starts_with(&needle_a) && t.contains('=') || t.starts_with(&needle_b) { + start = Some(i + 1); + break; + } + } + let Some(mut i) = start else { + return Ok(None); + }; + while i < lines.len() && !lines[i].trim().starts_with('|') { + if !lines[i].trim().is_empty() && !lines[i].trim().starts_with('|') { + // Prose between the binding and the table is allowed. + } + i += 1; + } + if i >= lines.len() { + return Ok(None); + } + let mut rows = Vec::new(); + let mut header: Option> = None; + while i < lines.len() { + let t = lines[i].trim(); + if !t.starts_with('|') { + break; + } + i += 1; + if t.chars().all(|c| c == '|' || c == '-' || c == ':' || c.is_whitespace()) { + continue; + } + let cells = split_row(t); + if header.is_none() { + header = Some(cells); + continue; + } + let h = header.as_ref().unwrap(); + if cells.len() != h.len() { + return Err(format!( + "table `{name}`: row has {} cells, header has {}", + cells.len(), + h.len() + )); + } + let mut row = HashMap::new(); + for (k, v) in h.iter().zip(cells) { + row.insert(k.clone(), v); + } + rows.push(row); + } + Ok(Some(rows)) +} + +fn table_any( + source: &str, + names: &[&str], +) -> Result>>, String> { + for name in names { + if let Some(rows) = table_after(source, name)? { + return Ok(Some(rows)); + } + } + Ok(None) +} + +fn col<'a>(row: &'a HashMap, names: &[&str]) -> Option<&'a String> { + for n in names { + if let Some(v) = row.get(*n) { + if !v.is_empty() { + return Some(v); + } + } + } + None +} + +fn collect_cells(stmts: &[crate::ast::Stmt], out: &mut Vec, seen: &mut HashSet) -> Result<(), String> { + for stmt in stmts { + match stmt { + crate::ast::Stmt::Assign { + name, + value: crate::ast::Expr::Code(c), + span, + end_line, + } => { + if !seen.insert(name.clone()) { + return Err(format!( + "cell `{name}` is assigned more than once (line {})", + span.line + )); + } + out.push(Cell { + name: name.clone(), + lang: c.lang.clone(), + source: c.source.clone(), + line_start: span.line, + line_end: *end_line, + source_hash: hash_source(&c.source), + kernel: String::new(), + listed: false, + status: CellStatus::Never, + runs: 0, + last_ms: 0, + last_ok: false, + last_error: String::new(), + }); + } + crate::ast::Stmt::Branch { arms, .. } => { + for arm in arms { + collect_cells(&arm.body, out, seen)?; + } + } + crate::ast::Stmt::While { body, .. } | crate::ast::Stmt::ForEach { body, .. } => { + collect_cells(body, out, seen)?; + } + _ => {} + } + } + Ok(()) +} + +impl DocumentSession { + pub fn open(path: &Path, root: &Path) -> Result { + let source = std::fs::read_to_string(path) + .map_err(|e| format!("read {}: {e}", path.display()))?; + let module = parse_source(&source).map_err(|e| format!("parse {}: {e}", path.display()))?; + let entry = module + .functions + .iter() + .find(|f| f.name == "main" && f.is_object()) + .or_else(|| { + let objs: Vec<_> = module.functions.iter().filter(|f| f.is_object()).collect(); + if objs.len() == 1 { + Some(objs[0]) + } else { + None + } + }) + .ok_or_else(|| "notebook: no `# main` (or sole object) to index".to_string())?; + let mut cells = Vec::new(); + let mut seen = HashSet::new(); + collect_cells(&entry.body, &mut cells, &mut seen)?; + if cells.is_empty() { + return Err("notebook: no bound code fences (`name` = + ```lang)".into()); + } + + let mut kernels: Vec = Vec::new(); + let mut kernel_map: HashMap = HashMap::new(); + if let Some(rows) = table_any(&source, &["内核表", "kernels", "Kernels"])? { + if rows.is_empty() { + return Err("内核表: at least one kernel row is required".into()); + } + for row in rows { + let name = col(&row, &["名称", "Name", "name"]) + .ok_or_else(|| "内核表: missing 名称/Name".to_string())? + .clone(); + let lang = col(&row, &["语言", "Language", "language", "lang"]) + .ok_or_else(|| format!("内核表[{name}]: missing 语言/Language"))? + .clone(); + let lang = registry::canonical(&lang); + let cmd = col(&row, &["命令", "Command", "command", "cmd"]).cloned(); + if kernel_map.contains_key(&name) { + return Err(format!("内核表: kernel `{name}` is declared twice")); + } + let decl = KernelDecl { + name: name.clone(), + lang, + cmd, + implicit: false, + }; + kernel_map.insert(name.clone(), decl.clone()); + kernels.push(decl); + } + } + + let mut order: Vec = Vec::new(); + let session_rows = table_any(&source, &["会话表", "session", "Session"])?; + if let Some(rows) = session_rows { + if rows.is_empty() { + return Err("会话表: at least one cell row is required".into()); + } + let by_name: HashMap = cells + .iter() + .enumerate() + .map(|(i, c)| (c.name.clone(), i)) + .collect(); + let mut listed = HashSet::new(); + for row in rows { + let cell_name = col(&row, &["单元", "Cell", "cell", "单元名"]) + .ok_or_else(|| "会话表: missing 单元/Cell".to_string())? + .clone(); + let kernel_name = col(&row, &["内核", "Kernel", "kernel"]) + .ok_or_else(|| format!("会话表[{cell_name}]: missing 内核/Kernel"))? + .clone(); + let Some(&ci) = by_name.get(&cell_name) else { + return Err(format!("会话表: unknown cell `{cell_name}`")); + }; + if !listed.insert(cell_name.clone()) { + return Err(format!("会话表: cell `{cell_name}` is listed twice")); + } + let kernel = resolve_kernel(&mut kernels, &mut kernel_map, &kernel_name)?; + if registry::canonical(&cells[ci].lang) != registry::canonical(&kernel.lang) { + return Err(format!( + "会话表: cell `{cell_name}` ({}) cannot use kernel `{}` ({})", + cells[ci].lang, kernel.name, kernel.lang + )); + } + cells[ci].kernel = kernel.name.clone(); + cells[ci].listed = true; + order.push(cell_name); + } + for cell in &mut cells { + if !cell.listed { + cell.status = CellStatus::Unlisted; + } + } + } else { + for cell in &mut cells { + let kernel = ensure_default_kernel( + &mut kernels, + &mut kernel_map, + &cell.lang, + ); + cell.kernel = kernel; + cell.listed = true; + order.push(cell.name.clone()); + } + } + + let mut host = HostContext::default(); + let doc_dir = path.parent().unwrap_or_else(|| Path::new(".")); + host.cwd = doc_dir.to_path_buf(); + host.fs_root = Some(root.to_path_buf()); + host.entry_path = Some(path.to_path_buf()); + host.entry_source = Some(source); + + Ok(Self { + path: path.to_path_buf(), + cells, + kernels, + order, + journal: Vec::new(), + value_store: HashMap::new(), + cursor: 0, + opened_ms: now_ms(), + host, + kernel_sessions: HashMap::new(), + seq: 0, + }) + } + + pub fn title(&self) -> String { + self.path + .file_stem() + .and_then(|s| s.to_str()) + .unwrap_or("session") + .trim_end_matches(".mq") + .to_string() + } + + fn cell_index(&self, name: &str) -> Option { + self.cells.iter().position(|c| c.name == name) + } + + fn kernel(&self, name: &str) -> Option<&KernelDecl> { + self.kernels.iter().find(|k| k.name == name) + } + + fn ensure_kernel_session(&mut self, kernel_name: &str) -> Result { + if let Some(id) = self.kernel_sessions.get(kernel_name) { + if self.host.foreign_sessions.contains_key(id) { + return Ok(id.clone()); + } + } + let decl = self + .kernel(kernel_name) + .ok_or_else(|| format!("unknown kernel `{kernel_name}`"))? + .clone(); + let cmd_value = decl.cmd.map(Value::Text); + let lang = Value::Text(decl.lang.clone()); + let id = foreign_session::open( + &mut self.host, + &lang, + cmd_value.as_ref(), + None, + None, + None, + )?; + let id = match id { + Value::Text(s) => s, + _ => return Err("session_open returned non-text id".into()), + }; + self.kernel_sessions + .insert(kernel_name.to_string(), id.clone()); + Ok(id) + } + + fn record_result(&mut self, cell: &str, kernel: &str, record: &Value) -> Result<(), String> { + let field = |k: &str| match record { + Value::Map(entries) => entries + .iter() + .find(|(kk, _)| kk == k) + .map(|(_, v)| v.clone()), + _ => None, + }; + let ok = matches!(field("ok"), Some(Value::Bool(true))); + let ms = match field("ms") { + Some(Value::Int(n)) => n as u64, + _ => 0, + }; + let error = field("error") + .and_then(|v| v.reveal_text().map(|s| s.to_string())) + .unwrap_or_default(); + let code = match field("code") { + Some(Value::Int(n)) => n, + _ => 0, + }; + let lang = self + .cell_index(cell) + .map(|i| self.cells[i].lang.clone()) + .unwrap_or_default(); + if let Some(i) = self.cell_index(cell) { + let c = &mut self.cells[i]; + c.runs += 1; + c.last_ms = ms; + c.last_ok = ok; + c.last_error = error.clone(); + c.status = if ok { CellStatus::Clean } else { CellStatus::Error }; + } + self.seq += 1; + self.journal.push(JournalRecord { + seq: self.seq, + cell: cell.to_string(), + kernel: kernel.to_string(), + lang, + ok, + code, + ms, + timestamp_ms: now_ms(), + error, + }); + Ok(()) + } + + pub fn run_cell(&mut self, cell_name: &str, kernel_override: Option<&str>) -> Result { + let ci = self + .cell_index(cell_name) + .ok_or_else(|| format!("unknown cell `{cell_name}`"))?; + if !self.cells[ci].listed && kernel_override.is_none() { + return Err(format!("cell `{cell_name}` is not in 会话表")); + } + let kernel = match kernel_override { + Some(k) => { + if self.kernel(k).is_none() { + return Err(format!("unknown kernel `{k}`")); + } + let ci_lang = registry::canonical(&self.cells[ci].lang); + let klang = registry::canonical( + &self.kernel(k).map(|d| d.lang.clone()).unwrap_or_default(), + ); + if ci_lang != klang { + return Err(format!( + "cell `{cell_name}` ({}) cannot run in kernel `{k}` ({klang})", + self.cells[ci].lang + )); + } + self.cells[ci].kernel = k.to_string(); + self.cells[ci].listed = true; + k.to_string() + } + None => self.cells[ci].kernel.clone(), + }; + self.cells[ci].status = CellStatus::Running; + let result = (|| -> Result { + let id = self.ensure_kernel_session(&kernel)?; + let source = Value::Text(self.cells[ci].source.clone()); + let record = foreign_session::eval( + &mut self.host, + &Value::Text(id), + None, + Some(&source), + None, + None, + )?; + self.record_result(cell_name, &kernel, &record)?; + Ok(record) + })(); + if result.is_err() { + self.cells[ci].status = CellStatus::Error; + } + result + } + + pub fn step(&mut self) -> Result { + if self.cursor >= self.order.len() { + return Ok(Value::Map(vec![ + ("done".into(), Value::Bool(true)), + ("cursor".into(), Value::Int(self.cursor as i64)), + ])); + } + let name = self.order[self.cursor].clone(); + let record = self.run_cell(&name, None)?; + let ci = self.cell_index(&name).unwrap_or(0); + let kernel = self.cells[ci].kernel.clone(); + self.cursor += 1; + let mut fields = match record { + Value::Map(m) => m, + other => vec![("result".into(), other)], + }; + fields.push(("cell".into(), Value::Text(name))); + fields.push(("kernel".into(), Value::Text(kernel))); + fields.push(("cursor".into(), Value::Int(self.cursor as i64))); + Ok(Value::Map(fields)) + } + + pub fn run_all(&mut self, restart: bool) -> Result { + if restart { + self.restart_all()?; + } + self.cursor = 0; + let mut records = Vec::new(); + let mut failed = 0i64; + for name in self.order.clone() { + let record = self.run_cell(&name, None)?; + let ok = match &record { + Value::Map(m) => matches!( + m.iter().find(|(k, _)| k == "ok").map(|(_, v)| v), + Some(Value::Bool(true)) + ), + _ => false, + }; + if !ok { + failed += 1; + } + let mut m = match record { + Value::Map(m) => m, + other => vec![("result".into(), other)], + }; + m.push(("cell".into(), Value::Text(name))); + records.push(Value::Map(m)); + self.cursor += 1; + } + Ok(Value::Map(vec![ + ("ok".into(), Value::Bool(failed == 0)), + ("ran".into(), Value::Int(self.order.len() as i64)), + ("failed".into(), Value::Int(failed)), + ("records".into(), Value::List(records)), + ])) + } + + pub fn restart_kernel(&mut self, name: &str) -> Result { + if let Some(id) = self.kernel_sessions.remove(name) { + let _ = foreign_session::close(&mut self.host, &Value::Text(id)); + } + for c in &mut self.cells { + if c.kernel == name { + c.status = CellStatus::Never; + c.last_error.clear(); + } + } + Ok(Value::Bool(true)) + } + + pub fn restart_all(&mut self) -> Result { + let names: Vec = self.kernel_sessions.keys().cloned().collect(); + for name in names { + self.restart_kernel(&name)?; + } + self.cursor = 0; + for c in &mut self.cells { + c.status = if c.listed { CellStatus::Never } else { CellStatus::Unlisted }; + } + Ok(Value::Bool(true)) + } + + pub fn assign_kernel(&mut self, cell: &str, kernel: &str) -> Result { + let ci = self + .cell_index(cell) + .ok_or_else(|| format!("unknown cell `{cell}`"))?; + let decl = self + .kernel(kernel) + .ok_or_else(|| format!("unknown kernel `{kernel}`"))? + .clone(); + if registry::canonical(&self.cells[ci].lang) != registry::canonical(&decl.lang) { + return Err(format!( + "cell `{cell}` ({}) cannot use kernel `{kernel}` ({})", + self.cells[ci].lang, decl.lang + )); + } + self.cells[ci].kernel = kernel.to_string(); + self.cells[ci].listed = true; + self.cells[ci].status = CellStatus::Dirty; + Ok(Value::None) + } + + pub fn state_list(&mut self) -> Result { + let marqdo = self + .value_store + .iter() + .map(|(k, v)| (k.clone(), v.clone())) + .collect::>(); + let mut kernels = Vec::new(); + for k in &self.kernels { + let live = self.kernel_sessions.get(&k.name).cloned(); + let mut vars = Vec::new(); + if let Some(id) = live { + if self.host.foreign_sessions.contains_key(&id) { + if let Ok(names) = foreign_session::names(&mut self.host, &Value::Text(id)) { + if let Value::List(xs) = names { + vars = xs; + } + } + } + } + kernels.push(Value::Map(vec![ + ("name".into(), Value::Text(k.name.clone())), + ("lang".into(), Value::Text(k.lang.clone())), + ("vars".into(), Value::List(vars)), + ])); + } + Ok(Value::Map(vec![ + ("marqdo".into(), Value::Map(marqdo)), + ("kernels".into(), Value::List(kernels)), + ])) + } + + pub fn push_value(&mut self, kernel: &str, name: &str, value: Value) -> Result { + let id = self.ensure_kernel_session(kernel)?; + foreign_session::set( + &mut self.host, + &Value::Text(id), + &Value::Text(name.to_string()), + &value, + )?; + self.value_store.insert(name.to_string(), value); + Ok(Value::None) + } + + pub fn pull_value(&mut self, kernel: &str, name: &str) -> Result { + let id = self.ensure_kernel_session(kernel)?; + let value = foreign_session::get( + &mut self.host, + &Value::Text(id), + &Value::Text(name.to_string()), + )?; + self.value_store + .insert(name.to_string(), value.clone()); + Ok(value) + } + + pub fn summary(&self) -> Value { + let cells = self + .cells + .iter() + .map(|c| { + Value::Map(vec![ + ("name".into(), Value::Text(c.name.clone())), + ("lang".into(), Value::Text(c.lang.clone())), + ("kernel".into(), Value::Text(c.kernel.clone())), + ("listed".into(), Value::Bool(c.listed)), + ("status".into(), Value::Text(c.status.as_str().into())), + ("line_start".into(), Value::Int(c.line_start as i64)), + ("line_end".into(), Value::Int(c.line_end as i64)), + ("runs".into(), Value::Int(c.runs as i64)), + ("last_ms".into(), Value::Int(c.last_ms as i64)), + ("last_ok".into(), Value::Bool(c.last_ok)), + ("last_error".into(), Value::Text(c.last_error.clone())), + ]) + }) + .collect(); + let kernels = self + .kernels + .iter() + .map(|k| { + Value::Map(vec![ + ("name".into(), Value::Text(k.name.clone())), + ("lang".into(), Value::Text(k.lang.clone())), + ("implicit".into(), Value::Bool(k.implicit)), + ( + "live".into(), + Value::Bool(self.kernel_sessions.contains_key(&k.name)), + ), + ]) + }) + .collect(); + Value::Map(vec![ + ("title".into(), Value::Text(self.title())), + ("path".into(), Value::Text(self.path.display().to_string())), + ("cells".into(), Value::List(cells)), + ("kernels".into(), Value::List(kernels)), + ("order".into(), Value::List( + self.order.iter().cloned().map(Value::Text).collect(), + )), + ("cursor".into(), Value::Int(self.cursor as i64)), + ("journal".into(), Value::List( + self.journal + .iter() + .map(|j| { + Value::Map(vec![ + ("seq".into(), Value::Int(j.seq as i64)), + ("cell".into(), Value::Text(j.cell.clone())), + ("kernel".into(), Value::Text(j.kernel.clone())), + ("lang".into(), Value::Text(j.lang.clone())), + ("ok".into(), Value::Bool(j.ok)), + ("code".into(), Value::Int(j.code)), + ("ms".into(), Value::Int(j.ms as i64)), + ("timestamp_ms".into(), Value::Int(j.timestamp_ms)), + ("error".into(), Value::Text(j.error.clone())), + ]) + }) + .collect(), + )), + ("opened_ms".into(), Value::Int(self.opened_ms)), + ]) + } + + pub fn journal_json(&self) -> Value { + Value::List( + self.journal + .iter() + .map(|j| { + Value::Map(vec![ + ("seq".into(), Value::Int(j.seq as i64)), + ("cell".into(), Value::Text(j.cell.clone())), + ("kernel".into(), Value::Text(j.kernel.clone())), + ("lang".into(), Value::Text(j.lang.clone())), + ("ok".into(), Value::Bool(j.ok)), + ("code".into(), Value::Int(j.code)), + ("ms".into(), Value::Int(j.ms as i64)), + ("timestamp_ms".into(), Value::Int(j.timestamp_ms)), + ("error".into(), Value::Text(j.error.clone())), + ]) + }) + .collect(), + ) + } + + pub fn close(&mut self) { + let ids: Vec = self.kernel_sessions.values().cloned().collect(); + for id in ids { + let _ = foreign_session::close(&mut self.host, &Value::Text(id)); + } + self.kernel_sessions.clear(); + } +} + +fn resolve_kernel( + kernels: &mut Vec, + map: &mut HashMap, + name: &str, +) -> Result { + if let Some(k) = map.get(name) { + return Ok(k.clone()); + } + if registry::preset_spec(name).is_some() { + let lang = registry::canonical(name); + let decl = KernelDecl { + name: lang.clone(), + lang, + cmd: None, + implicit: true, + }; + map.insert(decl.name.clone(), decl.clone()); + kernels.push(decl.clone()); + return Ok(decl); + } + Err(format!( + "会话表: kernel `{name}` is not declared in 内核表" + )) +} + +fn ensure_default_kernel( + kernels: &mut Vec, + map: &mut HashMap, + lang: &str, +) -> String { + let lang = registry::canonical(lang); + let name = format!("default:{lang}"); + if !map.contains_key(&name) { + let decl = KernelDecl { + name: name.clone(), + lang, + cmd: None, + implicit: true, + }; + map.insert(name.clone(), decl.clone()); + kernels.push(decl); + } + name +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn rows_parse() { + assert_eq!(split_row("| a | b |"), vec!["a", "b"]); + assert_eq!(split_row("| `a` | b |"), vec!["a", "b"]); + } + + #[test] + fn table_after_finds_rows() { + let src = "# main\n\n`内核表` =\n\n| 名称 | 语言 |\n|---|---|\n| 分析 | python |\n"; + let rows = table_after(src, "内核表").unwrap().unwrap(); + assert_eq!(rows.len(), 1); + assert_eq!(rows[0].get("名称").map(|s| s.as_str()), Some("分析")); + } + + fn node_available() -> bool { + std::process::Command::new("node") + .args(["-e", "process.exit(0)"]) + .output() + .map(|o| o.status.success()) + .unwrap_or(false) + } + + fn field(record: &Value, key: &str) -> Option { + match record { + Value::Map(entries) => entries + .iter() + .find(|(k, _)| k == key) + .map(|(_, v)| v.clone()), + _ => None, + } + } + + #[test] + fn shared_state_and_isolation() { + if !node_available() { + return; + } + let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")); + let path = root.join(format!( + "target/notebook-test-{}-{}.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 + +`内核表` = + +| 名称 | 语言 | 命令 | 说明 | +|------|------|------|------| +| 分析 | node | | shared | +| 绘图 | node | | isolated | + +`会话表` = + +| 单元 | 内核 | 说明 | +|------|------|------| +| 设置 | 分析 | write | +| 读取 | 分析 | read | +| 隔离 | 绘图 | isolated | + +`设置` = +```node +let shared = 41; +``` + +`读取` = +```node +console.log(shared + 1); +``` + +`隔离` = +```node +console.log(typeof shared === "undefined" ? "isolated" : "leaked"); +``` +"#; + std::fs::write(&path, source).unwrap(); + let mut s = DocumentSession::open(&path, &root).unwrap(); + assert_eq!( + s.order, + vec!["设置".to_string(), "读取".to_string(), "隔离".to_string()] + ); + let r = s.run_cell("设置", None).unwrap(); + assert_eq!(field(&r, "ok"), Some(Value::Bool(true))); + let r = s.run_cell("读取", None).unwrap(); + assert_eq!( + field(&r, "stdout").and_then(|v| v.reveal_text().map(|s| s.to_string())), + Some("42\n".to_string()) + ); + let r = s.run_cell("隔离", None).unwrap(); + assert_eq!( + field(&r, "stdout").and_then(|v| v.reveal_text().map(|s| s.to_string())), + Some("isolated\n".to_string()) + ); + s.restart_all().unwrap(); + let r = s.run_cell("读取", None).unwrap(); + assert_eq!(field(&r, "ok"), Some(Value::Bool(false))); + s.close(); + let _ = std::fs::remove_file(&path); + } +} diff --git a/src/view/html.rs b/src/view/html.rs index 8cb4cbe..15672d6 100644 --- a/src/view/html.rs +++ b/src/view/html.rs @@ -2824,6 +2824,219 @@ pub fn page_index(files: &[PathBuf], only: Option<&Path>, links: &LinkMode) -> S layout("index", &nav, &main) } +fn notebook_ui() -> &'static str { + r#" + + + +"# +} + pub fn page_file(files: &[PathBuf], rel: &str, vm: &FileViewModel, links: &LinkMode) -> String { let nav = nav_html(files, Some(rel), links); let (status, status_label, out_text) = if vm.awaiting_input { @@ -2963,6 +3176,11 @@ pub fn page_file(files: &[PathBuf], rel: &str, vm: &FileViewModel, links: &LinkM let trace_safe = vm .trace_json .replace(" @@ -2973,6 +3191,7 @@ window.MARQDO_AUTO_STREAM = {auto_stream};

{title}{status_label}

{rel}

+{notebook}

Structure

{structure_block} @@ -3002,6 +3221,7 @@ window.MARQDO_AUTO_STREAM = {auto_stream}; status = status, status_label = status_label, rel = escape(rel), + notebook = notebook, structure_block = structure_block, stdin_panel = stdin_panel, stream_panel = stream_panel, @@ -3195,3 +3415,25 @@ mod plan_card_tests { assert!(!html.contains("pp-type\">delta"), "{html}"); } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn notebook_ui_has_controls() { + let ui = notebook_ui(); + for id in [ + "nb-run-all", + "nb-restart", + "nb-step", + "nb-state", + "nb-kernel-input", + "nb-push", + "nb-pull", + "nb-state-out", + ] { + assert!(ui.contains(id), "notebook UI missing {id}"); + } + } +} diff --git a/src/view/mod.rs b/src/view/mod.rs index eb5530a..08c0786 100644 --- a/src/view/mod.rs +++ b/src/view/mod.rs @@ -6,6 +6,7 @@ mod debug_api; mod debug_page; mod document; mod html; +mod notebook_api; mod output; mod render; @@ -173,6 +174,61 @@ fn handle(root: &ViewRoot, request: Request) -> Result<()> { match path_part { "/api/foreign-run" => return api_foreign_run(root, request), "/api/run" => return api_run(root, request), + "/api/session/open" => { + return api_debug_post(request, |body| { + notebook_api::api_open(&root.root, body) + }) + } + "/api/session/close" => { + return api_debug_post(request, |body| { + notebook_api::api_close(&root.root, body) + }) + } + "/api/session/cell/run" => { + return api_debug_post(request, |body| { + notebook_api::api_cell_run(&root.root, body) + }) + } + "/api/session/cell/step" => { + return api_debug_post(request, |body| { + notebook_api::api_cell_step(&root.root, body) + }) + } + "/api/session/run_all" => { + return api_debug_post(request, |body| { + notebook_api::api_run_all(&root.root, body) + }) + } + "/api/session/kernel/restart" => { + return api_debug_post(request, |body| { + notebook_api::api_kernel_restart(&root.root, body) + }) + } + "/api/session/kernel/assign" => { + return api_debug_post(request, |body| { + notebook_api::api_assign(&root.root, body) + }) + } + "/api/session/state/list" => { + return api_debug_post(request, |body| { + notebook_api::api_state_list(&root.root, body) + }) + } + "/api/session/state/push" => { + return api_debug_post(request, |body| { + notebook_api::api_state_push(&root.root, body) + }) + } + "/api/session/state/pull" => { + return api_debug_post(request, |body| { + notebook_api::api_state_pull(&root.root, body) + }) + } + "/api/session/journal" => { + return api_debug_post(request, |body| { + notebook_api::api_journal(&root.root, body) + }) + } _ => { let resp = Response::from_string("method not allowed").with_status_code(StatusCode(405)); diff --git a/src/view/notebook_api.rs b/src/view/notebook_api.rs new file mode 100644 index 0000000..2956ab7 --- /dev/null +++ b/src/view/notebook_api.rs @@ -0,0 +1,277 @@ +//! Live-view notebook session APIs. + +use std::collections::HashMap; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, Mutex, OnceLock}; + +use crate::host::json::{json_to_value, value_to_json}; +use crate::notebook::DocumentSession; +use crate::value::Value; + +fn sessions() -> &'static Mutex>>> { + static S: OnceLock>>>> = OnceLock::new(); + S.get_or_init(|| Mutex::new(HashMap::new())) +} + +fn body_value(body: &str) -> serde_json::Value { + serde_json::from_str(body).unwrap_or(serde_json::Value::Null) +} + +fn path_of(root: &Path, v: &serde_json::Value) -> Result<(String, PathBuf), String> { + let rel = v + .get("path") + .and_then(|p| p.as_str()) + .unwrap_or("") + .trim() + .to_string(); + if rel.is_empty() { + return Err("missing path".into()); + } + let abs = root.join(rel.replace('/', std::path::MAIN_SEPARATOR_STR)); + if !abs.is_file() { + return Err(format!("file not found: {rel}")); + } + Ok((rel, abs)) +} + +fn get_or_open(root: &Path, abs: &Path) -> Result>, String> { + let key = abs.display().to_string(); + let mut map = sessions().lock().map_err(|_| "session lock poisoned".to_string())?; + if let Some(s) = map.get(&key) { + return Ok(Arc::clone(s)); + } + let session = DocumentSession::open(abs, root)?; + let arc = Arc::new(Mutex::new(session)); + map.insert(key, Arc::clone(&arc)); + Ok(arc) +} + +fn json_value(v: &Value) -> serde_json::Value { + value_to_json(v).unwrap_or(serde_json::Value::Null) +} + +fn ok_session(session: &DocumentSession, extra: serde_json::Value) -> serde_json::Value { + let mut out = serde_json::json!({ + "ok": true, + "session": json_value(&session.summary()), + }); + if let (Some(dst), Some(src)) = (out.as_object_mut(), extra.as_object()) { + for (k, v) in src { + dst.insert(k.clone(), v.clone()); + } + } + out +} + +fn err(error: String) -> serde_json::Value { + serde_json::json!({ "ok": false, "error": error }) +} + +pub fn api_open(root: &Path, body: &str) -> serde_json::Value { + let v = body_value(body); + let (_rel, abs) = match path_of(root, &v) { + Ok(p) => p, + Err(e) => return err(e), + }; + match get_or_open(root, &abs) { + Ok(s) => match s.lock() { + Ok(sess) => ok_session(&sess, serde_json::json!({})), + Err(_) => err("session lock poisoned".into()), + }, + Err(e) => err(e), + } +} + +pub fn api_close(root: &Path, body: &str) -> serde_json::Value { + let v = body_value(body); + let (_rel, abs) = match path_of(root, &v) { + Ok(p) => p, + Err(e) => return err(e), + }; + let key = abs.display().to_string(); + let removed = sessions() + .lock() + .ok() + .and_then(|mut m| m.remove(&key)); + if let Some(arc) = removed { + if let Ok(mut s) = arc.lock() { + s.close(); + } + } + serde_json::json!({ "ok": true }) +} + +fn with_session(root: &Path, body: &str, action: &str, f: F) -> serde_json::Value +where + F: FnOnce(&mut DocumentSession) -> Result, +{ + let v = body_value(body); + let (_rel, abs) = match path_of(root, &v) { + Ok(p) => p, + Err(e) => return err(e), + }; + let arc = match get_or_open(root, &abs) { + Ok(s) => s, + Err(e) => return err(e), + }; + let mut sess = match arc.lock() { + Ok(s) => s, + Err(_) => return err("session lock poisoned".into()), + }; + match f(&mut sess) { + Ok(value) => { + let mut extra = serde_json::Map::new(); + extra.insert(action.into(), json_value(&value)); + ok_session(&sess, serde_json::Value::Object(extra)) + } + Err(e) => err(e), + } +} + +pub fn api_cell_run(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 kernel = v.get("kernel").and_then(|x| x.as_str()).filter(|s| !s.is_empty()); + if cell.is_empty() { + return err("missing cell".into()); + } + with_session(root, body, "record", |s| s.run_cell(cell, kernel)) +} + +pub fn api_cell_step(root: &Path, body: &str) -> serde_json::Value { + with_session(root, body, "record", |s| s.step()) +} + +pub fn api_run_all(root: &Path, body: &str) -> serde_json::Value { + let v = body_value(body); + let restart = v.get("restart").and_then(|x| x.as_bool()).unwrap_or(false); + with_session(root, body, "summary", |s| s.run_all(restart)) +} + +pub fn api_kernel_restart(root: &Path, body: &str) -> serde_json::Value { + let v = body_value(body); + let kernel = v.get("kernel").and_then(|x| x.as_str()).unwrap_or(""); + if kernel.is_empty() { + return err("missing kernel".into()); + } + with_session(root, body, "value", |s| s.restart_kernel(kernel)) +} + +pub fn api_assign(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 kernel = v.get("kernel").and_then(|x| x.as_str()).unwrap_or(""); + if cell.is_empty() || kernel.is_empty() { + return err("missing cell/kernel".into()); + } + with_session(root, body, "value", |s| s.assign_kernel(cell, kernel)) +} + +pub fn api_state_list(root: &Path, body: &str) -> serde_json::Value { + with_session(root, body, "state", |s| s.state_list()) +} + +pub fn api_state_push(root: &Path, body: &str) -> serde_json::Value { + let v = body_value(body); + let kernel = v.get("kernel").and_then(|x| x.as_str()).unwrap_or(""); + let name = v.get("name").and_then(|x| x.as_str()).unwrap_or(""); + if kernel.is_empty() || name.is_empty() { + return err("missing kernel/name".into()); + } + let value = match v.get("value") { + Some(v) => match json_to_value(v) { + Ok(v) => v, + Err(e) => return err(e), + }, + None => Value::None, + }; + with_session(root, body, "value", |s| s.push_value(kernel, name, value)) +} + +pub fn api_state_pull(root: &Path, body: &str) -> serde_json::Value { + let v = body_value(body); + let kernel = v.get("kernel").and_then(|x| x.as_str()).unwrap_or(""); + let name = v.get("name").and_then(|x| x.as_str()).unwrap_or(""); + if kernel.is_empty() || name.is_empty() { + return err("missing kernel/name".into()); + } + with_session(root, body, "value", |s| s.pull_value(kernel, name)) +} + +pub fn api_journal(root: &Path, body: &str) -> serde_json::Value { + with_session(root, body, "journal", |s| Ok(s.journal_json())) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn node_available() -> bool { + std::process::Command::new("node") + .args(["-e", "process.exit(0)"]) + .output() + .map(|o| o.status.success()) + .unwrap_or(false) + } + + fn open_body() -> &'static str { + r#"{"path":"shared.mq.md"}"# + } + + #[test] + fn api_shared_state_and_kernel_switch() { + if !node_available() { + return; + } + let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/notebook"); + let open = api_open(&root, open_body()); + assert_eq!(open.get("ok").and_then(|v| v.as_bool()), Some(true), "{open:?}"); + let run = api_cell_run( + &root, + r#"{"path":"shared.mq.md","cell":"设置"}"#, + ); + assert_eq!(run.get("ok").and_then(|v| v.as_bool()), Some(true), "{run:?}"); + let read = api_cell_run( + &root, + r#"{"path":"shared.mq.md","cell":"读取"}"#, + ); + let stdout = read + .get("record") + .and_then(|r| r.get("stdout")) + .and_then(|v| v.as_str()) + .unwrap_or(""); + assert_eq!(stdout, "42\n", "{read:?}"); + let assign = api_assign( + &root, + r#"{"path":"shared.mq.md","cell":"读取","kernel":"绘图"}"#, + ); + assert_eq!(assign.get("ok").and_then(|v| v.as_bool()), Some(true), "{assign:?}"); + let failed = api_cell_run( + &root, + r#"{"path":"shared.mq.md","cell":"读取"}"#, + ); + assert_eq!( + failed + .get("record") + .and_then(|r| r.get("ok")) + .and_then(|v| v.as_bool()), + Some(false), + "{failed:?}" + ); + let push = api_state_push( + &root, + r#"{"path":"shared.mq.md","kernel":"分析","name":"z","value":9}"#, + ); + assert_eq!(push.get("ok").and_then(|v| v.as_bool()), Some(true), "{push:?}"); + let pull = api_state_pull( + &root, + r#"{"path":"shared.mq.md","kernel":"分析","name":"z"}"#, + ); + assert_eq!( + pull.get("value").and_then(|v| v.as_i64()), + Some(9), + "{pull:?}" + ); + let _ = api_close(&root, open_body()); + } +} diff --git a/src/view/render.rs b/src/view/render.rs index 081cf3a..45ab4a2 100644 --- a/src/view/render.rs +++ b/src/view/render.rs @@ -1254,7 +1254,7 @@ fn render_stmt( let lang = escape(&c.lang); let src = escape(&c.source); format!( - r#"
+ r#"
code `{name}` = diff --git a/tests/notebook/shared.mq.md b/tests/notebook/shared.mq.md new file mode 100644 index 0000000..8f5334d --- /dev/null +++ b/tests/notebook/shared.mq.md @@ -0,0 +1,35 @@ +--- +title: notebook shared state +--- + +# main + +`内核表` = + +| 名称 | 语言 | 命令 | 说明 | +|------|------|------|------| +| 分析 | node | | 共享状态的内核 | +| 绘图 | node | | 隔离的内核 | + +`会话表` = + +| 单元 | 内核 | 说明 | +|------|------|------| +| 设置 | 分析 | 写入共享变量 | +| 读取 | 分析 | 读取共享变量 | +| 隔离 | 绘图 | 看不到 shared | + +`设置` = +```node +let shared = 41; +``` + +`读取` = +```node +console.log(shared + 1); +``` + +`隔离` = +```node +console.log(typeof shared === "undefined" ? "isolated" : "leaked"); +```