Skip to content

Visual Studio Code, rebuilt in Rust

Rust
76.2 KB
Raw Blame
use std::path::Path;
use std::sync::{Arc, Mutex};

use exthost::scan::scan_extension;
use gpui::{TestAppContext, VisualTestContext};
use serde_json::json;

use crate::host_sync::HostSync;
use crate::languages::Languages;
use crate::theme::load_theme;
use crate::workbench::Workbench;

fn notebook_workbench(cx: &mut TestAppContext) -> (gpui::Entity<Workbench>, &mut VisualTestContext) {
    let (workbench, cx, _) = workbench_with_cells(json!([{ "cellKind": 2, "language": "python", "source": "x", "outputs": [], "metadata": {} }]), cx);
    workbench.update_in(cx, |workbench, window, cx| window.focus(&workbench.editor_focus, cx));
    cx.run_until_parked();
    (workbench, cx)
}

/// An untitled notebook of `cells` shown in its editor, as `vscode.openNotebookDocument` and `showNotebookDocument`.
fn workbench_with_cells(cells: serde_json::Value, cx: &mut TestAppContext) -> (gpui::Entity<Workbench>, &mut VisualTestContext, std::sync::mpsc::Receiver<crate::host_sync::HostMessage>) {
    let app_root = Path::new(env!("VSCODE_SRC")).to_path_buf();
    let themes = scan_extension(&app_root.join("extensions/theme-defaults"), true).unwrap();
    let theme = load_theme(&[themes], "Dark Modern").unwrap();
    // One folder per call: tests run in parallel threads of one process and would remove each other's.
    static NEXT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
    let run = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
    let dir = std::env::temp_dir().join(format!("vsrustium-notebook-editor-{}-{run}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(dir.join("User")).unwrap();
    let settings = config::service::Settings::load(config::registry::Registry::with_extensions(&[]), dir.join("User"), None);
    let (sender, receiver) = std::sync::mpsc::channel();
    let (workbench, cx) = cx.add_window_view(|_, cx| Workbench::new(theme, app_root.clone(), None, Languages::new(&[]), Arc::new(Mutex::new(settings)), HostSync::new(sender), cx));
    let uri = json!({ "scheme": "untitled", "authority": "", "path": "Untitled-1.ipynb", "query": "", "fragment": "" });
    let data = json!({ "cells": cells, "metadata": {} });
    workbench.update_in(cx, |workbench, window, cx| {
        workbench.load_keybindings(crate::keybindings::default_keybindings(&[]), dir.join("User/keybindings.json"));
        let key = crate::notebook::uri_string(&uri);
        // As `open_notebook` holds a model until its editor shows it.
        workbench.host.notebooks.held.push(key.clone());
        workbench.add_notebook(uri.clone(), "jupyter-notebook", &data, false, cx);
        workbench.show_notebook(&key, &json!({}), window, cx).unwrap();
        workbench.host.notebooks.held.clear();
    });
    cx.run_until_parked();
    (workbench, cx, receiver)
}

fn run(workbench: &gpui::Entity<Workbench>, id: &str, cx: &mut VisualTestContext) {
    let args = match id {
        "type" => vec![json!({ "text": "1" })],
        _ => Vec::new(),
    };
    workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command(id, args, window, cx)));
    cx.run_until_parked();
}

/// The cells' sources, in order.
fn sources(workbench: &gpui::Entity<Workbench>, cx: &mut VisualTestContext) -> Vec<String> {
    workbench.read_with(cx, |workbench, _| {
        let model = &workbench.host.notebooks.models[0];
        model.cells.iter().map(|cell| workbench.cell_text(&cell.uri)).collect()
    })
}

/// notebook.contribution.ts: with `notebook.undoRedoPerCell` off a cell's text edits go on the notebook's stack, so
/// undo in a cell editor takes cell edits and text edits in the order they happened.
#[gpui::test]
fn without_undo_redo_per_cell_undo_takes_cell_edits_and_cell_text_edits_in_order(cx: &mut TestAppContext) {
    let (workbench, cx) = notebook_workbench(cx);
    workbench.update(cx, |workbench, cx| {
        let before = workbench.model_creation_options();
        let change = workbench.settings.lock().unwrap().update_value("notebook.undoRedoPerCell", Some(&json!(false)), config::service::Target::User, None, &[]).unwrap();
        workbench.configuration_changed(&change, before, cx);
    });
    run(&workbench, "type", cx);
    assert_eq!(sources(&workbench, cx), ["1x"]);
    run(&workbench, "notebook.cell.insertCodeCellBelow", cx);
    assert_eq!(sources(&workbench, cx), ["1x", ""]);
    run(&workbench, "undo", cx);
    assert_eq!(sources(&workbench, cx), ["1x"]);
    run(&workbench, "undo", cx);
    assert_eq!(sources(&workbench, cx), ["x"]);
    run(&workbench, "redo", cx);
    assert_eq!(sources(&workbench, cx), ["1x"]);
    run(&workbench, "redo", cx);
    assert_eq!(sources(&workbench, cx), ["1x", ""]);
}

/// The default `notebook.undoRedoPerCell`: a cell editor undoes its own cell's text, the cell list the notebook's
/// cell edits.
#[gpui::test]
fn a_cell_editor_undoes_its_cell_and_the_cell_list_the_cell_edits(cx: &mut TestAppContext) {
    let (workbench, cx) = notebook_workbench(cx);
    run(&workbench, "type", cx);
    run(&workbench, "notebook.cell.insertCodeCellBelow", cx);
    assert_eq!(sources(&workbench, cx), ["1x", ""]);
    run(&workbench, "undo", cx);
    assert_eq!(sources(&workbench, cx), ["1x", ""], "the new cell's editor has nothing to undo");
    focus_cell_list(&workbench, cx);
    run(&workbench, "undo", cx);
    assert_eq!(sources(&workbench, cx), ["1x"]);
    run(&workbench, "undo", cx);
    assert_eq!(sources(&workbench, cx), ["1x"], "the text edit is on its cell's stack");
}

fn focus_cell_list(workbench: &gpui::Entity<Workbench>, cx: &mut VisualTestContext) {
    workbench.update_in(cx, |workbench, window, cx| window.focus(&workbench.notebook_views.list_focus, cx));
    cx.run_until_parked();
}

/// `applyEdits` of `cell_edits` on the notebook as one undo step (bulkCellEdits.ts).
fn apply_cell_edits(workbench: &gpui::Entity<Workbench>, cell_edits: serde_json::Value, cx: &mut VisualTestContext) {
    workbench.update(cx, |workbench, cx| {
        let resource = workbench.host.notebooks.models[0].uri.clone();
        let edits: Vec<_> = cell_edits.as_array().unwrap().iter().map(|edit| json!({ "resource": resource, "cellEdit": edit })).collect();
        workbench.apply_workspace_cell_edits(&edits, files::operations::new_undo_group(), cx).unwrap();
    });
}

fn markup_workbench(cx: &mut TestAppContext) -> (gpui::Entity<Workbench>, &mut VisualTestContext) {
    let cells = json!([
        { "cellKind": 1, "language": "markdown", "source": "# header 1", "outputs": [], "metadata": {} },
        { "cellKind": 1, "language": "markdown", "source": "body", "outputs": [], "metadata": {} },
    ]);
    let (workbench, cx, _) = workbench_with_cells(cells, cx);
    focus_cell_list(&workbench, cx);
    (workbench, cx)
}

fn length_and_version(workbench: &gpui::Entity<Workbench>, cx: &mut VisualTestContext) -> (usize, u64) {
    workbench.read_with(cx, |workbench, _| (workbench.host.notebooks.models[0].cells.len(), workbench.host.notebooks.models[0].version_id))
}

/// notebookUndoRedo.test.ts `Basics`.
#[gpui::test]
fn notebook_undo_redo_basics(cx: &mut TestAppContext) {
    let (workbench, cx) = markup_workbench(cx);
    apply_cell_edits(&workbench, json!([{ "editType": 1, "index": 0, "count": 2, "cells": [] }]), cx);
    assert_eq!(length_and_version(&workbench, cx), (0, 1));
    run(&workbench, "undo", cx);
    assert_eq!(length_and_version(&workbench, cx), (2, 2));
    run(&workbench, "redo", cx);
    assert_eq!(length_and_version(&workbench, cx), (0, 3));
    let header = json!({ "cellKind": 1, "language": "markdown", "source": "# header 3", "outputs": [], "metadata": {} });
    apply_cell_edits(&workbench, json!([{ "editType": 1, "index": 0, "count": 0, "cells": [header] }]), cx);
    assert_eq!(length_and_version(&workbench, cx), (1, 4));
    run(&workbench, "undo", cx);
    assert_eq!(length_and_version(&workbench, cx), (0, 5));
}

