From 4ff5739854998585fc4f33944c5dab2d7cc377e3 Mon Sep 17 00:00:00 2001 From: LU XIANGRUI <1078666705@qq.com> Date: Sat, 28 Nov 2026 00:02:19 +0900 Subject: [PATCH] feat(notebook): show the running kernel's variables in a Jupyter Variables tool window (#6517) A Jupyter Variables tool window (bottom, under the stripe's overflow until first opened; also in Find Action) lists the variables of the last active notebook's kernel: name, type and a truncated repr, hiding private names, modules and IPython's own names. It refreshes after a run, a kernel restart and a switch of notebook, and never starts a kernel. The variables are read with a silent execute_request carrying a user expression (no output, history, execution count or busy/idle status), only while the kernel is idle; a run started meanwhile waits for it, bounded to 10 seconds. A notebook tab restored at startup picks up its session once it opens. Closes #6508 Co-authored-by: wildcatDownstairs <26499420+wildcatDownstairs@users.noreply.github.com> --- crates/ide-host/src/notebook.rs | 56 ++++++++++++++- crates/ide-host/src/notebook_variables.py | 23 ++++++ crates/ide-host/src/ops/notebook.rs | 13 ++++ crates/ide-notebook/src/kernel.rs | 58 ++++++++++++++- crates/ide-notebook/src/kernel/transport.rs | 22 ++++-- crates/ide-notebook/tests/kernel_runtime.rs | 20 ++++++ docs/en/guide/notebook.mdx | 6 ++ docs/zh/guide/notebook.mdx | 6 ++ fixtures/README.md | 3 +- fixtures/python-app/notebooks/variables.ipynb | 67 +++++++++++++++++ src-tauri/tests/commands.snap | 1 + src/bindings.ts | 8 +++ .../notebook/VariablesView.module.css | 27 +++++++ src/features/notebook/VariablesView.test.tsx | 28 ++++++++ src/features/notebook/VariablesView.tsx | 72 +++++++++++++++++++ src/features/notebook/index.ts | 24 +++++++ src/features/notebook/session.ts | 14 +++- src/platform/locales/text/en.json | 5 ++ src/platform/locales/text/zh.json | 5 ++ 19 files changed, 449 insertions(+), 9 deletions(-) create mode 100644 crates/ide-host/src/notebook_variables.py create mode 100644 fixtures/python-app/notebooks/variables.ipynb create mode 100644 src/features/notebook/VariablesView.module.css create mode 100644 src/features/notebook/VariablesView.test.tsx create mode 100644 src/features/notebook/VariablesView.tsx diff --git a/crates/ide-host/src/notebook.rs b/crates/ide-host/src/notebook.rs index 3a7055d4af..f8b62ca271 100644 --- a/crates/ide-host/src/notebook.rs +++ b/crates/ide-host/src/notebook.rs @@ -1,11 +1,12 @@ //! Project-incarnation notebook ownership and whole-batch execution admission. use crate::ops::Channel; +use base64::Engine; use ide_core::error::ErrorKind; use ide_core::{CancellationToken, IdeError, IdeEvent, IdeResult, IpcPath, SharedSink}; use ide_notebook::kernel::{KernelManager, KernelOutput}; use ide_notebook::{NotebookDocument, NotebookEdit, NotebookSnapshot}; use parking_lot::Mutex; -use serde::Serialize; +use serde::{Deserialize, Serialize}; use specta::Type; use std::collections::{HashMap, HashSet}; use std::path::{Path, PathBuf}; @@ -28,6 +29,31 @@ pub struct NotebookOutputEvent { pub changed_cells: Vec, } +/// One row of the Jupyter Variables tool window. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)] +pub struct NotebookVariable { + pub name: String, + #[serde(rename = "type")] + pub type_name: String, + pub value: String, +} + +const VARIABLES: &str = include_str!("notebook_variables.py"); + +/// The rows from the `user_expressions` of the variables request. +fn parse_variables(reply: &serde_json::Value) -> IdeResult> { + let rows = &reply["rows"]; + if rows["status"] != "ok" { + let reason = rows["evalue"].as_str().unwrap_or("no result"); + return Err(IdeError::unavailable(format!("could not read the kernel's variables: {reason}"))); + } + // The value is a base64 str, so its text/plain is that text in quotes. + let text = rows["data"]["text/plain"].as_str().unwrap_or_default().trim_matches(['\'', '"']); + let bad = |error: String| IdeError::unavailable(format!("could not read the kernel's variables: {error}")); + let json = base64::engine::general_purpose::STANDARD.decode(text).map_err(|e| bad(e.to_string()))?; + serde_json::from_slice(&json).map_err(|e| bad(e.to_string())) +} + #[derive(Default)] struct Registry { stopped: bool, @@ -323,6 +349,19 @@ impl NotebookService { Ok(()) } + /// The variables of the notebook's running kernel; `None` when no kernel runs. + pub async fn variables(&self, id: &str) -> IdeResult>> { + let document = self.resolve(id)?; + if document.state.lock().active.is_some() { + return Err(IdeError::unavailable("notebook is running")); + } + let expressions = HashMap::from([("rows".to_owned(), "_openidea_variables()".to_owned())]); + match self.kernels.inspect(&document.path, VARIABLES, expressions).await? { + Some(reply) => parse_variables(&reply).map(Some), + None => Ok(None), + } + } + pub(crate) fn admit( &self, id: &str, @@ -588,6 +627,21 @@ mod tests { use super::*; use serde_json::json; + #[test] + fn variables_are_decoded_from_the_user_expression() { + let rows = r#"[{"name": "x", "type": "int", "value": "1"}]"#; + let text = format!("'{}'", base64::engine::general_purpose::STANDARD.encode(rows)); + let reply = json!({"rows": {"status": "ok", "data": {"text/plain": text}, "metadata": {}}}); + assert_eq!( + parse_variables(&reply).unwrap(), + vec![NotebookVariable { name: "x".into(), type_name: "int".into(), value: "1".into() }] + ); + let failed = + json!({"rows": {"status": "error", "ename": "NameError", "evalue": "name 'get_ipython' is not defined"}}); + assert!(parse_variables(&failed).unwrap_err().message.contains("get_ipython")); + assert!(parse_variables(&json!({})).is_err()); + } + fn fixture() -> (tempfile::TempDir, Arc, NotebookSnapshot) { let dir = tempfile::tempdir().unwrap(); let path = dir.path().join("session.ipynb"); diff --git a/crates/ide-host/src/notebook_variables.py b/crates/ide-host/src/notebook_variables.py new file mode 100644 index 0000000000..ee26d7e8eb --- /dev/null +++ b/crates/ide-host/src/notebook_variables.py @@ -0,0 +1,23 @@ +# Run silently on a notebook's kernel by the Jupyter Variables tool window; the IDE then +# evaluates `_openidea_variables()` as a user expression. Same rows as the Python Console's. +def _openidea_variables(): + import base64 + import json + import reprlib + import types + + shell = get_ipython() # noqa: F821 -- defined in every IPython namespace + short = reprlib.Repr() + short.maxstring = short.maxother = 200 + rows = [] + for name, value in list(shell.user_ns.items()): + if name.startswith("_") or name in shell.user_ns_hidden or isinstance(value, types.ModuleType): + continue + try: + text = short.repr(value) + except Exception as error: # a broken __repr__ must not hide the other variables + text = "" % type(error).__name__ + rows.append({"name": name, "type": type(value).__name__, "value": text}) + rows.sort(key=lambda row: row["name"]) + # Base64 so the expression's text/plain (a str repr) needs no unescaping. + return base64.b64encode(json.dumps(rows).encode()).decode() diff --git a/crates/ide-host/src/ops/notebook.rs b/crates/ide-host/src/ops/notebook.rs index 8f34ae9eaf..a7b7e76edc 100644 --- a/crates/ide-host/src/ops/notebook.rs +++ b/crates/ide-host/src/ops/notebook.rs @@ -93,6 +93,18 @@ pub async fn notebook_interrupt(host: &Host, window: &str, id: String) -> IdeRes .map_err(|error| IdeError::internal(error.to_string()))? } +#[command(trust = trusted)] +pub async fn notebook_variables( + host: &Host, + window: &str, + id: String, +) -> IdeResult>> { + let notebooks = host.project(window)?.notebooks.clone(); + tokio::spawn(async move { notebooks.variables(&id).await }) + .await + .map_err(|error| IdeError::internal(error.to_string()))? +} + #[allow(clippy::too_many_arguments)] #[command(trust = trusted)] pub async fn notebook_execute( @@ -162,4 +174,5 @@ ide_command::domain!( notebook_restart, notebook_save, notebook_undo, + notebook_variables, ); diff --git a/crates/ide-notebook/src/kernel.rs b/crates/ide-notebook/src/kernel.rs index 7529904213..5403d1c40a 100644 --- a/crates/ide-notebook/src/kernel.rs +++ b/crates/ide-notebook/src/kernel.rs @@ -55,6 +55,9 @@ impl KernelState { pub struct ExecutionResult { pub status: String, pub execution_count: Option, + /// The reply's `user_expressions`, by name. + #[serde(skip)] + pub user_expressions: Option, } struct Slot { @@ -62,6 +65,8 @@ struct Slot { interrupt: Mutex>, stop: Mutex>, closed: AtomicBool, + /// A silent inspection holds `operation`; a run waits for it instead of failing as busy. + inspecting: AtomicBool, } impl Slot { @@ -71,6 +76,7 @@ impl Slot { interrupt: Mutex::new(None), stop: Mutex::new(None), closed: AtomicBool::new(false), + inspecting: AtomicBool::new(false), } } @@ -97,6 +103,13 @@ impl Drop for ActiveExecution<'_> { } } +struct Inspecting<'a>(&'a Slot); +impl Drop for Inspecting<'_> { + fn drop(&mut self) { + self.0.inspecting.store(false, Ordering::Release); + } +} + pub struct KernelManager { runtime_dir: PathBuf, on_status: StatusCallback, @@ -139,7 +152,11 @@ impl KernelManager { } let _active = ActiveExecution(&slot); // A second caller must not sit in a queue and execute stale source later. - let mut running = slot.operation.try_lock().map_err(|_| IdeError::unavailable("notebook kernel is busy"))?; + let mut running = match slot.operation.try_lock() { + Ok(running) => running, + Err(_) if slot.inspecting.load(Ordering::Acquire) => slot.operation.lock().await, + Err(_) => return Err(IdeError::unavailable("notebook kernel is busy")), + }; if slot.closed.load(Ordering::Acquire) { return Err(IdeError::unavailable("notebook kernel was closed")); } @@ -177,7 +194,8 @@ impl KernelManager { return Err(error); } } - let result = running.as_ref().expect("initialized kernel").execute(code, cancel, interrupt, on_output).await; + let result = + running.as_ref().expect("initialized kernel").execute(code, None, cancel, interrupt, on_output).await; if running.as_ref().is_some_and(transport::Running::is_finished) { if let Some(dead) = running.take() { dead.shutdown().await; @@ -187,6 +205,42 @@ impl KernelManager { result } + /// Runs `code` silently on the notebook's idle kernel and returns the reply's + /// `user_expressions`. Never starts a kernel: `None` when none is running. + pub async fn inspect( + &self, + notebook: &Path, + code: &str, + expressions: HashMap, + ) -> IdeResult> { + let slot = self.slots.lock().get(notebook).cloned(); + let Some(slot) = slot else { return Ok(None) }; + if slot.interrupt.lock().is_some() { + return Err(IdeError::unavailable("notebook kernel is busy")); + } + // Flagged before locking, so a run arriving meanwhile waits rather than failing. + slot.inspecting.store(true, Ordering::Release); + let _inspecting = Inspecting(&slot); + let running = slot.operation.try_lock().map_err(|_| IdeError::unavailable("notebook kernel is busy"))?; + let Some(kernel) = running.as_ref().filter(|r| !r.is_finished() && !slot.closed.load(Ordering::Acquire)) else { + return Ok(None); + }; + // A fixed bound; a wedged `__repr__` is interrupted when the reply is dropped. + let result = tokio::time::timeout( + std::time::Duration::from_secs(10), + kernel.execute( + code, + Some(expressions), + CancellationToken::new(), + CancellationToken::new(), + Arc::new(|_| {}), + ), + ) + .await + .map_err(|_| IdeError::unavailable("kernel did not answer within 10 seconds"))??; + Ok(result.user_expressions) + } + /// Cancels the active request, including startup. The execution future drains /// reply+idle before returning, or stops the owned process on interrupt timeout. pub async fn interrupt(&self, notebook: &Path) -> IdeResult<()> { diff --git a/crates/ide-notebook/src/kernel/transport.rs b/crates/ide-notebook/src/kernel/transport.rs index 46a814b8b7..a9406a06f8 100644 --- a/crates/ide-notebook/src/kernel/transport.rs +++ b/crates/ide-notebook/src/kernel/transport.rs @@ -5,6 +5,7 @@ use jupyter_protocol::{ExecuteRequest, JupyterMessage, KernelInfoRequest, Shutdo use jupyter_zmq_client::{ClientControlConnection, Connection, DealerSendConnection, RawMessage}; use parking_lot::Mutex; use serde_json::Value; +use std::collections::HashMap; use std::path::PathBuf; use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; @@ -33,6 +34,8 @@ impl Drop for Admission { struct Execution { code: String, + /// Set for a silent inspection: no output, history, count or status change. + expressions: Option>, cancel: CancellationToken, interrupt: CancellationToken, output: OutputCallback, @@ -69,6 +72,7 @@ impl Running { pub async fn execute( &self, code: &str, + expressions: Option>, cancel: CancellationToken, interrupt: CancellationToken, output: OutputCallback, @@ -79,6 +83,7 @@ impl Running { let (reply, result) = oneshot::channel(); let execution = Execution { code: code.to_owned(), + expressions, cancel, interrupt, output, @@ -307,18 +312,24 @@ impl Session { if execution.cancel.is_cancelled() || execution.interrupt.is_cancelled() || execution.reply.is_closed() { return Err(IdeError::cancelled()); } + let expressions = execution.expressions.take(); + let silent = expressions.is_some(); let request: JupyterMessage = ExecuteRequest { code: std::mem::take(&mut execution.code), + silent, + store_history: !silent, + user_expressions: expressions, allow_stdin: false, stop_on_error: true, - ..Default::default() } .into(); let request_id = request.header.msg_id.clone(); // If sending fails/times out, delivery is uncertain. Supervisor closes // the process; no caller may retry user code automatically. send(&mut self.shell, request).await?; - status(notebook, KernelState::Busy, None); + if !silent { + status(notebook, KernelState::Busy, None); + } let mut completion = Completion::default(); let mut budget = Budget::default(); let mut interrupted = false; @@ -360,7 +371,9 @@ impl Session { (execution.output)(KernelOutput { kind: frame.kind, content: frame.content, msg_id: frame.parent }); } if completion.complete() { - status(notebook, KernelState::Idle, None); + if !silent { + status(notebook, KernelState::Idle, None); + } if interrupted || execution.cancel.is_cancelled() || execution.interrupt.is_cancelled() { return Err(IdeError::cancelled()); } @@ -443,7 +456,8 @@ impl Completion { .ok_or_else(|| protocol("invalid execution count"))?, ), }; - self.reply = Some(ExecutionResult { status: status.to_owned(), execution_count: count }); + let user_expressions = frame.content.get("user_expressions").cloned(); + self.reply = Some(ExecutionResult { status: status.to_owned(), execution_count: count, user_expressions }); } Ok(()) } diff --git a/crates/ide-notebook/tests/kernel_runtime.rs b/crates/ide-notebook/tests/kernel_runtime.rs index eff49c6e27..e484ce0255 100644 --- a/crates/ide-notebook/tests/kernel_runtime.rs +++ b/crates/ide-notebook/tests/kernel_runtime.rs @@ -320,3 +320,23 @@ async fn changing_selected_python_recreates_kernel_instead_of_reusing_old_enviro ); manager.shutdown().await; } + +#[tokio::test] +#[ignore = "requires OPENIDEA_TEST_PYTHON with real ipykernel"] +async fn inspection_is_silent_and_never_starts_a_kernel() { + let root = tempfile::tempdir().unwrap(); + let notebook = root.path().join("inspect.ipynb"); + let python = python(); + let manager = manager(root.path()); + let expressions = || std::collections::HashMap::from([("v".to_owned(), "answer * 2".to_owned())]); + assert!(manager.inspect(¬ebook, "", expressions()).await.unwrap().is_none()); + let (result, _) = run(&manager, ¬ebook, &python, "answer = 21").await; + assert_eq!(result.unwrap().execution_count, Some(1)); + let reply = manager.inspect(¬ebook, "print('hidden')", expressions()).await.unwrap().unwrap(); + assert_eq!(reply["v"]["status"], "ok"); + assert_eq!(reply["v"]["data"]["text/plain"], "42"); + let (result, outputs) = run(&manager, ¬ebook, &python, "answer").await; + assert_eq!(result.unwrap().execution_count, Some(2), "a silent request must not take an execution count"); + assert!(outputs.iter().all(|o| o.content["text"].as_str().is_none_or(|text| !text.contains("hidden")))); + manager.shutdown().await; +} diff --git a/docs/en/guide/notebook.mdx b/docs/en/guide/notebook.mdx index 9c3e73fe72..8423b4b709 100644 --- a/docs/en/guide/notebook.mdx +++ b/docs/en/guide/notebook.mdx @@ -99,6 +99,12 @@ The script uses `# %%` cell markers, the format VS Code and Jupytext read: **Convert to Jupyter Notebook** on a `.py` file does the reverse: it writes `.ipynb` with a Python 3 kernel and opens it. Each `# %%` (or `#%%`) line starts a cell, `[markdown]` and `[raw]` cells lose their `# ` prefix, and a file without markers becomes a single code cell. Lines commented out on export stay comments. +## Jupyter Variables + +**View › Tool Windows › Jupyter Variables** (or **Jupyter Variables** in Find Action) lists the variables of the last active notebook's kernel: name, type and a short value. It refreshes when a run finishes, after a kernel restart and when you switch to another notebook. Names starting with `_`, modules and the names IPython defines itself are not shown. + +The list is read from the kernel without a visible run: it adds no output, history entry or execution count. It never starts a kernel; run a cell first. + ## Limits - Only Python kernels are supported. Kernels for other languages and remote Jupyter servers are not. diff --git a/docs/zh/guide/notebook.mdx b/docs/zh/guide/notebook.mdx index 7cdcfe14dd..67fe9e9cb1 100644 --- a/docs/zh/guide/notebook.mdx +++ b/docs/zh/guide/notebook.mdx @@ -99,6 +99,12 @@ OpenIDEA 用笔记本编辑器打开 `.ipynb` 文件。你可以编辑代码单 在 `.py` 文件上选择**转换为 Jupyter Notebook** 则反过来:写出使用 Python 3 内核的 `.ipynb` 并打开它。每个 `# %%`(或 `#%%`)行开始一个单元格,`[markdown]` 和 `[raw]` 单元格会去掉 `# ` 前缀,没有标记的文件会成为一个代码单元格。导出时被注释掉的行在转换回来后仍是注释。 +## Jupyter 变量 + +**视图 › 工具窗口 › Jupyter 变量**(或在查找操作中搜索 **Jupyter 变量**)列出最近激活的笔记本的内核变量:名称、类型和简短的值。运行结束、内核重启后以及切换到另一个笔记本时会刷新。以 `_` 开头的名称、模块以及 IPython 自己定义的名称不会显示。 + +变量列表直接从内核读取,不会产生可见的运行:不添加输出、历史记录,也不占用执行编号。它不会启动内核,请先运行一个单元格。 + ## 限制 - 只支持 Python 内核,不支持其他语言的内核,也不能连接远程 Jupyter 服务器。 diff --git a/fixtures/README.md b/fixtures/README.md index f8d31c76db..74f7ffcde1 100644 --- a/fixtures/README.md +++ b/fixtures/README.md @@ -53,7 +53,8 @@ git init -q && git add -A && git commit -qm "initial" # for the VCS checks Then open the folder with **File › Open…** (`⌘⇧⌥O`) or from the Welcome screen. For `ts-app` / `playwright-app` / `mocha-app` / `polyglot/web` run `pnpm install` first (`npm install` for `biome-app`, `cypress-app`, `dprint-app` and `stylelint-app`); for `python-app` create a -venv (`python3 -m venv .venv && .venv/bin/pip install -e '.[dev]'`); for +venv (`python3 -m venv .venv && .venv/bin/pip install -e '.[dev]'`; add `ipykernel` to run +`notebooks/variables.ipynb`, which exercises the Jupyter Variables tool window); for `php-app` run `composer install` (debugging it needs Xdebug in the PHP on `PATH`). Missing language servers / debuggers can be installed from the IDE: diff --git a/fixtures/python-app/notebooks/variables.ipynb b/fixtures/python-app/notebooks/variables.ipynb new file mode 100644 index 0000000000..d8b4285573 --- /dev/null +++ b/fixtures/python-app/notebooks/variables.ipynb @@ -0,0 +1,67 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "cell-0", + "metadata": {}, + "source": [ + "# Kernel variables\n", + "\n", + "Run the cells, then open **Jupyter Variables**." + ] + }, + { + "cell_type": "code", + "id": "cell-1", + "metadata": {}, + "source": [ + "import json\n", + "\n", + "tasks = [\"write\", \"review\", \"ship\"]\n", + "done = {\"write\": True, \"review\": False}\n", + "_scratch = \"hidden: starts with _\"" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "id": "cell-2", + "metadata": {}, + "source": [ + "class Broken:\n", + " def __repr__(self):\n", + " raise RuntimeError(\"no repr\")\n", + "\n", + "\n", + "broken = Broken()\n", + "long_text = \"x\" * 500" + ], + "execution_count": null, + "outputs": [] + }, + { + "cell_type": "code", + "id": "cell-3", + "metadata": {}, + "source": [ + "count = len(tasks)\n", + "count" + ], + "execution_count": null, + "outputs": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "name": "python" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/src-tauri/tests/commands.snap b/src-tauri/tests/commands.snap index 4f095c5d49..75e82a907f 100644 --- a/src-tauri/tests/commands.snap +++ b/src-tauri/tests/commands.snap @@ -460,6 +460,7 @@ notebook_reload always project_host bin notebook_restart trusted project_host bindings async notebook_save always project_host bindings async notebook_undo always project_host bindings async +notebook_variables trusted project_host bindings async open_project always project_host bindings async path_completions always project_host bindings async plugin_activation_event trusted desktop bindings async diff --git a/src/bindings.ts b/src/bindings.ts index cc29d9e42d..2594135d6a 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -1239,6 +1239,7 @@ export const commands = { notebookRestart: (id: string) => typedError(__TAURI_INVOKE("notebook_restart", { id })), notebookSave: (id: string) => typedError(__TAURI_INVOKE("notebook_save", { id })), notebookUndo: (id: string) => typedError(__TAURI_INVOKE("notebook_undo", { id })), + notebookVariables: (id: string) => typedError(__TAURI_INVOKE("notebook_variables", { id })), openProject: (path: string) => typedError(__TAURI_INVOKE("open_project", { path })), /** Files and folders that continue `prefix`, a path being typed in `from`. */ pathCompletions: (from: IpcPath, prefix: string) => typedError(__TAURI_INVOKE("path_completions", { from, prefix })), @@ -10774,6 +10775,13 @@ export type NotebookSnapshot = { cells: NotebookCell[], }; +/** One row of the Jupyter Variables tool window. */ +export type NotebookVariable = { + name: string, + type: string, + value: string, +}; + /** A notification button that runs one of the publishing plugin's commands. */ export type NotificationAction = { label: string, diff --git a/src/features/notebook/VariablesView.module.css b/src/features/notebook/VariablesView.module.css new file mode 100644 index 0000000000..1d09360a03 --- /dev/null +++ b/src/features/notebook/VariablesView.module.css @@ -0,0 +1,27 @@ +.list { + height: 100%; + overflow: auto; + font-family: var(--font-mono); + font-size: var(--fs-code); +} + +.row { + display: flex; + gap: var(--space-2); + padding: var(--space-0-5) var(--space-2); + white-space: nowrap; +} + +.name { + color: var(--fg-editor); +} + +.type { + color: var(--fg-muted); +} + +.value { + overflow: hidden; + text-overflow: ellipsis; + color: var(--fg-editor); +} diff --git a/src/features/notebook/VariablesView.test.tsx b/src/features/notebook/VariablesView.test.tsx new file mode 100644 index 0000000000..7eb90a5eba --- /dev/null +++ b/src/features/notebook/VariablesView.test.tsx @@ -0,0 +1,28 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import { act, cleanup, render, screen } from "@testing-library/react"; +import { closeNotebook, notebookSession } from "./session"; +import { VariablesView } from "./VariablesView"; + +const PATH = "/p/restored.ipynb"; + +vi.mock("@/workbench/contributions", async (original) => ({ + ...(await original()), + maybeEditorService: () => ({ activeInput: () => ({ path: PATH }), onActiveInputChange: () => () => {} }), +})); + +afterEach(async () => { + cleanup(); + await closeNotebook(PATH); +}); + +describe("Jupyter Variables", () => { + it("picks up the session of a notebook tab that was active before the session opened", async () => { + render(); + expect(screen.getByText("No notebook open")).toBeTruthy(); + await act(async () => { + notebookSession(PATH); + await Promise.resolve(); + }); + expect(screen.getByText("No kernel running")).toBeTruthy(); + }); +}); diff --git a/src/features/notebook/VariablesView.tsx b/src/features/notebook/VariablesView.tsx new file mode 100644 index 0000000000..d4b7095bf4 --- /dev/null +++ b/src/features/notebook/VariablesView.tsx @@ -0,0 +1,72 @@ +/** Jupyter Variables tool window: the variables of the last active notebook's kernel. */ +import { useEffect, useState, useSyncExternalStore } from "react"; +import type { NotebookVariable } from "@/bindings"; +import { useTx } from "@/platform/i18n"; +import { call, commands } from "@/platform/ipc"; +import { EmptyState, T } from "@/ui"; +import { maybeEditorService } from "@/workbench/contributions"; +import { existingNotebookSession, onNotebookSessionsChange, type NotebookSession } from "./session"; +import styles from "./VariablesView.module.css"; + +const activePath = () => maybeEditorService()?.activeInput?.()?.path ?? null; +const subscribeActive = (fn: () => void) => maybeEditorService()?.onActiveInputChange?.(fn) ?? (() => {}); +const noSession = { subscribe: () => () => {}, getState: () => null }; + +let lastNotebook: string | null = null; +/** The notebook tab last made active; other tabs keep it. */ +function notebookPath(): string | null { + const path = activePath(); + if (path && /\.ipynb$/i.test(path)) lastNotebook = path; + return lastNotebook; +} + +function useNotebook(): NotebookSession | null { + const path = useSyncExternalStore(subscribeActive, notebookPath); + // A restored notebook tab is active before its session exists. + return useSyncExternalStore(onNotebookSessionsChange, () => (path && existingNotebookSession(path)) || null); +} + +export function VariablesView() { + const session = useNotebook(); + const source = session ?? noSession; + const state = useSyncExternalStore(source.subscribe, source.getState); + const t = useTx(); + // rows null: no kernel running. + const [loaded, setLoaded] = useState<{ id: string; rows: NotebookVariable[] | null } | null>(null); + const id = state?.snapshot?.id; + const settled = !!id && !state.running && !state.frozen && state.kernel === "idle"; + const variables = id && state.kernel !== "dead" && loaded?.id === id ? loaded.rows : null; + + useEffect(() => { + if (!id || !settled) return; + let current = true; + // A busy kernel keeps the last list; the next finished run asks again. + call(commands.notebookVariables(id)).then( + (rows) => current && setLoaded({ id, rows }), + () => {}, + ); + return () => { + current = false; + }; + }, [id, settled]); + + if (!session) return ; + if (!variables) + return ( + + Run a cell to start the kernel. + + ); + if (!variables.length) return ; + return ( +
+ {variables.map((v) => ( +
+ {v.name} + {v.type} + {v.value} +
+ ))} +
+ ); +} diff --git a/src/features/notebook/index.ts b/src/features/notebook/index.ts index 10b50e137b..e9fa04040f 100644 --- a/src/features/notebook/index.ts +++ b/src/features/notebook/index.ts @@ -1,12 +1,15 @@ import type { NotebookSnapshot } from "@/bindings"; import { registerPendingEdits } from "@/editor/api"; +import { registerActions } from "@/platform/actions"; import { basename } from "@/platform/project"; import { lazyComponent } from "@/ui"; import { editorService, registerEditorKind, registerFileEditorProvider, + registerToolWindow, registerUriOpener, + toolWindowService, type EditorDocumentLifecycle, } from "@/workbench/contributions"; import { isTauri } from "@/platform/ipc"; @@ -48,9 +51,30 @@ const document: EditorDocumentLifecycle = { }, }; +const VARIABLES = "jupyterVariables"; + export function activate(): () => void { const disposers = [ registerConversions(), + registerToolWindow({ + id: VARIABLES, + title: "Jupyter Variables", + icon: "file-jupyter", + anchor: "bottom", + // Listed under the stripe's "…" until first opened: most projects have no notebooks. + stripe: "onUse", + order: 28, + component: lazyComponent(() => import("./VariablesView").then((m) => m.VariablesView)), + }), + registerActions([ + { + id: "notebook.variables.show", + title: "Jupyter Variables", + category: "Tools", + when: "projectOpen", + run: () => toolWindowService().show(VARIABLES, true), + }, + ]), registerEditorKind({ kind: "notebook", restorable: true, diff --git a/src/features/notebook/session.ts b/src/features/notebook/session.ts index df65a7a589..740f086ddd 100644 --- a/src/features/notebook/session.ts +++ b/src/features/notebook/session.ts @@ -618,11 +618,20 @@ export class NotebookSession { } const sessions = new Map(); +const sessionListeners = new Set<() => void>(); +// Deferred: a session is often created while a notebook editor renders. +const sessionsChanged = () => queueMicrotask(() => sessionListeners.forEach((fn) => fn())); +/** Calls `fn` after a notebook session opens or closes. */ +export function onNotebookSessionsChange(fn: () => void): () => void { + sessionListeners.add(fn); + return () => void sessionListeners.delete(fn); +} export function notebookSession(path: string): NotebookSession { let session = sessions.get(path); if (!session) { session = new NotebookSession(path); sessions.set(path, session); + sessionsChanged(); } return session; } @@ -638,6 +647,9 @@ export async function closeNotebook(path: string) { try { await session.close(); } finally { - if (sessions.get(path) === session) sessions.delete(path); + if (sessions.get(path) === session) { + sessions.delete(path); + sessionsChanged(); + } } } diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index 188128b754..e4bdf4d12d 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -3977,6 +3977,11 @@ "Unsatisfied package requirements": "Unsatisfied package requirements", "Reports requirements in requirements.txt and pyproject.toml that the project's Python interpreter does not have installed, or whose installed version does not match.": "Reports requirements in requirements.txt and pyproject.toml that the project's Python interpreter does not have installed, or whose installed version does not match.", "Python Console": "Python Console", + "Jupyter Variables": "Jupyter Variables", + "Jupyter variables": "Jupyter variables", + "No notebook open": "No notebook open", + "No kernel running": "No kernel running", + "Run a cell to start the kernel.": "Run a cell to start the kernel.", "Execute Selection in Python Console": "Execute Selection in Python Console", "No Python interpreter": "No Python interpreter", "Select an interpreter for this project to use the Python Console.": "Select an interpreter for this project to use the Python Console.", diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index a1749b8a5f..81996d6537 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -6742,6 +6742,11 @@ "Refresh Python interpreters": "刷新 Python 解释器", "Reload Notebook from Disk": "从磁盘重新加载笔记本", "Restart Kernel": "重启内核", + "Jupyter Variables": "Jupyter 变量", + "Jupyter variables": "Jupyter 变量", + "No notebook open": "没有打开的笔记本", + "No kernel running": "没有运行中的内核", + "Run a cell to start the kernel.": "运行一个单元格以启动内核。", "Retry Pending Edits": "重试待提交更改", "Run All": "运行全部", "Run Cell": "运行单元格",