From 23bbed8bfeaa735c9ea829dd04d043381306e0b7 Mon Sep 17 00:00:00 2001 From: LU XIANGRUI <1078666705@qq.com> Date: Sat, 28 Nov 2026 15:58:28 +0900 Subject: [PATCH] fix(notebook): keep the Jupyter Variables read cheap and out of the way of runs (#6643) Follow-up to #6517. The Variables read shortens bytes, bytearray and str subclasses without building the full repr, and is interrupted after 5 seconds instead of dropped, so a run waiting behind it gets a drained kernel; a read interrupted for its time limit keeps the kernel. Interrupt, restart and close reach an in-flight read, and several reads can be in flight while a run waits for them. Co-authored-by: wildcatDownstairs <26499420+wildcatDownstairs@users.noreply.github.com> --- crates/ide-host/src/notebook.rs | 7 +- crates/ide-host/src/notebook_variables.py | 34 ++++++-- crates/ide-notebook/src/kernel.rs | 66 +++++++++----- crates/ide-notebook/src/kernel/transport.rs | 9 +- crates/ide-notebook/tests/kernel_runtime.rs | 84 ++++++++++++++++++ .../notebook/VariablesView.module.css | 4 + .../notebook/VariablesView.refresh.test.tsx | 85 +++++++++++++++++++ src/features/notebook/VariablesView.tsx | 48 +++++++---- src/features/notebook/index.ts | 12 ++- src/features/notebook/session.test.ts | 22 ++++- src/features/notebook/session.ts | 7 ++ src/features/notebook/variables.test.ts | 55 ++++++++++++ src/platform/locales/text/en.json | 1 + src/platform/locales/text/zh.json | 1 + 14 files changed, 382 insertions(+), 53 deletions(-) create mode 100644 src/features/notebook/VariablesView.refresh.test.tsx create mode 100644 src/features/notebook/variables.test.ts diff --git a/crates/ide-host/src/notebook.rs b/crates/ide-host/src/notebook.rs index f8b62ca271..0698a75890 100644 --- a/crates/ide-host/src/notebook.rs +++ b/crates/ide-host/src/notebook.rs @@ -45,11 +45,12 @@ 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}"))); + return Err(IdeError::new(ErrorKind::Protocol, 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 bad = + |error: String| IdeError::new(ErrorKind::Protocol, 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())) } @@ -355,7 +356,7 @@ impl NotebookService { 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())]); + let expressions = HashMap::from([("rows".to_owned(), r#"globals().pop("_openidea_variables")()"#.to_owned())]); match self.kernels.inspect(&document.path, VARIABLES, expressions).await? { Some(reply) => parse_variables(&reply).map(Some), None => Ok(None), diff --git a/crates/ide-host/src/notebook_variables.py b/crates/ide-host/src/notebook_variables.py index ee26d7e8eb..fa7649e1f8 100644 --- a/crates/ide-host/src/notebook_variables.py +++ b/crates/ide-host/src/notebook_variables.py @@ -1,7 +1,9 @@ -# 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. +# Run silently on a notebook's kernel by the Jupyter Variables tool window. The IDE then +# evaluates `globals().pop("_openidea_variables")()` as a user expression, which also takes +# the function back out of the notebook's namespace. Same rows as the Python Console's. def _openidea_variables(): import base64 + import collections import json import reprlib import types @@ -9,15 +11,33 @@ def _openidea_variables(): shell = get_ipython() # noqa: F821 -- defined in every IPython namespace short = reprlib.Repr() short.maxstring = short.maxother = 200 + limit = short.maxother + items = 100 + containers = (dict, list, tuple, set, frozenset, collections.deque) + + def value_text(value): + # reprlib shortens the exact builtin types itself; for anything else it builds the + # full repr() and then cuts it. That is right for a subclass's own repr (a namedtuple, + # an OrderedDict, a defaultdict), but costs seconds and gigabytes for a big one. + kind = type(value) + if isinstance(value, (str, bytes, bytearray)) and kind is not str and len(value) > limit: + return repr(value[:limit]) + "..." + if isinstance(value, containers) and kind not in containers and len(value) > items: + return "<%s len=%d>" % (kind.__name__, len(value)) + return short.repr(value) + 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): + if name.startswith("_") or name in shell.user_ns_hidden: 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}) + if isinstance(value, types.ModuleType): + continue + kind = type(value).__name__ + text = value_text(value) + except Exception as error: # a broken __repr__ or __class__ must not hide the other variables + kind, text = "?", "" % type(error).__name__ + rows.append({"name": name, "type": kind, "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-notebook/src/kernel.rs b/crates/ide-notebook/src/kernel.rs index 5403d1c40a..dd58d20405 100644 --- a/crates/ide-notebook/src/kernel.rs +++ b/crates/ide-notebook/src/kernel.rs @@ -14,9 +14,14 @@ use specta::Type; use std::collections::HashMap; use std::path::{Path, PathBuf}; use std::sync::Arc; -use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::time::Duration; use tokio::sync::Mutex as AsyncMutex; +/// A read of the variables running longer is interrupted. Its kernel is kept even if it does +/// not drain; an Interrupt then stops it like a run. +const READ_LIMIT: Duration = Duration::from_secs(5); + pub(super) type StatusCallback = Arc) + Send + Sync>; pub(super) type OutputCallback = Arc; @@ -65,8 +70,12 @@ 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, + /// Inspections in flight. One holds `operation`; a run waits for it instead of failing as busy. + inspecting: AtomicUsize, + /// Interrupts the inspection holding `operation`. + inspection: Mutex>, + /// Counts `cancel()` calls, so an inspection sees one that came before its token was set. + interrupts: AtomicUsize, } impl Slot { @@ -76,14 +85,21 @@ impl Slot { interrupt: Mutex::new(None), stop: Mutex::new(None), closed: AtomicBool::new(false), - inspecting: AtomicBool::new(false), + inspecting: AtomicUsize::new(0), + inspection: Mutex::new(None), + interrupts: AtomicUsize::new(0), } } fn cancel(&self) { + self.interrupts.fetch_add(1, Ordering::SeqCst); if let Some(token) = self.interrupt.lock().as_ref() { token.cancel(); } + // A run waiting behind a stuck inspection is interrupted through it. + if let Some(token) = self.inspection.lock().as_ref() { + token.cancel(); + } } fn stop(&self) { @@ -106,7 +122,7 @@ impl Drop for ActiveExecution<'_> { struct Inspecting<'a>(&'a Slot); impl Drop for Inspecting<'_> { fn drop(&mut self) { - self.0.inspecting.store(false, Ordering::Release); + self.0.inspecting.fetch_sub(1, Ordering::AcqRel); } } @@ -154,7 +170,7 @@ impl KernelManager { // A second caller must not sit in a queue and execute stale source later. let mut running = match slot.operation.try_lock() { Ok(running) => running, - Err(_) if slot.inspecting.load(Ordering::Acquire) => slot.operation.lock().await, + Err(_) if slot.inspecting.load(Ordering::Acquire) > 0 => slot.operation.lock().await, Err(_) => return Err(IdeError::unavailable("notebook kernel is busy")), }; if slot.closed.load(Ordering::Acquire) { @@ -218,27 +234,33 @@ impl KernelManager { 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 interrupts = slot.interrupts.load(Ordering::SeqCst); + // Counted before locking, so a run arriving meanwhile waits rather than failing. + slot.inspecting.fetch_add(1, Ordering::AcqRel); 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) + // Interrupt, restart and close reach it through `inspection` and the stop token. + let interrupt = CancellationToken::new(); + *slot.inspection.lock() = Some(interrupt.clone()); + if slot.interrupts.load(Ordering::SeqCst) != interrupts { + interrupt.cancel(); + } + // Interrupted at the limit, never dropped: the waiting run needs the kernel drained. + let limit = CancellationToken::new(); + let timer = tokio::spawn({ + let limit = limit.clone(); + async move { + tokio::time::sleep(READ_LIMIT).await; + limit.cancel(); + } + }); + let result = kernel.execute(code, Some(expressions), limit, interrupt, Arc::new(|_| {})).await; + timer.abort(); + slot.inspection.lock().take(); + Ok(result?.user_expressions) } /// Cancels the active request, including startup. The execution future drains diff --git a/crates/ide-notebook/src/kernel/transport.rs b/crates/ide-notebook/src/kernel/transport.rs index a9406a06f8..18250d0da6 100644 --- a/crates/ide-notebook/src/kernel/transport.rs +++ b/crates/ide-notebook/src/kernel/transport.rs @@ -346,7 +346,8 @@ impl Session { interrupted = true; interrupt_deadline = Some(Instant::now() + INTERRUPT_TIMEOUT); }, - _ = execution.interrupt.cancelled(), if !interrupted => { + // Also after a read's time limit, which leaves no deadline. + _ = execution.interrupt.cancelled(), if interrupt_deadline.is_none() => { self.process.interrupt()?; interrupted = true; interrupt_deadline = Some(Instant::now() + INTERRUPT_TIMEOUT); @@ -358,7 +359,11 @@ impl Session { interrupt_deadline = Some(Instant::now() + INTERRUPT_TIMEOUT); } if interrupt_deadline.is_some_and(|deadline| Instant::now() >= deadline) { - return Err(IdeError::unavailable("kernel did not drain within 5 seconds of interrupt; owned kernel stopped")); + // A read interrupted for its time limit keeps its kernel; Interrupt stops it. + if !silent || execution.interrupt.is_cancelled() { + return Err(IdeError::unavailable("kernel did not drain within 5 seconds of interrupt; owned kernel stopped")); + } + interrupt_deadline = None; } if let Some(message) = self.process.death()? { return Err(IdeError::unavailable(message)); } }, diff --git a/crates/ide-notebook/tests/kernel_runtime.rs b/crates/ide-notebook/tests/kernel_runtime.rs index e484ce0255..ba4eb61c07 100644 --- a/crates/ide-notebook/tests/kernel_runtime.rs +++ b/crates/ide-notebook/tests/kernel_runtime.rs @@ -340,3 +340,87 @@ async fn inspection_is_silent_and_never_starts_a_kernel() { assert!(outputs.iter().all(|o| o.content["text"].as_str().is_none_or(|text| !text.contains("hidden")))); manager.shutdown().await; } + +#[tokio::test] +#[ignore = "requires OPENIDEA_TEST_PYTHON with real ipykernel"] +async fn a_run_waits_for_a_slow_inspection_and_keeps_the_kernel() { + let root = tempfile::tempdir().unwrap(); + let notebook = root.path().join("slow.ipynb"); + let python = python(); + let manager = manager(root.path()); + let (result, _) = run(&manager, ¬ebook, &python, + "import time\nclass Slow:\n def __repr__(self):\n time.sleep(2)\n return 'slow'\nslow = Slow()\nkept = 1").await; + assert_eq!(result.unwrap().status, "ok"); + let expressions = std::collections::HashMap::from([("v".to_owned(), "repr(slow)".to_owned())]); + let inspecting = { + let (manager, notebook) = (manager.clone(), notebook.clone()); + tokio::spawn(async move { manager.inspect(¬ebook, "", expressions).await }) + }; + tokio::time::sleep(Duration::from_millis(500)).await; + // Arrives during the inspection: waits for it instead of failing as busy. + let (result, outputs) = run(&manager, ¬ebook, &python, "kept + 1").await; + assert_eq!(result.unwrap().status, "ok"); + assert!(outputs.iter().any(|o| o.kind == "execute_result" && o.content["data"]["text/plain"] == "2")); + assert_eq!(inspecting.await.unwrap().unwrap().unwrap()["v"]["data"]["text/plain"], "'slow'"); + manager.shutdown().await; +} + +#[tokio::test] +#[ignore = "requires OPENIDEA_TEST_PYTHON with real ipykernel"] +async fn a_stuck_inspection_is_interrupted_at_its_limit_and_the_waiting_run_goes_on() { + let root = tempfile::tempdir().unwrap(); + let notebook = root.path().join("hung.ipynb"); + let python = python(); + let manager = manager(root.path()); + let (result, _) = run( + &manager, + ¬ebook, + &python, + "import time\nclass Hung:\n def __repr__(self):\n time.sleep(600)\nhung = Hung()\nkept = 1", + ) + .await; + assert_eq!(result.unwrap().status, "ok"); + let expressions = std::collections::HashMap::from([("v".to_owned(), "repr(hung)".to_owned())]); + let inspecting = { + let (manager, notebook) = (manager.clone(), notebook.clone()); + tokio::spawn(async move { manager.inspect(¬ebook, "", expressions).await }) + }; + tokio::time::sleep(Duration::from_millis(500)).await; + let started = std::time::Instant::now(); + let (result, outputs) = + tokio::time::timeout(Duration::from_secs(15), run(&manager, ¬ebook, &python, "kept + 1")).await.unwrap(); + assert_eq!(result.unwrap().status, "ok", "the run waits for the read, not fails"); + assert!(outputs.iter().any(|o| o.kind == "execute_result" && o.content["data"]["text/plain"] == "2")); + assert!(started.elapsed() < Duration::from_secs(10)); + assert_eq!(inspecting.await.unwrap().unwrap_err().kind, ErrorKind::Cancelled); + manager.shutdown().await; +} + +#[tokio::test] +#[ignore = "requires OPENIDEA_TEST_PYTHON with real ipykernel"] +async fn interrupt_stops_a_stuck_inspection_and_keeps_state() { + let root = tempfile::tempdir().unwrap(); + let notebook = root.path().join("stuck.ipynb"); + let python = python(); + let manager = manager(root.path()); + let (result, _) = run( + &manager, + ¬ebook, + &python, + "import time\nclass Stuck:\n def __repr__(self):\n time.sleep(600)\nstuck = Stuck()\nkept = 1", + ) + .await; + assert_eq!(result.unwrap().status, "ok"); + let expressions = std::collections::HashMap::from([("v".to_owned(), "repr(stuck)".to_owned())]); + let inspecting = { + let (manager, notebook) = (manager.clone(), notebook.clone()); + tokio::spawn(async move { manager.inspect(¬ebook, "", expressions).await }) + }; + tokio::time::sleep(Duration::from_millis(500)).await; + tokio::time::timeout(Duration::from_secs(10), manager.interrupt(¬ebook)).await.unwrap().unwrap(); + let inspected = tokio::time::timeout(Duration::from_secs(10), inspecting).await.unwrap().unwrap(); + assert_eq!(inspected.unwrap_err().kind, ErrorKind::Cancelled); + let (result, _) = run(&manager, ¬ebook, &python, "kept").await; + assert_eq!(result.unwrap().status, "ok", "the kernel and its state survive"); + manager.shutdown().await; +} diff --git a/src/features/notebook/VariablesView.module.css b/src/features/notebook/VariablesView.module.css index 1d09360a03..60bd19b737 100644 --- a/src/features/notebook/VariablesView.module.css +++ b/src/features/notebook/VariablesView.module.css @@ -25,3 +25,7 @@ text-overflow: ellipsis; color: var(--fg-editor); } + +.error { + overflow-wrap: anywhere; +} diff --git a/src/features/notebook/VariablesView.refresh.test.tsx b/src/features/notebook/VariablesView.refresh.test.tsx new file mode 100644 index 0000000000..84f2cb8663 --- /dev/null +++ b/src/features/notebook/VariablesView.refresh.test.tsx @@ -0,0 +1,85 @@ +import { act, render, screen, waitFor } from "@testing-library/react"; +import { describe, expect, it, vi } from "vitest"; +import type { NotebookViewState } from "./session"; + +const variables = vi.hoisted(() => vi.fn()); +vi.mock("@/platform/ipc", async (orig) => { + const actual = await orig(); + return { + ...actual, + call: (p: Promise) => p, + commands: { ...actual.commands, notebookVariables: variables }, + }; +}); + +// One notebook, with a state the test changes as the session would. +const notebook = vi.hoisted(() => { + const listeners = new Set<() => void>(); + let state = { + snapshot: { id: "nb-1" }, + running: false, + frozen: false, + kernel: "idle", + } as unknown as NotebookViewState; + return { + path: "/p/a.ipynb", + subscribe: (fn: () => void) => (listeners.add(fn), () => listeners.delete(fn)), + getState: () => state, + set(patch: Partial) { + state = { ...state, ...patch }; + listeners.forEach((fn) => fn()); + }, + }; +}); +vi.mock("./session", () => ({ + existingNotebookSession: (path: string) => (path === notebook.path ? notebook : undefined), + notebookSessions: () => [notebook], + onNotebookSessionsChange: () => () => {}, +})); +// A .py tab is active: the window has not seen the notebook's tab yet. +vi.mock("@/workbench/contributions", () => ({ + maybeEditorService: () => ({ activeInput: () => ({ path: "/p/main.py" }), onActiveInputChange: () => () => {} }), +})); + +const { VariablesView } = await import("./VariablesView"); +const row = (name: string, value: string) => ({ name, type: "int", value }); + +describe("Jupyter Variables", () => { + it("shows the open notebook's variables and reads them again after each run", async () => { + variables.mockResolvedValueOnce([row("x", "1")]); + render(); + expect(await screen.findByText("x")).toBeTruthy(); + expect(variables).toHaveBeenCalledTimes(1); + + variables.mockResolvedValueOnce([row("x", "1"), row("y", "2")]); + act(() => notebook.set({ running: true, kernel: "busy" })); + act(() => notebook.set({ kernel: "idle" })); + // Not while the run lasts, even when the kernel is idle between cells. + expect(variables).toHaveBeenCalledTimes(1); + act(() => notebook.set({ running: false })); + expect(await screen.findByText("y")).toBeTruthy(); + expect(variables).toHaveBeenCalledTimes(2); + }); + + it("keeps the list when the kernel is busy and shows other failures", async () => { + const { IpcError } = await import("@/platform/ipc"); + const run = () => { + act(() => notebook.set({ running: true })); + act(() => notebook.set({ running: false })); + }; + variables.mockResolvedValueOnce([row("x", "1")]); + render(); + expect(await screen.findByText("x")).toBeTruthy(); + + variables.mockRejectedValueOnce(new IpcError({ kind: "unavailable", message: "notebook kernel is busy" })); + run(); + await waitFor(() => expect(variables).toHaveBeenCalledTimes(2)); + expect(screen.getByText("x")).toBeTruthy(); + + variables.mockRejectedValueOnce( + new IpcError({ kind: "protocol", message: "could not read the kernel's variables: boom" }), + ); + run(); + expect(await screen.findByText("could not read the kernel's variables: boom")).toBeTruthy(); + }); +}); diff --git a/src/features/notebook/VariablesView.tsx b/src/features/notebook/VariablesView.tsx index d4b7095bf4..82050f4a10 100644 --- a/src/features/notebook/VariablesView.tsx +++ b/src/features/notebook/VariablesView.tsx @@ -2,28 +2,27 @@ import { useEffect, useState, useSyncExternalStore } from "react"; import type { NotebookVariable } from "@/bindings"; import { useTx } from "@/platform/i18n"; -import { call, commands } from "@/platform/ipc"; +import { call, commands, IpcError } from "@/platform/ipc"; import { EmptyState, T } from "@/ui"; import { maybeEditorService } from "@/workbench/contributions"; -import { existingNotebookSession, onNotebookSessionsChange, type NotebookSession } from "./session"; +import { existingNotebookSession, notebookSessions, 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 { +/** The active notebook tab's session, else the session of the notebook active last. */ +function notebookSession(): NotebookSession | null { const path = activePath(); - if (path && /\.ipynb$/i.test(path)) lastNotebook = path; - return lastNotebook; + // A restored notebook tab is active before its session exists: wait for it. + if (path && /\.ipynb$/i.test(path)) return existingNotebookSession(path) ?? null; + return [...notebookSessions()].at(-1) ?? null; } 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); + useSyncExternalStore(subscribeActive, activePath); + return useSyncExternalStore(onNotebookSessionsChange, notebookSession); } export function VariablesView() { @@ -32,25 +31,40 @@ export function VariablesView() { 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 [loaded, setLoaded] = useState<{ id: string; rows: NotebookVariable[] | null; error?: string } | 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; + const current = id && state.kernel !== "dead" && loaded?.id === id ? loaded : null; + const variables = current?.rows ?? null; useEffect(() => { if (!id || !settled) return; - let current = true; - // A busy kernel keeps the last list; the next finished run asks again. + let live = true; call(commands.notebookVariables(id)).then( - (rows) => current && setLoaded({ id, rows }), - () => {}, + (rows) => live && setLoaded({ id, rows }), + (error: unknown) => { + // A busy kernel keeps the last list; the next finished run asks again. + if (!live || (error instanceof IpcError && (error.kind === "unavailable" || error.kind === "cancelled"))) + return; + setLoaded((last) => ({ + id, + rows: last?.id === id ? last.rows : null, + error: String((error as Error).message ?? error), + })); + }, ); return () => { - current = false; + live = false; }; }, [id, settled]); if (!session) return ; + if (current?.error) + return ( + + {current.error} + + ); if (!variables) return ( diff --git a/src/features/notebook/index.ts b/src/features/notebook/index.ts index e9fa04040f..1ede7ae977 100644 --- a/src/features/notebook/index.ts +++ b/src/features/notebook/index.ts @@ -5,6 +5,7 @@ import { basename } from "@/platform/project"; import { lazyComponent } from "@/ui"; import { editorService, + maybeEditorService, registerEditorKind, registerFileEditorProvider, registerToolWindow, @@ -15,7 +16,14 @@ import { import { isTauri } from "@/platform/ipc"; import { ProviderAcquisitions } from "@/workbench/providerAcquisition"; import { registerConversions } from "./convert"; -import { closeNotebook, existingNotebookSession, notebookBackend, notebookSession, notebookSessions } from "./session"; +import { + closeNotebook, + existingNotebookSession, + markNotebookActive, + notebookBackend, + notebookSession, + notebookSessions, +} from "./session"; const acquisitions = new ProviderAcquisitions( (snapshot) => existingNotebookSession(snapshot.path)?.getState().snapshot?.id === snapshot.id, @@ -129,6 +137,8 @@ export function activate(): () => void { } }, }), + // Jupyter Variables falls back to the notebook active last. + maybeEditorService()?.onActiveInputChange?.((input) => input?.path && markNotebookActive(input.path)) ?? (() => {}), ]; return () => disposers.reverse().forEach((dispose) => dispose()); } diff --git a/src/features/notebook/session.test.ts b/src/features/notebook/session.test.ts index 4ba6cd7dcc..bede0e5c87 100644 --- a/src/features/notebook/session.test.ts +++ b/src/features/notebook/session.test.ts @@ -4,7 +4,15 @@ import { EditorState } from "@codemirror/state"; import type { IdeEvent, NotebookSnapshot } from "@/bindings"; import { IpcError } from "@/platform/ipc"; import type * as Ipc from "@/platform/ipc"; -import { caretAfterHistory, NotebookSession, notebookBackend } from "./session"; +import { + caretAfterHistory, + closeNotebook, + markNotebookActive, + NotebookSession, + notebookBackend, + notebookSession, + notebookSessions, +} from "./session"; type KernelEvent = Extract; const kernelListeners = vi.hoisted(() => new Set<(event: KernelEvent) => void>()); @@ -681,3 +689,15 @@ describe("undo and redo keep the focused cell's caret", () => { await session.close(); }); }); + +describe("notebookSessions", () => { + it("ends with the notebook made active last", async () => { + const [a, b] = ["/p/a.ipynb", "/p/b.ipynb"]; + notebookSession(a); + notebookSession(b); + markNotebookActive(a); + markNotebookActive("/p/unopened.ipynb"); + expect([...notebookSessions()].map((s) => s.path)).toEqual([b, a]); + await Promise.all([closeNotebook(a), closeNotebook(b)]); + }); +}); diff --git a/src/features/notebook/session.ts b/src/features/notebook/session.ts index 740f086ddd..251b41298e 100644 --- a/src/features/notebook/session.ts +++ b/src/features/notebook/session.ts @@ -638,9 +638,16 @@ export function notebookSession(path: string): NotebookSession { export function existingNotebookSession(path: string) { return sessions.get(path); } +/** Open sessions, the notebook made active last at the end. */ export function notebookSessions(): Iterable { return sessions.values(); } +export function markNotebookActive(path: string) { + const session = sessions.get(path); + if (!session) return; + sessions.delete(path); + sessions.set(path, session); +} export async function closeNotebook(path: string) { const session = sessions.get(path); if (!session) return; diff --git a/src/features/notebook/variables.test.ts b/src/features/notebook/variables.test.ts new file mode 100644 index 0000000000..c72e356760 --- /dev/null +++ b/src/features/notebook/variables.test.ts @@ -0,0 +1,55 @@ +// @vitest-environment node +import { spawnSync } from "node:child_process"; +import { fileURLToPath } from "node:url"; +import { expect, it } from "vitest"; + +// The script the Jupyter Variables window runs on the kernel (crates/ide-host), run here with a +// stand-in for IPython's shell and the same user expression. +const SCRIPT = fileURLToPath(new URL("../../../crates/ide-host/src/notebook_variables.py", import.meta.url)); +const PYTHON = ["python3", "python"].find((p) => spawnSync(p, ["--version"]).status === 0); + +const HARNESS = ` +import base64, builtins, collections, json, sys +class Shell: pass +shell = Shell() +builtins.get_ipython = lambda: shell +ns = {"get_ipython": builtins.get_ipython} +class Proxy: + @property + def __class__(self): raise RuntimeError("no class") +class Loud: + def __repr__(self): raise ValueError("no repr") +class Tagged(dict): + def __repr__(self): return "Tagged!" +Point = collections.namedtuple("Point", "x y") +shell.user_ns = ns +shell.user_ns_hidden = {"In": 1, "get_ipython": 1} +ns.update(In=[], tasks=["a", "b"], _private=1, json=json, proxy=Proxy(), loud=Loud(), tagged=Tagged(a=1), + point=Point(1, 2), ordered=collections.OrderedDict(b=1, a=2), blob=b"x" * 1000, + counts=collections.Counter(range(1000))) +exec(open(sys.argv[1]).read(), ns) +rows = json.loads(base64.b64decode(eval('globals().pop("_openidea_variables")()', ns))) +print(json.dumps({"rows": rows, "left": "_openidea_variables" in ns})) +`; + +it.skipIf(!PYTHON)("lists user variables, shortened, and survives broken objects", () => { + const result = spawnSync(PYTHON!, ["-I", "-S", "-c", HARNESS, SCRIPT], { encoding: "utf8" }); + expect(result.stderr).toBe(""); + const { rows, left } = JSON.parse(result.stdout); + const byName = Object.fromEntries(rows.map((r: { name: string }) => [r.name, r])); + // Hidden: IPython's own names, `_` names and modules. + expect(Object.keys(byName)).toEqual(["blob", "counts", "loud", "ordered", "point", "proxy", "tagged", "tasks"]); + expect(byName.tasks).toEqual({ name: "tasks", type: "list", value: "['a', 'b']" }); + expect(byName.blob.value).toMatch(/^b'x{200}'\.\.\.$/); + // A big subclass would build its full repr(): only its size is shown. + expect(byName.counts.value).toBe(""); + // A small one keeps its own repr. + expect(byName.point.value).toBe("Point(x=1, y=2)"); + // In insertion order (the form changed in Python 3.12). + expect(byName.ordered.value).toMatch(/^OrderedDict\(.*'b'.*'a'.*\)$/); + expect(byName.tagged.value).toBe("Tagged!"); + // reprlib catches a failing __repr__ itself. + expect(byName.loud).toMatchObject({ type: "Loud", value: expect.stringMatching(/^$/) }); + expect(byName.proxy).toEqual({ name: "proxy", type: "?", value: "" }); + expect(left).toBe(false); +}); diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.json index ccd8412e1e..6f3f99a4c7 100644 --- a/src/platform/locales/text/en.json +++ b/src/platform/locales/text/en.json @@ -4016,6 +4016,7 @@ "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", + "Could not read the variables": "Could not read the variables", "Jupyter variables": "Jupyter variables", "No notebook open": "No notebook open", "No kernel running": "No kernel running", diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.json index 84d84a3699..08752dacd3 100644 --- a/src/platform/locales/text/zh.json +++ b/src/platform/locales/text/zh.json @@ -6811,6 +6811,7 @@ "Reload Notebook from Disk": "从磁盘重新加载笔记本", "Restart Kernel": "重启内核", "Jupyter Variables": "Jupyter 变量", + "Could not read the variables": "无法读取变量", "Jupyter variables": "Jupyter 变量", "No notebook open": "没有打开的笔记本", "No kernel running": "没有运行中的内核",