/// notebookUndoRedo.test.ts `Invalid replace count should not throw` and `Invalid replace count should not affect
/// undo/redo`.
#[gpui::test]
fn an_invalid_replace_count_neither_throws_nor_affects_undo_redo(cx: &mut TestAppContext) {
    let (workbench, cx) = markup_workbench(cx);
    apply_cell_edits(&workbench, json!([{ "editType": 1, "index": 0, "count": 2, "cells": [] }]), cx);
    let header = json!({ "cellKind": 1, "language": "markdown", "source": "# header 2", "outputs": [], "metadata": {} });
    apply_cell_edits(&workbench, json!([{ "editType": 1, "index": 0, "count": 2, "cells": [header] }]), cx);
    assert_eq!(length_and_version(&workbench, cx).0, 1);
    run(&workbench, "undo", cx);
    run(&workbench, "undo", cx);
    assert_eq!(length_and_version(&workbench, cx).0, 2);
    apply_cell_edits(&workbench, json!([{ "editType": 1, "index": 1, "count": 2, "cells": [] }]), cx);
    assert_eq!(length_and_version(&workbench, cx).0, 1);
}

/// notebookUndoRedo.test.ts `Replace beyond length`.
#[gpui::test]
fn notebook_undo_of_a_replace_beyond_the_length(cx: &mut TestAppContext) {
    let (workbench, cx) = markup_workbench(cx);
    apply_cell_edits(&workbench, json!([{ "editType": 1, "index": 1, "count": 2, "cells": [] }]), cx);
    assert_eq!(length_and_version(&workbench, cx).0, 1);
    run(&workbench, "undo", cx);
    assert_eq!(length_and_version(&workbench, cx).0, 2);
}

/// notebookUndoRedo.test.ts `Batch edits`.
#[gpui::test]
fn notebook_undo_redo_of_batch_edits(cx: &mut TestAppContext) {
    let (workbench, cx) = markup_workbench(cx);
    let header = json!({ "cellKind": 1, "language": "markdown", "source": "# header 2", "outputs": [], "metadata": {} });
    apply_cell_edits(&workbench, json!([{ "editType": 1, "index": 2, "count": 0, "cells": [header] }, { "editType": 3, "index": 0, "metadata": { "inputCollapsed": false } }]), cx);
    let first_metadata = |cx: &mut VisualTestContext| workbench.read_with(cx, |workbench, _| workbench.host.notebooks.models[0].cells[0].metadata.clone());
    assert_eq!(first_metadata(cx), json!({ "inputCollapsed": false }));
    run(&workbench, "undo", cx);
    assert_eq!(length_and_version(&workbench, cx).0, 2);
    assert_eq!(first_metadata(cx), json!({}));
    run(&workbench, "redo", cx);
    assert_eq!(length_and_version(&workbench, cx).0, 3);
    assert_eq!(first_metadata(cx), json!({ "inputCollapsed": false }));
}

/// notebookTextModel.ts `dispose`: `removeElements(this.uri)`.
#[gpui::test]
fn a_released_notebook_drops_its_undo_stack(cx: &mut TestAppContext) {
    let (workbench, cx) = markup_workbench(cx);
    apply_cell_edits(&workbench, json!([{ "editType": 1, "index": 0, "count": 1, "cells": [] }]), cx);
    let key = workbench.read_with(cx, |workbench, _| workbench.host.notebooks.models[0].uri_string());
    let has_elements = |cx: &mut VisualTestContext| workbench.read_with(cx, |workbench, _| workbench.editors.undo_redo.borrow().has_elements(&key));
    assert!(has_elements(cx));
    workbench.update(cx, |workbench, _| workbench.host.notebooks.models[0].dirty = false);
    run(&workbench, "workbench.action.closeActiveEditor", cx);
    assert!(workbench.read_with(cx, |workbench, _| workbench.host.notebooks.models.is_empty()), "the notebook is released");
    assert!(!has_elements(cx));
}

#[gpui::test]
fn cell_edits_of_a_workspace_edit_are_one_undo_step(cx: &mut TestAppContext) {
    let cells = json!([
        { "cellKind": 2, "language": "python", "source": "a", "outputs": [], "metadata": {} },
        { "cellKind": 2, "language": "python", "source": "b", "outputs": [], "metadata": {} },
    ]);
    let (workbench, cx, _) = workbench_with_cells(cells, cx);
    focus_cell_list(&workbench, cx);
    apply_cell_edits(&workbench, json!([{ "editType": 1, "index": 0, "count": 1, "cells": [] }, { "editType": 4, "index": 1, "language": "rust" }]), cx);
    assert_eq!(sources(&workbench, cx), ["b"]);
    run(&workbench, "undo", cx);
    assert_eq!(sources(&workbench, cx), ["a", "b"]);
    let languages = |cx: &mut VisualTestContext| workbench.read_with(cx, |workbench, _| workbench.host.notebooks.models[0].cells.iter().map(|cell| cell.language.clone()).collect::<Vec<_>>());
    assert_eq!(languages(cx), ["python", "python"]);
    run(&workbench, "redo", cx);
    assert_eq!(sources(&workbench, cx), ["b"]);
    assert_eq!(languages(cx), ["rust"]);
}

/// bulkCellEdits.ts passes the workspace edit's `undoRedoGroup`: its cell edits and its text edit of a cell, on two
/// stacks, are one undo step.
#[gpui::test]
fn the_cell_and_text_edits_of_a_workspace_edit_undo_together(cx: &mut TestAppContext) {
    let (workbench, cx) = notebook_workbench(cx);
    focus_cell_list(&workbench, cx);
    workbench.update(cx, |workbench, cx| {
        let group = files::operations::new_undo_group();
        let model = &workbench.host.notebooks.models[0];
        let text_edit = json!([{ "resource": model.cells[0].uri, "textEdit": { "range": { "startLineNumber": 1, "startColumn": 1, "endLineNumber": 1, "endColumn": 1 }, "text": "1" } }]);
        let cell_edit = [json!({ "resource": model.uri, "cellEdit": { "editType": 4, "index": 0, "language": "rust" } })];
        workbench.apply_workspace_text_edits(&text_edit, &json!([]), group, None, cx).unwrap();
        workbench.apply_workspace_cell_edits(&cell_edit, group, cx).unwrap();
    });
    let language = |cx: &mut VisualTestContext| workbench.read_with(cx, |workbench, _| workbench.host.notebooks.models[0].cells[0].language.clone());
    assert_eq!((sources(&workbench, cx), language(cx)), (vec!["1x".to_owned()], "rust".to_owned()));
    run(&workbench, "undo", cx);
    assert_eq!((sources(&workbench, cx), language(cx)), (vec!["x".to_owned()], "python".to_owned()));
    run(&workbench, "redo", cx);
    assert_eq!((sources(&workbench, cx), language(cx)), (vec!["1x".to_owned()], "rust".to_owned()));
}

/// `StackOperation.label` of the edits a workspace edit applied: `SpliceCellsEdit` names the cells actually removed
/// (a count past the end is clipped), and an edit that changes nothing pushes no operation.
#[gpui::test]
fn a_cell_edit_is_labeled_by_the_operations_it_pushed(cx: &mut TestAppContext) {
    let (workbench, cx) = markup_workbench(cx);
    let label = |cx: &mut VisualTestContext| {
        workbench.read_with(cx, |workbench, _| {
            let key = workbench.host.notebooks.models[0].uri_string();
            workbench.editors.undo_redo.borrow().last_label(&key).unwrap().to_owned()
        })
    };
    let cell = json!({ "cellKind": 1, "language": "markdown", "source": "", "outputs": [], "metadata": {} });
    apply_cell_edits(&workbench, json!([{ "editType": 4, "index": 0, "language": "markdown" }, { "editType": 6, "index": 0, "length": 1, "newIdx": 1 }]), cx);
    assert_eq!(label(cx), "Move Cell");
    apply_cell_edits(&workbench, json!([{ "editType": 1, "index": 0, "count": 0, "cells": [cell.clone(), cell] }]), cx);
    assert_eq!(label(cx), "Insert Cells");
    apply_cell_edits(&workbench, json!([{ "editType": 1, "index": 3, "count": 5, "cells": [] }]), cx);
    assert_eq!(label(cx), "Delete Cell");
    apply_cell_edits(&workbench, json!([{ "editType": 4, "index": 0, "language": "python" }, { "editType": 4, "index": 1, "language": "python" }]), cx);
    assert_eq!(label(cx), "edit");
}

#[gpui::test]
fn the_focused_cell_is_the_code_editor_the_workbench_edits(cx: &mut TestAppContext) {
    let (workbench, cx) = notebook_workbench(cx);
    workbench.read_with(cx, |workbench, _| assert_eq!(workbench.editors.active().unwrap().document().scheme, crate::notebook::CELL_SCHEME));
    run(&workbench, "notebook.cell.insertCodeCellBelow", cx);
    run(&workbench, "type", cx);
    assert_eq!(sources(&workbench, cx), ["x", "1"]);
}

