feat(notebook): document session with shared kernels and view controls
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.
This commit is contained in:
1 parent
050d71927f
commit
3001ed7ba5
14 files changed
+1582
-8
No files matched your search
@@ -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(),
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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<String>,
|
||||
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<Cell>,
|
||||
pub kernels: Vec<KernelDecl>,
|
||||
pub order: Vec<String>,
|
||||
pub journal: Vec<JournalRecord>,
|
||||
pub value_store: HashMap<String, Value>,
|
||||
pub cursor: usize,
|
||||
pub opened_ms: i64,
|
||||
host: HostContext,
|
||||
kernel_sessions: HashMap<String, String>,
|
||||
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<String> {
|
||||
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<Option<Vec<HashMap<String, String>>>, 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<Vec<String>> = 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<Option<Vec<HashMap<String, String>>>, 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<String, String>, 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<Cell>, seen: &mut HashSet<String>) -> 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<Self, String> {
|
||||
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<KernelDecl> = Vec::new();
|
||||
let mut kernel_map: HashMap<String, KernelDecl> = 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<String> = 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<String, usize> = 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<usize> {
|
||||
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<String, String> {
|
||||
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<Value, String> {
|
||||
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<Value, String> {
|
||||
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<Value, String> {
|
||||
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<Value, String> {
|
||||
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<Value, String> {
|
||||
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<Value, String> {
|
||||
let names: Vec<String> = 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<Value, String> {
|
||||
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<Value, String> {
|
||||
let marqdo = self
|
||||
.value_store
|
||||
.iter()
|
||||
.map(|(k, v)| (k.clone(), v.clone()))
|
||||
.collect::<Vec<_>>();
|
||||
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<Value, String> {
|
||||
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<Value, String> {
|
||||
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<String> = 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<KernelDecl>,
|
||||
map: &mut HashMap<String, KernelDecl>,
|
||||
name: &str,
|
||||
) -> Result<KernelDecl, String> {
|
||||
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<KernelDecl>,
|
||||
map: &mut HashMap<String, KernelDecl>,
|
||||
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<Value> {
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -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#"<style>
|
||||
.notebook-bar{display:flex;flex-wrap:wrap;gap:.4rem;align-items:center;margin:.6rem 0;padding:.45rem .6rem;border:1px solid #2d2d2d;background:#232323;border-radius:4px;font:0.75rem/1.3 var(--mono);}
|
||||
.notebook-bar button{cursor:pointer;background:#2f2f2f;color:#ddd;border:1px solid #444;border-radius:3px;padding:.2rem .45rem;font:inherit;}
|
||||
.notebook-bar button:hover{background:#3a3a3a;}
|
||||
.nb-badge{font:0.6rem/1 var(--mono);padding:.15rem .3rem;border-radius:3px;background:#333;color:#aaa;margin-left:.3rem;}
|
||||
.nb-badge.ok{background:#1d3a24;color:#8fd19e;}
|
||||
.nb-badge.bad{background:#3a1d1d;color:#f19a9a;}
|
||||
.nb-kernel{font:0.65rem/1 var(--mono);background:#2a2a2a;color:#ddd;border:1px solid #444;border-radius:3px;padding:.12rem .2rem;margin-left:.3rem;}
|
||||
#nb-state-out{max-height:18rem;overflow:auto;margin:.4rem 0;padding:.4rem;background:#1b1b1b;border:1px solid #2d2d2d;color:#bbb;font:0.7rem/1.35 var(--mono);white-space:pre-wrap;}
|
||||
#nb-state-actions input{background:#1b1b1b;color:#ddd;border:1px solid #444;border-radius:3px;padding:.18rem .3rem;font:inherit;width:7rem;}
|
||||
</style>
|
||||
<div class="notebook-bar" id="notebook-bar" hidden>
|
||||
<strong>Notebook</strong>
|
||||
<button type="button" id="nb-run-all">Run All</button>
|
||||
<button type="button" id="nb-restart">Restart & Run All</button>
|
||||
<button type="button" id="nb-step">Step</button>
|
||||
<button type="button" id="nb-state">State</button>
|
||||
<span id="nb-status">opening…</span>
|
||||
</div>
|
||||
<div class="notebook-bar" id="nb-state-actions" hidden>
|
||||
<span>Bridge</span>
|
||||
<input id="nb-kernel-input" placeholder="kernel" autocomplete="off"/>
|
||||
<input id="nb-name-input" placeholder="name" autocomplete="off"/>
|
||||
<input id="nb-value-input" placeholder="JSON value" autocomplete="off"/>
|
||||
<button type="button" id="nb-push">Push</button>
|
||||
<button type="button" id="nb-pull">Pull</button>
|
||||
<span id="nb-pull-out"></span>
|
||||
</div>
|
||||
<pre id="nb-state-out" hidden></pre>
|
||||
<script>
|
||||
(function () {
|
||||
if (!window.MARQDO_VIEW_LIVE) return;
|
||||
var path = window.MARQDO_FILE_PATH || "";
|
||||
if (!path) return;
|
||||
var state = { open: false, kernels: [], cells: {} };
|
||||
function post(url, body) {
|
||||
return fetch(url, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(Object.assign({ path: path }, body || {}))
|
||||
}).then(function (r) { return r.json(); });
|
||||
}
|
||||
function status(t) { var e = document.getElementById("nb-status"); if (e) e.textContent = t; }
|
||||
function card(name) {
|
||||
var els = document.querySelectorAll(".code-card");
|
||||
for (var i = 0; i < els.length; i++) {
|
||||
if (els[i].getAttribute("data-code-name") === name) return els[i];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
function badge(el, text, ok) {
|
||||
if (!el) return;
|
||||
var b = el.querySelector(".nb-badge");
|
||||
if (!b) {
|
||||
b = document.createElement("span");
|
||||
var head = el.querySelector(".code-head");
|
||||
if (!head) return;
|
||||
head.appendChild(b);
|
||||
}
|
||||
b.textContent = text;
|
||||
b.className = "nb-badge " + (ok ? "ok" : (text === "clean" || text === "never" ? "" : "bad"));
|
||||
}
|
||||
function renderRecord(name, rec) {
|
||||
var el = card(name);
|
||||
if (!el || !rec) return;
|
||||
var out = el.querySelector(".code-out");
|
||||
if (out) {
|
||||
out.hidden = false;
|
||||
var parts = [];
|
||||
if (rec.stdout) parts.push(rec.stdout);
|
||||
if (rec.stderr) parts.push("[stderr]\n" + rec.stderr);
|
||||
if (rec.error) parts.push(rec.error);
|
||||
var meta = [];
|
||||
if (typeof rec.code === "number") meta.push("exit " + rec.code);
|
||||
if (typeof rec.ms === "number") meta.push(rec.ms + "ms");
|
||||
if (rec.timed_out) meta.push("timed out");
|
||||
if (rec.truncated) meta.push("truncated");
|
||||
if (meta.length) parts.push("— " + meta.join(" · "));
|
||||
out.textContent = parts.length ? parts.join("\n\n") : "(no output)";
|
||||
out.classList.toggle("err", !rec.ok);
|
||||
}
|
||||
badge(el, rec.ok ? "clean" : "error", !!rec.ok);
|
||||
}
|
||||
function renderSummary(s) {
|
||||
if (!s) return;
|
||||
state.kernels = s.kernels || [];
|
||||
state.cells = {};
|
||||
(s.cells || []).forEach(function (c) { state.cells[c.name] = c; });
|
||||
(s.cells || []).forEach(function (c) {
|
||||
var el = card(c.name);
|
||||
if (!el) return;
|
||||
badge(el, c.status, c.status === "clean");
|
||||
var sel = el.querySelector(".nb-kernel");
|
||||
if (!sel) {
|
||||
sel = document.createElement("select");
|
||||
sel.className = "nb-kernel";
|
||||
var head = el.querySelector(".code-head");
|
||||
if (head) head.appendChild(sel);
|
||||
sel.addEventListener("change", function () {
|
||||
post("/api/session/kernel/assign", { cell: c.name, kernel: sel.value }).then(function (r) {
|
||||
status(r.ok ? "kernel: " + sel.value : (r.error || "assign failed"));
|
||||
});
|
||||
});
|
||||
}
|
||||
var opts = state.kernels.filter(function (k) { return k.lang === c.lang; }).map(function (k) { return k.name; });
|
||||
if (!opts.length) opts = [c.kernel];
|
||||
sel.innerHTML = "";
|
||||
opts.forEach(function (n) {
|
||||
var o = document.createElement("option");
|
||||
o.value = n; o.textContent = n;
|
||||
if (n === c.kernel) o.selected = true;
|
||||
sel.appendChild(o);
|
||||
});
|
||||
});
|
||||
}
|
||||
function openSession() {
|
||||
var bar = document.getElementById("notebook-bar");
|
||||
if (bar) bar.hidden = false;
|
||||
post("/api/session/open", {}).then(function (r) {
|
||||
if (!r.ok) { status(r.error || "session open failed"); return; }
|
||||
state.open = true;
|
||||
renderSummary(r.session);
|
||||
status("session ready");
|
||||
});
|
||||
}
|
||||
function runOne(name) {
|
||||
return post("/api/session/cell/run", { cell: name }).then(function (r) {
|
||||
if (r.ok) { renderRecord(name, r.record); if (r.session) renderSummary(r.session); }
|
||||
else status(r.error || "run failed");
|
||||
});
|
||||
}
|
||||
function runAll(restart) {
|
||||
status(restart ? "restarting…" : "running all…");
|
||||
post("/api/session/run_all", { restart: !!restart }).then(function (r) {
|
||||
if (!r.ok) { status(r.error || "run all failed"); return; }
|
||||
if (r.session) renderSummary(r.session);
|
||||
var recs = (r.summary && r.summary.records) || [];
|
||||
recs.forEach(function (rec) { if (rec.cell) renderRecord(rec.cell, rec); });
|
||||
status("run all done");
|
||||
});
|
||||
}
|
||||
function bind(id, fn) { var b = document.getElementById(id); if (b) b.addEventListener("click", fn); }
|
||||
function init() {
|
||||
bind("nb-run-all", function () { runAll(false); });
|
||||
bind("nb-restart", function () { runAll(true); });
|
||||
bind("nb-step", function () {
|
||||
post("/api/session/cell/step", {}).then(function (r) {
|
||||
if (!r.ok) { status(r.error || "step failed"); return; }
|
||||
if (r.record) {
|
||||
if (r.record.cell) renderRecord(r.record.cell, r.record);
|
||||
if (r.record.done) status("done");
|
||||
}
|
||||
if (r.session) renderSummary(r.session);
|
||||
if (!r.record || !r.record.done) status("step");
|
||||
});
|
||||
});
|
||||
bind("nb-state", function () {
|
||||
post("/api/session/state/list", {}).then(function (r) {
|
||||
var pre = document.getElementById("nb-state-out");
|
||||
var actions = document.getElementById("nb-state-actions");
|
||||
var ki = document.getElementById("nb-kernel-input");
|
||||
if (!pre) return;
|
||||
pre.hidden = false;
|
||||
pre.textContent = JSON.stringify(r.state || r, null, 2);
|
||||
if (actions) actions.hidden = false;
|
||||
if (ki && !ki.value && state.kernels.length) ki.value = state.kernels[0].name;
|
||||
});
|
||||
});
|
||||
bind("nb-push", function () {
|
||||
var k = (document.getElementById("nb-kernel-input") || {}).value || "";
|
||||
var n = (document.getElementById("nb-name-input") || {}).value || "";
|
||||
var raw = (document.getElementById("nb-value-input") || {}).value || "";
|
||||
if (!k || !n) { status("kernel and name required"); return; }
|
||||
var value = null;
|
||||
if (raw.trim()) {
|
||||
try { value = JSON.parse(raw); } catch (e) { status("value must be JSON"); return; }
|
||||
}
|
||||
post("/api/session/state/push", { kernel: k, name: n, value: value }).then(function (r) {
|
||||
status(r.ok ? "pushed " + n + " → " + k : (r.error || "push failed"));
|
||||
});
|
||||
});
|
||||
bind("nb-pull", function () {
|
||||
var k = (document.getElementById("nb-kernel-input") || {}).value || "";
|
||||
var n = (document.getElementById("nb-name-input") || {}).value || "";
|
||||
var out = document.getElementById("nb-pull-out");
|
||||
if (!k || !n) { status("kernel and name required"); return; }
|
||||
post("/api/session/state/pull", { kernel: k, name: n }).then(function (r) {
|
||||
if (out) out.textContent = r.ok ? (n + " = " + JSON.stringify(r.value)) : (r.error || "pull failed");
|
||||
status(r.ok ? "pulled " + n + " ← " + k : "pull failed");
|
||||
});
|
||||
});
|
||||
document.addEventListener("click", function (e) {
|
||||
var btn = e.target && e.target.closest ? e.target.closest(".code-run") : null;
|
||||
if (!btn || !state.open) return;
|
||||
var el = btn.closest(".code-card");
|
||||
if (!el) return;
|
||||
var name = el.getAttribute("data-code-name");
|
||||
if (!name) return;
|
||||
e.preventDefault();
|
||||
e.stopImmediatePropagation();
|
||||
btn.disabled = true;
|
||||
status("running " + name);
|
||||
runOne(name).finally(function () { btn.disabled = false; status("ready"); });
|
||||
}, true);
|
||||
openSession();
|
||||
}
|
||||
if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", init);
|
||||
else init();
|
||||
})();
|
||||
</script>"#
|
||||
}
|
||||
|
||||
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("</", "<\\/");
|
||||
let notebook = if matches!(links, LinkMode::Live) {
|
||||
notebook_ui().to_string()
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
let main = format!(
|
||||
r#"
|
||||
<script>
|
||||
@@ -2973,6 +3191,7 @@ window.MARQDO_AUTO_STREAM = {auto_stream};
|
||||
<script type="application/json" id="mq-view-trace">{trace}</script>
|
||||
<h1 class="page">{title}<span class="status-pill {status}">{status_label}</span></h1>
|
||||
<p class="meta">{rel}</p>
|
||||
{notebook}
|
||||
<section class="block">
|
||||
<h2>Structure</h2>
|
||||
{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}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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));
|
||||
|
||||
@@ -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<HashMap<String, Arc<Mutex<DocumentSession>>>> {
|
||||
static S: OnceLock<Mutex<HashMap<String, Arc<Mutex<DocumentSession>>>>> = 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<Arc<Mutex<DocumentSession>>, 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<F>(root: &Path, body: &str, action: &str, f: F) -> serde_json::Value
|
||||
where
|
||||
F: FnOnce(&mut DocumentSession) -> Result<Value, String>,
|
||||
{
|
||||
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());
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -1254,7 +1254,7 @@ fn render_stmt(
|
||||
let lang = escape(&c.lang);
|
||||
let src = escape(&c.source);
|
||||
format!(
|
||||
r#"<div class="card code-card" data-lang="{lang}">
|
||||
r#"<div class="card code-card" data-lang="{lang}" data-code-name="{name}">
|
||||
<div class="code-head">
|
||||
<span class="badge">code</span>
|
||||
<code class="expr">`{name}` =</code>
|
||||
|
||||
Reference in new issue
Block a user