Skip to content

Visual Studio Code, rebuilt in Rust

Rust

feat(notebook): add cell execute menu, kernel sources and variables view

rokartur27289f70c8b0
diff --git a/native/crates/app/src/menus.rs b/native/crates/app/src/menus.rs
index 25927ed2c05..af4522afe56 100644
--- a/native/crates/app/src/menus.rs
+++ b/native/crates/app/src/menus.rs
@@ -134,6 +134,12 @@ pub enum MenuId {
NotebookCellDelete,
/// `MenuId.NotebookCellInsert`: the cell toolbar's Insert Cell submenu.
NotebookCellInsert,
+ /// `MenuId.NotebookCellExecute`: the dropdown beside a code cell's run button.
+ NotebookCellExecute,
+ /// `MenuId.NotebookKernelSource`: the kernel sources the kernel picker offers.
+ NotebookKernelSource,
+ /// `MenuId.NotebookVariablesContext`: a Notebook Variables row's context menu.
+ NotebookVariablesContext,
/// `MenuId.InteractiveCellTitle` and `InteractiveCellDelete`: the cell toolbar of an interactive window or REPL.
InteractiveCellTitle,
InteractiveCellDelete,
@@ -543,6 +549,7 @@ const WORKBENCH_MENUS: &[Row] = &[
// shortcut: the `inline` View Binary Data items wait for the rows' action bars (ledger debug row).
(MenuId::DebugVariablesContext, None, "debug.setVariable", "Set Value", "3_modification", 10., Some("debugSetVariableSupported || variableEvaluateNamePresent && debugSetExpressionSupported"), Some("!variableIsReadonly")),
(MenuId::DebugVariablesContext, None, "workbench.debug.viewlet.action.copyValue", "Copy Value", "5_cutcopypaste", 10., None, None),
+ (MenuId::NotebookVariablesContext, None, "workbench.debug.viewlet.action.copyWorkspaceVariableValue", "Copy Value", "navigation", 20., Some("variableValue"), None),
(MenuId::DebugVariablesContext, None, "debug.copyEvaluatePath", "Copy as Expression", "5_cutcopypaste", 20., Some("variableEvaluateNamePresent"), None),
(MenuId::DebugVariablesContext, None, "debug.addToWatchExpressions", "Add to Watch", "z_commands", 100., Some("variableEvaluateNamePresent"), None),
(MenuId::DebugVariablesContext, None, "debug.breakWhenValueIsRead", "Break on Value Read", "z_commands", 200., Some("breakWhenValueIsReadSupported"), None),
@@ -750,6 +757,8 @@ const WORKBENCH_MENUS: &[Row] = &[
(MenuId::NotebookCellTitle, None, "notebook.cell.split", "Split Cell", "inline/cell", 5., Some("notebookEditable && notebookCellEditable && !notebookCellInputIsCollapsed"), None),
(MenuId::NotebookCellTitle, None, "notebook.cell.clearOutputs", "Clear Cell Outputs", "inline/output", 6., Some("notebookCellType == 'code' && (notebookKernelCount > 0 || notebookKernelSourceCount > 0) && notebookCellHasOutputs && notebookEditable && notebookCellEditable && !config.notebook.consolidatedOutputButton"), None),
(MenuId::NotebookCellDelete, None, "notebook.cell.delete", "Delete Cell", "inline/cell", 0., Some("notebookEditable"), None),
+ (MenuId::NotebookCellExecute, None, "notebook.cell.executeCellsAbove", "Execute Above Cells", "", 0., Some("notebookCellType == 'code' && (notebookKernelCount > 0 || notebookKernelSourceCount > 0 || notebookMissingKernelExtension) && config.notebook.consolidatedRunButton == true"), None),
+ (MenuId::NotebookCellExecute, None, "notebook.cell.executeCellAndBelow", "Execute Cell and Below", "", 0., Some("notebookCellType == 'code' && (notebookKernelCount > 0 || notebookKernelSourceCount > 0 || notebookMissingKernelExtension) && config.notebook.consolidatedRunButton == true"), None),
(MenuId::InteractiveCellDelete, None, "notebook.cell.delete", "Delete Cell", "inline/cell", 0., None, None),
// The cell toolbar's `...`: notebookClipboard.ts, coreActions.ts, cellCommands.ts and layoutActions.ts in
// `CellOverflowToolbarGroups`; Show Cell Line Numbers is added in `workbench_menus` for its check.
@@ -1031,6 +1040,9 @@ const API_MENUS: &[(&str, MenuId)] = &[
("interactive/toolbar", MenuId::InteractiveToolbar),
("notebook/toolbar", MenuId::NotebookToolbar),
("notebook/cell/title", MenuId::NotebookCellTitle),
+ ("notebook/cell/execute", MenuId::NotebookCellExecute),
+ ("notebook/kernelSource", MenuId::NotebookKernelSource),
+ ("notebook/variables/context", MenuId::NotebookVariablesContext),
("interactive/cell/title", MenuId::InteractiveCellTitle),
("scm/sourceControl", MenuId::ScmSourceControl),
("scm/repositories/title", MenuId::ScmSourceControlTitle),
@@ -1190,6 +1202,7 @@ pub fn extension_menus(extensions: &[ScannedExtension]) -> Vec<MenuItem> {
"diffEditor/gutter/selection" => Some("contribDiffEditorGutterToolBarMenus"),
"scm/historyItemRef/context" => Some("contribSourceControlHistoryItemMenu"),
"viewContainer/title" => Some("contribViewContainerTitle"),
+ "notebook/kernelSource" => Some("notebookKernelSource"),
_ => None,
};
if let Some(proposal) = proposal.filter(|proposal| !extension.description["enabledApiProposals"].as_array().is_some_and(|proposals| proposals.iter().any(|enabled| enabled == proposal))) {
diff --git a/native/crates/app/src/menus/tests.rs b/native/crates/app/src/menus/tests.rs
index d8b81d6e732..675f5c602bb 100644
--- a/native/crates/app/src/menus/tests.rs
+++ b/native/crates/app/src/menus/tests.rs
@@ -192,11 +192,14 @@ fn api_menu_keys_reach_their_menus() {
("viewContainer/title", MenuId::ViewContainerTitle),
("extension/context", MenuId::ExtensionContext),
("editor/title/run", MenuId::EditorTitleRun),
+ ("notebook/cell/execute", MenuId::NotebookCellExecute),
+ ("notebook/kernelSource", MenuId::NotebookKernelSource),
+ ("notebook/variables/context", MenuId::NotebookVariablesContext),
];
for (key, menu) in keys {
let item = json!({ "command": "k.run", "when": "viewContainer == workbench.view.debug" });
let mut contributor = extension("k", json!({ "commands": [{ "command": "k.run", "title": "Run" }], "menus": { key: [item] } }));
- contributor.description["enabledApiProposals"] = json!(["contribSourceControlHistoryItemMenu", "contribViewContainerTitle"]);
+ contributor.description["enabledApiProposals"] = json!(["contribSourceControlHistoryItemMenu", "contribViewContainerTitle", "notebookKernelSource"]);
let items = extension_menus(&[contributor]);
let reached: Vec<_> = items.iter().map(|item| item.menu).collect();
assert_eq!(reached, [menu], "{key}");
diff --git a/native/crates/app/src/workbench.rs b/native/crates/app/src/workbench.rs
index 1901c4b26e0..50b33e499ec 100644
--- a/native/crates/app/src/workbench.rs
+++ b/native/crates/app/src/workbench.rs
@@ -138,6 +138,7 @@ pub mod logs_actions;
pub mod interactive;
mod kernel_picker;
mod notebook_editor;
+mod notebook_variables;
mod repl_notebook;
mod notebook_outline;
mod notebook_status_bar;
@@ -505,6 +506,7 @@ pub struct Workbench {
pub search_editor_widget: search_editor_widget::SearchEditorWidget,
pub webview_panels: webview_panels::WebviewPanels,
notebook_views: notebook_editor::NotebookViews,
+ notebook_variables: notebook_variables::NotebookVariables,
/// breadcrumbsControl.ts `_updateEditorTypeControl` per group: computed when the group's active editor (or the
/// two settings) changes, keyed by that state, never when extensions register editors afterwards.
editor_type_controls: std::cell::RefCell<HashMap<u32, (String, Option<editor_type_picker::EditorTypes>)>>,
@@ -890,6 +892,7 @@ impl Workbench {
search_editor_widget: search_editor_widget::SearchEditorWidget::new(cx),
webview_panels: Default::default(),
notebook_views: notebook_editor::NotebookViews::new(cx),
+ notebook_variables: Default::default(),
editor_type_controls: Default::default(),
memento_custom_editors: None,
scm: scm_view::ScmView::new(cx),
@@ -1245,6 +1248,8 @@ impl Workbench {
self.reveal_active_file();
self.record_editor_history();
self.capture_notebook_status_editor();
+ self.init_notebook_variables_view(None, cx);
+ self.notebook_variables_editor_changed(cx);
self.drop_closed_search_editors();
self.drop_closed_playground();
self.sync_terminal_editors(cx);
diff --git a/native/crates/app/src/workbench/configuration.rs b/native/crates/app/src/workbench/configuration.rs
index 555047a99f4..032ff3ec0df 100644
--- a/native/crates/app/src/workbench/configuration.rs
+++ b/native/crates/app/src/workbench/configuration.rs
@@ -166,6 +166,9 @@ impl Workbench {
if affects(change, "scm.repositories.explorer") || affects(change, "scm.repositories.selectionMode") {
self.scm_explorer_changed(cx);
}
+ if affects(change, "notebook.variablesView") {
+ self.init_notebook_variables_view(None, cx);
+ }
if affects(change, "notebook.undoRedoPerCell") {
self.update_cell_undo_redo_comparison_key();
}
diff --git a/native/crates/app/src/workbench/debug_view.rs b/native/crates/app/src/workbench/debug_view.rs
index 09143971c79..c086475fcb2 100644
--- a/native/crates/app/src/workbench/debug_view.rs
+++ b/native/crates/app/src/workbench/debug_view.rs
@@ -12,6 +12,7 @@ use super::Workbench;
use super::call_stack_menu::CallStackItem;
use super::hover::{HoverContent, HoverOptions};
use super::input_box_view::{InputId, InputLook};
+use super::notebook_variables::NOTEBOOK_VARIABLES_VIEW;
use super::variable_menu::VariableMenuRow;
use crate::debug::session::{Session, StackFrame, State, Variable};
use crate::input_box::InputBox;
@@ -92,7 +93,7 @@ impl DebugView {
run_to_cursor: None,
selected: None,
focused_row: None,
- list_focus: [VARIABLES_VIEW, WATCH_VIEW, CALL_STACK_VIEW, BREAKPOINTS_VIEW, LOADED_SCRIPTS_VIEW].into_iter().map(|id| (id, cx.focus_handle())).collect(),
+ list_focus: [VARIABLES_VIEW, WATCH_VIEW, CALL_STACK_VIEW, BREAKPOINTS_VIEW, LOADED_SCRIPTS_VIEW, NOTEBOOK_VARIABLES_VIEW].into_iter().map(|id| (id, cx.focus_handle())).collect(),
hint: None,
widget_view: Default::default(),
widget_focus: cx.focus_handle(),
@@ -136,6 +137,9 @@ impl Workbench {
if !self.debug.model.breakpoints.is_empty() || !self.debug.model.function_breakpoints.is_empty() || !self.debug.model.exception_breakpoints.is_empty() {
views.push((BREAKPOINTS_VIEW, false));
}
+ if self.notebook_variables.registered {
+ views.push((NOTEBOOK_VARIABLES_VIEW, false));
+ }
return views;
}
let loaded = self.debug.focused_session().is_some_and(|session| session.capabilities["supportsLoadedSourcesRequest"] == true);
@@ -144,6 +148,10 @@ impl Workbench {
if loaded {
views.insert(3, (LOADED_SCRIPTS_VIEW, true));
}
+ // notebookVariables.ts `initializeView`: order 50, after Breakpoints.
+ if self.notebook_variables.registered {
+ views.push((NOTEBOOK_VARIABLES_VIEW, false));
+ }
views
}
@@ -347,6 +355,9 @@ impl Workbench {
/// A view of the container as a pane: its name, its title actions and its rows.
pub(super) fn debug_view_pane(&self, id: &'static str, window: &Window, cx: &mut Context<Self>) -> super::view_panes::ViewPane {
+ if id == NOTEBOOK_VARIABLES_VIEW {
+ return self.notebook_variables_pane(window, cx);
+ }
let (title, actions) = match id {
WATCH_VIEW => ("Watch", vec![("add", "workbench.debug.viewlet.action.addWatchExpression", true), ("close-all", "workbench.debug.viewlet.action.removeAllWatchExpressions", !self.debug.model.watch_expressions.is_empty())]),
BREAKPOINTS_VIEW => (
@@ -593,7 +604,7 @@ impl Workbench {
}
}
- fn row_selected(&self, key: &str) -> bool {
+ pub(super) fn row_selected(&self, key: &str) -> bool {
self.debug_view.selected.as_deref() == Some(key)
}
diff --git a/native/crates/app/src/workbench/kernel_picker.rs b/native/crates/app/src/workbench/kernel_picker.rs
index 974ad495354..be44b90d186 100644
--- a/native/crates/app/src/workbench/kernel_picker.rs
+++ b/native/crates/app/src/workbench/kernel_picker.rs
@@ -7,7 +7,9 @@ use serde_json::{Value, json};
use super::Workbench;
use crate::commands::Outcome;
+use crate::contextkey::Context as ContextKeys;
use crate::extension_enablement::EnablementState;
+use crate::menus::{MenuAction, MenuId, MenuItem, menu_actions};
use crate::notebook::kernels::{Kernel, association_args};
use crate::quick_input::{Button, Entry, Item, Kind, QuickInput};
@@ -27,6 +29,19 @@ enum SourcePick {
Install(Vec<String>),
/// `install`: Browse marketplace for kernel extensions.
Marketplace,
+ /// `isSourcePick`: a `notebook/kernelSource` command, run with the notebook (`SourceAction.runAction`).
+ Action { id: String, title: String },
+}
+
+/// notebookKernelServiceImpl.ts `getSourceActions`: the commands of `MenuId.NotebookKernelSource` whose `when` holds.
+pub(super) fn kernel_source_actions(menus: &[MenuItem], context: &dyn ContextKeys) -> Vec<(String, String)> {
+ let mut actions = Vec::new();
+ for action in menu_actions(menus, MenuId::NotebookKernelSource, context) {
+ if let MenuAction::Command { id, title, .. } = action {
+ actions.push((id, title));
+ }
+ }
+ actions
}
impl Workbench {
@@ -130,7 +145,7 @@ impl Workbench {
let Some(key) = self.active_notebook_editor().map(|editor| editor.notebook.clone()) else { return Outcome::Ready(Ok(json!(false))) };
let model = self.host.notebooks.model(&key).expect("an editor shows an open notebook");
let (view_type, uri) = (model.view_type.clone(), model.uri.clone());
- let picks = self.kernel_sources(&key, &view_type);
+ let picks = self.kernel_sources(&key, &view_type, window);
let mut input = QuickInput::new(0, Kind::QuickPick);
input.title = Some(if kernel_list_empty { "Select Kernel" } else { "Select Another Kernel" }.into());
input.placeholder = Some("Type to choose a kernel source".into());
@@ -155,6 +170,7 @@ impl Workbench {
SourcePick::Group { source, kernels } => workbench.show_extension_kernel_picker(&source, &kernels, &view_type, &uri, window, cx),
SourcePick::Marketplace => workbench.show_kernel_extensions(&view_type, &[], window, cx),
SourcePick::Install(ids) => workbench.show_kernel_extensions(&view_type, &ids, window, cx),
+ SourcePick::Action { id, title } => workbench.run_kernel_source_action(&key, &uri, &id, &title, window, cx),
}
});
let _ = sender.send(match outcome {
@@ -167,10 +183,12 @@ impl Workbench {
Outcome::Pending(receiver)
}
- /// `_calculdateKernelSources` (source actions are not asked: the port has no kernel source action providers).
- fn kernel_sources(&self, key: &str, view_type: &str) -> Vec<(Item, SourcePick)> {
+ /// `_calculdateKernelSources`: the kernels by extension, then the `notebook/kernelSource` actions (the port has no
+ /// `registerKernelSourceActionProvider` providers).
+ fn kernel_sources(&self, key: &str, view_type: &str, window: &Window) -> Vec<(Item, SourcePick)> {
let (all, _) = self.host.notebooks.kernels.matching(view_type, key);
- if all.is_empty() {
+ let actions = kernel_source_actions(&self.menus, &self.key_context(window));
+ if all.is_empty() && actions.is_empty() {
return self.kernel_recommendations(key);
}
let mut groups: Vec<(String, Vec<&Kernel>)> = Vec::new();
@@ -191,9 +209,40 @@ impl Workbench {
let ids = kernels.iter().map(|kernel| kernel.id.clone()).collect();
picks.push((Item { label: source.clone(), pickable: true, ..Default::default() }, SourcePick::Group { source, kernels: ids }));
}
+ for (id, title) in actions {
+ picks.push((Item { label: title.clone(), pickable: true, ..Default::default() }, SourcePick::Action { id, title }));
+ }
picks
}
+ /// `SourceAction.runAction`: the command with the notebook (`MarshalledId.NotebookActionContext`); while it runs
+ /// the kernel status shows its label, and a second pick waits for the same run.
+ fn run_kernel_source_action(&mut self, key: &str, uri: &Value, id: &str, title: &str, window: &mut Window, cx: &mut Context<Self>) -> Outcome {
+ if self.notebook_views.running_sources.contains_key(key) {
+ return Outcome::Ready(Ok(json!(true)));
+ }
+ self.notebook_views.running_sources.insert(key.to_owned(), title.to_owned());
+ cx.notify();
+ let run = self.execute_command(id, vec![json!({ "uri": uri, "$mid": 14 })], window, cx);
+ let key = key.to_owned();
+ let (sender, receiver) = futures::channel::oneshot::channel();
+ cx.spawn(async move |workbench, cx| {
+ if let Outcome::Pending(pending) = run {
+ // `_runAction` only warns when the command fails.
+ if let Ok(Err(error)) = pending.await {
+ eprintln!("Kernel source command failed: {error}");
+ }
+ }
+ let _ = workbench.update(cx, |workbench, cx| {
+ workbench.notebook_views.running_sources.remove(&key);
+ cx.notify();
+ });
+ let _ = sender.send(Ok(json!(true)));
+ })
+ .detach();
+ Outcome::Pending(receiver)
+ }
+
/// `_getKernelRecommendationsQuickPickItems`: Install/Enable suggested extensions for a Python notebook (none
/// when they are installed and enabled: they may still be detecting kernels), then Browse marketplace.
fn kernel_recommendations(&self, key: &str) -> Vec<(Item, SourcePick)> {
diff --git a/native/crates/app/src/workbench/notebook_editor.rs b/native/crates/app/src/workbench/notebook_editor.rs
index 9949d4821df..3fe823e37ee 100644
--- a/native/crates/app/src/workbench/notebook_editor.rs
+++ b/native/crates/app/src/workbench/notebook_editor.rs
@@ -111,6 +111,9 @@ pub struct NotebookViews {
cell_clipboard: Option<(Vec<Value>, bool)>,
/// `CellViewModel.lineNumbers` other than `inherit`, by cell URI: whether the cell shows line numbers.
cell_line_numbers: HashMap<String, bool>,
+ /// notebookKernelServiceImpl.ts `getRunningSourceActions`: the label of the kernel source action running, by
+ /// notebook.
+ pub(super) running_sources: HashMap<String, String>,
}
impl NotebookViews {
@@ -127,6 +130,7 @@ impl NotebookViews {
find: find::NotebookFind::new(cx),
view_states: Default::default(),
cell_line_numbers: HashMap::new(),
+ running_sources: HashMap::new(),
}
}
}
@@ -145,6 +149,8 @@ struct NotebookView {
shown_empty: HashSet<String>,
/// The cell whose toolbar `...` dropdown is open (`cell-toolbar-dropdown-active`).
toolbar_menu: Option<u64>,
+ /// The cell whose run button dropdown is open (`cell-run-toolbar-dropdown-active`).
+ run_menu: Option<u64>,
/// Header cells whose section is collapsed (foldingModel.ts), by handle.
collapsed: HashSet<u64>,
/// A cell editor had the keyboard at the last render (`editorFocused` of the view state).
@@ -1128,7 +1134,7 @@ impl Workbench {
fn notebook_toolbar(&self, model: &NotebookModel, window: &Window, cx: &mut Context<Self>) -> Div {
let foreground = self.color("foreground");
let icon_color = self.color("icon.foreground");
- let button = |id: &'static str, icon: &str, label: &str, command: &'static str, args: Vec<Value>, cx: &mut Context<Self>| {
+ let button = |id: &'static str, icon: &'static str, label: &str, command: &'static str, args: Vec<Value>, cx: &mut Context<Self>| {
div()
.id(id)
.h(px(22.))
@@ -1139,15 +1145,19 @@ impl Workbench {
.rounded(px(4.))
.cursor_pointer()
.hover(|button| button.bg(self.color("toolbar.hoverBackground")))
- .child(self.icon(icon, 16., 16., icon_color))
+ .child(self.badge_icon(icon, 16., icon_color))
.child(label.to_owned())
.on_click(cx.listener(move |workbench, _: &ClickEvent, window, cx| {
drop(workbench.execute_command(command, args.clone(), window, cx));
}))
};
- // `updateKernelStatusAction`: the bound kernel, else the only one.
+ // `updateKernelStatusAction`: a running kernel source action with the spinning executing icon, else the bound
+ // kernel, else the only one.
let kernel = self.host.notebooks.kernels.resolve(&model.view_type, &model.uri_string()).map(|kernel| kernel.label.clone());
- let kernel_label = kernel.unwrap_or("Select Kernel".into());
+ let (kernel_icon, kernel_label) = match self.notebook_views.running_sources.get(&model.uri_string()) {
+ Some(action) => ("sync~spin", action.clone()),
+ None => ("server-environment", kernel.unwrap_or("Select Kernel".into())),
+ };
let toolbar = div().h(px(TOOLBAR_HEIGHT)).flex_none().px(px(8.)).flex().items_center().gap(px(4.)).text_size(px(13.)).text_color(foreground);
// The interactive window's and REPL editor's toolbar (`MenuId.InteractiveToolbar`): its `navigation` items on the
// left with the toolbar's context (notebookEditorToolbar.ts), the kernel picker on the right.
@@ -1173,7 +1183,7 @@ impl Workbench {
}
items.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1)));
let toolbar = toolbar.children(items.into_iter().map(|(_, _, element)| element));
- return toolbar.child(div().flex_1()).child(button("notebook-kernel", "server-environment", &kernel_label, "_notebook.selectKernel", Vec::new(), cx));
+ return toolbar.child(div().flex_1()).child(button("notebook-kernel", kernel_icon, &kernel_label, "_notebook.selectKernel", Vec::new(), cx));
}
toolbar
.child(button("notebook-insert-code", "add", "Code", "notebook.cell.insertCodeCellBelowAndFocusContainer", Vec::new(), cx))
@@ -1183,7 +1193,7 @@ impl Workbench {
.child(button("notebook-run-all", "run-all", "Run All", "notebook.execute", Vec::new(), cx))
.children(self.notebook_toolbar_more(window, cx).map(|more| more.ml(px(4.))))
.child(div().flex_1())
- .child(button("notebook-kernel", "server-environment", &kernel_label, "_notebook.selectKernel", Vec::new(), cx))
+ .child(button("notebook-kernel", kernel_icon, &kernel_label, "_notebook.selectKernel", Vec::new(), cx))
}
/// notebookCellList.ts: the cells at their tops less the scroll, the webview placed over the list.
@@ -1324,7 +1334,7 @@ impl Workbench {
.child(self.cell_status_bar(model, row.index, focused, window, cx));
container = container.child(editor_box);
if row.kind == CODE {
- container = container.child(self.cell_run_gutter(tab, model, row, cx)).children(self.output_toolbars(tab, model, row, cx));
+ container = container.child(self.cell_run_gutter(tab, model, row, window, cx)).children(self.output_toolbars(tab, model, row, cx));
}
container.children(shows_toolbar.then(|| self.cell_toolbar(tab, model, row, window, cx)).flatten())
}
@@ -1383,7 +1393,7 @@ impl Workbench {
/// cellExecution.ts and the run toolbar: the run button over the gutter of a focused cell, the execution order
/// (`[n]`) or the running state at the bottom of the gutter.
- fn cell_run_gutter(&self, tab: u32, model: &NotebookModel, row: &CellRow, cx: &mut Context<Self>) -> Div {
+ fn cell_run_gutter(&self, tab: u32, model: &NotebookModel, row: &CellRow, window: &Window, cx: &mut Context<Self>) -> Div {
let cell = &model.cells[row.index];
let state = self.host.notebooks.kernels.state(&model.uri_string(), cell.handle);
// cellExecution.ts: the order shows with a kernel that implements it, or without a kernel.
@@ -1399,9 +1409,6 @@ impl Workbench {
let run = self
.icon(if state.is_some() { "stop" } else { "play" }, 22., 16., self.color("icon.foreground"))
.id(("notebook-run-cell", row.handle as usize))
- .absolute()
- .top(px(row.layout.editor_top + 4.))
- .left(px(layout::CODE_CELL_LEFT_MARGIN + 6.))
.rounded(px(5.))
.cursor_pointer()
.hover(|button| button.bg(self.color("toolbar.hoverBackground")))
@@ -1412,7 +1419,17 @@ impl Workbench {
.child(self.hover_target(("notebook-run-cell-hover", row.handle as usize), HoverContent::Text("Execute Cell".into()), HoverOptions::mouse()));
// The interactive window's and REPL editor's `cellExecuteToolbar` (`MenuId.InteractiveCellExecute`) is empty.
let composite = self.host.notebooks.interactives.iter().any(|interactive| interactive.notebook == model.uri_string());
- let shows_run = !composite && (self.notebook_views.views.get(&tab).is_some_and(|view| view.hovered == Some(row.handle)) || self.host.notebooks.editor(tab).is_some_and(|editor| editor.focus == row.index));
+ let dropdown_open = self.context_menu.is_some() && self.notebook_views.views.get(&tab).is_some_and(|view| view.run_menu == Some(row.handle));
+ let shows_run = !composite && (dropdown_open || self.notebook_views.views.get(&tab).is_some_and(|view| view.hovered == Some(row.handle)) || self.host.notebooks.editor(tab).is_some_and(|editor| editor.focus == row.index));
+ let secondary = self.cell_execute_actions(model, row, window);
+ // notebook.css: the 35px `.run-button-container` centers its toolbar; a lone button has 6px padding, the
+ // dropdown-with-primary (22px button, 12px chevron 3px over it) none, its icon 3px from the top.
+ let (top, left) = if secondary.is_empty() { (4., 6.) } else { (0., 2.) };
+ let run = match secondary.is_empty() {
+ true => run.into_any_element(),
+ false => self.cell_run_dropdown(tab, model, row, run, secondary, cx).into_any_element(),
+ };
+ let run = div().absolute().top(px(row.layout.editor_top + top)).left(px(layout::CODE_CELL_LEFT_MARGIN + left)).child(run);
div()
.child(
div()
diff --git a/native/crates/app/src/workbench/notebook_editor/cell_actions.rs b/native/crates/app/src/workbench/notebook_editor/cell_actions.rs
index c318a05c59f..387409055f9 100644
--- a/native/crates/app/src/workbench/notebook_editor/cell_actions.rs
+++ b/native/crates/app/src/workbench/notebook_editor/cell_actions.rs
@@ -64,12 +64,11 @@ pub(in crate::workbench) fn toggled_cell_toolbar_position(setting: &Value, view_
}
impl Workbench {
- /// notebookEditorWidgetContextKeys.ts `_updateKernelContext` and `_updateForInstalledExtension`. The port has no
- /// kernel source actions (`notebook/kernelSource`), so their count is 0.
+ /// notebookEditorWidgetContextKeys.ts `_updateKernelContext` and `_updateForInstalledExtension`.
pub(in crate::workbench) fn notebook_kernel_context(&self, model: &NotebookModel, context: &mut HashMap<String, Value>) {
let (all, _) = self.host.notebooks.kernels.matching(&model.view_type, &model.uri_string());
context.insert("notebookKernelCount".into(), json!(all.len()));
- context.insert("notebookKernelSourceCount".into(), json!(0));
+ context.insert("notebookKernelSourceCount".into(), json!(super::super::kernel_picker::kernel_source_actions(&self.menus, context).len()));
let extension = KERNEL_EXTENSIONS.iter().find(|(view_type, _)| *view_type == model.view_type).map(|(_, id)| *id);
let missing = extension.is_some_and(|id| !self.extensions.iter().any(|extension| extension.id.eq_ignore_ascii_case(id)));
context.insert("notebookMissingKernelExtension".into(), json!(missing));
@@ -153,6 +152,44 @@ impl Workbench {
(primary, more, delete)
}
+ /// codeCellRunToolbar.ts `secondaryMenu`: the run button's dropdown, `MenuId.NotebookCellExecute`'s non-inline
+ /// groups for the row's cell.
+ pub(super) fn cell_execute_actions(&self, model: &NotebookModel, row: &CellRow, window: &Window) -> Vec<MenuAction> {
+ let context = self.cell_toolbar_context(model, row, window);
+ menu_group_actions(&self.menus, MenuId::NotebookCellExecute, &context, |group| !is_inline(group))
+ }
+
+ /// codeCellRunToolbar.ts `DropdownWithPrimaryActionViewItem`: the run button, then a chevron (More...) opening
+ /// the execute menu for the cell; dropdown.css's 5px corners and one hover background over both.
+ pub(super) fn cell_run_dropdown(&self, tab: u32, model: &NotebookModel, row: &CellRow, primary: gpui::Stateful<Div>, actions: Vec<MenuAction>, cx: &mut Context<Self>) -> Div {
+ let bounds = Rc::new(Cell::new(gpui::Bounds::default()));
+ let measured = bounds.clone();
+ let handle = row.handle;
+ let args = vec![json!({ "start": row.index, "end": row.index + 1, "ui": true }), model.uri.clone()];
+ let open = self.context_menu.is_some() && self.notebook_views.views.get(&tab).is_some_and(|view| view.run_menu == Some(handle));
+ let chevron = self
+ .icon("chevron-down", 12., 12., self.color("icon.foreground"))
+ .id(("notebook-cell-run-dropdown", handle as usize))
+ .debug_selector(move || format!("notebook-cell-run-dropdown-{handle}"))
+ .h(px(22.))
+ .ml(px(-3.))
+ .rounded(px(5.))
+ .cursor_pointer()
+ .when(open, |chevron| chevron.bg(self.color("toolbar.activeBackground")))
+ .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
+ .child(canvas(move |element_bounds, _, _| measured.set(element_bounds), |_, _, _, _| {}).absolute().size_full())
+ .child(self.hover_target(("notebook-cell-run-dropdown-hover", handle as usize), HoverContent::Text("More...".into()), HoverOptions::mouse()))
+ .on_click(cx.listener(move |workbench, _: &ClickEvent, window, cx| {
+ cx.stop_propagation();
+ if let Some(view) = workbench.notebook_views.views.get_mut(&tab) {
+ view.run_menu = Some(handle);
+ }
+ let context = workbench.key_context(window);
+ workbench.show_context_menu_actions(actions.clone(), &context, bounds.get(), args.clone(), window, cx);
+ }));
+ div().flex().items_center().rounded(px(5.)).hover(|item| item.bg(self.color("toolbar.hoverBackground"))).child(primary).child(chevron)
+ }
+
/// One `.action-item.menu-entry`: 24px square, 1px 2px margins, its command's icon.
fn cell_toolbar_button(&self, handle: u64, action: &MenuAction, args: &[Value], cx: &mut Context<Self>) -> Option<gpui::Stateful<Div>> {
let MenuAction::Command { id, title, enabled, .. } = action else { return None };
diff --git a/native/crates/app/src/workbench/notebook_editor/tests.rs b/native/crates/app/src/workbench/notebook_editor/tests.rs
index ee5ef9b79a0..23acc29e182 100644
--- a/native/crates/app/src/workbench/notebook_editor/tests.rs
+++ b/native/crates/app/src/workbench/notebook_editor/tests.rs
@@ -555,6 +555,62 @@ fn the_variable_provider_command_collects_what_the_bound_kernel_sends(cx: &mut T
assert_eq!(collected[0]["variable"]["name"], "a");
}
+/// notebookVariables.ts: with `notebook.variablesView` on, an execution of a notebook whose kernel provides variables
+/// adds the Notebook Variables view to Run and Debug; it lists the root variables 100ms after the execution ends, splits
+/// 250 indexed children into pages of 100, and its row menu copies the value (notebookVariableCommands.ts).
+#[gpui::test]
+fn the_notebook_variables_view_lists_the_kernels_variables(cx: &mut TestAppContext) {
+ use crate::workbench::notebook_variables::NOTEBOOK_VARIABLES_VIEW;
+ let (workbench, cx, receiver) = workbench_with_cells(json!([{ "cellKind": 2, "language": "python", "source": "a = 1", "outputs": [], "metadata": {} }]), cx);
+ let kernel = json!({ "id": "pub.ext/k", "notebookType": "jupyter-notebook", "label": "K", "hasVariableProvider": true, "extensionLocation": { "scheme": "file", "path": "/ext" }, "preloads": [] });
+ let shown = |cx: &mut VisualTestContext| workbench.read_with(cx, |workbench, _| workbench.debug_views().iter().any(|(id, _)| *id == NOTEBOOK_VARIABLES_VIEW));
+ workbench.update_in(cx, |workbench, window, cx| {
+ workbench.handle_notebook_request("MainThreadNotebookKernels", "$addKernel", &[json!(3), kernel], window, cx);
+ let uri = workbench.host.notebooks.models[0].uri.clone();
+ workbench.host.notebooks.kernels.select(Some("pub.ext/k"), "jupyter-notebook", &uri);
+ let cell = workbench.host.notebooks.models[0].cells[0].handle;
+ workbench.handle_notebook_request("MainThreadNotebookKernels", "$createExecution", &[json!(7), json!("pub.ext/k"), uri, json!(cell)], window, cx);
+ });
+ assert!(!shown(cx), "off by default");
+ workbench.update_in(cx, |workbench, window, cx| {
+ workbench.update_setting("notebook.variablesView", json!(true));
+ let uri = workbench.host.notebooks.models[0].uri.clone();
+ let cell = workbench.host.notebooks.models[0].cells[0].handle;
+ workbench.handle_notebook_request("MainThreadNotebookKernels", "$createExecution", &[json!(8), json!("pub.ext/k"), uri, json!(cell)], window, cx);
+ workbench.handle_notebook_request("MainThreadNotebookKernels", "$completeExecution", &[json!(8), json!({})], window, cx);
+ });
+ assert!(shown(cx));
+ let enabled = workbench.update_in(cx, |workbench, window, _| workbench.key_context(window)["notebookVariableViewEnabled"].clone());
+ assert_eq!(enabled, json!(true));
+ cx.executor().advance_clock(std::time::Duration::from_millis(100));
+ cx.run_until_parked();
+ let call = receiver.try_iter().find(|message| message.method == "$provideVariables").expect("the root is asked for");
+ assert_eq!((call.args[3].clone(), call.args[4].clone()), (json!(null), json!("named")));
+ let request = call.args[1].clone();
+ workbench.update_in(cx, |workbench, window, cx| {
+ for variable in [json!({ "id": 1, "name": "a", "value": "1", "type": "int", "hasNamedChildren": false, "indexedChildrenCount": 0 }), json!({ "id": 2, "name": "items", "value": "[0, 1, ...]", "hasNamedChildren": false, "indexedChildrenCount": 250 })] {
+ workbench.handle_notebook_request("MainThreadNotebookKernels", "$receiveVariable", &[request.clone(), variable], window, cx);
+ }
+ });
+ let _ = call.reply.expect("a call").send(Ok(json!(null)));
+ cx.run_until_parked();
+ let names = |cx: &mut VisualTestContext| workbench.read_with(cx, |workbench, _| workbench.notebook_variable_names());
+ assert_eq!(names(cx), ["a", "items"]);
+ workbench.update(cx, |workbench, cx| workbench.toggle_notebook_variable_row("2", cx));
+ assert_eq!(names(cx), ["a", "items", " [0..99]", " [100..199]", " [200..249]"]);
+
+ workbench.update_in(cx, |workbench, window, cx| workbench.show_notebook_variable_row_menu("1", window, cx));
+ let (titles, args) = workbench.read_with(cx, |workbench, _| {
+ let menu = workbench.context_menu.as_ref().expect("the menu shows");
+ let titles: Vec<String> = menu.levels[0].actions.iter().filter_map(|action| match action { crate::menus::MenuAction::Command { title, .. } => Some(title.clone()), _ => None }).collect();
+ (titles, menu.args.clone())
+ });
+ assert_eq!(titles, ["Copy Value"]);
+ assert_eq!((args[0]["name"].clone(), args[0]["value"].clone(), args[0]["type"].clone()), (json!("a"), json!("1"), json!("int")));
+ workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command("workbench.debug.viewlet.action.copyWorkspaceVariableValue", args, window, cx)));
+ assert_eq!(cx.read_from_clipboard().and_then(|item| item.text()).as_deref(), Some("1"));
+}
+
/// editorStatus.ts keeps the `activeCodeEditor` of the moment the notebook editor became active: a notebook opened on
/// a code cell shows that cell editor's entries, one opened on a markdown cell shows none, also once a code cell has
/// the focus.
@@ -604,6 +660,47 @@ fn renderer_messages_wait_for_the_renderer_activation(cx: &mut TestAppContext) {
assert_eq!(posted, [json!("three")]);
}
+/// notebookKernelServiceImpl.ts `getSourceActions`: a `notebook/kernelSource` command counts in
+/// `notebookKernelSourceCount` and replaces the recommendations of the sources picker; picked, it runs with the
+/// notebook (`MarshalledId.NotebookActionContext`) and the kernel status shows it until it ends.
+#[gpui::test]
+fn kernel_source_actions_run_from_the_kernel_picker(cx: &mut TestAppContext) {
+ let (workbench, cx, _) = workbench_with_cells(json!([{ "cellKind": 2, "language": "python", "source": "a", "outputs": [], "metadata": {} }]), cx);
+ let ran = std::rc::Rc::new(std::cell::RefCell::new(Vec::new()));
+ let (sender, receiver) = futures::channel::oneshot::channel();
+ let receiver = std::cell::RefCell::new(Some(receiver));
+ workbench.update(cx, |workbench, _| {
+ let description = json!({
+ "enabledApiProposals": ["notebookKernelSource"],
+ "contributes": { "commands": [{ "command": "pub.connect", "title": "Connect to a Server" }], "menus": { "notebook/kernelSource": [{ "command": "pub.connect", "when": "notebookType == 'jupyter-notebook'" }] } }
+ });
+ workbench.menus.extend(crate::menus::extension_menus(&[exthost::scan::ScannedExtension { id: "pub.source".into(), location: "/ext".into(), description }]));
+ let ran = ran.clone();
+ workbench.commands.register("pub.connect", move |_, args, _, _| {
+ ran.borrow_mut().push(args);
+ crate::commands::Outcome::Pending(receiver.borrow_mut().take().unwrap())
+ });
+ });
+ let context = workbench.update_in(cx, |workbench, window, _| workbench.key_context(window));
+ assert_eq!(context["notebookKernelSourceCount"], json!(1));
+ workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command("_notebook.selectKernel", Vec::new(), window, cx)));
+ cx.run_until_parked();
+ let rows = workbench.read_with(cx, |workbench, _| {
+ let input = workbench.quick_inputs.current().unwrap();
+ input.order.iter().map(|row| input.rows[*row].item.label.clone()).collect::<Vec<_>>()
+ });
+ assert_eq!(rows, ["Connect to a Server"]);
+ cx.simulate_keystrokes("enter");
+ cx.run_until_parked();
+ let uri = workbench.read_with(cx, |workbench, _| workbench.host.notebooks.models[0].uri.clone());
+ assert_eq!(*ran.borrow(), [vec![json!({ "uri": uri, "$mid": 14 })]]);
+ let running = |cx: &mut VisualTestContext| workbench.read_with(cx, |workbench, _| workbench.notebook_views.running_sources.values().cloned().collect::<Vec<_>>());
+ assert_eq!(running(cx), ["Connect to a Server"]);
+ sender.send(Ok(json!(null))).unwrap();
+ cx.run_until_parked();
+ assert_eq!(running(cx), Vec::<String>::new());
+}
+
/// notebookKernelQuickPickStrategy.ts `KernelPickerMRUStrategy`: with no kernel the sources picker recommends
/// extensions; with kernels it groups them by extension; a picked kernel is bound and then listed as selected above
/// Select Another Kernel...
@@ -872,6 +969,30 @@ fn the_cell_toolbar_menus(cx: &mut TestAppContext) {
assert_eq!(more[6], "Change Cell to Markdown");
}
+/// codeCellRunToolbar.ts: `notebook.consolidatedRunButton` moves Execute Above Cells and Execute Cell and Below from
+/// the cell toolbar to the run button's dropdown (`MenuId.NotebookCellExecute`), which a code cell only has.
+#[gpui::test]
+fn the_cell_execute_menu(cx: &mut TestAppContext) {
+ let cells = json!([
+ { "cellKind": 1, "language": "markdown", "source": "# Title", "outputs": [], "metadata": {} },
+ { "cellKind": 2, "language": "python", "source": "x", "outputs": [], "metadata": {} },
+ ]);
+ let (workbench, cx, _) = workbench_with_cells(cells, cx);
+ let menus = |index: usize, cx: &mut VisualTestContext| {
+ workbench.update_in(cx, |workbench, window, _| {
+ let model = &workbench.host.notebooks.models[0];
+ let row = workbench.notebook_rows(workbench.host.notebooks.editors[0].tab_model_id, model).into_iter().nth(index).unwrap();
+ (titles(&workbench.cell_execute_actions(model, &row, window)), titles(&workbench.cell_toolbar_actions(model, &row, window).0))
+ })
+ };
+ assert_eq!(menus(1, cx).0, Vec::<String>::new(), "no dropdown by default");
+ workbench.update(cx, |workbench, _| workbench.update_user_setting("notebook.consolidatedRunButton", json!(true)));
+ let (execute, primary) = menus(1, cx);
+ assert_eq!(execute, ["Execute Above Cells", "Execute Cell and Below"]);
+ assert_eq!(primary, ["Split Cell"]);
+ assert_eq!(menus(0, cx).0, Vec::<String>::new());
+}
+
/// foldingController.ts: Fold Cell and Unfold Cell on the innermost section of the focused markdown cell; collapsed
/// sections hide their cells and keep the sections inside them collapsed.
#[gpui::test]
diff --git a/native/crates/app/src/workbench/notebook_variables.rs b/native/crates/app/src/workbench/notebook_variables.rs
new file mode 100644
index 00000000000..4ca76f6dc39
--- /dev/null
+++ b/native/crates/app/src/workbench/notebook_variables.rs
@@ -0,0 +1,384 @@
+//! The Notebook Variables view in the Run and Debug container (notebookVariables.ts, notebookVariablesView.ts,
+//! notebookVariablesDataSource.ts, notebookVariablesTree.ts) and its `MenuId.NotebookVariablesContext` menu
+//! (notebookVariableCommands.ts).
+
+use std::collections::HashMap;
+use std::time::Duration;
+
+use futures::channel::oneshot;
+use gpui::{ClickEvent, Context, MouseButton, MouseDownEvent, Window, div, prelude::*, px};
+use serde_json::{Value, json};
+
+use super::Workbench;
+use super::debug_view::{EXPRESSION_FONT, EXPRESSION_FONT_SIZE};
+use super::hover::{HoverContent, HoverOptions};
+use crate::commands::Outcome;
+use crate::debug::session::Variable;
+use crate::menus::{MenuId, menu_group_actions};
+use crate::notebook;
+
+pub(super) const NOTEBOOK_VARIABLES_VIEW: &str = "workbench.notebook.variables";
+/// notebookKernelService.ts `variablePageSize`.
+const PAGE_SIZE: u64 = 100;
+/// notebookVariablesDataSource.ts `indexedChildCountLimit`.
+const INDEXED_CHILD_COUNT_LIMIT: u64 = 1_000_000;
+/// notebookVariablesTree.ts `MAX_VALUE_RENDER_LENGTH_IN_VIEWLET`.
+const MAX_VALUE_LENGTH: usize = 1024;
+const ROOT: &str = "";
+
+#[derive(Default)]
+pub(super) struct NotebookVariables {
+ /// notebookVariables.ts `initialized`: the view registers once and stays.
+ pub registered: bool,
+ /// notebookVariablesView.ts `activeNotebook`, and whether it shows in a REPL (the REPL Variables title).
+ notebook: Option<String>,
+ repl: bool,
+ /// The tree's children by parent element id, `ROOT` for the notebook.
+ children: HashMap<String, Vec<Element>>,
+ /// `updateScheduler` and `dataSource.cancel`: an answer of an older generation is dropped.
+ generation: u64,
+}
+
+/// notebookVariablesDataSource.ts `INotebookVariableElement`.
+#[derive(Clone, Debug, PartialEq)]
+struct Element {
+ id: String,
+ ext_host_id: Value,
+ name: String,
+ value: String,
+ type_name: Option<String>,
+ result: Value,
+ indexed_children_count: u64,
+ index_start: Option<u64>,
+ has_named_children: bool,
+}
+
+impl Element {
+ /// `createVariableElement`: a `VariablesResult` of the extension host.
+ fn from_result(result: &Value) -> Element {
+ Element {
+ id: result["id"].to_string(),
+ ext_host_id: result["id"].clone(),
+ name: result["name"].as_str().unwrap_or_default().to_owned(),
+ value: result["value"].as_str().unwrap_or_default().to_owned(),
+ type_name: result["type"].as_str().map(str::to_owned),
+ result: result.clone(),
+ indexed_children_count: result["indexedChildrenCount"].as_u64().unwrap_or_default(),
+ index_start: None,
+ has_named_children: result["hasNamedChildren"] == true,
+ }
+ }
+
+ fn has_children(&self) -> bool {
+ self.has_named_children || self.indexed_children_count > 0
+ }
+
+ /// `getIndexedChildren` over a page: the ranges of `nestedPageSize` children it splits into, and a last row when
+ /// the count passes the display limit.
+ fn index_ranges(&self) -> Vec<Element> {
+ let page = (self.indexed_children_count as f64 / PAGE_SIZE as f64).max(100.).floor() as u64;
+ let mut start = self.index_start.unwrap_or_default();
+ let last = start + self.indexed_children_count.min(INDEXED_CHILD_COUNT_LIMIT);
+ let range = |id: String, name: String, count: u64, index_start: Option<u64>| Element {
+ id,
+ ext_host_id: self.ext_host_id.clone(),
+ name,
+ value: String::new(),
+ type_name: None,
+ result: Value::Null,
+ indexed_children_count: count,
+ index_start,
+ has_named_children: false,
+ };
+ let mut ranges = Vec::new();
+ while start < last {
+ let end = (start + page).min(last);
+ ranges.push(range(format!("{}{start}", self.id), format!("[{start}..{}]", end - 1), end - start, Some(start)));
+ start += page;
+ }
+ if self.indexed_children_count > INDEXED_CHILD_COUNT_LIMIT {
+ ranges.push(range(format!("{}{}", self.id, last + 1), "Display limit reached".into(), 0, None));
+ }
+ ranges
+ }
+}
+
+impl Workbench {
+ /// notebookVariables.ts `handleInitEvent` on an active editor change (`notebook` None), an execution change of
+ /// `notebook` or a `notebook.variablesView` change: with the setting on (or a REPL active) and a notebook whose
+ /// selected kernel has a variable provider, the view registers and `notebookVariableViewEnabled` turns on.
+ pub(super) fn init_notebook_variables_view(&mut self, notebook: Option<&str>, cx: &mut Context<Self>) {
+ if self.notebook_variables.registered {
+ return;
+ }
+ let repl = self.active_interactive().is_some_and(|interactive| interactive.repl);
+ let enabled = repl || self.setting("notebook.variablesView") == true || self.setting("notebook.experimental.variablesView") == true;
+ // `activeEditorPane.getId() === 'workbench.editor.notebook'`: an interactive window or REPL is not one.
+ let active = self.active_notebook_editor().filter(|_| self.active_interactive().is_none()).map(|editor| editor.notebook.clone());
+ let Some(key) = notebook.map(str::to_owned).or(active).filter(|_| enabled) else { return };
+ if !self.has_variable_provider(&key) {
+ return;
+ }
+ self.notebook_variables.registered = true;
+ self.context_keys.insert("notebookVariableViewEnabled".into(), json!(true));
+ self.notebook_variables_editor_changed(cx);
+ }
+
+ fn has_variable_provider(&self, key: &str) -> bool {
+ let notebooks = &self.host.notebooks;
+ let Some(model) = notebooks.model(key) else { return false };
+ notebooks.kernels.matching(&model.view_type, key).1.is_some_and(|kernel| kernel.has_variable_provider)
+ }
+
+ /// notebookVariablesView.ts `handleCloseEditor`, the shown notebook's editor closed leaves an empty tree, and
+ /// `handleActiveEditorChange`, a new active notebook (a REPL's too) becomes the input.
+ pub(super) fn notebook_variables_editor_changed(&mut self, cx: &mut Context<Self>) {
+ if !self.notebook_variables.registered {
+ return;
+ }
+ let shown = self.notebook_variables.notebook.clone();
+ if shown.as_ref().is_some_and(|key| !self.host.notebooks.editors.iter().any(|editor| editor.notebook == *key)) {
+ self.notebook_variables.notebook = None;
+ self.notebook_variables.children.clear();
+ self.notebook_variables.generation += 1;
+ }
+ let Some(key) = self.active_notebook_editor().map(|editor| editor.notebook.clone()) else { return };
+ if self.notebook_variables.notebook.as_deref() == Some(key.as_str()) {
+ return;
+ }
+ self.notebook_variables.repl = self.active_interactive().is_some();
+ self.notebook_variables.notebook = Some(key);
+ self.notebook_variables.children.clear();
+ self.schedule_notebook_variables_update(cx);
+ }
+
+ /// `handleExecutionStateChange`: an execution that starts or runs cancels the pending requests, one that ends
+ /// asks again; `handleVariablesChanged` asks again too.
+ pub(super) fn notebook_variables_changed(&mut self, key: &str, ended: bool, cx: &mut Context<Self>) {
+ if self.notebook_variables.notebook.as_deref() != Some(key) {
+ return;
+ }
+ self.notebook_variables.generation += 1;
+ if ended {
+ self.schedule_notebook_variables_update(cx);
+ }
+ }
+
+ /// `updateScheduler`: 100ms later `tree.updateChildren()` asks again for the root and every expanded element.
+ fn schedule_notebook_variables_update(&mut self, cx: &mut Context<Self>) {
+ self.notebook_variables.generation += 1;
+ let generation = self.notebook_variables.generation;
+ cx.spawn(async move |workbench, cx| {
+ cx.background_executor().timer(Duration::from_millis(100)).await;
+ let _ = workbench.update(cx, |workbench, cx| {
+ if workbench.notebook_variables.generation == generation {
+ workbench.load_notebook_variables(None, cx);
+ }
+ });
+ })
+ .detach();
+ }
+
+ /// notebookVariablesDataSource.ts `getChildren` of `parent` (the root for None), then of its expanded children.
+ fn load_notebook_variables(&mut self, parent: Option<Element>, cx: &mut Context<Self>) {
+ let Some(key) = self.notebook_variables.notebook.clone() else { return };
+ let parent_id = parent.as_ref().map_or(ROOT.to_owned(), |parent| parent.id.clone());
+ if let Some(parent) = parent.as_ref().filter(|parent| parent.indexed_children_count > PAGE_SIZE) {
+ let ranges = parent.index_ranges();
+ return self.set_notebook_variables(parent_id, ranges, cx);
+ }
+ // The named children come first, then a page of the indexed ones (`getIndexedChildren`).
+ let mut requests = Vec::new();
+ match &parent {
+ None => requests.push((self.provide_variables(&key, Value::Null, "named", 0, cx), usize::MAX)),
+ Some(parent) => {
+ if parent.has_named_children {
+ requests.push((self.provide_variables(&key, parent.ext_host_id.clone(), "named", 0, cx), usize::MAX));
+ }
+ if parent.indexed_children_count > 0 {
+ requests.push((self.provide_variables(&key, parent.ext_host_id.clone(), "indexed", parent.index_start.unwrap_or_default(), cx), PAGE_SIZE as usize));
+ }
+ }
+ }
+ let generation = self.notebook_variables.generation;
+ cx.spawn(async move |workbench, cx| {
+ let mut children = Vec::new();
+ for (request, limit) in requests {
+ let Some(request) = request else { continue };
+ let results = request.await.ok().and_then(Result::ok).unwrap_or_default();
+ children.extend(results.iter().take(limit).map(Element::from_result));
+ }
+ let _ = workbench.update(cx, |workbench, cx| {
+ if workbench.notebook_variables.generation == generation {
+ workbench.set_notebook_variables(parent_id, children, cx);
+ }
+ });
+ })
+ .detach();
+ }
+
+ fn set_notebook_variables(&mut self, parent_id: String, children: Vec<Element>, cx: &mut Context<Self>) {
+ let expanded: Vec<Element> = children.iter().filter(|child| child.has_children() && self.debug_view.expanded.contains(&row_key(&child.id))).cloned().collect();
+ self.notebook_variables.children.insert(parent_id, children);
+ for child in expanded {
+ self.load_notebook_variables(Some(child), cx);
+ }
+ cx.notify();
+ }
+
+ /// mainThreadNotebookKernels.ts `provideVariables` of the notebook's selected kernel: the variables
+ /// `$receiveVariable` brought while `$provideVariables` ran. None without a variable provider.
+ fn provide_variables(&mut self, key: &str, parent: Value, kind: &str, start: u64, cx: &mut Context<Self>) -> Option<oneshot::Receiver<Result<Vec<Value>, Value>>> {
+ let model = self.host.notebooks.model(key)?;
+ let (uri, view_type) = (model.uri.clone(), model.view_type.clone());
+ let kernels = &mut self.host.notebooks.kernels;
+ let handle = kernels.matching(&view_type, key).1.filter(|kernel| kernel.has_variable_provider)?.handle;
+ let request_id = format!("{handle}variables{}", kernels.variable_request_index);
+ kernels.variable_request_index += 1;
+ kernels.variable_requests.insert(request_id.clone(), Vec::new());
+ let call = self.host.call_cancellable("ExtHostNotebookKernels", "$provideVariables", vec![json!(handle), json!(request_id), uri, parent, json!(kind), json!(start)]);
+ let (sender, receiver) = oneshot::channel();
+ cx.spawn(async move |workbench, cx| {
+ let answer = call.await;
+ let collected = workbench.update(cx, |workbench, _| workbench.host.notebooks.kernels.variable_requests.remove(&request_id).unwrap_or_default()).unwrap_or_default();
+ let _ = sender.send(match answer {
+ Ok(Err(error)) => Err(error),
+ _ => Ok(collected),
+ });
+ })
+ .detach();
+ Some(receiver)
+ }
+
+ /// notebookVariableCommands.ts `_executeNotebookVariableProvider`: the named variables of the notebook's selected
+ /// kernel, when it has a variable provider.
+ pub(super) fn execute_notebook_variable_provider(&mut self, resource: Option<&Value>, cx: &mut Context<Self>) -> Outcome {
+ let key = resource.map(notebook::uri_string).unwrap_or_default();
+ let Some(request) = self.provide_variables(&key, Value::Null, "named", 0, cx) else { return Outcome::Ready(Ok(json!([]))) };
+ let (sender, receiver) = oneshot::channel();
+ cx.spawn(async move |_, _| {
+ let _ = sender.send(request.await.unwrap_or(Ok(Vec::new())).map(|collected| json!(collected)));
+ })
+ .detach();
+ Outcome::Pending(receiver)
+ }
+
+ pub(super) fn register_notebook_variable_commands(&mut self) {
+ self.commands.register("_executeNotebookVariableProvider", |workbench, args, _, cx| workbench.execute_notebook_variable_provider(args.first(), cx));
+ // COPY_NOTEBOOK_VARIABLE_VALUE_ID: the menu's `contextMenuArg`.
+ self.commands.register("workbench.debug.viewlet.action.copyWorkspaceVariableValue", |_, args, _, cx| {
+ if let Some(value) = args.first().and_then(|arg| arg["value"].as_str()).filter(|value| !value.is_empty()) {
+ cx.write_to_clipboard(gpui::ClipboardItem::new_string(value.to_owned()));
+ }
+ Outcome::done()
+ });
+ }
+
+ pub(super) fn notebook_variables_pane(&self, window: &Window, cx: &mut Context<Self>) -> super::view_panes::ViewPane {
+ // notebookVariablesView.ts `setActiveNotebook`: `REPL_TITLE` for a composite notebook editor.
+ let title = if self.notebook_variables.repl { "REPL Variables" } else { "Notebook Variables" };
+ let focus = self.debug_view.list_focus[NOTEBOOK_VARIABLES_VIEW].clone();
+ let menu_return = self.context_menu.as_ref().and_then(|menu| menu.focus_to_return.as_ref());
+ let list_focused = focus.is_focused(window) || menu_return == Some(&focus);
+ let mut rows = Vec::new();
+ self.notebook_variable_rows(ROOT, 0, list_focused, &mut rows, cx);
+ let body = div().id(NOTEBOOK_VARIABLES_VIEW).flex_1().min_h_0().overflow_y_scroll().track_focus(&focus).capture_any_mouse_down(move |_, window, cx| window.focus(&focus, cx));
+ super::view_panes::ViewPane { id: NOTEBOOK_VARIABLES_VIEW, title: title.into(), description: None, actions: None, draws_more: false, show_actions: false, body: body.children(rows).into_any_element() }
+ }
+
+ /// notebookVariablesTree.ts `NotebookVariableRenderer`: `name:` with the type as its title, then the value in the
+ /// debug token colors, cut at 1024 characters.
+ fn notebook_variable_rows(&self, parent: &str, depth: usize, list_focused: bool, rows: &mut Vec<gpui::AnyElement>, cx: &mut Context<Self>) {
+ let Some(children) = self.notebook_variables.children.get(parent) else { return };
+ for element in children {
+ let key = row_key(&element.id);
+ let expandable = element.has_children();
+ let expanded = expandable && self.debug_view.expanded.contains(&key);
+ let name = if element.value.trim().is_empty() { element.name.clone() } else { format!("{}:", element.name) };
+ let mut value = element.value.clone();
+ if value.len() > MAX_VALUE_LENGTH {
+ value = format!("{}...", value.chars().take(MAX_VALUE_LENGTH).collect::<String>());
+ }
+ let color = self.value_color(&Variable { value: value.clone(), ..Variable::default() });
+ let mut name_label = div().id(gpui::SharedString::from(format!("{key}/name"))).flex_none().text_color(self.color("debugTokenExpression.name")).child(name);
+ if let Some(type_name) = element.type_name.clone().filter(|type_name| !type_name.is_empty()) {
+ name_label = name_label.child(self.hover_target(gpui::SharedString::from(format!("{key}/type")), HoverContent::Text(type_name), HoverOptions::mouse()));
+ }
+ let label = div().flex().min_w_0().overflow_hidden().whitespace_nowrap().font_family(EXPRESSION_FONT).text_size(px(EXPRESSION_FONT_SIZE)).child(name_label).child(div().ml(px(6.)).text_color(color).overflow_hidden().text_ellipsis().child(value));
+ let (toggled, menu_element) = (element.clone(), element.clone());
+ let row = self.debug_row(key.clone(), depth, expandable.then_some(expanded), self.row_selected(&key), list_focused, cx).child(label);
+ let row = row.on_click(cx.listener(move |workbench, _: &ClickEvent, _, cx| {
+ if expandable {
+ workbench.toggle_notebook_variable(toggled.clone(), cx);
+ }
+ }));
+ let row = row.on_mouse_down(MouseButton::Right, cx.listener(move |workbench, event: &MouseDownEvent, window, cx| {
+ workbench.show_notebook_variable_menu(&menu_element, gpui::Bounds::new(event.position, Default::default()), window, cx);
+ }));
+ rows.push(row.into_any_element());
+ if expanded {
+ self.notebook_variable_rows(&element.id, depth + 1, list_focused, rows, cx);
+ }
+ }
+ }
+
+ fn toggle_notebook_variable(&mut self, element: Element, cx: &mut Context<Self>) {
+ let key = row_key(&element.id);
+ if !self.debug_view.expanded.remove(&key) {
+ self.debug_view.expanded.insert(key);
+ if !self.notebook_variables.children.contains_key(&element.id) {
+ self.load_notebook_variables(Some(element), cx);
+ }
+ }
+ cx.notify();
+ }
+
+ /// notebookVariablesView.ts `onContextMenu`: the row's keys over the context and its `contextMenuArg` forwarded.
+ fn show_notebook_variable_menu(&mut self, element: &Element, anchor: gpui::Bounds<gpui::Pixels>, window: &mut Window, cx: &mut Context<Self>) {
+ let Some(key) = self.notebook_variables.notebook.clone() else { return };
+ let source = self.host.notebooks.model(&key).map(|model| model.uri_string()).unwrap_or(key);
+ let result = &element.result;
+ let mut context = self.key_context(window);
+ let keys = [("variableName", json!(element.name)), ("variableValue", json!(element.value)), ("variableType", result["type"].clone()), ("variableInterfaces", result["interfaces"].clone()), ("variableLanguage", result["language"].clone()), ("variableExtensionId", result["extensionId"].clone())];
+ for (name, value) in keys {
+ context.insert(name.into(), value);
+ }
+ let arg = json!({ "source": source, "name": element.name, "value": element.value, "type": result["type"], "expression": result["expression"], "language": result["language"], "extensionId": result["extensionId"] });
+ let actions = menu_group_actions(&self.menus, MenuId::NotebookVariablesContext, &context, |_| true);
+ self.show_context_menu_actions(actions, &context, anchor, vec![arg], window, cx);
+ }
+}
+
+#[cfg(test)]
+impl Workbench {
+ /// The shown rows' names, two spaces deeper per level.
+ pub(super) fn notebook_variable_names(&self) -> Vec<String> {
+ fn walk(workbench: &Workbench, parent: &str, depth: usize, names: &mut Vec<String>) {
+ for element in workbench.notebook_variables.children.get(parent).into_iter().flatten() {
+ names.push(format!("{}{}", " ".repeat(depth), element.name));
+ if workbench.debug_view.expanded.contains(&row_key(&element.id)) {
+ walk(workbench, &element.id, depth + 1, names);
+ }
+ }
+ }
+ let mut names = Vec::new();
+ walk(self, ROOT, 0, &mut names);
+ names
+ }
+
+ fn notebook_variable(&self, id: &str) -> Element {
+ self.notebook_variables.children.values().flatten().find(|element| element.id == id).expect("a shown row").clone()
+ }
+
+ pub(super) fn toggle_notebook_variable_row(&mut self, id: &str, cx: &mut Context<Self>) {
+ self.toggle_notebook_variable(self.notebook_variable(id), cx);
+ }
+
+ pub(super) fn show_notebook_variable_row_menu(&mut self, id: &str, window: &mut Window, cx: &mut Context<Self>) {
+ self.show_notebook_variable_menu(&self.notebook_variable(id), Default::default(), window, cx);
+ }
+}
+
+fn row_key(id: &str) -> String {
+ format!("{NOTEBOOK_VARIABLES_VIEW}/{id}")
+}
diff --git a/native/crates/app/src/workbench/notebooks.rs b/native/crates/app/src/workbench/notebooks.rs
index 07b4a34ea19..d89f914d6da 100644
--- a/native/crates/app/src/workbench/notebooks.rs
+++ b/native/crates/app/src/workbench/notebooks.rs
@@ -105,36 +105,12 @@ impl Workbench {
}
}
- /// notebookVariableCommands.ts `_executeNotebookVariableProvider`: the named variables of the notebook's bound
- /// kernel, when it has a variable provider.
- fn execute_notebook_variable_provider(&mut self, resource: Option<&Value>, cx: &mut Context<Self>) -> Outcome {
- let Some(model) = resource.and_then(|uri| self.host.notebooks.model(&notebook::uri_string(uri))) else { return Outcome::Ready(Ok(json!([]))) };
- let (uri, key, view_type) = (model.uri.clone(), model.uri_string(), model.view_type.clone());
- let kernels = &mut self.host.notebooks.kernels;
- let Some(handle) = kernels.matching(&view_type, &key).1.filter(|kernel| kernel.has_variable_provider).map(|kernel| kernel.handle) else { return Outcome::Ready(Ok(json!([]))) };
- let request_id = format!("{handle}variables{}", kernels.variable_request_index);
- kernels.variable_request_index += 1;
- kernels.variable_requests.insert(request_id.clone(), Vec::new());
- let call = self.host.call_cancellable("ExtHostNotebookKernels", "$provideVariables", vec![json!(handle), json!(request_id), uri, Value::Null, json!("named"), json!(0)]);
- let (sender, receiver) = oneshot::channel();
- cx.spawn(async move |workbench, cx| {
- let answer = call.await;
- let collected = workbench.update(cx, |workbench, _| workbench.host.notebooks.kernels.variable_requests.remove(&request_id).unwrap_or_default()).unwrap_or_default();
- let _ = sender.send(match answer {
- Ok(Err(error)) => Err(error),
- _ => Ok(json!(collected)),
- });
- })
- .detach();
- Outcome::Pending(receiver)
- }
-
pub(super) fn register_notebook_commands(&mut self) {
self.commands.register("notebook.cell.changeLanguage", |workbench, args, window, cx| {
workbench.change_cell_language(&args, window, cx);
Outcome::done()
});
- self.commands.register("_executeNotebookVariableProvider", |workbench, args, _, cx| workbench.execute_notebook_variable_provider(args.first(), cx));
+ self.register_notebook_variable_commands();
self.commands.register("_resolveNotebookContentProvider", |workbench, _, _, _| Outcome::Ready(Ok(json!(workbench.notebook_types().iter().map(NotebookType::info).collect::<Vec<_>>()))));
self.commands.register("_executeDataToNotebook", |_, args, _, cx| {
let view_type = args.first().and_then(Value::as_str).unwrap_or_default().to_owned();
@@ -1148,9 +1124,15 @@ impl Workbench {
if let Some(execution) = self.host.notebooks.kernels.executions.remove(&handle) {
self.complete_cell_execution(&execution.notebook, execution.cell_handle, arg(1), cx);
self.scroll_interactive_to_executed(&execution.notebook, execution.cell_handle, cx);
+ self.init_notebook_variables_view(Some(&execution.notebook), cx);
+ self.notebook_variables_changed(&execution.notebook, true, cx);
}
Outcome::done()
}
+ "$variablesUpdated" => {
+ self.notebook_variables_changed(&notebook::uri_string(arg(0)), true, cx);
+ Outcome::done()
+ }
"$postMessage" => {
let editor_id = arg(1).as_str().map(str::to_owned);
let message = json!({ "__vscode_notebook_message": true, "type": "customKernelMessage", "message": arg(2) });
@@ -1177,6 +1159,8 @@ impl Workbench {
let execution = notebook::kernels::Execution { notebook: key.clone(), cell_handle, state: ExecutionState::Pending };
self.host.notebooks.kernels.executions.insert(handle, execution);
self.scroll_interactive_to_executed(&key, cell_handle, cx);
+ self.init_notebook_variables_view(Some(&key), cx);
+ self.notebook_variables_changed(&key, false, cx);
Ok(Value::Null)
}
diff --git a/native/crates/app/src/workbench/view_locations.rs b/native/crates/app/src/workbench/view_locations.rs
index d56da95c729..d83b54d6a93 100644
--- a/native/crates/app/src/workbench/view_locations.rs
+++ b/native/crates/app/src/workbench/view_locations.rs
@@ -11,6 +11,7 @@ use super::layout::Part;
use super::search_view::SideBarView;
use super::tree_view::static_id;
use super::debug_view::{BREAKPOINTS_VIEW, CALL_STACK_VIEW, DEBUG_CONTAINER, DEBUG_WELCOME_VIEW, LOADED_SCRIPTS_VIEW, VARIABLES_VIEW, WATCH_VIEW};
+use super::notebook_variables::NOTEBOOK_VARIABLES_VIEW;
use super::view_panes::{EMPTY_VIEW, FILE_VIEW, OPEN_EDITORS_VIEW, OUTLINE_VIEW, PaneContainer, SCM_CHANGES_VIEW, SCM_HISTORY_VIEW, SCM_REPOSITORIES_VIEW, TIMELINE_VIEW, ViewPane};
use crate::commands::Outcome;
use crate::quick_input::{Entry, Item, Kind, QuickInput};
@@ -113,6 +114,7 @@ impl Workbench {
view(CALL_STACK_VIEW, "Call Stack", DEBUG_CONTAINER, "debug-alt"),
view(LOADED_SCRIPTS_VIEW, "Loaded Scripts", DEBUG_CONTAINER, "debug-alt"),
view(BREAKPOINTS_VIEW, "Breakpoints", DEBUG_CONTAINER, "debug-alt"),
+ view(NOTEBOOK_VARIABLES_VIEW, "Notebook Variables", DEBUG_CONTAINER, "debug-alt"),
];
views.extend(self.panel.views.iter().map(|panel_view| view(panel_view.view_id, panel_view.title, panel_view.id, panel_view_icon(panel_view.id))));
for tree_view in &self.tree_views.views {
@@ -431,7 +433,7 @@ impl Workbench {
let provider = self.active_scm_provider().expect("Graph shows with a history provider");
self.scm_graph_pane(provider, window, cx)
}
- VARIABLES_VIEW | WATCH_VIEW | CALL_STACK_VIEW | LOADED_SCRIPTS_VIEW | BREAKPOINTS_VIEW | DEBUG_WELCOME_VIEW => self.debug_view_pane(id, window, cx),
+ VARIABLES_VIEW | WATCH_VIEW | CALL_STACK_VIEW | LOADED_SCRIPTS_VIEW | BREAKPOINTS_VIEW | DEBUG_WELCOME_VIEW | NOTEBOOK_VARIABLES_VIEW => self.debug_view_pane(id, window, cx),
_ => match self.panel.views.iter().find(|view| view.view_id == id) {
Some(view) => {
let (title, render, actions) = (view.title, view.render, view.actions);
@@ -599,7 +601,7 @@ impl Workbench {
OPEN_EDITORS_VIEW | OUTLINE_VIEW | TIMELINE_VIEW => !self.view_hidden(container, view.id),
SCM_HISTORY_VIEW => self.active_scm_provider().is_some_and(|provider| provider.has_history_provider),
SCM_REPOSITORIES_VIEW => !self.scm.model.providers.is_empty() && !self.view_hidden(container, view.id),
- VARIABLES_VIEW | WATCH_VIEW | CALL_STACK_VIEW | LOADED_SCRIPTS_VIEW | BREAKPOINTS_VIEW => self.debug_views().iter().any(|(id, _)| *id == view.id),
+ VARIABLES_VIEW | WATCH_VIEW | CALL_STACK_VIEW | LOADED_SCRIPTS_VIEW | BREAKPOINTS_VIEW | NOTEBOOK_VARIABLES_VIEW => self.debug_views().iter().any(|(id, _)| *id == view.id),
id => match (self.panel.views.iter().find(|panel_view| panel_view.view_id == id), self.tree_views.views.iter().find(|tree_view| tree_view.id == id)) {
(Some(panel_view), _) => (panel_view.visible)(self),
(None, Some(tree_view)) => tree_view.when.as_ref().is_none_or(|when| when.evaluate(&self.context_keys)) && !self.view_hidden(container, id),
diff --git a/native/crates/app/src/workbench/view_panes.rs b/native/crates/app/src/workbench/view_panes.rs
index 774db9ebef4..fe4b66aa164 100644
--- a/native/crates/app/src/workbench/view_panes.rs
+++ b/native/crates/app/src/workbench/view_panes.rs
@@ -16,6 +16,7 @@ use serde_json::{Value, json};
use super::Workbench;
use super::extensions_view::VIEWLET_ID as EXTENSIONS_CONTAINER;
use super::debug_view::{BREAKPOINTS_VIEW, CALL_STACK_VIEW, DEBUG_CONTAINER, LOADED_SCRIPTS_VIEW, VARIABLES_VIEW, WATCH_VIEW};
+use super::notebook_variables::NOTEBOOK_VARIABLES_VIEW;
use super::testing_view::TESTING_VIEW;
use super::view_locations::{EXPLORER_CONTAINER, SCM_CONTAINER, SEARCH_CONTAINER, SEARCH_VIEW, TESTING_CONTAINER};
use super::view_visibility::container_storage_id;
@@ -104,7 +105,7 @@ fn view_weight(id: &str) -> f32 {
TESTING_VIEW => 80.,
OUTLINE_VIEW | TIMELINE_VIEW | CALL_STACK_VIEW => 30.,
WATCH_VIEW => 10.,
- LOADED_SCRIPTS_VIEW => 5.,
+ LOADED_SCRIPTS_VIEW | NOTEBOOK_VARIABLES_VIEW => 5.,
_ => 20.,
}
}
diff --git a/port/fixtures/ui-pair/m17/notebook-cell-execute.json b/port/fixtures/ui-pair/m17/notebook-cell-execute.json
new file mode 100644
index 00000000000..f8d9433934a
--- /dev/null
+++ b/port/fixtures/ui-pair/m17/notebook-cell-execute.json
@@ -0,0 +1,15 @@
+[
+ { "wait": 15000 },
+ { "hotkey": ["cmd", "p"] },
+ { "wait": 800 },
+ { "type": "sample.ipynb" },
+ { "wait": 800 },
+ { "key": "return" },
+ { "wait": 45000 },
+ { "click": [700, 330] },
+ { "wait": 1000 },
+ { "shot": "run-dropdown" },
+ { "click": [345, 311] },
+ { "wait": 1000 },
+ { "shot": "run-menu" }
+]
diff --git a/port/ledger.md b/port/ledger.md
index 9f00ca127ec..b61167cd2ef 100644
--- a/port/ledger.md
+++ b/port/ledger.md
@@ -567,7 +567,7 @@ One row per upstream unit, generated by `bun port/tools/gen-ledger.ts`; mileston
| workbench/contrib/meteredConnection | workbench contribution | M19 | verified | | the metered warning status entry and Configure Metered Connection (workbench/power.rs); port/tools/shell-check (port/fixtures/extensions/shell-tests, 6/6); cargo test -p app metered_connection |
| workbench/contrib/modernUI | workbench contribution | M11 | verified | | the modern layout only: the classic layout (`workbench.experimental.modernUI: false`) is removed by Artur's decision (port/notes.md Modern UI); `window.density.layout` compact and the Manage menu's Layout Density (cargo test -p app -- compact_density layout_density; ui-pair m11/layout-density.json and m11/status-backgrounds.json in both densities with SETTINGS `{"window.density.layout": "compact"}`, port/results/layout-density.md); the 1.147.0 modernUI CSS audit in port/notes.md Modern UI |
| workbench/contrib/multiDiffEditor | workbench contribution | M14 | verified | | multi_diff_editor.rs, workbench/editor_view/multi_diff_editor_view.rs, workbench/code_editors.rs: cargo test -p app multi_diff unchanged_bars_drag the_content_menu_floats_over_the_diffs a_file_side_is_a_code_editor every_drawn_file_side; ui-pair port/fixtures/ui-pair/menus/multi-diff-content.json with `FILE=notes.txt`, `steps-multi-diff-edit.json` (matches but for the reference's TypeScript diagnostics; port/notes.md Comments in diff editors); verified: cargo test -p app the_content_menu_floats_over_the_diffs, ui-pair menus/multi-diff-content.json: the toolbar's rows match the reference's |
-| workbench/contrib/notebook | workbench contribution | M17 | ported | [3 M] notebook_editor: no cell execute toolbar (`notebook/cell/execute`, notebookEditorWidget.ts:138 `cellExecuteToolbar`); kernel_picker.rs: no `notebook/kernelSource` actions (notebookKernelServiceImpl.ts:322); no notebookVariablesView.ts, so no `notebook/variables/context` | notebook.rs, notebook/kernels.rs, notebook/layout.rs, notebook/outline.rs, workbench/notebooks.rs, workbench/notebook_editor.rs, workbench/notebook_editor/outputs.rs, cell_actions.rs, folding.rs, dnd.rs (port/notes.md milestone 17): cargo test -p app -- notebook kernel renderer backup interactive repl outline quick_input explorer list_scroll walkthrough (288/0); cargo test -p app markdown_editor_files_offer notebook::tests::stream_compression a_dirty_notebook_backs_up the_cell_language_picker the_output_toolbar_menu renderers a_notebook_editor_comes_back the_customize_notebook_submenu the_cell_toolbar markdown_headers_fold headings_fold split_points the_toolbar_position a_cell_dragged_by_its_left_column_moves_or_copies_to_the_drop_place markdown_headers_fold_their_sections every_selected_range_moves_to_the_drop_place the_outline_header_collapses_and_expands_the_notebook_s_headers; api-tests `MOCHA_GREP="Notebook|ipynb|Interactive Window|Ensure tabs getter"` 41/10/0 three runs in a row (10 pending are upstream skips); ui-pair m17 notebook-open, -keys-outline, -output-toolbar, -kernel-picker, -restore, -cell-click, -scroll, -toolbars, -find (within 1 device px). Differences left are reference quirks not copied (port/notes.md session m17d) |
+| workbench/contrib/notebook | workbench contribution | M17 | verified | | notebook.rs, notebook/kernels.rs, notebook/layout.rs, notebook/outline.rs, workbench/notebooks.rs, workbench/notebook_editor.rs, workbench/notebook_editor/outputs.rs, cell_actions.rs, folding.rs, dnd.rs, kernel_picker.rs, notebook_variables.rs (port/notes.md milestone 17): cargo test -p app -- notebook kernel renderer backup interactive repl outline quick_input explorer list_scroll walkthrough markdown_editor debug view menus (872/0), incl. the_cell_execute_menu, kernel_source_actions_run_from_the_kernel_picker, the_notebook_variables_view_lists_the_kernels_variables; cargo test -p app markdown_editor_files_offer notebook::tests::stream_compression a_dirty_notebook_backs_up the_cell_language_picker the_output_toolbar_menu renderers a_notebook_editor_comes_back the_customize_notebook_submenu the_cell_toolbar markdown_headers_fold headings_fold split_points the_toolbar_position a_cell_dragged_by_its_left_column_moves_or_copies_to_the_drop_place markdown_headers_fold_their_sections every_selected_range_moves_to_the_drop_place the_outline_header_collapses_and_expands_the_notebook_s_headers; api-tests `MOCHA_GREP="Notebook|ipynb|Interactive Window|Ensure tabs getter"` 41/10/0 three runs in a row (10 pending are upstream skips); ui-pair m17 notebook-open, -keys-outline, -output-toolbar, -kernel-picker, -restore, -cell-click, -scroll, -toolbars, -find (within 1 device px); ui-pair m17 notebook-cell-execute with `SETTINGS={"notebook.consolidatedRunButton":true}` (run button, chevron and menu items match). Differences left are reference quirks not copied (port/notes.md session m17d) |
| workbench/contrib/onboarding | workbench contribution | M19 | removed | | the only registered tours are the Agents window ones (src/vs/sessions/contrib/onboardingTours): no AI by decision (port/notes.md) |
| workbench/contrib/opener | workbench contribution | M12 | verified | | workbench/opener.rs open_folder_link: a link to a workspace folder reveals it in the Explorer; verified at port-m12b-verify: cargo test -p app opener 4/4 |
| workbench/contrib/outline | workbench contribution | M13 | verified | | workbench/outline_pane.rs, workbench/outline_actions.rs, workbench/outline_find.rs, workbench/icon_label.rs: cargo test -p app outline_pane outline the_compare_commands_open_diff_editors focus_view_commands_open_the_explorer_pane_and_focus_it find_filters_or_highlights_the_symbols the_keys_move_the_focus_and_the_list_commands_act_on_it a_description_is_0_9em; cargo test -p app -- a_row_s_contents_start_30px_into_the_row the_detail_follows_the_name_s_exact_width; ui-pair m12/compare-outline.json, steps-outline.json (port/results/language-features.md), m12/outline-find.json, search and quick open rows |
diff --git a/port/notes.md b/port/notes.md
index 28792481721..c0e64244c3d 100644
--- a/port/notes.md
+++ b/port/notes.md
@@ -741,6 +741,7 @@ Scope (milestone 18): extension management on disk with VSIX install and uninsta
- Session m17b (fourth pass): notebook find (`workbench/notebook_editor/find.rs`, notebookFindWidget.ts, findModel.ts): Cmd+F in the list or a cell editor (`actions.find` routes to it in a notebook editor), the widget at the list's top right under the toolbar, cell sources searched natively and rendered markdown and outputs by the preloads (`find`, `didFind`, `findHighlightCurrent`), the four filters as a checked menu, Enter and Shift+Enter, replace and replace all on sources (markup cells with matches open in edit mode while the replace input shows), research on each edit, decorations in the cell editors. The back layer webview draws over GPUI, so its clip view gets a CALayer mask with a hole where the widget lies, and presses there go to GPUI (`ClipView::place` `hole`). Checks: `cargo test -p app notebook_find`, ui-pair m17/notebook-find.json (typed, next, output: count, match highlights in a code cell and an output, webview current match as the reference). Not done: the widget's resize sash, Find in Selection (shown, inert), the `+` count past 1000 in the webview. Notebook view state (`NotebookEditorViewState` in `memento/workbench.editor.notebook`): focused cell, `editorFocused`, scroll, editing cells, each cell editor's view state, saved on close and shutdown, loaded for a new editor: `cargo test -p app a_reopened_notebook_editor_brings_back`. The focused cell's editor with the keyboard has the `notebook.focusedEditorBorder` border (ui-pair m17/notebook-cell-click.json). A markup cell's toolbar goes when its `...` menu opens (the hidden webview never sends `mouseLeaveMarkupCell`, now handled too): `cargo test -p app a_markdown_cell_toolbar_goes_with_its_more_menu`; ui-pair notebook-toolbars code-toolbar still shows it, because the press at (1000,160) lands in the markup preview and hovers it in the port, not in the reference (open). With a cell editor focused by a click the reference's cell toolbar shows only `...` and delete; the port shows all (open). REPL input status bar: the input's EOL only, then the list's indentation, EOL and `Cell N of M` (seen in the reference): `cargo test -p app a_notebook_shown_as_repl`. The cell toolbar's Share submenu holds github's Copy vscode.dev Link in a GitHub repository: `cargo test -p app the_github_share_items_fill_the_share_submenus`.
- Session m17d: the MRU kernel picker (`workbench/kernel_picker.rs`), `onRenderer:` activation, the outline's Filter Entries, `notebook.cellToolbarVisibility` click, the notebook and interactive status bar items, restored editors taking the focus, REPL scratchpad backups, dirty notebooks in the Explorer badge. The cell list's vertical scrollbar and `NotebookOverviewRuler` (`workbench/notebook_editor/overview_ruler.rs`): the list scrolls as a workbench list (`ListId::Notebook`, list_scroll.rs: wheel sensitivity, smooth scrolling, the fading 10px scrollbar, the top shadow), the back layer's `did-scroll-wheel` takes the same path, and the list scrolls until 50px of the last cell are left (`paddingBottom` of `editor.scrollBeyondLastLine`, not in interactive and REPL history lists). The webview clip leaves the list's right 10px to the scrollbar and ruler (the cells end 16px from it). The ruler draws find's decorations in the center lane as notebookOverviewRuler.ts: scaled by the editor height with the 26px toolbar over the scroll height, a line at most the editor line height in canvas pixels (half of it on a 2x display). An unfocused cell editor has a cover that takes the mouse: a press focuses the cell and places its cursor (`click_active_editor_at`, shared with the playground); its lines answered for the active editor before, and a hover past the focused cell's last line panicked. Checks: `cargo test -p app the_notebook_list_scrolls_beyond, the_mouse_over_a_longer_unfocused_cell, overview_ruler`; ui-pair m17/notebook-find.json (ruler marks at the reference's place), m17/notebook-scroll.json. Differences named, not copied: the cell title toolbar keeps stale actions until a menu context key changes (the reference shows only `...` and delete on a cell focused by keyboard or click); the reference's breadcrumbs show `…` for a code cell until its content changes; the webview hides under menus and quick input (native layer, see above); a restored notebook's status bar in the reference leaves out the cell editor's items (`Ln, Col`, `LF`) though the cell editor has the focus; Add Cell Output to Chat (AI removed). Unfocused cell editors show their hovers since (`the_mouse_over_an_unfocused_cell_shows_its_hover`). Hovering a markdown preview then Down moves the focused cell in both (ui-pair hover-down, the open question of m17c closed).
- Views audit (ui-pairs m17/notebook-open, notebook-keys-outline, notebook-output-toolbar, notebook-toolbars, notebook-cli at 8f138e76960, Studio /tmp/views-ipynb and /tmp/views-ipynb2): the "differences left" above now match: breadcrumbs (also `sample.ipynb > …` and the chain after keyboard moves), Run All `...`, output `...` and its menu, fold chevron, code and markup cell toolbars, title gear, focus bars over the outputs, `Spaces: 4`, the Outline filter action, and on the command line the JSON breadcrumbs `> …` and the `{ }` language status. Left: the reference shows only `...` and delete on the markup cell right after opening (its stale toolbar, named above, not copied); the Output menu leaves out Add Cell Output to Chat (AI removed); in one of two runs a click on the markdown preview then Down kept Cell 1 focused (ledger row extension/ipynb). The reference showed git's "A git repository was found in the parent folders" prompt within 6 s of notebook-cli, the port did not (fixture inside this repository; not notebook code).
+- Session m17-gaps: the cell execute dropdown (codeCellRunToolbar.ts): with `notebook.consolidatedRunButton` the run button gets a chevron that opens the non-inline groups of `notebook/cell/execute` (Execute Above Cells, Execute Cell and Below), the button placed as `.run-button-container` in notebook.css (`cargo test -p app the_cell_execute_menu`, ui-pair m17/notebook-cell-execute.json). The kernel picker lists `notebook/kernelSource` actions (notebookKernelServiceImpl.ts `getSourceActions`) and runs them with `{uri, $mid: 14}`, the notebook toolbar's kernel button shows `sync~spin` and the action's title while one runs; a failed action is logged to stderr, as upstream only warns (`kernel_source_actions_run_from_the_kernel_picker`). The Notebook Variables view (`workbench/notebook_variables.rs`, notebookVariablesView.ts) sits in Run and Debug after Breakpoints when `notebook.variablesView` is on (or a REPL is active) and the bound kernel has a variable provider; it pages children by 100 and its context menu is `notebook/variables/context` with Copy Value (`the_notebook_variables_view_lists_the_kernels_variables`). Not seen in a ui-pair: no extension in the fixtures contributes kernel source actions or a variable provider for the reference.
## Milestone 14: source control and diff