#[gpui::test]
fn a_click_on_the_text_of_another_code_cell_edits_that_cell(cx: &mut TestAppContext) {
    let cells = json!([
        { "cellKind": 2, "language": "python", "source": "a = 1", "outputs": [], "metadata": {} },
        { "cellKind": 2, "language": "python", "source": "b = 2", "outputs": [], "metadata": {} },
    ]);
    let (workbench, cx, _) = workbench_with_cells(cells, cx);
    let handle = workbench.read_with(cx, |workbench, _| workbench.host.notebooks.models[0].cells[1].handle);
    let bounds = cx.debug_bounds(Box::leak(format!("notebook-cell-editor-{handle}").into_boxed_str())).unwrap();
    cx.simulate_click(bounds.origin + gpui::point(gpui::px(60.), gpui::px(8.)), gpui::Modifiers::default());
    workbench.update_in(cx, |workbench, window, _| {
        assert_eq!(workbench.active_notebook_editor().unwrap().focus, 1);
        assert!(workbench.editor_focus.is_focused(window));
        let editor = workbench.editors.active().unwrap();
        assert_eq!(editor.document().lines[0], "b = 2");
        assert_eq!(editor.selection().head.line, 0);
    });
}

#[gpui::test]
fn the_mouse_over_a_longer_unfocused_cell_reaches_that_cell(cx: &mut TestAppContext) {
    let cells = json!([
        { "cellKind": 2, "language": "python", "source": "a = 1", "outputs": [], "metadata": {} },
        { "cellKind": 2, "language": "python", "source": "b = 2\nc = 3\nd = 4", "outputs": [], "metadata": {} },
    ]);
    let (workbench, cx, _) = workbench_with_cells(cells, cx);
    let handle = workbench.read_with(cx, |workbench, _| workbench.host.notebooks.models[0].cells[1].handle);
    let bounds = cx.debug_bounds(Box::leak(format!("notebook-cell-editor-{handle}").into_boxed_str())).unwrap();
    let line_height = workbench.read_with(cx, |workbench, _| workbench.notebook_line_height());
    // Line 3 of the second cell, past the focused cell's only line.
    let third_line = bounds.origin + gpui::point(gpui::px(60.), gpui::px(line_height * 2.5));
    cx.simulate_mouse_move(third_line, None, gpui::Modifiers::default());
    cx.run_until_parked();
    cx.simulate_click(third_line, gpui::Modifiers::default());
    workbench.update_in(cx, |workbench, _, _| {
        assert_eq!(workbench.active_notebook_editor().unwrap().focus, 1);
        assert_eq!(workbench.editors.active().unwrap().selection().head.line, 2);
    });
}

#[gpui::test]
fn notebook_find_goes_through_the_matches_of_all_cells_and_replaces_them(cx: &mut TestAppContext) {
    let cells = json!([
        { "cellKind": 2, "language": "python", "source": "x = 1\nx", "outputs": [], "metadata": {} },
        { "cellKind": 2, "language": "python", "source": "y = x", "outputs": [], "metadata": {} },
        { "cellKind": 1, "language": "markdown", "source": "x md", "outputs": [], "metadata": {} },
    ]);
    let (workbench, cx, _) = workbench_with_cells(cells, cx);
    cx.simulate_keystrokes(&crate::keybindings::primary_keys("secondary-f"));
    workbench.update_in(cx, |workbench, window, cx| {
        assert!(workbench.notebook_views.find.find_focus.is_focused(window), "Cmd+F in the cell list focuses the notebook find input");
        workbench.edit_notebook_find_input(super::super::input_box_view::InputId::NotebookFind, |input| input.set_value("x".into()), cx);
    });
    cx.run_until_parked();
    let label = |cx: &mut VisualTestContext| workbench.read_with(cx, |workbench, _| workbench.notebook_find_count_label());
    assert_eq!(label(cx), "1 of 3", "a markdown preview's source is left to the rendered markdown filter");
    cx.simulate_keystrokes("enter");
    cx.simulate_keystrokes("enter");
    assert_eq!(label(cx), "3 of 3");
    workbench.update_in(cx, |workbench, window, _| {
        assert_eq!(workbench.active_notebook_editor().unwrap().focus, 1, "the match's cell takes the focus");
        assert!(workbench.notebook_views.find.find_focus.is_focused(window), "the find input keeps the keyboard");
        let editor = workbench.editors.active().unwrap();
        assert_eq!((editor.selection().start(), editor.selection().end()), (crate::editor::Position::new(0, 4), crate::editor::Position::new(0, 5)));
    });
    cx.simulate_keystrokes("shift-enter");
    assert_eq!(label(cx), "2 of 3");
    run(&workbench, "_notebook.find.filter.markupPreview", cx);
    assert_eq!(label(cx), "2 of 4", "without the rendered markdown filter the markdown source counts");
    workbench.update_in(cx, |workbench, _, cx| {
        workbench.notebook_views.find.state.replace_string = "z".into();
        workbench.notebook_find_replace_all(cx);
    });
    cx.run_until_parked();
    assert_eq!(sources(&workbench, cx), ["z = 1\nz", "y = z", "z md"]);
    assert_eq!(label(cx), "No results");
    cx.simulate_keystrokes("escape");
    workbench.update_in(cx, |workbench, window, _| {
        assert!(!workbench.notebook_find_visible());
        assert!(workbench.notebook_views.list_focus.is_focused(window), "the focus returns to the cell list");
    });
}

#[gpui::test]
fn a_reopened_notebook_editor_brings_back_its_focused_cell_editor_and_selection(cx: &mut TestAppContext) {
    let cells = json!([
        { "cellKind": 2, "language": "python", "source": "a = 1", "outputs": [], "metadata": {} },
        { "cellKind": 2, "language": "python", "source": "b = 22", "outputs": [], "metadata": {} },
    ]);
    let (workbench, cx, _) = workbench_with_cells(cells, cx);
    cx.simulate_keystrokes("down enter end shift-left");
    let key = workbench.read_with(cx, |workbench, _| workbench.host.notebooks.models[0].uri_string());
    workbench.update_in(cx, |workbench, window, cx| {
        workbench.host.notebooks.held.push(key.clone());
        drop(workbench.execute_command("workbench.action.closeActiveEditor", Vec::new(), window, cx));
    });
    cx.run_until_parked();
    workbench.read_with(cx, |workbench, _| assert!(workbench.active_notebook_editor().is_none()));
    workbench.update_in(cx, |workbench, window, cx| workbench.show_notebook(&key, &json!({}), window, cx).unwrap());
    cx.run_until_parked();
    workbench.update_in(cx, |workbench, window, _| {
        assert_eq!(workbench.active_notebook_editor().unwrap().focus, 1);
        assert!(workbench.editor_focus.is_focused(window), "the cell editor had the keyboard");
        let editor = workbench.editors.active().unwrap();
        assert_eq!(editor.document().lines[0], "b = 22");
        assert_eq!((editor.selection().anchor, editor.selection().head), (crate::editor::Position::new(0, 6), crate::editor::Position::new(0, 5)));
    });
}

#[gpui::test]
fn a_markdown_cell_toolbar_goes_with_its_more_menu(cx: &mut TestAppContext) {
    let cells = json!([
        { "cellKind": 2, "language": "python", "source": "x", "outputs": [], "metadata": {} },
        { "cellKind": 1, "language": "markdown", "source": "# Title", "outputs": [], "metadata": {} },
    ]);
    let (workbench, cx, _) = workbench_with_cells(cells, cx);
    let (tab, handle) = workbench.read_with(cx, |workbench, _| (workbench.host.notebooks.editors[0].tab_model_id, workbench.host.notebooks.models[0].cells[1].handle));
    workbench.update(cx, |workbench, cx| {
        workbench.update_user_setting("notebook.cellToolbarVisibility", json!("hover"));
        workbench.notebook_views.views.entry(tab).or_default().hovered = Some(handle);
        cx.notify();
    });
    cx.run_until_parked();
    let more = Box::leak(format!("notebook-cell-toolbar-more-{handle}").into_boxed_str());
    let center = cx.debug_bounds(more).unwrap().center();
    cx.simulate_click(center, gpui::Modifiers::default());
    cx.simulate_keystrokes("escape");
    cx.run_until_parked();
    assert!(cx.debug_bounds(more).is_none(), "the hidden webview never reports the pointer leaving the preview for the menu");
}

/// cellDnd.ts: a cell dragged by its left column drops below the lower half of another cell, or with Alt is copied.
#[gpui::test]
fn a_cell_dragged_by_its_left_column_moves_or_copies_to_the_drop_place(cx: &mut TestAppContext) {
    let cells = json!([
        { "cellKind": 2, "language": "python", "source": "a", "outputs": [], "metadata": {} },
        { "cellKind": 2, "language": "python", "source": "b", "outputs": [], "metadata": {} },
        { "cellKind": 2, "language": "python", "source": "c", "outputs": [], "metadata": {} },
    ]);
    let (workbench, cx, _) = workbench_with_cells(cells, cx);
    let drag = |from: usize, to: usize, lower: bool, modifiers: gpui::Modifiers, cx: &mut VisualTestContext| {
        let handles: Vec<u64> = workbench.read_with(cx, |workbench, _| workbench.host.notebooks.models[0].cells.iter().map(|cell| cell.handle).collect());
        let start = cx.debug_bounds(Box::leak(format!("notebook-cell-drag-handle-{}", handles[from]).into_boxed_str())).unwrap().center();
        let target = cx.debug_bounds(Box::leak(format!("notebook-cell-drag-handle-{}", handles[to]).into_boxed_str())).unwrap();
        let end = gpui::point(target.center().x, if lower { target.center().y + gpui::px(10.) } else { target.top() + gpui::px(4.) });
        cx.simulate_mouse_down(start, gpui::MouseButton::Left, gpui::Modifiers::default());
        cx.simulate_mouse_move(start + gpui::point(gpui::px(0.), gpui::px(10.)), Some(gpui::MouseButton::Left), gpui::Modifiers::default());
        cx.simulate_mouse_move(end, Some(gpui::MouseButton::Left), modifiers);
        cx.simulate_mouse_up(end, gpui::MouseButton::Left, modifiers);
        cx.run_until_parked();
    };
    drag(0, 2, true, gpui::Modifiers::default(), cx);
    assert_eq!(sources(&workbench, cx), ["b", "c", "a"]);
    assert_eq!(workbench.read_with(cx, |workbench, _| workbench.active_notebook_editor().unwrap().focus), 2);
    drag(2, 0, false, gpui::Modifiers::alt(), cx);
    assert_eq!(sources(&workbench, cx), ["a", "b", "c", "a"]);
}

