feat(foreign): own view sessions and clear outputs
foreign.session returns a handle from ordinary kernel/cell tables; view consumes only the 会话 binding. Sessions live in host foreign_doc. Without 会话, view cells run stateless one-shot. Add /api/session/clear and a Clear outputs button for every view page; clearing keeps persistent kernel state.
This commit is contained in:
1 parent
01468ad976
commit
fb28eee62f
21 files changed
+379
-75
No files matched your search
@@ -210,7 +210,7 @@ Design: [ext-quantum.md](../../doc/design/ext-quantum.md) · Q7: [ext-quantum-q7
|
||||
- `invoke` returns a record (`ok`, `code`, `stdout`, `stderr`, `ms`, `timed_out`, `truncated`, `result`); pass `input` for JSON stdin and `output="json"` for a parsed result.
|
||||
- `call` is JSON-in / JSON-out; `call_many` fans out one program over a list with ordered results.
|
||||
- `session_open` starts a persistent Python/Node kernel; `session_eval` evaluates source; `session_set` / `session_get` bridge values explicitly as JSON. Close it with `session_close`.
|
||||
- A view document can expose cells: bind `内核表` and `会话表` as ordinary tables inside `# main`. `marqdo view` evaluates those bindings through the interpreter (`capture_declarations`), never by scanning source lines, and adds cell stepping, Run All, kernel switching, journal and reload. There is no separate notebook CLI mode or command, and no new Markdown marker exists.
|
||||
- A view document opts into kernel state with `会话 = > foreign.session kernels=... cells=...`; the table names are free. `view` consumes only the `会话` handle and never scans source lines or reserved table names. Without `会话`, cells are stateless one-shot runs; no kernel is created. Clearing outputs calls `/api/session/clear` and keeps persistent kernel state. There is no separate notebook CLI mode or command, and no new Markdown marker exists.
|
||||
- The same source remains the authority; state crossing kernels is explicit, never implicitly mirrored.
|
||||
|
||||
## AI authoring workflow
|
||||
|
||||
+2
-1
@@ -4,7 +4,8 @@
|
||||
|
||||
### Added
|
||||
|
||||
- **view cells 概念收敛**:`view` 是唯一交互面;所有 view 页面共用同一套 cell 工具栏/布局;cell plan 由解释器 `capture_declarations` 对 `内核表` / `会话表` 求值(含简单依赖),删除源码行扫描;移除 `In []` / `Out []` 的 Jupyter 式提示与 Notebook 品牌;没有新增 CLI 或第二个交互模式。
|
||||
- **foreign 拥有视图会话**:新增 `foreign.session kernels= cells=`,返回 foreign 会话句柄;`view` 只消费 `会话` 绑定,不再识别 `内核表` / `会话表` 保留名。没有 `会话` 时,view cells 使用无状态一次性执行,不创建内核。清除输出已接通 `/api/session/clear`,普通 view 与 foreign cells 共用;移除 `In []` / `Out []` 与 Notebook 品牌;没有新增 CLI 或第二个交互模式。
|
||||
|
||||
### Fixed
|
||||
|
||||
### Changed
|
||||
|
||||
@@ -151,7 +151,7 @@ marqdo catalog public -o .marqdo
|
||||
|
||||
## 现状(v1.5.0)
|
||||
|
||||
- **外联 v2 / view 交互单元(v1.5.0)**:结构化 invoke · JSON call/call_many · 并行扇出 · Python/Node 持久内核 · 显式状态桥 · cell 单步/Run All/内核切换 · 解释器求值 cell plan(无源码行扫描)· 高对比浅深主题;扩展包同步 **1.5.0**
|
||||
- **外联 v2 / view 交互单元(v1.5.0)**:结构化 invoke · JSON call/call_many · 并行扇出 · Python/Node 持久内核 · 显式状态桥 · cell 单步/Run All/内核切换 · `foreign.session` 句柄 · 无 `会话` 时无状态 cells · 清除输出 API · 高对比浅深主题;扩展包同步 **1.5.0**
|
||||
- **裸自增升参(v1.4.6)**:首次粗体赋值左值即声明;`**n = n + 1**` 无反引号也升为必选形参。扩展包仍为 **1.4.5**
|
||||
- **Streamable HTTP MCP + web invoke 鉴权(v1.4.5)**:`agent_mcp_serve transport=http` · Bearer/`X-Api-Key` 注入 · `unauthorized`→401 · openai/agent `json.get` 硬化
|
||||
- **LLM 传输软失败 + `ext/ai` 表优先(v1.4.4)**:上游不可达 → `status=error`(不 abort);`agent`/`llm` 去 `json.set` 胶水 · [agent-llm-transport-soft-2026-10.md](doc/research/agent-llm-transport-soft-2026-10.md)
|
||||
|
||||
@@ -27,8 +27,8 @@
|
||||
|
||||
| 能力 | 状态 | 位置 |
|
||||
|---|---|---|
|
||||
| `内核表` / `会话表` 解析(中英列名) | ✅ | `src/notebook/mod.rs` |
|
||||
| cell plan 求值 | ✅ 解释器 `capture_declarations`;不再扫描源码行 | `src/interp.rs` · `src/notebook/mod.rs` |
|
||||
| `foreign.session` 句柄(kernels/cells 表参数) | ✅ | `lib/foreign.mq.md` · `src/host/foreign_doc.rs` |
|
||||
| cell plan 求值 | ✅ 解释器求值 `会话` 绑定;不扫描源码行、不认保留表名 | `src/interp.rs` · `src/host/foreign_doc.rs` |
|
||||
| cell index(绑定名 / 行号 / source hash) | ✅ | 同上 |
|
||||
| 命名内核 + 默认内核 + 语言校验 | ✅ | 同上 |
|
||||
| 同内核共享 / 跨内核隔离 | ✅ | Node 金样例 + 单测 |
|
||||
@@ -41,7 +41,7 @@
|
||||
| `POST /api/session/*` | ✅(含 `reload`) | `src/view/notebook_api.rs` |
|
||||
| cell step | ✅ | 同上 |
|
||||
| Marqdo statement step | ✅(view 工具栏 Debug → 同一 view 服务的 `/debug`;`/api/debug/*`) | `src/debug` · `src/view/debug_api.rs` |
|
||||
| dirty/stale 自动检测 | 部分(reload → dirty;assign → dirty;stale 传播待做) | `src/notebook/mod.rs` |
|
||||
| dirty/stale 自动检测 | 部分(reload → dirty;assign → dirty;stale 传播待做) | `src/host/foreign_doc.rs` |
|
||||
| writeback 集成 | 待做 | `writeback` |
|
||||
| replay / 持久化 | 待做 | — |
|
||||
| Python 会话 | ✅(本机无 python,CI/用户机条件测试) | `src/host/foreign_session.rs` |
|
||||
@@ -84,7 +84,7 @@
|
||||
```
|
||||
|
||||
- 共享 cell index 与 kernel registry。
|
||||
- `run` 不使用 cell 表;`view` 在文档声明 `内核表` / `会话表` 时提供 cell 控制。
|
||||
- `run` 不消费视图会话;`view` 只在文档绑定 `会话 = > foreign.session ...` 时提供持久 cell 控制;无 `会话` 时 cells 无状态一次性执行。
|
||||
- 冲突时以 `run` 的程序语义为准;view cells 不改变文档语义。
|
||||
|
||||
---
|
||||
@@ -131,7 +131,7 @@ DocumentSession
|
||||
1. 读取/解析文档(现有 `parse_source` / `load_module`)。
|
||||
2. 遍历 AST,找 `Stmt::Assign { name, value: Expr::Code(c) }`。
|
||||
3. 记录 name、lang、source、span、source hash。
|
||||
4. 通过解释器求值 `内核表` / `会话表` 绑定(`capture_declarations`,含简单依赖);不扫描源码行(见 [notebook-syntax.md](notebook-syntax.md))。
|
||||
4. 通过解释器求值 `会话` 绑定(`foreign.session` 返回的句柄,含简单依赖);不扫描源码行、不认保留表名(见 [notebook-syntax.md](notebook-syntax.md))。
|
||||
5. 解析 kernel 声明与 cell 归属;校验;生成诊断。
|
||||
6. 生成执行顺序:
|
||||
- 有会话表 → 行顺序;
|
||||
@@ -464,7 +464,7 @@ Kernel: [分析 ▾] Status: ready [Restart] [Interrupt]
|
||||
### 12.1 服务端
|
||||
|
||||
- cell index:绑定名/行号/lang/source hash;未绑定围栏排除。
|
||||
- 表解析:内核表/会话表/自动模式/重复/未知/语言不匹配。
|
||||
- 会话解析:foreign.session 句柄/自动模式/重复/未知/语言不匹配。
|
||||
- 会话:open/close/reload;kernel 启动/重启/中断。
|
||||
- cell run:状态机 never→running→clean/error;dirty/stale。
|
||||
- step:cell step 顺序;statement step 与 debug 联动。
|
||||
@@ -475,7 +475,7 @@ Kernel: [分析 ▾] Status: ready [Restart] [Interrupt]
|
||||
|
||||
### 12.2 金样例
|
||||
|
||||
- `tests/notebook/kernels.mq.md`:内核表/会话表。
|
||||
- `tests/notebook/kernels.mq.md`:foreign.session 句柄。
|
||||
- `tests/notebook/shared-state.mq.md`:两个 Python cell 共享 `x`。
|
||||
- `tests/notebook/step.mq.md`:cell step 顺序。
|
||||
- `tests/notebook/state-bridge.mq.md`:Marqdo ↔ Python 推拉。
|
||||
@@ -510,7 +510,7 @@ Kernel: [分析 ▾] Status: ready [Restart] [Interrupt]
|
||||
| 阶段 | 内容 |
|
||||
|---|---|
|
||||
| D0 | 设计/语法/决策文档(本文件) |
|
||||
| D1 | `src/notebook/`:cell index、表解析、session 结构、诊断 |
|
||||
| D1 | `src/host/foreign_doc.rs`:cell index、foreign.session 句柄、session 结构、诊断 |
|
||||
| D2 | 服务端 API:open/close/cell run/step/run_all/restart/interrupt |
|
||||
| D3 | view UI:工具栏、cell 徽标、kernel 下拉、状态面板、journal |
|
||||
| D4 | statement step 接入;dirty/stale;writeback |
|
||||
|
||||
@@ -231,7 +231,7 @@ print(x + 1)
|
||||
| 情况 | 诊断(中文示例) | 修复建议 |
|
||||
|---|---|---|
|
||||
| 内核名重复 | `内核表: 内核名「分析」重复(第 12、20 行)` | 改名或合并 |
|
||||
| 会话引用未知内核 | `会话表: 单元「汇总」引用了未声明的内核「分析」` | 在 `内核表` 声明,或改用语言 id |
|
||||
| 会话引用未知内核 | `foreign.session: cell「汇总」引用了未声明的内核「分析」` | 在 kernels 表声明,或改用语言 id |
|
||||
| 会话引用未知单元 | `会话表: 找不到名为「清洗」的代码单元` | 检查 `` `清洗` = `` 绑定 |
|
||||
| 单元重复 | `会话表: 单元「汇总」重复出现` | 每个单元只列一次 |
|
||||
| 语言不匹配 | `会话表: 单元「前端」(node) 不能使用 python 内核「分析」` | 换内核或换语言 |
|
||||
@@ -245,9 +245,9 @@ print(x + 1)
|
||||
|
||||
## 7. 与 program execution 的关系
|
||||
|
||||
- `内核表` / `会话表` 是**声明**,不是执行指令。
|
||||
- `内核表` / `会话表` 只是传递给 `foreign.session` 的普通表变量,不是保留名。
|
||||
- `marqdo run` 仍然执行 `# main` 的程序语义;这两个表会被求值为普通数据。
|
||||
- `run` 的外联编排用显式 API(`foreign.session_open` / `session_eval` / `call`);表只服务 `view` 的 cells 与一键 Run All。
|
||||
- `run` 的外联编排用显式 API(`foreign.session_open` / `session_eval` / `call`);`foreign.session` 句柄服务 `view` 的 cells 与一键 Run All。
|
||||
- 两者可以并存:
|
||||
- 文档用表描述“交互时怎么跑”;
|
||||
- `# main` 用显式调用描述“CI 时怎么跑”。
|
||||
@@ -295,7 +295,7 @@ v2 **不**为状态交换新增表格/注释。原因:
|
||||
|
||||
| 逻辑 | 位置 |
|
||||
|---|---|
|
||||
| 识别 `内核表` / `会话表` 绑定 | `src/notebook/syntax.rs`(新) |
|
||||
| 识别 `会话` 的 foreign.session 句柄 | `src/host/foreign_doc.rs` |
|
||||
| 读取绑定值 | AST `Stmt::Assign` + `Expr::Table` / `Expr::List`;或最近一次 run 的 bindings |
|
||||
| 校验名称/语言/重复/未入会话 | 同上;错误进入现有 Diagnostic |
|
||||
| cell index(绑定名/行号/语言/source hash) | 解析后的 `Module` 遍历 |
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
---
|
||||
title: lib/foreign
|
||||
description: Run bound code fences and inline sources via local interpreters
|
||||
import table:lib/table.mq.md
|
||||
---
|
||||
|
||||
Run bound code fences and inline sources via local interpreters.
|
||||
@@ -148,6 +149,21 @@ in input order. Raises with the failing index after all workers finish.
|
||||
|
||||
*> host_foreign_call_many inputs=`inputs` code=`code` lang=`lang` source=`source` cmd=`cmd` env=`env` cwd=`cwd` timeout=`timeout` args=`args` max_output=`max_output` concurrency=`concurrency`*
|
||||
|
||||
## session
|
||||
+ `kernels`=None
|
||||
+ `cells`=None
|
||||
|
||||
Declare a document view session. `kernels` and `cells` are ordinary tables:
|
||||
kernels are `|名称|语言|命令|` (ZH or EN), cells are `|单元|内核|`.
|
||||
Returns a foreign session handle consumed by `view`; without this handle the
|
||||
view has no persistent kernel state.
|
||||
|
||||
**p = > table.empty_map**
|
||||
**p = > table.put in=`p` at="kind" value="foreign-session"**
|
||||
**p = > table.put in=`p` at="kernels" value=`kernels`**
|
||||
**p = > table.put in=`p` at="cells" value=`cells`**
|
||||
*p*
|
||||
|
||||
## session_open
|
||||
+ `lang`
|
||||
+ `cmd`=None
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
---
|
||||
title: lib/外联
|
||||
description: 通过本机解释器运行绑定的代码围栏与内联源码
|
||||
import table:lib/table.mq.md
|
||||
---
|
||||
|
||||
通过本机解释器运行绑定的代码围栏与内联源码。
|
||||
@@ -146,6 +147,19 @@ JSON 进 / JSON 出:把 `输入` 编码到 stdin,解析 stdout JSON 返回
|
||||
|
||||
*> host_foreign_call_many inputs=`输入表` code=`代码` lang=`语言` source=`源码` cmd=`命令` env=`环境` cwd=`工作目录` timeout=`超时` args=`参数` max_output=`最大输出` concurrency=`并发`*
|
||||
|
||||
## 会话
|
||||
+ `内核表`=None
|
||||
+ `单元表`=None
|
||||
|
||||
声明文档视图会话。内核表和单元表都是普通表格;返回一个 foreign 会话句柄,
|
||||
供 view 消费。没有这个句柄时,view 的 cells 是无状态的。
|
||||
|
||||
**p = > table.empty_map**
|
||||
**p = > table.put in=`p` at="kind" value="foreign-session"**
|
||||
**p = > table.put in=`p` at="kernels" value=`内核表`**
|
||||
**p = > table.put in=`p` at="cells" value=`单元表`**
|
||||
*p*
|
||||
|
||||
## 会话开启
|
||||
+ `语言`
|
||||
+ `命令`=None
|
||||
|
||||
@@ -62,23 +62,25 @@ The same module also supports JSON calls, parallel fan-out, persistent kernels a
|
||||
A view document is still a document. Named kernels and a cell order are ordinary bound tables:
|
||||
|
||||
```text
|
||||
`内核表` =
|
||||
`分析内核` =
|
||||
|
||||
| 名称 | 语言 | 说明 |
|
||||
|------|------|------|
|
||||
| 分析 | python | shared state |
|
||||
| 复核 | python | isolated state |
|
||||
|
||||
`会话表` =
|
||||
`分析单元` =
|
||||
|
||||
| 单元 | 内核 | 说明 |
|
||||
|------|------|------|
|
||||
| 准备数据 | 分析 | write |
|
||||
| 计算指标 | 分析 | read |
|
||||
| 独立复核 | 复核 | validate |
|
||||
|
||||
`会话` = > foreign.session kernels=`分析内核` cells=`分析单元`
|
||||
```
|
||||
|
||||
`marqdo view` turns that into Run All, Step, per-cell kernels, a journal and a state panel. There is no separate interactive mode or command; `marqdo run` still executes the file as one program.
|
||||
`marqdo view` consumes the foreign-owned `会话` handle and turns it into Run All, Step, per-cell kernels, a journal and a state panel. Without `会话`, cells are stateless one-shot runs. There is no separate interactive mode or command; `marqdo run` still executes the file as one program.
|
||||
|
||||
Documentation becomes knowledge when it can be discovered, verified and reused. OKF supplies the portable Markdown + YAML shape; EKC projects the repository into catalog layers L0–L4, a graph and an engineering preflight. The source `.mq.md` remains the only authority; generated artifacts are marked and rebuildable.
|
||||
|
||||
|
||||
+5
-3
@@ -62,23 +62,25 @@ print("hello-from-python")
|
||||
view 仍然是一篇文档。命名内核与单元顺序就是普通绑定表:
|
||||
|
||||
```text
|
||||
`内核表` =
|
||||
`分析内核` =
|
||||
|
||||
| 名称 | 语言 | 说明 |
|
||||
|------|------|------|
|
||||
| 分析 | python | 共享状态 |
|
||||
| 复核 | python | 隔离状态 |
|
||||
|
||||
`会话表` =
|
||||
`分析单元` =
|
||||
|
||||
| 单元 | 内核 | 说明 |
|
||||
|------|------|------|
|
||||
| 准备数据 | 分析 | 写入 |
|
||||
| 计算指标 | 分析 | 读取 |
|
||||
| 独立复核 | 复核 | 校验 |
|
||||
|
||||
`会话` = > foreign.session kernels=`分析内核` cells=`分析单元`
|
||||
```
|
||||
|
||||
`marqdo view` 会把它变成 Run All、Step、每单元内核、journal 与状态面板。没有单独的交互模式或命令;`marqdo run` 仍然把文件当单个程序运行。
|
||||
`marqdo view` 消费 foreign 拥有的 `会话` 句柄,变成 Run All、Step、每单元内核、journal 与状态面板。没有 `会话` 时,单元是无状态的一次性运行。没有单独的交互模式或命令;`marqdo run` 仍然把文件当单个程序运行。
|
||||
|
||||
文档能被发现、验证和复用时,才成为知识。OKF 提供可移植的 Markdown + YAML 形态;EKC 把仓库投影成 catalog L0–L4、图与工程 preflight。源 `.mq.md` 始终是唯一权威,生成物有标记、可重建。
|
||||
|
||||
|
||||
@@ -150,14 +150,14 @@ print(json.dumps(value + 1))
|
||||
Cells in view. Named kernels and a cell order are ordinary bound tables, not fence metadata or YAML config.
|
||||
|
||||
```text
|
||||
`内核表` =
|
||||
`分析内核` =
|
||||
|
||||
| 名称 | 语言 | 命令 | 说明 |
|
||||
|------|------|------|------|
|
||||
| 分析 | python | | shared analysis |
|
||||
| 复核 | python | | isolated review |
|
||||
|
||||
`会话表` =
|
||||
`分析单元` =
|
||||
|
||||
| 单元 | 内核 | 说明 |
|
||||
|------|------|------|
|
||||
@@ -166,7 +166,9 @@ Cells in view. Named kernels and a cell order are ordinary bound tables, not fen
|
||||
| 独立复核 | 复核 | read the JSON report |
|
||||
```
|
||||
|
||||
`marqdo view` renders these as cells with Run All, Step, per-cell kernel switching, a journal, dirty reload and a state panel. There is no separate interactive command; `marqdo run` still executes the same file as one program.
|
||||
`会话` = > foreign.session kernels=`分析内核` cells=`分析单元`
|
||||
|
||||
`marqdo view` consumes the foreign-owned `会话` handle and renders Run All, Step, per-cell kernel switching, a journal, dirty reload and a state panel. Without that handle, cells are stateless one-shot runs. There is no separate interactive command; `marqdo run` still executes the same file as one program.
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -150,14 +150,14 @@ print(json.dumps(value + 1))
|
||||
view 中的单元。命名内核和单元顺序都是普通绑定表,不是 fence 元数据或 YAML 配置。
|
||||
|
||||
```text
|
||||
`内核表` =
|
||||
`分析内核` =
|
||||
|
||||
| 名称 | 语言 | 命令 | 说明 |
|
||||
|------|------|------|------|
|
||||
| 分析 | python | | 共享分析 |
|
||||
| 复核 | python | | 独立复核 |
|
||||
|
||||
`会话表` =
|
||||
`分析单元` =
|
||||
|
||||
| 单元 | 内核 | 说明 |
|
||||
|------|------|------|
|
||||
@@ -166,7 +166,9 @@ view 中的单元。命名内核和单元顺序都是普通绑定表,不是 fe
|
||||
| 独立复核 | 复核 | 读取 JSON 报告 |
|
||||
```
|
||||
|
||||
`marqdo view` 会把这些渲染成带 Run All、Step、切换内核、journal、dirty reload 和状态面板的单元。没有单独的交互命令;`marqdo run` 仍把同一份文件当单个程序执行。
|
||||
`会话` = > foreign.session kernels=`分析内核` cells=`分析单元`
|
||||
|
||||
`marqdo view` 消费 foreign 拥有的 `会话` 句柄,渲染 Run All、Step、切换内核、journal、dirty reload 和状态面板。没有该句柄时,单元是无状态的一次性运行。没有单独的交互命令;`marqdo run` 仍把同一份文件当单个程序执行。
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -108,26 +108,28 @@ This is a JSON copy, not shared memory. The kernel receives a value; Marqdo rece
|
||||
|
||||
Cells in view.
|
||||
|
||||
A document can declare named kernels and a cell order without new Markdown markers:
|
||||
`foreign.session` owns the document's kernel state. The kernel and cell order are ordinary tables passed as arguments; the names are free:
|
||||
|
||||
```text
|
||||
`内核表` =
|
||||
`分析内核` =
|
||||
|
||||
| 名称 | 语言 | 命令 | 说明 |
|
||||
|------|------|------|------|
|
||||
| 分析 | python | | shared analysis |
|
||||
| 复核 | python | | isolated review |
|
||||
|
||||
`会话表` =
|
||||
`分析单元` =
|
||||
|
||||
| 单元 | 内核 | 说明 |
|
||||
|------|------|------|
|
||||
| 准备数据 | 分析 | write state |
|
||||
| 计算指标 | 分析 | read state |
|
||||
| 独立复核 | 复核 | isolated kernel |
|
||||
|
||||
`会话` = > foreign.session kernels=`分析内核` cells=`分析单元`
|
||||
```
|
||||
|
||||
`marqdo view` then adds Run All, Step, kernel switching, a journal and per-cell state. This is a view capability, not a second CLI mode. See the complete Python walkthrough in [`features/19-foreign-view-cells.mq.md`](../features/19-foreign-view-cells.mq.md).
|
||||
`view` consumes the `会话` handle and adds Run All, Step, kernel switching, a journal and per-cell state. Without `会话`, view cells are stateless one-shot runs: same shell, no persistent kernel. There is no second CLI mode. See the complete Python walkthrough in [`features/19-foreign-view-cells.mq.md`](../features/19-foreign-view-cells.mq.md).
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -108,26 +108,28 @@ process.stdin.on("end", () => {
|
||||
|
||||
view 中的单元。
|
||||
|
||||
文档可以直接声明命名内核和单元顺序,不需要新增 Markdown 标记:
|
||||
`foreign.session` 拥有文档的内核状态。内核和单元顺序都是作为参数传入的普通表格,名字可以自由选择:
|
||||
|
||||
```text
|
||||
`内核表` =
|
||||
`分析内核` =
|
||||
|
||||
| 名称 | 语言 | 命令 | 说明 |
|
||||
|------|------|------|------|
|
||||
| 分析 | python | | 共享分析 |
|
||||
| 复核 | python | | 独立复核 |
|
||||
|
||||
`会话表` =
|
||||
`分析单元` =
|
||||
|
||||
| 单元 | 内核 | 说明 |
|
||||
|------|------|------|
|
||||
| 准备数据 | 分析 | 写入状态 |
|
||||
| 计算指标 | 分析 | 读取状态 |
|
||||
| 独立复核 | 复核 | 隔离内核 |
|
||||
|
||||
`会话` = > foreign.session kernels=`分析内核` cells=`分析单元`
|
||||
```
|
||||
|
||||
`marqdo view` 会提供 Run All、Step、切换内核、journal 和单元状态。这是 view 的能力,不是第二个 CLI 模式。完整 Python 示例见 [`features/19-外联视图单元.mq.md`](../features/19-外联视图单元.mq.md)。
|
||||
`view` 消费 `会话` 句柄,提供 Run All、Step、切换内核、journal 和单元状态。没有 `会话` 时,view 的 cells 是无状态的一次性运行:同一套外壳,但没有持久内核。没有第二个 CLI 模式。完整 Python 示例见 [`features/19-外联视图单元.mq.md`](../features/19-外联视图单元.mq.md)。
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
//! 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.
|
||||
//! Stateful cells live here, owned by the foreign runtime. The view reads a
|
||||
//! `会话 = > foreign.session ...` handle; no table names are reserved, and a
|
||||
//! document without that handle gets stateless one-shot cells.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::path::{Path, PathBuf};
|
||||
@@ -78,6 +79,8 @@ pub struct JournalRecord {
|
||||
|
||||
pub struct DocumentSession {
|
||||
pub path: PathBuf,
|
||||
root: PathBuf,
|
||||
pub persistent: bool,
|
||||
pub cells: Vec<Cell>,
|
||||
pub kernels: Vec<KernelDecl>,
|
||||
pub order: Vec<String>,
|
||||
@@ -125,10 +128,20 @@ fn table_rows(v: &Value) -> Result<Vec<HashMap<String, Value>>, String> {
|
||||
Ok(out)
|
||||
}
|
||||
Value::Map(cols) => {
|
||||
// A single-row table may evaluate to a map of scalar fields rather
|
||||
// than a column map. Treat that map as one record.
|
||||
if !cols.iter().all(|(_, v)| matches!(v, Value::List(_))) {
|
||||
let row = cols
|
||||
.iter()
|
||||
.filter(|(k, _)| k != "@")
|
||||
.map(|(k, v)| (k.clone(), v.clone()))
|
||||
.collect();
|
||||
return Ok(vec![row]);
|
||||
}
|
||||
let mut width = 0usize;
|
||||
for (name, value) in cols {
|
||||
for (_, value) in cols {
|
||||
let Value::List(xs) = value else {
|
||||
return Err(format!("view table column `{name}` is not a list"));
|
||||
unreachable!();
|
||||
};
|
||||
width = width.max(xs.len());
|
||||
}
|
||||
@@ -150,16 +163,34 @@ fn table_rows(v: &Value) -> Result<Vec<HashMap<String, Value>>, String> {
|
||||
}
|
||||
}
|
||||
|
||||
fn table_from_bindings(
|
||||
fn plan_tables(
|
||||
bindings: &HashMap<String, Value>,
|
||||
names: &[&str],
|
||||
) -> Result<Option<Vec<HashMap<String, Value>>>, String> {
|
||||
for name in names {
|
||||
if let Some(value) = bindings.get(*name) {
|
||||
return table_rows(value).map(Some);
|
||||
}
|
||||
) -> Result<(Option<Vec<HashMap<String, Value>>>, Option<Vec<HashMap<String, Value>>>), String> {
|
||||
let Some(plan) = bindings.get("会话") else {
|
||||
return Ok((None, None));
|
||||
};
|
||||
let Value::Map(fields) = plan else {
|
||||
return Err("`会话` must be a foreign.session handle".into());
|
||||
};
|
||||
let field = |name: &str| {
|
||||
fields
|
||||
.iter()
|
||||
.find(|(k, _)| k == name)
|
||||
.map(|(_, v)| v.clone())
|
||||
};
|
||||
let kind = field("kind").map(|v| value_text(&v)).unwrap_or_default();
|
||||
if kind != "foreign-session" {
|
||||
return Err("`会话` must be a foreign.session handle".into());
|
||||
}
|
||||
Ok(None)
|
||||
let kernels = match field("kernels") {
|
||||
Some(Value::None) | None => None,
|
||||
Some(v) => Some(table_rows(&v)?),
|
||||
};
|
||||
let cells = match field("cells") {
|
||||
Some(Value::None) | None => None,
|
||||
Some(v) => Some(table_rows(&v)?),
|
||||
};
|
||||
Ok((kernels, cells))
|
||||
}
|
||||
|
||||
fn col_value<'a>(row: &'a HashMap<String, Value>, names: &[&str]) -> Option<&'a Value> {
|
||||
@@ -201,10 +232,7 @@ fn capture_bindings(
|
||||
host.entry_metadata = module.metadata.clone();
|
||||
let mut interp = crate::interp::Interpreter::with_capture(Some(path), false).with_host(host);
|
||||
interp
|
||||
.capture_declarations(
|
||||
module,
|
||||
&["内核表", "kernels", "Kernels", "会话表", "session", "Session"],
|
||||
)
|
||||
.capture_declarations(module, &["会话"])
|
||||
.map_err(|e| format!("view plan evaluation: {e}"))
|
||||
}
|
||||
|
||||
@@ -281,21 +309,23 @@ impl DocumentSession {
|
||||
collect_cells(&entry.body, &mut cells, &mut seen)?;
|
||||
let declarations = capture_bindings(path, root, &module, &source)?;
|
||||
|
||||
let persistent = declarations.contains_key("会话");
|
||||
let (plan_kernels, plan_cells) = plan_tables(&declarations)?;
|
||||
let mut kernels: Vec<KernelDecl> = Vec::new();
|
||||
let mut kernel_map: HashMap<String, KernelDecl> = HashMap::new();
|
||||
if let Some(rows) = table_from_bindings(&declarations, &["内核表", "kernels", "Kernels"])? {
|
||||
if let Some(rows) = plan_kernels {
|
||||
if rows.is_empty() {
|
||||
return Err("内核表: at least one kernel row is required".into());
|
||||
return Err("foreign.session: at least one kernel row is required".into());
|
||||
}
|
||||
for row in rows {
|
||||
let name = col_text(&row, &["名称", "Name", "name"])
|
||||
.ok_or_else(|| "内核表: missing 名称/Name".to_string())?;
|
||||
.ok_or_else(|| "foreign.session kernels: missing 名称/Name".to_string())?;
|
||||
let lang = col_text(&row, &["语言", "Language", "language", "lang"])
|
||||
.ok_or_else(|| format!("内核表[{name}]: missing 语言/Language"))?;
|
||||
.ok_or_else(|| format!("foreign.session[{name}]: missing 语言/Language"))?;
|
||||
let lang = registry::canonical(&lang);
|
||||
let cmd = col_text(&row, &["命令", "Command", "command", "cmd"]);
|
||||
if kernel_map.contains_key(&name) {
|
||||
return Err(format!("内核表: kernel `{name}` is declared twice"));
|
||||
return Err(format!("foreign.session: kernel `{name}` is declared twice"));
|
||||
}
|
||||
let decl = KernelDecl {
|
||||
name: name.clone(),
|
||||
@@ -309,10 +339,10 @@ impl DocumentSession {
|
||||
}
|
||||
|
||||
let mut order: Vec<String> = Vec::new();
|
||||
let session_rows = table_from_bindings(&declarations, &["会话表", "session", "Session"])?;
|
||||
let session_rows = plan_cells;
|
||||
if let Some(rows) = session_rows {
|
||||
if rows.is_empty() {
|
||||
return Err("会话表: at least one cell row is required".into());
|
||||
return Err("foreign.session cells: at least one cell row is required".into());
|
||||
}
|
||||
let by_name: HashMap<String, usize> = cells
|
||||
.iter()
|
||||
@@ -322,19 +352,19 @@ impl DocumentSession {
|
||||
let mut listed = HashSet::new();
|
||||
for row in rows {
|
||||
let cell_name = col_text(&row, &["单元", "Cell", "cell", "单元名"])
|
||||
.ok_or_else(|| "会话表: missing 单元/Cell".to_string())?;
|
||||
.ok_or_else(|| "foreign.session cells: missing 单元/Cell".to_string())?;
|
||||
let kernel_name = col_text(&row, &["内核", "Kernel", "kernel"])
|
||||
.ok_or_else(|| format!("会话表[{cell_name}]: missing 内核/Kernel"))?;
|
||||
.ok_or_else(|| format!("foreign.session[{cell_name}]: missing 内核/Kernel"))?;
|
||||
let Some(&ci) = by_name.get(&cell_name) else {
|
||||
return Err(format!("会话表: unknown cell `{cell_name}`"));
|
||||
return Err(format!("foreign.session: unknown cell `{cell_name}`"));
|
||||
};
|
||||
if !listed.insert(cell_name.clone()) {
|
||||
return Err(format!("会话表: cell `{cell_name}` is listed twice"));
|
||||
return Err(format!("foreign.session: 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 `{}` ({})",
|
||||
"foreign.session: cell `{cell_name}` ({}) cannot use kernel `{}` ({})",
|
||||
cells[ci].lang, kernel.name, kernel.lang
|
||||
));
|
||||
}
|
||||
@@ -347,7 +377,7 @@ impl DocumentSession {
|
||||
cell.status = CellStatus::Unlisted;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
} else if persistent {
|
||||
for cell in &mut cells {
|
||||
let kernel = ensure_default_kernel(
|
||||
&mut kernels,
|
||||
@@ -358,6 +388,12 @@ impl DocumentSession {
|
||||
cell.listed = true;
|
||||
order.push(cell.name.clone());
|
||||
}
|
||||
} else {
|
||||
for cell in &mut cells {
|
||||
cell.kernel = "one-shot".into();
|
||||
cell.listed = true;
|
||||
order.push(cell.name.clone());
|
||||
}
|
||||
}
|
||||
|
||||
let mut host = HostContext::default();
|
||||
@@ -369,6 +405,8 @@ impl DocumentSession {
|
||||
|
||||
Ok(Self {
|
||||
path: path.to_path_buf(),
|
||||
root: root.to_path_buf(),
|
||||
persistent,
|
||||
cells,
|
||||
kernels,
|
||||
order,
|
||||
@@ -527,7 +565,34 @@ impl DocumentSession {
|
||||
.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 会话表"));
|
||||
return Err(format!("cell `{cell_name}` is not listed in the foreign session"));
|
||||
}
|
||||
if !self.persistent {
|
||||
self.cells[ci].kernel = "one-shot".into();
|
||||
self.cells[ci].status = CellStatus::Running;
|
||||
let lang = self.cells[ci].lang.clone();
|
||||
let source = self.cells[ci].source.clone();
|
||||
let result = crate::host::foreign::invoke_for_view(
|
||||
&self.root,
|
||||
&lang,
|
||||
&source,
|
||||
None,
|
||||
None,
|
||||
None,
|
||||
);
|
||||
return match result {
|
||||
Ok(record) => {
|
||||
self.record_result(cell_name, "one-shot", &record)?;
|
||||
Ok(record)
|
||||
}
|
||||
Err(e) => {
|
||||
if let Some(i) = self.cell_index(cell_name) {
|
||||
self.cells[i].status = CellStatus::Error;
|
||||
self.cells[i].last_error = e.clone();
|
||||
}
|
||||
Err(e)
|
||||
}
|
||||
};
|
||||
}
|
||||
let kernel = match kernel_override {
|
||||
Some(k) => {
|
||||
@@ -766,6 +831,7 @@ impl DocumentSession {
|
||||
Value::Map(vec![
|
||||
("title".into(), Value::Text(self.title())),
|
||||
("path".into(), Value::Text(self.path.display().to_string())),
|
||||
("persistent".into(), Value::Bool(self.persistent)),
|
||||
("cells".into(), Value::List(cells)),
|
||||
("kernels".into(), Value::List(kernels)),
|
||||
("order".into(), Value::List(
|
||||
@@ -794,6 +860,22 @@ impl DocumentSession {
|
||||
])
|
||||
}
|
||||
|
||||
/// Clear displayed outputs and per-cell records; kernels and live state survive.
|
||||
pub fn clear_outputs(&mut self) -> Value {
|
||||
for cell in &mut self.cells {
|
||||
cell.runs = 0;
|
||||
cell.last_ms = 0;
|
||||
cell.last_ok = false;
|
||||
cell.last_error.clear();
|
||||
if cell.listed {
|
||||
cell.status = CellStatus::Never;
|
||||
}
|
||||
}
|
||||
self.journal.clear();
|
||||
self.cursor = 0;
|
||||
self.summary()
|
||||
}
|
||||
|
||||
pub fn journal_json(&self) -> Value {
|
||||
Value::List(
|
||||
self.journal
|
||||
@@ -845,7 +927,7 @@ fn resolve_kernel(
|
||||
return Ok(decl);
|
||||
}
|
||||
Err(format!(
|
||||
"会话表: kernel `{name}` is not declared in 内核表"
|
||||
"foreign.session: kernel `{name}` is not declared in kernels"
|
||||
))
|
||||
}
|
||||
|
||||
@@ -904,22 +986,29 @@ mod tests {
|
||||
.map(|d| d.as_nanos())
|
||||
.unwrap_or(0)
|
||||
));
|
||||
let source = r#"# main
|
||||
let source = r#"---
|
||||
title: evaluated plan test
|
||||
import foreign:lib/foreign.mq.md
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
`lang` = python
|
||||
|
||||
`内核表` =
|
||||
`分析内核` =
|
||||
|
||||
| @ | 名称 | 语言 |
|
||||
|---|------|------|
|
||||
| 1 | 分析 | `lang` |
|
||||
|
||||
`会话表` =
|
||||
`分析单元` =
|
||||
|
||||
| @ | 单元 | 内核 |
|
||||
|---|------|------|
|
||||
| 1 | 单元 | 分析 |
|
||||
|
||||
`会话` = > foreign.session kernels=`分析内核` cells=`分析单元`
|
||||
|
||||
`单元` =
|
||||
```python
|
||||
print(1)
|
||||
@@ -982,7 +1071,12 @@ print(1)
|
||||
.map(|d| d.as_nanos())
|
||||
.unwrap_or(0)
|
||||
));
|
||||
let source = r#"# main
|
||||
let source = r#"---
|
||||
title: shared state test
|
||||
import foreign:lib/foreign.mq.md
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
`内核表` =
|
||||
|
||||
@@ -999,6 +1093,8 @@ print(1)
|
||||
| 读取 | 分析 | read |
|
||||
| 隔离 | 绘图 | isolated |
|
||||
|
||||
`会话` = > foreign.session kernels=`内核表` cells=`会话表`
|
||||
|
||||
`设置` =
|
||||
```node
|
||||
let shared = 41;
|
||||
@@ -1039,6 +1135,119 @@ console.log(typeof shared === "undefined" ? "isolated" : "leaked");
|
||||
let _ = std::fs::remove_file(&path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn magic_table_names_without_session_are_ignored() {
|
||||
if !node_available() {
|
||||
return;
|
||||
}
|
||||
let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
|
||||
let path = root.join(format!(
|
||||
"target/view-stateless-{}-{}.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 |
|
||||
|
||||
`会话表` =
|
||||
|
||||
| 单元 | 内核 |
|
||||
|------|------|
|
||||
| a | 分析 |
|
||||
|
||||
`a` =
|
||||
```node
|
||||
console.log("stateless");
|
||||
```
|
||||
"#;
|
||||
std::fs::write(&path, source).unwrap();
|
||||
let mut s = DocumentSession::open(&path, &root).unwrap();
|
||||
assert!(!s.persistent);
|
||||
assert!(s.kernels.is_empty(), "magic tables must not create kernels");
|
||||
assert_eq!(s.order, vec!["a".to_string()]);
|
||||
assert_eq!(s.cells[0].kernel, "one-shot");
|
||||
let r = s.run_cell("a", None).unwrap();
|
||||
assert_eq!(
|
||||
field(&r, "stdout").and_then(|v| v.reveal_text().map(|s| s.to_string())),
|
||||
Some("stateless\n".to_string())
|
||||
);
|
||||
assert_eq!(s.cells[0].status, CellStatus::Clean);
|
||||
s.clear_outputs();
|
||||
assert_eq!(s.cells[0].status, CellStatus::Never);
|
||||
assert!(s.journal.is_empty());
|
||||
s.close();
|
||||
let _ = std::fs::remove_file(&path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clear_outputs_keeps_persistent_kernel_state() {
|
||||
if !node_available() {
|
||||
return;
|
||||
}
|
||||
let root = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"));
|
||||
let path = root.join(format!(
|
||||
"target/view-clear-{}-{}.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#"---
|
||||
title: clear outputs
|
||||
import foreign:lib/foreign.mq.md
|
||||
---
|
||||
|
||||
# main
|
||||
|
||||
`内核` =
|
||||
|
||||
| 名称 | 语言 |
|
||||
|------|------|
|
||||
| 分析 | node |
|
||||
|
||||
`单元` =
|
||||
|
||||
| 单元 | 内核 |
|
||||
|------|------|
|
||||
| a | 分析 |
|
||||
|
||||
`会话` = > foreign.session kernels=`内核` cells=`单元`
|
||||
|
||||
`a` =
|
||||
```node
|
||||
globalThis.kept = (globalThis.kept || 0) + 1;
|
||||
console.log(globalThis.kept);
|
||||
```
|
||||
"#;
|
||||
std::fs::write(&path, source).unwrap();
|
||||
let mut s = DocumentSession::open(&path, &root).unwrap();
|
||||
let r = s.run_cell("a", None).unwrap();
|
||||
assert_eq!(
|
||||
field(&r, "stdout").and_then(|v| v.reveal_text().map(|s| s.to_string())),
|
||||
Some("1\n".to_string())
|
||||
);
|
||||
s.clear_outputs();
|
||||
assert_eq!(s.cells[0].status, CellStatus::Never);
|
||||
assert!(s.journal.is_empty());
|
||||
let r = s.run_cell("a", None).unwrap();
|
||||
assert_eq!(
|
||||
field(&r, "stdout").and_then(|v| v.reveal_text().map(|s| s.to_string())),
|
||||
Some("2\n".to_string()),
|
||||
"clear outputs must not restart the kernel"
|
||||
);
|
||||
s.close();
|
||||
let _ = std::fs::remove_file(&path);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reload_marks_changed_cell_dirty() {
|
||||
if !node_available() {
|
||||
@@ -15,6 +15,8 @@ pub mod event_bus;
|
||||
#[cfg(feature = "exec-host")]
|
||||
pub mod foreign;
|
||||
#[cfg(feature = "exec-host")]
|
||||
pub mod foreign_doc;
|
||||
#[cfg(feature = "exec-host")]
|
||||
pub mod foreign_session;
|
||||
mod fs;
|
||||
mod hash;
|
||||
|
||||
@@ -34,8 +34,6 @@ 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;
|
||||
|
||||
+36
-2
@@ -3466,6 +3466,7 @@ body.notebook-page .stdin-form button {
|
||||
<button type="button" id="nb-step">Step</button>
|
||||
<button type="button" id="nb-state">State</button>
|
||||
<button type="button" id="nb-journal">Journal</button>
|
||||
<button type="button" id="nb-clear">Clear outputs</button>
|
||||
<button type="button" id="nb-reload">Reload</button>
|
||||
<button type="button" id="nb-debug">Debug</button>
|
||||
<button type="button" id="nb-theme" title="切换浅色/深色主题">浅色</button>
|
||||
@@ -3501,7 +3502,7 @@ body.notebook-page .stdin-form button {
|
||||
if (!window.MARQDO_VIEW_LIVE) return;
|
||||
var path = window.MARQDO_FILE_PATH || "";
|
||||
if (!path) return;
|
||||
var state = { open: false, kernels: [], cells: {} };
|
||||
var state = { open: false, persistent: false, kernels: [], cells: {} };
|
||||
function post(url, body) {
|
||||
return fetch(url, {
|
||||
method: "POST",
|
||||
@@ -3552,6 +3553,7 @@ body.notebook-page .stdin-form button {
|
||||
}
|
||||
function renderSummary(s) {
|
||||
if (!s) return;
|
||||
state.persistent = !!s.persistent;
|
||||
state.kernels = s.kernels || [];
|
||||
state.cells = {};
|
||||
(s.cells || []).forEach(function (c) { state.cells[c.name] = c; });
|
||||
@@ -3559,6 +3561,11 @@ body.notebook-page .stdin-form button {
|
||||
var el = card(c.name);
|
||||
if (!el) return;
|
||||
badge(el, c.status, c.status === "clean");
|
||||
if (!state.persistent) {
|
||||
var old = el.querySelector(".nb-kernel");
|
||||
if (old) old.remove();
|
||||
return;
|
||||
}
|
||||
var sel = el.querySelector(".nb-kernel");
|
||||
if (!sel) {
|
||||
sel = document.createElement("select");
|
||||
@@ -3608,6 +3615,30 @@ body.notebook-page .stdin-form button {
|
||||
status("run all done");
|
||||
});
|
||||
}
|
||||
function clearDom() {
|
||||
document.querySelectorAll(".code-out").forEach(function (el) {
|
||||
el.hidden = true;
|
||||
el.textContent = "";
|
||||
el.classList.remove("err");
|
||||
});
|
||||
document.querySelectorAll(".nb-badge").forEach(function (el) {
|
||||
el.textContent = "never";
|
||||
el.className = "nb-badge";
|
||||
});
|
||||
var exec = document.getElementById("exec-main");
|
||||
if (exec) { exec.hidden = true; exec.textContent = ""; }
|
||||
var stateOut = document.getElementById("nb-state-out");
|
||||
if (stateOut) { stateOut.hidden = true; stateOut.textContent = ""; }
|
||||
var pullOut = document.getElementById("nb-pull-out");
|
||||
if (pullOut) pullOut.textContent = "";
|
||||
}
|
||||
function clearOutputs() {
|
||||
clearDom();
|
||||
post("api/session/clear", {}).then(function (r) {
|
||||
if (r.ok && r.session) renderSummary(r.session);
|
||||
status(r.ok ? "outputs cleared" : (r.error || "clear failed"));
|
||||
}).catch(function (e) { status(String(e)); });
|
||||
}
|
||||
function bind(id, fn) { var b = document.getElementById(id); if (b) b.addEventListener("click", fn); }
|
||||
function init() {
|
||||
var themeBtn = document.getElementById("nb-theme");
|
||||
@@ -3687,6 +3718,7 @@ body.notebook-page .stdin-form button {
|
||||
bind("nb-debug", function () {
|
||||
window.open("debug?path=" + encodeURIComponent(path), "_blank");
|
||||
});
|
||||
bind("nb-clear", clearOutputs);
|
||||
bind("nb-reload", function () {
|
||||
post("api/session/reload", {}).then(function (r) {
|
||||
if (!r.ok) { status(r.error || "reload failed"); return; }
|
||||
@@ -3879,7 +3911,7 @@ window.MARQDO_AUTO_STREAM = {auto_stream};
|
||||
{stdin_panel}
|
||||
{stream_panel}
|
||||
{plan_card}
|
||||
<div class="out {status}">{out}</div>
|
||||
<div class="out {status}" id="exec-main">{out}</div>
|
||||
{plots}
|
||||
</section>
|
||||
<section class="block source-block">
|
||||
@@ -4124,6 +4156,8 @@ mod tests {
|
||||
assert!(ui.contains("post(\"api/session/open\""));
|
||||
assert!(!ui.contains("In ["), "view cells must not mimic Jupyter In[] prompts");
|
||||
assert!(!ui.contains("Out ["), "view cells must not mimic Jupyter Out[] prompts");
|
||||
assert!(ui.contains("id=\"nb-clear\""), "view must expose Clear outputs");
|
||||
assert!(ui.contains("api/session/clear"), "Clear outputs must call the session API");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -189,6 +189,11 @@ fn handle(root: &ViewRoot, request: Request) -> Result<()> {
|
||||
notebook_api::api_close(&root.root, body)
|
||||
})
|
||||
}
|
||||
"/api/session/clear" => {
|
||||
return api_debug_post(request, |body| {
|
||||
notebook_api::api_clear(&root.root, body)
|
||||
})
|
||||
}
|
||||
"/api/session/cell/run" => {
|
||||
return api_debug_post(request, |body| {
|
||||
notebook_api::api_cell_run(&root.root, body)
|
||||
|
||||
@@ -5,7 +5,7 @@ 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::host::foreign_doc::DocumentSession;
|
||||
use crate::value::Value;
|
||||
|
||||
fn sessions() -> &'static Mutex<HashMap<String, Arc<Mutex<DocumentSession>>>> {
|
||||
@@ -151,6 +151,10 @@ where
|
||||
}
|
||||
}
|
||||
|
||||
pub fn api_clear(root: &Path, body: &str) -> serde_json::Value {
|
||||
with_session(root, body, "cleared", |s| Ok(s.clear_outputs()))
|
||||
}
|
||||
|
||||
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("");
|
||||
@@ -281,6 +285,10 @@ mod tests {
|
||||
Some(false),
|
||||
"{failed:?}"
|
||||
);
|
||||
let clear = api_clear(&root, r#"{"path":"shared.mq.md"}"#);
|
||||
assert_eq!(clear.get("ok").and_then(|v| v.as_bool()), Some(true), "{clear:?}");
|
||||
let cleared = clear.get("session").and_then(|s| s.get("cells")).and_then(|c| c.as_array()).cloned().unwrap_or_default();
|
||||
assert!(cleared.iter().all(|c| c.get("runs").and_then(|v| v.as_u64()) == Some(0)));
|
||||
let push = api_state_push(
|
||||
&root,
|
||||
r#"{"path":"shared.mq.md","kernel":"分析","name":"z","value":9}"#,
|
||||
|
||||
@@ -23,6 +23,8 @@ import foreign:lib/foreign.mq.md
|
||||
| 生成报告 | 分析 | ASCII 图 + JSON 报告 |
|
||||
| 独立复核 | 复核 | 另一个内核读取报告做校验 |
|
||||
|
||||
`会话` = > foreign.session kernels=`内核表` cells=`会话表`
|
||||
|
||||
`准备数据` =
|
||||
```python
|
||||
import math
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
---
|
||||
title: notebook shared state
|
||||
import foreign:lib/foreign.mq.md
|
||||
---
|
||||
|
||||
# main
|
||||
@@ -19,6 +20,8 @@ title: notebook shared state
|
||||
| 读取 | 分析 | 读取共享变量 |
|
||||
| 隔离 | 绘图 | 看不到 shared |
|
||||
|
||||
`会话` = > foreign.session kernels=`内核表` cells=`会话表`
|
||||
|
||||
`设置` =
|
||||
```node
|
||||
let shared = 41;
|
||||
|
||||
Reference in new issue
Block a user