/// notebookEditorWidget.ts `paddingBottom`: with `editor.scrollBeyondLastLine` the list scrolls until 50px of it
/// are left; the wheel scrolls it as a workbench list, 50px a notch.
#[gpui::test]
fn the_notebook_list_scrolls_beyond_its_last_cell_with_the_wheel(cx: &mut TestAppContext) {
    use crate::workbench::list_scroll::ListId;
    let (workbench, cx) = notebook_workbench(cx);
    let tab = workbench.read_with(cx, |workbench, _| workbench.active_notebook_tab().unwrap().0);
    let scroller = |cx: &mut VisualTestContext| workbench.read_with(cx, |workbench, _| workbench.list_scroller(ListId::Notebook(tab)));
    let (bounds, content) = workbench.read_with(cx, |workbench, _| {
        let model = &workbench.host.notebooks.models[0];
        (workbench.list_scroller(ListId::Notebook(tab)).bounds(), workbench.notebook_rows(tab, model).last().map(|row| row.layout.top + row.layout.height).unwrap())
    });
    assert!(content < f32::from(bounds.size.height), "one cell fits the list: {content} in {bounds:?}");
    assert_eq!(scroller(cx).max_position().y, content - 50.);
    cx.simulate_event(gpui::ScrollWheelEvent { position: bounds.center(), delta: gpui::ScrollDelta::Lines(gpui::point(0., -1.)), ..Default::default() });
    cx.run_until_parked();
    assert_eq!(scroller(cx).position().y, 50.);
}

#[gpui::test]
fn the_cell_list_takes_the_keyboard_and_enter_and_escape_move_into_and_out_of_a_cell(cx: &mut TestAppContext) {
    let cells = json!([
        { "cellKind": 1, "language": "markdown", "source": "# Title\ntext", "outputs": [], "metadata": {} },
        { "cellKind": 2, "language": "python", "source": "a = 1\nb = 2", "outputs": [], "metadata": {} },
    ]);
    let (workbench, cx, _) = workbench_with_cells(cells, cx);
    let state = |cx: &mut VisualTestContext| {
        workbench.update_in(cx, |workbench, window, _| (workbench.active_notebook_editor().unwrap().focus, workbench.notebook_views.list_focus.is_focused(window), workbench.editor_focus.is_focused(window)))
    };
    assert_eq!(state(cx), (0, true, false), "the notebook opens with the focus on its cell list");
    cx.simulate_keystrokes("down");
    assert_eq!(state(cx), (1, true, false));
    cx.simulate_keystrokes("enter");
    assert_eq!(state(cx), (1, false, true), "Enter edits the focused cell");
    cx.simulate_keystrokes("up");
    assert_eq!(state(cx), (0, true, false), "Up on the first line goes to the cell above, a markdown preview takes no editor focus");
    cx.simulate_keystrokes("enter");
    assert_eq!(state(cx), (0, false, true), "Enter edits the markdown cell");
    cx.simulate_keystrokes("escape");
    assert_eq!(state(cx), (0, true, false), "Escape leaves the cell editor for the list");
    cx.simulate_keystrokes(&crate::keybindings::primary_keys("secondary-down"));
    assert_eq!(state(cx), (1, true, false));
    let crumbs = workbench.read_with(cx, |workbench, _| workbench.notebook_breadcrumbs(gpui::rgba(0xffffffff), 22.).unwrap().1.into_iter().map(|(_, label)| label).collect::<Vec<_>>());
    // notebookOutline.ts renders `' ' + label` right after a margin-less codicon.
    assert_eq!(crumbs, [" Title", " a = 1"], "the breadcrumbs name the header and the code cell below it");
}

#[gpui::test]
fn the_outline_header_collapses_and_expands_the_notebook_s_headers(cx: &mut TestAppContext) {
    let cells = json!([
        { "cellKind": 1, "language": "markdown", "source": "# Title\n## Part", "outputs": [], "metadata": {} },
        { "cellKind": 1, "language": "markdown", "source": "# Other", "outputs": [], "metadata": {} },
    ]);
    let (workbench, cx, _) = workbench_with_cells(cells, cx);
    let all_collapsed = |cx: &mut VisualTestContext| workbench.read_with(cx, |workbench, _| workbench.outline_all_collapsed());
    assert!(!all_collapsed(cx), "`# Title` has `## Part` below it and starts expanded");
    workbench.update(cx, |workbench, cx| workbench.set_outline_all_expanded(false, cx));
    assert!(all_collapsed(cx), "Collapse All folds `# Title`; `# Other` is a leaf");
    workbench.update(cx, |workbench, cx| workbench.set_outline_all_expanded(true, cx));
    assert!(!all_collapsed(cx));
    let depths = workbench.read_with(cx, |workbench, _| workbench.tree_depths(crate::workbench::list_scroll::ListId::Outline));
    assert_eq!(depths, [0, 1, 0], "the sticky rows read the notebook outline's shown depths");
}

#[gpui::test]
fn contributed_cell_status_items_follow_their_provider(cx: &mut TestAppContext) {
    let cells = json!([{ "cellKind": 2, "language": "python", "source": "a = 1", "outputs": [], "metadata": {} }]);
    let (workbench, cx, receiver) = workbench_with_cells(cells, cx);
    let answer = |receiver: &std::sync::mpsc::Receiver<crate::host_sync::HostMessage>, cache: u64, text: &str, cx: &mut VisualTestContext| {
        let mut count = 0;
        for message in receiver.try_iter().filter(|message| message.method == "$provideNotebookCellStatusBarItems") {
            assert_eq!((message.args[0].clone(), message.args[2].clone()), (json!(7), json!(0)));
            count += 1;
            let _ = message.reply.expect("a call").send(Ok(json!({ "cacheId": cache, "items": [{ "text": text, "alignment": 1 }] })));
        }
        cx.run_until_parked();
        count
    };
    let items = |cx: &mut VisualTestContext| {
        workbench.read_with(cx, |workbench, _| {
            let key = workbench.active_notebook_editor().unwrap().notebook.clone();
            let handle = workbench.host.notebooks.model(&key).unwrap().cells[0].handle;
            workbench.notebook_views.status_bars.items(&key, handle).iter().map(|item| item["text"].as_str().unwrap().to_owned()).collect::<Vec<_>>()
        })
    };
    let request = |method: &'static str, args: Vec<serde_json::Value>, cx: &mut VisualTestContext| workbench.update_in(cx, |workbench, window, cx| _ = workbench.handle_notebook_request("MainThreadNotebook", method, &args, window, cx));
    request("$registerNotebookCellStatusBarItemProvider", vec![json!(7), json!(8), json!("jupyter-notebook")], cx);
    assert_eq!(answer(&receiver, 1, "first", cx), 1);
    assert_eq!(items(cx), ["first"]);
    request("$emitCellStatusBarEvent", vec![json!(8)], cx);
    let released = |receiver: &std::sync::mpsc::Receiver<crate::host_sync::HostMessage>| receiver.try_iter().filter(|message| message.method == "$releaseNotebookCellStatusBarItems").map(|message| message.args[0].clone()).collect::<Vec<_>>();
    assert_eq!(answer(&receiver, 2, "second", cx), 1);
    assert_eq!(items(cx), ["second"]);
    assert_eq!(released(&receiver), [json!(1)], "the replaced list is released");
}

#[gpui::test]
fn the_variable_provider_command_collects_what_the_bound_kernel_sends(cx: &mut TestAppContext) {
    let cells = json!([{ "cellKind": 2, "language": "python", "source": "a = 1", "outputs": [], "metadata": {} }]);
    let (workbench, cx, receiver) = workbench_with_cells(cells, cx);
    let kernel = json!({ "id": "pub.ext/k", "notebookType": "jupyter-notebook", "label": "K", "hasVariableProvider": true, "extensionLocation": { "scheme": "file", "path": "/ext" }, "preloads": [] });
    let outcome = 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);
        workbench.execute_command("_executeNotebookVariableProvider", vec![uri], window, cx)
    });
    let crate::commands::Outcome::Pending(answer) = outcome else { panic!("the command waits for the kernel") };
    let call = receiver.try_iter().find(|message| message.method == "$provideVariables").expect("the kernel is asked");
    assert_eq!((call.args[0].clone(), call.args[1].clone(), call.args[4].clone()), (json!(3), json!("3variables0"), json!("named")));
    workbench.update_in(cx, |workbench, window, cx| {
        let variable = json!({ "variable": { "name": "a", "value": "1" }, "hasNamedChildren": false, "indexedChildrenCount": 0 });
        workbench.handle_notebook_request("MainThreadNotebookKernels", "$receiveVariable", &[json!("3variables0"), variable], window, cx);
    });
    let _ = call.reply.expect("a call").send(Ok(serde_json::Value::Null));
    cx.run_until_parked();
    let collected = futures::executor::block_on(answer).unwrap().unwrap();
    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.
#[gpui::test]
fn the_editor_status_keeps_the_code_cell_editor_a_notebook_opened_on(cx: &mut TestAppContext) {
    let (workbench, cx, _) = workbench_with_cells(json!([json!({ "cellKind": 2, "language": "python", "source": "x", "outputs": [], "metadata": {} }), json!({ "cellKind": 1, "language": "markdown", "source": "# m", "outputs": [], "metadata": {} })]), cx);
    assert!(workbench.read_with(cx, |workbench, _| workbench.notebook_status_editor().is_some()));
}

#[gpui::test]
fn the_editor_status_of_a_notebook_opened_on_a_markdown_cell_stays_empty(cx: &mut TestAppContext) {
    let (workbench, cx, _) = workbench_with_cells(json!([json!({ "cellKind": 1, "language": "markdown", "source": "# m", "outputs": [], "metadata": {} }), json!({ "cellKind": 2, "language": "python", "source": "x", "outputs": [], "metadata": {} })]), cx);
    workbench.update_in(cx, |workbench, window, cx| {
        let tab = workbench.host.notebooks.editors[0].tab_model_id;
        let handle = workbench.host.notebooks.models[0].cells[1].handle;
        workbench.focus_notebook_cell(tab, handle, true, window, cx);
    });
    cx.run_until_parked();
    assert!(workbench.read_with(cx, |workbench, _| workbench.notebook_status_editor().is_none()));
}

/// notebookRendererMessagingServiceImpl.ts: a renderer's messages from the webview reach the host only after its
/// `onRenderer:` activation, in the order they came.
#[gpui::test]
fn renderer_messages_wait_for_the_renderer_activation(cx: &mut TestAppContext) {
    let cells = json!([{ "cellKind": 2, "language": "python", "source": "x", "outputs": [], "metadata": {} }]);
    let (workbench, cx, receiver) = workbench_with_cells(cells, cx);
    receiver.try_iter().for_each(drop);
    let post = |text: &str, cx: &mut VisualTestContext| {
        workbench.update(cx, |workbench, cx| {
            let editor_id = workbench.host.notebooks.editors[0].id.clone();
            workbench.post_renderer_message(editor_id, "pub.r".into(), json!(text), cx);
        });
        cx.run_until_parked();
    };
    post("one", cx);
    post("two", cx);
    let sent: Vec<_> = receiver.try_iter().collect();
    assert!(!sent.iter().any(|message| message.method == "$postRendererMessage"));
    let activation = sent.into_iter().find(|message| message.method == "$activateByEvent" && message.args[0] == "onRenderer:pub.r").expect("the renderer activates");
    let _ = activation.reply.expect("a call").send(Ok(serde_json::Value::Null));
    cx.run_until_parked();
    let posted: Vec<_> = receiver.try_iter().filter(|message| message.method == "$postRendererMessage").map(|message| message.args[2].clone()).collect();
    assert_eq!(posted, [json!("one"), json!("two")]);
    post("three", cx);
    let posted: Vec<_> = receiver.try_iter().filter(|message| message.method == "$postRendererMessage").map(|message| message.args[2].clone()).collect();
    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...
#[gpui::test]
fn the_kernel_picker_recommends_groups_and_remembers_kernels(cx: &mut TestAppContext) {
    let cells = json!([
        { "cellKind": 2, "language": "python", "source": "a", "outputs": [], "metadata": {} },
        { "cellKind": 2, "language": "python", "source": "b", "outputs": [], "metadata": {} },
    ]);
    let (workbench, cx, _) = workbench_with_cells(cells, cx);
    let rows = |cx: &mut VisualTestContext| {
        workbench.read_with(cx, |workbench, _| {
            let input = workbench.quick_inputs.current().unwrap();
            let rows = input.order.iter().map(|row| &input.rows[*row]);
            let rows = rows.map(|row| format!("{}{} {}", row.separator.as_ref().map(|label| format!("--{label}--")).unwrap_or_default(), row.item.label, row.item.description.clone().unwrap_or_default()));
            (input.title.clone().unwrap_or_default(), rows.collect::<Vec<_>>())
        })
    };
    let pick = |label: &str, cx: &mut VisualTestContext| {
        workbench.update_in(cx, |workbench, window, cx| {
            let input = workbench.quick_inputs.find_mut(|owner| matches!(owner, crate::main_thread_quick_open::Owner::Choose(_))).unwrap();
            let handle = input.rows.iter().find(|row| row.item.label == label).unwrap().item.handle;
            input.set_active_items(&[handle]);
            workbench.flush_quick_input_events(window, cx);
        });
        cx.simulate_keystrokes("enter");
        cx.run_until_parked();
    };
    let select_kernel = |cx: &mut VisualTestContext| {
        workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command("_notebook.selectKernel", Vec::new(), window, cx)));
        cx.run_until_parked();
    };

    select_kernel(cx);
    let recommended = ["$(lightbulb) Install/Enable suggested extensions Python + Jupyter", "Browse marketplace for kernel extensions "];
    assert_eq!(rows(cx), ("Select Kernel".to_owned(), recommended.map(str::to_owned).to_vec()));
    cx.simulate_keystrokes("escape");
    cx.run_until_parked();

    workbench.update_in(cx, |workbench, window, cx| {
        for (handle, id, label) in [(1, "a", "A"), (2, "b", "B")] {
            let kernel = json!({ "id": format!("pub.ext/{id}"), "extensionId": { "value": "pub.ext" }, "notebookType": "jupyter-notebook", "label": label, "extensionLocation": { "scheme": "file", "path": "/ext" }, "preloads": [] });
            workbench.handle_notebook_request("MainThreadNotebookKernels", "$addKernel", &[json!(handle), kernel], window, cx);
        }
    });
    select_kernel(cx);
    assert_eq!(rows(cx), ("Select Kernel".to_owned(), vec!["pub.ext ".to_owned()]));
    pick("pub.ext", cx);
    assert_eq!(rows(cx), ("Select Kernel from pub.ext".to_owned(), vec!["A ".to_owned(), "B ".to_owned()]));
    pick("B", cx);
    let bound = workbench.read_with(cx, |workbench, _| {
        let model = &workbench.host.notebooks.models[0];
        workbench.host.notebooks.kernels.matching(&model.view_type, &model.uri_string()).1.map(|kernel| kernel.id.clone())
    });
    assert_eq!(bound.as_deref(), Some("pub.ext/b"));

    select_kernel(cx);
    assert_eq!(rows(cx), (String::new(), vec!["B Currently Selected".to_owned(), "----Select Another Kernel... ".to_owned()]));
}

/// editActions.ts `ChangeCellLanguageAction`: the status bar's language item opens the picker (Auto Detect, then
/// markdown and the cell's language, then the others by id); markdown turns the code cell into a markup cell with
/// its text, another language back into a code cell, each one undo step.
#[gpui::test]
fn the_cell_language_picker_changes_the_language_and_the_kind(cx: &mut TestAppContext) {
    let (workbench, cx, _) = workbench_with_cells(json!([{ "cellKind": 2, "language": "python", "source": "x", "outputs": [], "metadata": {} }]), cx);
    let languages = json!({ "contributes": { "languages": [
        { "id": "python", "aliases": ["Python"] },
        { "id": "rust", "aliases": ["Rust"] },
        { "id": "markdown", "aliases": ["Markdown"] },
        { "id": "css", "aliases": ["CSS"] },
    ] } });
    workbench.update(cx, |workbench, _| workbench.languages = Languages::new(&[exthost::scan::ScannedExtension { id: "port.languages".into(), location: "/ext".into(), description: languages }]));
    let handle = workbench.read_with(cx, |workbench, _| workbench.host.notebooks.models[0].cells[0].handle);
    workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command("notebook.cell.changeLanguage", vec![json!({ "$mid": 13, "cell": { "handle": handle, "index": 0 } })], 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]).map(|row| format!("{}{} {}", row.separator.as_ref().map(|label| format!("--{label}--")).unwrap_or_default(), row.item.label, row.item.description.clone().unwrap_or_default())).collect::<Vec<_>>()
    });
    assert_eq!(rows, ["Auto Detect ", "--languages (identifier)--Python (python) - Current Language", "Markdown (markdown)", "----Binary (code-text-binary)", "CSS (css)", "Plain Text (plaintext)", "Rust (rust)"]);
    workbench.update_in(cx, |workbench, window, cx| {
        let input = workbench.quick_inputs.find_mut(|owner| matches!(owner, crate::main_thread_quick_open::Owner::EditorStatus(_))).unwrap();
        let handle = input.rows.iter().find(|row| row.item.label == "Markdown").unwrap().item.handle;
        input.set_active_items(&[handle]);
        workbench.flush_quick_input_events(window, cx);
    });
    cx.simulate_keystrokes("enter");
    cx.run_until_parked();
    let cell = |cx: &mut VisualTestContext| workbench.read_with(cx, |workbench, _| {
        let cell = &workbench.host.notebooks.models[0].cells[0];
        (cell.kind, cell.language.clone(), workbench.cell_text(&cell.uri))
    });
    assert_eq!(cell(cx), (crate::notebook::MARKUP, "markdown".into(), "x".into()));
    workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command("notebook.cell.changeLanguage", vec![json!({ "start": 0, "end": 1 }), json!("rust")], window, cx)));
    cx.run_until_parked();
    assert_eq!(cell(cx), (crate::notebook::CODE, "rust".into(), "x".into()));
    focus_cell_list(&workbench, cx);
    run(&workbench, "undo", cx);
    assert_eq!(cell(cx).0, crate::notebook::MARKUP);
    run(&workbench, "undo", cx);
    assert_eq!(cell(cx), (crate::notebook::CODE, "python".into(), "x".into()));
}

/// cellOutput.ts `_attachToolbar`: each output's `...` menu has the `NotebookOutputToolbar` actions that hold for it
/// (Clear Cell Outputs on the first output, no Copy on a stream after a stream, Show Empty Outputs while one is
/// hidden) and Change Presentation first for an output with more than one; their commands copy, show and re-pick.
#[gpui::test]
fn the_output_toolbar_menu_and_its_commands(cx: &mut TestAppContext) {
    let item = |mime: &str, text: &str| json!({ "mime": mime, "valueBytes": text.as_bytes() });
    let outputs = json!([
        { "outputId": "a", "items": [item("application/vnd.code.notebook.stdout", "hello\n")] },
        { "outputId": "b", "items": [item("application/vnd.code.notebook.stdout", "world\n")] },
        { "outputId": "c", "items": [item("text/html", "<b>x</b>"), item("text/plain", "x")] },
    ]);
    let (workbench, cx, _) = workbench_with_cells(json!([{ "cellKind": 2, "language": "python", "source": "x", "outputs": outputs, "metadata": {} }]), cx);
    let renderers = json!({ "contributes": { "notebookRenderer": [
        { "id": "builtin", "displayName": "Built-in", "mimeTypes": ["text/plain", "application/vnd.code.notebook.stdout"], "entrypoint": "a.js" },
        { "id": "html", "displayName": "HTML", "mimeTypes": ["text/html"], "entrypoint": "b.js" },
    ] } });
    workbench.update(cx, |workbench, _| workbench.extensions = vec![exthost::scan::ScannedExtension { id: "port.renderers".into(), location: "/ext".into(), description: renderers }]);
    let menu = |index: usize, cx: &mut VisualTestContext| {
        workbench.update_in(cx, |workbench, window, _| {
            let editor = workbench.active_notebook_editor().unwrap();
            let model = workbench.host.notebooks.model(&editor.notebook).unwrap();
            let actions = workbench.output_menu_actions(editor.tab_model_id, model, 0, index, window);
            actions.into_iter().map(|action| match action {
                crate::menus::MenuAction::Command { title, .. } => title,
                other => format!("{other:?}"),
            }).collect::<Vec<_>>()
        })
    };
    assert_eq!(menu(0, cx), ["Clear Cell Outputs", "Copy Cell Output", "Show Empty Outputs"], "the unmeasured outputs after the first are hidden");
    assert_eq!(menu(1, cx), ["Show Empty Outputs"]);
    assert_eq!(menu(2, cx), ["Change Presentation", "Copy Cell Output", "Show Empty Outputs"]);
    let uri = workbench.read_with(cx, |workbench, _| workbench.host.notebooks.models[0].uri.clone());
    let context = |output: &str| vec![json!({ "start": 0, "end": 1, "outputId": output }), uri.clone()];
    let command = |id: &str, args: Vec<serde_json::Value>, cx: &mut VisualTestContext| {
        workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command(id, args, window, cx)));
        cx.run_until_parked();
    };
    command("notebook.cellOutput.copy", context("a"), cx);
    assert_eq!(cx.read_from_clipboard().and_then(|item| item.text()), Some("hello\nworld".into()), "a stream copies the streams from it on");
    command("notebook.cellOuput.showEmptyOutputs", context("a"), cx);
    assert_eq!(menu(0, cx), ["Clear Cell Outputs", "Copy Cell Output"]);
    command("notebook.output.pickMimetype", context("c"), cx);
    let rows = workbench.read_with(cx, |workbench, _| {
        let input = workbench.quick_inputs.current().unwrap();
        input.order.iter().map(|row| &input.rows[*row]).map(|row| format!("{} {}", row.item.label, row.item.description.clone().unwrap_or_default())).collect::<Vec<_>>()
    });
    assert_eq!(rows, ["text/html Currently Active", "text/plain "]);
    workbench.update_in(cx, |workbench, window, cx| {
        let input = workbench.quick_inputs.find_mut(|_| true).unwrap();
        let handle = input.rows.iter().find(|row| row.item.label == "text/plain").unwrap().item.handle;
        input.set_active_items(&[handle]);
        workbench.flush_quick_input_events(window, cx);
    });
    cx.simulate_keystrokes("enter");
    cx.run_until_parked();
    let picked = workbench.read_with(cx, |workbench, _| {
        let model = &workbench.host.notebooks.models[0];
        workbench.output_presentations(&model.view_type, &model.cells[0].outputs[2])[0].0.clone()
    });
    assert_eq!(picked, "text/plain", "the picked presentation shows from now on");
}

/// NotebookEditorSerializer: the editor part saves a notebook tab as `workbench.input.notebook` and opens it again
/// from workspace storage once its notebook resolves.
#[gpui::test]
fn a_notebook_editor_comes_back_from_workspace_storage(cx: &mut TestAppContext) {
    let (workbench, cx, _) = workbench_with_cells(json!([{ "cellKind": 2, "language": "python", "source": "x", "outputs": [], "metadata": {} }]), cx);
    let saved = workbench.update(cx, |workbench, _| {
        workbench.save_editor_part_state();
        workbench.workspace_storage.lock().unwrap().get("memento/workbench.parts.editor").map(str::to_owned).unwrap()
    });
    let state: serde_json::Value = serde_json::from_str(&saved).unwrap();
    let editor = &state["editorpart.state"]["serializedGrid"]["root"]["data"][0]["data"]["editors"][0];
    assert_eq!(editor["id"], "workbench.input.notebook");
    let value: serde_json::Value = serde_json::from_str(editor["value"].as_str().unwrap()).unwrap();
    assert_eq!((value["viewType"].clone(), value["resource"]["path"].clone()), (json!("jupyter-notebook"), json!("Untitled-1.ipynb")));
    let key = workbench.update(cx, |workbench, _| {
        let key = workbench.host.notebooks.models[0].uri_string();
        workbench.host.notebooks.held.push(key.clone());
        key
    });
    run(&workbench, "workbench.action.closeAllEditors", cx);
    assert!(workbench.read_with(cx, |workbench, _| workbench.editors.editors.is_empty()));
    let storage = Arc::new(Mutex::new(storage::Storage::in_memory()));
    storage.lock().unwrap().set("memento/workbench.parts.editor", saved);
    workbench.update_in(cx, |workbench, window, cx| {
        workbench.restore_workspace_state(storage);
        workbench.restore_notebook_editors(window, cx);
    });
    cx.run_until_parked();
    let tabs = workbench.read_with(cx, |workbench, _| workbench.editors.editors.iter().map(|editor| (editor.document().path.to_string_lossy().into_owned(), editor.preview)).collect::<Vec<_>>());
    assert_eq!(tabs, [(key, false)]);
}

/// layoutActions.ts: the notebook editor title's gear opens Customize Notebook..., whose toggles show their short
/// titles, checked by and flipping their settings.
#[gpui::test]
fn the_customize_notebook_submenu(cx: &mut TestAppContext) {
    let (workbench, cx, _) = workbench_with_cells(json!([{ "cellKind": 2, "language": "python", "source": "x", "outputs": [], "metadata": {} }]), cx);
    let menu = |cx: &mut VisualTestContext| {
        workbench.update_in(cx, |workbench, window, _| {
            let context = workbench.key_context(window);
            let title = crate::menus::menu_actions(&workbench.menus, crate::menus::MenuId::EditorTitle, &context).into_iter().any(|action| matches!(action, crate::menus::MenuAction::Submenu { ref title, .. } if title == "Customize Notebook..."));
            assert!(title, "the gear is in the notebook's editor title");
            let actions = crate::menus::menu_actions(&workbench.menus, crate::menus::MenuId::NotebookEditorLayoutConfigure, &context);
            actions.into_iter().filter_map(|action| match action {
                crate::menus::MenuAction::Command { title, checked, .. } => Some((title, checked)),
                _ => None,
            }).collect::<Vec<_>>()
        })
    };
    let entry = |title: &str, checked: bool| (title.to_owned(), checked);
    assert_eq!(menu(cx), [entry("Customize Notebook Layout", false), entry("Line Numbers", false), entry("Breadcrumbs", true), entry("Toggle Cell Toolbar Position", false)]);
    run(&workbench, "notebook.toggleLineNumbersFromEditorTitle", cx);
    assert_eq!(menu(cx)[1], entry("Line Numbers", true));
}

/// The titles of menu actions: separators as `-`, submenus as `<title> >`.
fn titles(actions: &[crate::menus::MenuAction]) -> Vec<String> {
    let mut titles = Vec::new();
    for action in actions {
        titles.push(match action {
            crate::menus::MenuAction::Command { title, .. } => title.clone(),
            crate::menus::MenuAction::Submenu { title, .. } => format!("{title} >"),
            crate::menus::MenuAction::Separator => "-".to_owned(),
        });
    }
    titles
}

fn run_on_cell(workbench: &gpui::Entity<Workbench>, id: &str, index: usize, cx: &mut VisualTestContext) {
    let args = vec![json!({ "start": index, "end": index + 1, "ui": true })];
    workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command(id, args, window, cx)));
    cx.run_until_parked();
}

/// cellToolbars.ts: a cell's buttons, `...` dropdown and delete button from `MenuId.NotebookCellTitle` and
/// `NotebookCellDelete`, as the reference shows them for an ipynb without the Jupyter extension.
#[gpui::test]
fn the_cell_toolbar_menus(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 toolbar = |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();
            let (primary, more, delete) = workbench.cell_toolbar_actions(model, &row, window);
            (titles(&primary), titles(&more), titles(&delete))
        })
    };
    let (primary, more, delete) = toolbar(0, cx);
    assert_eq!(primary, ["Run Cells In Section", "Edit Cell", "Split Cell"]);
    let overflow = ["Cut Cell", "Copy Cell", "Paste Cell", "-", "Insert Cell >", "-", "Change Cell to Code", "Join With Previous Cell", "Join With Next Cell", "Join Selected Cells", "Copy Cell Down", "-", "Show Cell Line Numbers", "Toggle Cell Toolbar Position"];
    assert_eq!(more, overflow);
    assert_eq!(delete, ["Delete Cell"]);
    // `notebookMissingKernelExtension`: running above and below shows without a kernel.
    let (primary, more, _) = toolbar(1, cx);
    assert_eq!(primary, ["Execute Above Cells", "Execute Cell and Below", "Split Cell"]);
    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]
fn markdown_headers_fold_their_sections(cx: &mut TestAppContext) {
    let cells = json!([
        { "cellKind": 1, "language": "markdown", "source": "# A", "outputs": [], "metadata": {} },
        { "cellKind": 2, "language": "python", "source": "x", "outputs": [], "metadata": {} },
        { "cellKind": 1, "language": "markdown", "source": "## B", "outputs": [], "metadata": {} },
        { "cellKind": 2, "language": "python", "source": "y", "outputs": [], "metadata": {} },
    ]);
    let (workbench, cx, _) = workbench_with_cells(cells, cx);
    let rows = |cx: &mut VisualTestContext| {
        workbench.read_with(cx, |workbench, _| {
            let model = &workbench.host.notebooks.models[0];
            let rows = workbench.notebook_rows(workbench.host.notebooks.editors[0].tab_model_id, model);
            (rows.iter().map(|row| row.hidden).collect::<Vec<_>>(), rows.iter().map(|row| row.fold).collect::<Vec<_>>(), workbench.host.notebooks.editors[0].focus)
        })
    };
    assert_eq!(rows(cx), (vec![false; 4], vec![Some((false, 3)), None, Some((false, 1)), None], 0));
    workbench.update(cx, |workbench, _| workbench.host.notebooks.editors[0].focus = 3);
    // A code cell folds nothing downwards.
    run(&workbench, "notebook.fold", cx);
    assert_eq!(rows(cx).0, [false; 4]);
    workbench.update(cx, |workbench, _| workbench.host.notebooks.editors[0].focus = 2);
    run(&workbench, "notebook.fold", cx);
    assert_eq!(rows(cx), (vec![false, false, false, true], vec![Some((false, 3)), None, Some((true, 1)), None], 2));
    workbench.update(cx, |workbench, _| workbench.host.notebooks.editors[0].focus = 1);
    run(&workbench, "notebook.fold", cx);
    assert_eq!(rows(cx).0, [false, false, false, true], "a code cell folds nothing");
    workbench.update(cx, |workbench, _| workbench.host.notebooks.editors[0].focus = 0);
    run(&workbench, "notebook.fold", cx);
    assert_eq!(rows(cx).0, [false, true, true, true]);
    run(&workbench, "notebook.unfold", cx);
    assert_eq!(rows(cx).0, [false, false, false, true], "the inner section stays collapsed");

    // `levels`: two levels down unfold the section and the one inside it; two levels up fold both again.
    let with_args = |id: &str, args: serde_json::Value, cx: &mut VisualTestContext| {
        workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command(id, vec![args], window, cx)));
    };
    with_args("notebook.unfold", json!({ "index": 0, "levels": 2 }), cx);
    assert_eq!(rows(cx).0, [false; 4]);
    with_args("notebook.fold", json!({ "index": 3, "levels": 2, "direction": "up" }), cx);
    assert_eq!(rows(cx).1, [Some((true, 3)), None, Some((true, 1)), None]);
}

/// cellCommands.ts, notebookClipboard.ts and cellEditorOptions.ts on the toolbar's cell.
#[gpui::test]
fn the_cell_toolbar_commands(cx: &mut TestAppContext) {
    let cells = json!([
        { "cellKind": 2, "language": "python", "source": "a\nb", "outputs": [], "metadata": {} },
        { "cellKind": 2, "language": "python", "source": "c", "outputs": [], "metadata": {} },
        { "cellKind": 1, "language": "markdown", "source": "# T", "outputs": [], "metadata": {} },
    ]);
    let (workbench, cx, _) = workbench_with_cells(cells, cx);
    run_on_cell(&workbench, "notebook.cell.copy", 1, cx);
    run_on_cell(&workbench, "notebook.cell.paste", 2, cx);
    assert_eq!(sources(&workbench, cx), ["a\nb", "c", "# T", "c"]);
    run_on_cell(&workbench, "notebook.cell.cut", 0, cx);
    assert_eq!(sources(&workbench, cx), ["c", "# T", "c"]);
    assert_eq!(cx.read_from_clipboard().and_then(|item| item.text()).as_deref(), Some("a\nb"));
    run_on_cell(&workbench, "notebook.cell.joinBelow", 0, cx);
    assert_eq!(sources(&workbench, cx), ["c\n# T", "c"]);
    // From the toolbar the cell editor has no cursor: the split point is the start.
    run_on_cell(&workbench, "notebook.cell.split", 0, cx);
    assert_eq!(sources(&workbench, cx), ["", "c\n# T", "c"]);
    run_on_cell(&workbench, "notebook.cell.changeToMarkdown", 2, cx);
    run_on_cell(&workbench, "notebook.cell.moveUp", 2, cx);
    let kinds = |cx: &mut VisualTestContext| workbench.read_with(cx, |workbench, _| workbench.host.notebooks.models[0].cells.iter().map(|cell| cell.kind).collect::<Vec<_>>());
    assert_eq!(kinds(cx), [crate::notebook::CODE, crate::notebook::MARKUP, crate::notebook::CODE]);
    focus_cell_list(&workbench, cx);
    run(&workbench, "undo", cx);
    assert_eq!(kinds(cx), [crate::notebook::CODE, crate::notebook::CODE, crate::notebook::MARKUP]);
    run_on_cell(&workbench, "notebook.cell.insertMarkdownCellAbove", 0, cx);
    assert_eq!(sources(&workbench, cx), ["", "", "c\n# T", "c"]);
    assert_eq!(kinds(cx)[0], crate::notebook::MARKUP);
    let line_numbers = |cx: &mut VisualTestContext| {
        workbench.read_with(cx, |workbench, _| {
            let model = &workbench.host.notebooks.models[0];
            model.cells.iter().map(|cell| workbench.cell_model(&cell.uri).is_some_and(|editor| workbench.cell_line_numbers(&editor.document().uri_string()))).collect::<Vec<_>>()
        })
    };
    run_on_cell(&workbench, "notebook.cell.toggleLineNumbers", 1, cx);
    assert_eq!(line_numbers(cx), [false, true, false, false]);
}

#[gpui::test]
fn a_wheel_over_an_unfocused_cell_scrolls_that_cell(cx: &mut TestAppContext) {
    let long = "x".repeat(400);
    let cells = json!([
        { "cellKind": 2, "language": "python", "source": long, "outputs": [], "metadata": {} },
        { "cellKind": 2, "language": "python", "source": long, "outputs": [], "metadata": {} },
    ]);
    let (workbench, cx, _) = workbench_with_cells(cells, cx);
    // The unfocused cell's text area draws the frame after the one that asked for it.
    cx.update(|window, _| window.refresh());
    cx.run_until_parked();
    let handle = workbench.read_with(cx, |workbench, _| workbench.host.notebooks.models[0].cells[1].handle);
    let bounds = cx.debug_bounds(Box::leak(format!("notebook-cell-editor-{handle}").into_boxed_str())).unwrap();
    cx.simulate_event(gpui::ScrollWheelEvent { position: bounds.center(), delta: gpui::ScrollDelta::Pixels(gpui::point(gpui::px(-100.), gpui::px(0.))), ..Default::default() });
    cx.run_until_parked();
    workbench.read_with(cx, |workbench, _| {
        let cells = &workbench.host.notebooks.models[0].cells;
        let scroll_left = |index: usize| workbench.cell_model(&cells[index].uri).unwrap().scroll.left;
        assert_eq!(workbench.active_notebook_editor().unwrap().focus, 0);
        assert_eq!(scroll_left(0), 0.);
        assert!(scroll_left(1) > 0., "the wheel scrolled the second cell");
    });
}

/// contentHoverController.ts runs per code editor: a move over an unfocused cell's text hovers that cell.
#[gpui::test]
fn the_mouse_over_an_unfocused_cell_shows_its_hover(cx: &mut TestAppContext) {
    // The Cyrillic `\u{430}` is an ambiguous character: the unicode highlighter's hover part explains it.
    let cells = json!([
        { "cellKind": 2, "language": "python", "source": "a = 1", "outputs": [], "metadata": {} },
        { "cellKind": 2, "language": "python", "source": "b = '\u{430}'", "outputs": [], "metadata": {} },
    ]);
    let (workbench, cx, _) = workbench_with_cells(cells, cx);
    cx.update(|window, _| window.refresh());
    cx.run_until_parked();
    let (handle, model_id) = workbench.read_with(cx, |workbench, _| {
        let cell = &workbench.host.notebooks.models[0].cells[1];
        (cell.handle, workbench.cell_model(&cell.uri).unwrap().model_id)
    });
    let (content_left, char_width, line_height) = workbench.update_in(cx, |workbench, window, _| {
        let metrics = workbench.editor_metrics(workbench.editors.editor_by_id(model_id).unwrap(), window);
        (metrics.content_left(), metrics.char_width, metrics.line_height)
    });
    let bounds = cx.debug_bounds(Box::leak(format!("notebook-cell-editor-{handle}").into_boxed_str())).unwrap();
    let on_char = bounds.origin + gpui::point(gpui::px(content_left + 5.25 * char_width), gpui::px(line_height / 2.));
    cx.simulate_mouse_move(on_char, None, gpui::Modifiers::default());
    cx.executor().advance_clock(std::time::Duration::from_millis(1000));
    cx.update(|window, _| window.refresh());
    cx.run_until_parked();
    workbench.read_with(cx, |workbench, _| {
        assert_eq!(workbench.active_notebook_editor().unwrap().focus, 0);
        let shown = workbench.content_hover.shown.as_ref().expect("the hover shows");
        assert_eq!((shown.anchor.model_id, shown.anchor.line, shown.anchor.start), (model_id, 0, 5));
        assert!(workbench.content_hover.widget_bounds.get().is_some(), "the unfocused cell draws the hover widget");
    });
    // `_onEditorMouseLeave`: off the cell's text area, the hover goes.
    cx.simulate_mouse_move(bounds.origin + gpui::point(gpui::px(content_left), bounds.size.height + gpui::px(40.)), None, gpui::Modifiers::default());
    cx.run_until_parked();
    workbench.read_with(cx, |workbench, _| assert!(workbench.content_hover.shown.is_none(), "leaving the cell hides its hover"));
}

/// A press on an unfocused cell lands where its wrapped view line shows the text, as the line's own press would.
#[gpui::test]
fn a_click_on_a_wrapped_line_of_an_unfocused_cell_places_the_cursor_there(cx: &mut TestAppContext) {
    let cells = json!([
        { "cellKind": 2, "language": "python", "source": "a = 1", "outputs": [], "metadata": {} },
        // Three model lines keep the box three lines high; the first wraps.
        { "cellKind": 2, "language": "python", "source": format!("{}\nb\nc", "x".repeat(400)), "outputs": [], "metadata": {} },
    ]);
    let (workbench, cx, _) = workbench_with_cells(cells, cx);
    workbench.update(cx, |workbench, _| workbench.update_user_setting("editor.wordWrap", json!("on")));
    for _ in 0..2 {
        cx.update(|window, _| window.refresh());
        cx.run_until_parked();
    }
    let (handle, model_id) = workbench.read_with(cx, |workbench, _| {
        let cell = &workbench.host.notebooks.models[0].cells[1];
        (cell.handle, workbench.cell_model(&cell.uri).unwrap().model_id)
    });
    let (content_left, char_width, line_height, second_start) = workbench.update_in(cx, |workbench, window, _| {
        let editor = workbench.editors.editor_by_id(model_id).unwrap();
        let metrics = workbench.editor_metrics(editor, window);
        (metrics.content_left(), metrics.char_width, metrics.line_height, editor.segment(1).start)
    });
    assert!(second_start > 0, "the cell's line wraps");
    let bounds = cx.debug_bounds(Box::leak(format!("notebook-cell-editor-{handle}").into_boxed_str())).unwrap();
    cx.simulate_click(bounds.origin + gpui::point(gpui::px(content_left + 2.25 * char_width), gpui::px(line_height * 1.5)), gpui::Modifiers::default());
    workbench.read_with(cx, |workbench, _| {
        assert_eq!(workbench.active_notebook_editor().unwrap().focus, 1);
        assert_eq!(workbench.editors.active().unwrap().selection().head, crate::editor::Position::new(0, second_start + 2));
    });
}

/// listView.ts renders the cells in view only, each code cell's editor takes its model (codeCell.ts `setModel`), a
/// row that leaves the view releases its template with the model still set (rowCache.ts), and a row that comes into
/// view takes a released template: the host sees the code editors of those templates only.
#[gpui::test]
fn the_host_sees_the_code_editors_of_the_rendered_cells(cx: &mut TestAppContext) {
    let cells: Vec<serde_json::Value> = (0..40).map(|index| json!({ "cellKind": 2, "language": "python", "source": format!("x{index}"), "outputs": [], "metadata": {} })).collect();
    let (workbench, cx, _receiver) = workbench_with_cells(json!(cells), cx);
    let draw = |cx: &mut VisualTestContext| {
        cx.update(|window, _| window.refresh());
        cx.run_until_parked();
    };
    draw(cx);
    let editor_cells = |cx: &mut VisualTestContext| {
        workbench.read_with(cx, |workbench, _| {
            let editors = workbench.host.text_editors(&workbench.editors);
            editors.iter().filter_map(|(_, editor, _)| workbench.host.notebooks.cell(&editor.document().uri()).map(|(_, index)| index)).collect::<std::collections::BTreeSet<usize>>()
        })
    };
    let rendered = |cx: &mut VisualTestContext| {
        workbench.read_with(cx, |workbench, _| {
            let (tab, notebook) = workbench.active_notebook_tab().unwrap();
            let view = &workbench.notebook_views.views[&tab];
            let (top, height) = (view.scroll_top, f32::from(view.bounds.get().size.height));
            let rows = workbench.notebook_rows(tab, workbench.host.notebooks.model(&notebook).unwrap());
            rows.iter().filter(|row| row.layout.top < top + height && row.layout.top + row.layout.height > top).map(|row| row.index).collect::<std::collections::BTreeSet<usize>>()
        })
    };
    let in_view = rendered(cx);
    assert!(!in_view.is_empty() && in_view.len() < 20, "a part of the cells is in view: {in_view:?}");
    assert_eq!(editor_cells(cx), in_view, "the rendered cells have editors, the others none");

    let scroll_to = |row: Option<usize>, cx: &mut VisualTestContext| {
        workbench.update(cx, |workbench, _| {
            let (tab, notebook) = workbench.active_notebook_tab().unwrap();
            let rows = workbench.notebook_rows(tab, workbench.host.notebooks.model(&notebook).unwrap());
            let top = match row {
                Some(row) => rows[row].layout.top,
                None => workbench.notebook_scroll_height(tab) - f32::from(workbench.notebook_views.views[&tab].bounds.get().size.height),
            };
            workbench.set_notebook_scroll_top(tab, top);
        });
        draw(cx);
    };
    scroll_to(Some(20), cx);
    let moved = rendered(cx);
    assert_eq!(moved.first(), Some(&20));
    let mut expected = moved.clone();
    // The focused cell stays the group's code editor.
    expected.insert(0);
    assert_eq!(editor_cells(cx), expected, "the rows in view took the released templates");

    scroll_to(None, cx);
    let last = rendered(cx);
    let held: Vec<usize> = editor_cells(cx).into_iter().filter(|index| *index != 0).collect();
    assert!(last.iter().all(|index| held.contains(index)) && held.len() > last.len(), "the templates the fewer rows at the end left keep their cells' models: {held:?} for {last:?}");
}